Emacs editing environment, Part 2: Learn the essential modes and editing features of Emacs

Get going with this famous open source editor

One of the powerhouses of UNIX® computing, the open source Emacs editor is a large, complex application that does everything from edit text to function as a complete development environment. This tutorial, the second in a series, introduces you to some of the essential concept of modes, shows you some of the powerful text manipulation functions available, and teaches you how to use the built-in search, replace, and spellcheck facilities of Emacs.

Before you start

Learn what to expect from this tutorial, and how to get the most out of it.

About this series

The Emacs editing environment is a favorite of UNIX® developers. It's known around the world as the king of editors, but many users find it has a bit of a learning curve. The Emacs environment doesn't seem intuitive at first glance, and it doesn't work like other editors and word processors. But learning Emacs doesn't have to be difficult. Once you get going, you'll see how intuitive it is and become more comfortable with it after each use. This tutorial series shows you the way, taking you from the basics of Emacs, such as its features, philosophy, key-command layout, and methods for editing text, through many of its powerful editing features.

After completing this series, you'll be able to comfortably use Emacs for everyday editing, be well on your way to Emacs proficiency, and have a good feel for many of the advanced capabilities of Emacs.

About this tutorial

This tutorial, the second in a series, demonstrates how to use some of the vital features for text editing and introduces the concept of modes, showing you what to use them for, how to invoke them, and which popular modes you're liable to use in your normal editing. It also describes a special mode for defining abbreviations as useful shorthand and explains how to use some of the text-editing features that work regardless of mode -- including important text manipulation commands, the search and replace facility, and the built-in spell checker.

Objectives

The primary objective of this tutorial is to take users who are already familiar with the basics of the Emacs editor, such as its manner of keyboard input and the paradigm of buffers, and illustrate some of its essential but more intermediate features, including editing modes, incremental search, and other important Emacs text manipulation commands and facilities.

After completing this tutorial, you will have a firm knowledge of the editing modes of Emacs and how to utilize these various text-manipulation features in Emacs.

Prerequisites

The only prerequisite for this tutorial is that you already have a basic understanding of Emacs, which you can gain by taking the first tutorial in this series.

Although this tutorial is written for all levels of UNIX expertise, it's helpful if you have at least a rudimentary understanding of the UNIX filesystem:

  • Files
  • Directories
  • Permissions
  • Filesystem hierarchy

System requirements

This tutorial requires a user account on any UNIX-based system that has a recent copy of Emacs installed.

There are several varieties of Emacs; the original and most popular is GNU Emacs, which is published online by the GNU Project (see Resources).

You should have a recent copy of GNU Emacs -- one that is at version 20 or greater. Versions 20 and 21 are the most commonly available, and development snapshots of version 22 are also available. This tutorial works with any of these versions for Emacs. If your system is running something older, it's time to upgrade.

To know what version of Emacs you have running, use the GNU-style --version flag:

$ emacs --version
GNU Emacs 22.0.91.1
Copyright (C) 2006 Free Software Foundation, Inc.
GNU Emacs comes with ABSOLUTELY NO WARRANTY.
You may redistribute copies of Emacs
under the terms of the GNU General Public License.
For more information about these matters, see the file named COPYING.
$

Editing modes

Emacs is classified as a modeless editor, meaning that unlike editors such as vi, there is no special command mode for running editor commands or insert mode for inserting text into the buffer -- as you saw in the previous tutorial in this series, both commands and text insertion can be done at any time.

However, Emacs does have its own kind of editing modes, which are functions that extend its capabilities or change the way some features work. Modes are generally written for editing a certain type or class of data, such as regular documents (written in any of the Indo-European languages), source code in a particular computer programming language (C, Fortran, Lisp, and so forth), text formatted a certain way (outlines, e-mail messages, usenet articles, character-based illustrations, and so forth) or in a markup language (Hypertext Markup Language (HTML), Nroff, TeX, and Extensible Markup Language (XML)). There's even a mode for editing non-text (binary) data. Additionally, many special modes for other kinds of data and system processes are accessible through Emacs, including network connections and Internet Relay Chat (IRC), shell sessions, and the UNIX filesystem itself.

Modes are classified as either major or minor. The major mode dictates the main editing behavior and is applied only to that buffer in the current editing session. Every buffer always has one, and only one, major mode active at any one time.

Although a buffer can only have one major mode active at any time, you can switch between major modes whenever you like. Specialized major modes offer extra functionality and aids (such as context highlighting and colorization) that can help when you're editing certain kinds of documents, but you're not required to select a particular mode to edit a certain kind of file or document -- a C program source code file might be edited in any mode for editing text just as it might be done in the special mode available for editing C programs.

Minor modes normally offer some feature or capability not associated with any particular major mode. Think of them as toggles that control features: Calling a minor mode by its function name turns that minor mode on or off, and you can have many minor modes turned on at any one time.

Minor modes include Overwrite mode (described in the first tutorial in this series), RCS mode for managing files checked into the revision control system (RCS), and Auto Fill mode to handle automatic word wrapping. All these minor modes and many others like them can be active at any one time.

This section of the tutorial shows you what you need to know to use the Emacs modes successfully:

  • How to know which modes are active
  • How to get a description of the current modes and their capabilities
  • How to invoke a mode
  • Which modes you should know about

See which modes are active

As described in the first tutorial in this series, the highlighted bar near the bottom of the Emacs window, called the mode line, tells you all about the current buffer -- including which modes are currently active. The current modes are indicated in parentheses toward the right side of the mode line. The abbreviated name of the major mode is listed first, followed by the abbreviated names of any minor modes.

When you start Emacs with no files, you're in the scratch buffer. By default, this buffer is opened with Lisp Interaction mode, which is a special mode for the evaluation of Lisp code.

See for yourself by starting Emacs in the usual way, and look at what's written in the mode line.

Any time you change modes, you'll see it reflected in the mode line. Try it now: Press the Ins key to turn on Overwrite mode, and notice how the mode line changes. (The Ins key is bound to the overwrite-mode function).

Press Ins again to turn off Overwrite mode.

When a minor mode is enabled, it's normally indicated inside the parentheses, right after the major mode. However, not all minor modes have this indicator -- some minor modes are self-evident, such as Tool Bar mode, which displays the graphical tool bar at the top of the Emacs frame. Other minor modes in newer versions of Emacs are so minor (and always on) that it would only clutter the display to have them all shown; for example, the purpose of the Unify 8859 On Encoding minor mode is to provide an encoding unification for the various ISO 8859 character sets, which is useful for internationalization.

Additionally, some modes offer extra indicators that appear in the mode line. Line Number mode, for instance, is indicated by an L followed by the line number in the buffer where the cursor is currently located.

Get a description of the current mode

Use the describe-mode function, which is bound to C-h m, to get a description of the current mode. When you run this function, a new help buffer opens that lists all the key bindings that are special to the current major mode in the buffer you typed it in followed by any bindings that apply to any of the minor modes that are on.

Try it now by typing C-h m, as in Figure 1.

Figure 1. List the key bindings applicable to current Emacs modes
List the key bindings applicable to current Emacs modes

As you can see, one of the special bindings for Lisp Interaction mode is the Tab key. In this mode, Tab doesn't move the cursor to the next tab stop as you'd expect on a typewriter or in a word-processor application; as the mode description says, it indents the current line of Lisp code. Because you haven't written any Lisp code in this buffer, Tab does nothing -- try it and see.

The default mode

Although the scratch buffer is usually set to Lisp Interaction mode, that's not the default Emacs mode. To find out what is, switch to a new buffer: Type C-x b and give the name lamb.txt as the name of the buffer. Get rid of the help buffer by typing C-x 1.

You'll see that your new lamb.txt buffer has a new major mode, Fundamental. This is the default mode for Emacs buffers. It's the most plain and simple of all Emacs modes, with the fewest special key bindings and settings. Here, the Tab key works as you'd expect it to.

Go ahead and get a description of the modes by typing C-h m again.

You'll see the following for the description of Fundamental mode:

Fundamental mode:
Major mode not specialized for anything in particular.
Other major modes are defined by comparison with this one.

Type C-x 1 again to get rid of the help window.

When you open the contents of an existing file in a new buffer, Emacs selects a mode for you based on the file type. If you open a file containing C program source code, C mode will be major mode; and, if you open a file containing text in a spoken language such as English, Emacs sets Text mode as the major mode.

You can always change the mode, and you can configure all these settings so that certain files or certain types of buffers always open in a particular mode. Table 1 describes popular Emacs modes and gives their function names.

Table 1. Popular Emacs modes
ModeFunctionTypeDescription
Fundamentalfundamental-modeMajorThis mode is the default Emacs mode with minimal settings and bindings.
Texttext-modeMajorThis mode is the basic mode for editing text.
Abbrevabbrev-modeMinorThis mode is for making and using abbreviations (see Abbrev mode).
Auto Fillauto-fill-modeMinorThis mode is for automatic word wrap and filling long lines and paragraphs.
Overwriteoverwrite-modeMinorThis mode is for overwriting any existing text in a buffer instead of inserting text at point. It's bound by default to the Ins key.
Cc-modeMajorThis mode is for editing C program source code.
Line Numberline-number-modeMinorThis mode is for displaying the current line number.
Lisp Interactionlisp-interactionMajorThis mode is for editing and compiling Lisp code.
Paragraph-Indent Textparagraph-indent-text-modeMajorThis mode is a special variation of the Text mode where the paragraph-movement commands work for paragraphs whose first lines are indented, and not just for paragraphs separated by blank lines.
TeXtex-modeMajorThis mode is for editing TeX documents.
WordStarwordstar-modeMajorThis special mode provides the key bindings of the WordStar editor.

Set the mode

Emacs modes are functions. To invoke one, you type M-x and then give the name of the mode.

Try invoking Text mode in your new buffer now: Type M-x text-mode and press Enter. You'll immediately see the change in the mode line, where Fundamental is replaced by Text.

Type in Text mode

Text mode is a basic mode with few changes from the Fundamental mode, so its benefits are subtle; but it's a good base for editing text in spoken languages, such as English. Many of the special modes for editing certain kinds of text or documents from TeX mode to Outline mode are based on Text mode.

Try typing some text in your new buffer, continuing the theme of William Blake from the last tutorial:

Little lamb, who made thee?
Dost thou know who made thee?

In Text mode, the Tab key is defined to indent paragraphs relative to the previous indentations of the paragraph, if any; if the previous paragraph isn't indented, pressing Tab inserts a literal tab character, moving point to the next tab stop.

To see how Text mode handles tabs, type a few lines with tabs and spaces:

  1. Type two spaces on the next new line in your buffer, type the text Gave thee life, and baid thee feed, and press Enter to end this new paragraph.

  2. Press Tab -- notice how point is lined up with the line (paragraph) above it -- type By the stream and o'er the mead;, and press Enter.

  3. Type a new line with no indentation: Gave thee something of delight, and press Enter

  4. Press Tab. Notice how you're shifted out many spaces -- a literal tab character has been inserted. Type the line Softest something, woolly, bright; and press Enter.

  5. Type Gave thee such a tender voice, and press Enter.

  6. Press Tab. Another tab character is inserted. Type the line Making all the vales rejoice?

Your buffer should now look like Figure 2.

Figure 2. Type tabs in Text mode
Type tabs in text mode

Table 2 shows the key bindings that are set by Text mode.

Table 2. Text mode key bindings
KeyDescription or function
EscPrefix for mode-specific commands
Esc Tab, M-Tabispell-complete-word
Esc S, M-Scenter-paragraph
Esc s, M-scenter-line

Abbrev mode

An Emacs abbrev is a special word defined by a particular string. When an abbrev is typed in a buffer (and Abbrev mode is turned on), the abbrev is expanded or replaced by the string it's defined by.

Abbrev mode (a minor mode) allows you to make quick shorthand for long strings or phrases, but you can probably think of other ways that you can use it, too.

Define an abbrev

The easy way to add abbrevs is to run one of the inverse-add abbrev functions, inverse-add-global-abbrev or inverse-add-local-abbrev. These functions let you define a word in the buffer as an abbrev; the first applies the abbrev to any buffer you open in your current Emacs session, and the second defines the abbrev only to buffers with the same major mode as the current buffer. The latter is useful for defining abbrevs that are only appropriate to certain modes, such as for long variable names in a buffer containing program source code.

Try defining an abbrev so that it works across all buffers:

  1. On the next new line, type an abbreviated word, li, so that point is at the end of the word (after the i).

  2. Run the inverse-add-global-abbrev function by typing C-x a i g.

  3. Define your abbrev where prompted in the minibuffer: Type Little lamb and press Enter.

Notice that the abbrev you type in the buffer is replaced by its definition and point moved to the beginning of the definition.

Now move point to a new line and make a new abbrev the way you just did, by typing an x (abbrevs aren't case-sensitive) and using the string He is to define it.

You've defined two abbrevs. However, as you can see from the mode line, Abbrev mode is off. Turn it on: Type M-x abbrev-mode. Erase those two lines with the definitions you just made and then type the code from Listing 1.

Listing 1. Sample lines with abbrevs
Li, I'll tell thee,
Li, I'll tell thee:
x called by thy name,
For he calls himself a lamb.
x meek, and x mild;

The abbrevs for li and x expand as you type them so, when you're done, the buffer looks like Figure 3.

Figure 3. Abbrevs expanded in an Emacs buffer
Emacs buffer showing expanded abbrevs

This example showed how to define abbrevs that work in all buffers. To define an abbrev so that it only works in buffers set to the current mode, use C-x a i l instead.

Use a word as an abbrev definition

You can also define abbrevs for a single word in the buffer. This is particularly useful when you're writing program source code and you've just typed a long variable.

To define an abbrev for a word, use C-x a g when point is after the word. Once you've done that, you're prompted in the minibuffer for the abbrev to replace that word when Abbrev mode is on.

Try it now:

  1. Type He became a little child on a new line.

  2. When point is immediately after the word child, type C-x a g.

  3. Type c in the minibuffer and press Enter.

End the current line with a period and then type a few more lines to watch the expansion occur:

.
We are called by his name.
I a c, and thou a lamb,

Notice that Emacs recognizes the c followed by a comma as an abbrev, but not the c in called.

Likewise, to define an abbrev in such a way that it applies only to the current major mode, use C-x a l.

Erase an abbrev

To kill all the abbrevs you've defined in your session, use the kill-all-abbrevs function.

Try it: Type M-x kill-all-abbrevs.

Now none of the abbrevs you've defined (li, x, and c) expand to their definitions, in any buffer, regardless of the mode. Type two more lines to finish:

Little lamb, God bless thee!
Little lamb, God bless thee!

Text manipulation

In this section, learn some of the special commands and key bindings for editing text, most of which work regardless of the current major mode.

Indent and fill text

Regions can be automatically indented in different ways. The indent-rigidly function, which you run by typing C-x C-i, indents all lines in the region to the right by one space.

Try it:

  1. Type C-Space to set the mark at the bottom of the buffer.

  2. Move point to the beginning of the line that reads, "Little lamb, I'll tell thee," to mark the last 10 lines in the buffer as the region.

  3. Type C-x C-i to indent the region one space.

  4. Type C-x C-i again to indent the region another space.

Just as you can run indent-rigidly multiple times, you can give a certain number of spaces to indent by preceding it with C-u followed by a number; use a negative number to move the region toward the left.

Try it:

  1. Indent the region by 10 more spaces: Type C-u 10 C-x C-i.

  2. Take the indentation back five spaces: Type C-u -5 C-x C-i.

After this, your buffer should look like Figure 4.

Figure 4. Inserting rigid indentation
Inserting rigid indentation

The indent-rigidly function is also bound to the C-x Tab.

To fill the region, justify the text with a ragged right margin and run the fill-region function. A similar function, fill-paragraph, applies to the current paragraph. It has a keyboard equivalent of M-q.

Try it: Type M-x fill-region. Notice that once the region is filled, point is moved to just after the region.

Like any of the Emacs formatting commands, the commands for indentation and filling can be undone with the undo function, which was described in the first tutorial in this series. Try it once now to undo the region fill: Type C-_ once.

Just as you can add or remove vertical space with indentations, you can also take out any existing horizontal space. To do this, use the delete-horizontal-space function, M-\ (that's the Meta key followed by the \ key). It removes all leading whitespace between the first nonspace character anywhere to the left of point and the first nonspace character to the right of point, no matter where point happens to be in the space.

Go ahead and try it. Take out all the leading spaces in the buffer by moving point to the space on each line and typing M-\ before moving to the next line with spaces.

To add a line of vertical space, you can always press Enter, but doing so also moves point. To add vertical space without moving point, run the open-line function, which is bound to C-o.

Try it: Move down eight lines from the top of the buffer so that point is at the beginning of the line reading "Little lamb, I'll tell thee," and type C-o. Now your buffer should look like Figure 5.

Figure 5. Remove horizontal space and insert vertical space
Remove horizontal space and insert vertical space

Transpose text

Emacs has commands for transposition, which allow you to exchange the characters, words, or lines immediately after point with those immediately before point. These are good commands for making quick corrections in text.

Use C-t, the transpose-chars function, to transpose the single character before point and the single character after point; use M-t, the transpose-words function, to transpose the single words before and after point.

Try it now:

  1. Move point to the o in For and then type C-t to transpose the o and F characters.

  2. Type C-t again to transpose the r and F characters.

  3. Move point back to the F and type C-t once to move the F back one character.

  4. Move point back to the F again and type C-t once more to move the F back to the beginning of the line.

  5. Type M-t to transpose the words For and he.

  6. Type M-t again to transpose the words For and calls.

  7. Move point between he and For and type M-t again to transpose them.

  8. Move point between calls and For and type M-t again to transpose them.

  9. Type M-t one last time to transpose calls and he.

The transpose-lines function, C-x C-t, transposes the line at point and the line before it.

Try it: Move point to the beginning of the line that begins "I a child" and type C-x C-t.

Note that you can also precede any of these commands with a numeric value by using the universal argument, C-u: C-u 2 C-x C-t transposes the line at point with the line two lines ahead of point.

Another useful command, delete-indentation, joins the line at point with the previous line, separated by a space character. It's bound to M-^, which you type by pressing and holding Meta and using the Shift key to type a caret (^). An alternate, C-1 M-^, joins the current line with the line that follows it.

Convert case

There are several Emacs functions for converting case. The uppercase-word function (bound to M-u) converts to uppercase letters of all the text beginning from point forward to the end of the word. Similarly, downcase-word (bound to M-l) converts everything from point to the end of the word to lowercase letters.

Try these on the buffer:

  1. Move point to the line that begins with "For he calls" and type M-c M-c M-l M-c M-l M-c so that the line is properly capitalized.

  2. Move point down to the line that begins with "We are called" and type M-u M-u M-u M-u M-u M-u so that the entire line is converted to uppercase letters.

  3. Type C-a to move point to the beginning of the line and type C-c C-l C-l C-l C-l C-c C-l so that the line is properly capitalized.

You can operate on words before point by preceding any of these commands with the negative-argument function, M--, which you type by pressing and holding the Meta key and then pressing a hyphen character (-). You can apply the case-changing commands to the region by using the downcase-region and upcase-region functions, which are bound to C-x C-l and C-x C-u, respectively.

Summary of text manipulation commands

Table 3 lists the various text manipulation commands you've just learned and describes their meanings.

Table 3. Emacs text manipulation commands
BindingCommand or functionDescription
C-x C-i, C-x Tabindent-rigidlyThis command indents lines in the region (or at point).
fill-regionThis command fills all paragraphs in the region.
M-qfill-paragraphThis command fills the single paragraph at point.
M-\delete-horizontal-spaceThis command removes any horizontal space to the right and left of point.
C-oopen-lineThis command opens a new line of vertical space below point, without moving point.
C-ttranspose-charsThis command transposes the single characters to the right and left of point.
M-ttranspose-wordsThis command transposes the single words to the right and left of point.
C-x C-ttranspose-linesThis command transposes the line at point with the line before it.
M-^delete-indentationThis command joins the line at point with the previous line. Preface with C-1 to join the line at point with the next line.
M-uuppercase-wordThis command converts the text at point to the end of the word to uppercase letters.
M-ldowncase-wordThis command converts the text at point to the end of the word to lowercase letters.
C-x C-ldowncase-regionThis command converts the region to lowercase letters.
C-x C-uupcase-regionThis command converts the region to uppercase letters.

Search and replace text

The commands for searching and replacing in Emacs work in all modes and are described in this section.

Incremental search

The basic and most popular way to search in Emacs is to use incremental search, so called because the search begins immediately, as soon as you type the first character. It searches in increments with every character you type, so if you search for the text lamb, for instance, as soon as you type the l, point moves to the next l in the buffer; and when you type the a, it moves to the first instance of la (which might or might not be the same place where the first l was found) and so on.

This is a very efficient way of searching text, because unlike applications with search-box facilities where you type a term and then press Enter (or -- worse -- you have to click the OK button), an incremental search begins the moment you type the first letter of your term. As soon as the right match is found, you can stop typing.

The most common incremental search is the isearch-forward function, which is bound to C-s. It searches forward from point in the buffer for the text you give it. To repeat a search and move to the next match, type C-s again.

When you reach the end of the buffer, Emacs rings the bell and prints a message in the minibuffer that the end of the buffer has been reached. If you type C-s again after that, the search wraps around to the beginning of the buffer (and you're so notified in the minibuffer).

Try it:

  1. Type C-s. Notice how you're prompted to give a string to search for in the minibuffer.

  2. Type l and see how point is moved to the next l in the buffer. If you have a very recent version of Emacs, all the l characters in the buffer will also be highlighted.

  3. Type e and see how point moves forward and highlights the next l and the e character right after it.

  4. Type a space and see how point moves to the next line and highlights the le in that line.

  5. Type C-s to repeat the search for le and see how point moves to the next line.

  6. Type C-s to repeat the search for le and notice how Emacs tells you that the search has failed -- it's reached the end of the buffer without finding another match for the le you're searching for.

  7. Type C-s to repeat the search for le anyway, wrapping around to the front of the buffer, and see how point moves to where it's found on the first line at the top.

There's also a way to search for text you see in the buffer: C-s C-w puts the string from point forward to the end of the word into the search buffer, and C-s C-y puts everything from point to the end of the line into the search buffer.

Incremental searches are normally case-insensitive; however, if you specify anything but all lowercase letters in your search, then only the case you give is matched.

Backward incremental search

To search backward from point, use isearch-backward (bound to C-r), searching in reverse through the buffer.

As with the forward incremental search, typing this command twice starts a search for the text that was last searched. When you get to the top of the buffer, typing C-r again wraps around to the bottom.

Try it: Type C-r lit to search in reverse and then type C-r multiple times to wrap down to the bottom of the buffer in reverse.

Non-incremental search

There's a way to do a non-incremental search, too. This is useful when, for instance, you want to search for a particular phrase or string that you see in the buffer, but instead of typing it, you'd rather paste it.

The non-incremental search works the same for both the forward and reverse searches. To do it, press Enter after typing either C-s or C-r for the search, type the entire string to search for, and press Enter again.

Try it:

  1. Type C-s to start a forward search and press Enter to specify that it be done non-incrementally.

  2. Type the word little and press Enter.

Word search

Sometimes you might want to search for words or phrases in a buffer and find them no matter how they happen to be spaced or formatted -- even if they're split between lines.

For instance, what if you want to match feed by in the buffer, where it's split by a newline?

Try it: Type C-r and give feed by as the text to search for.

Emacs quickly beeps and reports "Failing I-search" because there's a newline character between the words.

To match phrases regardless of the spacing between words, use the Emacs word search. You can do this with either a forward or reverse incremental search -- press Enter, type C-w, and then give the word or phrase to search for.

Try the search again:

  1. Move point to the top of the buffer.

  2. Type C-s to start a forward search.

  3. Press Enter.

  4. Type C-w to specify a word search.

  5. Type feed by and press Enter.

The string is matched even across a newline, and point is moved to just after the By in the second line of the phrase.

Regexp search

You can also search for regular expressions in Emacs. To do this, run the isearch-forward-regexp or isearch-backward-regexp function. These functions are bound to C-M-s and C-M-r, respectively. Then, give a regular expression as an argument. These searches are incremental.

Try searching forward and notice how the matches change depending on how you build the regexp:

  1. Type C-M-s to start a forward regexp search.

  2. Give the regexp l.*e and notice how the matches change for every character you type.

Replace text

There are several ways to replace text in Emacs.

The replace-string function prompts you for a string to match and a string to replace it with, and it replaces all instances from point to the end of the buffer.

Try replacing the word something with clothing throughout the buffer:

  1. Type M-x replace-string and press Enter.

  2. Type something and press Enter.

  3. Type clothing and press Enter.

After the command runs, it reports in the minibuffer how many occurrences it replaced -- in this case, two.

To delete a word or phrase throughout a buffer, run this command and replace it with nothing.

Another powerful function for replacing text is replace-regexp, which takes a regular expression as a string to search for and a string of text to replace it with.

Finally, you can run the query-replace function, which queries for every instance of the replacement. It's bound to M-%. Your choices for each match are described in Table 4.

Table 4. Options for Emacs' query-replace function
KeyDescription
Space, yReplace this match.
Del, nSkip this match and move to the next.
Enter, qExit query-replace.
.Make this replacement and then exit query-replace.
,Make this replacement, move point to it, and exit query-replace.
C-rSpecify a recursive edit.
C-wDelete the match and recursive edit.
C-lRedraw the screen with this line in the center.
!Continue making all replacements without querying first.
EEdit the replacement string.
^Go back to the previous replacement.

The replace-regexp and query-replace-regexp functions work similarly, but they take a regular expression as the string to be replaced.

Summary of search and replace commands

Table 5 shows a summary of the various Emacs search and replace commands you've just learned.

Table 5. Emacs search and replace commands
BindingCommand or functionDescription
C-s [string] [C-w] [C-y]isearch-forwardIncrementally search forward through the buffer for string (default is the last search string you gave, if any); C-w uses the text from point forward to the end of the word and C-y uses everything from point to the end of the line.
C-r [string] [C-w] [C-y]isearch-backwardIncrementally search backward through the buffer for string (default is the last search string you gave, if any); C-w uses the text from point forward to the end of the word, and C-y uses everything from point to the end of the line.
C-s Enter C-wword or phraseword-search-forwardSearch forward through the buffer for the given word or phrase, regardless of spacing.
C-r Enter C-wword or phraseword-search-backwardSearch backward through the buffer for the given word or phrase, regardless of spacing.
C-M-sisearch-forward-regexpIncrementally search forward through the buffer for a given regular expression.
C-M-risearch-backward-regexpIncrementally search backward through the buffer for a given regular expression.
replace-stringSearch for a given string from point to the end of the buffer and replace it with a given string.
replace-regexpSearch for a given regular expression from point to the end of the buffer and replace it with a given string.
M-%query-replaceSearch for a given string from point to the end of the buffer and, in each instance, query (as described in Table 4) to replace it with a given string.
C-M-%query-replace-regexpSearch for a given regular expression from point to the end of the buffer and, in each instance, query (as described in Table 4) to replace it with a given string.

Use the spelling checker

Ispell, an interactive UNIX spelling checker, is built into Emacs and is a powerful and convenient way to check buffers for misspelled words. The various ispell- functions are described in this section.

Spell check a word

Use the ispell-word function (or its equivalent key binding, M-$) to check the spelling of the word at point.

That word baid doesn't look right. Move point to it and check the spelling by typing M-$.

Emacs doesn't recognize this word either, so it's highlighted as a misspelling; you're given a list of suggestions in a new window above the buffer window, as in Figure 6. Each suggestion is prefaced with a character you can type to replace the misspelling with that suggestion. (You can also type C-g to cancel the replacement.)

Figure 6. Correct spelling in Emacs with Ispell
Correct spelling in Emacs with Ispell.

Find the word you want, bid, and press the key that corresponds to it. Ispell exits and the misspelled word is replaced with the one you chose.

Spell check a region

You can also spell check the region with the ispell-region function.

Try using the mouse to highlight the last two lines in the buffer by pressing and holding B1 as you drag over them (as described in the first tutorial in this series). Then type M-x ispell-region to spell check this highlighted region of text.

In the minibuffer, Ispell reports that spell checking is complete and that no misspellings have been found.

Spell check a buffer

To check the spelling of the whole buffer, use the ispell-buffer function.

Try running it: Type M-x ispell-buffer.

As with all the Ispell commands, you have many options whenever you encounter a misspelling in a buffer check. They are described in Table 6.

Table 6. Ispell word-replacement commands
KeyDescription
characterMake the suggested replacement prefaced by (character).
SpaceAccept this word as correct in this context.
iAccept this word as correct and insert it into the personal dictionary file.
aAccept this word as correct only for this Emacs session.
AAccept this word as correct only for this buffer in this Emacs session.
rReplace the word with a string you type (and that Ispell then rechecks).
RReplace the word with a string you type (and that Ispell then rechecks) and run a query-replace through the rest of the buffer.
lReplace the word with a given string and do a lookup of the new string in a given dictionary file.
uInsert a lowercase version of the word into the personal dictionary file.
mReplace the word with a given string, save it to the personal dictionary, and then recheck the word.
C-lRecenter the screen on the current line.
C-rEnter a recursive edit.
C-zSuspend Emacs. (In X, this iconifies the Emacs client window.)
xExit the spell check and move point back to its original position.
XExit the spell check, leaving point where it is.
qImmediately quit the spell check.
?Display a menu of options.

Catch misspellings as they happen

Flyspell mode is a special minor mode that highlights misspellings as you type them. This is particularly useful when you're writing quick documents (such as e-mails) or first drafts that have to get into production quickly. When Emacs encounters a misspelling, it doesn't stop you -- you can keep on typing -- but the misspelled word is highlighted in the buffer.

Flyspell mode works by running Ispell in the background; after you turn on Flyspell mode, even the existing text in the buffer is checked and any misspellings are highlighted.

Try it:

  1. Turn on Flyspell mode: Type M-x flyspell-mode.

  2. Move down to the end of the first stanza and type the following two lines, with the intentional misspelling on the first line:

    Little lamb, hwo made thee?
    Dost thou know who made thee?

Notice that Emacs didn't like Blake's antique Dost, even though you know it's right. Both it and the misspelled hwo are highlighted, as in Figure 7.

Figure 7. Use Emacs' Flyspell mode
Use Emacs' Flyspell mode

To correct the highlighted words, use the mouse pointer to click the middle button on each of them; a menu appears with suggested words. For hwo, choose the correct who; for Dost, choose Accept (buffer) to accept the spelling as correct for this buffer.

A few more commands are bound in Flyspell mode in addition to the mouse control; a list is given in Table 7.

Table 7. Key bindings for Flyspell mode
BindingDescription
M-$Correct the last misspelled word using Ispell.
M-x flyspell-auto-correct-word, M-TabCorrect the last misspelled word automatically, with a suggestion found with Ispell.
M-x flyspell-auto-correct-previous-wordCorrect the previous misspelled word automatically, with a suggestion found with Ispell.
M-x flyspell-correct-word, B2Display a pop-up menu with word suggestions.

Summary of Emacs spelling commands

Table 8 summarizes the various spelling functions you've just learned for Emacs, describing their meanings and giving the default key bindings, if any.

Table 8. Spelling commands for Emacs
BindingCommand or functionDescription
M-$ispell-wordCall Ispell to check the spelling of the word at point.
ispell-regionCall Ispell to check the spelling of the region.
ispell-bufferCall Ispell to check the spelling of all the words from point to the end of the buffer.
flyspell-modeCall Ispell to check the spelling of all the words in buffer in the background as you type and highlight all misspellings.

Summary

Wrap-up

With this tutorial to guide you, you've got a handle on many important editing concepts in Emacs, and you've learned a lot of powerful techniques along the way. You've also learned what Emacs modes are and how to use them, you learned various text-manipulation tricks -- including methods of indentation, changing case, and search and replace -- and you've learned how to use the Emacs spell checker and abbreviation facilities.

You're starting to get the hang of Emacs, but there's a lot more to it. Watch for the third installment in this series for a look at some advanced concepts.

Resources

Learn

Get products and technologies

  • Latest GNU Emacs: Download a free copy of the latest GNU Emacs for your operating system and architecture free of charge from the GNU Project Web site.
  • IBM trial software: Build your next development project with software for download directly from developerWorks.

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into AIX and Unix on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=AIX and UNIX, Open source
ArticleID=208259
ArticleTitle=Emacs editing environment, Part 2: Learn the essential modes and editing features of Emacs
publish-date=04102007