Unix vi Editor

John O’Gorman

john@og.co.nz

28 August 2002

1 Unix Editors - vi and emacs

Most Unix/Linux people use one of 2 editors to edit text files:
Both programs integrate well with the Unix/Linux environment. They allow you to filter text through unix commands (like sort) and to send text out to shell commands and piplines,
vi is very easy to learn but (arguably) less familiar to use. All its commands are mnemonic and there are only a few of them to learn.
emacs is more powerful but its enormous repertoire of command key sequences takes a lot of learning. In compensation, its modeless operation is more familiar to people from other OS worlds.
This paper is intended as an introduction to vi. it concentrates on the principles on which vi is based and lists the most frequently used commands. It is not intended to be a complete reference. Use the Linux command man vi or info vi commands for a complete reference (or in the Linux version of vi: :help).

1.1 Why bother to learn vi?

The Informix programs dbaccess and isql invoke vi when you take the USE Editor option for the Query menu. Similarly the Modify Form and Modify Report options of isql invoke vi.
The bash shell (if the environment variable EDITOR=vi) and ksh shell both accept vi commands to access and edit history commands. This makes command line sessions much quicker, easier, and for those with inconsistent typing skills, less error prone.
Most of Unix/Linux configuration (users, mail, network access etc.) is done in plain text files. Often the quickest and easiest way to reconfigure is to edit these files.
The use of shell scripts is a great labour saver. You can easily mechanise routine cyclical activities by putting command sequences into shell scripts. Use vi to create the scripts.

1.2 vi

vi (visual extension of ex) was written by Bill Joy at UCB (University of California Berkeley). It is an addendum to ex (extended editor) which was a line editor, vi is supplied with all Unix, Linux, and Mac OSX systems. Linux has a clone called vim (which is also a link to vi) a very near equivalent to the original vi. It basically has 3 modes:

1.3 emacs

emacs is an extremely large and complex program based on the LisP programming language. It is almost entirely configurabe by the user. It is modeless and requires the user to learn a very large number of control and escape sequences to execute editor commands. The user can create LisP macros and bind them to a control key sequence to create new commands.

2 Vi invocation end exit

To invoke vi, the command is vi filename
where filename is the name of a new or existing file.
If the file exists, the first screen-full of text will be displayed. vi will wait for you to enter some commands.
To exit from vi, you can do any of the following:
:wq
:x
ZZ
The above will all write any changes you have made and then exit from vi (returning you to the shell prompt).
If you have not made any intended changes to the text since invoking vi, you can insted exit with :q!

3 Vi modes

vi has 3 modes: command, text, colon. By default when you invoke vi you are in commond mode.

4 Vi commands

4.1 Text input commands

To enter text input mode, use the commands: open, append, insert, replace.
Command Action
0 ..........ESC open a line below the cursor
O ..........ESC open a line above the cursor
a ..........ESC append text after the cursor
A .........ESC append text after the end of current line
i ...........ESC insert text before the cursor
I ...........ESC insert text before the beginning of the current line
R ..........ESC replace (overwrite) characters
r replace a single character and go to command mode

4.2 Navigation commands

To move about the text, you can use arrow keys (or h,j,k,l which are their equivalent).
Navigation Commands
0 ^ $ first, first visible, last character in line
h j k l left, down, up, right arraow
w n e next word, beginning, end of word
W B E ditto, but treats any nonblank sequence as a word
G goto (by default last line, else line no)
( ) beginning,end of sentence
{ } beginning, end of paragraph
[[ ]] beginning, end of section
In the literature, the above are called motion indicators,

4.2.1 Search for patterns using / or ?

The / and ? keys allow you to search for the next (or previous) instance of a pattern. e.g. /John with find the next instance of John in the file. ? will search backwards for the pattern. To continue the search for the next instance, use n. N will search in the reverse direction.
The pattern you enter after the / or ? is called in the trade a regular expression .
Regular expressions (REs) can include values with represent sets, repetitions etc. A full list is boyond the scope of this paper but a few useful ones are:
RE example Meaning
. any single character
* zero or more instances of the previous RE
? zero or one instance of the previous RE
[aeiou] any one of the characters a,e,i,o,u
[^a-z] any one character except a-z
^ the beginning of the line
$ the end of the line
Note that some of the above REs (* and ?) have a deceptive similarity to shell wildcards. They are slightly different. The shells interpret a * on the command line as matching any sequence of zero or more characters. When used as part of an RE (in vi, sed, grep, awk, perl, etc) * means zero or more instances of the previous RE. The RE equivalent of the shells’ wildcard * is .* ( the . means any single character, so .* means any single character followed by zero or more instances of any character)
Also note the 2 completely different meanings for ^. If ^ is the 1st character inside brackets [], the ^ means the complement of the set. If ^ is inside brackets [] but not the 1st character then it matches the ^ character literally. In all other contexts, ^ means beginning of a line.

4.2.2 Mark Command m makes marks: a .. z

You can place up to 26 marks (labelled a to z) anywhere in the file. Use the mark command: m. e.g. ma will mark the current cursor position as mark a. To navigate back to a mark use either the quote command ’ or the backquote ‘. e.g. ’b will jump to the line of mark b,. ‘b with jump to the exact character of mark b.

4.3 Repeat Count

If you precede any of the above with a number, vi will treat that as a repeat count. e.g. 17G means go to line 17, 8w means jump along 8 words, 3k means go up 3 lines, and so on.

4.4 Change and Delete commands c and d

vi offers commands: change, delete to alter text.
The format of the command is:
The idea is that the command applies to all the text that the cursor passes over to get to the target. The examples above therefore deletes the cursor character and all the characters between it and where the 7w would take you (i.e. 7 words along)
Examples:
Command Action
6dw (or d6w) Delete 6 words
3cw (or c3w) Change 3 words
dG Delete to the last line
c$ Change text to end of this line
d/Unix delete text up to the word Unix
d’a delete text to mark “a

4.5 Cutting (or Copying) and Pasting

To cut and paste, you use the delete command, then move to the new location and type the p(or P) command to paste

4.5.1 Using named buffers “a .. “z

If you precede a yank or delete command with the buffer name “a ..”z, the passage deleted or yanked with to be saved in that buffer. This allows you to hole up to 26 pieces of separate text.
To paste from the named buffers, put the buffer name before the pasted command: p

4.5.2 Using numbered buffers “1 .. “9

When you do (say) 9 consecutive deletes, the most recent delete in held in the current buffer (which in unnamed), The one before that is held in buffer “1. Similarly each previous delete is held in buffers numbered up to “9
To paste from any of these numbered buffers, precede tge p command with the buffer id. e.g. “3p

4.6 Geminated commands (dd, cc, etc) affect lines

To apply a command to whole lines, geminate (ie.e repeat) the command letter
Command Action
5dd Delete 5 lines
6yy Yank 6 lines
cc Change the current line (enter text then ESC)
6p Past the buffer 6 times

4.7 Shortcut synonyms (x, s)

There is a small set of convenience commands:

4.8 Miscellaneous Commands: J ~ n N u U r xp

J joins the current line to the one(s) below.
~ inverts the case of the letter under the cursor
. repeats the last change command
u undoes the last change command
U undoes all changes to the current line
n jumps to next example of pattern (if you have searched with the / command)
N reverses the direction of the search pattern (if you have searched with the / command)
r replaces a single letter and immediately to to command mode (no ESC needed)
xp transposes 2 characters. This not really a separate command. It works because x deletes the character under the cursor (equivalent of dl - delete to right arror) and p pastes after the cursor.

4.8.1 Slash n .

A frequently useful command sequence to selectively alter text in a file is / n .
/ finds the pattern, n finds the next one, . repeats the command (without your having to retype it all in)
For example if you wish to replace most instances of Unix with Linux
  1. Use the / command to find the 1st instance of Unix: /Unix
  2. Change it to Linux: cwLinuxESC
  3. Get the next instance: n
  4. Repeat the change: .
  5. And so on.

5 ex (colon) mode

vi is a software addon to an earlier line editor called ex (extended editor). ex has a large set of commands, most of which you don’t need as they have equivalents in vi. But you do need to use ex to interact with the operating system - for things such as reading or writing files, getting the output from commands into your text, changing configuration options and so on.
The commands that you will most frequently use in ex mode are: read, write, quit, set. Examples are clearer than explanations:
Command Action
:r /etc/passwd read the contents of file /etc/passwd into our current file
:w write (i.e. save) the current contents to disc
:wq write and quit
:q! quit without saving
:r !date read the output from the command date into the current file
:w version2 write a copy of our work into a file called version2
:w !lpr -Plaser2 write the file to the print spooler for printing on printer laser2
:2,.d delete from line 2 to the current line (called . in ex)
:,.$s/Unix/Linux/g Substitute every instance of Uniz with Linux from here to last line
:! ls Tun the Unix ls command separately then return to vi
:e fred Without re-invoking vi, start editing file fred
:e # Change back to the previous file you were editing
:n Change to the next file (works only if you called vi with 2 or more args)
Note that ! (called bang vy Unix/Linux people) is used to indicate execution of a program. This is a common theme in applications Iincluding Informix and PLUS menus). If you use the bank for this purpose it must be the 1st character of part of the command, When you append the bank to a command (e.g.q!) it has a totally different meaning (override normal restrictions).