The vi editor

Two modes

The vi is a very powerful tool and has a very extensive manual. We will only discuss the very basics here to get you started. The vi editor has an excellent built-in help function that will teach you all there is to know.

What makes vi confusing to the beginner, is that it can operate in two modes: command and insert mode. The editor always starts in command mode. Commands can move you through the text, search, replace, mark blocks and perform other editing, and some of them switch the editor to insert mode.

This means that each key has one but likely two meanings: it can either represent a command for the editor when in command mode, or a character that you want in a text when in insert mode.

Note

It's pronounced "vee-eye".

Basic commands

Moving through the text

Moving through the text is usually possible with the arrow keys. If not, try:

  • h to move the cursor to the left

  • l to move it to the right

  • k to move up

  • j to move down

SHIFT-G will put the prompt at the end of the document.

Basic operations

  • n dd will delete n lines starting from the current cursor position.

  • n dw will delete n words at the right side of the cursor.

  • x will delete the character on which the cursor is positioned

  • n CTRL-G moves to line n of the file.

  • :w will save (write) the file

  • :q will exit the editor

  • :wq will save and exit

  • /astring will search the string in the file and position the cursor on the first match below its position.

  • / will perform the same search again, moving the cursor to the next match.

  • :1, $s/word/anotherword/g will replace word with anotherword throughout the file.

  • :recover will recover a file after an unexpected interruption.

Commands that switch the editor to insert mode

  • a will append: it moves the cursor one position to the right before switching to insert mode

  • i will insert

  • o will insert a blank line under the current cursor position and move the cursor to that line.

Pressing the ESC key switches back to command mode. If you're not sure what mode you're in because you use an old version of vi that doesn't display an "INSERT" message, type ESC and you'll be sure to return to command mode. It is possible that the system gives a little alert when you are already in command mode when hitting ESC, by beeping or giving a visual bell (a flash on the screen). This is normal behaviour.

Other features

Some implementations of vi support the :help command. If they don't, refer to the manpage.

Some Unix distributions provide vim, vi improved. This version uses the same commands, but has additional features such as support for a number of programming languages, multilevel undo, syntax highlighting, filename completion etc:

Figure 1. Vi IMproved screenshot