; * lisp/ldefs-boot.el: Update.
[emacs.git] / src / search.c
blobdb7fecd9bab25c19e3ad1941b65259ff7118e921
1 /* String search routines for GNU Emacs.
3 Copyright (C) 1985-1987, 1993-1994, 1997-1999, 2001-2019 Free Software
4 Foundation, Inc.
6 This file is part of GNU Emacs.
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 (at
11 your option) any later version.
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.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. */
22 #include <config.h>
24 #include "lisp.h"
25 #include "character.h"
26 #include "buffer.h"
27 #include "syntax.h"
28 #include "charset.h"
29 #include "region-cache.h"
30 #include "blockinput.h"
31 #include "intervals.h"
33 #include "regex.h"
35 #define REGEXP_CACHE_SIZE 20
37 /* If the regexp is non-nil, then the buffer contains the compiled form
38 of that regexp, suitable for searching. */
39 struct regexp_cache
41 struct regexp_cache *next;
42 Lisp_Object regexp, f_whitespace_regexp;
43 /* Syntax table for which the regexp applies. We need this because
44 of character classes. If this is t, then the compiled pattern is valid
45 for any syntax-table. */
46 Lisp_Object syntax_table;
47 struct re_pattern_buffer buf;
48 char fastmap[0400];
49 /* True means regexp was compiled to do full POSIX backtracking. */
50 bool posix;
53 /* The instances of that struct. */
54 static struct regexp_cache searchbufs[REGEXP_CACHE_SIZE];
56 /* The head of the linked list; points to the most recently used buffer. */
57 static struct regexp_cache *searchbuf_head;
60 /* Every call to re_match, etc., must pass &search_regs as the regs
61 argument unless you can show it is unnecessary (i.e., if re_match
62 is certainly going to be called again before region-around-match
63 can be called).
65 Since the registers are now dynamically allocated, we need to make
66 sure not to refer to the Nth register before checking that it has
67 been allocated by checking search_regs.num_regs.
69 The regex code keeps track of whether it has allocated the search
70 buffer using bits in the re_pattern_buffer. This means that whenever
71 you compile a new pattern, it completely forgets whether it has
72 allocated any registers, and will allocate new registers the next
73 time you call a searching or matching function. Therefore, we need
74 to call re_set_registers after compiling a new pattern or after
75 setting the match registers, so that the regex functions will be
76 able to free or re-allocate it properly. */
77 /* static struct re_registers search_regs; */
79 /* The buffer in which the last search was performed, or
80 Qt if the last search was done in a string;
81 Qnil if no searching has been done yet. */
82 /* static Lisp_Object last_thing_searched; */
84 static void set_search_regs (ptrdiff_t, ptrdiff_t);
85 static void save_search_regs (void);
86 static EMACS_INT simple_search (EMACS_INT, unsigned char *, ptrdiff_t,
87 ptrdiff_t, Lisp_Object, ptrdiff_t, ptrdiff_t,
88 ptrdiff_t, ptrdiff_t);
89 static EMACS_INT boyer_moore (EMACS_INT, unsigned char *, ptrdiff_t,
90 Lisp_Object, Lisp_Object, ptrdiff_t,
91 ptrdiff_t, int);
92 static EMACS_INT search_buffer (Lisp_Object, ptrdiff_t, ptrdiff_t,
93 ptrdiff_t, ptrdiff_t, EMACS_INT, int,
94 Lisp_Object, Lisp_Object, bool);
96 static _Noreturn void
97 matcher_overflow (void)
99 error ("Stack overflow in regexp matcher");
102 static void
103 freeze_buffer_relocation (void)
105 #ifdef REL_ALLOC
106 /* Prevent ralloc.c from relocating the current buffer while
107 searching it. */
108 r_alloc_inhibit_buffer_relocation (1);
109 record_unwind_protect_int (r_alloc_inhibit_buffer_relocation, 0);
110 #endif
113 static void
114 thaw_buffer_relocation (void)
116 #ifdef REL_ALLOC
117 unbind_to (SPECPDL_INDEX () - 1, Qnil);
118 #endif
121 /* Compile a regexp and signal a Lisp error if anything goes wrong.
122 PATTERN is the pattern to compile.
123 CP is the place to put the result.
124 TRANSLATE is a translation table for ignoring case, or nil for none.
125 POSIX is true if we want full backtracking (POSIX style) for this pattern.
126 False means backtrack only enough to get a valid match.
128 The behavior also depends on Vsearch_spaces_regexp. */
130 static void
131 compile_pattern_1 (struct regexp_cache *cp, Lisp_Object pattern,
132 Lisp_Object translate, bool posix)
134 const char *whitespace_regexp;
135 char *val;
137 cp->regexp = Qnil;
138 cp->buf.translate = (! NILP (translate) ? translate : make_number (0));
139 cp->posix = posix;
140 cp->buf.multibyte = STRING_MULTIBYTE (pattern);
141 cp->buf.charset_unibyte = charset_unibyte;
142 if (STRINGP (Vsearch_spaces_regexp))
143 cp->f_whitespace_regexp = Vsearch_spaces_regexp;
144 else
145 cp->f_whitespace_regexp = Qnil;
147 /* rms: I think BLOCK_INPUT is not needed here any more,
148 because regex.c defines malloc to call xmalloc.
149 Using BLOCK_INPUT here means the debugger won't run if an error occurs.
150 So let's turn it off. */
151 /* BLOCK_INPUT; */
153 whitespace_regexp = STRINGP (Vsearch_spaces_regexp) ?
154 SSDATA (Vsearch_spaces_regexp) : NULL;
156 val = (char *) re_compile_pattern (SSDATA (pattern), SBYTES (pattern),
157 posix, whitespace_regexp, &cp->buf);
159 /* If the compiled pattern hard codes some of the contents of the
160 syntax-table, it can only be reused with *this* syntax table. */
161 cp->syntax_table = cp->buf.used_syntax ? BVAR (current_buffer, syntax_table) : Qt;
163 /* unblock_input (); */
164 if (val)
165 xsignal1 (Qinvalid_regexp, build_string (val));
167 cp->regexp = Fcopy_sequence (pattern);
170 /* Shrink each compiled regexp buffer in the cache
171 to the size actually used right now.
172 This is called from garbage collection. */
174 void
175 shrink_regexp_cache (void)
177 struct regexp_cache *cp;
179 for (cp = searchbuf_head; cp != 0; cp = cp->next)
181 cp->buf.allocated = cp->buf.used;
182 cp->buf.buffer = xrealloc (cp->buf.buffer, cp->buf.used);
186 /* Clear the regexp cache w.r.t. a particular syntax table,
187 because it was changed.
188 There is no danger of memory leak here because re_compile_pattern
189 automagically manages the memory in each re_pattern_buffer struct,
190 based on its `allocated' and `buffer' values. */
191 void
192 clear_regexp_cache (void)
194 int i;
196 for (i = 0; i < REGEXP_CACHE_SIZE; ++i)
197 /* It's tempting to compare with the syntax-table we've actually changed,
198 but it's not sufficient because char-table inheritance means that
199 modifying one syntax-table can change others at the same time. */
200 if (!EQ (searchbufs[i].syntax_table, Qt))
201 searchbufs[i].regexp = Qnil;
204 /* Compile a regexp if necessary, but first check to see if there's one in
205 the cache.
206 PATTERN is the pattern to compile.
207 TRANSLATE is a translation table for ignoring case, or nil for none.
208 REGP is the structure that says where to store the "register"
209 values that will result from matching this pattern.
210 If it is 0, we should compile the pattern not to record any
211 subexpression bounds.
212 POSIX is true if we want full backtracking (POSIX style) for this pattern.
213 False means backtrack only enough to get a valid match. */
215 struct re_pattern_buffer *
216 compile_pattern (Lisp_Object pattern, struct re_registers *regp,
217 Lisp_Object translate, bool posix, bool multibyte)
219 struct regexp_cache *cp, **cpp;
221 for (cpp = &searchbuf_head; ; cpp = &cp->next)
223 cp = *cpp;
224 /* Entries are initialized to nil, and may be set to nil by
225 compile_pattern_1 if the pattern isn't valid. Don't apply
226 string accessors in those cases. However, compile_pattern_1
227 is only applied to the cache entry we pick here to reuse. So
228 nil should never appear before a non-nil entry. */
229 if (NILP (cp->regexp))
230 goto compile_it;
231 if (SCHARS (cp->regexp) == SCHARS (pattern)
232 && STRING_MULTIBYTE (cp->regexp) == STRING_MULTIBYTE (pattern)
233 && !NILP (Fstring_equal (cp->regexp, pattern))
234 && EQ (cp->buf.translate, (! NILP (translate) ? translate : make_number (0)))
235 && cp->posix == posix
236 && (EQ (cp->syntax_table, Qt)
237 || EQ (cp->syntax_table, BVAR (current_buffer, syntax_table)))
238 && !NILP (Fequal (cp->f_whitespace_regexp, Vsearch_spaces_regexp))
239 && cp->buf.charset_unibyte == charset_unibyte)
240 break;
242 /* If we're at the end of the cache, compile into the nil cell
243 we found, or the last (least recently used) cell with a
244 string value. */
245 if (cp->next == 0)
247 compile_it:
248 compile_pattern_1 (cp, pattern, translate, posix);
249 break;
253 /* When we get here, cp (aka *cpp) contains the compiled pattern,
254 either because we found it in the cache or because we just compiled it.
255 Move it to the front of the queue to mark it as most recently used. */
256 *cpp = cp->next;
257 cp->next = searchbuf_head;
258 searchbuf_head = cp;
260 /* Advise the searching functions about the space we have allocated
261 for register data. */
262 if (regp)
263 re_set_registers (&cp->buf, regp, regp->num_regs, regp->start, regp->end);
265 /* The compiled pattern can be used both for multibyte and unibyte
266 target. But, we have to tell which the pattern is used for. */
267 cp->buf.target_multibyte = multibyte;
269 return &cp->buf;
273 static Lisp_Object
274 looking_at_1 (Lisp_Object string, bool posix)
276 Lisp_Object val;
277 unsigned char *p1, *p2;
278 ptrdiff_t s1, s2;
279 register ptrdiff_t i;
280 struct re_pattern_buffer *bufp;
282 if (running_asynch_code)
283 save_search_regs ();
285 /* This is so set_image_of_range_1 in regex.c can find the EQV table. */
286 set_char_table_extras (BVAR (current_buffer, case_canon_table), 2,
287 BVAR (current_buffer, case_eqv_table));
289 CHECK_STRING (string);
290 bufp = compile_pattern (string,
291 (NILP (Vinhibit_changing_match_data)
292 ? &search_regs : NULL),
293 (!NILP (BVAR (current_buffer, case_fold_search))
294 ? BVAR (current_buffer, case_canon_table) : Qnil),
295 posix,
296 !NILP (BVAR (current_buffer, enable_multibyte_characters)));
298 /* Do a pending quit right away, to avoid paradoxical behavior */
299 maybe_quit ();
301 /* Get pointers and sizes of the two strings
302 that make up the visible portion of the buffer. */
304 p1 = BEGV_ADDR;
305 s1 = GPT_BYTE - BEGV_BYTE;
306 p2 = GAP_END_ADDR;
307 s2 = ZV_BYTE - GPT_BYTE;
308 if (s1 < 0)
310 p2 = p1;
311 s2 = ZV_BYTE - BEGV_BYTE;
312 s1 = 0;
314 if (s2 < 0)
316 s1 = ZV_BYTE - BEGV_BYTE;
317 s2 = 0;
320 re_match_object = Qnil;
322 freeze_buffer_relocation ();
323 i = re_match_2 (bufp, (char *) p1, s1, (char *) p2, s2,
324 PT_BYTE - BEGV_BYTE,
325 (NILP (Vinhibit_changing_match_data)
326 ? &search_regs : NULL),
327 ZV_BYTE - BEGV_BYTE);
328 thaw_buffer_relocation ();
330 if (i == -2)
331 matcher_overflow ();
333 val = (i >= 0 ? Qt : Qnil);
334 if (NILP (Vinhibit_changing_match_data) && i >= 0)
336 for (i = 0; i < search_regs.num_regs; i++)
337 if (search_regs.start[i] >= 0)
339 search_regs.start[i]
340 = BYTE_TO_CHAR (search_regs.start[i] + BEGV_BYTE);
341 search_regs.end[i]
342 = BYTE_TO_CHAR (search_regs.end[i] + BEGV_BYTE);
344 /* Set last_thing_searched only when match data is changed. */
345 XSETBUFFER (last_thing_searched, current_buffer);
348 return val;
351 DEFUN ("looking-at", Flooking_at, Slooking_at, 1, 1, 0,
352 doc: /* Return t if text after point matches regular expression REGEXP.
353 This function modifies the match data that `match-beginning',
354 `match-end' and `match-data' access; save and restore the match
355 data if you want to preserve them. */)
356 (Lisp_Object regexp)
358 return looking_at_1 (regexp, 0);
361 DEFUN ("posix-looking-at", Fposix_looking_at, Sposix_looking_at, 1, 1, 0,
362 doc: /* Return t if text after point matches regular expression REGEXP.
363 Find the longest match, in accord with Posix regular expression rules.
364 This function modifies the match data that `match-beginning',
365 `match-end' and `match-data' access; save and restore the match
366 data if you want to preserve them. */)
367 (Lisp_Object regexp)
369 return looking_at_1 (regexp, 1);
372 static Lisp_Object
373 string_match_1 (Lisp_Object regexp, Lisp_Object string, Lisp_Object start,
374 bool posix)
376 ptrdiff_t val;
377 struct re_pattern_buffer *bufp;
378 EMACS_INT pos;
379 ptrdiff_t pos_byte, i;
381 if (running_asynch_code)
382 save_search_regs ();
384 CHECK_STRING (regexp);
385 CHECK_STRING (string);
387 if (NILP (start))
388 pos = 0, pos_byte = 0;
389 else
391 ptrdiff_t len = SCHARS (string);
393 CHECK_NUMBER (start);
394 pos = XINT (start);
395 if (pos < 0 && -pos <= len)
396 pos = len + pos;
397 else if (0 > pos || pos > len)
398 args_out_of_range (string, start);
399 pos_byte = string_char_to_byte (string, pos);
402 /* This is so set_image_of_range_1 in regex.c can find the EQV table. */
403 set_char_table_extras (BVAR (current_buffer, case_canon_table), 2,
404 BVAR (current_buffer, case_eqv_table));
406 bufp = compile_pattern (regexp,
407 (NILP (Vinhibit_changing_match_data)
408 ? &search_regs : NULL),
409 (!NILP (BVAR (current_buffer, case_fold_search))
410 ? BVAR (current_buffer, case_canon_table) : Qnil),
411 posix,
412 STRING_MULTIBYTE (string));
413 re_match_object = string;
415 val = re_search (bufp, SSDATA (string),
416 SBYTES (string), pos_byte,
417 SBYTES (string) - pos_byte,
418 (NILP (Vinhibit_changing_match_data)
419 ? &search_regs : NULL));
421 /* Set last_thing_searched only when match data is changed. */
422 if (NILP (Vinhibit_changing_match_data))
423 last_thing_searched = Qt;
425 if (val == -2)
426 matcher_overflow ();
427 if (val < 0) return Qnil;
429 if (NILP (Vinhibit_changing_match_data))
430 for (i = 0; i < search_regs.num_regs; i++)
431 if (search_regs.start[i] >= 0)
433 search_regs.start[i]
434 = string_byte_to_char (string, search_regs.start[i]);
435 search_regs.end[i]
436 = string_byte_to_char (string, search_regs.end[i]);
439 return make_number (string_byte_to_char (string, val));
442 DEFUN ("string-match", Fstring_match, Sstring_match, 2, 3, 0,
443 doc: /* Return index of start of first match for REGEXP in STRING, or nil.
444 Matching ignores case if `case-fold-search' is non-nil.
445 If third arg START is non-nil, start search at that index in STRING.
446 For index of first char beyond the match, do (match-end 0).
447 `match-end' and `match-beginning' also give indices of substrings
448 matched by parenthesis constructs in the pattern.
450 You can use the function `match-string' to extract the substrings
451 matched by the parenthesis constructions in REGEXP. */)
452 (Lisp_Object regexp, Lisp_Object string, Lisp_Object start)
454 return string_match_1 (regexp, string, start, 0);
457 DEFUN ("posix-string-match", Fposix_string_match, Sposix_string_match, 2, 3, 0,
458 doc: /* Return index of start of first match for REGEXP in STRING, or nil.
459 Find the longest match, in accord with Posix regular expression rules.
460 Case is ignored if `case-fold-search' is non-nil in the current buffer.
461 If third arg START is non-nil, start search at that index in STRING.
462 For index of first char beyond the match, do (match-end 0).
463 `match-end' and `match-beginning' also give indices of substrings
464 matched by parenthesis constructs in the pattern. */)
465 (Lisp_Object regexp, Lisp_Object string, Lisp_Object start)
467 return string_match_1 (regexp, string, start, 1);
470 /* Match REGEXP against STRING using translation table TABLE,
471 searching all of STRING, and return the index of the match,
472 or negative on failure. This does not clobber the match data. */
474 ptrdiff_t
475 fast_string_match_internal (Lisp_Object regexp, Lisp_Object string,
476 Lisp_Object table)
478 ptrdiff_t val;
479 struct re_pattern_buffer *bufp;
481 bufp = compile_pattern (regexp, 0, table,
482 0, STRING_MULTIBYTE (string));
483 re_match_object = string;
485 val = re_search (bufp, SSDATA (string),
486 SBYTES (string), 0,
487 SBYTES (string), 0);
488 return val;
491 /* Match REGEXP against STRING, searching all of STRING ignoring case,
492 and return the index of the match, or negative on failure.
493 This does not clobber the match data.
494 We assume that STRING contains single-byte characters. */
496 ptrdiff_t
497 fast_c_string_match_ignore_case (Lisp_Object regexp,
498 const char *string, ptrdiff_t len)
500 ptrdiff_t val;
501 struct re_pattern_buffer *bufp;
503 regexp = string_make_unibyte (regexp);
504 re_match_object = Qt;
505 bufp = compile_pattern (regexp, 0,
506 Vascii_canon_table, 0,
508 val = re_search (bufp, string, len, 0, len, 0);
509 return val;
512 /* Match REGEXP against the characters after POS to LIMIT, and return
513 the number of matched characters. If STRING is non-nil, match
514 against the characters in it. In that case, POS and LIMIT are
515 indices into the string. This function doesn't modify the match
516 data. */
518 ptrdiff_t
519 fast_looking_at (Lisp_Object regexp, ptrdiff_t pos, ptrdiff_t pos_byte,
520 ptrdiff_t limit, ptrdiff_t limit_byte, Lisp_Object string)
522 bool multibyte;
523 struct re_pattern_buffer *buf;
524 unsigned char *p1, *p2;
525 ptrdiff_t s1, s2;
526 ptrdiff_t len;
528 if (STRINGP (string))
530 if (pos_byte < 0)
531 pos_byte = string_char_to_byte (string, pos);
532 if (limit_byte < 0)
533 limit_byte = string_char_to_byte (string, limit);
534 p1 = NULL;
535 s1 = 0;
536 p2 = SDATA (string);
537 s2 = SBYTES (string);
538 re_match_object = string;
539 multibyte = STRING_MULTIBYTE (string);
541 else
543 if (pos_byte < 0)
544 pos_byte = CHAR_TO_BYTE (pos);
545 if (limit_byte < 0)
546 limit_byte = CHAR_TO_BYTE (limit);
547 pos_byte -= BEGV_BYTE;
548 limit_byte -= BEGV_BYTE;
549 p1 = BEGV_ADDR;
550 s1 = GPT_BYTE - BEGV_BYTE;
551 p2 = GAP_END_ADDR;
552 s2 = ZV_BYTE - GPT_BYTE;
553 if (s1 < 0)
555 p2 = p1;
556 s2 = ZV_BYTE - BEGV_BYTE;
557 s1 = 0;
559 if (s2 < 0)
561 s1 = ZV_BYTE - BEGV_BYTE;
562 s2 = 0;
564 re_match_object = Qnil;
565 multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
568 buf = compile_pattern (regexp, 0, Qnil, 0, multibyte);
569 freeze_buffer_relocation ();
570 len = re_match_2 (buf, (char *) p1, s1, (char *) p2, s2,
571 pos_byte, NULL, limit_byte);
572 thaw_buffer_relocation ();
574 return len;
578 /* The newline cache: remembering which sections of text have no newlines. */
580 /* If the user has requested the long scans caching, make sure it's on.
581 Otherwise, make sure it's off.
582 This is our cheezy way of associating an action with the change of
583 state of a buffer-local variable. */
584 static struct region_cache *
585 newline_cache_on_off (struct buffer *buf)
587 struct buffer *base_buf = buf;
588 bool indirect_p = false;
590 if (buf->base_buffer)
592 base_buf = buf->base_buffer;
593 indirect_p = true;
596 /* Don't turn on or off the cache in the base buffer, if the value
597 of cache-long-scans of the base buffer is inconsistent with that.
598 This is because doing so will just make the cache pure overhead,
599 since if we turn it on via indirect buffer, it will be
600 immediately turned off by its base buffer. */
601 if (NILP (BVAR (buf, cache_long_scans)))
603 if (!indirect_p
604 || NILP (BVAR (base_buf, cache_long_scans)))
606 /* It should be off. */
607 if (base_buf->newline_cache)
609 free_region_cache (base_buf->newline_cache);
610 base_buf->newline_cache = 0;
613 return NULL;
615 else
617 if (!indirect_p
618 || !NILP (BVAR (base_buf, cache_long_scans)))
620 /* It should be on. */
621 if (base_buf->newline_cache == 0)
622 base_buf->newline_cache = new_region_cache ();
624 return base_buf->newline_cache;
629 /* Search for COUNT newlines between START/START_BYTE and END/END_BYTE.
631 If COUNT is positive, search forwards; END must be >= START.
632 If COUNT is negative, search backwards for the -COUNTth instance;
633 END must be <= START.
634 If COUNT is zero, do anything you please; run rogue, for all I care.
636 If END is zero, use BEGV or ZV instead, as appropriate for the
637 direction indicated by COUNT.
639 If we find COUNT instances, set *SHORTAGE to zero, and return the
640 position past the COUNTth match. Note that for reverse motion
641 this is not the same as the usual convention for Emacs motion commands.
643 If we don't find COUNT instances before reaching END, set *SHORTAGE
644 to the number of newlines left unfound, and return END.
646 If BYTEPOS is not NULL, set *BYTEPOS to the byte position corresponding
647 to the returned character position.
649 If ALLOW_QUIT, check for quitting. That's good to do
650 except when inside redisplay. */
652 ptrdiff_t
653 find_newline (ptrdiff_t start, ptrdiff_t start_byte, ptrdiff_t end,
654 ptrdiff_t end_byte, ptrdiff_t count, ptrdiff_t *shortage,
655 ptrdiff_t *bytepos, bool allow_quit)
657 struct region_cache *newline_cache;
658 int direction;
659 struct buffer *cache_buffer;
661 if (count > 0)
663 direction = 1;
664 if (!end)
665 end = ZV, end_byte = ZV_BYTE;
667 else
669 direction = -1;
670 if (!end)
671 end = BEGV, end_byte = BEGV_BYTE;
673 if (end_byte == -1)
674 end_byte = CHAR_TO_BYTE (end);
676 newline_cache = newline_cache_on_off (current_buffer);
677 if (current_buffer->base_buffer)
678 cache_buffer = current_buffer->base_buffer;
679 else
680 cache_buffer = current_buffer;
682 if (shortage != 0)
683 *shortage = 0;
685 if (count > 0)
686 while (start != end)
688 /* Our innermost scanning loop is very simple; it doesn't know
689 about gaps, buffer ends, or the newline cache. ceiling is
690 the position of the last character before the next such
691 obstacle --- the last character the dumb search loop should
692 examine. */
693 ptrdiff_t tem, ceiling_byte = end_byte - 1;
695 /* If we're using the newline cache, consult it to see whether
696 we can avoid some scanning. */
697 if (newline_cache)
699 ptrdiff_t next_change;
700 int result = 1;
702 while (start < end && result)
704 ptrdiff_t lim1;
706 result = region_cache_forward (cache_buffer, newline_cache,
707 start, &next_change);
708 if (result)
710 /* When the cache revalidation is deferred,
711 next-change might point beyond ZV, which will
712 cause assertion violation in CHAR_TO_BYTE below.
713 Limit next_change to ZV to avoid that. */
714 if (next_change > ZV)
715 next_change = ZV;
716 start = next_change;
717 lim1 = next_change = end;
719 else
720 lim1 = min (next_change, end);
722 /* The cache returned zero for this region; see if
723 this is because the region is known and includes
724 only newlines. While at that, count any newlines
725 we bump into, and exit if we found enough off them. */
726 start_byte = CHAR_TO_BYTE (start);
727 while (start < lim1
728 && FETCH_BYTE (start_byte) == '\n')
730 start_byte++;
731 start++;
732 if (--count == 0)
734 if (bytepos)
735 *bytepos = start_byte;
736 return start;
739 /* If we found a non-newline character before hitting
740 position where the cache will again return non-zero
741 (i.e. no newlines beyond that position), it means
742 this region is not yet known to the cache, and we
743 must resort to the "dumb loop" method. */
744 if (start < next_change && !result)
745 break;
746 result = 1;
748 if (start >= end)
750 start = end;
751 start_byte = end_byte;
752 break;
755 /* START should never be after END. */
756 if (start_byte > ceiling_byte)
757 start_byte = ceiling_byte;
759 /* Now the text after start is an unknown region, and
760 next_change is the position of the next known region. */
761 ceiling_byte = min (CHAR_TO_BYTE (next_change) - 1, ceiling_byte);
763 else if (start_byte == -1)
764 start_byte = CHAR_TO_BYTE (start);
766 /* The dumb loop can only scan text stored in contiguous
767 bytes. BUFFER_CEILING_OF returns the last character
768 position that is contiguous, so the ceiling is the
769 position after that. */
770 tem = BUFFER_CEILING_OF (start_byte);
771 ceiling_byte = min (tem, ceiling_byte);
774 /* The termination address of the dumb loop. */
775 unsigned char *lim_addr = BYTE_POS_ADDR (ceiling_byte) + 1;
776 ptrdiff_t lim_byte = ceiling_byte + 1;
778 /* Nonpositive offsets (relative to LIM_ADDR and LIM_BYTE)
779 of the base, the cursor, and the next line. */
780 ptrdiff_t base = start_byte - lim_byte;
781 ptrdiff_t cursor, next;
783 for (cursor = base; cursor < 0; cursor = next)
785 /* The dumb loop. */
786 unsigned char *nl = memchr (lim_addr + cursor, '\n', - cursor);
787 next = nl ? nl - lim_addr : 0;
789 /* If we're using the newline cache, cache the fact that
790 the region we just traversed is free of newlines. */
791 if (newline_cache && cursor != next)
793 know_region_cache (cache_buffer, newline_cache,
794 BYTE_TO_CHAR (lim_byte + cursor),
795 BYTE_TO_CHAR (lim_byte + next));
796 /* know_region_cache can relocate buffer text. */
797 lim_addr = BYTE_POS_ADDR (ceiling_byte) + 1;
800 if (! nl)
801 break;
802 next++;
804 if (--count == 0)
806 if (bytepos)
807 *bytepos = lim_byte + next;
808 return BYTE_TO_CHAR (lim_byte + next);
810 if (allow_quit)
811 maybe_quit ();
814 start_byte = lim_byte;
815 start = BYTE_TO_CHAR (start_byte);
818 else
819 while (start > end)
821 /* The last character to check before the next obstacle. */
822 ptrdiff_t tem, ceiling_byte = end_byte;
824 /* Consult the newline cache, if appropriate. */
825 if (newline_cache)
827 ptrdiff_t next_change;
828 int result = 1;
830 while (start > end && result)
832 ptrdiff_t lim1;
834 result = region_cache_backward (cache_buffer, newline_cache,
835 start, &next_change);
836 if (result)
838 start = next_change;
839 lim1 = next_change = end;
841 else
842 lim1 = max (next_change, end);
843 start_byte = CHAR_TO_BYTE (start);
844 while (start > lim1
845 && FETCH_BYTE (start_byte - 1) == '\n')
847 if (++count == 0)
849 if (bytepos)
850 *bytepos = start_byte;
851 return start;
853 start_byte--;
854 start--;
856 if (start > next_change && !result)
857 break;
858 result = 1;
860 if (start <= end)
862 start = end;
863 start_byte = end_byte;
864 break;
867 /* Start should never be at or before end. */
868 if (start_byte <= ceiling_byte)
869 start_byte = ceiling_byte + 1;
871 /* Now the text before start is an unknown region, and
872 next_change is the position of the next known region. */
873 ceiling_byte = max (CHAR_TO_BYTE (next_change), ceiling_byte);
875 else if (start_byte == -1)
876 start_byte = CHAR_TO_BYTE (start);
878 /* Stop scanning before the gap. */
879 tem = BUFFER_FLOOR_OF (start_byte - 1);
880 ceiling_byte = max (tem, ceiling_byte);
883 /* The termination address of the dumb loop. */
884 unsigned char *ceiling_addr = BYTE_POS_ADDR (ceiling_byte);
886 /* Offsets (relative to CEILING_ADDR and CEILING_BYTE) of
887 the base, the cursor, and the previous line. These
888 offsets are at least -1. */
889 ptrdiff_t base = start_byte - ceiling_byte;
890 ptrdiff_t cursor, prev;
892 for (cursor = base; 0 < cursor; cursor = prev)
894 unsigned char *nl = memrchr (ceiling_addr, '\n', cursor);
895 prev = nl ? nl - ceiling_addr : -1;
897 /* If we're looking for newlines, cache the fact that
898 this line's region is free of them. */
899 if (newline_cache && cursor != prev + 1)
901 know_region_cache (cache_buffer, newline_cache,
902 BYTE_TO_CHAR (ceiling_byte + prev + 1),
903 BYTE_TO_CHAR (ceiling_byte + cursor));
904 /* know_region_cache can relocate buffer text. */
905 ceiling_addr = BYTE_POS_ADDR (ceiling_byte);
908 if (! nl)
909 break;
911 if (++count >= 0)
913 if (bytepos)
914 *bytepos = ceiling_byte + prev + 1;
915 return BYTE_TO_CHAR (ceiling_byte + prev + 1);
917 if (allow_quit)
918 maybe_quit ();
921 start_byte = ceiling_byte;
922 start = BYTE_TO_CHAR (start_byte);
926 if (shortage)
927 *shortage = count * direction;
928 if (bytepos)
930 *bytepos = start_byte == -1 ? CHAR_TO_BYTE (start) : start_byte;
931 eassert (*bytepos == CHAR_TO_BYTE (start));
933 return start;
936 /* Search for COUNT instances of a line boundary.
937 Start at START. If COUNT is negative, search backwards.
939 We report the resulting position by calling TEMP_SET_PT_BOTH.
941 If we find COUNT instances. we position after (always after,
942 even if scanning backwards) the COUNTth match, and return 0.
944 If we don't find COUNT instances before reaching the end of the
945 buffer (or the beginning, if scanning backwards), we return
946 the number of line boundaries left unfound, and position at
947 the limit we bumped up against.
949 If ALLOW_QUIT, check for quitting. That's good to do
950 except in special cases. */
952 ptrdiff_t
953 scan_newline (ptrdiff_t start, ptrdiff_t start_byte,
954 ptrdiff_t limit, ptrdiff_t limit_byte,
955 ptrdiff_t count, bool allow_quit)
957 ptrdiff_t charpos, bytepos, shortage;
959 charpos = find_newline (start, start_byte, limit, limit_byte,
960 count, &shortage, &bytepos, allow_quit);
961 if (shortage)
962 TEMP_SET_PT_BOTH (limit, limit_byte);
963 else
964 TEMP_SET_PT_BOTH (charpos, bytepos);
965 return shortage;
968 /* Like above, but always scan from point and report the
969 resulting position in *CHARPOS and *BYTEPOS. */
971 ptrdiff_t
972 scan_newline_from_point (ptrdiff_t count, ptrdiff_t *charpos,
973 ptrdiff_t *bytepos)
975 ptrdiff_t shortage;
977 if (count <= 0)
978 *charpos = find_newline (PT, PT_BYTE, BEGV, BEGV_BYTE, count - 1,
979 &shortage, bytepos, 1);
980 else
981 *charpos = find_newline (PT, PT_BYTE, ZV, ZV_BYTE, count,
982 &shortage, bytepos, 1);
983 return shortage;
986 /* Like find_newline, but doesn't allow QUITting and doesn't return
987 SHORTAGE. */
988 ptrdiff_t
989 find_newline_no_quit (ptrdiff_t from, ptrdiff_t frombyte,
990 ptrdiff_t cnt, ptrdiff_t *bytepos)
992 return find_newline (from, frombyte, 0, -1, cnt, NULL, bytepos, 0);
995 /* Like find_newline, but returns position before the newline, not
996 after, and only search up to TO.
997 This isn't just find_newline_no_quit (...)-1, because you might hit TO. */
999 ptrdiff_t
1000 find_before_next_newline (ptrdiff_t from, ptrdiff_t to,
1001 ptrdiff_t cnt, ptrdiff_t *bytepos)
1003 ptrdiff_t shortage;
1004 ptrdiff_t pos = find_newline (from, -1, to, -1, cnt, &shortage, bytepos, 1);
1006 if (shortage == 0)
1008 if (bytepos)
1009 DEC_BOTH (pos, *bytepos);
1010 else
1011 pos--;
1013 return pos;
1016 /* Subroutines of Lisp buffer search functions. */
1018 static Lisp_Object
1019 search_command (Lisp_Object string, Lisp_Object bound, Lisp_Object noerror,
1020 Lisp_Object count, int direction, int RE, bool posix)
1022 EMACS_INT np;
1023 EMACS_INT lim;
1024 ptrdiff_t lim_byte;
1025 EMACS_INT n = direction;
1027 if (!NILP (count))
1029 CHECK_NUMBER (count);
1030 n *= XINT (count);
1033 CHECK_STRING (string);
1034 if (NILP (bound))
1036 if (n > 0)
1037 lim = ZV, lim_byte = ZV_BYTE;
1038 else
1039 lim = BEGV, lim_byte = BEGV_BYTE;
1041 else
1043 CHECK_NUMBER_COERCE_MARKER (bound);
1044 lim = XINT (bound);
1045 if (n > 0 ? lim < PT : lim > PT)
1046 error ("Invalid search bound (wrong side of point)");
1047 if (lim > ZV)
1048 lim = ZV, lim_byte = ZV_BYTE;
1049 else if (lim < BEGV)
1050 lim = BEGV, lim_byte = BEGV_BYTE;
1051 else
1052 lim_byte = CHAR_TO_BYTE (lim);
1055 /* This is so set_image_of_range_1 in regex.c can find the EQV table. */
1056 set_char_table_extras (BVAR (current_buffer, case_canon_table), 2,
1057 BVAR (current_buffer, case_eqv_table));
1059 np = search_buffer (string, PT, PT_BYTE, lim, lim_byte, n, RE,
1060 (!NILP (BVAR (current_buffer, case_fold_search))
1061 ? BVAR (current_buffer, case_canon_table)
1062 : Qnil),
1063 (!NILP (BVAR (current_buffer, case_fold_search))
1064 ? BVAR (current_buffer, case_eqv_table)
1065 : Qnil),
1066 posix);
1067 if (np <= 0)
1069 if (NILP (noerror))
1070 xsignal1 (Qsearch_failed, string);
1072 if (!EQ (noerror, Qt))
1074 eassert (BEGV <= lim && lim <= ZV);
1075 SET_PT_BOTH (lim, lim_byte);
1076 return Qnil;
1077 #if 0 /* This would be clean, but maybe programs depend on
1078 a value of nil here. */
1079 np = lim;
1080 #endif
1082 else
1083 return Qnil;
1086 eassert (BEGV <= np && np <= ZV);
1087 SET_PT (np);
1089 return make_number (np);
1092 /* Return true if REGEXP it matches just one constant string. */
1094 static bool
1095 trivial_regexp_p (Lisp_Object regexp)
1097 ptrdiff_t len = SBYTES (regexp);
1098 unsigned char *s = SDATA (regexp);
1099 while (--len >= 0)
1101 switch (*s++)
1103 case '.': case '*': case '+': case '?': case '[': case '^': case '$':
1104 return 0;
1105 case '\\':
1106 if (--len < 0)
1107 return 0;
1108 switch (*s++)
1110 case '|': case '(': case ')': case '`': case '\'': case 'b':
1111 case 'B': case '<': case '>': case 'w': case 'W': case 's':
1112 case 'S': case '=': case '{': case '}': case '_':
1113 case 'c': case 'C': /* for categoryspec and notcategoryspec */
1114 case '1': case '2': case '3': case '4': case '5':
1115 case '6': case '7': case '8': case '9':
1116 return 0;
1120 return 1;
1123 /* Search for the n'th occurrence of STRING in the current buffer,
1124 starting at position POS and stopping at position LIM,
1125 treating STRING as a literal string if RE is false or as
1126 a regular expression if RE is true.
1128 If N is positive, searching is forward and LIM must be greater than POS.
1129 If N is negative, searching is backward and LIM must be less than POS.
1131 Returns -x if x occurrences remain to be found (x > 0),
1132 or else the position at the beginning of the Nth occurrence
1133 (if searching backward) or the end (if searching forward).
1135 POSIX is nonzero if we want full backtracking (POSIX style)
1136 for this pattern. 0 means backtrack only enough to get a valid match. */
1138 #define TRANSLATE(out, trt, d) \
1139 do \
1141 if (! NILP (trt)) \
1143 Lisp_Object temp; \
1144 temp = Faref (trt, make_number (d)); \
1145 if (INTEGERP (temp)) \
1146 out = XINT (temp); \
1147 else \
1148 out = d; \
1150 else \
1151 out = d; \
1153 while (0)
1155 /* Only used in search_buffer, to record the end position of the match
1156 when searching regexps and SEARCH_REGS should not be changed
1157 (i.e. Vinhibit_changing_match_data is non-nil). */
1158 static struct re_registers search_regs_1;
1160 static EMACS_INT
1161 search_buffer (Lisp_Object string, ptrdiff_t pos, ptrdiff_t pos_byte,
1162 ptrdiff_t lim, ptrdiff_t lim_byte, EMACS_INT n,
1163 int RE, Lisp_Object trt, Lisp_Object inverse_trt, bool posix)
1165 ptrdiff_t len = SCHARS (string);
1166 ptrdiff_t len_byte = SBYTES (string);
1167 register ptrdiff_t i;
1169 if (running_asynch_code)
1170 save_search_regs ();
1172 /* Searching 0 times means don't move. */
1173 /* Null string is found at starting position. */
1174 if (len == 0 || n == 0)
1176 set_search_regs (pos_byte, 0);
1177 return pos;
1180 if (RE && !(trivial_regexp_p (string) && NILP (Vsearch_spaces_regexp)))
1182 unsigned char *p1, *p2;
1183 ptrdiff_t s1, s2;
1184 struct re_pattern_buffer *bufp;
1186 bufp = compile_pattern (string,
1187 (NILP (Vinhibit_changing_match_data)
1188 ? &search_regs : &search_regs_1),
1189 trt, posix,
1190 !NILP (BVAR (current_buffer, enable_multibyte_characters)));
1192 maybe_quit (); /* Do a pending quit right away,
1193 to avoid paradoxical behavior */
1194 /* Get pointers and sizes of the two strings
1195 that make up the visible portion of the buffer. */
1197 p1 = BEGV_ADDR;
1198 s1 = GPT_BYTE - BEGV_BYTE;
1199 p2 = GAP_END_ADDR;
1200 s2 = ZV_BYTE - GPT_BYTE;
1201 if (s1 < 0)
1203 p2 = p1;
1204 s2 = ZV_BYTE - BEGV_BYTE;
1205 s1 = 0;
1207 if (s2 < 0)
1209 s1 = ZV_BYTE - BEGV_BYTE;
1210 s2 = 0;
1212 re_match_object = Qnil;
1214 freeze_buffer_relocation ();
1216 while (n < 0)
1218 ptrdiff_t val;
1220 val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
1221 pos_byte - BEGV_BYTE, lim_byte - pos_byte,
1222 (NILP (Vinhibit_changing_match_data)
1223 ? &search_regs : &search_regs_1),
1224 /* Don't allow match past current point */
1225 pos_byte - BEGV_BYTE);
1226 if (val == -2)
1228 matcher_overflow ();
1230 if (val >= 0)
1232 if (NILP (Vinhibit_changing_match_data))
1234 pos_byte = search_regs.start[0] + BEGV_BYTE;
1235 for (i = 0; i < search_regs.num_regs; i++)
1236 if (search_regs.start[i] >= 0)
1238 search_regs.start[i]
1239 = BYTE_TO_CHAR (search_regs.start[i] + BEGV_BYTE);
1240 search_regs.end[i]
1241 = BYTE_TO_CHAR (search_regs.end[i] + BEGV_BYTE);
1243 XSETBUFFER (last_thing_searched, current_buffer);
1244 /* Set pos to the new position. */
1245 pos = search_regs.start[0];
1247 else
1249 pos_byte = search_regs_1.start[0] + BEGV_BYTE;
1250 /* Set pos to the new position. */
1251 pos = BYTE_TO_CHAR (search_regs_1.start[0] + BEGV_BYTE);
1254 else
1256 thaw_buffer_relocation ();
1257 return (n);
1259 n++;
1260 maybe_quit ();
1262 while (n > 0)
1264 ptrdiff_t val;
1266 val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
1267 pos_byte - BEGV_BYTE, lim_byte - pos_byte,
1268 (NILP (Vinhibit_changing_match_data)
1269 ? &search_regs : &search_regs_1),
1270 lim_byte - BEGV_BYTE);
1271 if (val == -2)
1273 matcher_overflow ();
1275 if (val >= 0)
1277 if (NILP (Vinhibit_changing_match_data))
1279 pos_byte = search_regs.end[0] + BEGV_BYTE;
1280 for (i = 0; i < search_regs.num_regs; i++)
1281 if (search_regs.start[i] >= 0)
1283 search_regs.start[i]
1284 = BYTE_TO_CHAR (search_regs.start[i] + BEGV_BYTE);
1285 search_regs.end[i]
1286 = BYTE_TO_CHAR (search_regs.end[i] + BEGV_BYTE);
1288 XSETBUFFER (last_thing_searched, current_buffer);
1289 pos = search_regs.end[0];
1291 else
1293 pos_byte = search_regs_1.end[0] + BEGV_BYTE;
1294 pos = BYTE_TO_CHAR (search_regs_1.end[0] + BEGV_BYTE);
1297 else
1299 thaw_buffer_relocation ();
1300 return (0 - n);
1302 n--;
1303 maybe_quit ();
1305 thaw_buffer_relocation ();
1306 return (pos);
1308 else /* non-RE case */
1310 unsigned char *raw_pattern, *pat;
1311 ptrdiff_t raw_pattern_size;
1312 ptrdiff_t raw_pattern_size_byte;
1313 unsigned char *patbuf;
1314 bool multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
1315 unsigned char *base_pat;
1316 /* Set to positive if we find a non-ASCII char that need
1317 translation. Otherwise set to zero later. */
1318 int char_base = -1;
1319 bool boyer_moore_ok = 1;
1320 USE_SAFE_ALLOCA;
1322 /* MULTIBYTE says whether the text to be searched is multibyte.
1323 We must convert PATTERN to match that, or we will not really
1324 find things right. */
1326 if (multibyte == STRING_MULTIBYTE (string))
1328 raw_pattern = SDATA (string);
1329 raw_pattern_size = SCHARS (string);
1330 raw_pattern_size_byte = SBYTES (string);
1332 else if (multibyte)
1334 raw_pattern_size = SCHARS (string);
1335 raw_pattern_size_byte
1336 = count_size_as_multibyte (SDATA (string),
1337 raw_pattern_size);
1338 raw_pattern = SAFE_ALLOCA (raw_pattern_size_byte + 1);
1339 copy_text (SDATA (string), raw_pattern,
1340 SCHARS (string), 0, 1);
1342 else
1344 /* Converting multibyte to single-byte. */
1345 raw_pattern_size = SCHARS (string);
1346 raw_pattern_size_byte = SCHARS (string);
1347 raw_pattern = SAFE_ALLOCA (raw_pattern_size + 1);
1348 copy_text (SDATA (string), raw_pattern,
1349 SBYTES (string), 1, 0);
1352 /* Copy and optionally translate the pattern. */
1353 len = raw_pattern_size;
1354 len_byte = raw_pattern_size_byte;
1355 SAFE_NALLOCA (patbuf, MAX_MULTIBYTE_LENGTH, len);
1356 pat = patbuf;
1357 base_pat = raw_pattern;
1358 if (multibyte)
1360 /* Fill patbuf by translated characters in STRING while
1361 checking if we can use boyer-moore search. If TRT is
1362 non-nil, we can use boyer-moore search only if TRT can be
1363 represented by the byte array of 256 elements. For that,
1364 all non-ASCII case-equivalents of all case-sensitive
1365 characters in STRING must belong to the same character
1366 group (two characters belong to the same group iff their
1367 multibyte forms are the same except for the last byte;
1368 i.e. every 64 characters form a group; U+0000..U+003F,
1369 U+0040..U+007F, U+0080..U+00BF, ...). */
1371 while (--len >= 0)
1373 unsigned char str_base[MAX_MULTIBYTE_LENGTH], *str;
1374 int c, translated, inverse;
1375 int in_charlen, charlen;
1377 /* If we got here and the RE flag is set, it's because we're
1378 dealing with a regexp known to be trivial, so the backslash
1379 just quotes the next character. */
1380 if (RE && *base_pat == '\\')
1382 len--;
1383 raw_pattern_size--;
1384 len_byte--;
1385 base_pat++;
1388 c = STRING_CHAR_AND_LENGTH (base_pat, in_charlen);
1390 if (NILP (trt))
1392 str = base_pat;
1393 charlen = in_charlen;
1395 else
1397 /* Translate the character. */
1398 TRANSLATE (translated, trt, c);
1399 charlen = CHAR_STRING (translated, str_base);
1400 str = str_base;
1402 /* Check if C has any other case-equivalents. */
1403 TRANSLATE (inverse, inverse_trt, c);
1404 /* If so, check if we can use boyer-moore. */
1405 if (c != inverse && boyer_moore_ok)
1407 /* Check if all equivalents belong to the same
1408 group of characters. Note that the check of C
1409 itself is done by the last iteration. */
1410 int this_char_base = -1;
1412 while (boyer_moore_ok)
1414 if (ASCII_CHAR_P (inverse))
1416 if (this_char_base > 0)
1417 boyer_moore_ok = 0;
1418 else
1419 this_char_base = 0;
1421 else if (CHAR_BYTE8_P (inverse))
1422 /* Boyer-moore search can't handle a
1423 translation of an eight-bit
1424 character. */
1425 boyer_moore_ok = 0;
1426 else if (this_char_base < 0)
1428 this_char_base = inverse & ~0x3F;
1429 if (char_base < 0)
1430 char_base = this_char_base;
1431 else if (this_char_base != char_base)
1432 boyer_moore_ok = 0;
1434 else if ((inverse & ~0x3F) != this_char_base)
1435 boyer_moore_ok = 0;
1436 if (c == inverse)
1437 break;
1438 TRANSLATE (inverse, inverse_trt, inverse);
1443 /* Store this character into the translated pattern. */
1444 memcpy (pat, str, charlen);
1445 pat += charlen;
1446 base_pat += in_charlen;
1447 len_byte -= in_charlen;
1450 /* If char_base is still negative we didn't find any translated
1451 non-ASCII characters. */
1452 if (char_base < 0)
1453 char_base = 0;
1455 else
1457 /* Unibyte buffer. */
1458 char_base = 0;
1459 while (--len >= 0)
1461 int c, translated, inverse;
1463 /* If we got here and the RE flag is set, it's because we're
1464 dealing with a regexp known to be trivial, so the backslash
1465 just quotes the next character. */
1466 if (RE && *base_pat == '\\')
1468 len--;
1469 raw_pattern_size--;
1470 base_pat++;
1472 c = *base_pat++;
1473 TRANSLATE (translated, trt, c);
1474 *pat++ = translated;
1475 /* Check that none of C's equivalents violates the
1476 assumptions of boyer_moore. */
1477 TRANSLATE (inverse, inverse_trt, c);
1478 while (1)
1480 if (inverse >= 0200)
1482 boyer_moore_ok = 0;
1483 break;
1485 if (c == inverse)
1486 break;
1487 TRANSLATE (inverse, inverse_trt, inverse);
1492 len_byte = pat - patbuf;
1493 pat = base_pat = patbuf;
1495 EMACS_INT result
1496 = (boyer_moore_ok
1497 ? boyer_moore (n, pat, len_byte, trt, inverse_trt,
1498 pos_byte, lim_byte,
1499 char_base)
1500 : simple_search (n, pat, raw_pattern_size, len_byte, trt,
1501 pos, pos_byte, lim, lim_byte));
1502 SAFE_FREE ();
1503 return result;
1507 /* Do a simple string search N times for the string PAT,
1508 whose length is LEN/LEN_BYTE,
1509 from buffer position POS/POS_BYTE until LIM/LIM_BYTE.
1510 TRT is the translation table.
1512 Return the character position where the match is found.
1513 Otherwise, if M matches remained to be found, return -M.
1515 This kind of search works regardless of what is in PAT and
1516 regardless of what is in TRT. It is used in cases where
1517 boyer_moore cannot work. */
1519 static EMACS_INT
1520 simple_search (EMACS_INT n, unsigned char *pat,
1521 ptrdiff_t len, ptrdiff_t len_byte, Lisp_Object trt,
1522 ptrdiff_t pos, ptrdiff_t pos_byte,
1523 ptrdiff_t lim, ptrdiff_t lim_byte)
1525 bool multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
1526 bool forward = n > 0;
1527 /* Number of buffer bytes matched. Note that this may be different
1528 from len_byte in a multibyte buffer. */
1529 ptrdiff_t match_byte = PTRDIFF_MIN;
1531 if (lim > pos && multibyte)
1532 while (n > 0)
1534 while (1)
1536 /* Try matching at position POS. */
1537 ptrdiff_t this_pos = pos;
1538 ptrdiff_t this_pos_byte = pos_byte;
1539 ptrdiff_t this_len = len;
1540 unsigned char *p = pat;
1541 if (pos + len > lim || pos_byte + len_byte > lim_byte)
1542 goto stop;
1544 while (this_len > 0)
1546 int charlen, buf_charlen;
1547 int pat_ch, buf_ch;
1549 pat_ch = STRING_CHAR_AND_LENGTH (p, charlen);
1550 buf_ch = STRING_CHAR_AND_LENGTH (BYTE_POS_ADDR (this_pos_byte),
1551 buf_charlen);
1552 TRANSLATE (buf_ch, trt, buf_ch);
1554 if (buf_ch != pat_ch)
1555 break;
1557 this_len--;
1558 p += charlen;
1560 this_pos_byte += buf_charlen;
1561 this_pos++;
1564 if (this_len == 0)
1566 match_byte = this_pos_byte - pos_byte;
1567 pos += len;
1568 pos_byte += match_byte;
1569 break;
1572 INC_BOTH (pos, pos_byte);
1575 n--;
1577 else if (lim > pos)
1578 while (n > 0)
1580 while (1)
1582 /* Try matching at position POS. */
1583 ptrdiff_t this_pos = pos;
1584 ptrdiff_t this_len = len;
1585 unsigned char *p = pat;
1587 if (pos + len > lim)
1588 goto stop;
1590 while (this_len > 0)
1592 int pat_ch = *p++;
1593 int buf_ch = FETCH_BYTE (this_pos);
1594 TRANSLATE (buf_ch, trt, buf_ch);
1596 if (buf_ch != pat_ch)
1597 break;
1599 this_len--;
1600 this_pos++;
1603 if (this_len == 0)
1605 match_byte = len;
1606 pos += len;
1607 break;
1610 pos++;
1613 n--;
1615 /* Backwards search. */
1616 else if (lim < pos && multibyte)
1617 while (n < 0)
1619 while (1)
1621 /* Try matching at position POS. */
1622 ptrdiff_t this_pos = pos;
1623 ptrdiff_t this_pos_byte = pos_byte;
1624 ptrdiff_t this_len = len;
1625 const unsigned char *p = pat + len_byte;
1627 if (this_pos - len < lim || (pos_byte - len_byte) < lim_byte)
1628 goto stop;
1630 while (this_len > 0)
1632 int pat_ch, buf_ch;
1634 DEC_BOTH (this_pos, this_pos_byte);
1635 PREV_CHAR_BOUNDARY (p, pat);
1636 pat_ch = STRING_CHAR (p);
1637 buf_ch = STRING_CHAR (BYTE_POS_ADDR (this_pos_byte));
1638 TRANSLATE (buf_ch, trt, buf_ch);
1640 if (buf_ch != pat_ch)
1641 break;
1643 this_len--;
1646 if (this_len == 0)
1648 match_byte = pos_byte - this_pos_byte;
1649 pos = this_pos;
1650 pos_byte = this_pos_byte;
1651 break;
1654 DEC_BOTH (pos, pos_byte);
1657 n++;
1659 else if (lim < pos)
1660 while (n < 0)
1662 while (1)
1664 /* Try matching at position POS. */
1665 ptrdiff_t this_pos = pos - len;
1666 ptrdiff_t this_len = len;
1667 unsigned char *p = pat;
1669 if (this_pos < lim)
1670 goto stop;
1672 while (this_len > 0)
1674 int pat_ch = *p++;
1675 int buf_ch = FETCH_BYTE (this_pos);
1676 TRANSLATE (buf_ch, trt, buf_ch);
1678 if (buf_ch != pat_ch)
1679 break;
1680 this_len--;
1681 this_pos++;
1684 if (this_len == 0)
1686 match_byte = len;
1687 pos -= len;
1688 break;
1691 pos--;
1694 n++;
1697 stop:
1698 if (n == 0)
1700 eassert (match_byte != PTRDIFF_MIN);
1701 if (forward)
1702 set_search_regs ((multibyte ? pos_byte : pos) - match_byte, match_byte);
1703 else
1704 set_search_regs (multibyte ? pos_byte : pos, match_byte);
1706 return pos;
1708 else if (n > 0)
1709 return -n;
1710 else
1711 return n;
1714 /* Do Boyer-Moore search N times for the string BASE_PAT,
1715 whose length is LEN_BYTE,
1716 from buffer position POS_BYTE until LIM_BYTE.
1717 DIRECTION says which direction we search in.
1718 TRT and INVERSE_TRT are translation tables.
1719 Characters in PAT are already translated by TRT.
1721 This kind of search works if all the characters in BASE_PAT that
1722 have nontrivial translation are the same aside from the last byte.
1723 This makes it possible to translate just the last byte of a
1724 character, and do so after just a simple test of the context.
1725 CHAR_BASE is nonzero if there is such a non-ASCII character.
1727 If that criterion is not satisfied, do not call this function. */
1729 static EMACS_INT
1730 boyer_moore (EMACS_INT n, unsigned char *base_pat,
1731 ptrdiff_t len_byte,
1732 Lisp_Object trt, Lisp_Object inverse_trt,
1733 ptrdiff_t pos_byte, ptrdiff_t lim_byte,
1734 int char_base)
1736 int direction = ((n > 0) ? 1 : -1);
1737 register ptrdiff_t dirlen;
1738 ptrdiff_t limit;
1739 int stride_for_teases = 0;
1740 int BM_tab[0400];
1741 register unsigned char *cursor, *p_limit;
1742 register ptrdiff_t i;
1743 register int j;
1744 unsigned char *pat, *pat_end;
1745 bool multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
1747 unsigned char simple_translate[0400];
1748 /* These are set to the preceding bytes of a byte to be translated
1749 if char_base is nonzero. As the maximum byte length of a
1750 multibyte character is 5, we have to check at most four previous
1751 bytes. */
1752 int translate_prev_byte1 = 0;
1753 int translate_prev_byte2 = 0;
1754 int translate_prev_byte3 = 0;
1756 /* The general approach is that we are going to maintain that we know
1757 the first (closest to the present position, in whatever direction
1758 we're searching) character that could possibly be the last
1759 (furthest from present position) character of a valid match. We
1760 advance the state of our knowledge by looking at that character
1761 and seeing whether it indeed matches the last character of the
1762 pattern. If it does, we take a closer look. If it does not, we
1763 move our pointer (to putative last characters) as far as is
1764 logically possible. This amount of movement, which I call a
1765 stride, will be the length of the pattern if the actual character
1766 appears nowhere in the pattern, otherwise it will be the distance
1767 from the last occurrence of that character to the end of the
1768 pattern. If the amount is zero we have a possible match. */
1770 /* Here we make a "mickey mouse" BM table. The stride of the search
1771 is determined only by the last character of the putative match.
1772 If that character does not match, we will stride the proper
1773 distance to propose a match that superimposes it on the last
1774 instance of a character that matches it (per trt), or misses
1775 it entirely if there is none. */
1777 dirlen = len_byte * direction;
1779 /* Record position after the end of the pattern. */
1780 pat_end = base_pat + len_byte;
1781 /* BASE_PAT points to a character that we start scanning from.
1782 It is the first character in a forward search,
1783 the last character in a backward search. */
1784 if (direction < 0)
1785 base_pat = pat_end - 1;
1787 /* A character that does not appear in the pattern induces a
1788 stride equal to the pattern length. */
1789 for (i = 0; i < 0400; i++)
1790 BM_tab[i] = dirlen;
1792 /* We use this for translation, instead of TRT itself.
1793 We fill this in to handle the characters that actually
1794 occur in the pattern. Others don't matter anyway! */
1795 for (i = 0; i < 0400; i++)
1796 simple_translate[i] = i;
1798 if (char_base)
1800 /* Setup translate_prev_byte1/2/3/4 from CHAR_BASE. Only a
1801 byte following them are the target of translation. */
1802 eassume (0x80 <= char_base && char_base <= MAX_CHAR);
1803 unsigned char str[MAX_MULTIBYTE_LENGTH];
1804 int cblen = CHAR_STRING (char_base, str);
1806 translate_prev_byte1 = str[cblen - 2];
1807 if (cblen > 2)
1809 translate_prev_byte2 = str[cblen - 3];
1810 if (cblen > 3)
1811 translate_prev_byte3 = str[cblen - 4];
1815 i = 0;
1816 while (i != dirlen)
1818 unsigned char *ptr = base_pat + i;
1819 i += direction;
1820 if (! NILP (trt))
1822 /* If the byte currently looking at is the last of a
1823 character to check case-equivalents, set CH to that
1824 character. An ASCII character and a non-ASCII character
1825 matching with CHAR_BASE are to be checked. */
1826 int ch = -1;
1828 if (ASCII_CHAR_P (*ptr) || ! multibyte)
1829 ch = *ptr;
1830 else if (char_base
1831 && ((pat_end - ptr) == 1 || CHAR_HEAD_P (ptr[1])))
1833 unsigned char *charstart = ptr - 1;
1835 while (! (CHAR_HEAD_P (*charstart)))
1836 charstart--;
1837 ch = STRING_CHAR (charstart);
1838 if (char_base != (ch & ~0x3F))
1839 ch = -1;
1842 if (ch >= 0200 && multibyte)
1843 j = (ch & 0x3F) | 0200;
1844 else
1845 j = *ptr;
1847 if (i == dirlen)
1848 stride_for_teases = BM_tab[j];
1850 BM_tab[j] = dirlen - i;
1851 /* A translation table is accompanied by its inverse -- see
1852 comment following downcase_table for details. */
1853 if (ch >= 0)
1855 int starting_ch = ch;
1856 int starting_j = j;
1858 while (1)
1860 TRANSLATE (ch, inverse_trt, ch);
1861 if (ch >= 0200 && multibyte)
1862 j = (ch & 0x3F) | 0200;
1863 else
1864 j = ch;
1866 /* For all the characters that map into CH,
1867 set up simple_translate to map the last byte
1868 into STARTING_J. */
1869 simple_translate[j] = starting_j;
1870 if (ch == starting_ch)
1871 break;
1872 BM_tab[j] = dirlen - i;
1876 else
1878 j = *ptr;
1880 if (i == dirlen)
1881 stride_for_teases = BM_tab[j];
1882 BM_tab[j] = dirlen - i;
1884 /* stride_for_teases tells how much to stride if we get a
1885 match on the far character but are subsequently
1886 disappointed, by recording what the stride would have been
1887 for that character if the last character had been
1888 different. */
1890 pos_byte += dirlen - ((direction > 0) ? direction : 0);
1891 /* loop invariant - POS_BYTE points at where last char (first
1892 char if reverse) of pattern would align in a possible match. */
1893 while (n != 0)
1895 ptrdiff_t tail_end;
1896 unsigned char *tail_end_ptr;
1898 /* It's been reported that some (broken) compiler thinks that
1899 Boolean expressions in an arithmetic context are unsigned.
1900 Using an explicit ?1:0 prevents this. */
1901 if ((lim_byte - pos_byte - ((direction > 0) ? 1 : 0)) * direction
1902 < 0)
1903 return (n * (0 - direction));
1904 /* First we do the part we can by pointers (maybe nothing) */
1905 maybe_quit ();
1906 pat = base_pat;
1907 limit = pos_byte - dirlen + direction;
1908 if (direction > 0)
1910 limit = BUFFER_CEILING_OF (limit);
1911 /* LIMIT is now the last (not beyond-last!) value POS_BYTE
1912 can take on without hitting edge of buffer or the gap. */
1913 limit = min (limit, pos_byte + 20000);
1914 limit = min (limit, lim_byte - 1);
1916 else
1918 limit = BUFFER_FLOOR_OF (limit);
1919 /* LIMIT is now the last (not beyond-last!) value POS_BYTE
1920 can take on without hitting edge of buffer or the gap. */
1921 limit = max (limit, pos_byte - 20000);
1922 limit = max (limit, lim_byte);
1924 tail_end = BUFFER_CEILING_OF (pos_byte) + 1;
1925 tail_end_ptr = BYTE_POS_ADDR (tail_end);
1927 if ((limit - pos_byte) * direction > 20)
1929 unsigned char *p2;
1931 p_limit = BYTE_POS_ADDR (limit);
1932 p2 = (cursor = BYTE_POS_ADDR (pos_byte));
1933 /* In this loop, pos + cursor - p2 is the surrogate for pos. */
1934 while (1) /* use one cursor setting as long as i can */
1936 if (direction > 0) /* worth duplicating */
1938 while (cursor <= p_limit)
1940 if (BM_tab[*cursor] == 0)
1941 goto hit;
1942 cursor += BM_tab[*cursor];
1945 else
1947 while (cursor >= p_limit)
1949 if (BM_tab[*cursor] == 0)
1950 goto hit;
1951 cursor += BM_tab[*cursor];
1954 /* If you are here, cursor is beyond the end of the
1955 searched region. You fail to match within the
1956 permitted region and would otherwise try a character
1957 beyond that region. */
1958 break;
1960 hit:
1961 i = dirlen - direction;
1962 if (! NILP (trt))
1964 while ((i -= direction) + direction != 0)
1966 int ch;
1967 cursor -= direction;
1968 /* Translate only the last byte of a character. */
1969 if (! multibyte
1970 || ((cursor == tail_end_ptr
1971 || CHAR_HEAD_P (cursor[1]))
1972 && (CHAR_HEAD_P (cursor[0])
1973 /* Check if this is the last byte of
1974 a translatable character. */
1975 || (translate_prev_byte1 == cursor[-1]
1976 && (CHAR_HEAD_P (translate_prev_byte1)
1977 || (translate_prev_byte2 == cursor[-2]
1978 && (CHAR_HEAD_P (translate_prev_byte2)
1979 || (translate_prev_byte3 == cursor[-3]))))))))
1980 ch = simple_translate[*cursor];
1981 else
1982 ch = *cursor;
1983 if (pat[i] != ch)
1984 break;
1987 else
1989 while ((i -= direction) + direction != 0)
1991 cursor -= direction;
1992 if (pat[i] != *cursor)
1993 break;
1996 cursor += dirlen - i - direction; /* fix cursor */
1997 if (i + direction == 0)
1999 ptrdiff_t position, start, end;
2000 #ifdef REL_ALLOC
2001 ptrdiff_t cursor_off;
2002 #endif
2004 cursor -= direction;
2006 position = pos_byte + cursor - p2 + ((direction > 0)
2007 ? 1 - len_byte : 0);
2008 #ifdef REL_ALLOC
2009 /* set_search_regs might call malloc, which could
2010 cause ralloc.c relocate buffer text. We need to
2011 update pointers into buffer text due to that. */
2012 cursor_off = cursor - p2;
2013 #endif
2014 set_search_regs (position, len_byte);
2015 #ifdef REL_ALLOC
2016 p_limit = BYTE_POS_ADDR (limit);
2017 p2 = BYTE_POS_ADDR (pos_byte);
2018 cursor = p2 + cursor_off;
2019 #endif
2021 if (NILP (Vinhibit_changing_match_data))
2023 start = search_regs.start[0];
2024 end = search_regs.end[0];
2026 else
2027 /* If Vinhibit_changing_match_data is non-nil,
2028 search_regs will not be changed. So let's
2029 compute start and end here. */
2031 start = BYTE_TO_CHAR (position);
2032 end = BYTE_TO_CHAR (position + len_byte);
2035 if ((n -= direction) != 0)
2036 cursor += dirlen; /* to resume search */
2037 else
2038 return direction > 0 ? end : start;
2040 else
2041 cursor += stride_for_teases; /* <sigh> we lose - */
2043 pos_byte += cursor - p2;
2045 else
2046 /* Now we'll pick up a clump that has to be done the hard
2047 way because it covers a discontinuity. */
2049 limit = ((direction > 0)
2050 ? BUFFER_CEILING_OF (pos_byte - dirlen + 1)
2051 : BUFFER_FLOOR_OF (pos_byte - dirlen - 1));
2052 limit = ((direction > 0)
2053 ? min (limit + len_byte, lim_byte - 1)
2054 : max (limit - len_byte, lim_byte));
2055 /* LIMIT is now the last value POS_BYTE can have
2056 and still be valid for a possible match. */
2057 while (1)
2059 /* This loop can be coded for space rather than
2060 speed because it will usually run only once.
2061 (the reach is at most len + 21, and typically
2062 does not exceed len). */
2063 while ((limit - pos_byte) * direction >= 0)
2065 int ch = FETCH_BYTE (pos_byte);
2066 if (BM_tab[ch] == 0)
2067 goto hit2;
2068 pos_byte += BM_tab[ch];
2070 break; /* ran off the end */
2072 hit2:
2073 /* Found what might be a match. */
2074 i = dirlen - direction;
2075 while ((i -= direction) + direction != 0)
2077 int ch;
2078 unsigned char *ptr;
2079 pos_byte -= direction;
2080 ptr = BYTE_POS_ADDR (pos_byte);
2081 /* Translate only the last byte of a character. */
2082 if (! multibyte
2083 || ((ptr == tail_end_ptr
2084 || CHAR_HEAD_P (ptr[1]))
2085 && (CHAR_HEAD_P (ptr[0])
2086 /* Check if this is the last byte of a
2087 translatable character. */
2088 || (translate_prev_byte1 == ptr[-1]
2089 && (CHAR_HEAD_P (translate_prev_byte1)
2090 || (translate_prev_byte2 == ptr[-2]
2091 && (CHAR_HEAD_P (translate_prev_byte2)
2092 || translate_prev_byte3 == ptr[-3])))))))
2093 ch = simple_translate[*ptr];
2094 else
2095 ch = *ptr;
2096 if (pat[i] != ch)
2097 break;
2099 /* Above loop has moved POS_BYTE part or all the way
2100 back to the first pos (last pos if reverse).
2101 Set it once again at the last (first if reverse) char. */
2102 pos_byte += dirlen - i - direction;
2103 if (i + direction == 0)
2105 ptrdiff_t position, start, end;
2106 pos_byte -= direction;
2108 position = pos_byte + ((direction > 0) ? 1 - len_byte : 0);
2109 set_search_regs (position, len_byte);
2111 if (NILP (Vinhibit_changing_match_data))
2113 start = search_regs.start[0];
2114 end = search_regs.end[0];
2116 else
2117 /* If Vinhibit_changing_match_data is non-nil,
2118 search_regs will not be changed. So let's
2119 compute start and end here. */
2121 start = BYTE_TO_CHAR (position);
2122 end = BYTE_TO_CHAR (position + len_byte);
2125 if ((n -= direction) != 0)
2126 pos_byte += dirlen; /* to resume search */
2127 else
2128 return direction > 0 ? end : start;
2130 else
2131 pos_byte += stride_for_teases;
2134 /* We have done one clump. Can we continue? */
2135 if ((lim_byte - pos_byte) * direction < 0)
2136 return ((0 - n) * direction);
2138 return BYTE_TO_CHAR (pos_byte);
2141 /* Record beginning BEG_BYTE and end BEG_BYTE + NBYTES
2142 for the overall match just found in the current buffer.
2143 Also clear out the match data for registers 1 and up. */
2145 static void
2146 set_search_regs (ptrdiff_t beg_byte, ptrdiff_t nbytes)
2148 ptrdiff_t i;
2150 if (!NILP (Vinhibit_changing_match_data))
2151 return;
2153 /* Make sure we have registers in which to store
2154 the match position. */
2155 if (search_regs.num_regs == 0)
2157 search_regs.start = xmalloc (2 * sizeof (regoff_t));
2158 search_regs.end = xmalloc (2 * sizeof (regoff_t));
2159 search_regs.num_regs = 2;
2162 /* Clear out the other registers. */
2163 for (i = 1; i < search_regs.num_regs; i++)
2165 search_regs.start[i] = -1;
2166 search_regs.end[i] = -1;
2169 search_regs.start[0] = BYTE_TO_CHAR (beg_byte);
2170 search_regs.end[0] = BYTE_TO_CHAR (beg_byte + nbytes);
2171 XSETBUFFER (last_thing_searched, current_buffer);
2174 DEFUN ("search-backward", Fsearch_backward, Ssearch_backward, 1, 4,
2175 "MSearch backward: ",
2176 doc: /* Search backward from point for STRING.
2177 Set point to the beginning of the occurrence found, and return point.
2178 An optional second argument bounds the search; it is a buffer position.
2179 The match found must not begin before that position. A value of nil
2180 means search to the beginning of the accessible portion of the buffer.
2181 Optional third argument, if t, means if fail just return nil (no error).
2182 If not nil and not t, position at limit of search and return nil.
2183 Optional fourth argument COUNT, if a positive number, means to search
2184 for COUNT successive occurrences. If COUNT is negative, search
2185 forward, instead of backward, for -COUNT occurrences. A value of
2186 nil means the same as 1.
2187 With COUNT positive, the match found is the COUNTth to last one (or
2188 last, if COUNT is 1 or nil) in the buffer located entirely before
2189 the origin of the search; correspondingly with COUNT negative.
2191 Search case-sensitivity is determined by the value of the variable
2192 `case-fold-search', which see.
2194 See also the functions `match-beginning', `match-end' and `replace-match'. */)
2195 (Lisp_Object string, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
2197 return search_command (string, bound, noerror, count, -1, 0, 0);
2200 DEFUN ("search-forward", Fsearch_forward, Ssearch_forward, 1, 4, "MSearch: ",
2201 doc: /* Search forward from point for STRING.
2202 Set point to the end of the occurrence found, and return point.
2203 An optional second argument bounds the search; it is a buffer position.
2204 The match found must not end after that position. A value of nil
2205 means search to the end of the accessible portion of the buffer.
2206 Optional third argument, if t, means if fail just return nil (no error).
2207 If not nil and not t, move to limit of search and return nil.
2208 Optional fourth argument COUNT, if a positive number, means to search
2209 for COUNT successive occurrences. If COUNT is negative, search
2210 backward, instead of forward, for -COUNT occurrences. A value of
2211 nil means the same as 1.
2212 With COUNT positive, the match found is the COUNTth one (or first,
2213 if COUNT is 1 or nil) in the buffer located entirely after the
2214 origin of the search; correspondingly with COUNT negative.
2216 Search case-sensitivity is determined by the value of the variable
2217 `case-fold-search', which see.
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)
2222 return search_command (string, bound, noerror, count, 1, 0, 0);
2225 DEFUN ("re-search-backward", Fre_search_backward, Sre_search_backward, 1, 4,
2226 "sRE search backward: ",
2227 doc: /* Search backward from point for regular expression REGEXP.
2228 This function is almost identical to `re-search-forward', except that
2229 by default it searches backward instead of forward, and the sign of
2230 COUNT also indicates exactly the opposite searching direction.
2231 See `re-search-forward' for details.
2233 Note that searching backwards may give a shorter match than expected,
2234 because REGEXP is still matched in the forward direction. See Info
2235 anchor `(elisp) re-search-backward' for details. */)
2236 (Lisp_Object regexp, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
2238 return search_command (regexp, bound, noerror, count, -1, 1, 0);
2241 DEFUN ("re-search-forward", Fre_search_forward, Sre_search_forward, 1, 4,
2242 "sRE search: ",
2243 doc: /* Search forward from point for regular expression REGEXP.
2244 Set point to the end of the occurrence found, and return point.
2245 The optional second argument BOUND is a buffer position that bounds
2246 the search. The match found must not end after that position. A
2247 value of nil means search to the end of the accessible portion of
2248 the buffer.
2249 The optional third argument NOERROR indicates how errors are handled
2250 when the search fails. If it is nil or omitted, emit an error; if
2251 it is t, simply return nil and do nothing; if it is neither nil nor
2252 t, move to the limit of search and return nil.
2253 The optional fourth argument COUNT is a number that indicates the
2254 search direction and the number of occurrences to search for. If it
2255 is positive, search forward for COUNT successive occurrences; if it
2256 is negative, search backward, instead of forward, for -COUNT
2257 occurrences. A value of nil means the same as 1.
2258 With COUNT positive/negative, the match found is the COUNTth/-COUNTth
2259 one in the buffer located entirely after/before the origin of the
2260 search.
2262 Search case-sensitivity is determined by the value of the variable
2263 `case-fold-search', which see.
2265 See also the functions `match-beginning', `match-end', `match-string',
2266 and `replace-match'. */)
2267 (Lisp_Object regexp, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
2269 return search_command (regexp, bound, noerror, count, 1, 1, 0);
2272 DEFUN ("posix-search-backward", Fposix_search_backward, Sposix_search_backward, 1, 4,
2273 "sPosix search backward: ",
2274 doc: /* Search backward from point for match for regular expression REGEXP.
2275 Find the longest match in accord with Posix regular expression rules.
2276 Set point to the beginning of the occurrence found, and return point.
2277 An optional second argument bounds the search; it is a buffer position.
2278 The match found must not begin before that position. A value of nil
2279 means search to the beginning of the accessible portion of the buffer.
2280 Optional third argument, if t, means if fail just return nil (no error).
2281 If not nil and not t, position at limit of search and return nil.
2282 Optional fourth argument COUNT, if a positive number, means to search
2283 for COUNT successive occurrences. If COUNT is negative, search
2284 forward, instead of backward, for -COUNT occurrences. A value of
2285 nil means the same as 1.
2286 With COUNT positive, the match found is the COUNTth to last one (or
2287 last, if COUNT is 1 or nil) in the buffer located entirely before
2288 the origin of the search; correspondingly with COUNT negative.
2290 Search case-sensitivity is determined by the value of the variable
2291 `case-fold-search', which see.
2293 See also the functions `match-beginning', `match-end', `match-string',
2294 and `replace-match'. */)
2295 (Lisp_Object regexp, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
2297 return search_command (regexp, bound, noerror, count, -1, 1, 1);
2300 DEFUN ("posix-search-forward", Fposix_search_forward, Sposix_search_forward, 1, 4,
2301 "sPosix search: ",
2302 doc: /* Search forward from point for regular expression REGEXP.
2303 Find the longest match in accord with Posix regular expression rules.
2304 Set point to the end of the occurrence found, and return point.
2305 An optional second argument bounds the search; it is a buffer position.
2306 The match found must not end after that position. A value of nil
2307 means search to the end of the accessible portion of the buffer.
2308 Optional third argument, if t, means if fail just return nil (no error).
2309 If not nil and not t, move to limit of search and return nil.
2310 Optional fourth argument COUNT, if a positive number, means to search
2311 for COUNT successive occurrences. If COUNT is negative, search
2312 backward, instead of forward, for -COUNT occurrences. A value of
2313 nil means the same as 1.
2314 With COUNT positive, the match found is the COUNTth one (or first,
2315 if COUNT is 1 or nil) in the buffer located entirely after the
2316 origin of the search; correspondingly with COUNT negative.
2318 Search case-sensitivity is determined by the value of the variable
2319 `case-fold-search', which see.
2321 See also the functions `match-beginning', `match-end', `match-string',
2322 and `replace-match'. */)
2323 (Lisp_Object regexp, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
2325 return search_command (regexp, bound, noerror, count, 1, 1, 1);
2328 DEFUN ("replace-match", Freplace_match, Sreplace_match, 1, 5, 0,
2329 doc: /* Replace text matched by last search with NEWTEXT.
2330 Leave point at the end of the replacement text.
2332 If optional second arg FIXEDCASE is non-nil, do not alter the case of
2333 the replacement text. Otherwise, maybe capitalize the whole text, or
2334 maybe just word initials, based on the replaced text. If the replaced
2335 text has only capital letters and has at least one multiletter word,
2336 convert NEWTEXT to all caps. Otherwise if all words are capitalized
2337 in the replaced text, capitalize each word in NEWTEXT.
2339 If optional third arg LITERAL is non-nil, insert NEWTEXT literally.
2340 Otherwise treat `\\' as special:
2341 `\\&' in NEWTEXT means substitute original matched text.
2342 `\\N' means substitute what matched the Nth `\\(...\\)'.
2343 If Nth parens didn't match, substitute nothing.
2344 `\\\\' means insert one `\\'.
2345 `\\?' is treated literally
2346 (for compatibility with `query-replace-regexp').
2347 Any other character following `\\' signals an error.
2348 Case conversion does not apply to these substitutions.
2350 If optional fourth argument STRING is non-nil, it should be a string
2351 to act on; this should be the string on which the previous match was
2352 done via `string-match'. In this case, `replace-match' creates and
2353 returns a new string, made by copying STRING and replacing the part of
2354 STRING that was matched (the original STRING itself is not altered).
2356 The optional fifth argument SUBEXP specifies a subexpression;
2357 it says to replace just that subexpression with NEWTEXT,
2358 rather than replacing the entire matched text.
2359 This is, in a vague sense, the inverse of using `\\N' in NEWTEXT;
2360 `\\N' copies subexp N into NEWTEXT, but using N as SUBEXP puts
2361 NEWTEXT in place of subexp N.
2362 This is useful only after a regular expression search or match,
2363 since only regular expressions have distinguished subexpressions. */)
2364 (Lisp_Object newtext, Lisp_Object fixedcase, Lisp_Object literal, Lisp_Object string, Lisp_Object subexp)
2366 enum { nochange, all_caps, cap_initial } case_action;
2367 ptrdiff_t pos, pos_byte;
2368 bool some_multiletter_word;
2369 bool some_lowercase;
2370 bool some_uppercase;
2371 bool some_nonuppercase_initial;
2372 int c, prevc;
2373 ptrdiff_t sub;
2374 ptrdiff_t opoint, newpoint;
2376 CHECK_STRING (newtext);
2378 if (! NILP (string))
2379 CHECK_STRING (string);
2381 case_action = nochange; /* We tried an initialization */
2382 /* but some C compilers blew it */
2384 if (search_regs.num_regs <= 0)
2385 error ("`replace-match' called before any match found");
2387 if (NILP (subexp))
2388 sub = 0;
2389 else
2391 CHECK_NUMBER (subexp);
2392 if (! (0 <= XINT (subexp) && XINT (subexp) < search_regs.num_regs))
2393 args_out_of_range (subexp, make_number (search_regs.num_regs));
2394 sub = XINT (subexp);
2397 if (NILP (string))
2399 if (search_regs.start[sub] < BEGV
2400 || search_regs.start[sub] > search_regs.end[sub]
2401 || search_regs.end[sub] > ZV)
2402 args_out_of_range (make_number (search_regs.start[sub]),
2403 make_number (search_regs.end[sub]));
2405 else
2407 if (search_regs.start[sub] < 0
2408 || search_regs.start[sub] > search_regs.end[sub]
2409 || search_regs.end[sub] > SCHARS (string))
2410 args_out_of_range (make_number (search_regs.start[sub]),
2411 make_number (search_regs.end[sub]));
2414 if (NILP (fixedcase))
2416 /* Decide how to casify by examining the matched text. */
2417 ptrdiff_t last;
2419 pos = search_regs.start[sub];
2420 last = search_regs.end[sub];
2422 if (NILP (string))
2423 pos_byte = CHAR_TO_BYTE (pos);
2424 else
2425 pos_byte = string_char_to_byte (string, pos);
2427 prevc = '\n';
2428 case_action = all_caps;
2430 /* some_multiletter_word is set nonzero if any original word
2431 is more than one letter long. */
2432 some_multiletter_word = 0;
2433 some_lowercase = 0;
2434 some_nonuppercase_initial = 0;
2435 some_uppercase = 0;
2437 while (pos < last)
2439 if (NILP (string))
2441 c = FETCH_CHAR_AS_MULTIBYTE (pos_byte);
2442 INC_BOTH (pos, pos_byte);
2444 else
2445 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c, string, pos, pos_byte);
2447 if (lowercasep (c))
2449 /* Cannot be all caps if any original char is lower case */
2451 some_lowercase = 1;
2452 if (SYNTAX (prevc) != Sword)
2453 some_nonuppercase_initial = 1;
2454 else
2455 some_multiletter_word = 1;
2457 else if (uppercasep (c))
2459 some_uppercase = 1;
2460 if (SYNTAX (prevc) != Sword)
2462 else
2463 some_multiletter_word = 1;
2465 else
2467 /* If the initial is a caseless word constituent,
2468 treat that like a lowercase initial. */
2469 if (SYNTAX (prevc) != Sword)
2470 some_nonuppercase_initial = 1;
2473 prevc = c;
2476 /* Convert to all caps if the old text is all caps
2477 and has at least one multiletter word. */
2478 if (! some_lowercase && some_multiletter_word)
2479 case_action = all_caps;
2480 /* Capitalize each word, if the old text has all capitalized words. */
2481 else if (!some_nonuppercase_initial && some_multiletter_word)
2482 case_action = cap_initial;
2483 else if (!some_nonuppercase_initial && some_uppercase)
2484 /* Should x -> yz, operating on X, give Yz or YZ?
2485 We'll assume the latter. */
2486 case_action = all_caps;
2487 else
2488 case_action = nochange;
2491 /* Do replacement in a string. */
2492 if (!NILP (string))
2494 Lisp_Object before, after;
2496 before = Fsubstring (string, make_number (0),
2497 make_number (search_regs.start[sub]));
2498 after = Fsubstring (string, make_number (search_regs.end[sub]), Qnil);
2500 /* Substitute parts of the match into NEWTEXT
2501 if desired. */
2502 if (NILP (literal))
2504 ptrdiff_t lastpos = 0;
2505 ptrdiff_t lastpos_byte = 0;
2506 /* We build up the substituted string in ACCUM. */
2507 Lisp_Object accum;
2508 Lisp_Object middle;
2509 ptrdiff_t length = SBYTES (newtext);
2511 accum = Qnil;
2513 for (pos_byte = 0, pos = 0; pos_byte < length;)
2515 ptrdiff_t substart = -1;
2516 ptrdiff_t subend = 0;
2517 bool delbackslash = 0;
2519 FETCH_STRING_CHAR_ADVANCE (c, newtext, pos, pos_byte);
2521 if (c == '\\')
2523 FETCH_STRING_CHAR_ADVANCE (c, newtext, pos, pos_byte);
2525 if (c == '&')
2527 substart = search_regs.start[sub];
2528 subend = search_regs.end[sub];
2530 else if (c >= '1' && c <= '9')
2532 if (c - '0' < search_regs.num_regs
2533 && search_regs.start[c - '0'] >= 0)
2535 substart = search_regs.start[c - '0'];
2536 subend = search_regs.end[c - '0'];
2538 else
2540 /* If that subexp did not match,
2541 replace \\N with nothing. */
2542 substart = 0;
2543 subend = 0;
2546 else if (c == '\\')
2547 delbackslash = 1;
2548 else if (c != '?')
2549 error ("Invalid use of `\\' in replacement text");
2551 if (substart >= 0)
2553 if (pos - 2 != lastpos)
2554 middle = substring_both (newtext, lastpos,
2555 lastpos_byte,
2556 pos - 2, pos_byte - 2);
2557 else
2558 middle = Qnil;
2559 accum = concat3 (accum, middle,
2560 Fsubstring (string,
2561 make_number (substart),
2562 make_number (subend)));
2563 lastpos = pos;
2564 lastpos_byte = pos_byte;
2566 else if (delbackslash)
2568 middle = substring_both (newtext, lastpos,
2569 lastpos_byte,
2570 pos - 1, pos_byte - 1);
2572 accum = concat2 (accum, middle);
2573 lastpos = pos;
2574 lastpos_byte = pos_byte;
2578 if (pos != lastpos)
2579 middle = substring_both (newtext, lastpos,
2580 lastpos_byte,
2581 pos, pos_byte);
2582 else
2583 middle = Qnil;
2585 newtext = concat2 (accum, middle);
2588 /* Do case substitution in NEWTEXT if desired. */
2589 if (case_action == all_caps)
2590 newtext = Fupcase (newtext);
2591 else if (case_action == cap_initial)
2592 newtext = Fupcase_initials (newtext);
2594 return concat3 (before, newtext, after);
2597 /* Record point, then move (quietly) to the start of the match. */
2598 if (PT >= search_regs.end[sub])
2599 opoint = PT - ZV;
2600 else if (PT > search_regs.start[sub])
2601 opoint = search_regs.end[sub] - ZV;
2602 else
2603 opoint = PT;
2605 /* If we want non-literal replacement,
2606 perform substitution on the replacement string. */
2607 if (NILP (literal))
2609 ptrdiff_t length = SBYTES (newtext);
2610 unsigned char *substed;
2611 ptrdiff_t substed_alloc_size, substed_len;
2612 bool buf_multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
2613 bool str_multibyte = STRING_MULTIBYTE (newtext);
2614 bool really_changed = 0;
2616 substed_alloc_size = (length <= (STRING_BYTES_BOUND - 100) / 2
2617 ? length * 2 + 100
2618 : STRING_BYTES_BOUND);
2619 substed = xmalloc (substed_alloc_size);
2620 substed_len = 0;
2622 /* Go thru NEWTEXT, producing the actual text to insert in
2623 SUBSTED while adjusting multibyteness to that of the current
2624 buffer. */
2626 for (pos_byte = 0, pos = 0; pos_byte < length;)
2628 unsigned char str[MAX_MULTIBYTE_LENGTH];
2629 const unsigned char *add_stuff = NULL;
2630 ptrdiff_t add_len = 0;
2631 ptrdiff_t idx = -1;
2632 ptrdiff_t begbyte UNINIT;
2634 if (str_multibyte)
2636 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, newtext, pos, pos_byte);
2637 if (!buf_multibyte)
2638 c = CHAR_TO_BYTE8 (c);
2640 else
2642 /* Note that we don't have to increment POS. */
2643 c = SREF (newtext, pos_byte++);
2644 if (buf_multibyte)
2645 MAKE_CHAR_MULTIBYTE (c);
2648 /* Either set ADD_STUFF and ADD_LEN to the text to put in SUBSTED,
2649 or set IDX to a match index, which means put that part
2650 of the buffer text into SUBSTED. */
2652 if (c == '\\')
2654 really_changed = 1;
2656 if (str_multibyte)
2658 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, newtext,
2659 pos, pos_byte);
2660 if (!buf_multibyte && !ASCII_CHAR_P (c))
2661 c = CHAR_TO_BYTE8 (c);
2663 else
2665 c = SREF (newtext, pos_byte++);
2666 if (buf_multibyte)
2667 MAKE_CHAR_MULTIBYTE (c);
2670 if (c == '&')
2671 idx = sub;
2672 else if (c >= '1' && c <= '9' && c - '0' < search_regs.num_regs)
2674 if (search_regs.start[c - '0'] >= 1)
2675 idx = c - '0';
2677 else if (c == '\\')
2678 add_len = 1, add_stuff = (unsigned char *) "\\";
2679 else
2681 xfree (substed);
2682 error ("Invalid use of `\\' in replacement text");
2685 else
2687 add_len = CHAR_STRING (c, str);
2688 add_stuff = str;
2691 /* If we want to copy part of a previous match,
2692 set up ADD_STUFF and ADD_LEN to point to it. */
2693 if (idx >= 0)
2695 begbyte = CHAR_TO_BYTE (search_regs.start[idx]);
2696 add_len = CHAR_TO_BYTE (search_regs.end[idx]) - begbyte;
2697 if (search_regs.start[idx] < GPT && GPT < search_regs.end[idx])
2698 move_gap_both (search_regs.start[idx], begbyte);
2701 /* Now the stuff we want to add to SUBSTED
2702 is invariably ADD_LEN bytes starting at ADD_STUFF. */
2704 /* Make sure SUBSTED is big enough. */
2705 if (substed_alloc_size - substed_len < add_len)
2706 substed =
2707 xpalloc (substed, &substed_alloc_size,
2708 add_len - (substed_alloc_size - substed_len),
2709 STRING_BYTES_BOUND, 1);
2711 /* We compute this after the call to xpalloc, because that
2712 could cause buffer text be relocated when ralloc.c is used. */
2713 if (idx >= 0)
2714 add_stuff = BYTE_POS_ADDR (begbyte);
2716 /* Now add to the end of SUBSTED. */
2717 if (add_stuff)
2719 memcpy (substed + substed_len, add_stuff, add_len);
2720 substed_len += add_len;
2724 if (really_changed)
2725 newtext = make_specified_string ((const char *) substed, -1,
2726 substed_len, buf_multibyte);
2727 xfree (substed);
2730 /* The functions below modify the buffer, so they could trigger
2731 various modification hooks (see signal_before_change and
2732 signal_after_change). If these hooks clobber the match data we
2733 error out since otherwise this will result in confusing bugs. */
2734 ptrdiff_t sub_start = search_regs.start[sub];
2735 ptrdiff_t sub_end = search_regs.end[sub];
2736 unsigned num_regs = search_regs.num_regs;
2737 newpoint = search_regs.start[sub] + SCHARS (newtext);
2739 /* Replace the old text with the new in the cleanest possible way. */
2740 replace_range (search_regs.start[sub], search_regs.end[sub],
2741 newtext, 1, 0, 1, 1);
2742 /* Update saved data to match adjustment made by replace_range. */
2744 ptrdiff_t change = newpoint - sub_end;
2745 if (sub_start >= sub_end)
2746 sub_start += change;
2747 sub_end += change;
2750 if (case_action == all_caps)
2751 Fupcase_region (make_number (search_regs.start[sub]),
2752 make_number (newpoint),
2753 Qnil);
2754 else if (case_action == cap_initial)
2755 Fupcase_initials_region (make_number (search_regs.start[sub]),
2756 make_number (newpoint));
2758 if (search_regs.start[sub] != sub_start
2759 || search_regs.end[sub] != sub_end
2760 || search_regs.num_regs != num_regs)
2761 error ("Match data clobbered by buffer modification hooks");
2763 /* Put point back where it was in the text. */
2764 if (opoint <= 0)
2765 TEMP_SET_PT (opoint + ZV);
2766 else
2767 TEMP_SET_PT (opoint);
2769 /* Now move point "officially" to the start of the inserted replacement. */
2770 move_if_not_intangible (newpoint);
2772 return Qnil;
2775 static Lisp_Object
2776 match_limit (Lisp_Object num, bool beginningp)
2778 EMACS_INT n;
2780 CHECK_NUMBER (num);
2781 n = XINT (num);
2782 if (n < 0)
2783 args_out_of_range (num, make_number (0));
2784 if (search_regs.num_regs <= 0)
2785 error ("No match data, because no search succeeded");
2786 if (n >= search_regs.num_regs
2787 || search_regs.start[n] < 0)
2788 return Qnil;
2789 return (make_number ((beginningp) ? search_regs.start[n]
2790 : search_regs.end[n]));
2793 DEFUN ("match-beginning", Fmatch_beginning, Smatch_beginning, 1, 1, 0,
2794 doc: /* Return position of start of text matched by last search.
2795 SUBEXP, a number, specifies which parenthesized expression in the last
2796 regexp.
2797 Value is nil if SUBEXPth pair didn't match, or there were less than
2798 SUBEXP pairs.
2799 Zero means the entire text matched by the whole regexp or whole string.
2801 Return value is undefined if the last search failed. */)
2802 (Lisp_Object subexp)
2804 return match_limit (subexp, 1);
2807 DEFUN ("match-end", Fmatch_end, Smatch_end, 1, 1, 0,
2808 doc: /* Return position of end of text matched by last search.
2809 SUBEXP, a number, specifies which parenthesized expression in the last
2810 regexp.
2811 Value is nil if SUBEXPth pair didn't match, or there were less than
2812 SUBEXP pairs.
2813 Zero means the entire text matched by the whole regexp or whole string.
2815 Return value is undefined if the last search failed. */)
2816 (Lisp_Object subexp)
2818 return match_limit (subexp, 0);
2821 DEFUN ("match-data", Fmatch_data, Smatch_data, 0, 3, 0,
2822 doc: /* Return a list describing what the last search matched.
2823 Element 2N is `(match-beginning N)'; element 2N + 1 is `(match-end N)'.
2824 All the elements are markers or nil (nil if the Nth pair didn't match)
2825 if the last match was on a buffer; integers or nil if a string was matched.
2826 Use `set-match-data' to reinstate the data in this list.
2828 If INTEGERS (the optional first argument) is non-nil, always use
2829 integers (rather than markers) to represent buffer positions. In
2830 this case, and if the last match was in a buffer, the buffer will get
2831 stored as one additional element at the end of the list.
2833 If REUSE is a list, reuse it as part of the value. If REUSE is long
2834 enough to hold all the values, and if INTEGERS is non-nil, no consing
2835 is done.
2837 If optional third arg RESEAT is non-nil, any previous markers on the
2838 REUSE list will be modified to point to nowhere.
2840 Return value is undefined if the last search failed. */)
2841 (Lisp_Object integers, Lisp_Object reuse, Lisp_Object reseat)
2843 Lisp_Object tail, prev;
2844 Lisp_Object *data;
2845 ptrdiff_t i, len;
2847 if (!NILP (reseat))
2848 for (tail = reuse; CONSP (tail); tail = XCDR (tail))
2849 if (MARKERP (XCAR (tail)))
2851 unchain_marker (XMARKER (XCAR (tail)));
2852 XSETCAR (tail, Qnil);
2855 if (NILP (last_thing_searched))
2856 return Qnil;
2858 prev = Qnil;
2860 USE_SAFE_ALLOCA;
2861 SAFE_NALLOCA (data, 1, 2 * search_regs.num_regs + 1);
2863 len = 0;
2864 for (i = 0; i < search_regs.num_regs; i++)
2866 ptrdiff_t start = search_regs.start[i];
2867 if (start >= 0)
2869 if (EQ (last_thing_searched, Qt)
2870 || ! NILP (integers))
2872 XSETFASTINT (data[2 * i], start);
2873 XSETFASTINT (data[2 * i + 1], search_regs.end[i]);
2875 else if (BUFFERP (last_thing_searched))
2877 data[2 * i] = Fmake_marker ();
2878 Fset_marker (data[2 * i],
2879 make_number (start),
2880 last_thing_searched);
2881 data[2 * i + 1] = Fmake_marker ();
2882 Fset_marker (data[2 * i + 1],
2883 make_number (search_regs.end[i]),
2884 last_thing_searched);
2886 else
2887 /* last_thing_searched must always be Qt, a buffer, or Qnil. */
2888 emacs_abort ();
2890 len = 2 * i + 2;
2892 else
2893 data[2 * i] = data[2 * i + 1] = Qnil;
2896 if (BUFFERP (last_thing_searched) && !NILP (integers))
2898 data[len] = last_thing_searched;
2899 len++;
2902 /* If REUSE is not usable, cons up the values and return them. */
2903 if (! CONSP (reuse))
2904 reuse = Flist (len, data);
2905 else
2907 /* If REUSE is a list, store as many value elements as will fit
2908 into the elements of REUSE. */
2909 for (i = 0, tail = reuse; CONSP (tail);
2910 i++, tail = XCDR (tail))
2912 if (i < len)
2913 XSETCAR (tail, data[i]);
2914 else
2915 XSETCAR (tail, Qnil);
2916 prev = tail;
2919 /* If we couldn't fit all value elements into REUSE,
2920 cons up the rest of them and add them to the end of REUSE. */
2921 if (i < len)
2922 XSETCDR (prev, Flist (len - i, data + i));
2925 SAFE_FREE ();
2926 return reuse;
2929 /* We used to have an internal use variant of `reseat' described as:
2931 If RESEAT is `evaporate', put the markers back on the free list
2932 immediately. No other references to the markers must exist in this
2933 case, so it is used only internally on the unwind stack and
2934 save-match-data from Lisp.
2936 But it was ill-conceived: those supposedly-internal markers get exposed via
2937 the undo-list, so freeing them here is unsafe. */
2939 DEFUN ("set-match-data", Fset_match_data, Sset_match_data, 1, 2, 0,
2940 doc: /* Set internal data on last search match from elements of LIST.
2941 LIST should have been created by calling `match-data' previously.
2943 If optional arg RESEAT is non-nil, make markers on LIST point nowhere. */)
2944 (register Lisp_Object list, Lisp_Object reseat)
2946 ptrdiff_t i;
2947 register Lisp_Object marker;
2949 if (running_asynch_code)
2950 save_search_regs ();
2952 CHECK_LIST (list);
2954 /* Unless we find a marker with a buffer or an explicit buffer
2955 in LIST, assume that this match data came from a string. */
2956 last_thing_searched = Qt;
2958 /* Allocate registers if they don't already exist. */
2960 EMACS_INT length = XFASTINT (Flength (list)) / 2;
2962 if (length > search_regs.num_regs)
2964 ptrdiff_t num_regs = search_regs.num_regs;
2965 if (PTRDIFF_MAX < length)
2966 memory_full (SIZE_MAX);
2967 search_regs.start =
2968 xpalloc (search_regs.start, &num_regs, length - num_regs,
2969 min (PTRDIFF_MAX, UINT_MAX), sizeof (regoff_t));
2970 search_regs.end =
2971 xrealloc (search_regs.end, num_regs * sizeof (regoff_t));
2973 for (i = search_regs.num_regs; i < num_regs; i++)
2974 search_regs.start[i] = -1;
2976 search_regs.num_regs = num_regs;
2979 for (i = 0; CONSP (list); i++)
2981 marker = XCAR (list);
2982 if (BUFFERP (marker))
2984 last_thing_searched = marker;
2985 break;
2987 if (i >= length)
2988 break;
2989 if (NILP (marker))
2991 search_regs.start[i] = -1;
2992 list = XCDR (list);
2994 else
2996 Lisp_Object from;
2997 Lisp_Object m;
2999 m = marker;
3000 if (MARKERP (marker))
3002 if (XMARKER (marker)->buffer == 0)
3003 XSETFASTINT (marker, 0);
3004 else
3005 XSETBUFFER (last_thing_searched, XMARKER (marker)->buffer);
3008 CHECK_NUMBER_COERCE_MARKER (marker);
3009 from = marker;
3011 if (!NILP (reseat) && MARKERP (m))
3013 unchain_marker (XMARKER (m));
3014 XSETCAR (list, Qnil);
3017 if ((list = XCDR (list), !CONSP (list)))
3018 break;
3020 m = marker = XCAR (list);
3022 if (MARKERP (marker) && XMARKER (marker)->buffer == 0)
3023 XSETFASTINT (marker, 0);
3025 CHECK_NUMBER_COERCE_MARKER (marker);
3026 if ((XINT (from) < 0
3027 ? TYPE_MINIMUM (regoff_t) <= XINT (from)
3028 : XINT (from) <= TYPE_MAXIMUM (regoff_t))
3029 && (XINT (marker) < 0
3030 ? TYPE_MINIMUM (regoff_t) <= XINT (marker)
3031 : XINT (marker) <= TYPE_MAXIMUM (regoff_t)))
3033 search_regs.start[i] = XINT (from);
3034 search_regs.end[i] = XINT (marker);
3036 else
3038 search_regs.start[i] = -1;
3041 if (!NILP (reseat) && MARKERP (m))
3043 unchain_marker (XMARKER (m));
3044 XSETCAR (list, Qnil);
3047 list = XCDR (list);
3050 for (; i < search_regs.num_regs; i++)
3051 search_regs.start[i] = -1;
3054 return Qnil;
3057 /* If true the match data have been saved in saved_search_regs
3058 during the execution of a sentinel or filter. */
3059 /* static bool search_regs_saved; */
3060 /* static struct re_registers saved_search_regs; */
3061 /* static Lisp_Object saved_last_thing_searched; */
3063 /* Called from Flooking_at, Fstring_match, search_buffer, Fstore_match_data
3064 if asynchronous code (filter or sentinel) is running. */
3065 static void
3066 save_search_regs (void)
3068 if (!search_regs_saved)
3070 saved_search_regs.num_regs = search_regs.num_regs;
3071 saved_search_regs.start = search_regs.start;
3072 saved_search_regs.end = search_regs.end;
3073 saved_last_thing_searched = last_thing_searched;
3074 last_thing_searched = Qnil;
3075 search_regs.num_regs = 0;
3076 search_regs.start = 0;
3077 search_regs.end = 0;
3079 search_regs_saved = 1;
3083 /* Called upon exit from filters and sentinels. */
3084 void
3085 restore_search_regs (void)
3087 if (search_regs_saved)
3089 if (search_regs.num_regs > 0)
3091 xfree (search_regs.start);
3092 xfree (search_regs.end);
3094 search_regs.num_regs = saved_search_regs.num_regs;
3095 search_regs.start = saved_search_regs.start;
3096 search_regs.end = saved_search_regs.end;
3097 last_thing_searched = saved_last_thing_searched;
3098 saved_last_thing_searched = Qnil;
3099 search_regs_saved = 0;
3103 /* Called from replace-match via replace_range. */
3104 void
3105 update_search_regs (ptrdiff_t oldstart, ptrdiff_t oldend, ptrdiff_t newend)
3107 /* Adjust search data for this change. */
3108 ptrdiff_t change = newend - oldend;
3109 ptrdiff_t i;
3111 for (i = 0; i < search_regs.num_regs; i++)
3113 if (search_regs.start[i] >= oldend)
3114 search_regs.start[i] += change;
3115 else if (search_regs.start[i] > oldstart)
3116 search_regs.start[i] = oldstart;
3117 if (search_regs.end[i] >= oldend)
3118 search_regs.end[i] += change;
3119 else if (search_regs.end[i] > oldstart)
3120 search_regs.end[i] = oldstart;
3124 static void
3125 unwind_set_match_data (Lisp_Object list)
3127 /* It is NOT ALWAYS safe to free (evaporate) the markers immediately. */
3128 Fset_match_data (list, Qt);
3131 /* Called to unwind protect the match data. */
3132 void
3133 record_unwind_save_match_data (void)
3135 record_unwind_protect (unwind_set_match_data,
3136 Fmatch_data (Qnil, Qnil, Qnil));
3139 /* Quote a string to deactivate reg-expr chars */
3141 DEFUN ("regexp-quote", Fregexp_quote, Sregexp_quote, 1, 1, 0,
3142 doc: /* Return a regexp string which matches exactly STRING and nothing else. */)
3143 (Lisp_Object string)
3145 char *in, *out, *end;
3146 char *temp;
3147 ptrdiff_t backslashes_added = 0;
3149 CHECK_STRING (string);
3151 USE_SAFE_ALLOCA;
3152 SAFE_NALLOCA (temp, 2, SBYTES (string));
3154 /* Now copy the data into the new string, inserting escapes. */
3156 in = SSDATA (string);
3157 end = in + SBYTES (string);
3158 out = temp;
3160 for (; in != end; in++)
3162 if (*in == '['
3163 || *in == '*' || *in == '.' || *in == '\\'
3164 || *in == '?' || *in == '+'
3165 || *in == '^' || *in == '$')
3166 *out++ = '\\', backslashes_added++;
3167 *out++ = *in;
3170 Lisp_Object result
3171 = make_specified_string (temp,
3172 SCHARS (string) + backslashes_added,
3173 out - temp,
3174 STRING_MULTIBYTE (string));
3175 SAFE_FREE ();
3176 return result;
3179 /* Like find_newline, but doesn't use the cache, and only searches forward. */
3180 static ptrdiff_t
3181 find_newline1 (ptrdiff_t start, ptrdiff_t start_byte, ptrdiff_t end,
3182 ptrdiff_t end_byte, ptrdiff_t count, ptrdiff_t *shortage,
3183 ptrdiff_t *bytepos, bool allow_quit)
3185 if (count > 0)
3187 if (!end)
3188 end = ZV, end_byte = ZV_BYTE;
3190 else
3192 if (!end)
3193 end = BEGV, end_byte = BEGV_BYTE;
3195 if (end_byte == -1)
3196 end_byte = CHAR_TO_BYTE (end);
3198 if (shortage != 0)
3199 *shortage = 0;
3201 if (count > 0)
3202 while (start != end)
3204 /* Our innermost scanning loop is very simple; it doesn't know
3205 about gaps, buffer ends, or the newline cache. ceiling is
3206 the position of the last character before the next such
3207 obstacle --- the last character the dumb search loop should
3208 examine. */
3209 ptrdiff_t tem, ceiling_byte = end_byte - 1;
3211 if (start_byte == -1)
3212 start_byte = CHAR_TO_BYTE (start);
3214 /* The dumb loop can only scan text stored in contiguous
3215 bytes. BUFFER_CEILING_OF returns the last character
3216 position that is contiguous, so the ceiling is the
3217 position after that. */
3218 tem = BUFFER_CEILING_OF (start_byte);
3219 ceiling_byte = min (tem, ceiling_byte);
3222 /* The termination address of the dumb loop. */
3223 unsigned char *lim_addr = BYTE_POS_ADDR (ceiling_byte) + 1;
3224 ptrdiff_t lim_byte = ceiling_byte + 1;
3226 /* Nonpositive offsets (relative to LIM_ADDR and LIM_BYTE)
3227 of the base, the cursor, and the next line. */
3228 ptrdiff_t base = start_byte - lim_byte;
3229 ptrdiff_t cursor, next;
3231 for (cursor = base; cursor < 0; cursor = next)
3233 /* The dumb loop. */
3234 unsigned char *nl = memchr (lim_addr + cursor, '\n', - cursor);
3235 next = nl ? nl - lim_addr : 0;
3237 if (! nl)
3238 break;
3239 next++;
3241 if (--count == 0)
3243 if (bytepos)
3244 *bytepos = lim_byte + next;
3245 return BYTE_TO_CHAR (lim_byte + next);
3247 if (allow_quit)
3248 maybe_quit ();
3251 start_byte = lim_byte;
3252 start = BYTE_TO_CHAR (start_byte);
3256 if (shortage)
3257 *shortage = count;
3258 if (bytepos)
3260 *bytepos = start_byte == -1 ? CHAR_TO_BYTE (start) : start_byte;
3261 eassert (*bytepos == CHAR_TO_BYTE (start));
3263 return start;
3266 DEFUN ("newline-cache-check", Fnewline_cache_check, Snewline_cache_check,
3267 0, 1, 0,
3268 doc: /* Check the newline cache of BUFFER against buffer contents.
3270 BUFFER defaults to the current buffer.
3272 Value is an array of 2 sub-arrays of buffer positions for newlines,
3273 the first based on the cache, the second based on actually scanning
3274 the buffer. If the buffer doesn't have a cache, the value is nil. */)
3275 (Lisp_Object buffer)
3277 struct buffer *buf, *old = NULL;
3278 ptrdiff_t shortage, nl_count_cache, nl_count_buf;
3279 Lisp_Object cache_newlines, buf_newlines, val;
3280 ptrdiff_t from, found, i;
3282 if (NILP (buffer))
3283 buf = current_buffer;
3284 else
3286 CHECK_BUFFER (buffer);
3287 buf = XBUFFER (buffer);
3288 old = current_buffer;
3290 if (buf->base_buffer)
3291 buf = buf->base_buffer;
3293 /* If the buffer doesn't have a newline cache, return nil. */
3294 if (NILP (BVAR (buf, cache_long_scans))
3295 || buf->newline_cache == NULL)
3296 return Qnil;
3298 /* find_newline can only work on the current buffer. */
3299 if (old != NULL)
3300 set_buffer_internal_1 (buf);
3302 /* How many newlines are there according to the cache? */
3303 find_newline (BEGV, BEGV_BYTE, ZV, ZV_BYTE,
3304 TYPE_MAXIMUM (ptrdiff_t), &shortage, NULL, true);
3305 nl_count_cache = TYPE_MAXIMUM (ptrdiff_t) - shortage;
3307 /* Create vector and populate it. */
3308 cache_newlines = make_uninit_vector (nl_count_cache);
3310 if (nl_count_cache)
3312 for (from = BEGV, found = from, i = 0; from < ZV; from = found, i++)
3314 ptrdiff_t from_byte = CHAR_TO_BYTE (from);
3316 found = find_newline (from, from_byte, 0, -1, 1, &shortage,
3317 NULL, true);
3318 if (shortage != 0 || i >= nl_count_cache)
3319 break;
3320 ASET (cache_newlines, i, make_number (found - 1));
3322 /* Fill the rest of slots with an invalid position. */
3323 for ( ; i < nl_count_cache; i++)
3324 ASET (cache_newlines, i, make_number (-1));
3327 /* Now do the same, but without using the cache. */
3328 find_newline1 (BEGV, BEGV_BYTE, ZV, ZV_BYTE,
3329 TYPE_MAXIMUM (ptrdiff_t), &shortage, NULL, true);
3330 nl_count_buf = TYPE_MAXIMUM (ptrdiff_t) - shortage;
3331 buf_newlines = make_uninit_vector (nl_count_buf);
3332 if (nl_count_buf)
3334 for (from = BEGV, found = from, i = 0; from < ZV; from = found, i++)
3336 ptrdiff_t from_byte = CHAR_TO_BYTE (from);
3338 found = find_newline1 (from, from_byte, 0, -1, 1, &shortage,
3339 NULL, true);
3340 if (shortage != 0 || i >= nl_count_buf)
3341 break;
3342 ASET (buf_newlines, i, make_number (found - 1));
3344 for ( ; i < nl_count_buf; i++)
3345 ASET (buf_newlines, i, make_number (-1));
3348 /* Construct the value and return it. */
3349 val = make_uninit_vector (2);
3350 ASET (val, 0, cache_newlines);
3351 ASET (val, 1, buf_newlines);
3353 if (old != NULL)
3354 set_buffer_internal_1 (old);
3355 return val;
3358 void
3359 syms_of_search (void)
3361 register int i;
3363 for (i = 0; i < REGEXP_CACHE_SIZE; ++i)
3365 searchbufs[i].buf.allocated = 100;
3366 searchbufs[i].buf.buffer = xmalloc (100);
3367 searchbufs[i].buf.fastmap = searchbufs[i].fastmap;
3368 searchbufs[i].regexp = Qnil;
3369 searchbufs[i].f_whitespace_regexp = Qnil;
3370 searchbufs[i].syntax_table = Qnil;
3371 staticpro (&searchbufs[i].regexp);
3372 staticpro (&searchbufs[i].f_whitespace_regexp);
3373 staticpro (&searchbufs[i].syntax_table);
3374 searchbufs[i].next = (i == REGEXP_CACHE_SIZE-1 ? 0 : &searchbufs[i+1]);
3376 searchbuf_head = &searchbufs[0];
3378 /* Error condition used for failing searches. */
3379 DEFSYM (Qsearch_failed, "search-failed");
3381 /* Error condition used for failing searches started by user, i.e.,
3382 where failure should not invoke the debugger. */
3383 DEFSYM (Quser_search_failed, "user-search-failed");
3385 /* Error condition signaled when regexp compile_pattern fails. */
3386 DEFSYM (Qinvalid_regexp, "invalid-regexp");
3388 Fput (Qsearch_failed, Qerror_conditions,
3389 listn (CONSTYPE_PURE, 2, Qsearch_failed, Qerror));
3390 Fput (Qsearch_failed, Qerror_message,
3391 build_pure_c_string ("Search failed"));
3393 Fput (Quser_search_failed, Qerror_conditions,
3394 listn (CONSTYPE_PURE, 4,
3395 Quser_search_failed, Quser_error, Qsearch_failed, Qerror));
3396 Fput (Quser_search_failed, Qerror_message,
3397 build_pure_c_string ("Search failed"));
3399 Fput (Qinvalid_regexp, Qerror_conditions,
3400 listn (CONSTYPE_PURE, 2, Qinvalid_regexp, Qerror));
3401 Fput (Qinvalid_regexp, Qerror_message,
3402 build_pure_c_string ("Invalid regexp"));
3404 last_thing_searched = Qnil;
3405 staticpro (&last_thing_searched);
3407 saved_last_thing_searched = Qnil;
3408 staticpro (&saved_last_thing_searched);
3410 DEFVAR_LISP ("search-spaces-regexp", Vsearch_spaces_regexp,
3411 doc: /* Regexp to substitute for bunches of spaces in regexp search.
3412 Some commands use this for user-specified regexps.
3413 Spaces that occur inside character classes or repetition operators
3414 or other such regexp constructs are not replaced with this.
3415 A value of nil (which is the normal value) means treat spaces literally. */);
3416 Vsearch_spaces_regexp = Qnil;
3418 DEFSYM (Qinhibit_changing_match_data, "inhibit-changing-match-data");
3419 DEFVAR_LISP ("inhibit-changing-match-data", Vinhibit_changing_match_data,
3420 doc: /* Internal use only.
3421 If non-nil, the primitive searching and matching functions
3422 such as `looking-at', `string-match', `re-search-forward', etc.,
3423 do not set the match data. The proper way to use this variable
3424 is to bind it with `let' around a small expression. */);
3425 Vinhibit_changing_match_data = Qnil;
3427 defsubr (&Slooking_at);
3428 defsubr (&Sposix_looking_at);
3429 defsubr (&Sstring_match);
3430 defsubr (&Sposix_string_match);
3431 defsubr (&Ssearch_forward);
3432 defsubr (&Ssearch_backward);
3433 defsubr (&Sre_search_forward);
3434 defsubr (&Sre_search_backward);
3435 defsubr (&Sposix_search_forward);
3436 defsubr (&Sposix_search_backward);
3437 defsubr (&Sreplace_match);
3438 defsubr (&Smatch_beginning);
3439 defsubr (&Smatch_end);
3440 defsubr (&Smatch_data);
3441 defsubr (&Sset_match_data);
3442 defsubr (&Sregexp_quote);
3443 defsubr (&Snewline_cache_check);