Using the “vi” Editor

This chapter introduces the vi editor and describes how to get started using it. Although the vi editor is not the most friendly nor easiest to use editor, it is found on almost all Unix systems. Thus, it is worthwhile to at least become familiar with this editor so that you will have an editing tool you can use should you find yourself on a system which lacks your favorite editor.

vi is a full-screen editor which can be used to create and edit files in Unix environments. Several books describe use of the vi editor and many of the general books about Unix contain a section describing its use. Manual pages for vi are available online and may be viewed using the man command. A comprehensive tabulation of vi commands is available in Vi Commands.

vi is very different from most other editors — the typewriter keys are used both to enter text and to enter commands. Since the vi command structure is not intuitive for most people, several practice editing sessions may be required before you will feel comfortable using its commands. The basic commands provided within this users guide should provide you with enough information to begin editing files productively with a minimum of frustration.

Beginning vi

To begin editing a file, simply enter: vi file_name where “file_name” is the name of the file you wish to edit or create.

If you are not placed in full screen mode when you begin vi, it is likely that the TERM environmental variable has not been set correctly for full screen terminal emulation mode.  The Unix env command (or the command printenv in some environments) can be used to display a list of the current environmental variables.  If you are unsure what type of terminal emulation you should use, try vt100 first as it is supported by a variety of machines. See Defining the Terminal Type for details of reassigning the value of the TERM environmental variable.

vi Modes

The three primary modes in vi are: command mode, input mode, and lastline mode. When you begin editing a file in vi, you will be in command mode. Any key you press will issue a command which enables you to move to a specific location in the file, open a new line, read in an external file, delete text, or begin entering new text.

Cursor Movement Keys

When you are in command mode on many Unix systems, the cursor (or arrow) keys will enable you to move from one location to another in the file. If they do not function, you can still move around in the file using the default movement keys which are located in the “hjkl” row on the right hand side of the keyboard. You should be familiar with these keys so that you will be prepared should you log onto a Unix system and find that the cursor arrow keys are not functional on that system:

  • <h>   move the cursor left
  • <j>   move the cursor down
  • <k>   move the cursor up
  • <l>   move the cursor right

Note: You will also need to be familiar with these keys if you wish to use vi for command line recall and editing capabilities of the Korn Shell.

vi remains in command mode when the above commands are entered. Observe that these key assignments are keyboard positional and not mnemonic; i.e., pressing the <l> key located in the right-most position of the “hjkl” row moves the cursor right and not left. Likewise, the <h> key moves the cursor to the left.

The <j> and <k> keys move the cursor down and up respectively. If you attempt to move the cursor above the top line on the screen or below the bottom line, the screen will scroll upwards or downwards so that new text lines appear. Scrolling stops when the top or bottom of the file is encountered.  As an aid to remember which key performs the down function, note that the tail of the letter “j” extends down below the current line.

Most vi commands can be preceded by a number which results in the command being performed for the specified number of units, e.g., entering the command “9j” will result in the cursor moving down 9 lines. This capability is very powerful as it enables you to move rapidly within a file with a minimum of key strokes.

Input Mode

Adding Blank Lines for Text Input

From command mode, press the <o> key to add a blank line below the line containing the cursor; press <O> (capital “o”) to add a line above the current line. After entering either of the above commands, vi will be in input mode which enables you to enter text.

Press the <Esc> key whenever you wish to return to command mode. If you are ever unsure if you are in command mode, press the <Esc> key twice. Pressing the<Esc> once will usually be sufficient, but pressing it twice will guarantee that you are in command mode.

Pressing the <Return> key while in input mode when at the end of a line can also be used to open a new line for entering text. If you press the <Return> key in the middle of a line while in input mode, you will split the line at the cursor position. You will remain in input mode after either of these operations.

Other Commands to Enter Input Mode

The following commands can also be used to enter input mode:

  • <i> begin entering text immediately in front of the cursor
  • <I> begin entering text at the beginning of the line
  • <a> begin entering text immediately after the cursor
  • <A> begin entering text at the end of the line

Cursor Movement and Commands in Input Mode

While in input mode, the cursor keys may not function as expected. Press <Esc> to return to command mode in order to move about in your file. Keyboard Mappings describes how you can map the cursor keys so that they will function in input mode as well as in command mode.

To join two lines together, press <Esc> twice to guarantee that you are in command mode, locate the cursor anywhere within the uppermost line and press the “J” key. The cursor need not be placed at the end of the line.

While in input mode, you may be able to delete the character to the left of the cursor by pressing the <Del> or <Backspace> key.

Using Command and Lastline Modes

The <Esc> key is used to return to command mode. You may press the <Esc> key additional times; on most systems you will simply hear a beep if you were already in command mode. When in doubt, press: <Esc>

Exiting From vi

To save your changes and exit from vi, enter “ZZ” or “:wq” from command mode. If you wish to quit without saving, enter “:q!” instead. The command “:q” can be used to quit from a file if no changes have been made.

Note: Commands such as “:wq” and “:q!” are lastline (“ed” or “ex” editor) commands which are supported by vi. Lastline commands are invoked from command mode by entering the character “:” followed by the desired command.

Correcting Mistakes

vi includes an undo feature. Providing you have not moved from the line where the last change was made, you can enter the “u” command to undo the last change; entering the “U” command will undo all changes made since you had moved to the current line.

Modifying Text

To change (replace) a single character, enter the letter “r” from command mode followed by the new character;  to begin replacing characters from the current cursor position to the end of the line, enter the vi command “R”. Press <Esc> to return to command mode.

Deleting Characters Within a Line

To delete a character, press <Esc> twice to guarantee that you are in command mode, move the cursor to the character you wish to delete, and then press “x”. Use the command “dw” to delete from the cursor position to the end of the word; to delete an entire word, place the cursor on the first character of the word and enter “dw”. Use the “D” command to erase all text from the current cursor position to the end of the line.

Deleting Lines

To delete a line of text, enter the command “dd”; to delete 9 lines of text downward beginning with the line containing the cursor, enter the command “9dd”.

Moving and Copying Lines

To move a set of lines, first delete them, then move to the line below which you wish to move the text and enter the paste command “p”. To copy a line, instead of moving it, yank it into a buffer using the “yy” command, move to the new location, and enter the command “p”. As in the procedure used for deleting lines, you can precede the yank command with a number to indicate how many lines should be included in the yank buffer.

Search and Replace

To find a text string which occurs in the file after the current cursor position (forward search), enter a slash (/) followed by the string of text you would like to locate. Use the “n” command to locate the next occurrence of the text string.

To change every occurrence of a specific string, enter:

:%s/old string/new string/g

where old string is the original string which is to be changed and new string is the new text you wish to substitute.

The “%” indicates that the action is to be performed for the whole work buffer. The range within which changes are to be made can be restricted by specifying an address of lines instead of “%”. For example, to change all occurrences of the text string in lines 12 to 27, substitute “12,27” for “%” in the previous example.

The letter g in the example is used to indicate that a global change (all occurrences) within the specified range is desired. To perform a selective change, that is, to verify each change before it is made, use “gc” instead of “g” in the change command illustrated above. Enter “y” to make the change at the current cursor position, press <Return> to leave the text unchanged and move to the next occurrence of the “old text” string specified by the change command. You can press <Ctrl-C>to terminate the selective change prior to reaching the last occurrence of the text within the file.

Merging Files

Enter the command :r filespec to merge another file into the one currently being edited. The merged text will be placed below the line containing the cursor.

Changing the Default vi Environment

The file .exrc, located in your home directory, contains commands which define your default processing environment for “vi”. This file may include set commands to specify file processing options, keyboard mappings, and abbreviations. These commands can also be invoked as lastline commands by entering the character “:” while in command mode and then typing in the command you wish to invoke.

The set command is used to define the general environment. Some of the most commonly used set options include:

  • showmode enables a message in the lower right corner indicating when the program is in INPUT or REPLACE mode; no message is displayed when the editor is in command mode.
  • number results in a display of the line numbers along the left margin.
  • wm=2 sets the wrapmargin at two characters from the right margin. This command enables wordwrap at the right margin.
  • list results in the display of hidden characters such as control sequences and new line.

The above options could be defined by individual set commands, or by entering the following while in command mode: :set showmode number wm=2 list

All of the above options may not be available in the implementation of vi provided with your operating system. To display a list of the possible configuration options available on your system and their current settings, enter the following from command mode: :set all

Note: Although the values of the set variable can be defined in the environmental variable EXINIT, it is recommended that you avoid using this variable and define the vi settings you would like to use in the file “.exrc”. On some systems, the presence of the environmental variable EXINIT inhibits invocation of the definitions stored in “.exrc”.

Keyboard Mappings

Commands can be assigned to any of the keyboard characters, however, it is advised that you not use the keys which are assigned functions by vi itself. Safe keys to use for assigning commands are the function (F) keys, and when in command mode: <Ctrl-A>, <Ctrl-C>, <Ctrl-I> <Ctrl-K>, <Ctrl-O>, <Ctrl-T>, <Ctrl-W>, <Ctrl-X>, @, #, *, \, g, q, v, K, V, and Z.

The <Ctrl-V> key sequence is used to quote the function of a key so that the escape sequence generated by the key can be used in a keyboard map definition. For example, to include the sequence which would be generated when the <Return> key is pressed as part of a map definition, press the sequence <Ctrl-V><Return>.

To assign a map definition to a key, type the command “map” followed by a space, press the key sequence to which you would like to assign a command, and then enter the command you would like to have executed by this key. Include <Ctrl-V> before any key sequences which must be disabled in order to be included in the definition. For example, to assign the equivalent of the Xedit Quit command (exit from the file if no changes have been made) to the command mode F3 key, enter:map <Ctrl-V><F3> " <Ctrl-V><Return>

You can also use “map!” instead of “map” to assign a command to a function key or arrow key when in insert mode. If you would like to assign the “quit” command to the “F3” key in input mode as well as in command mode, duplicate the above map command and include an exclamation point following the word “map” and an<Esc> key sequence to return to command mode prior to issuing the “”” command:

map! <Ctrl-V><F3> <Ctrl-V><Esc>" <Ctrl-V><Return>

To assign the sequence <Esc> “h” “a” (i.e., go into command mode, use the vi “h” command to move the cursor to the right, and then execute the vi “a” command which places you in insert mode after the cursor) to the LeftArrow key, include the following line in your “.exrc” file:

map! <Ctrl-V><LeftArrow> <Ctrl-V><Esc>ha

Once this has been done, you need no longer be concerned about whether you are or are not in insert mode when you press the left arrow key. If you are in input mode, the definition assigned by the “map!” command will be used; if you are in command mode, the default definition or that assigned by the map command will be used. The remaining arrow keys could be assigned functions in a similar fashion.

Note: Keyboard mappings are terminal dependent, and must be entered from the terminal you will be using — see the documentation for your ssh client for infomation on keyboard mappings.

Assigning Abbreviations

The :ab command can be included in the “.exrc” file to assign text strings so that you can enter the abbreviation and have it expanded to the full text string by the editor. For example, suppose you frequently make reference to “Virginia Tech” within your writing. This phrase could be assigned the abbreviation VT by inclusion of the following line in your “.exrc” file:

:ab VT Virginia Tech