Emacs has a nice search mode called incremental search. To use it,
type C-s
. The text "I-search:" will appear in the echo area. Now
start typing a search string. As you type, Emacs will search for your
string in real-time (starting at point), highlighting any matches it
finds. You can backspace and re-type text, and the search will
continue to change with the text you type. When you find a match, you
can hit C-s
to search again and jump to the next match, or you can
just hit Enter
to exit the search mode and leave the cursor at the
last match. C-g
will abort the search and put your cursor back where
you started. Searches will re-start at the top of a buffer if they hit
the bottom. You can search backwards in a similar fashion with C-r
.
To replace text that matches a search pattern, type M-%
. You'll see
"Query replace:" in the echo area. Type a search string, and hit
Enter
. The echo area will now display "Query replace <search string>
with:". Type the replacement string, and hit Enter
again. Emacs will
search through your buffer, looking for the search string. When it
finds it, it will display "Query replacing <search string> with
<replacement string>: (? for help)". Type "y" to replace this match
and move onto the next, or "n" to skip this match. Type "!" to replace
this occurrence of the search string and all other occurrences in your
buffer without prompting. As usual, you can type C-g
to abort a
search/replace operation.
All searches in Emacs are case-insensitive by default, unless you type at least one capital letter in your search string - in that case, the search becomes case-sensitive.
One nice feature you'll notice is that Emacs remembers the search and
replacement strings you've used, so if you type M-%
again, the last
search/replace operation can be repeated by just hitting the Enter
key. Prior search and replacement strings can be accessed with up- or
down-arrow keys or M-p
and M-n
(for previous- and next-,
respectively) - this is like the history mechanism in the Bash shell.
Another nice tip during searches is that C-w
will highlight the word
around the cursor, then successive words each time it's pressed during
a search (so the highlighted area will grow with each press of
C-w
). You can search again by typing C-s
, this time the search
string is whatever was highlighted.
Here are the search and replace commands we discussed:
C-s | Search forward |
C-r | Search backward |
M-% | Search and replace |
C-g | Abort a search |
C-w | During a search, highlight the word around the cursor |
Up, down arrow keys or M-p, M-n | Access search string history |