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