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