Learning the vi Editor/Details

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
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

or
 * -s
 * 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.


 * -C
 * 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.


 * -l
 * (lower-case letter L) Change some default settings so they are more useful for editing LISP source code.


 * -L
 * (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.


 * -R
 * Readonly. Files can only be viewed, not written.


 * -S
 * 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.


 * -v
 * Start in visual mode. Only useful if the editor is started under the name ex and not vi.


 * -V
 * 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.


 * -wnumber
 * 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.


 * -x
 * 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.

or
 * +command
 * -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 <tt>script.awk</tt> 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):


 * vi
 * The usual way to start vi.


 * view
 * vi starts in read-only mode.


 * vedit
 * 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 <tt>vi</tt>

General
Until now, this tutorial has just talked about commands, and that commands can be used in conjunction with things like word counts. E.g. <tt>d2w</tt> has been explained as the operator <tt>d</tt>elete applied to two words. Note the <tt>2w</tt> part. You have learned that this part specifies to which text the operator should apply. And indeed, the <tt>2w</tt> 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.

Objects
We told you that things like the <tt>w</tt> command moves one word. We actually cheated a little bit when telling you this. There is no such thing as a <tt>w</tt> command. <tt>w</tt> is an object specification, not a command. The object specification was given without an explicit operator like <tt>d</tt>. 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

 * }
 * Everything until next paragraph end.


 * Everything until previous paragraph end.
 * Everything until previous paragraph end.


 * ]]
 * [Everything until next section end.]


 * [Everything until previous section end.]
 * [Everything until previous section end.]


 * Everything until next sentence end.
 * Everything until next sentence end.


 * Everything until previous sentence end.
 * Everything until previous sentence end.

Line Objects

 * [number]G
 * Everything until line number. If number is omitted, last (not first) line in file. The first line can be addressed as <tt>1G</tt> instead.


 * [number]H
 * number of lines after the first line currently on screen. If number is not given, the first line on the screen.


 * [number]L
 * number of lines before the last line currently on screen. If number is not given, the last line on the screen.


 * M
 * The middle line of the screen.


 * j
 * One line down from current line.


 * k
 * One line up from current line.


 * _
 * (underscore) The current line as a whole.

Positions within Lines

 * 0
 * (Digit 0). Backward to first column of line. Same as <tt>1|</tt> (not <tt>0|</tt>).


 * Backward to first non-whitespace character.
 * Backward to first non-whitespace character.


 * Forward to end of line.
 * Forward to end of line.


 * [number]|
 * Column number of the current line. If number is not given, column 1 is used.


 * tchar
 * Before the next appearance of character char on the current line.


 * Tchar
 * Backwards after the next appearance of character char on the current line.


 * fchar
 * Next appearance of character char on the current line.


 * Fchar
 * Previous appearance of character char on the current line.


 * Repetition of the last <tt>t</tt>, <tt>T</tt>, <tt>f</tt>, or <tt>F</tt> command.
 * Repetition of the last <tt>t</tt>, <tt>T</tt>, <tt>f</tt>, or <tt>F</tt> command.


 * Repetition of the last <tt>t</tt>, <tt>T</tt>, <tt>f</tt>, or <tt>F</tt> command, but in opposite direction.
 * Repetition of the last <tt>t</tt>, <tt>T</tt>, <tt>f</tt>, or <tt>F</tt> command, but in opposite direction.

or
 * <CR>
 * To the first non-whitespace character on the next line.


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

Word Objects

 * w
 * Forward to next begin of a word.


 * e
 * Forward to next end of a word.


 * b
 * Backwards to next begin of a word.

Character Object
or
 * h
 * <BS>
 * Left character.

or
 * l
 * <SPACE>
 * (lower-case letter L or space) Right character.

Pattern Matching Objects

 * : 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 <tt>/</tt> or <tt>?</tt>.
 * : Repeat the last <tt>/</tt> or <tt>?</tt> in opposite direction.
 * : To next matching (, {, or [.

Operators
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

 * c : change - change the addressed objects. In fact, the text is replaced by what is typed in.


 * d : delete - delete the addressed objects. The deleted text is placed in the undo buffer.


 * y : 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
r, s,


 * x : 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
There are two special forms when typing an operator:


 * 1) Typing the character in upper-case, instead of lower-case. E.g. <tt>Y</tt> instead of <tt>y</tt>, and
 * 2) doubling the character. E.g. <tt>yy</tt> instead of <tt>y</tt>.

'Strange' lines on the screen
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:

~line 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.

@line 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
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.

Options
The option <tt>shiftwidth</tt> (sw) determines how much space is used for indentation. E.g.

shiftwidth=4 or sw=4

tells vi to use four spaces for indentation.

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

autoindent or ai

And it is turned off by

noautoindent or noai

Command Mode
Shifting lines is done with the commands. < moves the text one <tt>shiftwidth</tt> to the left (outdenting), while > moves the text one <tt>shiftwidth</tt> 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.

E.g.

>G

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

Or

<}

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 <tt>%</tt>, 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:

or
 * [number]<<
 * <[number]<
 * Moves number of lines, starting at the current line, one <tt>shiftwidth</tt> to the left (outdenting). If number is not given, 1 is assumed - this leads to the shifting of the current line to the left.

or
 * [number]>>
 * >[number]>
 * Moves number of lines, starting at the current line, one <tt>shiftwidth</tt> 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 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:


 * <'m<
 * Shifts the lines from the marker m up and including the current line to the left.


 * >'m>
 * Shifts the lines from the marker m up and including the current line to the right.

Insert Mode

 * ^t
 * Moves shiftwidth to the right. Note, it is a common mistake to use the <TAB> key instead of <tt>^t</tt>. <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 <tt>^t</tt> for indenting when shiftwidth is also set to 8.


 * ^d
 * 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 return; } // bracket moved back to the left


 * one would type

if(true) {<CR> ^tprintf("done"); // start sw indent<CR> return;<CR> ^d} // bracket moved back to the left<CR>

There are some special variants of <tt>^d</tt>, too:


 * ^ ^d
 * (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>


 * 0^d
 * (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 <tt>^t</tt>).


 * E.g. to enter the following text when using autoindenting

INTEGER FUNCTION FAC(N) FAC = 1 DO 100 I = 2, N          FAC = I * FAC C C PROVIDE LABEL TO END LOOP C A HINT FOR THOSE GRASSHOPPERS: THIS IS FORTRAN CODE :-) C 100 CONTINUE      RETURN      END
 * one would type

<ESC>:set sw=5<CR> o^tINTEGER FUNCTION FAC(N)<CR> FAC = 1<CR> DO 100 I = 2, N<CR> ^tFAC = I * FAC<CR> 0^dC<CR> C PROVIDE LABEL TO END LOOP<CR> C A HINT FOR THOSE GRASSHOPPERS: THIS IS FORTRAN CODE :-)<CR> C<CR> 100 CONTINUE<CR> ^tRETURN<CR> END<CR>

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

unrelated text <tt>vi:</tt>command<tt>:</tt> more unrelated text

or

unrelated text <tt>ex:</tt>command<tt>:</tt> 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 (<tt>vi:</tt> or <tt>ex:</tt>) or behind the closing <tt>:</tt> 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, <tt>shiftwidth</tt> (<tt>sw</tt>) is set to 4, <tt>autoindent</tt> (<tt>ai</tt>) is turned on, and the <tt>showmatch</tt> (<tt>sm</tt>) option is turned on, too. There is no particular reason why two <tt>set</tt> 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

vi:q!:

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 <tt>:q!</tt> instead of just <tt>:q</tt>. If instead <tt>ZZ</tt> 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
''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

Overview
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 <tt>.exrc</tt> 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)
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

tag-name<TAB>file-name<TAB>ex-command


 * tag-name
 * The name of the item. E.g. a function name or macro name.


 * file-name
 * The name of the file in which the tag-name item can be found


 * ex-command
 * 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 <tt>/</tt>tag-name<tt>/</tt>. 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:

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

Ex Commands
By default, vi looks in a file called <tt>tags</tt> 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 <tt>.exrc</tt> 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 "<tt>\ </tt>" (backslash space) or "<tt>;</tt>" (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>
 * or


 * : 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
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



':' specifies an Ex command.

Address

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. Commands

Options

Vi Commands
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 <tt>:ta</tt> 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:


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

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

Shell escape
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
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

<CR>

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

<CR>

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

<CR> :!! | more<CR> <CR>

is actually equal to

<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

<CR>

would be equal to

<CR>

and not

<CR>

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 (<tt>:w</tt>), set the file's attributes to executable (<tt>!chmod ...</tt>), and run it (<tt>!%</tt>):

:!chmod 755 %<CR> <CR> :!%<CR> <CR>

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

:!chmod 755 script.sh<CR> <CR> :!script.sh<CR> <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:

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

Vi Commands
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 <tt>!</tt> (note, as opposed to the ex shell escape command, there is no leading <tt>:</tt>). <tt>!</tt> follows the usual vi command format. So one can specify the scope to which it should apply. E.g. <tt>!!</tt> means to filter the current line, or <tt>!}</tt> means to filter the current paragraph.

The <tt>!</tt> 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

!}fmt<CR>

<tt>!</tt> 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 <tt>o</tt>), and then use <tt>!!</tt> to replace the empty line with the output of a command. For example,

o<ESC>!!ls<CR>

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

Execute command from Buffer
''This module is a stub. You can help Wikibooks by fixing it.''


 * @b
 * Execute command stored in buffer b.

vi for Programmers
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
See Indenting and shifting

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

Tags for Navigating
See Tags

Shell Escapes
See Shell escape

<ESC>:w<CR> :!make<CR>
 * 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).

!} recomment
 * See for the recomment script for Unix.

Editing multiple Files
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:


 * :n : next - Move to the next file in the file list
 * :rew : 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
:e x.h <CR> some changes to x.h, then going back to x.c <ESC>:w<CR> :e#<CR>
 * Flip between two files using <tt>#</tt> as the name of the last file. E.g. to flip between a C source file and the corresponding header file.


 * Flipping between two files using <tt>CTRL-^</tt>. This is one of the forgotten vi commands.

The error(1) Program
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 <tt>###</tt> and <tt>%%%</tt> in the source file, navigation can be done with vi commands like <tt>/</tt> and <tt>n</tt>.

There are two common ways to use error with vi: $ cc *.c 2>&1 | error -v # |     - the output is feed to error as input
 * 1) From outside vi and letting error start vi. error can start vi on all files which produced an error during compilation, using the <tt>-v</tt> flag:
 * 1) Notes:
 * 2)  cc    - the C compiler
 * 3)  *.c   - all C files in the current directory
 * 4)  2>&1  - Standard error output is redirected to normal standard output
 * 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 (<tt>:e!</tt>), and finally the first mark is searched with <tt>/###</tt>:

first time <ESC>:w<CR> :!cc % 2>&1 | error <CR> :e! <CR> /###<CR>

and afterwards <ESC>:w<CR> :!! <CR> :e! <CR> /###<CR>


 * Note : : 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
vi's provides the <tt>:map</tt> and <tt>:map!</tt> commands to define useful shortcuts and macros, and <tt>ab</tt> to provide abbreviations.


 * Todo: Provide a few such macros?

qqI//<Esc>jq places a comment at the beginning of a line and moves down
 * Is this (above) what you mean by macro?

Overview
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:

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

To simplify navigation in such a text file vi knows the common macro names for sections (the <tt>.SH</tt> in the above example) and paragraphs (the <tt>.PP</tt> 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:

<ESC>:w<CR> : !nroff -man % | more<CR>

Options
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 <tt>:set</tt> ex command:




 * sections :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 <tt>.SH</tt>, <tt>.NH</tt>, <tt>.H</tt>, and <tt>.HU</tt>. So the sections option reads like

sections=SHNHH HU


 * paragraphs :or
 * para :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 <tt>.IP</tt>, <tt>.LP</tt>, <tt>.PP</tt>, <tt>.QP</tt>, <tt>.PL</tt>, <tt>.Ib</tt>, <tt>.p</tt>. So the paragraphs option reads like

paragraphs=IPLPPPQPPLIbp

Vi Commands
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.