Полезная информация



TOC
BACK
FORWARD
HOME

UNIX Unleashed, Internet Edition

- 3 -

Text Editing with vi and Emacs

by Jeffrey A. Simon

A text editor is one of the most common and useful tools to be found in any computer system. It is a program that is used to create and modify text or other data-type objects, usually interactively by the user at a terminal. It is distinguished from a word processor or desktop publishing program in that a text editor is generally expected to produce plain ASCII text files that do not have embedded formatting information. The latter programs are intended to produce more complex documents that contain much more formatting information. For example, a typical word processor has a graphical user interface and is capable of producing "what-you-see-is-what-you-get" printed output.

Common uses of a text editor are to produce simple ASCII text files, program source code, e-mail, and so on. Therefore, text editors are often extended to provide features that assist with specific aspects of such tasks, such as the formatting of a specific programming language. For example, such extended modes exist for C++, Lisp, and HTML, to name only a few. Detailed examples of some of these features will be described later in this chapter.

This chapter will examine two of the most popular and widely used editors in the UNIX world, vi and Emacs. In addition to being useful tools, each of these editors has its own group of devoted users, ready to "sing praises" to the virtues of using their favorites. In any case, you can get a lot of work done with either of these tools.

Full-Screen Editors Versus Line Editors

A full-screen editor is one that displays on the user's terminal a view of all or a portion of the document he or she is working on. For example, on a 25-line display, the user sees a 24-line section of the document. When using an editor, you are not actually making edits to the file that is stored on the hard disk. What happens is that when the editor is commanded to begin working with a particular file, a working copy of that file is made. This working copy is often called the buffer. Adding, changing, and deleting of text ("editing") is done only within the buffer until the file is saved. You often hear the advice to "save your work." This advice is applicable to using a full-screen editor as well as any other computer work that uses a buffer in the same way.

You can think of the screen as a movable viewport into the buffer. This viewport is also often called a window. Editing actions take place at or relative to a specific point on the screen referred to as the cursor. The cursor is usually indicated on the screen by some sort of highlighting, such as a underscore or a solid block, which may or may not be blinking. Edits to the buffer are shown on the screen as soon as they are entered. This type of user-interface makes simple editing functions very convenient for the user.

In contrast, a line editor is one that does not attempt to show the appearance of a continuous section of the document being edited. It concentrates on editing one line at a time. Thus, its user interface is more primitive. The type of editing that you would naturally do in a full-screen editor becomes more cumbersome under such an arrangement.

However, you should not be misled into thinking that the primitive user interface of the line editor means that a line editor lacks power or that all line editors are obsolete. (A great many line editors are obsolete; the trick is in recognizing those that are not!)

There are certain very powerful editing functions that are most easily executed by using a line editor. As an example, if you had to reverse the order of the lines in a file, you could do that with eight keystrokes in vi! So it might be a good thing if there was an editor that could take advantage of the power of both the full-screen and line-oriented modes.

What Is vi?

vi (usually pronounced vee-eye) is a full-screen text editor that comes with nearly every UNIX system. Many versions of vi or very similar programs have been made for other operating systems. Such versions exist for Amiga, Atari, Macintosh, MS-DOS, OS/2, Windows 3.1/95/NT, and probably more.

The Relationship of vi and ex

vi is "closely" related to the line editor ex. (In fact, they are one and the same!) vi is the visual (or open) mode of ex. This means that you could start editing a file with the ex editor. At any time, you can invoke the visual mode of ex. Voile--you are in vi! From vi you can at any time "drop down into ex" because all ex commands are available from within vi. Thus you can easily go back and forth between the visual and line-oriented modes, executing the particular editing operation you need from the mode in which it is most effectively accomplished. Later on in this chapter, you will see examples of such operations.

Why Would I Be Interested in Using vi?

Many computer users are familiar with the powerful word processing programs available widely on personal computers. If you are used to such a tool, you may be disappointed to find out the vi is not a "what-you-see-is-what-you-get" or WYSIWYG (pronounced wissy-wig) word processor. However, it is rare that such a word processing program is available on the typical UNIX system. vi on the other hand is nearly always available. One of the strongest reasons for knowing at least the rudiments of vi is the fact that it is nearly always available on any UNIX system. It becomes particularly invaluable to those who have to periodically go into a UNIX environment away from their everyday system.

While the lack of a graphical user interface might be a hindrance to the novice, many "power users" believe that the fastest and most productive interaction with online tools is through command-based interfaces. This is also true of vi. Once the keystrokes of the commands become second nature, the productivity of a vi user is not easily surpassed. In fact, the apprehension of the uninitiated toward command-based interfaces is probably due to the following common misconception: People think they have to memorized an obtuse, counter-intuitive set of command keys when, in fact, it is more a matter of finger training than memorization.

For example, suppose you want to move the cursor (the point where actions on the text take place) down one line. After learning to use vi and becoming comfortable with it, there is no mental process (such as "Move down--let's see that's a "j"). Rather it is a physical motion (such as "Move down--finger motion to press the "j" key). Think of it as like learning to drive a car. After having mastered the process, if you see a ball bouncing into the road ahead, you do not have a mental process (such as "Ball--child--STOP!--Let's see, which pedal is it? Where's the instruction manual?!). Rather, your body reacts instantly to press the brake pedal. It is the same way with a command-based interface. After you learn it, it is your fingers that effectively execute the command.

Starting Up and Exiting vi

The first thing to learn with any new program is how to start it and how to get out of it! The simplest way to start vi is to type its name along with the name of the file you wish to edit. If no name is specified, vi responds with an empty screen, except for a column of tildes along the left side. Your screen looks similar to the following:

~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
Empty buffer

At the bottom of the screen there may be nothing at all (yet another example of the terseness of UNIX!), or "Empty buffer," depending upon your version of vi. The tildes (which is the name of the "squiggly-line" character) indicate that the line is empty. There are as many tildes as needed to fill your monitor's screen, leaving one line at the bottom which is used to display status information (as shown in the previous example), or to enter commands. In this chapter, the line at the bottom of the screen will be referred to as the command line.

If you entered a file name, the first lines of that file are displayed until the screen is full. If there are not enough lines to fill the screen, once again, tildes are displayed on the empty lines. In addition, the name of the file and the number of lines are displayed at the bottom of the screen. For example, your screen may look like the following example of a vi screen after loading a text file. (The reader may recognize this text as taken from Sun Tzu, The Art of War.)

    If wise, a commander is able to recognize changing circumstances and to
act expediently.  If sincere, his men will have no doubt of the certainty of
rewards and punishments.  If humane, he loves mankind, sympathizes with others,
and appreciates their industry and toil.  If courageous, he gains victory by
seizing opportunity without hesitation.  If strict, his troops are disciplined
because they are in awe of him and are afraid of punishment.
    Shen Pao-hsu ... said: 'If a general is not courageous he will be unable
to conquer doubts or to create great plans.'
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
"art1"  8 lines, 576 characters

The second most important thing to know about operating a program is how to get out of it! There are several useful ways to get out of vi, depending upon what you want to do with your buffer. All of them must be executed from command mode (described later in this chapter), so to be sure you are in command mode, press the Esc (for Escape) key until you hear a beep before trying the following commands while you are learning.

Entering the command ZZ will save your file and exit. The other ways of exiting involve ex mode commands. To enter ex mode, enter the colon character ":". The screen display will change so that a colon is displayed on the bottom line of the screen and the cursor will be positioned immediately to the right of this colon, waiting for your command.

The q key will "quit" the file, if no changes have been made since the last save of the file. If a change has been made, you will be prevented from exiting and the following warning will be displayed: No write since last change (use ! to override). The command wq can be used to handle this situation, by writing the file before exiting. Or you can go ahead and use the q! as the message indicates, to go ahead and quit anyway, abandoning all of your edits since the last save of the file. (It's good to keep in mind the :q! command for those cases in which you have truly messed up and want to get rid of your mess!)

Table 3.1 summarizes the exiting commands presented so far.

Table 3.1. Exiting commands.

Keystrokes Result
ZZ Save file and immediately exit
:wq Save file and immediately exit (same as ZZ)
:q Exit; prevented if file not saved
:q! Exit; forced exit whether saved or not

Getting Started: The Big Picture

Let's look at some of the pieces of the big picture that give vi its character.

vi Has Modes

vi was created back when the keyboard and screen method of interaction with computers was new. In those primitive days, keyboards did not have all of the useful function keys that are now familiar. Therefore, vi was designed to allow you to enter and modify text using only the typewriter keys plus the escape key. (Nowadays other key sequences are sometimes recognized, such as the cursor control keys.)

Although it may seem like a limitation to not take advantage of the many additional keys available on the modern keyboard, the "silver lining" of this limitation is that all functions can be executed without taking your hands away from the touch-typing position. The result makes for efficient and rapid typing.

To enable the many editing functions necessary for interactive, full-screen editing, vi is operated in three modes. The insert mode is used for entering text. While in insert mode, every typewriter key pressed is displayed on the screen and entered into your text. The command mode is used for most editing functions. While in command mode, nearly every typewriter key pressed will cause some action other than the direct entry of text, such as moving around to different points in your text, deleting blocks of text, copying blocks of text, and so on. A third mode, called ex mode is used to execute additional functions, such as searching, global replacement, manipulation of multiple file, and many more. The ex mode is based on the underlying ex editor and will be described in greater detail later in the section "Using the Power of ex from vi."

Starting vi

When vi is started up, the default mode is command mode. Test this out: start vi by typing in the program name only:

$ vi

You will see something similar to the following:

~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
Empty buffer

i--Insert

Now press the "i" key to enter insert mode. The "i" character will not echo (that is, it will not be displayed on your screen). Thereafter, every key you press will be displayed as it is entered into the buffer. Now begin to enter some text. Let's assume you are entering some text from The Art of War by Sun Tzu, and that the passage you have selected results in your screen looking as follows. Note that the cursor position is indicated in the example by an underscore under the period at the very end of the passage:

    If wise, a commander is able to recognize changing circumstances and to
act expediently.  If sincere, his men will have no doubt of the certainty of
rewards and punishments.  If humane, he loves mankind, sympathizes with others,
and appreciates their industry and toil.  If courageous, he gains victory by
seizing opportunity without hesitation.  If strict, his troops are disciplined
because they are in awe of him and are afraid of punishment.
    Shen Pao-hsu ... said: 'If a general is not courageous he will be unable
to conquer doubts or to create great plans.'
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~

Esc--Cancel

When you have entered enough, press the Esc key to return to command mode. (If you are already in command mode when you press Esc, you will hear a beep.) The Esc key is used to cancel an incomplete command as well as to terminate any type of insert mode. After pressing Esc, the cursor backs up over the last character you typed. Leave it there for now.

Unfortunately, there is no readily visible indication of which mode you are in. However, it is pretty easy to see what mode you are in. If the keystrokes go into the text, you are in insert mode; if your screen jumps around wildly, beeps, and all kinds of weird things are happening, either you are asleep and having a vi nightmare, or you are most definitely in command mode. If you are unsure of what mode you are in, just press Esc twice to get the beep confirming that you are in command mode. (Be sure to pinch yourself first to make sure you are awake!)

Moving Around and Simple Editing

It's time to look at the most basic movement commands, the ones that you must train your fingers to execute automatically.

The Most Important Movement Keys

Editing commands in vi are composed of objects and commands. Objects are used by themselves to move around, or "navigate," in the buffer. A single object keystroke either causes the cursor position to move on the screen, or to reposition the "viewport" in the buffer. Let's see how the various movement commands affect the cursor position in our sample text.

hh--Cursor Left

First, move the cursor back five positions by pressing the h key five times (if you see five h's go into the text, you forgot to press the Esc key). The cursor should now be under the "p" of "plans" (see the following example):

    If wise, a commander is able to recognize changing circumstances and to
act expediently.  If sincere, his men will have no doubt of the certainty of
rewards and punishments.  If humane, he loves mankind, sympathizes with others,
and appreciates their industry and toil.  If courageous, he gains victory by
seizing opportunity without hesitation.  If strict, his troops are disciplined
because they are in awe of him and are afraid of punishment.
    Shen Pao-hsu ... said: 'If a general is not courageous he will be unable
to conquer doubts or to create great plans.'
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~

kk--Cursor Up

Now let's move the cursor up five lines using the k key. As you might expect, there is a shortcut for pressing the key five times. And you would be right. Just prefix the object (or action) portion of the command with a number. Instead of pressing the k key five times, you would have the same result by typing 5k. Try this now. The cursor should now be under the "e" of "he" (see the following example):

    If wise, a commander is able to recognize changing circumstances and to
act expediently.  If sincere, his men will have no doubt of the certainty of
rewards and punishments.  If humane, he loves mankind, sympathizes with others,
and appreciates their industry and toil.  If courageous, he gains victory by
seizing opportunity without hesitation.  If strict, his troops are disciplined
because they are in awe of him and are afraid of punishment.
    Shen Pao-hsu ... said: 'If a general is not courageous he will be unable
to conquer doubts or to create great plans.'
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~

There is a limit to the effect of the object you can use. For example, if the h or l keys are used with an object that would go beyond either the beginning or the end of the line the cursor is on, the cursor stays at the beginning or end of the line and the beep will sound.

There are other commands that work like the h and k keys. Their functions are described in Table 3.2. The best way to get used to how they work is to practice using them. The most frequently used movement keys are as shown in Table 3.2.

Table 3.2. Frequently used movement keys.

Keystroke(s) Moves
h one character left
j one line down
k one line up
l one character right
w, W one word forward (W ignores punctuation)
b, B one word backward (B ignores punctuation)
$ to end of line
^ to first non-space character of line
0 to beginning of line
G to top of buffer
nG where n is a whole number, to line n

The upper- and lowercase versions of the word movement commands have a subtle difference. The lowercase version counts most punctuation marks as "words." The uppercase version skips over them as if they were not present.

You should practice moving around in your sample text, using the previously described commands. Although they may seem awkward at first, you will soon get used to them as your fingers are trained.

The Most Important Editing Procedures

Let's look at some of the simplest and most often used editing procedures:

Changing Text Nobody's perfect. So you will sooner or later want to change some text that you have created. In fact, more text editing time is probably spent modifying existing text than in entering brand new text. So you will need some easy ways of changing text. This section shows how.

x--Delete Character The simplest way to delete text is with the x command. This command causes the character that the cursor is over to be deleted, and the remaining characters on the line to be shifted one character to the left. You can think of "x-ing" out the text you want to get rid of. If the character deleted is the last one on the line, the cursor moves one character to the left, so as not to be over non-existent text. If there is no more text on the line, the beep will sound.

d--Delete Object The delete command requires a text object on which to operate. A text object, or object for short, is the block of text that would be traversed by the use of a movement command. For example, w will advance to the next word. So dw will delete to the beginning of the next word. 5w will advance to the beginning of the fifth word (remember, punctuation symbols count as "words" to the w command). So 5dw (or alternatively d5w) will delete to the beginning of the fifth word. Both forms work because 5dw mean "do five delete-words;" d5w means "do delete five words."

dd--Line Delete One of the most often used forms of the d command is the special version, dd, which will delete an entire line. As before, 5dd would delete five lines.

D--Big Delete The uppercase form D is used to delete from the cursor position to the end of the line. It has the same action as d$.

u--Undo After learning how to do deletes, the first thing I want to know is whether there is an undo function! There is. It is invoked naturally by the u command. The u command will undo the most recent change to the file (not only deletes, but any edits). The cursor does not need to be at the location of that most recent change. Unfortunately, standard vi has only one level of undo. Once a second change is made, you cannot undo the first. If you press u a second time, it will "undo the undo," which is sometimes known as "redo." Repeated presses of the u key will toggle the text back and forth between the two versions.

U--Big Undo The "big brother" of the u command, the U command will undo all changes made to the line that the cursor is on, since the cursor was last moved on to that line. After the cursor is moved off of a line, the U command will no longer work on the edits that have already been made to that line.

.--Repeat Repeats the last editing command.

How Commands Are Formed By now you have probably noticed that there is a pattern to the structure of the vi commands. Firstly, the commands are (somewhat) mnemonic, which means that the letter of the command should remind you of the function being executed. Secondly, many commands have an uppercase version, which are usually a modified form the basic, lowercase form. Thirdly, all commands can be multiplied by a repeat count, entered as a prefix.

The easiest ways to see how the commands are formed is shown in Table 3.3. You can see that there are several ways of combining command elements to get the result you want. To repeat a command, just enter the repeat count prior to the command itself, as in the previous examples of cursor motion and deletion.

Table 3.3. How vi commands are formed.

General Form of vi Commands
{count}{command}{object} All parts are optional (see the following).
The {count}, if present, causes the command to be executed count number of times.
The {command}, if present, causes some action to take place. If absent, the cursor is moved according to the object.
The {object} is used together with the command to indicate what portion of the text is to be affected.
Specific Forms of vi Commands
{count} Position the cursor count lines down, if terminated with return or +; position the cursor count line up if terminated with -.
{command} Execute the command.
{object} Move the cursor over the indicated block.
{count}{command} Execute the command count times.
{count}{object} Move the cursor over count indicated blocks.
{command}{object} Execute the command over the indicated block.

Some examples of combining some of the commands that you already know are shown in Table 3.4.

Table 3.4. Examples of combining commands.

Command Result
h Move cursor left one character
3h Move cursor left three characters
dd Delete one line
3dd Delete three lines
w Move cursor forward one word
dw Delete one word
3dw Delete three words

You now have the basic editing commands that will enable you to get started. You might wish to start practicing right away with these few commands. With these commands you would be able to do any text editing project. But you wouldn't want to. By adding some additional commands, you can make your work much faster and easier. The whole point of computers is to make work easier, so why not use the power of vi to have the computer do what it is good at!

Other Useful Editing Commands a--Append The a command is used to append text. It is almost identical to the i command. The slight difference is that the i command inserts text at the cursor position; the a command appends text immediately after the cursor position. To illustrate the difference, we will use both commands to insert the phrase "is able to" into the sample text. For example, suppose your screen looks like the following example, with the cursor at the "r" of "recognize" (we want to insert the missing phrase "is able to" between the words "commander" and "recognize" ):

If wise, a commander recognize changing
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~

Type the following to use the i command to insert text:

iis able to Esc

(There is a blank between the word "to" and the Esc key.) Your screen should look like this after inserting "is able to":

    If wise, a commander is able to_recognize changing
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~

Now restore the text to the way it was by executing an undo command. Press the u key. (If a "u" is inserted into your text, you forgot to press Esc after the first insert.) Now before trying the a command, move the cursor back one character with the h key. Your screen should now look like the following:

     If wise, a commander_recognize changing
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~

Type the following:

ais able to Esc

As you can see, the action of the i and a commands differ by where the insertion begins.

A--Big Append Like the a command, but begins the append at the end of the line.

TIP: You can insert a repeated string sequence by using one of the insert or append commands with a repeat count. For example, to insert 78 asterisk characters you could type 78i*Esc.

c--Change Object To change text, you can use the c command. The c command takes an object to indicate the block of text that will be changed. The c command works like the d command followed by the i command. That is, it first performs the deletion that would be performed by the d command with the same object, then allows the insert of any amount of text (including line feeds) until the Esc key is pressed. This behavior makes it especially useful in such situations where you want to change the text from the position of the cursor to the beginning of the line (using c0) or to the end of the line (using c$).

cc--Change Line In a similar vein, the cc command works like the dd command followed by an i command. It deletes the line the cursor is on and then inserts all keystrokes typed until the Esc key is pressed.

C--Big Change The C command works like the D command followed by the i command; it deletes the text from the cursor position to the end of the line; then enters insert mode. The C command has the same action as c$.

r--Replace Character The r command will replace the single character where the cursor is placed. After the r key is pressed, no change is seen on the screen. The next key typed will replace the character at the cursor position, and then vi returns to command mode. It is a simple way to change just one character.

When used with a numeric count, the same replacement occurs over count characters. For example, suppose the screen looks like the following, with the cursor under the "c" of "commander":

If wise, a commander recognize changing
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~

Now suppose you type 4rx. The screen will now look like the following, and vi will be in command mode. Note that the cursor has moved to the end of the replaced text:

     If wise, a xxxxander is able to recognize changing
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~

R--Big Replace The uppercase version of the r command differs from the r command by the same pattern that the uppercase version of the d command and the c command differ from their lowercase versions. The R command allows the replacement of the text from the cursor position to the end of the line. Any text entered after typing R until the Esc key is pressed will overlay the existing text on the screen, up to the end of the line. Thereafter, text entered will be appended to the end of the line.

When used with a numeric count, the same replacement occurs count times. This use of the R command may not produce what you are expecting.

o--Open Line The o command opens up a new line below the line the cursor is on and goes into insert mode.

O--Big Open Line The O command opens up a new line above the line the cursor is on and goes into insert mode.

A Copy Is a "Yank" Many text editors have features known as "cut and paste" or "copy and paste." vi calls the copy part of "copy and paste" a yank. You can use the yank command to save any block of text in the undo buffer. The undo buffer is a special place that vi keeps internally. You can't directly see the contents of this buffer. The contents of this buffer can be put into the text with the p command (see the following).

Each use of the y command overwrites the contents of the undo buffer, as does any delete command. There is a more advanced version of the yank command explained in the section "How To Use Buffers," which can be used to save text in multiple named buffers.

y--Yank The yank command works with an object in the same way as the c and d commands. You can yank a word with yw, yank to the end of the line with y$, yank three lines with 3yy.

Y--Big Yank There is an exception to the pattern however. For some reason, the Y command does not take its action to the end of the line as C and D do. Instead, it yanks the whole line, and is therefore identical to yy.

Copying Text The commands discussed in the following sections are used to copy text.

p--Put The p command takes whatever is in the undo buffer and inserts it into the text after the cursor position.

P--Big Put The P command takes whatever is in the undo buffer and inserts it into the text before the cursor position.

Moving Text In addition to text that you specifically yank being placed in the undo buffer, each portion of text that is deleted goes into the same undo buffer, replacing the previous contents each time. So to perform a cut and paste you would use any delete function, then move the cursor to the desired insertion point, then use one of the put commands to insert the text. You will have to pay attention to the location of the cursor and whether to use the p or P commands to get exactly what you want.

For example, suppose your screen appears as shown in the following example:

    If wise, a commander is able to recognize changing circumstances and to
act expediently.  If sincere, his men will have no doubt of the certainty of
rewards and punishments.  If humane, he loves mankind, sympathizes with others,
and appreciates their industry and toil.  If courageous, he gains victory by
seizing opportunity without hesitation.  If strict, his troops are disciplined
because they are in awe of him and are afraid of punishment.
    Shen Pao-hsu ... said: 'If a general is not courageous he will be unable
to conquer doubts or to create great plans.'
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~

Now suppose you wish you change the order of the paragraphs so that the paragraph beginning with "Shen Pao-hsu" comes first. First, move the cursor on to any character in the first line of the "Shen Pao-hsu" paragraph, as shown here:

    If wise, a commander is able to recognize changing circumstances and to
act expediently.  If sincere, his men will have no doubt of the certainty of
rewards and punishments.  If humane, he loves mankind, sympathizes with others,
and appreciates their industry and toil.  If courageous, he gains victory by
seizing opportunity without hesitation.  If strict, his troops are disciplined
because they are in awe of him and are afraid of punishment.
    Shen Pao-hsu ... said: 'If a general is not courageous he will be unable
to conquer doubts or to create great plans.'
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~

Then press 2dd to delete the second paragraph. Your screen will appear as in the following example:

    If wise, a commander is able to recognize changing circumstances and to
act expediently.  If sincere, his men will have no doubt of the certainty of
rewards and punishments.  If humane, he loves mankind, sympathizes with others,
and appreciates their industry and toil.  If courageous, he gains victory by
seizing opportunity without hesitation.  If strict, his troops are disciplined
because they are in awe of him and are afraid of punishment. ~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~

Now move the cursor to any character on the top line, as shown here:

    If wise, a commander is able to recognize changing circumstances and to
act expediently.  If sincere, his men will have no doubt of the certainty of
rewards and punishments.  If humane, he loves mankind, sympathizes with others,
and appreciates their industry and toil.  If courageous, he gains victory by
seizing opportunity without hesitation.  If strict, his troops are disciplined
because they are in awe of him and are afraid of punishment.
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~

Now use the p command to put the text. Oops! Your screen looks like this:

    If wise, a commander is able to recognize changing circumstances and to
    Shen Pao-hsu ... said: 'If a general is not courageous he will be unable to
act expediently.  If sincere, his men will have no doubt of the certainty of
rewards and punishments.  If humane, he loves mankind, sympathizes with others,
and appreciates their industry and toil.  If courageous, he gains victory by
seizing opportunity without hesitation.  If strict, his troops are disciplined
because they are in awe of him and are afraid of punishment. ~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~

This is not what we intended! To fix it, first press u to undo; then press P to put before the cursor. After a little practice, you will get used to easily accomplishing what you want to do.

You probably noticed during this exercise that you were able to use the put command repeatedly to put the same text. You are able to do this because the put command does not change the contents of the undo buffer. This feature sometimes comes in quite handy.

Searching for Patterns /, //, ?, ??, n, and N--Search One of the more useful ways of moving around in your text is to search for a pattern. You might be editing a long source code file, and want to go back to a routine that you remember contains a specific instruction. You can do this by using /, the forward search command, or ?, the backward search command. As soon as you type the slash or question mark while in command mode, the cursor moves to the command line. You then type the pattern that you wish to find. This pattern can be a literal text string, which is the exact character sequence you wish to find. Or it can be a regular expression, described in detail in the "Regular Expressions" section.

After pressing the Return key, the text is repositioned so that the line containing the first occurrence of the pattern is displayed approximately in the center of the screen (assuming there is enough surrounding text to permit this) and the cursor is positioned to the first character of the matched text. If the pattern is not found, the message "Pattern not found: pattern" is displayed on the command line.

You use the / command to search forward in the text (that is, from where the cursor is positioned to the end of the buffer). You use the ? command to search backward in the text (that is, from where the cursor is positioned to the top of the buffer). You can repeat either forward or backward searches without reentering the pattern by using the two search again commands (/ and ? without any search text--// and ?? also work). You must also enter the Return key after these search again commands. Once a pattern has been entered, you can intermix the forward and backward search commands.

Another variation on repeating search commands is to use the n command, which repeats the previous search in the same direction, whether forward or backward. The N command repeats the previous search in the opposite direction.

vi searches "wrap around" the top and bottom of the buffer. When searching for the pattern, if vi hits one end of the buffer, a message will display on the command line notifying you of this fact. For example, the message "search hit BOTTOM, continuing at TOP" may appear. At this point, you may press Return the continue the search. (This behavior can be changed; please refer to the "For the Power User: Customizing vi" section to see how you can use special settings to change vi's default behavior.)

How To Use Buffers

The undo buffer contains only the most recent yanked or deleted text. This means that if you were intending to yank some text and copy it in somewhere, but before you put the text you performed any other deletion, you would be disappointed with the result. In order to keep various text snippets available for putting you will have to use named buffers.

Named Buffers Named buffers allow you to keep up to 26 separate places where text can be deleted or yanked. Using the named buffers allows you to overcome the problem of intermediate deletes replacing the text that you have yanked or deleted. The contents of a named buffer remains unchanged until the end of your vi session, unless you use commands to deliberately change it.

Buffers are named by using a " followed by a lowercase letter. So the buffers are named from "a to "z. To yank or delete into a named buffer, prefix the yank or delete command with the name. For example, to yank two lines from the cursor position into buffer z, you would use the following keystrokes: "z2yy. To put from the named buffers, the key sequence is the buffer name followed by the p command. Table 3.5 following shows some examples of using named buffers (some object commands have not been introduced yet; I hope this will whet your appetite for more, rather than confuse you):

Table 3.5. Examples of using named buffers.

Keystrokes Result
"a2dw Delete next two words into named buffer a
"jD Delete from cursor to end of line into named buffer j
"jp Put the contents of named buffer j after the cursor
"by) Yank from cursor position to end of sentence into named buffer b

As with a normal yank into the regular (unnamed) undo buffer, the action of the yank or delete into the named buffer will replace the previous contents of that buffer. If, instead, you want to collect text in a named buffer by appending it to what is already there, you may do this by uppercasing the letter of the buffer's name. Yanks and deletes can be intermixed when using the appending method, as shown in the sequence in Table 3.6.

Table 3.6. Intermixed sequence of yanks and a delete.

Keystrokes Result
"a2yy Yank two lines into named buffer a, discarding the previous contents
"Ad4w Delete the next four words, and append them into buffer a
"Ay) Yank from the cursor to the end of the sentence, and append into buffer a


Caution: You will have to be careful in executing such a sequence not to forget to use the capital letter. If you forget, the previous contents are obliterated and your careful work is lost. For this reason, I seldom use this technique, and when I do use it, I do carefully!

Delete Buffers In addition to the named buffers, vi provides numbered delete buffers. A normal undo can only undo the last delete and only if it was the last edit. However, vi saves the most recent nine deletes in buffers numbered from 1 to 9. The most recent delete is kept in buffer 1, the next most recent in buffer 2, and so on. To recover the contents of one of these buffers, use the number as the buffer name with the p command, as in "2p to put from the second delete buffer.


Tip: How do you know what is in each of the delete buffers? A special feature of the . (repeat) command (described later in the "Recovering Deleted Text: Cutting and Pasting" section) allows you to easily choose from among the numbered buffers. When the repeat command is used after a command referencing a numbered buffer, the buffer number is incremented.
Thus you can put from numbered buffer 1, see the text that is inserted, use the u command to undo the put, then just press . (the repeat command) to see the next buffer's contents. Continuing this process with a series of u commands and . (repeat) commands will quickly scan through the nine most recent deletions. (When you get to the ninth one, continued key presses "stick" on the ninth buffers contents.) This is another technique that is a lot easier to do than to describe.

The Complete Guide to Movement and Editing: Command Reference Tables

By this point you have seen the most commonly used vi commands. However, there are many useful and powerful movement and editing commands that, while less frequently used, might become invaluable to you as you learn to use them. Some of them are likely to be included in your repertoire of often-used commands, sooner or later. This section is intended to provide complete coverage of the movement, editing, and other commands, for easy reference.

Note that some commands are shifted commands. Commands represented by uppercase letters are entered by holding down the Shift key while the alphabetic letter is pressed. So called control-key commands are entered in a similar fashion, with the Control key held down while the other key is pressed. Control-key commands are indicated in the vi sections by prefixing the command with a caret symbol (^), or alternately by the sequence Ctrl-key. So for example, when you see in the text the symbol ^A, this means you are to hold down the Ctrl key while you press the letter a. (Later, when discussing Emacs, I will adopt the standard Emacs way of indicating control keys--do not let this confuse you!)

Be aware that all of the commands shown in the table can be combined in the ways described in Table 3.3. That is, you can amplify the effect of commands by using a count or an object or both, as appropriate.

Some of the commands included here have not been introduced yet. They will be explained in detail in the advanced editing section.

Movement In Table 3.7 the following words in the command column have the specified meaning: char means any character; number (or nbr) is a whole number; pattern is a string of characters or a regular expression.

In the description column, a small word is a word that can be either a string of alphanumeric characters (plus the underscore) or a string of punctuation characters, delimited by white space (spaces, tabs, and line feeds); a big word is a sequence of non-blank characters. What these precise but technical definitions are saying, in effect, that small words consider the punctuation to be separate "words;" big words include the punctuation as part of the word. The easiest way to see the difference is first to try a repeated sequence of moves using the lowercase version of a command; then try the uppercase version of the command.

Table 3.7. Movement commands.

Single Character Cursor Motion
Command Result
h one character left
^H left-arrow
j one line down
^J down-arrow
^N one line up
k up-arrow
^P one character right
l right-arrow
Movement Within a Line
Command Result
^ first non-space character on the line
0 beginning of the line
$ end of line
fchar to next occurrence of character char
Fchar to previous occurrence of character char
tchar to character before next occurrence of character char
Tchar to character after previous occurrence of character char
; repeats previous f, F, t, or T command; same direction
, repeats previous f, F, t, or T command; opposite direction
Motion To a Specified Line
Command Result
Enter to next line
+ to next line (usually used with preceding count)
- to previous line (usually used with preceding count)
numberG to line number
number| to column number
Screen Positioning
Command Result
H to top line displayed on screen
L to bottom line displayed on screen
M to middle line displayed on screen
^D scroll down one-half screen
number^D scroll down number lines
^U scroll up one-half screen
number^U scroll up number lines
^F scroll forward one screen
^B scroll backward one screen
^E scroll down one line
^Y scroll up one line
Lexical Object Positioning
Command Result
w forward one small word
W forward one big word
b backward one small word
B backward on big word
e to end of next small word
E to end of n