Friday, May 27, 2011

Chapter 5. Using the vi Editor

Chapter Syllabus

5.1 Modes Used in vi

5.2 Starting and Stopping vi

5.3 Cursor Movement

5.4 Inserting and Deleting Text

5.5 Replacing Text

5.6 Undo and Redo

5.7 Scrolling Text

5.8 Search and Replace

5.9 Cut, Copy, and Paste

5.10 Importing and Exporting Text

5.11 Configuring vi Options

Until now you have been creating new files but had no way to edit a file. This chapter builds skill in using the vi editor, which is the most widely used editor on UNIX. The vi editor is available with every distribution of the UNIX operating system. Initially, all users of UNIX find the vi editor difficult to use. But as they become used to it, they start to like it due to its simplicity and power. It is not like common editors found on desktops with menus and screen displays. It gives you the full screen for displaying text. The bottom line is mostly used for vi commands when needed.

This editor is capable of handling multiple files simultaneously. All open files are called buffers in vi terminology. You can perform routine editing tasks within one buffer as well as across buffers. You can cut, copy, and paste text, search and replace text, export and import text to and from other files, and spell check. In

addition, it is possible to configure the vi editor according to your requirements using a configuration file.

In the beginning, it is difficult to remember vi commands because there are no menus. As you continue using vi, you will soon remember these commands because they are simple. I have seen many experienced UNIX users who use vi, although other GUI-based editors are available, just because of its simplicity and power. In addition to the use of vi for general file editing, it is also used for typing email and editing the command line. You have already learned the EDITOR environment variable in Chapter 3. If you set the value of this variable to vi, all of your command line editing will use the same commands you use in vi.

This chapter does not explain all of the powers of the vi editor but provides sufficient explanation for the commonly used features. You will learn most of the file editing tasks in this chapter. We will start with vi modes and cursor movement and then move toward other text editing features.

5.1 Modes Used in vi

There are three modes used in the vi editor. These are the command mode, the last line mode, and the insert or input mode. Command mode is used to issue commands. Commands used in vi are not echoed on the screen and they take effect when you press a command key. Last line mode is also called ex command mode. In this mode, ex commands are used, and these are echoed at the last line of your screen. These commands usually start with a colon character. Some commands also start with a slash character, and these are used for search and replace operations. In this chapter, I will use vi command for both vi and ex commands. Insert or input mode means to type or insert text into the active buffer. The insert mode is also called the text entry mode.

When you start vi, it is in command mode. This means that whatever you type is considered a command by the editor. You can switch to text entry mode or insert mode by pressing i at any time in the command mode. After that, whatever you type is inserted into the file buffer and is displayed on the terminal screen. A file

buffer is an area in memory where files are loaded and edited by vi. When you are in insert mode, you can't issue any command until you return to the command mode. To go back to command mode insert mode, you press the key on your keyboard. During a file editing session, you may switch between command mode and insert mode many times.

Note

If you are not sure at any time which mode you are in, just press the key once or twice. If you are in command mode, you will remain in command mode and if you are in insert mode, you will go into command mode.

5.2 Starting and Stopping vi

The editor is started when you use a vi command and give a file name as its argument. For example, if you want to edit a file with the name myfile, you will use:

$ vi myfile

This command starts vi and allocates a memory buffer for file myfile. If the file already exists, text in the file will be displayed on the screen. The bottom line, which is used as a status line, will display a file name, line number, and number of characters in the file. Remember that you can't add any text to the file until you go into insert mode because vi started in the command mode. You will see something like Figure 5-1 when you start vi.

Figure 5-1. A sample vi startup window.

The tilde character (~) you see in the screen shot shows that the file has no text in these lines. To switch to insert mode, you press the i character just after starting vi. After that you can insert any text into the file. One line of text may be up to 256 characters in length. When you press the key, you go to the next line. When you have finished entering text into the file, you press the key to return to command mode. Now you can issue any required command. To save the file, you can use the :w command. You will observe that as soon as you enter the colon character, the cursor goes to the bottommost line (the same line that was used as the status line) and the colon is displayed in the start of that line. This is the line where vi commands are displayed.

After you save the file, you can quit the editor with the :q command. You can also use :x or :wq to save and quit in one step.

Note that you can use the vi command without any file name. In that case the editor will start with an unnamed file buffer in the memory. When you need to save a file, you can use :w filename instead of :w in the command mode. The buffer will be saved with the file name you supplied with the :w command. In the

same fashion, you can use the :w filename command to save a file buffer with a new name if you have already opened a named file.

Multiple files can be opened with vi by supplying multiple file names at the command line. If you want to open three files (file1, file2, file3) simultaneously, the command will be as follows.

$ vi file1 file2 file3

If you made some changes to a file and don't want to save them, you can quit the vi editor with the :q! command. If you try to quit the vi editor after making changes to it with the :q command, it will refuse. The exclamation symbol "!" forces vi to quit even if the file buffer is changed. You can add the exclamation symbol to any command when you want to force vi to do something.

Note

Most vi beginners make mistakes while using vi, resulting in unexpected changes to the file being edited. It is a good habit to use the :w command every few minutes to save the file being edited. Then if you make a mistake and don't understand what has happened, just quit vi with the :q! command and restart it with the saved file. In this case, you will lose only the data typed after the last save.

5.3 Cursor Movement

To move the cursor, you must be in command mode. On most of the modern terminals, you can move the cursor with the arrow keys on your keyboard. If this is not possible with your keyboard, you can move your cursor using other commands, as mentioned in Table 5-1.

Table 5-1. Cursor Movement Commands

Command

Effect

l

Move one character right

h

Move one character left

j

Move one line down

k

Move one line up

Table 5-1. Cursor Movement Commands

Command Effect

Move one character right

G

Go to last line of the file

nG

Go to line number n in the file

$

Go to end of current line

^

Go to start of line

w

Go to beginning of next word

b

Go to beginning of previous word

e

Move to end of word

H

Go to first line of screen

M

Go to middle line of screen

L

Go to last line of screen

(

Go to beginning of sentence

)

Go to end of sentence

{

Go to beginning of paragraph

}

Go to end of paragraph

Before using any of these commands, make sure that you are in the command mode by pressing the key. The G command is used to go to a line number in the file. If you want to go to the start of the file, use 1G. To go to end of file, use G. To go to line number 100, use 100G. You can press at any time to find out which line you are on. You can also instruct the vi editor to display the line number with each line using the :set number command.

The start and end of a sentence are considered with reference to the dot "." character. The start and end of a paragraph are indicated with reference to a blank line. In other words, text within two blank lines is considered to be a paragraph.

We can combine vi commands. For example, $ is used to go to the end of a line, and G is used to go to the last line of the file. We can combine these two

commands as $G to go to end of the last line of a file. Other commands can be combined in a similar fashion.

5.4 Inserting and Deleting Text

Text insertion takes place only when you are in insert mode. Text deletion tasks are performed in command mode. You already know how to switch between these two modes. Here we will introduce some more commands to switch to insert mode from command mode.

When you use the i command to go to insert mode, new text is entered where the cursor is at the time you press the character i. When you insert new text, the previous text on the right-hand side of the cursor moves toward the right. If you use the a command to go to insert mode, the new text entry takes place after the current position of the cursor. You can use the I command to start entering new text at the beginning of a line and the A command to start entering at the end of a line. If you want to enter text at the end of the file, you can combine the G and A commands for this purpose. See Table 5-2 for a list of text entry commands.

Table 5-2. Text Insertion Commands

Command

Effect

i

Start inserting text at the current cursor location.

I

Start inserting text at the beginning of the current line.

a

Start inserting text at the next character position relative to the current cursor location.

A

Start inserting text at the end of the current line.

o

Append a blank line just below the current line and start inserting text from the beginning of that line.

O

Append a blank line just above the current line and start inserting text from the beginning of that line.

To delete text, press to go to command mode and then use any of the commands described in Table 5-3.

Table 5-3. Text Deletion Commands

Command

Effect

x

Delete character at current cursor location.

nx

Delete n characters starting at current cursor location.

X

Delete previous character from the current cursor location.

nX

Delete n previous characters from the current cursor location.

dd

Delete current line.

db

Delete previous word.

dw

Delete from current cursor location to the end of word.

dG

Delete to the end of file including current line.

5.5 Replacing Text

In addition to inserting and deleting text, you can also replace existing text with new text. You can replace a single character or many lines of the text. The r command is used to replace a single character. When you press r while in command mode, nothing happens, but as soon as you press the next character, it appears on the screen replacing the character at the current cursor location. To replace one character and then go to insert mode, use the s command. You will see a $ symbol and vi will put you in the insert mode just after replacing the current character. You can also replace multiple characters with the R command. These and other replacement commands are listed in Table 5-4.

Table 5-4. Text Replacement Commands

Command

Effect

r

Replace current character remaining in command mode.

s

Replace current character and go to insert mode.

R

Replace multiple characters until the key is pressed.

cw

Change to the beginning of next word.

cc

Change entire line.

cG

Change to the end of file.

5 6 Undo and Redo

If you make a change by mistake, you can always undo that change. You use the u command to undo the last change. You can also use the U command to undo all changes made to the current line. To redo something changed by undo, you can use the "." (dot) command. Undo and redo are opposite to each other.

5.7 Scrolling Text

You can scroll text in both the upward and downward directions. Table 5-5 shows the commands to scroll text. Before using any command, press to go to command mode.

5.8 Search and Replace

Search and replace is a necessary editing feature found in all good editors. If you want to find a text pattern in vi, you can use the /text command, where text is the string you want to search. This command searches the text in the forward direction from the current cursor position. You can search in the backward direction if you replace / with ? in the command. To repeat the search once you find a string, just use / or ? without typing the string again.

You can also replace text after a search is made. For example, if you want to replace the word "Atlanta" with "Chicago," you can use the command :s/Atlanta/Chicago/ to search for the next occurrence of "Atlanta" and then replace it with "Chicago." You can use the search-and-replace feature in as many lines as you want or in all of the file. Table 5-6 shows a summary of search-and-replace commands used in vi.

Table 5-6. Text Searching and Replacing Commands

Command

Effect

/text

Search text in forward direction starting from current cursor location.

?text

Search text in backward direction starting from current cursor

Table 5-6. Text Searching and Replacing Commands

Command Effect

location.

/

Repeat previous search in forward direction.

?

Repeat previous search in backward direction.

n

Repeat search in the same direction.

N

Repeat search in the opposite direction.

:s/oldtext/newtext

Search oldtext in the forward direction and replace it with newtext.

:m,ns/oldtext/newtext

Search oldtext in the forward direction from line m to line n and replace it with newtext.

:s/oldtext/newtext/g

Search oldtext in the entire file and replace it with newtext.

/text

If you put a space between the / and the text to be searched, only whole words are searched.

/^text

Search text only in the beginning of a line.

/text$

Search text only in the end of a line.

/(More than one word)

Use parenthesis to search multiple words.

Escape characters have special meaning in vi. For example, the $ character is used to show the end of a line. If you want to search the $ sign in vi, you need to put a backslash (\) in front of it to tell vi that it should be considered an ordinary character and no special meaning of $ should be taken. You will use "/\$" to search for the $ character in a file. Similarly, other special characters (^, *, /, .) must also be escaped.

5.9 Cut, Copy, and Paste

You have already seen commands used to delete text, such as dd and dw. These commands cut the text and put it on a cut buffer. Text from the cut buffer can be pasted anyplace using the p command. The text that you want to copy from one place and paste at another is yanked (copied) first. We use the yy command to yank one line of text. You can also yank multiple lines of text by using the nyy

command where n is the number of lines starting from the current cursor position. To paste the text at a new place in the file, move the cursor to that place and use the p command to place the text after the cursor position. You can also use the P command to paste the text before the cursor position.

The cut-paste combination is the same as moving text from one place to another. You can move text with the m command. The m command moves one line of text from the current cursor position to a new position given to m. For example, m 7 will move the current line to line number 7. You can also move multiple lines of text with the m command, for example, "1,15m76" will move lines 1 to 15 and paste them after line number 76.

The line number method can also be used to copy and paste text. As an example, "7,23t55" will copy lines 7 to 23 and will paste these lines after line number 55. To remind you, you can use the :set number command to see line numbers with each line. Table 5-7 shows commands related to cut, copy, and paste.

Table 5-7. Cut, Copy, and Paste Commands

Command

Effect

yy

Copy or yank current line.

nyy

Copy n lines starting from current line position.

p

Paste yanked text after the current cursor position.

P

Paste yanked text before the current cursor position.

:m a

Move current line and paste after line number a.

:a,bmc

Move lines from a to b and paste after line number c.

:a,btc

Copy lines from a to b and paste after line number c.

5.10 Importing and Exporting Text

The vi editor lets you deal with files in many ways. We can open multiple files, copy text from an opened file to save it to another file on disk (export), or insert a disk file into the editor at a specific location (import).

Importing a Disk File into Editor

To insert a disk file into a location in the opened file, we use the :r filename command. The filename is the name of a file, with full path. If the path is not specified, vi searches for the file in the current directory. For example, if you have opened a file file1 in the editor and want to insert another file file2 after line number 8, you first move the cursor to line number 8. Then you issue the :r file2 command. All contents of file file2 are inserted into the editor after the current line. This is a handy way to combine multiple files.

Exporting Text from the Current File

You can export any number of lines so that they are saved as a new file on the disk. We use the w command for this purpose. As an example, if you have opened file1 in the editor and want to save lines 3 to 47 as file3, you can use the command :3,47w file3.

If you want to save the opened file as a new file (to make a backup), the same command can be used without line numbers. To save the current file as file4, you use :w file4.

5.11 Configuring vi Options

You can customize vi according to your requirements using vi environment options. Each option can be set in vi with the :set option command, where the word option is replaced with some valid option name. Options can also be unset using the same command and by adding no before the option name, like :set nooption.

You have already seen how you can tell vi to display line numbers with every line. For this you used the command :set number. A list of vi options is shown in Table 5-8.

Table 5-8. vi Options

Option

Effect

Table 5-8. vi Options

Option Effect

:set number

Sets line number in front of each line in vi.

:set all

Lists all available options.

:set autoindent

The next line is indented the same number of character as the current line.

:set readonly

Sets the current file as read-only. No change is saved.

:set wrapmargin=n

Sets the right wrap margin equal to n. If we are using 80-column display and the wrap margin is set to 6, every line will be wrapped to the next line after 74 characters.

:set showmode

Shows the user when the user is in "insert mode," "replace one character mode," or "replace mode."

You can also use abbreviations for these commands. For example, you can use :se nu instead of :set number.

The vi editor has a configuration file with the name .exrc, which is stored in the home directory of each user. You can put vi options in this file to make the settings permanent. After creating this file, whenever you start the editor, it will first read the $HOME/.exrc file and set the options automatically. For example, if you are writing C programs, you may want to set autoindent and number every time you start editing a C program. You can create an .exrc file with the following two lines in it.

se nu

se ai

Now these two settings are permanent until you make a change in the $HOME/.exrc file manually.

Test Your Knowledge

1:

You have made changes to a file and want to quit vi without saving these changes. What command will you use?

A. :wq

B. x

C. q!

D. w!

2:

You want to replace cat with dogin your file at all locations in the vi editor. You use:

A. /s/cat/dog

B. s/cat/dog/

C. s/cat/dog/g

D. s/dog/cat/g

3:

While in command mode you press "a"; what happens?

A. This is an invalid command.

B. The editor goes into insert mode and starts inserting text after the current cursor location.

C. The editor searches for character "a" in the open file.

D. The editor gives a beep sound.

5 comments: