Master the vi Editor

If you love working in the command line window, the vi text editor is an excellent tool. It lets you work entirely from the keyboard, without having to touch a mouse or menus. It isn't hard to learn the basics, and it makes you tremendously efficient.

What Is Vi?

The standard specification of vi is the POSIX specification. Most systems today actually use vim, which implements a superset of vi. It comes already installed on many desktop systems, and downloads are available for the major operating systems. A GUI variant of vim, called gVim, is available from the vim site. Other vi-derived editors include neovim, which bills itself as a modernized version, and vile, which includes some features of Emacs. Getting the original vi is difficult, and there really isn't a good reason to. Using vim is the most straightforward choice.

Preinstalled Linux distributions usually include vim, but it may be the "tiny" version, with limited capabilities. Explicitly installing vim with the full set of runtime files may get you a more recent version as well as making sure you have the full features.

Different versions sometimes behave differently. The commands given here are verified with vim 7.3 (Mac) and 7.4 (Linux).

What Does Vi Do?

With vi you can edit text files using just the keyboard. This includes XML, TeX, HTML, and programming languages, but not binary files like Word or OpenDocument. To edit a file, type the command line:


vi filename

When vi runs, it takes over the terminal window. If the file already exists, the beginning of it will fill up the screen. The file's name will appear on the last line. If it doesn't already exist, the screen will fill with lines that are blank except for a tilde in the left margin. The bottom line will show "[New File]" after the name.

Initially, you're in command mode. This is one of vi's three main modes. In command mode, any keystroke is a command. You can start by pressing "i." You're now in insert mode, as the word "-- INSERT --" at the bottom of the window reminds you. Everything you type will be inserted as text. To get back from insert to command mode, hit the <esc> key.

The third mode is last line mode. You get to it from command mode by typing the colon (:) key. While you're in last line mode, you're entering a command line at the bottom of the window. It's executed only when you press <enter>. To save what you've inserted, type ":w" (colon followed by lower-case w and <enter>). That will write the file out. If it is a new file, you will need to provide a file name. This is done by entering ":w filename" followed by <enter>. After this, you will return you to command mode.

All keystrokes in vi are case sensitive! If you accidentally leave caps lock on, strange things can happen.

This article describes only some basic vi commands. For more advanced information, look at the vim documentation.

Small-Scale Movement

You can move the cursor with the arrow keys, or with "j" (down), "k" (up), "h" or <backspace>(left), and "l" or <space> (right). It is best to avoid the arrow keys for a number of reasons. The biggest is that your fingers don't need to leave the home position. Another is that they aren't always available — if you find an old version or one where the terminal type is not set correctly. Finally, if you us the :map function (see below), it is easier to use the letter commands.

You can advance one word with "w" or go back a word with "b."

Large-Scale Movement

Typing "0" will take you to the beginning of the line, and "$" to the end. Similarly, ":0" will take you to the beginning of the file, and ":$" will take you to the end of it. This is part of a general system where ":num" will take you to line number num. So ":101" will take you to line number 101. (If there are less than 101 lines in the file, it will take you to the end of the file.)

Vi usually allows you to do important things in more than one way. So you can go to a particular line with "Gnum" where num is the line number. It has the advantage of requiring one less character. But it has the disadvantage of not being consistent with "0" and "$" so that "0G" does not take you to the beginning of the file and "$G" doesn't take you to the end.

Two more critical navigation commands are ctrl-b to go back a page, and ctrl-f to go forward a page.

Adding and Modifying Text

You've already seen the "i" command to insert text. It will place what you type starting at the cursor position. The "a" command will insert text starting at the character after the one you are at. So it is easy to think of these two commands are insert (i) and append (a). If you remember those, you can easily remember the capitalized versions of these command. The "A" command inserts text at the end of the line, and the "I" command inserts text at the beginning of the line The capital "A" command will append what you type at the end of the line.

Typing "o" will open up a new line after the cursor line and let you start typing into it. Capital "O" will do the same before the cursor line.

Deleting Text

The deletion commands are highly versatile. Typing "dw" will delete a word, starting at the cursor position. You can put a number in front of it to delete that many words. So "3dw" will delete three words. Typing "d$" or "D" will delete to the end of the line. The "dd" command will delete the whole line, and "10dd" will delete ten lines. Typing "d " (the letter d followed by a space) or "x" will delete a single character. Typing "20x" will delete up to 20 characters but won't go past the current line.

Changing Text

The command to change text is "c." It works exactly the same as the "d" command except that it then goes into insert mode where the text was deleted. So 3cw will delete three words and replace them with whatever you type until you hit <enter>.

Don't panic if you deleted the wrong thing. The "u" command will undo the last change you made. In most implementations, you can enter it multiple times to undo recent changes. If you undo one time too many, ctrl-r will redo what you just undid.

One of the most powerful things in vi is the "." command. This repeats your last change. So if you just used "3cw" to change some text, entering "." will cause the next three words (wherever you are) to whatever you changed the last three words to. Or, if you just deleted ten lines with "10dd," entering "." will delete the next ten lines. This is also very useful with the ":map" command.

Pasting Text

You can move text from one place to another by deleting and pasting. The command to paste is "p" to paste after the cursor or "P" to paste before it. If you delete one or more full lines of text, the text will appear below (with "p") or above (with "P") the current line.

Yanking Text

The "y" command, for "yank," copies rather than deleting. It puts the text into a temporary buffer which you can paste elsewhere, once or multiple times. The options are like the ones for deletion, except that "yy" is used to yank a whole line. (This corresponds with "dd" to delete a whole line.)

Be careful. Each time you yank or delete, the text goes into the unnamed buffer, which is like the clipboard in other applications. It replaces the previous unnamed buffer. If you want to keep text around a little longer, you can use one of the 26 named buffers. You specify it by preceding its letter with a double-quote character. To yank four lines into the buffer named "c," type '4"cyy' (quoted in single quotes just for clarity). To paste it, you use the same double-quote character and buffer letter before the paste command. So if you want to paste the four lines we just copied to the "c" buffer to the line below the current one, you would use the '"cp' command.

Searching

To search for text, type "/" followed by the search string and <enter>. It will find the next match after the cursor, wrapping around to the top if necessary. To search backward, type "?" instead of "/."

Case

Searching is case sensitive by default. To do a case-insensitive search, start the search string with "\c". So if you use "/\cthis" followed by <enter>, vi will find "this" regardless of its capitalization. You can also change the default by entering ":set ignorecase" followed by <enter>. You can also enter ":set ic." To go back to case sensitive searches, you would enter ":set noignorecase" or ":set noic."

You can repeat the last search with the "n" command. If you wish to search in the opposite direction, use the "N" command.

Regular Expressions

The search string is actually a regular expression. This lets you search for patterns, but certain characters don't work as literal matches. As a simple example, searching for "w..d" will find "wood," "wind," or "w00d." This is because "." in a search matches any character. If you want to search for the "." you enter a backslash before it. So you would enter the "/\." command.

For more information on regular expressions, check out our article, Regular Expressions Primer and Resource.

Working With Files

As already mentioned, ":w" will save the file. If you want to save it to a different file, type ":w newfilename." When you're all done with vi, you can type ":wq" to save and exit. Don't forget that a last-line command starting with a colon requires you to type <enter> to complete it. As a result, many vi enthusiasts use the "ZZ" command, which does the same thing.

New File

To switch to a different file, type ":e newfilename". If you haven't saved the previous file, vi will warn you. If you really want to discard your changes, use "e! newfilename". You can use ":e!" without a filename if you've messed up and want to return to the last saved version of the current file.

You can switch between the current file and the last file you edited by using the ":e#" command. With this, you can switch back and forth between two files, which is similar to editing two files at once, which we discuss below.

Multiple Files

You can edit multiple files at once and switch among them. In vi terminology, you're switching among their edit buffers. To edit multiple files in one session, launch vi with a command line like this:


vi file1 file2 file3

The first file you list will appear on the screen. To cycle through them, you can use ":bn" (next buffer) or ":bp" (previous buffer). You can yank into named buffers to copy text from one file to another. (Edit buffers and paste buffers are two different things. It's a little confusing.)

Shell Commands from Vi

You can run shell commands without leaving vi. To do this, type ":!" (colon and exclamation mark) followed by the command. You'll see the output of the command, and then you need to hit <enter> to get back to command mode. You can even type ":!sh" to run a shell from within vi, perform multiple commands, and then exit back to vi. This is handy if you're editing some code and want to test your changes.

You can run a shell command and insert its output into the current file by typing ":r!command".

Keyboard Mapping

One of the most powerful things about vi is its ability to map commands onto keys. It is done as follows:


:map key commands

The key is a single character. It can be any character, but you are best off not using a key that is already a command like "c" or "a." The commands can be quite complicated. They can, for example include the enter key with "<enter>" and the escape key with "<esc>." So if you have a repetitive task, you can easily map it to a single key. For example, the following command will cause the "q" key to move to the the second word of the next row, change it it to "Help!" and return to the first character of the original row:


:map q j0wcwHelp!<esc>k

The map command is at its most powerful when combined with regular expressions and the repeat (".") command. Whenever you find yourself doing something boring while in vi, see if you can construct a mapping that can do it. In most cases, you can.

Further Reading

This has been a very quick overview of what's possible in vi. Again, check the documentation for complete information. You might want to bookmark a cheat sheet, such as vimsheet.com or the Vim Cheat Sheet for Programmers. Here are some more resources:

Tutorials

Books

It takes a while to become a vi expert, but once you get there, you'll wonder why you ever bothered with a mouse.