Skip to content

Instantly share code, notes, and snippets.

@wazery
Created May 25, 2014 10:00
Show Gist options
  • Save wazery/d68f8d6b65a2755f0e77 to your computer and use it in GitHub Desktop.
Save wazery/d68f8d6b65a2755f0e77 to your computer and use it in GitHub Desktop.
Welcome document
Vim for Rails
=====================
----------
## Contents
- Introduction to Vim
- Setting up your Vim
- Vim themes
- Editing .vimrc config
- Vim modes
- Vim commands
- Vim recording
- Killer commands
- Some Productivity Tips
- Source Navigation
- Vim Ruby Plugin
- Installation
- Usage/commands
- Rails.vim 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
## Introduction to Vim
### Brief history of Vi and Vim
### Why to use Vim, is Vim a text editor only?
### Vim for Rubyists
### 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][1]
Vim Installation Confirmation
![Vim 7.2 License Agreement][2]
Vim 7.2 License Agreement
![Vim Installation Option. (Make sure to select “Full” from the drop-down list)][3]
Vim Installation Option. (Make sure to select “Full” from the drop-down list)
![Vim Installation location ( directory should end with vim )][4]
Vim Installation location ( directory should end with vim )
![gVim Installation Progress and Completion][5]
gVim Installation Progress and Completion
#### 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][6] and [Pathogen][7], 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][8] first. [Here][9] 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][10] 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**
**7- Deleting 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][11] 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.
### 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 Vim.
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][12]. 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 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 and hence you learn new things. After some time you start composeing or chaining commands efficiently hence 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][13] 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][14] that will introduce you to the basic Vim movement commands. Have a look on it and try pracitce 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.
- 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 save and exit use `:wq!`.
- Undo.
- To undo last edit use `u`.
- 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!).
- 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`.
- Operate on lines.
- 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`.
- Switch between splits.
- To switch to the next split screen use `CTRL + w + w`.
- 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.
- Execute a shell command.
As mentioned before commands in Vim are mnemonic, which gives them simplicity.
> **Source:** Thoughtbot's [Vim checklist][15]
the basics:
How to switch from command mode to insert mode i
How to switch from insert mode to command mode Esc
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
How to save a file :wEnter (write)
How to exit without saving (in command mode) :q!Enter
How to Undo u
How to Redo Ctrl+r
You can combine writing and quitting (in command mode): :wqEnter
- Vim recording
- Killer commands
- Some Productivity Tips
- Source Navigation
Some Tips
- Copy to system clipboard
#### 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][16] 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.
----------
# 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://static.thegeekstuff.com/wp-content/uploads/2009/12/gvim-setup-confirmation.PNG
[2]: http://static.thegeekstuff.com/wp-content/uploads/2009/12/gvim-license-agreement.PNG
[3]: http://static.thegeekstuff.com/wp-content/uploads/2009/12/gvim-installation-options.PNG
[4]: http://static.thegeekstuff.com/wp-content/uploads/2009/12/gvim-installation-location.PNG
[5]: http://static.thegeekstuff.com/wp-content/uploads/2009/12/gvim-installation-complete.PNG
[6]: https://github.com/gmarik/Vundle.vim
[7]: http://www.vim.org/scripts/script.php?script_id=2332
[8]: http://git-scm.com/
[9]: http://git-scm.com/book/en/Getting-Started-Installing-Git
[10]: https://github.com/tpope/vim-fugitive
[11]: http://www.vimninjas.com/2012/08/26/10-vim-color-schemes-you-need-to-own/
[12]: http://vim-adventures.com/
[13]: http://www.viemu.com/vi-vim-cheat-sheet.gif
[14]: https://raw.githubusercontent.com/LevelbossMike/vim_shortcut_wallpaper/master/vim-shortcuts_1280x800.png
[15]: https://learn.thoughtbot.com/vim
[16]: 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