Logo Microtux


vi Manual


Unlike most word processors you may be used to, vi does not use modifier keys in command sequences. Typically on a PC, you would use some combination of function keys, alt, shift and ctrl. Vi was written to run on a text based system, and so almost entirely uses no modifier keys for commands.
Vi has two operational modes: COMMAND mode and INPUT mode.
When you start vi, you are in COMMAND mode. When you add, insert, replace, or change text, you need to enter INPUT mode. Pressing the ESC (Escape) key at any time, will return you to the command mode. If you are already in command mode, your terminal will simply beep you, telling you so.
For the next several sections, we will be in command mode only. We will learn about the input mode once we know how to navigate around in a file.
Starting vi
To invoke vi with a new (blank) file, simply type “vi” at the prompt:
>> prompt% vi
You should get a screen with the cursor blinking at the top left, and tildes “~” along the left margin. The tildes indicate that those lines are completely void of any characters (spaces, tabs, returns included).
To edit an existing file, type “vi” followed by the filename:
>> prompt% vi filename
You should see your file, along with a status line along the bottom stating the name of the file, the number of lines, and the number of characters in that file:
Example: “pton.list” 399 lines, 22543 characters
To view a file only (you will not be making any changes, or want to prevent any accidental changes) type “view” followed by the filename:
>> prompt% view filename
Cursor Keys
You can move the cursor around using the movement keys. “h” and “l” moves the cursor left and right; “j” and “k” moves down and up.
                   (left)     h         l    (right)
NOTE: The arrow keys work in vi as well, but not all terminals may have them. In any case using hjkl is recommended, since it keeps your hands on the keyboard, and so you don’t have to reposition your hand everytime you move the cursor. Alternative keys:
             (left)  Backspace            (spacebar) (right)
Word and Line Movement Keys
If you’re editing a file that’s primarily text (that is, words and sentences and not a ton of computer code) there are more convenient ways to move around than one column/row at a time.
We’re still in command mode. To move to the beginning of the next word, type “w”. To move to the beginning of the previous word, type “b”. You can also move to the end of the next word, type “e”.
>> Beginning of next word      w
>> Beginning of prev word      b
You can also jump to the start and end of lines if you’re somewhere in the middle. 0 (zero) or ^ (caret) jumps to the start, “$” jumps to the end.
>> Start of line               0 (zero) or ^
>> End of line                 $
If you’re a fan of run-on sentences, you might want to jump from sentence to sentence. Use “(” to move to the start of the previous sentence and “)” to move to the start of the next sentence.
>> Start of previous sentence   (
>> Start of next sentence       )
We can jump in even larger units. Using “{” and “}”, we can jump to previous and next paragraphs.
>> Start of previous paragraph  {
>> Start of next paragraph      }
Also, if you hit RETURN at any time, you will move to the beginning of the *next* line down.
>> Start of following line:  RETURN
There are also several commands to jump to relative locations on the screen and in the file:
>> Move to top of screen         H (home)
>> Move to middle of screen      M (middle)
>> Move to last line of screen   L (last)
One other useful command, is “G”, which let’s you jump to the end of your file:
>> Last line in file             G
In the next section we’ll see how to jump to any line in a file.
Number Counts
Much of the time even using the word movement keys is too slow. If we could jump any number of words/lines instead of having to press the keys each time, things would be much easier. Vi, therefore, provides a way to repeat commands.
>> To repeat command X, n times:  nX
To move 10 lines down         10j
To move 4 characters left     4h
To move 5 words right         5w
Number counts can be used with almost all movement and editing commands. As you know, “G” by itself moves to the last line. To move to the first line of a file, type “1G”. To move to the nth line, type “nG”.
>> First line in file:  1G
Example: 45th line in file 45G
Cancelling Commands
If at any time, you want to cancel a number count or any other command before you finish typing it, you can always hit ESCAPE.
Status Line
Sometimes when you jump around in a file a lot, you lose track of where you are. CTRL-G will give your current position and the file name you’re editing at the bottom of the screen. It should look something like:
“filename” line 20 of 399 –5%–
Scroll Commands
When you’re simply reading through a file, often times you just want to page through the text and not make any changes. Having to type “40j” every page would be too tedious.
Fortunately, vi has a set of scroll commands. To scroll down a screen (forward), press CTRL-f. To scroll back a screen (backwards), press CTRL- b. To scroll up half a screen, CTRL-u. To scroll down half a screen, CTRL-d.
>> Scroll forward one screen    CTRL-f
>> Scroll back one screen       CTRL-b        

>> Scroll up half a screen      CTRL-u
>> Scroll down half a screen    CTRL-d
Delete Commands
To delete a single character, type “x”. This deletes the character directly under the cursor and moves the remaining text to the right one space to the left.
>> To delete a single character at cursor      x
We can combine number counts with “x” as well:
delete 4 characters: 4x
Of course, if you want to delete large sections of text, typing “9999x” is a bit unwieldy. Fortunately (as you may have guessed), vi has another delete command, “d”.
By now, you know how to move an distance in any direction by combining a number with a movement key. The delete commands work in a similar fashion.
“d” is always used with another command, never by itself. We need to tell it which direction you want to delete and how far in that direction. We already know how to move any distance in any direction, right? Now all we do is combine “d” with any movement key and we’ve learned almost all the delete commands.
>> To delete from cursor to start of next word         dw
>> To delete from cursor to end of line                d$
>> To delete from current line to bottom of screen     dL
>> To delete one character before cursor               dh
(Note: “dl” works to delete one character at the cursor, but this is exactly what “x” does.)
Vi does provide a short cut for d$. You can use “D” to the same effect.
>> Shortcut delete from cursor to end of line     D
To delete the current line, instead of having to type “^d$” (move to start of line and delete to the end), vi has a shortcut command, “dd”.
>> To delete the current line   dd
Of course, “d” is just like any other command, so we can combine a number count with any “d” command.
Examples: Delete three words: 3dw Delete three words: d3w
Two ways? Which one is right? Vi isn’t picky. They’re both right. Deleting three words once (d3w) is the same as delete one word three times (3dw).
Now…what command would you use to delete 5 lines starting from the current line?
The expected way: 5dd Alternate way: 4dj
Why “4dj”? Remember, deletion always occurs relative to the cursor position when we give it a direction. So “4dj” deletes the current line and the 4 lines below it. Similarly, “4dk” deletes 5 lines, the current line and the 4 lines above it.
Other delete commands:
>> Delete from current line to end of file     dG
>> Delete from current line to start of file   d1G
>> Delete line 5                               5Gdd
    (this is merely combining two commands, 5G and dd)
Input/Editing Commands (finally!)
Now that we know how to navigate through files and delete text from them it’s time we learn how to insert text. There are six input modes: append, insert, change, open, substitute, and replace. Each mode has two invocations, lowercase first letter and uppercase first letter (i.e., “a” and “A” for append).
Remember that we always start in command mode. As soon as you type any of the input commands (except “r” replace) you stay in input mode until you hit ESCAPE. So in order for you to go back any make changes in what you’ve typed, just press ESC and move to where you have to go and enter the appropriate input mode.
To enter text, use either insert (i or I) or append (a or A).
>> Insert text before the cursor    i
>> Insert text after the cursor     a

>> Insert text at start of line     I
>> Insert text at end of line       A
Number counts, of course, can be used to do repeated insertions of text.
>> Insert 5 “newtext”       5inewtext

Example:  insert 5 copies of “hello”      5ihello
If you need to insert blank lines, use open (o or O).
>> Insert blank line below current line     o
>> Insert blank line above current line     O
(Just think of “lowercase = lower/below” and “uppercase = uppper/above”.)
Often times you want to type over something instead of having to insert new text and then delete old text. To do this we use change.
>> Change from cursor to end of line     C
>> Change a word to “newtext”            cwnewtext
>> Change entire line                    cc  (vi will blank out the entire
Note that when you use “C” vi will change the last character in the line to “$” to show you what how far your change in the text will delete the old text.
Similarly for “cw”, vi will change the last character of the word you intend to change into “$”.
Replace and substitute are fairly similar to change, although with subtle differences in usage.
>> Replace character at cursor with x        rx
>> Replace (overwrite) from cursor onward    R

Examples replace with 5 “g”‘s             5rg
Note that “r” with or without a number count will replace and then return you to command mode. “R” stays in input mode.
>> Substitute one or more characters for a single character    snewtext
>> Substitute entire line                                      S
Search (see also Search and Replace later in this section)
To jump a string or substring anywhere in your file, type “/” and the string you want to search for.
>> Search for a string “foo”     /foo
This search will move your cursor to the next occurrence (forwards search) of “foo” if it exists. You can jump to the next occurrence either by typing “/” by itself, or “n”. If you want to search backwards, use “N”.
>> Repeat search forward     n or /
>> Repeat search backward    N
If you are at the last occurrence of a string, a repeat search forward (n or /) will start search again from the top of the file. If the pattern doesn’t exist, it will give you the message “Pattern not found”.
Copy, Paste, Undo, Repeat
Vi also has the capacity to copy and paste text. Copying text is much like deleting text. You give it the copy command and then a direction and distance in that direction. The copy command is “y” (yank).
>> Copy current line     yy  or Y
>> Copy a word           yw
>> Copy 4 words          y4w  or 4yw
Now to paste what you’ve just copied, use the paste command, “p”, to paste after the cursor, “P” to paste before the cursor.
>> Paste after cursor    p
>> Paste before cursor   P
What about cut n’ pasting? You, in fact, already know how to cut and paste. The delete commands automatically save the text you last deleted into the paste buffer. It’s important to note that using the “x” command only deletes one character at a time, and therefore vi only saves each character individually. If you type “x” repeatedly and try to paste, you will only paste one letter.
However, if you use a number count with x, like “25x”, paste *will* insert all 25 characters.
>> Reversing two lines      ddp
>> Reverse two characters   xp
To paste what you previously pasted again, but somewhere else, go to your next point of insertion, and type Ctrl-@.
>> Insert previously pasted text here        ^@ (max of 128 chars)
You can also paste text without having to move your cursor to the location you want to paste to.
>> Paste current line after line 5  :t 5
>> Paste line x after line 5        :xt 5
>> Paste line 9 after line 5        :9t 5
If you want to move the text, instead of just pasting, use :m.
>> Move current line after line 5   :m 5
>> Move line x after line 5         :xt 5
>> Move line 9 after line 5         :9t 5
Of course, all this cutting and pasting would be rather dangerous if we couldn’t reverse the changes if we don’t like it. So of course vi has an undo command, and as you’d expect, it’s the letter “u”. Undo comes in two forms, like all the other commands: lowercase and uppercase.
>> Undo last modification                u
>> Undo all changes on a given line      U
“U” will undo all changes on a given line *only* if you keep the cursor on that line. As soon as you move the cursor to another line, you cannot undo all changes on that line. You can still undo the last change however using “u”. If you want to repeat the last editing command you did, use “.”
ex Commands (saving files, opening files, quiting vi)
Before vi was written, the only way to edit files was to use the line editor, ex. You had could only process one line at a time. Nowadays, there’s no need to rough it anymore, but vi carries over some of the file saving, opening, and quitting commands.
The ex commands are all invoked with the colon, “:”. Once you type “:”, vi will give you the ex prompt “:” in the lower left corner.
Saving and Quiting
Once you finish your editing, you’ll want to save your work and exit vi. There happen to three ways to quit and save.
>> To write (save) to file and quit  –>   :wq
                                            ZZ   (no colon)
Saving only
Often times you’ll want to save your work while still working on it (in case you accidentally get logged out, or the machine crashes, or you somehow lose your changes). To do this, simply type “:w”.
>> To write (save) to file     –>   :w
>> To write (save) to newfile  –>   :w filename
Vi protects your files, so in case you try to write to a file that exists, it will give you a message: “foo” File exists – use “w! foo” to overwrite
If you want to overwrite the existing file, then you use :w! filename
>> To write over existing file  –>  :w! filename
Quiting only
If you haven’t made any changes and simply want to exit, just type “:q”. If you *have* made changes, but do NOT want to save them, and you want to exit, then type “:q!”.
>> To quit                       –> :q
>> To quit (don’t save changes)  –> :q!
Shell escapes
If you need to execute a UNIX command while in vi you can make use of the shell escape. Just type “:! command”. Vi will execute your command and then return to your editing after you hit RETURN.
>> Execute UNIX command  –>   :! command
Shell escapes are useful for checking on filenames in your directory, or maybe reading mail that has recently come in.
Example,  :! ls
(see UNIX help section on alternate ways to do this, re: suspending jobs)
Opening files
Often times you’ll be editing a series of files. Having to type “vi file1” and exiting with :wq each time can be a hassle. If you know the name of your other files, you can open those files from inside vi, by typing “:e file2”.
>> Open another file  –>  :e filename
If you have made changes to your current file, you need to save your changes before using “:e” to open another file. However, as with :w and :q, you can override this by using “:e!”
>> Open another file (don’t save most recent changes)  –>  :e! filename
Inserting files
If you write a lot of mail message or post a lot of articles to USENET, many times you’ll want to append or insert other documents into your letter or article. To do this, move your cursor where you want the file, and type “:r filename”
>> Insert file at cursor position –>  :r filename
Status line
We saw back in the status line section that CTRL-g gives your file’s attributes. An alternative way is to use “:f”. This command also informs you if the file has been changed since you opened it with vi.
>> Show file status  –>   :f
Search and Replace
This is about as complicated as it gets in vi, since search and replace sytnax is taken from the UNIX sed (stream editor) command.
>> Global search and replace  –>  :1,$ s/old/new/g
                                     ^  ^  ^   ^  ^
In english, this means:              |  |  |   |  |
                                     |  |  |   |  |
            From 1 to $ (end of file)   |  |   |  |
                                        |  |   |  |
            substitute —————–/  |   |  |
                                           |   |  |
            occurrences of “old” ———-/   |  |
                                               |  |
            with occurrences of “new” ——–/   |
            globally (i.e., all instances of “old”)
I won’t go into details on using sed in this section (see the UNIX sections on sed and regular expressions), but you can easily change the range to search and replace from by changing “1” and “$” to your needs.