Advanced Editing

The basic emacs commands suffice for many editing tasks but the serious user will quickly discover the need for more power. This section presents some of the more advanced emacs capabilities.

Undoing Changes

An editing session begins when you read a file into an emacs buffer. At that point the buffer content matches the file exactly. As you insert text and give editing commands, the buffer content becomes increasingly more different from the file. If you are satisfied with the changes, you can write the altered buffer back out to the file and end the session.

Near the left end of the Mode Line (Figure 7-1, page 202) is an indicator that shows the modification state of the buffer that is displayed in the window. The three possible states are -- (not modified), * * (modified), and %% (readonly).

The emacs editor keeps a record of all the keys you have pressed (text and commands) since the beginning of the editing session, up to a limit currently set at 20,000 characters. If you are within this limit, it is possible to undo the entire session for this buffer, one change at a time. If you have multiple buffers (page 224), each buffer has its own undo record.

Undoing is considered so important that it has a backup key sequence, just in case some keyboards cannot easily handle the primary sequence. The two sequences are CONTROL-_ (underscore, which on old ASR-33 TTY keyboards was LEFT ARROW) and CONTROL-X u. When you type CONTROL-_, emacs undoes the last command and moves the cursor to that position in the buffer so you can see what happened. If you type CONTROL-_ a second time, the next-to-last command is undone, and so on. If you keep typing CONTROL-_, eventually you will get the buffer back to its original unmodified state and the * * Mode Line indicator will change to --.

When you break the string of Undo commands with anything (text or any command except Undo), all reverse changes you made during the string of undos become a part of the change record and can themselves be undone. This strategy offers a way to redo some or all the undo operations. If you decide you backed up too far, type a command (something innocuous, such as CONTROL-F, that does not change the buffer), and begin undoing in reverse. Table 7-4 lists some examples of Undo commands.

Table 7-4. Undo commands




Undoes the last change


Undoes the last change and changes it back again


Undoes the last two changes


Undoes two changes and changes them both back again


Undoes two changes and changes one of them back again

If you do not remember the last change you made, you can type CONTROL-_ and undo it. If you wanted to make this change, type CONTROL-F CONTROL-_ and make it again. If you modified a buffer by accident, you can keep typing CONTROL-_ until the Mode Line indicator shows once more.

If the buffer is completely ruined and you want to start over, issue the command META-x revert-buffer to discard the current buffer contents and reread the associated file. The emacs editor asks you to confirm this command.

Mark and Region

Point is the current editing position in a buffer which you can move anywhere within the buffer by moving the cursor. It is also possible to set a marker called Mark in the buffer. The contiguous characters between Point and Mark (either one may come first) are called the Region. Many commands operate on a buffer's Region, not just on the characters near Point.

Moving Mark and Establishing a Region


Mark is not as easy to move as Point. Once set, Mark can be moved only by setting it somewhere else. Each buffer has only one Mark. The CONTROL-@ (or CONTROL-SPACE) command explicitly sets Mark at the current cursor (and Point) position. Some key-boards generate CONTROL-@ when you type CONTROL-Q. Although this is not really a backup key binding, it is occasionally a convenient alternative. You can use CONTROL-X CONTROL-X to exchange Point and Mark (and move the cursor to the new Point).

To establish a Region, you usually position the cursor (and Point) at one end of the desired Region, set Mark with CONTROL-@, and then move the cursor (and Point) to the other end of the Region. If you forget where you left Mark, you can move the cursor back to it again with CONTROL-X CONTROL-X or hop back and forth with repeated CONTROL-X CONTROL-X to show the Region more clearly.

If a Region boundary is not to your liking, you can swap Point and Mark using CONTROL-X CONTROL-X to move the cursor from one end of the Region to the other and then move Point. Continue until you are satisfied with the Region.

Operating on a Region

Table 7-5 lists selected commands that operate on a Region. Give the command CONTROL-H a region to see a complete list of these commands.

Table 7-5. Operating on a region




Copies the Region nondestructively (without killing it) to the Kill Ring


Kills the Region

META-x print-region

Sends the Region to the printer

META-x append-to-buffer

Prompts for a buffer and appends the Region to that buffer

META-x append-to-file

Prompts for a filename and appends the Region to that file

META-x capitalize-region

Converts the Region to uppercase

The Mark Ring

Each time you set Mark in a buffer, you are also pushing Mark's former location onto the buffer's Mark Ring. The Mark Ring is organized as a FIFO (first-in-first-out) list and holds the 16 most recent locations where Mark was set. Each buffer has its own Mark Ring. This record of recent Mark history is useful because it often holds locations that you want to jump back to quickly. Jumping to a location pointed to by the Mark Ring can be faster and easier than scrolling or searching your way through the buffer to find the site of a previous change.


To work your way backward along the trail of former Mark locations, give the command CONTROL-U CONTROL-@ one or more times. Each time you give the command, emacs

  • Moves Point (and the cursor) to the current Mark location

  • Saves the current Mark location at the oldest end of the Mark Ring

  • Pops off the youngest (most recent) Mark Ring entry and sets Mark

Each additional CONTROL-U CONTROL-@ command causes emacs to move Point and the cursor to the previous entry on the Mark Ring.

Although this process may seem complex, it really just makes a safe jump to a previous Mark location. It is safe because each jump's starting point is recirculated through the Mark Ring, where it is easy to find again. You can jump to all previous locations on the Mark Ring (it may be fewer than 16) by giving the command CONTROL-U CONTROL-@ again and again. You can go around the ring as many times as you like and stop whenever you want.

Setting Mark Automatically

Some commands set Mark automatically: The idea is to leave a bookmark before moving Point a long distance. For example, META-> sets Mark before jumping to the end of the buffer. You can then return to your starting position with CONTROL-U CONTROL-@. Searches behave similarly. To avoid surprises the message Mark Set appears in the Echo Area whenever Mark is set, either explicitly or implicitly.

Cut and Paste: Yanking Killed Text

Recall that killed text is not discarded but rather is kept in the Kill Ring. The Kill Ring holds the last 30 pieces of killed text and is visible from all buffers.

Retrieving text from the Kill Ring is called yanking. This terminology is the opposite of that used in vim: In vim yanking pulls text from the buffer, and putting puts text into the buffer. Killing and yankingwhich are roughly analogous to cutting and pastingare emacs's primary mechanisms for moving and copying text. Table 7-6 lists the most common kill and yank commands.

Table 7-6. Common kill and yank commands




Kills to end of current word


Kills from beginning of previous word


Kills to end of line, not including LINEFEED


Kills to end of line, including LINEFEED


Kills from beginning of line


Copies the Region (between Point and Mark) to the Kill Ring but does not erase the Region from the buffer


Kills the Region (between Point and Mark)

META-z char

Kills up to next occurrence of char


Yanks the most recently killed text into the current buffer at Point, sets Mark at the beginning of this text, and positions Point and the cursor at the end


Erases the just-yanked text, rotates the Kill Ring, and yanks the next item (only after CONTROL-Y or META-y)

To move two lines of text, move Point to the beginning of the first line and then enter CONTROL-U 2 CONTROL-K to kill two lines. Next move Point to the destination position, and enter CONTROL-Y.

To copy two lines of text, move Point to the beginning of the first line and give the commands CONTROL-U 2 CONTROL-K CONTROL-Y to kill and then yank back immediately. Then move Point to the destination position and type CONTROL-Y.

To copy a larger piece of the buffer, set the Region to cover this piece and then type CONTROL-W CONTROL-Y to kill and yank back at once. Next move Point to the destination, and type CONTROL-Y. You can also set the Region and use META-w to copy the Region to the Kill Ring.

The Kill Ring is organized as a fixed-length FIFO list, with each new entry causing the eldest to be discarded (once you build up to 30 entries). Simple cut-and-paste operations generally use only the newest entry. The older entries are retained to give you time to change your mind about a deletion. If you do change your mind you can "mine" the Kill Ring like an archaeological dig, working backward through time and down through the strata of killed material to copy a specific item back into the buffer.

To view every entry in the Kill Ring, begin a yanking session by pressing CONTROL-Y. This action copies the youngest entry to your buffer at the current cursor position. If this entry is not the item you want, continue the yanking session by pressing META-y. This action erases the previous yank and copies the next youngest entry to the buffer at the current cursor position. If this still is not the item you wanted, press META-y again to erase it and retrieve a copy of the next entry, and so on. You can continue giving META-y commands all the way back to the oldest entry. If you continue to press META-y, you wrap back to the youngest entry again. In this manner you can examine each entry as many times as you wish.

The sequence used in a yanking session consists of CONTROL-Y followed by any mixture of CONTROL-Y and META-y. If you type any other command after META-y, the sequence is broken and you must give the CONTROL-Y command again to start another yanking session.

As you work backward in the Kill Ring, it is useful to think of this process as advancing a Last Yank pointer back through history to increasingly older entries. This pointer is not reset to the youngest entry until you give a new kill command. Using this technique, you can work backward partway through the Kill Ring with CONTROL-Y and a few META-y commands, give some commands that do not kill, and then pick up where you left off with another CONTROL-Y and a succession of META-y commands.

It is also possible to position the Last Yank pointer with positive or negative numeric arguments to META-y. Refer to the online documentation for more information.

Inserting Special Characters

As stated earlier, emacs inserts everything that is not a command into the buffer at the position of the cursor. To insert characters that would ordinarily be emacs commands, you can use the emacs escape character: CONTROL-Q. There are two ways of using this escape character:

  • CONTROL-Q followed by any other character inserts that character in the buffer, no matter what command interpretation it was supposed to have.

  • CONTROL-Q followed by three octal digits inserts a byte with that value in the buffer.


Depending on the way your terminal is set up, CONTROL-Q may clash with software flow control. If CONTROL-Q seems to have no effect, it is most likely being used for flow control. In that case you must bind another key to the command quoted-insert (page 240).

Global Buffer Commands

The vim editor and its predecessors have global commands for bufferwide search and replace operations. Their default operating Region is the entire buffer. The emacs editor has a similar family of commands. Their operating Region begins at Point and extends to the end of the buffer. If you wish to operate on the entire buffer, use META-< to set Point at the beginning of the buffer before issuing the command.

Line-Oriented Operations

The commands listed in Table 7-7 take a regular expression and apply it to the lines between Point and the end of the buffer.

Table 7-7. Line-oriented operations



META-x occur

Prompts for a regular expression and copies each line with a match for the expression in a buffer named *Occur*

META-x delete-matching-lines

Prompts for a regular expression and deletes each line with a match for the expression

META-x delete-non-matching-lines

Prompts for a regular expression and deletes each line that does not have a match for that expression

The META-x occur command puts its output in a special buffer named *Occur*, which you can peruse and discard or use as a jump menu to reach each line quickly. To use the *Occur* buffer as a jump menu, switch to it (CONTROL-X o [lowercase "o"]), move the cursor to the copy of the desired destination line, and type CONTROL-C CONTROL-C. This command moves the cursor to the buffer that was searched and positions it on the line that the regular expression matched.

As with any buffer change, you can undo the deletion commands.

Unconditional and Interactive Replacement

The commands listed in Table 7-8 operate on the characters between Point and the end of the buffer, changing every string match or regular expression match. An unconditional replacement makes all replacements automatically. An interactive replacement gives you the opportunity to see and approve each replacement before it is made.

Table 7-8. Replacement commands



META-x replace-string

Prompts for string and newstring and replaces every instance of string with newstring. Point is left at the site of the last replacement, but Mark is set when you give the command, so you can return to it with CONTROL-U CONTROL-@.

META-x replace-regexp

Prompts for regexp and newstring and replaces every match for regexp with newstring. Point is left at the site of the last replacement, but Mark is set when you give the command, so you can return to it with CONTROL-U CONTROL-@.

META-% string or META-x query-replace

The first form uses string, the second form prompts for string. Both forms prompt for newstring, query each instance of string, and, depending on your response, replace it with newstring. Point is left at the site of the last replacement, but Mark is set when you give the command, so you can return to it with CONTROL-U CONTROL-@.

META-x query-replace-regexp

Prompts for regexp and newstring, queries each match for regexp, and, depending on your response, replaces it with newstring. Point is left at the site of the last replacement, but Mark is set when you give the command, so you can return to it with CONTROL-U CONTROL-@.

If you perform an interactive replacement, emacs displays each instance of string or match for regexp and prompts you for an action to take. Table 7-9 lists some of the possible responses.

Table 7-9. Responses to interactive replacement prompts




Do not do any more replacements; quit now.


Make this replacement and go on.


Do not make this replacement. Skip it and go on.

, (comma)

Make this replacement, display the result, and ask for another command. Any command is legal except DELETE is treated like SPACE and does not undo the change.

. (period)

Make this replacement and quit searching.

! (exclamation point)

Replace this and all remaining instances without asking any more questions.


When you visit (emacs terminology for "call up") a file, emacs reads it into a buffer (page 224), allows you to edit the buffer, and eventually saves the buffer back to the file. The commands discussed here relate to visiting and saving files.

META-x pwd META-x cd

Each emacs buffer keeps a record of its default directory (the directory the file was read from or the working directory, if it is a new file) that is prepended to any relative pathname you specify. This convenience is meant to save some typing. Enter META-x pwd to print the default directory for the current buffer or META-x cd to prompt for a new default directory and assign it to this buffer.

Visiting Files

The emacs editor deals well with visiting a file that has already been called up and whose image is now in a buffer. After a check of the modification time to ensure that the file has not been changed since it was last called up, emacs simply switches to that buffer. Table 7-10 lists commands used to visit files.

Table 7-10. Visiting files




Prompts for a filename and reads its contents into a freshly created buffer. Assigns the file's simple filename as the buffer name. Other buffers are unaffected. It is common and often useful to have several files open simultaneously for editing.


Prompts for a filename and replaces the current buffer with a buffer containing the contents of the requested file. The current buffer is destroyed.


Prompts for a filename and reads its contents into a new buffer. Assigns the file's simple filename as the buffer name. Creates a new window for this buffer and selects that window. The window selected before the command still displays the buffer it was showing before this operation, although the new window may cover up part of the old window.

To create a new file, simply call it up. An empty buffer is created and properly named so you can eventually save it. The message (New File) appears in the Echo Area, reflecting emacs's understanding of the situation. Of course, if this "new file" grew out of a typographical error, you will probably want to issue CONTROL-X CONTROL-V with the correct name.

Saving Files

You save a buffer by copying its contents back to the original file you called up. The relevant commands are listed in Table 7-11.

Table 7-11. Saving files




This workhorse file-saving command saves the current buffer into its original file. If the current buffer is not modified, you get the following message: (No changes need to be saved).


For each modified buffer, you are asked whether you wish to save it. Answer y or n. This command is given automatically as you exit from emacs and allows you to save any buffers that have been modified but not yet written out. If you want to save intermediate copies of your work, you can give this command at any time.

META-x set-visited-file-name

Prompts for a filename and sets this name as the current buffer's "original" name.


Prompts for a filename, sets this name as the "original" name for the current buffer, and saves the current buffer into that file. It is equivalent to META-x set-visited-file-name followed by CONTROL-X CONTROL-S.

META-~ (tilde)

Clears modified flag from the current buffer. If you mistakenly typed META-~ against a buffer with changes you want to keep, you need to make sure that the modified condition and its * * indicator are turned back on before leaving emacs, or all the changes will be lost. One easy way to do this is to insert a SPACE into the buffer and then remove it again with DELETE.

Caution: Did you modify a buffer by mistake?

When you give a CONTROL-X s command, you may discover files whose buffers were modified by mistake as emacs TRies to save the wrong changes back to the file. When emacs prompts you to confirm the save, do not answer y if you are not sure. First exit from the CONTROL-X s dialog by typing n to any saves you are not sure about. You then have several options:

  • Save the suspicious buffer into a temporary file with CONTROL-X CONTROL-W and analyze it later.

  • Undo the changes with a string of CONTROL-_ commands until the * * indicator disappears from the buffer's Mode Line.

  • If you are sure that all the changes are wrong, use META-x revert-buffer to get a fresh copy of the file.

  • Kill the buffer outright. Because it is modified, emacs asks whether you are sure before carrying out this command.

  • Give the META-~ (tilde) command to clear the modified condition and * * indicator. A subsequent CONTROL-X s then believes that the buffer does not need to be written.

Caution: You can exit without first getting a warning

Clearing the modified flag (META-~) allows you to exit without saving a modified buffer with no warning. Make sure you know what you are doing when you use META-~.


An emacs buffer is a storage object that you can edit. It often holds the contents of a file but can also exist without being associated with a file. You can select only one buffer at a time, designated as the current buffer. Most commands operate only on the current buffer, even when multiple windows show two or more buffers on the screen. For the most part each buffer is its own world: It has its own name, its own modes, its own file associations, its own modified state, and perhaps its own special key bindings. You can use the commands shown in Table 7-12 to create, select, list, and manipulate buffers.

Table 7-12. Work with buffers




Prompts for a buffer name and selects it. If the buffer you name does not exist, this command creates it.


Prompts for a buffer name and selects it in another window. The existing window is not disturbed, although the new window may overlap it.


Creates a buffer named *Buffer List* and displays it in another window. The existing window is not disturbed, although the new window may overlap it. The new buffer is not selected. In the *Buffer List* buffer, each buffer's data is shown along with the name, size, mode(s), and original filename. A % appears for a readonly buffer, a * indicates a modified buffer, and . appears for the selected buffer.

META-x rename-buffer

Prompts for a new buffer name and gives this new name to the current buffer.


Toggles the current buffer's readonly status and the associated %% Mode Line indicator. This can be useful to prevent accidental buffer modification or to allow modification of a buffer when visiting a readonly file.

META-x append-to-buffer

Prompts for a buffer name and appends the Region (between Point and Mark) to the end of that buffer.

META-x prepend-to-buffer

Prompts for a buffer name and prepends the Region (between Point and Mark) to the beginning of that buffer.

META-x copy-to-buffer

Prompts for a buffer name and deletes the contents of the buffer before copying the Region (between Point and Mark) to that buffer.

META-x insert-buffer

Prompts for a buffer name and inserts the entire contents of that buffer into the current buffer at Point.


Prompts for a buffer name and deletes that buffer. If the buffer is modified but unsaved, you are asked to confirm the operation.

META-x kill-some-buffers

Goes through the entire buffer list and offers the chance to delete each buffer. As with CONTROL-X k, you are asked to confirm the kill command if a modified buffer is not yet saved.


An emacs window is a viewport that looks into a buffer. The emacs screen begins by displaying a single window, but this screen space can later be divided among two or more windows. On the screen the current window holds the cursor and views the current buffer. For a tip on terminology, see "The screen and emacs windows" on page 201.

A window views one buffer at a time. You can switch the buffer that a window views by giving the command CONTROL-X b buffer-name in the current window. Multiple windows can view one buffer; each window may view different parts of the same buffer; and each window has its own Point value. Any change to a buffer is reflected in all the windows viewing that buffer. Also, a buffer can exist without a window open on it.

Splitting a Window

One way to divide the screen is to split the starting window explicitly into two or more pieces. The command CONTROL-X 2 splits the current window in two, with one new window appearing above the other. A numeric argument is taken as the size of the upper window in lines. The command CONTROL-X 3 splits the current window in two, with the new windows being arranged side by side (Figure 7-7). A numeric argument is taken as the number of columns to give the left window. For example, CONTROL-U CONTROL-X 2 splits the current window in two; because of the special "times 4" interpretation of CONTROL-U standing alone, the upper window is given four lines (barely enough to be useful).

Figure 7-7. Splitting a window vertically

Although these commands split the current window, both windows continue to view the same buffer. You can select a new buffer in either or both new windows, or you can scroll each window to show different portions of the same buffer.

Manipulating Windows


You can use CONTROL-X o (lowercase "o") to select the other window. If more than two windows appear on the screen, a sequence of CONTROL-X o commands cycles through them in top-to-bottom, left-to-right order. The META-CONTROL-V command scrolls the other window. If more than two windows are visible, the command scrolls the window that CONTROL-X o would select next. You can use a positive or negative scrolling argument, just as with CONTROL-V scrolling in the current window.

Other-Window Display


In normal emacs operation, explicit window splitting is not nearly as common as the implicit splitting done by the family of CONTROL-X 4 commands. The CONTROL-X 4b command, for example, prompts for a buffer name and selects it in the other window. If there is no other window, this command begins with a half-and-half split that arranges the windows one above the other. The CONTROL-X 4f command prompts for a filename, calls it up in the other window, and selects the other window. If there is no other window, this command begins with a half-and-half split that arranges the windows one above the other.

Adjusting and Deleting Windows


Windows may be destroyed when they get in the way. No data is lost in the window's associated buffer with this operation, and you can make another window whenever you like. The CONTROL-X 0 (zero) command deletes the current window and gives its space to its neighbors; CONTROL-X 1 deletes all windows except the current window.


You can also adjust the dimensions of the current window, once again at the expense of its neighbors. To make a window shorter, use META-x shrink-window. Use CONTROL-X^ to increase the height of a window, CONTROL-X} to make the window wider, and CONTROL-X{ to make the window narrower. Each of these commands adds or subtracts one line or column to or from the window, unless you precede the command with a numeric argument.

The emacs editor has its own guidelines for a window's minimum useful size and may destroy a window before you force one of its dimensions to zero. Although the window may disappear, the buffer remains intact.

Foreground Shell Commands

The emacs editor can run a subshell (a shell that is a child of the shell that is running emacsrefer to "Executing a Command" on page 294) to execute a single command line, optionally with standard input coming from the Region of the current buffer and optionally with standard output replacing the Region (Table 7-13). This process is analogous to executing a shell command from the vim editor and having the input come from the file you are editing and the output go back to the same file (page 187). As with vim, how well this process works depends in part on the capabilities of the shell.

Table 7-13. Foreground shell commands



META-! (exclamation point)

Prompts for a shell command, executes it, and displays the output

CONTROL-U META-! (exclamation point)

Prompts for a shell command, executes it, and inserts the output at Point

META-| (vertical bar)

Prompts for a shell command, gives the Region as input, filters it through the command, and displays the output

CONTROL-U META-| (vertical bar)

Prompts for a shell command, gives the Region as input, filters it through the command, deletes the old Region, and inserts the output in that position

The emacs editor can also start an interactive subshell that runs continuously in its own buffer. See "Shell Mode" on page 237 for more information.

Background Shell Commands

The emacs editor can run processes in the background, with their output being fed into a growing emacs buffer that does not have to remain in view. You can continue editing while the background process runs and look at its output later. Any shell command can be run in this way.

The growing output buffer is always named *compilation*. You can read it, copy from it, or edit it in any way, without waiting for the background process to finish. Most commonly this buffer is used to review the output of program compilation and to correct any syntax errors found by the compiler.

META-x compile

To run a process in the background, give the command META-x compile to prompt for a shell command and begin executing it as a background process. The screen splits in half to show the *compilation* buffer.

You can switch to the *compilation* buffer and watch the execution, if you wish. To make the display scroll as you watch, position the cursor at the very end of the text with a META-> command. If you are not interested in this display just remove the window with CONTROL-X 0 (zero) if you are in it or CONTROL-X 1 otherwise and keep working. You can switch back to the *compilation* buffer later with CONTROL-X b.

You can kill the background process with META-x kill-compilation. The emacs editor asks for confirmation and then kills the background process.

If standard format error messages appear in *compilation*, you can automatically visit the line in the file where each error occurred. Give the command CONTROL-X' (back tick) to split the screen into two windows and visit the file and line of the next error message. Scroll the *compilation* buffer until this error message appears at the top of its window. Use CONTROL-U CONTROL-X' to start over with the first error message and visit that file and line.

A Practical Guide to UNIX[r] for Mac OS[r] X Users
A Practical Guide to UNIX for Mac OS X Users
ISBN: 0131863339
EAN: 2147483647
Year: 2005
Pages: 234

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: