Chapter 2. Editing

Now that you know how to enter and exit Emacs as well as the basics of working with files, it's time to learn how to move around in and edit files. Emacs offers lots of ways to move around in files. At first, you might find it confusing that there are so many ways to do the same thing. Be patient—as you learn, the confusion will lessen, and you'll begin to appreciate the variety of Emacs commands. The more ways you learn, the fewer keystrokes you'll need to get to the part of the file you want to edit.

If you want to practice commands while you're reading—which will help you learn faster—start by typing a page or two from anything you happen to have handy; the newspaper is fine. That will give you some text to work with as you learn the editing skills described in this chapter. Don't worry if you make mistakes; just keep on typing. You can correct any mistakes after you learn the basic editing skills outlined here. Learning any editor is primarily a matter of forming certain finger habits rather than memorizing what the book says. You will learn the right finger habits only if you start typing.

When you are typing and you get to the right side of the display, you have two options. You can press Enter to go to the next line, or you can keep typing. If you type a long line and don't press Enter, Emacs waits until you reach the end of the display. Then it puts a curved arrow at the end of the line and one at the beginning of the next line as a visual indication that the next line is a continuation of the previous line (see Figure 2-1). If Emacs is run in a nongraphical environment, a backslash (\) is used instead.


Figure 2-1. Graphical versions of Emacs use curved arrows to indicate that a line is continued; terminal versions use backslashes


Refill mode is a minor mode that keeps paragraphs neat as you edit them. It is not on by default. Look at the mode line. If the word

Refill
appears, you are in refill mode already. If not, you can turn it on for this buffer only by typing M-x refill-mode Enter. If you decide that you don't like refill mode, type M-x refill-mode Enter again. This command is like a light switch: it toggles refill mode on and off.

You may decide that you want to enter refill mode automatically whenever you edit. We'll describe how to do so at the end of this chapter.

In some contexts, refill mode can be annoying, and it is still a work in progress according to the Emacs manual. You may prefer auto-fill mode. You enter it in the same way; type M-x auto-fill-mode Enter. The word

Fill
appears on the mode line.

When you type paragraphs, auto-fill mode formats them. When you edit them, however, auto-fill mode does not automatically reformat them. You do that yourself using the fill-paragraph command, M-q.

If you turn on refill mode and then decide to use auto-fill mode, you still have to turn refill mode off explicitly by typing M-x refill-mode Enter. Otherwise, both modes appear on the mode line, and refill mode continues its merry automatic reformatting of paragraphs, ignoring the fact that auto-fill mode has been enabled.

Watch out for one important pitfall when reformatting paragraphs. In text mode, a paragraph is any text that is indented or has a blank line before and after it. If you have a file with no blank lines, Emacs thinks it is all one long paragraph. Typing M-q takes all the text, ignoring line breaks, and makes it one long paragraph. This command is a particular problem if you have a data file, a program, or if you just prefer to write files with no blank lines. Luckily, pressing C-_ or C-x u (both for undo) magically puts things back the way they were. If you regularly create files with no blank lines, here are some suggestions:

• Instead of writing in text mode, use paragraph indent text mode. In this mode, a line that starts with any blank space is a new paragraph. Type M-x paragraph-indent-text-mode to start this mode; you'll see

Parindent
on the mode line. See Chapter 6 for more details.

• Use a specific mode rather than text mode for writing. For example, use HTML mode or LaTeX mode, described in Chapter 8, for editing files of these types. These special modes redefine what a paragraph means so that the fill-paragraph command works correctly. Otherwise, these modes are very similar to text mode.

• Instead of filling a paragraph, fill a marked section of text called a region (we'll discuss regions later in this chapter). Define the region you want to fill and press M-x fill-region Enter. This command takes a region and formats each individual paragraph within it.

Table 2-1 lists commands for filling text automatically and reformatting paragraphs with auto-fill mode.


Table 2-1. Text filling and reformatting commands

Keystrokes Command name Action
(none)[10] refill-mode Toggle refill mode, in which Emacs automatically reformats text.
(none)OptionsWord Wrap in Text Modes auto-fill-mode Toggle auto-fill mode, in which Emacs formats paragraphs as you type them.
M-q fill-paragraph Reformat paragraph.
(none)EditFill fill-region Reformat individual paragraphs within a region.

2.1 Moving the Cursor

The easiest way to move the cursor is to click the left button on your mouse or to press the arrow keys. However, it's a hassle to reach for a mouse all the time. Learn to use keyboard commands to move around so that you will ultimately achieve blinding speed and maximum productivity in Emacs.

To use Emacs commands to move the cursor forward one space, type C-f (f for "forward"). As you might guess, C-b moves the cursor backward. To move up, type C-p (for previous-line), and to move down, type C-n (for next-line). It's easier to memorize commands if you remember what the letters stand for.

Figure 2-2 illustrates how to move up, down, left, and right using Emacs commands.


Figure 2-2. Basic cursor motion


If you're at the end of a line, C-f moves to the first character on the next line. Likewise, if you're at the beginning of a line, C-b moves to the last character of the previous line. If there's no place to go, Emacs beeps and displays the message

Beginning of buffer
or
End of buffer
.

2.1.1 Other Ways to Move the Cursor

Now we'll learn some more advanced ways to move the cursor. One common way is moving forward and backward by word: M-f moves forward a word; M-b moves backward a word. You can also move to the beginning or end of the line. C-a moves you to the beginning of the line (just like a is the beginning of the alphabet). C-e moves you to the end of the line. To move backward one sentence, type M-a; to move forward one sentence, type M-e. To move forward a whole paragraph at a time, type M-}; to move backward a paragraph, type M-{. If you're in the middle of a sentence or paragraph, moving back a sentence or paragraph actually takes you to the beginning of the current sentence or paragraph.

Figure 2-3 uses a few paragraphs of Victor Hugo's Les Misérables to show how you can move the cursor more than one character at a time.


Figure 2-3. Moving the cursor more than one character at a time


You may have picked up on a pattern here. Notice the difference between commands starting with Ctrl and those starting with Meta. Ctrl commands generally move in smaller units than their associated Meta commands. For example, C-b moves the cursor backward one character, whereas M-b moves the cursor back one word. Likewise, C-a moves to the beginning of the line, whereas M-a moves to the beginning of a sentence.

There's one caveat about moving by sentence or paragraph. Emacs defines a sentence pretty strictly. You need two spaces after the final punctuation mark, unless you're at the end of the line. If there's only one space, Emacs won't recognize it. Similarly, moving backward and forward by paragraph involves understanding the Emacs definition of a paragraph. To Emacs (and to most of us), paragraphs are either indented with a tab or at least one space or have blank lines between them (block style). You can change these definitions, but first you have to understand how to use regular expressions, which are discussed briefly in Chapter 3 and in more depth in Chapter 11. Chapter 10 discusses how to change variables.

If your file has page breaks in it, you can move to the next page or previous page by typing C-x ] (forward-page) or C-x [ (backward-page). Similar to paragraph and sentence movement, moving by page involves the Emacs definition of what a page is. A variable called page-delimiter defines what constitutes a page break. If there are no Emacs-recognized page breaks in the file, Emacs regards the buffer as one very long page. In this case, the forward-page command takes you to the end of the buffer, and the backward-page command takes you to the beginning of the buffer.

In text mode, a page break is a formfeed character that tells the printer to move to the next page (to feed the next form or page through the printer, hence the term formfeed) before continuing to print. If you are in text mode and you want to insert page breaks in your file, type C-q C-l (the lowercase letter L). C-q is the quoted-insert command. It tells Emacs to put a C-l control character in your file, rather than interpreting C-l as the recenter command. A C-l character looks like two characters (^L), but it's really only one. (Try to erase one using Del and see what we mean.)

2.1.2 Moving a Screen (or More) at a Time

Like other graphical applications, you can use the scrollbar to move around in Emacs. Like most things in Emacs, in addition to using the mouse or scrollbar to move around, you should learn Emacs's own keyboard commands to maximize your productivity.

If you want to page through a file one screen at a time, use the PgDown key or type C-v. Emacs displays the next full screen from your file. It leaves a couple of lines from the previous screen at the top to give you a sense of context. Likewise, pressing M-v (or the PgUp key) shows you the previous screen. Together, M-v and C-v provide a convenient way to scroll through a file quickly.

Scrolling happens automatically if you type any motion command that takes you beyond the limits of the text currently displayed. For example, if you are on the last line of the screen and press C-n, Emacs scrolls forward. Similarly, if you are at the top of the screen and press C-p, Emacs scrolls backward.

You often want to move all the way to the beginning or the end of a file. Type M-> or press End to go to the end of a buffer. To go to the beginning, type M-< or press Home. It may help you to remember that > points to the end of the buffer, and < points to the beginning of the buffer.

There are two more ways to move around that may come in handy. M-x goto-line Enter n Enter moves the cursor to line n of the file. Of course, Emacs starts counting lines from the beginning of the file. Likewise, M-x goto-char Enter n Enter goes to the nth character of the file, counting from the beginning. In both cases, n is a number.

For programmers, these commands are useful because many compilers give error messages like

Syntax error on line 356
. By using these commands, you can move easily to the location of your error. There are some more sophisticated ways to link Emacs with error reports from compilers and other programs. In addition, several other cursor motion commands are applicable only when you are editing programs (see Chapter 9 for details).

2.1.3 Repeating Commands

Now let's learn some efficiency tricks. Emacs lets you repeat any command as many times as you want to. First, you can repeat a command any number of times by pressing M-n before the command, where n is the number of times you want to repeat it. This command is called the digit-argument command.

You can give M-n a large argument if you want it to repeat the command many times. For example, let's say you are editing a large file of 1000 lines. If you typed M-500 C-n, the cursor would move down 500 lines, to the halfway point in the file. If you give M-n a larger argument than it can execute, it repeats the command as many times as possible and then stops.

There's another multiplier command you can use, too: C-u (the universal-argument command). You can give C-u an argument just like you do M-n. Typing either M-5 or C-u 5 repeats the command that follows five times. But unlike M-n, C-u doesn't need an argument to repeat commands. With no argument, C-u executes the next command four times. If you type C-u C-u, it executes the command 16 times. In this way, you can stack up C-u's to make commands execute many times: 16, 64, 256, and so on.[11]

2.1.4 Centering the Display

C-l, the recenter command, puts the current line in the center of the window vertically. This feature is useful if you're typing at the bottom or the top of the display. Typing C-l quickly moves the material that you care about to the middle of the display, where it is easier to see the full context.

C-l also redraws the display, if for any reason it appears obscured or contains random characters. This doesn't happen as often as it used to when we used terminals, but it can be a handy thing to know about, especially if you find yourself using Emacs remotely in a terminal interface.

Table 2-2 lists cursor movement commands. If the command is mnemonic, the word to remember is given in italics.


Table 2-2. Cursor movement commands

Keystrokes Command name Action
C-f forward-char Move forward one character (right).
C-b backward-char Move backward one character (left).
C-p previous-line Move to previous line (up).
C-n next-line Move to next line (down).
M-f forward-word Move one word forward.
M-b backward-word Move one word backward.
C-a beginning-of-line Move to beginning of line.
C-e end-of-line Move to end of line.
M-e forward-sentence Move forward one sentence.
M-a backward-sentence Move backward one sentence.
M-} forward-paragraph Move forward one paragraph.
M-{ backward-paragraph Move backward one paragraph.
C-v scroll-up Move forward one screen.
M-v scroll-down Move backward one screen.
C-x ] forward-page Move forward one page.
C-x [ backward-page Move backward one page.
M-< beginning-of-buffer Move to beginning of file.
M-> end-of-buffer Move to end of file.
(none) goto-line Go to line n of file.
(none) goto-char Go to character n of file.
C-l recenter Redraw screen with current line in the center.
M-n digit-argument Repeat the next command n times.
C-u n universal-argument Repeat the next command n times (four times if you omit n).

2.1.5 Emacs Commands and Your Keyboard

You can access many Emacs commands by pressing standard keys on your keyboard, such as PageDown (to scroll down one screen) or Home (to go to the beginning of a buffer). Figure 2-4 shows a sample keyboard layout and what the keys do. Your keys may be in a slightly different place, but if you have a key with the same or a similar name, it should work. We say "should" because there are situations in which the keys won't work—for example, if you use Emacs on a remote machine. We recommend that you also learn the standard Emacs commands; they work on any keyboard, and they are often easier to reach once you learn them.


Figure 2-4. Emacs commands and your keyboard

2.2 Deleting Text

Before you start practicing deletion commands, you might want to know the undo command, which is discussed fully later in this chapter. Typing C-_ or C-x u undoes your last edit; typing undo again undoes the edit before that one, and so on.

Emacs provides many ways to delete text. The simplest way to delete text is to press the Del key, which deletes the character immediately to the left of the cursor. See Figure 2-4 for possible locations of the Del key on your keyboard. It is sometimes referred to as the Backspace key. Del is easiest to define by what it does: it deletes the previous character. If you're typing and you decide to erase the last character you typed, what key do you reach for? That's the key Emacs refers to as Del.

Emacs provides a number of other deletion commands—perhaps too many for your taste, although you'll eventually find a reason to use most of them. For example, C-d (for delete-character) deletes the character under the cursor. The command for deleting the next word is M-d (for kill-word). Once again, note how the Meta key augments the command: C-d operates on a character, and M-d operates on a word.

Emacs has commands to delete the next or previous word, sentence, and paragraph. By their names, you can guess what they do when you're between words, sentences, or paragraphs. If you're in the middle of an entity, however, they do something a little surprising: they delete a portion of the current word, sentence, or paragraph, backward or forward depending on whether the command deletes previous or next. For example, here's how M-d acts differently depending on where the cursor is.


If the cursor is here: M-d makes this edit:
It was the worst of times
It was the w
_
of times
It was the worst of times
It was the
_
of times
It was the worst of times
It was the wors
_
of times

Similarly, if you are in the middle of a word and ask Emacs to delete the previous word (M-Del, for backward-kill-word), it deletes from the cursor position back to the beginning of the current word.

If you want to delete an entire line or part of a line, use the command C-k (for kill-line). This command deletes everything from the cursor to the end of the line. Typing C-k on a blank line deletes the line itself. So, it usually takes two C-k's to delete a line: one to delete the text and one to delete the resulting blank line. If you want to delete everything from the beginning of the line up to the cursor, try the more complex incantation Meta - C-k (i.e., hold down Meta, followed by a hyphen, and then C-k).

You can also use C-k to join two lines. If you're at the end of a line, C-k deletes the newline character, effectively making two lines into one long line.

2.2.1 The Kill Ring

By now you may have noticed that some deletion commands in Emacs are called kill commands, such as kill-region, kill-word, and the like. In Emacs, killing is not fatal, but in fact, quite the opposite. Text that has been killed is not gone forever but is hidden in an area called the kill ring. The kill ring, though it sounds somewhat like a violent gang, is an internal storage area where Emacs puts things you've copied or deleted. Do not confuse the kill ring with the system clipboard, which allows for copying and pasting between applications. We'll cover how Emacs relates to the system clipboard later in this chapter.

You can get back what you've deleted by typing C-y (for yank).[12] Conveniently, if you kill several lines in succession, Emacs collects them into a single item and places the whole unit into the kill ring; a single C-y command will bring everything back. In the following example, we'll use C-k four times to delete the first two lines of A Tale of Two Cities. (Remember: the first C-k deletes the text; the second C-k deletes the remaining blank line.) Then we'll use a single C-y to bring everything back.


Initial state:

The cursor is in upper-left corner.


Type: C-k C-k C-k C-k

You have deleted the first two lines with C-k.


Type: C-y

You got everything back with a single command.


What exactly goes into the kill ring? Everything you delete with C-k in addition to everything you delete with C-w and everything you copy with M-w (two commands that you'll learn shortly) go into the kill ring. Words, sentences, and paragraphs that you delete with M-d, M-Del, and their relatives also go into the kill ring. In addition, text that you delete with C-u followed by either Del or C-d goes into the kill ring. About the only thing that Emacs doesn't save in the kill ring is single characters, deleted with Del or C-d. (If you need to, you can get this type of deletion back using the undo command, bound to both C-_ and C-x u.)

Emacs is clever about what it puts into the kill ring: when it is assembling a big block of text from a group of deletions, it always assembles the text correctly. For example, you can type a few M-d's, followed by some M-Del's, with a couple of C-k's thrown in. When you type C-y, Emacs yanks all the text that you've deleted in the proper order.

However, there's one thing you have to watch out for. Emacs stops assembling these blocks of text as soon as you give any command that isn't a kill command. For example, if you type C-k, then delete a single character with C-d, then type another C-k, you've broken the chain. Emacs doesn't consider deletion of a single character with C-d a "kill" command; it's just a deletion and it isn't stored. In this case, you haven't made a single chain of kill commands; you've made two chains. Later, we'll see how to get the older killed text back.

Table 2-3 summarizes the commands for deleting, killing, and yanking text, including options from the Edit menu.


Table 2-3. Deletion commands

Keystrokes Command name Action
C-d delete-char Delete character under cursor.
Del delete-backward-char Delete previous character.
M-d kill-word Delete next word.
M-Del backward-kill-word Delete previous word.
C-k kill-line Delete from cursor to end of line.
M-k kill-sentence Delete next sentence.
C-x Del backward-kill-sentence Delete previous sentence.
C-y yank Restore what you've deleted.
C-w EditCut kill-region Delete a marked region (see next section).
(none) kill-paragraph Delete next paragraph.
(none) backward-kill-paragraph Delete previous paragraph.

2.3 Marking Text to Delete, Move, or Copy

What if the text you want to delete is just a phrase? Or half a paragraph? Or several paragraphs? In Emacs, you select text by defining an area called a region. You can mark regions with the mouse or by using the keyboard. What happens with the mouse is a bit complicated, so we describe it later in this chapter, following our discussion of the system clipboard.

To define a region using the keyboard, you use a secondary pointer called a mark. Some versions of Emacs display the mark on the screen; unfortunately, in GNU Emacs, the mark is invisible.

You set the mark at one end of the region by pressing C-Space or C-@, then move the cursor to the other end of the region. (The cursor is sometimes also referred to as point. There is one minor but important difference between the cursor and the point, however. The cursor is on top of a character; in Emacs, the point is actually in between the character the cursor is on and the previous character. As we said, this difference is minor, but it helps you to visualize where the cursor should be when you mark a region.) Figure 2-5 illustrates point, mark, and region.


Figure 2-5. Point, mark, and region


Let's mark a sample region. In this example, we remove the phrase "it was the worst of times." First, we find the beginning of the phrase. Then we set the mark, move forward to the end of the phrase, and cut.


Move to the beginning of "it" and press C-Space.

Set the mark; Mark set appears in the minibuffer.


Move to the "i" in "it was the age of wisdom." Because the point is really just before the "i," this placement will be just right.


Move to the "i" in "it was the age of wisdom"

The point is at the end of the region to be marked.


Now the region is marked. If the region is not highlighted, you'll want to make sure it is marked correctly before giving the delete command. Press C-x C-x (for exchange-point-and-mark); this command swaps the locations of the mark and the point. If the cursor moves to where you thought the mark was, the region is marked correctly. Especially because you can't see the mark, it's a good habit to check its location using C-x C-x before deleting a region. People who have used Emacs for years still forget to set the mark and then make a deletion without knowing what they've just deleted. (The undo command, bound to C-_ and C-x u, comes in handy in such a case.)

To cut the region, press C-w (for kill-region). (The scissors icon on the toolbar also works.)


Press: C-w

C-w cuts the region.


If you're not sure of what you deleted, just press C-_ to undo it. The text is still marked, and you can delete it again with C-w if you want to. To move text, mark it, press C-w to cut the region, then move the cursor to the place you want to insert the text, and press C-y. If you yank the text back into the wrong location, just type C-_ to undo it, then move to the place you really wanted to put the text, and press C-y again.

When you're defining a region, you normally set the mark at one end and then move the cursor to the other end of the region. A few shortcuts are helpful in some of the most common situations. To mark a paragraph, press M-h. This sets the mark at the end of the paragraph and places the cursor at the beginning automatically. Similarly, C-x h (for mark-whole-buffer) marks the entire buffer; the cursor goes to the beginning, and the mark is placed at the end. Finally, C-x C-p marks the current page, with pages being defined by the C-l character if you are in text mode. Of course, marking a paragraph, page, or buffer is usually only the prelude to some other operation, like killing (C-w).

2.3.1 Copying Text

To copy text, mark a region, then press M-w (for kill-ring-save; the toolbar icon with two pieces of paper also runs this command). Move the cursor to the place where you want to insert the copied text and press C-y. Copying text is exactly the same as killing it, except that Emacs doesn't delete anything. The text you have copied is placed in the kill ring, so you can use C-y to access it as often as you like.

One advantage to M-w is that it works on read-only files and buffers. For example, if you wanted to create a file of Emacs hints, you could use M-w to copy some text from online help into one of your buffers.

Here are the steps for some common deletion tasks.

To mark a region:

1. Move the cursor to the beginning of the area you want to delete.

2. Press C-Space. Emacs displays the message Mark set.

3. Move the cursor to the end of the region you want to delete.

To delete a region:

1. Mark the region to be deleted.

2. Press C-w to delete the region.

To move text:

1. Delete the text you want to move using the procedures for marking and deleting a region.

2. Move the cursor where you want to insert the text.

3. Press C-y. Emacs inserts the text you deleted.

To copy text:

1. Mark the region you want to copy.

2. Press M-w to copy the text.

3. Move the cursor where you want to insert the copied text and press C-y. Emacs inserts the text you copied.

2.3.2 Recovering Earlier Deletions

Earlier we mentioned the kill ring, a temporary storage area in which Emacs saves the stuff you delete. So far, we've assumed that you're interested in resurrecting what you've most recently killed. However, the kill ring does a lot more. It actually stores your last 30 deletions. We've seen that C-y restores the text you deleted most recently. Typing M-y deletes the text you just yanked and gets the next most recent text from the kill ring.

Here's how it works. In Table 2-4, assume that you've just killed the words "most recent." C-y retrieves these words from the kill ring. When you press M-y, Emacs gets rid of "most recent" and gets the next entry from the kill ring ("second-last").


Table 2-4. The kill ring in action

Keystrokes Action
C-y
This was the most recent
_
deletion.
M-y
This was the second-last
_
deletion.
M-y
This was the third-last
_
deletion.
M-y
This was the fourth-last
_
deletion.

You can keep on typing M-y, retrieving successively more ancient deletions, until you reach the end of the kill ring (at which point it cycles back to the most recently killed text; that's why it's called a ring).

Thirty deletions by default is a nice size—far more generous than most programs offer. But you can enlarge or reduce the size of the kill ring if you wish, using a variable called kill-ring-max. To experiment, give the command: M-x set-variable Enter kill-ring-max Enter new-value Enter (where new-value is a number).

2.3.3 Selecting and Pasting

Using the menus, you can access text from the kill ring in a more straightforward way: by choosing Edit → Select and Paste. A menu showing deletions appears, with the most recent ones on top. To show you as many deletions as possible, each line in the window represents a separate deletion. So if you've killed a large region, say 500 lines, you see only the beginning of the first line of that deletion, ellipses, and the end of the deletion. Your selection is pasted into the buffer at the cursor position.

Table 2-5 summarizes commands for working with regions.


Table 2-5. Commands for working with regions

Keystrokes Command name Action
C-@ or C- Space set-mark-command Mark the beginning (or end) of a region.
C-x C-x exchange-point-and-mark Exchange location of cursor and mark.
C-w kill-region Delete the region.
C-y yank Paste most recently killed or copied text.
M-w kill-ring-save Copy the region (so it can be pasted with C-y).
M-h mark-paragraph Mark paragraph.
C-x C-p mark-page Mark page.
C-x h mark-whole-buffer Mark buffer.
M-y yank-pop After C-y, pastes earlier deletion.

2.4 Emacs and the Clipboard

Emacs 21 plays well with the clipboard, though it still may not do what you want it to in some cases. Let's dig into this in a little more detail.

2.4.1 Placing Text on the Clipboard

By default, text that you cut or copy using icons on the toolbar or options on the Edit menu is placed on the clipboard and is accessible to other applications.

Unfortunately, Emacs diverges by platform on this issue. Normally we save platform-specific issues for Chapter 13, but cutting and pasting is such a vital operation that we must describe the differences here.

On Windows and Mac OS X (but not on Linux) any text you cut or copy using C-w or M-w is also copied to the clipboard.

On Windows and Mac OS X, simply selecting text with the mouse places it on the clipboard. (This doesn't work on Linux.). Most applications require you to highlight text, then issue a copy command. Emacs doesn't. Table 2-6 shows how this works on various platforms.


Table 2-6. Selecting text with the mouse

Linux Windows Mac OS X graphical Mac OS X terminal
Sends to clipboard? no yes yes no[13]
Sends to kill ring? yes yes yes no

To send text to the clipboard on Linux, select it with the mouse (or mark it as a region), then click on the cut or copy toolbar icon or menu option. You can also use the clipboard-specific commands listed in Table 2-7 on any platform.

2.4.2 Retrieving Text from the Clipboard

As we mentioned, in other applications, you typically cut and paste by selecting text, then issuing a copy command. How do you then paste that text into Emacs?

Not surprisingly, the paste icon on the toolbar and the associated option on the Edit menu do this in most cases (see Table 2-7; Emacs on Mac OS X disables both the icon and the option inappropriately; the associated command name clipboard-yank works, however). C-y inserts text from the clipboard too. Additionally, an easy mouse gesture works on most platforms: simply click the middle mouse button or mouse wheel in the Emacs window to paste from the clipboard. The caveat here is that you must have a mouse with a middle button.


Table 2-7. Pasting from the clipboard

Linux Windows Mac OS X graphical Mac OS X terminal
C-y pastes? yes yes yes no[14]
Toolbar paste icon pastes? yes yes no no
Edit → Paste option pastes? yes yes no no
Middle mouse button pastes? yes yes yes no
M-x clipboard-yank pastes? yes yes yes no

Another issue with cutting and pasting is encoding. Encoding is a complex topic in Emacs; full Unicode support is slated for Emacs 22. At this point, we can only point you to a variable that may help you resolve cut-and-paste related encoding issues: set-clipboard-coding-system.

If you're interested in the clipboard, you may want to change Emacs' keys for cutting and pasting to the more universal C-x, C-c, and C-v. See "Making Emacs Work the Way You Want" later in this chapter for more details.

Table 2-8 summarizes clipboard-related commands.


Table 2-8. Clipboard commands

Keystrokes Command name Action
(none) clipboard-kill-region Cut region and place both in kill ring and on system clipboard.
(none) clipboard-yank Paste text from clipboard.
(none) clipboard-kill-ring-save Copy text to clipboard.

2.5 Editing Tricks and Shortcuts

Now that you've learned the basics of editing—moving the cursor to the right position, deleting, copying, and moving text—you can learn some tricks that make editing easier.

2.5.1 Fixing Transpositions

The most common typo involves the transposition of two letters, and most typos are noticed immediately after you make them. Pressing C-t transposes two letters, to put them in the right order:


Before C-t After C-t
the best of timse, it
the best of times
_
it

To transpose two letters, put the cursor on the second of the two letters to be transposed. Press C-t. (If you often transpose letters, word abbreviation mode, discussed in Chapter 3, cleans up typos automatically.)

You can also transpose two words, lines, paragraphs, or sentences. To transpose two words, put the cursor between the two words and press M-t. After Emacs has finished, the cursor follows the second of the two (transposed) words:


Before M-t After M-t
one three
_
two
one two three
_

Interestingly, Emacs moves words, but not punctuation. Let's say that two names are reversed:


Before M-t After M-t
Charles, Dickens
Dickens, Charles
_

To transpose two lines, put the cursor anywhere on the second of the two and press C-x C-t. Emacs moves the second before the first:


Before C-x C-t After C-x C-t
second line
first line
first line
second line
third line
third line

Table 2-9 summarizes the transposition commands.


Table 2-9. Transposition commands

Keystrokes Command name Action
C-t transpose-chars Transpose two letters.
M-t transpose-words Transpose two words.
C-x C-t transpose-lines Transpose two lines.
(none) transpose-sentences Transpose two sentences.
(none) transpose-paragraphs Transpose two paragraphs.

2.5.2 Changing Capitalization

Mistakes in capitalization are also common and annoying typing errors. Emacs has some special commands for fixing capitalization. To capitalize the first letter of any word, put the cursor on the first letter and press M-c. To put a word in lowercase, press M-l. To put a word in uppercase, press M-u. The key bindings here are mnemonic: Meta followed by c for capitalize, l for lowercase, and u for uppercase. Note that if the cursor is in the middle of a word, Emacs takes action only from the character under the cursor to the end of the word. You can easily use M-l to lowercase the second half of a word, and so on.

If you notice that the word you just typed is incorrect, you can use the same commands prefaced by Meta- (press and hold Meta followed by a hyphen). This corrects the previous word without moving the cursor. If the cursor is positioned in the middle of a word, using Meta- before a command causes it to work on the first part of the word (the part preceding the cursor), rather than the part following the cursor.

For example, starting with

abcdefghij
:


If you press: You'll get:
Meta - u
abcdEFGHIJ
_
Meta - M-u
ABCDefghij
M-c
abcdEfghij
_
Meta - M-c
Abcdefghij

Table 2-10 summarizes the capitalization commands.


Table 2-10. Capitalization commands

Keystrokes Command name Action
M-c capitalize-word Capitalize first letter of word.
M-u upcase-word Uppercase word.
M-l downcase-word Lowercase word.
Meta - M-c negative-argument; capitalize-word Capitalize previous word.
Meta - M-u negative-argument; upcase-word Uppercase previous word.
Meta - M-l negative-argument; downcase-word Lowercase previous word.

2.5.3 Overwrite Mode

You may be used to typing over old text rather than having to delete it. There is a certain satisfaction in destroying some really bad text in this way. You can do this in Emacs, too, by entering a minor mode called overwrite mode. When you're in overwrite mode, any new text you type wipes out the text that's underneath. When you're not in overwrite mode (i.e., in normal Emacs), any new text you type is inserted at the cursor position and any subsequent text is pushed to the right. (Other software may refer to this as insert mode; because it is the way GNU Emacs normally behaves, it doesn't have a name here.)

To enter overwrite mode, press the Insert key.[15] Ovwrt should appear on the mode line. If this doesn't work (or if you don't have an Insert key), type M-x overwrite-mode Enter. You can turn off overwrite mode by typing M-x overwrite-mode Enter again. Using Emacs's command completion, simply type M-x ov and press Enter. This is enough of a unique string to tell Emacs you want to toggle overwrite mode. Completion, one of the best shortcuts in Emacs, is discussed further in Chapter 14.

2.6 Canceling Commands and Undoing Changes

Sometimes you start a command by accident or change your mind about it. Don't worry: with Emacs, you can quit in the middle or undo it.

2.6.1 Canceling Commands

When you want to cancel any command that's in progress, press C-g. The word Quit appears in the command area. This command is helpful when you are stuck in the minibuffer and didn't really mean to go there. Depending on what you were doing, you may have to press C-g a few times.

2.6.2 Undoing Changes

What happens if you make a mistake while you're editing? You can undo your changes by pressing C-_ or C-x u (for undo; conveniently, the toolbar also has an undo icon, a curved left arrow). By typing undo repeatedly, you can gradually work your way back to a point before your mistake.[16] Although the undo command is very powerful, saving your file frequently, if not compulsively, is nevertheless a good idea. We usually save a file whenever we stop typing—even if only for a few seconds. Train your fingers to press C-x C-s whenever you pause; it's a good habit to form.

If you're used to typing C-z to undo, you can easily change Emacs's behavior to match your habits. See "Making Emacs Work the Way You Want" at the end of this chapter for information on CUA mode.

What if you'd like to redo a command after you type undo? There is no formal redo command, but you can use undo in the following way. Just move the cursor in any direction, and type C-_ or C-x u again. Emacs redoes the last command you undid. You can repeat it to redo previous undos.

Although undo is an important command, it can be slow if you want to undo a large number of changes. Table 2-11 summarizes three methods for undoing changes and circumstances in which you might want to use them.


Table 2-11. Methods for undoing changes

If you: Use this command:
Don't like the recent changes you've made and want to undo them one by one C-_ or C-x u (undo)
Want to undo all changes made since you last saved the file M-x revert-buffer Enter
Want to go back to an earlier version of the file (the file as it was when you started this editing session) C-x C-f filename~ Enter C-x C-w filename Enter

We've already talked about undoing changes with undo; next we describe how to revert a buffer from a file and how to go back to an earlier version.

2.6.3 Reverting a Buffer from a File

If the undo command isn't useful, there's another way to restore a file to an earlier state. If you want to get the file back to the state that is stored on disk, type M-x revert-buffer Enter. Emacs asks the following question:

Revert buffer from file filename? (yes or no)

The filename is the name of your original file. Type yes if you want to restore the file, or no if you've changed your mind. Emacs copies the file stored on disk into the buffer, conveniently forgetting everything that happened since the last time you saved the file. Although this command is called revert-buffer, note that it can revert only buffers associated with files.

2.6.4 Going Back to a Previous Version: Backup Files

The first time you save a file during an editing session, Emacs creates a backup file. If something disastrous happens, and the other techniques for undoing changes won't help you, you can always return to the backup file. The name of the backup file is the same as the name of the file you're editing, with a tilde (~) added. For example, if you are editing the file text, the backup file is text~.

Emacs doesn't provide any special commands for restoring a buffer from the backup copy. The easiest way to do this is to edit the backup copy and then save it as the real file. For example, if you were working with a file called text, you could: exit Emacs by typing C-x C-c, then start Emacs again by typing emacs text~. After the backup file is displayed, save it as the real file by typing C-x C-w text Enter. As a safeguard, Emacs asks you before it writes over the original file:

File text exists; overwrite? (y or n)

Type y to overwrite the original file with the backup file.

GNU Emacs also has a numbered backup facility. If you turn on numbered backups, Emacs creates a backup file (with the suffix ~n~) every time you save your file. n increments with each successive save. If you are nervous about deleting older versions, it might be worth using: you can keep all of your old versions forever, if you want to. However, numbered backups can also waste disk space; a happy medium may be to tell Emacs to keep the last n versions, where n is the number of versions you want to keep. The variables that control numbered backups are described in Appendix A. If you are interested in full-blown version control, check out VC mode, discussed in Chapter 12. Table 2-12 summarizes the commands for stopping commands and undoing changes.


Table 2-12. Stopping and undoing commands

Keystrokes Command name Action
C-g keyboard-quit Abort current command.
C-x u advertised-undo[17] Undo last edit (can be done repeatedly).
C-_ EditUndo undo Undo last edit (can be done repeatedly).
(none) revert-buffer Restore buffer to the state it was in when the file was last saved (or auto-saved).

2.6.5 Recovering Lost Changes

We've just discussed how to eliminate changes you don't want to keep; getting back changes you've lost is a different kind of problem. You might lose changes if the power goes out momentarily or if the computer you're working on suddenly freezes or is turned off accidentally. You might also lose changes if you exit Emacs abnormally. Luckily, Emacs, being the watchful editor that it is, saves your file for you every so often in auto-save files. If you watch carefully, you'll see the message Auto saving in the minibuffer from time to time. Using auto-save files, you can get back most, if not all, of your changes. The name of an auto-save file is the same as the name of the file you are editing, with a sharp (#) added to the beginning and the end. For example, if you are editing the file text, its auto-save file is #text#.

To recover text from an auto-save file, type M-x recover-file Enter. Emacs opens a window that lists both the file and its associated auto-save file so that you can compare the time at which they were created, their size, and so forth. Emacs asks you the following question:

Recover auto-save file #text#? (yes or no)

Type yes to confirm that you want to copy the contents of the auto-save file into the current file or no if you change your mind. (If you are unsure, you might want to use C-x C-f to read the auto-save file #text# into a buffer first and look it over carefully before using the recover-file command. If you really want to compare the differences between the two versions, see "Comparing Files Between Windows" in Chapter 4.)

When does Emacs create auto-save files? Emacs creates an auto-save file every few hundred keystrokes or if Emacs is terminated abnormally.[18] You can change the frequency with which Emacs creates auto-save files by changing the variable auto-save-interval. By default, Emacs creates an auto-save file every 300 keystrokes. For more information on changing variable values, see Chapter 10.

There's one more important fact to know about Emacs and auto-save files. If you delete a large portion of a file, Emacs stops auto-saving the file and displays a message telling you so. To make Emacs start auto-saving again, save the file with C-x C-s or type M-1 M-x auto-save Enter (that's the number 1).

Now you've learned enough commands for most of the editing you'll do with Emacs. At this point, you may want to learn how to make Emacs turn on certain features like auto-fill mode automatically, so you don't have to turn them on every time you enter Emacs. The next section provides a brief introduction to customization; this topic is covered in much greater detail in Chapter 10.

2.7 Making Emacs Work the Way You Want

If you've been reading straight through this book, you may have started a list of things you'd like to change about Emacs, such as

• Hiding the toolbar

• Changing Emacs cut and paste commands to C-x, C-c, and C-v

• Turning on text mode and a fill mode so Emacs does word wrap

• Changing the way some of the keys work

We're going to tell you how to give Emacs the to-do list, a list of options to turn on each time you enter Emacs. These options are defined in an initialization file called .emacs. Initialization files run automatically. Some run when you start up your computer. Others, like .emacs, run when you start up an associated software program. So .emacs runs automatically when you start Emacs and turns on whatever options the file defines. Emacs doesn't need this file to run; its only purpose is to make Emacs work the way you want it to.

The .emacs file consists of Lisp statements. If you're not a Lisp programmer, you can think of each line as an incantation that follows a certain pattern; you need to type it exactly.

Emacs now has another way to handle customization: an interactive interface called Custom that writes Lisp for you and automatically inserts it in your .emacs file. The Custom interface is discussed in Chapter 10, but we'll show you an even faster method for common options.

When you want to add a line to your .emacs file directly, take these steps:

1. Enter Emacs (if you're not already there).

2. Type C-x C-f ~/.emacs Enter.

3. Type the line to be added exactly as shown in this book and press Enter.

4. Press C-x C-s to save the .emacs file.

5. Press C-x C-c to exit Emacs.

6. Restart Emacs to have the line take effect.

If you make a minor typing mistake (such as forgetting a single quotation mark or a parenthesis), you are likely to get an error message that says

Error in init file
when you restart Emacs. Simply edit the .emacs file again, checking the line you added against the place you got it from, whether from this book or another user's .emacs file. Usually, you can find the error if you look hard enough; if not, find someone who has a .emacs file (and preferably understands Lisp) and ask for help. Make the changes, save the file, and restart Emacs.

What if you make a change that essentially keeps Emacs from being able to start? You can still exit Emacs, rename the file, edit it, then save it as .emacs and try again.

2.7.1 Hiding the Toolbar

New users may find the toolbar helpful. Others may not. It's easy to hide it by selecting Options → Show/Hide → Toolbar, and then Options → Save Options.

When Emacs sets options for you through Custom (and this is what it is doing even when you use the Options menu), it writes your .emacs file. If you already have a .emacs file, it appends to it. Custom essentially groups all of its settings in one part of the file, and it is commented to indicate that you should not change it manually. Here's the .emacs file that we created by selecting this option:

(custom-set-variables

 ;; custom-set-variables was added by Custom.

 ;; If you edit it by hand, you could mess it up, so be careful.

 ;; Your init file should contain only one such instance.

 ;; If there is more than one, they won't work right.

'(tool-bar-mode nil nil (tool-bar)))

(custom-set-faces

 ;; custom-set-faces was added by Custom.

 ;; If you edit it by hand, you could mess it up, so be careful.

 ;; Your init file should contain only one such instance.

 ;; If there is more than one, they won't work right.

)

This may seem a bit bulky, but as we'll see in the next section, Emacs adds this section only once and then augments it when you set more options either through the options menu or directly through the Custom interface. Also note that this auto-generated Lisp is certainly less clean than Lisp statements you'll typically see in .emacs files. That's another reason not to edit Custom's work directly.

2.7.2 Turning On CUA Mode for C-x, C-c, and C-v to Cut, Copy, and Paste

If you're new to Emacs, you might be used to the Common User Access (CUA) conventions for cutting, copying, and pasting, C-x, C-c, and C-v respectively. You might reach for C-z for undo. CUA mode was once an add-on mode that you had to install separately, but it became so popular that it is now part of Emacs. It's coded in a clever way that doesn't interfere with Emacs keystrokes that are prefixed with C-x and C-c. Details on CUA mode can be found in Chapter 13.

You can turn this feature on through the Options menu to try it out. Simply choose Options → C-x/C-c/C-v cut and paste (CUA). After you select this option, a check mark appears next to it on the Options menu. To keep it for subsequent sections, select Save Options from the Options menu. Emacs writes your .emacs file for you. If you turned off the toolbar and then set this option, your .emacs file would look like this (note that the line relating to CUA mode is bold so you can see the difference from the previous example):

(custom-set-variables

 ;; custom-set-variables was added by Custom.

 ;; If you edit it by hand, you could mess it up, so be careful.

 ;; Your init file should contain only one such instance.

 ;; If there is more than one, they won't work right.

 '(cua-mode t nil (cua-base))

 '(tool-bar-mode nil nil (tool-bar)))

(custom-set-faces

 ;; custom-set-faces was added by Custom.

 ;; If you edit it by hand, you could mess it up, so be careful.

 ;; Your init file should contain only one such instance.

 ;; If there is more than one, they won't work right.

)

Interestingly, Emacs happily writes the .emacs file even if it is open at the time. You can watch Emacs change the file if you have it open when you choose Save Options.

2.7.3 Turning On Text Mode and Auto-Fill Mode Automatically

To make text mode the default major mode and start auto-fill mode automatically each time you enter Emacs, add these lines to your .emacs file:

(setq default-major-mode 'text-mode)

(add-hook 'text-mode-hook 'turn-on-auto-fill)

The first line tells Emacs to make text mode the default major mode; in other words, "Turn on text mode unless I tell you otherwise." The second line turns on auto-fill mode whenever you are in text mode. Alternatively, selecting Options→ Word Wrap in Text Modes, and then Options→ Save Options adds auto-fill mode to your .emacs file directly. It doesn't make text mode the default major mode, however.

If you prefer refill mode, replace the second line of code with this line:

(add-hook 'text-mode-hook (lambda ( ) (refill-mode 1)))

2.7.4 Remapping Keys

Another major use of the .emacs file is to redefine things about Emacs that irritate you. You may have ergonomic concerns about Emacs; more than one person has aggravated carpal tunnel syndrome using the default bindings. You may simply be used to reaching for certain keys for certain functions and would rather change Emacs than your habits. Whatever the case, this section gives a brief introduction to key remapping; for more details, see Chapter 10.

If you use the default bindings (rather than CUA mode), you may use C-x u for undo.[19] (Undo is such a common command that it's easy to type C-x C-u by mistake when you undo repeatedly. Unfortunately, C-x C-u is a disabled command for upcase-region. If you type C-x C-u, an annoying message about enabling the command pops up.

If you don't anticipate a big need for upcasing regions, you can redefine C-x C-u so that it also runs undo. To do so, add this line to your .emacs file:

(define-key global-map "\C-x\C-u" 'undo)

After making this change, typing C-x C-u runs undo, just as C-x u does.

Emacs customization is extremely powerful, and you can make Emacs work just the way you want it to. A far more extensive treatment of customization is found in Chapter 10. This brief introduction is meant to whet your appetite and to make it possible for you to add lines to your .emacs file as we mention potential customizations throughout the book.

The next chapter covers topics such as the many searches offered by Emacs, including query-replace, as well as spell checking and word abbreviation mode (often used to correct typos automatically). If you want to learn about these features, go on to the next chapter. From here on, you can take a selective approach to reading this book, picking and choosing whatever you want to learn about; you don't need to read the rest of the book sequentially.

2.7.5 Problems You May Encounter

You get an error message when you start Emacs after changing the .emacs file. The message appears only briefly; press M-p to view it again. Edit your .emacs file, checking the lines you added carefully against their source for minor typographical errors. Something as simple as a missing hyphen or apostrophe can cause this error. Fix the error, save the file, exit Emacs, and reenter. In extreme cases (the .emacs file is so messed up that Emacs won't even let you edit it), exit Emacs, rename the .emacs file, and then start Emacs and edit it again to fix it. Rename it back to .emacs and start again.

Paragraphs are not reformatted properly. This seems to relate to window size. Try resizing the window horizontally until paragraphs format properly.

Загрузка...