Editing with vi


A good screen editor would have all of the simplicity and features of the basic UNIX line editor, ed: its little language, its use of regular expressions, and its sophisticated search and substitute capabilities. But a good editor would take better advantage of CRT displays on both terminals and PC screens. Looking at 23 or more lines of text provides context and allows the writer to think in terms of the content of paragraphs and sentences instead of lines and words.

vi has been designed to address these requirements for a better editor; vi has all of these features. vi is a superset of ed; it contains all of ed’s features and syntax. In addition, vi provides extensions of its own that enable customizing and programming the editor.

The need for an extension to the UNIX System ed editor was the reason vi was first developed. In the late 1970s, Bill Joy, then a graduate student at the University of California at Berkeley, wrote an editor called ex. ex was an enhanced version of ed that retained all of ed’s features and added many more, including the ability to see a screenful of text under the visual option. ex became a popular editor. People used its display editing feature so much that the ability to call up the editor directly in visual mode was added.

Setting Your Terminal Display Type for vi

Instead of displaying a few lines of text, vi shows a full screen. vi shows you as many lines of text as your screen can display Twenty-three lines of 80 characters is standard for most terminals, but workstation displays can hold many more; for example, an SGI workstation can comfortably display 65 lines of 155 characters of small type.

Because the characteristics of terminals differ, the first thing you must do before using vi with a terminal display is specify the terminal type by setting a shell environment variable. For example, the VT-100 is an early model of a DEC terminal. Most current terminals and terminal emulation programs on PCs support a vt100 mode. If you use such a terminal, or wish to emulate it, typing

 $ TERM=vt100 $ export TERM

sets the terminal variable to the DEC VT-100 terminal and makes that information available to programs that need it. Rather than type in the terminal information every time you log in, you can include the lines

 # # Set terminal type to vt100 and # export variable to other programs # TERM=vt100 export TERM

in your .profile to have your terminal type automatically set to vt100 (replace vt100 with whichever terminal you use) whenever you log in. If you use different terminals, the following script placed in your .profile will help set TERM correctly each time:

 # # Ask for terminal type, set and export # terminal variable to other programs # echo Terminal Type?\c      read a      TERM=$a export TERM

Starting vi

Users who are familiar with ed will find it easy to use vi because of the many basic similarities. vi, like ed, is an editor with two modes. When the editor is in input mode, characters you type are entered as text in the buffer. When the editor is in command mode, characters you type are commands that navigate around the screen or change the contents of the buffer. Figure 5–1 shows the two modes in vi, the input mode and the command mode. When you are in input mode, ESC (escape) places you in command mode; anything else you type is entered into your document.

image from book
Figure 5–1: Command and input modes in vi

When you are in command mode, several commands (a, A, i, I, o, and O, described next) will place you in input mode; anything else you type is interpreted as a command.

To edit a file, the command vi dog will have vi copy your file into a temporary storage area called an editing buffer and show you the first screenful of that buffer, as in Figure 5–2.

image from book
Figure 5–2: A sample vi screen

In newer versions of UNIX, vi reshapes the screen and refreshes the window if you change the size of the windows.

If you do not have a file dog, vi will create it. vi puts the cursor at the first position in the first line. The position of the cursor marks your current position in the buffer. To position the cursor on the last line, type vi + dog and you will be shown the end of the file, and the cursor will be positioned on the last line. To put the cursor on line 67, type vi + 67 dog and the cursor will be put on line number 67, if it exists. If there are fewer than 67 lines in the file, as in this example, vi will tell you that there are not that many lines in the file, and it will position the cursor at the beginning of the last line.

vi is a subset of the ex editor, which includes most of ed’s functions. If you type a : (colon) when in command mode, the cursor will drop to the last line of the screen and wait for a command. Because vi includes the ed commands, you can issue most ed commands while in vi. For example, if your terminal type isn’t set correctly, vi will behave weirdly

The command : (colon) will place the cursor at the bottom of the screen, and the command: q will quit the editor, just as it does in ed.

Entering Input Mode

vi starts up in command mode. To enter text, you need to switch to input mode. vi provides several ways to do this. For example, the command a puts vi in input mode and begins appending typed text into the buffer immediately after the position of the cursor. (Note that it appends text after the character pointed to by the cursor, not after the line pointed to, as in ed.) The command i puts vi in input mode and begins inserting typed text immediately before the position of the cursor. The command A puts vi in input mode and appends material at the end of the current line. The command I puts vi in input mode and inserts material at the beginning of the current line. The command O (uppercase O) Opens up a line above the current line, places the cursor there, and puts vi in input mode. The command o (lowercase o) opens up a line below the current line, places the cursor there, and puts vi in input mode.

All further typing that you do is entered into the buffer. Whenever you are in input mode, existing text moves as new text is entered. The new text you type in does not overwrite the old.

Leaving Input Mode

Because vi is a two-mode editor, the most important commands for a beginner to remember are the ones that are needed to change modes. The commands a and A, i and I, and o and O place you in input mode.

When you are done creating text, you can leave input mode and go into command mode by pressing ESC (the escape key is usually at the upper-left of the keyboard). Anytime you press ESC, even in the middle of a line, you will be put back in command mode. The only way to stop appending or inserting text and return to command mode is to press ESC. This gets vi out of input mode and back into command mode.

To automatically keep track of where you are (command or input mode), it is a good idea to press ESC as soon as you are done entering a portion of text. This puts you back into command mode.

Exiting vi

When you have finished typing in your text, you need to exit the editor. Remember, if you make serious errors, you can always exit and start again. First get out of input mode by hitting ESC. Typing : (colon) puts you in a mode in which ed commands work. The cursor drops to the bottom of the screen, prints a : (colon), and waits. The command : w will write the contents of the editing buffer into the file. It is at this point that the original file is replaced with the new, edited version. The combined commands : wq will write and quit. Since : wq is a common command sequence in every editing session, the abbreviation ZZ, which represents “last command,” is equivalent to : wq. The command : x stands for exit and is also equivalent to : wq. If you have made some changes you regret, you can cancel all the changes you’ve made by quitting the editor without writing the buffer to a file. To do this, use the : q! command. This means “quit, and I really mean it.”

Moving Within a Window

The main benefit of a screen editor is that you can see a portion of your file and use context to move around and decide on changes. In vi’s command mode, you have several ways to move around a window. One set of commands enables you to move around by lines or characters, as shown in Table 5–1.

Table 5–1: Moving Around by Lines or Characters in vi

Command

What It Does

l or SPACEBAR or

Moves right one character

h or CTRL-H or BACKSPACE or

Moves left one character

j or CTRL-J or CTRL-N or

Moves down one line

k or CTRL-P or

Moves up one line

0

Moves to the beginning of the line

$

Moves to the end of the current line

+ or ENTER

Moves to the beginning of the next line

Moves to the beginning of the previous line

You don’t need to think only in terms of characters and lines; vi also lets you move in other units. In normal text entry, a word is a sequence of letters delimited by spaces or by punctuation; and a sentence ends with a period (.), question mark (?), or exclamation point (!) and is separated from the previous sentence by two spaces, or by a ENTER. With these definitions, the commands shown in Table 5–2 enable you to move across larger sections of text when you are in input mode.

Table 5–2: Moving Across a Section of Text in vi

Command

What It Does

w

Moves to the next word or punctuation mark

W

Moves to the next word

e

Moves to the end of this word or punctuation mark

E

Moves to the next end of word

b

Moves back to the beginning of word or punctuation

B

Moves back to the beginning of the word

)

Moves to the start of the next sentence

(

Moves back to the start of the sentence

}

Moves to the start of the next paragraph

{

Moves back to the last start of paragraph

]]

Moves to the start of the next section

[[

Moves back to the last start of section

These commands can take a numerical prefix: 5w means move ahead five words; 9e means move the cursor to the end of the ninth word ahead.

The {and} and the [[and]] commands move by paragraphs or sections of your text and use the text formatting commands in the mm macros discussed on the companion web site. For example, the command, {} (move to the next paragraph) will move you to the next .P in your file.

Moving the Window in the Buffer

vi shows you the text file, one window at a time. Normally, you edit by moving the cursor around on the screen, making changes and additions, and by displaying different portions of the text on the screen. The commands in the previous section showed you how to move the cursor in the text. You can also move the window that displays the text with the following five commands:

CTRL-F (Forward)

Moves forward one full screen

CTRL-D (Down)

Moves forward one half screen

CTRL-B (Back)

Moves back one full screen

CTRL-U (Up)

Moves back one half screen

G (Go)

Moves to end of file

These commands also take numeric prefixes to move further ahead in the file. The command 3CTRL-F (hitting the number 3 key, then the CTRL and F keys simultaneously) will move ahead three full screens, whereas the command 4CTRL-B will move back four screens. The G command goes to a specific line number or goes to the end if no line number is specified. Therefore, the command 23G positions the cursor at line 23; the command 1G (number 1 and letter G) positions it at the first line in the file, whereas the command G goes to the last line.

Modifying Text

vi provides simple commands for changing and deleting parts of your text. The command rn means replace the current character (where the cursor is located) with the character n. You can also replace multiple characters; for example, the command 3rn replaces three characters with n.

The command RstringESC replaces the current characters with the string you type in. Characters are overwritten until you press ESC (the escape key, usually in the upper left-hand of the keyboard).

The c (change) command enables you to make larger-scale modifications to words or lines. For example, the command cwstringESC changes the current word by replacing it (that is, overwriting it) with whatever string you type. The change continues until you press ESC. When you make such a change, vi puts a $ over the last character of the word to be changed. The $ disappears when you press ESC.

The command c$stringESC will change everything from the current cursor position to the end of the line ($) by replacing the text with the string you type in. ESC takes you out of input mode.

The change commands also can take numerical arguments, so the command 4cw will change the next four words, and the command 3c$ will change the next three lines.

DeletingText

vi provides two delete commands that let you delete small or large chunks of text. To delete single letters, use the command x. x deletes the current character. As with other vi commands, x takes a numerical argument. This means that the command 7x deletes seven characters-the character under the cursor and the six to the right of it. The d (delete) command works on larger units of text. Table 5–3 shows some examples of the delete command.

Table 5–3: Examples of the delete Command

Command

What It Does

dw

Deletes from the cursor to the end of the word

3dw

Deletes three words

d$

Deletes to the end of the line

D

Deletes to the end of the line (a synonym for d$)

3d$

Deletes to the end of the third line ahead

d)

Deletes to the beginning of the next line

d}

Deletes to the beginning of the next paragraph

d]]

Deletes to the beginning of the next section

dd

Deletes the current line

2dd

Deletes two lines

dENTER

Deletes two lines

dG

Deletes from the cursor to the end of the file

Undoing Changes and Deletions

You have several ways to restore text after you have changed it. This section covers three of the simplest ways to restore text. Other useful ways of recovering changed text are discussed later in this chapter.

To undo the most recent change or deletion, use the command u. u (lowercase u) undoes the most recent change. If you change a word, u will change it back. If you delete a section, u will restore it. u only works on the last change or deletion, and it does not work on single-character changes.

If you use the command U (uppercase U), all of the changes made in a line since you last moved to that line will be undone, including single-character changes. U restores the current line to what it looked like before you issued any of the commands that changed it. If you make changes, move away from the line, and then move back, U will not work as it is intended to.

When vi deletes some material, it places the text in a separate buffer. If you delete more material, this buffer is overwritten, so that it always contains the most recently deleted material. Using the command p, you can restore the deleted text. The p (lowercase p) command puts the contents of the buffer to the right of the cursor position. If you have deleted whole lines, p will put them on a new line immediately below the current line. The command P (uppercase P) will put the contents of the buffer to the left of the cursor. If you have deleted whole lines, P will put them above the current line. Notice that you can move text by deleting into the buffer with the d command, moving the cursor, and putting the text someplace else.

If you notice that you have made some horrible mistake, you can partially recover with the command :e!-the colon (:) causes the cursor to drop to the bottom line, and the e! command means “edit again.” This command throws away all changes you made since the last time you wrote (saved) the file. This command restarts your session by reading in the file from disk again. Note that you cannot undo this command.

The Ten-Minute vi Tutorial

vi is a complex program. It will be useful for you to have a list of vi commands handy; however, simply reading a command summary will not teach you how to use the editor.

The most effective way to learn vi is to try out the commands to see how they work and what effect they have on the file. To make this easy for you to do, this ten-minute tutorial is provided. It will quickly teach you enough of the features and commands of vi to begin using it productively for text editing and command editing in the shell. Before you begin, you should be logged into UNIX with your terminal (TERM) variable set. Next, follow these steps:

  1. Type vi mydog.

    vi will start and show you an almost-blank screen. Your cursor will be at the first position of the first line, and all other lines will be marked by the ~ character.

  2. Type the command i (lowercase I).

    vi goes into input mode.

  3. Type the following text:

    The quick brown fox jumped over the lazy dog. Through half-shut eyes, the dog watched the fox jump, and then wrote down his name. The dog drifted back to sleep and dreamed of biting the fox. What a foolish, sleepy dog.

  4. Press ESC. The ESC key puts you back in command mode. vi does not signal that you are in command mode, but if you hit ESC a second time, your terminal bell will ring. Hitting ESC multiple times is an easy way to confirm that you are back in command mode.

  5. Go to the beginning of the last line in the file by typing the command G.

  6. Write the contents of the buffer to a new file named dog by typing : w dog.

  7. Read in the contents of this file by typing : r dog.

  8. Go to the first line in the file by typing 1G.

  9. Go to the sixth line by typing 6G.

  10. The h, j, k, and l commands move the cursor by one position as follows: h moves the cursor one character to the left and l moves one character to the right, while j moves the cursor down one line and k moves it up one line.

  11. Using these commands, position the cursor at the word “fox” in the next line and delete three characters by typing 3x.

  12. Insert the word “cat” by typing i catESC.

  13. Your terminal bell should ring, indicating you are in command mode.

  14. Pressing ENTER takes you to the beginning of the next line, and-(minus) takes you to the beginning of the preceding line. Press-(minus) until the cursor is at the / in “lazy dog.”

  15. Typing w will advance one word, and b will back up one word. Advance to “dog” by pressing w, and then go back to “lazy” by pressing b. Delete the word by typing dw.

  16. Undo this deletion by typing u.

  17. Scroll through the file by pressing CTRL-D to advance one half screen; then press CTRL-U to back up one half screen. Scroll to the end of the file, and then back up once by pressing CTRL-D CTRL-D CTRL-D CTRL-U.

  18. Your cursor will be at “down his name.” If it isn’t, move it there using the h, j, k, and l commands.

  19. Change the word “his” to “my” by using the cw command like this: cwmyESC.

  20. Move back to the first line of the file by typing 1G.

  21. Delete three lines into a buffer with the command 3dd.

  22. Move to the end of the file by typing G.

  23. Put the deleted material here by typing p.

  24. Move back one-half screenful with CTRL-U.

  25. Delete the line by typing dd.

  26. Write the file and quit using the command ZZ.

Advanced Editing with vi

At this point, you have read enough about vi to be able to enter some text and begin to edit it by making additions, changes, and deletions. In this section, you will learn about some features of vi that make it easier for you to edit documents.

Searching for Text

With vi you use the same commands for searching in your file as in ed. To search forward in your document, use the command /string. For example, typing /lazy will cause the cursor to drop to the status line (the last line on the screen), print the string “/lazy” and then refresh the screen, positioning the cursor at the next occurrence of “lazy” in the file. As in ed, the command // will search for the next occurrence of the search string “lazy,” as will /ENTER.

To search backward in the file for the string “lazy,” use the command ? lazy. This will cause the cursor to drop to the status line, print the string “?lazy,” and then refresh the screen, positioning the cursor at the previous occurrence of “lazy” in the file.

To repeat the last search, regardless of whether it is a forward (/) or backward (?) search, use the command n.

The command n is a synonym for either / / or ? ?. The command N will reverse the direction of the search. If you use /word to search forward for “word,” the command N will search backward for the same search term.

Copying and MovingText

Rearranging portions of text using vi involves three steps:

  1. You yank or delete the material.

  2. You move the cursor to where the material is to go.

  3. You place the yanked or deleted material there.

The command y (for yank) copies the characters starting at the cursor into a storage area (the buffer). yank has the same command syntax as delete. A numeric prefix specifies the number of objects to be yanked, and a suffix after y defines the objects to be yanked. Some examples of the y command are shown in Table 5–4.

Table 5–4: Some Examples of Yanking

Command

What It Does

yw

Yanks a word

3yw

Yanks three words

y$

Yanks to the end of the line

y)

Yanks to the end of the sentence

y}

Yanks to the end of the paragraph

y]]

Yanks to the end of the section

yy or Y

Yanks the current line

3Y

Yanks three lines, starting at the current line

Y}

Yanks lines to the end of the paragraph

To move yanked text, put the cursor where you wish to place the yanked material, and use the p command to put the text there. The command p (lowercase p) puts the yanked text to the right of the cursor. If an entire line was yanked (Y), the text is placed below the current line. The command P (uppercase P) puts the yanked text to the left of the cursor. If an entire line was yanked, the text is placed above the current line.

Working Buffers

In addition to its editing buffer, vi maintains several other temporary storage areas called working buffers that you have access to.

There is one unnamed buffer. vi automatically saves the material you last yanked, deleted, or changed in this unnamed buffer. Anytime you yank, delete, or change something, the contents of this buffer are overwritten; that is, the contents are replaced with the new material. You can place the contents of this buffer wherever you wish with the p or P command, as shown previously

vi also maintains 26 named buffers, named a, b,c,d,z. vi does not automatically save material to these buffers. If you wish to put text into them, you precede a command (Y, d, c) with a double quotation mark (") and the name of the buffer you wish to use. For example, "a3 Y yanks three lines into buffer a, and "g5dd deletes five lines of text beginning with the current line and places them in buffer g.

Although the material in the unnamed buffer is always overwritten, you can append text to the named buffers. If you use the command "b5Y to yank five lines into buffer b, the command "B5Y will yank five lines and append them to buffer b. This is especially useful if you are making many rearrangements of a passage. You can append several lines or sentences into a buffer, in the order you wish, and then move them together.

To put the contents of the buffer back into the text, use the p or P (put) commands, preceded by a double quotation mark (") and the buffer name. For example, "bp will put the contents of buffer b to the right of the cursor, or below the current line if the entire line was yanked. The command "bP will put the contents of the b buffer to the left of the cursor position, or above the current line if the entire line was yanked.

vi also maintains nine numbered buffers that it uses automatically Whenever you use the d command to delete more than a portion of one line, the deleted material is placed in the numbered buffers. Buffer number 1 contains your most recently deleted material, buffer number 2 contains your second most recently deleted material, and so forth.

To recover material that was deleted, use the p or P command preceded by a double quotation mark (") and the number of the buffer. For example, "1p (number 1 and p) will put the most recently deleted material below the line where the cursor is positioned. The command "6P will take the material deleted six delete commands ago (the contents of buffer 6) and put it above the current line.

Editing Multiple Files

vi allows you to work on several files in one editing session. This is especially handy if you want to move text from one file to another. If you invoke vi with multiple filenames, for example: vi dog cat letter, vi will edit them sequentially When you have finished editing dog, the commands :w and :n will write the contents of the editing buffer to the file dog and begin editing the file cat. When cat is finished, you can write that editing buffer to its file and begin working on letter.

The benefit of editing several files in one editing session rather than issuing three vi commands (vi dog; vi cat; vi letter) is that named buffers retain their contents within an editing session, even across files. You can move text between files in this way For example, first issue the command vi dog cat letter. Then, you can yank material from the dog file using "a9Y to yank nine lines into buffer a. The command : n then starts to edit the next file, cat. You can yank text from this file; for example, "b2Y will yank two lines into buffer b. Then you can move to the third file, letter, with the command : n.

Once in the letter file, you can put the material in buffers a and b into letter. The commands "ap and "bp will put the contents of buffer a (from the first file, dog) below this line, and put the contents of buffer b (from the second file, cat) below that line.

Inserting Output from Shell Commands

It is often useful to be able to insert the output of shell commands into a file that you are editing. For example, you might want to time-stamp an entry that you make in a file that acts as a daily journal. vi provides the capability to execute a command within vi and replace the current line with its output. For example, to create a time stamp, the command : r !date will read the output of the date command into the buffer, after the current line, so that it appears in the following format: Thu Aug 3 16:24:04 EDT 2006.

Setting vi Options

vi can be customized easily. Because it supports many options, setting the values of these options is a simple way to have vi behave the way you wish. There are three ways to set options in vi, and each has advantages. If you wish to set or change options during a vi editing session, simply type the : (colon) command while in command mode and issue the set command. For example, the command : set wrapmargin=15 or, alternatively, : set wm=15 will set the value of the wrapmargin option to 15 for the rest of the session (that is, lines will automatically be split 15 spaces before the edge of the screen). Any of the options can be set in this way during your current editing session.

Using an .exrc File   You can have your options set automatically before you invoke vi by placing all of your set commands in a file called .exrc (for ex run command) in your login directory These set commands will be executed automatically when you invoke vi.

Normally, the .exrc file in the current directory is not checked. If you wish vi to check for .exrc in the working directory, put the line set exrc in the $HOME/.exrc file.

An advantage of using .exrc files to define your options is that you can place different .exrc files in different directories. An .exrc file in a subdirectory will override the .exrc in your login directory as long as you are working in that subdirectory If you do different kinds of editing, this feature is especially useful. If you write computer programs in a Prog directory, for instance, you can customize Prog/.exrc to use options that make sense in program editing. For example, adding the line set ai noic nomagic sets the autoindent option, which makes each line start in the same column as the preceding line; that is, it automatically sets blocks of program text. It also sets the noignorecase option, which treats uppercase and lowercase characters as different letters in a search. This is important in programming because many languages treat uppercase and lowercase as totally different characters. The example also sets the option nomagic; that is, it ignores the special meanings of regular expression characters such as {,}, and *. Because these characters have literal meanings in programs, they should be searched for as characters, not as regular expressions.

If you write memos in a Memos directory, you can customize Memos/.exrc to set these options and make writing prose easier. For example, the entry : set noai ic magic wm=15 nu does not set an autoindent option (noai); consequently, all columns begin in the leftmost column, as they should for text. It sets the ignorecase option (ic) in searches, so you can find a search string regardless of how it is capitalized. It sets magic, so that you can use special characters in regular expression searches, and it sets the wrapmargin option to 15; that is, lines are automatically broken at the space to the left of the fifteenth column from the right of the screen. It also sets the number option, which causes each line of the file to be displayed with its line number offset to the left of the line.

Using an EXINIT Variable   You can have your vi options defined when you log in by setting options in an EXINIT variable in your .profile or .login file. For example, for the Korn shell, put lines like the following in your .profile file: the line EXINIT="set noautoindent ignorecase magic wrapmargin=15 number" followed by the line entry export EXINIT. If you use the C shell (csh), put lines like the following in your .login file: the line setenv EXINIT "set noautoindent ignorecase magic wrapmargin=15 number" followed by the line entry export EXINIT.

If you define an EXINIT variable in .profile or .login, the settings apply every time you use vi during that login session. An advantage of using EXINIT is that vi will start up faster, because settings are defined once when you log in, rather than each time you start using vi. A second advantage is that vi will always work the same way in every directory.

Table 5–5 lists some useful vi options.

Table 5–5: Some Useful vi Options

Option

Type

Default

Description

autoindent, ai

On/Off

noai

(Do not) Start each line at the same column as the preceding line.

autowrite, aw

On/Off

noaw

(Do not) Automatically write any changes in buffer before executing certain vi commands.

flash

On/Off

flash

Flash/blink screen instead of ringing terminal bell.

ignorecase, ic

On/Off

noic

Uppercase and lowercase are (not) equivalent in searches.

magic

On/Off

magic

nomagic ignores the special meanings of regular expressions except ^, ., and $.

number, nu

On/Off

nonu

(Do not) Number each line.

report

Numeric

5

Displays number of lines changed (changed, deleted, or yanked) by the last command.

shell, sh

String

login shell

Shell executed by vi commands, :!, or !.

showmode, smd

On/Off

nosmd

(Do not) Print “INPUT MODE" at bottom right of screen when in input mode.

terse

On/Off

noterse

terse provides short error messages.

timeout

On/Off

timeout

With timeout, you must enter a macro name in less than one second.

wrapmargin, wm

Numeric

0 (Off)

Automatically break lines before right margin. wm=20 defines a right margin 20 spaces to the right of the edge of the screen.

Displaying Current Option Settings

You have three ways to view your current option settings. Each of them involves issuing an ex command.

To see the value of any specific option, type :set optionname? The editor will return the value of that option. The ? at the end of the command is required if you are inquiring about a specific option setting. For example, in the command :set nu?, nu is the option to display the line number for each line in the buffer. If this option is not set, vi returns the message “nonumber.” To see the values of all options that you have changed, type :set. To see the values of all the options in vi, type :set all.

vi Options

You can set three kinds of options in vi: those that are on or off, those that take a numeric argument, and those that take a string argument. In all three cases, several options can be set with a single :set command.

On/Off Options   For those options that are turned on or off, you issue a set command such as :set terse or : set noterse. terse is an option that provides short error messages. : set terse says you want the shorter version of error messages, : set noterse means you want this option off-you want longer error messages.

showmode is another useful option that can be set on or off. showmode tells you when you are in input mode by displaying the words “INPUT MODE" in the lower-right corner of your screen. For example, : set showmode sets this option.

The number option precedes each line that is displayed with its line number in the file with the command : set number.

Numeric Options   You set options that take a numeric argument by specifying a number value. For example, : set wm=21 applies to the wrapmargin (wm) option, which causes vi to automatically break lines by inserting a carriage return between words. The line break is made as close as possible to the margin specified by the wm option. wm=21 defines a margin 21 spaces away from the right edge of the screen.

Another useful numeric option is report. vi will show you, at the bottom of your screen, the number of lines changed, deleted, or yanked. Normally, this is displayed only if five or more lines have been modified. If you want feedback when more or fewer lines are affected, set report appropriately, such as the command : set report=1. This command will have vi tell you every time you have modified one or more lines.

String Options   Certain options take a string as an argument. You set these by specifying the string in the set command. For example, to specify which shell you wish to use to execute shell commands (those that begin with :! or !) use a command such as :set shell=/usr/ bin/sh. This particular command sets the shell to the Korn shell.

Writing vi Macros

vi provides a map capability that enables you to combine a sequence of editing commands into one command called a macro. You use map to associate any keystrokes with a sequence of up to 100 vi commands.

How to Enter Macros

Macro definitions are nothing more than the string of commands that you would enter from the keyboard. Before you can actually make up your own definitions, you need to know how to enter the macros into vi. vi macros include some special characters you need to know about. The ESC (^[) and return (^M) characters are part of the macro definition. You need to include these characters to be able to leave input mode and to terminate a command. If you type the macro exactly as you would enter the command string, it won’t work. When you press ESC, you leave input mode-you do not put an ESC character in the line. When you press ENTER, you move to the next line (or end a command)-you do not put a CTRL-M (^M) in the line. To put these commands into a definition, you need the CTRL-V command. CTRL-V says to vi, “put the next literal character in the line.” To put an ESC into the command, you press CTRL-V ESC and you see ^[ on the screen. (Remember, ^[ is the way vi displays the ESC character on the screen.) Similarly, to put a return in the command, press CTRL-V ENTER and you will see ^M. Remember, ^M is the way vi represents the return character.

You can define macros that work in command mode, in input mode, or in both. For example, in command mode you can define a new command Q, which will quit vi without writing changes to a file, by typing : map Q : q! ^M. This command says to map the uppercase letter Q to the command sequence :q!. The macro ends with a return, which in vi is represented as ^M (CTRL-M). The general format for any macro definition is map macroname commands ENTER.

When you define a macro in this way, it applies to command mode only. That is, the uppercase letter Q is still interpreted as Q in input mode, but as :q! in command mode. To undo a macro, use the unmap command; for example unmap macroname.

Macros are especially useful when you have many repetitive editing changes to make. In editing a long memo, or a manuscript, you may find that you need to change the font that you use. You may need to put all product names in bold type, for example. If you use a UNIX/Linux System text formatter, such as troff or groff, you do this by adding a command to change the font-\fB (font bold), \fI (font italic), and \fP (font previous) are commonly used. A detailed discussion of text formatting with troff is on the companion web site.

If you type the word “example,” it is printed in roman type and looks like “example.” If you type ‘\fBexample\fP,” troff prints the word in bold and then switches back to the previous font; thus, it looks like “example.” To change a word from roman font to bold, you need to add the string \fB to the beginning of the word and the string \fP to the end. Or you could define a vi macro that would do it automatically For example, the macro definition : map v i\fB^[ea\fP^[ ^M maps the υ (lowercase v) into the command sequence that goes into input mode (i), adds the string for bold font (\fB), leaves input mode (the ^[is how vi represents the ESC character on the screen), goes to the end of the word (e), appends (a) the string for previous font (\fP), and leaves input mode (the ^[represents the ESC character). The ^M represents the ENTER at the end of the macro. When you type v in command mode, all letters from the position of your cursor to the end of the word will be surrounded by the \fB, \fP pair and will be made bold when you format your document.

Defining Macros in Input Mode

You can also define macros that work only when vi is in input mode. The command :map! indicates the macro is to work in input mode, so that the general form of such a macro def inition is :map! macroname string ENTER. For example, :map ! ZZ ^[:wq ^M defines an input macro, called ZZ, that is equivalent to hitting the ESC key (^[) and typing : wq followed by a carriage return (^M is how vi represents a carriage return). By defining this macro, we can have the ZZ command write and quit in input mode, as well as in command mode (as it normally does).

Macros in .exrc or EXINIT   You can use the map command to define a macro in the same way that you can set vi options. You can type : map Q : q! ENTER from the keyboard while in vi, you can add the map command to your .exrc file, or you can add it to your EXINIT variable in .profile or .login.

The name of the macro should be short, only a few characters at most. When you use it, the entire macro name must be typed in less than one second. For example, with the ZZ macro defined in input mode, you must type both Zs within one second. If you don’t, the Zs will be entered in the file.

Useful Text Processing Macros

Following is a discussion of two useful vi macros, vispell and search. These macros illustrate how vi macros can be written to provide powerful command combinations in vi that are useful in everyday text processing.

Checking Spelling in Your File

Writers need to check spelling as they work. Most UNIX systems include a spelling checker called spell. Normally, you execute spell from the shell, giving it a filename, for example, $ spell mydog. spell lists on your display all the words in the file that are not in its dictionary You can capture this output to another file by typing $ spell mydog > errors. You can then invoke the vi editor and go to the end of the file mydog by typing $ vi + mydog.

Then you can read the errors file into the vi buffer by typing : r errors and search for each error in the file mydog.

The vispell Macro

You can check and correct spelling from within vi with the vispell macro. Define the following macro in your .exrc file or EXINIT: map # 1 1G!Gvi spell^M^[.

The name of this macro is #1, which refers to Function Key 1 or the PF1 key on your terminal. When you press PF1, the right-hand side of the macro is invoked. This says, “Go to line 1 (1G), invoke a shell (!), take the text from the current line (1) to the end (G), and send it as input to the command (vispell)” The ^M represents the carriage return needed to end the command, and the ^[represents the ESC needed to return to command mode.

Place the following shell script in your directory:

 #!/bin/sh # # vispell-The first half of an interactive # spelling checker for vi # tee ./vis$$ echo SpellingList trap '/bin/rm −f ./vis$$;exit' 0 1 2 3 15 /usr/bin/spell vis$$| comm −23-$HOME/lib/spelldict|tee −a $HOME/lib/spell.errors

Shell scripts are discussed in Chapter 20. The end result of this macro is that a list of misspelled words, one per line, is appended to your file while you are in vi. For example,

 and this finally is the end of this memo. reddendent finalty wrod

The search Macro

At this point vispell is useful. You could go to the end of the file (G), and type /wrod to search for an occurrence of this misspelled word. The n command will find the next occurrence, and so forth. Consider an enhancement of the normal search (/ and ?) capabilities of ed and vi. In a normal search, vi searches for strings; that is, if you search for “the,” you will also find “theater,” “another,” and “thelma.” In vi, the expression \<string matches “string” when it appears at the beginning of a word, and the expression \>string matches “string” at the end of a word. To search for “the” at the beginning of a word, you need to use /\<the; to search for “the” at the end of a word, you need to use /the\>. To search for a word that contains only “the” (the same beginning and end), you need to use /\<the\>, which searches for the word “the” rather than the string “the.” We can create a search macro that provides an efficient way to search for misspellings found by vispell. The search macro is defined in .exrc or in EXINIT by adding the following line: map #2 Gi / \ <^[A\ >^["adda.

The preceding macro maps the macro name Function Key 2 or PF2 (#2) to the right-hand side of the macro. The right-hand side says go to the beginning of the last line (G), go into input mode (i), insert the character for “search” (/) and the characters for “beginning of a word” (\<), and issue an ESC (^[) to leave input mode. It appends to the end of the line (A) the characters for “end of a word” (\>), and issues an ESC (^[) to leave input mode. It identifies a register ("a) and deletes the line into it (dd); then it invokes the contents of that register as a macro (a).

After all the additions and deletions, the a register contains the command /\<wrod\ > where “wrod” is the misspelled word found by vispell. The search macro provides a way to search for the misspelling as a word rather than as a string. Using this macro will find the first occurrence of an error in your file. To search for the next occurrence, use the n command. vi will display the message “Pattern not found” if no more errors of this type exist. You can then press PF2 to search for the next error, and so forth. Note that if you are using the UNIX formatting macros, this search macro might not find all misspellings. For example, \fBwrod\fP would not be found.

A Final Note on vi

With all of the special character use in vi, and movement back and forth and left to right on your display, your screen may occasionally not respond correctly, and you may end up looking at a bunch of nonsense on your screen. One of the best features of vi is the ability to clear and redraw the screen by using the CTRL-L key sequence. Since the editor remembers what the correct display should be, vi will return to a readable screen with the up-to-date content on it.




UNIX. The Complete Reference
UNIX: The Complete Reference, Second Edition (Complete Reference Series)
ISBN: 0072263369
EAN: 2147483647
Year: 2006
Pages: 316

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net