You are on page 1of 28

How to Use the vi Editor*

*Copyright 1991 by Simon Fraser University. Reprinted with permission.

The vi editor is available on almost all Unix systems. vi can be used from any type
of terminal because it does not depend on arrow keys and function keys--it uses
the standard alphabetic keys for commands.

vi (pronounced "vee-eye") is short for "vi"sual editor. It displays a window into


the file being edited that shows 24 lines of text. vi is a text editor, not a "what you
see is what you get" word processor. vi lets you add, change, and delete text, but
does not provide such formatting capabilities as centering lines or indenting
paragraphs.

This help note explains the basics of vi:

• opening and closing a file


• moving around in a file
• elementary editing

vi has many other commands and options not described here. The following
resources can help you get started using the vi editor, and are available at the UW
University Book Store:

• "vi Tutorial." Specialized Systems Consultants (SSC).


• "vi Reference." Specialized Systems Consultants (SSC).
• "Learning the vi Editor." Linda Lamb, 1990.

Starting vi

You may use vi to open an already existing file by typing

vi filename

where "filename" is the name of the existing file. If the file is not in your current
directory, you must use the full pathname.

Or you may create a new file by typing

vi newname

where "newname" is the name you wish to give the new file.

To open a new file called "testvi," enter


vi testvi

On-screen, you will see blank lines, each with a tilde (~) at the left, and a line at
the bottom giving the name and status of the new file:

"testvi" [New file]

vi Modes

vi has two modes:

• command mode
• insert mode

In command mode, the letters of the keyboard perform editing functions (like
moving the cursor, deleting text, etc.). To enter command mode, press the escape
<Esc> key.

In insert mode, the letters you type form words and sentences. Unlike many word
processors, vi starts up in command mode.

Entering Text

In order to begin entering text in this empty file, you must change from command
mode to insert mode. To do this, type

Nothing appears to change, but you are now in insert mode and can begin typing
text. In general, vi's commands do not display on the screen and do not require the
Return key to be pressed.

Type a few short lines and press <Return> at the end of each line. If you type a
long line, you will notice the vi does not word wrap, it merely breaks the line
unceremoniously at the edge of the screen.

If you make a mistake, pressing <Backspace> or <Delete> may remove the error,
depending on your terminal type.

Moving the Cursor


To move the cursor to another position, you must be in command mode. If you
have just finished typing text, you are still in insert mode. Go back to command
mode by pressing <Esc>. If you are not sure which mode you are in, press <Esc>
once or twice until you hear a beep. When you hear the beep, you are in command
mode.

The cursor is controlled with four keys: h, j, k, l.

Key Cursor Movement


--- ---------------
h left one space
j down one line
k up one line
l right one space

When you have gone as far as possible in one direction, the cursor stops moving
and you hear a beep. For example, you cannot use l to move right and wrap around
to the next line, you must use j to move down a line. See the section entitled
"Moving Around in a File" for ways to move more quickly through a file.

Basic Editing

Editing commands require that you be command mode. Many of the editing
commands have a different function depending on whether they are typed as
upper- or lowercase. Often, editing commands can be preceded by a number to
indicate a repetition of the command.

Deleting Characters

To delete a character from a file, move the cursor until it is on the incorrect letter,
then type

The character under the cursor disappears. To remove four characters (the one
under the cursor and the next three) type

4x

To delete the character before the cursor, type

X (uppercase)

Deleting Words
To delete a word, move the cursor to the first letter of the word, and type

dw

This command deletes the word and the space following it.

To delete three words type

3dw

Deleting Lines

To delete a whole line, type

dd

The cursor does not have to be at the beginning of the line. Typing dd deletes the
entire line containing the cursor and places the cursor at the start of the next line.
To delete two lines, type

2dd

To delete from the cursor position to the end of the line, type

D (uppercase)

Replacing Characters

To replace one character with another:

1. Move the cursor to the character to be replaced.


2. Type r
3. Type the replacement character.

The new character will appear, and you will still be in command mode.

Replacing Words

To replace one word with another, move to the start of the incorrect word and type

cw

The last letter of the word to be replaced will turn into a $. You are now in insert
mode and may type the replacement. The new text does not need to be the same
length as the original. Press <Esc> to get back to command mode. To replace three
words, type

3cw

Replacing Lines

To change text from the cursor position to the end of the line:

1. Type C (uppercase).
2. Type the replacement text.
3. Press <Esc>.

Inserting Text

To insert text in a line:

1. Position the cursor where the new text should go.


2. Type i
3. Enter the new text.

The text is inserted BEFORE the cursor.

4. Press <Esc> to get back to command mode.

Appending Text

To add text to the end of a line:

1. Position the cursor on the last letter of the line.


2. Type a
3. Enter the new text.

This adds text AFTER the cursor.

4. Press <Esc> to get back to command mode.

Opening a Blank Line

To insert a blank line below the current line, type

• (lowercase)

To insert a blank line above the current line, type


O (uppercase)

Joining Lines

To join two lines together:

1. Put the cursor on the first line to be joined.


2. Type J

To join three lines together:

1. Put the cursor on the first line to be joined.


2. Type 3J

Undoing

To undo your most recent edit, type

To undo all the edits on a single line, type

U (uppercase)

Undoing all edits on a single line only works as long as the cursor stays on that
line. Once you move the cursor off a line, you cannot use U to restore the line.

Moving Around in a File

There are shortcuts to move more quickly though a file. All these work in
command mode.

Key Movement
--- --------
w forward word by word
b backward word by word
$ to end of line
0 (zero) to beginning of line
H to top line of screen
M to middle line of screen
L to last line of screen
G to last line of file
1G to first line of file
<Control>f scroll forward one screen
<Control>b scroll backward one screen
<Control>d scroll down one-half screen
<Control>u scroll up one-half screen

Moving by Searching

To move quickly by searching for text, while in command mode:

1. Type / (slash).
2. Enter the text to search for.
3. Press <Return>.

The cursor moves to the first occurrence of that text.

To repeat the search in a forward direction, type

To repeat the search in a backward direction, type

Closing and Saving a File

With vi, you edit a copy of the file, rather than the original file. Changes are made
to the original only when you save your edits.

To save the file and quit vi, type

ZZ

The vi editor editor is built on an earler Unix text editor called ex. ex commands
can be used within vi. ex commands begin with a : (colon) and end with a
<Return>. The command is displayed on the status line as you type. Some ex
commands are useful when saving and closing files.

To save the edits you have made, but leave vi running and your file open:

1. Press <Esc>.
2. Type :w
3. Press <Return>.

To quit vi, and discard any changes your have made since last saving:
1. Press <Esc>.
2. Type :q!
3. Press <Return>.

Command Summary

STARTING vi

vi filename edit a file named "filename"


vi newfile create a new file named "newfile"

ENTERING TEXT

i insert text left of cursor


a append text right of cursor

MOVING THE CURSOR

h left one space


j down one line
k up one line
l right one space

BASIC EDITING

x delete character
nx delete n characters
X delete character before cursor
dw delete word
ndw delete n words
dd delete line
ndd delete n lines
D delete characters from cursor to end of line
r replace character under cursor
cw replace a word
ncw replace n words
C change text from cursor to end of line
o insert blank line below cursor
(ready for insertion)
O insert blank line above cursor
(ready for insertion)
J join succeeding line to current cursor line
nJ join n succeeding lines to current cursor line
u undo last change
U restore current line

MOVING AROUND IN A FILE

w forward word by word


b backward word by word
$ to end of line
0 (zero) to beginning of line
H to top line of screen
M to middle line of screen
L to last line of screen
G to last line of file
1G to first line of file
<Control>f scroll forward one screen
<Control>b scroll backward one screen
<Control>d scroll down one-half screen
<Control>u scroll up one-half screen
n repeat last search in same direction
N repeat last search in opposite direction

CLOSING AND SAVING A FILE

ZZ save file and then quit


:w save file
:q! discard changes and quit file

1. Command Line Options

Command Action
vi file Invoke vi on file
vi file1 file2 Invoke vi on files sequentially
view file Invoke vi on file in read-only mode
vi -R file Invoke vi on file in read-only mode
vi -r file Recover file and recent edits after a crash
vi -t tag Look up a tag and start editing at its definition
vi -w n Set the windows size to n; useful over a slow connection
vi + file Open file at last line
vi +n file Open file directly at line number n
vi -c command Open file, execute command, which is usually a search command
file or line number (POSIX)
vi +/pattern file Open file directly at pattern
ex file Invoke ex on file
Invoke ex on file, taking commands from script; surpress
ex - file <script
informative messages and prompts
ex -s file Invoke ex on file, taking commands from script; surpress
<script informative messages and prompts (POSIX)

2. vi Commands

Most vi command follow a general pattern:

[command][number]text object

or the equivalent form:

[number][command]text object

Movement Commands

Command Meaning

Character
h, j,
k, l Left, down, up, right

Text
w, W,
b, B Forward, backward by word
e, E End of word
), ( Beginning of next, previous sentence
}, { Beginning of next, previous paragraph
]], [[ Beginning of next, previous section

Lines
RETURN First nonblank character of next line
0, $ First, last position of current line
^ First nonblank character of current line
+, - First nonblank character of next, previous line
n| Column n of current line
H Top line of screen
M Middle line of screen
L Last line of screen
nH n (number) of lines after top line
nL n (number) of lines before last line

Scrolling
CTRL-F, CTRL-B Scroll forward, backward one screen
CTRL-D, CTRL-U Scroll down, up one-half screen
CTRL-E, CTRL-Y Show one more line at bottom, top of window
zRETURN Reposition line with cursor to top of screen
z. Reposition line with cursor to middle of screen
z- Reposition line with cursor to bottom of screen
CTRL-L Redraw screen (without scrolling)

Searches
/pattern Search forward for pattern
?pattern Search backward for pattern
n, N Repeat last search in the same, opposite direction
/, ? Repeat previous search forward, backward
fx Search forward for character x in current line
Fx Search backward for character x in current line
tx Search forward to character before x in current line
Tx Search backward to character after x in current line
; Repeat previous current line search
, Repeat previous current line search in opposite direction

Line Number
CTRL-G Display current line number
nG Move to line number n
G Move to last line in file
:n Move to line n in file

Marking position
mx Mark current position as x
``x Move cursor to mark x
`` Return to previous mark or context
'x Move to the beginning of line containing mark x
'' Return to beginning of line containing previous mark
Editing Commands

Command Action

Insert
i, a Insert text before, after cursor
I, A Insert text before beginning, after end of line
o, O Open new line for text below, above cursor

Change
r Replace character
cw Change word
cc Change current line
cmotion Change text between the cursor and the target of motion
C Change to end of line
R Type over (overwrite) characters
s Substitute: delete character and insert new text
S Substitute: delete current line and insert new text

Delete, move
x Delete character under cursor
X Delete character before cursor
dw Delete word
dd Delete current line
dmotion Delete text between the cursor and the target of motion
D Delete to end of line
p, P Put deleted text after, before cursor
Put text from delete buffer number n after cursor (for last nine
"np
deletions)

Yank
yw Yank (copy) word
yy Yank cureent line
Yank current line into named buffer a (a-z). Uppercase names
"ayy
append text
ymotion Yank text between the cursor and the target of motion
p, P Put yanked text after, before cursor
"aPv Put text from buffer a before cursor (a-z)
Other
Commands
. Repeat last edit command
u, U Undo last edit, restore current line
J Join two lines

ex edit
commands
:d Delete lines
:m Move lines
:co or :t Copy lines
:.,$d Delete from current line to end of file
:30,60m0 Move lines 30 through 60 to top of file
Copy from current line through line containing pattern to end of
:.,/pattern/co$
file

Exit Commands

Command Meaning
ZZ Write (save) and quit file
:x Write (save) and quit file
:wq Write (save) and quit file
:w Write (save) file
:w! Write (save) file, overriding protection
:30,60w newfile Write from line 30 through line 60 as newfile
:30,60w>> file Write from line 30 through line 60 and append to file
:w %.new Write current buffer named file as file.new
:q Quit file
:q! Quit file, overriding protection
Q Quit vi and invoke ex
:e file2 Edit file2 without leaving vi
:n Edit next file
:e! Return to version of current file at time of last write (save)
:e # Edit alternate file
:vi Invoke vi from ex
: Invoke one ex command from vi editor
% Current filename (substitutes into ex command line)
# Alternate filename (substitutes into ex command line)

Solaris vi Command-Mode Tag Commands


Command Action
Look up the location of the identifier under the cursor in the tags file
^] and move to that location; if tag stacking is enabled, the current
location is automatically pushed onto the tag stack
Return to the previous location in the tag stack, i.e., pop off one
^T
element

Buffer Names

Buffer Names Buffer Use


1-9 The last nine deletions, from most to least recent
a-z Named buffers to use as needed; uppercase letters append to buffer

Buffer and Marking Commands

Command Meaning
"bcommand Do command with buffer b
mx Mark current position with x
'x Move cursor to first character of line marked by x
`x Move cursor to character marked by x
`` Return to exact position of previous mark or context
'' Return to beginning of the line of previous mark or context

3. Input Mode Shortcuts

Word Abbreviation

:ab abbr phrase

Define abbr as an abbreviation for phrase.

:unab abbr

Remove definition of abbr.

Be careful with abbreviation texts that either end with the abbreviation name or
contain the abbreviation name in the middle.

Command and Input Mode Maps

:map x sequence
Define character(s) x as a sequence of editing commands.

:unmap x

Disable sequence defined for x

:map

List the characters that are currently mapped .

:map! x sequence

Define character(s) x as a sequence of editing commands or text that will be


recognized in input mode.

:unmap! x

Disable the sequence defined for the input mode map x.

For both command and input mode maps, the map name x can take several forms:

One Character

When you type the character, vi executes the associated sequence of commands.

Multiple Characters

All the characters must be txped within one second. The value of notimeout
changes the behaviour.

Function key notation: a # followed by a digit n represents the sequence of


#n
characters sent by the terminal's function number n

To enter characters such as Escape (^]) or carriage return (^M) first type a CTRL-
V (^V).

Executable Buffers

Named buffers provide yet another way to create "macros" - complex command
sequences you can repeat with a few keystrokes. Here's how it's done:

1. Type a vi command sequence or ex command preceded by a colon; return to


command mode.
2. Delete the text into a named buffer.
3. Execute the buffer with the @ command followed by the buffer letter.

The ex command: @buf-name works similarly.

Some versions treat * identically to @ when used from the ex command line. In
addition, if the buffer character supplied after the @ or * commands is *, the
command is taken from the default (unnamed) buffer.

Automatic Indentation

You enable automatic indentation with the command:

:set autoindent

Four special input sequences affect automatic indentation:

^T Add one level of indentation; typed in insert mode


^D Remove one level of indentation; type in insert mode
Shift the cursor back to the beginning of the line, but only for the current
^ ^D
line*
Shift the cursor back to the beginning of the line and reset the current auto-
0 ^D
indent level to zero+

* ^ ^D and 0 ^D are not in elvis 2.0


+ The nvi 1.79 documentation has these two commands switched, but the program
actually behaves as described here.

Two commands can be used for shifting source:

<< Shift a line left eight spaces


>> Shift a line right eight spaces

The default shift is the value of shiftwidth, usually eight spaces.

4. Substitution and Regular Expressions

The Substitute Command

The general form of the substitute command is:

:[addr1][,addr2]s/old/new/[flags]
Omitting the search pattern (:s//replacement/) uses the last search or substitution
regular expression.

An empty replacement part (:s/pattern//) "replaces" the matched text with nothing,
effectively deleting it from the line.

Substitution flags
Flag Meaning
c Confirm each substitution
g Change all occurences of old to new on each line (globally)
p Print the line after the change is made

It's often useful to combine the substitute command with the ex global command,
:g:

:g/Object Oriented/s//Buzzword compliant/g

vi Regular Expressions

. Matches any single character except newline. Remember that spaces are
treated as characters.
* Matches zero of more (as many as there are) of the single character that
immediately precedes it. The * can follow a metacharacter, such as . or a
range in brackets.
^ When used at the start of a regular expression, ^ requires that the following
regular expression be found at the beginning of the line. When not at the
beginning of a regular expression, ^ stands for itself.
$ When used at the end of a regular expression, $ requires that the following
regular expression be found at the end of the line. When not at the end of a
regular expression, ^ stands for itself.
\ Treats the following character as an ordinary character. (Use \\ to get a literal
backslash.)
[] Matches any one of the characters enclosed between the brackets. A range of
consecutive characters can be specified by separating the first and last
characters in the range with a hyphen..

You can include more than one range inside brackets and specify a mix of
ranges and separate characters.

Most metacharacters lose their special meaning inside brackets, so you don't
need to escape them if you want to use them as ordinary characters. Within
brackets, the three metacharacters you still need to escape are \ - ]. (The
hypen (-) acquires meaning as a range specifier; to use an actual hypen, you
can also place it as the first character inside brackets.)

A caret (^) has special meaning only when it's the first character inside
brackets, but in this case, the meaning differs from that of the normal ^
metacharacter. As the first character within brackets, a ^ reverses their sense:
the brackets match any one character not in the list. For example, [^a-z]
matches any character that is not a lowercase letter.
\( \) Saves the pattern enclosed between \( and \) into a special holding space or
"hold buffer". up to nine patterns can be saved in this way on a single line.

You can also use the \n notation within a search or substitute string:

:s/\(abcd\)\1/alphabet-soup/

changes abcdabcd into alphabet-soup.*

* This works with vi, nvi, and vim, but not with elvis 2.0 , vile 7.4, or vile 8.0.
\< \> Matches characters at the beginning (\<) or end (\>) of a word. The end or
beginning of a word determined either by a punctuation mark or by a space.
Unlike \(...\), these don't have to be used in matched pairs.
~ Matches whatever regular expression was used in the last search.

POSIX Brackets Expressions

POSIX bracket expressions may contain the following:

Character classes

A POSIX character class consists of keywords bracketed by [: and :]. The


keywords describe different classes of characters such as alphabetic characters,
control characters, and so on (see the following table).

Collating symbols

A collating symbol is a multicharacter sequence that should be treated as a unit. It


consists of the characters bracketed by [, and ,].

Equivalence classes
An equivalence class lists a set of characters that should be considered equivalent,
such as e and è. It consists of a named element from the locale, bracketed by [=
and =].

All three contructs must appear inside square brackets of a bracket expression.

POSIX character classes


Class Matching Characters
[:alnum:] Alphanumeric characters
[:alpha:] Alphabetic characters
[:blank:] Space and tab characters
[:cntrl:] Control characters
[:digit:] Numeric characters
[:graph:] Printable and visible (nonspace) characters
[:lower:] lowercase characters
[:print:] Printable characters (includes whitespace)
[:punct:] Punctuation characters
[:space:] Whitespace characters
[:upper:] Uppercase characters
[:xdigit:] Hexdecimal digits

Metacharacters Used in Replacement Strings

\n Is replaced with the text matched by the nth pattern previously saved by
\( and \), where n is a number from 1 to 9, and previously saved patterns
(kept in hold buffers) are counted from the left on the line.
\ Treats the following special characters as an ordinary character. To
specify a real backslash, type two in a row (\\).
& Is replaced with the entire text matched by the search pattern when used
in a replacement string. This is useful when you want to avoid retyping
text.
~ The string found is replaced with the replacement text specified in the
last substitute command. This is useful for repeating an edit.
\u or \l Changes the next character in the replacement string to upper- or
lowercase, respectively.
\U or \L, \U and \L are similar to \u or \l, but all following characters are converted
\e or \E to upper- or lowercase until the end of the replacement string or until \e
or \E is reached. If there is no \e or \E, all characters of the replacement
text affected by the \U or \L.

More Substitution Tricks


• You can instruct vi to ignore case by typing: set ic.
• A simple :s is the same as :s//~/.
• :& is the same as :s. You can follow the & with a g to make the subsitution
globally on the line, and even use it with a line range.
• The & key can be used as a vi command to perform the :& command, i.e.,
to repeat the last substitution.
• The :~ command is similar to the :& command, but with a subtle difference.
The search pattern used is the last regular expression used in any command,
not necessarily the one used in the last substitute command.
• Besides the / character, you may use any nonalphanumerical,
nonwhitespace character as your delimiter, except backslash, double-quote,
and the vertical bar (\, ", and |).
• When the edcompatible option is enabled, vi remembers the flags (g for
global and c for confirmation) used on the last substitute and applies then to
the next one.

5. ex Commands

Command Syntax

:[address]command[options]

Address Symbols

Address Inlcudes
1,$ All lines in the file
x,y Lines x through y
x;y Lines x through y, with current line reset to x
0 Top of the file
. Current line
n Absolute line number n
$ Last line
% All lines; same as 1,$
x-n n lines before x
x+n n lines after x
-[n] One or n lines previous
+[n] One or n lines ahead
'x Line marked with x
'' Previous mark
/pat/ or Ahead or back to line where pat matches
?pat?
Command Option Symbols

Symbol Meaning
! A variant form of the command
count Repeat the command count times
file Filename: % is current file, # is previous file

Alphabetical List of Commands

Full Name Command


Abbrev ab [string text]
Append [address]a[!]
text
.
Args ar
Change [address]c[!]
text
.
Copy [address]co destination
Delete [address]d [buffer]
Edit e[!][+n] [filename]
File f [filename]
Global [address]g[!]/pattern/[commands]
Insert [address]i[!]
text
.
Join [address]j[!][count]
K (mark) [address]k char
List [address]l [count]
Map map char commands
Mark [address]ma char
Move [address]m destination
Next n[!][[+command] filelist]
Number [address]nu [count]
Open [address]o [/pattern]
Preserve pre
Print [address]P [count]
[address]p [count]
Put [address]pu [char]
Quit q[!]
Read [address]r filename
Read [address]r ! command
Recover rec
Rewind rew[!]
Set set
set option
set nooption
set option=value
set option?
Shell sh
Source so filename
Substitute [addr]s [/pat/repl/][opts]
T (to) [address]t destination
Tag [address]ta tag
Unabbreviate una word
Undo u
Unmap unm char
V (global [address]v/pattern/[commands]
exclude)
Version ve
Visual [address]vi[type][count]
Visual vi [+n] [filename]
Write [address]w[!] [[>>]filename]
Write [address]w !command
Wq wq[!]
Xit x
Yank [address]y[char][count]
Z (position line)
[address]z[type][count]
type can be one of:
+ Place line at the top of the window (default)
- Place line at bottom of the window
. Place line in the center of the window
^ Print the previous window
= Place line in the center of the window and leave the current
line at this line
! [address]!command
= (line number) [address]=
<> (shift) [address]<[count]
[address]>[count]
Address address
Return (next RETURN
line)
& [address]& [options][count]
repeat substitute
~ [address]~[count]
Like &, but with last used regular expression; for details, see
Chapter 6 of Learning the vi Editor

6. Initialization and Recovery

Initialization

vi performs the following initialization steps:

1. If the EXINIT environment variable exist, execute the commands it


contains. Separate multiple commands by a pipe symboll (|).
2. If EXINIT doesn't exist, look for file $HOME/.exrc. If it exists, read and
execute it.
3. If either EXINIT or $HOME/.exrc turns on the exrc option, read and
execute the file ./.exrc, if it exists
4. Execute search or goto command given with +/pattern or +n command-line
options (POSIX: -c option).

The .exrc files are simple scripts of ex commands; they don't need a leading colon.
You can put comments in your scripts by starting a line with a double quote (").
This is recommended.

Recovery

The commands ex -r or vi -r list any files you can recover. You then use the
command:

$ vi -r file

to recover a particular file.

Even without a crash, you can force the system to preserve your buffer by using
the command :pre (preserve).

7. vi Options

autoindent (ai) noai


autoprint (ap) ap
autowrite (aw) noaw
beautify (bf) nobf
directory (dir) /tmp
edcompatible noedcompatible
errorbells (eb) errorbells
exrc (ex) (ex) noexrc
hardtabs (ht) 8
ignorecase (ic) noic
lisp nolisp
list nolist
magic magic
novice nonovice
number (nu) nonu
open open
optimize (opt) noopt
paragraphs (para) IPLPPPQP LIpplpipbp
prompt prompt
readonly (ro) noro
read (re)
remap remap
report 5
scroll half window
sections (sect) SHNHH HU
shell (sh) /bin/sh
shiftwidth (sw) 8
showmatch (sm) nosm
showmode noshowmode
slowopen (slow)
tabstop (ts) 8
taglength (tl) 0
tags tags /usr/lib/tags
tagstack tagstack
term (from $TERM)
terse noterse
timeout (to) timeout
ttytype (from $TERM)
warn warn
window (w)
wrapscan (ws) ws
wrapmargin (wm) 0
writeany (wa) nowa

vitutor tutorial
vilearn tutorial
Using the VI editor other VI manuals/tutorials
frequently asked questions
(the very basics)
2-page PDF summary
The VI editor is a screen-based text editor available on all Unix computers (and available
for all other kinds of computers, sometimes as ``vim'' rather than ``vi''). Given that it
takes some effort, why bother to learn VI? Because

• sometimes it's the only available editor


• when you log on remotely (ssh) to a Unix host from a Mac or PC, only a text
editor (like VI or emacs or pico) can be used to edit files in a text-only terminal
window
• mouse movements (e.g., menus, highlighting, clicking, scrolling) slow down the
touch-typist. VI requires none
• as mentioned above, VI is the editor sure to be on every Unix computer in the
world
• VI is a very powerful editor for those who learn more than just the beginner
commands, and even more powerful for those who are familiar with Unix
commands

If you will be using Unix/Linux computers, especially via ssh, save yourself headaches
and learn the basics of VI now! This web page (and the 2-page PDF summary) are for
reference; for a hands-on tutorial type the Unix command ``vitutor'' or ``vilearn'', or
try the hyperlinks at the top of this page.

In the following, ^X denotes a control character. For example, ``^D'' means to hold down
the Control key and press the ``d'' key. Also ``Rtn'' means to press the Return (or Enter)
key, while ``Esc'' means to press the Escape key, located in the far upper left corner of the
keyboard.

1. Starting: To edit a file named (say) ``mytext'' on a Unix computer, type the
command ``vi mytext''. Note that you must type the command with lowercase letters.

2. Two Modes: Pay attention, this is the crucial feature of VI! There are two
modes, command and insert. When in insert mode, everything you type appears in the
document at the place where the blinking cursor is. When in command mode,
keystrokes perform special functions rather than actually inserting text to the document.
(This makes up for the lack of mouse, menus, etc.!) You must know which keystroke
will switch you from one mode to the other:
• Switch to insert mode: press i (or a, or o)
• Switch to command mode: press Esc

3. Getting out: When you want to get out of the editor, switch to command mode
(press Esc) if necessary, then

• type :wq Rtn to save the edited file and quit


• type :q! Rtn to quit the editor without saving changes
• type ZZ to save and quit (a shortcut for :wq Rtn)
• type :w filename to save the edited file to new file ``filename''

4. Moving Around: When in command mode you can use


the arrow keys to move the cursor up, down, left, right. In addition,
these keystrokes will move the cursor:

b back one word


h left one character ^B back one page
f forward one word
l right one character ^F forward one page
{ up one paragraph
k up one line 17G to line #17
} down one paragraph
j down one line G to the last line
$ to end of the line

5. Inserting Text: From command mode, these keystrokes


switch you into insert mode with new text being inserted

i just before the current cursor position I at the beginning of the current line
a just after the current cursor position A at the end of the current line
o into a new line below current cursor O into a new line above current cursor

6. Cutting, Copying, Pasting: From command mode, use these keystroke (or
keystroke-combination) commands for the described cut/copy/paste function:

• x delete (cut) character under the cursor


• 24x delete (cut) 24 characters
• dd delete (cut) current line
• 4dd delete (cut) four lines
• D delete to the end of the line from the cursor
• dw delete to the end of the current word
• yy copy (without cutting) current line
• 5yy copy (without cutting) 5 lines
• p paste after current cursor position/line
• P paste before current cursor position/line
7. Searching for Text: Instead of using the ``Moving Around'' commands,
above, you can go directly forward or backward to specified text using ``/'' and ``?''.
Examples:

• /wavelet Rtn jump forward to the next occurrence of the string ``wavelet''
• ?wavelet Rtn jump backward to the previous occurrence of the string
``wavelet''
• n repeat the last search given by ``/'' or ``?''

8. Replacing Text: This amounts to combining two steps; deleting, then inserting
text.

• r replace 1 character (under the cursor) with another character


• 8r replace each of the next 8 characters with a given character
• R overwrite; replace text with typed input, ended with Esc
• C replace from cursor to end of line, with typed input (ended with Esc)
• S replace entire line with typed input (ended with Esc)
• 4S replace 4 lines with typed input (ended with Esc)
• cw replace (remainder of) word with typed input (ended with Esc)

9. Miscellany: The commands on these two pages are just the start. Many more
powerful commands exist in VI, especially those which invoke other Unix text-filtering
commands (sort, fmt, uniq, cat, sed, awk, grep, etc.). More complete descriptions of all
the possible commands are available on the web; see the list of VI manuals/tutorials
maintained at The Vi Lovers Home Page or use a generic web search to search for ``vi
tutorial'' or ``vim tutorial''.

Some useful or spectacular ``miscellaneous'' commands (not in categories 1-8 above):


typed command what it does
undo the last change to the file (and type ``u'' again to re-do the
u
change)
U undo all changes to the current line
^G show the current filename and status and line number
:set nu Rtn show all line numbers (``:set nonu'' gets rid of the numbers)
^L clear and redraw the screen
:%s/Joe/Bob/g Rtn change every ``Joe'' to ``Bob'' throughout the document
J join this line to the next line
5J join 5 lines
exchange two characters (actually the two commands x=delete
xp
and p=paste)
:w Rtn write (save) the current text, but don't quit VI
:12,17w filename Rtn write lines #12-17 of the current text to a (new) text file
:r filename Rtn read (and insert) contents of a text file
sort all lines from cursor downwards, deleting duplicates, and
!]]sort -u | cat -n
number the lines
:26,$s/\<[a-z]/\U&/g Capitalize the first letter of each word from line #26 through the
Rtn end of the file

You might also like