Transcript

Emacs editing environment, Part 2: Learn theessential modes and editing features of EmacsGet going with this famous open source editor

Skill Level: Introductory

Michael Stutz ([email protected])AuthorConsultant

10 Apr 2007

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

Section 1. 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 aroundthe 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 worklike other editors and word processors. But learning Emacs doesn't have to bedifficult. Once you get going, you'll see how intuitive it is and become morecomfortable with it after each use. This tutorial series shows you the way, taking youfrom 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 everydayediting, be well on your way to Emacs proficiency, and have a good feel for many of

Learn the essential modes and editing features of Emacs© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 31

the advanced capabilities of Emacs.

About this tutorial

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

Objectives

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

After completing this tutorial, you will have a firm knowledge of the editing modes ofEmacs 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 understandingof 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 haveat 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 recentcopy 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).

developerWorks® ibm.com/developerWorks

Learn the essential modes and editing features of EmacsPage 2 of 31 © Copyright IBM Corporation 1994, 2008. All rights reserved.

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 snapshotsof version 22 are also available. This tutorial works with any of these versions forEmacs. 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 --versionflag:

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

Section 2. 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 forinserting text into the buffer -- as you saw in the previous tutorial in this series, bothcommands and text insertion can be done at any time.

However, Emacs does have its own kind of editing modes, which are functions thatextend its capabilities or change the way some features work. Modes are generallywritten for editing a certain type or class of data, such as regular documents (writtenin any of the Indo-European languages), source code in a particular computerprogramming language (C, Fortran, Lisp, and so forth), text formatted a certain way(outlines, e-mail messages, usenet articles, character-based illustrations, and soforth) 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 systemprocesses are accessible through Emacs, including network connections andInternet Relay Chat (IRC), shell sessions, and the UNIX filesystem itself.

Modes are classified as either major or minor. The major mode dictates the mainediting 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 switchbetween major modes whenever you like. Specialized major modes offer extrafunctionality and aids (such as context highlighting and colorization) that can helpwhen you're editing certain kinds of documents, but you're not required to select aparticular mode to edit a certain kind of file or document -- a C program source codefile might be edited in any mode for editing text just as it might be done in the specialmode available for editing C programs.

ibm.com/developerWorks developerWorks®

Learn the essential modes and editing features of Emacs© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 3 of 31

Minor modes normally offer some feature or capability not associated with anyparticular major mode. Think of them as toggles that control features: Calling a minormode by its function name turns that minor mode on or off, and you can have manyminor 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), andAuto Fill mode to handle automatic word wrapping. All these minor modes and manyothers like them can be active at any one time.

This section of the tutorial shows you what you need to know to use the Emacsmodes 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 ofthe Emacs window, called the mode line, tells you all about the current buffer --including which modes are currently active. The current modes are indicated inparentheses toward the right side of the mode line. The abbreviated name of themajor 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, thisbuffer is opened with Lisp Interaction mode, which is a special mode for theevaluation of Lisp code.

See for yourself by starting Emacs in the usual way, and look at what's written in themode 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 linechanges. (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, rightafter the major mode. However, not all minor modes have this indicator -- someminor modes are self-evident, such as Tool Bar mode, which displays the graphicaltool bar at the top of the Emacs frame. Other minor modes in newer versions ofEmacs are so minor (and always on) that it would only clutter the display to havethem all shown; for example, the purpose of the Unify 8859 On Encoding minormode is to provide an encoding unification for the various ISO 8859 character sets,which is useful for internationalization.

developerWorks® ibm.com/developerWorks

Learn the essential modes and editing features of EmacsPage 4 of 31 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Additionally, some modes offer extra indicators that appear in the mode line. LineNumber mode, for instance, is indicated by an L followed by the line number in thebuffer 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 ofthe current mode. When you run this function, a new help buffer opens that lists allthe key bindings that are special to the current major mode in the buffer you typed itin 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

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 atypewriter or in a word-processor application; as the mode description says, itindents the current line of Lisp code. Because you haven't written any Lisp code inthis 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

ibm.com/developerWorks developerWorks®

Learn the essential modes and editing features of Emacs© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 5 of 31

default Emacs mode. To find out what is, switch to a new buffer: Type C-x b andgive the name lamb.txt as the name of the buffer. Get rid of the help buffer by typingC-x 1.

You'll see that your new lamb.txt buffer has a new major mode, Fundamental. This isthe default mode for Emacs buffers. It's the most plain and simple of all Emacsmodes, with the fewest special key bindings and settings. Here, the Tab key worksas 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 amode for you based on the file type. If you open a file containing C program sourcecode, C mode will be major mode; and, if you open a file containing text in a spokenlanguage 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 thatcertain files or certain types of buffers always open in a particular mode. Table 1describes popular Emacs modes and gives their function names.

Table 1. Popular Emacs modesMode Function Type Description

Fundamental fundamental-mode Major This mode is thedefault Emacsmode with minimalsettings andbindings.

Text text-mode Major This mode is thebasic mode forediting text.

Abbrev abbrev-mode Minor This mode is formaking and usingabbreviations (seeAbbrev mode).

Auto Fill auto-fill-mode Minor This mode is forautomatic wordwrap and fillinglong lines andparagraphs.

Overwrite overwrite-mode Minor This mode is foroverwriting anyexisting text in abuffer instead of

developerWorks® ibm.com/developerWorks

Learn the essential modes and editing features of EmacsPage 6 of 31 © Copyright IBM Corporation 1994, 2008. All rights reserved.

inserting text atpoint. It's bound bydefault to the Inskey.

C c-mode Major This mode is forediting C programsource code.

Line Number line-number-mode Minor This mode is fordisplaying thecurrent linenumber.

Lisp Interaction lisp-interaction Major This mode is forediting andcompiling Lispcode.

Paragraph-IndentText

paragraph-indent-text-mode Major This mode is aspecial variation ofthe Text modewhere theparagraph-movementcommands workfor paragraphswhose first linesare indented, andnot just forparagraphsseparated by blanklines.

TeX tex-mode Major This mode is forediting TeXdocuments.

WordStar wordstar-mode Major This special modeprovides the keybindings of theWordStar editor.

Set the mode

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

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

Type in Text mode

Text mode is a basic mode with few changes from the Fundamental mode, so itsbenefits are subtle; but it's a good base for editing text in spoken languages, such as

ibm.com/developerWorks developerWorks®

Learn the essential modes and editing features of Emacs© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 7 of 31

English. Many of the special modes for editing certain kinds of text or documentsfrom TeX mode to Outline mode are based on Text mode.

Try typing some text in your new buffer, continuing the theme of William Blake fromthe 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 previousindentations 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 Gavethee life, and baid thee feed, and press Enter to end this newparagraph.

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 ofdelight, and press Enter

4. Press Tab. Notice how you're shifted out many spaces -- a literal tabcharacter 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 allthe vales rejoice?

Your buffer should now look like Figure 2.

Figure 2. Type tabs in Text mode

developerWorks® ibm.com/developerWorks

Learn the essential modes and editing features of EmacsPage 8 of 31 © Copyright IBM Corporation 1994, 2008. All rights reserved.

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

Table 2. Text mode key bindingsKey Description or function

Esc Prefix for mode-specific commands

Esc Tab, M-Tab ispell-complete-word

Esc S, M-S center-paragraph

Esc s, M-s center-line

Section 3. Abbrev mode

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

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

ibm.com/developerWorks developerWorks®

Learn the essential modes and editing features of Emacs© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 9 of 31

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. Thesefunctions let you define a word in the buffer as an abbrev; the first applies the abbrevto any buffer you open in your current Emacs session, and the second defines theabbrev only to buffers with the same major mode as the current buffer. The latter isuseful for defining abbrevs that are only appropriate to certain modes, such as forlong 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 theend of the word (after the i).

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

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

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

Now move point to a new line and make a new abbrev the way you just did, bytyping 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, Abbrevmode is off. Turn it on: Type M-x abbrev-mode. Erase those two lines with thedefinitions 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 bufferlooks like Figure 3.

Figure 3. Abbrevs expanded in an Emacs buffer

developerWorks® ibm.com/developerWorks

Learn the essential modes and editing features of EmacsPage 10 of 31 © Copyright IBM Corporation 1994, 2008. All rights reserved.

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

Use a word as an abbrev definition

You can also define abbrevs for a single word in the buffer. This is particularly usefulwhen 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. Onceyou've done that, you're prompted in the minibuffer for the abbrev to replace thatword 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.

ibm.com/developerWorks developerWorks®

Learn the essential modes and editing features of Emacs© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 11 of 31

End the current line with a period and then type a few more lines to watch theexpansion 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 cin called.

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

Erase an abbrev

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

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

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

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

Section 4. Text manipulation

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

Indent and fill text

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

Try it:

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

developerWorks® ibm.com/developerWorks

Learn the essential modes and editing features of EmacsPage 12 of 31 © Copyright IBM Corporation 1994, 2008. All rights reserved.

2. Move point to the beginning of the line that reads, "Little lamb, I'll tellthee," 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 certainnumber of spaces to indent by preceding it with C-u followed by a number; use anegative 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

ibm.com/developerWorks developerWorks®

Learn the essential modes and editing features of Emacs© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 13 of 31

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 thefill-region function. A similar function, fill-paragraph, applies to the currentparagraph. It has a keyboard equivalent of M-q.

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

Like any of the Emacs formatting commands, the commands for indentation andfilling can be undone with the undo function, which was described in the first tutorialin 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 takeout any existing horizontal space. To do this, use the delete-horizontal-spacefunction, M-\ (that's the Meta key followed by the \ key). It removes all leadingwhitespace between the first nonspace character anywhere to the left of point andthe first nonspace character to the right of point, no matter where point happens tobe in the space.

Go ahead and try it. Take out all the leading spaces in the buffer by moving point tothe 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 alsomoves point. To add vertical space without moving point, run the open-linefunction, which is bound to C-o.

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

Figure 5. Remove horizontal space and insert vertical space

developerWorks® ibm.com/developerWorks

Learn the essential modes and editing features of EmacsPage 14 of 31 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Transpose text

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

Use C-t, the transpose-chars function, to transpose the single character beforepoint 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 Fcharacters.

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 onecharacter.

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

ibm.com/developerWorks developerWorks®

Learn the essential modes and editing features of Emacs© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 15 of 31

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 linebefore it.

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

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

Another useful command, delete-indentation, joins the line at point with theprevious line, separated by a space character. It's bound to M-^, which you type bypressing 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-wordfunction (bound to M-u) converts to uppercase letters of all the text beginning frompoint 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-cM-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-uM-u M-u M-u M-u M-u so that the entire line is converted to uppercaseletters.

developerWorks® ibm.com/developerWorks

Learn the essential modes and editing features of EmacsPage 16 of 31 © Copyright IBM Corporation 1994, 2008. All rights reserved.

3. Type C-a to move point to the beginning of the line and type C-c C-lC-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 withthe negative-argument function, M--, which you type by pressing and holding theMeta key and then pressing a hyphen character (-). You can apply thecase-changing commands to the region by using the downcase-region andupcase-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 anddescribes their meanings.

Table 3. Emacs text manipulation commandsBinding Command or function Description

C-x C-i, C-x Tab indent-rigidly This command indents lines in theregion (or at point).

fill-region This command fills all paragraphs inthe region.

M-q fill-paragraph This command fills the singleparagraph at point.

M-\ delete-horizontal-space This command removes anyhorizontal space to the right and leftof point.

C-o open-line This command opens a new line ofvertical space below point, withoutmoving point.

C-t transpose-chars This command transposes the singlecharacters to the right and left ofpoint.

M-t transpose-words This command transposes the singlewords to the right and left of point.

C-x C-t transpose-lines This command transposes the line atpoint with the line before it.

M-^ delete-indentation This command joins the line at pointwith the previous line. Preface withC-1 to join the line at point with thenext line.

M-u uppercase-word This command converts the text atpoint to the end of the word touppercase letters.

M-l downcase-word This command converts the text atpoint to the end of the word tolowercase letters.

ibm.com/developerWorks developerWorks®

Learn the essential modes and editing features of Emacs© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 17 of 31

C-x C-l downcase-region This command converts the region tolowercase letters.

C-x C-u upcase-region This command converts the region touppercase letters.

Section 5. Search and replace text

The commands for searching and replacing in Emacs work in all modes and aredescribed 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 firstcharacter. It searches in increments with every character you type, so if you searchfor the text lamb, for instance, as soon as you type the l, point moves to the next l inthe buffer; and when you type the a, it moves to the first instance of la (which mightor 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 withsearch-box facilities where you type a term and then press Enter (or -- worse -- youhave to click the OK button), an incremental search begins the moment you type thefirst 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 isbound to C-s. It searches forward from point in the buffer for the text you give it. Torepeat 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 inthe minibuffer that the end of the buffer has been reached. If you type C-s againafter that, the search wraps around to the beginning of the buffer (and you're sonotified in the minibuffer).

Try it:

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

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

developerWorks® ibm.com/developerWorks

Learn the essential modes and editing features of EmacsPage 18 of 31 © Copyright IBM Corporation 1994, 2008. All rights reserved.

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

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

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

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

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

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

Incremental searches are normally case-insensitive; however, if you specify anythingbut 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 searchfor the text that was last searched. When you get to the top of the buffer, typing C-ragain wraps around to the bottom.

Try it: Type C-r lit to search in reverse and then type C-r multiple times to wrapdown 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, butinstead of typing it, you'd rather paste it.

The non-incremental search works the same for both the forward and reverse

ibm.com/developerWorks developerWorks®

Learn the essential modes and editing features of Emacs© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 19 of 31

searches. To do it, press Enter after typing either C-s or C-r for the search, typethe 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 bedone 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 themno matter how they happen to be spaced or formatted -- even if they're split betweenlines.

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

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 newlinecharacter between the words.

To match phrases regardless of the spacing between words, use the Emacs wordsearch. You can do this with either a forward or reverse incremental search -- pressEnter, 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 Byin the second line of the phrase.

developerWorks® ibm.com/developerWorks

Learn the essential modes and editing features of EmacsPage 20 of 31 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Regexp search

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

Try searching forward and notice how the matches change depending on how youbuild 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 everycharacter 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 toreplace 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 itreplaced -- in this case, two.

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

Another powerful function for replacing text is replace-regexp, which takes aregular 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 instanceof the replacement. It's bound to M-%. Your choices for each match are described inTable 4.

ibm.com/developerWorks developerWorks®

Learn the essential modes and editing features of Emacs© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 21 of 31

Table 4. Options for Emacs' query-replace functionKey Description

Space, y Replace this match.

Del, n Skip this match and move to the next.

Enter, q Exit query-replace.

. Make this replacement and then exitquery-replace.

, Make this replacement, move point to it, and exitquery-replace.

C-r Specify a recursive edit.

C-w Delete the match and recursive edit.

C-l Redraw the screen with this line in the center.

! Continue making all replacements withoutquerying first.

E Edit the replacement string.

^ Go back to the previous replacement.

The replace-regexp and query-replace-regexp functions work similarly, butthey 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 commandsyou've just learned.

Table 5. Emacs search and replace commandsBinding Command or function Description

C-s [string] [C-w] [C-y] isearch-forward Incrementally search forwardthrough the buffer for string(default is the last search stringyou gave, if any); C-w uses thetext from point forward to theend of the word and C-y useseverything from point to the endof the line.

C-r [string] [C-w] [C-y] isearch-backward Incrementally search backwardthrough the buffer for string(default is the last search stringyou gave, if any); C-w uses thetext from point forward to theend of the word, and C-y useseverything from point to the endof the line.

C-s Enter C-w word orphrase

word-search-forward Search forward through thebuffer for the given word orphrase, regardless of spacing.

developerWorks® ibm.com/developerWorks

Learn the essential modes and editing features of EmacsPage 22 of 31 © Copyright IBM Corporation 1994, 2008. All rights reserved.

C-r Enter C-w word orphrase

word-search-backward Search backward through thebuffer for the given word orphrase, regardless of spacing.

C-M-s isearch-forward-regexp Incrementally search forwardthrough the buffer for a givenregular expression.

C-M-r isearch-backward-regexp Incrementally search backwardthrough the buffer for a givenregular expression.

replace-string Search for a given string frompoint to the end of the bufferand replace it with a givenstring.

replace-regexp Search for a given regularexpression from point to the endof the buffer and replace it witha given string.

M-% query-replace Search for a given string frompoint to the end of the bufferand, in each instance, query (asdescribed in Table 4) to replaceit with a given string.

C-M-% query-replace-regexp Search for a given regularexpression from point to the endof the buffer and, in eachinstance, query (as described inTable 4) to replace it with agiven string.

Section 6. Use the spelling checker

Ispell, an interactive UNIX spelling checker, is built into Emacs and is a powerful andconvenient 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 thespelling of the word at point.

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

Emacs doesn't recognize this word either, so it's highlighted as a misspelling; you'regiven a list of suggestions in a new window above the buffer window, as in Figure 6.

ibm.com/developerWorks developerWorks®

Learn the essential modes and editing features of Emacs© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 23 of 31

Each suggestion is prefaced with a character you can type to replace the misspellingwith that suggestion. (You can also type C-g to cancel the replacement.)

Figure 6. Correct spelling in Emacs with Ispell

Find the word you want, bid, and press the key that corresponds to it. Ispell exits andthe 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 andholding 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 nomisspellings 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.

developerWorks® ibm.com/developerWorks

Learn the essential modes and editing features of EmacsPage 24 of 31 © Copyright IBM Corporation 1994, 2008. All rights reserved.

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

Table 6. Ispell word-replacement commandsKey Description

character Make the suggested replacement prefaced by(character).

Space Accept this word as correct in this context.

i Accept this word as correct and insert it into thepersonal dictionary file.

a Accept this word as correct only for this Emacssession.

A Accept this word as correct only for this buffer inthis Emacs session.

r Replace the word with a string you type (and thatIspell then rechecks).

R Replace the word with a string you type (and thatIspell then rechecks) and run a query-replacethrough the rest of the buffer.

l Replace the word with a given string and do alookup of the new string in a given dictionary file.

u Insert a lowercase version of the word into thepersonal dictionary file.

m Replace the word with a given string, save it tothe personal dictionary, and then recheck theword.

C-l Recenter the screen on the current line.

C-r Enter a recursive edit.

C-z Suspend Emacs. (In X, this iconifies the Emacsclient window.)

x Exit the spell check and move point back to itsoriginal position.

X Exit the spell check, leaving point where it is.

q Immediately 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) orfirst drafts that have to get into production quickly. When Emacs encounters amisspelling, it doesn't stop you -- you can keep on typing -- but the misspelled wordis highlighted in the buffer.

Flyspell mode works by running Ispell in the background; after you turn on Flyspell

ibm.com/developerWorks developerWorks®

Learn the essential modes and editing features of Emacs© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 25 of 31

mode, even the existing text in the buffer is checked and any misspellings arehighlighted.

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

To correct the highlighted words, use the mouse pointer to click the middle button oneach of them; a menu appears with suggested words. For hwo, choose the correctwho; 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;

developerWorks® ibm.com/developerWorks

Learn the essential modes and editing features of EmacsPage 26 of 31 © Copyright IBM Corporation 1994, 2008. All rights reserved.

a list is given in Table 7.

Table 7. Key bindings for Flyspell modeBinding Description

M-$ Correct the last misspelled word using Ispell.

M-x flyspell-auto-correct-word, M-Tab Correct the last misspelled word automatically,with a suggestion found with Ispell.

M-xflyspell-auto-correct-previous-word

Correct the previous misspelled wordautomatically, with a suggestion found with Ispell.

M-x flyspell-correct-word, B2 Display 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 EmacsBinding Command or function Description

M-$ ispell-word Call Ispell to check the spellingof the word at point.

ispell-region Call Ispell to check the spellingof the region.

ispell-buffer Call Ispell to check the spellingof all the words from point to theend of the buffer.

flyspell-mode Call Ispell to check the spellingof all the words in buffer in thebackground as you type andhighlight all misspellings.

Section 7. Summary

Wrap-up

With this tutorial to guide you, you've got a handle on many important editingconcepts 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 learnedvarious text-manipulation tricks -- including methods of indentation, changing case,and search and replace -- and you've learned how to use the Emacs spell checkerand abbreviation facilities.

ibm.com/developerWorks developerWorks®

Learn the essential modes and editing features of Emacs© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 27 of 31

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

developerWorks® ibm.com/developerWorks

Learn the essential modes and editing features of EmacsPage 28 of 31 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Resources

Learn

• "Emacs editing environment": Check out other parts in this series.

• "Use free software within commercial UNIX" (developerWorks, February 2006):Learn how to install GNU Emacs on the IBM AIX operating system or anothercommercial UNIX.

• Emacs commands: The IBM DB2® Universal Database Information Center hasa quick summary of basic Emacs commands.

• "Using Emacs for XML documents" (developerWorks, December 2001): Learnhow to use the Emacs SGML and XML modes.

• GNU Project: Learn more about the GNU Project and the Free SoftwareFoundation from its Web site.

• Check out other articles and tutorials written by Michael Stutz:

• AIX and UNIX zone

• Across developerWorks and IBM

• Search the AIX and UNIX library by topic:

• System administration

• Application development

• Performance

• Porting

• Security

• Tips

• Tools and utilities

• Java™ technology

• Linux®

• Open source

• AIX and UNIX: The AIX and UNIX developerWorks zone provides a wealth ofinformation relating to all aspects of AIX systems administration and expandingyour UNIX skills.

• New to AIX and UNIX?: Visit the New to AIX and UNIX page to learn moreabout AIX and UNIX.

• AIX 5L Wiki: A collaborative environment for technical information related toAIX.

ibm.com/developerWorks developerWorks®

Learn the essential modes and editing features of Emacs© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 29 of 31

• Safari bookstore: Visit this e-reference library to find specific technicalresources.

• developerWorks technical events and webcasts: Stay current withdeveloperWorks technical events and webcasts.

• Podcasts: Tune in and catch up with IBM technical experts.

Get products and technologies

• Latest GNU Emacs: Download a free copy of the latest GNU Emacs for youroperating system and architecture free of charge from the GNU Project Website.

• IBM trial software: Build your next development project with software fordownload directly from developerWorks.

Discuss

• Participate in the developerWorks blogs and get involved in the developerWorkscommunity.

• Participate in the AIX and UNIX forums:

• AIX 5L -- technical forum

• AIX for Developers Forum

• Cluster Systems Management

• IBM Support Assistant

• Performance Tools -- technical

• Virtualization -- technical

• More AIX and UNIX forums

About the author

Michael StutzMichael Stutz is author of The Linux Cookbook , which he also designed and typesetusing only open source software. His research interests include digital publishing andthe future of the book. He has used various UNIX operating systems for 20 years.You can reach Michael at [email protected].

Trademarks

IBM, AIX, AIX 5L, and DB2 are registered trademarks of International BusinessMachines Corporation in the United States, other countries, or both.

developerWorks® ibm.com/developerWorks

Learn the essential modes and editing features of EmacsPage 30 of 31 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in theUnited States, other countries, or both.Linux is a registered trademark of Linus Torvalds in the United States, othercountries, or both.UNIX is a registered trademark of The Open Group in the United States and othercountries.

ibm.com/developerWorks developerWorks®

Learn the essential modes and editing features of Emacs© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 31 of 31