vi Primer

This is a primer for vi editor, written for someone just competent enough to log into a UNIX machine. I'm compiling this primer largely because vi can look so dry when first started up, and because the documentation for vi is spread across the manual pages for ed, ex and vi, and is none to clear. I make use of analogies to Microsoft Word or similar environments, so knowing a window based text editor on some platform will be useful but not required. This primer is best used while running a window with vi in it in parallel, i.e. on a Mac or Windows machine by running a terminal program, or on a UNIX box running an xwindows, so that all commands explained can be tried out immediately.

Editor Jihad

Now then, if you've been around the net for any significant amount of time, you've probably heard someone mention that choice of editor is a religious issue. Yet around Stanford it seems as though 80% of the people I've met only know emacs, or whatever editing environment thier favorite mail program provides. So this is a primer on vi, the competitor to emacs in the editor jihad, an editor whose totally different paradigm is a good thing to be exposed to, even if you don't end up liking it much.

Why vi?

Most people 'grew up on' an editor where you either use the mouse or some arrow keys to move around the screen, and anything you type appears immediately in text. All manipulations of text, or other special commands like saving, are accomplished through menus, or through key combinations involving the command keys to the left and right of the space bar. In vi, the default is not for text to go directly to the screen. Instead, you start out in command mode, and in this mode, even typing a random lowercase character can end up drastically altering your text. So a lot of beginning users tend to get flustered when they forget they are in command mode and accidentally take out half a page while just trying to type a sentence, but here's why command mode is useful:

o From command mode, you type either a lowercase i or a to begin inserting. Think about this: when you are typing in general, you type in long bursts of a sentence or two, then maybe move around and type somewhere else. Therefore getting in and out of insert mode doesn't significantly hamper your typing.

o While using the mouse can be useful and user friendly, a proficient vi user is typically even quicker at moving around his text than a mouse user, because his hands never leave the keyboard. Also the lack of mouse use makes vi use portable across almost any kind of terminal. A mouse based editor typically has little support for jumping through text with keyboard commands, and so is really a pain to use over a text terminal.

o Typically in a mouse based editor, or even one based on a prolific number of command keys, a user doesn't tend to use the features very much, since to do so means to stop typing, move to the menu and pick an item, or to hold down one or two keys and type another. So we are willing to retype whole phrases rather than go get them from elsewhere in the text. With vi, the commands are so immediate you won't be want to so much as retype a long word rather than quickly grab it.

o Last but not least, when you are proficient with vi, a person watching you type sees the cursor seem to jump around the screen at insane rates as if by the sheer force of your will, without any mouse intervention, and truly you seem to them to be on high.

Now, I know I'm not going to win the editor jihad on the spot, and I don't claim that emacs doesn't have a thousand useful features to it as well ( as many enjoy saying, it is an operating system unto itself ). I just want to let you know about the light at the end of the tunnel, so to speak, since a user starting up vi with no knowledge of it's use can typically percieve a featureless desert ( they can't even type anything, and when text does start appearing, they have no idea it's because they hit 'i' ).

Getting Started

So, the basics. There are two main modes to vi, as I've implied:

o Command Mode

o Insert Mode

Insert Mode

vi starts in command mode. To enter insert mode type a lowercase i or a. i is to start typing right at the cursor (insert), a is to start typing at the next space over (append). Now you can type whatever you want, and you can use your usual backspace to move backward and get at an error, but you can only get to text you have typed on this insert. In other words, it's not that you have suddenly entered Miscrosoft Word mode, you have only entered an insertion mode, and you can only affect the text you are inserting.

To leave insert mode, type [ESC]. This will trim off any characters you have backspaced through.

That's it for insert mode, we're halfway through! (sort of)

Command Mode

There are basically two kind of commands to use in command mode, ones that appear on the bottom of the screen as you type them, and those that don't (I'll hereafter refer to these as area commands and sweep commands respectively, for reasons we'll get into later). Area commands begin with either a colon (:), forward slash (/) or a question mark (?), and when you type this first character, vi displays it like a prompt at the bottom of the terminal with a cursor after it, and anything you type appears here and is sent as a command only when you hit return. Area commands are the kind of command Microsoft Word would pop up a dialog box for, i.e. searching text or saving a file. Sweep commands happen as soon as you have specified a complete command ( which we'll discuss later ), and are the reason vi is so powerful. But let's get through the file manipulation first.

File manipulations commands look like area commands, and all start with colons, but are really simple. Here's a list:

File Manipulation Commands

o :w [filename] writes the file you are working on to disk. You only need to specify a filename if you didn't specify a file to edit when you booted vi ( e.g., by typing vi foobar ), or if you want to save to a different file.

o :q This quits vi. If the buffer hasn't been saved since your last changes, vi will stop you once, and let you quit anyway the second time. You can force a quit without changes with :q!

o :e [filename] Open a file for editing.

o :n Edit the next file in the list of files to edit. That is, if you start vi with a list of files, or with a wildcard (i.e. vi lev* for all files starting with lev), then :n gets you the next file in the list.

That's it for the common, useful file manipulations. Now for the real reason I call these commands area commands.

Area Commands

You can specify an action to be done on an area of text, that is, a certain range of lines. This is a command that starts with a colon. You specify lines with an address, which is basically a pair of values separated by a comma indicating where to start and stop doing the action you specify. You can also use a $ to mean the last line in the loaded file, and a period (.) to mean the line you are currently on. And, you can use + and - to adjust the line numbers as well. So, to tie that all together, here are several example addresses and what lines they refer to.

5,11		Line 5 to line 11

6,$ Line 6 to the end of the file

.,50 From here to line 50

.,$-5 From here to five lines before the end of the file

Now you know how to specify an address. A useful thing to do if you specify addresses by specific line numbers a lot is to turn the line numbering option on, which basically makes vi display line numbers before every line. To turn this option on, hit colon and type set nu.

Now comes what addresses are for. Now that you have specified a range of lines,you can specify something to be done for every line. vi actually supports something nearly as complex as a scripting language for this kind of thing, and can even let you pipe the buffer out to a shell and back, but this is all very task specific info that one can learn from a man page (specifically the one for ex) once one is familiar with vi. What I'll explain here is probably the most freqently used command over a range of lines, which is the substitution command. It looks like this, with an address:


Notice there are no spaces. What this would do is go through the first fifty lines of the file being edited and switch all occurences of the word unix with the word UNIX. So this is useful as a quick way of fixing repeated spelling mistakes, or, if you are a programmer, to change a variable's name throughout a function.

One caveat: the substitution will only happen once per line. So the in the above example, you might end up with a line like this in your file:

which really makes UNIX unique. unix was written on top of C, because

To prevent this, you might want to repeat the command once or twice. Also, you can use just a % sign along to signify the address 1,$ (all lines), which is a useful shortcut considering find/replace operations are usually on the whole text.

Sweep Commands

Now we come to the real functionality of vi. The idea is this: in command mode there a wide variety of single keystrokes which can hop you around text. There are also various modes in which you can make these jumps. The default mode to make a jump in is just to move the cursor, but you can also specify that you want to modify all the text you sweep through on your way. This can be useful in somewhat larger tasks that you would typically reach for the mouse for, like deleting or moving an entire paragraph, and is also very useful in small changes like deleting the last word. So, here are the various most useful text movements:

Moving withing a line

w or W
move forward a word. little w counts apostrophes and such as word breaks.
b or B
back a word, same difference
jump to the beginning of the current line
jump to the end of the current line
Moving between lines

( or )
back or forward one sentence
{ or }
back or forward one paragraph ( to an empty line )
H or L or M
top, bottom and middle line of screen I suppose I ought to admit to as well that the arrow keys will move you around the text, should you resort to them. But they will not work with the "sweep modes" described below.


Searching in vi is as easy as touching the slash (/) key and typing in what to look for (use ? to go in the other direction). It is literally that simple. Here's some hints though, on what general parts of your text to use when jumping around:

o For typos: often typos juxtapose some consonants in a very unique way. If your jumping back to correct a typo you've spotted, this is usually the best way. For instance, searching for "dne" if you've typed "suddnely".

o Span your search phrase across words. For instance, look at the sentence above this. Searching backward to land in the phrase "consonants in a very..." I could search for "a v" and hit " a very unique..". Think about it: fruitless as trying to jump back to "a" or "very" would be in a long document, "a v" would probably only occur once every few pages or so!

o Don't be afraid to type too little. If you find yourself typing whole words for a search, your overdoing it, and your losing the efficiency vi can give you. Besides, if you hit the wrong phrase on a search, searching again is as easy as typing "n". So short of really blowing your search key (e.g. something like "ar"), you can just tap through the first few hits.

Hopefully your picking up on just how quick vi can be. Now then...

Sweep Modes

Edit text for about 15 minutes, consciously trying to use the keys above, and you'll be proficient already. Here's how that ability to move can be a powerful editing tool as well. As I said, as you move through text, using the methods above, you are in the default "pure movement" mode. You can also, for instance, change the text you are running through, with any of the following:

delete text. So a quick one is: dw ( deletes the next word on the line ). This is the equivalent of "cut" in Microsoft Word.
change text. Basically deleting some text and immediately entering insert mode.
yank text. This is the equivalent of "copy" in MS Word.

Mode and Movement

To use a mode on a move, just juxtapose them, mode first. So here is a slew of examples:

dw		delete next word
y$		yank to end of line
cw		change this word
db		delete last word
d/,		delete to next comma
d(		delete last sentence
y{		yank last paragraph
In a mouse based editor, what would you have done? Held down backspace until a sentence disappeared? Or get it with the mouse and hit delete? When you get used to using these you will be far more efficient.

Must-Know Tidbits

Here are various things that didn't fit neatly into any of the categories above, that even a first time user will really want to know:

o x deletes the character the cursor is on.

o J joins the current line and next line of text together.

o u undos the last command. There is something known as the undo buffer, which holds text to revert to, or text that was cut out. When you delete something, with dw for instance, this text goes into the undo buffer and can be retrieved by typing p or P ( P places the text after the cursor, p before ). You can also specify a different buffer to yank to (cut) and place from (paste) by typing a double quote and a lower case letter. So for instance:



...would delete to the end of the line and put it back. You can store various text segments in these buffers and grab them when necessary, because they will stay there the entire vi session. Not specifying buffer a in the above command would have done the same thing, but the yank'd text would have disappeared from the undo buffer the next time something was changed.

o dd deletes an entire line, even from the middle. cc does the equivalent for change.

o Typing a number before a command like dw or dd makes it repeat that many times. So, 5dd deletes five lines, and 5w jumps five words forward.

o Typing a number and then a G goes to number of that line. This can also be used in conjunction with a movement mode, as in d5G ( delete from here to line 5 ).

o [ctrl-d] and [ctrl-u] scroll you down and up file respectively. These do not work with sweep modes, i.e. d[ctrl-d] just beeps at you.

To become a true guru...

Aaaah yes, another aspirant. Well, I would suggest you make sure using the commands in this primer has become something of a reflex for you, then begin cruising the man pages every now and then to pick up more stunts. You should definetly check out the definition of a regular expression in UNIX ( on the ed man page ), and the ex man page contains the interesting area commands you can do. There are lot of interesting options for overall settings on the vi man page, along with keyboard mappings that make the shortcuts even shorter. You will also find a few less common variations of the commands given here in various places. There is also a program called nvi out (new-vi), which is a superset of vi with some off the wall capabilities like screen splitting. Have fun!