VI: Very Indispensible

Quick 'n dirty tutorial

Don't Panic

"All comments will be mostly welcome." > /dev/null
author:
federico yikong pietrolucci
last modified:
2001-01-02
target reader:
beginner or occasional UNIX users, especially developers.
scope:
Quick introduction to basic usage.

Contents

1. Prerequisites

It is assumed that the you are already able to: on your system. Actually, the tutorial was written with a UNIX environment in mind, although the vi editor has been ported to most other operative systems. Also, it is assumed that you know what a text editor cursor is, and that you are able to recognize an average one if you chance upon it. External shell tools named here are available for other platforms with the free cygwin package.

2. What is vi?

Vi(pronounced vee-eye, short for visual editor) is, in the UNIX world, the truly ubiquitous editor.
Whatever the vintage, flavour and size of your system, you can be confident vi will be among the available tools. Aquiring basic vi skills is among the most productive single steps you can take in order to enable yourself to do something useful with your UNIX account.
There have been sightings of IT-professionals using it as their sole text editing tool.
On the downside, vi requires you to memorize a number of keystroke combinations, that might take some time to get used to. Still, those same combinations are used in other useful tools found in a UNIX environment, which definitely turns out to be a boon if you spend a lot of time in the shell.

3. Running Thereto, and Gettin Out, too...

To run vi, just enter:

$ vi 
Note.

Ok, vi started. What you have before your eyes is a column of tilde ('~')characters. This is vi's representation of an empty document. The interface can be said to be Spartan, but there's actually even worse stuff out there.
Typically, there are at least two sorts of things one would expect to be doing with a text editor: type text, and give it commands (open or save documents, exit...)
Vi has two corresponding modes, which we may call insert and command respectively. In order to switch between these two modes, you use diverse key combinations.
Vi starts in command mode. Profit from this situation, and learn your first command, which will enable you to get out of there. Type:

:q
That's it: colon, 'q' and line feed. Out you go.
Notice that vi will prompt for confirmation befre exiting, in case you have not saved the latest changes in your document. In order to 'force' the command, append a '!':
:q!
Another eample of the usage of !:
:w!
This will force wrinting to a write-protected file.
Now let's do some actual text-mangling. Start vi again, then switch to insert mode by typing a single 'i'. Vi's interface, as pointed out earlier, is rather unobtrusive. The majority of versions won't show in any way that anything at all happened. Still, you just shifted mode, and you can now go on typing. Try!
Note that while, if you are used to GUIs, vi's curtness can be taunting, it actually helps keeping your mind and fingers on the task at hand, rather than distracting you with fireworks and notifications that are seldom necessary.

Alritee, that's enough now. It's time to save the fruit of your typing efforts. You will need to switch back to command mode first. You always do that by pressing esc. That's somewhere in the upper left portion of most keyboards I have seen of late.
Now enter the write command (':w') followed by a name for the file you save your text to:

:w myfile
That is: colon, 'w', space, file name and line feed.
Now get out of vi, and check that the file was created and that it contains what you typed. You could do this, for example, by using the cat program thusly:
$ cat myfile
And now...

4. Moving Around

By character

There is a wealth of commands allowing you to move (the cursor!) through the text in a variety of ways. In order to have a look at the commands as they are mentioned, you should open a sizeable document first. If you already have something you can use, fine. Otherwise, you could make a copy of, for example /etc/termcap, and use that as a scrap book.
Any which way, start vi and open your file.
Do it now, in one single step:

$ vi file
Or you can start vi as done earlier, and then use the edit command:
:e file
Now move around one character at a time, in the four directions left, down, up, right by just pressing the keys h, j, k, l respectively.
This might take a while to get used to, but it allows to move around in the text without changing your finger's stance. This is one general feature of vi, which those of you that do a lot of typing, and those who start to get aching joints from mouse usage, should be bound to appreciate.

By Word, Sentence, Paragraph and Block

You can move the cursor by word boundaries by pressing the keys w(forward one word), and b(backward one word.)
Moving around by sentence or paragraph is somewhat less intuitive. You use round parens ( '(' and ')') to move to the beginning of the previous and next sentences, respectively. You use curly parens ('{' and '}') to move to beginning of the previous and next paragraphs.
One feature that is particualrly interesting for developers is vi's ability to have the cursor move by text block as defined by parens pair: if you position the cursor on any kind of parens character, you can use the command '%' to jump to the matching opening or closing parens. It goes without saying that this is useful with huge blocks or when the structure of nested blocks gets complicated. Then again, that could be the time to consider refactoring the code you are working on instead... ;^)

By Line and Page

For those of you who are familiar with regular expressions, it will not be a surprise that vi's command to move the cursor to the beginning and end of a line are '^' and '$' respectively. If you mean to move up and down by line, and you think that the up and down command mentioned above don't cut it, you can use '-' and '+' to move to the beginning of the previous and next lines respectively.
If you are in a hurry, you can move up and down by half-screens (Ctrl-U, Ctrl-D), or by whole screens (Ctrl-B, Ctrl-F.)
You can move to a specific line by typing the line's number followed by 'G', or by typing colon, fllowed by the line number:

:69

5. Cut, Paste, Undo, Repeat. Copycat

Cut by Character and Line. Whoops...

In the unlikely case you want to correct the text in your hands, here's a few relevant commands. Firstly, you erase one character, the one currently under your cursor, by the command:

x
You can erase several characters at a time, starting from the one under your cursor and forward, by typing the number of characters to be deleted before the 'x' command:
666x
The majority of vi commands can be combined with numbers thusly, to multiply the number of times they are applied to the text by the editor.
to erase one word, you do:
dw
and to erase, say, six words in one swoop:
6dw
Which shouldn't surprise you if you paid attention so far. To erase the whole line your cursor is on, use:
dd
Even 'dd', as most commands in vi, can be instructed to act x times by prepending a number:
96dd
will erase 96 lines from the cursor's position.
Whoops! As you hit the linefeed key, you realise you only wanted to erase 69 lines... Vi has an undo command:
u
You are stuck with a one-level undo in most versions of our fine editor. Think twice cut once®.

the Grievous Paste

Whenever you perform an erase operation, vi copies the affected text in a register(yes, there are several registers.) You can paste back the register's contents using the commands:
P
to paste before the cursor, and
p
to paste after the cursor.

Copy

To copy stuff into the buffer directly, you can use the y command. (for yank into the buffer.) The yank command is special in that you must specify the direction in which the text to be yanked lies in respect to the cursor. Thus, in order to yank the word "supercalifragilistic", one would place the cursor on the word's first letter and use the command:
y20l
That is: "Yank 20 characters to the left". Horribly bothersome for long words. In this case, we should be more creative and do:
yw
instead. That is "yank one word". Guess what you do in order to yank several words?

Repeat

You can always repeat the latest command by pressing '.'.
As we've already seen, prepending an integer to commands will cause them to be executed a corresponding number of times.

6. Search, Replace and Suches

The search tool is activated by typing a slash ('/') in command mode. You then type the character pattern you are looking for, and press enter. The cursor is moved to the next occurrence of your pattern in the text. The search is case sensitive. Press 'n' to repeat the last search. You use '?' instead of '/' to search backwards. You can even reverse the search direction after entering the patternd just by using 'N' to repeat the search.
The search and replace syntax is:
:s/pattern/substitution
This will substitute the first occurrence of pattern with substitution. If you want to substitute all occurrences of pattern in your current line, you specify that by doing:
s/pattern/substitution/g
where 'g' stands for 'global'. Apply to the next 13 lines by doing:
s/pattern/substitution/g13
You tell vi to apply the pattern substitution to the whole file this way:
:%s/pattern/susbstitution/g
The '%' is taken by vi to stand for the open file. Weird? I agree.
Maybe you would like to actually confirm susbstitutions before they are performed. Adding the 'c' (confirm) flag to the above does the trick:
:%s/pattern/susbstitution/gc

7. Spell, Sort, Transform?

Vi does not come with an internal spell checker, or other fancy tools that allow you to insert my grandmother's birthday in iso-8601 format, or the list of active sockets on your machine or suches. However, a hefty number of specialized text-handling tools is generally included in any Unix system. As vi is able to execute shell commands, it is possible to use some of these powerful tools as if they were part to the editor itself. The spelling-checker 'spell' is likely to be one of the available tools on your system. Still, being spellan interactive tool, it has to be used separately. Non-interactive tools, on the other hand, can easily be used as filters from inside vi. To achieve this, enter ':' in command mode, add a direction (like seen earlier for the 'y' command), use the shell escape character ('!') and then the desired shell command. It takes more to say it than to do it. Here's a few 'interesting' cookbook examples.
Sort the next three lines (use the 'sort' program):
:.,+3!sort
That is: from the line we are on ('.') and three lines forward, filter with 'sort'.
Change all lowercase letters to uppercase (use the 'tr' (transform)) program:
:.,+3! tr '[a-z]' '[A-Z]'

That is: transform all letters in the a-z range to the correspondent letters in the A-Z range. Apply to the next three lines, including the one the cursor is on.

You can also insert ('read') a tool's output into your text with the 'read' command: to insert today's date in the text, by running the date from the shell
:r date 
That is read the output from date.

8. Quick Reference

Command line:

vi file
vi file1 file2 filen...
vi +n file
vi +/pattern file
edit file
edit files sequentially
edit file, jumping first to line n
edit file, jumping first to the first occurrence of pattern

Move:

h, j, k, l
w, b
(, )
{, }
%
Left, down, up, right by one character
forward, backward by one word
beginning of previous, next sentence
beginning of previous, next paragraph
to matching parens

Cut and Paste:

x
dd
y[ndirection]
yw
yy
p, P
erase character
erase line
yank ntimes in direction
yank one word
yank one line
put buffer's content after, before cursor

Search:

/,?
n, N
Search forward, backward
repeat search, repeat by inverting search direction

Exit:

:q
:q!
quit file.
quit file. force exit if the text has not been saved
:x, :wq
:wq!
Write, save if needed, and quit file.
As above, but force save if the file is write-protected

Miscellaneous:

.
<<, >>
:r
! cmd
repeat last command
indent left, right
read into text
escape to shell and execute cmd

9. Further Sources

i The VI Pages - All About VI and its clones
The VIM (Vi IMproved) Home Page
The vi Powered! logo (U.S. Mirror)

There is also an excellent nutshell book about vi.
Ah, and don't forget to do man vi!.

Notes

The '$' character here stands for the prompt the shell you are using provides you with. It could be some other character, or look completely different. You don't want to type the '$', in other words.
Ask your local guru if in doubt ®.
If nothing happens, or if your shell complains, for example to the effect that the program is not to be found, well, that's your sysop's department. Give him/her a call, get a cup of coffe and relax.