Vi (pronounced vee-eye), the standard screen-oriented editor provided with Unix operating systems, is the ``visual'' mode of the Ex line editor. Both Vi and Ex commands can be issued from within Vi, as you will see in the examples that follow.
To invoke Vi, type
where filename is the name of the file or files to be created or modified. Pattern matching characters, such as * or ?, can be used when specifying the filename; Vi will be prepared to edit each file that is matched in alphabetical order. If filename exists, your screen will show the first screenful of the file; if the filename does not exist, you will see a screen similar to the one shown below.
Vi puts the contents of the file you specify into a temporary buffer; any changes you make during your editing session will only be made to this temporary copy (buffer). Changes will be made to your permanent file when you explicitly save to the file using a write command. (See the section of this document entitled ``How to Read from and Write to a File.'')
To create a new file named ``test.vi,'' type
If the filename you give Vi does not exist, your terminal screen will look something like the following:
~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ "test.vi" [New file] |
The cursor is positioned at the top left of the screen. Each of the tildes (~) represents an empty line. The information at the bottom of the screen gives status information. Some Vi commands are typed using the left part of the bottom line; the right part of the bottom line is used to display a message informing you of the ``mode'' you are in.[*]
Vi has two modes: command mode and input mode.
When you start your Vi editing session, you are in command mode. If you want to insert text, you first need to issue a command to put you into input mode. You cannot do anything in input mode except insert text. For instance, you cannot move the cursor while in input mode. This means that if you are in input mode and you want to move the cursor, you will have to end input mode and then issue cursor movement commands.
A typical editing session would consist of the following steps.
ESC
in this document).
Since Vi is a bi-modal editor, as was described above, anything you type while in command mode will be interpreted as a command, and anything you type while in input mode will become text in your file. There are several commands which will initiate input mode; pressing the escape key will end input mode.
Initiating Input Mode | |||
---|---|---|---|
Command |
Meaning |
Mode | |
a |
append after cursor |
APPEND MODE | |
A |
append at end of current line |
APPEND MODE | |
i |
insert at cursor |
INSERT MODE | |
I |
insert at beginning of current line |
INSERT MODE | |
o |
open a line below current line |
OPEN MODE | |
O |
open a line above current line |
OPEN MODE |
All of the above commands will initiate input mode; return to
command mode by pressing the escape key (ESC
). If the
computer or terminal issues a beep, you are already out of input mode
and in command mode; it never hurts to press ESC
more
than once if you are not certain what mode you are in.
To insert text into a new file called ``test.vi,'' type i. Then type the lines as shown below. Use the backspace key (may be marked ) to correct errors as you type. Press the carriage return key at the end of each line.
ESC
Note that the last thing you enter is ESC
, which ends
input mode. If you now type CTRL-G
(hold down the
control key while typing the letter g), the screen will look like
this:
This is a practice file to help me learn how to use the Vi editor. The more I practice, the better I will get! Two paragraphs will be enough to practice moving the cursor, deleting text, moving and copying text. ~ ~ ~ ~ ~ ~ "test.vi" [Modified] line 8 of 8 --100%-- |
If you prefer to enter text without having to press the carriage return key at the end of each line, issue the following command:
The colon (:) causes the cursor to move to the bottom of the screen. Type the rest of the command, ending with a carriage return. Now Vi will automatically break the input lines when they get within ten characters of the right margin. This is called ``power typing.'' You need only press the carriage return key to start a new paragraph.
To turn power typing off, type
For more information on setting options like wrapmargin, see the section on Customizing Vi.
There are two types of Vi commands:
It is possible to accidently put Vi into line-editing mode; you will know this has happened when a colon and the cursor remain at the bottom of the screen after each command. To return to full-screen mode, enter the command:
- vi<CR>
It is possible to undo a command if you remember to undo it right away! The following table summarizes the undo commands; additional commands to retrieve deleted text are shown in a later section.
Undo Commands | |
---|---|
u |
reverses effects of previous command that changed the buffer (commands a,i,d,c,m,co,s, discussed below) |
U |
returns current sentence to its previous state |
:e! |
undoes all commands issued since file was last written to disk |
The table below shows some of the commands you can use to move the
cursor in Vi. You will probably find a half-dozen commands that you
can remember and use regularly, but you might want to refer to this
table from time to time to pick up an occasional new trick! Some
commands require the use of the control key, which may be marked on
your keyboard with CONTROL or CTRL (indicated with CTRL-
in this document). Hold down the control key and type the letter that
is specified. Although the letters are shown in upper case in this
document, no shift is required for control sequences. For all other
commands, the case of the letter is important and should be typed
exactly as shown.
Cursor Motion Commands | |
---|---|
h or |
left one character |
l or space or -> |
right one character |
j or |
down one line, same column |
k or |
up one line, same column |
0 or ^ |
beginning of current line |
$ |
end of current line |
+ or <CR> |
beginning of next line |
- |
beginning of previous line |
G |
beginning of last line of file; if prefixed with a number, goes to beginning of specified line (use 1G to go to first line of file) |
b |
back one word |
w |
forward one word |
e |
end of next word |
|
scroll down in file a half-screen |
|
scroll up in file a half-screen |
|
forward one screen |
|
back one screen |
H |
beginning of top line of screen |
M |
beginning of middle line of screen |
L |
beginning of last line of screen |
z<CR> |
line-up; current line to top of screen |
z. |
current line to middle of screen |
z- |
line-down; current line to bottom of screen |
) |
forward a sentence |
( |
back a sentence |
} |
forward a paragraph |
{ |
back a paragraph |
`` |
go to previous location (two left single quotes) |
% |
go to matching bracket |
Most Vi commands may be preceded by a number to specify the number of times to execute the command. For example:
3w |
move cursor forward 3 words |
---|---|
3) |
move cursor forward 3 sentences |
36G |
put cursor on (``go to'') line 36 |
The following table summarizes the commands to delete text:
dw |
delete from cursor to end of current word |
---|---|
d$ or D |
delete from cursor to end of line |
dd |
delete current line |
d) |
delete from cursor to end of sentence |
d} |
delete from cursor to end of paragraph |
x |
delete single character under cursor |
. |
repeat last command that changed the buffer |
These commands may be preceded by a number indicating the number of words, lines, etc., that you want to delete. For example, the command 5dd will delete 5 lines.
The change commands put you into input mode, marking the end of
the amount of text to be changed with a $. Once you have
entered the new text, press ESC
. The following table
summarizes the commands to change text:
End input with | |
---|---|
cw |
change from cursor to end of word |
c$ or C |
change from cursor to end of line |
cc or S |
change line |
c) |
change from cursor to end of sentence |
c} |
change from cursor to end of paragraph |
R |
replace (overlay) characters on current line |
No | |
r |
replace single character at cursor |
xp |
transpose two characters |
The change commands may also be preceded by a number indicating the number of words, lines, etc., that you want to change. For example, the command 3cw will mark three words for change.
The text that was most recently deleted is stored in a nameless buffer; generally it can be retrieved by using the put command. Lower-case p puts the deleted text below or after the cursor position; upper-case P puts the deleted text above or before the cursor. If the text is one or more lines, it will be put in the line below (p) or above (P) the current line. If the deleted text is a portion of a line, it will be retrieved into the current line either after (p) or before (P) the cursor. Text deleted with one of the change commands (such as cw or cc) is also stored in the nameless buffer and can be retrieved using one of the put commands.
Like the delete and change commands, the yank commands store text in the nameless buffer. Unlike the delete and change commands, the yank commands do not delete text--rather they copy text to the nameless buffer. The following table summarizes the commands to yank text.
yw |
yank from cursor to end of word |
---|---|
y$ |
yank from cursor to end of line |
yy or Y |
yank current line |
y) |
yank from cursor to end of sentence |
y} |
yank from cursor to end of paragraph |
The yank commands may be preceded by a number indicating the number of words, lines, etc., that you want to delete. For example, 5yy will yank five lines.
Because the yank commands copy text to the nameless buffer, p or P can be used to bring back recently yanked text.
The nameless buffer only holds the last text that was deleted, changed or yanked. If you delete or change a large block of text, expecting it to be stored in the nameless buffer, and then, before retrieving the large block, you accidentally delete, change or yank some other text, the large block of text will no longer be in the nameless buffer. Instead, the most recently deleted, changed or yanked text will be in the nameless buffer. This can be especially frustrating if the last delete, change or yank placed a small chunk of text like a word or a blank line into the nameless buffer!
Fortunately, Vi provides a way to retrieve the large block of text. Vi saves up to nine deleted or changed blocks of whole lines in buffers numbered from 1 to 9. The contents of buffer 1 will often be the same as the contents of the nameless buffer; buffers 2-9 will contain previously deleted or changed text. (Yanked text is not put into the numbered buffers.) Vi only puts whole lines of text into the numbered buffers. The text in these buffers can be retrieved with the command:
where n is a number from 1 through 9.
If you are not sure which numbered buffer to specify, you can retrieve the contents of all nine numbered buffers with the command:
Each time you type a period, the contents of the next
higher-numbered buffer will be retrieved. If a buffer is empty, Vi
will display the message Nothing in register
n
where
n
is the buffer number.
By inserting a u before the . , the restored text will be deleted. In this way, you can search for the text you want to retrieve, deleting the unwanted text as you go. Stop typing u. when you have found the text you want.
Vi also provides twenty-six named buffers. The named buffers are named with the letters of the alphabet. If you want to store text in a named buffer or retrieve text from a named buffer, you need to specify the particular named buffer as a part of your delete, yank or put command. Named buffers are specified as follows:
where n is the name of the buffer. If the name is upper case, deleted or yanked text will be appended to the end of the current contents of that buffer. If the name is lower case, Vi will overwrite the current contents of the named buffer with the new text.
The specification of the named buffer precedes the appropriate yank or delete command so that the text will be put in the named rather than the nameless buffer. In the following example, four lines of text will be deleted and stored in the buffer named k.
See the section entitled ``How to Edit a Second File'' for an example of how to use named buffers to copy text between files.
The following table summarizes the commands used for retrieving text.
p |
puts most recently deleted or yanked text below current line or after cursor in current line |
---|---|
P |
puts most recently deleted or yanked text above current line or before cursor in current line |
"np |
puts contents of buffer n after current line; n can be 1-9 a-z or A-Z |
"1p . . . . . . . . |
retrieves text from all nine numbered buffers |
|
|
There are several ways to copy and move text. You can store the text in the nameless buffer and then retrieve it or you can describe a block of text with line numbers or symbols and use Ex commands; another method is described in the ``Advanced Topics'' section of this document.
- 5yy (or 5dd to move)
- p to put the lines after the current line
or
- P to put the lines above the current line
where M and N can be replaced with a line number or symbol representing the desired line. Some of the symbols that can be used for M and N are:
.:Current line $:Last line %:All lines
For example, to copy or move from line 1 through line 5 to a position after line 10, use the command:
The following table shows how to search for a given string:
|
searches forward from cursor for first occurrence of string; if the noic (do not ignore case) option is on (default), string must match exactly; n repeats search forward, N repeats search backward |
|
searches backward for first occurrence of string; n repeats search backward,N repeats search forward |
n |
repeats the search for string in the direction of the search command |
---|---|
N |
reverses search for string |
Several of Vi's options affect the behavior of searches: ignorecase, wrapscan, and magic.
- :set ignorecase<CR>
- :set nowrapscan<CR>
- :set nomagic<CR>
Further discussion on setting options is contained in the ``Customizing Vi'' section.
If all occurrences of a string are to be replaced by a new string, use the command:
where M is the line number, special symbol or mark at which the substitution is to begin, and N is the line number, special symbol or mark where the substitution is to end. Use the symbol % to specify the entire file. string1 will be replaced by string2. The g specifies that multiple occurrences of string1 on a line are to be replaced. Omitting g will result in replacement of only the first occurrence of string1 on each line.
For example, to replace all occurrences of ``this'' with ``that'' in a file, use the command:
The following chart shows some ways to read another file into your Vi edit session and how to write the file or a portion of your file from Vi.
:r other_file |
insert other_file below current line |
---|---|
:w |
write (save) current buffer to file |
:w outfile |
write current buffer to outfile |
:M,N w outfile |
writes block of text to outfile |
:M,N w >>outfile |
appends block of text to outfile |
If Vi reports that a file to which you are writing already exists and you \f(BIdo want to overwrite the file, losing its current contents, use the command :w! outfile. The ! means that you really want to overwrite the existing file.
You can edit additional files without ending your current Vi session. Follow the steps below to switch to another file:
- :w<CR>
- :ed other_file<CR>
If you forget to write the original file, Vi will remind you that you have changes that you have not saved. If you decide not to save your changes to the permanent file before you switch, use the command :ed! other_file. Any changes you made to the buffer that were not written to the permanent file will be lost.
You will now see the first screenful of other_file. If you want to return to the previous file, use the command:
You can ``cut and paste'' portions of one file into another using the twenty-six named buffers that Vi provides. For example, if you want to copy five lines of text from a file named ``file1'' into a file named ``file2,'' you could follow the steps below:
- vi file1 file2<CR>
- "a5yy (or "a5dd if you want to delete the lines)
(Note that " is the double-quote character)- to yank the five lines into the buffer named a. If you use A rather than a, you will append the five lines to the previous contents of the buffer.
- :n<CR>
- "ap<CR>
Exit Vi with
The commands ZZ and :x write only if changes have been made; the command :wq writes and quits, regardless of changes.
If you do not want to save your changes, use
Command Meaning J join current line with next line
r<CR>;split current line at cursor; place cursor on
space :n,$d<CR> delete all the lines from line
number n to the end of the file CTRL-L
;redraw
the screen CTRL-G
;return current line number and the
number of lines in the file ~ change case of letter at
cursor position :!command<CR> issue Unix command
As mentioned previously, there are a number of options that can be set to customize Vi. To set these options, issue the following command from within Vi:
To see the current values of all the options, enter the command:
Name | On | Off | Default | Explanation |
---|---|---|---|---|
autoindent | ai | noai | noai | Useful when entering programs; release with CTRL-D .
|
autowrite | aw | noaw | noaw | Writes file before switching to a second file. |
ignorecase | ic | noic | noic | For string searches. |
list | list | nolist | nolist | Shows TABs (^I) and EOLs ($). |
magic | magic | nomagic | magic | Characters such as . * [ have special meaning. |
number | nu | nonu | nonu | Line numbers. |
redraw | redraw | noredraw | redraw | For slow terminals. |
showmode | smd | nosmd | noshowmode[*] | Display input mode. |
wrapscan | ws | nows | ws | Searches will continue past beginning point. |
Name | Syntax | Default | |
---|---|---|---|
report | report=number | 5 | Y, D, C of lines >= 5 are reported. |
shiftwidth | sw=number | 8 | Amount of shift for >> and <<. |
tabstop | ts=number | 8 | Amount of tab. |
wrapmargin | wm=number | 0 | ``Power typing;'' 0=off. number is distancefrom right margin at which lines are to be broken. |
The options may be set in one of the following ways:
- :set nu ic <CR>
Your .exrc file can have one or more lines. A sample line is
This line sets line numbering on and sets searches to ignore case. When you start Vi, the .exrc file will be executed, setting the options for you.
To ensure that the .exrc file is always found no matter what directory you are in, set the shell variable EXINIT as follows:
Put this line in your .variables.ksh file.
A single command that executes several commands is called a macro. The Ex map command provides the ability to map a sequence of commands to a single key. You can create your own macros with this command. Issue the following command while in Vi to create a macro which will write the current buffer to the permanent file.
CTRL-V<CR><CR>
Note: The command above will appear as :map v
:w^M
on the screen.
CTRL-V
is called the quote character; using it
enables the carriage return or other non-printing characters to be
inserted as a character into the macro. The spaces around the
letter ``v'' are required. The final carriage return issues the
command. Now, whenever you type v while in command mode,
the command :w<CR> will be issued.
The next section on ``Reformatting a Paragraph'' shows another example of how to assign a sequence of commands to a key using the Ex map command. By mapping any key (letter, number, other character or control character) to a sequence of commands you can create your own commands. You can put your command (macro) definitions in your .exrc file, a process described in the ``Customizing Vi'' section.
When editing a file, deleting text and adding text, the text may get ``uneven'' looking in your file. To ``even up'' the text, issue the following command from within Vi:
CTRL-V<CR><CR>
Note: You will see :map F !}fmt^M
on the
screen.
After the mapping has been installed, you can use the upper-case F to reformat from the cursor position to the end of the current paragraph, which is defined as the next blank line or troff command that defines a paragraph. If you plan on using this macro often, put the command in your .exrc file, omitting the initial colon and final carriage return.
If there is a long string of text that you use frequently, it can be assigned to a sequence of letters (an abbreviation) so that whenever the abbreviation is entered when you are in input mode, the long string will be substituted for the abbreviation. For instance, the string ``Information Technology and Communication'' is frequently used in our documents; it could be assigned to the abbreviation ``Itc'' by issuing the following Ex command:
The twenty-six letters of the alphabet can be used to mark locations in your text. An example of the use of marks follows, in which a mark is placed at the beginning and the end of a block of text. Then an Ex command can be issued using the marks rather than line numbers or symbols to describe the block of text. The steps are as follows: