Vim

From Noah.org
Jump to navigationJump to search

Vi is an archaic text editor from the early dawn of the computer age. It is amazing that it has survived to this day. Vi continues to evolve and adapt in the form of Vim. Learning Vim is like learning short-hand. It seems crazy and cryptic at first, but given time Vim will become second nature.

There are not many great books on Vim. It's best to start with the `vimtutor` which is installed wherever Vim in found. Just run `vimtutor`. Once you get comfortable I recommend Hacking Vim for intermediate users.

My .vimrc

This is a link to my super-terrific .vimrc file.

   .vimrc

You can also see the entire .vimrc file at the end of this article: #.vimrc.

To make full use of this you also want the .vim directory and everything below it.

I tried to balance vi compatibility and Vim features. I didn't want to make my vim so custom and unique that I would go crazy when I had to go back to a machine without my custom Vim. I tried to add some really useful features, but keep Vim familiar. Some have customized Vim so much that it is nearly unrecognizable (see Cream).

Temptations

It's very tempting to remap lots of keys, but this temptation can quickly get out of control. For example, I would like a little bit of emacs compatibility (CTRL-A and CTRL-E for beginning and end of line); an inverted T for cursor control would be better than HJKL cursor control; the redo key should be r not Control-R. But after a while you would not be able to use a stock Vim installation. This happened to me when I first learned Emacs. I had my own version of Emacs so tweaked that I forgot how to use the default key bindings. I avoid most temptations to "fix" Vim. It's better to stick with stock.

But I have made a few small concessions to sanity that deviate from the default Vim key mappings. The following .vimrc settings change Vim's default behavior.


Q

I mapped this to replay a recording named 'q'. My typical habit is to type qq to start a recording named 'q'. Then I type Q to replay the recording named 'q'. By default Q puts you in ex mode. When have I ever needed to use ex mode? Never.

<up> and <down>

These are mapped to do gk and gj, which move the cursor up and down based on the display rows. The difference is subtle. It's useful for editing 1000 character long lines with wrap set. The j and k keys still do the normal up and down. Only the arrow keys <up> and <down> are effected.

The power of :g

:g

Run a macro on matching lines

After you record a macro it's easy to play it back on lines that match a pattern (example assumes a macro recorded as 'q'):

:g/<pattern>/normal @q

Or run the macro on lines that don't match:

:g!/<pattern>/normal @q

Folding

Most folding is complicated and bothersome. These notes describe easy Vim folding.

My favorite trick is to fold on the current /search/ pattern. This way I can see only the lines that contain what I'm searching for. This is handy even for regular text documents, not just code.

set foldexpr=getline(v:lnum)!~@/
set foldmethod=expr foldlevel=0 foldcolumn=1

To make life easy, I map that to a key sequence \z (The <leader> character is the \ key on most systems).

map <silent><leader>z :set foldexpr=getline(v:lnum)!~@/ foldlevel=0 foldcolumn=0 foldmethod=expr<CR>

When I fold code, I just want show class, method, and function names. I just want an index view of my code. I don't want to fold on every nested statement, so I only need one level of folding. I add a map so that I can quickly set the search pattern to find all classes and functions. The following search pattern works for both PHP and Python:

/^\s*class\s\\|^\s*function\s\\|^\s*def\s/

I combine this with the search folding trick so that I can quickly fold code without the bother of syntax files or nested folding regions.

Finally, I add a map so that the SPACE key will toggle the hide/show state of the fold under the cursor.

To use these tips together, in normal mode type "zff" to highlight all classes and functions. Then type "\z" to fold. Now the document looks like an index. Press SPACE to view a class or function.

Put the following in your .vimrc file:

" folding using /search/ pattern
" \z
" This folds every line that does not contain the search pattern.
" see vimtip #282 and vimtip #108
map <silent><leader>z :set foldexpr=getline(v:lnum)!~@/ foldlevel=0 foldcolumn=0 foldmethod=expr<CR>
" this folds all classes and function to create a code index.
" mnemonic: think "function fold"
map zff :/^\s*class\s\\|^\s*function\s\\|^\s*def\s/<CR>:set foldmethod=expr foldlevel=0 foldcolumn=1<CR><CR>
" space toggles the fold state under the cursor.
nnoremap <silent><space> :exe 'silent! normal! za'.(foldlevel('.')?'':'l')<cr>

Intermediate Vim

help

Vim has very complete help, but it can be difficult to search because of the ambiguous matches on many commands. Usually it helps to specify the context (normal mode, insert mode, command-line command, etc.)

        WHAT                  PREPEND    EXAMPLE
    Normal mode command      (nothing)   :help x
    Visual mode command         v_       :help v_u
    Insert mode command         i_       :help i_<Esc>
    Command-line command        :        :help :quit
    Command-line editing        c_       :help c_<Del>
    Vim command argument        -        :help -r
    Option                      '        :help 'textwidth'

Dumb Vim commands that I actually use

These are commands that I thought seemed pretty lame when I first learned them. I thought that I would forget them quickly, yet for some reason I find that I keep using them.

CTRL-A CTRL-X

This increments a number to the right of the cursor. I thought this was totally pointless when I first saw it; yet, I seem to use it a lot.

 :h i_CTRL-A

CTRL-X does the opposite -- it decrements a number to the right of the cursor.

CTRL-O

This executes one command then returns to Insert mode. For example, if you want to reformat the paragraph you are editing type:

 CTRL-Ogwap

I tend to forget about the insert mode commands.

 :h i_CTRL-O

CTRL-W

This backspaces an entire word in insert mode.

 :h i_CTRL-W

Recording keystrokes

When you record a sequence of keystrokes using q these go into a register. You can paste the register and edit the recording then Yank the lines back into a register and play it back. This is handy if you have a long recording that you want to fix.

Visual mode range

Pressing v, V, or <C-v> in normal mode will switch to visual mode. This lets you select lines visually. If you go out of visual mode and want to return to visual mode with the same range that you had selected previously then type:

 gv

Run macro recording on a visual range

After you record a macro you may want to run the macro for each line in a range. For example, if your macro recording is store in register q then select a visual range and type:

 :'<,'>normal @q

To run the macro on every line in the file:

 :%normal @q

filename-modifiers

In Vim scripting you can refer to a the current working filename using %. For example, to make a backup copy of the current file do this:

silent! execute '!cp % %.bak'

There are also modifiers to filenames that allow you to just refer to the extension (%:e) of the filename before the extension (%:r). For example, the following makes a backup but changes the extension:

silent! execute '!cp % %:r.bak'


See help for more info:

  :h filename-modifiers

Set GVim as the default editor in Gnome

This saves you the hassle of having to set GVim as the default editor for each file type individually. Edit ~/.local/share/applications/defaults.list to look something like this:

[Default Applications]
text/plain=gvim.desktop

Vim Cheat Sheet

VIM Cheat SheetClick to view this handy VIM cheat sheet. This was taken from ViEmu -- home of vi/vim emulation for Microsoft Visual Sutdio.

.vimrc

<include svncat src="file:///home/svn/src/dotfiles/.vimrc" />