[Home] [About The World] [Kiosk Web Hosting] [Customer Help]
[Memo] [Login] [WebMail Login]


Brief introduction to the "vi" text editor


What's vi?

A text editor is a program that lets you edit text -- basically, a
word-processor that doesn"t do italics or colors. If you do work under
UNIX (that is, connecting to The World via telnet to speak directly to
the UNIX command line as opposed to using programs on your own
computer) you will occasionally need to edit a text file. (Heck, you
might even need to edit a mail message when you make a typo.) Examples
of different text editors include "pico", "vi", and "emacs". Today I"m
going to talk about how to use vi.  (If you don't like vi, pico is
considered by some to be more friendly, and emacs certainly has more
features.  vi is a middle-of-the-road program with a pretty big
feature set but it isn't obvious how to use it.)

In the earliest days of UNIX, there was only one editor: "ed".
ed was not what anyone would call verbose.  If something went horribly
wrong, ed's idea of displaying a detailed help message consisted of
ed saying:

                ?

That's right, ed never gave you more than a single question mark as
a way of letting you know what was going on.  So, about the only
thing the early UNIX programmers did with ed was to use it to write
better text editors.

One of the sons-of-ed was named "ex".  ex was a little more powerful
than ed.  Like ed, it was strictly command-driven (you couldn't
move the cursor around the screen, you had to retype any lines you
wanted to change) but it was a big step forward.  Then, around the
time computers started having screens instead of teletypes, some
clever guy came up with the idea of letting you move your newfangled
cursor up and down to edit anything anywhere.  So they added a mode
to ex that let you do that.  That mode was invoked with a command
named "vi" for "visual".

ex's vi-mode caught on and became more popular than everything else
in ex combined.  As a result, now the pair of ex and vi is known as
"vi" and it starts up in visual mode (and you can still enter ex
commands if you want to use the older parts that came from ex.)

This writeup will introduce you to some of the basics of vi.  It is
by no means comprehensive, but it introduces the commands you will
need to move around within a file, change text, search, and save.
(In general there's more than one way to do everything in vi.
I'm just going to cover all the commands you really need to know
to do actual work with vi.)

Getting In & Out

The first thing you'll need to know is how to start vi.  (Unless you've
already started it by accident, in which case the first thing you'll
need to know is how to exit vi.)

To start vi, type "vi filename".  (If that file doesn't exist, it will
create it for you.  You can also type "vi filename1 filename2 filename3"
or even "vi fi*" to edit multiple files at a time.)

To save your file and exit vi, type ":wq" (colon-w-q) and press the Enter
key.  ("Enter" = "Return" on Macs.)  ":wq" = "write and quit".

If you're editing more than one file, to save the current file and switch
to the next one, type ":w" (Enter) and then ":n" (Enter).  No, you
can't combine ":w" ("write") and ":n" ("next") into ":wn".

To exit vi WITHOUT saving your file, type ":q!" (colon-q-exclamation) and
press Enter.  (":q!" = "quit, yes, really.")


                    COMMANDS TO GET IN & OUT OF VI

    start vi                  --  "vi filename" at the UNIX command line

    start vi with multiple files  --  "vi filename1 filename2" or "vi fi*"

    write (save) & quit       --  ":wq" (Enter)

    write (save) & next file  --  ":w" (Enter) ":n" (Enter)

    quit without saving       --  ":q!"


Note:  The standard (ancient) version of vi has one cute little bug I've
run into from time to time -- if you type ":wq" really fast (so that you
type the "wq" before vi shows the ":" at the bottom left of your screen)
vi will sometimes save your document to a file named "wq" instead of
where it should save it.  So pause for a second between the ":" and the
"wq" if you type really fast.

If You Get An Error

When vi starts, it will display the size of your file at the bottom
and may also display a message if it wants to alert you to something.

"Read Only" means you don't have permission to write to that file
(you can look at it but not change it).

"Incomplete last line" means there's no carriage-return character at
the very end (usually not fatal.)

"Line Too Long" means there is a line with 1024 or more characters
on it, and vi (like many UNIX utilities) breaks at 1024 characters.
If you get "Line Too Long", you can't edit the file with vi.  (About
the only place you'll run into really long lines in your own files
is your .newsrc, which can sometimes develop really long lines.
Incidentally, emacs doesn't have a line-length limit.)

vi is also limited to files with fifteen million lines in them
(15,687,678 to be precise) but you probably will never have any
files that enormous.

Fundamentals of vi

As I said above, vi is the hybrid of a visual editor (where you can
move the cursor around the screen) and an older command-driven editor
(where you type commands and press Enter.)  Usually in vi you will
be moving the cursor around the screen pressing single keys that
do things.  Fancier actions require you to press ":" to type a
command (which might involve more than one key and is terminated
by the Enter key.)  In other words, vi has different "modes", which
can make it confusing for novices -- there's "moving the cursor
around the screen" mode, there's "typing a command" mode, and there's
also "I am inserting text now" mode.

Basically, the one-key commands don't require you to press Enter,
and commands starting with ":" do.  And when you're inserting or
replacing text, you'll need to tell vi when to stop (so that it
knows whether you're typing text or commands.)  We'll get to that
a little later.  First let's see how to move the cursor around the
screen.

Moving the Cursor

In vi, you can move the cursor with the arrow keys on your keyboard.
(At least if your terminal type is properly set, i.e. if The World
knows that you have a vt100 or whatever.  Most telnet programs do vt100
emulation.)  You can also move the cursor with the "h", "j", "k", "l"
keys if you're on one of those keyboards that doesn't have arrows.
(Fun fact: vi and the game "nethack" share those keys for moving.
However, vi doesn't let you move diagonally or kill monsters.)
Anyway, if you have arrow keys, and they seem to work, you know what
to do with them.

You can jump the cursor forward or backward by whole screenfuls with
"^F" (control-F) and "^B" (control-B) for "forwards" and "backwards".
(No, you can't use your "page up" and "page down" keys!  Those probably
just make your telnet window do weird things while vi is running.)

To go to the start or end of a line, you can use "0" (zero) to go
all the way to the left, and "$" to go to the end of a line.
(A long line might wrap around the screen a few times, by the way.)
Another way to go to the start of a line is "^", which takes you
to the first non-blank character (i.e. "0" goes all the way to the
left of the screen, while "^" goes to wherever your text is indented.)

To go to a specific line number, type ":123" (Enter).  The first
and last lines are ":1" and ":$".


                        MOVING AROUND IN VI

    move the cursor                 --  arrow keys
                                        or h (left), j (up),
                                        k (down), l (right)

    move by one screenful           --  ^F (forwards) or ^B (backwards)


    beginning of line               --  0 (zero)
                                        or ^ (caret) to go to the first
                                        non-blank character

    end of line                     --  $

    beginning of file (first line)  --  :1 (Enter)

    end of file (last line)         --  :$ (Enter)

    a particular line number        --  :123 (Enter)

Inserting, Deleting, and Replacing Text

Here's where the fun begins.  Above I said that you had to tell
vi when you were typing actual text versus typing commands.
(For instance, "h" moves the cursor to the left, so you need to
be able to switch between "h" meaning "left" and "h" meaning
the letter "h"!)

To go into "insert" mode (where words you type are actually inserted
into your document", press "i".  Anything you type from that point
onwards will be inserted (starting just before the character your
cursor was sitting on) until you press the Esc (escape) key.
"a" (for "append") works like "i" except it inserts the text after
the cursor's position instead of before.

You can also press "A" to append at the end of the line, or
"I" to insert after the first non-blank character at the start
of the line (i.e. at the start of your text after any indentation.)

To insert a new line, you can just press Enter while inserting/appending,
or press "o" (lowercase) to open a new line below the current line.
(Capital "O" will open a line above.)

If you make a mistake while typing, you can backspace with your backspace key
(it's marked "delete" on Macs and some other computers).  vi is smart
enough to know that both ASCII codes generated by different terminals
(^H and ^?) should be treated as backspace (unlike emacs which uses
^H for something altogether different.)

Once you've pressed Esc to stop typing text, you can press "u" (undo)
to remove whatever you've inserted.

To delete existing text, you can move the cursor anywhere and press "x"
to delete one character.  Type "dd" to delete the whole line.
(There are many other ways of deleting chunks of text, which you
can find in the manual.)

To replace a single character -- as in changing a "1" to a "2" in
your document -- put the cursor on it and press "r", then type one
character.  To replace a bunch of characters, press "R", type your
new text, then press Esc.



               INSERTING, DELETING, & REPLACING IN VI

    insert text before cursor location    --  i (type text and press Esc)

    append text after cursor location     --  a (type text and press Esc)

    insert at the start of the line       --  I (type text and press Esc)

    append at the end of the line         --  A (type text and press Esc)

    open a new line below the current one --  o (type text and press Esc)

    open a new line above the current one --  O (type text and press Esc)

    undo whatever you just did            --  u

    delete one character                  --  x

    delete a whole line                   --  dd

    replace one character                 --  r (then press a key)

    replace text                          --  R (type text and press Esc)


TIP:  If you're trying to type a command and it becomes part of
your document, press Esc!  (Then press "u" for "undo" to take it out.)

TIP:  If you're trying to insert text and vi keeps beeping, you
need to press "i" or "a" first.

When in doubt about what mode you're in, you can always hit "Esc"
to get control of your cursor back.  The worst it can do is beep at
you if you're already out of insert mode.

Miscellaneous Useful Commands

You can search the file (starting where the cursor is) by typing
"/" followed by some text and Enter.  (To search backwards from
where you are, use "?" instead.)  For power users, vi takes
"regular expressions" like grep, if you know what that means.

Pressing the "n" key will repeat your last search.  (The cursor
will cycle through the file repeatedly, so when the same match
shows up again, you know you've seen them all.)

To change two lines into one long line, press "J" (capital).
(It will put a space between them.)

If you want to copy a line to elsewhere in the file, type "yy"
(yank line) then move the cursor to the line it should be
inserted after and press "p" (paste).  To copy more than one
line, say "5yy" or "29yy" or whatever.  (Note:  When using "yy",
vi forgets the yanked text if you don't go paste it somewhere
right away.  In other words, you can't yank a line, edit something,
and then paste.)

If you feel the need to execute a single UNIX command while
vi is running, type ":!" followed by the command and Enter.
(Or, you can suspend and resume vi like any other UNIX program --
press ^Z to stop it, which brings up your UNIX shell, then
type "fg" to bring your vi session back.)

If you want to see what the olden days were like, pressing
capital "Q" will bring up the ":" prompt just as if you had
pressed ":", except that it will stay in command-driven mode (ex)
until you type "vi" to go back to using regular visual mode.


               MISCELLANEOUS USEFUL VI FUNCTIONS

    search forwards from here   --  / (type text and Enter)

    search backwards from here  --  ? (type text and Enter)

    repeat the search (next)    --  n

    join two lines              --  J

    yank (copy) a line          --  yy

    yank (copy) several lines   --  12yy

    paste below current line    --  p

    execute a UNIX command      --  :! (type command and Enter)

    suspend vi (go to shell)    --  ^Z (control-Z)

    resume vi (if suspended)    --  the UNIX command "fg"

    switch from visual editing to command-line (ex) --  Q

    switch from ex mode to visual editing           --  vi (Enter)

Setting vi as Your Default Editor

If you want vi (and not emacs or pico or some other editor) to
come up when some program wants you to edit something (such as
a mail message), find where "EDITOR" is defined in your .login
file -- there will be a line like this:

  setenv EDITOR /usr/local/bin/emacs

For vi, change that line of your .login file to:

  setenv EDITOR /usr/ucb/vi

(...or you could just learn emacs, which is more powerful anyhow.
It's even weirder, too.)

Various UNIX programs use that "EDITOR" variable to launch your
choice of editor when you ask to edit something.  For instance,
if you use the "mail" command to send mail, typing "~v" (Enter)
in the middle of a message will start your editor on that message
so you can alter it at will.

Setting Advanced vi Options

To set options permanently, you can create a file named ".exrc"
in your home directory containing settings that will be used
every time you start vi in the future.  One that I've used is

  set wrapmargin=8

...that automatically inserts a carriage return 8 spaces before
the 80th column (i.e. it breaks lines to be 72 characters or less.)
Obviously that it's something you want to do if you need long lines,
but it's great for mail.  You can turn it on and off in vi
with ":set wrapmargin=8" and ":set wrapmargin=0" (off).

There are a bunch of other options you can set, documented in
the manuals for vi and ex (see below.)

Additional Help

For a complete list of all the vi commands (there are many more
than I could show here) see the manual for vi.  It's the only
place you'll find some of the really obscure stuff documented.

  Official vi manual:

  world%  man vi

  (that means to type the UNIX command "man vi".  Your shell's
  prompt may look different from "world%".)

  To save the vi manual to a file you can download:

  world%  man vi | col -b >vi.txt

  (then you have a plain text file you can read anywhere,
  you could even read it in vi...)

  The extended commands (the ones beginning with colons)
  and options you can set are in the ex manual:

  world%  man ex

  And we have a slightly newer, slightly fancier version of
  vi named "nvi" which has a good command summary in its manual:

  world%  man nvi

We also have two other vi references on our Web site:

  Beginners help with vi:
  http://world.std.com/help/cmd/vi/beg.html

  Quick reference guide to vi & ex:
  http://world.std.com/help/cmd/vi/qcd.html

  Intro to vi (you're reading it):
  http://world.std.com/help/cmd/vi/vi-intro.shtml


(@) THE WORLD
Comments? Questions? Problems? Contact us.
Page last modified August 17, 2001.
Web site contents & design Copyright © 2001 Software Tool & Die.
  Legal info.