BUY THIS BOOK

Safari Books Online

What is this?

Looking to Reprint this content?


Learning the vi Editor
Learning the vi Editor, Sixth Edition

By Linda Lamb, Arnold Robbins

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: The vi Text Editor
UNIX has a number of editors that can process the contents of text files, whether those files contain data, source code, or sentences. There are line editors, such as ed and ex, which display a line of the file on the screen; and there are screen editors, such as vi and emacs, which display a part of the file on your terminal screen. Text editors based on the X Window System are also commonly available, and are becoming increasing popular. Both GNU emacs and its derivative xemacs provide multiple X windows; an interesting alternative is the sam editor from Bell Labs. All but one of the vi clones described in Part II of this book also provide X-based interfaces.
vi is the most useful standard text editor on your system. (vi is short for visual editor and is pronounced "vee-eye.") Unlike emacs, it is available in nearly identical form on almost every UNIX system, thus providing a kind of text-editing lingua franca. The same might be said of ed and ex, but screen editors are generally much easier to use. With a screen editor, you can scroll the page, move the cursor, delete lines, insert characters, and more, while seeing the results of your edits as you make them. Screen editors are very popular, since they allow you to make changes as you read through a file, like you would edit a printed copy, only faster.
To many beginners, vi looks unintuitive and cumbersome—instead of using special control keys for word processing functions and just letting you type normally, it uses all of the regular keyboard keys for issuing commands. When the keyboard keys are issuing commands, vi is said to be in command mode. You must be in a special insert mode before you can type actual text on the screen. In addition, there seem to be so many commands.
Once you start learning, however, you realize that vi is well designed. You need only a few keystrokes to tell vi to do complex tasks. As you learn vi, you learn shortcuts that transfer more and more of the editing work to the computer—where it belongs.
vi (like any text editor) is not a "what you see is what you get" word processor. If you want to produce formatted documents, you must type in codes that are used by another formatting program to control the appearance of the printed copy. If you want to indent several paragraphs, for instance, you put a code where the indent begins and ends. Formatting codes allow you to experiment with or change the appearance of your printed files, and in many ways, give you much more control over the appearance of your documents than a word processor. UNIX supports the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Opening and Closing Files
You can use vi to edit any text file. vi copies the file to be edited into a buffer (an area temporarily set aside in memory), displays the buffer (though you can see only one screenful at a time), and lets you add, delete, and change text. When you save your edits, vi copies the edited buffer back into a permanent file, replacing the old file of the same name. Remember that you are always working on a copy of your file in the buffer, and that your edits will not affect your original file until you save the buffer. Saving your edits is also called "writing the buffer," or more commonly, "writing your file."
vi is the UNIX command that invokes the vi editor for an existing file or for a brand new file. The syntax for the vi command is:
$ vi [filename]
The brackets shown on the above command line indicate that the filename is optional. The brackets should not be typed. The $ is the UNIX prompt. If the filename is omitted, vi will open an unnamed buffer. You can assign the name when you write the buffer into a file. For right now, though, let's stick to naming the file on the command line.
A filename must be unique inside its directory. On older System V UNIX systems, it cannot exceed 14 characters in length (most common UNIX systems allow much longer names). A filename can include any 8-bit character except a slash (/), which is reserved as the separator between files and directories in a pathname, and ASCII NUL, the character with all zero bits. You can even include spaces in a filename by typing a backslash (\) before the space. In practice, though, filenames generally consist of any combination of uppercase and lowercase letters, numbers, and the characters dot (.) and underscore (_). Remember that UNIX is case-sensitive: lowercase letters are distinct from uppercase letters. Also remember that you must press RETURN to tell UNIX that you are finished issuing your command.
When you want to open a new file in a directory, give a new filename with the vi command. For example, if you want to open a new file called
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Quitting Without Saving Edits
When you are first learning vi, especially if you are an intrepid experimenter, there are two other ex commands that are handy for getting out of any mess that you might create.
What if you want to wipe out all of the edits you have made in a session and then return to the original file? The command:
:e! RETURN
            
returns you to the last saved version of the file, so you can start over.
Suppose, however, that you want to wipe out your edits and then just quit vi? The command:
:q! RETURN
            
quits the file you're editing and returns you to the UNIX prompt. With both of these commands, you lose all edits made in the buffer since the last time you saved the file. vi normally won't let you throw away your edits. The exclamation point added to the :e or :q command causes vi to override this prohibition, performing the operation even though the buffer has been modified.
  • You try to write your file, but you get one of the following messages:
    File exists
    File file exists - use w!
    [Existing file]
    File is read only
    Type :w! file to overwrite the existing file, or type :w newfile to save the edited version in a new file.
  • You want to write a file, but you don't have write permission for it. You get the message "Permission denied."
    Use :w newfile to write out the buffer into a new file. If you have write permission for the directory, you can use mv to replace the original version with your copy of it. If you don't have write permission for the directory, type :w pathname/file to write out the buffer to a directory in which you do have write permission (such as your home directory, or /tmp).
  • You try to write your file, but you get a message telling you that the file system is full.
    Type :!rm junkfile to delete a (large) unneeded file and free some space. (Starting an
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Simple Editing
This chapter introduces you to editing with vi, and it is set up to be read as a tutorial. In it you will learn how to move the cursor and how to make some simple edits. If you've never worked with vi, you should read the entire chapter.
Later chapters show you how to expand your skills to perform faster and more powerful edits. One of the biggest advantages for an adept user of vi is that there are so many options to choose from. (One of the biggest disadvantages for a newcomer to vi is that there are so many different editor commands.)
You can't learn vi by memorizing every single vi command. Start out by learning the basic commands introduced in this chapter. Note the patterns of use that the commands have in common.
As you learn vi, be on the lookout for more tasks that you can delegate to the editor, and then find the command that accomplishes it. In later chapters you will learn more advanced features of vi, but before you can handle the advanced, you must master the simple.
This chapter covers:
  • Moving the cursor
  • Adding and changing text
  • Deleting, moving, and copying text
  • More ways to enter insert mode
vi has two modes: command mode and insert mode. As soon as you enter a file, you are in command mode, and the editor is waiting for you to enter a command. Commands enable you to move anywhere in the file, to perform edits, or to enter insert mode to add new text. Commands can also be given to exit the file (saving or ignoring your edits) in order to return to the UNIX prompt.
You can think of the different modes as representing two different keyboards. In insert mode, your keyboard functions like a typewriter. In command mode, each key has a new meaning or initiates some instruction.
There are several ways to tell vi that you want to begin insert mode. One of the most common is to press i. The i doesn't appear on the screen, but after you press it, whatever you type will appear on the screen and will be entered into the buffer. The cursor marks the current insertion point. To tell vi that you want to stop inserting text, press ESC. Pressing
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
vi Commands
vi has two modes: command mode and insert mode. As soon as you enter a file, you are in command mode, and the editor is waiting for you to enter a command. Commands enable you to move anywhere in the file, to perform edits, or to enter insert mode to add new text. Commands can also be given to exit the file (saving or ignoring your edits) in order to return to the UNIX prompt.
You can think of the different modes as representing two different keyboards. In insert mode, your keyboard functions like a typewriter. In command mode, each key has a new meaning or initiates some instruction.
There are several ways to tell vi that you want to begin insert mode. One of the most common is to press i. The i doesn't appear on the screen, but after you press it, whatever you type will appear on the screen and will be entered into the buffer. The cursor marks the current insertion point. To tell vi that you want to stop inserting text, press ESC. Pressing ESC moves the cursor back one space (so that it is on the last character you typed) and returns vi to command mode.
For example, suppose you have opened a new file and want to insert the word "introduction". If you type the keystrokes iintroduction, what appears on the screen is:
introduction
When you open a new file, vi starts in command mode and interprets the first keystroke (i) as the insert command. All keystrokes made after the insert command are considered text until you press ESC. If you need to correct a mistake while in insert mode, backspace and type over the error. Depending on the type of terminal you are using, backspacing may erase what you've previously typed or may just back up over it. In either case, whatever you back up over will be deleted. Note that you can't use the backspace key to back up beyond the point where you entered insert mode.
vi has an option that lets you define a right margin and provides a carriage return automatically when you reach it. For right now, while you are inserting text, press RETURN to break the lines.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Moving the Cursor
You may spend only a small amount of time in an editing session adding new text in insert mode; much of the time you will be making edits to existing text.
In command mode you can position the cursor anywhere in the file. Since you begin all basic edits (changing, deleting, and copying text) by placing the cursor at the text that you want to change, you want to be able to move the cursor to that place as quickly as possible.
There are vi commands to move the cursor:
  • Up, down, left, or right—one character at a time
  • Forward or backward by blocks of text such as words, sentences, or paragraphs
  • Forward or backward through a file, one screen at a time
In Figure 2.1, an underscore marks the present cursor position. Circles show movement of the cursor from its current position to the position that would result from various vi commands.
Figure 2.1: Sample movement commands
The keys h, j, k, and l, right under your fingertips, will move the cursor:
h
left, one space
j
down, one line
k
up, one line
l
right, one space
You can also use the cursor arrow keys (, , , ), + and - to go up and down, or the RETURN and BACKSPACE keys, but they are out of the way, and the arrow keys are not supported by all terminals. At first, it may seem awkward to use letter keys instead of arrows for cursor movement. After a short while, though, you'll find it is one of the things you'll like best about vi—you can move around without ever taking your fingers off the center of the keyboard.
Before you move the cursor, press ESC to make sure that you are in command mode. Use h, j, k, and l to move forward or backward in the file from the current cursor position. When you have gone as far as possible in one direction, you hear a beep and the cursor stops. For example, once you're at the beginning or end of a line, you cannot use h or l to wrap around to the previous or next line; you have to use
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Simple Edits
When you enter text in your file, it is rarely perfect. You find typos or want to improve on a phrase; sometimes your program has a bug. Once you enter text, you have to be able to change it, delete it, move it, or copy it. Figure 2.3 shows the kinds of edits you might want to make to a file. The edits are indicated by proofreading marks.
Figure 2.3: Proofreading edits
In vi you can perform any of these edits with a few basic keystrokes: i for insert (which you've already seen); a for append; c for change; and d for delete. To move or copy text, you use a pair of commands. You move text with a d for delete, then a p for put; you copy text with a y for "yank," then a p for put. Each type of edit is described in this section. Figure 2.4 shows the vi commands you use to make the edits marked in Figure 2.3.
Figure 2.4: Edits with vi commands
You have already seen the insert command used to enter text into a new file. You also use the insert command while editing existing text to add missing characters, words, and sentences. In the file practice, suppose you have the sentence:
with the cursor positioned as shown. To insert With a screen editor at the beginning of the sentence, enter the following:
KeystrokesResults
2k
Move the cursor up two lines with the k command, to the line where you want to make the insertion.
iWith a
Press i to enter insert mode and begin inserting text.
screen editor ESC
Finish inserting text, and press ESC to end the insert and return to command mode.
On the screen shown in the example above, vi pushes existing text to the right as the new text is inserted. That is because we are assuming that you are using
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
More Ways to Insert Text
You have inserted text before the cursor with the sequence:
itext to be inserted
               ESC
            
You've also inserted text after the cursor with the a command. There are other insert commands for inserting text at different positions relative to the cursor:
A
Append text to end of current line.
I
Insert text at beginning of line.
o
Open blank line below cursor for text.
O
Open blank line above cursor for text.
s
Delete character at cursor and substitute text.
S
Delete line and substitute text.
R
Overstrike existing characters with new characters.
All of these commands place you in insert mode. After inserting text, remember to press ESC to escape back to command mode.
A (append) and I (insert) save you from having to move your cursor to the end or beginning of the line before invoking insert mode. (The A command saves one keystroke over $a. Although one keystroke might not seem like much of a saving, the more adept—and impatient—an editor you become, the more keystrokes you will want to omit.)
o and O (open) save you from having to insert a carriage return. You can type these commands from anywhere within the line.
s and S (substitute) allow you to delete a character or a whole line and replace the deletion with any amount of new text. s is the equivalent of the two-stroke command c SPACE and S is the same as cc. One of the best uses for s is to change one character to several characters.
R ("large" replace) is useful when you want to start changing text, but you don't know exactly how much. For example, instead of guessing whether to say 3cw or 4cw, just type R and then enter your replacement text.
Except for o and O, the above insert commands (plus i and a) take numeric prefixes. With numeric prefixes, you might use the commands i, I, a, and A to insert a row of underlines or alternating characters. For example, typing 50i* ESC inserts 50 asterisks, and typing
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Joining Two Lines with J
Sometimes while editing a file you will end up with a series of short lines that are difficult to scan. When you want to merge two lines into one, position the cursor anywhere on the first line, and press J to join the two lines.
Suppose your file practice reads:
KeystrokesResults
J
J joins the line the cursor is on with the line below.
.
Repeat the last command (J) with the . to join the next line with the current line.
Using a numeric argument with J joins that number of consecutive lines. In the example above, you could have joined three lines by using the command 3J.
  • When you type commands, text jumps around on the screen and nothing works the way it's supposed to.
    Make sure you're not typing the J command when you mean j.
    You may have hit the CAPS LOCK key without noticing it. vi is case-sensitive. That is, uppercase commands (I, A, J, etc.) are different from lowercase commands (i, a, j), so all your commands are being interpreted not as lowercase but as uppercase commands. Press the CAPS LOCK key again to return to lowercase, press ESC to ensure that you are in command mode, then type either U to restore the last line changed or u to undo the last command. You'll probably also have to do some additional editing to fully restore the garbled part of your file.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Review of Basic vi Commands
Table 2.1 presents a few of the commands you can perform by combining the commands c, d, and y with various text objects. The last two rows show additional commands for editing. Table 2.2 and Table 2.3 list some other basic commands. Table 2.4 summarizes the rest of the commands described in this chapter.
Table 2.1: Edit Commands
Text ObjectChangeDeleteCopy
1 word cw dw yw
2 words, not counting punctuation
2cW or c2W 2dW or d2W 2yW or y2W
3 words back3cb or c3b 3db or d3b 3yb or y3b
1 line cc dd yy or Y
To end of linec$ or C d$ or D y$
To beginning of line c0 d0 y0
Single character r x or X yl or yh
Five characters 5s 5x 5yl
Table 2.2: Movement
MovementCommands
,,,
h, j, k, l
To first character of next line +
To first character of previous line -
To end of worde or E
Forward by wordw or W
Backward by wordb or B
To end of line $
To beginning of line 0
Table 2.3: Other Operations
Operations
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Moving Around in a Hurry
You will not use vi just to create new files. You'll spend a lot of your time in vi editing existing files. You rarely want to simply open to the first line in the file and move through it line by line. You want to get to a specific place in a file and start work.
All edits begin by moving the cursor to where you want to begin the edit (or, with ex line editor commands, by identifying the line numbers to be edited). This chapter shows you how to think about movement in a variety of ways (by screens, by text, by patterns, or by line numbers). There are many ways to move in vi, since editing speed depends on getting to your destination with only a few keystrokes.
This chapter covers:
  • Movement by screens
  • Movement by text blocks
  • Movement by searches for patterns
  • Movement by line number
When you read a book, you think of "places" in the book by page: the page where you stopped reading or the page number in an index. You don't have this convenience when you're editing files. Some files take up only a few lines, and you can see the whole file at once. But many files have hundreds of lines.
You can think of a file as text on a long roll of paper. The screen is a window of (usually) 24 lines of text on that long roll.
In insert mode, as you fill up the screen with text, you will end up typing on the bottom line of the screen. When you reach the end and press RETURN, the top line rolls out of sight, and a blank line appears on the bottom of the screen for new text. This is called scrolling.
In command mode, you can move through a file to see any text in it by scrolling the screen ahead or back. And, since cursor movements can be multiplied by numeric prefixes, you can move quickly to anywhere in your file.
There are vi commands to scroll forward and backward through the file by full and half screens:
^F
Scroll forward one screen.
^B
Scroll backward one screen.
^D
Scroll forward half screen (down).
^U
Scroll backward half screen (up).
(In the list of commands above, the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Movement by Screens
When you read a book, you think of "places" in the book by page: the page where you stopped reading or the page number in an index. You don't have this convenience when you're editing files. Some files take up only a few lines, and you can see the whole file at once. But many files have hundreds of lines.
You can think of a file as text on a long roll of paper. The screen is a window of (usually) 24 lines of text on that long roll.
In insert mode, as you fill up the screen with text, you will end up typing on the bottom line of the screen. When you reach the end and press RETURN, the top line rolls out of sight, and a blank line appears on the bottom of the screen for new text. This is called scrolling.
In command mode, you can move through a file to see any text in it by scrolling the screen ahead or back. And, since cursor movements can be multiplied by numeric prefixes, you can move quickly to anywhere in your file.
There are vi commands to scroll forward and backward through the file by full and half screens:
^F
Scroll forward one screen.
^B
Scroll backward one screen.
^D
Scroll forward half screen (down).
^U
Scroll backward half screen (up).
(In the list of commands above, the ^ symbol represents the CTRL key. ^F means to hold down the CTRL key and press the f key simultaneously.)
There are also commands to scroll the screen up one line (^E) and down one line (^Y). However, these two commands do not send the cursor to the beginning of the line. The cursor remains at the same point in the line as when the command was issued.
If you want to scroll the screen up or down, but you want the cursor to remain on the line where you left it, use the z command.
z RETURN
Move current line to top of screen and scroll.
z.
Move current line to center of screen and scroll.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Movement by Text Blocks
Another way that you can think of moving through a vi file is by text blocks—words, sentences, paragraphs, or sections.
You have already learned to move forward and backward by word (w, W, b or B). In addition, you can use these commands:
e
Move to end of word.
E
Move to end of word (ignore punctuation).
(
Move to beginning of current sentence.
)
Move to beginning of next sentence.
{
Move to beginning of current paragraph.
}
Move to beginning of next paragraph.
[[
Move to beginning of current section.
]]
Move to beginning of next section.
To find the end of a sentence, vi looks for one of the punctuation marks ? . !. vi locates the end of a sentence when the punctuation is followed by at least two spaces or when it appears as the last non-blank character on a line. If you have left only a single space following a period, or if the sentence ends with a quotation mark, vi won't recognize the sentence.
A paragraph is defined as text up to the next blank line, or up to one of the default paragraph macros (.IP, .PP, .LP, or .QP) from the troff MS macro package. Similarly, a section is defined as text up to the next default section macro (.NH, .SH, .H 1, .HU). The macros that are recognized as paragraph or section separators can be customized with the :set command, as described in Chapter 7.
Remember that you can combine numbers with movement. For example, 3) moves ahead three sentences. Also remember that you can edit using movement commands:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Movement by Searches
One of the most useful ways to move around in a large file quickly is by searching for text, or more properly, a pattern of characters. Sometimes a search can be performed to find a misspelled word or to find each occurrence of a variable in a program.
The search command is the special character / (slash). When you enter a slash, it appears on the bottom line of the screen; you then type in the pattern that you want to find: / pattern.
A pattern can be a whole word or any other sequence of characters (called a "character string"). For example, if you search for the characters red, you will match red as a whole word, but you'll also match occurred. If you include a space before or after pattern, the spaces will be treated as part of the word. As with all bottom-line commands, press RETURN to finish. vi, like all other UNIX editors, has a special pattern-matching language that allows you to look for variable text patterns; for example, any word beginning with a capital letter, or the word The at the beginning of a line.
We'll talk about this more powerful pattern-matching syntax in Chapter 6. For right now, think of pattern simply as a word or phrase.
vi begins the search at the cursor and searches forward, wrapping around to the start of the file if necessary. The cursor will move to the first occurrence of the pattern. If there is no match, the message "Pattern not found" will be shown on the status line.
Using the file practice, here's how to move the cursor by searches:
KeystrokesResults
/edits
Search for the pattern edits. Press RETURN to enter. The cursor moves directly to that pattern.
/scr
Search for the pattern scr. Press RETURN to enter. Note that there is no space after scr.
The search wraps around to the front of the file. Note that you can give any combination of characters; a search does not have to be for a complete word.
To search backward, type a
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Movement by Line Number
Lines in a file are numbered sequentially, and you can move through a file by specifying line numbers.
Line numbers are useful for identifying the beginning and end of large blocks of text you want to edit. Line numbers are also useful for programmers, since compiler error messages refer to line numbers. Line numbers are also used by ex commands, which you will learn in the next chapters.
If you are going to move by line numbers, you must have a way to identify them. Line numbers can be displayed on the screen using the :set nu option described in Chapter 7. In vi, you can also display the current line number on the bottom of the screen.
The command CTRL-G causes the following to be displayed at the bottom of your screen: the current line number, the total number of lines in the file, and what percentage of the total the present line number represents. For example, for the file practice, CTRL-G might display:
"practice" line 3 of 6 --50%--
CTRL-G is useful either for displaying the line number to use in a command or for orienting yourself if you have been distracted from your editing session.
Depending upon the implementation of vi you're using, you may see additional information, such as what column the cursor is on, and an indication as to whether or not the file has been modified but not yet written out. The exact format of the message will vary as well.
You can use line numbers to move the cursor through a file. The G (go to) command uses a line number as a numeric argument and moves directly to that line. For instance, 44G moves the cursor to the beginning of line 44. G without a line number moves the cursor to the last line of the file.
Typing two backquotes (` `) returns you to your original position (the position where you issued the last G command), unless you have done some edits in the meantime. If you have made an edit, and then moved the cursor using some command other than G, ` ` will return the cursor to the site of your last edit. If you have issued a search command (/ or ?), ` ` will return the cursor to its position when you started the search. A pair of apostrophes (
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Review of vi Motion Commands
Table 3.1 summarizes the commands covered in this chapter.
Table 3.1: Movement Commands
MovementCommand
Scroll forward one screen.
^F
Scroll backward one screen.
^B
Scroll forward half screen.
^D
Scroll backward half screen.
^U
Scroll forward one line.
^E
Scroll backward one line.
^Y
Move current line to top of screen and scroll.
z RETURN
Move current line to center of screen and scroll.
z.
Move current line to bottom of screen and scroll.
z-
Redraw the screen.
^L
Move to home—top line of screen.
H
Move to middle line of screen.
M
Move to bottom line of screen.
L
Move to first character of next line.
RETURN
Move to first character of next line.
+
Move to first character of previous line.
-
Move to first non-blank character of current line.
^
Move to column n of current line.
n
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Beyond the Basics
You have already been introduced to the basic vi editing commands, i, a, c, d, and y. This chapter expands on what you already know about editing. It covers:
  • Description of additional editing facilities, with a review of general command form
  • Additional ways to enter vi
  • Making use of buffers that store yanks and deletions
  • Marking your place in a file
In Chapter 2, you learned the edit commands c, d, and y, as well as how to combine them with movements and numbers (such as 2cw or 4dd). In Chapter 3, you added many more movement commands to your repertoire. Although the fact that you can combine edit commands with movement is not a new concept to you, Table 4.1 gives you a feel for the many editing options you now have.
Table 4.1: More Editing Commands
ChangeDeleteCopyfrom Cursor to ...
cH dH yH top of screen
cL dL yL bottom of screen
c+ d+ y+ next line
c5| d5| y5| column 5 of current line
2c) 2d) 2y) second sentence following
c{ d{ y{ previous paragraph
c/ pattern d/ pattern y/ pattern pattern
cn dn yn next pattern
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
More Command Combinations
In Chapter 2, you learned the edit commands c, d, and y, as well as how to combine them with movements and numbers (such as 2cw or 4dd). In Chapter 3, you added many more movement commands to your repertoire. Although the fact that you can combine edit commands with movement is not a new concept to you, Table 4.1 gives you a feel for the many editing options you now have.
Table 4.1: More Editing Commands
ChangeDeleteCopyfrom Cursor to ...
cH dH yH top of screen
cL dL yL bottom of screen
c+ d+ y+ next line
c5| d5| y5| column 5 of current line
2c) 2d) 2y) second sentence following
c{ d{ y{ previous paragraph
c/ pattern d/ pattern y/ pattern pattern
cn dn yn next pattern
cG dG yG end of file
c13G d13G y13G line number 13
Notice how all of the above sequences follow the general pattern:
(number)(command)(text object)
number is the optional numeric argument.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Options When Starting vi
In this handbook, you have invoked the vi editor with the command:
$ vi 
               file
            
There are other options to the vi command that can be helpful. You can open a file directly to a specific line number or pattern. You can also open a file in read-only mode. Another option recovers all changes to a file that you were editing when the system crashed.
When you begin editing an existing file, you can call the file in and then move to the first occurrence of a pattern or to a specific line number. You can also specify your first movement by search or by line number right on the command line:
$ vi +n file
Opens file at line number n.
$ vi + file
Opens file at last line.
$ vi +/pattern file
Opens file at the first occurrence of pattern.
In the file practice, to open the file and advance directly to the line containing the word Screen, enter:
KeystrokesResults
vi +/Screen practice
Give the vi command with the option +/ pattern to go directly to the line containing Screen.
As you see in the example above, your search pattern will not necessarily be positioned at the top of the screen. If you include spaces in the pattern, you must enclose the whole pattern within single or double quotes:
+/"you make"
or escape the space with a backslash:
+/you\ make
In addition, if you want to use the general pattern-matching syntax described in Chapter 6, you may need to protect one or more special characters from interpretation by the shell with either single quotes or backslashes.
Using +/ pattern is helpful if you have to leave an editing session in the middle. You can mark your place by inserting a pattern such as ZZZ or HERE. Then when you return to the file, all you have to remember is
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Making Use of Buffers
You have seen that while you are editing, your last deletion (d or x) or yank (y) is saved in a buffer (a place in stored memory). You can access the contents of that buffer and put the saved text back in your file with the put command (p or P).
The last nine deletions are stored by vi in numbered buffers. You can access any of these numbered buffers to restore any (or all) of the last nine deletions. (Small deletions, of only parts of lines, are not saved in numbered buffers, however. These deletions can only be recovered by using the p or P command immediately after you've made the deletion.)
vi also allows you to place yanks (copied text) in buffers identified by letters. You can fill up to 26 (a-z) buffers with yanked text and restore that text with a put command at any time in your editing session.
Being able to delete large blocks of text at a single bound is all very well and good, but what if you mistakenly delete 53 lines that you need? There is a way to recover any of your past nine deletions, for they are saved in numbered buffers. The last delete is saved in buffer 1, the second-to-last in buffer 2, and so on.
To recover a deletion, type " (double quote), identify the buffered text by number, then give the put command. To recover your second-to-last deletion from buffer 2:
"2p
The deletion in buffer 2 is placed after the cursor.
If you're not sure which buffer contains the deletion you want to restore, you don't have to keep typing " n p over and over again. If you use the repeat command (.) with p after u, it automatically increments the buffer number. As a result, you can search through the numbered buffers as follows:
"1pu.u.u etc.
               
to put the contents of each succeeding buffer in the file one after the other. Each time you type u, the restored text is removed; when you type a dot (.), the contents of the next buffer is restored to your file. Keep typing u and . until you've recovered the text you're looking for.
You have seen that you must put (p or P) the contents of the unnamed buffer before you make any other edit, or the buffer will be overwritten. You can also use
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Marking Your Place
During a vi session, you can mark your place in the file with an invisible "bookmark," perform edits elsewhere, then return to your marked place. In command mode:
m x
Marks the current position with x (x can be any letter).
' x
(apostrophe) Moves the cursor to the first character of the line marked by x.
` x
(backquote) Moves the cursor to the character marked by x.
``
(backquotes) Returns to the exact position of the previous mark or context after a move.
''
(apostrophes) Returns to the beginning of the line of the previous mark or context.
Place markers are set only during the current vi session; they are not stored in the file.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Other Advanced Edits
There are other advanced edits that you can execute with vi, but to use them you must first learn a bit more about the ex editor by reading the next chapter.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Review of vi Buffer and Marking Commands
Table 4.2 summarizes the command-line options common to all versions of vi. Table 4.3 and Table 4.4 summarize the buffer and marking commands.
Table 4.2: Command-Line Options
OptionMeaning
+ n file