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