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