Learning the vi Editor/Details

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Learning the vi Editor: Getting acquaintedBasic tasksMaking your work easierAdvanced tasksDetailsVi clones (VimBasic navigationModesTips and TricksUseful things for programmers to knowEnhancing VimVim on WindowsVimL Script language, Vile, BB vi)vi Reference

This section describes some of the details of the vi program itself (such as command line features), and other advanced vi features for aspiring vi power users.

Command line invocation[edit]

Different vi clones of course have different ways of starting the program (invocation). Usually, however, command-line versions of vi share a common basic set of command line options. These following command line options and flags are typically available. In addition, vi can be started under different names. Depending on the name used to start vi, it may either behave slightly differently or load a different vi clone.

The common command line options and flags are



Suppress. All interactive user feedback is suppressed (not written to the terminal). This allows to pipe editing commands through the editor, and use it as a kind of stream editor. There are probably better streaming editor tools on Unix, like sed(1), awk(1), or Perl(n).
Note, "-" is a common Unix notation to indicate standard input. It has been chosen as an alternative to -s by the vi authors to provide a familiar look when piping commands. It does not really mean 'read from standard input' since vi does that anyhow.
Encryption. vi prompts the user for a key (a kind of password), and uses this key to encrypt its files before writing. It also uses this key to decrypt any file opened with vi. This feature is not supported by many clones, and the encryption algorithm is a very weak one (it is based on a 256-element one-rotor algorithm). The algorithm is easy to crack. It is compatible with the Unix crypt(1) command. See also -x.
(lower-case letter L) Change some default settings so they are more useful for editing LISP source code.
(upper case letter L) Lists all files which have been saved during a crash. See -r, too.
-r filename
Recover the file filename after a crash. Use -L to get a list of files which can be recovered.
Readonly. Files can only be viewed, not written.
Tags are not sorted. When a tag file is used, this flag tells vi that the tag file is not sorted, therefore vi will use a slower algorithm to look up tags. See -t, too.
-t tag
Edit (open) that file which contains the given tag. This of course requires that a tag file (called tags) is available.
Start in visual mode. Only useful if the editor is started under the name ex and not vi.
Verbose. Commands read via standard input are echoed to standard error. This is useful for debugging when the editor is used as a streaming editor.
Window size. Set the editor's number of lines to number. vi behaves as if the terminal has only number number of lines. This was used in the old days to speed up things when connecting via a slow terminal or modem line.
Encryption. Similar to -C. The difference is that vi tries to guess if a file that is opened needs decryption or not. -C on the other hand always runs the decryption when a file is opened.


-c command
Execute the command command before allowing the user to enter own commands. The most common usage is to use this to position the editor at some specific line in a file. E.g.
vi +10 list.txt
will open the file list.txt and position the cursor at line 10. Another common usage is to specify a pattern:
vi +/END script.awk
This will open the file script.awk and position the cursor at the first occurrence of the pattern 'END'.

As already mentioned, vi can be started using different names (all may not be available depending on the particular clone):

The usual way to start vi.
vi starts in read-only mode.
A few settings are changed to better suit beginners: magic is cleared, showmode and novice are set, and report is set to 1.
ex -v
Same as just typing vi

Commands: Objects & Operators[edit]


Until now, this tutorial has just talked about commands, and that commands can be used in conjunction with things like word counts. E.g. d2w has been explained as the operator delete applied to two words. Note the 2w part. You have learned that this part specifies to which text the operator should apply. And indeed, the 2w part specifies to which objects of the text (words, lines, characters etc.) the operator is supposed to be applied. And you have seen that the same object specifiers can be used with all types of operators - as long as the combination makes sense.

vi commands in fact follow a general schema. Commands are made up from operators and objects:

   [[count] operator] [[number] object]

This means the operator should be executed count times on number of objects. Almost all parts are optional. Also, some operators don't take objects at all. This operator/operation syntax is vi's heart. It is why people either love or hate vi. People love it, because it is such a simple schema. Once one knows the few operators (not more than ten), and a few of the objects one can be very productive in vi. People who hate vi simply can't get this schema, and the fact that there is a difference between command and insert mode, into their heads.


We told you that things like the w command moves one word. We actually cheated a little bit when telling you this. There is no such thing as a w command. w is an object specification, not a command. The object specification was given without an explicit operator like d. In such a case vi uses the implicit default operator. And that operator is move.

Whenever you use an object specification without an operator, the operator move will be used. Therefore, object specifiers degrade to move commands. The following is a list and summary of all object specifier. Logically, you can use them in conjunction with operators, or to move around if used stand-alone. You have seen a few of them already:

Paragraph, Section, Sentence Objects[edit]

Everything until next paragraph end.
Everything until previous paragraph end.
[Everything until next section end.]
[Everything until previous section end.]
Everything until next sentence end.
Everything until previous sentence end.

Line Objects[edit]

Everything until line number. If number is omitted, last (not first) line in file. The first line can be addressed as 1G instead.
number of lines after the first line currently on screen. If number is not given, the first line on the screen.
number of lines before the last line currently on screen. If number is not given, the last line on the screen.
The middle line of the screen.
One line down from current line.
One line up from current line.
(underscore) The current line as a whole.

Positions within Lines[edit]

(Digit 0). Backward to first column of line. Same as 1| (not 0|).
Backward to first non-whitespace character.
Forward to end of line.
Column number of the current line. If number is not given, column 1 is used.
Before the next appearance of character char on the current line.
Backwards after the next appearance of character char on the current line.
Next appearance of character char on the current line.
Previous appearance of character char on the current line.
Repetition of the last t, T, f, or F command.
Repetition of the last t, T, f, or F command, but in opposite direction.


To the first non-whitespace character on the next line.
To first non-whitespace character on the previous line.

Word Objects[edit]

Forward to next begin of a word.
Forward to next end of a word.
Backwards to next begin of a word.

Character Object[edit]



Left character.


(lower-case letter L or space) Right character.

Pattern Matching Objects[edit]

Forward to the beginning of the first match of pattern pattern.
Backwards to the beginning of the first match of pattern pattern.
Repeat the last / or ?.
Repeat the last / or ? in opposite direction.
To next matching (, {, or [.


The previously listed objects can be used as arguments to operators. If no operator is given, the default move operator is used. The number of operators in vi is surprisingly small - ten in total. Here is a list of the operators:

needs better descriptions, a few of them are separately described later in this module

Operators taking Objects[edit]

change - change the addressed objects. In fact, the text is replaced by what is typed in.
delete - delete the addressed objects. The deleted text is placed in the undo buffer.
yank - copy the text of the addressed objects into the buffer.
shift left - object arguments can only be objects which address lines Indenting and Shifting.
shift right - object arguments can only be objects which address lines Indenting and Shifting.
bang filter-through - filter lines through an external program. Objects can only be objects addressing lines Filtering (stub).

Operators not taking Objects[edit]

r, s,

Delete character. Use the d operator for deleting other objects than characters.
Flip case of character at cursor position. An uppercase letter becomes its lowercase equivalent, and a lowercase letter becomes its uppercase equivalent.

Special Operator Forms[edit]

There are two special forms when typing an operator:

  1. Typing the character in upper-case, instead of lower-case. E.g. Y instead of y , and
  2. doubling the character. E.g. yy instead of y.

'Strange' lines on the screen[edit]

vi was written at a time when terminal or modem connections were slow. Therefore, vi used several optimisation techniques to limit the need for redrawing the whole screen. In such cases, vi used to display lines beginning with a special marker. Modern vi's seldom have the need for such performance optimizations any more, but they still have the habit to display such lines.

There are two special markers used:


A leading '~' indicates that the line is past the end of the file (non-existent). This can be observed, for example, when vi is started on a new or empty file.


The line is only on the screen, not in the file. This happens for deleted lines. If wrap is enabled (the default), this also happens for lines that are too long to show on the screen all at once.

Indenting and shifting[edit]

vi supports auto-indentation of text lines and also provides command for manual indentation. This is useful when editing program source code. It is a common convention in many programming languages to use indentation to increase readability of the source code.


The option shiftwidth (sw) determines how much space is used for indentation. E.g.

<ESC>:set shiftwidth=4<CR>


<ESC>:set sw=4<CR>

tells vi to use four spaces for indentation.

The option [no]autoindent (ai) tells vi to use auto identation or not. Auto indentation is turned on by

<ESC>:set autoindent<CR>


<ESC>:set ai<CR>

And it is turned off by

<ESC>:set noautoindent<CR>


<ESC>:set noai<CR>

Command Mode[edit]

Shifting lines is done with the < and > commands. < moves the text one shiftwidth to the left (outdenting), while > moves the text one shiftwidth to the right (indenting). The number of lines which can be affected are specified in vi's typical way. However, only objects which identify lines, and not objects which identify words or individual characters can be used.



moves all lines from the current line until the end of the file to the right.



moves all lines from the current line until the end of the paragraph to the left. Of course, the shift commands can be used in conjunction with %, which indicates the next opening bracket. E.g. to shift the lines encompassing the current cursor position up to the first line with a matching (, {, or [ to the left one would type:


Like with all commands it is also possible to specify a line count:



Moves number of lines, starting at the current line, one shiftwidth to the left (outdenting). If number is not given, 1 is assumed - this leads to the shifting of the current line to the left.


Moves number of lines, starting at the current line, one shiftwidth to the right (indenting). If number is not given, 1 is assumed - this leads to the shifting of the current line to the right.

The < and > commands can also be used with a marker. In this case, the reference to the marker is placed between the two characters of the command:

Shifts the lines from the marker m up and including the current line to the left.
Shifts the lines from the marker m up and including the current line to the right.

Insert Mode[edit]

Moves shiftwidth to the right. Note, it is a common mistake to use the <TAB> key instead of ^t. <TAB> inserts a Ctrl-I character and moves to the next multiple of tabstop, and not to shiftwidth. So <TAB> only works if tabstop and shiftwidth are set to the same value.
Since it is not a good idea to set tabstop to anything else than 8, <TAB> can only be used instead of ^t for indenting when shiftwidth is also set to 8.
In autoindent mode, backtabs one shiftwidth. E.g. if autoindent is on, and one wants to enter the follwing text:
if(true) {
    printf("done"); // start sw indent
} // bracket moved back to the left
one would type
if(true) {<CR>
^tprintf("done"); // start sw indent<CR>
^d} // bracket moved back to the left<CR>

There are some special variants of ^d, too:

(the letter ^ followed by Ctrl-D). When this is typed first on a new line, all autoindent is killed (the insertion point is moved to the beginning of the line). Autoindent is then continued on the next line.
E.g. to enter the following text when using autoindenting
        an indented paragraph
        another line in the indented paragraph
.F roff formating commands have to start at column one with a '.'
        more text in the indented paragraph

one would type

^tan indented paragraph<CR>
another line in the indented paragraph<CR>
^^d.F roff formating commands have to start at column one with a '.'<CR>
more text in the indented paragraph<CR>
(the digit 0 followed by Ctrl-D). Kills all autoindent (moves cursor to the beginning of the line), and leaves autoindent off, until text is once manually indented (using ^t).
E.g. to enter the following text when using autoindenting
     FAC = 1
     DO 100 I = 2, N
          FAC = I * FAC
one would type
<ESC>:set sw=5<CR>
FAC = 1<CR>
DO 100 I = 2, N<CR>
^tFAC = I * FAC<CR>


Modelines are lines in text files which are specially interpreted by vi when such a text file is opened. When the modeline (ml) (in some version of vi also called modelines) option is turned on (e.g. in the users .exrc file), vi scans the first and last five lines of each opened file for text of the form

unrelated text vi:command: more unrelated text


unrelated text ex:command: more unrelated text

Each command from such lines is taken and executed as it would have been typed by the user. Any text in front of the modeline-marker (vi: or ex:) or behind the closing : is ignored for the modeline interpretation. This can be used to place modelines in comments if they are used in some programming source code.

Here is an example Java source code file. It contains a modeline on the second and third line, in a Java comment:

 * vi:set sw=4 ai:
 * vi:set showmatch: 
package gnu.freesoftware; public class Interpreter { public Interpreter() ... ...

When modelines are turned on, and this file is opened, shiftwidth (sw) is set to 4, autoindent (ai) is turned on, and the showmatch (sm) option is turned on, too. There is no particular reason why two set commands on two modelines are used other than to demonstrate that all modeline commands found in the first and last five lines are executed, and not just the first.

Modelines can be used to play some practical jokes. E.g., a file with the modeline


immediately closes the editor and makes it impossible to edit the file as long as modelines are turned on.

Modelines get outright dangerous if they mess with system files. E.g., if the super user (administrator) of a Unix system has modelines turned on, and is tricked into opening a file with the following modeline, the important Unix password file is overwritten with the contents of the opened file:

vi:2,$w! /etc/passwd:
root:A shiny new root password:0:0:System Administrator:/:/bin/sh
anotheruser:Another shiny new password:1:0:Just another user:/home/anotheruser:/bin/sh

Therefore modelines should only be turned on in a controlled environment. This is sad, since in principle it is a nice idea that files are able to provide the editor with a configuration best suited to edit that file.

There are some other problems with modelines. Classic vi versions always set a file's status to modified if they find a modeline, even if no editing in the file has taken place. This forces the user to leave the editor with :q! instead of just :q. If instead ZZ is used to leave, the file is written. This causes tools like make to think the file has changed if it in fact hasn't.

.exrc Configuration File[edit]

This module is a stub. You can help Wikibooks by fixing it. For a start:

.exrc files are files containing vi (and ex) configuration data. The format of the data in such a file is that of ex commands, without the leading ':' (column). Typically, .exrc files are used to load some default mappings (map and map! ex commands) or define particular defaults. E.g. the following .exrc file would set autoindent and the shiftwidth when vi is started:

set ai
set sw=4

Normally, a .exrc file is placed in the user's home directory. Since the file name starts with a '.', the file is hidden under Unix-like operating systems. It is possible to place .exrc files in other directories, too. Vi can read the .exrc file in the current directory from which it is started. However, this feature is considered a security risk and turned off by default. It is considered a risk, because similar jokes can be played with .exrc files as with what has been described for modelines. The .exrc file in a user's home directory is considered safe, because on a correctly configured Unix system only the particular user should have write access to it.

There are three important things which should be observed when working with a classic vi and .exrc files:

  1. .exrc files must not contain empty lines. Classic vi chokes on these lines with all kinds of cryptic error messages.
  2. There is no official way to place a comment in .exrc files. However, since the beginning of time the following hack is used and is known to work: A line which starts with a " (quotation character) is ignored by vi.
  3. Classic vi is very picky about map and map! commands. Definitions which by all means should work can trigger strange error messages. This is due to classic vi's limited parser and interpreter for such definitions. Spliting a map or map1 command in several smaller ones can sometimes help.

Many clones have relaxed these rules by allowing empty lines in an .exrc file, and by officially specifying the " as the comment character. Also, good clones should have no problem with map or map! specifications.

" This is a comment in an .exrc file
" A .exrc file must not contain empty lines, so
" comment lines need to be used to separate entries
set sm
set sw=8
set wm=8
" map 'g' to go to begin of file
map g 1G
" rcs check-out (/co) and check-in (/ci)
map /co :w! %.co.bak^M:!co -l %^M:e!
map /ci :w^M:!ci -u %^M:e!^M
" Abbreviations
ab Lx Linux



Vi can use so called tag files (or tags) to allow for quick navigation (jump) to "interesting" information in a set of files. The most common usage for this is to navigate within source code files. E.g. to jump from the usage of a certain function to the function's definition, possibly in another file.

The mechanism is relatively simple. You tell vi to go to a particular tag. vi looks up the file in which the tag can be found, opens that file and jumps to the location of the tag in that file. In order to find the file and position of a tag, vi consults a tag file. A tag file contains an index of tags. A tag is an item (e.g. some programming language object) for which such an index entry can be found in a tag file. When vi is asked to jump to a particular tag, vi looks up the index entry for that tag, and uses the information to jump to the particular item.

In order to use this feature one first has to create a tag file, or a set of tag files, containing entries for all potentially interesting items. These tag file or files then need to be made known to vi - if the default file name is not used. This can e.g. be done by having appropriate commands in an .exrc file.

Modern IDEs provide similar navigation features, but without the need to build a tag file separately. IDEs build the necessary index on-the-fly or use fast brute-force full-text search algorithms. The need for the extra step of creating a tag file for vi is annoying by modern standards. Still, vi's tag file system works and is usable.

Tag File Format, Creation & ctags(1)[edit]

The creation of a tag file typically requires to use a tool which analyses the input text files (e.g. programming source code) and generates entries for each item of interest found in the input text file. The most common tool is called ctags(1) and is a standard Unix program. Several vi clones come with own versions of ctags, sometimes called differently.

ctags knows the syntax of a number of programming languages and generates index information for items like function names, and macro definitions.

In case ctags is not available, or the available version of ctags does not support the programming language in use it is also possible to generate tag files with text processing tools like awk(1), sed(1) or perl(n) and some clever scripts, because tag files are ASCII files.

Typically an entry in a tag file looks like

The name of the item. E.g. a function name or macro name.
The name of the file in which the tag-name item can be found
An ex editor command indicating how to locate the item in the file. This can be any ex command. But two types of ex commands make the most sense:
  1. In the simple form ex-command is a line number, which is indeed a valid ex command.
  2. Usually, however, it is a better idea to use a search pattern like /tag-name/. This provides some flexibility if the file is edited later. It reduces the number of times the tag file has to be re-build, because something moved inside a file. ctags also mostly generates pattern search commands and not line numbers.

Typically vi clones allow for some extensions of this format. Check the particular documentation.

A tag file should be sorted in alphabetic order to speed up operation. If this can't be done, vi's -S command line option can be used.

It is usually not a good idea to generate tag files by manually running ctags or an own tool. Instead the building of tag files is usually better integrated into the software build system. For Unix this means using Makefiles. Typically, the make(1s) targets for generating tag files are called tags, because that's the name of the to be created tag file:

# Makefile snippet
SRCS = ... # all source code
tags: $(SRCS)
        ctags -dt $(SRCS)

Ex Commands[edit]

By default, vi looks in a file called tags for any tags. This file name can be changed with the following ex command. In fact, more than one file name can be specified. They are all loaded to find tags. The command is maybe best placed in a project-specific .exrc file.

:set tags=filename[\ filename ...]<CR>
Set name of files which contain tag information. The syntax of the command varies a little bit from vi to vi version if more than one tag filename is supposed to be provided. Filenames have either to be separated by "\ " (backslash space) or ";" (semicolon).

Naviation to tags can be done via the following ex command. There is also a vi command to do this.

:ta tag-name<CR>
:tag tag-name<CR>
Look up the tag-name in the tags file(s), open the file named in the index entry and execute the ex-command from the index entry. This effectively positions the user at the file and position where the symbol tag-name is defined. The command also remembers the current file and position on the tag stack.

EX commands in vi[edit]

Ex is a line editor that serves as the foundation for the screen editor vi. Ex commands work on the current line or on a range of lines in a file.

Syntax of Ex commands
:[address] command [options]

':' specifies an Ex command.

The 'address' specifies the lines number or range of lines that are the object of command.If no address is given, the current line is the object of the command.

Address Ranges can be specified by any of the following ways in Ex command syntax.

Syntax Range
 :% All the lines in the file.
:1,$ All the lines in the file.
:^,$ All the lines in the file.
:X,Y All the lines between Line number X to Line number Y.
:.,.+n All the lines between current line and next n lines.
:.,.-n All the lines between current line and previous n lines.
:X;Y Line number X to Line number Y with current line set as Line Number X.
:X,+n All the lines between Line number X and next n lines from Current Line.
:X,-n All the lines between Line number X and previous n lines from Current Line.
:X The Line number X.
:. The Current Line.
:$ The Last line of File.
:0 The First line of file
:X-n The Line which is n lines before Line number X .
:X+n The Line which is n lines after Line number X .
:'b The Line which is marked by letter b.
:' The Line which is marked.
:/word Next Line containing pattern word
:?word Previous Line containing pattern word


Command Ex Syntax Operation
Substitute :%s/str1/str2/g Substitute str1 by str2 in the Address range specified as whole file.
Copy and Paste :t8 Copy current line and Paste after Line number 8.
Copy and Paste :9t11 Copy line 9 and Paste after Line number 11.
Copy and Paste :5,8t10 copy lines 5 through 8 and Paste after Line number 5.
Copy and Paste :10,14co20 Copy lines 10 through 14 and Paste after Line number 20.
Move and Paste :m8 Cut current line and Paste after Line number 8.
Move and Paste :9m11 Cut line 9 and Paste after Line number 11.
Move and Paste :5,8m10 Cut lines 5 through 8 and Paste after Line number 5.
Yank/Copy in named buffer. :3,10y p Copy the text between line number 3 and line number 10 in a buffer p (single lowercase char)
Yank/Copy. :3,10y Copy the text between line number 3 and line number 10 in a temporary buffer.
Paste/Put :10p Paste the text in temporary buffer at line number 10.
Paste/Put :p Paste the text in temporary buffer at Current line .
Paste/Put :+10p Paste the text in temporary buffer at 10 lines after Current line
Write/Save file :w! Save the current file.
Write/Save file :w fname Save the current file as fname. Similar to "Save as" in Windows Operating system.
Write/Save file :15,30w fnew Saves the Lines between Line number 15 to Line number 30 of current file in a new file named fnew.
Write/Save file :15,30w >> fexist appends the Lines between Line number 15 to Line number 30 of current file in a file named fexist.
Write/Save file :x! Save & Quit current file Forcefully.
Quit file :q Quit the current file.
Quit file :q! Quit current file Forcefully without saving.
Edit/Refresh :e! Refresh- Discard changes not saved.
Edit :e fname Edit file named fname without leaving vi.
Edit :n Edit next file without leaving vi.
Edit :p Edit previous file without leaving vi.
Edit :rew Edit previous file without leaving vi.
Insert file :r fname Inserts all the text in the file named "fname" at the current cursor location.
Read/Insert :r! command Inserts the output of command at the current cursor location.
read/Insert 10:r! command Inserts the output of command at Line number 10.
Insert file :r fname Inserts all the text in the file named "fname" at the current cursor location.
Insert text :45i! Sets up insert mode at Line number 45.
append text :45a! Sets up append mode at Line number 45.
Delete Lines :d Deletes current line.
Delete Line :45d Delete Line number 45.
Delete Lines :.,.+15d Delete all the lines between current line and next 15 lines
Delete Lines and put in buffer :.,.+15d f Delete all the lines between current line and next 15 lines and put them in a buffer named f
mark a Line :10ma f Mark the Line number 10 with a single lowercase char f.Return later to the mark by 'f.
Shell Command 10,15:! command Execute command in a shell. Treat the text between Line number 10 and Line numner 15 as standard input to command, and replace these lines with the output.
View :10z Set up a view with Line number 10 at the Top of screen.
View :10z+ Set up a view with Line number 10 at the Top of screen.
View :10z- Set up a view with Line number 10 at the bottom of screen.
View :100z. Set up a view with Line number 100 at the center of screen.
View :100z^ Set up a view with Line number 100 at the center of screen and set current line as Line number 100.
View :10z+ 5 Set up a view with Line number 10 at the Top of screen and display next 5 lines from Line number 10.
Status :f Shows current position and the file name at the bottom of the screen.It also specifies if any changes are made to the file since it has been opened.


Option Operation
! Specifies the command has to be executed forcefully.
destination Specifies the Line number where the text is to be pasted.Used with Copy and Move commands.
count Specifies the number of time command is to be repeated.This number always succeed the command.
fname Specifies that the object is a file name "fname".

Vi Commands[edit]

Navigation to tags can be done via the following vi command:

Take the tag-name at the cursor position, look it up in the tag file(s) and navigate to it, similar to the :ta ex command. The command also remembers the current file and position on the tag stack.

The following command uses the tag stack to go back to the previous position. Older vi's don't have it implemented:

Get the previous position and file from the tag stack and return to it. The data is removed from the file.

Command Line[edit]

Vi can also be started with a tag name instead of a file name. See the -t command line option.

Shell escape[edit]

While one is working in vi there might arise a need to run another operating system command. In these modern days this is not a big issue. One can open another terminal window and do as pleased. However, this is not necessary when working with vi. Vi, like many of the older interactive Unix tools, contains features to run operating system commands or start a command line interpreter (shell) from within the editor. This dates back to the times when there were no graphical user interfaces and an editor like vi would take up the complete screen of the terminal (a real terminal of course, not a terminal emulation). Being able to run commands from vi spares one the need to first quit the editor just to look something up, e.g. in a manual page.

In addition, vi provides features to insert the text output of other commands directly into the text under editing.

Ex Commands[edit]

The editor commands to run another command from within vi are in fact implemented as ex commands. That is, they start with the familiar ':' in command mode.

To execute one command from within vi, one would type


At the end of the command one has to hit Return (the second <CR> shown above) to go back to vi. Vi then repaints the screen and continues where editing was left.

In order to repeat the last command, one can simply type


It is possible to append to a previous command by using :!!, followed by whatever should be appended. For example, the second of the following two commands

 :!! | more<CR>

is actually equal to

:!ls | more<CR>

(Note, ls is the Unix command to list a directory, more is the Unix command to paginate output, so it doesn't just scroll off the screen).

Once something is appended to a command, it becomes part of the last remembered command. So in the example above, another


would be equal to

:!ls | more<CR>

and not


Two placeholders can be used in shell escapes to denote the current file name or the name of the previously edited file name:

is a placeholder for the current file name,
is a placeholder for the previously edited file name.

For example, if one is editing some shell script and wants to try it out, one could type the following commands to save the file (:w), set the file's attributes to executable (!chmod ...), and run it (!%):

 :!chmod 755 %<CR>

If the file's name is, e.g. script.sh, the above would be equal to typing

 :!chmod 755 script.sh<CR>

Instead of running a command from within vi it is also possible to start the shell from within vi. vi has an own command for this, which looks up the user's default shell (e.g. the Bourne shell or the C shell) and starts it. It is important to note that a new shell is started. The user is not returned to the shell from which vi was started. The command is called :sh, and it can be used as it follows:

$ #shell commands, when done exit shells:
$ exit<CR>

Vi Commands[edit]

It is possible to filter all or parts of a text currently under editing through an external program. The original text is then replaced with the output of the external command.

The classic example for this feature is the usage of the Unix text formatter fmt. vi itself doesn't have any specific formating capabilities, however, by running the text or parts of it through an external formater from within vi, the desired formatting is easily achieved.

The vi command for filtering text is ! (note, as opposed to the ex shell escape command, there is no leading :). ! follows the usual vi command format. So one can specify the scope to which it should apply. E.g. !! means to filter the current line, or !} means to filter the current paragraph.

The ! vi command has to be followed by by the name of the external program to be used for filtering. E.g. in order to format the current paragraph with the already mentioned Unix text formatter fmt, one would type


! can also be used to just insert the output of some external command into the currently edited text. To do so, one would first create a new empty line (e.g. with o), and then use !! to replace the empty line with the output of a command. For example,


would include a listing of the files in the current directory into the text under Unix.

Execute command from Buffer[edit]

This module is a stub. You can help Wikibooks by fixing it.

Execute command stored in buffer b.

vi for Programmers[edit]

Classic vi provides a number of features which are useful for programmers. Vi was made by programmers for programmers -- but at a time when programming was different. Classic vi's programming support is, by today's standards, not too great, but of course still usable. And it is still more convenient to use vi for editing programming code than any of the ...pad editors like notepad (Windows) or dtpad (CDE/Motif). vi probably works best on Unix systems due to the many text filters that come with Unix and the ease with which additional special-purpose filters can be scripted.

Useful features in vi for programmers are:

Autoindent and manual Shifting of Lines[edit]

See Indenting and shifting


Modelines to set per-language defaults - if security is not an issue (see Modelines)

Tags for Navigating[edit]

See Tags

Shell Escapes[edit]

See Shell escape

  • One way to use shell escapes is to run a makefile or the compiler from within vi. It is in general a good idea to first save the current file before trying to compile it:
or <ESC>:w<CR> :!cc %<CR>
and afterwards <ESC>:w<CR> :!!<CR>
  • Another way is filter source code through an external command, e.g. through a comment-reformator for the specific language. For example, the following command will filter the current paragraph through a external comment-reformator called recomment (not a standard Unix program, but available as a separate script).
See [1] for the recomment script for Unix.

Editing multiple Files[edit]

vi can be started with a list of files:

vi file1 file2 file3 ...

Combined with other Unix features, like file matching, this can be a powerful feature. E.g. to open all C source code, including header files in a directory (.h), the following command can be used:

vi *.[ch]

Or to find all files which contain a certain keyword and open them, something like

vi `grep -l Keyword *.txt`

can be used.

Once vi has been started with a list of files it is possible to navigate within the list with the following commands:

next - Move to the next file in the file list
rewind - rewind the file list and open the first file in the list.

vi clones like vim typically provide more commands, e.g. to go back one file in the file list.

Flip between two Files[edit]

  • Flip between two files using # as the name of the last file. E.g. to flip between a C source file and the corresponding header file.
:e x.c<CR>
:e x.h<CR>
some changes to x.h, then going back to x.c
  • Flipping between two files using CTRL-^. This is one of the forgotten vi commands.

The error(1) Program[edit]

The error(1) program on Unix can be used to capture error messages from compilers and later jump from error message to error message in the editor. error's way of working is archaic. It parses error messages from the compiler and inserts them as comments into the source file in which the compiler detected the error. Since error marks error messages with ### and %%% in the source file, navigation can be done with vi commands like / and n.

There are two common ways to use error with vi:

  1. From outside vi and letting error start vi. error can start vi on all files which produced an error during compilation, using the -v flag:
$ cc *.c 2>&1 | error -v
# Notes:
#  cc    - the C compiler
#  *.c   - all C files in the current directory
#  2>&1  - Standard error output is redirected to normal standard output
#  |     - the output is feed to error as input
2. From inside vi, on the current file. First the file is saved, then it is tried to compile it, processing potential error messages with error, then the potentially changed source file is re-read (:e!), and finally the first mark is searched with /###:
first time
:!cc % 2>&1 | error<CR>
and afterwards <ESC>:w<CR> :!!<CR> :e!<CR> /###<CR>
error is a horrible kludge and can really mess up source code and a version control system! We recommend you try it at least once and form your own opinion. Also have a look at error's man page first. vi clones like vim provide a much more sensible system. Here the editor executes the compiler (or make(1s)) and captures the output of the compiler. The information is recorded in an error message file by vim. vim then allows to navigate the source code by extracting file names and line numbers from the error message and jump to these positions. This is the same mechanism as provided by IDEs.

Macros & Shortcuts[edit]

vi's provides the :map and :map! commands to define useful shortcuts and macros, and ab to provide abbreviations.

Todo: Provide a few such macros?
places a comment at the beginning of a line and moves down
Is this (above) what you mean by macro?

nroff/troff Typesetting Support[edit]


vi provides support for editing text files for the Unix typesetters nroff and troff. The most "common" usage for this typesetter these days is probably to write manual (man) pages for Unix applications.

The support for writing nroff/troff input text files is always active, there is no special vi mode or option which needs to be turned on. Already from this it can be concluded that there aren't too many nroff/troff specific operations in vi. In fact, vi just provides simple ways to navigate between nroff/troff paragraphs and sections. Nevertheless, these features help when editing nroff/troff files.

nroff's/troff's text file format is simple. Normal text and macros are mixed, where macros indicate how the text should be formatted. A macro starts with a '.' in column one, followed by a one or two letter macro name followed by optional macro arguments. A typical nroff/troff text file with some macros might look like:

Some text making up the first paragraph in the section.
More text in the paragraph.
A new paragraph has been started.
More text in this second paragraph.
Yet another paragraph.
.\" A comment infront of the next section header
Paragraph text.

To simplify navigation in such a text file vi knows the common macro names for sections (the .SH in the above example) and paragraphs (the .PP in the example) and provides commands to move to the next/previous section. The list of macro names is configurable in vi.

Several of the common vi features also help when editing nroff/troff text. E.g. shell escapes to run the typesetter from within vi. The following will format the current file with the manual page macros:

:!nroff -man % | more<CR>


The following options are used to define the nroff/troff macro names as known by vi. Like all options, one changes them by using the :set ex command:

:set option[=value]
List of macro names which vi interprets as section delimiters. Two consecutive characters in the list form one macro name. Typically, vi's default contains .SH, .NH, .H, and .HU. So the sections option reads like
sections=SHNHH HU
List of macro names which vi interprets as paragraph delimiters. Two consecutive characters in the list form one macro name. vi's default typically contains .IP, .LP, .PP, .QP, .PL, .Ib, .p. So the paragraphs option reads like

Vi Commands[edit]

When in command mode, the following commands relate to working on nroff/troff text:

Moves to the previous section.
Moves to the next section.
Moves to the previous paragraph.
Moves to the next paragraph.

And, for completeness:

Moves to the previous sentence.
Moves to the next sentence.

Learning the vi Editor: Getting acquaintedBasic tasksMaking your work easierAdvanced tasksDetailsVi clones (VimBasic navigationModesTips and TricksUseful things for programmers to knowEnhancing VimVim on WindowsVimL Script language, Vile, BB vi)vi Reference