1. Introduction
  2. A sample dot-vimrc file
  3. Conclusion

1. Introduction

VIM (Vi IMproved) is a really powerful text-editor, and adding a few lines to your setup file (usually $HOME/.vimrc) can make your life a whole lot easier.

2. A sample dot-vimrc file

Here are some examples taken from my VIM setup file.

2.1. Basic settings

 1  " Basic settings
 2  set autoindent      " copy indent from current line for new lines.
 3  set autowrite       " save a modified file if you suspend your session.
 4  set directory=/tmp  " where your edit recovery file goes.
 5  set nobackup        " don't make automatic backups, I'll handle that.
 6  set nomodeline      " for security.
 7  set noremap         " don't let key mappings work recursively.
 8  set redraw          " redraw screen when VIM starts.
 9  set shell=/bin/sh   " use this shell for external commands.
10  set wm=2            " wrap line when 2 chars from right border.
11  set writeany        " allow writing a file without checking its mode.

Line 1 is your basic comment. Nothing to see here, please move along.

Lines 2-11 handle basic things that any editor should do, like whether or not you want the next line you type to be indented as far as the current line (autoindent), if/when the current line should wrap to a new one (wm), etc.

VIM comes with extensive online documentation; for example, typing ":help autowrite" will tell you how to make sure a modified file is automatically saved if you move to a new file or suspend your current edit session.

2.2. Where am I?

12  " Status line
13  set ls=2
14  set statusline=%F%h%m%r%=chr:0x%B\ \ %l,%c%V\ %P

Line 13 tells VIM to always show a status line somewhere on the screen holding information about the file being edited; you can turn this off if you're editing several files at one time and you don't want to waste any screen real-estate.

Line 14 defines the information displayed in the status line. In my VIM setup, I have it near the bottom of the screen, with one line below for entering commands. If I'm editing this file, I'm on the line starting with VIM comes with extensive, and my cursor is on the "e" in "online", the status line looks like this:

/tmp/vimrc.t2t                                       chr:0x65  38,31 14%

2.3. Changing what keys do

You can map keys or key combinations to do pretty much whatever you like.

15  " Key mappings
16  map   ;   >>
17  map   =   <<
18  map   g   <C-Z>
19  map   q   z.

I don't like pressing SHIFT if I don't have to, and I definitely don't like pressing two keys when one will do, so lines 16-17 will indent and un-indent a line by a single tab-space, respectively.

Line 18 lets me suspend my edit session and return to the shell by simply pressing "g" instead of Control-Z.

Line 19 lets me move the display to put the current line in the center of the screen by pressing "q", so I can see it more easily. I tend to miss things when the cursor is at the top or bottom of the screen.

20  map   E o<Esc>i....+....1....+....2....+....3....+....4....+....5<Esc>

Line 20 is me being lazy. The map command says pressing "E" is the same as doing the following:

Keystrokes What they do
o open a new line, enter insert mode...
Esc ...leave insert mode, cancelling any indenting ...
i ...start adding something that looks vaguely like a column ruler...
Esc ...and leave insert mode again

VIM will display a column ruler if you like, but it's at a fixed screen position. This way, it shows up where I want with one keystroke, so I can get rid of it with one keystroke (u = undo).

21  map   V   }jmbk{ma}:'a,.!fmt -1\|fmt<CR>'b

Line 21 reformats a paragraph with weird spacing to make it more readable:

Keystrokes What they do
} Jump to the end of the current paragraph...
j ... and go one line further...
mb ... mark the current position with the name "b"...
k ... go up one line (we're back in the paragraph again)...
{ ... jump to the beginning of the paragraph...
ma ... mark the current position with the name "a"...
} ... jump to the end of the paragraph again...
:'a,.!fmt ... run the paragraph through the "fmt" program...
-1 ... putting one word on each line...
|fmt ... pipe the result through "fmt" again, for regular-length lines...
<CR> ... end the command with a carriage-return...
'b ... and jump back to one line after the end of the current paragraph.

The backslash after "fmt -1" escapes the pipe symbol, which is necessary in map commands.

This lets me quickly handle paragraphs with odd spacing, lines that are way too short or long, etc. It leaves one space between words and two spaces after sentences, which I find easier to read; YMMV.

2.4. How to save typing

I enter dates and times quite often. Here are some ways to speed that up:

22  " Date and time abbreviations
23  inoremap ,d <C-R>=strftime("%a, %d %b %Y %T %z")<CR>
24  map ,t :.!sh -c 'line=`cat`; date -d "$line"'<CR>

25  if has("unix")
26      iab _day  <c-r>=strftime("%a, %d %b %Y")<CR>
27      iab _date <c-r>=strftime("%a, %d %b %Y %X %z")<CR>
28      iab _time <c-r>=strftime("%H:%M:%S")<CR>
29  endif

Line 23 says if you type a comma followed by a "d" in insert mode, replace both characters with the current time in this format: Thu, 30 Jul 2009 19:31:51 -0400

Line 24 shows how to filter all or part of your file through an external program. Let's do this one in pieces:

So, if I move to a line in this file consisting of the word "yesterday" and press comma-t, it would be replaced with yesterday's date.

Lines 26-28 show how to use abbreviations to insert time and date strings. When I'm entering text, an underscore followed by "time" will be replaced by the current time in hr:min:sec format.

2.5. Tabs

I don't like tab characters because you never know how they're going to display on someone else's screen. They also tend to show up at inconvenient times, like when I'm trying to cut up a file based on a given range of columns.

30  " Tabs
31  set shiftwidth=4
32  set tabstop=4
33  set expandtab

Line 31 sets the indentation used when you hit the tab key to 4 spaces, what Emacs calls c-basic-offset.

Line 32 causes the TAB character to be displayed as 4 spaces, what Emacs calls tab-width.

Line 33 causes only spaces to be used, what Emacs calls indent-tabs-mode.

2.6. Writing your own functions

You can use functions to insert, delete, or change lines when you enter or leave a file.

34  " Utility functions
35  autocmd BufWritePre * ks|call TimeStamp()|'s

Line 35 makes VIM call the TimeStamp function just before it saves a file.

36  function! TimeStamp()
37   if &modified
38    let lines = line("$") < 5 ? line("$") : 5
39    let pattern1 = '\(Last [Mm]odified:\).*'
40    let replace1 = '\1' . strftime(" %a, %d %b %Y %T %z")
41    execute printf('1,%ds/\C\m%s/%s/e', lines, pattern1, replace1)
42    execute printf('$-%d+1,$s/\C\m%s/%s/e', lines, pattern1, replace1)
43    let pattern2 = '\($Id: \f\+ \d\+\.\d\+\(\.\d\+\.\d\+\)*\)\(+\(\d\+\)\)\?'
44    let replace2 = '\=submatch(1) . "+" . (submatch(4) + 1)'
45    execute printf('1,%ds/\C\m%s/%s/e', lines, pattern2, replace2)
46    execute printf('$-%d+1,$s/\C\m%s/%s/e', lines, pattern2, replace2)
47   endif
48  endfunction

Lines 36-48 hold the function. Line 37 prevents it from doing anything unless the file has been modified. Line 38 will only make changes within the first or last 5 lines.

Lines 39-42 will look for the string "Last modified" (with upper- or lower-case "m") and replace anything after it with the current date and time in this format: Thu, 30 Jul 2009 19:31:51 -0400

Lines 43-46 will update an RCS revision string if one is present. RCS is an old but reliable version-control system that stores file revisions. It can insert revision and date information in a file if you include specifically-formatted strings. Putting the string dollarsign-Id-dollarsign at the bottom of this file and then checking out the latest version gives me a nice revision date and time summary:

$ Id: vimrc.t2t,v 1.13 2009/07/30 23:39:38 vogelke Exp $

Sometimes I forget to check in a file after I've modified it, which kind of defeats the purpose of using version-control in the first place. This VIM function will find any Id strings near the top or bottom of the file and modify the revision number to show that the file's been changed since it was last checked in. If I've made two edits since the last checkin, the Id string will look like this:

$ Id: vimrc.t2t,v 1.13+2 2009/07/30 23:39:38 vogelke Exp $

I notice this when I'm listing version information, and it keeps me out of all sorts of trouble.

3. Conclusion

This is a small sample of what VIM can do. The complete dot-vimrc file is here. Feel free to send comments.

Generated from vimrc.t2t by txt2tags
$Revision: 1.13 $