(Fcall_process): Sync with HEAD.
[bpt/emacs.git] / src / search.c
CommitLineData
ca1d1d23 1/* String search routines for GNU Emacs.
0b5538bd 2 Copyright (C) 1985, 1986, 1987, 1993, 1994, 1997, 1998, 1999, 2002, 2003,
aaef169d 3 2004, 2005, 2006 Free Software Foundation, Inc.
ca1d1d23
JB
4
5This file is part of GNU Emacs.
6
7GNU Emacs is free software; you can redistribute it and/or modify
8it under the terms of the GNU General Public License as published by
7c938215 9the Free Software Foundation; either version 2, or (at your option)
ca1d1d23
JB
10any later version.
11
12GNU Emacs is distributed in the hope that it will be useful,
13but WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15GNU General Public License for more details.
16
17You should have received a copy of the GNU General Public License
18along with GNU Emacs; see the file COPYING. If not, write to
4fc5845f
LK
19the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20Boston, MA 02110-1301, USA. */
ca1d1d23
JB
21
22
18160b98 23#include <config.h>
ca1d1d23
JB
24#include "lisp.h"
25#include "syntax.h"
5679531d 26#include "category.h"
ca1d1d23 27#include "buffer.h"
76eb0881 28#include "character.h"
9169c321 29#include "region-cache.h"
ca1d1d23 30#include "commands.h"
9ac0d9e0 31#include "blockinput.h"
bf1760bb 32#include "intervals.h"
4746118a 33
ca1d1d23
JB
34#include <sys/types.h>
35#include "regex.h"
36
1d288aef 37#define REGEXP_CACHE_SIZE 20
ca1d1d23 38
487282dc
KH
39/* If the regexp is non-nil, then the buffer contains the compiled form
40 of that regexp, suitable for searching. */
1d288aef
RS
41struct regexp_cache
42{
487282dc 43 struct regexp_cache *next;
ecdb561e 44 Lisp_Object regexp, whitespace_regexp;
487282dc
KH
45 struct re_pattern_buffer buf;
46 char fastmap[0400];
b819a390
RS
47 /* Nonzero means regexp was compiled to do full POSIX backtracking. */
48 char posix;
487282dc 49};
ca1d1d23 50
487282dc
KH
51/* The instances of that struct. */
52struct regexp_cache searchbufs[REGEXP_CACHE_SIZE];
ca1d1d23 53
487282dc
KH
54/* The head of the linked list; points to the most recently used buffer. */
55struct regexp_cache *searchbuf_head;
ca1d1d23 56
ca1d1d23 57
4746118a
JB
58/* Every call to re_match, etc., must pass &search_regs as the regs
59 argument unless you can show it is unnecessary (i.e., if re_match
60 is certainly going to be called again before region-around-match
61 can be called).
62
63 Since the registers are now dynamically allocated, we need to make
64 sure not to refer to the Nth register before checking that it has
1113d9db
JB
65 been allocated by checking search_regs.num_regs.
66
67 The regex code keeps track of whether it has allocated the search
487282dc
KH
68 buffer using bits in the re_pattern_buffer. This means that whenever
69 you compile a new pattern, it completely forgets whether it has
1113d9db
JB
70 allocated any registers, and will allocate new registers the next
71 time you call a searching or matching function. Therefore, we need
72 to call re_set_registers after compiling a new pattern or after
73 setting the match registers, so that the regex functions will be
74 able to free or re-allocate it properly. */
ca1d1d23
JB
75static struct re_registers search_regs;
76
daa37602
JB
77/* The buffer in which the last search was performed, or
78 Qt if the last search was done in a string;
79 Qnil if no searching has been done yet. */
80static Lisp_Object last_thing_searched;
ca1d1d23 81
8e6208c5 82/* error condition signaled when regexp compile_pattern fails */
ca1d1d23
JB
83
84Lisp_Object Qinvalid_regexp;
85
41a33295 86Lisp_Object Vsearch_spaces_regexp;
f31a9a68 87
ca325161 88static void set_search_regs ();
044f81f1 89static void save_search_regs ();
facdc750
RS
90static int simple_search ();
91static int boyer_moore ();
b819a390
RS
92static int search_buffer ();
93
ca1d1d23
JB
94static void
95matcher_overflow ()
96{
97 error ("Stack overflow in regexp matcher");
98}
99
b819a390
RS
100/* Compile a regexp and signal a Lisp error if anything goes wrong.
101 PATTERN is the pattern to compile.
102 CP is the place to put the result.
facdc750 103 TRANSLATE is a translation table for ignoring case, or nil for none.
b819a390
RS
104 REGP is the structure that says where to store the "register"
105 values that will result from matching this pattern.
106 If it is 0, we should compile the pattern not to record any
107 subexpression bounds.
108 POSIX is nonzero if we want full backtracking (POSIX style)
5679531d 109 for this pattern. 0 means backtrack only enough to get a valid match.
8f924df7 110 MULTIBYTE is nonzero iff a target of match is a multibyte buffer or
bbc73b48
KH
111 string.
112
113 The behavior also depends on Vsearch_spaces_regexp. */
ca1d1d23 114
487282dc 115static void
5679531d 116compile_pattern_1 (cp, pattern, translate, regp, posix, multibyte)
487282dc 117 struct regexp_cache *cp;
ca1d1d23 118 Lisp_Object pattern;
facdc750 119 Lisp_Object translate;
487282dc 120 struct re_registers *regp;
b819a390 121 int posix;
5679531d 122 int multibyte;
ca1d1d23 123{
d451e4db 124 char *val;
b819a390 125 reg_syntax_t old;
ca1d1d23 126
487282dc 127 cp->regexp = Qnil;
59fab369 128 cp->buf.translate = (! NILP (translate) ? translate : make_number (0));
b819a390 129 cp->posix = posix;
93daa011
KH
130 cp->buf.multibyte = STRING_MULTIBYTE (pattern);
131 cp->buf.target_multibyte = multibyte;
bbc73b48 132 cp->whitespace_regexp = Vsearch_spaces_regexp;
9ac0d9e0 133 BLOCK_INPUT;
fb4a568d 134 old = re_set_syntax (RE_SYNTAX_EMACS
b819a390 135 | (posix ? 0 : RE_NO_POSIX_BACKTRACKING));
bbc73b48
KH
136 re_set_whitespace_regexp (NILP (Vsearch_spaces_regexp) ? NULL
137 : SDATA (Vsearch_spaces_regexp));
138
8f924df7
KH
139 val = (char *) re_compile_pattern ((char *) SDATA (pattern),
140 SBYTES (pattern), &cp->buf);
bbc73b48
KH
141
142 re_set_whitespace_regexp (NULL);
143
b819a390 144 re_set_syntax (old);
9ac0d9e0 145 UNBLOCK_INPUT;
ca1d1d23 146 if (val)
487282dc 147 Fsignal (Qinvalid_regexp, Fcons (build_string (val), Qnil));
1113d9db 148
487282dc 149 cp->regexp = Fcopy_sequence (pattern);
487282dc
KH
150}
151
6efc7887
RS
152/* Shrink each compiled regexp buffer in the cache
153 to the size actually used right now.
154 This is called from garbage collection. */
155
156void
157shrink_regexp_cache ()
158{
a968f437 159 struct regexp_cache *cp;
6efc7887
RS
160
161 for (cp = searchbuf_head; cp != 0; cp = cp->next)
162 {
163 cp->buf.allocated = cp->buf.used;
164 cp->buf.buffer
b23c0a83 165 = (unsigned char *) xrealloc (cp->buf.buffer, cp->buf.used);
6efc7887
RS
166 }
167}
168
487282dc 169/* Compile a regexp if necessary, but first check to see if there's one in
b819a390
RS
170 the cache.
171 PATTERN is the pattern to compile.
facdc750 172 TRANSLATE is a translation table for ignoring case, or nil for none.
b819a390
RS
173 REGP is the structure that says where to store the "register"
174 values that will result from matching this pattern.
175 If it is 0, we should compile the pattern not to record any
176 subexpression bounds.
177 POSIX is nonzero if we want full backtracking (POSIX style)
178 for this pattern. 0 means backtrack only enough to get a valid match. */
487282dc
KH
179
180struct re_pattern_buffer *
0c8533c6 181compile_pattern (pattern, regp, translate, posix, multibyte)
487282dc
KH
182 Lisp_Object pattern;
183 struct re_registers *regp;
facdc750 184 Lisp_Object translate;
0c8533c6 185 int posix, multibyte;
487282dc
KH
186{
187 struct regexp_cache *cp, **cpp;
188
189 for (cpp = &searchbuf_head; ; cpp = &cp->next)
190 {
191 cp = *cpp;
f1b9c7c1
KR
192 /* Entries are initialized to nil, and may be set to nil by
193 compile_pattern_1 if the pattern isn't valid. Don't apply
49a5f770
KR
194 string accessors in those cases. However, compile_pattern_1
195 is only applied to the cache entry we pick here to reuse. So
196 nil should never appear before a non-nil entry. */
7c752c80 197 if (NILP (cp->regexp))
f1b9c7c1 198 goto compile_it;
d5db4077 199 if (SCHARS (cp->regexp) == SCHARS (pattern)
cf69b13e 200 && STRING_MULTIBYTE (cp->regexp) == STRING_MULTIBYTE (pattern)
1d288aef 201 && !NILP (Fstring_equal (cp->regexp, pattern))
59fab369 202 && EQ (cp->buf.translate, (! NILP (translate) ? translate : make_number (0)))
5679531d 203 && cp->posix == posix
bbc73b48
KH
204 && cp->buf.target_multibyte == multibyte
205 && !NILP (Fequal (cp->whitespace_regexp, Vsearch_spaces_regexp)))
487282dc
KH
206 break;
207
f1b9c7c1
KR
208 /* If we're at the end of the cache, compile into the nil cell
209 we found, or the last (least recently used) cell with a
210 string value. */
487282dc
KH
211 if (cp->next == 0)
212 {
f1b9c7c1 213 compile_it:
5679531d 214 compile_pattern_1 (cp, pattern, translate, regp, posix, multibyte);
487282dc
KH
215 break;
216 }
217 }
218
219 /* When we get here, cp (aka *cpp) contains the compiled pattern,
220 either because we found it in the cache or because we just compiled it.
221 Move it to the front of the queue to mark it as most recently used. */
222 *cpp = cp->next;
223 cp->next = searchbuf_head;
224 searchbuf_head = cp;
1113d9db 225
6639708c
RS
226 /* Advise the searching functions about the space we have allocated
227 for register data. */
228 if (regp)
229 re_set_registers (&cp->buf, regp, regp->num_regs, regp->start, regp->end);
230
487282dc 231 return &cp->buf;
ca1d1d23
JB
232}
233
234/* Error condition used for failing searches */
235Lisp_Object Qsearch_failed;
236
237Lisp_Object
238signal_failure (arg)
239 Lisp_Object arg;
240{
241 Fsignal (Qsearch_failed, Fcons (arg, Qnil));
242 return Qnil;
243}
244\f
b819a390
RS
245static Lisp_Object
246looking_at_1 (string, posix)
ca1d1d23 247 Lisp_Object string;
b819a390 248 int posix;
ca1d1d23
JB
249{
250 Lisp_Object val;
251 unsigned char *p1, *p2;
252 int s1, s2;
253 register int i;
487282dc 254 struct re_pattern_buffer *bufp;
ca1d1d23 255
7074fde6
FP
256 if (running_asynch_code)
257 save_search_regs ();
258
b7826503 259 CHECK_STRING (string);
487282dc
KH
260 bufp = compile_pattern (string, &search_regs,
261 (!NILP (current_buffer->case_fold_search)
0190922f 262 ? current_buffer->case_canon_table : Qnil),
0c8533c6
RS
263 posix,
264 !NILP (current_buffer->enable_multibyte_characters));
ca1d1d23
JB
265
266 immediate_quit = 1;
267 QUIT; /* Do a pending quit right away, to avoid paradoxical behavior */
268
269 /* Get pointers and sizes of the two strings
270 that make up the visible portion of the buffer. */
271
272 p1 = BEGV_ADDR;
fa8ed3e0 273 s1 = GPT_BYTE - BEGV_BYTE;
ca1d1d23 274 p2 = GAP_END_ADDR;
fa8ed3e0 275 s2 = ZV_BYTE - GPT_BYTE;
ca1d1d23
JB
276 if (s1 < 0)
277 {
278 p2 = p1;
fa8ed3e0 279 s2 = ZV_BYTE - BEGV_BYTE;
ca1d1d23
JB
280 s1 = 0;
281 }
282 if (s2 < 0)
283 {
fa8ed3e0 284 s1 = ZV_BYTE - BEGV_BYTE;
ca1d1d23
JB
285 s2 = 0;
286 }
8bb43c28
RS
287
288 re_match_object = Qnil;
177c0ea7 289
487282dc 290 i = re_match_2 (bufp, (char *) p1, s1, (char *) p2, s2,
fa8ed3e0
RS
291 PT_BYTE - BEGV_BYTE, &search_regs,
292 ZV_BYTE - BEGV_BYTE);
de182d70 293 immediate_quit = 0;
177c0ea7 294
ca1d1d23
JB
295 if (i == -2)
296 matcher_overflow ();
297
298 val = (0 <= i ? Qt : Qnil);
fa8ed3e0
RS
299 if (i >= 0)
300 for (i = 0; i < search_regs.num_regs; i++)
301 if (search_regs.start[i] >= 0)
302 {
303 search_regs.start[i]
304 = BYTE_TO_CHAR (search_regs.start[i] + BEGV_BYTE);
305 search_regs.end[i]
306 = BYTE_TO_CHAR (search_regs.end[i] + BEGV_BYTE);
307 }
a3668d92 308 XSETBUFFER (last_thing_searched, current_buffer);
ca1d1d23
JB
309 return val;
310}
311
b819a390 312DEFUN ("looking-at", Flooking_at, Slooking_at, 1, 1, 0,
8c1a1077
PJ
313 doc: /* Return t if text after point matches regular expression REGEXP.
314This function modifies the match data that `match-beginning',
315`match-end' and `match-data' access; save and restore the match
316data if you want to preserve them. */)
317 (regexp)
94f94972 318 Lisp_Object regexp;
b819a390 319{
94f94972 320 return looking_at_1 (regexp, 0);
b819a390
RS
321}
322
323DEFUN ("posix-looking-at", Fposix_looking_at, Sposix_looking_at, 1, 1, 0,
8c1a1077
PJ
324 doc: /* Return t if text after point matches regular expression REGEXP.
325Find the longest match, in accord with Posix regular expression rules.
326This function modifies the match data that `match-beginning',
327`match-end' and `match-data' access; save and restore the match
328data if you want to preserve them. */)
329 (regexp)
94f94972 330 Lisp_Object regexp;
b819a390 331{
94f94972 332 return looking_at_1 (regexp, 1);
b819a390
RS
333}
334\f
335static Lisp_Object
336string_match_1 (regexp, string, start, posix)
ca1d1d23 337 Lisp_Object regexp, string, start;
b819a390 338 int posix;
ca1d1d23
JB
339{
340 int val;
487282dc 341 struct re_pattern_buffer *bufp;
0c8533c6
RS
342 int pos, pos_byte;
343 int i;
ca1d1d23 344
7074fde6
FP
345 if (running_asynch_code)
346 save_search_regs ();
347
b7826503
PJ
348 CHECK_STRING (regexp);
349 CHECK_STRING (string);
ca1d1d23
JB
350
351 if (NILP (start))
0c8533c6 352 pos = 0, pos_byte = 0;
ca1d1d23
JB
353 else
354 {
d5db4077 355 int len = SCHARS (string);
ca1d1d23 356
b7826503 357 CHECK_NUMBER (start);
0c8533c6
RS
358 pos = XINT (start);
359 if (pos < 0 && -pos <= len)
360 pos = len + pos;
361 else if (0 > pos || pos > len)
ca1d1d23 362 args_out_of_range (string, start);
0c8533c6 363 pos_byte = string_char_to_byte (string, pos);
ca1d1d23
JB
364 }
365
487282dc
KH
366 bufp = compile_pattern (regexp, &search_regs,
367 (!NILP (current_buffer->case_fold_search)
0190922f 368 ? current_buffer->case_canon_table : Qnil),
0c8533c6
RS
369 posix,
370 STRING_MULTIBYTE (string));
ca1d1d23 371 immediate_quit = 1;
8bb43c28 372 re_match_object = string;
177c0ea7 373
d5db4077
KR
374 val = re_search (bufp, (char *) SDATA (string),
375 SBYTES (string), pos_byte,
376 SBYTES (string) - pos_byte,
ca1d1d23
JB
377 &search_regs);
378 immediate_quit = 0;
daa37602 379 last_thing_searched = Qt;
ca1d1d23
JB
380 if (val == -2)
381 matcher_overflow ();
382 if (val < 0) return Qnil;
0c8533c6
RS
383
384 for (i = 0; i < search_regs.num_regs; i++)
385 if (search_regs.start[i] >= 0)
386 {
387 search_regs.start[i]
388 = string_byte_to_char (string, search_regs.start[i]);
389 search_regs.end[i]
390 = string_byte_to_char (string, search_regs.end[i]);
391 }
392
393 return make_number (string_byte_to_char (string, val));
ca1d1d23 394}
e59a8453 395
b819a390 396DEFUN ("string-match", Fstring_match, Sstring_match, 2, 3, 0,
8c1a1077 397 doc: /* Return index of start of first match for REGEXP in STRING, or nil.
b85acc4b 398Matching ignores case if `case-fold-search' is non-nil.
8c1a1077
PJ
399If third arg START is non-nil, start search at that index in STRING.
400For index of first char beyond the match, do (match-end 0).
401`match-end' and `match-beginning' also give indices of substrings
2bd2f32d
RS
402matched by parenthesis constructs in the pattern.
403
404You can use the function `match-string' to extract the substrings
405matched by the parenthesis constructions in REGEXP. */)
8c1a1077 406 (regexp, string, start)
b819a390
RS
407 Lisp_Object regexp, string, start;
408{
409 return string_match_1 (regexp, string, start, 0);
410}
411
412DEFUN ("posix-string-match", Fposix_string_match, Sposix_string_match, 2, 3, 0,
8c1a1077
PJ
413 doc: /* Return index of start of first match for REGEXP in STRING, or nil.
414Find the longest match, in accord with Posix regular expression rules.
415Case is ignored if `case-fold-search' is non-nil in the current buffer.
416If third arg START is non-nil, start search at that index in STRING.
417For index of first char beyond the match, do (match-end 0).
418`match-end' and `match-beginning' also give indices of substrings
419matched by parenthesis constructs in the pattern. */)
420 (regexp, string, start)
b819a390
RS
421 Lisp_Object regexp, string, start;
422{
423 return string_match_1 (regexp, string, start, 1);
424}
425
e59a8453
RS
426/* Match REGEXP against STRING, searching all of STRING,
427 and return the index of the match, or negative on failure.
428 This does not clobber the match data. */
429
430int
431fast_string_match (regexp, string)
432 Lisp_Object regexp, string;
433{
434 int val;
487282dc 435 struct re_pattern_buffer *bufp;
e59a8453 436
facdc750
RS
437 bufp = compile_pattern (regexp, 0, Qnil,
438 0, STRING_MULTIBYTE (string));
e59a8453 439 immediate_quit = 1;
8bb43c28 440 re_match_object = string;
177c0ea7 441
d5db4077
KR
442 val = re_search (bufp, (char *) SDATA (string),
443 SBYTES (string), 0,
444 SBYTES (string), 0);
e59a8453
RS
445 immediate_quit = 0;
446 return val;
447}
5679531d
KH
448
449/* Match REGEXP against STRING, searching all of STRING ignoring case,
450 and return the index of the match, or negative on failure.
0c8533c6
RS
451 This does not clobber the match data.
452 We assume that STRING contains single-byte characters. */
5679531d
KH
453
454extern Lisp_Object Vascii_downcase_table;
455
456int
b4577c63 457fast_c_string_match_ignore_case (regexp, string)
5679531d 458 Lisp_Object regexp;
96b80561 459 const char *string;
5679531d
KH
460{
461 int val;
462 struct re_pattern_buffer *bufp;
463 int len = strlen (string);
464
0c8533c6 465 regexp = string_make_unibyte (regexp);
b4577c63 466 re_match_object = Qt;
5679531d 467 bufp = compile_pattern (regexp, 0,
0190922f 468 Vascii_canon_table, 0,
f8bd51c4 469 0);
5679531d
KH
470 immediate_quit = 1;
471 val = re_search (bufp, string, len, 0, len, 0);
472 immediate_quit = 0;
473 return val;
474}
be5f4dfb
KH
475
476/* Like fast_string_match but ignore case. */
477
478int
479fast_string_match_ignore_case (regexp, string)
480 Lisp_Object regexp, string;
481{
482 int val;
483 struct re_pattern_buffer *bufp;
484
0190922f 485 bufp = compile_pattern (regexp, 0, Vascii_canon_table,
be5f4dfb
KH
486 0, STRING_MULTIBYTE (string));
487 immediate_quit = 1;
488 re_match_object = string;
489
490 val = re_search (bufp, (char *) SDATA (string),
491 SBYTES (string), 0,
492 SBYTES (string), 0);
493 immediate_quit = 0;
494 return val;
495}
ca1d1d23 496\f
9169c321
JB
497/* The newline cache: remembering which sections of text have no newlines. */
498
499/* If the user has requested newline caching, make sure it's on.
500 Otherwise, make sure it's off.
501 This is our cheezy way of associating an action with the change of
502 state of a buffer-local variable. */
503static void
504newline_cache_on_off (buf)
505 struct buffer *buf;
506{
507 if (NILP (buf->cache_long_line_scans))
508 {
509 /* It should be off. */
510 if (buf->newline_cache)
511 {
512 free_region_cache (buf->newline_cache);
513 buf->newline_cache = 0;
514 }
515 }
516 else
517 {
518 /* It should be on. */
519 if (buf->newline_cache == 0)
520 buf->newline_cache = new_region_cache ();
521 }
522}
523
524\f
525/* Search for COUNT instances of the character TARGET between START and END.
526
527 If COUNT is positive, search forwards; END must be >= START.
528 If COUNT is negative, search backwards for the -COUNTth instance;
529 END must be <= START.
530 If COUNT is zero, do anything you please; run rogue, for all I care.
531
532 If END is zero, use BEGV or ZV instead, as appropriate for the
533 direction indicated by COUNT.
ffd56f97
JB
534
535 If we find COUNT instances, set *SHORTAGE to zero, and return the
a9f2a45f 536 position past the COUNTth match. Note that for reverse motion
5bfe95c9 537 this is not the same as the usual convention for Emacs motion commands.
ffd56f97 538
9169c321
JB
539 If we don't find COUNT instances before reaching END, set *SHORTAGE
540 to the number of TARGETs left unfound, and return END.
ffd56f97 541
087a5f81
RS
542 If ALLOW_QUIT is non-zero, set immediate_quit. That's good to do
543 except when inside redisplay. */
544
dfcf069d 545int
9169c321
JB
546scan_buffer (target, start, end, count, shortage, allow_quit)
547 register int target;
548 int start, end;
549 int count;
550 int *shortage;
087a5f81 551 int allow_quit;
ca1d1d23 552{
9169c321 553 struct region_cache *newline_cache;
177c0ea7 554 int direction;
ffd56f97 555
9169c321
JB
556 if (count > 0)
557 {
558 direction = 1;
559 if (! end) end = ZV;
560 }
561 else
562 {
563 direction = -1;
564 if (! end) end = BEGV;
565 }
ffd56f97 566
9169c321
JB
567 newline_cache_on_off (current_buffer);
568 newline_cache = current_buffer->newline_cache;
ca1d1d23
JB
569
570 if (shortage != 0)
571 *shortage = 0;
572
087a5f81 573 immediate_quit = allow_quit;
ca1d1d23 574
ffd56f97 575 if (count > 0)
9169c321 576 while (start != end)
ca1d1d23 577 {
9169c321
JB
578 /* Our innermost scanning loop is very simple; it doesn't know
579 about gaps, buffer ends, or the newline cache. ceiling is
580 the position of the last character before the next such
581 obstacle --- the last character the dumb search loop should
582 examine. */
fa8ed3e0
RS
583 int ceiling_byte = CHAR_TO_BYTE (end) - 1;
584 int start_byte = CHAR_TO_BYTE (start);
67ce527d 585 int tem;
9169c321
JB
586
587 /* If we're looking for a newline, consult the newline cache
588 to see where we can avoid some scanning. */
589 if (target == '\n' && newline_cache)
590 {
591 int next_change;
592 immediate_quit = 0;
593 while (region_cache_forward
fa8ed3e0
RS
594 (current_buffer, newline_cache, start_byte, &next_change))
595 start_byte = next_change;
cbe0db0d 596 immediate_quit = allow_quit;
9169c321 597
fa8ed3e0
RS
598 /* START should never be after END. */
599 if (start_byte > ceiling_byte)
600 start_byte = ceiling_byte;
9169c321
JB
601
602 /* Now the text after start is an unknown region, and
603 next_change is the position of the next known region. */
fa8ed3e0 604 ceiling_byte = min (next_change - 1, ceiling_byte);
9169c321
JB
605 }
606
607 /* The dumb loop can only scan text stored in contiguous
608 bytes. BUFFER_CEILING_OF returns the last character
609 position that is contiguous, so the ceiling is the
610 position after that. */
67ce527d
KH
611 tem = BUFFER_CEILING_OF (start_byte);
612 ceiling_byte = min (tem, ceiling_byte);
9169c321
JB
613
614 {
177c0ea7 615 /* The termination address of the dumb loop. */
fa8ed3e0
RS
616 register unsigned char *ceiling_addr
617 = BYTE_POS_ADDR (ceiling_byte) + 1;
618 register unsigned char *cursor
619 = BYTE_POS_ADDR (start_byte);
9169c321
JB
620 unsigned char *base = cursor;
621
622 while (cursor < ceiling_addr)
623 {
624 unsigned char *scan_start = cursor;
625
626 /* The dumb loop. */
627 while (*cursor != target && ++cursor < ceiling_addr)
628 ;
629
630 /* If we're looking for newlines, cache the fact that
631 the region from start to cursor is free of them. */
632 if (target == '\n' && newline_cache)
633 know_region_cache (current_buffer, newline_cache,
fa8ed3e0
RS
634 start_byte + scan_start - base,
635 start_byte + cursor - base);
9169c321
JB
636
637 /* Did we find the target character? */
638 if (cursor < ceiling_addr)
639 {
640 if (--count == 0)
641 {
642 immediate_quit = 0;
fa8ed3e0 643 return BYTE_TO_CHAR (start_byte + cursor - base + 1);
9169c321
JB
644 }
645 cursor++;
646 }
647 }
648
fa8ed3e0 649 start = BYTE_TO_CHAR (start_byte + cursor - base);
9169c321 650 }
ca1d1d23
JB
651 }
652 else
9169c321
JB
653 while (start > end)
654 {
655 /* The last character to check before the next obstacle. */
fa8ed3e0
RS
656 int ceiling_byte = CHAR_TO_BYTE (end);
657 int start_byte = CHAR_TO_BYTE (start);
67ce527d 658 int tem;
9169c321
JB
659
660 /* Consult the newline cache, if appropriate. */
661 if (target == '\n' && newline_cache)
662 {
663 int next_change;
664 immediate_quit = 0;
665 while (region_cache_backward
fa8ed3e0
RS
666 (current_buffer, newline_cache, start_byte, &next_change))
667 start_byte = next_change;
cbe0db0d 668 immediate_quit = allow_quit;
9169c321
JB
669
670 /* Start should never be at or before end. */
fa8ed3e0
RS
671 if (start_byte <= ceiling_byte)
672 start_byte = ceiling_byte + 1;
9169c321
JB
673
674 /* Now the text before start is an unknown region, and
675 next_change is the position of the next known region. */
fa8ed3e0 676 ceiling_byte = max (next_change, ceiling_byte);
9169c321
JB
677 }
678
679 /* Stop scanning before the gap. */
67ce527d
KH
680 tem = BUFFER_FLOOR_OF (start_byte - 1);
681 ceiling_byte = max (tem, ceiling_byte);
9169c321
JB
682
683 {
684 /* The termination address of the dumb loop. */
fa8ed3e0
RS
685 register unsigned char *ceiling_addr = BYTE_POS_ADDR (ceiling_byte);
686 register unsigned char *cursor = BYTE_POS_ADDR (start_byte - 1);
9169c321
JB
687 unsigned char *base = cursor;
688
689 while (cursor >= ceiling_addr)
690 {
691 unsigned char *scan_start = cursor;
692
693 while (*cursor != target && --cursor >= ceiling_addr)
694 ;
695
696 /* If we're looking for newlines, cache the fact that
697 the region from after the cursor to start is free of them. */
698 if (target == '\n' && newline_cache)
699 know_region_cache (current_buffer, newline_cache,
fa8ed3e0
RS
700 start_byte + cursor - base,
701 start_byte + scan_start - base);
9169c321
JB
702
703 /* Did we find the target character? */
704 if (cursor >= ceiling_addr)
705 {
706 if (++count >= 0)
707 {
708 immediate_quit = 0;
fa8ed3e0 709 return BYTE_TO_CHAR (start_byte + cursor - base);
9169c321
JB
710 }
711 cursor--;
712 }
713 }
714
fa8ed3e0 715 start = BYTE_TO_CHAR (start_byte + cursor - base);
9169c321
JB
716 }
717 }
718
ca1d1d23
JB
719 immediate_quit = 0;
720 if (shortage != 0)
ffd56f97 721 *shortage = count * direction;
9169c321 722 return start;
ca1d1d23 723}
fa8ed3e0
RS
724\f
725/* Search for COUNT instances of a line boundary, which means either a
726 newline or (if selective display enabled) a carriage return.
727 Start at START. If COUNT is negative, search backwards.
728
729 We report the resulting position by calling TEMP_SET_PT_BOTH.
730
731 If we find COUNT instances. we position after (always after,
732 even if scanning backwards) the COUNTth match, and return 0.
733
734 If we don't find COUNT instances before reaching the end of the
735 buffer (or the beginning, if scanning backwards), we return
736 the number of line boundaries left unfound, and position at
737 the limit we bumped up against.
738
739 If ALLOW_QUIT is non-zero, set immediate_quit. That's good to do
d5d57b92 740 except in special cases. */
ca1d1d23 741
63fa018d 742int
fa8ed3e0
RS
743scan_newline (start, start_byte, limit, limit_byte, count, allow_quit)
744 int start, start_byte;
745 int limit, limit_byte;
746 register int count;
747 int allow_quit;
63fa018d 748{
fa8ed3e0
RS
749 int direction = ((count > 0) ? 1 : -1);
750
751 register unsigned char *cursor;
752 unsigned char *base;
753
754 register int ceiling;
755 register unsigned char *ceiling_addr;
756
d5d57b92
RS
757 int old_immediate_quit = immediate_quit;
758
fa8ed3e0
RS
759 /* The code that follows is like scan_buffer
760 but checks for either newline or carriage return. */
761
d5d57b92
RS
762 if (allow_quit)
763 immediate_quit++;
fa8ed3e0
RS
764
765 start_byte = CHAR_TO_BYTE (start);
766
767 if (count > 0)
768 {
769 while (start_byte < limit_byte)
770 {
771 ceiling = BUFFER_CEILING_OF (start_byte);
772 ceiling = min (limit_byte - 1, ceiling);
773 ceiling_addr = BYTE_POS_ADDR (ceiling) + 1;
774 base = (cursor = BYTE_POS_ADDR (start_byte));
775 while (1)
776 {
777 while (*cursor != '\n' && ++cursor != ceiling_addr)
778 ;
779
780 if (cursor != ceiling_addr)
781 {
782 if (--count == 0)
783 {
d5d57b92 784 immediate_quit = old_immediate_quit;
fa8ed3e0
RS
785 start_byte = start_byte + cursor - base + 1;
786 start = BYTE_TO_CHAR (start_byte);
787 TEMP_SET_PT_BOTH (start, start_byte);
788 return 0;
789 }
790 else
791 if (++cursor == ceiling_addr)
792 break;
793 }
794 else
795 break;
796 }
797 start_byte += cursor - base;
798 }
799 }
800 else
801 {
fa8ed3e0
RS
802 while (start_byte > limit_byte)
803 {
804 ceiling = BUFFER_FLOOR_OF (start_byte - 1);
805 ceiling = max (limit_byte, ceiling);
806 ceiling_addr = BYTE_POS_ADDR (ceiling) - 1;
807 base = (cursor = BYTE_POS_ADDR (start_byte - 1) + 1);
808 while (1)
809 {
810 while (--cursor != ceiling_addr && *cursor != '\n')
811 ;
812
813 if (cursor != ceiling_addr)
814 {
815 if (++count == 0)
816 {
d5d57b92 817 immediate_quit = old_immediate_quit;
fa8ed3e0
RS
818 /* Return the position AFTER the match we found. */
819 start_byte = start_byte + cursor - base + 1;
820 start = BYTE_TO_CHAR (start_byte);
821 TEMP_SET_PT_BOTH (start, start_byte);
822 return 0;
823 }
824 }
825 else
826 break;
827 }
828 /* Here we add 1 to compensate for the last decrement
829 of CURSOR, which took it past the valid range. */
830 start_byte += cursor - base + 1;
831 }
832 }
833
834 TEMP_SET_PT_BOTH (limit, limit_byte);
d5d57b92 835 immediate_quit = old_immediate_quit;
fa8ed3e0
RS
836
837 return count * direction;
63fa018d
RS
838}
839
ca1d1d23 840int
fa8ed3e0 841find_next_newline_no_quit (from, cnt)
ca1d1d23
JB
842 register int from, cnt;
843{
fa8ed3e0 844 return scan_buffer ('\n', from, 0, cnt, (int *) 0, 0);
9169c321
JB
845}
846
9169c321
JB
847/* Like find_next_newline, but returns position before the newline,
848 not after, and only search up to TO. This isn't just
849 find_next_newline (...)-1, because you might hit TO. */
fa8ed3e0 850
9169c321
JB
851int
852find_before_next_newline (from, to, cnt)
cbe0db0d 853 int from, to, cnt;
9169c321
JB
854{
855 int shortage;
856 int pos = scan_buffer ('\n', from, to, cnt, &shortage, 1);
857
858 if (shortage == 0)
859 pos--;
177c0ea7 860
9169c321 861 return pos;
ca1d1d23
JB
862}
863\f
ca1d1d23
JB
864/* Subroutines of Lisp buffer search functions. */
865
866static Lisp_Object
b819a390 867search_command (string, bound, noerror, count, direction, RE, posix)
ca1d1d23
JB
868 Lisp_Object string, bound, noerror, count;
869 int direction;
870 int RE;
b819a390 871 int posix;
ca1d1d23
JB
872{
873 register int np;
9f43ad85 874 int lim, lim_byte;
ca1d1d23
JB
875 int n = direction;
876
877 if (!NILP (count))
878 {
b7826503 879 CHECK_NUMBER (count);
ca1d1d23
JB
880 n *= XINT (count);
881 }
882
b7826503 883 CHECK_STRING (string);
ca1d1d23 884 if (NILP (bound))
9f43ad85
RS
885 {
886 if (n > 0)
887 lim = ZV, lim_byte = ZV_BYTE;
888 else
889 lim = BEGV, lim_byte = BEGV_BYTE;
890 }
ca1d1d23
JB
891 else
892 {
b7826503 893 CHECK_NUMBER_COERCE_MARKER (bound);
ca1d1d23 894 lim = XINT (bound);
6ec8bbd2 895 if (n > 0 ? lim < PT : lim > PT)
ca1d1d23
JB
896 error ("Invalid search bound (wrong side of point)");
897 if (lim > ZV)
9f43ad85 898 lim = ZV, lim_byte = ZV_BYTE;
588d2fd5 899 else if (lim < BEGV)
9f43ad85 900 lim = BEGV, lim_byte = BEGV_BYTE;
588d2fd5
KH
901 else
902 lim_byte = CHAR_TO_BYTE (lim);
ca1d1d23
JB
903 }
904
9f43ad85 905 np = search_buffer (string, PT, PT_BYTE, lim, lim_byte, n, RE,
ca1d1d23 906 (!NILP (current_buffer->case_fold_search)
facdc750 907 ? current_buffer->case_canon_table
3135e9fd 908 : Qnil),
ca1d1d23 909 (!NILP (current_buffer->case_fold_search)
facdc750 910 ? current_buffer->case_eqv_table
3135e9fd 911 : Qnil),
b819a390 912 posix);
ca1d1d23
JB
913 if (np <= 0)
914 {
915 if (NILP (noerror))
916 return signal_failure (string);
917 if (!EQ (noerror, Qt))
918 {
919 if (lim < BEGV || lim > ZV)
920 abort ();
9f43ad85 921 SET_PT_BOTH (lim, lim_byte);
a5f217b8
RS
922 return Qnil;
923#if 0 /* This would be clean, but maybe programs depend on
924 a value of nil here. */
481399bf 925 np = lim;
a5f217b8 926#endif
ca1d1d23 927 }
481399bf
RS
928 else
929 return Qnil;
ca1d1d23
JB
930 }
931
932 if (np < BEGV || np > ZV)
933 abort ();
934
935 SET_PT (np);
936
937 return make_number (np);
938}
939\f
fa8ed3e0
RS
940/* Return 1 if REGEXP it matches just one constant string. */
941
b6d6a51c
KH
942static int
943trivial_regexp_p (regexp)
944 Lisp_Object regexp;
945{
d5db4077
KR
946 int len = SBYTES (regexp);
947 unsigned char *s = SDATA (regexp);
b6d6a51c
KH
948 while (--len >= 0)
949 {
950 switch (*s++)
951 {
952 case '.': case '*': case '+': case '?': case '[': case '^': case '$':
953 return 0;
954 case '\\':
955 if (--len < 0)
956 return 0;
957 switch (*s++)
958 {
959 case '|': case '(': case ')': case '`': case '\'': case 'b':
960 case 'B': case '<': case '>': case 'w': case 'W': case 's':
29f89fe7 961 case 'S': case '=': case '{': case '}': case '_':
5679531d 962 case 'c': case 'C': /* for categoryspec and notcategoryspec */
866f60fd 963 case '1': case '2': case '3': case '4': case '5':
b6d6a51c
KH
964 case '6': case '7': case '8': case '9':
965 return 0;
966 }
967 }
968 }
969 return 1;
970}
971
ca325161 972/* Search for the n'th occurrence of STRING in the current buffer,
ca1d1d23 973 starting at position POS and stopping at position LIM,
b819a390 974 treating STRING as a literal string if RE is false or as
ca1d1d23
JB
975 a regular expression if RE is true.
976
977 If N is positive, searching is forward and LIM must be greater than POS.
978 If N is negative, searching is backward and LIM must be less than POS.
979
facdc750 980 Returns -x if x occurrences remain to be found (x > 0),
ca1d1d23 981 or else the position at the beginning of the Nth occurrence
b819a390
RS
982 (if searching backward) or the end (if searching forward).
983
984 POSIX is nonzero if we want full backtracking (POSIX style)
985 for this pattern. 0 means backtrack only enough to get a valid match. */
ca1d1d23 986
aff2ce94
RS
987#define TRANSLATE(out, trt, d) \
988do \
989 { \
990 if (! NILP (trt)) \
991 { \
992 Lisp_Object temp; \
993 temp = Faref (trt, make_number (d)); \
994 if (INTEGERP (temp)) \
995 out = XINT (temp); \
996 else \
997 out = d; \
998 } \
999 else \
1000 out = d; \
1001 } \
1002while (0)
facdc750 1003
b819a390 1004static int
9f43ad85
RS
1005search_buffer (string, pos, pos_byte, lim, lim_byte, n,
1006 RE, trt, inverse_trt, posix)
ca1d1d23
JB
1007 Lisp_Object string;
1008 int pos;
9f43ad85 1009 int pos_byte;
ca1d1d23 1010 int lim;
9f43ad85 1011 int lim_byte;
ca1d1d23
JB
1012 int n;
1013 int RE;
facdc750
RS
1014 Lisp_Object trt;
1015 Lisp_Object inverse_trt;
b819a390 1016 int posix;
ca1d1d23 1017{
d5db4077
KR
1018 int len = SCHARS (string);
1019 int len_byte = SBYTES (string);
facdc750 1020 register int i;
ca1d1d23 1021
7074fde6
FP
1022 if (running_asynch_code)
1023 save_search_regs ();
1024
a7e4cdde 1025 /* Searching 0 times means don't move. */
ca1d1d23 1026 /* Null string is found at starting position. */
a7e4cdde 1027 if (len == 0 || n == 0)
ca325161 1028 {
0353b28f 1029 set_search_regs (pos_byte, 0);
ca325161
RS
1030 return pos;
1031 }
3f57a499 1032
41a33295 1033 if (RE && !(trivial_regexp_p (string) && NILP (Vsearch_spaces_regexp)))
ca1d1d23 1034 {
facdc750
RS
1035 unsigned char *p1, *p2;
1036 int s1, s2;
487282dc
KH
1037 struct re_pattern_buffer *bufp;
1038
0c8533c6
RS
1039 bufp = compile_pattern (string, &search_regs, trt, posix,
1040 !NILP (current_buffer->enable_multibyte_characters));
ca1d1d23 1041
ca1d1d23
JB
1042 immediate_quit = 1; /* Quit immediately if user types ^G,
1043 because letting this function finish
1044 can take too long. */
1045 QUIT; /* Do a pending quit right away,
1046 to avoid paradoxical behavior */
1047 /* Get pointers and sizes of the two strings
1048 that make up the visible portion of the buffer. */
1049
1050 p1 = BEGV_ADDR;
fa8ed3e0 1051 s1 = GPT_BYTE - BEGV_BYTE;
ca1d1d23 1052 p2 = GAP_END_ADDR;
fa8ed3e0 1053 s2 = ZV_BYTE - GPT_BYTE;
ca1d1d23
JB
1054 if (s1 < 0)
1055 {
1056 p2 = p1;
fa8ed3e0 1057 s2 = ZV_BYTE - BEGV_BYTE;
ca1d1d23
JB
1058 s1 = 0;
1059 }
1060 if (s2 < 0)
1061 {
fa8ed3e0 1062 s1 = ZV_BYTE - BEGV_BYTE;
ca1d1d23
JB
1063 s2 = 0;
1064 }
8bb43c28 1065 re_match_object = Qnil;
177c0ea7 1066
ca1d1d23
JB
1067 while (n < 0)
1068 {
42db823b 1069 int val;
487282dc 1070 val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
4996330b
KH
1071 pos_byte - BEGV_BYTE, lim_byte - pos_byte,
1072 &search_regs,
42db823b 1073 /* Don't allow match past current point */
4996330b 1074 pos_byte - BEGV_BYTE);
ca1d1d23 1075 if (val == -2)
b6d6a51c
KH
1076 {
1077 matcher_overflow ();
1078 }
ca1d1d23
JB
1079 if (val >= 0)
1080 {
26aff150 1081 pos_byte = search_regs.start[0] + BEGV_BYTE;
4746118a 1082 for (i = 0; i < search_regs.num_regs; i++)
ca1d1d23
JB
1083 if (search_regs.start[i] >= 0)
1084 {
fa8ed3e0
RS
1085 search_regs.start[i]
1086 = BYTE_TO_CHAR (search_regs.start[i] + BEGV_BYTE);
1087 search_regs.end[i]
1088 = BYTE_TO_CHAR (search_regs.end[i] + BEGV_BYTE);
ca1d1d23 1089 }
a3668d92 1090 XSETBUFFER (last_thing_searched, current_buffer);
ca1d1d23
JB
1091 /* Set pos to the new position. */
1092 pos = search_regs.start[0];
1093 }
1094 else
1095 {
1096 immediate_quit = 0;
1097 return (n);
1098 }
1099 n++;
1100 }
1101 while (n > 0)
1102 {
42db823b 1103 int val;
487282dc 1104 val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
4996330b
KH
1105 pos_byte - BEGV_BYTE, lim_byte - pos_byte,
1106 &search_regs,
1107 lim_byte - BEGV_BYTE);
ca1d1d23 1108 if (val == -2)
b6d6a51c
KH
1109 {
1110 matcher_overflow ();
1111 }
ca1d1d23
JB
1112 if (val >= 0)
1113 {
26aff150 1114 pos_byte = search_regs.end[0] + BEGV_BYTE;
4746118a 1115 for (i = 0; i < search_regs.num_regs; i++)
ca1d1d23
JB
1116 if (search_regs.start[i] >= 0)
1117 {
fa8ed3e0
RS
1118 search_regs.start[i]
1119 = BYTE_TO_CHAR (search_regs.start[i] + BEGV_BYTE);
1120 search_regs.end[i]
1121 = BYTE_TO_CHAR (search_regs.end[i] + BEGV_BYTE);
ca1d1d23 1122 }
a3668d92 1123 XSETBUFFER (last_thing_searched, current_buffer);
ca1d1d23
JB
1124 pos = search_regs.end[0];
1125 }
1126 else
1127 {
1128 immediate_quit = 0;
1129 return (0 - n);
1130 }
1131 n--;
1132 }
1133 immediate_quit = 0;
1134 return (pos);
1135 }
1136 else /* non-RE case */
1137 {
facdc750
RS
1138 unsigned char *raw_pattern, *pat;
1139 int raw_pattern_size;
1140 int raw_pattern_size_byte;
1141 unsigned char *patbuf;
1142 int multibyte = !NILP (current_buffer->enable_multibyte_characters);
a967ed62 1143 unsigned char *base_pat;
49e44e81
KH
1144 /* Set to positive if we find a non-ASCII char that need
1145 translation. Otherwise set to zero later. */
1146 int char_base = -1;
040272ce 1147 int boyer_moore_ok = 1;
facdc750
RS
1148
1149 /* MULTIBYTE says whether the text to be searched is multibyte.
1150 We must convert PATTERN to match that, or we will not really
1151 find things right. */
1152
1153 if (multibyte == STRING_MULTIBYTE (string))
1154 {
d5db4077
KR
1155 raw_pattern = (unsigned char *) SDATA (string);
1156 raw_pattern_size = SCHARS (string);
1157 raw_pattern_size_byte = SBYTES (string);
facdc750
RS
1158 }
1159 else if (multibyte)
1160 {
d5db4077 1161 raw_pattern_size = SCHARS (string);
facdc750 1162 raw_pattern_size_byte
d5db4077 1163 = count_size_as_multibyte (SDATA (string),
facdc750 1164 raw_pattern_size);
7276d3d8 1165 raw_pattern = (unsigned char *) alloca (raw_pattern_size_byte + 1);
d5db4077
KR
1166 copy_text (SDATA (string), raw_pattern,
1167 SCHARS (string), 0, 1);
facdc750
RS
1168 }
1169 else
1170 {
1171 /* Converting multibyte to single-byte.
1172
1173 ??? Perhaps this conversion should be done in a special way
1174 by subtracting nonascii-insert-offset from each non-ASCII char,
1175 so that only the multibyte chars which really correspond to
1176 the chosen single-byte character set can possibly match. */
d5db4077
KR
1177 raw_pattern_size = SCHARS (string);
1178 raw_pattern_size_byte = SCHARS (string);
7276d3d8 1179 raw_pattern = (unsigned char *) alloca (raw_pattern_size + 1);
d5db4077
KR
1180 copy_text (SDATA (string), raw_pattern,
1181 SBYTES (string), 1, 0);
facdc750
RS
1182 }
1183
1184 /* Copy and optionally translate the pattern. */
1185 len = raw_pattern_size;
1186 len_byte = raw_pattern_size_byte;
f5f7578b 1187 patbuf = (unsigned char *) alloca (len * MAX_MULTIBYTE_LENGTH);
facdc750
RS
1188 pat = patbuf;
1189 base_pat = raw_pattern;
1190 if (multibyte)
1191 {
a17ae96a
KH
1192 /* Fill patbuf by translated characters in STRING while
1193 checking if we can use boyer-moore search. If TRT is
1194 non-nil, we can use boyer-moore search only if TRT can be
1195 represented by the byte array of 256 elements. For that,
1196 all non-ASCII case-equivalents of all case-senstive
1197 characters in STRING must belong to the same charset and
1198 row. */
1199
facdc750
RS
1200 while (--len >= 0)
1201 {
a17ae96a 1202 unsigned char str_base[MAX_MULTIBYTE_LENGTH], *str;
aff2ce94 1203 int c, translated, inverse;
a17ae96a 1204 int in_charlen, charlen;
facdc750
RS
1205
1206 /* If we got here and the RE flag is set, it's because we're
1207 dealing with a regexp known to be trivial, so the backslash
1208 just quotes the next character. */
1209 if (RE && *base_pat == '\\')
1210 {
1211 len--;
62221f22 1212 raw_pattern_size--;
facdc750
RS
1213 len_byte--;
1214 base_pat++;
1215 }
1216
1217 c = STRING_CHAR_AND_LENGTH (base_pat, len_byte, in_charlen);
040272ce 1218
a17ae96a 1219 if (NILP (trt))
facdc750 1220 {
a17ae96a
KH
1221 str = base_pat;
1222 charlen = in_charlen;
1223 }
1224 else
1225 {
1226 /* Translate the character. */
1227 TRANSLATE (translated, trt, c);
1228 charlen = CHAR_STRING (translated, str_base);
1229 str = str_base;
1230
1231 /* Check if C has any other case-equivalents. */
1232 TRANSLATE (inverse, inverse_trt, c);
1233 /* If so, check if we can use boyer-moore. */
1234 if (c != inverse && boyer_moore_ok)
1235 {
1236 /* Check if all equivalents belong to the same
1237 group of characters. Note that the check of C
49e44e81
KH
1238 itself is done by the last iteration. */
1239 int this_char_base = -1;
1240
1241 while (boyer_moore_ok)
a17ae96a 1242 {
49e44e81 1243 if (ASCII_BYTE_P (inverse))
a17ae96a 1244 {
49e44e81
KH
1245 if (this_char_base > 0)
1246 boyer_moore_ok = 0;
1247 else
a17ae96a 1248 {
49e44e81
KH
1249 this_char_base = 0;
1250 if (char_base < 0)
1251 char_base = this_char_base;
a17ae96a
KH
1252 }
1253 }
49e44e81
KH
1254 else if (CHAR_BYTE8_P (inverse))
1255 /* Boyer-moore search can't handle a
1256 translation of an eight-bit
1257 character. */
1258 boyer_moore_ok = 0;
1259 else if (this_char_base < 0)
1260 {
1261 this_char_base = inverse & ~0x3F;
1262 if (char_base < 0)
1263 char_base = this_char_base;
1264 else if (char_base > 0
1265 && this_char_base != char_base)
1266 boyer_moore_ok = 0;
1267 }
1268 else if ((inverse & ~0x3F) != this_char_base)
1269 boyer_moore_ok = 0;
a17ae96a
KH
1270 if (c == inverse)
1271 break;
1272 TRANSLATE (inverse, inverse_trt, inverse);
1273 }
1274 }
aff2ce94 1275 }
49e44e81
KH
1276 if (char_base < 0)
1277 char_base = 0;
facdc750
RS
1278
1279 /* Store this character into the translated pattern. */
a17ae96a
KH
1280 bcopy (str, pat, charlen);
1281 pat += charlen;
facdc750
RS
1282 base_pat += in_charlen;
1283 len_byte -= in_charlen;
1284 }
1285 }
1286 else
1287 {
040272ce 1288 /* Unibyte buffer. */
a17ae96a 1289 char_base = 0;
facdc750
RS
1290 while (--len >= 0)
1291 {
040272ce 1292 int c, translated;
facdc750
RS
1293
1294 /* If we got here and the RE flag is set, it's because we're
1295 dealing with a regexp known to be trivial, so the backslash
1296 just quotes the next character. */
1297 if (RE && *base_pat == '\\')
1298 {
1299 len--;
0190922f 1300 raw_pattern_size--;
facdc750
RS
1301 base_pat++;
1302 }
1303 c = *base_pat++;
aff2ce94 1304 TRANSLATE (translated, trt, c);
facdc750
RS
1305 *pat++ = translated;
1306 }
1307 }
1308
1309 len_byte = pat - patbuf;
1310 len = raw_pattern_size;
1311 pat = base_pat = patbuf;
1312
040272ce 1313 if (boyer_moore_ok)
facdc750 1314 return boyer_moore (n, pat, len, len_byte, trt, inverse_trt,
aff2ce94 1315 pos, pos_byte, lim, lim_byte,
a17ae96a 1316 char_base);
facdc750
RS
1317 else
1318 return simple_search (n, pat, len, len_byte, trt,
1319 pos, pos_byte, lim, lim_byte);
1320 }
1321}
1322\f
1323/* Do a simple string search N times for the string PAT,
1324 whose length is LEN/LEN_BYTE,
1325 from buffer position POS/POS_BYTE until LIM/LIM_BYTE.
1326 TRT is the translation table.
f8bd51c4 1327
facdc750
RS
1328 Return the character position where the match is found.
1329 Otherwise, if M matches remained to be found, return -M.
f8bd51c4 1330
facdc750
RS
1331 This kind of search works regardless of what is in PAT and
1332 regardless of what is in TRT. It is used in cases where
1333 boyer_moore cannot work. */
1334
1335static int
1336simple_search (n, pat, len, len_byte, trt, pos, pos_byte, lim, lim_byte)
1337 int n;
1338 unsigned char *pat;
1339 int len, len_byte;
1340 Lisp_Object trt;
1341 int pos, pos_byte;
1342 int lim, lim_byte;
1343{
1344 int multibyte = ! NILP (current_buffer->enable_multibyte_characters);
ab228c24 1345 int forward = n > 0;
49e44e81
KH
1346 /* Number of buffer bytes matched. Note that this may be different
1347 from len_byte in a multibyte buffer. */
1348 int match_byte;
facdc750
RS
1349
1350 if (lim > pos && multibyte)
1351 while (n > 0)
1352 {
1353 while (1)
f8bd51c4 1354 {
facdc750
RS
1355 /* Try matching at position POS. */
1356 int this_pos = pos;
1357 int this_pos_byte = pos_byte;
1358 int this_len = len;
1359 int this_len_byte = len_byte;
1360 unsigned char *p = pat;
1361 if (pos + len > lim)
1362 goto stop;
1363
1364 while (this_len > 0)
1365 {
1366 int charlen, buf_charlen;
ab228c24 1367 int pat_ch, buf_ch;
facdc750 1368
ab228c24 1369 pat_ch = STRING_CHAR_AND_LENGTH (p, this_len_byte, charlen);
facdc750
RS
1370 buf_ch = STRING_CHAR_AND_LENGTH (BYTE_POS_ADDR (this_pos_byte),
1371 ZV_BYTE - this_pos_byte,
1372 buf_charlen);
aff2ce94 1373 TRANSLATE (buf_ch, trt, buf_ch);
facdc750
RS
1374
1375 if (buf_ch != pat_ch)
1376 break;
ab228c24
RS
1377
1378 this_len_byte -= charlen;
1379 this_len--;
1380 p += charlen;
1381
1382 this_pos_byte += buf_charlen;
1383 this_pos++;
facdc750
RS
1384 }
1385
1386 if (this_len == 0)
1387 {
49e44e81 1388 match_byte = this_pos_byte - pos_byte;
facdc750 1389 pos += len;
49e44e81 1390 pos_byte += match_byte;
facdc750
RS
1391 break;
1392 }
1393
1394 INC_BOTH (pos, pos_byte);
f8bd51c4 1395 }
facdc750
RS
1396
1397 n--;
1398 }
1399 else if (lim > pos)
1400 while (n > 0)
1401 {
1402 while (1)
f8bd51c4 1403 {
facdc750
RS
1404 /* Try matching at position POS. */
1405 int this_pos = pos;
1406 int this_len = len;
1407 unsigned char *p = pat;
1408
1409 if (pos + len > lim)
1410 goto stop;
1411
1412 while (this_len > 0)
1413 {
1414 int pat_ch = *p++;
1415 int buf_ch = FETCH_BYTE (this_pos);
aff2ce94 1416 TRANSLATE (buf_ch, trt, buf_ch);
facdc750
RS
1417
1418 if (buf_ch != pat_ch)
1419 break;
ab228c24
RS
1420
1421 this_len--;
1422 this_pos++;
facdc750
RS
1423 }
1424
1425 if (this_len == 0)
1426 {
49e44e81 1427 match_byte = len;
facdc750
RS
1428 pos += len;
1429 break;
1430 }
1431
1432 pos++;
f8bd51c4 1433 }
facdc750
RS
1434
1435 n--;
1436 }
1437 /* Backwards search. */
1438 else if (lim < pos && multibyte)
1439 while (n < 0)
1440 {
1441 while (1)
f8bd51c4 1442 {
facdc750
RS
1443 /* Try matching at position POS. */
1444 int this_pos = pos - len;
130b729c 1445 int this_pos_byte;
facdc750
RS
1446 int this_len = len;
1447 int this_len_byte = len_byte;
1448 unsigned char *p = pat;
1449
1450 if (pos - len < lim)
1451 goto stop;
130b729c 1452 this_pos_byte = CHAR_TO_BYTE (this_pos);
49e44e81 1453 match_byte = pos_byte - this_pos_byte;
facdc750
RS
1454
1455 while (this_len > 0)
1456 {
1457 int charlen, buf_charlen;
ab228c24 1458 int pat_ch, buf_ch;
facdc750 1459
ab228c24 1460 pat_ch = STRING_CHAR_AND_LENGTH (p, this_len_byte, charlen);
facdc750
RS
1461 buf_ch = STRING_CHAR_AND_LENGTH (BYTE_POS_ADDR (this_pos_byte),
1462 ZV_BYTE - this_pos_byte,
1463 buf_charlen);
aff2ce94 1464 TRANSLATE (buf_ch, trt, buf_ch);
facdc750
RS
1465
1466 if (buf_ch != pat_ch)
1467 break;
ab228c24
RS
1468
1469 this_len_byte -= charlen;
1470 this_len--;
1471 p += charlen;
1472 this_pos_byte += buf_charlen;
1473 this_pos++;
facdc750
RS
1474 }
1475
1476 if (this_len == 0)
1477 {
1478 pos -= len;
49e44e81 1479 pos_byte -= match_byte;
facdc750
RS
1480 break;
1481 }
1482
1483 DEC_BOTH (pos, pos_byte);
f8bd51c4
KH
1484 }
1485
facdc750
RS
1486 n++;
1487 }
1488 else if (lim < pos)
1489 while (n < 0)
1490 {
1491 while (1)
b6d6a51c 1492 {
facdc750
RS
1493 /* Try matching at position POS. */
1494 int this_pos = pos - len;
1495 int this_len = len;
1496 unsigned char *p = pat;
1497
1498 if (pos - len < lim)
1499 goto stop;
1500
1501 while (this_len > 0)
1502 {
1503 int pat_ch = *p++;
1504 int buf_ch = FETCH_BYTE (this_pos);
aff2ce94 1505 TRANSLATE (buf_ch, trt, buf_ch);
facdc750
RS
1506
1507 if (buf_ch != pat_ch)
1508 break;
ab228c24
RS
1509 this_len--;
1510 this_pos++;
facdc750
RS
1511 }
1512
1513 if (this_len == 0)
b6d6a51c 1514 {
49e44e81 1515 match_byte = len;
facdc750
RS
1516 pos -= len;
1517 break;
b6d6a51c 1518 }
facdc750
RS
1519
1520 pos--;
b6d6a51c 1521 }
facdc750
RS
1522
1523 n++;
b6d6a51c 1524 }
facdc750
RS
1525
1526 stop:
1527 if (n == 0)
aff2ce94 1528 {
ab228c24 1529 if (forward)
49e44e81 1530 set_search_regs ((multibyte ? pos_byte : pos) - match_byte, match_byte);
ab228c24 1531 else
49e44e81 1532 set_search_regs (multibyte ? pos_byte : pos, match_byte);
aff2ce94
RS
1533
1534 return pos;
1535 }
facdc750
RS
1536 else if (n > 0)
1537 return -n;
1538 else
1539 return n;
1540}
1541\f
0190922f 1542/* Do Boyer-Moore search N times for the string BASE_PAT,
facdc750
RS
1543 whose length is LEN/LEN_BYTE,
1544 from buffer position POS/POS_BYTE until LIM/LIM_BYTE.
1545 DIRECTION says which direction we search in.
1546 TRT and INVERSE_TRT are translation tables.
0190922f 1547 Characters in PAT are already translated by TRT.
facdc750 1548
0190922f
KH
1549 This kind of search works if all the characters in BASE_PAT that
1550 have nontrivial translation are the same aside from the last byte.
1551 This makes it possible to translate just the last byte of a
1552 character, and do so after just a simple test of the context.
a17ae96a 1553 CHAR_BASE is nonzero iff there is such a non-ASCII character.
facdc750
RS
1554
1555 If that criterion is not satisfied, do not call this function. */
1556
1557static int
1558boyer_moore (n, base_pat, len, len_byte, trt, inverse_trt,
a17ae96a 1559 pos, pos_byte, lim, lim_byte, char_base)
facdc750
RS
1560 int n;
1561 unsigned char *base_pat;
1562 int len, len_byte;
1563 Lisp_Object trt;
1564 Lisp_Object inverse_trt;
1565 int pos, pos_byte;
1566 int lim, lim_byte;
a17ae96a 1567 int char_base;
facdc750
RS
1568{
1569 int direction = ((n > 0) ? 1 : -1);
1570 register int dirlen;
a968f437 1571 int infinity, limit, stride_for_teases = 0;
facdc750
RS
1572 register int *BM_tab;
1573 int *BM_tab_base;
177c0ea7 1574 register unsigned char *cursor, *p_limit;
facdc750 1575 register int i, j;
cb6792d2 1576 unsigned char *pat, *pat_end;
facdc750
RS
1577 int multibyte = ! NILP (current_buffer->enable_multibyte_characters);
1578
1579 unsigned char simple_translate[0400];
0190922f 1580 /* These are set to the preceding bytes of a byte to be translated
49e44e81 1581 if char_base is nonzero. As the maximum byte length of a
a17ae96a 1582 multibyte character is 5, we have to check at most four previous
0190922f
KH
1583 bytes. */
1584 int translate_prev_byte1 = 0;
1585 int translate_prev_byte2 = 0;
1586 int translate_prev_byte3 = 0;
a17ae96a 1587 int translate_prev_byte4 = 0;
facdc750
RS
1588
1589#ifdef C_ALLOCA
1590 int BM_tab_space[0400];
1591 BM_tab = &BM_tab_space[0];
1592#else
1593 BM_tab = (int *) alloca (0400 * sizeof (int));
1594#endif
1595 /* The general approach is that we are going to maintain that we know */
1596 /* the first (closest to the present position, in whatever direction */
1597 /* we're searching) character that could possibly be the last */
1598 /* (furthest from present position) character of a valid match. We */
1599 /* advance the state of our knowledge by looking at that character */
1600 /* and seeing whether it indeed matches the last character of the */
1601 /* pattern. If it does, we take a closer look. If it does not, we */
1602 /* move our pointer (to putative last characters) as far as is */
1603 /* logically possible. This amount of movement, which I call a */
1604 /* stride, will be the length of the pattern if the actual character */
1605 /* appears nowhere in the pattern, otherwise it will be the distance */
1606 /* from the last occurrence of that character to the end of the */
1607 /* pattern. */
1608 /* As a coding trick, an enormous stride is coded into the table for */
1609 /* characters that match the last character. This allows use of only */
1610 /* a single test, a test for having gone past the end of the */
1611 /* permissible match region, to test for both possible matches (when */
1612 /* the stride goes past the end immediately) and failure to */
177c0ea7 1613 /* match (where you get nudged past the end one stride at a time). */
facdc750
RS
1614
1615 /* Here we make a "mickey mouse" BM table. The stride of the search */
1616 /* is determined only by the last character of the putative match. */
1617 /* If that character does not match, we will stride the proper */
1618 /* distance to propose a match that superimposes it on the last */
1619 /* instance of a character that matches it (per trt), or misses */
177c0ea7 1620 /* it entirely if there is none. */
facdc750
RS
1621
1622 dirlen = len_byte * direction;
1623 infinity = dirlen - (lim_byte + pos_byte + len_byte + len_byte) * direction;
cb6792d2
RS
1624
1625 /* Record position after the end of the pattern. */
1626 pat_end = base_pat + len_byte;
1627 /* BASE_PAT points to a character that we start scanning from.
1628 It is the first character in a forward search,
1629 the last character in a backward search. */
facdc750 1630 if (direction < 0)
cb6792d2
RS
1631 base_pat = pat_end - 1;
1632
facdc750
RS
1633 BM_tab_base = BM_tab;
1634 BM_tab += 0400;
1635 j = dirlen; /* to get it in a register */
1636 /* A character that does not appear in the pattern induces a */
1637 /* stride equal to the pattern length. */
1638 while (BM_tab_base != BM_tab)
1639 {
1640 *--BM_tab = j;
1641 *--BM_tab = j;
1642 *--BM_tab = j;
1643 *--BM_tab = j;
1644 }
1645
1646 /* We use this for translation, instead of TRT itself.
1647 We fill this in to handle the characters that actually
1648 occur in the pattern. Others don't matter anyway! */
1649 bzero (simple_translate, sizeof simple_translate);
1650 for (i = 0; i < 0400; i++)
1651 simple_translate[i] = i;
1652
a17ae96a 1653 if (char_base)
0190922f 1654 {
a17ae96a 1655 /* Setup translate_prev_byte1/2/3/4 from CHAR_BASE. Only a
0190922f 1656 byte following them are the target of translation. */
0190922f 1657 unsigned char str[MAX_MULTIBYTE_LENGTH];
a17ae96a 1658 int len = CHAR_STRING (char_base, str);
0190922f
KH
1659
1660 translate_prev_byte1 = str[len - 2];
1661 if (len > 2)
1662 {
1663 translate_prev_byte2 = str[len - 3];
1664 if (len > 3)
a17ae96a
KH
1665 {
1666 translate_prev_byte3 = str[len - 4];
1667 if (len > 4)
1668 translate_prev_byte4 = str[len - 5];
1669 }
0190922f
KH
1670 }
1671 }
1672
facdc750
RS
1673 i = 0;
1674 while (i != infinity)
1675 {
cb6792d2 1676 unsigned char *ptr = base_pat + i;
facdc750
RS
1677 i += direction;
1678 if (i == dirlen)
1679 i = infinity;
1680 if (! NILP (trt))
ca1d1d23 1681 {
49e44e81
KH
1682 /* If the byte currently looking at is the last of a
1683 character to check case-equivalents, set CH to that
1684 character. An ASCII character and a non-ASCII character
1685 matching with CHAR_BASE are to be checked. */
a17ae96a
KH
1686 int ch = -1;
1687
1688 if (ASCII_BYTE_P (*ptr) || ! multibyte)
1689 ch = *ptr;
49e44e81 1690 else if (char_base
86dc6ccb 1691 && ((pat_end - ptr) == 1 || CHAR_HEAD_P (ptr[1])))
ca1d1d23 1692 {
49e44e81
KH
1693 unsigned char *charstart = ptr - 1;
1694
1695 while (! (CHAR_HEAD_P (*charstart)))
1696 charstart--;
1697 ch = STRING_CHAR (charstart, ptr - charstart + 1);
a17ae96a
KH
1698 if (char_base != (ch & ~0x3F))
1699 ch = -1;
ca1d1d23 1700 }
facdc750 1701
6786a107 1702 if (ch >= 0400)
49e44e81
KH
1703 j = (ch & 0x3F) | 0200;
1704 else
1705 j = *ptr;
1706
facdc750
RS
1707 if (i == infinity)
1708 stride_for_teases = BM_tab[j];
ab228c24 1709
facdc750
RS
1710 BM_tab[j] = dirlen - i;
1711 /* A translation table is accompanied by its inverse -- see */
177c0ea7 1712 /* comment following downcase_table for details */
a17ae96a 1713 if (ch >= 0)
ab228c24
RS
1714 {
1715 int starting_ch = ch;
49e44e81 1716 int starting_j = j;
a17ae96a 1717
ab228c24
RS
1718 while (1)
1719 {
1720 TRANSLATE (ch, inverse_trt, ch);
6786a107 1721 if (ch >= 0400)
49e44e81 1722 j = (ch & 0x3F) | 0200;
ab228c24 1723 else
a17ae96a 1724 j = ch;
ab228c24
RS
1725
1726 /* For all the characters that map into CH,
1727 set up simple_translate to map the last byte
1728 into STARTING_J. */
1729 simple_translate[j] = starting_j;
1730 if (ch == starting_ch)
1731 break;
1732 BM_tab[j] = dirlen - i;
1733 }
1734 }
facdc750
RS
1735 }
1736 else
1737 {
1738 j = *ptr;
1739
1740 if (i == infinity)
1741 stride_for_teases = BM_tab[j];
1742 BM_tab[j] = dirlen - i;
ca1d1d23 1743 }
facdc750
RS
1744 /* stride_for_teases tells how much to stride if we get a */
1745 /* match on the far character but are subsequently */
1746 /* disappointed, by recording what the stride would have been */
1747 /* for that character if the last character had been */
1748 /* different. */
1749 }
1750 infinity = dirlen - infinity;
1751 pos_byte += dirlen - ((direction > 0) ? direction : 0);
1752 /* loop invariant - POS_BYTE points at where last char (first
1753 char if reverse) of pattern would align in a possible match. */
1754 while (n != 0)
1755 {
1756 int tail_end;
1757 unsigned char *tail_end_ptr;
1758
1759 /* It's been reported that some (broken) compiler thinks that
1760 Boolean expressions in an arithmetic context are unsigned.
1761 Using an explicit ?1:0 prevents this. */
1762 if ((lim_byte - pos_byte - ((direction > 0) ? 1 : 0)) * direction
1763 < 0)
1764 return (n * (0 - direction));
1765 /* First we do the part we can by pointers (maybe nothing) */
1766 QUIT;
1767 pat = base_pat;
1768 limit = pos_byte - dirlen + direction;
67ce527d
KH
1769 if (direction > 0)
1770 {
1771 limit = BUFFER_CEILING_OF (limit);
1772 /* LIMIT is now the last (not beyond-last!) value POS_BYTE
1773 can take on without hitting edge of buffer or the gap. */
1774 limit = min (limit, pos_byte + 20000);
1775 limit = min (limit, lim_byte - 1);
1776 }
1777 else
1778 {
1779 limit = BUFFER_FLOOR_OF (limit);
1780 /* LIMIT is now the last (not beyond-last!) value POS_BYTE
1781 can take on without hitting edge of buffer or the gap. */
1782 limit = max (limit, pos_byte - 20000);
1783 limit = max (limit, lim_byte);
1784 }
facdc750
RS
1785 tail_end = BUFFER_CEILING_OF (pos_byte) + 1;
1786 tail_end_ptr = BYTE_POS_ADDR (tail_end);
1787
1788 if ((limit - pos_byte) * direction > 20)
ca1d1d23 1789 {
facdc750
RS
1790 unsigned char *p2;
1791
1792 p_limit = BYTE_POS_ADDR (limit);
1793 p2 = (cursor = BYTE_POS_ADDR (pos_byte));
1794 /* In this loop, pos + cursor - p2 is the surrogate for pos */
1795 while (1) /* use one cursor setting as long as i can */
ca1d1d23 1796 {
facdc750 1797 if (direction > 0) /* worth duplicating */
ca1d1d23 1798 {
facdc750
RS
1799 /* Use signed comparison if appropriate
1800 to make cursor+infinity sure to be > p_limit.
1801 Assuming that the buffer lies in a range of addresses
1802 that are all "positive" (as ints) or all "negative",
1803 either kind of comparison will work as long
1804 as we don't step by infinity. So pick the kind
1805 that works when we do step by infinity. */
1806 if ((EMACS_INT) (p_limit + infinity) > (EMACS_INT) p_limit)
1807 while ((EMACS_INT) cursor <= (EMACS_INT) p_limit)
1808 cursor += BM_tab[*cursor];
ca1d1d23 1809 else
facdc750
RS
1810 while ((EMACS_UINT) cursor <= (EMACS_UINT) p_limit)
1811 cursor += BM_tab[*cursor];
1812 }
1813 else
1814 {
1815 if ((EMACS_INT) (p_limit + infinity) < (EMACS_INT) p_limit)
1816 while ((EMACS_INT) cursor >= (EMACS_INT) p_limit)
1817 cursor += BM_tab[*cursor];
1818 else
1819 while ((EMACS_UINT) cursor >= (EMACS_UINT) p_limit)
1820 cursor += BM_tab[*cursor];
1821 }
ca1d1d23 1822/* If you are here, cursor is beyond the end of the searched region. */
facdc750
RS
1823/* This can happen if you match on the far character of the pattern, */
1824/* because the "stride" of that character is infinity, a number able */
1825/* to throw you well beyond the end of the search. It can also */
1826/* happen if you fail to match within the permitted region and would */
1827/* otherwise try a character beyond that region */
1828 if ((cursor - p_limit) * direction <= len_byte)
1829 break; /* a small overrun is genuine */
1830 cursor -= infinity; /* large overrun = hit */
1831 i = dirlen - direction;
1832 if (! NILP (trt))
1833 {
1834 while ((i -= direction) + direction != 0)
ca1d1d23 1835 {
facdc750
RS
1836 int ch;
1837 cursor -= direction;
1838 /* Translate only the last byte of a character. */
1839 if (! multibyte
1840 || ((cursor == tail_end_ptr
1841 || CHAR_HEAD_P (cursor[1]))
1842 && (CHAR_HEAD_P (cursor[0])
0190922f
KH
1843 /* Check if this is the last byte of
1844 a translable character. */
1845 || (translate_prev_byte1 == cursor[-1]
1846 && (CHAR_HEAD_P (translate_prev_byte1)
1847 || (translate_prev_byte2 == cursor[-2]
1848 && (CHAR_HEAD_P (translate_prev_byte2)
1849 || (translate_prev_byte3 == cursor[-3]))))))))
facdc750
RS
1850 ch = simple_translate[*cursor];
1851 else
1852 ch = *cursor;
1853 if (pat[i] != ch)
1854 break;
ca1d1d23 1855 }
facdc750
RS
1856 }
1857 else
1858 {
1859 while ((i -= direction) + direction != 0)
ca1d1d23 1860 {
facdc750
RS
1861 cursor -= direction;
1862 if (pat[i] != *cursor)
1863 break;
ca1d1d23 1864 }
facdc750
RS
1865 }
1866 cursor += dirlen - i - direction; /* fix cursor */
1867 if (i + direction == 0)
1868 {
1869 int position;
0c8533c6 1870
facdc750 1871 cursor -= direction;
1113d9db 1872
facdc750
RS
1873 position = pos_byte + cursor - p2 + ((direction > 0)
1874 ? 1 - len_byte : 0);
1875 set_search_regs (position, len_byte);
ca325161 1876
facdc750
RS
1877 if ((n -= direction) != 0)
1878 cursor += dirlen; /* to resume search */
ca1d1d23 1879 else
facdc750
RS
1880 return ((direction > 0)
1881 ? search_regs.end[0] : search_regs.start[0]);
ca1d1d23 1882 }
facdc750
RS
1883 else
1884 cursor += stride_for_teases; /* <sigh> we lose - */
ca1d1d23 1885 }
facdc750
RS
1886 pos_byte += cursor - p2;
1887 }
1888 else
1889 /* Now we'll pick up a clump that has to be done the hard */
1890 /* way because it covers a discontinuity */
1891 {
1892 limit = ((direction > 0)
1893 ? BUFFER_CEILING_OF (pos_byte - dirlen + 1)
1894 : BUFFER_FLOOR_OF (pos_byte - dirlen - 1));
1895 limit = ((direction > 0)
1896 ? min (limit + len_byte, lim_byte - 1)
1897 : max (limit - len_byte, lim_byte));
1898 /* LIMIT is now the last value POS_BYTE can have
1899 and still be valid for a possible match. */
1900 while (1)
ca1d1d23 1901 {
facdc750
RS
1902 /* This loop can be coded for space rather than */
1903 /* speed because it will usually run only once. */
1904 /* (the reach is at most len + 21, and typically */
177c0ea7 1905 /* does not exceed len) */
facdc750
RS
1906 while ((limit - pos_byte) * direction >= 0)
1907 pos_byte += BM_tab[FETCH_BYTE (pos_byte)];
1908 /* now run the same tests to distinguish going off the */
1909 /* end, a match or a phony match. */
1910 if ((pos_byte - limit) * direction <= len_byte)
1911 break; /* ran off the end */
1912 /* Found what might be a match.
1913 Set POS_BYTE back to last (first if reverse) pos. */
1914 pos_byte -= infinity;
1915 i = dirlen - direction;
1916 while ((i -= direction) + direction != 0)
ca1d1d23 1917 {
facdc750
RS
1918 int ch;
1919 unsigned char *ptr;
1920 pos_byte -= direction;
1921 ptr = BYTE_POS_ADDR (pos_byte);
1922 /* Translate only the last byte of a character. */
1923 if (! multibyte
1924 || ((ptr == tail_end_ptr
1925 || CHAR_HEAD_P (ptr[1]))
1926 && (CHAR_HEAD_P (ptr[0])
0190922f
KH
1927 /* Check if this is the last byte of a
1928 translable character. */
1929 || (translate_prev_byte1 == ptr[-1]
1930 && (CHAR_HEAD_P (translate_prev_byte1)
1931 || (translate_prev_byte2 == ptr[-2]
1932 && (CHAR_HEAD_P (translate_prev_byte2)
1933 || translate_prev_byte3 == ptr[-3])))))))
facdc750
RS
1934 ch = simple_translate[*ptr];
1935 else
1936 ch = *ptr;
1937 if (pat[i] != ch)
1938 break;
1939 }
1940 /* Above loop has moved POS_BYTE part or all the way
1941 back to the first pos (last pos if reverse).
1942 Set it once again at the last (first if reverse) char. */
1943 pos_byte += dirlen - i- direction;
1944 if (i + direction == 0)
1945 {
1946 int position;
1947 pos_byte -= direction;
1113d9db 1948
facdc750 1949 position = pos_byte + ((direction > 0) ? 1 - len_byte : 0);
0c8533c6 1950
facdc750 1951 set_search_regs (position, len_byte);
ca325161 1952
facdc750
RS
1953 if ((n -= direction) != 0)
1954 pos_byte += dirlen; /* to resume search */
ca1d1d23 1955 else
facdc750
RS
1956 return ((direction > 0)
1957 ? search_regs.end[0] : search_regs.start[0]);
ca1d1d23 1958 }
facdc750
RS
1959 else
1960 pos_byte += stride_for_teases;
1961 }
1962 }
1963 /* We have done one clump. Can we continue? */
1964 if ((lim_byte - pos_byte) * direction < 0)
1965 return ((0 - n) * direction);
ca1d1d23 1966 }
facdc750 1967 return BYTE_TO_CHAR (pos_byte);
ca1d1d23 1968}
ca325161 1969
fa8ed3e0 1970/* Record beginning BEG_BYTE and end BEG_BYTE + NBYTES
a7e4cdde
RS
1971 for the overall match just found in the current buffer.
1972 Also clear out the match data for registers 1 and up. */
ca325161
RS
1973
1974static void
fa8ed3e0
RS
1975set_search_regs (beg_byte, nbytes)
1976 int beg_byte, nbytes;
ca325161 1977{
a7e4cdde
RS
1978 int i;
1979
ca325161
RS
1980 /* Make sure we have registers in which to store
1981 the match position. */
1982 if (search_regs.num_regs == 0)
1983 {
2d4a771a
RS
1984 search_regs.start = (regoff_t *) xmalloc (2 * sizeof (regoff_t));
1985 search_regs.end = (regoff_t *) xmalloc (2 * sizeof (regoff_t));
487282dc 1986 search_regs.num_regs = 2;
ca325161
RS
1987 }
1988
a7e4cdde
RS
1989 /* Clear out the other registers. */
1990 for (i = 1; i < search_regs.num_regs; i++)
1991 {
1992 search_regs.start[i] = -1;
1993 search_regs.end[i] = -1;
1994 }
1995
fa8ed3e0
RS
1996 search_regs.start[0] = BYTE_TO_CHAR (beg_byte);
1997 search_regs.end[0] = BYTE_TO_CHAR (beg_byte + nbytes);
a3668d92 1998 XSETBUFFER (last_thing_searched, current_buffer);
ca325161 1999}
ca1d1d23
JB
2000\f
2001/* Given a string of words separated by word delimiters,
2002 compute a regexp that matches those exact words
2003 separated by arbitrary punctuation. */
2004
2005static Lisp_Object
2006wordify (string)
2007 Lisp_Object string;
2008{
2009 register unsigned char *p, *o;
0c8533c6 2010 register int i, i_byte, len, punct_count = 0, word_count = 0;
ca1d1d23 2011 Lisp_Object val;
0c8533c6
RS
2012 int prev_c = 0;
2013 int adjust;
ca1d1d23 2014
b7826503 2015 CHECK_STRING (string);
d5db4077
KR
2016 p = SDATA (string);
2017 len = SCHARS (string);
ca1d1d23 2018
0c8533c6
RS
2019 for (i = 0, i_byte = 0; i < len; )
2020 {
2021 int c;
177c0ea7 2022
93daa011 2023 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c, string, i, i_byte);
0c8533c6
RS
2024
2025 if (SYNTAX (c) != Sword)
2026 {
2027 punct_count++;
2028 if (i > 0 && SYNTAX (prev_c) == Sword)
2029 word_count++;
2030 }
ca1d1d23 2031
0c8533c6
RS
2032 prev_c = c;
2033 }
2034
2035 if (SYNTAX (prev_c) == Sword)
2036 word_count++;
2037 if (!word_count)
b07b65aa 2038 return empty_string;
0c8533c6
RS
2039
2040 adjust = - punct_count + 5 * (word_count - 1) + 4;
8a2df937
RS
2041 if (STRING_MULTIBYTE (string))
2042 val = make_uninit_multibyte_string (len + adjust,
d5db4077 2043 SBYTES (string)
8a2df937
RS
2044 + adjust);
2045 else
2046 val = make_uninit_string (len + adjust);
ca1d1d23 2047
d5db4077 2048 o = SDATA (val);
ca1d1d23
JB
2049 *o++ = '\\';
2050 *o++ = 'b';
1e9582d4 2051 prev_c = 0;
ca1d1d23 2052
1e9582d4
RS
2053 for (i = 0, i_byte = 0; i < len; )
2054 {
2055 int c;
2056 int i_byte_orig = i_byte;
177c0ea7 2057
93daa011 2058 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c, string, i, i_byte);
1e9582d4
RS
2059
2060 if (SYNTAX (c) == Sword)
2061 {
5d69fe10 2062 bcopy (SDATA (string) + i_byte_orig, o,
1e9582d4
RS
2063 i_byte - i_byte_orig);
2064 o += i_byte - i_byte_orig;
2065 }
2066 else if (i > 0 && SYNTAX (prev_c) == Sword && --word_count)
2067 {
2068 *o++ = '\\';
2069 *o++ = 'W';
2070 *o++ = '\\';
2071 *o++ = 'W';
2072 *o++ = '*';
2073 }
2074
2075 prev_c = c;
2076 }
ca1d1d23
JB
2077
2078 *o++ = '\\';
2079 *o++ = 'b';
2080
2081 return val;
2082}
2083\f
2084DEFUN ("search-backward", Fsearch_backward, Ssearch_backward, 1, 4,
8c1a1077
PJ
2085 "MSearch backward: ",
2086 doc: /* Search backward from point for STRING.
2087Set point to the beginning of the occurrence found, and return point.
2088An optional second argument bounds the search; it is a buffer position.
2089The match found must not extend before that position.
2090Optional third argument, if t, means if fail just return nil (no error).
2091 If not nil and not t, position at limit of search and return nil.
2092Optional fourth argument is repeat count--search for successive occurrences.
2093
2094Search case-sensitivity is determined by the value of the variable
2095`case-fold-search', which see.
2096
2097See also the functions `match-beginning', `match-end' and `replace-match'. */)
2098 (string, bound, noerror, count)
ca1d1d23
JB
2099 Lisp_Object string, bound, noerror, count;
2100{
b819a390 2101 return search_command (string, bound, noerror, count, -1, 0, 0);
ca1d1d23
JB
2102}
2103
6af43974 2104DEFUN ("search-forward", Fsearch_forward, Ssearch_forward, 1, 4, "MSearch: ",
8c1a1077
PJ
2105 doc: /* Search forward from point for STRING.
2106Set point to the end of the occurrence found, and return point.
2107An optional second argument bounds the search; it is a buffer position.
2108The match found must not extend after that position. nil is equivalent
2109 to (point-max).
2110Optional third argument, if t, means if fail just return nil (no error).
2111 If not nil and not t, move to limit of search and return nil.
2112Optional fourth argument is repeat count--search for successive occurrences.
2113
2114Search case-sensitivity is determined by the value of the variable
2115`case-fold-search', which see.
2116
2117See also the functions `match-beginning', `match-end' and `replace-match'. */)
2118 (string, bound, noerror, count)
ca1d1d23
JB
2119 Lisp_Object string, bound, noerror, count;
2120{
b819a390 2121 return search_command (string, bound, noerror, count, 1, 0, 0);
ca1d1d23
JB
2122}
2123
2124DEFUN ("word-search-backward", Fword_search_backward, Sword_search_backward, 1, 4,
8c1a1077
PJ
2125 "sWord search backward: ",
2126 doc: /* Search backward from point for STRING, ignoring differences in punctuation.
2127Set point to the beginning of the occurrence found, and return point.
2128An optional second argument bounds the search; it is a buffer position.
2129The match found must not extend before that position.
2130Optional third argument, if t, means if fail just return nil (no error).
2131 If not nil and not t, move to limit of search and return nil.
2132Optional fourth argument is repeat count--search for successive occurrences. */)
2133 (string, bound, noerror, count)
ca1d1d23
JB
2134 Lisp_Object string, bound, noerror, count;
2135{
b819a390 2136 return search_command (wordify (string), bound, noerror, count, -1, 1, 0);
ca1d1d23
JB
2137}
2138
2139DEFUN ("word-search-forward", Fword_search_forward, Sword_search_forward, 1, 4,
8c1a1077
PJ
2140 "sWord search: ",
2141 doc: /* Search forward from point for STRING, ignoring differences in punctuation.
2142Set point to the end of the occurrence found, and return point.
2143An optional second argument bounds the search; it is a buffer position.
2144The match found must not extend after that position.
2145Optional third argument, if t, means if fail just return nil (no error).
2146 If not nil and not t, move to limit of search and return nil.
2147Optional fourth argument is repeat count--search for successive occurrences. */)
2148 (string, bound, noerror, count)
ca1d1d23
JB
2149 Lisp_Object string, bound, noerror, count;
2150{
b819a390 2151 return search_command (wordify (string), bound, noerror, count, 1, 1, 0);
ca1d1d23
JB
2152}
2153
2154DEFUN ("re-search-backward", Fre_search_backward, Sre_search_backward, 1, 4,
8c1a1077
PJ
2155 "sRE search backward: ",
2156 doc: /* Search backward from point for match for regular expression REGEXP.
2157Set point to the beginning of the match, and return point.
2158The match found is the one starting last in the buffer
2159and yet ending before the origin of the search.
2160An optional second argument bounds the search; it is a buffer position.
2161The match found must start at or after that position.
2162Optional third argument, if t, means if fail just return nil (no error).
2163 If not nil and not t, move to limit of search and return nil.
2164Optional fourth argument is repeat count--search for successive occurrences.
2165See also the functions `match-beginning', `match-end', `match-string',
2166and `replace-match'. */)
2167 (regexp, bound, noerror, count)
19c0a730 2168 Lisp_Object regexp, bound, noerror, count;
ca1d1d23 2169{
b819a390 2170 return search_command (regexp, bound, noerror, count, -1, 1, 0);
ca1d1d23
JB
2171}
2172
2173DEFUN ("re-search-forward", Fre_search_forward, Sre_search_forward, 1, 4,
8c1a1077
PJ
2174 "sRE search: ",
2175 doc: /* Search forward from point for regular expression REGEXP.
2176Set point to the end of the occurrence found, and return point.
2177An optional second argument bounds the search; it is a buffer position.
2178The match found must not extend after that position.
2179Optional third argument, if t, means if fail just return nil (no error).
2180 If not nil and not t, move to limit of search and return nil.
2181Optional fourth argument is repeat count--search for successive occurrences.
2182See also the functions `match-beginning', `match-end', `match-string',
2183and `replace-match'. */)
2184 (regexp, bound, noerror, count)
19c0a730 2185 Lisp_Object regexp, bound, noerror, count;
ca1d1d23 2186{
b819a390
RS
2187 return search_command (regexp, bound, noerror, count, 1, 1, 0);
2188}
2189
2190DEFUN ("posix-search-backward", Fposix_search_backward, Sposix_search_backward, 1, 4,
8c1a1077
PJ
2191 "sPosix search backward: ",
2192 doc: /* Search backward from point for match for regular expression REGEXP.
2193Find the longest match in accord with Posix regular expression rules.
2194Set point to the beginning of the match, and return point.
2195The match found is the one starting last in the buffer
2196and yet ending before the origin of the search.
2197An optional second argument bounds the search; it is a buffer position.
2198The match found must start at or after that position.
2199Optional third argument, if t, means if fail just return nil (no error).
2200 If not nil and not t, move to limit of search and return nil.
2201Optional fourth argument is repeat count--search for successive occurrences.
2202See also the functions `match-beginning', `match-end', `match-string',
2203and `replace-match'. */)
2204 (regexp, bound, noerror, count)
b819a390
RS
2205 Lisp_Object regexp, bound, noerror, count;
2206{
2207 return search_command (regexp, bound, noerror, count, -1, 1, 1);
2208}
2209
2210DEFUN ("posix-search-forward", Fposix_search_forward, Sposix_search_forward, 1, 4,
8c1a1077
PJ
2211 "sPosix search: ",
2212 doc: /* Search forward from point for regular expression REGEXP.
2213Find the longest match in accord with Posix regular expression rules.
2214Set point to the end of the occurrence found, and return point.
2215An optional second argument bounds the search; it is a buffer position.
2216The match found must not extend after that position.
2217Optional third argument, if t, means if fail just return nil (no error).
2218 If not nil and not t, move to limit of search and return nil.
2219Optional fourth argument is repeat count--search for successive occurrences.
2220See also the functions `match-beginning', `match-end', `match-string',
2221and `replace-match'. */)
2222 (regexp, bound, noerror, count)
b819a390
RS
2223 Lisp_Object regexp, bound, noerror, count;
2224{
2225 return search_command (regexp, bound, noerror, count, 1, 1, 1);
ca1d1d23
JB
2226}
2227\f
d7a5ad5f 2228DEFUN ("replace-match", Freplace_match, Sreplace_match, 1, 5, 0,
8c1a1077 2229 doc: /* Replace text matched by last search with NEWTEXT.
4dd0c271
RS
2230Leave point at the end of the replacement text.
2231
8c1a1077
PJ
2232If second arg FIXEDCASE is non-nil, do not alter case of replacement text.
2233Otherwise maybe capitalize the whole text, or maybe just word initials,
2234based on the replaced text.
2235If the replaced text has only capital letters
2236and has at least one multiletter word, convert NEWTEXT to all caps.
4dd0c271
RS
2237Otherwise if all words are capitalized in the replaced text,
2238capitalize each word in NEWTEXT.
8c1a1077
PJ
2239
2240If third arg LITERAL is non-nil, insert NEWTEXT literally.
2241Otherwise treat `\\' as special:
2242 `\\&' in NEWTEXT means substitute original matched text.
2243 `\\N' means substitute what matched the Nth `\\(...\\)'.
2244 If Nth parens didn't match, substitute nothing.
2245 `\\\\' means insert one `\\'.
4dd0c271
RS
2246Case conversion does not apply to these substitutions.
2247
8c1a1077 2248FIXEDCASE and LITERAL are optional arguments.
8c1a1077
PJ
2249
2250The optional fourth argument STRING can be a string to modify.
2251This is meaningful when the previous match was done against STRING,
2252using `string-match'. When used this way, `replace-match'
2253creates and returns a new string made by copying STRING and replacing
2254the part of STRING that was matched.
2255
2256The optional fifth argument SUBEXP specifies a subexpression;
2257it says to replace just that subexpression with NEWTEXT,
2258rather than replacing the entire matched text.
2259This is, in a vague sense, the inverse of using `\\N' in NEWTEXT;
2260`\\N' copies subexp N into NEWTEXT, but using N as SUBEXP puts
2261NEWTEXT in place of subexp N.
2262This is useful only after a regular expression search or match,
2263since only regular expressions have distinguished subexpressions. */)
2264 (newtext, fixedcase, literal, string, subexp)
d7a5ad5f 2265 Lisp_Object newtext, fixedcase, literal, string, subexp;
ca1d1d23
JB
2266{
2267 enum { nochange, all_caps, cap_initial } case_action;
ac3b28b1 2268 register int pos, pos_byte;
ca1d1d23 2269 int some_multiletter_word;
97832bd0 2270 int some_lowercase;
73dc8771 2271 int some_uppercase;
208767c3 2272 int some_nonuppercase_initial;
ca1d1d23 2273 register int c, prevc;
d7a5ad5f 2274 int sub;
3e18eecf 2275 int opoint, newpoint;
ca1d1d23 2276
b7826503 2277 CHECK_STRING (newtext);
ca1d1d23 2278
080c45fd 2279 if (! NILP (string))
b7826503 2280 CHECK_STRING (string);
080c45fd 2281
ca1d1d23
JB
2282 case_action = nochange; /* We tried an initialization */
2283 /* but some C compilers blew it */
4746118a
JB
2284
2285 if (search_regs.num_regs <= 0)
d72cdbfc 2286 error ("`replace-match' called before any match found");
4746118a 2287
d7a5ad5f
RS
2288 if (NILP (subexp))
2289 sub = 0;
2290 else
2291 {
b7826503 2292 CHECK_NUMBER (subexp);
d7a5ad5f
RS
2293 sub = XINT (subexp);
2294 if (sub < 0 || sub >= search_regs.num_regs)
2295 args_out_of_range (subexp, make_number (search_regs.num_regs));
2296 }
2297
080c45fd
RS
2298 if (NILP (string))
2299 {
d7a5ad5f
RS
2300 if (search_regs.start[sub] < BEGV
2301 || search_regs.start[sub] > search_regs.end[sub]
2302 || search_regs.end[sub] > ZV)
2303 args_out_of_range (make_number (search_regs.start[sub]),
2304 make_number (search_regs.end[sub]));
080c45fd
RS
2305 }
2306 else
2307 {
d7a5ad5f
RS
2308 if (search_regs.start[sub] < 0
2309 || search_regs.start[sub] > search_regs.end[sub]
d5db4077 2310 || search_regs.end[sub] > SCHARS (string))
d7a5ad5f
RS
2311 args_out_of_range (make_number (search_regs.start[sub]),
2312 make_number (search_regs.end[sub]));
080c45fd 2313 }
ca1d1d23
JB
2314
2315 if (NILP (fixedcase))
2316 {
2317 /* Decide how to casify by examining the matched text. */
ac3b28b1 2318 int last;
ca1d1d23 2319
ac3b28b1
KH
2320 pos = search_regs.start[sub];
2321 last = search_regs.end[sub];
fa8ed3e0
RS
2322
2323 if (NILP (string))
ac3b28b1 2324 pos_byte = CHAR_TO_BYTE (pos);
fa8ed3e0 2325 else
ac3b28b1 2326 pos_byte = string_char_to_byte (string, pos);
fa8ed3e0 2327
ca1d1d23
JB
2328 prevc = '\n';
2329 case_action = all_caps;
2330
2331 /* some_multiletter_word is set nonzero if any original word
2332 is more than one letter long. */
2333 some_multiletter_word = 0;
97832bd0 2334 some_lowercase = 0;
208767c3 2335 some_nonuppercase_initial = 0;
73dc8771 2336 some_uppercase = 0;
ca1d1d23 2337
ac3b28b1 2338 while (pos < last)
ca1d1d23 2339 {
080c45fd 2340 if (NILP (string))
ac3b28b1 2341 {
93daa011 2342 c = FETCH_CHAR_AS_MULTIBYTE (pos_byte);
ac3b28b1
KH
2343 INC_BOTH (pos, pos_byte);
2344 }
080c45fd 2345 else
93daa011 2346 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c, string, pos, pos_byte);
080c45fd 2347
ca1d1d23
JB
2348 if (LOWERCASEP (c))
2349 {
2350 /* Cannot be all caps if any original char is lower case */
2351
97832bd0 2352 some_lowercase = 1;
ca1d1d23 2353 if (SYNTAX (prevc) != Sword)
208767c3 2354 some_nonuppercase_initial = 1;
ca1d1d23
JB
2355 else
2356 some_multiletter_word = 1;
2357 }
d16c2b66 2358 else if (UPPERCASEP (c))
ca1d1d23 2359 {
73dc8771 2360 some_uppercase = 1;
97832bd0 2361 if (SYNTAX (prevc) != Sword)
c4d460ce 2362 ;
97832bd0 2363 else
ca1d1d23
JB
2364 some_multiletter_word = 1;
2365 }
208767c3
RS
2366 else
2367 {
2368 /* If the initial is a caseless word constituent,
2369 treat that like a lowercase initial. */
2370 if (SYNTAX (prevc) != Sword)
2371 some_nonuppercase_initial = 1;
2372 }
ca1d1d23
JB
2373
2374 prevc = c;
2375 }
2376
97832bd0
RS
2377 /* Convert to all caps if the old text is all caps
2378 and has at least one multiletter word. */
2379 if (! some_lowercase && some_multiletter_word)
2380 case_action = all_caps;
c4d460ce 2381 /* Capitalize each word, if the old text has all capitalized words. */
208767c3 2382 else if (!some_nonuppercase_initial && some_multiletter_word)
ca1d1d23 2383 case_action = cap_initial;
208767c3 2384 else if (!some_nonuppercase_initial && some_uppercase)
73dc8771
KH
2385 /* Should x -> yz, operating on X, give Yz or YZ?
2386 We'll assume the latter. */
2387 case_action = all_caps;
97832bd0
RS
2388 else
2389 case_action = nochange;
ca1d1d23
JB
2390 }
2391
080c45fd
RS
2392 /* Do replacement in a string. */
2393 if (!NILP (string))
2394 {
2395 Lisp_Object before, after;
2396
2397 before = Fsubstring (string, make_number (0),
d7a5ad5f
RS
2398 make_number (search_regs.start[sub]));
2399 after = Fsubstring (string, make_number (search_regs.end[sub]), Qnil);
080c45fd 2400
636a5e28
RS
2401 /* Substitute parts of the match into NEWTEXT
2402 if desired. */
080c45fd
RS
2403 if (NILP (literal))
2404 {
d131e79c
RS
2405 int lastpos = 0;
2406 int lastpos_byte = 0;
080c45fd
RS
2407 /* We build up the substituted string in ACCUM. */
2408 Lisp_Object accum;
2409 Lisp_Object middle;
d5db4077 2410 int length = SBYTES (newtext);
080c45fd
RS
2411
2412 accum = Qnil;
2413
ac3b28b1 2414 for (pos_byte = 0, pos = 0; pos_byte < length;)
080c45fd
RS
2415 {
2416 int substart = -1;
6bbd7a29 2417 int subend = 0;
1e79ec24 2418 int delbackslash = 0;
080c45fd 2419
0c8533c6
RS
2420 FETCH_STRING_CHAR_ADVANCE (c, newtext, pos, pos_byte);
2421
080c45fd
RS
2422 if (c == '\\')
2423 {
0c8533c6 2424 FETCH_STRING_CHAR_ADVANCE (c, newtext, pos, pos_byte);
177c0ea7 2425
080c45fd
RS
2426 if (c == '&')
2427 {
d7a5ad5f
RS
2428 substart = search_regs.start[sub];
2429 subend = search_regs.end[sub];
080c45fd 2430 }
76fc1ea2 2431 else if (c >= '1' && c <= '9')
080c45fd 2432 {
76fc1ea2
KH
2433 if (search_regs.start[c - '0'] >= 0
2434 && c <= search_regs.num_regs + '0')
080c45fd
RS
2435 {
2436 substart = search_regs.start[c - '0'];
2437 subend = search_regs.end[c - '0'];
2438 }
76fc1ea2
KH
2439 else
2440 {
2441 /* If that subexp did not match,
2442 replace \\N with nothing. */
2443 substart = 0;
2444 subend = 0;
2445 }
080c45fd 2446 }
1e79ec24
KH
2447 else if (c == '\\')
2448 delbackslash = 1;
636a5e28
RS
2449 else
2450 error ("Invalid use of `\\' in replacement text");
080c45fd
RS
2451 }
2452 if (substart >= 0)
2453 {
d131e79c
RS
2454 if (pos - 2 != lastpos)
2455 middle = substring_both (newtext, lastpos,
2456 lastpos_byte,
2457 pos - 2, pos_byte - 2);
080c45fd
RS
2458 else
2459 middle = Qnil;
2460 accum = concat3 (accum, middle,
0c8533c6
RS
2461 Fsubstring (string,
2462 make_number (substart),
080c45fd
RS
2463 make_number (subend)));
2464 lastpos = pos;
0c8533c6 2465 lastpos_byte = pos_byte;
080c45fd 2466 }
1e79ec24
KH
2467 else if (delbackslash)
2468 {
d131e79c
RS
2469 middle = substring_both (newtext, lastpos,
2470 lastpos_byte,
2471 pos - 1, pos_byte - 1);
0c8533c6 2472
1e79ec24
KH
2473 accum = concat2 (accum, middle);
2474 lastpos = pos;
0c8533c6 2475 lastpos_byte = pos_byte;
1e79ec24 2476 }
080c45fd
RS
2477 }
2478
d131e79c
RS
2479 if (pos != lastpos)
2480 middle = substring_both (newtext, lastpos,
2481 lastpos_byte,
0c8533c6 2482 pos, pos_byte);
080c45fd
RS
2483 else
2484 middle = Qnil;
2485
2486 newtext = concat2 (accum, middle);
2487 }
2488
636a5e28 2489 /* Do case substitution in NEWTEXT if desired. */
080c45fd
RS
2490 if (case_action == all_caps)
2491 newtext = Fupcase (newtext);
2492 else if (case_action == cap_initial)
2b2eead9 2493 newtext = Fupcase_initials (newtext);
080c45fd
RS
2494
2495 return concat3 (before, newtext, after);
2496 }
2497
09c4719e 2498 /* Record point, then move (quietly) to the start of the match. */
9160906f 2499 if (PT >= search_regs.end[sub])
b0eba991 2500 opoint = PT - ZV;
9160906f
RS
2501 else if (PT > search_regs.start[sub])
2502 opoint = search_regs.end[sub] - ZV;
b0eba991
RS
2503 else
2504 opoint = PT;
2505
886ed6ec
RS
2506 /* If we want non-literal replacement,
2507 perform substitution on the replacement string. */
2508 if (NILP (literal))
ca1d1d23 2509 {
d5db4077 2510 int length = SBYTES (newtext);
68e69fbd
RS
2511 unsigned char *substed;
2512 int substed_alloc_size, substed_len;
3bc25e52
KH
2513 int buf_multibyte = !NILP (current_buffer->enable_multibyte_characters);
2514 int str_multibyte = STRING_MULTIBYTE (newtext);
2515 Lisp_Object rev_tbl;
886ed6ec 2516 int really_changed = 0;
3bc25e52 2517
8f924df7 2518 rev_tbl = Qnil;
ac3b28b1 2519
68e69fbd
RS
2520 substed_alloc_size = length * 2 + 100;
2521 substed = (unsigned char *) xmalloc (substed_alloc_size + 1);
2522 substed_len = 0;
2523
3bc25e52
KH
2524 /* Go thru NEWTEXT, producing the actual text to insert in
2525 SUBSTED while adjusting multibyteness to that of the current
2526 buffer. */
ca1d1d23 2527
ac3b28b1 2528 for (pos_byte = 0, pos = 0; pos_byte < length;)
ca1d1d23 2529 {
68e69fbd 2530 unsigned char str[MAX_MULTIBYTE_LENGTH];
f8ce8a0d
GM
2531 unsigned char *add_stuff = NULL;
2532 int add_len = 0;
68e69fbd 2533 int idx = -1;
9a76659d 2534
3bc25e52
KH
2535 if (str_multibyte)
2536 {
eb99a8dd 2537 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, newtext, pos, pos_byte);
3bc25e52
KH
2538 if (!buf_multibyte)
2539 c = multibyte_char_to_unibyte (c, rev_tbl);
2540 }
2541 else
2542 {
2543 /* Note that we don't have to increment POS. */
5d69fe10 2544 c = SREF (newtext, pos_byte++);
3bc25e52
KH
2545 if (buf_multibyte)
2546 c = unibyte_char_to_multibyte (c);
2547 }
ac3b28b1 2548
68e69fbd
RS
2549 /* Either set ADD_STUFF and ADD_LEN to the text to put in SUBSTED,
2550 or set IDX to a match index, which means put that part
2551 of the buffer text into SUBSTED. */
2552
ca1d1d23
JB
2553 if (c == '\\')
2554 {
886ed6ec
RS
2555 really_changed = 1;
2556
3bc25e52
KH
2557 if (str_multibyte)
2558 {
eb99a8dd
KH
2559 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, newtext,
2560 pos, pos_byte);
071ce769 2561 if (!buf_multibyte && !ASCII_CHAR_P (c))
3bc25e52
KH
2562 c = multibyte_char_to_unibyte (c, rev_tbl);
2563 }
2564 else
2565 {
d5db4077 2566 c = SREF (newtext, pos_byte++);
3bc25e52
KH
2567 if (buf_multibyte)
2568 c = unibyte_char_to_multibyte (c);
2569 }
2570
ca1d1d23 2571 if (c == '&')
68e69fbd 2572 idx = sub;
78445046 2573 else if (c >= '1' && c <= '9' && c <= search_regs.num_regs + '0')
ca1d1d23
JB
2574 {
2575 if (search_regs.start[c - '0'] >= 1)
68e69fbd 2576 idx = c - '0';
ca1d1d23 2577 }
636a5e28 2578 else if (c == '\\')
68e69fbd 2579 add_len = 1, add_stuff = "\\";
636a5e28 2580 else
3bc25e52
KH
2581 {
2582 xfree (substed);
2583 error ("Invalid use of `\\' in replacement text");
2584 }
ca1d1d23
JB
2585 }
2586 else
68e69fbd
RS
2587 {
2588 add_len = CHAR_STRING (c, str);
2589 add_stuff = str;
2590 }
2591
2592 /* If we want to copy part of a previous match,
2593 set up ADD_STUFF and ADD_LEN to point to it. */
2594 if (idx >= 0)
2595 {
2596 int begbyte = CHAR_TO_BYTE (search_regs.start[idx]);
2597 add_len = CHAR_TO_BYTE (search_regs.end[idx]) - begbyte;
2598 if (search_regs.start[idx] < GPT && GPT < search_regs.end[idx])
2599 move_gap (search_regs.start[idx]);
2600 add_stuff = BYTE_POS_ADDR (begbyte);
2601 }
2602
2603 /* Now the stuff we want to add to SUBSTED
2604 is invariably ADD_LEN bytes starting at ADD_STUFF. */
2605
2606 /* Make sure SUBSTED is big enough. */
2607 if (substed_len + add_len >= substed_alloc_size)
2608 {
2609 substed_alloc_size = substed_len + add_len + 500;
2610 substed = (unsigned char *) xrealloc (substed,
2611 substed_alloc_size + 1);
2612 }
2613
2614 /* Now add to the end of SUBSTED. */
f8ce8a0d
GM
2615 if (add_stuff)
2616 {
2617 bcopy (add_stuff, substed + substed_len, add_len);
2618 substed_len += add_len;
2619 }
ca1d1d23 2620 }
68e69fbd 2621
886ed6ec 2622 if (really_changed)
76fc1ea2
KH
2623 {
2624 if (buf_multibyte)
2625 {
2626 int nchars = multibyte_chars_in_text (substed, substed_len);
68e69fbd 2627
76fc1ea2
KH
2628 newtext = make_multibyte_string (substed, nchars, substed_len);
2629 }
2630 else
2631 newtext = make_unibyte_string (substed, substed_len);
2632 }
68e69fbd 2633 xfree (substed);
ca1d1d23
JB
2634 }
2635
886ed6ec
RS
2636 /* Replace the old text with the new in the cleanest possible way. */
2637 replace_range (search_regs.start[sub], search_regs.end[sub],
2638 newtext, 1, 0, 1);
d5db4077 2639 newpoint = search_regs.start[sub] + SCHARS (newtext);
ca1d1d23
JB
2640
2641 if (case_action == all_caps)
886ed6ec
RS
2642 Fupcase_region (make_number (search_regs.start[sub]),
2643 make_number (newpoint));
ca1d1d23 2644 else if (case_action == cap_initial)
886ed6ec
RS
2645 Fupcase_initials_region (make_number (search_regs.start[sub]),
2646 make_number (newpoint));
3e18eecf 2647
98e942e0
RS
2648 /* Adjust search data for this change. */
2649 {
5b88a2c5 2650 int oldend = search_regs.end[sub];
41c01205 2651 int oldstart = search_regs.start[sub];
98e942e0
RS
2652 int change = newpoint - search_regs.end[sub];
2653 int i;
2654
2655 for (i = 0; i < search_regs.num_regs; i++)
2656 {
41c01205 2657 if (search_regs.start[i] >= oldend)
98e942e0 2658 search_regs.start[i] += change;
41c01205
DK
2659 else if (search_regs.start[i] > oldstart)
2660 search_regs.start[i] = oldstart;
2661 if (search_regs.end[i] >= oldend)
98e942e0 2662 search_regs.end[i] += change;
41c01205
DK
2663 else if (search_regs.end[i] > oldstart)
2664 search_regs.end[i] = oldstart;
98e942e0
RS
2665 }
2666 }
2667
b0eba991 2668 /* Put point back where it was in the text. */
8d808a65 2669 if (opoint <= 0)
fa8ed3e0 2670 TEMP_SET_PT (opoint + ZV);
b0eba991 2671 else
fa8ed3e0 2672 TEMP_SET_PT (opoint);
b0eba991
RS
2673
2674 /* Now move point "officially" to the start of the inserted replacement. */
3e18eecf 2675 move_if_not_intangible (newpoint);
177c0ea7 2676
ca1d1d23
JB
2677 return Qnil;
2678}
2679\f
2680static Lisp_Object
2681match_limit (num, beginningp)
2682 Lisp_Object num;
2683 int beginningp;
2684{
2685 register int n;
2686
b7826503 2687 CHECK_NUMBER (num);
ca1d1d23 2688 n = XINT (num);
f90a5bf5 2689 if (n < 0)
bd2cbd56 2690 args_out_of_range (num, make_number (0));
f90a5bf5
RS
2691 if (search_regs.num_regs <= 0)
2692 error ("No match data, because no search succeeded");
9b9ceb61 2693 if (n >= search_regs.num_regs
4746118a 2694 || search_regs.start[n] < 0)
ca1d1d23
JB
2695 return Qnil;
2696 return (make_number ((beginningp) ? search_regs.start[n]
2697 : search_regs.end[n]));
2698}
2699
2700DEFUN ("match-beginning", Fmatch_beginning, Smatch_beginning, 1, 1, 0,
8c1a1077
PJ
2701 doc: /* Return position of start of text matched by last search.
2702SUBEXP, a number, specifies which parenthesized expression in the last
2703 regexp.
2704Value is nil if SUBEXPth pair didn't match, or there were less than
2705 SUBEXP pairs.
2706Zero means the entire text matched by the whole regexp or whole string. */)
2707 (subexp)
5806161b 2708 Lisp_Object subexp;
ca1d1d23 2709{
5806161b 2710 return match_limit (subexp, 1);
ca1d1d23
JB
2711}
2712
2713DEFUN ("match-end", Fmatch_end, Smatch_end, 1, 1, 0,
8c1a1077
PJ
2714 doc: /* Return position of end of text matched by last search.
2715SUBEXP, a number, specifies which parenthesized expression in the last
2716 regexp.
2717Value is nil if SUBEXPth pair didn't match, or there were less than
2718 SUBEXP pairs.
2719Zero means the entire text matched by the whole regexp or whole string. */)
2720 (subexp)
5806161b 2721 Lisp_Object subexp;
ca1d1d23 2722{
5806161b 2723 return match_limit (subexp, 0);
177c0ea7 2724}
ca1d1d23 2725
abd0071c 2726DEFUN ("match-data", Fmatch_data, Smatch_data, 0, 3, 0,
8c1a1077
PJ
2727 doc: /* Return a list containing all info on what the last search matched.
2728Element 2N is `(match-beginning N)'; element 2N + 1 is `(match-end N)'.
2729All the elements are markers or nil (nil if the Nth pair didn't match)
2730if the last match was on a buffer; integers or nil if a string was matched.
2731Use `store-match-data' to reinstate the data in this list.
2732
41c01205
DK
2733If INTEGERS (the optional first argument) is non-nil, always use
2734integers \(rather than markers) to represent buffer positions. In
2735this case, and if the last match was in a buffer, the buffer will get
2736stored as one additional element at the end of the list.
2737
abd0071c
KS
2738If REUSE is a list, reuse it as part of the value. If REUSE is long
2739enough to hold all the values, and if INTEGERS is non-nil, no consing
2740is done.
2741
2742If optional third arg RESEAT is non-nil, any previous markers on the
2743REUSE list will be modified to point to nowhere.
2744
140a6b7e 2745Return value is undefined if the last search failed. */)
abd0071c
KS
2746 (integers, reuse, reseat)
2747 Lisp_Object integers, reuse, reseat;
ca1d1d23 2748{
56256c2a 2749 Lisp_Object tail, prev;
4746118a 2750 Lisp_Object *data;
ca1d1d23
JB
2751 int i, len;
2752
abd0071c
KS
2753 if (!NILP (reseat))
2754 for (tail = reuse; CONSP (tail); tail = XCDR (tail))
2755 if (MARKERP (XCAR (tail)))
2756 {
51f10faa 2757 unchain_marker (XMARKER (XCAR (tail)));
abd0071c
KS
2758 XSETCAR (tail, Qnil);
2759 }
2760
daa37602 2761 if (NILP (last_thing_searched))
c36bcf1b 2762 return Qnil;
daa37602 2763
6bbd7a29
GM
2764 prev = Qnil;
2765
41c01205 2766 data = (Lisp_Object *) alloca ((2 * search_regs.num_regs + 1)
4746118a
JB
2767 * sizeof (Lisp_Object));
2768
41c01205 2769 len = 0;
4746118a 2770 for (i = 0; i < search_regs.num_regs; i++)
ca1d1d23
JB
2771 {
2772 int start = search_regs.start[i];
2773 if (start >= 0)
2774 {
56256c2a
RS
2775 if (EQ (last_thing_searched, Qt)
2776 || ! NILP (integers))
ca1d1d23 2777 {
c235cce7
KH
2778 XSETFASTINT (data[2 * i], start);
2779 XSETFASTINT (data[2 * i + 1], search_regs.end[i]);
ca1d1d23 2780 }
0ed62dc7 2781 else if (BUFFERP (last_thing_searched))
ca1d1d23
JB
2782 {
2783 data[2 * i] = Fmake_marker ();
daa37602
JB
2784 Fset_marker (data[2 * i],
2785 make_number (start),
2786 last_thing_searched);
ca1d1d23
JB
2787 data[2 * i + 1] = Fmake_marker ();
2788 Fset_marker (data[2 * i + 1],
177c0ea7 2789 make_number (search_regs.end[i]),
daa37602 2790 last_thing_searched);
ca1d1d23 2791 }
daa37602
JB
2792 else
2793 /* last_thing_searched must always be Qt, a buffer, or Qnil. */
2794 abort ();
2795
abd0071c 2796 len = 2 * i + 2;
ca1d1d23
JB
2797 }
2798 else
abd0071c 2799 data[2 * i] = data[2 * i + 1] = Qnil;
ca1d1d23 2800 }
56256c2a 2801
bd2cbd56 2802 if (BUFFERP (last_thing_searched) && !NILP (integers))
41c01205 2803 {
bd2cbd56 2804 data[len] = last_thing_searched;
41c01205
DK
2805 len++;
2806 }
2807
56256c2a
RS
2808 /* If REUSE is not usable, cons up the values and return them. */
2809 if (! CONSP (reuse))
41c01205 2810 return Flist (len, data);
56256c2a
RS
2811
2812 /* If REUSE is a list, store as many value elements as will fit
2813 into the elements of REUSE. */
2814 for (i = 0, tail = reuse; CONSP (tail);
c1d497be 2815 i++, tail = XCDR (tail))
56256c2a 2816 {
41c01205 2817 if (i < len)
f3fbd155 2818 XSETCAR (tail, data[i]);
56256c2a 2819 else
f3fbd155 2820 XSETCAR (tail, Qnil);
56256c2a
RS
2821 prev = tail;
2822 }
2823
2824 /* If we couldn't fit all value elements into REUSE,
2825 cons up the rest of them and add them to the end of REUSE. */
41c01205
DK
2826 if (i < len)
2827 XSETCDR (prev, Flist (len - i, data + i));
56256c2a
RS
2828
2829 return reuse;
ca1d1d23
JB
2830}
2831
51f10faa
KS
2832/* Internal usage only:
2833 If RESEAT is `evaporate', put the markers back on the free list
2834 immediately. No other references to the markers must exist in this case,
2835 so it is used only internally on the unwind stack and save-match-data from
2836 Lisp. */
ca1d1d23 2837
abd0071c 2838DEFUN ("set-match-data", Fset_match_data, Sset_match_data, 1, 2, 0,
8c1a1077 2839 doc: /* Set internal data on last search match from elements of LIST.
abd0071c
KS
2840LIST should have been created by calling `match-data' previously.
2841
51f10faa 2842If optional arg RESEAT is non-nil, make markers on LIST point nowhere. */)
abd0071c
KS
2843 (list, reseat)
2844 register Lisp_Object list, reseat;
ca1d1d23
JB
2845{
2846 register int i;
2847 register Lisp_Object marker;
2848
7074fde6
FP
2849 if (running_asynch_code)
2850 save_search_regs ();
2851
ca1d1d23 2852 if (!CONSP (list) && !NILP (list))
b37902c8 2853 list = wrong_type_argument (Qconsp, list);
ca1d1d23 2854
41c01205
DK
2855 /* Unless we find a marker with a buffer or an explicit buffer
2856 in LIST, assume that this match data came from a string. */
daa37602
JB
2857 last_thing_searched = Qt;
2858
4746118a
JB
2859 /* Allocate registers if they don't already exist. */
2860 {
d084e942 2861 int length = XFASTINT (Flength (list)) / 2;
4746118a
JB
2862
2863 if (length > search_regs.num_regs)
2864 {
1113d9db
JB
2865 if (search_regs.num_regs == 0)
2866 {
2867 search_regs.start
2868 = (regoff_t *) xmalloc (length * sizeof (regoff_t));
2869 search_regs.end
2870 = (regoff_t *) xmalloc (length * sizeof (regoff_t));
2871 }
4746118a 2872 else
1113d9db
JB
2873 {
2874 search_regs.start
2875 = (regoff_t *) xrealloc (search_regs.start,
2876 length * sizeof (regoff_t));
2877 search_regs.end
2878 = (regoff_t *) xrealloc (search_regs.end,
2879 length * sizeof (regoff_t));
2880 }
4746118a 2881
e62371e9
KH
2882 for (i = search_regs.num_regs; i < length; i++)
2883 search_regs.start[i] = -1;
2884
487282dc 2885 search_regs.num_regs = length;
4746118a 2886 }
ca1d1d23 2887
abd0071c 2888 for (i = 0; CONSP (list); i++)
41c01205 2889 {
abd0071c 2890 marker = XCAR (list);
bd2cbd56 2891 if (BUFFERP (marker))
c3762cbd 2892 {
bd2cbd56 2893 last_thing_searched = marker;
c3762cbd
DK
2894 break;
2895 }
2896 if (i >= length)
2897 break;
41c01205
DK
2898 if (NILP (marker))
2899 {
2900 search_regs.start[i] = -1;
abd0071c 2901 list = XCDR (list);
41c01205
DK
2902 }
2903 else
2904 {
2905 int from;
abd0071c 2906 Lisp_Object m;
e2811828 2907
abd0071c 2908 m = marker;
41c01205
DK
2909 if (MARKERP (marker))
2910 {
2911 if (XMARKER (marker)->buffer == 0)
2912 XSETFASTINT (marker, 0);
2913 else
2914 XSETBUFFER (last_thing_searched, XMARKER (marker)->buffer);
2915 }
e2811828 2916
41c01205
DK
2917 CHECK_NUMBER_COERCE_MARKER (marker);
2918 from = XINT (marker);
e2811828 2919
abd0071c
KS
2920 if (!NILP (reseat) && MARKERP (m))
2921 {
2922 if (EQ (reseat, Qevaporate))
2923 free_marker (m);
2924 else
2925 unchain_marker (XMARKER (m));
9ad54a7e 2926 XSETCAR (list, Qnil);
abd0071c
KS
2927 }
2928
2929 if ((list = XCDR (list), !CONSP (list)))
2930 break;
2931
2932 m = marker = XCAR (list);
2933
41c01205
DK
2934 if (MARKERP (marker) && XMARKER (marker)->buffer == 0)
2935 XSETFASTINT (marker, 0);
e2811828 2936
41c01205
DK
2937 CHECK_NUMBER_COERCE_MARKER (marker);
2938 search_regs.start[i] = from;
2939 search_regs.end[i] = XINT (marker);
abd0071c
KS
2940
2941 if (!NILP (reseat) && MARKERP (m))
2942 {
2943 if (EQ (reseat, Qevaporate))
2944 free_marker (m);
2945 else
2946 unchain_marker (XMARKER (m));
9ad54a7e 2947 XSETCAR (list, Qnil);
abd0071c 2948 }
41c01205 2949 }
abd0071c 2950 list = XCDR (list);
41c01205 2951 }
ca1d1d23 2952
41c01205
DK
2953 for (; i < search_regs.num_regs; i++)
2954 search_regs.start[i] = -1;
2955 }
ca1d1d23 2956
177c0ea7 2957 return Qnil;
ca1d1d23
JB
2958}
2959
7074fde6
FP
2960/* If non-zero the match data have been saved in saved_search_regs
2961 during the execution of a sentinel or filter. */
75ebf74b 2962static int search_regs_saved;
7074fde6 2963static struct re_registers saved_search_regs;
41c01205 2964static Lisp_Object saved_last_thing_searched;
7074fde6
FP
2965
2966/* Called from Flooking_at, Fstring_match, search_buffer, Fstore_match_data
2967 if asynchronous code (filter or sentinel) is running. */
2968static void
2969save_search_regs ()
2970{
2971 if (!search_regs_saved)
2972 {
2973 saved_search_regs.num_regs = search_regs.num_regs;
2974 saved_search_regs.start = search_regs.start;
2975 saved_search_regs.end = search_regs.end;
41c01205
DK
2976 saved_last_thing_searched = last_thing_searched;
2977 last_thing_searched = Qnil;
7074fde6 2978 search_regs.num_regs = 0;
2d4a771a
RS
2979 search_regs.start = 0;
2980 search_regs.end = 0;
7074fde6
FP
2981
2982 search_regs_saved = 1;
2983 }
2984}
2985
2986/* Called upon exit from filters and sentinels. */
2987void
abd0071c 2988restore_search_regs ()
7074fde6
FP
2989{
2990 if (search_regs_saved)
2991 {
2992 if (search_regs.num_regs > 0)
2993 {
2994 xfree (search_regs.start);
2995 xfree (search_regs.end);
2996 }
2997 search_regs.num_regs = saved_search_regs.num_regs;
2998 search_regs.start = saved_search_regs.start;
2999 search_regs.end = saved_search_regs.end;
41c01205
DK
3000 last_thing_searched = saved_last_thing_searched;
3001 saved_last_thing_searched = Qnil;
7074fde6
FP
3002 search_regs_saved = 0;
3003 }
3004}
3005
abd0071c
KS
3006static Lisp_Object
3007unwind_set_match_data (list)
3008 Lisp_Object list;
3009{
51f10faa 3010 /* It is safe to free (evaporate) the markers immediately. */
abd0071c
KS
3011 return Fset_match_data (list, Qevaporate);
3012}
3013
3014/* Called to unwind protect the match data. */
3015void
3016record_unwind_save_match_data ()
3017{
3018 record_unwind_protect (unwind_set_match_data,
3019 Fmatch_data (Qnil, Qnil, Qnil));
3020}
3021
ca1d1d23
JB
3022/* Quote a string to inactivate reg-expr chars */
3023
3024DEFUN ("regexp-quote", Fregexp_quote, Sregexp_quote, 1, 1, 0,
8c1a1077
PJ
3025 doc: /* Return a regexp string which matches exactly STRING and nothing else. */)
3026 (string)
5806161b 3027 Lisp_Object string;
ca1d1d23
JB
3028{
3029 register unsigned char *in, *out, *end;
3030 register unsigned char *temp;
0c8533c6 3031 int backslashes_added = 0;
ca1d1d23 3032
b7826503 3033 CHECK_STRING (string);
ca1d1d23 3034
d5db4077 3035 temp = (unsigned char *) alloca (SBYTES (string) * 2);
ca1d1d23
JB
3036
3037 /* Now copy the data into the new string, inserting escapes. */
3038
d5db4077
KR
3039 in = SDATA (string);
3040 end = in + SBYTES (string);
177c0ea7 3041 out = temp;
ca1d1d23
JB
3042
3043 for (; in != end; in++)
3044 {
66bc6082 3045 if (*in == '['
ca1d1d23
JB
3046 || *in == '*' || *in == '.' || *in == '\\'
3047 || *in == '?' || *in == '+'
3048 || *in == '^' || *in == '$')
0c8533c6 3049 *out++ = '\\', backslashes_added++;
ca1d1d23
JB
3050 *out++ = *in;
3051 }
3052
3f8100f1 3053 return make_specified_string (temp,
d5db4077 3054 SCHARS (string) + backslashes_added,
3f8100f1
RS
3055 out - temp,
3056 STRING_MULTIBYTE (string));
ca1d1d23 3057}
177c0ea7 3058\f
dfcf069d 3059void
ca1d1d23
JB
3060syms_of_search ()
3061{
3062 register int i;
3063
487282dc
KH
3064 for (i = 0; i < REGEXP_CACHE_SIZE; ++i)
3065 {
3066 searchbufs[i].buf.allocated = 100;
b23c0a83 3067 searchbufs[i].buf.buffer = (unsigned char *) xmalloc (100);
487282dc
KH
3068 searchbufs[i].buf.fastmap = searchbufs[i].fastmap;
3069 searchbufs[i].regexp = Qnil;
ecdb561e 3070 searchbufs[i].whitespace_regexp = Qnil;
487282dc 3071 staticpro (&searchbufs[i].regexp);
aa77b5ce 3072 staticpro (&searchbufs[i].whitespace_regexp);
487282dc
KH
3073 searchbufs[i].next = (i == REGEXP_CACHE_SIZE-1 ? 0 : &searchbufs[i+1]);
3074 }
3075 searchbuf_head = &searchbufs[0];
ca1d1d23
JB
3076
3077 Qsearch_failed = intern ("search-failed");
3078 staticpro (&Qsearch_failed);
3079 Qinvalid_regexp = intern ("invalid-regexp");
3080 staticpro (&Qinvalid_regexp);
3081
3082 Fput (Qsearch_failed, Qerror_conditions,
3083 Fcons (Qsearch_failed, Fcons (Qerror, Qnil)));
3084 Fput (Qsearch_failed, Qerror_message,
3085 build_string ("Search failed"));
3086
3087 Fput (Qinvalid_regexp, Qerror_conditions,
3088 Fcons (Qinvalid_regexp, Fcons (Qerror, Qnil)));
3089 Fput (Qinvalid_regexp, Qerror_message,
3090 build_string ("Invalid regexp"));
3091
daa37602
JB
3092 last_thing_searched = Qnil;
3093 staticpro (&last_thing_searched);
3094
0f6af254
DK
3095 saved_last_thing_searched = Qnil;
3096 staticpro (&saved_last_thing_searched);
3097
41a33295 3098 DEFVAR_LISP ("search-spaces-regexp", &Vsearch_spaces_regexp,
e2811828 3099 doc: /* Regexp to substitute for bunches of spaces in regexp search.
f31a9a68
RS
3100Some commands use this for user-specified regexps.
3101Spaces that occur inside character classes or repetition operators
3102or other such regexp constructs are not replaced with this.
3103A value of nil (which is the normal value) means treat spaces literally. */);
41a33295 3104 Vsearch_spaces_regexp = Qnil;
f31a9a68 3105
ca1d1d23 3106 defsubr (&Slooking_at);
b819a390
RS
3107 defsubr (&Sposix_looking_at);
3108 defsubr (&Sstring_match);
3109 defsubr (&Sposix_string_match);
ca1d1d23
JB
3110 defsubr (&Ssearch_forward);
3111 defsubr (&Ssearch_backward);
3112 defsubr (&Sword_search_forward);
3113 defsubr (&Sword_search_backward);
3114 defsubr (&Sre_search_forward);
3115 defsubr (&Sre_search_backward);
b819a390
RS
3116 defsubr (&Sposix_search_forward);
3117 defsubr (&Sposix_search_backward);
ca1d1d23
JB
3118 defsubr (&Sreplace_match);
3119 defsubr (&Smatch_beginning);
3120 defsubr (&Smatch_end);
3121 defsubr (&Smatch_data);
3f1c005b 3122 defsubr (&Sset_match_data);
ca1d1d23
JB
3123 defsubr (&Sregexp_quote);
3124}
76fc1ea2
KH
3125
3126/* arch-tag: a6059d79-0552-4f14-a2cb-d379a4e3c78f
3127 (do not change this comment) */