July 5, 2006

Emacs tips: Searching and replacing

Author: Nathan Willis

Even if you use Emacs every day, sometimes you'll misplace a word or phrase. When that happens, you'll be glad that Emacs has flexible, built-in search and replace commands to help you find exactly what you are looking for.

You start a basic search in Emacs by typing Ctrl-s. This launches isearch-forward, an incremental search. As soon as you type Ctrl-s, you can begin typing the search string that you are looking for, and Emacs will search for it as you type, highlighting the first match.

Emacs might find the first match after just the first few characters -- saving you keystrokes and freeing you from worry if you are looking for some complex, easily misspelled string. If you do mistype a character, just hit Backspace and re-type the correct one -- Emacs will keep up with you as you make changes.

As soon as you have found the word you are looking for, all you have to do is click in the active window to get back to your text editing; the search ends automatically.

As the name implies, isearch-forward searches forward from wherever the cursor is at the moment. To search backwards instead, you would type Ctrl-r, and follow the exact same procedure.

As either search finds matches for your string, it jumps the cursor to the position of that word -- beginning with the first instance it sees. To leap to the next instance, just press Ctrl-s (or Ctrl-r) again. Doing this, you can cycle through all of the matches in your document.

When you are not in the middle of a search, you can repeat the last search by typing Ctrl-s Ctrl-s -- in a sense, simply starting over the last search you performed, and jumping to the "next match." You can repeat other searches from earlier in the session by starting a search with Ctrl-s, then using Meta-n and Meta-p (for next and previous) to cycle through the search history.

Non-incremental searching

Emacs is unique in its preference for incremental searching -- most other editors make you type the entire search string before they begin looking for it. You may wonder, then, if Emacs can operate in this mode. The answer is a resounding yes.

To perform a non-incremental search, just type Ctrl-s, then press Enter. Now type the search string, and press Enter again. To perform a non-incremental search going backward, you would type Ctrl-r Enter searchstring Enter.

The old new 'un

Sometimes you are searching for a string just to jump to a particular location in a file, but another common usage is to search for a string in order to replace it. For this task, the best bet is what Emacs calls a query-replace. To use it, press Meta-%, type the string you are looking for followed by Enter, then the replacement string, also followed by Enter.

So, for example, if you want to replace the word "Fry" with the word "Bender," you would type Meta-% Fry Enter Bender Enter. Immediately, Emacs will jump to the first match that it finds. Here again, you are in an interactive mode -- Emacs will find and highlight this first match, but you must give it a thumbs-up or a thumbs-down before it will move on. To perform the replacement, press y, or to skip it, press n. To quit the search-and-replace, press q. To replace all matches without being asked for each one, press ! (the exclamation point).

Capital letters

Searches in Emacs are case-insensitive, so long as the search string is composed of lower-case letters only. This applies to normal search functions, search-and-replace functions, and regular expression searches. To make a search case-sensitive, all you have to do is specify a capital letter in the search string.

Making it complex

Emacs also has several forms of advanced searching, such as word search and regular expression search.

Word search looks for matches to the specified string while ignoring such non-word interlopers like punctuation, whitespace, and formatting characters. It is useful when you're editing formatted documents such as LaTeX files, or for when you need to find a string but you don't know exactly what characters may be in or around it. Starting a word search is much like starting a non-incremental search; type Ctrl-s, then press Enter. Then comes the difference -- you type Ctrl-w, then the search string, then finally Enter. So the word search Ctrl-s Enter Ctrl-w DVD RW Enter would find both DVD-RW and DVD+RW.

The most powerful searching tool in Emacs is a regular expression search. You can match single- and multi-character wildcards, ranges of characters, empty strings, and newlines, all according to the standard regular expression syntax. To start an (incremental) regular expression search, just press Ctrl-Meta-s or Ctrl-Meta-r instead of Ctrl-s and Ctrl-r.

Regular expression quick reference

. (period) - matches any single character except a newline.
* (asterisk) - matches zero or more instances of the preceding character.
+ (plus) - matches one or more instances of the preceding character.
? (question mark) - matches zero or one (but not more) instances of the preceding character.
\{n\} (backslash-braces) - matches exactly n repetitions of the preceding character.
[ ... ] (brackets) - delimit a set of possible characters.
^ (caret) - matches the beginning-of-line character.
$ (period) - matches the end-of-line character.

For the uninitiated, regular expressions are a powerful syntax for search patterns. The syntax is formally defined and is used in all kinds of programming languages and applications, from Perl to grep. People have written entire books on regular expressions, but most of us can get by with just the basics: wildcards, sets, and ranges. At left is a brief cheat sheet.

With these rules, you can create pretty complicated search patterns. The postfix operators (such as * and ?) can be appended not just to single characters, but to sets as well. So, for example, the expression ^[AaEeIiOoUu]? will find strings that start with a vowel (upper- or lower-case) at the beginning of a new line.

Regular expressions -- like Emacs itself -- are very powerful. If you want to learn more about them, including far more operators and options than are mentioned here, a good place to start is the Regular-Expressions.info reference site -- it has excellent tutorials and examples.

Emacs is happy to meet your searching and replacing needs even with its basic incremental search capability, so even if regular expressions are not your cup of tea, search no further.

Click Here!