Ch 3 -- Text Editing with vi and Emacs
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 next big word |
( |
to beginning of previous sentence |
) |
to beginning of next sentence |
{ |
to beginning of previous paragraph |
{ |
to beginning of next paragraph |
[[ |
to beginning of next section |
]] |
to beginning of previous section |
Screen Redrawing |
Command |
Result |
z |
redraws screen with current line at top of the screen |
z- |
redraws screen with current line at bottom of the screen |
z. |
redraws screen with current line at center of the screen |
Positioning by Pattern Searching |
Command |
Result |
/pattern |
moves to next line containing pattern |
?pattern |
moves to previous line containing pattern |
/ |
repeats last search forward |
? |
repeats last search backward |
n |
repeats last search in same direction |
N |
repeats last search in opposite direction |
/pattern/+nbr |
to nbr lines after next line containing pattern |
?pattern?-nbr |
to nbr lines before previous line containing pattern |
/pattern/z- |
redraws screen with next line containing pattern at bottom of the
screen (other z options will give the corresponding positioning) |
% |
to parenthesis or brace matching the one at the current cursor position |
Positioning to Marked Text Locations |
Command |
Result |
mchar |
marks the current cursor position with the letter char |
'char |
to mark specified by char |
'char |
to beginning of line containing mark specified by char |
'' |
to previous location of the current line (after a cursor movement) |
'' |
to beginning of line containing previous location of current line (after a cursor
movement) |
Editing In Table 3.8 the words in the command column have the specified
meaning: object means an object command from Table 3.7; letter means
one of the 26 alphabetic characters from a to z. All editing commands can take nearly
any movement command as an object. The text insertion commands cause entry into insert
mode; vi then stays in that mode until you press the Esc key.
Table 3.8. Editing commands.
Inserting Text |
Command |
Result |
i |
inserts text before the cursor |
I |
inserts text before first non-blank character of line |
a |
inserts text after the cursor |
A |
inserts text at the end of the line |
o |
adds an empty line below the current line and enters insert mode there |
O |
adds an empty line above the current line and enters insert mode there
(Note: These commands are only available while in insert mode.) |
Changing Text While in Insert Mode |
Command |
Result |
^H |
backspaces and erases the previous character (only since insert began) |
^W |
backspaces over and erases the previous small word (only since insert began) |
|
quotes the erase and kill characters |
Esc |
ends insert mode and go back to command mode |
^D |
back to previous auto-indent stop |
^^D |
(caret followed by Ctrl-D) no auto-indent on current line only |
0^D |
moves cursor back to left margin |
^V |
enters any character into text (do not interpret control characters) |
Changing Text |
Command |
Result |
cobject |
changes the text object to the text inserted until the Esc key is pressed |
C |
changes the rest of the line to the text insert until the Esc key is pressed (same
as c$) |
cc |
changes the whole line to the text inserted until the Esc key is pressed |
rchar |
replaces the character the cursor is on with char; then return to command
mode |
R |
overwrites text until the Esc key is pressed; if you go past the end of the line,
append new text to the end of the line |
s |
substitutes characters (same as cl) |
S |
substitutes lines (same as cc) |
Deleting Text |
Command |
Result |
x |
deletes the character under the cursor |
X |
deletes the character before the cursor |
dobject |
deletes the text object |
D |
deletes the reset of the line (same as d$) |
dd |
deletes the line |
Using Buffers |
Command |
Result |
u |
undo the last change |
U |
restores the current line to the state it was in when the cursor was last positioned
to it |
yobject |
places the text of the object into the undo buffer |
yy |
places the line the cursor is on into the undo buffer |
Y |
places the line the cursor is on into the undo buffer (same as yy, which
is a departure from the pattern set up by C and D) |
p |
inserts the text in the undo buffer after the cursor |
P |
inserts the text in the undo buffer before the cursor |
"letterdobject |
deletes the object into the letter buffer |
"letteryobject |
yanks (copies) the object into the letter buffer |
"letterp |
inserts the text in the letter buffer after the cursor |
"numberp |
inserts the number-th last delete of a complete line or block of lines |
Other Editing Commands |
Command |
Result |
. |
repeats the last editing command (and increments n in a "np command) |
~ |
changes the case of the letter under the cursor and moves cursor to left one character
(does not support a count in standard vi) |
J |
joins two lines |
>> |
shifts line shiftwidth characters to the right (use :set sw to change
the shiftwidth) |
>L |
shifts all lines from the line the cursor is on to the end of the screen shiftwidth
characters to the right (use :set sw to change the shiftwidth) |
<< |
shifts line shiftwidth characters to the left (use :set sw to change
the shiftwidth) |
<L |
shifts all lines from the line the cursor is on to the end of the screen shiftwidth
characters to the left (use :set sw to change the shiftwidth) |
Other vi Commands In Table 3.9, commands that start with :
(colon) are ex commands. If these are being executed from within the ex
editor, you do not need the colon. When the ! modifier is included with
a command, some form of override will be performed. Not all combinations that include
the ! are shown.
In the command column, the following words have the specified meaning: file
means the name of a disk file; number or nbr means a positive whole
number; command or cmd means a UNIX shell command; tag means
a function identifier created using the ctags program; addr means an
ex line address (defined in the "Using the Power of ex from
vi" section following).
Table 3.9. Other vi commands.
Saving the Buffer to a File |
Command |
Result |
:w |
writes (saves) the buffer to disk, using the original file name |
:w file |
writes the buffer to disk, to file |
:w! |
writes the buffer to disk, overwriting file |
Exiting Commands |
Command |
Result |
ZZ |
writes the buffer to disk and exits the program |
Q |
enters the ex editor (same as typing :) |
:q |
quit vi, unless you have an unsaved buffer |
:q! |
always quits vi, overriding warning about an unsaved buffer |
:wq |
writes the buffer to disk and exits the program (same as ZZ) |
Editing Other Files |
Command |
Result |
:e file |
edits file, unless you have an unsaved buffer |
:e! |
discards any changes and starts over with the last saved version of the file from
disk |
:e + file |
edits file, unless you have an unsaved buffer; places cursor bottom line |
:e +nbr file |
edits file, unless you have an unsaved buffer; places cursor on line nbr |
:e # |
edits alternate file |
:n |
edits the next file (applies when a list of files was entered on the command line) |
:n file file file |
sets up a new list of files to edit |
:r file |
reads (inserts) contents of file into the buffer on the line below the cursor |
:r !command |
runs the shell command and inserts the output of the command on the line below
the cursor |
^G |
displays information about the current file (filename, current line number, number
of lines in file, percentage through the file) |
:ta tag |
jumps to the file and the location in the file specified by tag (before you
can use this function, you must use the ctags program to create the tags
file. Refer to the section on the :ta command for details.) |
Redrawing the Screen |
Command |
Result |
^L |
redraws the screen (implementation depends upon terminal type) |
^R |
redraws the screen; eliminates blank lines marked with @ (implementation depends
upon terminal type) |
znumber |
sets screen window to number lines |
UNIX Shell Commands |
Command |
Result |
:sh |
executes a shell; remain in shell until shell exit command given (^D) |
:!command |
executes the shell command and returns to vi (after the !
command, certain special characters are expanded. # is expanded to the alternate
file name; % is expanded to the current file name; ! is expanded to
the previous shell command) |
:!! |
repeat the previous shell command |
!object cmd |
execute the shell cmd; replace the text object with the shell cmd
output. If the shell cmd takes standard input, the designated text object
is used. |
nbr!!cmd |
execute the shell cmd; replace nbr lines beginning at the current line
with the shell cmd output. If nbr is missing, 1 is assumed. If the
shell cmd takes standard input, the designated lines are used. |
ex Editing Commands |
Command |
Result |
:vi |
enters visual mode from the ex command line |
:addrd |
delete the lines specified by addr |
:addrmnbr |
move the lines specified by addr after line nbr |
:addrconbr |
copy the lines specified by addr after line nbr |
:addrtnbr |
copy the lines specified by addr after line nbr (same as co
command) |
Advanced Editing: Tips and Techniques
You may be ready for the any of the topics included in this section at any time
while you are learning vi. Do not let the title of the section deter you
from browsing for features that interest you. While some vi commands are
less often used, the real power of the vi editor will not be fully yours
until you are comfortable with at least some of these features.
Using the Power of ex from vi
As mentioned in the section "Full-Screen Editors versus Line Editors,"
vi is actually the visual mode of the ex editor. As such, all of
the power and features of the ex editor are available at any time while
editing in vi, without leaving your place in the file. vi commands
that are actually ex commands are shown in the command reference tables
and elsewhere in this chapter prefixed with a : (colon). You can think of
this prefix in either of two ways: (1) as a prefix to a special vi command;
or, (2) the command that takes the editor into ex mode, at which time the
screen display changes so that a colon is displayed on the bottom line and the cursor
is placed immediately to the right of the colon. Thereafter, the editor will act
exactly the same as if you were in the ex editor, except that you will still
have the vi screen displayed on all lines but the bottom line. Certain commands
will return you to the vi mode; others will leave you in the ex
mode. To return explicitly to the vi mode, just enter the :vi command.
The real power of using ex commands from within vi is that certain
specific editing functions are provided in this way that are usually not available
in most text editors. (The power of such operations is approached by macro languages
included with PC-based word processing programs; however, the simplicity and elegance
of the ex commands are not.)
The types of operations that are available only from the ex command line
are using basic ex commands to manipulate blocks of text, search and replace
operations, global search and replace with regular expressions, and edit multiple
files.
Using Basic ex Commands to Manipulate Blocks
of Text
ex has its own versions of delete, copy, and move commands. Sometimes
these commands are preferable to the vi versions, particularly when you
want to manipulate the file as a whole. The main ex commands for these operations
will be covered here.
First, let's look at the general form of an ex command. An ex
command is composed of an object and an operation to perform on the lines in the
file that are selected by the object. The general form is
:object command Return
where Return means to press the Return key. All ex commands require
the Return key (which is labeled Enter on a PC keyboard) to be pressed. The spaces
shown in the preceding example can be used if desired for readability, but they are
not necessary.
Rather than using the vi concepts of a full-screen display with the cursor
position to indicate where actions will take place, ex has the concept of
a current line. This concept means that ex will take its action on or relative
to that line.
Both the object and command are optional. If the object is missing, the default
is to apply the command to the current line. If the command is missing, the default
is the ex print command, which displays the selected lines on the
screen. Spaces between the parts of the command are also optional. In the examples,
spaces are included to for clarity.
When using the ex editor from the command line (that is, you are not
running from within vi), ex responds to each command by displaying
the lines effected. In the examples that follow, the behavior of the ex
editor is shown with the assumption that you are using it from the command line,
rather than from within vi. You may wish to get a feel for the pure ex
mode of interaction by trying it from the command line. When operating from within
vi, the effect on the text you are editing is shown, just as if you executed
the equivalent vi command. The screen display is repositioned if necessary.
The ex editor can be entered from within vi to edit the file
you are currently editing by typing :. It can also be started from the command
line with the name of the file you wish to edit. If you start if from the command
line in this way, you may see the following on your screen (assuming you are editing
the same sample file that we have been using all along):
$ex art1
"art" 8 lines, 576 characters
:
Selecting Lines to Edit
Sets of lines may be selected in several ways. Because you already know that ex
is a line editor, it is not surprising that line addresses refer to lines in the
file without regard to content. The simplest way to address a line is with its number.
For example, to print line three of your file, you could enter the following command:
:3p
rewards and punishments. If humane, he loves mankind, sympathizes with others,
Another way to give an address is with a pattern search. A pattern search is indicated
by surrounding the exact character string you are looking for with forward slashes.
For example, to display on the screen the first line of your file containing the
word "general" you could enter the following command:
:/general/p
Shen Pao-hsu ... said: 'If a general is not courageous he will be unable
In both of these last two examples, you could leave off the p command,
because as mentioned already, the p command is the default.
You may also specify a range of lines by entering two addresses separated by commas,
as in the following example:
:3,6p
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
Patterns also work in range selection, as in the following example:
:/humane/,/hesitation/p
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
You can mix patterns and line numbers too:
:4,/awe/p
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.
There are special ex line addressing symbols that can be used as addresses.
Line addressing takes on greater flexibility when you add these capabilities to the
ones you already know. The special symbols are shown in Table 3.10:
Table 3.10. Special ex line addressing symbols.
Command |
Result |
. |
the current line |
$ |
the last line of the file |
% |
every line in the file |
Another feature to allow greater flexibility in line addressing is line number
arithmetic. This feature allows you to use the + and - symbols along with numbers
to refer to offsets from the position specified. For example, to refer to 20 lines
from the current line number, you would use .+20.
When using two line addresses, the second address cannot be less than the first
address. Sometimes when you try to use search patterns to select a line or line number
arithmetic, you may get the error message ex: The first address cannot exceed
the second address. This is because both line addresses are determined relative
to the current line. In this case, you will get an error message. What you really
wanted was to have the second address be determined relative to the first address.
ex has a feature that causes the second line address to be relative to the
first. You use this feature by using a semi-colon between the two addresses instead
of a comma.
Table 3.11 following shows several examples of all of the various methods of line
addressing presented so far.
Table 3.11. Various methods of line addressing.
Command |
Result |
1,5 |
lines 1 through 5 |
.,20 |
from the current line to line 20 |
.,.+20 |
20 lines beginning at the current line |
.,$ |
from the current line to the end of the file |
1,$ |
all lines in the file (same as %) |
8,/pattern/ |
from line 8 to the next line containing pattern |
5;.+20 |
from line 5 to 20 lines beyond line 5 |
Basic ex Commands
ex has the property that every command has a name. You can enter the
full name of the command, or any length abbreviation of the command that sufficiently
distinguishes it from all other commands. As I introduce new ex commands,
I will first use the full command name. However, the examples will use the shortest
possible abbreviation of the command, because that is the way you will wish to use
them. Table 3.12 following shows a few of the basic ex commands:
Table 3.12. Basic ex commands.
Command |
Result |
d |
delete |
m |
move |
co |
copy |
t |
copy (synonym for co) |
Table 3.13 following presents examples of various ex editing commands.
It summarizes the information given in this section on manipulating blocks of text.
Table 3.13. Examples of ex editing commands.
Command |
Result |
1,5d |
delete lines 1 through 5 |
.,20m$ |
move the current line through line 20 to the end of the file |
.,.+20co0 |
copy 20 lines beginning at the current line to the top of the file |
8,/pattern/t. |
copy from line 8 to the next line containing pattern to the point after the
current line |
In this section, I have introduced some of the basic ex commands that
are useful to extend the power of vi. There are several additional ex
commands that provide an alternate way of doing various editing tasks. However, all
of these are more easily done by using the features of vi. Therefore, such
commands are not covered here.
Search and Replace
One of the main uses for ex commands from within vi (in addition
to working with files and exiting the program) is to execute search and replace operations.
In this section, basic search and replace operations are introduced. The next section
introduces the topic of regular expressions. Regular expressions are extraordinarily
powerful tools to search for text. If you are familiar with so-called "wildcard"
searches offered by certain text manipulation tools, you can think of regular expressions
as "wildcards on steroids!" The use of regular expressions for searching
is covered in the second section following this one.
Simple search and replace operations are done in ex (and, therefore,
in vi) by using the substitute command. Unless line addressing is used (see
the following), the substitute command operates on the current line, so it is necessary
to move the cursor to the line you want edit first. The following example assumes
that you want to substitute the word "opportunities" for the word "plan"
in line 8 of the sample text. Note that the final slash is required:
:8 Position to line 8 of the buffer
:s/plans/opportunities/ Replace "plans" with "opportunities" on the current line
You can also perform search and replace operations on the entire file, or a selected
range of lines. Table 3.14 following shows examples of using the substitute command
to operate on all lines in the buffer, or a selected range of lines.
Table 3.14. Using the substitute command.
Command |
Result |
:%s/warrior/general/g |
Replace every occurrence in the buffer of warrior with general. |
:.,.+20s/warrior/general/ |
Replace the first occurrence of warrior with general on 20 lines
beginning with the current line. |
Another way to search is to use the global command, as shown here:
:g/plans/command
When used in this way, the command is performed on all lines that match the pattern.
To negate the action of the search (that is, to act on all lines which do not
match the pattern), use :g!.
If the global command is used without the final slash and the command, the cursor
will be positioned to the last line in the file that contains the pattern (or does
not contain the pattern, if ! is used). If no match is found, the screen
will not be changed and the cursor will stay where it is. (There is little point
to using the global command to search in this way--use the vi /
or ? instead.)
You can use the global command with line addressing to limit the scope of its
action. Examples of using the global command with other commands are shown in Table
3.15.
Table 3.15. Using the global command with other commands.
Command |
Result |
:g/22/d |
Delete all lines containing 22. |
:g/plans/p |
Display all lines containing plans. |
:g!/22/d |
Delete all lines not containing 22. |
:8,12g/plans/p |
Display all lines between lines 8 and 12 containing plans. |
The global command can also be used to perform replacements. However, the real
power of this command for replacements does not emerge until you begin to use it
with regular expressions, which are explained in the next section.
Regular Expressions
Regular expressions are patterns used in search and replace operations that vastly
extends the power and flexibility of the editing you can do. Regular expressions
include in addition to literal characters, combinations of so-called metacharacters,
which have special properties. Table 3.16 shows all of the metacharacters available
for use within vi. (While there are a number of UNIX tools that can operate
on regular expressions such as grep, sed, awk, certain metacharacters
shown in the table are not implemented for these other tools. Such vi-and-Emacs-only
metacharacters are indicated by the comment "editors only.")
Table 3.16. Metacharacters available with vi.
Metacharacter |
Matches |
. |
Any single character, except a newline |
* |
Zero or more occurrences of the previous character |
^ |
When the first character of the regular expression, the beginning of a line |
$ |
When the last character of the regular expression, the end of a line |
< |
The first character of a word (editors only) |
> |
The last character of a word (editors only) |
|
The escape character; alters ("escapes from") the standard interpretation
of the following character. For example, to search for the literal presence of a
metacharacter, you must escape the character by preceding it with a backslash. |
[ ] |
Any single character within the brackets; ranges may be used with a hyphen. For example,
[a-z] matches all lowercase letters, [a-zA-Z] matches both lower- and uppercase characters.
When metacharacters (other than ^) appear within square brackets, they do not need
to be escaped. The literal hyphen can be included by placing it as the first character
after the left square bracket |
[^ ] |
Any single character not within the brackets |
( ) |
In a search pattern, saves the text matched within the escaped parenthesis in a numbered
buffer for later "replaying" (the number is the position in the line as
it is scanned from left to right; the first occurrence of this metacharacter pair
is numbered 1, the second occurrence 2, and so on) |
n |
In a replacement pattern, where n is a digit from 1 to 9, "replays" the
text saved by the escaped parenthesis |
& |
Uses the entire search pattern which produced the match; used to save typing |
u or l |
In a replacement pattern, causes the next character to be either upper- or lowercased |
U or L |
In a replacement pattern, causes the rest of the replacement pattern (or until a
e or E is scanned) to be upper- or lowercased |
e or E |
In a replacement pattern, terminates the action of U or L |
~ |
Matches the search pattern of the last regular expression search |
CAUTION: The use of metacharacters might
vary in different contexts. The shells use metacharacters for file name expansion;
however, the interpretation of the metacharacters by the shells is slightly different
from the interpretation by the utilities and text editors. (A shell is the name given
to the UNIX command processor. There are several common versions of shell programs.
The most common are sh, csh, ksh, and bash. Please refer to Part 2,
"UNIX Shells" in UNIX Unleashed, System Administrator's Edition,
for an extensive discussion on this topic.) This may be a source of confusion, especially
to the newcomer. To make matters worse, the implementation of metacharacters differs
between different UNIX versions.
TIP: All regular expression matches are
limited to a single line. That is, a match that "wraps around" from the
end of one line to the beginning of the next is not allowed.
TIP: All regular expression searches are
case sensitive. You have to explicitly use the features of the metacharacters to
perform case-insensitive searches. For example, if you wish to perform a search for
the word "general" that is case-insensitive on the initial "g,"
you should use /[Gg]eneral/ for the search string.
TIP: Regular expressions are usually delimited
by forward slash (/) characters. However, any non-alphanumeric character
other than ", |, or # can be used. This is especially
helpful when the slash is one of the characters in the search string and you don't
want to escape the slash.
Global Search and Replace with Regular Expressions
You have already seen how to perform searches from vi using the /
and ? commands. As mentioned when these commands were introduced,
you can use these commands with regular expressions as well as with literal text
strings. There are two ways to use regular expressions to perform search and replace
operations. Both methods work from the ex command line, and both are extensions
of commands you have been exposed to in the "Search and Replace"
section. One way is to use the substitute command; the other way is through
the use of the global command.
Using the Substitute Command with Regular Expressions
When you wish to make a global replacement, you can use the substitute command
with line addressing and regular expressions. A commonly used form is to use the
% addressing symbol to refer to all lines in the file. The general form
of such a command is as follows:
:address s/searchexpression/replaceexpression/options
(The space after address in the preceding example is for clarity and is
optional.) The options refer to one of the options shown in Table 3.17.
Table 3.17. Substitute options.
Command |
Result |
g |
Make the substitution global (Without this option, the substitution only occurs on
the first occurrence in the line; with it all occurrences on the line are
substituted. Do not confuse this option to the substitute command, which is placed
at the far right of the command, with the global command itself, which occurs on
the left of the command line near the colon.) |
c |
Confirm. vi displays each line found and indicates the text to
be substituted with '^' symbols as follows:
this is some text ^^^^
You must enter a "y" to make the substitution; any other response causes
the substitution not to be made. (Note: Some versions of vi handle this
a little differently, using text highlighting to indicate the pattern matched, and
allowing additional choices at each step.)
|
You may combine both of these options into one substitute command.
Using the Global Command with Regular Expressions
The global command becomes very powerful when combined with the substitute command.
One interesting way to use this combination is to use the global command to select
the lines, and then use the substitute command to cause a change on the lines that
does not directly relate to the text the caused the line to be selected.
In effect, what the global command does is to provide a two-step editing function.
First, a set of lines is selected using several of various techniques (line addressing
and pattern matching). Then another command is used upon the lines selected. When
the global command was first introduced in this chapter, it was used in a simple
way with other commands to display or delete text. In fact, the global command can
be used with most any other command. (There are some creative techniques, indeed,
that have been invented that use the global command. Some are shown in the examples
of Table 3.18.)
The best way to show how the substitute command works and how the global and substitute
commands can be used together is to present some examples. Table 3.18 shows a few
of the types of search and replace operations that can be done. (Note: For clarity,
the bolded lowercase letter b is used to indicate a single blank space.)
Table 3.18. Examples of search and replace with the
s and g commands.
Command |
Result |
:%s/ex/vi/g |
Substitute every occurrence of ex in the buffer with vi. |
:.,$s/ex/vi/c |
Substitute the first occurrence of ex with vi on every line from
the current line to the end of the buffer, confirming each substitution. |
:%s/<author>/contractor/g |
Substitute the word contractor for each occurrence of the full word author
in the buffer; note that text objects containing author as a substring, such
as authority will not be substituted. |
:g/editor/s/line/full-screen/g |
Substitute every occurrence of line with full-screen on all lines containing
the pattern editor |
:g/editor/s//word-processor/g |
Substitute every occurrence of editor with word-processor; note that
when the second search string is missing, the first search string is used; in this
case, the string editor |
:%s/bb*/b/g |
Substitute a single space for every occurrence of one or more spaces (note: the b
stands for a single space). |
:%s/[:.]bb*([a-z])/.bbu1/g |
Search for all occurrences of a colon or a period followed by one or more spaces
and a lowercase letter; substitutes a period, two spaces and the uppercase form of
the letter. |
:g/^$/d |
Delete all blank lines (lines that have only a beginning followed immediately by
the end) |
:g/^/m0 |
Reverse all the lines in the buffer |
:g!/Complete/s/$/ To be done/ |
Append To be done to all lines not containing the string Complete |
Working with Files
The basic commands for saving files were introduced in the "Starting Up and
Exiting vi" section. This section will more fully explain these
commands and show how to use them to work with more than one file at a time.
Saving Changes to a File
:w--Write The w command is used to write the buffer to
the current disk file. The current disk file is the one that was most recently loaded
for editing, either from the command line when vi was started, or using
the :e command. If there is no current disk file (perhaps because vi
was loaded without specifying a file to edit), vi will display an error
message and no action will occur. In this case, you can give a name to the current
disk file with the version of the :w presented next.
Until the buffer is written to disk, all edits to the file are only stored temporarily.
It is, therefore, a good habit to develop to save your work frequently during your
session to minimize the inconvenience of a system failure or major editing error
that may occur.
:w filename--Write to filename This version of the
write command will save the buffer to the named filename. If there was previously
no current file defined, the filename will become the current file. Otherwise,
the current file will remain the same as it was before the :w filename
command was issued.
If the filename file already exists, as usual vi warns you of
this fact with an error message, and gives advice on how to override the warning,
as follows for a file name art1:
"art1" ex: The file already exists. Use w! art1 to force the write.
If you do in fact wish to overwrite the existing version, you can use the syntax
:w! filename.
:address w filename--Write addressed lines to filename
This version of the write command further refines the action of the :w
filename version. The difference is that only the lines selected by
the address will be written. The same caveat regarding existing files applies.
:address w >> filename--Append addressed lines
to filename This version of the write command uses the UNIX redirect and
append operator to add the addressed lines on to the end of an existing filename
file. As you would expect, if you omit the address portion, the full buffer is
appended.
Editing a Different File
:e filename--Edit file Begins to edit the filename
file. If the file does not exist, then a new file is started and filename
becomes the current file. (That is, a subsequent :w command will write the
filename file.)
If the current file has been changed since the last time it was saved, the :e
filename command is not allowed. Instead, vi gives the usual
warning about the unsaved file, which may look as follows:
ex: No write since the file was last changed. The edit! command will force the
action.
Once again, you could use :e! filename "to force the action."
:e!--Revert This special use of the edit command forces the last
saved version of the current file to be loaded for editing. This has the effect of
reverting back to the last saved version, discarding all edits you made since then.
(If you omit the exclamation point, in effect you are telling vi to begin
editing the current file. If there were no changes yet, vi would oblige;
however, this is a useless function. If there were changes, vi would do
its normal routine of warning you that there has been "no write, etc."
So the only useful version of this command is with the exclamation point.)
:e + filename--Edit filename at end Edit the filename
file; place the cursor at the end of the file.
:e + number filename--Edit filename at line number Edit
the filename file; place the cursor on line number.
:address r filename--Import (read) filename The
read command allows you to import the full contents of another file into the buffer.
If the optional address is present, the filename file's lines are imported
immediately after the line selected by the address. If the address is omitted, the
lines are imported immediately after the line the cursor is presently on. The address
can be a line number (with 0 indicating the top of the file), $
to indicate the last line of the file, or a search pattern.
Editing More than One File
:n--Next file When vi is started, more than one file
can be listed on the command line. For example, to edit the three files art1,
art2, and art3 you would enter the following shell command:
$vi art1 art2 art3
vi loads the file art1 as usual and you may begin editing it.
After saving the file, you can go on to the next file with the :n command.
If you try to use the next command before you have saved the current file, you will
get the usual warning, which can be overridden in the usual way (yes, you guessed
it--with n!).
Alternating Between Two Files
vi keeps two filenames available via special symbols for use with ex
commands. These are # for the alternate file, and % for the current
file. Once you have switched files with the :e command, the previous ("alternate")
file can be referenced via the # symbol. You can toggle back and forth between
the two files by just typing :e# each time you wish to switch.
The % symbol is mainly used to save typing within shell commands.
Moving Text Between Files
You can use the undo buffer or the named buffers to copy or move text from one
file to another. The method is just like copying or moving text from one part of
a single file to another part of that file using the buffers as already described
in the "How To Use Buffers" section. The difference is that after (say)
a yank is done, an :e command is used to change to another file.
Then the put is done into the new file.
The reason this technique works is that when you change files with the :e
commands, the contents of all of the buffers is retained.
Using the Power of UNIX from within vi
You may have already seen in UNIX Unleashed, System Administrator's Edition, Chapter
5, "General Commands," the general UNIX strategy for combining the functions
of single-purpose or specialized tools to achieve results. vi shares in
the capability to interact with the shell, filters, and utilities, and, in general,
with any program that reads from the standard input and writes to the standard output.
This section explains the various vi commands that make this possible.
:sh--Shell This :sh command invokes the shell. The shell
that is run depends upon your UNIX environment, but can be controlled with the sh
setting (see the "Changing vi Settings" section). You would use
this command when you wish to temporarily leave vi to enter the shell and
then return to the vi session at the point where you left off. You would
usually enter the shell to run one or more shell commands, staying within the shell
between each command. Any output to the terminal from the command you type is displayed
normally, and the display of the vi session scrolls upward.
To return to your vi session, press ^D (or use the proper
convention for the shell that you are using). You are then returned to vi,
with the screen still showing the output of your shell session. In addition, at the
bottom of the screen, the text "Press return to continue" is displayed.
After pressing Return, the screen is cleared and redrawn. You are then at the exact
point in your editing session where you left off.
:!--Shell In some versions of vi, the same as the :sh
command. Other versions will give an error message prompting you to use the :sh
form.
:!shellcommand--Shell Command Execute the shellcommand
and return to vi. Note that in the shell command, the ex special
symbols for files (introduced in the section "Editing Multiple Files")
are expanded. These are % for the current file, and # for the alternate
file. If you wish to prevent these from being expanded, you must escape them with
a (backslash). The role of the escape character is explained in detail
next, under "Repeat Shell Command."
:!!-- Repeat Shell Command Repeats the last :!shellcommand.
Note that any unescaped ! that follows the :! command will be expanded
to the last shell command issued via :!. For example, if you enter the following
sequence, you will get a result similar to what follows (the text in italics
are my comments):
:!ls to display your directory
art1 art2 !test1 lsefair contents of the directory (perhaps)
[Press return to continue]
:!ls -l !* attempt display of long listing for all files starting with !
-rw-rw-rw- 1 jas system 2886 Nov 3 10:07 lsefair
[Press return to continue] not what you wanted!
What has happened is that when you entered :!ls -l !*, the final exclamation
point was expanded to the last command issued. Because the last command issued was
ls, the actual command passed to the shell was ls -l ls*, where
the ! was replaced with ls. To prevent expansion of the !
you must escape it by preceding it with a (backslash). The correct
way to enter the command is :!ls -l !*.
:address!shellcommand--Filtering text through a shell
command (ex) This command works with ex line addressing to select some
text to send to a shell command. The output of the command then replaces the selected
lines. You could use this command, for example, to sort a section of your text. The
following example shows how to sort lines 100 to 108:
:100,108!sort
Note that if the shell command does not take any standard input, then the selected
lines are just replaced.
!object shellcommand--Filtering text through a shell command (vi)
You can also select vi objects to filter, using certain of the keystrokes
that are used to select objects. This technique will not work on anything less than
a whole line, so you must either use keystrokes that will cover more than a line,
or use a count prefix to extend the object selected. The following example shows
how to uppercase the next paragraph using the tr filter:
!}tr '[a-z]' '[A-Z]'
When you use this technique, you will note that vi responds in a special
way. First, when you type the initial exclamation point, nothing is displayed on
the screen. After the keystrokes are typed to select an object, an exclamation point
appears on the command line, but the keystrokes for the selected object do not. At
this point you can type the shell command, as shown previously. In addition, there
are certain special features available. If you type another exclamation point, it
is expanded to the text of any previous shell command. So for example, if you wanted
to continue to move around in your file and uppercase various text objects after
typing the string in the previous example, you could just type !object!
each time after positioning to the chosen spot. count!!shellcommand--Filtering
text through a shell command
!count!shellcommand These two commands are equivalent.
They are variations on the preceding vi text filtering command. They apply
to count number of lines relative to the line the cursor is on. The count
is optional; if absent, the current line is processed.
Marking Your Position
It is often necessary when editing larger files to move back and forth between
specific points. Many editors implement the concept of a bookmark, which is
a mechanism for marking a place in your buffer, and then allowing an easy way to
return to that exact place. In vi, there are several ways that this concept
is implemented.
mx--Mark Marks the position that the cursor is presently
at with the letter x, where x is any letter. The
mark is not visible on the screen.
'x (backquote)--Move to mark x The 'x
(backquote) command moves the cursor to the exact position marked by the letter
x.
'x (apostrophe)--Move to beginning of line of mark x The
'x (apostrophe) command moves the cursor to the beginning
of the line marked by the letter x.
'' (two backquotes)--Move to previous location Moves to the exact
position before the previous repositioning of the cursor via pattern search, G
command, or move to a mark.
'' (two apostrophes)-- Move to beginning of line of previous location
Moves to the beginning of the line of the cursor position before the previous repositioning
of the cursor via pattern search, G command, or move to a mark.
For the Power User: Customizing vi
If you have stuck with this chapter this far, you are probably looking for the
"Power User" features. Here they are!
Automation of Common Chores
As you become more familiar with an editor, you may find yourself seeking to automate
certain keystroke sequences that seem to be occurring over and over. There are two
ways to doing this in vi: abbreviations and key mappings. Both of
these methods are described in the following section.
Abbreviations vi has the built-in capability of using abbreviations
that you set up. For example, suppose you are often found typing the phrase "SAMS
Publishing, an imprint of Macmillan Computer Publishing USA." You
could abbreviate this phrase for example as SAMS, with the following command:
:ab SAMS SAMS Publishing, an imprint of Macmillan Computer Publishing USA
vi expands the abbreviation while you are in insert mode into the full
text after you have typed the abbreviation plus either a space or a punctuation character.
Note that the abbreviation is case-sensitive, so you can retain the ability to omit
the expansion by a judicious choice of upper- and lowercase characters in the abbreviation.
To see all the abbreviations currently in effect, just enter :ab with
no arguments (that is, by itself). To eliminate an abbreviation (perhaps so that
you can include the literal characters of the abbreviation itself, use the :unab
command.
Tip: Although the abbreviation feature is used
primarily to save retyping common strings, there is another very useful technique
that can be used with the feature: correcting common mistypings. Just set up as an
abbreviation the mistyped word.
For example, I am in the habit of typing "wrok" when I mean "work,"
and "flies" when I mean "files." I could set both of these as
abbreviations and see vi automatically change my mistyping into the correct
word. However, do not overdo this--as you can see, if I used "flies" as
an abbreviation for "files," then I lose the ability to use the word "flies."
Creating Macros with the :map Command The :map command
is used in a similar way as an abbreviation. The :map command allows use
to assign command mode keystroke sequences to a single (or multiple) keystroke sequence.
Such commands are often called keyboard macros. Often :map commands
are used to assign keystrokes available on your keyboard (such as the cursor control
arrow keys) to the desired vi commands (h, j, k,
and l).
A :map command is entered just like an abbreviation. For example, to
map the command sequence dwelp (which will reverse the order of two adjacent
words) to the letter "v":
:map v dwelp
To use a control character in the mapping, you must precede the entry of that
control character with a ^V. Otherwise, vi will immediately try
to interpret the control character you are typing. The ^V tells vi,
in effect, "do not interpret the next character, just enter it into text."
When you type the ^V, only the ^ (caret) shows. For example, when
you want to insert an Esc character into the mapping, you would type ^V
followed by the Esc key. Suppose you wanted to map the "v" key to the Esc
key. What you would see on the screen after typing the ^V would be the following:
:map v ^
Then when you pressed the Esc key, your screen would look like this:
:map v ^[
Then after pressing Return, your mapping would be in effect.
To remap certain keys that might be on your keyboard to the equivalent function
in vi, you may not even need to know what character sequence is assigned
to your keyboard. Just use the ^V key; then type the key that you wish to
assign. (This may or may not work, depending upon the terminal mapping in effect
at your terminal. See your system administrator for help if you are having trouble
setting up your keyboard mappings.)
It is useful to see what keys are not already used by vi, and are, therefore,
available for mappings without losing any functions (there are, in fact, a few keys
left unused). They are as follows: g, K, q, V,
v, ^A, ^K, ^O, ^T, ^W, ^X,
_, *, , =. (The = key is not available
if the lisp setting is in effect.)
To remove the mapping, use the :unmap command. To see all mappings that
are currently in effect, use the :map command with no arguments.
Other creative uses for the map command are shown in Table 3.19, which shows several
examples of both the :ab and :map commands:
Table 3.19. Some examples of the ab and map
commands.
Command |
Result |
:ab L1 Level One |
Sets L1 to expand to "Level One" |
:ab |
Displays all abbreviations |
:unab L1 |
Removes the expansion of L1 |
:map v dwelp |
Reverses two adjacent words (not at the end of a line) |
:map ^A i"^[ea"^[ |
Surrounds a word with quote characters |
Changing vi Settings
Up until this section, I have been describing the default behavior of vi
under various circumstances. You can modify these default behaviors by changing the
vi settings. The easiest way to understand these settings is with an example.
One such default behavior is what vi does while you are inserting text and
you get to the end of the line. The default behavior is to continue adding text to
the line; however, the display gives the appearance of wrapping to the next line.
(You can check this by using the 0 and $ commands from command
mode to see where vi considers lines to begin and end.) You can alter this
default behavior to suit your requirements.
Tip: In addition to using the 0
and $ commands to see where lines begin and end, you can also use line
numbering with :set nu to see how vi is assigning line numbers.
Another technique that might help is using :set list, which will show tabs
and line ends with ^I and $, respectively.
If you are typing the text of a memo for example, you may wish vi to
automatically wrap lines. By using the setting wrapmargin, (abbreviated
as wm), you can cause vi to insert a line feed automatically when
you get close to the end of the line. (The exact behavior of the wm setting
is described later.) If, on the other hand, you are editing a source code file, most
likely you would want there to be no such wrapping, so the default behavior is what
you want.
The vi settings can be modified in four ways, as shown in Table 3.20.
Table 3.20. Ways to modify default vi characteristics.
Command |
Result |
set commands |
Executed during a vi session to temporarily change the characteristic, until
they are explicitly changed again or the vi session ends |
.exrc file |
Changes included in the .exrc file will go into effect whenever the editor
is started, until overridden during the session by a set command |
EXINIT |
An environment variable that can be used just like the .exrc file (if the
same setting is changed by both an entry in an .exrc file and the EXINIT
environment variable, the setting from the .exrc file takes precedence) |
The methods are listed in precedence order, from highest to lowest. This means
that any of the commands in effect override the effect of the same command of a type
shown lower in the table. For example, a set command overrides the same
command from the .exrc file, which in turn overrides the effect of the same
command from the EXINIT environment variable).
There are two type of vi settings. The first is a toggle setting, which
may be either on or off. To put the setting into effect, you would use the command
:set option, where option is the desired setting to put into
effect. To remove the setting from effect, you would use the command :set nooption,
where nooption is the same name as you would use to put it into effect with
the characters "no" preceding the name.
The other type of setting is a numeric setting, which has a numeric value. For
example, the wrapmargin setting may have a value of 10. To use a
numeric setting, you would use the command :set option=x,
where option is the name of the setting, and x is the numeric value.
For example, use :set wrapmargin=10 to set the wrapmargin setting
to a value of 10.
Many of the settings have abbreviations. For example, you have already been introduced
to the wrapmargin abbreviation of wm.
The .exrc file is a plain text file that is located in the user's home
directory. It consists of set, ab, and map commands,
entered one per line. (The ab and map commands were described in
the "Automation Of Common Chores" section.) If such a file exists, vi
will read it immediately after starting and the commands it contains will be placed
into effect just as if you had typed them from the ex command line before
starting to edit. The following shows an example of an .exrc file:
set wrapmargin=10 nowrapscan
ab SAM SAMS Publishing
With the preceding example as your .exrc file, the wrapmargin
is set to 10, wrapscan is turned off, and an abbreviation is created every
time you start vi. In addition to reading the .exrc file in your
home directory, vi will try to read an .exrc file in the current
directory you are in when you start vi. If such a file is found, the entries
there will be added to the ones put into effect from the .exrc file in your
home directory. This feature allows you to have your preferred settings for all vi
sessions, plus special tailoring for separate projects.
NOTE: In System V UNIX, the feature to
look for an .exrc file in the current directory is only enabled if the exrc
setting is enabled (it is off by default). This setting is a security feature. An
attack on the security of a system could be made by planting an .exrc file
in a directory that causes some unintended and undesirable action.
You can see what settings you have placed in effect by entering :set
without any options. By entering :set all, the value of all settings is
displayed.
Table 3.21 following shows the most useful vi settings. There are a number
of additional settings not shown, falling into two categories: (1) settings that
are rarely used nowadays and should be considered obsolete (for example, several
settings are intended for slow line speeds such as 300 baud and under); and (2) settings
that are particular to specific vi implementations.
In the first column, the name of the setting is shown. The second column shows
the minimum abbreviation for the setting as well as for deactivation of the setting.
If there is a default value for a setting, it is shown in the third column, using
abbreviations wherever they exist. The fourth column contains the description of
the setting.
Table 3.21. The most useful vi settings.
Setting |
Abbreviation |
Default |
Description |
autoindent |
ai |
noai |
Inserted new lines of text are indented to the same distance as the preceding line. |
noai autowrite |
aw |
noaw |
Automatically saves a changed file before opening the next file with :n
or using a shell command with :!. |
noaw directory |
dir |
/tmp |
Directory in which buffer files are stored. |
edcompatible |
|
noedcompatible |
When substituting act like the ed editor |
errorbells |
eb |
eb |
Sound the bell |
noeb |
|
|
(usually called a "beep") when an error occurs. |
exrc |
ex |
noex |
Allows an .exrc file in the current directory to override the .exrc
file in the user's home directory. |
*noex |
lisp |
nolisp |
Helps formatting for editing lisp source code files.
Changes the behavior of indenting; the followingcommands are modified: (),{},[[,]]. |
list |
|
nolist |
Displays on the screen special characters: tabs show as^I; ends of lines
are marked with a $. |
magic |
|
magic |
The ., *, and [ ] characters act as wildcards in pattern
searches. |
mesg |
|
mesg |
System messages are allowed when vi is running. |
number |
nu |
nonu |
Display line numbers. These numbers are not saved in the file when the buffer is
written to disk. |
nonu paragraph |
para |
IPLPPPQP LIpplpipbp |
Defines paragraph moves using nroff macros, for use with {
and } commands |
readonly |
ro |
noro |
Buffer may not be written to a file unless ! override is used. |
noro redraw |
re |
nore |
After each edit, the screen is redrawn. By turning this option off, performance can
be improved when you have a slow line speed. |
nore |
|
|
When text is inserted with nore, the new characters will appear to
overwrite existing characters until the Esc key is pressed. When lines are
deleted with nore, the space taken by the lines is not closed up; instead
an @ character is displayed on the line. The main reason to be aware of
this setting is to be able to disable it if your terminal has it enabled. |
remap |
|
remap |
map commands may be nested. |
report |
|
5 |
When an edit affects more lines than this setting, a message is displayed. |
scroll |
|
half-window |
Number of screen lines to scroll. |
sections |
sect |
SHNHH HUnhsh |
Defines section moves using nroff macros, for use with [[
and ]]. |
shell |
sh |
/bin/sh |
Defines the shell to use for shell commands. Different UNIX variants may provide
a different default. |
shiftwidth |
sw |
8 |
Number of spaces to use for ^D backtabs. |
showmatch |
sm |
nosm |
When a ) or } is typed, the cursor is briefly positioned to the
matching character. Helps while programming in C or lisp. |
nosm |
|
|
|
showmode |
|
noshowmode |
Indicates type of insert mode. Only available in certain UNIX variants. |
tabstop |
ts |
8 |
The number of spaces the tab character moves over. |
taglength |
tl |
0 |
The number of characters that are significant in tags. |
tags |
|
/usr/lib/tags |
The default tags file path. |
term |
|
|
Defines the terminal in use. |
terse |
|
noterse |
Shorter error messages are displayed. |
timeout |
to |
to |
When to is in effect during the typing of a multi-key sequence that is mapped
(for example, :map xxx d} to delete the next paragraph), vi waits
one second to get the next keystroke. If longer than one second occurs, vi
does not consider the mapped sequence to have been typed. For example, three x characters
must be typed with less than a one-second interval between them in order for vi
to consider the mapped sequence to have occurred. |
noto |
|
|
When noto is in effect, vi will wait indefinitely between keystrokes
before making the determination. |
warn |
|
warn |
Gives a warning message when a shell command is issued but the buffer has been changed. |
wrapscan |
ws |
ws |
Searches reaching an end of the buffer wrap around to the other end. |
nows |
|
|
|
wrapmargin |
wm |
0 |
When set to a number other than zero, carriage returns are inserted automatically
when the cursor gets to within that number of spaces from the right edge of
the screen. Very useful for normal text editing (not for source code). |
writeany nowa |
wa |
nowa |
Allows writing to any file without using the ! override. |
(Note: This setting is only available in System
V; in other UNIX variants the setting does not exist, but the override is allowed;
that is, the behavior is as though the exrc setting was in effect).
Other Advanced Editing Techniques
Although we have definitely scratched the surface of the power of vi,
there is yet more available. The capabilities mentioned briefly in this section are
here to let you know they exist. You will only be able to get maximum benefit from
them by using them yourself.
@ Functions An @ function executes the content of a named
buffer as a vi command. So another way to build a macro command is to type
the text of a command that you wish to use repeatedly, escaping each control character
with a ^V, then deleting that text into a named buffer. You may then execute
the command in that buffer using the @x command, where x is
the named buffer.
Using autoindent The autoindent commands and settings
are indispensable when editing source code files. When the autoindent setting
is enabled, each new line is indented to the same distance as the previous line,
which makes for easy structuring of source code. There are several commands you can
use in conjunction with autoindent.
^D--Backtab (with autoindent) Backs up to the previous autoindent
stop, as specified by the shiftwidth setting. In order to use this most
effectively, you should coordinate the shiftwidth setting with the tabstop
setting.
^^D--End Autoindent, One Line Only This command is the caret character,
followed by a Ctrl-D. It causes autoindent to be suspended for the current
line only. The cursor moves back to the left margin. On the next line, the autoindent
resumes at the previous position.
0^D--Cursor to left margin Moves cursor back to the left margin.
Using Tags :ta tag--Jump to Tag The :ta
command is of interest only to C programmers. This command allows you to easily work
with a number of C source code files. It removes the need for you to keep track of
which C function is contained in which source code file.
Before you can use this command, you must first use the ctags program
to create a database of source code file names and function names. (Please refer
to the documentation of the ctags program.)
If the tags file has been created with the ctags program, the
command :ta tag will jump to the file containing the tag
function and position the cursor to that function. The tags file is first
searched for in the location given by the tags setting, then in the current
directory.
What Is Emacs?
Emacs is one of the most powerful text editing environments available
today. It is a mature tool, having evolved over more than 20 years; it is still evolving
today. Emacs has a reputation for being rather formidable and difficult
to learn. While it is true that it is a very large program (and that some say that
it has more features than can be possibly assimilated fully by any one individual),
that does not mean that it actually is hard to learn or use. In fact, after having
used it, you probably would wonder why such a fuss is made!
Comparison to vi
Because Emacs and vi are both text editors, they share many
of the general characteristics of text editors. For example, the concept of buffers
pertain to both programs, although Emacs has a more fully developed
implementation of the concept. Therefore, general advice such as "save your
work often" apply equally to both editors.
Like vi, Emacs is a full-screen editor. However, Emacs
does not have a separate mode for entering commands and inserting text. (Emacs
does have its own version of modes; see "The Big Picture" section.) You
are always able to enter text and commands without the annoyance of having to switch
modes. This feature alone first convinced me to give Emacs a try. The way
Emacs handles commands is to make all commands either shifted keys
or escape sequences. The way this works is described in detail in the "Basic
Editing: Getting Started" section.
One of the key advantages of Emacs is that of integration. Emacs
goes beyond providing text editing capabilities--it actually has so many built-in
tools and utilities that you may not need to acquire or learn several other tool
suites to do all of your work, as you would in other computing environments. The
real payoff of this high degree of integration is the great convenience and time
saving that you get. If Emacs is available to you, it is well worth your
effort to check it out.
Emacs is also extensible. This means that you are not limited
to the built-in capabilities provided with the editor, as you are with vi.
If you are familiar with the lisp programming language, you can even add your
own commands to Emacs!
How to get Emacs
A major difference between vi and Emacs is that while vi
is provided with nearly every UNIX implementation, Emacs must be obtained
and installed separately. For this reason alone, many have missed out on the
opportunity to sample its power and convenience. However, if you do not have access
to Emacs at present, that is no great hurdle, because it is readily available
over the internet at no out-of-pocket cost, most notably in the GNU Emacs
version, which is a product of the Free Software Foundation. Or you can just load
GNU Emacs version 19.30, which is provided with this book on the included
CD-ROM.
If you are obtaining the Emacs files electronically, be prepared for
a 10 megabyte file transfer; then be prepared to sacrifice over 100 megabytes of
your hard disk space! (I did say Emacs was large!)
Why Would I Be Interested in Using Emacs?
As already mentioned, Emacs can be a comprehensive work environment.
If you like powerful, integrated tools, you might find learning Emacs to
be one of the better investments of your time.
Starting Up and Exiting the Program
Starting Emacs is just like starting vi. Enter the name of the
program (which may vary, depending on the version you have), optionally followed
by one or more file names. If you omit the file name, Emacs will create
a new file for you. Emacs will start up with some general information about
the help system. As soon as you begin to type, this information will be cleared and
everything you type will be displayed on your screen. After typing some text, your
screen will look like the following:
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.'
-----Emacs: art1 (Text)--All-------------------------------------
Wrote /home/jas/art1
If you have entered a file name on the command line, the file is opened and loaded
into the editor. To exit from Emacs, use the sequence C-x C-c.
Basic Editing: Getting Started
When learning an editor, it is only necessary to learn some of the basic features
before you can be productive with the tool. As when learning vi, the learning
process is more a matter of training your fingers and reflexes than it is of memorization.
Also as in vi, there are certain patterns to the structure of the commands
that becomes comfortable after you gain familiarity with the program.
Control and Meta Key Sequences
All editing commands in Emacs have a name and can be executed by using
that name. However, it would be quite tedious and inefficient to have to use a long
command name every time you wanted to something as simple as moving the cursor forward
one character! So all of the commonly used commands are "bound" to more
easily-used keystroke sequences. Thus, the term binding is used in Emacs
to refer to the association of specific keystroke sequences to editing commands.
To distinguish commands from text that is to be inserted, Emacs uses
shift-key sequences. A shift-key sequence is entered by holding down the designated
shift key while another key is pressed. The shift keys used by Emacs
are the Ctrl key and the Meta key. In Emacs literature and in the Emacs
online help system, these keys are abbreviated as C-x and
M-x, where x is any other key name.
On most terminals the Meta key is not present. To get the effect of the Meta key
on terminals where it is not provided, you have to instead first press the Esc
key as a separate keystroke, followed by the second key.
Tip: On some terminals, the Alt key will take
the function of the Meta key, operating as a shift key. If you have an Alt key, be
sure to try it to see if works, because it is a lot more convenient to be able to
press and hold the Alt key during the pressing of the other keys, especially during
multiple shift-key sequences, than it is to have to press Esc before every keystroke.
There is a general pattern to the way that Emacs binds keystrokes to
functions. The shifted and Esc key sequences fall into five forms. First, the most
common commands are entered as C-*, where * is any key.
Second, the next most common commands are entered as ESC * (the Esc
key followed by any key; because most terminal do not have the Meta key, from this
point on, I will indicate an M-* sequence using the Esc key
notation).
Next, commands that are somewhat frequently used are entered as C-x *,
where C-x is the Control-X sequence, and * is any other command,
including shifted-key sequences. Then there are the least frequently used commands
or commands used in specialized modes that are entered as C-c *, where
C-c is the Control-C sequence and * is once again any other command.
Note: Where Emacs commands are shown
in this chapter as C-x * or ESC *, the space preceding the *
is only present for clarity. You should not type any spaces before the *.
When Emacs echoes the command in the mini-buffer, it also puts in the space,
even though you have not typed one.
Finally, there is a set of commands that do not have a key binding at all--you
must use the long command name. Such commands are entered by the following sequence:
ESC x commandname, where x is the literal "x" character
and commandname is the long command name (actually any command may be entered
in this format--it's just easier to use the key bindings once your fingers learn
them). Entering the long commandname is not as bad as it sounds: Emacs
has a completion feature (type a few characters of the name and press TAB;
Emacs will either complete the command name or give you a menu of choices,
which is described further in the "Completion" section) that makes this
quite simple.
These command forms are summarized in Table 3.22.
Table 3.22. Commands forms in Emacs.
Form |
Description |
C-* |
Most commonly used commands |
ESC * |
Next most commonly used commands |
C-x * |
Somewhat frequently used commands (such as file-related commands) |
C-c * |
Infrequent or specialized commands |
ESC x commandname |
Any command may be entered in this form; mandatory for those that do not have key
bindings |
The most important key bindings are shown in this chapter in tables. In these
tables, there are certain key name abbreviations, as shown in Table 3.23.
Table 3.23. Key name abbreviations used in this chapter.
Abbreviation |
Key |
C-x |
Control-X |
ESC x |
Escape X or Meta-X |
RETURN |
Return or Enter key |
DEL |
Delete or Del key |
INS |
Insert or Ins key |
SPACE |
Spacebar |
SHIFT |
Shift key |
TAB |
Tab key |
In addition to the defined commands that are built in to Emacs, you may
also create your own command bindings.
Note: Another word used in Emacs documentation
is the term point, which you can often think of as synonymous with cursor.
In fact, there is a slight technical difference between the two terms. The cursor
is the highlighted character position on your screen where the next text insertion
or editing action will take place. The point is the position in the buffer that is
analogous to the cursor, but actually between character positions.
So, for example, when you see the cursor on your screen on top of the letter "h"
in the word "the," the point is actually between the "t" and
the "h." Sometimes thinking about the point as between two characters helps
to understand the editing action that Emacs takes.
The Big Picture
Before getting into the details of working with Emacs commands, there
are several general attributes of Emacs with which you should be familiar.
Emacs is X-windows compatible. If you are running a version of X, Emacs
will run in an X client window. When running in this way, the usual features of X
are available to control the size and placement of the window, as well as window
and mouse controls to move around in the text. (Emacs has numerous special
functions available only when running under X Windows, but they will not be covered
here.)
The Emacs Screen Beginning with version 19.30 of Emacs,
even the text-based version (non-X-windows) has menus, as may be seen at the top
of the following example.
Buffers Files Tools Edit Search Help
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.'
-----Emacs: art1 (Text)--All-------------------------------------
You will notice several key features about this screen. First, at the top of the
screen (if you are running Emacs version 19.30 or later) there is a set
of menu choices (that is, Buffers, Files, Tools, Edit, Search, Help). All of the
Emacs commands are available from the pull-down menu as well as from the
traditional keyboard bindings. In addition, there are some features that are only
available from the menus. These will be pointed out in the appropriate contexts.
On the second line from the bottom there is a status line, which contains the
following information: "Emacs," the filename, the current major
mode (described later) in parenthesis, file size, relative position in the file.
The last line of the screen is blank. This line is called the mini-buffer.
Modes As already mentioned, Emacs does not have a separate command
mode and insert mode as does vi. However, Emacs makes a great use
of modes to simplify your work. A major mode is simply a set of editing characteristics
and commands that are appropriate for a particular type of work. There are modes
for common tasks. For example, text mode is used for creating letters, memos, and
documents. It has characteristics that help in that task, namely recognizing text
elements such as sentences and paragraphs. There are modes for creating source code
files for popular languages. For example, C++ mode is used for editing C++ source
code; it has characteristics specific to that task, namely assisting with indenting
for C++. There are even modes for emulating other text editors and word processors,
such as vi and Wordstar!
Each buffer is in exactly one mode at all times. The most important major modes
are shown in Table 3.24.
Table 3.24. Emacs major modes.
Major Mode |
Description |
Fundamental |
Most basic mode; standard Emacs defaults only |
Text |
For writing general text |
Indented text |
Provides additional support for automatically indenting text |
Outline |
Allows selective hiding and display of levels of text |
Picture |
Allows drawing simple pictures from characters; repeats characters in a straight
line in one of eight selected "compass directions" |
Dired |
Provides file manager like functions for copying, deleting, and renaming files, and
many more |
View |
Provides read-only file access; for use with dired mode |
Shell |
Allows executing a UNIX shell within an Emacs buffer; you can edit the command
line with all Emacs capabilities |
Mail |
Assists with formatting and sending e-mail over the internet |
RMAIL |
For reading and managing e-mail you receive |
Telnet |
For using telnet from within Emacs to log into another system |
Ange-ftp |
Extends Emacs find-file command to work with ftp to find files over the
internet |
FORTRAN |
Assists with editing and formatting FORTRAN source code |
C |
Assists with editing and formatting C source code |
C++ |
Assists with editing and formatting C++ source code |
LISP |
Assists with editing and formatting LISP source code |
Minor modes can be toggled on or off individually. They act independently of one
another. The simplest example of a minor mode may be overwrite mode, which is used
to overwrite existing text. (Normally Emacs inserts new text into the buffer.)
Overwrite mode is toggled into by pressing the Ins key, or by using the ESC x
overwrite-mode RETURN sequence. Because this mode is a toggle, it is deactivated
by entering the command and second time.
The most important minor modes are described in Table 3.25.
Table 3.25. The most important Emacs minor
modes.
Minor Mode |
Description |
Abbrev |
Enables the word abbreviation feature (similar to vi abbreviations) |
Auto-fill |
Enables word wrap (similar to vi wrapmargin setting) |
Auto-save |
Enables automatic timed saving of your work |
Line number |
Display line numbers (similar to vi number setting) |
Overwrite |
Entered text types over existing text, rather than being inserted |
VC |
Provides an interface to several version control systems |
Completion Emacs implements a feature known as completion.
This very helpful feature can save a lot of time so you are strongly encouraged to
experiment with it. Completion is used when you are required to enter a string of
text in the mini-buffer, either to give a long command name, or to enter a file name.
In either case, after a portion of the string is entered, you can press the TAB
key and Emacs will automatically complete the entry of the full
name! (So the long commands are not so burdensome after all!) Or the rest of the
file name is provided!
When Emacs cannot fully resolve the command or file name, a menu of choices
is provided from which you may select your choice.
Emacs Is An Environment
The attractiveness of Emacs is largely from the degree of integration
that it offers. Emacs includes within in numerous features and functions
which are often provided in separate programs. By having all these programs integrated
into one, you may develop a working style that offers greater convenience and simplicity
than having to use a lot of tools separately.
Emacs has so many built-in features and extensions, that it is impossible
to cover them all within the scope of this chapter. Therefore, the coverage from
this point forward is intended to give you an overview of the many features, and
to convince you of the power of the program.
Moving Around and Simple Editing
One of the most user-friendly features of Emacs is that is has a built-in
help system, which includes a tutorial! The tutorial is geared for the complete novice
and is nicely done. So rather than present complete keystroke-by-keystroke details
as to the basic tasks of editing in Emacs, the best service I can
give you here is to point you towards this tutorial. The tutorial is entered by typing
the command sequence C-h t. Other elements of the Emacs help system
are covered later.
The Most Important Navigation Keys
Even in simple moving around there are differences between the Emacs
looks at the world and the way vi does. Movement forward and backward by
characters in vi is restricted to a single line. When you get to the end
of the line, and try to go farther, all you will get is a beep. Emacs is
a little more friendly here. When you attempt to go off the end of a line, Emacs
obligingly moves the cursor to the beginning of the next line. When you attempt to
off the beginning of a line, the cursor is likewise positioned to the end of the
previous line.
The most important navigation commands are as shown in Tables 3.26 and 3.27 following.
In these tables, the commands are separated into two subcategories to help you get
familiar with the way commands are structured. So-called "physically-oriented"
commands in Table 3.26 are oriented towards physical elements of the text: characters,
lines, screens, pages, and buffers. So-called "lexically-oriented" in Table
3.27 commands are oriented toward lexical (or language-related) elements of the text:
words, sentences, paragraphs. (If this distinction escapes you, no big deal--just
ignore it!)
Table 3.26. Physically-oriented movements.
Binding |
Function Name |
Move |
C-f |
forward-char |
one character forward |
C-b |
backward-char |
one character backward |
C-n |
next-line |
next line |
C-p |
previous-line |
previous line |
C-a |
beginning-of-line |
beginning of line |
C-e |
end-of-line |
end of line |
C-v |
scroll-up |
next screen |
ESC v |
scroll-down |
previous screen |
C-x] |
forward-page |
one page forward |
C-x[ |
backward-page |
one page backward |
ESC > |
end-of-buffer |
end of buffer |
ESC < |
beginning-of-buffer |
beginning of buffer |
Table 3.27. Lexically-oriented movements.
Binding |
Function Name |
Move |
ESC f |
forward-word |
one word forward |
ESC b |
backward-word |
one word backward |
ESC a |
forward-sentence |
beginning of sentence |
ESC e |
backward-sentence |
end of sentence |
ESC } |
forward-paragraph |
one paragraph forward |
ESC { |
backward-paragraph |
one paragraph backward |
The Most Important Editing Procedures
The most important editing procedures involve working with files and with the
procedures for deleting text, cutting and pasting text, and undoing edits.
Working with Files Before you can do much editing, you will need to know
the commands that Emacs uses to manipulate files. Table 3.28 following shows
the most important commands for working with files.
Table 3.28. Emacs file commands.
Binding |
Function Name |
Description |
C-x C-f |
find-file |
Open a file and load |
C-x C-v |
find-alternate-file |
Look for a different file |
C-x i |
insert-file |
Insert a file into the buffer |
C-x C-s |
save-file |
Write (save) buffer to original file (see caution below) |
C-x C-w |
write-file |
Write (save) buffer as file (defaults to original file) |
Caution: Note that you may have trouble using
the C-x C-s command if your terminal communications environment is using
XON/XOFF flow control. In such a case, the C-s key (also known as "XOFF")
is interpreted by the communications software to mean "stop sending characters."
If you press this key, your terminal will appear to freeze up. The corresponding
keystroke needed to re-enable communications to your terminal is the C-q
key (also known as "XON"), which in Emacs is normally the quoted-insert
function (which allows the following keystroke typed to be inserted into the text
rather than interpreted as a command).
Because of this very common situation, Emacs also provides the flow-control
command, which is executed as ESC x flow-control, which when invoked, causes
the functions normally bound to C-s and C-q to be replaced with
C- and C-^. That is, when flow_-control is in effect,
the command for saving a file is C-x C-; the command for quoted-insert
is C-^.
Deleting Text There are several simple delete commands. The DEL
key will delete the character to the left of the point. C-d will delete
the character the cursor is on (that is, to the right of the point). ESC d
will delete the next word.
Caution: The action of the DEL key is
similar to the action of the backspace key in many word processing programs. However,
the backspace key is usually bound to the character used to invoke the Emacs
help system. If you press the backspace key inadvertently and your screen is split
in a way you did not expect to open the help buffer, press C-g (quit) to
get back.
To delete the line the cursor is on use the C-k command.
This command operates in an unusual way. The first time C-k is pressed,
the text on the line the cursor is on is deleted, leaving a blank line. It takes
a second C-k command to delete the blank line.
To delete a particular portion of your text that is not a specific text element
such as a word, sentence, or line, you can use the mark command to mark a region
of text upon which to operate. The mark command C-@ (or alternatively C-SPACE)
is used as follows: first position the cursor to one end of the region you wish to
mark. Press one of the mark commands. Then move the cursor to the other end of the
region. From this point, any command that operates on a region will take effect on
all the text between the mark point and the current cursor position. For example,
to delete the text in the marked region, use the C-w (or alternatively SHIFT-DEL)
command.
The commands shown in Table 3.29 are used to delete text.
Table 3.29. Delete commands.
Binding |
Function Name |
Description of text deleted |
DEL |
delete-backward-char |
character to left of point (the one just typed) |
C-d |
delete-character |
the character the cursor is on |
C-k |
kill-line |
the line cursor is on |
ESC d |
kill-word |
the next word |
ESC DEL |
backward-kill-word |
the previous word |
ESC k |
kill-sentence |
the next sentence |
C-x DEL |
backward-kill-sentence |
the previous sentence |
C-@ |
set-mark-command |
mark one end of a region |
C-SPACE |
set-mark-command |
mark one end of a region (same as C-@) |
C-w |
kill-region |
marked region |
SHIFT-DEL |
kill-region |
marked region (same as C-w) |
Recovering Deleted Text: Cutting and Pasting There are two ways to get
back text that has been deleted: (1) yanking from the kill ring; (2) the Emacs
undo function.
Caution: There are some terminology differences
between Emacs and vi. vi calls its buffers where deletions
are kept the undo buffers. Emacs calls its equivalent the kill buffers.
In Emacs, a yank is conceived in the opposite way as it is in vi.
In vi, a yank will copy from your text to an undo buffer; in Emacs,
a yank is the reverse action of copying from the kill buffer back to the text.
Emacs keeps all killed text in internal buffers called the kill ring.
Text that is deleted, not killed is not saved in the kill ring. For example,
single characters deleted with DEL or C-d are not saved there.
To recover recently deleted text from the kill ring, you use two commands together.
First you must perform a yank with the C-y command (SHIFT-INS
is a synonym). This command will yank back the most recent deletion. If this is not
the deleted text you want, successive uses of the ESC y command
will recover the previous deletions in order, similar to the vi sequence
of the "np command followed by the repeat (.) command.
The first time ESC y is used, the first previously killed text is inserted.
The next ESC y replaces the yanked text with the next most recent deletion.
(After you have gone back to the limit of the number of deletions saved, the most
recent deletion is yanked in. That is where the term ring comes from. The initial
default size of the kill ring is 20.) Once you get used to the actions of these commands,
it becomes simple to rearrange text by a series of kill commands followed by yank
commands.
The yank commands are shown in Table 3.30.
Table 3.30. Yank commands.
Binding |
Function Name |
Description |
C-y |
yank |
Insert text from the start of the kill ring |
ESC y |
yank-pop |
Replace yanked text with previous kill |
Another Method of Deleting and Pasting As you can see from the discussion
of the delete and yank commands, one of the simplest ways of moving text around in
Emacs is via the menu commands for select and paste. When you use this command,
a window is displayed with the first line of each of the most recent deletions. You
can paste into your text any one of the displayed choices.
Undoing Edits The Emacs undo functions are very powerful. Repeated
applications of the undo function C-x u (or alternatively, C-_
or C-, unless you have remapped this binding) will successively undo each
edit you have done, eventually taking you back to the beginning of your editing session!
The undo function will undo every editing change, not just deletions.
You can also redo edits that you have undone. To redo one of the edits you have
undone, you have to move the cursor, then execute another undo command. Now each
time you undo, you will instead be redoing edits. To switch directions again, just
move the cursor again.
Other Useful Editing Functions
As you would expect there are numerous useful commands in Emacs that
go beyond the most basic editing requirements. Examples of such commands are those
to undo edits, reformat text, transpose text, modify capitalization.
The commands of this section are summarized the Table 3.31.
Table 3.31. Other useful editing commands.
Binding |
Function Name |
Reformat |
ESC q |
fill-paragraph |
paragraph, rewrapping the lines |
Binding |
Function Name |
Transpose |
C-t |
transpose-chars |
two adjacent characters |
ESC t |
transpose-words |
two adjacent words |
C-x C-t |
transpose-lines |
two adjacent lines |
Binding |
Function Name |
Capitalize |
ESC c |
capitalize-word |
first letter of word |
ESC u |
upcase-word |
uppercase whole word |
ESC l |
downcase-word |
lowercase whole word |
Binding |
Function Name |
Repeating Commands |
ESC x |
digit-argument |
repeats the next command x times, where x is a whole number |
C-u |
universal-argument |
repeats the next command 4 time; often used in a series (C-u C-u for 16
repetitions, C-u C-u C-u for 64 repetitions, and so on) |
C-u x |
|
repeats the next command x times (same as ESC x) |
Command Reference Tables
In this section, the most important editing commands are summarized. Please note
that the commands presented here in Tables 3.32 and 3.33 only scratch the surface
of Emacs. No commands are shown that are particular to the specialized modes
listed in Tables 3.24 and 3.25. (Some of the modes have literally dozens and dozens
of their own specialized commands and operations.)
Navigation Commands
Table 3.32. Command reference summary: navigation.
Binding |
Function Name |
Move (Physical) |
C-f |
forward-char |
one character forward |
C-b |
backward-char |
one character backward |
C-n |
next-line |
next line |
C-p |
previous-line |
previous line |
C-a |
beginning-of-line |
beginning of line |
C-e |
end-of-line |
end of line |
C-v |
scroll-up |
next screen |
ESC v |
scroll-down |
previous screen |
C-x] |
forward-page |
one page forward |
C-x[ |
backward-page |
one page backward |
ESC > |
end-of-buffer |
end of buffer |
ESC < |
beginning-of-buffer |
beginning of buffer |
Binding |
Function Name |
Move (Lexical) |
ESC f |
forward-word |
one word forward |
ESC b |
backward-word |
one word backward |
ESC a |
forward-sentence |
beginning of sentence |
ESC e |
backward-sentence |
end of sentence |
ESC } |
forward-paragraph |
one paragraph forward |
ESC { |
backward-paragraph |
one paragraph backward |
Binding |
Name |
Description |
C-x C-f |
find-file |
Open a file and load |
C-x C-v |
find-alternate-file |
Look for a different file |
C-x i |
insert-file |
Insert a file into the buffer |
C-x C-s |
save-file |
Write (save) buffer to original file (see caution below) |
C-x C-w |
write-file |
Write (save) buffer as file (defaults to original file) |
Editing Commands
Table 3.33. Command reference summary: editing.
Binding |
Function Name |
Delete |
DEL |
delete-backward-char |
character to left of point (the one just typed |
C-d |
delete-character |
the character the cursor is on |
C-k |
kill-line |
the line cursor is on |
ESC d |
kill-word |
the next word |
ESC DEL |
backward-kill-word |
the previous word |
ESC k |
kill-sentence |
the next sentence |
C-x DEL |
backward-kill-sentence |
previous sentence |
C-@ |
set-mark-command |
mark one end of a region |
C-SPACE |
set-mark-command |
mark one end of a region (same as C-@) |
C-w |
kill-region |
marked region |
SHIFT-DEL |
kill-region |
marked region (same as C-w) |
Binding |
Function Name |
Description |
C-y |
yank |
Insert text from the start of the kill ring |
ESC y |
yank-pop |
Replace yanked text with previous kill |
Binding |
Function Name |
Reformat |
ESC q |
fill-paragraph |
paragraph, rewrapping the lines |
Binding |
Function Name |
Transpose |
C-t |
transpose-chars |
two adjacent characters |
ESC t |
transpose-words |
two adjacent words |
C-x C-t |
transpose-lines |
two adjacent lines |
Binding |
Function Name |
Capitalize |
ESC c |
capitalize-word |
first letter of word |
ESC u |
upcase-word |
uppercase whole word |
ESC l |
downcase-word |
lowercase whole word |
Advanced Editing: Tips and Techniques
In this section, I will introduce some of the powerful things you can to do with
Emacs.
Search and Replace
Emacs has an abundance of different ways in which you can search for
and replace text. In the following discussion of the various search types, I will
use the term target to refer to both the text that you are looking for, as well as
the matching text that Emacs has found. I use the term replacement to refer
to the replacement string that you wish to substitute for the target. The following
are the five different search methods you can use:
- 1. Simple search. This type of search is the easiest to understand. Emacs
will look for a fixed string of characters, placing the cursor after the first matching
string is one is found.
To execute a simple search, the command C-s RETURN target RETURN is used. The search
may be repeated by simply entering C-s. To search backward, the command _C-r
RETURN target RETURN is used. To search backward again, just enter C-r.
To use the simple search with replacement of all text found with a replacement string,
use the command ESC x replace-string RETURN target RETURN replacement
RETURN, where the text replace-string is literally typed as it is the
name of the command.
In many cases, it is not a good idea to use the simple search and replace method
for replacing text, as such an action on any substantial amount of text will invariably
result in making numerous replacements that are not wanted. For example, in a contract
referring to the authorship of a work for hire, you might want to change all references
to the author into references to the contractor. If there are other uses of the string
author in the buffer, such as the word authority, you would end
up with the word contractority, clearly not what you desire.
2. Query-replace. The query replace overcomes the some of the problems
of the simple search and replace. As you might have guessed, the query search operates
by asking for your permission before making each replacement. To execute a query-replace,
enter the command ESC %. You are then prompted in the mini-buffer for a
search string. Enter the search string and press RETURN. Next you are prompted
for a replacement string. Enter the replacement string and again press RETURN.
When Emacs finds a match, you are then prompted as to your desired action.
You have many choices after each match has been found. Table 3.34 shows the responses
you may make.
Table 3.34. Query-replace responses.
Response |
Meaning |
y |
Replace and find next |
SPACE |
Replace and find next (same as y) |
n |
Do not replace; find next |
DEL |
Do not replace; find next (same as n) |
. |
Replace and quit searching |
, |
Replace but show the result before continuing search (requires confirmation before
continuing) |
! |
Replace all without further prompting |
q |
Quit query-replace |
RETURN |
Quit query-replace (same as q) |
A wonderful feature that Emacs provides as part of query-replace is the
ability to temporarily suspend the search and replace operation to allow you to do
some editing. This feature is called a recursive edit. I have numerous times hankered
after this feature while using various other editors.
In fact, I could almost state it as a rule, that just about every time I have
to execute a search and replace in a document of any size at all, that during the
query-replace type of operation, I see something near a found target string that
I want to edit. So without having the recursive edit feature, I either have to try
to remember to come back to the point in question later, which will then often not
occur, or I have to abandon the query-replace and restart it later.
The commands needed in conjunction with the recursive edit feature are shown in
Table 3.35.
Table 3.35. Recursive edit commands (only available
during query-replace).
Binding |
Action |
C-r |
Begin a recursive edit |
C-w |
Delete the target string and begin a recursive edit |
ESC C-c |
End the recursive edit and resume the query-replace |
C-] |
End both recursive edit and query-replace |
- 3. Incremental search. An incremental search is a feature
that is unique among text editors, although it is often implemented in applications
that provide some sort of list box processing or table lookup functions. An incremental
search takes place on-the-fly as you type in the target string. The way this works
is as follows: after invoking an incremental search command you start typing in the
characters of the search string. You type the first letter and Emacs searches
for the first matching target to that letter. You type the next letter, and Emacs
searches further for the first matching target to the two letters you have typed
so far. This process continues until Emacs has either found the target you
are seeking, or no such match exists.
To execute an incremental search, use the C-s command. Then start typing
in the characters of the target string. If you find the target string you are seeking,
press RETURN and the search will stop. You can continue searching for more
matching targets without typing in the search string again, by just entering the
C-s command again.
NOTE: Searching again for the same target
is done via the C-s command whether the original search was a simple search
or an incremental search. Once Emacs has located the target, the repeated
search action no longer depends upon how the original search was performed.
If the immediately prior action was a search, then C-s (or C-r
for a reverse search) will immediately jump to the next target. If there were intervening
commands, such as cursor positioning, the C-s (or C-r) will have
to be entered twice: once to start the search, and the second time to tell Emacs
to use the same target as the last search.
One advantage to an incremental search it that you may find the target you are
seeking without having to type the whole string. The commands needed with an incremental
search are listed in Table 3.36.
Table 3.36. Commands needed for incremental searching.
Binding |
Function Name |
Action |
C-s |
isearch-forward |
Begin incremental search forward |
C-r |
isearch-backward |
Begin incremental search backward (reverse) |
DEL |
|
Remove last character typed from search string (search backs up to previous matching
target) |
RETURN |
|
Quit incremental search after finding target |
C-g |
|
Quit incremental search while it is in progress |
- 4. Word search. A word search is another special type of search.
A word search will only match a complete word or phrase, ignoring spaces, punctuation,
and line breaks. You can use it to avoid the type of problem described previously
that simple searching has. A word search is the only search type that can wrap around
lines because it ignores line breaks. Because the other search types are confined
to a single line, they will often miss the target if a phrase is the target because
the target might be spread over two lines. To perform a word search, enter the command
C-s RETURN C-w target RETURN, where target is a word or a
phrase.
5. Regular expression searches. I introduced the topic of regular expressions
while discussing their use in vi. You can use this powerful tool in your
Emacs search and replace operations as well. Regular expressions can be
used with query-replace searches and incremental searches and also in a global form
to affect the whole buffer with no prompting. The commands to execute regular expression
searches are shown in Table 3.37.
Table 3.37. Commands for regular expression search and
replace.
Binding |
Function Name |
Action |
ESC C-s RETURN |
re-search-forward |
Search forward for a regular expression |
ESC C-r RETURN |
re-search-backward |
Search backward for a regular expression |
query-replace-regexp |
|
Query-replace for a regular expression |
ESC C-s |
isearch-forward-regexp |
Incremental search forward for a regular expression |
ESC C-r |
isearch-backward-regexp |
Incremental search backward for a regular expression |
(none) |
replace-regexp |
Search and replace using regular expressions |
Using Multiple Buffers
The relationship of files and buffers, which were discussed in the introductory
section of this chapter entitled "Full-screen Editors versus Line Editors,"
applies to Emacs. In that section, I used the terms buffer, cursor,
viewport, and window to describe how to think about your file and the
display on your screen.
In Emacs, these concepts are more fully developed than in vi.
Emacs has the ability to maintain several buffers in memory at the same
time. You can easily switch back and forth between several buffers to edit more than
one file at a time. Further, you can display several buffers at the same time on
your screen, each in its own window. When you use the Emacs help function,
you are in fact using this capability. The following example shows how a screen with
two buffers displayed in separate windows might look:
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.'
-----Emacs: art1 (Text)--All--------------------------------------
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.'
-----Emacs: art1 (Text)--All--------------------------------------
This function becomes more powerful as you use it in your own way. The following
are some of the most useful things you can do with multiple window displays: (1)
load a secondary text not to edit but for reference purposes; (2) easily copy and
paste sections of text between several files; (3) compare the text of two or more
files. There are special commands in Emacs that enhance your ability to
perform these tasks.
Working with Buffers
When you load a file with C-x C-f when you already have an open buffer,
Emacs creates a new buffer for the file that you are loading. It does not
lose the original buffer. You can change between buffers using the buffer command
C-x b. This command allows you to choose by name the buffer you want to
switch to. The name of the buffer is the name that is displayed on the status line
and is usually the name of the file that you are editing. Or you can create a new
buffer that is not associated with a file by using a new name. You can also use completion
with the buffer command (type a few characters of the name and press TAB;
Emacs will either complete the buffer name or give you a menu of choices).
Table 3.38 following shows the most important commands for working with buffers.
Table 3.38. Commands for working with buffers.
Binding |
Function Name |
Action |
C-x b |
switch-to-buffer |
Switch to the selected buffer |
C-x C-b |
list-buffers |
Open a the buffer list window |
C-x k |
kill-buffer |
Delete the current buffer |
C-x s |
save-some-buffers |
Buffer by buffer prompt to save each buffer |
A powerful way to work with buffers is through the buffer list. You can use the
buffer list to manipulate buffers via a set of commands that are active when the
buffer list is the active window. The following example shows what your screen might
look like when the buffer list is displayed.
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.'
-----Emacs: art1 (Text)--All--------------------------------------
MR Buffer Size Mode File
-- ------ ---- ---- ----
. art1 576 Text /home/jas/art1
*scratch* 0 Fundamental
* *Buffer List* 180 Fundamental
--%%-Emacs: *Buffer List* (Buffer Menu)--All-------------------------------
Working with Windows
When you have more than one window visible on your Emacs editing screen,
there are certain properties which pertain to each window. There is only one cursor
in an Emacs session; it can be in only one window at a time. The window
that contains the cursor is said to be the active window. However, each buffer maintains
its own point. So when you switch between different windows, the cursor will appear
at the point in that buffer where you last working.
You can use both vertical and horizontal windows in Emacs, and combinations
of both. The following example shows three windows, with one horizontal split and
one vertical split, with the same sample text in each window:
If wise, a commander is able to $| If wise, a commander is able to$
act expediently. If sincere, his men $|act expediently. If sincere, his men$
rewards and punishments. If humane, h$|rewards and punishments. If humane, $
and appreciates their industry and toi$|and appreciates their industry and to$
seizing opportunity without hesitation$|seizing opportunity without hesitatio$
because they are in awe of him and are$|because they are in awe of him and ar$
Shen Pao-hsu ... said: 'If a gen$| Shen Pao-hsu ... said: 'If a ge$
to conquer doubts or to create great p$|to conquer doubts or to create great $
|
|
|
-----Emacs: art1 (Text)--A -----Emacs: art1 (Text)--A
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.'
-----Emacs: art1 (Text)--All--------------------------------------
Table 3.39 shows the most important commands to work with windows.
Table 3.39. Commands to work with windows.
Binding |
Function Name |
Action |
C-x 2 |
split-window-vertically |
Splits the current window into two windows, one on the top and one on the bottom,
with each taking the full width of the current window |
C-x 3 |
split-window-vertically |
Splits the current window into two windows, one on the top and one on the bottom,
with each taking the full width of the current window |
C-x o |
other-window |
Switch to "next" window (clockwise) |
C-x 1 |
delete-other-windows |
Make the current window the only window |
C-x 0 |
delete-window |
Delete the current window (redraw others) |
C-x > |
scroll-right |
Scroll the contents of the current window right |
C-x < |
scroll-left |
Scroll the contents of the current window left |
(none) |
compare-windows |
Compare the contents of the buffers associated with the current window and the next
window (clockwise); cursor will stop at the next difference |
Bookmarks to Mark Your Position
Emacs provides a bookmark function that goes far beyond the text marking
capabilities of vi. When you set up a bookmark, Emacs creates a
file in your home directory in which to keep a permanent record of all of your bookmarks.
Each bookmark keeps track of the full path and name of the marked file and the marked
position in that file. Thereafter, each time you start an Emacs session,
this bookmark file is loaded. You can use a special set of commands to find any of
the points in any of the files you have been working with. When you are working on
a large project or dealing with multiple buffers, this full-featured bookmark capability
can become a great time-saver.
Emacs allows you to work with your bookmark list with a similar interface
as provided to work with buffers: you can display the bookmark list in a window,
then issue specialized commands to directly manipulate the bookmarks. Once again,
you can use the Emacs completion feature to select a bookmark (type a few
characters of the name and press TAB; Emacs will either complete
the bookmark name or give you a menu of choices). Table 3.40 shows the most important
commands for working with bookmarks and the bookmark list.
Table 3.40. Commands for working with bookmarks.
Binding |
Function Name |
Action |
C-x r m |
bookmark-set |
Record the current cursor position as a bookmark |
C-x r b |
bookmark-jump |
Jump to the bookmark |
C-x r l |
bookmark-menu-list |
Display the bookmark list (various subcommands are available) |
Formatting for Various Languages
Emacs provides programmers with assistance in writing source code. There
are a number of major modes for common computer languages. Some of the well-known
(and obscure) languages that Emacs supports with built-in modes are Assembly,
AWK, C, C++, FORTRAN, LISP, modula-2, Pascal, Perl, Prolog, Scheme, and SGML.
The types of features Emacs offers for each language differs. In general,
Emacs "understands" the syntax of the language in a very basic
way. When Emacs is in text mode, it recognizes the boundaries of certain
text structures such as words, sentences, and paragraphs, so that cursor movement
commands can be executed and so forth. In the same way, when in one of the language
modes, Emacs recognizes the basic building blocks of that language. These
building blocks are such language elements as identifiers, grouping symbols, terminators,
and so on. When Emacs recognizes such an element, the mode is set up to
perform a suitable action, such as automatically inserting a line feed, or indenting
a specified amount.
One of the main features of each language is help with setting the indent for
various code blocks and sub-blocks. While in C mode, for example, there are even
options for formatting according to several different styles (namely, GNU, K&R,
BSD, Stroustrup, Whitesmith, and Ellemtel). Or if you are handy with the LISP language
(in which Emacs is implemented) you can modify and extend these modes to
implement your own personal coding style.
Emacs as an Integrated Development Environment
To assist programmers even further, Emacs provides additional support
in the form of an integrated development environment. The main components of this
support are an interface to the make facility, the ability to execute a
compiler in a window, the ability to manipulate the error output of the compiler
to jump to the point of the error in the source file, and the ability to execute
a shell in a window, for testing and general utility purposes. There are several
commands that work in connection with each of these features.
A special feature that will be of interest to C and C++ programmers is the etags
facility. This facility is similar to the tags function of vi,
described in the vi section. The purpose of this facility is to use a database
of source code file names and program function names that was created by the separate
etags program. As usual, the Emacs version of this
feature is more powerful than the equivalent function used within vi--there
are more commands that can be used to work with the tags.
Using Emacs as an Environment
I hope by now you are convinced that Emacs provides a full array of tools
that cover nearly all aspects of anything to do with text. In case you are not convinced,
this section is going to cover yet additional facilities tightly integrated into
Emacs. Giving a thorough enough description to actually show you
how to use these tools is beyond the scope of this chapter. I hope that the richness
of Emacs as an environment is sufficient to tempt you into trying it out
for yourself.
In this section, I will describe some of the extension of Emacs into
a wide variety of tools. This section is by no means comprehensive, but merely a
sampling.
Using Emacs as a File Manager
The dired ("directory editor") mode was listed in Table 3.24 as one
of the major modes of Emacs. This mode can be started in several
ways. One way is to start Emacs with the name of a directory instead of
a file. A second way is to use the usual find-file command, but to supply
a directory name instead of a file name. The third way is to directly issued the
dired command by typing C-x d, then providing a directory name.
When you are in dired mode, the buffer appears similar to the output of the ls
command. From this buffer you can perform many file-related actions. You can copy,
move, delete, rename, compress, view, and edit individual files. You can create directories.
You can execute other UNIX commands on files. You can also mark a set of files for
these same manipulations. You can select files for manipulation using regular expressions.
It is often when operating on such sets of files that the greatest productivity gains
occur. For example, you can query-replace on a set of files all at once.
While it is true that you cannot do anything under dired mode that you could not
do by individually executing shell commands, I can definitely state as one who has
had long experience with both shell operations and using the dired file manager-like
methods, that there can be a great gain in productivity, depending upon your working
style. I routinely run into situations where an operation that otherwise would have
taken hours is reduced to minutes.
Using Emacs with Shell Buffers
Shell mode in Emacs can be explained quite simply. After starting a shell
buffer by entering the command ESC x shell, Emacs opens up buffer
in which you can execute normal UNIX shell commands. However, Emacs provides
the ability to use many of its editing capabilities on text you are entering, including
the completion feature, and screen history-like functions (the ability scroll back
through a "transcript" of your shell session to examine the output of commands,
and even to re-execute commands that are in the buffer without retyping them).
One of the best hidden treasures of Shell mode is the ability to be running multiple
simultaneous visible shell sessions, while also keeping the output of each session
from interfering with each other. In fact, before X-windows became popular, many
Emacs users had similar functionality just by using the Emacs shell
mode.
Using Emacs like a Word Processor
In addition to being a pretty good text editor, Emacs also can dress
up your documents somewhat when you want it to. Although not presuming to be a real
word processor, you can perform a limited set of simple formatting tasks. These tasks
include working with fonts and colors on your screen, alignment of text, indentation
of text, adding page breaks, working with columns, and working with outlines.
Using Emacs to Markup Text
With the World Wide Web gaining such widespread adoption, the concept of a markup
language has become more widely known. The language of the Web is HTML, which stands
for HyperText Markup Language. HTML is a form of text that contains ASCII characters
as well as special tags, which are interpreted by a browser to produce quite a polished
effect, depending upon the capabilities of the browser. The special tags have a fairly
simple structure. You could use any standard editor to create an HTML documents;
however, when an editor is extended to understand the HTML tags, it can help you
to get the job done more easily.
There are major modes and packages that implement HTML and other types of markup
languages. The common ones provided with Emacs are for troff
(the standard UNIX text formatter) and nroff (a version of troff
for character-based terminals), TEX, and LATEX.
Using Emacs with the Internet
There are several internet activities for which Emacs provides direct
support. You can use Emacs as an operating environment with features that
interface directly to e-mail, both sending, receiving and managing your correspondence.
You can use Telnet from within Emacs to log on to another system
and keep a transcript in an Emacs buffer of your session; you can extend
the find-file command with Ange-ftp mode to work with FTP to find and download
files. You can also use the Gnus newsreader (a separate program) directly from within
Emacs through the built-in interface.
Abbreviation Mode
As was hinted at in the section on minor modes, there is an abbreviation feature
in Emacs that can be enabled. The uses of this mode were covered in the
vi section, so I will do no more than briefly mention that Emacs
has such a mode, with a few more features than vi.
To enable the abbreviation mode, use the command ESC x abbrev-mode RETURN.
To set up an abbreviation, first type the abbreviation you want to use into your
text, then enter the command C-xaig. When Emacs asks you for the
expansion, type the full text that you wish to have inserted when you type the abbreviation,
then press RETURN. The abbreviation you just typed is expanded. It will
be expanded every time you type it followed by a space or punctuation mark.
Using Macros
Emacs provides a complete macro facility. An Emacs macro is a series
of keystrokes that are recorded for later playback. By playing back keystrokes, you
can accomplish a series of repetitive tasks quite easily. Many editors and word processors
provide a macro facility. The Emacs capability is especially powerful,
because virtually any series of keystroke and commands can be used. You can then
multiply the number of times the macro is executed by preceding the command with
one of the multiplier commands, such as C-u to repeat the macro four times,
or C-u C-u to repeat it 16 times, and so on.
There are two ways to execute a macro. You can either execute the most recently
recorded macro (the current macro), with the C-x e command. Or you can name
your macros and execute them by name. To name a macro, use the name-last-kbd-macro
function (there is no standard key binding for this command). When you record
macros, they are available only during the current Emacs session.
(The current macro is only available until you record another one; so if you want
to keep it around, you will have to name it as just described, so that you can record
another one.)
To make your macros permanent, you have to save them in a file. You can either
save them in a special file which you can then explicitly load when you desire to
use the macros it contains, or you can set them up to load automatically every time
you start Emacs (see the following section, "Configuring Emacs
to your Tastes").
The commands used for working with macros are shown in Table 3.41.
Table 3.41. Commands for working with macros.
Binding |
Function name |
Action |
C-x ( |
start-kbd-macro |
Begin recording a macro |
C-x ) |
end-kbd-macro |
End recording a macro |
C-x e |
call-last-kbd-macro |
Play back the current macro |
ESC n C-x e |
digit-argument |
Play back the current macro n times followed by call- last-kbd-macro |
(none) |
name-last-kbd-macro |
Assign a name to the current macro |
(none) |
insert-last-kbd-macro |
Write the last named macro into a file |
(none) |
macroname |
Play back the macroname macro |
(none) |
load-file |
Activate all the macros in the specified file |
Configuring Emacs to Your Tastes
As I am sure you have guessed by now, Emacs is extensively customizable.
The primary types of customization are (1) to create your own key bindings for functions
that have no standard bindings but you find that you are using frequently; or (2)
to remap function keys provided by your terminal to common Emacs functions.
Both of these customizations are effected through the use of the .emacs
file in your home directory.
For example, to bind the help function to the sequence C-x ? and to bind
the backspace function to C-h, you could enter the following in your .emacs
file (note the pair of double quotes and the single appearance of the single quote):
(global-set-key "C-x?" 'help-command)
(global-set-key "C-h" 'backward-char)
Another type of customization that is beyond the scope of this chapter is to actually
add functions to Emacs via coding in Emacs LISP,
which is the implementation language for Emacs (only the most basic
part of Emacs is written in C; the rest is written in Emacs LISP).
With this latter approach you could truly say that Emacs is infinitely flexible.
Command Summary
For your convenience, this section provides a quick reference of the major commands
for vi in Table 3.42 and for Emacs in Table 3.43. For explanations
of the symbols and conventions used in the tables, please refer to the text accompanying
Tables 3.7, 3.8, 3.9, 3.32, and 3.33.
Table 3.42. Quick Reference to vi 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 next big word |
( |
to beginning of previous sentence |
) |
to beginning of next sentence |
{ |
to beginning of previous paragraph |
{ |
to beginning of next paragraph |
[[ |
to beginning of next section |
]] |
to beginning of previous section |
Screen Redrawing |
Command |
Result |
z |
redraws screen with current line at top of the screen |
z- |
redraws screen with current line at bottom of the screen |
z. |
redraws screen with current line at center of the screen |
Positioning by Pattern Searching |
Command |
Result |
/pattern |
moves to next line containing pattern |
?pattern |
moves to previous line containing pattern |
/ |
repeats last search forward |
? |
repeats last search backward |
n |
repeats last search in same direction |
N |
repeats last search in opposite direction |
/pattern/+nbr |
to nbr lines after next line containing pattern |
?pattern?-nbr |
to nbr lines before previous line containing pattern |
/pattern/z- |
redraws screen with next line containing pattern at bottom of the
screen
(other z options will give the corresponding positioning) |
% |
to parenthesis or brace matching the one at the current cursor position |
Positioning to Marked Text Locations |
Command |
Result |
mchar |
marks the current cursor position with the letter char |
'char |
to mark specified by char |
'char |
to beginning of line containing mark specified by char |
'' |
to previous location of the current line (after a cursor movement) |
'' |
to beginning of line containing previous location of current line (after a cursor
movement) |
Inserting Text |
Command |
Result |
i |
inserts text before the cursor |
I |
inserts text before first non-blank character of line |
a |
inserts text after the cursor |
A |
inserts text at the end of the line |
o |
adds an empty line below the current line and enters insert mode there |
O |
adds an empty line above the current line and enters insert mode there |
Changing Text While in Insert Mode |
(Note: These commands are only available while in insert mode.) |
Command |
Result |
^H |
backspaces and erases the previous character (only since insert began) |
^W |
backspaces over and erases the previous small word (only since insert began) |
|
quotes the erase and kill characters |
Esc |
ends insert mode and go back to command mode |
^D |
back to previous auto-indent stop |
^^D |
(caret followed by Ctrl-D) no auto-indent on current line only |
0^D |
moves cursor back to left margin |
^V |
enters any character into text (do not interpret control characters) |
Changing Text |
Command |
Result |
cobject |
changes the text object to the text inserted until the Esc key is pressed |
C |
changes the rest of the line to the text insert until the Esc key is pressed (same
as c$) |
cc |
changes the whole line to the text inserted until the Esc key is pressed |
rchar |
replaces the character the cursor is on with char; then return to command
mode |
R |
overwrites text until the Esc key is pressed; if you go past the end of the line,
append new text to the end of the line |
s |
substitutes characters (same as cl) |
S |
substitutes lines (same as cc) |
Deleting Text |
Command |
Result |
x |
deletes the character under the cursor |
X |
deletes the character before the cursor |
dobject |
deletes the text object |
D |
deletes the reset of the line (same as d$) |
dd |
deletes the line |
Using Buffers |
Command |
Result |
u |
undo the last change |
U |
restores the current line to the state it was in when the cursor was last positioned
to it |
yobject |
places the text of the object into the undo buffer |
yy |
places the line the cursor is on into the undo buffer |
Y |
places the line the cursor is on into the undo buffer (same as yy, which
is a departure from the pattern set up by C and D) |
p |
inserts the text in the undo buffer after the cursor |
P |
inserts the text in the undo buffer before the cursor |
"letterdobject |
deletes the object into the letter buffer |
"letteryobject |
yanks (copies) the object into the letter buffer |
"letterp |
inserts the text in the letter buffer after the cursor |
"numberp |
inserts the number-th last delete of a complete line or block of lines |
Other Editing Commands |
Command |
Result |
. |
repeats the last editing command (and increments n in a "np command) |
~ |
changes the case of the letter under the cursor and moves cursor to left one character
(does not support a count in standard vi) |
J |
joins two lines |
>> |
shifts line shiftwidth characters to the right (use :set sw to change
the shiftwidth) |
>L |
shifts all lines from the line the cursor is on to the end of the screen shiftwidth
characters to the right (use :set sw to change the shiftwidth) |
<< |
shifts line shiftwidth characters to the left (use :set sw to change
the shiftwidth) |
<L |
shifts all lines from the line the cursor is on to the end of the screen shiftwidth
characters to the left (use :set sw to change the shiftwidth) |
Saving the Buffer to a File |
Command |
Result |
:w |
writes (saves) the buffer to disk, using the original file name |
:w file |
writes the buffer to disk, to file |
:w! |
writes the buffer to disk, overwriting file |
Exiting Commands |
Command |
Result |
ZZ |
writes the buffer to disk and exits the program |
Q |
enters the ex editor (same as typing :) |
:q |
quit vi, unless you have an unsaved buffer |
:q! |
always quits vi, overriding warning about an unsaved buffer |
:wq |
writes the buffer to disk and exits the program (same as ZZ) |
Editing Other Files |
Command |
Result |
:e file |
edits file, unless you have an unsaved buffer |
:e! |
discards any changes and starts over with the last saved version of the file from
disk |
:e + file |
edits file, unless you have an unsaved buffer; places cursor bottom line |
:e +nbr file |
edits file, unless you have an unsaved buffer; places cursor on line nbr |
:e # |
edits alternate file |
:n |
edits the next file (applies when a list of files was entered on the command line) |
:n file file file |
sets up a new list of files to edit |
:r file |
reads (inserts) contents of file into the buffer on the line below the cursor |
:r !command |
runs the shell command and inserts the output of the command on the line below
the cursor |
^G |
displays information about the current file (filename, current line number, number
of lines in file, percentage through the file) |
:ta tag |
jumps to the file and the location in the file specified by tag (before you
can use this function, you must use the ctags program to create the tags
file. Refer to the section on the :ta command for details.) |
Redrawing the Screen |
Command |
Result |
^L |
redraws the screen (implementation depends upon terminal type) |
^R |
redraws the screen; eliminates blank lines marked with @ (implementation depends
upon terminal type) |
znumber |
sets screen window to number lines |
UNIX Shell Commands |
Command |
Result |
:sh |
executes a shell; remain in shell until shell exit command given (^D) |
:!command |
executes the shell command and returns to vi (after the !
command, certain special characters are expanded. # is expanded to the alternate
file name; % is expanded to the current file name; ! is expanded to
the previous shell command) |
:!! |
repeat the previous shell command |
!object cmd |
execute the shell cmd; replace the text object with the shell cmd
output. If the shell cmd takes standard input, the designated text object
is used. |
nbr!!cmd |
execute the shell cmd; replace nbr lines beginning at the current line
with the shell cmd output. If nbr is missing, 1 is assumed. If the
shell cmd takes standard input, the designated lines are used. |
ex Editing Commands |
Command |
Result |
:vi |
enters visual mode from the ex command line |
:addrd |
delete the lines specified by addr |
:addrmnbr |
move the lines specified by addr after line nbr |
:addrconbr |
copy the lines specified by addr after line nbr |
:addrtnbr |
copy the lines specified by addr after line nbr (same as co
command) |
Table 3.43. Quick Reference to Emacs commands.
Binding |
Function Name |
Move (Physical) |
C-f |
forward-char |
one character forward |
C-b |
backward-char |
one character backward |
C-n |
next-line |
next line |
C-p |
previous-line |
previous line |
C-a |
beginning-of-line |
beginning of line |
C-e |
end-of-line |
end of line |
C-v |
scroll-up |
next screen |
ESC v |
scroll-down |
previous screen |
C-x] |
forward-page |
one page forward |
C-x[ |
backward-page |
one page backward |
ESC > |
end-of-buffer |
end of buffer |
ESC < |
beginning-of-buffer |
beginning of buffer |
Binding |
Function Name |
Move (Lexical) |
ESC f |
forward-word |
one word forward |
ESC b |
backward-word |
one word backward |
ESC a |
forward-sentence |
beginning of sentence |
ESC e |
backward-sentence |
end of sentence |
ESC } |
forward-paragraph |
one paragraph forward |
ESC { |
backward-paragraph |
one paragraph backward |
Binding |
Name |
Description |
C-x C-f |
find-file |
Open a file and load |
C-x C-v |
find-alternate-file |
Look for a different file |
C-x i |
insert-file |
Insert a file into the buffer |
C-x C-s |
save-file |
Write (save) buffer to original file (see caution below) |
C-x C-w |
write-file |
Write (save) buffer as file (defaults to original file) |
Binding |
Function Name |
Delete |
DEL |
delete-backward-char |
character to left of point (the one just typed |
C-d |
delete-character |
the character the cursor is on |
C-k |
kill-line |
the line cursor is on |
ESC d |
kill-word |
the next word |
ESC DEL |
backward-kill-word |
the previous word |
ESC k |
kill-sentence |
the next sentence |
C-x DEL |
backward-kill-sentence |
previous sentence |
C-@ |
set-mark-command |
mark one end of a region |
C-SPACE |
set-mark-command |
mark one end of a region (same as C-@) |
C-w |
kill-region |
marked region |
SHIFT-DEL |
kill-region |
marked region (same as C-w) |
Binding |
Function Name |
Description |
C-y |
yank |
Insert text from the start of the kill ring |
ESC y |
yank-pop |
Replace yanked text with previous kill |
Binding |
Function Name |
Reformat |
ESC q |
fill-paragraph |
paragraph, rewrapping the lines |
Binding |
Function Name |
Transpose |
C-t |
transpose-chars |
two adjacent characters |
ESC t |
transpose-words |
two adjacent words |
C-x C-t |
transpose-lines |
two adjacent lines |
Binding |
Function Name |
Capitalize |
ESC c |
capitalize-word |
first letter of word |
ESC u |
upcase-word |
uppercase whole word |
ESC l |
downcase-word |
lowercase whole word |
Summary
In this chapter two of the most important UNIX text editors have been introduced,
vi and Emacs. The important roles these tools play has been put
into perspective, and quite a bit of detailed instruction on their use has been presented.
I have compared these two editors to each other, to give you a feeling for the particular
strengths of each of them.
The coverage of vi has been extensive, with nearly every feature covered.
Differences between UNIX variants of vi has been pointed out where necessary.
I have included coverage of the important role of the ex editor and how
it relates to the vi editor. A moderately detailed presentation of regular
expressions was presented to enable the reader to quickly get up to speed in using
them within both vi and Emacs.
The role of Emacs as an integrating environment for uses such as file
management, e-mail, and shell programming, has been emphasized. The basics of its
operation as well as a selection of details on some of the more advanced features
has been covered.
Finally, more advanced uses of both editors have been presented, including methods
of customizing their use to your preferences.
©Copyright,
Macmillan Computer Publishing. All rights reserved.
|