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