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