Chapter 4. Search and Replace Operations

The commands we discussed in the first two chapters are enough to get you started, but they’re certainly not enough to do any serious editing. If you’re using Emacs for anything longer than a few paragraphs, you’ll want the support for serious document preparation this chapter describes. In this chapter, we cover the various ways that Emacs lets you search for and replace text. Emacs provides the traditional search and search/replace facilities you would expect in any editor; it also provides several important variants, including incremental searches, regular expression searches, and query-replace. We also cover spell checking here, because this function is a kind of replacement (errors are sought and replaced with corrections). Finally, we cover word abbreviation mode; this feature is a kind of automatic replacement that can be a real time saver.

Different Kinds of Searches

While you’re editing, you frequently want to find something you’ve already typed. Rather than hunt through the file trying to find what you’re looking for, virtually all editors provide some kind of search feature that lets you look for a particular text string. Emacs is no exception to the rule. It supplies a search command—in fact, it provides a dizzying array of search commands. Here’s a quick summary of the different kinds of searches that are available:

Simple search

You give Emacs a text string (called a search string), and it finds the next occurrence. You will find this search in almost any editor.

Incremental search

With incremental search, Emacs starts to search the file as soon as you type the first character of a search string. It continues to search as you type more characters.

Word search

A word search is like a simple search, except that Emacs searches only for full words and phrases. For example, if you are searching for the word hat, you don’t have to worry about finding the word that. A word search is also useful when you need to find a phrase that is spread across two lines.

Regular expression search

To search for patterns that may vary slightly, you can use a regular expression search. For example, if you wanted to find all instances of B1 and B2, you could search for them using the regular expression B[12]. However, regular expressions can be extremely complex. We’ll give a brief introduction to this topic in this chapter; it is discussed more fully in Chapter 13.

Incremental regular expression search

This search procedure is a combination of an incremental search and a regular expression search.

You can search forward or backward. Searches can be either case-sensitive, meaning that Emacs considers upper- and lowercase letters to be different (i.e., the words This and this are different); or case-insensitive, in which upper- and lowercase are not differentiated (i.e., This and this are the same). By default, searches are case-insensitive, with upper- and lowercase letters considered to be the same. One exception: if you type any uppercase letters, Emacs makes the whole search string case-sensitive, because it assumes you are looking for something precise since you’ve made the extra effort to type some letters uppercase.

Replacement operations are closely related to searches. As with searches, Emacs offers you several different flavors:

Simple search and replace

In this procedure, Emacs replaces all occurrences of one string with another. Usually, this is too radical a solution and can have unintended results. Try query-replace instead.

Query-replace

With query-replace, Emacs conditionally replaces a string throughout a file. Emacs finds all occurrences of the search string, and for each one it asks you whether or not to perform the replacement. This type of replacement is useful if you need to change some but not all instances of a word or phrase throughout a file.

Regular expression replace

Regular expression replacement uses UNIX’s powerful “regular expressions” facility (discussed later in this chapter) to find the replacement string.

So now you know what you’ll be looking at. Don’t be intimidated by the wealth of different searches that are available. In practice, you’ll probably settle on one search command and one replace command and use these for 99 percent of your work. For example, we use incremental search and query-replace most of the time. If you’re a writer, you may use word search all the time; if you’re a programmer, you might want a regular expression search. If you’re just beginning, you may want to learn incremental search and read the rest of this chapter later. However, if you know what’s available, you’ll be able to make use of the other search commands when they become useful.

Incremental Search

Incremental search starts to work from the moment you type the first character of the search string. For the beginner, it isn’t the easiest kind of search to use, but it has lots of advantages. Many users like the efficiency of incremental searches; but if you’re inclined to make typos, you may find incremental search rather frustrating and may want to use a simple search instead. However, we’ll start with incremental search because Emacs clearly wants you to use it and offers some perks for doing so.

To start an incremental search, type C-s and then type the text you want to find. Emacs temporarily enters Isearch mode. (This doesn’t affect you much; we just thought you might want to know about it.) Notice how this search works: Emacs looks for each character as soon as you type it. For example, if you are searching for the word meter, in an incremental search Emacs finds the next m as soon as you type the m; it finds the next me as soon as you type the e; it finds the met as soon as you type the t; and so on. Sooner or later, you either find what you want, or Emacs is unable to find anything. If you find what you want, press RETURN; doing so stops the search at the current place in the file. If Emacs can’t find anything that matches your search string, it prints the message Search failed at the bottom of your screen and then it beeps.

Here’s what happens when we search for the word meter; the numbers show how the cursor moves with each new letter in the search string.

Type: C-s meter RETURN

Incremental Search

In this incremental search, Emacs moves the cursor from position 1 to 2, to 3, and so on, as you type the search string meter. Also, note that I-search appears on the mode line.

What happens if you find the string you’re looking for but not the right occurrence of the string? Let’s say you’re searching for the word eschatology and you find the word, but you’re still not in the right place. Simply press C-s again to find the next occurrence of the current search string. Emacs uses the same search string; you don’t have to retype it.

Always remember to press RETURN when you’ve found the text you want. Forgetting to stop the search (by pressing RETURN or with any other cursor movement command) is a common mistake: you type a few things, and suddenly Emacs is off looking at some completely different part of the file. What has happened? Emacs thinks you’re still searching, and it has just added the characters you’ve typed to the search string.

Incremental search can be mildly frustrating if you type the search string incorrectly. If you type a letter in your search string incorrectly, press DEL: Emacs moves back to the first instance of the reduced string in the file. If you keep pressing DEL to delete characters from the search string, you’ll see Emacs cycle back through the file to previous matches.

To cancel a search (that is, to give up searching), type C-g. This command brings you back to the place where the search began.

Note

When Emacs is actually in the process of searching, the meaning of C-g changes slightly. This fact is important if you need to cancel a search before Emacs finds what it is looking for. A single C-g brings you back to the last character that Emacs found successfully, letting it continue the search. Typing C-g twice cancels the search completely, bringing you back to the point at which you started.

To search backwards through a file, use C-r, which works exactly like C-s except that it searches in the opposite direction. It puts the cursor at the beginning of the text you find. Just as you can do when repeating C-s, you can press C-r to make the search go in the other direction without retyping the search string.

To avoid typing your search string, you can copy text from the buffer into the search string. To copy text from the cursor position through the next space or punctuation mark into the search string, type C-s C-w (it may help to think of C-s C-w as “copy a word“). To copy text from the cursor to the end of the line into the search string, type C-s C-y. Notice that the text that is yanked is always converted to lowercase; this conversion ensures that the search will be case-insensitive. You can also copy text from the kill ring to the search string by typing C-s ESC y. Once you’ve given this command, you can press ESC p to see previous items from the kill ring. ESC n takes you to the next item if you’ve gone back with ESC p.

Once you’re in an incremental search, certain keys (such as RETURN and DEL) have different functions than they normally do. This situation may sound confusing, but it’s actually fairly easy to get used to. Table 3-1 shows a summary of special key functions during incremental search.

Table 4-1. Incremental Search Commands

Keystrokes

Command Name

Action

C-s

isearch-forward

Start incremental search forward; follow by search string. Also, find next occurrence (forward) of search string.

C-r

isearch-backward

Start incremental search backward; follow by search string. Also, find next occurrence (backward) of search string.

RETURN

(none)

Exit a search.

C-g

keyboard-quit

Cancel incremental search (you may need to press it twice).

DEL

(none)

Delete character from search string.

C-s C-w

(none)

Start an incremental search with the word the cursor is on as the search string.

C-s C-y

(none)

Start an incremental search with the text from the cursor position to the end of the line as the search string.

C-s ESC y

(none)

Start an incremental search with text from the kill ring as the search string.

C-s C-s

(none)

Repeat previous search.

Simple Searches

Incremental searches are very efficient if you type the search string correctly. If you sometimes make errors and have to delete the incorrect characters and then go on, you may become frustrated with incremental search. Emacs also offers a simple, or nonincremental, search. To use a more straightforward search, type C-s RETURN or select Search from the Search menu. Type the search string, press RETURN, and Emacs begins the search. Simply press C-s again to repeat the search. To start a nonincremental search backwards through the file, press C-r RETURN or select Search Backwards from the Search menu. Again, you type the search string and press RETURN to begin the search. Table 3-2 summarizes the simple search commands.

Table 4-2. Simple Search Commands

Keystrokes

Action

C-s RETURN searchstring RETURN

Start nonincremental search forward.

SearchSearch

 

C-s

Repeat search forward.

C-r RETURN searchstring RETURN

Start nonincremental search backward.

SearchSearch Backwards

 

C-r

Repeat search backward.

Word Search

If you’re searching for a phrase and you know it’s in the file but you can’t find it with incremental search, try word search. (You probably can’t find your phrase with incremental search because the phrase has a line break in it.) Word search is a nonincremental search that ignores line breaks, spaces, and punctuation. It also requires that your search string match entire words in the file.

To do a word search, type C-s RETURN C-w (for word-search-forward). The prompt Word search appears in the minibuffer. (Don’t be put off by the earlier prompts: you’ll see an I-search prompt after typing C-s and a search prompt after pressing RETURN. Ignore these.) Type the search string and press RETURN. Emacs searches for the given string. To do a word search backwards, type C-r RETURN C-w instead. For example, assume that you have the following text, with the cursor at the beginning:

He said, "All good elephants are wise, aren't they?"
She answered, "Some are smarter than others, but we
think this is socially conditioned."

The command C-s RETURN C-w they she RETURN positions the cursor after the word She. It looks horrible, but it’s nothing more than a word search (C-s RETURN C-w) for the word they, followed by the word she. It ignores the punctuation (?<">) and the new line between they and she.

Assume that you’re looking for the word the. You don’t want to bother with thence, there, theater, thesis, blithe, or any other word that happens to contain the letters the. In this situation, neither an incremental search nor a simple search is very useful—you need a word search. If you’re writing a paper, word search is often exactly what you need. It is the only one of the three basic search commands that allows you to find what you want even if the phrase is split between two lines.

Now that you’ve seen the three most commonly used searches, you might want to experiment and see which you find most useful.

Get Learning GNU Emacs, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.