Build Fix -- compatibility issue with newer autoconf
[sxemacs] / info / lispref / searching.texi
1 @c -*-texinfo-*-
2 @c This is part of the SXEmacs Lisp Reference Manual.
3 @c Copyright (C) 1990, 1991, 1992, 1993, 1994 Free Software Foundation, Inc.
4 @c Copyright (C) 2005 Sebastian Freundt <hroptatyr@sxemacs.org>
5 @c See the file lispref.texi for copying conditions.
6 @setfilename ../../info/searching.info
7
8 @node Searching and Matching, Syntax Tables, Text, Top
9 @chapter Searching and Matching
10 @cindex searching
11
12   XEmacs provides two ways to search through a buffer for specified
13 text: exact string searches and regular expression searches.  After a
14 regular expression search, you can examine the @dfn{match data} to
15 determine which text matched the whole regular expression or various
16 portions of it.
17
18 @menu
19 * String Search::         Search for an exact match.
20 * Regular Expressions::   Describing classes of strings.
21 * Regexp Search::         Searching for a match for a regexp.
22 * POSIX Regexps::         Searching POSIX-style for the longest match.
23 * Search and Replace::    Internals of @code{query-replace}.
24 * Match Data::            Finding out which part of the text matched
25                             various parts of a regexp, after regexp search.
26 * Searching and Case::    Case-independent or case-significant searching.
27 * Standard Regexps::      Useful regexps for finding sentences, pages,...
28 @end menu
29
30   The @samp{skip-chars@dots{}} functions also perform a kind of searching.
31 @xref{Skipping Characters}.
32
33
34 @node String Search, Regular Expressions, Searching and Matching, Searching and Matching
35 @section Searching for Strings
36 @cindex string search
37
38   These are the primitive functions for searching through the text in a
39 buffer.  They are meant for use in programs, but you may call them
40 interactively.  If you do so, they prompt for the search string;
41 @var{limit} and @var{noerror} are set to @code{nil}, and @var{count}
42 is set to 1.
43
44 @deffn Command search-forward string &optional limit noerror count buffer
45   This function searches forward from point for an exact match for
46 @var{string}.  If successful, it sets point to the end of the occurrence
47 found, and returns the new value of point.  If no match is found, the
48 value and side effects depend on @var{noerror} (see below).
49
50   In the following example, point is initially at the beginning of the
51 line.  Then @code{(search-forward "fox")} moves point after the last
52 letter of @samp{fox}:
53
54 @example
55 @group
56 ---------- Buffer: foo ----------
57 @point{}The quick brown fox jumped over the lazy dog.
58 ---------- Buffer: foo ----------
59 @end group
60
61 @group
62 (search-forward "fox")
63      @result{} 20
64
65 ---------- Buffer: foo ----------
66 The quick brown fox@point{} jumped over the lazy dog.
67 ---------- Buffer: foo ----------
68 @end group
69 @end example
70
71   The argument @var{limit} specifies the upper bound to the search.  (It
72 must be a position in the current buffer.)  No match extending after
73 that position is accepted.  If @var{limit} is omitted or @code{nil}, it
74 defaults to the end of the accessible portion of the buffer.
75
76 @kindex search-failed
77   What happens when the search fails depends on the value of
78 @var{noerror}.  If @var{noerror} is @code{nil}, a @code{search-failed}
79 error is signaled.  If @var{noerror} is @code{t}, @code{search-forward}
80 returns @code{nil} and does nothing.  If @var{noerror} is neither
81 @code{nil} nor @code{t}, then @code{search-forward} moves point to the
82 upper bound and returns @code{nil}.  (It would be more consistent now
83 to return the new position of point in that case, but some programs
84 may depend on a value of @code{nil}.)
85
86 If @var{count} is supplied (it must be an integer), then the search is
87 repeated that many times (each time starting at the end of the previous
88 time's match).  If @var{count} is negative, the search direction is
89 backward.  If the successive searches succeed, the function succeeds,
90 moving point and returning its new value.  Otherwise the search fails.
91
92 @var{buffer} is the buffer to search in, and defaults to the current buffer.
93 @end deffn
94
95 @deffn Command search-backward string &optional limit noerror count buffer
96 This function searches backward from point for @var{string}.  It is
97 just like @code{search-forward} except that it searches backwards and
98 leaves point at the beginning of the match.
99 @end deffn
100
101 @deffn Command word-search-forward string &optional limit noerror count buffer
102 @cindex word search
103 This function searches forward from point for a ``word'' match for
104 @var{string}.  If it finds a match, it sets point to the end of the
105 match found, and returns the new value of point.
106
107 Word matching regards @var{string} as a sequence of words, disregarding
108 punctuation that separates them.  It searches the buffer for the same
109 sequence of words.  Each word must be distinct in the buffer (searching
110 for the word @samp{ball} does not match the word @samp{balls}), but the
111 details of punctuation and spacing are ignored (searching for @samp{ball
112 boy} does match @samp{ball.  Boy!}).
113
114 In this example, point is initially at the beginning of the buffer; the
115 search leaves it between the @samp{y} and the @samp{!}.
116
117 @example
118 @group
119 ---------- Buffer: foo ----------
120 @point{}He said "Please!  Find
121 the ball boy!"
122 ---------- Buffer: foo ----------
123 @end group
124
125 @group
126 (word-search-forward "Please find the ball, boy.")
127      @result{} 35
128
129 ---------- Buffer: foo ----------
130 He said "Please!  Find
131 the ball boy@point{}!"
132 ---------- Buffer: foo ----------
133 @end group
134 @end example
135
136 If @var{limit} is non-@code{nil} (it must be a position in the current
137 buffer), then it is the upper bound to the search.  The match found must
138 not extend after that position.
139
140 If @var{noerror} is @code{nil}, then @code{word-search-forward} signals
141 an error if the search fails.  If @var{noerror} is @code{t}, then it
142 returns @code{nil} instead of signaling an error.  If @var{noerror} is
143 neither @code{nil} nor @code{t}, it moves point to @var{limit} (or the
144 end of the buffer) and returns @code{nil}.
145
146 If @var{count} is non-@code{nil}, then the search is repeated that many
147 times.  Point is positioned at the end of the last match.
148
149 @var{buffer} is the buffer to search in, and defaults to the current buffer.
150 @end deffn
151
152 @deffn Command word-search-backward string &optional limit noerror count buffer
153 This function searches backward from point for a word match to
154 @var{string}.  This function is just like @code{word-search-forward}
155 except that it searches backward and normally leaves point at the
156 beginning of the match.
157 @end deffn
158
159
160 @node Regular Expressions, Regexp Search, String Search, Searching and Matching
161 @section Regular Expressions
162 @cindex regular expression
163 @cindex regexp
164
165   A @dfn{regular expression} (@dfn{regexp}, for short) is a pattern that
166 denotes a (possibly infinite) set of strings.  Searching for matches for
167 a regexp is a very powerful operation.  This section explains how to write
168 regexps; the following section says how to search for them.
169
170  To gain a thorough understanding of regular expressions and how to use
171 them to best advantage, we recommend that you study @cite{Mastering
172 Regular Expressions, by Jeffrey E.F. Friedl, O'Reilly and Associates,
173 1997}. (It's known as the "Hip Owls" book, because of the picture on its
174 cover.)  You might also read the manuals to @ref{(gawk)Top},
175 @ref{(ed)Top}, @cite{sed}, @cite{grep}, @ref{(perl)Top},
176 @ref{(regex)Top}, @ref{(rx)Top}, @cite{pcre}, and @ref{(flex)Top}, which
177 also make good use of regular expressions.
178
179  The SXEmacs regular expression syntax most closely resembles that of
180 @cite{ed}, or @cite{grep}, the GNU versions of which all utilize the GNU
181 @cite{regex} library.  SXEmacs' version of @cite{regex} has recently been
182 extended with some Perl--like capabilities, described in the next
183 section.
184
185 @menu
186 * Syntax of Regexps::       Rules for writing regular expressions.
187 * Regexp Example::          Illustrates regular expression syntax.
188 @end menu
189
190
191 @node Syntax of Regexps, Regexp Example, Regular Expressions, Regular Expressions
192 @subsection Syntax of Regular Expressions
193
194   Regular expressions have a syntax in which a few characters are
195 special constructs and the rest are @dfn{ordinary}.  An ordinary
196 character is a simple regular expression that matches that character and
197 nothing else.  The special characters are @samp{.}, @samp{*}, @samp{+},
198 @samp{?}, @samp{[}, @samp{]}, @samp{^}, @samp{$}, and @samp{\}; no new
199 special characters will be defined in the future.  Any other character
200 appearing in a regular expression is ordinary, unless a @samp{\}
201 precedes it.
202
203 For example, @samp{f} is not a special character, so it is ordinary, and
204 therefore @samp{f} is a regular expression that matches the string
205 @samp{f} and no other string.  (It does @emph{not} match the string
206 @samp{ff}.)  Likewise, @samp{o} is a regular expression that matches
207 only @samp{o}.@refill
208
209 Any two regular expressions @var{a} and @var{b} can be concatenated.  The
210 result is a regular expression that matches a string if @var{a} matches
211 some amount of the beginning of that string and @var{b} matches the rest of
212 the string.@refill
213
214 As a simple example, we can concatenate the regular expressions @samp{f}
215 and @samp{o} to get the regular expression @samp{fo}, which matches only
216 the string @samp{fo}.  Still trivial.  To do something more powerful, you
217 need to use one of the special characters.  Here is a list of them:
218
219 @need 1200
220 @table @kbd
221 @item .@: @r{(Period)}
222 @cindex @samp{.} in regexp
223 is a special character that matches any single character except a newline.
224 Using concatenation, we can make regular expressions like @samp{a.b}, which
225 matches any three-character string that begins with @samp{a} and ends with
226 @samp{b}.@refill
227
228 @item *
229 @cindex @samp{*} in regexp
230 is not a construct by itself; it is a quantifying suffix operator that
231 means to repeat the preceding regular expression as many times as
232 possible.  In @samp{fo*}, the @samp{*} applies to the @samp{o}, so
233 @samp{fo*} matches one @samp{f} followed by any number of @samp{o}s.
234 The case of zero @samp{o}s is allowed: @samp{fo*} does match
235 @samp{f}.@refill
236
237 @samp{*} always applies to the @emph{smallest} possible preceding
238 expression.  Thus, @samp{fo*} has a repeating @samp{o}, not a
239 repeating @samp{fo}.@refill
240
241 The matcher processes a @samp{*} construct by matching, immediately, as
242 many repetitions as can be found; it is "greedy".  Then it continues
243 with the rest of the pattern.  If that fails, backtracking occurs,
244 discarding some of the matches of the @samp{*}-modified construct in
245 case that makes it possible to match the rest of the pattern.  For
246 example, in matching @samp{ca*ar} against the string @samp{caaar}, the
247 @samp{a*} first tries to match all three @samp{a}s; but the rest of the
248 pattern is @samp{ar} and there is only @samp{r} left to match, so this
249 try fails.  The next alternative is for @samp{a*} to match only two
250 @samp{a}s.  With this choice, the rest of the regexp matches
251 successfully.@refill
252
253 Nested repetition operators can be extremely slow if they specify
254 backtracking loops.  For example, it could take hours for the regular
255 expression @samp{\(x+y*\)*a} to match the sequence
256 @samp{xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxz}.  The slowness is because
257 SXEmacs must try each imaginable way of grouping the 35 @samp{x}'s before
258 concluding that none of them can work.  To make sure your regular
259 expressions run fast, check nested repetitions carefully.
260
261 @item +
262 @cindex @samp{+} in regexp
263 is a quantifying suffix operator similar to @samp{*} except that the
264 preceding expression must match at least once.  It is also "greedy".
265 So, for example, @samp{ca+r} matches the strings @samp{car} and
266 @samp{caaaar} but not the string @samp{cr}, whereas @samp{ca*r} matches
267 all three strings.
268
269 @item ?
270 @cindex @samp{?} in regexp
271 is a quantifying suffix operator similar to @samp{*}, except that the
272 preceding expression can match either once or not at all.  For example,
273 @samp{ca?r} matches @samp{car} or @samp{cr}, but does not match anything
274 else.
275
276 @item *?
277 @cindex @samp{*?} in regexp
278 works just like @samp{*}, except that rather than matching the longest
279 match, it matches the shortest match.  @samp{*?} is known as a
280 @dfn{non-greedy} quantifier, a regexp construct borrowed from Perl.
281 @c Did perl get this from somewhere?  What's the real history of *? ?
282
283 This construct is very useful for when you want to match the text inside
284 a pair of delimiters.  For instance, @samp{/\*.*?\*/} will match C
285 comments in a string.  This could not easily be achieved without the use
286 of a non-greedy quantifier.
287
288 This construct has not been available prior to XEmacs 20.4.  It is not
289 available in FSF Emacs.
290
291 @item +?
292 @cindex @samp{+?} in regexp
293 is the non-greedy version of @samp{+}.
294
295 @item ??
296 @cindex @samp{??} in regexp
297 is the non-greedy version of @samp{?}.
298
299 @item \@{n,m\@}
300 @c Note the spacing after the close brace is deliberate.
301 @cindex @samp{\@{n,m\@} }in regexp
302 serves as an interval quantifier, analogous to @samp{*} or @samp{+}, but
303 specifies that the expression must match at least @var{n} times, but no
304 more than @var{m} times.  This syntax is supported by most Unix regexp
305 utilities, and has been introduced to XEmacs for the version 20.3.
306
307 Unfortunately, the non-greedy version of this quantifier does not exist
308 currently, although it does in Perl.
309
310 @item [ @dots{} ]
311 @cindex character set (in regexp)
312 @cindex @samp{[} in regexp
313 @cindex @samp{]} in regexp
314 @samp{[} begins a @dfn{character set}, which is terminated by a
315 @samp{]}.  In the simplest case, the characters between the two brackets
316 form the set.  Thus, @samp{[ad]} matches either one @samp{a} or one
317 @samp{d}, and @samp{[ad]*} matches any string composed of just @samp{a}s
318 and @samp{d}s (including the empty string), from which it follows that
319 @samp{c[ad]*r} matches @samp{cr}, @samp{car}, @samp{cdr},
320 @samp{caddaar}, etc.@refill
321
322 The usual regular expression special characters are not special inside a
323 character set.  A completely different set of special characters exists
324 inside character sets: @samp{]}, @samp{-} and @samp{^}.@refill
325
326 @samp{-} is used for ranges of characters.  To write a range, write two
327 characters with a @samp{-} between them.  Thus, @samp{[a-z]} matches any
328 lower case letter.  Ranges may be intermixed freely with individual
329 characters, as in @samp{[a-z$%.]}, which matches any lower case letter
330 or @samp{$}, @samp{%}, or a period.@refill
331
332 To include a @samp{]} in a character set, make it the first character.
333 For example, @samp{[]a]} matches @samp{]} or @samp{a}.  To include a
334 @samp{-}, write @samp{-} as the first character in the set, or put it
335 immediately after a range.  (You can replace one individual character
336 @var{c} with the range @samp{@var{c}-@var{c}} to make a place to put the
337 @samp{-}.)  There is no way to write a set containing just @samp{-} and
338 @samp{]}.
339
340 To include @samp{^} in a set, put it anywhere but at the beginning of
341 the set.
342
343 @item [^ @dots{} ]
344 @cindex @samp{^} in regexp
345 @samp{[^} begins a @dfn{complement character set}, which matches any
346 character except the ones specified.  Thus, @samp{[^a-z0-9A-Z]}
347 matches all characters @emph{except} letters and digits.@refill
348
349 @samp{^} is not special in a character set unless it is the first
350 character.  The character following the @samp{^} is treated as if it
351 were first (thus, @samp{-} and @samp{]} are not special there).
352
353 Note that a complement character set can match a newline, unless
354 newline is mentioned as one of the characters not to match.
355
356 @item ^
357 @cindex @samp{^} in regexp
358 @cindex beginning of line in regexp
359 is a special character that matches the empty string, but only at the
360 beginning of a line in the text being matched.  Otherwise it fails to
361 match anything.  Thus, @samp{^foo} matches a @samp{foo} that occurs at
362 the beginning of a line.
363
364 When matching a string instead of a buffer, @samp{^} matches at the
365 beginning of the string or after a newline character @samp{\n}.
366
367 @item $
368 @cindex @samp{$} in regexp
369 is similar to @samp{^} but matches only at the end of a line.  Thus,
370 @samp{x+$} matches a string of one @samp{x} or more at the end of a line.
371
372 When matching a string instead of a buffer, @samp{$} matches at the end
373 of the string or before a newline character @samp{\n}.
374
375 @item \
376 @cindex @samp{\} in regexp
377 has two functions: it quotes the special characters (including
378 @samp{\}), and it introduces additional special constructs.
379
380 Because @samp{\} quotes special characters, @samp{\$} is a regular
381 expression that matches only @samp{$}, and @samp{\[} is a regular
382 expression that matches only @samp{[}, and so on.
383
384 Note that @samp{\} also has special meaning in the read syntax of Lisp
385 strings (@pxref{String Type}), and must be quoted with @samp{\}.  For
386 example, the regular expression that matches the @samp{\} character is
387 @samp{\\}.  To write a Lisp string that contains the characters
388 @samp{\\}, Lisp syntax requires you to quote each @samp{\} with another
389 @samp{\}.  Therefore, the read syntax for a regular expression matching
390 @samp{\} is @code{"\\\\"}.@refill
391 @end table
392
393 @strong{Please note:} For historical compatibility, special characters
394 are treated as ordinary ones if they are in contexts where their special
395 meanings make no sense.  For example, @samp{*foo} treats @samp{*} as
396 ordinary since there is no preceding expression on which the @samp{*}
397 can act.  It is poor practice to depend on this behavior; quote the
398 special character anyway, regardless of where it appears.@refill
399
400 For the most part, @samp{\} followed by any character matches only
401 that character.  However, there are several exceptions: characters
402 that, when preceded by @samp{\}, are special constructs.  Such
403 characters are always ordinary when encountered on their own.  Here
404 is a table of @samp{\} constructs:
405
406 @table @kbd
407 @item \|
408 @cindex @samp{|} in regexp
409 @cindex regexp alternative
410 specifies an alternative.
411 Two regular expressions @var{a} and @var{b} with @samp{\|} in
412 between form an expression that matches anything that either @var{a} or
413 @var{b} matches.@refill
414
415 Thus, @samp{foo\|bar} matches either @samp{foo} or @samp{bar}
416 but no other string.@refill
417
418 @samp{\|} applies to the largest possible surrounding expressions.  Only a
419 surrounding @samp{\( @dots{} \)} grouping can limit the grouping power of
420 @samp{\|}.@refill
421
422 Full backtracking capability exists to handle multiple uses of @samp{\|}.
423
424 @item \( @dots{} \)
425 @cindex @samp{(} in regexp
426 @cindex @samp{)} in regexp
427 @cindex regexp grouping
428 is a grouping construct that serves three purposes:
429
430 @enumerate
431 @item
432 To enclose a set of @samp{\|} alternatives for other operations.
433 Thus, @samp{\(foo\|bar\)x} matches either @samp{foox} or @samp{barx}.
434
435 @item
436 To enclose an expression for a suffix operator such as @samp{*} to act
437 on.  Thus, @samp{ba\(na\)*} matches @samp{bananana}, etc., with any
438 (zero or more) number of @samp{na} strings.@refill
439
440 @item
441 To record a matched substring for future reference.
442 @end enumerate
443
444 This last application is not a consequence of the idea of a
445 parenthetical grouping; it is a separate feature that happens to be
446 assigned as a second meaning to the same @samp{\( @dots{} \)} construct
447 because there is no conflict in practice between the two meanings.
448 Here is an explanation of this feature:
449
450 @item \@var{digit}
451 matches the same text that matched the @var{digit}th occurrence of a
452 @samp{\( @dots{} \)} construct.
453
454 In other words, after the end of a @samp{\( @dots{} \)} construct, the
455 matcher remembers the beginning and end of the text matched by that
456 construct.  Then, later on in the regular expression, you can use
457 @samp{\} followed by @var{digit} to match that same text, whatever it
458 may have been.
459
460 The strings matching the first nine @samp{\( @dots{} \)} constructs
461 appearing in a regular expression are assigned numbers 1 through 9 in
462 the order that the open parentheses appear in the regular expression.
463 So you can use @samp{\1} through @samp{\9} to refer to the text matched
464 by the corresponding @samp{\( @dots{} \)} constructs.
465
466 For example, @samp{\(.*\)\1} matches any newline-free string that is
467 composed of two identical halves.  The @samp{\(.*\)} matches the first
468 half, which may be anything, but the @samp{\1} that follows must match
469 the same exact text.
470
471 @item \(?: @dots{} \)
472 @cindex @samp{\(?:} in regexp
473 @cindex regexp grouping
474 is called a @dfn{shy} grouping operator, and it is used just like
475 @samp{\( @dots{} \)}, except that it does not cause the matched
476 substring to be recorded for future reference.
477
478 This is useful when you need a lot of grouping @samp{\( @dots{} \)}
479 constructs, but only want to remember one or two -- or if you have
480 more than nine groupings and need to use backreferences to refer to
481 the groupings at the end.  It also allows construction of regular
482 expressions from variable subexpressions that contain varying numbers of
483 non-capturing subexpressions, without disturbing the group counts for
484 the main expression.  For example
485
486 @example
487 (let ((sre (if foo "\\(?:bar\\|baz\\)" "quux")))
488   (re-search-forward (format "a\\(b+ %s c+\\) d" sre) nil t)
489   (match-string 1))
490 @end example
491
492 It is very tedious to write this kind of code without shy groups, even
493 if you know what all the alternative subexpressions will look like.
494
495 Using @samp{\(?: @dots{} \)} rather than @samp{\( @dots{} \)} should
496 give little performance gain, as the start of each group must be
497 recorded for the purpose of back-tracking in any case, and no string
498 copying is done until @code{match-string} is called.
499
500 The shy grouping operator has been borrowed from Perl, and was not
501 available prior to XEmacs 20.3, and has only been available in GNU Emacs
502 since version 21.
503
504 @item \w
505 @cindex @samp{\w} in regexp
506 matches any word-constituent character.  The editor syntax table
507 determines which characters these are.  @xref{Syntax Tables}.
508
509 @item \W
510 @cindex @samp{\W} in regexp
511 matches any character that is not a word constituent.
512
513 @item \s@var{code}
514 @cindex @samp{\s} in regexp
515 matches any character whose syntax is @var{code}.  Here @var{code} is a
516 character that represents a syntax code: thus, @samp{w} for word
517 constituent, @samp{-} for whitespace, @samp{(} for open parenthesis,
518 etc.  @xref{Syntax Tables}, for a list of syntax codes and the
519 characters that stand for them.
520
521 @item \S@var{code}
522 @cindex @samp{\S} in regexp
523 matches any character whose syntax is not @var{code}.
524
525 @item \c@var{category}
526 @cindex @samp{\c} in regexp
527 matches any character in @var{category}. Only available under Mule,
528 categories, and category tables, are further described in @ref{Category
529 Tables}. They are a mechanism for constructing classes of characters
530 that can be local to a buffer, and that do not require complicated []
531 expressions every time they are referenced.
532
533 @item \C@var{category}
534 @cindex @samp{\C} in regexp
535 matches any character outside @var{category}. @xref{Category Tables},
536 again, and note that this is only available under Mule.
537 @end table
538
539   The following regular expression constructs match the empty string---that is,
540 they don't use up any characters---but whether they match depends on the
541 context.
542
543 @table @kbd
544 @item \`
545 @cindex @samp{\`} in regexp
546 matches the empty string, but only at the beginning
547 of the buffer or string being matched against.
548
549 @item \'
550 @cindex @samp{\'} in regexp
551 matches the empty string, but only at the end of
552 the buffer or string being matched against.
553
554 @item \=
555 @cindex @samp{\=} in regexp
556 matches the empty string, but only at point.
557 (This construct is not defined when matching against a string.)
558
559 @item \b
560 @cindex @samp{\b} in regexp
561 matches the empty string, but only at the beginning or
562 end of a word.  Thus, @samp{\bfoo\b} matches any occurrence of
563 @samp{foo} as a separate word.  @samp{\bballs?\b} matches
564 @samp{ball} or @samp{balls} as a separate word.@refill
565
566 @item \B
567 @cindex @samp{\B} in regexp
568 matches the empty string, but @emph{not} at the beginning or
569 end of a word.
570
571 @item \<
572 @cindex @samp{\<} in regexp
573 matches the empty string, but only at the beginning of a word.
574
575 @item \>
576 @cindex @samp{\>} in regexp
577 matches the empty string, but only at the end of a word.
578 @end table
579
580 @kindex invalid-regexp
581   Not every string is a valid regular expression.  For example, a string
582 with unbalanced square brackets is invalid (with a few exceptions, such
583 as @samp{[]]}), and so is a string that ends with a single @samp{\}.  If
584 an invalid regular expression is passed to any of the search functions,
585 an @code{invalid-regexp} error is signaled.
586
587 @defun regexp-quote string
588 This function returns a regular expression string that matches exactly
589 @var{string} and nothing else.  This allows you to request an exact
590 string match when calling a function that wants a regular expression.
591
592 @example
593 @group
594 (regexp-quote "^The cat$")
595      @result{} "\\^The cat\\$"
596 @end group
597 @end example
598
599 One use of @code{regexp-quote} is to combine an exact string match with
600 context described as a regular expression.  For example, this searches
601 for the string that is the value of @code{string}, surrounded by
602 whitespace:
603
604 @example
605 @group
606 (re-search-forward
607  (concat "\\s-" (regexp-quote string) "\\s-"))
608 @end group
609 @end example
610 @end defun
611
612
613 @node Regexp Example,  , Syntax of Regexps, Regular Expressions
614 @subsection Complex Regexp Example
615
616   Here is a complicated regexp, used by SXEmacs to recognize the end of a
617 sentence together with any whitespace that follows.  It is the value of
618 the variable @code{sentence-end}.
619
620   First, we show the regexp as a string in Lisp syntax to distinguish
621 spaces from tab characters.  The string constant begins and ends with a
622 double-quote.  @samp{\"} stands for a double-quote as part of the
623 string, @samp{\\} for a backslash as part of the string, @samp{\t} for a
624 tab and @samp{\n} for a newline.
625
626 @example
627 "[.?!][]\"')@}]*\\($\\| $\\|\t\\|  \\)[ \t\n]*"
628 @end example
629
630   In contrast, if you evaluate the variable @code{sentence-end}, you
631 will see the following:
632
633 @example
634 @group
635 sentence-end
636 @result{}
637 "[.?!][]\"')@}]*\\($\\| $\\|  \\|  \\)[
638 ]*"
639 @end group
640 @end example
641
642 @noindent
643 In this output, tab and newline appear as themselves.
644
645   This regular expression contains four parts in succession and can be
646 deciphered as follows:
647
648 @table @code
649 @item [.?!]
650 The first part of the pattern is a character set that matches any one of
651 three characters: period, question mark, and exclamation mark.  The
652 match must begin with one of these three characters.
653
654 @item []\"')@}]*
655 The second part of the pattern matches any closing braces and quotation
656 marks, zero or more of them, that may follow the period, question mark
657 or exclamation mark.  The @code{\"} is Lisp syntax for a double-quote in
658 a string.  The @samp{*} at the end indicates that the immediately
659 preceding regular expression (a character set, in this case) may be
660 repeated zero or more times.
661
662 @item \\($\\|@ $\\|\t\\|@ @ \\)
663 The third part of the pattern matches the whitespace that follows the
664 end of a sentence: the end of a line, or a tab, or two spaces.  The
665 double backslashes mark the parentheses and vertical bars as regular
666 expression syntax; the parentheses delimit a group and the vertical bars
667 separate alternatives.  The dollar sign is used to match the end of a
668 line.
669
670 @item [ \t\n]*
671 Finally, the last part of the pattern matches any additional whitespace
672 beyond the minimum needed to end a sentence.
673 @end table
674
675
676 @node Regexp Search, POSIX Regexps, Regular Expressions, Searching and Matching
677 @section Regular Expression Searching
678 @cindex regular expression searching
679 @cindex regexp searching
680 @cindex searching for regexp
681
682   In SXEmacs, you can search for the next match for a regexp either
683 incrementally or not.  Incremental search commands are described in the
684 @cite{The SXEmacs Lisp Reference Manual}.  @xref{Regexp Search, , Regular Expression
685 Search, sxemacs, The SXEmacs Lisp Reference Manual}.  Here we describe only the search
686 functions useful in programs.  The principal one is
687 @code{re-search-forward}.
688
689 @deffn Command re-search-forward regexp &optional limit noerror count buffer
690 This function searches forward in the current buffer for a string of
691 text that is matched by the regular expression @var{regexp}.  The
692 function skips over any amount of text that is not matched by
693 @var{regexp}, and leaves point at the end of the first match found.
694 It returns the new value of point.
695
696 If @var{limit} is non-@code{nil} (it must be a position in the current
697 buffer), then it is the upper bound to the search.  No match extending
698 after that position is accepted.
699
700 What happens when the search fails depends on the value of
701 @var{noerror}.  If @var{noerror} is @code{nil}, a @code{search-failed}
702 error is signaled.  If @var{noerror} is @code{t},
703 @code{re-search-forward} does nothing and returns @code{nil}.  If
704 @var{noerror} is neither @code{nil} nor @code{t}, then
705 @code{re-search-forward} moves point to @var{limit} (or the end of the
706 buffer) and returns @code{nil}.
707
708 If @var{count} is supplied (it must be a positive number), then the
709 search is repeated that many times (each time starting at the end of the
710 previous time's match).  If these successive searches succeed, the
711 function succeeds, moving point and returning its new value.  Otherwise
712 the search fails.
713
714 In the following example, point is initially before the @samp{T}.
715 Evaluating the search call moves point to the end of that line (between
716 the @samp{t} of @samp{hat} and the newline).
717
718 @example
719 @group
720 ---------- Buffer: foo ----------
721 I read "@point{}The cat in the hat
722 comes back" twice.
723 ---------- Buffer: foo ----------
724 @end group
725
726 @group
727 (re-search-forward "[a-z]+" nil t 5)
728      @result{} 27
729
730 ---------- Buffer: foo ----------
731 I read "The cat in the hat@point{}
732 comes back" twice.
733 ---------- Buffer: foo ----------
734 @end group
735 @end example
736 @end deffn
737
738 @deffn Command re-search-backward regexp &optional limit noerror count buffer
739 This function searches backward in the current buffer for a string of
740 text that is matched by the regular expression @var{regexp}, leaving
741 point at the beginning of the first text found.
742
743 This function is analogous to @code{re-search-forward}, but they are not
744 simple mirror images.  @code{re-search-forward} finds the match whose
745 beginning is as close as possible to the starting point.  If
746 @code{re-search-backward} were a perfect mirror image, it would find the
747 match whose end is as close as possible.  However, in fact it finds the
748 match whose beginning is as close as possible.  The reason is that
749 matching a regular expression at a given spot always works from
750 beginning to end, and starts at a specified beginning position.
751
752 A true mirror-image of @code{re-search-forward} would require a special
753 feature for matching regexps from end to beginning.  It's not worth the
754 trouble of implementing that.
755 @end deffn
756
757 @defun string-match regexp string &optional start buffer
758 This function returns the index of the start of the first match for
759 the regular expression @var{regexp} in @var{string}, or @code{nil} if
760 there is no match.  If @var{start} is non-@code{nil}, the search starts
761 at that index in @var{string}.
762
763
764 Optional arg @var{buffer} controls how case folding is done (according
765 to the value of @code{case-fold-search} in @var{buffer} and
766 @var{buffer}'s case tables) and defaults to the current buffer.
767
768 For example,
769
770 @example
771 @group
772 (string-match
773  "quick" "The quick brown fox jumped quickly.")
774      @result{} 4
775 @end group
776 @group
777 (string-match
778  "quick" "The quick brown fox jumped quickly." 8)
779      @result{} 27
780 @end group
781 @end example
782
783 @noindent
784 The index of the first character of the
785 string is 0, the index of the second character is 1, and so on.
786
787 After this function returns, the index of the first character beyond
788 the match is available as @code{(match-end 0)}.  @xref{Match Data}.
789
790 @example
791 @group
792 (string-match
793  "quick" "The quick brown fox jumped quickly." 8)
794      @result{} 27
795 @end group
796
797 @group
798 (match-end 0)
799      @result{} 32
800 @end group
801 @end example
802 @end defun
803
804 @defun split-string string &optional pattern
805 This function splits @var{string} to substrings delimited by
806 @var{pattern}, and returns a list of substrings.  If @var{pattern} is
807 omitted, it defaults to @samp{[ \f\t\n\r\v]+}, which means that it
808 splits @var{string} by white--space.
809
810 @example
811 @group
812 (split-string "foo bar")
813      @result{} ("foo" "bar")
814 @end group
815
816 @group
817 (split-string "something")
818      @result{} ("something")
819 @end group
820
821 @group
822 (split-string "a:b:c" ":")
823      @result{} ("a" "b" "c")
824 @end group
825
826 @group
827 (split-string ":a::b:c" ":")
828      @result{} ("" "a" "" "b" "c")
829 @end group
830 @end example
831 @end defun
832
833 @defun split-path path
834 This function splits a search path into a list of strings.  The path
835 components are separated with the characters specified with
836 @code{path-separator}.  Under Unix, @code{path-separator} will normally
837 be @samp{:}, while under Windows, it will be @samp{;}.
838 @end defun
839
840 @defun looking-at regexp &optional buffer
841 This function determines whether the text in the current buffer directly
842 following point matches the regular expression @var{regexp}.  ``Directly
843 following'' means precisely that: the search is ``anchored'' and it can
844 succeed only starting with the first character following point.  The
845 result is @code{t} if so, @code{nil} otherwise.
846
847 This function does not move point, but it updates the match data, which
848 you can access using @code{match-beginning} and @code{match-end}.
849 @xref{Match Data}.
850
851 In this example, point is located directly before the @samp{T}.  If it
852 were anywhere else, the result would be @code{nil}.
853
854 @example
855 @group
856 ---------- Buffer: foo ----------
857 I read "@point{}The cat in the hat
858 comes back" twice.
859 ---------- Buffer: foo ----------
860
861 (looking-at "The cat in the hat$")
862      @result{} t
863 @end group
864 @end example
865 @end defun
866
867
868 @node POSIX Regexps, Search and Replace, Regexp Search, Searching and Matching
869 @section POSIX Regular Expression Searching
870
871   The usual regular expression functions do backtracking when necessary
872 to handle the @samp{\|} and repetition constructs, but they continue
873 this only until they find @emph{some} match.  Then they succeed and
874 report the first match found.
875
876   This section describes alternative search functions which perform the
877 full backtracking specified by the POSIX standard for regular expression
878 matching.  They continue backtracking until they have tried all
879 possibilities and found all matches, so they can report the longest
880 match, as required by POSIX.  This is much slower, so use these
881 functions only when you really need the longest match.
882
883   In Emacs versions prior to 19.29, these functions did not exist, and
884 the functions described above implemented full POSIX backtracking.
885
886 @deffn Command posix-search-forward regexp &optional limit noerror count buffer
887 This is like @code{re-search-forward} except that it performs the full
888 backtracking specified by the POSIX standard for regular expression
889 matching.
890 @end deffn
891
892 @deffn Command posix-search-backward regexp &optional limit noerror count buffer
893 This is like @code{re-search-backward} except that it performs the full
894 backtracking specified by the POSIX standard for regular expression
895 matching.
896 @end deffn
897
898 @defun posix-looking-at regexp &optional buffer
899 This is like @code{looking-at} except that it performs the full
900 backtracking specified by the POSIX standard for regular expression
901 matching.
902 @end defun
903
904 @defun posix-string-match regexp string &optional start buffer
905 This is like @code{string-match} except that it performs the full
906 backtracking specified by the POSIX standard for regular expression
907 matching.
908
909 Optional arg @var{buffer} controls how case folding is done (according
910 to the value of @code{case-fold-search} in @var{buffer} and
911 @var{buffer}'s case tables) and defaults to the current buffer.
912 @end defun
913
914 @ignore
915 @deffn Command delete-matching-lines regexp
916 This function is identical to @code{delete-non-matching-lines}, save
917 that it deletes what @code{delete-non-matching-lines} keeps.
918
919 In the example below, point is located on the first line of text.
920
921 @example
922 @group
923 ---------- Buffer: foo ----------
924 We hold these truths
925 to be self-evident,
926 that all men are created
927 equal, and that they are
928 ---------- Buffer: foo ----------
929 @end group
930
931 @group
932 (delete-matching-lines "the")
933      @result{} nil
934
935 ---------- Buffer: foo ----------
936 to be self-evident,
937 that all men are created
938 ---------- Buffer: foo ----------
939 @end group
940 @end example
941 @end deffn
942
943 @deffn Command flush-lines regexp
944 This function is an alias of @code{delete-matching-lines}.
945 @end deffn
946
947 @deffn Command delete-non-matching-lines regexp
948 This function deletes all lines following point which don't
949 contain a match for the regular expression @var{regexp}.
950 @end deffn
951
952 @deffn Command keep-lines regexp
953 This function is the same as @code{delete-non-matching-lines}.
954 @end deffn
955
956 @deffn Command count-matches regexp
957 This function counts the number of matches for @var{regexp} there are in
958 the current buffer following point.  It prints this number in
959 the echo area, returning the string printed.
960 @end deffn
961
962 @deffn Command how-many regexp
963 This function is an alias of @code{count-matches}.
964 @end deffn
965
966 @deffn Command list-matching-lines regexp &optional nlines
967 This function is a synonym of @code{occur}.
968 Show all lines following point containing a match for @var{regexp}.
969 Display each line with @var{nlines} lines before and after,
970 or @code{-}@var{nlines} before if @var{nlines} is negative.
971 @var{nlines} defaults to @code{list-matching-lines-default-context-lines}.
972 Interactively it is the prefix arg.
973
974 The lines are shown in a buffer named @samp{*Occur*}.
975 It serves as a menu to find any of the occurrences in this buffer.
976 @kbd{C-h m} (@code{describe-mode} in that buffer gives help.
977 @end deffn
978
979 @defopt list-matching-lines-default-context-lines
980 Default value is 0.
981 Default number of context lines to include around a @code{list-matching-lines}
982 match.  A negative number means to include that many lines before the match.
983 A positive number means to include that many lines both before and after.
984 @end defopt
985 @end ignore
986
987
988 @node Search and Replace, Match Data, POSIX Regexps, Searching and Matching
989 @section Search and Replace
990 @cindex replacement
991
992 @defun perform-replace from-string replacements query-flag regexp-flag delimited-flag &optional repeat-count map
993 This function is the guts of @code{query-replace} and related commands.
994 It searches for occurrences of @var{from-string} and replaces some or
995 all of them.  If @var{query-flag} is @code{nil}, it replaces all
996 occurrences; otherwise, it asks the user what to do about each one.
997
998 If @var{regexp-flag} is non-@code{nil}, then @var{from-string} is
999 considered a regular expression; otherwise, it must match literally.  If
1000 @var{delimited-flag} is non-@code{nil}, then only replacements
1001 surrounded by word boundaries are considered.
1002
1003 The argument @var{replacements} specifies what to replace occurrences
1004 with.  If it is a string, that string is used.  It can also be a list of
1005 strings, to be used in cyclic order.
1006
1007 If @var{repeat-count} is non-@code{nil}, it should be an integer.  Then
1008 it specifies how many times to use each of the strings in the
1009 @var{replacements} list before advancing cyclicly to the next one.
1010
1011 Normally, the keymap @code{query-replace-map} defines the possible user
1012 responses for queries.  The argument @var{map}, if non-@code{nil}, is a
1013 keymap to use instead of @code{query-replace-map}.
1014 @end defun
1015
1016 @defvar query-replace-map
1017 This variable holds a special keymap that defines the valid user
1018 responses for @code{query-replace} and related functions, as well as
1019 @code{y-or-n-p} and @code{map-y-or-n-p}.  It is unusual in two ways:
1020
1021 @itemize @bullet
1022 @item
1023 The ``key bindings'' are not commands, just symbols that are meaningful
1024 to the functions that use this map.
1025
1026 @item
1027 Prefix keys are not supported; each key binding must be for a single event
1028 key sequence.  This is because the functions don't use read key sequence to
1029 get the input; instead, they read a single event and look it up ``by hand.''
1030 @end itemize
1031 @end defvar
1032
1033 Here are the meaningful ``bindings'' for @code{query-replace-map}.
1034 Several of them are meaningful only for @code{query-replace} and
1035 friends.
1036
1037 @table @code
1038 @item act
1039 Do take the action being considered---in other words, ``yes.''
1040
1041 @item skip
1042 Do not take action for this question---in other words, ``no.''
1043
1044 @item exit
1045 Answer this question ``no,'' and give up on the entire series of
1046 questions, assuming that the answers will be ``no.''
1047
1048 @item act-and-exit
1049 Answer this question ``yes,'' and give up on the entire series of
1050 questions, assuming that subsequent answers will be ``no.''
1051
1052 @item act-and-show
1053 Answer this question ``yes,'' but show the results---don't advance yet
1054 to the next question.
1055
1056 @item automatic
1057 Answer this question and all subsequent questions in the series with
1058 ``yes,'' without further user interaction.
1059
1060 @item backup
1061 Move back to the previous place that a question was asked about.
1062
1063 @item edit
1064 Enter a recursive edit to deal with this question---instead of any
1065 other action that would normally be taken.
1066
1067 @item delete-and-edit
1068 Delete the text being considered, then enter a recursive edit to replace
1069 it.
1070
1071 @item recenter
1072 Redisplay and center the window, then ask the same question again.
1073
1074 @item quit
1075 Perform a quit right away.  Only @code{y-or-n-p} and related functions
1076 use this answer.
1077
1078 @item help
1079 Display some help, then ask again.
1080 @end table
1081
1082
1083 @node Match Data, Searching and Case, Search and Replace, Searching and Matching
1084 @section The Match Data
1085 @cindex match data
1086
1087   SXEmacs keeps track of the positions of the start and end of segments of
1088 text found during a regular expression search.  This means, for example,
1089 that you can search for a complex pattern, such as a date in an Rmail
1090 message, and then extract parts of the match under control of the
1091 pattern.
1092
1093   Because the match data normally describe the most recent search only,
1094 you must be careful not to do another search inadvertently between the
1095 search you wish to refer back to and the use of the match data.  If you
1096 can't avoid another intervening search, you must save and restore the
1097 match data around it, to prevent it from being overwritten.
1098
1099 @menu
1100 * Simple Match Data::     Accessing single items of match data,
1101                             such as where a particular subexpression started.
1102 * Replacing Match::       Replacing a substring that was matched.
1103 * Entire Match Data::     Accessing the entire match data at once, as a list.
1104 * Saving Match Data::     Saving and restoring the match data.
1105 @end menu
1106
1107
1108 @node Simple Match Data, Replacing Match, Match Data, Match Data
1109 @subsection Simple Match Data Access
1110
1111   This section explains how to use the match data to find out what was
1112 matched by the last search or match operation.
1113
1114   You can ask about the entire matching text, or about a particular
1115 parenthetical subexpression of a regular expression.  The @var{count}
1116 argument in the functions below specifies which.  If @var{count} is
1117 zero, you are asking about the entire match.  If @var{count} is
1118 positive, it specifies which subexpression you want.
1119
1120   Recall that the subexpressions of a regular expression are those
1121 expressions grouped with escaped parentheses, @samp{\(@dots{}\)}.  The
1122 @var{count}th subexpression is found by counting occurrences of
1123 @samp{\(} from the beginning of the whole regular expression.  The first
1124 subexpression is numbered 1, the second 2, and so on.  Only regular
1125 expressions can have subexpressions---after a simple string search, the
1126 only information available is about the entire match.
1127
1128 @defun match-string count &optional in-string
1129 This function returns, as a string, the text matched in the last search
1130 or match operation.  It returns the entire text if @var{count} is zero,
1131 or just the portion corresponding to the @var{count}th parenthetical
1132 subexpression, if @var{count} is positive.  If @var{count} is out of
1133 range, or if that subexpression didn't match anything, the value is
1134 @code{nil}.
1135
1136 If the last such operation was done against a string with
1137 @code{string-match}, then you should pass the same string as the
1138 argument @var{in-string}.  Otherwise, after a buffer search or match,
1139 you should omit @var{in-string} or pass @code{nil} for it; but you
1140 should make sure that the current buffer when you call
1141 @code{match-string} is the one in which you did the searching or
1142 matching.
1143 @end defun
1144
1145 @defun match-beginning count
1146 This function returns the position of the start of text matched by the
1147 last regular expression searched for, or a subexpression of it.
1148
1149 If @var{count} is zero, then the value is the position of the start of
1150 the entire match.  Otherwise, @var{count} specifies a subexpression in
1151 the regular expression, and the value of the function is the starting
1152 position of the match for that subexpression.
1153
1154 The value is @code{nil} for a subexpression inside a @samp{\|}
1155 alternative that wasn't used in the match.
1156 @end defun
1157
1158 @defun match-end count
1159 This function is like @code{match-beginning} except that it returns the
1160 position of the end of the match, rather than the position of the
1161 beginning.
1162 @end defun
1163
1164   Here is an example of using the match data, with a comment showing the
1165 positions within the text:
1166
1167 @example
1168 @group
1169 (string-match "\\(qu\\)\\(ick\\)"
1170               "The quick fox jumped quickly.")
1171               ;0123456789
1172      @result{} 4
1173 @end group
1174
1175 @group
1176 (match-string 0 "The quick fox jumped quickly.")
1177      @result{} "quick"
1178 (match-string 1 "The quick fox jumped quickly.")
1179      @result{} "qu"
1180 (match-string 2 "The quick fox jumped quickly.")
1181      @result{} "ick"
1182 @end group
1183
1184 @group
1185 (match-beginning 1)       ; @r{The beginning of the match}
1186      @result{} 4                 ;   @r{with @samp{qu} is at index 4.}
1187 @end group
1188
1189 @group
1190 (match-beginning 2)       ; @r{The beginning of the match}
1191      @result{} 6                 ;   @r{with @samp{ick} is at index 6.}
1192 @end group
1193
1194 @group
1195 (match-end 1)             ; @r{The end of the match}
1196      @result{} 6                 ;   @r{with @samp{qu} is at index 6.}
1197
1198 (match-end 2)             ; @r{The end of the match}
1199      @result{} 9                 ;   @r{with @samp{ick} is at index 9.}
1200 @end group
1201 @end example
1202
1203   Here is another example.  Point is initially located at the beginning
1204 of the line.  Searching moves point to between the space and the word
1205 @samp{in}.  The beginning of the entire match is at the 9th character of
1206 the buffer (@samp{T}), and the beginning of the match for the first
1207 subexpression is at the 13th character (@samp{c}).
1208
1209 @example
1210 @group
1211 (list
1212   (re-search-forward "The \\(cat \\)")
1213   (match-beginning 0)
1214   (match-beginning 1))
1215     @result{} (9 9 13)
1216 @end group
1217
1218 @group
1219 ---------- Buffer: foo ----------
1220 I read "The cat @point{}in the hat comes back" twice.
1221         ^   ^
1222         9  13
1223 ---------- Buffer: foo ----------
1224 @end group
1225 @end example
1226
1227 @noindent
1228 (In this case, the index returned is a buffer position; the first
1229 character of the buffer counts as 1.)
1230
1231
1232 @node Replacing Match, Entire Match Data, Simple Match Data, Match Data
1233 @subsection Replacing the Text That Matched
1234
1235   This function replaces the text matched by the last search with
1236 @var{replacement}.
1237
1238 @cindex case in replacements
1239 @defun replace-match replacement &optional fixedcase literal string strbuffer
1240 This function replaces the text in the buffer (or in @var{string}) that
1241 was matched by the last search.  It replaces that text with
1242 @var{replacement}.
1243
1244 If you did the last search in a buffer, you should specify @code{nil}
1245 for @var{string}.  Then @code{replace-match} does the replacement by
1246 editing the buffer; it leaves point at the end of the replacement text,
1247 and returns @code{t}.
1248
1249 If you did the search in a string, pass the same string as @var{string}.
1250 Then @code{replace-match} does the replacement by constructing and
1251 returning a new string.
1252
1253 If the fourth argument @var{string} is a string, fifth argument
1254 @var{strbuffer} specifies the buffer to be used for syntax-table and
1255 case-table lookup and defaults to the current buffer.  When @var{string}
1256 is not a string, the buffer that the match occurred in has automatically
1257 been remembered and you do not need to specify it.
1258
1259 If @var{fixedcase} is non-@code{nil}, then the case of the replacement
1260 text is not changed; otherwise, the replacement text is converted to a
1261 different case depending upon the capitalization of the text to be
1262 replaced.  If the original text is all upper case, the replacement text
1263 is converted to upper case.  If the first word of the original text is
1264 capitalized, then the first word of the replacement text is capitalized.
1265 If the original text contains just one word, and that word is a capital
1266 letter, @code{replace-match} considers this a capitalized first word
1267 rather than all upper case.
1268
1269 If @code{case-replace} is @code{nil}, then case conversion is not done,
1270 regardless of the value of @var{fixedcase}.  @xref{Searching and Case}.
1271
1272 If @var{literal} is non-@code{nil}, then @var{replacement} is inserted
1273 exactly as it is, the only alterations being case changes as needed.
1274 If it is @code{nil} (the default), then the character @samp{\} is treated
1275 specially.  If a @samp{\} appears in @var{replacement}, then it must be
1276 part of one of the following sequences:
1277
1278 @table @asis
1279 @item @samp{\&}
1280 @cindex @samp{&} in replacement
1281 @samp{\&} stands for the entire text being replaced.
1282
1283 @item @samp{\@var{n}}
1284 @cindex @samp{\@var{n}} in replacement
1285 @samp{\@var{n}}, where @var{n} is a digit, stands for the text that
1286 matched the @var{n}th subexpression in the original regexp.
1287 Subexpressions are those expressions grouped inside @samp{\(@dots{}\)}.
1288
1289 @item @samp{\\}
1290 @cindex @samp{\} in replacement
1291 @samp{\\} stands for a single @samp{\} in the replacement text.
1292 @end table
1293 @end defun
1294
1295
1296 @node Entire Match Data, Saving Match Data, Replacing Match, Match Data
1297 @subsection Accessing the Entire Match Data
1298
1299   The functions @code{match-data} and @code{set-match-data} read or
1300 write the entire match data, all at once.
1301
1302 @defun match-data &optional integers reuse
1303 This function returns a newly constructed list containing all the
1304 information on what text the last search matched.  Element zero is the
1305 position of the beginning of the match for the whole expression; element
1306 one is the position of the end of the match for the expression.  The
1307 next two elements are the positions of the beginning and end of the
1308 match for the first subexpression, and so on.  In general, element
1309 @ifinfo
1310 number 2@var{n}
1311 @end ifinfo
1312 @tex
1313 number {\mathsurround=0pt $2n$}
1314 @end tex
1315 corresponds to @code{(match-beginning @var{n})}; and
1316 element
1317 @ifinfo
1318 number 2@var{n} + 1
1319 @end ifinfo
1320 @tex
1321 number {\mathsurround=0pt $2n+1$}
1322 @end tex
1323 corresponds to @code{(match-end @var{n})}.
1324
1325 All the elements are markers or @code{nil} if matching was done on a
1326 buffer, and all are integers or @code{nil} if matching was done on a
1327 string with @code{string-match}.  However, if the optional first
1328 argument @var{integers} is non-@code{nil}, always use integers (rather
1329 than markers) to represent buffer positions.
1330
1331 If the optional second argument @var{reuse} is a list, reuse it as part
1332 of the value.  If @var{reuse} is long enough to hold all the values, and if
1333 @var{integers} is non-@code{nil}, no new lisp objects are created.
1334
1335 As always, there must be no possibility of intervening searches between
1336 the call to a search function and the call to @code{match-data} that is
1337 intended to access the match data for that search.
1338
1339 @example
1340 @group
1341 (match-data)
1342      @result{}  (#<marker at 9 in foo>
1343           #<marker at 17 in foo>
1344           #<marker at 13 in foo>
1345           #<marker at 17 in foo>)
1346 @end group
1347 @end example
1348 @end defun
1349
1350 @defun set-match-data match-list
1351 This function sets the match data from the elements of @var{match-list},
1352 which should be a list that was the value of a previous call to
1353 @code{match-data}.
1354
1355 If @var{match-list} refers to a buffer that doesn't exist, you don't get
1356 an error; that sets the match data in a meaningless but harmless way.
1357
1358 @findex store-match-data
1359 @code{store-match-data} is an alias for @code{set-match-data}.
1360 @end defun
1361
1362
1363 @node Saving Match Data,  , Entire Match Data, Match Data
1364 @subsection Saving and Restoring the Match Data
1365
1366   When you call a function that may do a search, you may need to save
1367 and restore the match data around that call, if you want to preserve the
1368 match data from an earlier search for later use.  Here is an example
1369 that shows the problem that arises if you fail to save the match data:
1370
1371 @example
1372 @group
1373 (re-search-forward "The \\(cat \\)")
1374      @result{} 48
1375 (foo)                   ; @r{Perhaps @code{foo} does}
1376                         ;   @r{more searching.}
1377 (match-end 0)
1378      @result{} 61              ; @r{Unexpected result---not 48!}
1379 @end group
1380 @end example
1381
1382   You can save and restore the match data with @code{save-match-data}:
1383
1384 @defspec save-match-data body@dots{}
1385 This special form executes @var{body}, saving and restoring the match
1386 data around it.
1387 @end defspec
1388
1389   You can use @code{set-match-data} together with @code{match-data} to
1390 imitate the effect of the special form @code{save-match-data}.  This is
1391 useful for writing code that can run in Emacs 18.  Here is how:
1392
1393 @example
1394 @group
1395 (let ((data (match-data)))
1396   (unwind-protect
1397       @dots{}   ; @r{May change the original match data.}
1398     (set-match-data data)))
1399 @end group
1400 @end example
1401
1402   SXEmacs automatically saves and restores the match data when it runs
1403 process filter functions (@pxref{Filter Functions}) and process
1404 sentinels (@pxref{Sentinels}).
1405
1406 @ignore
1407   Here is a function which restores the match data provided the buffer
1408 associated with it still exists.
1409
1410 @smallexample
1411 @group
1412 (defun restore-match-data (data)
1413 @c It is incorrect to split the first line of a doc string.
1414 @c If there's a problem here, it should be solved in some other way.
1415   "Restore the match data DATA unless the buffer is missing."
1416   (catch 'foo
1417     (let ((d data))
1418 @end group
1419       (while d
1420         (and (car d)
1421              (null (marker-buffer (car d)))
1422 @group
1423              ;; @file{match-data} @r{buffer is deleted.}
1424              (throw 'foo nil))
1425         (setq d (cdr d)))
1426       (set-match-data data))))
1427 @end group
1428 @end smallexample
1429 @end ignore
1430
1431
1432 @node Searching and Case, Standard Regexps, Match Data, Searching and Matching
1433 @section Searching and Case
1434 @cindex searching and case
1435
1436   By default, searches in SXEmacs ignore the case of the text they are
1437 searching through; if you specify searching for @samp{FOO}, then
1438 @samp{Foo} or @samp{foo} is also considered a match.  Regexps, and in
1439 particular character sets, are included: thus, @samp{[aB]} would match
1440 @samp{a} or @samp{A} or @samp{b} or @samp{B}.
1441
1442   If you do not want this feature, set the variable
1443 @code{case-fold-search} to @code{nil}.  Then all letters must match
1444 exactly, including case.  This is a buffer-local variable; altering the
1445 variable affects only the current buffer.  (@xref{Intro to
1446 Buffer-Local}.)  Alternatively, you may change the value of
1447 @code{default-case-fold-search}, which is the default value of
1448 @code{case-fold-search} for buffers that do not override it.
1449
1450   Note that the user-level incremental search feature handles case
1451 distinctions differently.  When given a lower case letter, it looks for
1452 a match of either case, but when given an upper case letter, it looks
1453 for an upper case letter only.  But this has nothing to do with the
1454 searching functions Lisp functions use.
1455
1456 @defopt case-replace
1457 This variable determines whether the replacement functions should
1458 preserve case.  If the variable is @code{nil}, that means to use the
1459 replacement text verbatim.  A non-@code{nil} value means to convert the
1460 case of the replacement text according to the text being replaced.
1461
1462 The function @code{replace-match} is where this variable actually has
1463 its effect.  @xref{Replacing Match}.
1464 @end defopt
1465
1466 @defopt case-fold-search
1467 This buffer-local variable determines whether searches should ignore
1468 case.  If the variable is @code{nil} they do not ignore case; otherwise
1469 they do ignore case.
1470 @end defopt
1471
1472 @defvar default-case-fold-search
1473 The value of this variable is the default value for
1474 @code{case-fold-search} in buffers that do not override it.  This is the
1475 same as @code{(default-value 'case-fold-search)}.
1476 @end defvar
1477
1478
1479 @node Standard Regexps,  , Searching and Case, Searching and Matching
1480 @section Standard Regular Expressions Used in Editing
1481 @cindex regexps used standardly in editing
1482 @cindex standard regexps used in editing
1483
1484   This section describes some variables that hold regular expressions
1485 used for certain purposes in editing:
1486
1487 @defvar page-delimiter
1488 This is the regexp describing line-beginnings that separate pages.  The
1489 default value is @code{"^\014"} (i.e., @code{"^^L"} or @code{"^\C-l"});
1490 this matches a line that starts with a formfeed character.
1491 @end defvar
1492
1493   The following two regular expressions should @emph{not} assume the
1494 match always starts at the beginning of a line; they should not use
1495 @samp{^} to anchor the match.  Most often, the paragraph commands do
1496 check for a match only at the beginning of a line, which means that
1497 @samp{^} would be superfluous.  When there is a nonzero left margin,
1498 they accept matches that start after the left margin.  In that case, a
1499 @samp{^} would be incorrect.  However, a @samp{^} is harmless in modes
1500 where a left margin is never used.
1501
1502 @defvar paragraph-separate
1503 This is the regular expression for recognizing the beginning of a line
1504 that separates paragraphs.  (If you change this, you may have to
1505 change @code{paragraph-start} also.)  The default value is
1506 @w{@code{"[@ \t\f]*$"}}, which matches a line that consists entirely of
1507 spaces, tabs, and form feeds (after its left margin).
1508 @end defvar
1509
1510 @defvar paragraph-start
1511 This is the regular expression for recognizing the beginning of a line
1512 that starts @emph{or} separates paragraphs.  The default value is
1513 @w{@code{"[@ \t\n\f]"}}, which matches a line starting with a space, tab,
1514 newline, or form feed (after its left margin).
1515 @end defvar
1516
1517 @defvar sentence-end
1518 This is the regular expression describing the end of a sentence.  (All
1519 paragraph boundaries also end sentences, regardless.)  The default value
1520 is:
1521
1522 @example
1523 "[.?!][]\"')@}]*\\($\\| $\\|\t\\| \\)[ \t\n]*"
1524 @end example
1525
1526 This means a period, question mark or exclamation mark, followed
1527 optionally by a closing parenthetical character, followed by tabs,
1528 spaces or new lines.
1529
1530 For a detailed explanation of this regular expression, see @ref{Regexp
1531 Example}.
1532 @end defvar