Customizing vi

The Unix editor vi lets you customize its behavior in a numer of ways. There are two ways to customize vi. The first way is to enter command mode by hitting Escape, then type a colon and the command as it is shown.

The second way is to create a file called .exrc in your home directory. Each command goes on its own line, and the commands are parsed as though you typed them directly in vi. There are a couple rules your .exrc needs to follow:

  • No blank lines are allowed.
  • Directives must be typed on a single line.
  • Lines beginning with double quotes (") are marked as comments and are ignored.

Setting options

vi has some options which take values, and other options which are either on or off. To set an option with some value, type set [option]=[value]. To turn a boolean option on, type set [option], and to turn it off type set no[option]. Here are a few examples which will demonstrate the syntax as well as list some useful options.

  • set tabstops=4 – sets tabstop width to 4 spaces
  • set autoindent – turns on auto-indent
  • set ignorecase – ignores case for searching
  • set showmatch – highlights matching parentheses and brackets when you type them
  • set nowrapscan – searches will not wrap around to the beginning when they reach the end

Most options have abbreviations. You can find a full list of options, their abbreviations, and what they do at: http://ex-vi.sourceforge.net/ex.html#11

Abbreviations

By setting an abbreviation, vi will replace any occurance of the abbreviation you type with the full phrase. To set an abbreviation, type abbr [abbreviation] [full phrase]. For example:
abbr _ssc Social Sciences Computing will take effect whenever you type “_ssc”. You don’t need to type any special commands, it will be replaced as you type.

Mappings

Mappings are just like abbreviations except they work in command mode rather than typing mode. You can set a map to perform a common task, like common replacements or insertions. You can put as many commands as you like into the mapping. The syntax for mappings is: map [abbreviation] [command list]

An example of a useful mapping would be one that spellchecks a word:
map teh :%s/teh/the/g

This executes a document-wide replacement command (teh → the) whenever you type “teh” in command mode. Note that you can use colon-prefixed commands here too. Also note that a better way to solve the above spellchecker would be to say: abbr teh the and vi would spellcheck as you type. ;)


A sample .exrc file which demonstrates a lot of features can be found at: http://grox.net/doc/unix/exrc.php