Office of Information Technology
Home

Calendar

Map
Home
Computing

Library

Search

Editing with vi

A standard Unix text editor, vi offers the advantage of being virtually identical under every implementation of Unix, unlike emacs, which can vary from system to system. Once learned, then, vican be used with confidence, regardless of the "flavor" of Unix running on a given machine or of other local variations.

Vi is a screen mode editor, like all the newer editing utilities. This means that the user can move around the screen at will to enter text or to make editing changes. (Line mode editors, in contrast, are oriented to the line numbers which appear in the far left column of each screen; all editing must be conducted with reference to the line numbers of the text to be affected. Because of this, line mode editors are cumbersome to use, and now are virtually obsolete.)

Unlike most screen editors, however, vi does not make use of function keys or keypad keys to execute editing commands, but instead uses the standard set of alphanumeric or "typewriter" keys for this purpose. This in large part accounts for its standardization across systems and across varying keyboards. This also means, though, that vi will need some way of interpreting the keystrokes you enter, since a given stroke could be text, but it also could be a command. You the user will provide the necessary interpretation through the frequent signals you send to vi. These are described below.

Starting Up vi

To start the vi editor, issue the vi command followed by a file name, as in vi flowers. Your system-level screen will clear, to be replaced by the editing screen. If flowers is a new file, the screen will be blank, with the exception of a series of ~ (tilde) characters in the far left column. At the bottom of the screen is vi's status line, which will display the file name inside quotation marks, with the notation that the file is a new one.

If, however, flowers is an old file that you are updating, the text you have already entered will appear on your screen, and the status line will inform you of the number of lines and characters the file currently contains. (Remember, however, that when you update and save a new version of flowers, Unix will automatically overwrite, or delete, the old version. If you expect you may need both versions, make sure to use Unix's cp command to copy the file's contents under another file name before invoking the editor.)

All vi commands are brief, often only one or two characters long. They are, however, case-oriented: Dis not the same as d. You will not see your command displayed on the screen in most instances, but you will see its effect. And with some exceptions, you will not need to press <RETURN> to execute it. Where a <RETURN> is needed, the sections below will so indicate.

Entering Text

Vi employs two basic modes, insert mode and command mode. By default, vi is in command mode. Enter the command i to move to insert mode. Then begin typing in your text. As you are typing, press <RETURN> at the end of each line. (Although vi does have a line wrapping option, using it is not a good idea when writing programming code; vi counts lines from <RETURN> keystroke to <RETURN> keystroke, not from the beginning of each line of screen output. Thus, many commands are likely to operate on the wrong number of lines if the wrap option is set.) When you have finished your insertion, inform vi by pressing <ESC>, the "escape" key. This tells vithat your next keystroke should be interpreted as a command, not as text. To return to inserting, enter the command i. Type in your text, end it with <ESC>, and so on.

Making Changes

Editing would be a simple matter if one always turned out a perfectly typed and polished product on the first pass. However, no one manages to accomplish this consistently. Words always seem to be misspelled or mistyped, or there is a better way of phrasing a particular section, or one part really should be moved ahead of another, and so on. Thus the need for a wide array of editing functions. Additionally, you must be able to move quickly back and forth through your text, using the editing functions efficiently, or your time at the computer will be swallowed up in editing and not in producing the desired output.

Moving Around In Your File

Like most editors, vi allows you to move about through the arrow keys, if they are available. This, however, is the slowest possible method, because each press of one of these keys achieves a movement of one row or one column position only. Since you must move the cursor to the place where you want to make your changes before they can be made, you will find yourself pressing a vast number of arrow keystrokes if you limit yourself to this method.

Vi offers many alternatives to the arrow keys, including some that seemingly accomplish the same thing:

    h

    Moves the cursor left one space.

    l

    Moves the cursor right one space.

    j

    Moves the cursor down one line.

    k

    Moves the cursor up one line.

The advantage to using these commands is that they can be combined with numeric arguments and with other vi commands so that they can operate on multiple spaces or lines. Preceding one of these commands with a numeric argument, as in 3j, will cause the cursor to multiply the effect by the argument. Thus 3j will move the cursor down 3 lines. This concept can be applied to other commands as well to produce a very efficient result.

In addition to movement by character position, it is possible to move by other units of text---words, lines, larger blocks of text, etc. Some of the commands to accomplish this are:

    w

    Moves the cursor forward one word.

    b

    Moves the cursor backward one word.

    e

    Moves the cursor to the end of the current word.

    0

    Moves the cursor to the beginning of the current line.

    $

    Moves the cursor to the end of the current line.

    <CTRL/F>

    Moves forward one screen.

    <CTRL/B>

    Moves backward one screen.

    H

    moves to top line on screen.

    L

    moves to last line on screen.

    G

    moves to last line in file.

You may also move to a specific line number in your file. This of course, leads to the question of how you would know a particular line number, especially in a lengthy file. The answer lies in using the set command, in this case, set nu. Precede this command with a colon, as in

    :set nu

The colon will cause the command to be displayed at the bottom of your screen. When you see it, press <RETURN>. Your text will be indented several spaces to the right, and line numbers will appear to the left. Now, if you want to move to the third line in your file, enter 3G and the cursor will be placed at the beginning of that line. To turn the line numbers option off again, the command is

    :set nonu

Adding Text

To add text to an existing file, move the cursor to the location of the new text and press i to enter insert mode. Move around for other additions. Press <ESC> when you have finished. Among other useful text addition commands are:

    o

    Opens a new line below the current line. End with <ESC>

    O

    Opens a new line above the current line. End with <ESC>

Deleting Text

As you might expect, vi provides many way of deleting text, including:

    x

    Deletes character at cursor position.

    X

    Deletes character to left of the cursor.

    dw

    Deletes characters from cursor to end of the word. (First exampl of combined vi commands.)

    D

    Deletes from cursor to end of line.

    dg

    Deletes from cursor to the end of the file.

    dd

    Deletes the line containing the cursor.

    2dw

    Deletes characters from cursor to end of second word.

    2db

    Deletes characters from cursor back to second word.

Changing Text

To replace existing text with new text, you can, of course, delete the old text and then put vi into insert mode to add new text. However, there are easier ways of accomplishing this. First, position the cursor within the text you want to replace.

    cw

    Short for "change word." A dollar sign will replace the last character of the word you are changing. Type in your new word, and then press <ESC>.

    cc

    Deletes the line containing the cursor and replaces it with the text you type before pressing <ESC>.

    C

    Same as cc except that the text from the cursor to the end of the line is deleted and replaced by the text you type before pressing <ESC>.

    cL

    Deletes the last line on the screen and replaces it with the text you type before pressing <ESC>.

Numeric arguments can be used with change commands as well, as in 2cw.

Moving Text Around

Like other editors, vi provides a full "cut and paste" feature, where text may be cut or deleted from one area and then pasted elsewhere. The cut text remains available for your use, even though it has been deleted and no longer appears on your screen, because it is stored temporarily in a special buffer, or text holding area. The vi command p (for put), allows the stored text to be inserted in another section of your file.

To use this feature, first enter one of the deletion commands described above to remove text from its current position. Then move your cursor to the location where you now want the text to appear and press p. The stored text will appear to the right of the cursor, with other text "moved over" to make room. If you delete one or more lines, the text will be pasted into a new line below the cursor. Note, however, that each time you delete a text element, the storage buffer is emptied to make room for the new deleted text. Thus the only text available for pasting with the p command is the last text deleted. Make sure that you use p before any subsequent deletions if you want to reuse your deleted text.

Copying Text

Should you want to copy text to another area or areas of your file without deleting it in its original location, vi provides a separate command, y, (for yank). Move your cursor to the beginning of the text you want to copy elsewhere, and use y in combination with a vi movement command to delimit the scope of your yank, as in

    y$

    Yanks text to the end of the current line.

    2yy

    Yanks two lines.

    y3H

    Yanks to three lines below the top line.

Then move to the location where you want to copy your text and use p as described above. Move elsewhere and use p again, if desired. When you either delete or yank text, you will be using the same storage buffer. Therefore you must do any pasting or copying of the selected text before executing another delete or yank command. Actually, a yank is like a deletion that is immediately repasted in its original location.

Joining Lines

After you text has undergone a fair amount of editing, you may be left with short line fragments. These can be joined with the J command. Move your cursor to the first line and enter J to join that line with the following one. A command such as 3J will join multiple lines in this manner.

Undoing And Repeating Changes

It is useful to know how to undo changes, in case you decide against a particular action. The command for this is U. For instance, if the last command has deleted a line, u will restore it.

To repeat the last change you have made, enter a period. This is a handy shortcut when you are reluctant to operate on a large block of text and feel safer manipulating a smaller chunk at one time.

Searches

Very often you will need to locate some or all instances of a particular word or phrase in your text. This is known as a string or pattern search. To initiate a forward search, type a slash (/) followed by the pattern and press <RETURN>.

    /bananas

    Causes a search for the string "bananas" from the cursor position to the end of the file. The command will appear on the status line at the bottom of your screen, and the cursor will move to the next instance of the string.

    ?bananas

    Causes a backwards search from the cursor to the beginning of the file. Remember to press <RETURN>.

Substitutions

Vi includes the ability to initiate searches and perform replacements with the same command. This operation can affect a single line, a larger but limited portion of your file, or the entire file, as you specify. To execute it on a subset of your file you will need to know the line numbers of the affected sections; this can be determined either by using the : set nu command as described above to assign numbers to all the lines in your file, or by entering <CTRL/G> to determine the current line number. The substitution command takes the form "range or location of substitution, the s command, forward slash, current text, forward slash, replacement text." A final qualifying "/g" is also possible. The command is preceded by a colon, and executed with <RETURN>.

:10,$s/fruit/bananas Replaces the first occurrence of "fruit" with "bananas" in each line from line 10 to the end.
:10,$s/fruit/bananas/g Replaces all occurrences of "fruit" with "bananas" in each line from line 10 to the end.
:.,10s/fruit/bananas Replaces the first occurrence of "fruit" with "bananas" in each line from the current line (symbolized by the period) through line 10.
:%s/fruit/bananas/g Replaces all occurrences of "fruit" with "bananas" in each line throughout the file.

The final example above shows global substitution within each line and for every line in the file.

Saving Or Discarding Your Work

To store edited text permanently on disk so that it will be available for future use, vi provides a selection of commands. It is possible to save text as you go along and also to leave the editor without saving any changes.

    ZZ

    Exits the vi editor, saving your file under the name you gave it in your current directory.

    :wq

    Has the same result as the above. However, since this is a colon command, you will need to press <RETURN> to execute it. Before doing so, you may type a different file name than you started with, as in :wq springtime, or even a different directory path location.

    :w

    Writes your file to a disk without exiting the editor.

    :q

    Ends your session without saving your work. Vi will balk at this if you have made changes to the file and have not saved them. In this case, type :quit! or :q!

    :e!

    Discards all your current changes and returns file to the form it had when you entered vi.

Recovering From A System Crash

Should you be in the midst of an editing session when a system crash occurs, vi provides a -r option as a means of recovering the work you had been doing. To illustrate, if you are editing flowers at the time of a system failure, at your next login type vi -r flowers to have your edited file restored.

Customizing vi

The main way that vi can be customized is through use of the :set command with its options. You are already familiar with :set nu to number the lines in your file; try typing :set all for a complete list of options, including those you have set as well as the default settings the editor uses. You may refer to detailed vi documentation in the oit technical library for more information on this.

In addition, if you have an .exrc initialization file in your home directory, vi will read it and execute any commands it contains at startup. Or, if you have set the variable EXINIT in your .cshrc file, its commands will be executed at startup rather than those in .exrc.

Using Advanced vi Features

Vi offers many more commands, options and features than can be described here. It is possible to move text between files, to copy text into a series of letter-identified buffers for temporary use, to access deletions stored in numbered buffers, to mark your place in files, to set up alternative environments, and to accomplish many other similar, advanced actions. To learn about these features, consult the Unix documentation maintained in the oit technical library, or refer to any other comprehensive guide to Unix usage.

Office of Information Technology • Main Office: ECS 125 • Phone: 410-455-3838 • Email: oit@umbc.edu