searching.texi 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935
  1. @c -*-texinfo-*-
  2. @c This is part of the GNU Emacs Lisp Reference Manual.
  3. @c Copyright (C) 1990-1995, 1998-1999, 2001-2016 Free Software
  4. @c Foundation, Inc.
  5. @c See the file elisp.texi for copying conditions.
  6. @node Searching and Matching
  7. @chapter Searching and Matching
  8. @cindex searching
  9. GNU Emacs provides two ways to search through a buffer for specified
  10. text: exact string searches and regular expression searches. After a
  11. regular expression search, you can examine the @dfn{match data} to
  12. determine which text matched the whole regular expression or various
  13. portions of it.
  14. @menu
  15. * String Search:: Search for an exact match.
  16. * Searching and Case:: Case-independent or case-significant searching.
  17. * Regular Expressions:: Describing classes of strings.
  18. * Regexp Search:: Searching for a match for a regexp.
  19. * POSIX Regexps:: Searching POSIX-style for the longest match.
  20. * Match Data:: Finding out which part of the text matched,
  21. after a string or regexp search.
  22. * Search and Replace:: Commands that loop, searching and replacing.
  23. * Standard Regexps:: Useful regexps for finding sentences, pages,...
  24. @end menu
  25. The @samp{skip-chars@dots{}} functions also perform a kind of searching.
  26. @xref{Skipping Characters}. To search for changes in character
  27. properties, see @ref{Property Search}.
  28. @node String Search
  29. @section Searching for Strings
  30. @cindex string search
  31. These are the primitive functions for searching through the text in a
  32. buffer. They are meant for use in programs, but you may call them
  33. interactively. If you do so, they prompt for the search string; the
  34. arguments @var{limit} and @var{noerror} are @code{nil}, and @var{repeat}
  35. is 1. For more details on interactive searching, @pxref{Search,,
  36. Searching and Replacement, emacs, The GNU Emacs Manual}.
  37. These search functions convert the search string to multibyte if the
  38. buffer is multibyte; they convert the search string to unibyte if the
  39. buffer is unibyte. @xref{Text Representations}.
  40. @deffn Command search-forward string &optional limit noerror repeat
  41. This function searches forward from point for an exact match for
  42. @var{string}. If successful, it sets point to the end of the occurrence
  43. found, and returns the new value of point. If no match is found, the
  44. value and side effects depend on @var{noerror} (see below).
  45. In the following example, point is initially at the beginning of the
  46. line. Then @code{(search-forward "fox")} moves point after the last
  47. letter of @samp{fox}:
  48. @example
  49. @group
  50. ---------- Buffer: foo ----------
  51. @point{}The quick brown fox jumped over the lazy dog.
  52. ---------- Buffer: foo ----------
  53. @end group
  54. @group
  55. (search-forward "fox")
  56. @result{} 20
  57. ---------- Buffer: foo ----------
  58. The quick brown fox@point{} jumped over the lazy dog.
  59. ---------- Buffer: foo ----------
  60. @end group
  61. @end example
  62. The argument @var{limit} specifies the bound to the search, and should
  63. be a position in the current buffer. No match extending after
  64. that position is accepted. If @var{limit} is omitted or @code{nil}, it
  65. defaults to the end of the accessible portion of the buffer.
  66. @kindex search-failed
  67. What happens when the search fails depends on the value of
  68. @var{noerror}. If @var{noerror} is @code{nil}, a @code{search-failed}
  69. error is signaled. If @var{noerror} is @code{t}, @code{search-forward}
  70. returns @code{nil} and does nothing. If @var{noerror} is neither
  71. @code{nil} nor @code{t}, then @code{search-forward} moves point to the
  72. upper bound and returns @code{nil}.
  73. @c I see no prospect of this ever changing, and frankly the current
  74. @c behavior seems better, so there seems no need to mention this.
  75. @ignore
  76. (It would be more consistent now to return the new position of point
  77. in that case, but some existing programs may depend on a value of
  78. @code{nil}.)
  79. @end ignore
  80. The argument @var{noerror} only affects valid searches which fail to
  81. find a match. Invalid arguments cause errors regardless of
  82. @var{noerror}.
  83. If @var{repeat} is a positive number @var{n}, it serves as a repeat
  84. count: the search is repeated @var{n} times, each time starting at the
  85. end of the previous time's match. If these successive searches
  86. succeed, the function succeeds, moving point and returning its new
  87. value. Otherwise the search fails, with results depending on the
  88. value of @var{noerror}, as described above. If @var{repeat} is a
  89. negative number -@var{n}, it serves as a repeat count of @var{n} for a
  90. search in the opposite (backward) direction.
  91. @end deffn
  92. @deffn Command search-backward string &optional limit noerror repeat
  93. This function searches backward from point for @var{string}. It is
  94. like @code{search-forward}, except that it searches backwards rather
  95. than forwards. Backward searches leave point at the beginning of the
  96. match.
  97. @end deffn
  98. @deffn Command word-search-forward string &optional limit noerror repeat
  99. This function searches forward from point for a word match for
  100. @var{string}. If it finds a match, it sets point to the end of the
  101. match found, and returns the new value of point.
  102. Word matching regards @var{string} as a sequence of words, disregarding
  103. punctuation that separates them. It searches the buffer for the same
  104. sequence of words. Each word must be distinct in the buffer (searching
  105. for the word @samp{ball} does not match the word @samp{balls}), but the
  106. details of punctuation and spacing are ignored (searching for @samp{ball
  107. boy} does match @samp{ball. Boy!}).
  108. In this example, point is initially at the beginning of the buffer; the
  109. search leaves it between the @samp{y} and the @samp{!}.
  110. @example
  111. @group
  112. ---------- Buffer: foo ----------
  113. @point{}He said "Please! Find
  114. the ball boy!"
  115. ---------- Buffer: foo ----------
  116. @end group
  117. @group
  118. (word-search-forward "Please find the ball, boy.")
  119. @result{} 39
  120. ---------- Buffer: foo ----------
  121. He said "Please! Find
  122. the ball boy@point{}!"
  123. ---------- Buffer: foo ----------
  124. @end group
  125. @end example
  126. If @var{limit} is non-@code{nil}, it must be a position in the current
  127. buffer; it specifies the upper bound to the search. The match found
  128. must not extend after that position.
  129. If @var{noerror} is @code{nil}, then @code{word-search-forward} signals
  130. an error if the search fails. If @var{noerror} is @code{t}, then it
  131. returns @code{nil} instead of signaling an error. If @var{noerror} is
  132. neither @code{nil} nor @code{t}, it moves point to @var{limit} (or the
  133. end of the accessible portion of the buffer) and returns @code{nil}.
  134. If @var{repeat} is non-@code{nil}, then the search is repeated that many
  135. times. Point is positioned at the end of the last match.
  136. @findex word-search-regexp
  137. Internally, @code{word-search-forward} and related functions use the
  138. function @code{word-search-regexp} to convert @var{string} to a
  139. regular expression that ignores punctuation.
  140. @end deffn
  141. @deffn Command word-search-forward-lax string &optional limit noerror repeat
  142. This command is identical to @code{word-search-forward}, except that
  143. the beginning or the end of @var{string} need not match a word
  144. boundary, unless @var{string} begins or ends in whitespace.
  145. For instance, searching for @samp{ball boy} matches @samp{ball boyee},
  146. but does not match @samp{balls boy}.
  147. @end deffn
  148. @deffn Command word-search-backward string &optional limit noerror repeat
  149. This function searches backward from point for a word match to
  150. @var{string}. This function is just like @code{word-search-forward}
  151. except that it searches backward and normally leaves point at the
  152. beginning of the match.
  153. @end deffn
  154. @deffn Command word-search-backward-lax string &optional limit noerror repeat
  155. This command is identical to @code{word-search-backward}, except that
  156. the beginning or the end of @var{string} need not match a word
  157. boundary, unless @var{string} begins or ends in whitespace.
  158. @end deffn
  159. @node Searching and Case
  160. @section Searching and Case
  161. @cindex searching and case
  162. By default, searches in Emacs ignore the case of the text they are
  163. searching through; if you specify searching for @samp{FOO}, then
  164. @samp{Foo} or @samp{foo} is also considered a match. This applies to
  165. regular expressions, too; thus, @samp{[aB]} would match @samp{a} or
  166. @samp{A} or @samp{b} or @samp{B}.
  167. If you do not want this feature, set the variable
  168. @code{case-fold-search} to @code{nil}. Then all letters must match
  169. exactly, including case. This is a buffer-local variable; altering the
  170. variable affects only the current buffer. (@xref{Intro to
  171. Buffer-Local}.) Alternatively, you may change the default value.
  172. In Lisp code, you will more typically use @code{let} to bind
  173. @code{case-fold-search} to the desired value.
  174. Note that the user-level incremental search feature handles case
  175. distinctions differently. When the search string contains only lower
  176. case letters, the search ignores case, but when the search string
  177. contains one or more upper case letters, the search becomes
  178. case-sensitive. But this has nothing to do with the searching
  179. functions used in Lisp code. @xref{Incremental Search,,, emacs,
  180. The GNU Emacs Manual}.
  181. @defopt case-fold-search
  182. This buffer-local variable determines whether searches should ignore
  183. case. If the variable is @code{nil} they do not ignore case; otherwise
  184. (and by default) they do ignore case.
  185. @end defopt
  186. @defopt case-replace
  187. This variable determines whether the higher-level replacement
  188. functions should preserve case. If the variable is @code{nil}, that
  189. means to use the replacement text verbatim. A non-@code{nil} value
  190. means to convert the case of the replacement text according to the
  191. text being replaced.
  192. This variable is used by passing it as an argument to the function
  193. @code{replace-match}. @xref{Replacing Match}.
  194. @end defopt
  195. @node Regular Expressions
  196. @section Regular Expressions
  197. @cindex regular expression
  198. @cindex regexp
  199. A @dfn{regular expression}, or @dfn{regexp} for short, is a pattern that
  200. denotes a (possibly infinite) set of strings. Searching for matches for
  201. a regexp is a very powerful operation. This section explains how to write
  202. regexps; the following section says how to search for them.
  203. @findex re-builder
  204. @cindex regular expressions, developing
  205. For interactive development of regular expressions, you
  206. can use the @kbd{M-x re-builder} command. It provides a convenient
  207. interface for creating regular expressions, by giving immediate visual
  208. feedback in a separate buffer. As you edit the regexp, all its
  209. matches in the target buffer are highlighted. Each parenthesized
  210. sub-expression of the regexp is shown in a distinct face, which makes
  211. it easier to verify even very complex regexps.
  212. @menu
  213. * Syntax of Regexps:: Rules for writing regular expressions.
  214. * Regexp Example:: Illustrates regular expression syntax.
  215. * Regexp Functions:: Functions for operating on regular expressions.
  216. @end menu
  217. @node Syntax of Regexps
  218. @subsection Syntax of Regular Expressions
  219. @cindex regexp syntax
  220. @cindex syntax of regular expressions
  221. Regular expressions have a syntax in which a few characters are
  222. special constructs and the rest are @dfn{ordinary}. An ordinary
  223. character is a simple regular expression that matches that character
  224. and nothing else. The special characters are @samp{.}, @samp{*},
  225. @samp{+}, @samp{?}, @samp{[}, @samp{^}, @samp{$}, and @samp{\}; no new
  226. special characters will be defined in the future. The character
  227. @samp{]} is special if it ends a character alternative (see later).
  228. The character @samp{-} is special inside a character alternative. A
  229. @samp{[:} and balancing @samp{:]} enclose a character class inside a
  230. character alternative. Any other character appearing in a regular
  231. expression is ordinary, unless a @samp{\} precedes it.
  232. For example, @samp{f} is not a special character, so it is ordinary, and
  233. therefore @samp{f} is a regular expression that matches the string
  234. @samp{f} and no other string. (It does @emph{not} match the string
  235. @samp{fg}, but it does match a @emph{part} of that string.) Likewise,
  236. @samp{o} is a regular expression that matches only @samp{o}.
  237. Any two regular expressions @var{a} and @var{b} can be concatenated. The
  238. result is a regular expression that matches a string if @var{a} matches
  239. some amount of the beginning of that string and @var{b} matches the rest of
  240. the string.
  241. As a simple example, we can concatenate the regular expressions @samp{f}
  242. and @samp{o} to get the regular expression @samp{fo}, which matches only
  243. the string @samp{fo}. Still trivial. To do something more powerful, you
  244. need to use one of the special regular expression constructs.
  245. @menu
  246. * Regexp Special:: Special characters in regular expressions.
  247. * Char Classes:: Character classes used in regular expressions.
  248. * Regexp Backslash:: Backslash-sequences in regular expressions.
  249. @end menu
  250. @node Regexp Special
  251. @subsubsection Special Characters in Regular Expressions
  252. @cindex regexp, special characters in
  253. Here is a list of the characters that are special in a regular
  254. expression.
  255. @need 800
  256. @table @asis
  257. @item @samp{.}@: @r{(Period)}
  258. @cindex @samp{.} in regexp
  259. is a special character that matches any single character except a newline.
  260. Using concatenation, we can make regular expressions like @samp{a.b}, which
  261. matches any three-character string that begins with @samp{a} and ends with
  262. @samp{b}.
  263. @item @samp{*}
  264. @cindex @samp{*} in regexp
  265. is not a construct by itself; it is a postfix operator that means to
  266. match the preceding regular expression repetitively as many times as
  267. possible. Thus, @samp{o*} matches any number of @samp{o}s (including no
  268. @samp{o}s).
  269. @samp{*} always applies to the @emph{smallest} possible preceding
  270. expression. Thus, @samp{fo*} has a repeating @samp{o}, not a repeating
  271. @samp{fo}. It matches @samp{f}, @samp{fo}, @samp{foo}, and so on.
  272. @cindex backtracking and regular expressions
  273. The matcher processes a @samp{*} construct by matching, immediately, as
  274. many repetitions as can be found. Then it continues with the rest of
  275. the pattern. If that fails, backtracking occurs, discarding some of the
  276. matches of the @samp{*}-modified construct in the hope that that will
  277. make it possible to match the rest of the pattern. For example, in
  278. matching @samp{ca*ar} against the string @samp{caaar}, the @samp{a*}
  279. first tries to match all three @samp{a}s; but the rest of the pattern is
  280. @samp{ar} and there is only @samp{r} left to match, so this try fails.
  281. The next alternative is for @samp{a*} to match only two @samp{a}s. With
  282. this choice, the rest of the regexp matches successfully.
  283. @strong{Warning:} Nested repetition operators can run for an
  284. indefinitely long time, if they lead to ambiguous matching. For
  285. example, trying to match the regular expression @samp{\(x+y*\)*a}
  286. against the string @samp{xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxz} could
  287. take hours before it ultimately fails. Emacs must try each way of
  288. grouping the @samp{x}s before concluding that none of them can work.
  289. Even worse, @samp{\(x*\)*} can match the null string in infinitely
  290. many ways, so it causes an infinite loop. To avoid these problems,
  291. check nested repetitions carefully, to make sure that they do not
  292. cause combinatorial explosions in backtracking.
  293. @item @samp{+}
  294. @cindex @samp{+} in regexp
  295. is a postfix operator, similar to @samp{*} except that it must match
  296. the preceding expression at least once. So, for example, @samp{ca+r}
  297. matches the strings @samp{car} and @samp{caaaar} but not the string
  298. @samp{cr}, whereas @samp{ca*r} matches all three strings.
  299. @item @samp{?}
  300. @cindex @samp{?} in regexp
  301. is a postfix operator, similar to @samp{*} except that it must match the
  302. preceding expression either once or not at all. For example,
  303. @samp{ca?r} matches @samp{car} or @samp{cr}; nothing else.
  304. @item @samp{*?}, @samp{+?}, @samp{??}
  305. @cindex non-greedy repetition characters in regexp
  306. These are @dfn{non-greedy} variants of the operators @samp{*}, @samp{+}
  307. and @samp{?}. Where those operators match the largest possible
  308. substring (consistent with matching the entire containing expression),
  309. the non-greedy variants match the smallest possible substring
  310. (consistent with matching the entire containing expression).
  311. For example, the regular expression @samp{c[ad]*a} when applied to the
  312. string @samp{cdaaada} matches the whole string; but the regular
  313. expression @samp{c[ad]*?a}, applied to that same string, matches just
  314. @samp{cda}. (The smallest possible match here for @samp{[ad]*?} that
  315. permits the whole expression to match is @samp{d}.)
  316. @item @samp{[ @dots{} ]}
  317. @cindex character alternative (in regexp)
  318. @cindex @samp{[} in regexp
  319. @cindex @samp{]} in regexp
  320. is a @dfn{character alternative}, which begins with @samp{[} and is
  321. terminated by @samp{]}. In the simplest case, the characters between
  322. the two brackets are what this character alternative can match.
  323. Thus, @samp{[ad]} matches either one @samp{a} or one @samp{d}, and
  324. @samp{[ad]*} matches any string composed of just @samp{a}s and @samp{d}s
  325. (including the empty string). It follows that @samp{c[ad]*r}
  326. matches @samp{cr}, @samp{car}, @samp{cdr}, @samp{caddaar}, etc.
  327. You can also include character ranges in a character alternative, by
  328. writing the starting and ending characters with a @samp{-} between them.
  329. Thus, @samp{[a-z]} matches any lower-case @acronym{ASCII} letter.
  330. Ranges may be intermixed freely with individual characters, as in
  331. @samp{[a-z$%.]}, which matches any lower case @acronym{ASCII} letter
  332. or @samp{$}, @samp{%} or period.
  333. If @code{case-fold-search} is non-@code{nil}, @samp{[a-z]} also
  334. matches upper-case letters. Note that a range like @samp{[a-z]} is
  335. not affected by the locale's collation sequence, it always represents
  336. a sequence in @acronym{ASCII} order.
  337. @c This wasn't obvious to me, since, e.g., the grep manual "Character
  338. @c Classes and Bracket Expressions" specifically notes the opposite
  339. @c behavior. But by experiment Emacs seems unaffected by LC_COLLATE
  340. @c in this regard.
  341. Note also that the usual regexp special characters are not special inside a
  342. character alternative. A completely different set of characters is
  343. special inside character alternatives: @samp{]}, @samp{-} and @samp{^}.
  344. To include a @samp{]} in a character alternative, you must make it the
  345. first character. For example, @samp{[]a]} matches @samp{]} or @samp{a}.
  346. To include a @samp{-}, write @samp{-} as the first or last character of
  347. the character alternative, or put it after a range. Thus, @samp{[]-]}
  348. matches both @samp{]} and @samp{-}. (As explained below, you cannot
  349. use @samp{\]} to include a @samp{]} inside a character alternative,
  350. since @samp{\} is not special there.)
  351. To include @samp{^} in a character alternative, put it anywhere but at
  352. the beginning.
  353. @c What if it starts with a multibyte and ends with a unibyte?
  354. @c That doesn't seem to match anything...?
  355. If a range starts with a unibyte character @var{c} and ends with a
  356. multibyte character @var{c2}, the range is divided into two parts: one
  357. spans the unibyte characters @samp{@var{c}..?\377}, the other the
  358. multibyte characters @samp{@var{c1}..@var{c2}}, where @var{c1} is the
  359. first character of the charset to which @var{c2} belongs.
  360. A character alternative can also specify named character classes
  361. (@pxref{Char Classes}). This is a POSIX feature. For example,
  362. @samp{[[:ascii:]]} matches any @acronym{ASCII} character.
  363. Using a character class is equivalent to mentioning each of the
  364. characters in that class; but the latter is not feasible in practice,
  365. since some classes include thousands of different characters.
  366. @item @samp{[^ @dots{} ]}
  367. @cindex @samp{^} in regexp
  368. @samp{[^} begins a @dfn{complemented character alternative}. This
  369. matches any character except the ones specified. Thus,
  370. @samp{[^a-z0-9A-Z]} matches all characters @emph{except} letters and
  371. digits.
  372. @samp{^} is not special in a character alternative unless it is the first
  373. character. The character following the @samp{^} is treated as if it
  374. were first (in other words, @samp{-} and @samp{]} are not special there).
  375. A complemented character alternative can match a newline, unless newline is
  376. mentioned as one of the characters not to match. This is in contrast to
  377. the handling of regexps in programs such as @code{grep}.
  378. You can specify named character classes, just like in character
  379. alternatives. For instance, @samp{[^[:ascii:]]} matches any
  380. non-@acronym{ASCII} character. @xref{Char Classes}.
  381. @item @samp{^}
  382. @cindex beginning of line in regexp
  383. When matching a buffer, @samp{^} matches the empty string, but only at the
  384. beginning of a line in the text being matched (or the beginning of the
  385. accessible portion of the buffer). Otherwise it fails to match
  386. anything. Thus, @samp{^foo} matches a @samp{foo} that occurs at the
  387. beginning of a line.
  388. When matching a string instead of a buffer, @samp{^} matches at the
  389. beginning of the string or after a newline character.
  390. For historical compatibility reasons, @samp{^} can be used only at the
  391. beginning of the regular expression, or after @samp{\(}, @samp{\(?:}
  392. or @samp{\|}.
  393. @item @samp{$}
  394. @cindex @samp{$} in regexp
  395. @cindex end of line in regexp
  396. is similar to @samp{^} but matches only at the end of a line (or the
  397. end of the accessible portion of the buffer). Thus, @samp{x+$}
  398. matches a string of one @samp{x} or more at the end of a line.
  399. When matching a string instead of a buffer, @samp{$} matches at the end
  400. of the string or before a newline character.
  401. For historical compatibility reasons, @samp{$} can be used only at the
  402. end of the regular expression, or before @samp{\)} or @samp{\|}.
  403. @item @samp{\}
  404. @cindex @samp{\} in regexp
  405. has two functions: it quotes the special characters (including
  406. @samp{\}), and it introduces additional special constructs.
  407. Because @samp{\} quotes special characters, @samp{\$} is a regular
  408. expression that matches only @samp{$}, and @samp{\[} is a regular
  409. expression that matches only @samp{[}, and so on.
  410. Note that @samp{\} also has special meaning in the read syntax of Lisp
  411. strings (@pxref{String Type}), and must be quoted with @samp{\}. For
  412. example, the regular expression that matches the @samp{\} character is
  413. @samp{\\}. To write a Lisp string that contains the characters
  414. @samp{\\}, Lisp syntax requires you to quote each @samp{\} with another
  415. @samp{\}. Therefore, the read syntax for a regular expression matching
  416. @samp{\} is @code{"\\\\"}.
  417. @end table
  418. @strong{Please note:} For historical compatibility, special characters
  419. are treated as ordinary ones if they are in contexts where their special
  420. meanings make no sense. For example, @samp{*foo} treats @samp{*} as
  421. ordinary since there is no preceding expression on which the @samp{*}
  422. can act. It is poor practice to depend on this behavior; quote the
  423. special character anyway, regardless of where it appears.
  424. As a @samp{\} is not special inside a character alternative, it can
  425. never remove the special meaning of @samp{-} or @samp{]}. So you
  426. should not quote these characters when they have no special meaning
  427. either. This would not clarify anything, since backslashes can
  428. legitimately precede these characters where they @emph{have} special
  429. meaning, as in @samp{[^\]} (@code{"[^\\]"} for Lisp string syntax),
  430. which matches any single character except a backslash.
  431. In practice, most @samp{]} that occur in regular expressions close a
  432. character alternative and hence are special. However, occasionally a
  433. regular expression may try to match a complex pattern of literal
  434. @samp{[} and @samp{]}. In such situations, it sometimes may be
  435. necessary to carefully parse the regexp from the start to determine
  436. which square brackets enclose a character alternative. For example,
  437. @samp{[^][]]} consists of the complemented character alternative
  438. @samp{[^][]} (which matches any single character that is not a square
  439. bracket), followed by a literal @samp{]}.
  440. The exact rules are that at the beginning of a regexp, @samp{[} is
  441. special and @samp{]} not. This lasts until the first unquoted
  442. @samp{[}, after which we are in a character alternative; @samp{[} is
  443. no longer special (except when it starts a character class) but @samp{]}
  444. is special, unless it immediately follows the special @samp{[} or that
  445. @samp{[} followed by a @samp{^}. This lasts until the next special
  446. @samp{]} that does not end a character class. This ends the character
  447. alternative and restores the ordinary syntax of regular expressions;
  448. an unquoted @samp{[} is special again and a @samp{]} not.
  449. @node Char Classes
  450. @subsubsection Character Classes
  451. @cindex character classes in regexp
  452. Here is a table of the classes you can use in a character alternative,
  453. and what they mean:
  454. @table @samp
  455. @item [:ascii:]
  456. This matches any @acronym{ASCII} character (codes 0--127).
  457. @item [:alnum:]
  458. This matches any letter or digit. For multibyte characters, it
  459. matches characters whose Unicode @samp{general-category} property
  460. (@pxref{Character Properties}) indicates they are alphabetic or
  461. decimal number characters.
  462. @item [:alpha:]
  463. This matches any letter. For multibyte characters, it matches
  464. characters whose Unicode @samp{general-category} property
  465. (@pxref{Character Properties}) indicates they are alphabetic
  466. characters.
  467. @item [:blank:]
  468. This matches space and tab only.
  469. @item [:cntrl:]
  470. This matches any @acronym{ASCII} control character.
  471. @item [:digit:]
  472. This matches @samp{0} through @samp{9}. Thus, @samp{[-+[:digit:]]}
  473. matches any digit, as well as @samp{+} and @samp{-}.
  474. @item [:graph:]
  475. This matches graphic characters---everything except whitespace,
  476. @acronym{ASCII} and non-@acronym{ASCII} control characters,
  477. surrogates, and codepoints unassigned by Unicode, as indicated by the
  478. Unicode @samp{general-category} property (@pxref{Character
  479. Properties}).
  480. @item [:lower:]
  481. This matches any lower-case letter, as determined by the current case
  482. table (@pxref{Case Tables}). If @code{case-fold-search} is
  483. non-@code{nil}, this also matches any upper-case letter.
  484. @item [:multibyte:]
  485. This matches any multibyte character (@pxref{Text Representations}).
  486. @item [:nonascii:]
  487. This matches any non-@acronym{ASCII} character.
  488. @item [:print:]
  489. This matches any printing character---either whitespace, or a graphic
  490. character matched by @samp{[:graph:]}.
  491. @item [:punct:]
  492. This matches any punctuation character. (At present, for multibyte
  493. characters, it matches anything that has non-word syntax.)
  494. @item [:space:]
  495. This matches any character that has whitespace syntax
  496. (@pxref{Syntax Class Table}).
  497. @item [:unibyte:]
  498. This matches any unibyte character (@pxref{Text Representations}).
  499. @item [:upper:]
  500. This matches any upper-case letter, as determined by the current case
  501. table (@pxref{Case Tables}). If @code{case-fold-search} is
  502. non-@code{nil}, this also matches any lower-case letter.
  503. @item [:word:]
  504. This matches any character that has word syntax (@pxref{Syntax Class
  505. Table}).
  506. @item [:xdigit:]
  507. This matches the hexadecimal digits: @samp{0} through @samp{9}, @samp{a}
  508. through @samp{f} and @samp{A} through @samp{F}.
  509. @end table
  510. @node Regexp Backslash
  511. @subsubsection Backslash Constructs in Regular Expressions
  512. @cindex backslash in regular expressions
  513. For the most part, @samp{\} followed by any character matches only
  514. that character. However, there are several exceptions: certain
  515. sequences starting with @samp{\} that have special meanings. Here is
  516. a table of the special @samp{\} constructs.
  517. @table @samp
  518. @item \|
  519. @cindex @samp{|} in regexp
  520. @cindex regexp alternative
  521. specifies an alternative.
  522. Two regular expressions @var{a} and @var{b} with @samp{\|} in
  523. between form an expression that matches anything that either @var{a} or
  524. @var{b} matches.
  525. Thus, @samp{foo\|bar} matches either @samp{foo} or @samp{bar}
  526. but no other string.
  527. @samp{\|} applies to the largest possible surrounding expressions. Only a
  528. surrounding @samp{\( @dots{} \)} grouping can limit the grouping power of
  529. @samp{\|}.
  530. If you need full backtracking capability to handle multiple uses of
  531. @samp{\|}, use the POSIX regular expression functions (@pxref{POSIX
  532. Regexps}).
  533. @item \@{@var{m}\@}
  534. is a postfix operator that repeats the previous pattern exactly @var{m}
  535. times. Thus, @samp{x\@{5\@}} matches the string @samp{xxxxx}
  536. and nothing else. @samp{c[ad]\@{3\@}r} matches string such as
  537. @samp{caaar}, @samp{cdddr}, @samp{cadar}, and so on.
  538. @item \@{@var{m},@var{n}\@}
  539. is a more general postfix operator that specifies repetition with a
  540. minimum of @var{m} repeats and a maximum of @var{n} repeats. If @var{m}
  541. is omitted, the minimum is 0; if @var{n} is omitted, there is no
  542. maximum.
  543. For example, @samp{c[ad]\@{1,2\@}r} matches the strings @samp{car},
  544. @samp{cdr}, @samp{caar}, @samp{cadr}, @samp{cdar}, and @samp{cddr}, and
  545. nothing else.@*
  546. @samp{\@{0,1\@}} or @samp{\@{,1\@}} is equivalent to @samp{?}.@*
  547. @samp{\@{0,\@}} or @samp{\@{,\@}} is equivalent to @samp{*}.@*
  548. @samp{\@{1,\@}} is equivalent to @samp{+}.
  549. @item \( @dots{} \)
  550. @cindex @samp{(} in regexp
  551. @cindex @samp{)} in regexp
  552. @cindex regexp grouping
  553. is a grouping construct that serves three purposes:
  554. @enumerate
  555. @item
  556. To enclose a set of @samp{\|} alternatives for other operations. Thus,
  557. the regular expression @samp{\(foo\|bar\)x} matches either @samp{foox}
  558. or @samp{barx}.
  559. @item
  560. To enclose a complicated expression for the postfix operators @samp{*},
  561. @samp{+} and @samp{?} to operate on. Thus, @samp{ba\(na\)*} matches
  562. @samp{ba}, @samp{bana}, @samp{banana}, @samp{bananana}, etc., with any
  563. number (zero or more) of @samp{na} strings.
  564. @item
  565. To record a matched substring for future reference with
  566. @samp{\@var{digit}} (see below).
  567. @end enumerate
  568. This last application is not a consequence of the idea of a
  569. parenthetical grouping; it is a separate feature that was assigned as a
  570. second meaning to the same @samp{\( @dots{} \)} construct because, in
  571. practice, there was usually no conflict between the two meanings. But
  572. occasionally there is a conflict, and that led to the introduction of
  573. shy groups.
  574. @item \(?: @dots{} \)
  575. @cindex shy groups
  576. @cindex non-capturing group
  577. @cindex unnumbered group
  578. @cindex @samp{(?:} in regexp
  579. is the @dfn{shy group} construct. A shy group serves the first two
  580. purposes of an ordinary group (controlling the nesting of other
  581. operators), but it does not get a number, so you cannot refer back to
  582. its value with @samp{\@var{digit}}. Shy groups are particularly
  583. useful for mechanically-constructed regular expressions, because they
  584. can be added automatically without altering the numbering of ordinary,
  585. non-shy groups.
  586. Shy groups are also called @dfn{non-capturing} or @dfn{unnumbered
  587. groups}.
  588. @item \(?@var{num}: @dots{} \)
  589. is the @dfn{explicitly numbered group} construct. Normal groups get
  590. their number implicitly, based on their position, which can be
  591. inconvenient. This construct allows you to force a particular group
  592. number. There is no particular restriction on the numbering,
  593. e.g., you can have several groups with the same number in which case
  594. the last one to match (i.e., the rightmost match) will win.
  595. Implicitly numbered groups always get the smallest integer larger than
  596. the one of any previous group.
  597. @item \@var{digit}
  598. matches the same text that matched the @var{digit}th occurrence of a
  599. grouping (@samp{\( @dots{} \)}) construct.
  600. In other words, after the end of a group, the matcher remembers the
  601. beginning and end of the text matched by that group. Later on in the
  602. regular expression you can use @samp{\} followed by @var{digit} to
  603. match that same text, whatever it may have been.
  604. The strings matching the first nine grouping constructs appearing in
  605. the entire regular expression passed to a search or matching function
  606. are assigned numbers 1 through 9 in the order that the open
  607. parentheses appear in the regular expression. So you can use
  608. @samp{\1} through @samp{\9} to refer to the text matched by the
  609. corresponding grouping constructs.
  610. For example, @samp{\(.*\)\1} matches any newline-free string that is
  611. composed of two identical halves. The @samp{\(.*\)} matches the first
  612. half, which may be anything, but the @samp{\1} that follows must match
  613. the same exact text.
  614. If a @samp{\( @dots{} \)} construct matches more than once (which can
  615. happen, for instance, if it is followed by @samp{*}), only the last
  616. match is recorded.
  617. If a particular grouping construct in the regular expression was never
  618. matched---for instance, if it appears inside of an alternative that
  619. wasn't used, or inside of a repetition that repeated zero times---then
  620. the corresponding @samp{\@var{digit}} construct never matches
  621. anything. To use an artificial example, @samp{\(foo\(b*\)\|lose\)\2}
  622. cannot match @samp{lose}: the second alternative inside the larger
  623. group matches it, but then @samp{\2} is undefined and can't match
  624. anything. But it can match @samp{foobb}, because the first
  625. alternative matches @samp{foob} and @samp{\2} matches @samp{b}.
  626. @item \w
  627. @cindex @samp{\w} in regexp
  628. matches any word-constituent character. The editor syntax table
  629. determines which characters these are. @xref{Syntax Tables}.
  630. @item \W
  631. @cindex @samp{\W} in regexp
  632. matches any character that is not a word constituent.
  633. @item \s@var{code}
  634. @cindex @samp{\s} in regexp
  635. matches any character whose syntax is @var{code}. Here @var{code} is a
  636. character that represents a syntax code: thus, @samp{w} for word
  637. constituent, @samp{-} for whitespace, @samp{(} for open parenthesis,
  638. etc. To represent whitespace syntax, use either @samp{-} or a space
  639. character. @xref{Syntax Class Table}, for a list of syntax codes and
  640. the characters that stand for them.
  641. @item \S@var{code}
  642. @cindex @samp{\S} in regexp
  643. matches any character whose syntax is not @var{code}.
  644. @cindex category, regexp search for
  645. @item \c@var{c}
  646. matches any character whose category is @var{c}. Here @var{c} is a
  647. character that represents a category: thus, @samp{c} for Chinese
  648. characters or @samp{g} for Greek characters in the standard category
  649. table. You can see the list of all the currently defined categories
  650. with @kbd{M-x describe-categories @key{RET}}. You can also define
  651. your own categories in addition to the standard ones using the
  652. @code{define-category} function (@pxref{Categories}).
  653. @item \C@var{c}
  654. matches any character whose category is not @var{c}.
  655. @end table
  656. The following regular expression constructs match the empty string---that is,
  657. they don't use up any characters---but whether they match depends on the
  658. context. For all, the beginning and end of the accessible portion of
  659. the buffer are treated as if they were the actual beginning and end of
  660. the buffer.
  661. @table @samp
  662. @item \`
  663. @cindex @samp{\`} in regexp
  664. matches the empty string, but only at the beginning
  665. of the buffer or string being matched against.
  666. @item \'
  667. @cindex @samp{\'} in regexp
  668. matches the empty string, but only at the end of
  669. the buffer or string being matched against.
  670. @item \=
  671. @cindex @samp{\=} in regexp
  672. matches the empty string, but only at point.
  673. (This construct is not defined when matching against a string.)
  674. @item \b
  675. @cindex @samp{\b} in regexp
  676. matches the empty string, but only at the beginning or
  677. end of a word. Thus, @samp{\bfoo\b} matches any occurrence of
  678. @samp{foo} as a separate word. @samp{\bballs?\b} matches
  679. @samp{ball} or @samp{balls} as a separate word.
  680. @samp{\b} matches at the beginning or end of the buffer (or string)
  681. regardless of what text appears next to it.
  682. @item \B
  683. @cindex @samp{\B} in regexp
  684. matches the empty string, but @emph{not} at the beginning or
  685. end of a word, nor at the beginning or end of the buffer (or string).
  686. @item \<
  687. @cindex @samp{\<} in regexp
  688. matches the empty string, but only at the beginning of a word.
  689. @samp{\<} matches at the beginning of the buffer (or string) only if a
  690. word-constituent character follows.
  691. @item \>
  692. @cindex @samp{\>} in regexp
  693. matches the empty string, but only at the end of a word. @samp{\>}
  694. matches at the end of the buffer (or string) only if the contents end
  695. with a word-constituent character.
  696. @item \_<
  697. @cindex @samp{\_<} in regexp
  698. matches the empty string, but only at the beginning of a symbol. A
  699. symbol is a sequence of one or more word or symbol constituent
  700. characters. @samp{\_<} matches at the beginning of the buffer (or
  701. string) only if a symbol-constituent character follows.
  702. @item \_>
  703. @cindex @samp{\_>} in regexp
  704. matches the empty string, but only at the end of a symbol. @samp{\_>}
  705. matches at the end of the buffer (or string) only if the contents end
  706. with a symbol-constituent character.
  707. @end table
  708. @kindex invalid-regexp
  709. Not every string is a valid regular expression. For example, a string
  710. that ends inside a character alternative without a terminating @samp{]}
  711. is invalid, and so is a string that ends with a single @samp{\}. If
  712. an invalid regular expression is passed to any of the search functions,
  713. an @code{invalid-regexp} error is signaled.
  714. @node Regexp Example
  715. @subsection Complex Regexp Example
  716. Here is a complicated regexp which was formerly used by Emacs to
  717. recognize the end of a sentence together with any whitespace that
  718. follows. (Nowadays Emacs uses a similar but more complex default
  719. regexp constructed by the function @code{sentence-end}.
  720. @xref{Standard Regexps}.)
  721. Below, we show first the regexp as a string in Lisp syntax (to
  722. distinguish spaces from tab characters), and then the result of
  723. evaluating it. The string constant begins and ends with a
  724. double-quote. @samp{\"} stands for a double-quote as part of the
  725. string, @samp{\\} for a backslash as part of the string, @samp{\t} for a
  726. tab and @samp{\n} for a newline.
  727. @example
  728. @group
  729. "[.?!][]\"')@}]*\\($\\| $\\|\t\\|@ @ \\)[ \t\n]*"
  730. @result{} "[.?!][]\"')@}]*\\($\\| $\\| \\|@ @ \\)[
  731. ]*"
  732. @end group
  733. @end example
  734. @noindent
  735. In the output, tab and newline appear as themselves.
  736. This regular expression contains four parts in succession and can be
  737. deciphered as follows:
  738. @table @code
  739. @item [.?!]
  740. The first part of the pattern is a character alternative that matches
  741. any one of three characters: period, question mark, and exclamation
  742. mark. The match must begin with one of these three characters. (This
  743. is one point where the new default regexp used by Emacs differs from
  744. the old. The new value also allows some non-@acronym{ASCII}
  745. characters that end a sentence without any following whitespace.)
  746. @item []\"')@}]*
  747. The second part of the pattern matches any closing braces and quotation
  748. marks, zero or more of them, that may follow the period, question mark
  749. or exclamation mark. The @code{\"} is Lisp syntax for a double-quote in
  750. a string. The @samp{*} at the end indicates that the immediately
  751. preceding regular expression (a character alternative, in this case) may be
  752. repeated zero or more times.
  753. @item \\($\\|@ $\\|\t\\|@ @ \\)
  754. The third part of the pattern matches the whitespace that follows the
  755. end of a sentence: the end of a line (optionally with a space), or a
  756. tab, or two spaces. The double backslashes mark the parentheses and
  757. vertical bars as regular expression syntax; the parentheses delimit a
  758. group and the vertical bars separate alternatives. The dollar sign is
  759. used to match the end of a line.
  760. @item [ \t\n]*
  761. Finally, the last part of the pattern matches any additional whitespace
  762. beyond the minimum needed to end a sentence.
  763. @end table
  764. @node Regexp Functions
  765. @subsection Regular Expression Functions
  766. These functions operate on regular expressions.
  767. @cindex quote special characters in regexp
  768. @defun regexp-quote string
  769. This function returns a regular expression whose only exact match is
  770. @var{string}. Using this regular expression in @code{looking-at} will
  771. succeed only if the next characters in the buffer are @var{string};
  772. using it in a search function will succeed if the text being searched
  773. contains @var{string}. @xref{Regexp Search}.
  774. This allows you to request an exact string match or search when calling
  775. a function that wants a regular expression.
  776. @example
  777. @group
  778. (regexp-quote "^The cat$")
  779. @result{} "\\^The cat\\$"
  780. @end group
  781. @end example
  782. One use of @code{regexp-quote} is to combine an exact string match with
  783. context described as a regular expression. For example, this searches
  784. for the string that is the value of @var{string}, surrounded by
  785. whitespace:
  786. @example
  787. @group
  788. (re-search-forward
  789. (concat "\\s-" (regexp-quote string) "\\s-"))
  790. @end group
  791. @end example
  792. @end defun
  793. @cindex optimize regexp
  794. @defun regexp-opt strings &optional paren
  795. This function returns an efficient regular expression that will match
  796. any of the strings in the list @var{strings}. This is useful when you
  797. need to make matching or searching as fast as possible---for example,
  798. for Font Lock mode@footnote{Note that @code{regexp-opt} does not
  799. guarantee that its result is absolutely the most efficient form
  800. possible. A hand-tuned regular expression can sometimes be slightly
  801. more efficient, but is almost never worth the effort.}.
  802. @c E.g., see http://debbugs.gnu.org/2816
  803. If the optional argument @var{paren} is non-@code{nil}, then the
  804. returned regular expression is always enclosed by at least one
  805. parentheses-grouping construct. If @var{paren} is @code{words}, then
  806. that construct is additionally surrounded by @samp{\<} and @samp{\>};
  807. alternatively, if @var{paren} is @code{symbols}, then that construct
  808. is additionally surrounded by @samp{\_<} and @samp{\_>}
  809. (@code{symbols} is often appropriate when matching
  810. programming-language keywords and the like).
  811. This simplified definition of @code{regexp-opt} produces a
  812. regular expression which is equivalent to the actual value
  813. (but not as efficient):
  814. @example
  815. (defun regexp-opt (strings &optional paren)
  816. (let ((open-paren (if paren "\\(" ""))
  817. (close-paren (if paren "\\)" "")))
  818. (concat open-paren
  819. (mapconcat 'regexp-quote strings "\\|")
  820. close-paren)))
  821. @end example
  822. @end defun
  823. @defun regexp-opt-depth regexp
  824. This function returns the total number of grouping constructs
  825. (parenthesized expressions) in @var{regexp}. This does not include
  826. shy groups (@pxref{Regexp Backslash}).
  827. @end defun
  828. @c Supposedly an internal regexp-opt function, but table.el uses it at least.
  829. @defun regexp-opt-charset chars
  830. This function returns a regular expression matching a character in the
  831. list of characters @var{chars}.
  832. @example
  833. (regexp-opt-charset '(?a ?b ?c ?d ?e))
  834. @result{} "[a-e]"
  835. @end example
  836. @end defun
  837. @c Internal functions: regexp-opt-group
  838. @node Regexp Search
  839. @section Regular Expression Searching
  840. @cindex regular expression searching
  841. @cindex regexp searching
  842. @cindex searching for regexp
  843. In GNU Emacs, you can search for the next match for a regular
  844. expression (@pxref{Syntax of Regexps}) either incrementally or not.
  845. For incremental search commands, see @ref{Regexp Search, , Regular
  846. Expression Search, emacs, The GNU Emacs Manual}. Here we describe
  847. only the search functions useful in programs. The principal one is
  848. @code{re-search-forward}.
  849. These search functions convert the regular expression to multibyte if
  850. the buffer is multibyte; they convert the regular expression to unibyte
  851. if the buffer is unibyte. @xref{Text Representations}.
  852. @deffn Command re-search-forward regexp &optional limit noerror repeat
  853. This function searches forward in the current buffer for a string of
  854. text that is matched by the regular expression @var{regexp}. The
  855. function skips over any amount of text that is not matched by
  856. @var{regexp}, and leaves point at the end of the first match found.
  857. It returns the new value of point.
  858. If @var{limit} is non-@code{nil}, it must be a position in the current
  859. buffer. It specifies the upper bound to the search. No match
  860. extending after that position is accepted.
  861. If @var{repeat} is supplied, it must be a positive number; the search
  862. is repeated that many times; each repetition starts at the end of the
  863. previous match. If all these successive searches succeed, the search
  864. succeeds, moving point and returning its new value. Otherwise the
  865. search fails. What @code{re-search-forward} does when the search
  866. fails depends on the value of @var{noerror}:
  867. @table @asis
  868. @item @code{nil}
  869. Signal a @code{search-failed} error.
  870. @item @code{t}
  871. Do nothing and return @code{nil}.
  872. @item anything else
  873. Move point to @var{limit} (or the end of the accessible portion of the
  874. buffer) and return @code{nil}.
  875. @end table
  876. In the following example, point is initially before the @samp{T}.
  877. Evaluating the search call moves point to the end of that line (between
  878. the @samp{t} of @samp{hat} and the newline).
  879. @example
  880. @group
  881. ---------- Buffer: foo ----------
  882. I read "@point{}The cat in the hat
  883. comes back" twice.
  884. ---------- Buffer: foo ----------
  885. @end group
  886. @group
  887. (re-search-forward "[a-z]+" nil t 5)
  888. @result{} 27
  889. ---------- Buffer: foo ----------
  890. I read "The cat in the hat@point{}
  891. comes back" twice.
  892. ---------- Buffer: foo ----------
  893. @end group
  894. @end example
  895. @end deffn
  896. @deffn Command re-search-backward regexp &optional limit noerror repeat
  897. This function searches backward in the current buffer for a string of
  898. text that is matched by the regular expression @var{regexp}, leaving
  899. point at the beginning of the first text found.
  900. This function is analogous to @code{re-search-forward}, but they are not
  901. simple mirror images. @code{re-search-forward} finds the match whose
  902. beginning is as close as possible to the starting point. If
  903. @code{re-search-backward} were a perfect mirror image, it would find the
  904. match whose end is as close as possible. However, in fact it finds the
  905. match whose beginning is as close as possible (and yet ends before the
  906. starting point). The reason for this is that matching a regular
  907. expression at a given spot always works from beginning to end, and
  908. starts at a specified beginning position.
  909. A true mirror-image of @code{re-search-forward} would require a special
  910. feature for matching regular expressions from end to beginning. It's
  911. not worth the trouble of implementing that.
  912. @end deffn
  913. @defun string-match regexp string &optional start
  914. This function returns the index of the start of the first match for
  915. the regular expression @var{regexp} in @var{string}, or @code{nil} if
  916. there is no match. If @var{start} is non-@code{nil}, the search starts
  917. at that index in @var{string}.
  918. For example,
  919. @example
  920. @group
  921. (string-match
  922. "quick" "The quick brown fox jumped quickly.")
  923. @result{} 4
  924. @end group
  925. @group
  926. (string-match
  927. "quick" "The quick brown fox jumped quickly." 8)
  928. @result{} 27
  929. @end group
  930. @end example
  931. @noindent
  932. The index of the first character of the
  933. string is 0, the index of the second character is 1, and so on.
  934. If this function finds a match, the index of the first character beyond
  935. the match is available as @code{(match-end 0)}. @xref{Match Data}.
  936. @example
  937. @group
  938. (string-match
  939. "quick" "The quick brown fox jumped quickly." 8)
  940. @result{} 27
  941. @end group
  942. @group
  943. (match-end 0)
  944. @result{} 32
  945. @end group
  946. @end example
  947. @end defun
  948. @defun string-match-p regexp string &optional start
  949. This predicate function does what @code{string-match} does, but it
  950. avoids modifying the match data.
  951. @end defun
  952. @defun looking-at regexp
  953. This function determines whether the text in the current buffer directly
  954. following point matches the regular expression @var{regexp}. ``Directly
  955. following'' means precisely that: the search is ``anchored'' and it can
  956. succeed only starting with the first character following point. The
  957. result is @code{t} if so, @code{nil} otherwise.
  958. This function does not move point, but it does update the match data.
  959. @xref{Match Data}. If you need to test for a match without modifying
  960. the match data, use @code{looking-at-p}, described below.
  961. In this example, point is located directly before the @samp{T}. If it
  962. were anywhere else, the result would be @code{nil}.
  963. @example
  964. @group
  965. ---------- Buffer: foo ----------
  966. I read "@point{}The cat in the hat
  967. comes back" twice.
  968. ---------- Buffer: foo ----------
  969. (looking-at "The cat in the hat$")
  970. @result{} t
  971. @end group
  972. @end example
  973. @end defun
  974. @defun looking-back regexp limit &optional greedy
  975. This function returns @code{t} if @var{regexp} matches the text
  976. immediately before point (i.e., ending at point), and @code{nil} otherwise.
  977. Because regular expression matching works only going forward, this is
  978. implemented by searching backwards from point for a match that ends at
  979. point. That can be quite slow if it has to search a long distance.
  980. You can bound the time required by specifying a non-@code{nil} value
  981. for @var{limit}, which says not to search before @var{limit}. In this
  982. case, the match that is found must begin at or after @var{limit}.
  983. Here's an example:
  984. @example
  985. @group
  986. ---------- Buffer: foo ----------
  987. I read "@point{}The cat in the hat
  988. comes back" twice.
  989. ---------- Buffer: foo ----------
  990. (looking-back "read \"" 3)
  991. @result{} t
  992. (looking-back "read \"" 4)
  993. @result{} nil
  994. @end group
  995. @end example
  996. If @var{greedy} is non-@code{nil}, this function extends the match
  997. backwards as far as possible, stopping when a single additional
  998. previous character cannot be part of a match for @var{regexp}. When
  999. the match is extended, its starting position is allowed to occur
  1000. before @var{limit}.
  1001. @c http://debbugs.gnu.org/5689
  1002. As a general recommendation, try to avoid using @code{looking-back}
  1003. wherever possible, since it is slow. For this reason, there are no
  1004. plans to add a @code{looking-back-p} function.
  1005. @end defun
  1006. @defun looking-at-p regexp
  1007. This predicate function works like @code{looking-at}, but without
  1008. updating the match data.
  1009. @end defun
  1010. @defvar search-spaces-regexp
  1011. If this variable is non-@code{nil}, it should be a regular expression
  1012. that says how to search for whitespace. In that case, any group of
  1013. spaces in a regular expression being searched for stands for use of
  1014. this regular expression. However, spaces inside of constructs such as
  1015. @samp{[@dots{}]} and @samp{*}, @samp{+}, @samp{?} are not affected by
  1016. @code{search-spaces-regexp}.
  1017. Since this variable affects all regular expression search and match
  1018. constructs, you should bind it temporarily for as small as possible
  1019. a part of the code.
  1020. @end defvar
  1021. @node POSIX Regexps
  1022. @section POSIX Regular Expression Searching
  1023. @cindex backtracking and POSIX regular expressions
  1024. The usual regular expression functions do backtracking when necessary
  1025. to handle the @samp{\|} and repetition constructs, but they continue
  1026. this only until they find @emph{some} match. Then they succeed and
  1027. report the first match found.
  1028. This section describes alternative search functions which perform the
  1029. full backtracking specified by the POSIX standard for regular expression
  1030. matching. They continue backtracking until they have tried all
  1031. possibilities and found all matches, so they can report the longest
  1032. match, as required by POSIX@. This is much slower, so use these
  1033. functions only when you really need the longest match.
  1034. The POSIX search and match functions do not properly support the
  1035. non-greedy repetition operators (@pxref{Regexp Special, non-greedy}).
  1036. This is because POSIX backtracking conflicts with the semantics of
  1037. non-greedy repetition.
  1038. @deffn Command posix-search-forward regexp &optional limit noerror repeat
  1039. This is like @code{re-search-forward} except that it performs the full
  1040. backtracking specified by the POSIX standard for regular expression
  1041. matching.
  1042. @end deffn
  1043. @deffn Command posix-search-backward regexp &optional limit noerror repeat
  1044. This is like @code{re-search-backward} except that it performs the full
  1045. backtracking specified by the POSIX standard for regular expression
  1046. matching.
  1047. @end deffn
  1048. @defun posix-looking-at regexp
  1049. This is like @code{looking-at} except that it performs the full
  1050. backtracking specified by the POSIX standard for regular expression
  1051. matching.
  1052. @end defun
  1053. @defun posix-string-match regexp string &optional start
  1054. This is like @code{string-match} except that it performs the full
  1055. backtracking specified by the POSIX standard for regular expression
  1056. matching.
  1057. @end defun
  1058. @node Match Data
  1059. @section The Match Data
  1060. @cindex match data
  1061. Emacs keeps track of the start and end positions of the segments of
  1062. text found during a search; this is called the @dfn{match data}.
  1063. Thanks to the match data, you can search for a complex pattern, such
  1064. as a date in a mail message, and then extract parts of the match under
  1065. control of the pattern.
  1066. Because the match data normally describe the most recent search only,
  1067. you must be careful not to do another search inadvertently between the
  1068. search you wish to refer back to and the use of the match data. If you
  1069. can't avoid another intervening search, you must save and restore the
  1070. match data around it, to prevent it from being overwritten.
  1071. Notice that all functions are allowed to overwrite the match data
  1072. unless they're explicitly documented not to do so. A consequence is
  1073. that functions that are run implicitly in the background
  1074. (@pxref{Timers}, and @ref{Idle Timers}) should likely save and restore
  1075. the match data explicitly.
  1076. @menu
  1077. * Replacing Match:: Replacing a substring that was matched.
  1078. * Simple Match Data:: Accessing single items of match data,
  1079. such as where a particular subexpression started.
  1080. * Entire Match Data:: Accessing the entire match data at once, as a list.
  1081. * Saving Match Data:: Saving and restoring the match data.
  1082. @end menu
  1083. @node Replacing Match
  1084. @subsection Replacing the Text that Matched
  1085. @cindex replace matched text
  1086. This function replaces all or part of the text matched by the last
  1087. search. It works by means of the match data.
  1088. @cindex case in replacements
  1089. @defun replace-match replacement &optional fixedcase literal string subexp
  1090. This function performs a replacement operation on a buffer or string.
  1091. If you did the last search in a buffer, you should omit the
  1092. @var{string} argument or specify @code{nil} for it, and make sure that
  1093. the current buffer is the one in which you performed the last search.
  1094. Then this function edits the buffer, replacing the matched text with
  1095. @var{replacement}. It leaves point at the end of the replacement
  1096. text.
  1097. If you performed the last search on a string, pass the same string as
  1098. @var{string}. Then this function returns a new string, in which the
  1099. matched text is replaced by @var{replacement}.
  1100. If @var{fixedcase} is non-@code{nil}, then @code{replace-match} uses
  1101. the replacement text without case conversion; otherwise, it converts
  1102. the replacement text depending upon the capitalization of the text to
  1103. be replaced. If the original text is all upper case, this converts
  1104. the replacement text to upper case. If all words of the original text
  1105. are capitalized, this capitalizes all the words of the replacement
  1106. text. If all the words are one-letter and they are all upper case,
  1107. they are treated as capitalized words rather than all-upper-case
  1108. words.
  1109. If @var{literal} is non-@code{nil}, then @var{replacement} is inserted
  1110. exactly as it is, the only alterations being case changes as needed.
  1111. If it is @code{nil} (the default), then the character @samp{\} is treated
  1112. specially. If a @samp{\} appears in @var{replacement}, then it must be
  1113. part of one of the following sequences:
  1114. @table @asis
  1115. @item @samp{\&}
  1116. @cindex @samp{&} in replacement
  1117. This stands for the entire text being replaced.
  1118. @item @samp{\@var{n}}, where @var{n} is a digit
  1119. @cindex @samp{\@var{n}} in replacement
  1120. This stands for the text that matched the @var{n}th subexpression in
  1121. the original regexp. Subexpressions are those expressions grouped
  1122. inside @samp{\(@dots{}\)}. If the @var{n}th subexpression never
  1123. matched, an empty string is substituted.
  1124. @item @samp{\\}
  1125. @cindex @samp{\} in replacement
  1126. This stands for a single @samp{\} in the replacement text.
  1127. @item @samp{\?}
  1128. This stands for itself (for compatibility with @code{replace-regexp}
  1129. and related commands; @pxref{Regexp Replace,,, emacs, The GNU
  1130. Emacs Manual}).
  1131. @end table
  1132. @noindent
  1133. Any other character following @samp{\} signals an error.
  1134. The substitutions performed by @samp{\&} and @samp{\@var{n}} occur
  1135. after case conversion, if any. Therefore, the strings they substitute
  1136. are never case-converted.
  1137. If @var{subexp} is non-@code{nil}, that says to replace just
  1138. subexpression number @var{subexp} of the regexp that was matched, not
  1139. the entire match. For example, after matching @samp{foo \(ba*r\)},
  1140. calling @code{replace-match} with 1 as @var{subexp} means to replace
  1141. just the text that matched @samp{\(ba*r\)}.
  1142. @end defun
  1143. @defun match-substitute-replacement replacement &optional fixedcase literal string subexp
  1144. This function returns the text that would be inserted into the buffer
  1145. by @code{replace-match}, but without modifying the buffer. It is
  1146. useful if you want to present the user with actual replacement result,
  1147. with constructs like @samp{\@var{n}} or @samp{\&} substituted with
  1148. matched groups. Arguments @var{replacement} and optional
  1149. @var{fixedcase}, @var{literal}, @var{string} and @var{subexp} have the
  1150. same meaning as for @code{replace-match}.
  1151. @end defun
  1152. @node Simple Match Data
  1153. @subsection Simple Match Data Access
  1154. This section explains how to use the match data to find out what was
  1155. matched by the last search or match operation, if it succeeded.
  1156. You can ask about the entire matching text, or about a particular
  1157. parenthetical subexpression of a regular expression. The @var{count}
  1158. argument in the functions below specifies which. If @var{count} is
  1159. zero, you are asking about the entire match. If @var{count} is
  1160. positive, it specifies which subexpression you want.
  1161. Recall that the subexpressions of a regular expression are those
  1162. expressions grouped with escaped parentheses, @samp{\(@dots{}\)}. The
  1163. @var{count}th subexpression is found by counting occurrences of
  1164. @samp{\(} from the beginning of the whole regular expression. The first
  1165. subexpression is numbered 1, the second 2, and so on. Only regular
  1166. expressions can have subexpressions---after a simple string search, the
  1167. only information available is about the entire match.
  1168. Every successful search sets the match data. Therefore, you should
  1169. query the match data immediately after searching, before calling any
  1170. other function that might perform another search. Alternatively, you
  1171. may save and restore the match data (@pxref{Saving Match Data}) around
  1172. the call to functions that could perform another search. Or use the
  1173. functions that explicitly do not modify the match data;
  1174. e.g., @code{string-match-p}.
  1175. @c This is an old comment and presumably there is no prospect of this
  1176. @c changing now. But still the advice stands.
  1177. A search which fails may or may not alter the match data. In the
  1178. current implementation, it does not, but we may change it in the
  1179. future. Don't try to rely on the value of the match data after a
  1180. failing search.
  1181. @defun match-string count &optional in-string
  1182. This function returns, as a string, the text matched in the last search
  1183. or match operation. It returns the entire text if @var{count} is zero,
  1184. or just the portion corresponding to the @var{count}th parenthetical
  1185. subexpression, if @var{count} is positive.
  1186. If the last such operation was done against a string with
  1187. @code{string-match}, then you should pass the same string as the
  1188. argument @var{in-string}. After a buffer search or match,
  1189. you should omit @var{in-string} or pass @code{nil} for it; but you
  1190. should make sure that the current buffer when you call
  1191. @code{match-string} is the one in which you did the searching or
  1192. matching. Failure to follow this advice will lead to incorrect results.
  1193. The value is @code{nil} if @var{count} is out of range, or for a
  1194. subexpression inside a @samp{\|} alternative that wasn't used or a
  1195. repetition that repeated zero times.
  1196. @end defun
  1197. @defun match-string-no-properties count &optional in-string
  1198. This function is like @code{match-string} except that the result
  1199. has no text properties.
  1200. @end defun
  1201. @defun match-beginning count
  1202. If the last regular expression search found a match, this function
  1203. returns the position of the start of the matching text or of a
  1204. subexpression of it.
  1205. If @var{count} is zero, then the value is the position of the start of
  1206. the entire match. Otherwise, @var{count} specifies a subexpression in
  1207. the regular expression, and the value of the function is the starting
  1208. position of the match for that subexpression.
  1209. The value is @code{nil} for a subexpression inside a @samp{\|}
  1210. alternative that wasn't used or a repetition that repeated zero times.
  1211. @end defun
  1212. @defun match-end count
  1213. This function is like @code{match-beginning} except that it returns the
  1214. position of the end of the match, rather than the position of the
  1215. beginning.
  1216. @end defun
  1217. Here is an example of using the match data, with a comment showing the
  1218. positions within the text:
  1219. @example
  1220. @group
  1221. (string-match "\\(qu\\)\\(ick\\)"
  1222. "The quick fox jumped quickly.")
  1223. ;0123456789
  1224. @result{} 4
  1225. @end group
  1226. @group
  1227. (match-string 0 "The quick fox jumped quickly.")
  1228. @result{} "quick"
  1229. (match-string 1 "The quick fox jumped quickly.")
  1230. @result{} "qu"
  1231. (match-string 2 "The quick fox jumped quickly.")
  1232. @result{} "ick"
  1233. @end group
  1234. @group
  1235. (match-beginning 1) ; @r{The beginning of the match}
  1236. @result{} 4 ; @r{with @samp{qu} is at index 4.}
  1237. @end group
  1238. @group
  1239. (match-beginning 2) ; @r{The beginning of the match}
  1240. @result{} 6 ; @r{with @samp{ick} is at index 6.}
  1241. @end group
  1242. @group
  1243. (match-end 1) ; @r{The end of the match}
  1244. @result{} 6 ; @r{with @samp{qu} is at index 6.}
  1245. (match-end 2) ; @r{The end of the match}
  1246. @result{} 9 ; @r{with @samp{ick} is at index 9.}
  1247. @end group
  1248. @end example
  1249. Here is another example. Point is initially located at the beginning
  1250. of the line. Searching moves point to between the space and the word
  1251. @samp{in}. The beginning of the entire match is at the 9th character of
  1252. the buffer (@samp{T}), and the beginning of the match for the first
  1253. subexpression is at the 13th character (@samp{c}).
  1254. @example
  1255. @group
  1256. (list
  1257. (re-search-forward "The \\(cat \\)")
  1258. (match-beginning 0)
  1259. (match-beginning 1))
  1260. @result{} (17 9 13)
  1261. @end group
  1262. @group
  1263. ---------- Buffer: foo ----------
  1264. I read "The cat @point{}in the hat comes back" twice.
  1265. ^ ^
  1266. 9 13
  1267. ---------- Buffer: foo ----------
  1268. @end group
  1269. @end example
  1270. @noindent
  1271. (In this case, the index returned is a buffer position; the first
  1272. character of the buffer counts as 1.)
  1273. @node Entire Match Data
  1274. @subsection Accessing the Entire Match Data
  1275. The functions @code{match-data} and @code{set-match-data} read or
  1276. write the entire match data, all at once.
  1277. @defun match-data &optional integers reuse reseat
  1278. This function returns a list of positions (markers or integers) that
  1279. record all the information on the text that the last search matched.
  1280. Element zero is the position of the beginning of the match for the
  1281. whole expression; element one is the position of the end of the match
  1282. for the expression. The next two elements are the positions of the
  1283. beginning and end of the match for the first subexpression, and so on.
  1284. In general, element
  1285. @ifnottex
  1286. number 2@var{n}
  1287. @end ifnottex
  1288. @tex
  1289. number {\mathsurround=0pt $2n$}
  1290. @end tex
  1291. corresponds to @code{(match-beginning @var{n})}; and
  1292. element
  1293. @ifnottex
  1294. number 2@var{n} + 1
  1295. @end ifnottex
  1296. @tex
  1297. number {\mathsurround=0pt $2n+1$}
  1298. @end tex
  1299. corresponds to @code{(match-end @var{n})}.
  1300. Normally all the elements are markers or @code{nil}, but if
  1301. @var{integers} is non-@code{nil}, that means to use integers instead
  1302. of markers. (In that case, the buffer itself is appended as an
  1303. additional element at the end of the list, to facilitate complete
  1304. restoration of the match data.) If the last match was done on a
  1305. string with @code{string-match}, then integers are always used,
  1306. since markers can't point into a string.
  1307. If @var{reuse} is non-@code{nil}, it should be a list. In that case,
  1308. @code{match-data} stores the match data in @var{reuse}. That is,
  1309. @var{reuse} is destructively modified. @var{reuse} does not need to
  1310. have the right length. If it is not long enough to contain the match
  1311. data, it is extended. If it is too long, the length of @var{reuse}
  1312. stays the same, but the elements that were not used are set to
  1313. @code{nil}. The purpose of this feature is to reduce the need for
  1314. garbage collection.
  1315. If @var{reseat} is non-@code{nil}, all markers on the @var{reuse} list
  1316. are reseated to point to nowhere.
  1317. As always, there must be no possibility of intervening searches between
  1318. the call to a search function and the call to @code{match-data} that is
  1319. intended to access the match data for that search.
  1320. @example
  1321. @group
  1322. (match-data)
  1323. @result{} (#<marker at 9 in foo>
  1324. #<marker at 17 in foo>
  1325. #<marker at 13 in foo>
  1326. #<marker at 17 in foo>)
  1327. @end group
  1328. @end example
  1329. @end defun
  1330. @defun set-match-data match-list &optional reseat
  1331. This function sets the match data from the elements of @var{match-list},
  1332. which should be a list that was the value of a previous call to
  1333. @code{match-data}. (More precisely, anything that has the same format
  1334. will work.)
  1335. If @var{match-list} refers to a buffer that doesn't exist, you don't get
  1336. an error; that sets the match data in a meaningless but harmless way.
  1337. If @var{reseat} is non-@code{nil}, all markers on the @var{match-list} list
  1338. are reseated to point to nowhere.
  1339. @c TODO Make it properly obsolete.
  1340. @findex store-match-data
  1341. @code{store-match-data} is a semi-obsolete alias for @code{set-match-data}.
  1342. @end defun
  1343. @node Saving Match Data
  1344. @subsection Saving and Restoring the Match Data
  1345. When you call a function that may search, you may need to save
  1346. and restore the match data around that call, if you want to preserve the
  1347. match data from an earlier search for later use. Here is an example
  1348. that shows the problem that arises if you fail to save the match data:
  1349. @example
  1350. @group
  1351. (re-search-forward "The \\(cat \\)")
  1352. @result{} 48
  1353. (foo) ; @r{@code{foo} does more searching.}
  1354. (match-end 0)
  1355. @result{} 61 ; @r{Unexpected result---not 48!}
  1356. @end group
  1357. @end example
  1358. You can save and restore the match data with @code{save-match-data}:
  1359. @defmac save-match-data body@dots{}
  1360. This macro executes @var{body}, saving and restoring the match
  1361. data around it. The return value is the value of the last form in
  1362. @var{body}.
  1363. @end defmac
  1364. You could use @code{set-match-data} together with @code{match-data} to
  1365. imitate the effect of the special form @code{save-match-data}. Here is
  1366. how:
  1367. @example
  1368. @group
  1369. (let ((data (match-data)))
  1370. (unwind-protect
  1371. @dots{} ; @r{Ok to change the original match data.}
  1372. (set-match-data data)))
  1373. @end group
  1374. @end example
  1375. Emacs automatically saves and restores the match data when it runs
  1376. process filter functions (@pxref{Filter Functions}) and process
  1377. sentinels (@pxref{Sentinels}).
  1378. @ignore
  1379. Here is a function which restores the match data provided the buffer
  1380. associated with it still exists.
  1381. @smallexample
  1382. @group
  1383. (defun restore-match-data (data)
  1384. @c It is incorrect to split the first line of a doc string.
  1385. @c If there's a problem here, it should be solved in some other way.
  1386. "Restore the match data DATA unless the buffer is missing."
  1387. (catch 'foo
  1388. (let ((d data))
  1389. @end group
  1390. (while d
  1391. (and (car d)
  1392. (null (marker-buffer (car d)))
  1393. @group
  1394. ;; @file{match-data} @r{buffer is deleted.}
  1395. (throw 'foo nil))
  1396. (setq d (cdr d)))
  1397. (set-match-data data))))
  1398. @end group
  1399. @end smallexample
  1400. @end ignore
  1401. @node Search and Replace
  1402. @section Search and Replace
  1403. @cindex replacement after search
  1404. @cindex searching and replacing
  1405. If you want to find all matches for a regexp in part of the buffer,
  1406. and replace them, the best way is to write an explicit loop using
  1407. @code{re-search-forward} and @code{replace-match}, like this:
  1408. @example
  1409. (while (re-search-forward "foo[ \t]+bar" nil t)
  1410. (replace-match "foobar"))
  1411. @end example
  1412. @noindent
  1413. @xref{Replacing Match,, Replacing the Text that Matched}, for a
  1414. description of @code{replace-match}.
  1415. However, replacing matches in a string is more complex, especially
  1416. if you want to do it efficiently. So Emacs provides a function to do
  1417. this.
  1418. @defun replace-regexp-in-string regexp rep string &optional fixedcase literal subexp start
  1419. This function copies @var{string} and searches it for matches for
  1420. @var{regexp}, and replaces them with @var{rep}. It returns the
  1421. modified copy. If @var{start} is non-@code{nil}, the search for
  1422. matches starts at that index in @var{string}, so matches starting
  1423. before that index are not changed.
  1424. This function uses @code{replace-match} to do the replacement, and it
  1425. passes the optional arguments @var{fixedcase}, @var{literal} and
  1426. @var{subexp} along to @code{replace-match}.
  1427. Instead of a string, @var{rep} can be a function. In that case,
  1428. @code{replace-regexp-in-string} calls @var{rep} for each match,
  1429. passing the text of the match as its sole argument. It collects the
  1430. value @var{rep} returns and passes that to @code{replace-match} as the
  1431. replacement string. The match data at this point are the result
  1432. of matching @var{regexp} against a substring of @var{string}.
  1433. @end defun
  1434. If you want to write a command along the lines of @code{query-replace},
  1435. you can use @code{perform-replace} to do the work.
  1436. @defun perform-replace from-string replacements query-flag regexp-flag delimited-flag &optional repeat-count map start end
  1437. This function is the guts of @code{query-replace} and related
  1438. commands. It searches for occurrences of @var{from-string} in the
  1439. text between positions @var{start} and @var{end} and replaces some or
  1440. all of them. If @var{start} is @code{nil} (or omitted), point is used
  1441. instead, and the end of the buffer's accessible portion is used for
  1442. @var{end}.
  1443. If @var{query-flag} is @code{nil}, it replaces all
  1444. occurrences; otherwise, it asks the user what to do about each one.
  1445. If @var{regexp-flag} is non-@code{nil}, then @var{from-string} is
  1446. considered a regular expression; otherwise, it must match literally. If
  1447. @var{delimited-flag} is non-@code{nil}, then only replacements
  1448. surrounded by word boundaries are considered.
  1449. The argument @var{replacements} specifies what to replace occurrences
  1450. with. If it is a string, that string is used. It can also be a list of
  1451. strings, to be used in cyclic order.
  1452. If @var{replacements} is a cons cell, @w{@code{(@var{function}
  1453. . @var{data})}}, this means to call @var{function} after each match to
  1454. get the replacement text. This function is called with two arguments:
  1455. @var{data}, and the number of replacements already made.
  1456. If @var{repeat-count} is non-@code{nil}, it should be an integer. Then
  1457. it specifies how many times to use each of the strings in the
  1458. @var{replacements} list before advancing cyclically to the next one.
  1459. If @var{from-string} contains upper-case letters, then
  1460. @code{perform-replace} binds @code{case-fold-search} to @code{nil}, and
  1461. it uses the @var{replacements} without altering their case.
  1462. Normally, the keymap @code{query-replace-map} defines the possible
  1463. user responses for queries. The argument @var{map}, if
  1464. non-@code{nil}, specifies a keymap to use instead of
  1465. @code{query-replace-map}.
  1466. This function uses one of two functions to search for the next
  1467. occurrence of @var{from-string}. These functions are specified by the
  1468. values of two variables: @code{replace-re-search-function} and
  1469. @code{replace-search-function}. The former is called when the
  1470. argument @var{regexp-flag} is non-@code{nil}, the latter when it is
  1471. @code{nil}.
  1472. @end defun
  1473. @defvar query-replace-map
  1474. This variable holds a special keymap that defines the valid user
  1475. responses for @code{perform-replace} and the commands that use it, as
  1476. well as @code{y-or-n-p} and @code{map-y-or-n-p}. This map is unusual
  1477. in two ways:
  1478. @itemize @bullet
  1479. @item
  1480. The key bindings are not commands, just symbols that are meaningful
  1481. to the functions that use this map.
  1482. @item
  1483. Prefix keys are not supported; each key binding must be for a
  1484. single-event key sequence. This is because the functions don't use
  1485. @code{read-key-sequence} to get the input; instead, they read a single
  1486. event and look it up ``by hand''.
  1487. @end itemize
  1488. @end defvar
  1489. Here are the meaningful bindings for @code{query-replace-map}.
  1490. Several of them are meaningful only for @code{query-replace} and
  1491. friends.
  1492. @table @code
  1493. @item act
  1494. Do take the action being considered---in other words, ``yes''.
  1495. @item skip
  1496. Do not take action for this question---in other words, ``no''.
  1497. @item exit
  1498. Answer this question ``no'', and give up on the entire series of
  1499. questions, assuming that the answers will be ``no''.
  1500. @item exit-prefix
  1501. Like @code{exit}, but add the key that was pressed to
  1502. @code{unread-command-events} (@pxref{Event Input Misc}).
  1503. @item act-and-exit
  1504. Answer this question ``yes'', and give up on the entire series of
  1505. questions, assuming that subsequent answers will be ``no''.
  1506. @item act-and-show
  1507. Answer this question ``yes'', but show the results---don't advance yet
  1508. to the next question.
  1509. @item automatic
  1510. Answer this question and all subsequent questions in the series with
  1511. ``yes'', without further user interaction.
  1512. @item backup
  1513. Move back to the previous place that a question was asked about.
  1514. @item undo
  1515. Undo last replacement and move back to the place where that
  1516. replacement was performed.
  1517. @item undo-all
  1518. Undo all replacements and move back to the place where the first
  1519. replacement was performed.
  1520. @item edit
  1521. Enter a recursive edit to deal with this question---instead of any
  1522. other action that would normally be taken.
  1523. @item edit-replacement
  1524. Edit the replacement for this question in the minibuffer.
  1525. @item delete-and-edit
  1526. Delete the text being considered, then enter a recursive edit to replace
  1527. it.
  1528. @item recenter
  1529. @itemx scroll-up
  1530. @itemx scroll-down
  1531. @itemx scroll-other-window
  1532. @itemx scroll-other-window-down
  1533. Perform the specified window scroll operation, then ask the same
  1534. question again. Only @code{y-or-n-p} and related functions use this
  1535. answer.
  1536. @item quit
  1537. Perform a quit right away. Only @code{y-or-n-p} and related functions
  1538. use this answer.
  1539. @item help
  1540. Display some help, then ask again.
  1541. @end table
  1542. @defvar multi-query-replace-map
  1543. This variable holds a keymap that extends @code{query-replace-map} by
  1544. providing additional keybindings that are useful in multi-buffer
  1545. replacements. The additional bindings are:
  1546. @table @code
  1547. @item automatic-all
  1548. Answer this question and all subsequent questions in the series with
  1549. ``yes'', without further user interaction, for all remaining buffers.
  1550. @item exit-current
  1551. Answer this question ``no'', and give up on the entire series of
  1552. questions for the current buffer. Continue to the next buffer in the
  1553. sequence.
  1554. @end table
  1555. @end defvar
  1556. @defvar replace-search-function
  1557. This variable specifies a function that @code{perform-replace} calls
  1558. to search for the next string to replace. Its default value is
  1559. @code{search-forward}. Any other value should name a function of 3
  1560. arguments: the first 3 arguments of @code{search-forward}
  1561. (@pxref{String Search}).
  1562. @end defvar
  1563. @defvar replace-re-search-function
  1564. This variable specifies a function that @code{perform-replace} calls
  1565. to search for the next regexp to replace. Its default value is
  1566. @code{re-search-forward}. Any other value should name a function of 3
  1567. arguments: the first 3 arguments of @code{re-search-forward}
  1568. (@pxref{Regexp Search}).
  1569. @end defvar
  1570. @node Standard Regexps
  1571. @section Standard Regular Expressions Used in Editing
  1572. @cindex regexps used standardly in editing
  1573. @cindex standard regexps used in editing
  1574. This section describes some variables that hold regular expressions
  1575. used for certain purposes in editing:
  1576. @defopt page-delimiter
  1577. This is the regular expression describing line-beginnings that separate
  1578. pages. The default value is @code{"^\014"} (i.e., @code{"^^L"} or
  1579. @code{"^\C-l"}); this matches a line that starts with a formfeed
  1580. character.
  1581. @end defopt
  1582. The following two regular expressions should @emph{not} assume the
  1583. match always starts at the beginning of a line; they should not use
  1584. @samp{^} to anchor the match. Most often, the paragraph commands do
  1585. check for a match only at the beginning of a line, which means that
  1586. @samp{^} would be superfluous. When there is a nonzero left margin,
  1587. they accept matches that start after the left margin. In that case, a
  1588. @samp{^} would be incorrect. However, a @samp{^} is harmless in modes
  1589. where a left margin is never used.
  1590. @defopt paragraph-separate
  1591. This is the regular expression for recognizing the beginning of a line
  1592. that separates paragraphs. (If you change this, you may have to
  1593. change @code{paragraph-start} also.) The default value is
  1594. @w{@code{"[@ \t\f]*$"}}, which matches a line that consists entirely of
  1595. spaces, tabs, and form feeds (after its left margin).
  1596. @end defopt
  1597. @defopt paragraph-start
  1598. This is the regular expression for recognizing the beginning of a line
  1599. that starts @emph{or} separates paragraphs. The default value is
  1600. @w{@code{"\f\\|[ \t]*$"}}, which matches a line containing only
  1601. whitespace or starting with a form feed (after its left margin).
  1602. @end defopt
  1603. @defopt sentence-end
  1604. If non-@code{nil}, the value should be a regular expression describing
  1605. the end of a sentence, including the whitespace following the
  1606. sentence. (All paragraph boundaries also end sentences, regardless.)
  1607. If the value is @code{nil}, as it is by default, then the function
  1608. @code{sentence-end} constructs the regexp. That is why you
  1609. should always call the function @code{sentence-end} to obtain the
  1610. regexp to be used to recognize the end of a sentence.
  1611. @end defopt
  1612. @defun sentence-end
  1613. This function returns the value of the variable @code{sentence-end},
  1614. if non-@code{nil}. Otherwise it returns a default value based on the
  1615. values of the variables @code{sentence-end-double-space}
  1616. (@pxref{Definition of sentence-end-double-space}),
  1617. @code{sentence-end-without-period}, and
  1618. @code{sentence-end-without-space}.
  1619. @end defun