* search.texi (Regexps): Copyedits. Mention character classes (Bug#7809).
[emacs.git] / doc / emacs / search.texi
blobe2ecb4a2385914117fa67435ee31420e4514ff25
1 @c This is part of the Emacs manual.
2 @c Copyright (C) 1985, 1986, 1987, 1993, 1994, 1995, 1997, 2000, 2001, 2002,
3 @c   2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
4 @c   Free Software Foundation, Inc.
5 @c See file emacs.texi for copying conditions.
6 @node Search, Fixit, Display, Top
7 @chapter Searching and Replacement
8 @cindex searching
9 @cindex finding strings within text
11   Like other editors, Emacs has commands to search for occurrences of
12 a string.  Emacs also has commands to replace occurrences of a string
13 with a different string.  There are also commands that do the same
14 thing, but search for patterns instead of fixed strings.
16   You can also search multiple files under the control of a tags table
17 (@pxref{Tags Search}) or through the Dired @kbd{A} command
18 (@pxref{Operating on Files}), or ask the @code{grep} program to do it
19 (@pxref{Grep Searching}).
22 @menu
23 * Incremental Search::        Search happens as you type the string.
24 * Nonincremental Search::     Specify entire string and then search.
25 * Word Search::               Search for sequence of words.
26 * Regexp Search::             Search for match for a regexp.
27 * Regexps::                   Syntax of regular expressions.
28 * Regexp Backslash::          Regular expression constructs starting with `\'.
29 * Regexp Example::            A complex regular expression explained.
30 * Search Case::               To ignore case while searching, or not.
31 * Replace::                   Search, and replace some or all matches.
32 * Other Repeating Search::    Operating on all matches for some regexp.
33 @end menu
35 @node Incremental Search
36 @section Incremental Search
37 @cindex incremental search
38 @cindex isearch
40   The principal search command in Emacs is @dfn{incremental}: it
41 begins searching as soon as you type the first character of the search
42 string.  As you type in the search string, Emacs shows you where the
43 string (as you have typed it so far) would be found.  When you have
44 typed enough characters to identify the place you want, you can stop.
45 Depending on what you plan to do next, you may or may not need to
46 terminate the search explicitly with @key{RET}.
48 @table @kbd
49 @item C-s
50 Incremental search forward (@code{isearch-forward}).
51 @item C-r
52 Incremental search backward (@code{isearch-backward}).
53 @end table
55 @menu
56 * Basic Isearch::       Basic incremental search commands.
57 * Repeat Isearch::      Searching for the same string again.
58 * Error in Isearch::    When your string is not found.
59 * Special Isearch::     Special input in incremental search.
60 * Isearch Yank::        Commands that grab text into the search string
61                           or else edit the search string.
62 * Isearch Scroll::      Scrolling during an incremental search.
63 * Isearch Minibuffer::  Incremental search of the minibuffer history.
64 * Slow Isearch::        Incremental search features for slow terminals.
65 @end menu
67 @node Basic Isearch
68 @subsection Basics of Incremental Search
70 @table @kbd
71 @item C-s
72 Begin incremental search (@code{isearch-forward}).
73 @item C-r
74 Begin reverse incremental search (@code{isearch-backward}).
75 @end table
77 @kindex C-s
78 @findex isearch-forward
79   @kbd{C-s} (@code{isearch-forward}) starts a forward incremental
80 search.  It reads characters from the keyboard, and moves point just
81 past the end of the next occurrence of those characters in the buffer.
83   For instance, if you type @kbd{C-s} and then @kbd{F}, that puts the
84 cursor after the first @samp{F} that occurs in the buffer after the
85 starting point.  Then if you then type @kbd{O}, the cursor moves to
86 just after the first @samp{FO}; the @samp{F} in that @samp{FO} might
87 not be the first @samp{F} previously found.  After another @kbd{O},
88 the cursor moves to just after the first @samp{FOO}.
90 @cindex faces for highlighting search matches
91   At each step, Emacs highlights the @dfn{current match}---the buffer
92 text that matches the search string---using the @code{isearch} face
93 (@pxref{Faces}).  The current search string is also displayed in the
94 echo area.
96   If you make a mistake typing the search string, type @key{DEL}.
97 Each @key{DEL} cancels the last character of the search string.
99   When you are satisfied with the place you have reached, type
100 @key{RET}.  This stops searching, leaving the cursor where the search
101 brought it.  Also, any command not specially meaningful in searches
102 stops the searching and is then executed.  Thus, typing @kbd{C-a}
103 exits the search and then moves to the beginning of the line.
104 @key{RET} is necessary only if the next command you want to type is a
105 printing character, @key{DEL}, @key{RET}, or another character that is
106 special within searches (@kbd{C-q}, @kbd{C-w}, @kbd{C-r}, @kbd{C-s},
107 @kbd{C-y}, @kbd{M-y}, @kbd{M-r}, @kbd{M-c}, @kbd{M-e}, and some others
108 described below).
110   As a special exception, entering @key{RET} when the search string is
111 empty launches nonincremental search (@pxref{Nonincremental Search}).
113   When you exit the incremental search, it adds the original value of
114 point to the mark ring, without activating the mark; you can thus use
115 @kbd{C-u C-@key{SPC}} to return to where you were before beginning the
116 search.  @xref{Mark Ring}.  It only does this if the mark was not
117 already active.
119 @kindex C-r
120 @findex isearch-backward
121   To search backwards, use @kbd{C-r} (@code{isearch-backward}) instead
122 of @kbd{C-s} to start the search.  A backward search finds matches
123 that end before the starting point, just as a forward search finds
124 matches that begin after it.
126 @node Repeat Isearch
127 @subsection Repeating Incremental Search
129   Suppose you search forward for @samp{FOO} and find a match, but not
130 the one you expected to find: the @samp{FOO} you were aiming for
131 occurs later in the buffer.  In this event, type another @kbd{C-s} to
132 move to the next occurrence of the search string.  You can repeat this
133 any number of times.  If you overshoot, you can cancel some @kbd{C-s}
134 characters with @key{DEL}.  Similarly, each @kbd{C-r} in a backward
135 incremental search repeats the backward search.
137 @cindex lazy search highlighting
138 @vindex isearch-lazy-highlight
139   If you pause for a little while during incremental search, Emacs
140 highlights all the other possible matches for the search string that
141 are present on the screen.  This helps you anticipate where you can
142 get to by typing @kbd{C-s} or @kbd{C-r} to repeat the search.  The
143 other matches are highlighted differently from the current match,
144 using the customizable face @code{lazy-highlight} (@pxref{Faces}).  If
145 you don't like this feature, you can disable it by setting
146 @code{isearch-lazy-highlight} to @code{nil}.
148   After exiting a search, you can search for the same string again by
149 typing just @kbd{C-s C-s}.  The first @kbd{C-s} is the key that
150 invokes incremental search, and the second @kbd{C-s} means ``search
151 again.''  Similarly, @kbd{C-r C-r} searches backward for the last
152 search string.  In determining the last search string, it doesn't
153 matter whether the string was searched for with @kbd{C-s} or
154 @kbd{C-r}.
156   If you are searching forward but you realize you were looking for
157 something before the starting point, type @kbd{C-r} to switch to a
158 backward search, leaving the search string unchanged.  Similarly,
159 @kbd{C-s} in a backward search switches to a forward search.
161   If a search is failing and you ask to repeat it by typing another
162 @kbd{C-s}, it starts again from the beginning of the buffer.
163 Repeating a failing reverse search with @kbd{C-r} starts again from
164 the end.  This is called @dfn{wrapping around}, and @samp{Wrapped}
165 appears in the search prompt once this has happened.  If you keep on
166 going past the original starting point of the search, it changes to
167 @samp{Overwrapped}, which means that you are revisiting matches that
168 you have already seen.
170 @cindex search ring
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.  To edit the current
175 search string in the minibuffer without replacing it with items from
176 the search ring, type @kbd{M-e}.  Type @kbd{C-s} or @kbd{C-r} to
177 terminate editing the string and search for it.
179 @node Error in Isearch
180 @subsection Errors in Incremental Search
182   If your string is not found at all, the echo area says @samp{Failing
183 I-Search}.  The cursor is after the place where Emacs found as much of
184 your string as it could.  Thus, if you search for @samp{FOOT}, and
185 there is no @samp{FOOT}, you might see the cursor after the @samp{FOO}
186 in @samp{FOOL}.  In the echo area, the part of the search string that
187 failed to match is highlighted using the customizable face
188 @code{isearch-fail}.
190   At this point, there are several things you can do.  If your string
191 was mistyped, you can use @key{DEL} to erase some of it and correct
192 it.  If you like the place you have found, you can type @key{RET} to
193 remain there.  Or you can type @kbd{C-g}, which removes from the
194 search string the characters that could not be found (the @samp{T} in
195 @samp{FOOT}), leaving those that were found (the @samp{FOO} in
196 @samp{FOOT}).  A second @kbd{C-g} at that point cancels the search
197 entirely, returning point to where it was when the search started.
199 @cindex quitting (in search)
200   The quit command, @kbd{C-g}, does special things during searches;
201 just what it does depends on the status of the search.  If the search
202 has found what you specified and is waiting for input, @kbd{C-g}
203 cancels the entire search, moving the cursor back to where you started
204 the search.  If @kbd{C-g} is typed when there are characters in the
205 search string that have not been found---because Emacs is still
206 searching for them, or because it has failed to find them---then the
207 search string characters which have not been found are discarded from
208 the search string.  With them gone, the search is now successful and
209 waiting for more input, so a second @kbd{C-g} will cancel the entire
210 search.
212 @node Special Isearch
213 @subsection Special Input for Incremental Search
215   Some of the characters you type during incremental search have
216 special effects.
218   If the search string you entered contains only lower-case letters,
219 the search is case-insensitive; as long as an upper-case letter exists
220 in the search string, the search becomes case-sensitive.  If you
221 delete the upper-case character from the search string, it ceases to
222 have this effect.  @xref{Search Case}.
224   To search for a newline character, type @kbd{C-j}.
226   To search for other control characters, such as @key{control-S},
227 quote it by typing @kbd{C-q} first (@pxref{Inserting Text}).  To
228 search for non-@acronym{ASCII} characters, you can either use
229 @kbd{C-q} and enter its octal code, or use an input method
230 (@pxref{Input Methods}).  If an input method is enabled in the current
231 buffer when you start the search, you can use it in the search string
232 also.  While typing the search string, you can toggle the input method
233 with the command @kbd{C-\} (@code{isearch-toggle-input-method}).  You
234 can also turn on a non-default input method with @kbd{C-^}
235 (@code{isearch-toggle-specified-input-method}), which prompts for the
236 name of the input method.  When an input method is active during
237 incremental search, the search prompt includes the input method
238 mnemonic, like this:
240 @example
241 I-search [@var{im}]:
242 @end example
244 @noindent
245 @findex isearch-toggle-input-method
246 @findex isearch-toggle-specified-input-method
247 where @var{im} is the mnemonic of the active input method.  Any input
248 method you enable during incremental search remains enabled in the
249 current buffer afterwards.
251 @kindex M-% @r{(Incremental search)}
252   Typing @kbd{M-%} in incremental search invokes @code{query-replace}
253 or @code{query-replace-regexp} (depending on search mode) with the
254 current search string used as the string to replace.  @xref{Query
255 Replace}.
257 @kindex M-TAB @r{(Incremental search)}
258   Typing @kbd{M-@key{TAB}} in incremental search invokes
259 @code{isearch-complete}, which attempts to complete the search string
260 using the search ring as a list of completion alternatives.
261 @xref{Completion}.  In many operating systems, the @kbd{M-@key{TAB}}
262 key sequence is captured by the window manager; you then need to
263 rebind @code{isearch-complete} to another key sequence if you want to
264 use it (@pxref{Rebinding}).
266 @vindex isearch-mode-map
267   When incremental search is active, you can type @kbd{C-h C-h} to
268 access interactive help options, including a list of special
269 keybindings.  These keybindings are part of the keymap
270 @code{isearch-mode-map} (@pxref{Keymaps}).
272 @node Isearch Yank
273 @subsection Isearch Yanking
275   Within incremental search, you can use @kbd{C-w} and @kbd{C-y} to grab
276 text from the buffer into the search string.  This makes it convenient
277 to search for another occurrence of text at point.
279   @kbd{C-w} copies the character or word after point and adds it to
280 the search string, advancing point over it.  (The decision, whether to
281 copy a character or a word, is heuristic.)
283   @kbd{C-y} is similar to @kbd{C-w} but copies all the rest of the
284 current line into the search string.  If point is already at the end
285 of a line, it grabs the entire next line.  If the search is currently
286 case-insensitive, both @kbd{C-y} and @kbd{C-w} convert the text they
287 copy to lower case, so that the search remains case-insensitive.
289   @kbd{C-M-w} and @kbd{C-M-y} modify the search string by only one
290 character at a time: @kbd{C-M-w} deletes the last character from the
291 search string and @kbd{C-M-y} copies the character after point to the
292 end of the search string.  An alternative method to add the character
293 after point into the search string is to enter the minibuffer by
294 @kbd{M-e} and to type @kbd{C-f} at the end of the search string in the
295 minibuffer.
297   The character @kbd{M-y} copies text from the kill ring into the
298 search string.  It uses the same text that @kbd{C-y} would yank.
299 @kbd{Mouse-2} in the echo area does the same.  @xref{Yanking}.
301 @node Isearch Scroll
302 @subsection Scrolling During Incremental Search
304 @vindex isearch-allow-scroll
305   You can enable the use of vertical scrolling during incremental
306 search (without exiting the search) by setting the customizable
307 variable @code{isearch-allow-scroll} to a non-@code{nil} value.  This
308 applies to using the vertical scroll-bar and to certain keyboard
309 commands such as @key{prior} (@code{scroll-down}), @key{next}
310 (@code{scroll-up}) and @kbd{C-l} (@code{recenter}).  You must run
311 these commands via their key sequences to stay in the search---typing
312 @kbd{M-x} will terminate the search.  You can give prefix arguments to
313 these commands in the usual way.
315   This feature won't let you scroll the current match out of visibility,
316 however.
318   The feature also affects some other commands, such as @kbd{C-x 2}
319 (@code{split-window-vertically}) and @kbd{C-x ^}
320 (@code{enlarge-window}) which don't exactly scroll but do affect where
321 the text appears on the screen.  In general, it applies to any command
322 whose name has a non-@code{nil} @code{isearch-scroll} property.  So you
323 can control which commands are affected by changing these properties.
325   For example, to make @kbd{C-h l} usable within an incremental search
326 in all future Emacs sessions, use @kbd{C-h c} to find what command it
327 runs.  (You type @kbd{C-h c C-h l}; it says @code{view-lossage}.)
328 Then you can put the following line in your @file{.emacs} file
329 (@pxref{Init File}):
331 @example
332 (put 'view-lossage 'isearch-scroll t)
333 @end example
335 @noindent
336 This feature can be applied to any command that doesn't permanently
337 change point, the buffer contents, the match data, the current buffer,
338 or the selected window and frame.  The command must not itself attempt
339 an incremental search.
341 @node Isearch Minibuffer
342 @subsection Searching the Minibuffer
343 @cindex minibuffer history, searching
345 If you start an incremental search while the minibuffer is active,
346 Emacs searches the contents of the minibuffer.  Unlike searching an
347 ordinary buffer, the search string is not shown in the echo area,
348 because that is used to display the minibuffer.
350 If an incremental search fails in the minibuffer, it tries searching
351 the minibuffer history.  @xref{Minibuffer History}.  You can visualize
352 the minibuffer and its history as a series of ``pages'', with the
353 earliest history element on the first page and the current minibuffer
354 on the last page.  A forward search, @kbd{C-s}, searches forward to
355 later pages; a reverse search, @kbd{C-r}, searches backwards to
356 earlier pages.  Like in ordinary buffer search, a failing search can
357 wrap around, going from the last page to the first page or vice versa.
359 When the current match is on a history element, that history element
360 is pulled into the minibuffer.  If you exit the incremental search
361 normally (e.g. by typing @key{RET}), it remains in the minibuffer
362 afterwards.  Cancelling the search, with @kbd{C-g}, restores the
363 contents of the minibuffer when you began the search.
365 @node Slow Isearch
366 @subsection Slow Terminal Incremental Search
368   Incremental search on a slow terminal uses a modified style of display
369 that is designed to take less time.  Instead of redisplaying the buffer at
370 each place the search gets to, it creates a new single-line window and uses
371 that to display the line that the search has found.  The single-line window
372 comes into play as soon as point moves outside of the text that is already
373 on the screen.
375   When you terminate the search, the single-line window is removed.
376 Emacs then redisplays the window in which the search was done, to show
377 its new position of point.
379 @vindex search-slow-speed
380   The slow terminal style of display is used when the terminal baud rate is
381 less than or equal to the value of the variable @code{search-slow-speed},
382 initially 1200.  See also the discussion of the variable @code{baud-rate}
383 (@pxref{baud-rate,, Customization of Display}).
385 @vindex search-slow-window-lines
386   The number of lines to use in slow terminal search display is controlled
387 by the variable @code{search-slow-window-lines}.  Its normal value is 1.
389 @node Nonincremental Search
390 @section Nonincremental Search
391 @cindex nonincremental search
393   Emacs also has conventional nonincremental search commands, which require
394 you to type the entire search string before searching begins.
396 @table @kbd
397 @item C-s @key{RET} @var{string} @key{RET}
398 Search for @var{string}.
399 @item C-r @key{RET} @var{string} @key{RET}
400 Search backward for @var{string}.
401 @end table
403   To start a nonincremental search, first type @kbd{C-s @key{RET}}.
404 This enters the minibuffer to read the search string; terminate the
405 string with @key{RET}, and then the search takes place.  If the string
406 is not found, the search command signals an error.
408   When you type @kbd{C-s @key{RET}}, the @kbd{C-s} invokes incremental
409 search as usual.  That command is specially programmed to invoke
410 nonincremental search, @code{search-forward}, if the string you
411 specify is empty.  (Such an empty argument would otherwise be
412 useless.)  @kbd{C-r @key{RET}} does likewise, for a reverse
413 incremental search.
415 @findex search-forward
416 @findex search-backward
417   Forward and backward nonincremental searches are implemented by the
418 commands @code{search-forward} and @code{search-backward}.  These
419 commands may be bound to other keys in the usual manner.
421 @node Word Search
422 @section Word Search
423 @cindex word search
425   A @dfn{word search} finds a sequence of words without regard to the
426 type of punctuation between them.  For instance, if you enter a search
427 string that consists of two words separated by a single space, the
428 search matches any sequence of those two words separated by one or
429 more spaces, newlines, or other punctuation characters.  This is
430 particularly useful for searching text documents, because you don't
431 have to worry whether the words you are looking for are separated by
432 newlines or spaces.
434 @table @kbd
435 @item M-s w
436 If incremental search is active, toggle word search mode
437 (@code{isearch-toggle-word}); otherwise, begin an incremental forward
438 word search (@code{isearch-forward-word}).
439 @item M-s w @key{RET} @var{words} @key{RET}
440 Search for @var{words}, using a forward nonincremental word search.
441 @item M-s w C-r @key{RET} @var{words} @key{RET}
442 Search backward for @var{words}, using a nonincremental word search.
443 @end table
445 @kindex M-s w
446 @findex isearch-forward-word
447   To begin a forward incremental word search, type @kbd{M-s w}.  If
448 incremental search is not already active, this runs the command
449 @code{isearch-forward-word}.  If incremental search is already active
450 (whether a forward or backward search), @kbd{M-s w} switches to a word
451 search while keeping the direction of the search and the current
452 search string unchanged.  You can toggle word search back off by
453 typing @kbd{M-s w} again.
455 @findex word-search-forward
456 @findex word-search-backward
457   To begin a nonincremental word search, type @kbd{M-s w @key{RET}}
458 for a forward search, or @kbd{M-s w C-r @key{RET}} for a backward search.
459 These run the commands @code{word-search-forward} and
460 @code{word-search-backward} respectively.
462   Incremental and nonincremental word searches differ slightly in the
463 way they find a match.  In a nonincremental word search, the last word
464 in the search string must exactly match a whole word.  In an
465 incremental word search, the matching is more lax: the last word in
466 the search string can match part of a word, so that the matching
467 proceeds incrementally as you type.  This additional laxity does not
468 apply to the lazy highlight, which always matches whole words.
470 @node Regexp Search
471 @section Regular Expression Search
472 @cindex regular expression
473 @cindex regexp
475   A @dfn{regular expression} (or @dfn{regexp} for short) is a pattern
476 that denotes a class of alternative strings to match.  GNU Emacs
477 provides both incremental and nonincremental ways to search for a
478 match for a regexp.  The syntax of regular expressions is explained in
479 the following section.
481 @table @kbd
482 @item C-M-s
483 Begin incremental regexp search (@code{isearch-forward-regexp}).
484 @item C-M-r
485 Begin reverse incremental regexp search (@code{isearch-backward-regexp}).
486 @end table
488 @kindex C-M-s
489 @findex isearch-forward-regexp
490 @kindex C-M-r
491 @findex isearch-backward-regexp
492   Incremental search for a regexp is done by typing @kbd{C-M-s}
493 (@code{isearch-forward-regexp}), by invoking @kbd{C-s} with a
494 prefix argument (whose value does not matter), or by typing @kbd{M-r}
495 within a forward incremental search.  This command reads a
496 search string incrementally just like @kbd{C-s}, but it treats the
497 search string as a regexp rather than looking for an exact match
498 against the text in the buffer.  Each time you add text to the search
499 string, you make the regexp longer, and the new regexp is searched
500 for.  To search backward for a regexp, use @kbd{C-M-r}
501 (@code{isearch-backward-regexp}), @kbd{C-r} with a prefix argument,
502 or @kbd{M-r} within a backward incremental search.
504   All of the special key sequences in an ordinary incremental search
505 do similar things in an incremental regexp search.  For instance,
506 typing @kbd{C-s} immediately after starting the search retrieves the
507 last incremental search regexp used and searches forward for it.
508 Incremental regexp and non-regexp searches have independent defaults.
509 They also have separate search rings, which you can access with
510 @kbd{M-p} and @kbd{M-n}.
512 @vindex search-whitespace-regexp
513   If you type @key{SPC} in incremental regexp search, it matches any
514 sequence of whitespace characters, including newlines.  If you want to
515 match just a space, type @kbd{C-q @key{SPC}}.  You can control what a
516 bare space matches by setting the variable
517 @code{search-whitespace-regexp} to the desired regexp.
519   In some cases, adding characters to the regexp in an incremental
520 regexp search can make the cursor move back and start again.  For
521 example, if you have searched for @samp{foo} and you add @samp{\|bar},
522 the cursor backs up in case the first @samp{bar} precedes the first
523 @samp{foo}.  @xref{Regexps}.
525   Forward and backward regexp search are not symmetrical, because
526 regexp matching in Emacs always operates forward, starting with the
527 beginning of the regexp.  Thus, forward regexp search scans forward,
528 trying a forward match at each possible starting position.  Backward
529 regexp search scans backward, trying a forward match at each possible
530 starting position.  These search methods are not mirror images.
532 @findex re-search-forward
533 @findex re-search-backward
534   Nonincremental search for a regexp is done by the functions
535 @code{re-search-forward} and @code{re-search-backward}.  You can
536 invoke these with @kbd{M-x}, or by way of incremental regexp search
537 with @kbd{C-M-s @key{RET}} and @kbd{C-M-r @key{RET}}.
539   If you use the incremental regexp search commands with a prefix
540 argument, they perform ordinary string search, like
541 @code{isearch-forward} and @code{isearch-backward}.  @xref{Incremental
542 Search}.
544 @node Regexps
545 @section Syntax of Regular Expressions
546 @cindex syntax of regexps
548   This manual describes regular expression features that users
549 typically use.  @xref{Regular Expressions,,, elisp, The Emacs Lisp
550 Reference Manual}, for additional features used mainly in Lisp
551 programs.
553   Regular expressions have a syntax in which a few characters are
554 special constructs and the rest are @dfn{ordinary}.  An ordinary
555 character matches that same character and nothing else.  The special
556 characters are @samp{$^.*+?[\}.  The character @samp{]} is special if
557 it ends a character alternative (see later).  The character @samp{-}
558 is special inside a character alternative.  Any other character
559 appearing in a regular expression is ordinary, unless a @samp{\}
560 precedes it.  (When you use regular expressions in a Lisp program,
561 each @samp{\} must be doubled, see the example near the end of this
562 section.)
564   For example, @samp{f} is not a special character, so it is ordinary, and
565 therefore @samp{f} is a regular expression that matches the string
566 @samp{f} and no other string.  (It does @emph{not} match the string
567 @samp{ff}.)  Likewise, @samp{o} is a regular expression that matches
568 only @samp{o}.  (When case distinctions are being ignored, these regexps
569 also match @samp{F} and @samp{O}, but we consider this a generalization
570 of ``the same string,'' rather than an exception.)
572   Any two regular expressions @var{a} and @var{b} can be concatenated.
573 The result is a regular expression which matches a string if @var{a}
574 matches some amount of the beginning of that string and @var{b}
575 matches the rest of the string.  For example, concatenating the
576 regular expressions @samp{f} and @samp{o} gives the regular expression
577 @samp{fo}, which matches only the string @samp{fo}.  Still trivial.
578 To do something nontrivial, you need to use one of the special
579 characters.  Here is a list of them.
581 @table @asis
582 @item @kbd{.}@: @r{(Period)}
583 is a special character that matches any single character except a
584 newline.  For example, the regular expressions @samp{a.b} matches any
585 three-character string that begins with @samp{a} and ends with
586 @samp{b}.
588 @item @kbd{*}
589 is not a construct by itself; it is a postfix operator that means to
590 match the preceding regular expression repetitively any number of
591 times, as many times as possible.  Thus, @samp{o*} matches any number
592 of @samp{o}s, including no @samp{o}s.
594 @samp{*} always applies to the @emph{smallest} possible preceding
595 expression.  Thus, @samp{fo*} has a repeating @samp{o}, not a repeating
596 @samp{fo}.  It matches @samp{f}, @samp{fo}, @samp{foo}, and so on.
598 The matcher processes a @samp{*} construct by matching, immediately,
599 as many repetitions as can be found.  Then it continues with the rest
600 of the pattern.  If that fails, backtracking occurs, discarding some
601 of the matches of the @samp{*}-modified construct in case that makes
602 it possible to match the rest of the pattern.  For example, in matching
603 @samp{ca*ar} against the string @samp{caaar}, the @samp{a*} first
604 tries to match all three @samp{a}s; but the rest of the pattern is
605 @samp{ar} and there is only @samp{r} left to match, so this try fails.
606 The next alternative is for @samp{a*} to match only two @samp{a}s.
607 With this choice, the rest of the regexp matches successfully.@refill
609 @item @kbd{+}
610 is a postfix operator, similar to @samp{*} except that it must match
611 the preceding expression at least once.  Thus, @samp{ca+r} matches the
612 strings @samp{car} and @samp{caaaar} but not the string @samp{cr},
613 whereas @samp{ca*r} matches all three strings.
615 @item @kbd{?}
616 is a postfix operator, similar to @samp{*} except that it can match
617 the preceding expression either once or not at all.  Thus, @samp{ca?r}
618 matches @samp{car} or @samp{cr}, and nothing else.
620 @item @kbd{*?}, @kbd{+?}, @kbd{??}
621 @cindex non-greedy regexp matching
622 are non-@dfn{greedy} variants of the operators above.  The normal
623 operators @samp{*}, @samp{+}, @samp{?} match as much as they can, as
624 long as the overall regexp can still match.  With a following
625 @samp{?}, they will match as little as possible.
627 Thus, both @samp{ab*} and @samp{ab*?} can match the string @samp{a}
628 and the string @samp{abbbb}; but if you try to match them both against
629 the text @samp{abbb}, @samp{ab*} will match it all (the longest valid
630 match), while @samp{ab*?}  will match just @samp{a} (the shortest
631 valid match).
633 Non-greedy operators match the shortest possible string starting at a
634 given starting point; in a forward search, though, the earliest
635 possible starting point for match is always the one chosen.  Thus, if
636 you search for @samp{a.*?$} against the text @samp{abbab} followed by
637 a newline, it matches the whole string.  Since it @emph{can} match
638 starting at the first @samp{a}, it does.
640 @item @kbd{\@{@var{n}\@}}
641 is a postfix operator specifying @var{n} repetitions---that is, the
642 preceding regular expression must match exactly @var{n} times in a
643 row.  For example, @samp{x\@{4\@}} matches the string @samp{xxxx} and
644 nothing else.
646 @item @kbd{\@{@var{n},@var{m}\@}}
647 is a postfix operator specifying between @var{n} and @var{m}
648 repetitions---that is, the preceding regular expression must match at
649 least @var{n} times, but no more than @var{m} times.  If @var{m} is
650 omitted, then there is no upper limit, but the preceding regular
651 expression must match at least @var{n} times.@* @samp{\@{0,1\@}} is
652 equivalent to @samp{?}. @* @samp{\@{0,\@}} is equivalent to
653 @samp{*}. @* @samp{\@{1,\@}} is equivalent to @samp{+}.
655 @item @kbd{[ @dots{} ]}
656 is a @dfn{character set}, beginning with @samp{[} and terminated by
657 @samp{]}.
659 In the simplest case, the characters between the two brackets are what
660 this set can match.  Thus, @samp{[ad]} matches either one @samp{a} or
661 one @samp{d}, and @samp{[ad]*} matches any string composed of just
662 @samp{a}s and @samp{d}s (including the empty string).  It follows that
663 @samp{c[ad]*r} matches @samp{cr}, @samp{car}, @samp{cdr},
664 @samp{caddaar}, etc.
666 You can also include character ranges in a character set, by writing the
667 starting and ending characters with a @samp{-} between them.  Thus,
668 @samp{[a-z]} matches any lower-case @acronym{ASCII} letter.  Ranges may be
669 intermixed freely with individual characters, as in @samp{[a-z$%.]},
670 which matches any lower-case @acronym{ASCII} letter or @samp{$}, @samp{%} or
671 period.
673 You can also include certain special @dfn{character classes} in a
674 character set.  A @samp{[:} and balancing @samp{:]} enclose a
675 character class inside a character alternative.  For instance,
676 @samp{[[:alnum:]]} matches any letter or digit.  @xref{Char Classes,,,
677 elisp, The Emacs Lisp Reference Manual}, for a list of character
678 classes.
680 To include a @samp{]} in a character set, you must make it the first
681 character.  For example, @samp{[]a]} matches @samp{]} or @samp{a}.  To
682 include a @samp{-}, write @samp{-} as the first or last character of the
683 set, or put it after a range.  Thus, @samp{[]-]} matches both @samp{]}
684 and @samp{-}.
686 To include @samp{^} in a set, put it anywhere but at the beginning of
687 the set.  (At the beginning, it complements the set---see below.)
689 When you use a range in case-insensitive search, you should write both
690 ends of the range in upper case, or both in lower case, or both should
691 be non-letters.  The behavior of a mixed-case range such as @samp{A-z}
692 is somewhat ill-defined, and it may change in future Emacs versions.
694 @item @kbd{[^ @dots{} ]}
695 @samp{[^} begins a @dfn{complemented character set}, which matches any
696 character except the ones specified.  Thus, @samp{[^a-z0-9A-Z]} matches
697 all characters @emph{except} @acronym{ASCII} letters and digits.
699 @samp{^} is not special in a character set unless it is the first
700 character.  The character following the @samp{^} is treated as if it
701 were first (in other words, @samp{-} and @samp{]} are not special there).
703 A complemented character set can match a newline, unless newline is
704 mentioned as one of the characters not to match.  This is in contrast to
705 the handling of regexps in programs such as @code{grep}.
707 @item @kbd{^}
708 is a special character that matches the empty string, but only at the
709 beginning of a line in the text being matched.  Otherwise it fails to
710 match anything.  Thus, @samp{^foo} matches a @samp{foo} that occurs at
711 the beginning of a line.
713 For historical compatibility reasons, @samp{^} can be used with this
714 meaning only at the beginning of the regular expression, or after
715 @samp{\(} or @samp{\|}.
717 @item @kbd{$}
718 is similar to @samp{^} but matches only at the end of a line.  Thus,
719 @samp{x+$} matches a string of one @samp{x} or more at the end of a line.
721 For historical compatibility reasons, @samp{$} can be used with this
722 meaning only at the end of the regular expression, or before @samp{\)}
723 or @samp{\|}.
725 @item @kbd{\}
726 has two functions: it quotes the special characters (including
727 @samp{\}), and it introduces additional special constructs.
729 Because @samp{\} quotes special characters, @samp{\$} is a regular
730 expression that matches only @samp{$}, and @samp{\[} is a regular
731 expression that matches only @samp{[}, and so on.
733 See the following section for the special constructs that begin
734 with @samp{\}.
735 @end table
737   Note: for historical compatibility, special characters are treated as
738 ordinary ones if they are in contexts where their special meanings make no
739 sense.  For example, @samp{*foo} treats @samp{*} as ordinary since there is
740 no preceding expression on which the @samp{*} can act.  It is poor practice
741 to depend on this behavior; it is better to quote the special character anyway,
742 regardless of where it appears.
744 As a @samp{\} is not special inside a character alternative, it can
745 never remove the special meaning of @samp{-} or @samp{]}.  So you
746 should not quote these characters when they have no special meaning
747 either.  This would not clarify anything, since backslashes can
748 legitimately precede these characters where they @emph{have} special
749 meaning, as in @samp{[^\]} (@code{"[^\\]"} for Lisp string syntax),
750 which matches any single character except a backslash.
752 @node Regexp Backslash
753 @section Backslash in Regular Expressions
755   For the most part, @samp{\} followed by any character matches only
756 that character.  However, there are several exceptions: two-character
757 sequences starting with @samp{\} that have special meanings.  The
758 second character in the sequence is always an ordinary character when
759 used on its own.  Here is a table of @samp{\} constructs.
761 @table @kbd
762 @item \|
763 specifies an alternative.  Two regular expressions @var{a} and @var{b}
764 with @samp{\|} in between form an expression that matches some text if
765 either @var{a} matches it or @var{b} matches it.  It works by trying to
766 match @var{a}, and if that fails, by trying to match @var{b}.
768 Thus, @samp{foo\|bar} matches either @samp{foo} or @samp{bar}
769 but no other string.@refill
771 @samp{\|} applies to the largest possible surrounding expressions.  Only a
772 surrounding @samp{\( @dots{} \)} grouping can limit the grouping power of
773 @samp{\|}.@refill
775 Full backtracking capability exists to handle multiple uses of @samp{\|}.
777 @item \( @dots{} \)
778 is a grouping construct that serves three purposes:
780 @enumerate
781 @item
782 To enclose a set of @samp{\|} alternatives for other operations.
783 Thus, @samp{\(foo\|bar\)x} matches either @samp{foox} or @samp{barx}.
785 @item
786 To enclose a complicated expression for the postfix operators @samp{*},
787 @samp{+} and @samp{?} to operate on.  Thus, @samp{ba\(na\)*} matches
788 @samp{bananana}, etc., with any (zero or more) number of @samp{na}
789 strings.@refill
791 @item
792 To record a matched substring for future reference.
793 @end enumerate
795 This last application is not a consequence of the idea of a
796 parenthetical grouping; it is a separate feature that is assigned as a
797 second meaning to the same @samp{\( @dots{} \)} construct.  In practice
798 there is usually no conflict between the two meanings; when there is
799 a conflict, you can use a ``shy'' group.
801 @item \(?: @dots{} \)
802 @cindex shy group, in regexp
803 specifies a ``shy'' group that does not record the matched substring;
804 you can't refer back to it with @samp{\@var{d}}.  This is useful
805 in mechanically combining regular expressions, so that you
806 can add groups for syntactic purposes without interfering with
807 the numbering of the groups that are meant to be referred to.
809 @item \@var{d}
810 @cindex back reference, in regexp
811 matches the same text that matched the @var{d}th occurrence of a
812 @samp{\( @dots{} \)} construct.  This is called a @dfn{back
813 reference}.
815 After the end of a @samp{\( @dots{} \)} construct, the matcher remembers
816 the beginning and end of the text matched by that construct.  Then,
817 later on in the regular expression, you can use @samp{\} followed by the
818 digit @var{d} to mean ``match the same text matched the @var{d}th time
819 by the @samp{\( @dots{} \)} construct.''
821 The strings matching the first nine @samp{\( @dots{} \)} constructs
822 appearing in a regular expression are assigned numbers 1 through 9 in
823 the order that the open-parentheses appear in the regular expression.
824 So you can use @samp{\1} through @samp{\9} to refer to the text matched
825 by the corresponding @samp{\( @dots{} \)} constructs.
827 For example, @samp{\(.*\)\1} matches any newline-free string that is
828 composed of two identical halves.  The @samp{\(.*\)} matches the first
829 half, which may be anything, but the @samp{\1} that follows must match
830 the same exact text.
832 If a particular @samp{\( @dots{} \)} construct matches more than once
833 (which can easily happen if it is followed by @samp{*}), only the last
834 match is recorded.
836 @item \`
837 matches the empty string, but only at the beginning of the string or
838 buffer (or its accessible portion) being matched against.
840 @item \'
841 matches the empty string, but only at the end of the string or buffer
842 (or its accessible portion) being matched against.
844 @item \=
845 matches the empty string, but only at point.
847 @item \b
848 matches the empty string, but only at the beginning or
849 end of a word.  Thus, @samp{\bfoo\b} matches any occurrence of
850 @samp{foo} as a separate word.  @samp{\bballs?\b} matches
851 @samp{ball} or @samp{balls} as a separate word.@refill
853 @samp{\b} matches at the beginning or end of the buffer
854 regardless of what text appears next to it.
856 @item \B
857 matches the empty string, but @emph{not} at the beginning or
858 end of a word.
860 @item \<
861 matches the empty string, but only at the beginning of a word.
862 @samp{\<} matches at the beginning of the buffer only if a
863 word-constituent character follows.
865 @item \>
866 matches the empty string, but only at the end of a word.  @samp{\>}
867 matches at the end of the buffer only if the contents end with a
868 word-constituent character.
870 @item \w
871 matches any word-constituent character.  The syntax table
872 determines which characters these are.  @xref{Syntax}.
874 @item \W
875 matches any character that is not a word-constituent.
877 @item \_<
878 matches the empty string, but only at the beginning of a symbol.
879 A symbol is a sequence of one or more symbol-constituent characters.
880 A symbol-constituent character is a character whose syntax is either
881 @samp{w} or @samp{_}.  @samp{\_<} matches at the beginning of the
882 buffer only if a symbol-constituent character follows.
884 @item \_>
885 matches the empty string, but only at the end of a symbol.  @samp{\_>}
886 matches at the end of the buffer only if the contents end with a
887 symbol-constituent character.
889 @item \s@var{c}
890 matches any character whose syntax is @var{c}.  Here @var{c} is a
891 character that designates a particular syntax class: thus, @samp{w}
892 for word constituent, @samp{-} or @samp{ } for whitespace, @samp{.}
893 for ordinary punctuation, etc.  @xref{Syntax}.
895 @item \S@var{c}
896 matches any character whose syntax is not @var{c}.
898 @cindex categories of characters
899 @cindex characters which belong to a specific language
900 @findex describe-categories
901 @item \c@var{c}
902 matches any character that belongs to the category @var{c}.  For
903 example, @samp{\cc} matches Chinese characters, @samp{\cg} matches
904 Greek characters, etc.  For the description of the known categories,
905 type @kbd{M-x describe-categories @key{RET}}.
907 @item \C@var{c}
908 matches any character that does @emph{not} belong to category
909 @var{c}.
910 @end table
912   The constructs that pertain to words and syntax are controlled by the
913 setting of the syntax table (@pxref{Syntax}).
915 @node Regexp Example
916 @section Regular Expression Example
918   Here is an example of a regexp---the regexp that Emacs uses, by
919 default, to recognize the end of a sentence, not including the
920 following space (i.e., the variable @code{sentence-end-base}):
922 @example
923 @verbatim
924 [.?!][]\"'””)}]*
925 @end verbatim
926 @end example
928 @noindent
929 This contains two parts in succession: a character set matching
930 period, @samp{?}, or @samp{!}, and a character set matching
931 close-brackets, quotes, or parentheses, repeated zero or more times.
933 @node Search Case
934 @section Searching and Case
936   Searches in Emacs normally ignore the case of the text they are
937 searching through, if you specify the text in lower case.  Thus, if
938 you specify searching for @samp{foo}, then @samp{Foo} and @samp{foo}
939 are also considered a match.  Regexps, and in particular character
940 sets, are included: @samp{[ab]} would match @samp{a} or @samp{A} or
941 @samp{b} or @samp{B}.@refill
943   An upper-case letter anywhere in the incremental search string makes
944 the search case-sensitive.  Thus, searching for @samp{Foo} does not find
945 @samp{foo} or @samp{FOO}.  This applies to regular expression search as
946 well as to string search.  The effect ceases if you delete the
947 upper-case letter from the search string.
949   Typing @kbd{M-c} within an incremental search toggles the case
950 sensitivity of that search.  The effect does not extend beyond the
951 current incremental search to the next one, but it does override the
952 effect of adding or removing an upper-case letter in the current
953 search.
955 @vindex case-fold-search
956   If you set the variable @code{case-fold-search} to @code{nil}, then
957 all letters must match exactly, including case.  This is a per-buffer
958 variable; altering the variable normally affects only the current buffer,
959 unless you change its default value.  @xref{Locals}.
960 This variable applies to nonincremental searches also, including those
961 performed by the replace commands (@pxref{Replace}) and the minibuffer
962 history matching commands (@pxref{Minibuffer History}).
964   Several related variables control case-sensitivity of searching and
965 matching for specific commands or activities.  For instance,
966 @code{tags-case-fold-search} controls case sensitivity for
967 @code{find-tag}.  To find these variables, do @kbd{M-x
968 apropos-variable @key{RET} case-fold-search @key{RET}}.
970 @node Replace
971 @section Replacement Commands
972 @cindex replacement
973 @cindex search-and-replace commands
974 @cindex string substitution
975 @cindex global substitution
977   Emacs provides several commands for performing search-and-replace
978 operations.  In addition to the simple @kbd{M-x replace-string}
979 command, there is @kbd{M-%} (@code{query-replace}), which presents
980 each occurrence of the pattern and asks you whether to replace it.
982   The replace commands normally operate on the text from point to the
983 end of the buffer.  When the mark is active, they operate on the
984 region instead (@pxref{Mark}).  The basic replace commands replace one
985 @dfn{search string} (or regexp) with one @dfn{replacement string}.  It
986 is possible to perform several replacements in parallel, using the
987 command @code{expand-region-abbrevs} (@pxref{Expanding Abbrevs}).
989 @menu
990 * Unconditional Replace::   Replacing all matches for a string.
991 * Regexp Replace::          Replacing all matches for a regexp.
992 * Replacement and Case::    How replacements preserve case of letters.
993 * Query Replace::           How to use querying.
994 @end menu
996 @node Unconditional Replace, Regexp Replace, Replace, Replace
997 @subsection Unconditional Replacement
998 @findex replace-string
1000 @table @kbd
1001 @item M-x replace-string @key{RET} @var{string} @key{RET} @var{newstring} @key{RET}
1002 Replace every occurrence of @var{string} with @var{newstring}.
1003 @end table
1005   To replace every instance of @samp{foo} after point with @samp{bar},
1006 use the command @kbd{M-x replace-string} with the two arguments
1007 @samp{foo} and @samp{bar}.  Replacement happens only in the text after
1008 point, so if you want to cover the whole buffer you must go to the
1009 beginning first.  All occurrences up to the end of the buffer are
1010 replaced; to limit replacement to part of the buffer, activate the
1011 region around that part.  When the region is active, replacement is
1012 limited to the region (@pxref{Mark}).
1014   When @code{replace-string} exits, it leaves point at the last
1015 occurrence replaced.  It adds the prior position of point (where the
1016 @code{replace-string} command was issued) to the mark ring, without
1017 activating the mark; use @kbd{C-u C-@key{SPC}} to move back there.
1018 @xref{Mark Ring}.
1020   A prefix argument restricts replacement to matches that are
1021 surrounded by word boundaries.  The argument's value doesn't matter.
1023   @xref{Replacement and Case}, for details about case-sensitivity in
1024 replace commands.
1026 @node Regexp Replace, Replacement and Case, Unconditional Replace, Replace
1027 @subsection Regexp Replacement
1028 @findex replace-regexp
1030   The @kbd{M-x replace-string} command replaces exact matches for a
1031 single string.  The similar command @kbd{M-x replace-regexp} replaces
1032 any match for a specified pattern.
1034 @table @kbd
1035 @item M-x replace-regexp @key{RET} @var{regexp} @key{RET} @var{newstring} @key{RET}
1036 Replace every match for @var{regexp} with @var{newstring}.
1037 @end table
1039 @cindex back reference, in regexp replacement
1040   In @code{replace-regexp}, the @var{newstring} need not be constant:
1041 it can refer to all or part of what is matched by the @var{regexp}.
1042 @samp{\&} in @var{newstring} stands for the entire match being
1043 replaced.  @samp{\@var{d}} in @var{newstring}, where @var{d} is a
1044 digit, stands for whatever matched the @var{d}th parenthesized
1045 grouping in @var{regexp}.  (This is called a ``back reference.'')
1046 @samp{\#} refers to the count of replacements already made in this
1047 command, as a decimal number.  In the first replacement, @samp{\#}
1048 stands for @samp{0}; in the second, for @samp{1}; and so on.  For
1049 example,
1051 @example
1052 M-x replace-regexp @key{RET} c[ad]+r @key{RET} \&-safe @key{RET}
1053 @end example
1055 @noindent
1056 replaces (for example) @samp{cadr} with @samp{cadr-safe} and @samp{cddr}
1057 with @samp{cddr-safe}.
1059 @example
1060 M-x replace-regexp @key{RET} \(c[ad]+r\)-safe @key{RET} \1 @key{RET}
1061 @end example
1063 @noindent
1064 performs the inverse transformation.  To include a @samp{\} in the
1065 text to replace with, you must enter @samp{\\}.
1067   If you want to enter part of the replacement string by hand each
1068 time, use @samp{\?} in the replacement string.  Each replacement will
1069 ask you to edit the replacement string in the minibuffer, putting
1070 point where the @samp{\?} was.
1072   The remainder of this subsection is intended for specialized tasks
1073 and requires knowledge of Lisp.  Most readers can skip it.
1075   You can use Lisp expressions to calculate parts of the
1076 replacement string.  To do this, write @samp{\,} followed by the
1077 expression in the replacement string.  Each replacement calculates the
1078 value of the expression and converts it to text without quoting (if
1079 it's a string, this means using the string's contents), and uses it in
1080 the replacement string in place of the expression itself.  If the
1081 expression is a symbol, one space in the replacement string after the
1082 symbol name goes with the symbol name, so the value replaces them
1083 both.
1085   Inside such an expression, you can use some special sequences.
1086 @samp{\&} and @samp{\@var{n}} refer here, as usual, to the entire
1087 match as a string, and to a submatch as a string.  @var{n} may be
1088 multiple digits, and the value of @samp{\@var{n}} is @code{nil} if
1089 subexpression @var{n} did not match.  You can also use @samp{\#&} and
1090 @samp{\#@var{n}} to refer to those matches as numbers (this is valid
1091 when the match or submatch has the form of a numeral).  @samp{\#} here
1092 too stands for the number of already-completed replacements.
1094   Repeating our example to exchange @samp{x} and @samp{y}, we can thus
1095 do it also this way:
1097 @example
1098 M-x replace-regexp @key{RET} \(x\)\|y @key{RET}
1099 \,(if \1 "y" "x") @key{RET}
1100 @end example
1102   For computing replacement strings for @samp{\,}, the @code{format}
1103 function is often useful (@pxref{Formatting Strings,,, elisp, The Emacs
1104 Lisp Reference Manual}).  For example, to add consecutively numbered
1105 strings like @samp{ABC00042} to columns 73 @w{to 80} (unless they are
1106 already occupied), you can use
1108 @example
1109 M-x replace-regexp @key{RET} ^.\@{0,72\@}$ @key{RET}
1110 \,(format "%-72sABC%05d" \& \#) @key{RET}
1111 @end example
1113 @node Replacement and Case, Query Replace, Regexp Replace, Replace
1114 @subsection Replace Commands and Case
1116   If the first argument of a replace command is all lower case, the
1117 command ignores case while searching for occurrences to
1118 replace---provided @code{case-fold-search} is non-@code{nil}.  If
1119 @code{case-fold-search} is set to @code{nil}, case is always significant
1120 in all searches.
1122 @vindex case-replace
1123   In addition, when the @var{newstring} argument is all or partly lower
1124 case, replacement commands try to preserve the case pattern of each
1125 occurrence.  Thus, the command
1127 @example
1128 M-x replace-string @key{RET} foo @key{RET} bar @key{RET}
1129 @end example
1131 @noindent
1132 replaces a lower case @samp{foo} with a lower case @samp{bar}, an
1133 all-caps @samp{FOO} with @samp{BAR}, and a capitalized @samp{Foo} with
1134 @samp{Bar}.  (These three alternatives---lower case, all caps, and
1135 capitalized, are the only ones that @code{replace-string} can
1136 distinguish.)
1138   If upper-case letters are used in the replacement string, they remain
1139 upper case every time that text is inserted.  If upper-case letters are
1140 used in the first argument, the second argument is always substituted
1141 exactly as given, with no case conversion.  Likewise, if either
1142 @code{case-replace} or @code{case-fold-search} is set to @code{nil},
1143 replacement is done without case conversion.
1145 @node Query Replace,, Replacement and Case, Replace
1146 @subsection Query Replace
1147 @cindex query replace
1149 @table @kbd
1150 @item M-% @var{string} @key{RET} @var{newstring} @key{RET}
1151 @itemx M-x query-replace @key{RET} @var{string} @key{RET} @var{newstring} @key{RET}
1152 Replace some occurrences of @var{string} with @var{newstring}.
1153 @item C-M-% @var{regexp} @key{RET} @var{newstring} @key{RET}
1154 @itemx M-x query-replace-regexp @key{RET} @var{regexp} @key{RET} @var{newstring} @key{RET}
1155 Replace some matches for @var{regexp} with @var{newstring}.
1156 @end table
1158 @kindex M-%
1159 @findex query-replace
1160   If you want to change only some of the occurrences of @samp{foo} to
1161 @samp{bar}, not all of them, use @kbd{M-%} (@code{query-replace}).
1162 This command finds occurrences of @samp{foo} one by one, displays each
1163 occurrence and asks you whether to replace it.  Aside from querying,
1164 @code{query-replace} works just like @code{replace-string}
1165 (@pxref{Unconditional Replace}).  In particular, it preserves case
1166 provided @code{case-replace} is non-@code{nil}, as it normally is
1167 (@pxref{Replacement and Case}).  A numeric argument means consider
1168 only occurrences that are bounded by word-delimiter characters.
1170 @kindex C-M-%
1171 @findex query-replace-regexp
1172   @kbd{C-M-%} performs regexp search and replace (@code{query-replace-regexp}).
1173 It works like @code{replace-regexp} except that it queries
1174 like @code{query-replace}.
1176 @cindex faces for highlighting query replace
1177   These commands highlight the current match using the face
1178 @code{query-replace}.  They highlight other matches using
1179 @code{lazy-highlight} just like incremental search (@pxref{Incremental
1180 Search}).  By default, @code{query-replace-regexp} will show
1181 substituted replacement string for the current match in the
1182 minibuffer.  If you want to keep special sequences @samp{\&} and
1183 @samp{\@var{n}} unexpanded, customize
1184 @code{query-replace-show-replacement} variable.
1186   The characters you can type when you are shown a match for the string
1187 or regexp are:
1189 @ignore @c Not worth it.
1190 @kindex SPC @r{(query-replace)}
1191 @kindex DEL @r{(query-replace)}
1192 @kindex , @r{(query-replace)}
1193 @kindex RET @r{(query-replace)}
1194 @kindex . @r{(query-replace)}
1195 @kindex ! @r{(query-replace)}
1196 @kindex ^ @r{(query-replace)}
1197 @kindex C-r @r{(query-replace)}
1198 @kindex C-w @r{(query-replace)}
1199 @kindex C-l @r{(query-replace)}
1200 @end ignore
1202 @c WideCommands
1203 @table @kbd
1204 @item @key{SPC}
1205 to replace the occurrence with @var{newstring}.
1207 @item @key{DEL}
1208 to skip to the next occurrence without replacing this one.
1210 @item , @r{(Comma)}
1211 to replace this occurrence and display the result.  You are then asked
1212 for another input character to say what to do next.  Since the
1213 replacement has already been made, @key{DEL} and @key{SPC} are
1214 equivalent in this situation; both move to the next occurrence.
1216 You can type @kbd{C-r} at this point (see below) to alter the replaced
1217 text.  You can also type @kbd{C-x u} to undo the replacement; this exits
1218 the @code{query-replace}, so if you want to do further replacement you
1219 must use @kbd{C-x @key{ESC} @key{ESC} @key{RET}} to restart
1220 (@pxref{Repetition}).
1222 @item @key{RET}
1223 to exit without doing any more replacements.
1225 @item .@: @r{(Period)}
1226 to replace this occurrence and then exit without searching for more
1227 occurrences.
1229 @item !
1230 to replace all remaining occurrences without asking again.
1232 @item ^
1233 to go back to the position of the previous occurrence (or what used to
1234 be an occurrence), in case you changed it by mistake or want to
1235 reexamine it.
1237 @item C-r
1238 to enter a recursive editing level, in case the occurrence needs to be
1239 edited rather than just replaced with @var{newstring}.  When you are
1240 done, exit the recursive editing level with @kbd{C-M-c} to proceed to
1241 the next occurrence.  @xref{Recursive Edit}.
1243 @item C-w
1244 to delete the occurrence, and then enter a recursive editing level as in
1245 @kbd{C-r}.  Use the recursive edit to insert text to replace the deleted
1246 occurrence of @var{string}.  When done, exit the recursive editing level
1247 with @kbd{C-M-c} to proceed to the next occurrence.
1249 @item e
1250 to edit the replacement string in the minibuffer.  When you exit the
1251 minibuffer by typing @key{RET}, the minibuffer contents replace the
1252 current occurrence of the pattern.  They also become the new
1253 replacement string for any further occurrences.
1255 @item C-l
1256 to redisplay the screen.  Then you must type another character to
1257 specify what to do with this occurrence.
1259 @item C-h
1260 to display a message summarizing these options.  Then you must type
1261 another character to specify what to do with this occurrence.
1262 @end table
1264   Some other characters are aliases for the ones listed above: @kbd{y},
1265 @kbd{n} and @kbd{q} are equivalent to @key{SPC}, @key{DEL} and
1266 @key{RET}.
1268   Aside from this, any other character exits the @code{query-replace},
1269 and is then reread as part of a key sequence.  Thus, if you type
1270 @kbd{C-k}, it exits the @code{query-replace} and then kills to end of
1271 line.
1273   To restart a @code{query-replace} once it is exited, use @kbd{C-x
1274 @key{ESC} @key{ESC}}, which repeats the @code{query-replace} because it
1275 used the minibuffer to read its arguments.  @xref{Repetition, C-x ESC
1276 ESC}.
1278   @xref{Operating on Files}, for the Dired @kbd{Q} command which
1279 performs query replace on selected files.  See also @ref{Transforming
1280 File Names}, for Dired commands to rename, copy, or link files by
1281 replacing regexp matches in file names.
1283 @node Other Repeating Search
1284 @section Other Search-and-Loop Commands
1286   Here are some other commands that find matches for a regular
1287 expression.  They all ignore case in matching, if the pattern contains
1288 no upper-case letters and @code{case-fold-search} is non-@code{nil}.
1289 Aside from @code{occur} and its variants, all operate on the text from
1290 point to the end of the buffer, or on the region if it is active.
1292 @findex list-matching-lines
1293 @findex occur
1294 @findex multi-occur
1295 @findex multi-occur-in-matching-buffers
1296 @findex how-many
1297 @findex flush-lines
1298 @findex keep-lines
1300 @table @kbd
1301 @item M-x multi-isearch-buffers
1302 Prompt for one or more buffer names, ending with @key{RET}; then,
1303 begin a multi-buffer incremental search in those buffers.  (If the
1304 search fails in one buffer, the next @kbd{C-s} tries searching the
1305 next specified buffer, and so forth.)  With a prefix argument, prompt
1306 for a regexp and begin a multi-buffer incremental search in buffers
1307 matching that regexp.
1309 @item M-x multi-isearch-buffers-regexp
1310 This command is just like @code{multi-isearch-buffers}, except it
1311 performs an incremental regexp search.
1313 @item M-x occur
1314 Prompt for a regexp, and display a list showing each line in the
1315 buffer that contains a match for it.  To limit the search to part of
1316 the buffer, narrow to that part (@pxref{Narrowing}).  A numeric
1317 argument @var{n} specifies that @var{n} lines of context are to be
1318 displayed before and after each matching line.  Currently,
1319 @code{occur} can not correctly handle multiline matches.
1321 @kindex RET @r{(Occur mode)}
1322 @kindex o @r{(Occur mode)}
1323 @kindex C-o @r{(Occur mode)}
1324 The buffer @samp{*Occur*} containing the output serves as a menu for
1325 finding the occurrences in their original context.  Click
1326 @kbd{Mouse-2} on an occurrence listed in @samp{*Occur*}, or position
1327 point there and type @key{RET}; this switches to the buffer that was
1328 searched and moves point to the original of the chosen occurrence.
1329 @kbd{o} and @kbd{C-o} display the match in another window; @kbd{C-o}
1330 does not select it.
1332 After using @kbd{M-x occur}, you can use @code{next-error} to visit
1333 the occurrences found, one by one.  @ref{Compilation Mode}.
1335 @kindex M-s o
1336 @item M-s o
1337 Run @code{occur} using the search string of the last incremental
1338 string search.  You can also run @kbd{M-s o} when an incremental
1339 search is active; this uses the current search string.
1341 @item M-x list-matching-lines
1342 Synonym for @kbd{M-x occur}.
1344 @item M-x multi-occur
1345 This command is just like @code{occur}, except it is able to search
1346 through multiple buffers.  It asks you to specify the buffer names one
1347 by one.
1349 @item M-x multi-occur-in-matching-buffers
1350 This command is similar to @code{multi-occur}, except the buffers to
1351 search are specified by a regular expression that matches visited file
1352 names.  With a prefix argument, it uses the regular expression to
1353 match buffer names instead.
1355 @item M-x how-many
1356 Prompt for a regexp, and print the number of matches for it in the
1357 buffer after point.  If the region is active, this operates on the
1358 region instead.
1360 @item M-x flush-lines
1361 Prompt for a regexp, and delete each line that contains a match for
1362 it, operating on the text after point.  This command deletes the
1363 current line if it contains a match starting after point.  If the
1364 region is active, it operates on the region instead; if a line
1365 partially contained in the region contains a match entirely contained
1366 in the region, it is deleted.
1368 If a match is split across lines, @code{flush-lines} deletes all those
1369 lines.  It deletes the lines before starting to look for the next
1370 match; hence, it ignores a match starting on the same line at which
1371 another match ended.
1373 @item M-x keep-lines
1374 Prompt for a regexp, and delete each line that @emph{does not} contain
1375 a match for it, operating on the text after point.  If point is not at
1376 the beginning of a line, this command always keeps the current line.
1377 If the region is active, the command operates on the region instead;
1378 it never deletes lines that are only partially contained in the region
1379 (a newline that ends a line counts as part of that line).
1381 If a match is split across lines, this command keeps all those lines.
1382 @end table
1384 @ignore
1385    arch-tag: fd9d8e77-66af-491c-b212-d80999613e3e
1386 @end ignore