The vi text editor
See also An Introduction to Display Editing with Vi by William Joy and Mark Horton
Introduction
The vi (visual) editor is a full-screen editor. This means that you will be able to position the cursor to the location in the file where you want to make your changes and additions. The changes that you make will be reflected on the screen. vi
will work with many different types of terminals if you have set the terminal type correctly before invoking the editor.
Unlike emacs
or pico
, vi
has two modes: insert mode (in which you can enter text into a file) and command mode (in which you give commands to vi
). vi
also lacks the windowing and full-undo capabilities of emacs
. vi
is, however, available on practically every Unix system.
More recently, vim
(which stands for vi-improved) adds multiple undo, syntax highlighting, screening, and many more features. The path for vim is /dcs/bin/vim
, in case it is not in your path. In the following text, substitute vim for vi if you want to use vim.
Entering and exiting the vi editor
You invoke the vi editor by typing vi filename
. If the file exists, vi
will display the first few lines of the file and give some status information about the file on the status line (the last line on the screen). If the file does not exist, you will see something like this:
~
~ ~ ~ ~ “letter.tex” [New file] |
vi
uses the the bottom line (the 24th line of most terminals) as its status line. It will display error messages, information on search strings, and various other informational messages on this line.
At the beginning of an editing session, vi
makes a copy of your file and places it into a work buffer. All the changes and additions you enter will be added to the work buffer and not to the original file. If you are satisfied with the changes you have made, you can exit using the following command from command mode. ZZ
Command mode is entered by pressing the Esc
key. If you are already in command mode, your terminal will beep at you. Don’t worry, no harm will be done if this happens.
If you have made some drastic errors, you can exit from the editor without saving any of the changes. The command to do this is :q!
which is entered at command mode.
Modes of Operation
vi
has two modes of operation, insert mode and command mode. When you first enter vi
you will automatically be placed in command mode. All of the vi
editing commands are entered while in this mode. You can make certain you are in command mode by pressing the Esc
key on your terminal. If you are already in command mode, no harm will be done by entering this mode again. You can exit command mode and enter insert mode by entering one of the insert commands.
Insert Mode
Insert mode allows you to insert text into the file you are editing. There are several ways to enter insert mode depending on what you want to do. They are:
key | action |
---|---|
a |
append text after current cursor position |
i |
insert text before the current cursor position |
A |
append text after end of current line |
I |
insert text at beginning of current line |
o |
open a line below the current line |
O |
open a line above the current line |
It is usually easiest to use i
to insert text. If, however, you want to add text to the end of a line, you have to use A
.
Once you have entered insert mode with any of the above commands you are able to continue typing and inserting text. vi
will allow you to delete characters and edit within the current line you are editing but will not give you any other cursor positioning capabilities or editing functions beyond the ability to backup and delete characters and entered. In fact, if you try to use any of the cursor positioning keys, besides the DEL
key or Ctrl-W
(used to backup over and delete words), while still in insert mode, you run the risk of losing portions of your text. Be certain that you are in command mode, not insert mode, when using the cursor positioning keys (please see the next section for a list of what these keys are).
If you need to do major editing on text, you can return to command mode by pressing the Esc
key. You may now use all the cursor positioning commands and editing commands available in command mode.
Command Mode
Command mode is the mode of vi
that you will use to perform most of your editing tasks. It is in this mode that you are able to position the cursor, delete text, change text, search for specific strings, substitute one string for another, exit from vi
, and perform a variety of other tasks.
Cursor Positioning
While in command mode you can position the cursor over any character on the screen. You can also display a different portion of the work buffer on the screen. You can move the cursor through the text by any Unit of Measure (i.e., character, word, line, sentence, paragraph, or screen). To move the cursor, just type the letter of the unit of measure. For example, to move ahead one word, type w
.
key | action |
---|---|
l, space bar, → |
one character to the right |
h, ← |
one character to the left |
w, b |
one word forward or backward (Punctuation counts as a word.) |
W, B |
one “blank-delimited” word forward or backward |
j, ↓ |
one line down |
k, ↑ |
one line up |
) |
beginning of next sentence |
( |
beginning of sentence |
} |
beginning of next section |
{ |
beginning of section |
Deletion
The x
command deletes the character under the cursor. You can precede the x
command by a repeat factor, i.e., a number that indicates the number of characters you wish to delete.
If you wish to delete words or lines, use the d
operator. The d
operator is used along with a repeat factor and a Unit of Measure. Here is a list of some useful delete commands and their results:
Keys | Action |
---|---|
d0 |
delete to beginning of line (That’s a zero!) |
dw |
delete to end of word |
d3w |
delete to end of third word |
db |
delete to beginning of word |
dd |
delete current line |
5dd |
delete 5 lines starting with the current line |
d) |
delete to end of sentence |
On some terminals, deleted lines are replaced by an @ symbol at the left of the screen. These lines will not be written to the Work Buffer. If you wish to redraw the screen to get rid of the @s type Ctrl-R
while in command mode.
Changing Text
The c
operator replaces existing text with new text that you enter. The new text does not have to occupy the same amount of space as the existing text. You may change one word to several words or a paragraph to a single character. The change operator c
places a $
at the end of the text specified by the Unit of Measure and places vi
in Insert Mode. Finish the change by pressing Esc
. Below is a list of some useful change commands with their Units of Measure:
Keys | Action |
---|---|
cw |
change to end of word |
c3w |
change to end of third word |
cb |
change to beginning of word |
cc |
change the current line |
5cc |
change 5 lines starting with the current line |
The Undo Command
The Undo command u
undoes what you just did. It restores text that you just deleted or changed by mistake. vi
will only restore the most recently changed text. If you deleted one line and then another with separate commands, the undo command will only restore the last line deleted.
The U
command will restore the current line to the way it was before you started changing it, even if you have made several changes.
vim
will let you undo as many times it can remember. Also, Ctrl-R
is the redo command in vim
. It lets you reverse an undo.
The Status Command
The status command Ctrl-G
displays the name of the file being edited, the current line number, the total number of lines in the Work Buffer, and the percent of the Work Buffer preceding the current line.
The . Command
The .
(period) command repeats the most recent command that made a change.
Searching for a String
The forward slash /
is used to find the next occurence of a string, while you are in command mode. The syntax of the search command is:
/string
where you substitute the actual string you wish to search for instead of the word “string” above.
If you wish to find the previous occurence of a string use the question mark instead of the forward slash. Notice that ?
and /
usually appear on the same key on the keyboard. You can repeat the previous search without re-entering the command by using the n
and N
keys. The n
key will repeat the last search exactly as entered and the N
key will repeat the last search in the opposite direction.
Special Characters in Search Strings
Several characters take on special meaning when used in search strings. They allow you to search for strings in specific positions of the file, or allow you to perform wildcard searches (i.e., look for a match on any character within a pattern in your search string). These special characters and their functions are listed in the table at the bottom of this section.
Here are some examples: When the circumflex is the first character in the search string vi
will look for the next line that begins with the string which follows. For example,
/^today
would find the next line that begins with today.
The dollar sign used after a string will find the next line that ends with that string. For example,
/?$
would find the next line that ends with a question mark.
The period .
is used to match any character, anywhere in a search string. For example,
/t..e
would find the words time, tile, and mattress. It would find any word that contained a t
followed by any two characters and then an e
.
The characters \>
are used to search for a word that ends with a specific string of characters. For example,
/ing\>
would find the next word that ends with “ing”.
The characters \<
will search for a word that begins with with the string entered. For example,
/\<9Lives
will find the next word that begins with “9Lives”.
Square brackets surrounding two or more characters will match any single character located between the brackets. For example,
/dis[ck]
would find the next occurrence of either “disc” or “disk”.
Search String Special Characters
Symbol | Meaning |
---|---|
^ |
matches beginning of line |
$ |
matches end of line |
. |
matches any single character |
\> |
matches the end of a word |
\< |
matches the beginning of a word |
[ab] |
matches any of the characters between the brackets (a or b) |
Issuing ex Commands
vi
is actually a screen-oriented extension of the ex
editor. It allows you to use ex
commands by preceding them with a colon :
. When you type :
, vi
will print a colon at the beginning of the last line of the screen and allow you to type the ex
command. If you change your mind and don’t want to issue an ex
command, just press the DEL key until the cursor is back in the text.
We’ll be discussing three of the many ex
commands available: the Substitute, Read, and Write commands. Substitute is described in the next section; Read and Write are described in another section. The range of ex
commands is too large for this guide. For more information, consult the “Ex Reference Manual” and the “Edit/Ex Command Summary”.
String Substitution
The Substitute command is a combination of a search command and a change command. The operator for the Substitute command is s
. It searches for a string, and when it finds it, it replaces it with the string you specify. The syntax of the Substitute command is:
:[address]s/search-string/replace-string[/g]
If you do not specify an address, the Substitute command will only search the current line. The g
indicates that you wish to make this substitution globally; i.e., each occurrence of the search-string on a line will be replaced by the replace-string (as opposed to just the first occurence).
The Substitute Address
The following characters are used to compose an address:
Keys | Action |
---|---|
n | Line number n will be searched |
n, m | specifies a range of line numbers ( n through m ) to be used in the search. The range is inclusive. |
. |
represents the current line |
$ |
represents the last line of the work buffer |
1,$ |
represents the entire work buffer |
% |
another way of saying1,$ |
Examples of String Substitution
:s/larger/largest
replaces the string “larger” on the current line with the string “largest”.
:1,.s/Section/Chapter/g
replaces every occurrence of the string “Section” with the string “Chapter” from line 1 in the file through the current line. The /g
indicates that “Section” should be replaced by “Chapter” every time on a line.
The Use of Buffers
One useful function of an editor is to move and copy text from one position in a file to another, or to insert a different file into the file you are currently editing. vi
gives you this capability through the use of buffers. vi
has a General Purpose Buffer and 26 Named Buffers that you can use to hold text during an editing session. Whenever you use a delete command, the text you delete is automatically placed in the General Purpose Buffer. You can put this text at another location in your file by the use of the Put commands (p
and P
).
The contents of the General Purpose Buffer are reinitialized every time you issue a change, delete, or yank command (yank will be described below). You can put the text from the General Purpose Buffer into several different places in the Work Buffer as long as you do not issue one of these commands between Put commands. The use of named buffers comes in handy when you would like to move text around in your file but do not want to worry about accidently writing over text in the General Purpose Buffer. The 26 named buffers are named by the 26 letters of the alphabet (lower-case letters only). You can store 26 different blocks of text which can be used by later put commands. To specify which named buffer to use, type "
and the letter of the buffer before typing the change, delete, or yank command.
The Yank Command
The Yank command y
is identical to the delete command except it does not delete text from the Work Buffer. It simply makes a copy of the text in the Work Buffer and places it in the General Purpose Buffer or one of the named buffers. The syntax of the yank command is the same as that for the delete command except you substitute a y
for the d
in all commands. Here are some examples:
Keys | Action |
---|---|
yy |
make a copy of the current line and place it in the General Purpose Buffer |
"gyy |
make a copy of the current line and place it in the named buffer “g” |
"a5yy |
copy the next 5 lines and place them in the named buffer “a” |
The Put Command
After you have deleted, changed, or yanked text from the Work Buffer you can place it elsewhere in your file by using the Put command. The Put command uses the p
and P
operators. The \keybox{p} operator places characters and words from the buffer after the current character, and places lines of text in the buffer after the current line. The P
operator places characters and words before the current character, and lines of text before the current line. Here are some examples:
Keys | Action |
---|---|
p |
Will put the contents of the General Purpose buffer after the current character or line (depending upon whether the buffer contains a character, word or line). |
"gp |
Will put the contents of the named buffer g after the cursor |
"aP |
Will put the contents of the named buffer a before the cursor |
Reading and Writing Files
vi
allows you to incorporate the contents of another file into your current Work Buffer. You are also able to create a new disk file consisting of all or part of your current Work Buffer. To do these two operations use the Read and Write commands.
The Read Command
The Read command :r
will read the contents of a disk file and insert it into the Work Buffer following the current line. The syntax for the command is
:r filename
where filename is the pathname of the file that you want to read.
The Write Command
The Write command :w
will write all or part of the Work Buffer to a file. The syntax for the command is
:[address]w! filename
If you do not use an address or a filename, the entire work buffer is written to the file you are editing, hence it gives you a way of permanently saving the changes you have made to your file without actually exiting from vi
with the ZZ
command. The address is specified in the same way as in the Substitute command and specifies the portion of the Work Buffer to be written. If no address is included, the entire Work Buffer is written. The exclamation point is necessary unless you are writing out the entire contents of the Work Buffer to the current file being edited. It forces vi
to perform the command. You are able to append to an existing file by using the following form of the command:
:[address]w>> filename
VIM Specific Features
Vim (vi-improved) has a many features that are missing in vi. The best way to find out is to go through the vim tutorial, which is part of vim. You can type :help
from inside vim.
Here we will just show a number of useful features.
Syntax Highlighting
Vim “understands” a number of languages and can do syntax highlighting. What this means is that it can use different colors to display different kinds of elements in the language. It is usually helpful to see keywords, identifiers, strings, comments, and operators in different colors. Vim will know what language it is, based on the file extension. For C files, the extension is .c
; for python files, the extension is .py
.
To turn on syntax-highlighting, do
:syntax on
(If you want syntax highlighting to be always on, just create a file named .vimrc
in your home directory, and put syntax on
in there without the colon.)
Unix, Mac, or DOS File Format
Text files may use Unix, Mac, or DOS file formats. The difference is the return character, whether it uses CR (carriage return), LF (line feed), or CRLF (carriage return followed by line feed). DOS uses CRLF, which is the most verbose. VIM and many modern text editors will handle all of them correctly, but some other might not. VIM will show you what type of file format it is using. What you can do is
:set fileformat
And it displays what file format it is. It actually does not set the fileformat, but merely displays it.
To force the file format to the one you want, you just type the command with =
and the format name. For example,
:set fileformat=unix
This forces the format to be unix, if not already. The options are unix, dos, mac.
Unicode and other encodings
Unlike vi, which is primarily for ASCII terminals, Vim is aware of different encodings and character sets, both roman and nonroman. Some encodings such as ASCII and other roman character sets use a single byte per character; however, east Asian characters tend to use two bytes per character.
More recently, unicode, which is a way to bring together all the character sets into one encoding, uses two bytes per character internally. However, to maintain compatibility with existing ASCII-based programs, unicode itself is almost always embedded in another coding scheme. The most common embedding is called “utf-8”. This is a variable-length encoding. For the ASCII subset, utf-8 looks identical to ASCII in that it uses a single byte per character. To handle other characters, it uses two bytes for some characters, and three bytes for other characters. The first byte will determine how many more bytes to follow.
To tell vim to set the encoding (to utf-8, say), do
:set encoding=utf-8
Be sure your terminal emulator also uses the corresponding encoding.
Split Screen (vim only)
vim allows you to split screen either horizontally or vertically.
:split
splits the screen horizontally:vsplit
splits the screen vertically:q
closes the current split screen, or quit vim if it’s the only screenCtrl-W w
(orCtrl-W Ctrl-W
): switch to the next screenCtrl-W W
: switch to the previous screen
Unfortunately, there is no easy way to run an interactive shell in one screen.