College of Arts and Sciences

Department of Mathematics

The vi Text Editor

Table of Contents
Using vi
Moving around
Inserting Text
Saving changes, and exiting vi
Deleting Text
Repeating actions
Finding and replacing text
Regular Expressions


Using vi

Vi is the standard editor for all UNIX operating systems. It is different from most other text editors in that it relies on "hot keys" to move around and insert text. Vi was designed before the mouse became a standard part of a computer, and so it was designed so that all movement actions could be generated from the keyboard. This makes it a less intuitive editor than some others.

To start the vi editor, simply type

vi filename

where filename is the name of the file you wish to edit. The screen will be filled with the first lines of the file. If you leave off the filename, then vi will create a new unnamed file. If the file you specify does not exist, then vi will create a new file, and assign it the given name.

The most important thing to remember about vi is that one it runs in two modes: command mode, and insert mode. In command mode, all keys are "hot", meaning that the keys are shortcuts to commands. One may not simply start typing to put in text. On the other hand, in insert mode one may type characters, and thereby modify the contents of the file. Even if the file being edited was just created, one must strike a key to tell vi to insert text before one may begin typing.

The second most important thing to remember about vi is how to get out. You may type "ZZ" at any time you are in command mode to save your changes and exit vi.

Moving around

To move the cursor around the screen, one should be in command mode. This is the state of vi when it is started. The simplest way to move around is to use the arrow keys. Just press the right arrow key to move one character to the right, the down arrow to move one line downward, and so on. Watch what happens when you try to move the cursor off the bottom of the screen. This may also be done using the h, j, k, and l keys. Try it.

Often one wishes to move faster. To move a whole screen length forwards, hold down the <Ctrl> key and press 'f'. To move a whole screen backward, hold down <Ctrl> and press 'b'. There are many keys to allow one to move quickly around the screen. A summary appears below.


Key          Action                                

<Ctrl> f     Move forward one screen               

<Ctrl> b     Move backward one screen              

<Ctrl> d     Move down half a screen               

<Ctrl> u     Move upward half a screen             

w            Move forward one word                 

b            Move backward one word                

$            Move to the end of the current line   

0            Move to the beginning of the current  
             line                                  

<Enter>      Move to the beginning of the next     
             line                                  

-            Move to the beginning of the          
             previous line                         



One may set a mark at any line that one desires to return to. To set a mark, type "m", followed by character to identify the mark, e.g. "a". In other words, from command mode, typing "ma" sets a mark at the beginning of the current line. To return to that line from any point in the file, just type 'a ("apostrophe a") from command mode.

Inserting Text

Move the cursor to an insertion point as described in the previous section. To insert characters in from of the character the cursor is pointing to, press the 'i' key. This puts vi into insert mode. Now type whatever characters are desired. When you are done inserting characters, press the <Esc> key (on VXT 2000 terminals, this is actually the F11 key). Whenever the <Esc> key is pressed, then vi leaves insert mode. If vi is not in insert mode when <Esc> is pressed, then it simply beeps, and remains in command mode.

The 'i' key is not the only way to put vi into insert mode. A summary of commands to insert text follows.


Key    Action                                                              

i      Insert text in front of the cursor                                  

I      Insert text at the beginning of the current line                    

a      Append text behind the cursor                                       

A      Append text after the end of the line                               

o      Open a new line below the current line, and insert text there.      

O      Open a new line above the current line, and insert text there.      

r      Replace one character.  The <Esc> key is not needed to leave        
       insert mode here.                                                   

R      Replace characters until <Esc>.                                     

cw     Change one word.  You may type in as many words to replace this     
       one as you wish.                                                    

cc     Change the current line.  You may replace this line with as many    
       lines as you wish.                                                  



Saving changes, and exiting vi

There are several ways to leave vi. As discussed in the introduction, the easiest is simply to type "ZZ" from command mode. An equivalent way to leave vi is to type ":wq" (for write-quit). This causes all of your changes to be saved to permanent storage, and then vi ends.

Sometimes it is desirable to quit vi without saving changes. To do this, type ":q!". This causes vi to quit without saving any changes to disk. Conversely, sometimes one wishes to save changes without quitting vi. To do this, type ":w". All changes will be saved to permanent storage, but vi will continue running.

Deleting Text

It is perhaps unfortunate that deleting text is very easy in vi. To delete a single character from command mode, simply type 'x'. To delete the entire current line, type "dd". A summary of delete commands appears below.


Command    Action                                

x          Delete current character              

dd         Delete current line                   

dw         Delete current word                   

D          Delete from cursor position to end    
           of line.                              



It is probably important to note that one may undo the last action (regardless of what it was) by typing 'u' from command mode. Thus if you should accidentally delete too many lines or words, one may immediately type 'u' to undo the action.

One should also note that none of the commands above work in insert mode. If one makes a mistake in inserting text, then one simply uses the backspace key to delete the offending characters.

Repeating actions

Any action described above may be applied to more than one character (or word or line) at a time. For example, to delete three words forward from the current word, type "3dw". Likewise, instead of deleting the words, one might choose to change them by typing "3cw". Thus, one could change the text "Do not change this text" to "Change this text" by putting the cursor at the beginning of the word "Do", typing "3cw" to put vi in insert mode, and then typing "Change". Of course, there are other ways to accomplish the same change. For example, one could place the cursor on the "Do", and type "2dw", which would delete "Do not" and leave the cursor at the beginning of "change". One could then type "r" followed by "C" to change the lower case "c" to an upper case character.

Another feature of vi that facilitates repetition is the "." command. This instructs vi to repeat the last command, starting from the current cursor position. For example, one might wish to alter the following lines of code.

dvi1 = sigma*epsilon;

dvi2 = sigma*delta;

Suppose that one wants to change both of the parameters dvi1 and dvi2 to be twice their previous size. One might move the cursor to the beginning of the word sigma on the first line, type "i" to put vi in insert mode, and then type "2.0*" followed by the <Esc> key. These actions would change the first line to dvi1 = 2.0*sigma*epsilon; . To change the second line, one would move the cursor to the beginning of the word sigma on the second line, and then press the "." key. This would change the second line to dvi = 2.0*sigma*delta. There are many other situations in which this command is useful. Again, one must take care to be in command mode in order to use this command.

Finding and replacing text

To find a text string or regular expression (regular expressions are discussed in the next section), press the "/" key and then type the expression that you wish to find, and then press <Enter>. Vi will search forward through the file to the first occurrence of the expression below the current cursor position. To find the next occurrence of the same expression, simply press "/" and <Enter>. It is not necessary to type the text of the string again. To find an occurrence of the string above the current cursor position, use "?" instead of "/". Note that certain characters in vi have special meanings, so they must be escaped, meaning that one places a "\" in front of them. The characters requiring this special treatment are listed below.

[ ] ( ) { } \ . , : ; '

Thus, to find the string "5.34", one would type /5\.34 .

Replacing text strings is somewhat more complicated. It requires the use of ex commands. Vi is actually an extension of a simpler line editor called ex, which provides a command-line interface for vi. It is possible to perform complicated manipulations of text by using ex, coupled with regular expressions. A full discussion of these properties is beyond the scope of this document, but the following should be enough to get started.

In order to use any ex command, one begins by typing the colon (":"). When this is done, the prompt moves to the lower left corner of the screen. Now one may type an ex command. A brief summary of ex commands appears in the table below.

Command                              Action                                

s                                    Substitute one regular expression     
                                     for another.                          

d                                    Delete a line.                        

y                                    Yank a line to the buffer.            


When using vi, the most useful of these seems to be the substitute command. Suppose that one wants to change the sentence

The quick green fox ate the small blue hare for breakfast, and then took a nap.

Since this sentence will be used repeatedly, it will be referred to as the hare line. The command :s/the/a/ tells vi to look for the string "the" and replace it with the string "a". The slashes act as delimiters, and could have been chosen to be almost any character. The result of either command is

The quick green fox ate a small blue hare for breakfast,

and then took a nap.

Note that vi did not change the first word, because it starts with a capital letter; it is not "the". Applying a numeric appendix to the command causes its effect to cover the whole line. For example, :s/he/wo/g changes the hare line to

Two quick green fox ate two small blue hare for breakfast,

and then took a nap.

while :s/he/wo/ yields

Two quick green fox ate the small blue hare for breakfast,

and then took a nap.

Applying g as a prefix has a different effect. It tells vi to search globally (over the whole file) for an expression which follows it. Thus the command :g/the/s//a/g tells vi to search for the string "the" through all of the file below the current line, and replace it with "a". It changes the hare string to

The quick green fox ate a small blue hare for breakfast,

and an took a nap.

Likewise, putting a numeric prefix on command line tells vi how many lines to apply the change to. Thus the command 2s/the/a/ would have the same effect on the hare line as the previous command.

Finally, one may append a "c" to the line to ask vi to check whether it should make each change or not. The command :g/the/s//a/gc would tell vi to go to the first occurrence of the string "the" below the cursor position, and then ask whether it should be changed to the string "a". Answering the question by typing "y" causes the change to be made. Vi then finds the next occurrence of the string, and again asks. Typing "n" causes vi to continue searching without making the change at that spot. The result on the hare line is

The quick green fox ate a small blue hare for breakfast, and then took a nap.

Vi has a the ability to cut, copy and paste text using ex. First, one sets a mark at the top of the section of text to be copied or cut, labeling it with "a", for the sake of the example. Next, one moves the cursor down to the last line to be cut or copied. Then, one types one of the following commands

:'a,.d            Delete text from the mark a to the current line,         
                  copying it into a buffer.                                

:'a,.y            Yank (copy) the text from the mark a to the current      
                  line to a buffer.                                        


To insert the text again, move the cursor to the point where the text is to be inserted, and type "p" (for put).

As a final example of a useful command, one might decide to go to the first character of the next five lines, and insert the character "c" (to comment lines out in Fortran). A command to do so is :5^i/c/.

The capabilities of ex go far beyond what is illustrated here. Though it is arcane (like everything that truly goes with UNIX), it is very powerful, and is one of the features that committed vi users like best.

Regular Expressions

To make full use of the properties of vi, or any UNIX editor, one should understand something about regular expressions. A text string is a simple collection of characters, such as "string" or "strin" or "stri". If one types "/stri" in vi, it will find "string", and it will also find "strings", "astringent", and "striated". A regular expression is a string of characters that is used to represent one or more text strings. This is done largely through the use of brackets. This is best illustrated through an example.

Suppose that one is editing a paper in which section five just became section six. One needs to find all references to section five, and change them to section six references. Unfortunately, sometimes section five is called "the fifth section", and sometimes it is called Section Five (One should be more careful...). The following command will find all such references.

/[Ff]i[fv]

The first bracket tells vi to look for strings that start with either "F" or "f". The second character must be "I", and the third character may be "f" or "v".

Suppose in a data file one wants to find a certain set of numbers: they all start with 1, then have a decimal point, followed by any digit, and then a 0. The following command would find such numbers.

/1\.[0-9]0

If the decimal point had not been escaped, then vi would have understood it to mean "match any single character." Thus 1@30 would be found. Similar expressions may be constructed with letters. The following command would find the words "starting", "carping", "starling", or any number of other similar words.

/ar[a-z]ing

The period (.) is not the only special character. The asterisk (*) is also useful for allowing matches of arbitrary numbers of characters. For example, /1*30 matches all of the following strings.

1.30

1-30

1+64z-30

Finally, one frequently wishes to find a word only when it lies at the end of a line. For example, to delete trailing spaces from lines of a program, one might type

:g/ $/s///g

This expression tells vi to look for a space at the end of a line, and replace it with nothing at all. Likewise, the character ^ represents the beginning of the line. Thus

:s/^ /c/5

tells vi to look for a space at the beginning of each of the next five lines, and if it is found, to change it to a 'c' (as in commenting out lines of code).

Regular expressions may be used in a variety of ways to create powerful commands that may save work. For a full discussion of the use of regular expressions in vi, consult the vi man page.

Department of Mathematics, PO Box 643113, Neill 103, Washington State University, Pullman WA 99164-3113 Phone: 509-335-3926 Fax: 509-335-1188 Contact Us