Skip to content

Instantly share code, notes, and snippets.

@wazery
Created May 28, 2014 12:14
Show Gist options
  • Save wazery/918f8eca7d886abee4c3 to your computer and use it in GitHub Desktop.
Save wazery/918f8eca7d886abee4c3 to your computer and use it in GitHub Desktop.
Welcome document
Vim for Rails
=====================
----------
### Brief history of Vi and Vim
Before the appearance of the famous operating system UNIX, the text editor “ed” appeared, which was written by Ken Thompson in 1971. ed is regarded as one of the oldest text editors ever, and it is also regarded as the first to implement the concept of Regular Expressions.
After that period the “ex” text editor appeared which is short for “EXtend” to add some features to “ed” and to make it simpler.
Then Vi appeared in 1976 by Bill Joy which is written for the BSD operating system, and of course under the licence with the same name as the operating system (the BSD licence).
Vi is regarded as an addition to “ex” which had only 2 modes of what Vim now has. We will explore the concept of modes and how to use them, in this tutorial.
After some years of Vi’s appearance some other editions of it appeared, and the most famous one is Vim which is short for Vi Improved, also “elvis” text editor appeared.
In 1991 Bram Moolenaar started to work on Vim, and the goal was to build an Amiga compatible text editor to edit the source code. Vim is licensed under GPL as an open source program. Vim was only working inside the shell till the year 1996 in which the first GUI interface programmed for it, and Vim back then was in its version 4.
Vim adds some features to Vi. Here are a few of the extended Vim features that I have come to rely on:
- Vim has been ported to a much wider range of OS's than vi.
- Vim includes support (syntax highlighting, code folding, etc) for several popular programming languages (C/C++, Python, Perl, shell, etc).
- Vim integrates with cscope.
- Vim can be used to edit files using network protocols like SSH and HTTP.
- Vim includes multilevel undo/redo.
- Vim allows the screen to be split for editing multiple files.
- Vim can edit files inside a compressed archive (gzip, zip, tar, etc).
- Vim includes a built in diff for comparing files (vimdiff).
- Vim includes support for plugins, and finer control over config and startup files.
- Vim can be scripted with vimscript, or with an external scripting language (e.g. python, perl, shell).
### Vim for Rubyists
There are a lot of Rubyists out there who are using Vim, although it is an old text editor (22 years!) it is still very useful. Vim's extensibility gives it a great power, you can add some awesome plugins to help you in your development. In this tutorial we will explore how to add a lot of useful plugins specifically for Ruby on Rails development, which will convert Vim to a very decent RoR text editor. Check this [list][1] of some of the popular Rubyists out there who are using Vim.
### Installing Vim
#### On Ubuntu
If you’re using a GNOME-based desktop such as Unity, you can use vim-gnome which is a GUI version of Vim. To install, type in a terminal
```
sudo apt-get install vim-gnome
```
If you’re running another desktop environment such as XFCE, LXDE, or KDE, you can use vim-gtk which doesn’t depend on as many extra library files as vim-gnome. To install, type in a terminal
```
sudo apt-get install vim-gtk
```
> **NOTE:**
> As of Ubuntu 6.10 (Edgy Eft), the default Vim install is a cut-down version called "vim-tiny". In order to get the full version complete with the online help documentation, and many of the advanced functions such as code folding; you will need to install "vim":
```
sudo apt-get install vim
```
#### On MacOSX
In MacOSX the alternatives to apt package manager are `Homebrew` and `MacPorts`. Their is a project called MacVim which is a GUI interface for Vim like GVim on Linux, to install it using Homebrew just type in the terminal:
```
brew install macvim --override-system-vim
```
This will create vim, vimdiff, etc. symlinks to `mvim` in `/usr/local/bin/vim`, and as long as `/usr/local/bin` is before `/usr/bin` in your PATH. MacVim come with built-in support for the Ruby language which will be useful for us when integrating some plugins like Command-T.
#### On Windows
1. Download Vim: Go to Vim Download page and click on “PC: MS-DOS and MS-Windows”. Click on the ``gvim72.exe``, which is a Self-installing executable, or download ``gvim72.exe`` directly.
2. Installing: After downloading click on `gVim72.exe`, which will install gVim on your Windows as shown below.
![Vim Installation Confirmation][2]
Vim Installation Confirmation
![Vim 7.2 License Agreement][3]
Vim 7.2 License Agreement
![Vim Installation Option. (Make sure to select “Full” from the drop-down list)][4]
Vim Installation Option. (Make sure to select “Full” from the drop-down list)
![Vim Installation location ( directory should end with vim )][5]
Vim Installation location ( directory should end with vim )
![gVim Installation Progress and Completion][6]
gVim Installation Progress and Completion
### Vim as a beginner
Why to use Vim?
The common funny scenario that happens when people try to use Vim for the first time is that: they start Vim then try to type 'test' and freakingly they got only the letter 't' printed! Then they try to close it, which is another big problem, they do a force quit or maybe killing its process. I think this scenario is enough for a lot of people to just forgot about Vim and never try to get back to use it again.
I think Vim shouldn't be treated like this, there are a plenty of useful resources to learn the basics of Vim, like the well known `vimtutor` (which you can use by typing `vimtutor` in the terminal and it will introduce you to the basics in less than 30 minutes), or even this awesome game called [Vim Adeventures][13]. Why not to give them a try before hitting `vim` command from the terminal or start the GUI version of Vim?
Yes Vim is not straight forward to start using it without knowing its basics, but once you have learned the basics, I think it will be easier to continue grasping more of it. A lot of people say that Vim has a formidable learning curve, which I think is the price for the efficiency in manipulating text you will get after some time practicing Vim.
Vim is like a game, you start playing it while knowing just the basics, then you learn more and more, maybe by accident or unintentionally. When you start using Vim you do the same, you just know the basic commands, then you try to speed up your text manipulation, so you search for some tricks, hence you learn new things. After some time you start composing or chaining commands efficiently so you build a muscle memory for these tricks you learned over time, and that is all about learning Vim. Speaking of the muscle memory it is recommended to keep a cheat sheet like this [one][14] while you use Vim.
You will notice the difference after some time using it, you will see that you become more quick in editing than your old text editor.
You can start Vim in console mode by typing `vi` or `vim` at the terminal or `vim` in graphical mode by typing `gvim` on Linux or `macvim` on Mac. Doing so should bring up a blank screen, with details about Vim. However, any attempts to type text will fail! as mentioned before, Which brings us to the most confusing feature for beginners - modes.
### Vim modes
Vim assumes that users edit text more often than they type it. Hence it has a mode for inserting text and several modes for editing text. The behavior of Vim depends on which mode it is set to:
1. **Command mode** is the default mode of Vim. It provides a library of keyboard-based commands to edit text. Pressing the escape key switches back to this mode.
2. **Insert mode** allows for the insertion of text. This is the functionality most users associate with text editors. Pressing the `i` key in command mode switches to this mode.
3. **Visual mode** provides functionality for text selection. Pressing the `v` key in command mode switches to this mode.
### Vim commands
Vi's design is very similar to that of the Unix operating system. That is, functionality is provided through a library of simple commands that can be combined into more complex commands.
Vim is influenced by the design of the Unix operating system, in which the functionality is provided through a library of simple commands that can be combined into more complex commands. For example, the `w` command moves the cursor to the beginning of the next word. The `d` command is the deletion command. Thus `dw` deletes the next word; `d2w` deletes the next two words, so here it comes the composability of commands in Vim, also you will realize the clever mnemonic naming of Vim's commands.
Here is a very clever [cheat sheet][15] that will introduce you to the basic Vim movement commands. Have a look on it and try practice each command.
#### As a beginning Vim user you should be able to:
- Switching between command mode and insert mode.
- To switch from command mode to insert mode (to insert text at the **current** cursor position) use `i` command.
- To switch from command mode to insert mode (to insert text at the **beginning** of the line) use `I` command which is apparently `Shift + i`.
- To switch from command mode to insert mode (to insert text at the **end** of the line) use `A` command (short for append), which is apparently `Shift + a`.
- To switch from insert mode back to command mode use `Esc` or `CTRL + [` which is better and easier.
- Opening new lines
- To open a new line after the current one, and begin inserting text (switching to insert mode) use `o`.
- To open a new line before the current one, and begin inserting text (switching to insert mode) use `O`.
- Navigating in the source using `hjkl`
- How to navigate **up** a line in command mode `k`
- How to navigate **down** a line in command mode `j`
- How to navigate **left** a character in command mode `h`
- How to navigate **right** a character `l`
- Save.
- To save current edits to the file use `:w` (short for write).
- Exit.
- To exit current file use `:q` (short for quit).
- To save and exit combine both commands `:wq`.
- To force exit without saving use `:q!`.
- To force save and exit use `:wq!`.
- Undo.
- To undo last edit use `u`.
- Redo.
- To redo use `CTRL + r`.
- Copy and paste.
- To select a block of a text use `Ctrl + v` to switch to the visual mode, then select a block.
- To copy the selected block use `yy` (which is short for yank).
- To paste the selected block use `p` (apparently paste!).
- To paste before cursor use `P`.
- Tab complete.
- To do a tab completion use `CTRL + p`.
- Move to beginning and end of a file.
- To move to the **beginning** of the line use `0`.
- To move to the **end** of the line use `$`.
- Substitute/Replace.
- To substitute a character use `r` followed by the character you will substitute.
- To switch to replace mode use `Shift + r`.
- Combine operators (like delete) with motions (like end of word).
- As mentioned before, Vim commands are composable, so you can combine *operations* like delete/change/copy with *motions* like beginning/end of word/line.
- To delete to the end of the word compose `dw`.
- To delete to the end of the line compose `d$`.
- To delete the **inner** text of quotes, double quotes, parentheses, brackets use `di'`, `di"`, `di(`, `di{` respectively.
- To copy to the end of the word compose `yw`.
- You can type a number before the command to execute it multiple times
- For example to delete 4 lines use `4dd`.
- Repeat last command
- To do so use `.`.
- Jump to specific position in a file.
- To jump to the **beginning** of a file use `gg`.
- To jump to the **end** of a file use `G`.
- To jump to the **specific** line in a file use `8gg` change this to the line number.
- Search forward and backward.
- Match parentheses and brackets.
- To match the current parentheses or bracket use `%`.
- Split horizontally and vertically.
- To split the screen **horizontally** use `:sp`.
- To split the screen **vertically** use `:vs`.
- Resize the splits
- Switch between splits.
- To switch to the next split screen use `CTRL + ww`.
- Jump forward and backward.
- To jump forward a page use `CTRL + f`.
- To jump backward a page use `CTRL + b`.
- Modify your environment via dotfiles.
- Now you can do so after reading this tutorial, not to forgot the easy way to edit your `.vimrc` file is `:e $MYVIMRC`.
- Execute a shell command.
- To execute a shell command simply type `:sh`.
For more commands check this awesome [tutorial][16].
As mentioned before which I think is very clear to you now, commands in Vim are mnemonic, which gives them simplicity and will build a muscle memory very easily for you.
#### Vim recording
Vim has a really great feature which is called Vim Macros, it enables you to record any actions you do and replay them or repeat them.
To start recording simply issue the `q` command then type any letter on the keyboard to record the macro on it.
So imagine that you want to add different words in specific positions in some lines like:
```
They smart
He smart
They smart
He smart
They smart
He smart
```
You want this to be converted to:
```
They are smart
He is smart
They are smart
He is smart
They are smart
He is smart
```
So start recording by pressing `q` and any letter from the keyboard for this example lets pick `w`, then from the beginning of the line move to the space after 'They' then enter the insert mode by pressing `i` command and type 'are', then hit `CTRL + [` or `Esc` to go back to the command mode, then hit `^` command to go to the beginning of the line, and `j` to go to the next line, now move to the space after the word 'He', then issue `i` to be in insert mode, then type 'is', then `CTRL + [` then go to the beginning of the line and `j` for the next line. Now you can press `q` to finish recording.
Now you can type `2@w` to repeat the macro for the rest of the lines.
### Some Productivity Tips
#### Copy to system clipboard
To enable copying to system clipboard using `CTRL + c` just insert the following line to your `vimrc` file:
```
" Enable copying to clipboard using `CTRL + c`
map <C-c> y:e ~/clipsongzboard<CR>P:w !pbcopy<CR><CR>:bdelete!<CR>
```
#### Using the arrow keys
In Vim you can use arrow keys in both command and insert mode, but I think it is not a good practice to do so. It is recommended to keep using `hjkl` navigation keys in your entire session, why to get back to the arrow keys and confuse your muscle memory? Also don't use the `Home` or `End` buttons and just stick to the `$` and `^` to move to the **beginning** and **end** of a line respectively.
Here is how to un-map the arrow keys to avoid confusion. Just add the following lines to your `vimrc` file.
```
noremap <Up> <nop>
noremap <Down> <nop>
noremap <Left> <nop>
noremap <Right> <nop>
```
#### Remap your CapsLock key to Control key
After some time of using Vim you will find that it's painful to use the Control key for your fingers. Control key is located in a really bad place in the keyboard, in contrast to the CapsLock key which is very close to your pinky finger, so why not remapping Control key to CapsLock?
Here is [how][17] to do it on Mac, Linux and Windows.
#### Changing case and repeating a command
Vim provides three awesome commands for text manipulations, I usually find some experienced Vim users that don't know about them which is really strange. Here are the three commands:
- `~ (tilde)` – toggle the casing of a letter/selection (upper-case/down-case).
- `. (dot)` – repeat the last set of commands (use in a combination with search, such as `*`, and jumps).
- `* (star)` - to search and highlight for the word that the cursor is currently located on.
#### Leaving insert mode to what it is for
Why to think of switching to the insert mode to delete some text? This will be very contradicting the nature of Vim; every text manipulation shouldn't be done in the insert mode. You should leave insert mode only for what its name indicates, so to delete some text just use the `d` command and compose it with whatever motion you want, or repeat it.
#### Setting up your Vim
When Vim starts up it loads a file called `vimrc`, which holds all the configuration settings that Vim needs. On Unix based systems the file is named `.vimrc` and is located in the .vim directory in your home, while in Windows it is called _vimrc. The home dirctory is specified by ``$HOME`` which is ``~`` in Unix based systems, while on Windows systems you can find ``$HOME`` by typing ``:echo $HOME`` in Vim. You can simply open your `vimrc` file by typing ``:e $MYVIMRC`` in Vim.
Type ``:help vimrc`` or for short ``:h vimrc`` in your Vim to have some documentation about it. In this tutorial we will edit the `vimrc` file a lot to add some plugins and some customizations.
#### Bare minimum .vimrc file at the beginning
It is recommended not to start with a huge `.vimrc` file of another's developer, yes there are a lot of popular developers who share their dotfiles (configuration files) but they built it a long their way depending on their usage and needs, so why just copy it entirely? I think every user should start with a bare minimum `.vimrc` file and configure it according to his/her needs, which will grant that every single line is useful for him/her.
This is a good starting point for your `.vimrc`:
```
set nocompatible " choose no compatibility with legacy vi
syntax enable
set encoding=utf-8
set showcmd " display incomplete commands
filetype plugin indent on " load file type plugins + indentation
"" Whitespace
set nowrap " don't wrap lines
set tabstop=2 shiftwidth=2 " a tab is two spaces (or set this to 4)
set expandtab " use spaces, not tabs (optional)
set backspace=indent,eol,start " backspace through everything in insert mode
"" Searching
set hlsearch " highlight matches
set incsearch " incremental searching
set ignorecase " searches are case insensitive...
set smartcase " ... unless they contain at least one capital letter
```
#### Recovering from errors
Some errors in your `vimrc` may prevent Vim from starting successfully. A reliable way to handle that would be to rename your `vimrc` file, then edit the renamed file, then give it the correct name. Alternatively, you could start Vim with a command like this (or use "GVim/MacVim" if that is how you run Vim):
> vim -N -u NONE -U NONE
The `-N` starts in "not compatible" mode (that is, with extra Vim features). The NONE argument (must be uppercase) skips initializations and does not read any `vimrc` file (-u), and does not read any gvimrc file (-U).
#### Using Vundle plugin manager
Vim has a plugin, or script system which can be used to add some more functionality to Vim. These plugins, or scripts are implemented as a simple configuration files which are located in subdirectories inside the `$HOME/.vim` directory. If you are using a lot of plugins, managing them would add some hassle, so here it comes the importance of a plugin manager to take care of them effectively and help make this task simpler.
There are some plugin managers for Vim like [Vundle][7] and [Pathogen][8], which make it super easy to add, install, update, search, or remove any plugin or runtime file you want each of which in their own private subdirectories. In this tutorial we will be exploring how to use Vundle.
Vundle is a short for `Vim Bundle`, and here is how to install and use it to manage your Vim plugins.
To install it you need to have [Git][9] first. [Here][10] is a guide on how to install it.
**1-** In your terminal type:
```
$ git clone https://github.com/gmarik/Vundle.vim.git ~/.vim/bundle/Vundle.vim
```
This command will clone the Vundle plugin into the correct location.
**2-** Open up your vimrc file simply by typing `:e $MYVIMRC` in your vim.
**3- Including Vundle in your vimrc**
Put this at the top of your `.vimrc` to use Vundle.
```
set nocompatible " be iMproved, required
filetype off " required
" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
" alternatively, pass a path where Vundle should install plugins
"call vundle#begin('~/some/path/here')
" let Vundle manage Vundle, required
Plugin 'gmarik/Vundle.vim'
" The following are examples of different formats supported.
" Keep Plugin commands between vundle#begin/end.
" All of your Plugins must be added before the following line
call vundle#end() " required
filetype plugin indent on " required
```
**4- Adding the plugins:**
Now you can add any plugin you want from just by adding the word `Plugin` and the URL for it or its Git repository (it doesn't matter if the repository is on Github or any other server or even on your machine just add the path to it). As an example to add the [vim-fugitive][11] plugin you will add the following line inside `call vundle#begin()` and `call vundle#end()` block.
```
Plugin 'tpope/vim-fugitive.git'
```
> **NOTE:**
> We didn't add the full git URL which is 'git@github.com:tpope/vim-fugitive.git', because Vundle will automatically do that for us if the repository is hosted on Github, so you will add the full path only if the repository is hosted somewhere else.
**5- Installing the plugins**
To install the plugins you already included you need to launch vim and run `:PluginInstall` or to install from command line just type:
```
$ vim +PluginInstall +qall
```
**6- Searching plugins**
One of the most useful functions of Vundle is the ability to find and install more plugins.
To list every plugin that Vundle can find on the `Vim Scripts` site use:
:Plugins
Or
:PluginSearch!
The "!" at the end of the command refreshes the local list from the Vim Scripts site.
If we want to search for a specific plugin, we can use this same syntax like this:
:PluginSearch! plugin_query
**7- Deleting plugins**
To delete a specific plugin, you need to list the plugins first by using the command `:PluginList`, then move to the plugin line and hit `D` to mark it for deletion. Then you will need to run the command `:PluginInstall`.
> **NOTE:**
> After doing so, the plugin is still there in the `vimrc` file, and you can re-install it by typing `:PluginInstall`.
Their is an easier way to delete a plugin, just delete it from the `vimrc` file then issue the command `:PluginClean` which deletes any plugin that is not in your `vimrc` file.
```
" Removing Plugins:
Plugin 'MarkdownFootnotes'
. . .
Continue? [Y/n]:
You can type "Y" to remove all unreferenced plugins.
```
### Vim Themes
You can add as many Vim color schemes into your Vim as you like, there are a plenty of color schemes out there varying from bright ones to dark ones, here is a [link][12] to the most popular schemes. In this tutorial we will explore how to add some schemes.
It is very easy to add color schemes to Vim. Each color scheme come in a file with a .vim extension, all you need to do is to download it to the `colors` subdirectory which is inside `~/.vim` directory. Then from your vimrc file change the line `colorscheme badwolf` to the name of your selected color scheme, or simply use this awesome color scheme scroller plugin.
#### Color Scheme Scroller Plugin
It will be very difficult to test your color schemes if you tried t change them manually from the `vimrc` file, imagine that you have a list of 15 color schemes and you need to select a good one that matches your mood, that will be painful!
So here it comes the advantage of the color scheme scroller plugin, in which you can scroll using your arrow keys to live view the themes very quickly and easily.
We can now install this awesome plugin using Vundle as we have seen, just put the following line into the correct block in your `vimrc` file:
```
Plugin 'https://github.com/vim-scripts/ScrollColors'
```
I am sure you know that the correct block is inside `call vundle#begin()` and `call vundle#end()` then do `:PluginInstall` which will do the work of installing the plugin for you.
Now you can use the plugin after restarting Vim, by just typing `:SCROLL` then use your arrow key to choose the color scheme you like.
> **NOTE:**
> This plugin just allow you to live view the themes and use them in the current opened Vim only. If you restarted Vim the color scheme change will not take effect, so you may need to add your selected color scheme manually to your vimrc if you will stick with it.
## Summary
Now after reading this tutorial, you know the basics of Vim and you know how to customize it to add any plugins or features that suits you. In the next part we will explore in detail how to customize Vim for Rails development and we will go through some really useful plugin that will transform Vim into a full featured RoR text edior.
----------
## Contents
- Introduction to Vim
- Setting up your Vim
- Vim themes
- Editing .vimrc config
- Source Navigation
- Vim modes
- Vim commands
- Vim recording
- Killer commands
- Some Productivity Tips
- Vim Ruby Plugin
- Installation
- Usage/commands
- Rails Plugin
- Basics
- File Navigation
- Timesaving commands
- Executing/Running migrations/scaffolds
- Ruby Refactoring Plugin
- Vim Cucumber
- Other useful Ruby/Rails plugins
- Vim Rake
- Vim Bundler
- CTags
- Indexing your Rails project tags
- Easy jumping to definitions
- Using regex to jump to definitions
- snipMate
- Adding Ruby snippets
- Ack
- Easy searching in your source code
- Editing .ackrc config
- Quick navigation through results using Vim
- tComment
- Easy commenting your Ruby code
- Sync with Dropbox or Github
-
# PART 2
### Ruby Plugin
- Installation
- Usage/commands
### Rails Plugin
- Basics
- File Navigation
- Timesaving commands
- Executing/Running migrations/scaffolds
### Learning Resources
- http://vim-adventures.com/
- http://robots.thoughtbot.com/vimulator
- http://www.viemu.com/vi-vim-cheat-sheet.gif
- http://blog.sanctum.geek.nz/vim-anti-patterns/
- http://www.moolenaar.net/habits.html
vim replacement icons
> **NOTE:**
>
> - StackEdit is accessible offline after the application has been loaded for the first time.
> - Your local documents are not shared between different browsers or computers.
> - Clearing your browser's data may **delete all your local documents!** Make sure your documents are backed up using **Google Drive** or **Dropbox** synchronization (see [<i class="icon-share"></i> Synchronization](#synchronization) section).
>
[^gfm]: **GitHub Flavored Markdown** (GFM) is supported by StackEdit.
[1]: http://www.vimninjas.com/2012/08/28/vim-for-rubyists-part-1/
[2]: http://static.thegeekstuff.com/wp-content/uploads/2009/12/gvim-setup-confirmation.PNG
[3]: http://static.thegeekstuff.com/wp-content/uploads/2009/12/gvim-license-agreement.PNG
[4]: http://static.thegeekstuff.com/wp-content/uploads/2009/12/gvim-installation-options.PNG
[5]: http://static.thegeekstuff.com/wp-content/uploads/2009/12/gvim-installation-location.PNG
[6]: http://static.thegeekstuff.com/wp-content/uploads/2009/12/gvim-installation-complete.PNG
[7]: https://github.com/gmarik/Vundle.vim
[8]: http://www.vim.org/scripts/script.php?script_id=2332
[9]: http://git-scm.com/
[10]: http://git-scm.com/book/en/Getting-Started-Installing-Git
[11]: https://github.com/tpope/vim-fugitive
[12]: http://www.vimninjas.com/2012/08/26/10-vim-color-schemes-you-need-to-own/
[13]: http://vim-adventures.com/
[14]: http://www.viemu.com/vi-vim-cheat-sheet.gif
[15]: https://raw.githubusercontent.com/LevelbossMike/vim_shortcut_wallpaper/master/vim-shortcuts_1280x800.png
[16]: http://mislav.uniqpath.com/2011/12/vim-revisited/
[17]: http://www.manicai.net/comp/swap-caps-ctrl.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment