Update copyright year to 2014 by running admin/update-copyright.
[emacs.git] / doc / emacs / search.texi
blobbf47dec99b80cd810e4aab7f426b9012e0ba262d
1 @c This is part of the Emacs manual.
2 @c Copyright (C) 1985-1987, 1993-1995, 1997, 2000-2014 Free Software
3 @c Foundation, Inc.
4 @c See file emacs.texi for copying conditions.
5 @node Search
6 @chapter Searching and Replacement
7 @cindex searching
8 @cindex finding strings within text
10   Like other editors, Emacs has commands to search for occurrences of
11 a string.  Emacs also has commands to replace occurrences of a string
12 with a different string.  There are also commands that do the same
13 thing, but search for patterns instead of fixed strings.
15   You can also search multiple files under the control of a tags table
16 (@pxref{Tags Search}) or through the Dired @kbd{A} command
17 (@pxref{Operating on Files}), or ask the @code{grep} program to do it
18 (@pxref{Grep Searching}).
20 @menu
21 * Incremental Search::        Search happens as you type the string.
22 * Nonincremental Search::     Specify entire string and then search.
23 * Word Search::               Search for sequence of words.
24 * Symbol Search::             Search for a source code symbol.
25 * Regexp Search::             Search for match for a regexp.
26 * Regexps::                   Syntax of regular expressions.
27 * Regexp Backslash::          Regular expression constructs starting with `\'.
28 * Regexp Example::            A complex regular expression explained.
29 * Search Case::               To ignore case while searching, or not.
30 * Replace::                   Search, and replace some or all matches.
31 * Other Repeating Search::    Operating on all matches for some regexp.
32 @end menu
34 @node Incremental Search
35 @section Incremental Search
36 @cindex incremental search
37 @cindex isearch
39   The principal search command in Emacs is @dfn{incremental}: it
40 begins searching as soon as you type the first character of the search
41 string.  As you type in the search string, Emacs shows you where the
42 string (as you have typed it so far) would be found.  When you have
43 typed enough characters to identify the place you want, you can stop.
44 Depending on what you plan to do next, you may or may not need to
45 terminate the search explicitly with @key{RET}.
47 @table @kbd
48 @item C-s
49 Incremental search forward (@code{isearch-forward}).
50 @item C-r
51 Incremental search backward (@code{isearch-backward}).
52 @end table
54 @menu
55 * Basic Isearch::        Basic incremental search commands.
56 * Repeat Isearch::       Searching for the same string again.
57 * Error in Isearch::     When your string is not found.
58 * Special Isearch::      Special input in incremental search.
59 * Isearch Yank::         Commands that grab text into the search string
60                            or else edit the search string.
61 * Not Exiting Isearch::  Prefix argument and scrolling commands.
62 * Isearch Minibuffer::   Incremental search of the minibuffer history.
63 @end menu
65 @node Basic Isearch
66 @subsection Basics of Incremental Search
68 @table @kbd
69 @item C-s
70 Begin incremental search (@code{isearch-forward}).
71 @item C-r
72 Begin reverse incremental search (@code{isearch-backward}).
73 @end table
75 @kindex C-s
76 @findex isearch-forward
77   @kbd{C-s} (@code{isearch-forward}) starts a forward incremental
78 search.  It reads characters from the keyboard, and moves point just
79 past the end of the next occurrence of those characters in the buffer.
81   For instance, if you type @kbd{C-s} and then @kbd{F}, that puts the
82 cursor after the first @samp{F} that occurs in the buffer after the
83 starting point.  Then if you then type @kbd{O}, the cursor moves to
84 just after the first @samp{FO}; the @samp{F} in that @samp{FO} might
85 not be the first @samp{F} previously found.  After another @kbd{O},
86 the cursor moves to just after the first @samp{FOO}.
88 @cindex faces for highlighting search matches
89   At each step, Emacs highlights the @dfn{current match}---the buffer
90 text that matches the search string---using the @code{isearch} face
91 (@pxref{Faces}).  The current search string is also displayed in the
92 echo area.
94   If you make a mistake typing the search string, type @key{DEL}.
95 Each @key{DEL} cancels the last character of the search string.
97   When you are satisfied with the place you have reached, type
98 @key{RET}.  This stops searching, leaving the cursor where the search
99 brought it.  Also, any command not specially meaningful in searches
100 stops the searching and is then executed.  Thus, typing @kbd{C-a}
101 exits the search and then moves to the beginning of the line.
102 @key{RET} is necessary only if the next command you want to type is a
103 printing character, @key{DEL}, @key{RET}, or another character that is
104 special within searches (@kbd{C-q}, @kbd{C-w}, @kbd{C-r}, @kbd{C-s},
105 @kbd{C-y}, @kbd{M-y}, @kbd{M-r}, @kbd{M-c}, @kbd{M-e}, and some others
106 described below).
108   As a special exception, entering @key{RET} when the search string is
109 empty launches nonincremental search (@pxref{Nonincremental Search}).
111   When you exit the incremental search, it adds the original value of
112 point to the mark ring, without activating the mark; you can thus use
113 @kbd{C-u C-@key{SPC}} to return to where you were before beginning the
114 search.  @xref{Mark Ring}.  It only does this if the mark was not
115 already active.
117 @kindex C-r
118 @findex isearch-backward
119   To search backwards, use @kbd{C-r} (@code{isearch-backward}) instead
120 of @kbd{C-s} to start the search.  A backward search finds matches
121 that end before the starting point, just as a forward search finds
122 matches that begin after it.
124 @node Repeat Isearch
125 @subsection Repeating Incremental Search
127   Suppose you search forward for @samp{FOO} and find a match, but not
128 the one you expected to find: the @samp{FOO} you were aiming for
129 occurs later in the buffer.  In this event, type another @kbd{C-s} to
130 move to the next occurrence of the search string.  You can repeat this
131 any number of times.  If you overshoot, you can cancel some @kbd{C-s}
132 characters with @key{DEL}.  Similarly, each @kbd{C-r} in a backward
133 incremental search repeats the backward search.
135 @cindex lazy search highlighting
136 @vindex isearch-lazy-highlight
137   If you pause for a little while during incremental search, Emacs
138 highlights all the other possible matches for the search string that
139 are present on the screen.  This helps you anticipate where you can
140 get to by typing @kbd{C-s} or @kbd{C-r} to repeat the search.  The
141 other matches are highlighted differently from the current match,
142 using the customizable face @code{lazy-highlight} (@pxref{Faces}).  If
143 you don't like this feature, you can disable it by setting
144 @code{isearch-lazy-highlight} to @code{nil}.
146   After exiting a search, you can search for the same string again by
147 typing just @kbd{C-s C-s}.  The first @kbd{C-s} is the key that
148 invokes incremental search, and the second @kbd{C-s} means ``search
149 again''.  Similarly, @kbd{C-r C-r} searches backward for the last
150 search string.  In determining the last search string, it doesn't
151 matter whether the string was searched for with @kbd{C-s} or
152 @kbd{C-r}.
154   If you are searching forward but you realize you were looking for
155 something before the starting point, type @kbd{C-r} to switch to a
156 backward search, leaving the search string unchanged.  Similarly,
157 @kbd{C-s} in a backward search switches to a forward search.
159   If a search is failing and you ask to repeat it by typing another
160 @kbd{C-s}, it starts again from the beginning of the buffer.
161 Repeating a failing reverse search with @kbd{C-r} starts again from
162 the end.  This is called @dfn{wrapping around}, and @samp{Wrapped}
163 appears in the search prompt once this has happened.  If you keep on
164 going past the original starting point of the search, it changes to
165 @samp{Overwrapped}, which means that you are revisiting matches that
166 you have already seen.
168 @cindex search ring
169 @kindex M-n @r{(Incremental search)}
170 @kindex M-p @r{(Incremental search)}
171   To reuse earlier search strings, use the @dfn{search ring}.  The
172 commands @kbd{M-p} and @kbd{M-n} move through the ring to pick a
173 search string to reuse.  These commands leave the selected search ring
174 element in the minibuffer, where you can edit it.
176 @kindex M-e @r{(Incremental search)}
177   To edit the current search string in the minibuffer without
178 replacing it with items from the search ring, type @kbd{M-e}.  Type @key{RET},
179 @kbd{C-s} or @kbd{C-r} to finish editing the string and search for it.
181 @node Error in Isearch
182 @subsection Errors in Incremental Search
184   If your string is not found at all, the echo area says @samp{Failing
185 I-Search}, and the cursor moves past the place where Emacs found as
186 much of your string as it could.  Thus, if you search for @samp{FOOT},
187 and there is no @samp{FOOT}, you might see the cursor after the
188 @samp{FOO} in @samp{FOOL}.  In the echo area, the part of the search
189 string that failed to match is highlighted using the face
190 @code{isearch-fail}.
192   At this point, there are several things you can do.  If your string
193 was mistyped, you can use @key{DEL} to erase some of it and correct
194 it.  If you like the place you have found, you can type @key{RET} to
195 remain there.  Or you can type @kbd{C-g}, which removes from the
196 search string the characters that could not be found (the @samp{T} in
197 @samp{FOOT}), leaving those that were found (the @samp{FOO} in
198 @samp{FOOT}).  A second @kbd{C-g} at that point cancels the search
199 entirely, returning point to where it was when the search started.
201 @cindex quitting (in search)
202 @kindex C-g @r{(Incremental search)}
203   The quit command, @kbd{C-g}, does special things during searches;
204 just what it does depends on the status of the search.  If the search
205 has found what you specified and is waiting for input, @kbd{C-g}
206 cancels the entire search, moving the cursor back to where you started
207 the search.  If @kbd{C-g} is typed when there are characters in the
208 search string that have not been found---because Emacs is still
209 searching for them, or because it has failed to find them---then the
210 search string characters which have not been found are discarded from
211 the search string.  With them gone, the search is now successful and
212 waiting for more input, so a second @kbd{C-g} will cancel the entire
213 search.
215 @node Special Isearch
216 @subsection Special Input for Incremental Search
218   Some of the characters you type during incremental search have
219 special effects.
221 @cindex lax space matching
222 @kindex M-s SPC @r{(Incremental search)}
223 @kindex SPC @r{(Incremental search)}
224 @findex isearch-toggle-lax-whitespace
225 @vindex search-whitespace-regexp
226   By default, incremental search performs @dfn{lax space matching}:
227 each space, or sequence of spaces, matches any sequence of one or more
228 spaces in the text.  Hence, @samp{foo bar} matches @samp{foo bar},
229 @samp{foo  bar}, @samp{foo   bar}, and so on (but not @samp{foobar}).
230 More precisely, Emacs matches each sequence of space characters in the
231 search string to a regular expression specified by the variable
232 @code{search-whitespace-regexp}.  For example, set it to
233 @samp{"[[:space:]\n]+"} to make spaces match sequences of newlines as
234 well as spaces.  To toggle lax space matching, type @kbd{M-s SPC}
235 (@code{isearch-toggle-lax-whitespace}).  To disable this feature
236 entirely, change @code{search-whitespace-regexp} to @code{nil}; then
237 each space in the search string matches exactly one space
239   If the search string you entered contains only lower-case letters,
240 the search is case-insensitive; as long as an upper-case letter exists
241 in the search string, the search becomes case-sensitive.  If you
242 delete the upper-case character from the search string, it ceases to
243 have this effect.  @xref{Search Case}.
245   To search for a newline character, type @kbd{C-j}.
247   To search for other control characters, such as @key{control-S},
248 quote it by typing @kbd{C-q} first (@pxref{Inserting Text}).  To
249 search for non-@acronym{ASCII} characters, you can either use
250 @kbd{C-q} and enter its octal code, or use an input method
251 (@pxref{Input Methods}).  If an input method is enabled in the current
252 buffer when you start the search, you can use it in the search string
253 also.  While typing the search string, you can toggle the input method
254 with the command @kbd{C-\} (@code{isearch-toggle-input-method}).  You
255 can also turn on a non-default input method with @kbd{C-^}
256 (@code{isearch-toggle-specified-input-method}), which prompts for the
257 name of the input method.  When an input method is active during
258 incremental search, the search prompt includes the input method
259 mnemonic, like this:
261 @example
262 I-search [@var{im}]:
263 @end example
265 @noindent
266 @findex isearch-toggle-input-method
267 @findex isearch-toggle-specified-input-method
268 where @var{im} is the mnemonic of the active input method.  Any input
269 method you enable during incremental search remains enabled in the
270 current buffer afterwards.
272 @kindex M-% @r{(Incremental search)}
273   Typing @kbd{M-%} in incremental search invokes @code{query-replace}
274 or @code{query-replace-regexp} (depending on search mode) with the
275 current search string used as the string to replace.  A negative
276 prefix argument means to replace backward.  @xref{Query Replace}.
278 @kindex M-TAB @r{(Incremental search)}
279   Typing @kbd{M-@key{TAB}} in incremental search invokes
280 @code{isearch-complete}, which attempts to complete the search string
281 using the search ring as a list of completion alternatives.
282 @xref{Completion}.  In many operating systems, the @kbd{M-@key{TAB}}
283 key sequence is captured by the window manager; you then need to
284 rebind @code{isearch-complete} to another key sequence if you want to
285 use it (@pxref{Rebinding}).
287 @vindex isearch-mode-map
288   When incremental search is active, you can type @kbd{C-h C-h} to
289 access interactive help options, including a list of special key
290 bindings.  These key bindings are part of the keymap
291 @code{isearch-mode-map} (@pxref{Keymaps}).
293 @node Isearch Yank
294 @subsection Isearch Yanking
296 @kindex C-y @r{(Incremental search)}
297 @kindex M-y @r{(Incremental search)}
298 @findex isearch-yank-kill
299 @findex isearch-yank-pop
300   Within incremental search, @kbd{C-y} (@code{isearch-yank-kill})
301 appends the current kill to the search string.  @kbd{M-y}
302 (@code{isearch-yank-pop}), if called after @kbd{C-y}, replaces that
303 appended text with an earlier kill, similar to the usual @kbd{M-y}
304 (@code{yank-pop}) command (@pxref{Yanking}).  @kbd{Mouse-2} appends
305 the current X selection (@pxref{Primary Selection}).
307 @kindex C-w @r{(Incremental search)}
308 @findex isearch-yank-word-or-char
309   @kbd{C-w} (@code{isearch-yank-word-or-char}) appends the next
310 character or word at point to the search string.  This is an easy way
311 to search for another occurrence of the text at point.  (The decision
312 of whether to copy a character or a word is heuristic.)
314 @kindex M-s C-e @r{(Incremental search)}
315 @findex isearch-yank-line
316   Similarly, @kbd{M-s C-e} (@code{isearch-yank-line}) appends the rest
317 of the current line to the search string.  If point is already at the
318 end of a line, it appends the next line.
320   If the search is currently case-insensitive, both @kbd{C-w} and
321 @kbd{M-s C-e} convert the text they copy to lower case, so that the
322 search remains case-insensitive.
324 @kindex C-M-w @r{(Incremental search)}
325 @kindex C-M-y @r{(Incremental search)}
326 @findex isearch-del-char
327 @findex isearch-yank-char
328   @kbd{C-M-w} (@code{isearch-del-char}) deletes the last character
329 from the search string, and @kbd{C-M-y} (@code{isearch-yank-char})
330 appends the character after point to the search string.  An
331 alternative method to add the character after point is to enter the
332 minibuffer with @kbd{M-e} (@pxref{Repeat Isearch}) and type @kbd{C-f}
333 at the end of the search string in the minibuffer.
335 @node Not Exiting Isearch
336 @subsection Not Exiting Incremental Search
338 This subsection describes two categories of commands which you can
339 type without exiting the current incremental search, even though they
340 are not themselves part of incremental search.
342 @table @asis
343 @item Prefix Arguments
344 @vindex isearch-allow-prefix
345   In incremental search, when you enter a prefix argument
346 (@pxref{Arguments}), by default it will apply either to the next
347 action in the search or to the command that exits the search.
349   In previous versions of Emacs, entering a prefix argument always
350 terminated the search.  You can revert to this behavior by setting the
351 variable @code{isearch-allow-prefix} to @code{nil}.
353   When @code{isearch-allow-scroll} is non-@code{nil} (see below),
354 prefix arguments always have the default behavior described above.
356 @item Scrolling Commands
357 @vindex isearch-allow-scroll
358   Normally, scrolling commands exit incremental search.  If you change
359 the variable @code{isearch-allow-scroll} to a non-@code{nil} value,
360 that enables the use of the scroll-bar, as well as keyboard scrolling
361 commands like @kbd{C-v}, @kbd{M-v}, and @kbd{C-l} (@pxref{Scrolling}).
362 This applies only to calling these commands via their bound key
363 sequences---typing @kbd{M-x} will still exit the search.  You can give
364 prefix arguments to these commands in the usual way.  This feature
365 won't let you scroll the current match out of visibility, however.
367   The @code{isearch-allow-scroll} feature also affects some other
368 commands, such as @kbd{C-x 2} (@code{split-window-below}) and @kbd{C-x
369 ^} (@code{enlarge-window}), which don't exactly scroll but do affect
370 where the text appears on the screen.  It applies to any command whose
371 name has a non-@code{nil} @code{isearch-scroll} property.  So you can
372 control which commands are affected by changing these properties.
374   For example, to make @kbd{C-h l} usable within an incremental search
375 in all future Emacs sessions, use @kbd{C-h c} to find what command it
376 runs (@pxref{Key Help}), which is @code{view-lossage}.  Then you can
377 put the following line in your init file (@pxref{Init File}):
379 @example
380 (put 'view-lossage 'isearch-scroll t)
381 @end example
383 @noindent
384 This feature can be applied to any command that doesn't permanently
385 change point, the buffer contents, the match data, the current buffer,
386 or the selected window and frame.  The command must not itself attempt
387 an incremental search.
388 @end table
390 @node Isearch Minibuffer
391 @subsection Searching the Minibuffer
392 @cindex minibuffer history, searching
394 If you start an incremental search while the minibuffer is active,
395 Emacs searches the contents of the minibuffer.  Unlike searching an
396 ordinary buffer, the search string is not shown in the echo area,
397 because that is used to display the minibuffer.
399 If an incremental search fails in the minibuffer, it tries searching
400 the minibuffer history.  @xref{Minibuffer History}.  You can visualize
401 the minibuffer and its history as a series of ``pages'', with the
402 earliest history element on the first page and the current minibuffer
403 on the last page.  A forward search, @kbd{C-s}, searches forward to
404 later pages; a reverse search, @kbd{C-r}, searches backwards to
405 earlier pages.  Like in ordinary buffer search, a failing search can
406 wrap around, going from the last page to the first page or vice versa.
408 When the current match is on a history element, that history element
409 is pulled into the minibuffer.  If you exit the incremental search
410 normally (e.g., by typing @key{RET}), it remains in the minibuffer
411 afterwards.  Canceling the search, with @kbd{C-g}, restores the
412 contents of the minibuffer when you began the search.
414 @node Nonincremental Search
415 @section Nonincremental Search
416 @cindex nonincremental search
418   Emacs also has conventional nonincremental search commands, which require
419 you to type the entire search string before searching begins.
421 @table @kbd
422 @item C-s @key{RET} @var{string} @key{RET}
423 Search for @var{string}.
424 @item C-r @key{RET} @var{string} @key{RET}
425 Search backward for @var{string}.
426 @end table
428   To start a nonincremental search, first type @kbd{C-s @key{RET}}.
429 This enters the minibuffer to read the search string; terminate the
430 string with @key{RET}, and then the search takes place.  If the string
431 is not found, the search command signals an error.
433 @findex search-forward
434 @findex search-backward
435   When you type @kbd{C-s @key{RET}}, the @kbd{C-s} invokes incremental
436 search as usual.  That command is specially programmed to invoke the
437 command for nonincremental search, @code{search-forward}, if the
438 string you specify is empty.  (Such an empty argument would otherwise
439 be useless.)  @kbd{C-r @key{RET}} does likewise, invoking the command
440 @code{search-backward}.
442 @node Word Search
443 @section Word Search
444 @cindex word search
446   A @dfn{word search} finds a sequence of words without regard to the
447 type of punctuation between them.  For instance, if you enter a search
448 string that consists of two words separated by a single space, the
449 search matches any sequence of those two words separated by one or
450 more spaces, newlines, or other punctuation characters.  This is
451 particularly useful for searching text documents, because you don't
452 have to worry whether the words you are looking for are separated by
453 newlines or spaces.
455 @table @kbd
456 @item M-s w
457 If incremental search is active, toggle word search mode
458 (@code{isearch-toggle-word}); otherwise, begin an incremental forward
459 word search (@code{isearch-forward-word}).
460 @item M-s w @key{RET} @var{words} @key{RET}
461 Search for @var{words}, using a forward nonincremental word search.
462 @item M-s w C-r @key{RET} @var{words} @key{RET}
463 Search backward for @var{words}, using a nonincremental word search.
464 @end table
466 @kindex M-s w
467 @findex isearch-forward-word
468   To begin a forward incremental word search, type @kbd{M-s w}.  If
469 incremental search is not already active, this runs the command
470 @code{isearch-forward-word}.  If incremental search is already active
471 (whether a forward or backward search), @kbd{M-s w} switches to a word
472 search while keeping the direction of the search and the current
473 search string unchanged.  You can toggle word search back off by
474 typing @kbd{M-s w} again.
476 @findex word-search-forward
477 @findex word-search-backward
478   To begin a nonincremental word search, type @kbd{M-s w @key{RET}}
479 for a forward search, or @kbd{M-s w C-r @key{RET}} for a backward search.
480 These run the commands @code{word-search-forward} and
481 @code{word-search-backward} respectively.
483   Incremental and nonincremental word searches differ slightly in the
484 way they find a match.  In a nonincremental word search, the last word
485 in the search string must exactly match a whole word.  In an
486 incremental word search, the matching is more lax: the last word in
487 the search string can match part of a word, so that the matching
488 proceeds incrementally as you type.  This additional laxity does not
489 apply to the lazy highlight, which always matches whole words.
491 @node Symbol Search
492 @section Symbol Search
493 @cindex symbol search
495   A @dfn{symbol search} is much like an ordinary search, except that
496 the boundaries of the search must match the boundaries of a symbol.
497 The meaning of @dfn{symbol} in this context depends on the major mode,
498 and usually refers to a source code token, such as a Lisp symbol in
499 Emacs Lisp mode.  For instance, if you perform an incremental symbol
500 search for the Lisp symbol @code{forward-word}, it would not match
501 @code{isearch-forward-word}.  This feature is thus mainly useful for
502 searching source code.
504 @table @kbd
505 @item M-s _
506 If incremental search is active, toggle symbol search mode
507 (@code{isearch-toggle-symbol}); otherwise, begin an incremental
508 forward symbol search (@code{isearch-forward-symbol}).
509 @item M-s .
510 Start a symbol incremental search forward with the symbol found near
511 point added to the search string initially.
512 @item M-s _ @key{RET} @var{symbol} @key{RET}
513 Search forward for @var{symbol}, nonincrementally.
514 @item M-s _ C-r @key{RET} @var{symbol} @key{RET}
515 Search backward for @var{symbol}, nonincrementally.
516 @end table
518 @kindex M-s _
519 @kindex M-s .
520 @findex isearch-forward-symbol
521 @findex isearch-forward-symbol-at-point
522   To begin a forward incremental symbol search, type @kbd{M-s _} (or
523 @kbd{M-s .} if the symbol to search is near point).  If incremental
524 search is not already active, this runs the command
525 @code{isearch-forward-symbol}.  If incremental search is already
526 active, @kbd{M-s _} switches to a symbol search, preserving the
527 direction of the search and the current search string; you can disable
528 symbol search by typing @kbd{M-s _} again.  In incremental symbol
529 search, only the beginning of the search string is required to match
530 the beginning of a symbol.
532   To begin a nonincremental symbol search, type @kbd{M-s _ @key{RET}}
533 for a forward search, or @kbd{M-s _ C-r @key{RET}} or a backward
534 search.  In nonincremental symbol searches, the beginning and end of
535 the search string are required to match the beginning and end of a
536 symbol, respectively.
538 @node Regexp Search
539 @section Regular Expression Search
540 @cindex regexp search
541 @cindex search for a regular expression
543   A @dfn{regular expression} (or @dfn{regexp} for short) is a pattern
544 that denotes a class of alternative strings to match.  Emacs
545 provides both incremental and nonincremental ways to search for a
546 match for a regexp.  The syntax of regular expressions is explained in
547 the next section.
549 @table @kbd
550 @item C-M-s
551 Begin incremental regexp search (@code{isearch-forward-regexp}).
552 @item C-M-r
553 Begin reverse incremental regexp search (@code{isearch-backward-regexp}).
554 @end table
556 @kindex C-M-s
557 @findex isearch-forward-regexp
558 @kindex C-M-r
559 @findex isearch-backward-regexp
560   Incremental search for a regexp is done by typing @kbd{C-M-s}
561 (@code{isearch-forward-regexp}), by invoking @kbd{C-s} with a
562 prefix argument (whose value does not matter), or by typing @kbd{M-r}
563 within a forward incremental search.  This command reads a
564 search string incrementally just like @kbd{C-s}, but it treats the
565 search string as a regexp rather than looking for an exact match
566 against the text in the buffer.  Each time you add text to the search
567 string, you make the regexp longer, and the new regexp is searched
568 for.  To search backward for a regexp, use @kbd{C-M-r}
569 (@code{isearch-backward-regexp}), @kbd{C-r} with a prefix argument,
570 or @kbd{M-r} within a backward incremental search.
572   All of the special key sequences in an ordinary incremental search
573 do similar things in an incremental regexp search.  For instance,
574 typing @kbd{C-s} immediately after starting the search retrieves the
575 last incremental search regexp used and searches forward for it.
576 Incremental regexp and non-regexp searches have independent defaults.
577 They also have separate search rings, which you can access with
578 @kbd{M-p} and @kbd{M-n}.
580   Just as in ordinary incremental search, any @key{SPC} typed in
581 incremental regexp search matches any sequence of one or more
582 whitespace characters.  The variable @code{search-whitespace-regexp}
583 specifies the regexp for the lax space matching, and @kbd{M-s SPC}
584 (@code{isearch-toggle-lax-whitespace}) toggles the feature.
585 @xref{Special Isearch}.
587   In some cases, adding characters to the regexp in an incremental
588 regexp search can make the cursor move back and start again.  For
589 example, if you have searched for @samp{foo} and you add @samp{\|bar},
590 the cursor backs up in case the first @samp{bar} precedes the first
591 @samp{foo}.  @xref{Regexps}.
593   Forward and backward regexp search are not symmetrical, because
594 regexp matching in Emacs always operates forward, starting with the
595 beginning of the regexp.  Thus, forward regexp search scans forward,
596 trying a forward match at each possible starting position.  Backward
597 regexp search scans backward, trying a forward match at each possible
598 starting position.  These search methods are not mirror images.
600 @findex re-search-forward
601 @findex re-search-backward
602   Nonincremental search for a regexp is done with the commands
603 @code{re-search-forward} and @code{re-search-backward}.  You can
604 invoke these with @kbd{M-x}, or by way of incremental regexp search
605 with @kbd{C-M-s @key{RET}} and @kbd{C-M-r @key{RET}}.
607   If you use the incremental regexp search commands with a prefix
608 argument, they perform ordinary string search, like
609 @code{isearch-forward} and @code{isearch-backward}.  @xref{Incremental
610 Search}.
612 @node Regexps
613 @section Syntax of Regular Expressions
614 @cindex syntax of regexps
615 @cindex regular expression
616 @cindex regexp
618   This manual describes regular expression features that users
619 typically use.  @xref{Regular Expressions,,, elisp, The Emacs Lisp
620 Reference Manual}, for additional features used mainly in Lisp
621 programs.
623   Regular expressions have a syntax in which a few characters are
624 special constructs and the rest are @dfn{ordinary}.  An ordinary
625 character matches that same character and nothing else.  The special
626 characters are @samp{$^.*+?[\}.  The character @samp{]} is special if
627 it ends a character alternative (see later).  The character @samp{-}
628 is special inside a character alternative.  Any other character
629 appearing in a regular expression is ordinary, unless a @samp{\}
630 precedes it.  (When you use regular expressions in a Lisp program,
631 each @samp{\} must be doubled, see the example near the end of this
632 section.)
634   For example, @samp{f} is not a special character, so it is ordinary, and
635 therefore @samp{f} is a regular expression that matches the string
636 @samp{f} and no other string.  (It does @emph{not} match the string
637 @samp{ff}.)  Likewise, @samp{o} is a regular expression that matches
638 only @samp{o}.  (When case distinctions are being ignored, these regexps
639 also match @samp{F} and @samp{O}, but we consider this a generalization
640 of ``the same string'', rather than an exception.)
642   Any two regular expressions @var{a} and @var{b} can be concatenated.
643 The result is a regular expression which matches a string if @var{a}
644 matches some amount of the beginning of that string and @var{b}
645 matches the rest of the string.  For example, concatenating the
646 regular expressions @samp{f} and @samp{o} gives the regular expression
647 @samp{fo}, which matches only the string @samp{fo}.  Still trivial.
648 To do something nontrivial, you need to use one of the special
649 characters.  Here is a list of them.
651 @table @asis
652 @item @kbd{.}@: @r{(Period)}
653 is a special character that matches any single character except a
654 newline.  For example, the regular expressions @samp{a.b} matches any
655 three-character string that begins with @samp{a} and ends with
656 @samp{b}.
658 @item @kbd{*}
659 is not a construct by itself; it is a postfix operator that means to
660 match the preceding regular expression repetitively any number of
661 times, as many times as possible.  Thus, @samp{o*} matches any number
662 of @samp{o}s, including no @samp{o}s.
664 @samp{*} always applies to the @emph{smallest} possible preceding
665 expression.  Thus, @samp{fo*} has a repeating @samp{o}, not a repeating
666 @samp{fo}.  It matches @samp{f}, @samp{fo}, @samp{foo}, and so on.
668 The matcher processes a @samp{*} construct by matching, immediately,
669 as many repetitions as can be found.  Then it continues with the rest
670 of the pattern.  If that fails, backtracking occurs, discarding some
671 of the matches of the @samp{*}-modified construct in case that makes
672 it possible to match the rest of the pattern.  For example, in matching
673 @samp{ca*ar} against the string @samp{caaar}, the @samp{a*} first
674 tries to match all three @samp{a}s; but the rest of the pattern is
675 @samp{ar} and there is only @samp{r} left to match, so this try fails.
676 The next alternative is for @samp{a*} to match only two @samp{a}s.
677 With this choice, the rest of the regexp matches successfully.
679 @item @kbd{+}
680 is a postfix operator, similar to @samp{*} except that it must match
681 the preceding expression at least once.  Thus, @samp{ca+r} matches the
682 strings @samp{car} and @samp{caaaar} but not the string @samp{cr},
683 whereas @samp{ca*r} matches all three strings.
685 @item @kbd{?}
686 is a postfix operator, similar to @samp{*} except that it can match
687 the preceding expression either once or not at all.  Thus, @samp{ca?r}
688 matches @samp{car} or @samp{cr}, and nothing else.
690 @item @kbd{*?}, @kbd{+?}, @kbd{??}
691 @cindex non-greedy regexp matching
692 are non-@dfn{greedy} variants of the operators above.  The normal
693 operators @samp{*}, @samp{+}, @samp{?} match as much as they can, as
694 long as the overall regexp can still match.  With a following
695 @samp{?}, they will match as little as possible.
697 Thus, both @samp{ab*} and @samp{ab*?} can match the string @samp{a}
698 and the string @samp{abbbb}; but if you try to match them both against
699 the text @samp{abbb}, @samp{ab*} will match it all (the longest valid
700 match), while @samp{ab*?}  will match just @samp{a} (the shortest
701 valid match).
703 Non-greedy operators match the shortest possible string starting at a
704 given starting point; in a forward search, though, the earliest
705 possible starting point for match is always the one chosen.  Thus, if
706 you search for @samp{a.*?$} against the text @samp{abbab} followed by
707 a newline, it matches the whole string.  Since it @emph{can} match
708 starting at the first @samp{a}, it does.
710 @item @kbd{\@{@var{n}\@}}
711 is a postfix operator specifying @var{n} repetitions---that is, the
712 preceding regular expression must match exactly @var{n} times in a
713 row.  For example, @samp{x\@{4\@}} matches the string @samp{xxxx} and
714 nothing else.
716 @item @kbd{\@{@var{n},@var{m}\@}}
717 is a postfix operator specifying between @var{n} and @var{m}
718 repetitions---that is, the preceding regular expression must match at
719 least @var{n} times, but no more than @var{m} times.  If @var{m} is
720 omitted, then there is no upper limit, but the preceding regular
721 expression must match at least @var{n} times.@* @samp{\@{0,1\@}} is
722 equivalent to @samp{?}. @* @samp{\@{0,\@}} is equivalent to
723 @samp{*}. @* @samp{\@{1,\@}} is equivalent to @samp{+}.
725 @item @kbd{[ @dots{} ]}
726 is a @dfn{character set}, beginning with @samp{[} and terminated by
727 @samp{]}.
729 In the simplest case, the characters between the two brackets are what
730 this set can match.  Thus, @samp{[ad]} matches either one @samp{a} or
731 one @samp{d}, and @samp{[ad]*} matches any string composed of just
732 @samp{a}s and @samp{d}s (including the empty string).  It follows that
733 @samp{c[ad]*r} matches @samp{cr}, @samp{car}, @samp{cdr},
734 @samp{caddaar}, etc.
736 You can also include character ranges in a character set, by writing the
737 starting and ending characters with a @samp{-} between them.  Thus,
738 @samp{[a-z]} matches any lower-case @acronym{ASCII} letter.  Ranges may be
739 intermixed freely with individual characters, as in @samp{[a-z$%.]},
740 which matches any lower-case @acronym{ASCII} letter or @samp{$}, @samp{%} or
741 period.
743 You can also include certain special @dfn{character classes} in a
744 character set.  A @samp{[:} and balancing @samp{:]} enclose a
745 character class inside a character alternative.  For instance,
746 @samp{[[:alnum:]]} matches any letter or digit.  @xref{Char Classes,,,
747 elisp, The Emacs Lisp Reference Manual}, for a list of character
748 classes.
750 To include a @samp{]} in a character set, you must make it the first
751 character.  For example, @samp{[]a]} matches @samp{]} or @samp{a}.  To
752 include a @samp{-}, write @samp{-} as the first or last character of the
753 set, or put it after a range.  Thus, @samp{[]-]} matches both @samp{]}
754 and @samp{-}.
756 To include @samp{^} in a set, put it anywhere but at the beginning of
757 the set.  (At the beginning, it complements the set---see below.)
759 When you use a range in case-insensitive search, you should write both
760 ends of the range in upper case, or both in lower case, or both should
761 be non-letters.  The behavior of a mixed-case range such as @samp{A-z}
762 is somewhat ill-defined, and it may change in future Emacs versions.
764 @item @kbd{[^ @dots{} ]}
765 @samp{[^} begins a @dfn{complemented character set}, which matches any
766 character except the ones specified.  Thus, @samp{[^a-z0-9A-Z]} matches
767 all characters @emph{except} @acronym{ASCII} letters and digits.
769 @samp{^} is not special in a character set unless it is the first
770 character.  The character following the @samp{^} is treated as if it
771 were first (in other words, @samp{-} and @samp{]} are not special there).
773 A complemented character set can match a newline, unless newline is
774 mentioned as one of the characters not to match.  This is in contrast to
775 the handling of regexps in programs such as @code{grep}.
777 @item @kbd{^}
778 is a special character that matches the empty string, but only at the
779 beginning of a line in the text being matched.  Otherwise it fails to
780 match anything.  Thus, @samp{^foo} matches a @samp{foo} that occurs at
781 the beginning of a line.
783 For historical compatibility reasons, @samp{^} can be used with this
784 meaning only at the beginning of the regular expression, or after
785 @samp{\(} or @samp{\|}.
787 @item @kbd{$}
788 is similar to @samp{^} but matches only at the end of a line.  Thus,
789 @samp{x+$} matches a string of one @samp{x} or more at the end of a line.
791 For historical compatibility reasons, @samp{$} can be used with this
792 meaning only at the end of the regular expression, or before @samp{\)}
793 or @samp{\|}.
795 @item @kbd{\}
796 has two functions: it quotes the special characters (including
797 @samp{\}), and it introduces additional special constructs.
799 Because @samp{\} quotes special characters, @samp{\$} is a regular
800 expression that matches only @samp{$}, and @samp{\[} is a regular
801 expression that matches only @samp{[}, and so on.
803 See the following section for the special constructs that begin
804 with @samp{\}.
805 @end table
807   Note: for historical compatibility, special characters are treated as
808 ordinary ones if they are in contexts where their special meanings make no
809 sense.  For example, @samp{*foo} treats @samp{*} as ordinary since there is
810 no preceding expression on which the @samp{*} can act.  It is poor practice
811 to depend on this behavior; it is better to quote the special character anyway,
812 regardless of where it appears.
814 As a @samp{\} is not special inside a character alternative, it can
815 never remove the special meaning of @samp{-} or @samp{]}.  So you
816 should not quote these characters when they have no special meaning
817 either.  This would not clarify anything, since backslashes can
818 legitimately precede these characters where they @emph{have} special
819 meaning, as in @samp{[^\]} (@code{"[^\\]"} for Lisp string syntax),
820 which matches any single character except a backslash.
822 @node Regexp Backslash
823 @section Backslash in Regular Expressions
825   For the most part, @samp{\} followed by any character matches only
826 that character.  However, there are several exceptions: two-character
827 sequences starting with @samp{\} that have special meanings.  The
828 second character in the sequence is always an ordinary character when
829 used on its own.  Here is a table of @samp{\} constructs.
831 @table @kbd
832 @item \|
833 specifies an alternative.  Two regular expressions @var{a} and @var{b}
834 with @samp{\|} in between form an expression that matches some text if
835 either @var{a} matches it or @var{b} matches it.  It works by trying to
836 match @var{a}, and if that fails, by trying to match @var{b}.
838 Thus, @samp{foo\|bar} matches either @samp{foo} or @samp{bar}
839 but no other string.
841 @samp{\|} applies to the largest possible surrounding expressions.  Only a
842 surrounding @samp{\( @dots{} \)} grouping can limit the grouping power of
843 @samp{\|}.
845 Full backtracking capability exists to handle multiple uses of @samp{\|}.
847 @item \( @dots{} \)
848 is a grouping construct that serves three purposes:
850 @enumerate
851 @item
852 To enclose a set of @samp{\|} alternatives for other operations.
853 Thus, @samp{\(foo\|bar\)x} matches either @samp{foox} or @samp{barx}.
855 @item
856 To enclose a complicated expression for the postfix operators @samp{*},
857 @samp{+} and @samp{?} to operate on.  Thus, @samp{ba\(na\)*} matches
858 @samp{bananana}, etc., with any (zero or more) number of @samp{na}
859 strings.
861 @item
862 To record a matched substring for future reference.
863 @end enumerate
865 This last application is not a consequence of the idea of a
866 parenthetical grouping; it is a separate feature that is assigned as a
867 second meaning to the same @samp{\( @dots{} \)} construct.  In practice
868 there is usually no conflict between the two meanings; when there is
869 a conflict, you can use a ``shy'' group.
871 @item \(?: @dots{} \)
872 @cindex shy group, in regexp
873 specifies a ``shy'' group that does not record the matched substring;
874 you can't refer back to it with @samp{\@var{d}}.  This is useful
875 in mechanically combining regular expressions, so that you
876 can add groups for syntactic purposes without interfering with
877 the numbering of the groups that are meant to be referred to.
879 @item \@var{d}
880 @cindex back reference, in regexp
881 matches the same text that matched the @var{d}th occurrence of a
882 @samp{\( @dots{} \)} construct.  This is called a @dfn{back
883 reference}.
885 After the end of a @samp{\( @dots{} \)} construct, the matcher remembers
886 the beginning and end of the text matched by that construct.  Then,
887 later on in the regular expression, you can use @samp{\} followed by the
888 digit @var{d} to mean ``match the same text matched the @var{d}th time
889 by the @samp{\( @dots{} \)} construct''.
891 The strings matching the first nine @samp{\( @dots{} \)} constructs
892 appearing in a regular expression are assigned numbers 1 through 9 in
893 the order that the open-parentheses appear in the regular expression.
894 So you can use @samp{\1} through @samp{\9} to refer to the text matched
895 by the corresponding @samp{\( @dots{} \)} constructs.
897 For example, @samp{\(.*\)\1} matches any newline-free string that is
898 composed of two identical halves.  The @samp{\(.*\)} matches the first
899 half, which may be anything, but the @samp{\1} that follows must match
900 the same exact text.
902 If a particular @samp{\( @dots{} \)} construct matches more than once
903 (which can easily happen if it is followed by @samp{*}), only the last
904 match is recorded.
906 @item \`
907 matches the empty string, but only at the beginning of the string or
908 buffer (or its accessible portion) being matched against.
910 @item \'
911 matches the empty string, but only at the end of the string or buffer
912 (or its accessible portion) being matched against.
914 @item \=
915 matches the empty string, but only at point.
917 @item \b
918 matches the empty string, but only at the beginning or
919 end of a word.  Thus, @samp{\bfoo\b} matches any occurrence of
920 @samp{foo} as a separate word.  @samp{\bballs?\b} matches
921 @samp{ball} or @samp{balls} as a separate word.
923 @samp{\b} matches at the beginning or end of the buffer
924 regardless of what text appears next to it.
926 @item \B
927 matches the empty string, but @emph{not} at the beginning or
928 end of a word.
930 @item \<
931 matches the empty string, but only at the beginning of a word.
932 @samp{\<} matches at the beginning of the buffer only if a
933 word-constituent character follows.
935 @item \>
936 matches the empty string, but only at the end of a word.  @samp{\>}
937 matches at the end of the buffer only if the contents end with a
938 word-constituent character.
940 @item \w
941 matches any word-constituent character.  The syntax table determines
942 which characters these are.  @xref{Syntax Tables,, Syntax Tables,
943 elisp, The Emacs Lisp Reference Manual}.
945 @item \W
946 matches any character that is not a word-constituent.
948 @item \_<
949 matches the empty string, but only at the beginning of a symbol.
950 A symbol is a sequence of one or more symbol-constituent characters.
951 A symbol-constituent character is a character whose syntax is either
952 @samp{w} or @samp{_}.  @samp{\_<} matches at the beginning of the
953 buffer only if a symbol-constituent character follows.
955 @item \_>
956 matches the empty string, but only at the end of a symbol.  @samp{\_>}
957 matches at the end of the buffer only if the contents end with a
958 symbol-constituent character.
960 @item \s@var{c}
961 matches any character whose syntax is @var{c}.  Here @var{c} is a
962 character that designates a particular syntax class: thus, @samp{w}
963 for word constituent, @samp{-} or @samp{ } for whitespace, @samp{.}
964 for ordinary punctuation, etc.  @xref{Syntax Tables,, Syntax Tables,
965 elisp, The Emacs Lisp Reference Manual}.
967 @item \S@var{c}
968 matches any character whose syntax is not @var{c}.
970 @cindex categories of characters
971 @cindex characters which belong to a specific language
972 @findex describe-categories
973 @item \c@var{c}
974 matches any character that belongs to the category @var{c}.  For
975 example, @samp{\cc} matches Chinese characters, @samp{\cg} matches
976 Greek characters, etc.  For the description of the known categories,
977 type @kbd{M-x describe-categories @key{RET}}.
979 @item \C@var{c}
980 matches any character that does @emph{not} belong to category
981 @var{c}.
982 @end table
984   The constructs that pertain to words and syntax are controlled by
985 the setting of the syntax table.  @xref{Syntax Tables,, Syntax Tables,
986 elisp, The Emacs Lisp Reference Manual}.
988 @node Regexp Example
989 @section Regular Expression Example
991   Here is an example of a regexp---similar to the regexp that Emacs
992 uses, by default, to recognize the end of a sentence, not including
993 the following space (i.e., the variable @code{sentence-end-base}):
995 @example
996 @verbatim
997 [.?!][]\"')}]*
998 @end verbatim
999 @end example
1001 @noindent
1002 This contains two parts in succession: a character set matching
1003 period, @samp{?}, or @samp{!}, and a character set matching
1004 close-brackets, quotes, or parentheses, repeated zero or more times.
1006 @node Search Case
1007 @section Searching and Case
1009   Searches in Emacs normally ignore the case of the text they are
1010 searching through, if you specify the text in lower case.  Thus, if
1011 you specify searching for @samp{foo}, then @samp{Foo} and @samp{foo}
1012 also match.  Regexps, and in particular character sets, behave
1013 likewise: @samp{[ab]} matches @samp{a} or @samp{A} or @samp{b} or
1014 @samp{B}.
1016   An upper-case letter anywhere in the incremental search string makes
1017 the search case-sensitive.  Thus, searching for @samp{Foo} does not find
1018 @samp{foo} or @samp{FOO}.  This applies to regular expression search as
1019 well as to string search.  The effect ceases if you delete the
1020 upper-case letter from the search string.
1022   Typing @kbd{M-c} within an incremental search toggles the case
1023 sensitivity of that search.  The effect does not extend beyond the
1024 current incremental search to the next one, but it does override the
1025 effect of adding or removing an upper-case letter in the current
1026 search.
1028 @vindex case-fold-search
1029   If you set the variable @code{case-fold-search} to @code{nil}, then
1030 all letters must match exactly, including case.  This is a per-buffer
1031 variable; altering the variable normally affects only the current buffer,
1032 unless you change its default value.  @xref{Locals}.
1033 This variable applies to nonincremental searches also, including those
1034 performed by the replace commands (@pxref{Replace}) and the minibuffer
1035 history matching commands (@pxref{Minibuffer History}).
1037   Several related variables control case-sensitivity of searching and
1038 matching for specific commands or activities.  For instance,
1039 @code{tags-case-fold-search} controls case sensitivity for
1040 @code{find-tag}.  To find these variables, do @kbd{M-x
1041 apropos-variable @key{RET} case-fold-search @key{RET}}.
1043 @node Replace
1044 @section Replacement Commands
1045 @cindex replacement
1046 @cindex search-and-replace commands
1047 @cindex string substitution
1048 @cindex global substitution
1050   Emacs provides several commands for performing search-and-replace
1051 operations.  In addition to the simple @kbd{M-x replace-string}
1052 command, there is @kbd{M-%} (@code{query-replace}), which presents
1053 each occurrence of the pattern and asks you whether to replace it.
1055   The replace commands normally operate on the text from point to the
1056 end of the buffer.  When the region is active, they operate on it
1057 instead (@pxref{Mark}).  The basic replace commands replace one
1058 @dfn{search string} (or regexp) with one @dfn{replacement string}.  It
1059 is possible to perform several replacements in parallel, using the
1060 command @code{expand-region-abbrevs} (@pxref{Expanding Abbrevs}).
1062 @vindex replace-lax-whitespace
1063   Unlike incremental search, the replacement commands do not use lax
1064 space matching (@pxref{Special Isearch}) by default.  To enable lax
1065 space matching for replacement, change the variable
1066 @code{replace-lax-whitespace} to @code{t}.  (This only affects how
1067 Emacs finds the text to replace, not the replacement text.)
1069 @menu
1070 * Unconditional Replace::   Replacing all matches for a string.
1071 * Regexp Replace::          Replacing all matches for a regexp.
1072 * Replacement and Case::    How replacements preserve case of letters.
1073 * Query Replace::           How to use querying.
1074 @end menu
1076 @node Unconditional Replace
1077 @subsection Unconditional Replacement
1078 @findex replace-string
1080 @table @kbd
1081 @item M-x replace-string @key{RET} @var{string} @key{RET} @var{newstring} @key{RET}
1082 Replace every occurrence of @var{string} with @var{newstring}.
1083 @end table
1085   To replace every instance of @samp{foo} after point with @samp{bar},
1086 use the command @kbd{M-x replace-string} with the two arguments
1087 @samp{foo} and @samp{bar}.  Replacement happens only in the text after
1088 point, so if you want to cover the whole buffer you must go to the
1089 beginning first.  All occurrences up to the end of the buffer are
1090 replaced; to limit replacement to part of the buffer, activate the
1091 region around that part.  When the region is active, replacement is
1092 limited to the region (@pxref{Mark}).
1094   When @code{replace-string} exits, it leaves point at the last
1095 occurrence replaced.  It adds the prior position of point (where the
1096 @code{replace-string} command was issued) to the mark ring, without
1097 activating the mark; use @kbd{C-u C-@key{SPC}} to move back there.
1098 @xref{Mark Ring}.
1100   A prefix argument restricts replacement to matches that are
1101 surrounded by word boundaries.
1103   @xref{Replacement and Case}, for details about case-sensitivity in
1104 replace commands.
1106 @node Regexp Replace
1107 @subsection Regexp Replacement
1108 @findex replace-regexp
1110   The @kbd{M-x replace-string} command replaces exact matches for a
1111 single string.  The similar command @kbd{M-x replace-regexp} replaces
1112 any match for a specified pattern.
1114 @table @kbd
1115 @item M-x replace-regexp @key{RET} @var{regexp} @key{RET} @var{newstring} @key{RET}
1116 Replace every match for @var{regexp} with @var{newstring}.
1117 @end table
1119 @cindex back reference, in regexp replacement
1120   In @code{replace-regexp}, the @var{newstring} need not be constant:
1121 it can refer to all or part of what is matched by the @var{regexp}.
1122 @samp{\&} in @var{newstring} stands for the entire match being
1123 replaced.  @samp{\@var{d}} in @var{newstring}, where @var{d} is a
1124 digit, stands for whatever matched the @var{d}th parenthesized
1125 grouping in @var{regexp}.  (This is called a ``back reference''.)
1126 @samp{\#} refers to the count of replacements already made in this
1127 command, as a decimal number.  In the first replacement, @samp{\#}
1128 stands for @samp{0}; in the second, for @samp{1}; and so on.  For
1129 example,
1131 @example
1132 M-x replace-regexp @key{RET} c[ad]+r @key{RET} \&-safe @key{RET}
1133 @end example
1135 @noindent
1136 replaces (for example) @samp{cadr} with @samp{cadr-safe} and @samp{cddr}
1137 with @samp{cddr-safe}.
1139 @example
1140 M-x replace-regexp @key{RET} \(c[ad]+r\)-safe @key{RET} \1 @key{RET}
1141 @end example
1143 @noindent
1144 performs the inverse transformation.  To include a @samp{\} in the
1145 text to replace with, you must enter @samp{\\}.
1147   If you want to enter part of the replacement string by hand each
1148 time, use @samp{\?} in the replacement string.  Each replacement will
1149 ask you to edit the replacement string in the minibuffer, putting
1150 point where the @samp{\?} was.
1152   The remainder of this subsection is intended for specialized tasks
1153 and requires knowledge of Lisp.  Most readers can skip it.
1155   You can use Lisp expressions to calculate parts of the
1156 replacement string.  To do this, write @samp{\,} followed by the
1157 expression in the replacement string.  Each replacement calculates the
1158 value of the expression and converts it to text without quoting (if
1159 it's a string, this means using the string's contents), and uses it in
1160 the replacement string in place of the expression itself.  If the
1161 expression is a symbol, one space in the replacement string after the
1162 symbol name goes with the symbol name, so the value replaces them
1163 both.
1165   Inside such an expression, you can use some special sequences.
1166 @samp{\&} and @samp{\@var{n}} refer here, as usual, to the entire
1167 match as a string, and to a submatch as a string.  @var{n} may be
1168 multiple digits, and the value of @samp{\@var{n}} is @code{nil} if
1169 subexpression @var{n} did not match.  You can also use @samp{\#&} and
1170 @samp{\#@var{n}} to refer to those matches as numbers (this is valid
1171 when the match or submatch has the form of a numeral).  @samp{\#} here
1172 too stands for the number of already-completed replacements.
1174   Repeating our example to exchange @samp{x} and @samp{y}, we can thus
1175 do it also this way:
1177 @example
1178 M-x replace-regexp @key{RET} \(x\)\|y @key{RET}
1179 \,(if \1 "y" "x") @key{RET}
1180 @end example
1182   For computing replacement strings for @samp{\,}, the @code{format}
1183 function is often useful (@pxref{Formatting Strings,,, elisp, The Emacs
1184 Lisp Reference Manual}).  For example, to add consecutively numbered
1185 strings like @samp{ABC00042} to columns 73 @w{to 80} (unless they are
1186 already occupied), you can use
1188 @example
1189 M-x replace-regexp @key{RET} ^.\@{0,72\@}$ @key{RET}
1190 \,(format "%-72sABC%05d" \& \#) @key{RET}
1191 @end example
1193 @node Replacement and Case
1194 @subsection Replace Commands and Case
1196   If the first argument of a replace command is all lower case, the
1197 command ignores case while searching for occurrences to
1198 replace---provided @code{case-fold-search} is non-@code{nil}.  If
1199 @code{case-fold-search} is set to @code{nil}, case is always significant
1200 in all searches.
1202 @vindex case-replace
1203   In addition, when the @var{newstring} argument is all or partly lower
1204 case, replacement commands try to preserve the case pattern of each
1205 occurrence.  Thus, the command
1207 @example
1208 M-x replace-string @key{RET} foo @key{RET} bar @key{RET}
1209 @end example
1211 @noindent
1212 replaces a lower case @samp{foo} with a lower case @samp{bar}, an
1213 all-caps @samp{FOO} with @samp{BAR}, and a capitalized @samp{Foo} with
1214 @samp{Bar}.  (These three alternatives---lower case, all caps, and
1215 capitalized, are the only ones that @code{replace-string} can
1216 distinguish.)
1218   If upper-case letters are used in the replacement string, they remain
1219 upper case every time that text is inserted.  If upper-case letters are
1220 used in the first argument, the second argument is always substituted
1221 exactly as given, with no case conversion.  Likewise, if either
1222 @code{case-replace} or @code{case-fold-search} is set to @code{nil},
1223 replacement is done without case conversion.
1225 @node Query Replace
1226 @subsection Query Replace
1227 @cindex query replace
1229 @table @kbd
1230 @item M-% @var{string} @key{RET} @var{newstring} @key{RET}
1231 Replace some occurrences of @var{string} with @var{newstring}.
1232 @item C-M-% @var{regexp} @key{RET} @var{newstring} @key{RET}
1233 Replace some matches for @var{regexp} with @var{newstring}.
1234 @end table
1236 @kindex M-%
1237 @findex query-replace
1238   If you want to change only some of the occurrences of @samp{foo} to
1239 @samp{bar}, not all of them, use @kbd{M-%} (@code{query-replace}).
1240 This command finds occurrences of @samp{foo} one by one, displays each
1241 occurrence and asks you whether to replace it.  Aside from querying,
1242 @code{query-replace} works just like @code{replace-string}
1243 (@pxref{Unconditional Replace}).  In particular, it preserves case
1244 provided @code{case-replace} is non-@code{nil}, as it normally is
1245 (@pxref{Replacement and Case}).  A numeric argument means to consider
1246 only occurrences that are bounded by word-delimiter characters.  A
1247 negative prefix argument replaces backward.
1249 @kindex C-M-%
1250 @findex query-replace-regexp
1251   @kbd{C-M-%} performs regexp search and replace (@code{query-replace-regexp}).
1252 It works like @code{replace-regexp} except that it queries
1253 like @code{query-replace}.
1255 @cindex faces for highlighting query replace
1256   These commands highlight the current match using the face
1257 @code{query-replace}.  They highlight other matches using
1258 @code{lazy-highlight} just like incremental search (@pxref{Incremental
1259 Search}).  By default, @code{query-replace-regexp} will show the
1260 substituted replacement string for the current match in the
1261 minibuffer.  If you want to keep special sequences @samp{\&} and
1262 @samp{\@var{n}} unexpanded, customize
1263 @code{query-replace-show-replacement} variable.
1265   The characters you can type when you are shown a match for the string
1266 or regexp are:
1268 @ignore @c Not worth it.
1269 @kindex SPC @r{(query-replace)}
1270 @kindex DEL @r{(query-replace)}
1271 @kindex , @r{(query-replace)}
1272 @kindex RET @r{(query-replace)}
1273 @kindex . @r{(query-replace)}
1274 @kindex ! @r{(query-replace)}
1275 @kindex ^ @r{(query-replace)}
1276 @kindex C-r @r{(query-replace)}
1277 @kindex C-w @r{(query-replace)}
1278 @kindex C-l @r{(query-replace)}
1279 @end ignore
1281 @c WideCommands
1282 @table @kbd
1283 @item @key{SPC}
1284 to replace the occurrence with @var{newstring}.
1286 @item @key{DEL}
1287 to skip to the next occurrence without replacing this one.
1289 @item , @r{(Comma)}
1290 to replace this occurrence and display the result.  You are then asked
1291 for another input character to say what to do next.  Since the
1292 replacement has already been made, @key{DEL} and @key{SPC} are
1293 equivalent in this situation; both move to the next occurrence.
1295 You can type @kbd{C-r} at this point (see below) to alter the replaced
1296 text.  You can also type @kbd{C-x u} to undo the replacement; this exits
1297 the @code{query-replace}, so if you want to do further replacement you
1298 must use @kbd{C-x @key{ESC} @key{ESC} @key{RET}} to restart
1299 (@pxref{Repetition}).
1301 @item @key{RET}
1302 to exit without doing any more replacements.
1304 @item .@: @r{(Period)}
1305 to replace this occurrence and then exit without searching for more
1306 occurrences.
1308 @item !
1309 to replace all remaining occurrences without asking again.
1311 @item Y @r{(Upper-case)}
1312 to replace all remaining occurrences in all remaining buffers in
1313 multi-buffer replacements (like the Dired `Q' command which performs
1314 query replace on selected files).  It answers this question and all
1315 subsequent questions in the series with "yes", without further
1316 user interaction.
1318 @item N @r{(Upper-case)}
1319 to skip to the next buffer in multi-buffer replacements without
1320 replacing remaining occurrences in the current buffer.  It answers
1321 this question "no", gives up on the questions for the current buffer,
1322 and continues to the next buffer in the sequence.
1324 @item ^
1325 to go back to the position of the previous occurrence (or what used to
1326 be an occurrence), in case you changed it by mistake or want to
1327 reexamine it.
1329 @item C-r
1330 to enter a recursive editing level, in case the occurrence needs to be
1331 edited rather than just replaced with @var{newstring}.  When you are
1332 done, exit the recursive editing level with @kbd{C-M-c} to proceed to
1333 the next occurrence.  @xref{Recursive Edit}.
1335 @item C-w
1336 to delete the occurrence, and then enter a recursive editing level as in
1337 @kbd{C-r}.  Use the recursive edit to insert text to replace the deleted
1338 occurrence of @var{string}.  When done, exit the recursive editing level
1339 with @kbd{C-M-c} to proceed to the next occurrence.
1341 @item e
1342 to edit the replacement string in the minibuffer.  When you exit the
1343 minibuffer by typing @key{RET}, the minibuffer contents replace the
1344 current occurrence of the pattern.  They also become the new
1345 replacement string for any further occurrences.
1347 @item C-l
1348 to redisplay the screen.  Then you must type another character to
1349 specify what to do with this occurrence.
1351 @item C-h
1352 to display a message summarizing these options.  Then you must type
1353 another character to specify what to do with this occurrence.
1354 @end table
1356   Some other characters are aliases for the ones listed above: @kbd{y},
1357 @kbd{n} and @kbd{q} are equivalent to @key{SPC}, @key{DEL} and
1358 @key{RET}.
1360   Aside from this, any other character exits the @code{query-replace},
1361 and is then reread as part of a key sequence.  Thus, if you type
1362 @kbd{C-k}, it exits the @code{query-replace} and then kills to end of
1363 line.
1365   To restart a @code{query-replace} once it is exited, use @kbd{C-x
1366 @key{ESC} @key{ESC}}, which repeats the @code{query-replace} because it
1367 used the minibuffer to read its arguments.  @xref{Repetition, C-x ESC
1368 ESC}.
1370   @xref{Operating on Files}, for the Dired @kbd{Q} command which
1371 performs query replace on selected files.  See also @ref{Transforming
1372 File Names}, for Dired commands to rename, copy, or link files by
1373 replacing regexp matches in file names.
1375 @node Other Repeating Search
1376 @section Other Search-and-Loop Commands
1378   Here are some other commands that find matches for a regular
1379 expression.  They all ignore case in matching, if the pattern contains
1380 no upper-case letters and @code{case-fold-search} is non-@code{nil}.
1381 Aside from @code{occur} and its variants, all operate on the text from
1382 point to the end of the buffer, or on the region if it is active.
1384 @findex list-matching-lines
1385 @findex occur
1386 @findex multi-occur
1387 @findex multi-occur-in-matching-buffers
1388 @findex how-many
1389 @findex flush-lines
1390 @findex keep-lines
1392 @table @kbd
1393 @item M-x multi-isearch-buffers
1394 Prompt for one or more buffer names, ending with @key{RET}; then,
1395 begin a multi-buffer incremental search in those buffers.  (If the
1396 search fails in one buffer, the next @kbd{C-s} tries searching the
1397 next specified buffer, and so forth.)  With a prefix argument, prompt
1398 for a regexp and begin a multi-buffer incremental search in buffers
1399 matching that regexp.
1401 @item M-x multi-isearch-buffers-regexp
1402 This command is just like @code{multi-isearch-buffers}, except it
1403 performs an incremental regexp search.
1405 @cindex Occur mode
1406 @cindex mode, Occur
1407 @item M-x occur
1408 Prompt for a regexp, and display a list showing each line in the
1409 buffer that contains a match for it.  To limit the search to part of
1410 the buffer, narrow to that part (@pxref{Narrowing}).  A numeric
1411 argument @var{n} specifies that @var{n} lines of context are to be
1412 displayed before and after each matching line.
1414 @kindex RET @r{(Occur mode)}
1415 @kindex o @r{(Occur mode)}
1416 @kindex C-o @r{(Occur mode)}
1417 In the @file{*Occur*} buffer, you can click on each entry, or move
1418 point there and type @key{RET}, to visit the corresponding position in
1419 the buffer that was searched.  @kbd{o} and @kbd{C-o} display the match
1420 in another window; @kbd{C-o} does not select it.  Alternatively, you
1421 can use the @kbd{C-x `} (@code{next-error}) command to visit the
1422 occurrences one by one (@pxref{Compilation Mode}).
1424 @cindex Occur Edit mode
1425 @cindex mode, Occur Edit
1426 Typing @kbd{e} in the @file{*Occur*} buffer switches to Occur Edit
1427 mode, in which edits made to the entries are also applied to the text
1428 in the originating buffer.  Type @kbd{C-c C-c} to return to Occur
1429 mode.
1431 The command @kbd{M-x list-matching-lines} is a synonym for @kbd{M-x
1432 occur}.
1434 @kindex M-s o
1435 @item M-s o
1436 Run @code{occur} using the search string of the last incremental
1437 string search.  You can also run @kbd{M-s o} when an incremental
1438 search is active; this uses the current search string.
1440 @item M-x multi-occur
1441 This command is just like @code{occur}, except it is able to search
1442 through multiple buffers.  It asks you to specify the buffer names one
1443 by one.
1445 @item M-x multi-occur-in-matching-buffers
1446 This command is similar to @code{multi-occur}, except the buffers to
1447 search are specified by a regular expression that matches visited file
1448 names.  With a prefix argument, it uses the regular expression to
1449 match buffer names instead.
1451 @item M-x how-many
1452 Prompt for a regexp, and print the number of matches for it in the
1453 buffer after point.  If the region is active, this operates on the
1454 region instead.
1456 @item M-x flush-lines
1457 Prompt for a regexp, and delete each line that contains a match for
1458 it, operating on the text after point.  This command deletes the
1459 current line if it contains a match starting after point.  If the
1460 region is active, it operates on the region instead; if a line
1461 partially contained in the region contains a match entirely contained
1462 in the region, it is deleted.
1464 If a match is split across lines, @code{flush-lines} deletes all those
1465 lines.  It deletes the lines before starting to look for the next
1466 match; hence, it ignores a match starting on the same line at which
1467 another match ended.
1469 @item M-x keep-lines
1470 Prompt for a regexp, and delete each line that @emph{does not} contain
1471 a match for it, operating on the text after point.  If point is not at
1472 the beginning of a line, this command always keeps the current line.
1473 If the region is active, the command operates on the region instead;
1474 it never deletes lines that are only partially contained in the region
1475 (a newline that ends a line counts as part of that line).
1477 If a match is split across lines, this command keeps all those lines.
1478 @end table