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