5. Using vi

vi is the visual editor[1]. It was the first of its class and many fans say that it will also be the last to die. No matter if you're a fan or not, it's true that vi is very widespread and you can find it on most if not all Unix systems. At work we use vi as our default editor because it is slim, powerful, text based and widespread. There are great documents about getting started with vi, for example LINK. Good literature is listed at the end of this paper. But as vi is so important, I still give a brief introduction here.

5.1. Getting started

To edit a file, execute the command vi followed by a file name. You are now in the command mode of vi. There are two modes, command mode and insert mode. The first one is here to execute commands that manipulate the document, while the second allows you to insert new text into the document. To change from the command mode to the insert mode, use one of the edit commands. For example `i' or `a' to insert text at or after the cursor position respectively. Once in insert mode you can type your text as you would do with any other text application. To return to command mode hit the escape key.

5.2. Navigate in the text

For all of this commands you must be in command mode.

To navigate in the file you can use the four keys h, j, k and l on your keyboard. Depending on the system configuration you can also use the PC arrow keys.

If you know the line number you want to go to, enter that line number followed by a capital `G'.

5.3. Search & Replace

To search for a regular expression (see section Regular Expressions) press slash, type the pattern and then start search with the enter key. vi jumps to the first occurrence of the specified pattern. To go to the next occurrence, press `n'.

Replacing is done using the `:s' command. Type ':s/pattern/replacement/g' to replace all occurrences of pattern with replacement in the current line.

Most of the time you want to work with the whole file, though. That is done using the `:%s' command. Use ':%s/pattern/replacement/g' and pattern is changed to replacement in the whole file. If you aren't sure whether you really want to replace all occurrences, you can append the character `c' at the end of the line. This stops at every occurrence of the pattern and asks if you really want to replace.

5.4. Important commands

See BOOK for a great reference sheet that you can print out and stick on your wall. Very handy to put on your desktop is BOOK.

Notes

[1]

No, I'm not going to continue the holy war here. I also like emacs very much and I use both very often (this documentation has been written with emacs). But first, vi is more widespread and second it doesn't use that much diskspace. Because of these reasons you often find a server with only vi and no emacs.