; * lisp/ldefs-boot.el: Update.
[emacs.git] / src / search.c
blob9bde884bc53bf48d545b6c6b2d4cd6b086dbd2b6
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.
1346 ??? Perhaps this conversion should be done in a special way
1347 by subtracting nonascii-insert-offset from each non-ASCII char,
1348 so that only the multibyte chars which really correspond to
1349 the chosen single-byte character set can possibly match. */
1350 raw_pattern_size = SCHARS (string);
1351 raw_pattern_size_byte = SCHARS (string);
1352 raw_pattern = SAFE_ALLOCA (raw_pattern_size + 1);
1353 copy_text (SDATA (string), raw_pattern,
1354 SBYTES (string), 1, 0);
1357 /* Copy and optionally translate the pattern. */
1358 len = raw_pattern_size;
1359 len_byte = raw_pattern_size_byte;
1360 SAFE_NALLOCA (patbuf, MAX_MULTIBYTE_LENGTH, len);
1361 pat = patbuf;
1362 base_pat = raw_pattern;
1363 if (multibyte)
1365 /* Fill patbuf by translated characters in STRING while
1366 checking if we can use boyer-moore search. If TRT is
1367 non-nil, we can use boyer-moore search only if TRT can be
1368 represented by the byte array of 256 elements. For that,
1369 all non-ASCII case-equivalents of all case-sensitive
1370 characters in STRING must belong to the same character
1371 group (two characters belong to the same group iff their
1372 multibyte forms are the same except for the last byte;
1373 i.e. every 64 characters form a group; U+0000..U+003F,
1374 U+0040..U+007F, U+0080..U+00BF, ...). */
1376 while (--len >= 0)
1378 unsigned char str_base[MAX_MULTIBYTE_LENGTH], *str;
1379 int c, translated, inverse;
1380 int in_charlen, charlen;
1382 /* If we got here and the RE flag is set, it's because we're
1383 dealing with a regexp known to be trivial, so the backslash
1384 just quotes the next character. */
1385 if (RE && *base_pat == '\\')
1387 len--;
1388 raw_pattern_size--;
1389 len_byte--;
1390 base_pat++;
1393 c = STRING_CHAR_AND_LENGTH (base_pat, in_charlen);
1395 if (NILP (trt))
1397 str = base_pat;
1398 charlen = in_charlen;
1400 else
1402 /* Translate the character. */
1403 TRANSLATE (translated, trt, c);
1404 charlen = CHAR_STRING (translated, str_base);
1405 str = str_base;
1407 /* Check if C has any other case-equivalents. */
1408 TRANSLATE (inverse, inverse_trt, c);
1409 /* If so, check if we can use boyer-moore. */
1410 if (c != inverse && boyer_moore_ok)
1412 /* Check if all equivalents belong to the same
1413 group of characters. Note that the check of C
1414 itself is done by the last iteration. */
1415 int this_char_base = -1;
1417 while (boyer_moore_ok)
1419 if (ASCII_CHAR_P (inverse))
1421 if (this_char_base > 0)
1422 boyer_moore_ok = 0;
1423 else
1424 this_char_base = 0;
1426 else if (CHAR_BYTE8_P (inverse))
1427 /* Boyer-moore search can't handle a
1428 translation of an eight-bit
1429 character. */
1430 boyer_moore_ok = 0;
1431 else if (this_char_base < 0)
1433 this_char_base = inverse & ~0x3F;
1434 if (char_base < 0)
1435 char_base = this_char_base;
1436 else if (this_char_base != char_base)
1437 boyer_moore_ok = 0;
1439 else if ((inverse & ~0x3F) != this_char_base)
1440 boyer_moore_ok = 0;
1441 if (c == inverse)
1442 break;
1443 TRANSLATE (inverse, inverse_trt, inverse);
1448 /* Store this character into the translated pattern. */
1449 memcpy (pat, str, charlen);
1450 pat += charlen;
1451 base_pat += in_charlen;
1452 len_byte -= in_charlen;
1455 /* If char_base is still negative we didn't find any translated
1456 non-ASCII characters. */
1457 if (char_base < 0)
1458 char_base = 0;
1460 else
1462 /* Unibyte buffer. */
1463 char_base = 0;
1464 while (--len >= 0)
1466 int c, translated, inverse;
1468 /* If we got here and the RE flag is set, it's because we're
1469 dealing with a regexp known to be trivial, so the backslash
1470 just quotes the next character. */
1471 if (RE && *base_pat == '\\')
1473 len--;
1474 raw_pattern_size--;
1475 base_pat++;
1477 c = *base_pat++;
1478 TRANSLATE (translated, trt, c);
1479 *pat++ = translated;
1480 /* Check that none of C's equivalents violates the
1481 assumptions of boyer_moore. */
1482 TRANSLATE (inverse, inverse_trt, c);
1483 while (1)
1485 if (inverse >= 0200)
1487 boyer_moore_ok = 0;
1488 break;
1490 if (c == inverse)
1491 break;
1492 TRANSLATE (inverse, inverse_trt, inverse);
1497 len_byte = pat - patbuf;
1498 pat = base_pat = patbuf;
1500 EMACS_INT result
1501 = (boyer_moore_ok
1502 ? boyer_moore (n, pat, len_byte, trt, inverse_trt,
1503 pos_byte, lim_byte,
1504 char_base)
1505 : simple_search (n, pat, raw_pattern_size, len_byte, trt,
1506 pos, pos_byte, lim, lim_byte));
1507 SAFE_FREE ();
1508 return result;
1512 /* Do a simple string search N times for the string PAT,
1513 whose length is LEN/LEN_BYTE,
1514 from buffer position POS/POS_BYTE until LIM/LIM_BYTE.
1515 TRT is the translation table.
1517 Return the character position where the match is found.
1518 Otherwise, if M matches remained to be found, return -M.
1520 This kind of search works regardless of what is in PAT and
1521 regardless of what is in TRT. It is used in cases where
1522 boyer_moore cannot work. */
1524 static EMACS_INT
1525 simple_search (EMACS_INT n, unsigned char *pat,
1526 ptrdiff_t len, ptrdiff_t len_byte, Lisp_Object trt,
1527 ptrdiff_t pos, ptrdiff_t pos_byte,
1528 ptrdiff_t lim, ptrdiff_t lim_byte)
1530 bool multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
1531 bool forward = n > 0;
1532 /* Number of buffer bytes matched. Note that this may be different
1533 from len_byte in a multibyte buffer. */
1534 ptrdiff_t match_byte = PTRDIFF_MIN;
1536 if (lim > pos && multibyte)
1537 while (n > 0)
1539 while (1)
1541 /* Try matching at position POS. */
1542 ptrdiff_t this_pos = pos;
1543 ptrdiff_t this_pos_byte = pos_byte;
1544 ptrdiff_t this_len = len;
1545 unsigned char *p = pat;
1546 if (pos + len > lim || pos_byte + len_byte > lim_byte)
1547 goto stop;
1549 while (this_len > 0)
1551 int charlen, buf_charlen;
1552 int pat_ch, buf_ch;
1554 pat_ch = STRING_CHAR_AND_LENGTH (p, charlen);
1555 buf_ch = STRING_CHAR_AND_LENGTH (BYTE_POS_ADDR (this_pos_byte),
1556 buf_charlen);
1557 TRANSLATE (buf_ch, trt, buf_ch);
1559 if (buf_ch != pat_ch)
1560 break;
1562 this_len--;
1563 p += charlen;
1565 this_pos_byte += buf_charlen;
1566 this_pos++;
1569 if (this_len == 0)
1571 match_byte = this_pos_byte - pos_byte;
1572 pos += len;
1573 pos_byte += match_byte;
1574 break;
1577 INC_BOTH (pos, pos_byte);
1580 n--;
1582 else if (lim > pos)
1583 while (n > 0)
1585 while (1)
1587 /* Try matching at position POS. */
1588 ptrdiff_t this_pos = pos;
1589 ptrdiff_t this_len = len;
1590 unsigned char *p = pat;
1592 if (pos + len > lim)
1593 goto stop;
1595 while (this_len > 0)
1597 int pat_ch = *p++;
1598 int buf_ch = FETCH_BYTE (this_pos);
1599 TRANSLATE (buf_ch, trt, buf_ch);
1601 if (buf_ch != pat_ch)
1602 break;
1604 this_len--;
1605 this_pos++;
1608 if (this_len == 0)
1610 match_byte = len;
1611 pos += len;
1612 break;
1615 pos++;
1618 n--;
1620 /* Backwards search. */
1621 else if (lim < pos && multibyte)
1622 while (n < 0)
1624 while (1)
1626 /* Try matching at position POS. */
1627 ptrdiff_t this_pos = pos;
1628 ptrdiff_t this_pos_byte = pos_byte;
1629 ptrdiff_t this_len = len;
1630 const unsigned char *p = pat + len_byte;
1632 if (this_pos - len < lim || (pos_byte - len_byte) < lim_byte)
1633 goto stop;
1635 while (this_len > 0)
1637 int pat_ch, buf_ch;
1639 DEC_BOTH (this_pos, this_pos_byte);
1640 PREV_CHAR_BOUNDARY (p, pat);
1641 pat_ch = STRING_CHAR (p);
1642 buf_ch = STRING_CHAR (BYTE_POS_ADDR (this_pos_byte));
1643 TRANSLATE (buf_ch, trt, buf_ch);
1645 if (buf_ch != pat_ch)
1646 break;
1648 this_len--;
1651 if (this_len == 0)
1653 match_byte = pos_byte - this_pos_byte;
1654 pos = this_pos;
1655 pos_byte = this_pos_byte;
1656 break;
1659 DEC_BOTH (pos, pos_byte);
1662 n++;
1664 else if (lim < pos)
1665 while (n < 0)
1667 while (1)
1669 /* Try matching at position POS. */
1670 ptrdiff_t this_pos = pos - len;
1671 ptrdiff_t this_len = len;
1672 unsigned char *p = pat;
1674 if (this_pos < lim)
1675 goto stop;
1677 while (this_len > 0)
1679 int pat_ch = *p++;
1680 int buf_ch = FETCH_BYTE (this_pos);
1681 TRANSLATE (buf_ch, trt, buf_ch);
1683 if (buf_ch != pat_ch)
1684 break;
1685 this_len--;
1686 this_pos++;
1689 if (this_len == 0)
1691 match_byte = len;
1692 pos -= len;
1693 break;
1696 pos--;
1699 n++;
1702 stop:
1703 if (n == 0)
1705 eassert (match_byte != PTRDIFF_MIN);
1706 if (forward)
1707 set_search_regs ((multibyte ? pos_byte : pos) - match_byte, match_byte);
1708 else
1709 set_search_regs (multibyte ? pos_byte : pos, match_byte);
1711 return pos;
1713 else if (n > 0)
1714 return -n;
1715 else
1716 return n;
1719 /* Do Boyer-Moore search N times for the string BASE_PAT,
1720 whose length is LEN_BYTE,
1721 from buffer position POS_BYTE until LIM_BYTE.
1722 DIRECTION says which direction we search in.
1723 TRT and INVERSE_TRT are translation tables.
1724 Characters in PAT are already translated by TRT.
1726 This kind of search works if all the characters in BASE_PAT that
1727 have nontrivial translation are the same aside from the last byte.
1728 This makes it possible to translate just the last byte of a
1729 character, and do so after just a simple test of the context.
1730 CHAR_BASE is nonzero if there is such a non-ASCII character.
1732 If that criterion is not satisfied, do not call this function. */
1734 static EMACS_INT
1735 boyer_moore (EMACS_INT n, unsigned char *base_pat,
1736 ptrdiff_t len_byte,
1737 Lisp_Object trt, Lisp_Object inverse_trt,
1738 ptrdiff_t pos_byte, ptrdiff_t lim_byte,
1739 int char_base)
1741 int direction = ((n > 0) ? 1 : -1);
1742 register ptrdiff_t dirlen;
1743 ptrdiff_t limit;
1744 int stride_for_teases = 0;
1745 int BM_tab[0400];
1746 register unsigned char *cursor, *p_limit;
1747 register ptrdiff_t i;
1748 register int j;
1749 unsigned char *pat, *pat_end;
1750 bool multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
1752 unsigned char simple_translate[0400];
1753 /* These are set to the preceding bytes of a byte to be translated
1754 if char_base is nonzero. As the maximum byte length of a
1755 multibyte character is 5, we have to check at most four previous
1756 bytes. */
1757 int translate_prev_byte1 = 0;
1758 int translate_prev_byte2 = 0;
1759 int translate_prev_byte3 = 0;
1761 /* The general approach is that we are going to maintain that we know
1762 the first (closest to the present position, in whatever direction
1763 we're searching) character that could possibly be the last
1764 (furthest from present position) character of a valid match. We
1765 advance the state of our knowledge by looking at that character
1766 and seeing whether it indeed matches the last character of the
1767 pattern. If it does, we take a closer look. If it does not, we
1768 move our pointer (to putative last characters) as far as is
1769 logically possible. This amount of movement, which I call a
1770 stride, will be the length of the pattern if the actual character
1771 appears nowhere in the pattern, otherwise it will be the distance
1772 from the last occurrence of that character to the end of the
1773 pattern. If the amount is zero we have a possible match. */
1775 /* Here we make a "mickey mouse" BM table. The stride of the search
1776 is determined only by the last character of the putative match.
1777 If that character does not match, we will stride the proper
1778 distance to propose a match that superimposes it on the last
1779 instance of a character that matches it (per trt), or misses
1780 it entirely if there is none. */
1782 dirlen = len_byte * direction;
1784 /* Record position after the end of the pattern. */
1785 pat_end = base_pat + len_byte;
1786 /* BASE_PAT points to a character that we start scanning from.
1787 It is the first character in a forward search,
1788 the last character in a backward search. */
1789 if (direction < 0)
1790 base_pat = pat_end - 1;
1792 /* A character that does not appear in the pattern induces a
1793 stride equal to the pattern length. */
1794 for (i = 0; i < 0400; i++)
1795 BM_tab[i] = dirlen;
1797 /* We use this for translation, instead of TRT itself.
1798 We fill this in to handle the characters that actually
1799 occur in the pattern. Others don't matter anyway! */
1800 for (i = 0; i < 0400; i++)
1801 simple_translate[i] = i;
1803 if (char_base)
1805 /* Setup translate_prev_byte1/2/3/4 from CHAR_BASE. Only a
1806 byte following them are the target of translation. */
1807 eassume (0x80 <= char_base && char_base <= MAX_CHAR);
1808 unsigned char str[MAX_MULTIBYTE_LENGTH];
1809 int cblen = CHAR_STRING (char_base, str);
1811 translate_prev_byte1 = str[cblen - 2];
1812 if (cblen > 2)
1814 translate_prev_byte2 = str[cblen - 3];
1815 if (cblen > 3)
1816 translate_prev_byte3 = str[cblen - 4];
1820 i = 0;
1821 while (i != dirlen)
1823 unsigned char *ptr = base_pat + i;
1824 i += direction;
1825 if (! NILP (trt))
1827 /* If the byte currently looking at is the last of a
1828 character to check case-equivalents, set CH to that
1829 character. An ASCII character and a non-ASCII character
1830 matching with CHAR_BASE are to be checked. */
1831 int ch = -1;
1833 if (ASCII_CHAR_P (*ptr) || ! multibyte)
1834 ch = *ptr;
1835 else if (char_base
1836 && ((pat_end - ptr) == 1 || CHAR_HEAD_P (ptr[1])))
1838 unsigned char *charstart = ptr - 1;
1840 while (! (CHAR_HEAD_P (*charstart)))
1841 charstart--;
1842 ch = STRING_CHAR (charstart);
1843 if (char_base != (ch & ~0x3F))
1844 ch = -1;
1847 if (ch >= 0200 && multibyte)
1848 j = (ch & 0x3F) | 0200;
1849 else
1850 j = *ptr;
1852 if (i == dirlen)
1853 stride_for_teases = BM_tab[j];
1855 BM_tab[j] = dirlen - i;
1856 /* A translation table is accompanied by its inverse -- see
1857 comment following downcase_table for details. */
1858 if (ch >= 0)
1860 int starting_ch = ch;
1861 int starting_j = j;
1863 while (1)
1865 TRANSLATE (ch, inverse_trt, ch);
1866 if (ch >= 0200 && multibyte)
1867 j = (ch & 0x3F) | 0200;
1868 else
1869 j = ch;
1871 /* For all the characters that map into CH,
1872 set up simple_translate to map the last byte
1873 into STARTING_J. */
1874 simple_translate[j] = starting_j;
1875 if (ch == starting_ch)
1876 break;
1877 BM_tab[j] = dirlen - i;
1881 else
1883 j = *ptr;
1885 if (i == dirlen)
1886 stride_for_teases = BM_tab[j];
1887 BM_tab[j] = dirlen - i;
1889 /* stride_for_teases tells how much to stride if we get a
1890 match on the far character but are subsequently
1891 disappointed, by recording what the stride would have been
1892 for that character if the last character had been
1893 different. */
1895 pos_byte += dirlen - ((direction > 0) ? direction : 0);
1896 /* loop invariant - POS_BYTE points at where last char (first
1897 char if reverse) of pattern would align in a possible match. */
1898 while (n != 0)
1900 ptrdiff_t tail_end;
1901 unsigned char *tail_end_ptr;
1903 /* It's been reported that some (broken) compiler thinks that
1904 Boolean expressions in an arithmetic context are unsigned.
1905 Using an explicit ?1:0 prevents this. */
1906 if ((lim_byte - pos_byte - ((direction > 0) ? 1 : 0)) * direction
1907 < 0)
1908 return (n * (0 - direction));
1909 /* First we do the part we can by pointers (maybe nothing) */
1910 maybe_quit ();
1911 pat = base_pat;
1912 limit = pos_byte - dirlen + direction;
1913 if (direction > 0)
1915 limit = BUFFER_CEILING_OF (limit);
1916 /* LIMIT is now the last (not beyond-last!) value POS_BYTE
1917 can take on without hitting edge of buffer or the gap. */
1918 limit = min (limit, pos_byte + 20000);
1919 limit = min (limit, lim_byte - 1);
1921 else
1923 limit = BUFFER_FLOOR_OF (limit);
1924 /* LIMIT is now the last (not beyond-last!) value POS_BYTE
1925 can take on without hitting edge of buffer or the gap. */
1926 limit = max (limit, pos_byte - 20000);
1927 limit = max (limit, lim_byte);
1929 tail_end = BUFFER_CEILING_OF (pos_byte) + 1;
1930 tail_end_ptr = BYTE_POS_ADDR (tail_end);
1932 if ((limit - pos_byte) * direction > 20)
1934 unsigned char *p2;
1936 p_limit = BYTE_POS_ADDR (limit);
1937 p2 = (cursor = BYTE_POS_ADDR (pos_byte));
1938 /* In this loop, pos + cursor - p2 is the surrogate for pos. */
1939 while (1) /* use one cursor setting as long as i can */
1941 if (direction > 0) /* worth duplicating */
1943 while (cursor <= p_limit)
1945 if (BM_tab[*cursor] == 0)
1946 goto hit;
1947 cursor += BM_tab[*cursor];
1950 else
1952 while (cursor >= p_limit)
1954 if (BM_tab[*cursor] == 0)
1955 goto hit;
1956 cursor += BM_tab[*cursor];
1959 /* If you are here, cursor is beyond the end of the
1960 searched region. You fail to match within the
1961 permitted region and would otherwise try a character
1962 beyond that region. */
1963 break;
1965 hit:
1966 i = dirlen - direction;
1967 if (! NILP (trt))
1969 while ((i -= direction) + direction != 0)
1971 int ch;
1972 cursor -= direction;
1973 /* Translate only the last byte of a character. */
1974 if (! multibyte
1975 || ((cursor == tail_end_ptr
1976 || CHAR_HEAD_P (cursor[1]))
1977 && (CHAR_HEAD_P (cursor[0])
1978 /* Check if this is the last byte of
1979 a translatable character. */
1980 || (translate_prev_byte1 == cursor[-1]
1981 && (CHAR_HEAD_P (translate_prev_byte1)
1982 || (translate_prev_byte2 == cursor[-2]
1983 && (CHAR_HEAD_P (translate_prev_byte2)
1984 || (translate_prev_byte3 == cursor[-3]))))))))
1985 ch = simple_translate[*cursor];
1986 else
1987 ch = *cursor;
1988 if (pat[i] != ch)
1989 break;
1992 else
1994 while ((i -= direction) + direction != 0)
1996 cursor -= direction;
1997 if (pat[i] != *cursor)
1998 break;
2001 cursor += dirlen - i - direction; /* fix cursor */
2002 if (i + direction == 0)
2004 ptrdiff_t position, start, end;
2005 #ifdef REL_ALLOC
2006 ptrdiff_t cursor_off;
2007 #endif
2009 cursor -= direction;
2011 position = pos_byte + cursor - p2 + ((direction > 0)
2012 ? 1 - len_byte : 0);
2013 #ifdef REL_ALLOC
2014 /* set_search_regs might call malloc, which could
2015 cause ralloc.c relocate buffer text. We need to
2016 update pointers into buffer text due to that. */
2017 cursor_off = cursor - p2;
2018 #endif
2019 set_search_regs (position, len_byte);
2020 #ifdef REL_ALLOC
2021 p_limit = BYTE_POS_ADDR (limit);
2022 p2 = BYTE_POS_ADDR (pos_byte);
2023 cursor = p2 + cursor_off;
2024 #endif
2026 if (NILP (Vinhibit_changing_match_data))
2028 start = search_regs.start[0];
2029 end = search_regs.end[0];
2031 else
2032 /* If Vinhibit_changing_match_data is non-nil,
2033 search_regs will not be changed. So let's
2034 compute start and end here. */
2036 start = BYTE_TO_CHAR (position);
2037 end = BYTE_TO_CHAR (position + len_byte);
2040 if ((n -= direction) != 0)
2041 cursor += dirlen; /* to resume search */
2042 else
2043 return direction > 0 ? end : start;
2045 else
2046 cursor += stride_for_teases; /* <sigh> we lose - */
2048 pos_byte += cursor - p2;
2050 else
2051 /* Now we'll pick up a clump that has to be done the hard
2052 way because it covers a discontinuity. */
2054 limit = ((direction > 0)
2055 ? BUFFER_CEILING_OF (pos_byte - dirlen + 1)
2056 : BUFFER_FLOOR_OF (pos_byte - dirlen - 1));
2057 limit = ((direction > 0)
2058 ? min (limit + len_byte, lim_byte - 1)
2059 : max (limit - len_byte, lim_byte));
2060 /* LIMIT is now the last value POS_BYTE can have
2061 and still be valid for a possible match. */
2062 while (1)
2064 /* This loop can be coded for space rather than
2065 speed because it will usually run only once.
2066 (the reach is at most len + 21, and typically
2067 does not exceed len). */
2068 while ((limit - pos_byte) * direction >= 0)
2070 int ch = FETCH_BYTE (pos_byte);
2071 if (BM_tab[ch] == 0)
2072 goto hit2;
2073 pos_byte += BM_tab[ch];
2075 break; /* ran off the end */
2077 hit2:
2078 /* Found what might be a match. */
2079 i = dirlen - direction;
2080 while ((i -= direction) + direction != 0)
2082 int ch;
2083 unsigned char *ptr;
2084 pos_byte -= direction;
2085 ptr = BYTE_POS_ADDR (pos_byte);
2086 /* Translate only the last byte of a character. */
2087 if (! multibyte
2088 || ((ptr == tail_end_ptr
2089 || CHAR_HEAD_P (ptr[1]))
2090 && (CHAR_HEAD_P (ptr[0])
2091 /* Check if this is the last byte of a
2092 translatable character. */
2093 || (translate_prev_byte1 == ptr[-1]
2094 && (CHAR_HEAD_P (translate_prev_byte1)
2095 || (translate_prev_byte2 == ptr[-2]
2096 && (CHAR_HEAD_P (translate_prev_byte2)
2097 || translate_prev_byte3 == ptr[-3])))))))
2098 ch = simple_translate[*ptr];
2099 else
2100 ch = *ptr;
2101 if (pat[i] != ch)
2102 break;
2104 /* Above loop has moved POS_BYTE part or all the way
2105 back to the first pos (last pos if reverse).
2106 Set it once again at the last (first if reverse) char. */
2107 pos_byte += dirlen - i - direction;
2108 if (i + direction == 0)
2110 ptrdiff_t position, start, end;
2111 pos_byte -= direction;
2113 position = pos_byte + ((direction > 0) ? 1 - len_byte : 0);
2114 set_search_regs (position, len_byte);
2116 if (NILP (Vinhibit_changing_match_data))
2118 start = search_regs.start[0];
2119 end = search_regs.end[0];
2121 else
2122 /* If Vinhibit_changing_match_data is non-nil,
2123 search_regs will not be changed. So let's
2124 compute start and end here. */
2126 start = BYTE_TO_CHAR (position);
2127 end = BYTE_TO_CHAR (position + len_byte);
2130 if ((n -= direction) != 0)
2131 pos_byte += dirlen; /* to resume search */
2132 else
2133 return direction > 0 ? end : start;
2135 else
2136 pos_byte += stride_for_teases;
2139 /* We have done one clump. Can we continue? */
2140 if ((lim_byte - pos_byte) * direction < 0)
2141 return ((0 - n) * direction);
2143 return BYTE_TO_CHAR (pos_byte);
2146 /* Record beginning BEG_BYTE and end BEG_BYTE + NBYTES
2147 for the overall match just found in the current buffer.
2148 Also clear out the match data for registers 1 and up. */
2150 static void
2151 set_search_regs (ptrdiff_t beg_byte, ptrdiff_t nbytes)
2153 ptrdiff_t i;
2155 if (!NILP (Vinhibit_changing_match_data))
2156 return;
2158 /* Make sure we have registers in which to store
2159 the match position. */
2160 if (search_regs.num_regs == 0)
2162 search_regs.start = xmalloc (2 * sizeof (regoff_t));
2163 search_regs.end = xmalloc (2 * sizeof (regoff_t));
2164 search_regs.num_regs = 2;
2167 /* Clear out the other registers. */
2168 for (i = 1; i < search_regs.num_regs; i++)
2170 search_regs.start[i] = -1;
2171 search_regs.end[i] = -1;
2174 search_regs.start[0] = BYTE_TO_CHAR (beg_byte);
2175 search_regs.end[0] = BYTE_TO_CHAR (beg_byte + nbytes);
2176 XSETBUFFER (last_thing_searched, current_buffer);
2179 DEFUN ("search-backward", Fsearch_backward, Ssearch_backward, 1, 4,
2180 "MSearch backward: ",
2181 doc: /* Search backward from point for STRING.
2182 Set point to the beginning of the occurrence found, and return point.
2183 An optional second argument bounds the search; it is a buffer position.
2184 The match found must not begin before that position. A value of nil
2185 means search to the beginning of the accessible portion of the buffer.
2186 Optional third argument, if t, means if fail just return nil (no error).
2187 If not nil and not t, position at limit of search and return nil.
2188 Optional fourth argument COUNT, if a positive number, means to search
2189 for COUNT successive occurrences. If COUNT is negative, search
2190 forward, instead of backward, for -COUNT occurrences. A value of
2191 nil means the same as 1.
2192 With COUNT positive, the match found is the COUNTth to last one (or
2193 last, if COUNT is 1 or nil) in the buffer located entirely before
2194 the origin of the search; correspondingly with COUNT negative.
2196 Search case-sensitivity is determined by the value of the variable
2197 `case-fold-search', which see.
2199 See also the functions `match-beginning', `match-end' and `replace-match'. */)
2200 (Lisp_Object string, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
2202 return search_command (string, bound, noerror, count, -1, 0, 0);
2205 DEFUN ("search-forward", Fsearch_forward, Ssearch_forward, 1, 4, "MSearch: ",
2206 doc: /* Search forward from point for STRING.
2207 Set point to the end of the occurrence found, and return point.
2208 An optional second argument bounds the search; it is a buffer position.
2209 The match found must not end after that position. A value of nil
2210 means search to the end of the accessible portion of the buffer.
2211 Optional third argument, if t, means if fail just return nil (no error).
2212 If not nil and not t, move to limit of search and return nil.
2213 Optional fourth argument COUNT, if a positive number, means to search
2214 for COUNT successive occurrences. If COUNT is negative, search
2215 backward, instead of forward, for -COUNT occurrences. A value of
2216 nil means the same as 1.
2217 With COUNT positive, the match found is the COUNTth one (or first,
2218 if COUNT is 1 or nil) in the buffer located entirely after the
2219 origin of the search; correspondingly with COUNT negative.
2221 Search case-sensitivity is determined by the value of the variable
2222 `case-fold-search', which see.
2224 See also the functions `match-beginning', `match-end' and `replace-match'. */)
2225 (Lisp_Object string, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
2227 return search_command (string, bound, noerror, count, 1, 0, 0);
2230 DEFUN ("re-search-backward", Fre_search_backward, Sre_search_backward, 1, 4,
2231 "sRE search backward: ",
2232 doc: /* Search backward from point for regular expression REGEXP.
2233 This function is almost identical to `re-search-forward', except that
2234 by default it searches backward instead of forward, and the sign of
2235 COUNT also indicates exactly the opposite searching direction.
2236 See `re-search-forward' for details.
2238 Note that searching backwards may give a shorter match than expected,
2239 because REGEXP is still matched in the forward direction. See Info
2240 anchor `(elisp) re-search-backward' for details. */)
2241 (Lisp_Object regexp, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
2243 return search_command (regexp, bound, noerror, count, -1, 1, 0);
2246 DEFUN ("re-search-forward", Fre_search_forward, Sre_search_forward, 1, 4,
2247 "sRE search: ",
2248 doc: /* Search forward from point for regular expression REGEXP.
2249 Set point to the end of the occurrence found, and return point.
2250 The optional second argument BOUND is a buffer position that bounds
2251 the search. The match found must not end after that position. A
2252 value of nil means search to the end of the accessible portion of
2253 the buffer.
2254 The optional third argument NOERROR indicates how errors are handled
2255 when the search fails. If it is nil or omitted, emit an error; if
2256 it is t, simply return nil and do nothing; if it is neither nil nor
2257 t, move to the limit of search and return nil.
2258 The optional fourth argument COUNT is a number that indicates the
2259 search direction and the number of occurrences to search for. If it
2260 is positive, search forward for COUNT successive occurrences; if it
2261 is negative, search backward, instead of forward, for -COUNT
2262 occurrences. A value of nil means the same as 1.
2263 With COUNT positive/negative, the match found is the COUNTth/-COUNTth
2264 one in the buffer located entirely after/before the origin of the
2265 search.
2267 Search case-sensitivity is determined by the value of the variable
2268 `case-fold-search', which see.
2270 See also the functions `match-beginning', `match-end', `match-string',
2271 and `replace-match'. */)
2272 (Lisp_Object regexp, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
2274 return search_command (regexp, bound, noerror, count, 1, 1, 0);
2277 DEFUN ("posix-search-backward", Fposix_search_backward, Sposix_search_backward, 1, 4,
2278 "sPosix search backward: ",
2279 doc: /* Search backward from point for match for regular expression REGEXP.
2280 Find the longest match in accord with Posix regular expression rules.
2281 Set point to the beginning of the occurrence found, and return point.
2282 An optional second argument bounds the search; it is a buffer position.
2283 The match found must not begin before that position. A value of nil
2284 means search to the beginning of the accessible portion of the buffer.
2285 Optional third argument, if t, means if fail just return nil (no error).
2286 If not nil and not t, position at limit of search and return nil.
2287 Optional fourth argument COUNT, if a positive number, means to search
2288 for COUNT successive occurrences. If COUNT is negative, search
2289 forward, instead of backward, for -COUNT occurrences. A value of
2290 nil means the same as 1.
2291 With COUNT positive, the match found is the COUNTth to last one (or
2292 last, if COUNT is 1 or nil) in the buffer located entirely before
2293 the origin of the search; correspondingly with COUNT negative.
2295 Search case-sensitivity is determined by the value of the variable
2296 `case-fold-search', which see.
2298 See also the functions `match-beginning', `match-end', `match-string',
2299 and `replace-match'. */)
2300 (Lisp_Object regexp, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
2302 return search_command (regexp, bound, noerror, count, -1, 1, 1);
2305 DEFUN ("posix-search-forward", Fposix_search_forward, Sposix_search_forward, 1, 4,
2306 "sPosix search: ",
2307 doc: /* Search forward from point for regular expression REGEXP.
2308 Find the longest match in accord with Posix regular expression rules.
2309 Set point to the end of the occurrence found, and return point.
2310 An optional second argument bounds the search; it is a buffer position.
2311 The match found must not end after that position. A value of nil
2312 means search to the end of the accessible portion of the buffer.
2313 Optional third argument, if t, means if fail just return nil (no error).
2314 If not nil and not t, move to limit of search and return nil.
2315 Optional fourth argument COUNT, if a positive number, means to search
2316 for COUNT successive occurrences. If COUNT is negative, search
2317 backward, instead of forward, for -COUNT occurrences. A value of
2318 nil means the same as 1.
2319 With COUNT positive, the match found is the COUNTth one (or first,
2320 if COUNT is 1 or nil) in the buffer located entirely after the
2321 origin of the search; correspondingly with COUNT negative.
2323 Search case-sensitivity is determined by the value of the variable
2324 `case-fold-search', which see.
2326 See also the functions `match-beginning', `match-end', `match-string',
2327 and `replace-match'. */)
2328 (Lisp_Object regexp, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
2330 return search_command (regexp, bound, noerror, count, 1, 1, 1);
2333 DEFUN ("replace-match", Freplace_match, Sreplace_match, 1, 5, 0,
2334 doc: /* Replace text matched by last search with NEWTEXT.
2335 Leave point at the end of the replacement text.
2337 If optional second arg FIXEDCASE is non-nil, do not alter the case of
2338 the replacement text. Otherwise, maybe capitalize the whole text, or
2339 maybe just word initials, based on the replaced text. If the replaced
2340 text has only capital letters and has at least one multiletter word,
2341 convert NEWTEXT to all caps. Otherwise if all words are capitalized
2342 in the replaced text, capitalize each word in NEWTEXT.
2344 If optional third arg LITERAL is non-nil, insert NEWTEXT literally.
2345 Otherwise treat `\\' as special:
2346 `\\&' in NEWTEXT means substitute original matched text.
2347 `\\N' means substitute what matched the Nth `\\(...\\)'.
2348 If Nth parens didn't match, substitute nothing.
2349 `\\\\' means insert one `\\'.
2350 `\\?' is treated literally
2351 (for compatibility with `query-replace-regexp').
2352 Any other character following `\\' signals an error.
2353 Case conversion does not apply to these substitutions.
2355 If optional fourth argument STRING is non-nil, it should be a string
2356 to act on; this should be the string on which the previous match was
2357 done via `string-match'. In this case, `replace-match' creates and
2358 returns a new string, made by copying STRING and replacing the part of
2359 STRING that was matched (the original STRING itself is not altered).
2361 The optional fifth argument SUBEXP specifies a subexpression;
2362 it says to replace just that subexpression with NEWTEXT,
2363 rather than replacing the entire matched text.
2364 This is, in a vague sense, the inverse of using `\\N' in NEWTEXT;
2365 `\\N' copies subexp N into NEWTEXT, but using N as SUBEXP puts
2366 NEWTEXT in place of subexp N.
2367 This is useful only after a regular expression search or match,
2368 since only regular expressions have distinguished subexpressions. */)
2369 (Lisp_Object newtext, Lisp_Object fixedcase, Lisp_Object literal, Lisp_Object string, Lisp_Object subexp)
2371 enum { nochange, all_caps, cap_initial } case_action;
2372 ptrdiff_t pos, pos_byte;
2373 bool some_multiletter_word;
2374 bool some_lowercase;
2375 bool some_uppercase;
2376 bool some_nonuppercase_initial;
2377 int c, prevc;
2378 ptrdiff_t sub;
2379 ptrdiff_t opoint, newpoint;
2381 CHECK_STRING (newtext);
2383 if (! NILP (string))
2384 CHECK_STRING (string);
2386 case_action = nochange; /* We tried an initialization */
2387 /* but some C compilers blew it */
2389 if (search_regs.num_regs <= 0)
2390 error ("`replace-match' called before any match found");
2392 if (NILP (subexp))
2393 sub = 0;
2394 else
2396 CHECK_NUMBER (subexp);
2397 if (! (0 <= XINT (subexp) && XINT (subexp) < search_regs.num_regs))
2398 args_out_of_range (subexp, make_number (search_regs.num_regs));
2399 sub = XINT (subexp);
2402 if (NILP (string))
2404 if (search_regs.start[sub] < BEGV
2405 || search_regs.start[sub] > search_regs.end[sub]
2406 || search_regs.end[sub] > ZV)
2407 args_out_of_range (make_number (search_regs.start[sub]),
2408 make_number (search_regs.end[sub]));
2410 else
2412 if (search_regs.start[sub] < 0
2413 || search_regs.start[sub] > search_regs.end[sub]
2414 || search_regs.end[sub] > SCHARS (string))
2415 args_out_of_range (make_number (search_regs.start[sub]),
2416 make_number (search_regs.end[sub]));
2419 if (NILP (fixedcase))
2421 /* Decide how to casify by examining the matched text. */
2422 ptrdiff_t last;
2424 pos = search_regs.start[sub];
2425 last = search_regs.end[sub];
2427 if (NILP (string))
2428 pos_byte = CHAR_TO_BYTE (pos);
2429 else
2430 pos_byte = string_char_to_byte (string, pos);
2432 prevc = '\n';
2433 case_action = all_caps;
2435 /* some_multiletter_word is set nonzero if any original word
2436 is more than one letter long. */
2437 some_multiletter_word = 0;
2438 some_lowercase = 0;
2439 some_nonuppercase_initial = 0;
2440 some_uppercase = 0;
2442 while (pos < last)
2444 if (NILP (string))
2446 c = FETCH_CHAR_AS_MULTIBYTE (pos_byte);
2447 INC_BOTH (pos, pos_byte);
2449 else
2450 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c, string, pos, pos_byte);
2452 if (lowercasep (c))
2454 /* Cannot be all caps if any original char is lower case */
2456 some_lowercase = 1;
2457 if (SYNTAX (prevc) != Sword)
2458 some_nonuppercase_initial = 1;
2459 else
2460 some_multiletter_word = 1;
2462 else if (uppercasep (c))
2464 some_uppercase = 1;
2465 if (SYNTAX (prevc) != Sword)
2467 else
2468 some_multiletter_word = 1;
2470 else
2472 /* If the initial is a caseless word constituent,
2473 treat that like a lowercase initial. */
2474 if (SYNTAX (prevc) != Sword)
2475 some_nonuppercase_initial = 1;
2478 prevc = c;
2481 /* Convert to all caps if the old text is all caps
2482 and has at least one multiletter word. */
2483 if (! some_lowercase && some_multiletter_word)
2484 case_action = all_caps;
2485 /* Capitalize each word, if the old text has all capitalized words. */
2486 else if (!some_nonuppercase_initial && some_multiletter_word)
2487 case_action = cap_initial;
2488 else if (!some_nonuppercase_initial && some_uppercase)
2489 /* Should x -> yz, operating on X, give Yz or YZ?
2490 We'll assume the latter. */
2491 case_action = all_caps;
2492 else
2493 case_action = nochange;
2496 /* Do replacement in a string. */
2497 if (!NILP (string))
2499 Lisp_Object before, after;
2501 before = Fsubstring (string, make_number (0),
2502 make_number (search_regs.start[sub]));
2503 after = Fsubstring (string, make_number (search_regs.end[sub]), Qnil);
2505 /* Substitute parts of the match into NEWTEXT
2506 if desired. */
2507 if (NILP (literal))
2509 ptrdiff_t lastpos = 0;
2510 ptrdiff_t lastpos_byte = 0;
2511 /* We build up the substituted string in ACCUM. */
2512 Lisp_Object accum;
2513 Lisp_Object middle;
2514 ptrdiff_t length = SBYTES (newtext);
2516 accum = Qnil;
2518 for (pos_byte = 0, pos = 0; pos_byte < length;)
2520 ptrdiff_t substart = -1;
2521 ptrdiff_t subend = 0;
2522 bool delbackslash = 0;
2524 FETCH_STRING_CHAR_ADVANCE (c, newtext, pos, pos_byte);
2526 if (c == '\\')
2528 FETCH_STRING_CHAR_ADVANCE (c, newtext, pos, pos_byte);
2530 if (c == '&')
2532 substart = search_regs.start[sub];
2533 subend = search_regs.end[sub];
2535 else if (c >= '1' && c <= '9')
2537 if (c - '0' < search_regs.num_regs
2538 && search_regs.start[c - '0'] >= 0)
2540 substart = search_regs.start[c - '0'];
2541 subend = search_regs.end[c - '0'];
2543 else
2545 /* If that subexp did not match,
2546 replace \\N with nothing. */
2547 substart = 0;
2548 subend = 0;
2551 else if (c == '\\')
2552 delbackslash = 1;
2553 else if (c != '?')
2554 error ("Invalid use of `\\' in replacement text");
2556 if (substart >= 0)
2558 if (pos - 2 != lastpos)
2559 middle = substring_both (newtext, lastpos,
2560 lastpos_byte,
2561 pos - 2, pos_byte - 2);
2562 else
2563 middle = Qnil;
2564 accum = concat3 (accum, middle,
2565 Fsubstring (string,
2566 make_number (substart),
2567 make_number (subend)));
2568 lastpos = pos;
2569 lastpos_byte = pos_byte;
2571 else if (delbackslash)
2573 middle = substring_both (newtext, lastpos,
2574 lastpos_byte,
2575 pos - 1, pos_byte - 1);
2577 accum = concat2 (accum, middle);
2578 lastpos = pos;
2579 lastpos_byte = pos_byte;
2583 if (pos != lastpos)
2584 middle = substring_both (newtext, lastpos,
2585 lastpos_byte,
2586 pos, pos_byte);
2587 else
2588 middle = Qnil;
2590 newtext = concat2 (accum, middle);
2593 /* Do case substitution in NEWTEXT if desired. */
2594 if (case_action == all_caps)
2595 newtext = Fupcase (newtext);
2596 else if (case_action == cap_initial)
2597 newtext = Fupcase_initials (newtext);
2599 return concat3 (before, newtext, after);
2602 /* Record point, then move (quietly) to the start of the match. */
2603 if (PT >= search_regs.end[sub])
2604 opoint = PT - ZV;
2605 else if (PT > search_regs.start[sub])
2606 opoint = search_regs.end[sub] - ZV;
2607 else
2608 opoint = PT;
2610 /* If we want non-literal replacement,
2611 perform substitution on the replacement string. */
2612 if (NILP (literal))
2614 ptrdiff_t length = SBYTES (newtext);
2615 unsigned char *substed;
2616 ptrdiff_t substed_alloc_size, substed_len;
2617 bool buf_multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
2618 bool str_multibyte = STRING_MULTIBYTE (newtext);
2619 bool really_changed = 0;
2621 substed_alloc_size = (length <= (STRING_BYTES_BOUND - 100) / 2
2622 ? length * 2 + 100
2623 : STRING_BYTES_BOUND);
2624 substed = xmalloc (substed_alloc_size);
2625 substed_len = 0;
2627 /* Go thru NEWTEXT, producing the actual text to insert in
2628 SUBSTED while adjusting multibyteness to that of the current
2629 buffer. */
2631 for (pos_byte = 0, pos = 0; pos_byte < length;)
2633 unsigned char str[MAX_MULTIBYTE_LENGTH];
2634 const unsigned char *add_stuff = NULL;
2635 ptrdiff_t add_len = 0;
2636 ptrdiff_t idx = -1;
2637 ptrdiff_t begbyte UNINIT;
2639 if (str_multibyte)
2641 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, newtext, pos, pos_byte);
2642 if (!buf_multibyte)
2643 c = CHAR_TO_BYTE8 (c);
2645 else
2647 /* Note that we don't have to increment POS. */
2648 c = SREF (newtext, pos_byte++);
2649 if (buf_multibyte)
2650 MAKE_CHAR_MULTIBYTE (c);
2653 /* Either set ADD_STUFF and ADD_LEN to the text to put in SUBSTED,
2654 or set IDX to a match index, which means put that part
2655 of the buffer text into SUBSTED. */
2657 if (c == '\\')
2659 really_changed = 1;
2661 if (str_multibyte)
2663 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, newtext,
2664 pos, pos_byte);
2665 if (!buf_multibyte && !ASCII_CHAR_P (c))
2666 c = CHAR_TO_BYTE8 (c);
2668 else
2670 c = SREF (newtext, pos_byte++);
2671 if (buf_multibyte)
2672 MAKE_CHAR_MULTIBYTE (c);
2675 if (c == '&')
2676 idx = sub;
2677 else if (c >= '1' && c <= '9' && c - '0' < search_regs.num_regs)
2679 if (search_regs.start[c - '0'] >= 1)
2680 idx = c - '0';
2682 else if (c == '\\')
2683 add_len = 1, add_stuff = (unsigned char *) "\\";
2684 else
2686 xfree (substed);
2687 error ("Invalid use of `\\' in replacement text");
2690 else
2692 add_len = CHAR_STRING (c, str);
2693 add_stuff = str;
2696 /* If we want to copy part of a previous match,
2697 set up ADD_STUFF and ADD_LEN to point to it. */
2698 if (idx >= 0)
2700 begbyte = CHAR_TO_BYTE (search_regs.start[idx]);
2701 add_len = CHAR_TO_BYTE (search_regs.end[idx]) - begbyte;
2702 if (search_regs.start[idx] < GPT && GPT < search_regs.end[idx])
2703 move_gap_both (search_regs.start[idx], begbyte);
2706 /* Now the stuff we want to add to SUBSTED
2707 is invariably ADD_LEN bytes starting at ADD_STUFF. */
2709 /* Make sure SUBSTED is big enough. */
2710 if (substed_alloc_size - substed_len < add_len)
2711 substed =
2712 xpalloc (substed, &substed_alloc_size,
2713 add_len - (substed_alloc_size - substed_len),
2714 STRING_BYTES_BOUND, 1);
2716 /* We compute this after the call to xpalloc, because that
2717 could cause buffer text be relocated when ralloc.c is used. */
2718 if (idx >= 0)
2719 add_stuff = BYTE_POS_ADDR (begbyte);
2721 /* Now add to the end of SUBSTED. */
2722 if (add_stuff)
2724 memcpy (substed + substed_len, add_stuff, add_len);
2725 substed_len += add_len;
2729 if (really_changed)
2730 newtext = make_specified_string ((const char *) substed, -1,
2731 substed_len, buf_multibyte);
2732 xfree (substed);
2735 /* The functions below modify the buffer, so they could trigger
2736 various modification hooks (see signal_before_change and
2737 signal_after_change). If these hooks clobber the match data we
2738 error out since otherwise this will result in confusing bugs. */
2739 ptrdiff_t sub_start = search_regs.start[sub];
2740 ptrdiff_t sub_end = search_regs.end[sub];
2741 unsigned num_regs = search_regs.num_regs;
2742 newpoint = search_regs.start[sub] + SCHARS (newtext);
2744 /* Replace the old text with the new in the cleanest possible way. */
2745 replace_range (search_regs.start[sub], search_regs.end[sub],
2746 newtext, 1, 0, 1, 1);
2747 /* Update saved data to match adjustment made by replace_range. */
2749 ptrdiff_t change = newpoint - sub_end;
2750 if (sub_start >= sub_end)
2751 sub_start += change;
2752 sub_end += change;
2755 if (case_action == all_caps)
2756 Fupcase_region (make_number (search_regs.start[sub]),
2757 make_number (newpoint),
2758 Qnil);
2759 else if (case_action == cap_initial)
2760 Fupcase_initials_region (make_number (search_regs.start[sub]),
2761 make_number (newpoint));
2763 if (search_regs.start[sub] != sub_start
2764 || search_regs.end[sub] != sub_end
2765 || search_regs.num_regs != num_regs)
2766 error ("Match data clobbered by buffer modification hooks");
2768 /* Put point back where it was in the text. */
2769 if (opoint <= 0)
2770 TEMP_SET_PT (opoint + ZV);
2771 else
2772 TEMP_SET_PT (opoint);
2774 /* Now move point "officially" to the start of the inserted replacement. */
2775 move_if_not_intangible (newpoint);
2777 return Qnil;
2780 static Lisp_Object
2781 match_limit (Lisp_Object num, bool beginningp)
2783 EMACS_INT n;
2785 CHECK_NUMBER (num);
2786 n = XINT (num);
2787 if (n < 0)
2788 args_out_of_range (num, make_number (0));
2789 if (search_regs.num_regs <= 0)
2790 error ("No match data, because no search succeeded");
2791 if (n >= search_regs.num_regs
2792 || search_regs.start[n] < 0)
2793 return Qnil;
2794 return (make_number ((beginningp) ? search_regs.start[n]
2795 : search_regs.end[n]));
2798 DEFUN ("match-beginning", Fmatch_beginning, Smatch_beginning, 1, 1, 0,
2799 doc: /* Return position of start of text matched by last search.
2800 SUBEXP, a number, specifies which parenthesized expression in the last
2801 regexp.
2802 Value is nil if SUBEXPth pair didn't match, or there were less than
2803 SUBEXP pairs.
2804 Zero means the entire text matched by the whole regexp or whole string.
2806 Return value is undefined if the last search failed. */)
2807 (Lisp_Object subexp)
2809 return match_limit (subexp, 1);
2812 DEFUN ("match-end", Fmatch_end, Smatch_end, 1, 1, 0,
2813 doc: /* Return position of end of text matched by last search.
2814 SUBEXP, a number, specifies which parenthesized expression in the last
2815 regexp.
2816 Value is nil if SUBEXPth pair didn't match, or there were less than
2817 SUBEXP pairs.
2818 Zero means the entire text matched by the whole regexp or whole string.
2820 Return value is undefined if the last search failed. */)
2821 (Lisp_Object subexp)
2823 return match_limit (subexp, 0);
2826 DEFUN ("match-data", Fmatch_data, Smatch_data, 0, 3, 0,
2827 doc: /* Return a list describing what the last search matched.
2828 Element 2N is `(match-beginning N)'; element 2N + 1 is `(match-end N)'.
2829 All the elements are markers or nil (nil if the Nth pair didn't match)
2830 if the last match was on a buffer; integers or nil if a string was matched.
2831 Use `set-match-data' to reinstate the data in this list.
2833 If INTEGERS (the optional first argument) is non-nil, always use
2834 integers (rather than markers) to represent buffer positions. In
2835 this case, and if the last match was in a buffer, the buffer will get
2836 stored as one additional element at the end of the list.
2838 If REUSE is a list, reuse it as part of the value. If REUSE is long
2839 enough to hold all the values, and if INTEGERS is non-nil, no consing
2840 is done.
2842 If optional third arg RESEAT is non-nil, any previous markers on the
2843 REUSE list will be modified to point to nowhere.
2845 Return value is undefined if the last search failed. */)
2846 (Lisp_Object integers, Lisp_Object reuse, Lisp_Object reseat)
2848 Lisp_Object tail, prev;
2849 Lisp_Object *data;
2850 ptrdiff_t i, len;
2852 if (!NILP (reseat))
2853 for (tail = reuse; CONSP (tail); tail = XCDR (tail))
2854 if (MARKERP (XCAR (tail)))
2856 unchain_marker (XMARKER (XCAR (tail)));
2857 XSETCAR (tail, Qnil);
2860 if (NILP (last_thing_searched))
2861 return Qnil;
2863 prev = Qnil;
2865 USE_SAFE_ALLOCA;
2866 SAFE_NALLOCA (data, 1, 2 * search_regs.num_regs + 1);
2868 len = 0;
2869 for (i = 0; i < search_regs.num_regs; i++)
2871 ptrdiff_t start = search_regs.start[i];
2872 if (start >= 0)
2874 if (EQ (last_thing_searched, Qt)
2875 || ! NILP (integers))
2877 XSETFASTINT (data[2 * i], start);
2878 XSETFASTINT (data[2 * i + 1], search_regs.end[i]);
2880 else if (BUFFERP (last_thing_searched))
2882 data[2 * i] = Fmake_marker ();
2883 Fset_marker (data[2 * i],
2884 make_number (start),
2885 last_thing_searched);
2886 data[2 * i + 1] = Fmake_marker ();
2887 Fset_marker (data[2 * i + 1],
2888 make_number (search_regs.end[i]),
2889 last_thing_searched);
2891 else
2892 /* last_thing_searched must always be Qt, a buffer, or Qnil. */
2893 emacs_abort ();
2895 len = 2 * i + 2;
2897 else
2898 data[2 * i] = data[2 * i + 1] = Qnil;
2901 if (BUFFERP (last_thing_searched) && !NILP (integers))
2903 data[len] = last_thing_searched;
2904 len++;
2907 /* If REUSE is not usable, cons up the values and return them. */
2908 if (! CONSP (reuse))
2909 reuse = Flist (len, data);
2910 else
2912 /* If REUSE is a list, store as many value elements as will fit
2913 into the elements of REUSE. */
2914 for (i = 0, tail = reuse; CONSP (tail);
2915 i++, tail = XCDR (tail))
2917 if (i < len)
2918 XSETCAR (tail, data[i]);
2919 else
2920 XSETCAR (tail, Qnil);
2921 prev = tail;
2924 /* If we couldn't fit all value elements into REUSE,
2925 cons up the rest of them and add them to the end of REUSE. */
2926 if (i < len)
2927 XSETCDR (prev, Flist (len - i, data + i));
2930 SAFE_FREE ();
2931 return reuse;
2934 /* We used to have an internal use variant of `reseat' described as:
2936 If RESEAT is `evaporate', put the markers back on the free list
2937 immediately. No other references to the markers must exist in this
2938 case, so it is used only internally on the unwind stack and
2939 save-match-data from Lisp.
2941 But it was ill-conceived: those supposedly-internal markers get exposed via
2942 the undo-list, so freeing them here is unsafe. */
2944 DEFUN ("set-match-data", Fset_match_data, Sset_match_data, 1, 2, 0,
2945 doc: /* Set internal data on last search match from elements of LIST.
2946 LIST should have been created by calling `match-data' previously.
2948 If optional arg RESEAT is non-nil, make markers on LIST point nowhere. */)
2949 (register Lisp_Object list, Lisp_Object reseat)
2951 ptrdiff_t i;
2952 register Lisp_Object marker;
2954 if (running_asynch_code)
2955 save_search_regs ();
2957 CHECK_LIST (list);
2959 /* Unless we find a marker with a buffer or an explicit buffer
2960 in LIST, assume that this match data came from a string. */
2961 last_thing_searched = Qt;
2963 /* Allocate registers if they don't already exist. */
2965 EMACS_INT length = XFASTINT (Flength (list)) / 2;
2967 if (length > search_regs.num_regs)
2969 ptrdiff_t num_regs = search_regs.num_regs;
2970 if (PTRDIFF_MAX < length)
2971 memory_full (SIZE_MAX);
2972 search_regs.start =
2973 xpalloc (search_regs.start, &num_regs, length - num_regs,
2974 min (PTRDIFF_MAX, UINT_MAX), sizeof (regoff_t));
2975 search_regs.end =
2976 xrealloc (search_regs.end, num_regs * sizeof (regoff_t));
2978 for (i = search_regs.num_regs; i < num_regs; i++)
2979 search_regs.start[i] = -1;
2981 search_regs.num_regs = num_regs;
2984 for (i = 0; CONSP (list); i++)
2986 marker = XCAR (list);
2987 if (BUFFERP (marker))
2989 last_thing_searched = marker;
2990 break;
2992 if (i >= length)
2993 break;
2994 if (NILP (marker))
2996 search_regs.start[i] = -1;
2997 list = XCDR (list);
2999 else
3001 Lisp_Object from;
3002 Lisp_Object m;
3004 m = marker;
3005 if (MARKERP (marker))
3007 if (XMARKER (marker)->buffer == 0)
3008 XSETFASTINT (marker, 0);
3009 else
3010 XSETBUFFER (last_thing_searched, XMARKER (marker)->buffer);
3013 CHECK_NUMBER_COERCE_MARKER (marker);
3014 from = marker;
3016 if (!NILP (reseat) && MARKERP (m))
3018 unchain_marker (XMARKER (m));
3019 XSETCAR (list, Qnil);
3022 if ((list = XCDR (list), !CONSP (list)))
3023 break;
3025 m = marker = XCAR (list);
3027 if (MARKERP (marker) && XMARKER (marker)->buffer == 0)
3028 XSETFASTINT (marker, 0);
3030 CHECK_NUMBER_COERCE_MARKER (marker);
3031 if ((XINT (from) < 0
3032 ? TYPE_MINIMUM (regoff_t) <= XINT (from)
3033 : XINT (from) <= TYPE_MAXIMUM (regoff_t))
3034 && (XINT (marker) < 0
3035 ? TYPE_MINIMUM (regoff_t) <= XINT (marker)
3036 : XINT (marker) <= TYPE_MAXIMUM (regoff_t)))
3038 search_regs.start[i] = XINT (from);
3039 search_regs.end[i] = XINT (marker);
3041 else
3043 search_regs.start[i] = -1;
3046 if (!NILP (reseat) && MARKERP (m))
3048 unchain_marker (XMARKER (m));
3049 XSETCAR (list, Qnil);
3052 list = XCDR (list);
3055 for (; i < search_regs.num_regs; i++)
3056 search_regs.start[i] = -1;
3059 return Qnil;
3062 /* If true the match data have been saved in saved_search_regs
3063 during the execution of a sentinel or filter. */
3064 /* static bool search_regs_saved; */
3065 /* static struct re_registers saved_search_regs; */
3066 /* static Lisp_Object saved_last_thing_searched; */
3068 /* Called from Flooking_at, Fstring_match, search_buffer, Fstore_match_data
3069 if asynchronous code (filter or sentinel) is running. */
3070 static void
3071 save_search_regs (void)
3073 if (!search_regs_saved)
3075 saved_search_regs.num_regs = search_regs.num_regs;
3076 saved_search_regs.start = search_regs.start;
3077 saved_search_regs.end = search_regs.end;
3078 saved_last_thing_searched = last_thing_searched;
3079 last_thing_searched = Qnil;
3080 search_regs.num_regs = 0;
3081 search_regs.start = 0;
3082 search_regs.end = 0;
3084 search_regs_saved = 1;
3088 /* Called upon exit from filters and sentinels. */
3089 void
3090 restore_search_regs (void)
3092 if (search_regs_saved)
3094 if (search_regs.num_regs > 0)
3096 xfree (search_regs.start);
3097 xfree (search_regs.end);
3099 search_regs.num_regs = saved_search_regs.num_regs;
3100 search_regs.start = saved_search_regs.start;
3101 search_regs.end = saved_search_regs.end;
3102 last_thing_searched = saved_last_thing_searched;
3103 saved_last_thing_searched = Qnil;
3104 search_regs_saved = 0;
3108 /* Called from replace-match via replace_range. */
3109 void
3110 update_search_regs (ptrdiff_t oldstart, ptrdiff_t oldend, ptrdiff_t newend)
3112 /* Adjust search data for this change. */
3113 ptrdiff_t change = newend - oldend;
3114 ptrdiff_t i;
3116 for (i = 0; i < search_regs.num_regs; i++)
3118 if (search_regs.start[i] >= oldend)
3119 search_regs.start[i] += change;
3120 else if (search_regs.start[i] > oldstart)
3121 search_regs.start[i] = oldstart;
3122 if (search_regs.end[i] >= oldend)
3123 search_regs.end[i] += change;
3124 else if (search_regs.end[i] > oldstart)
3125 search_regs.end[i] = oldstart;
3129 static void
3130 unwind_set_match_data (Lisp_Object list)
3132 /* It is NOT ALWAYS safe to free (evaporate) the markers immediately. */
3133 Fset_match_data (list, Qt);
3136 /* Called to unwind protect the match data. */
3137 void
3138 record_unwind_save_match_data (void)
3140 record_unwind_protect (unwind_set_match_data,
3141 Fmatch_data (Qnil, Qnil, Qnil));
3144 /* Quote a string to deactivate reg-expr chars */
3146 DEFUN ("regexp-quote", Fregexp_quote, Sregexp_quote, 1, 1, 0,
3147 doc: /* Return a regexp string which matches exactly STRING and nothing else. */)
3148 (Lisp_Object string)
3150 char *in, *out, *end;
3151 char *temp;
3152 ptrdiff_t backslashes_added = 0;
3154 CHECK_STRING (string);
3156 USE_SAFE_ALLOCA;
3157 SAFE_NALLOCA (temp, 2, SBYTES (string));
3159 /* Now copy the data into the new string, inserting escapes. */
3161 in = SSDATA (string);
3162 end = in + SBYTES (string);
3163 out = temp;
3165 for (; in != end; in++)
3167 if (*in == '['
3168 || *in == '*' || *in == '.' || *in == '\\'
3169 || *in == '?' || *in == '+'
3170 || *in == '^' || *in == '$')
3171 *out++ = '\\', backslashes_added++;
3172 *out++ = *in;
3175 Lisp_Object result
3176 = make_specified_string (temp,
3177 SCHARS (string) + backslashes_added,
3178 out - temp,
3179 STRING_MULTIBYTE (string));
3180 SAFE_FREE ();
3181 return result;
3184 /* Like find_newline, but doesn't use the cache, and only searches forward. */
3185 static ptrdiff_t
3186 find_newline1 (ptrdiff_t start, ptrdiff_t start_byte, ptrdiff_t end,
3187 ptrdiff_t end_byte, ptrdiff_t count, ptrdiff_t *shortage,
3188 ptrdiff_t *bytepos, bool allow_quit)
3190 if (count > 0)
3192 if (!end)
3193 end = ZV, end_byte = ZV_BYTE;
3195 else
3197 if (!end)
3198 end = BEGV, end_byte = BEGV_BYTE;
3200 if (end_byte == -1)
3201 end_byte = CHAR_TO_BYTE (end);
3203 if (shortage != 0)
3204 *shortage = 0;
3206 if (count > 0)
3207 while (start != end)
3209 /* Our innermost scanning loop is very simple; it doesn't know
3210 about gaps, buffer ends, or the newline cache. ceiling is
3211 the position of the last character before the next such
3212 obstacle --- the last character the dumb search loop should
3213 examine. */
3214 ptrdiff_t tem, ceiling_byte = end_byte - 1;
3216 if (start_byte == -1)
3217 start_byte = CHAR_TO_BYTE (start);
3219 /* The dumb loop can only scan text stored in contiguous
3220 bytes. BUFFER_CEILING_OF returns the last character
3221 position that is contiguous, so the ceiling is the
3222 position after that. */
3223 tem = BUFFER_CEILING_OF (start_byte);
3224 ceiling_byte = min (tem, ceiling_byte);
3227 /* The termination address of the dumb loop. */
3228 unsigned char *lim_addr = BYTE_POS_ADDR (ceiling_byte) + 1;
3229 ptrdiff_t lim_byte = ceiling_byte + 1;
3231 /* Nonpositive offsets (relative to LIM_ADDR and LIM_BYTE)
3232 of the base, the cursor, and the next line. */
3233 ptrdiff_t base = start_byte - lim_byte;
3234 ptrdiff_t cursor, next;
3236 for (cursor = base; cursor < 0; cursor = next)
3238 /* The dumb loop. */
3239 unsigned char *nl = memchr (lim_addr + cursor, '\n', - cursor);
3240 next = nl ? nl - lim_addr : 0;
3242 if (! nl)
3243 break;
3244 next++;
3246 if (--count == 0)
3248 if (bytepos)
3249 *bytepos = lim_byte + next;
3250 return BYTE_TO_CHAR (lim_byte + next);
3252 if (allow_quit)
3253 maybe_quit ();
3256 start_byte = lim_byte;
3257 start = BYTE_TO_CHAR (start_byte);
3261 if (shortage)
3262 *shortage = count;
3263 if (bytepos)
3265 *bytepos = start_byte == -1 ? CHAR_TO_BYTE (start) : start_byte;
3266 eassert (*bytepos == CHAR_TO_BYTE (start));
3268 return start;
3271 DEFUN ("newline-cache-check", Fnewline_cache_check, Snewline_cache_check,
3272 0, 1, 0,
3273 doc: /* Check the newline cache of BUFFER against buffer contents.
3275 BUFFER defaults to the current buffer.
3277 Value is an array of 2 sub-arrays of buffer positions for newlines,
3278 the first based on the cache, the second based on actually scanning
3279 the buffer. If the buffer doesn't have a cache, the value is nil. */)
3280 (Lisp_Object buffer)
3282 struct buffer *buf, *old = NULL;
3283 ptrdiff_t shortage, nl_count_cache, nl_count_buf;
3284 Lisp_Object cache_newlines, buf_newlines, val;
3285 ptrdiff_t from, found, i;
3287 if (NILP (buffer))
3288 buf = current_buffer;
3289 else
3291 CHECK_BUFFER (buffer);
3292 buf = XBUFFER (buffer);
3293 old = current_buffer;
3295 if (buf->base_buffer)
3296 buf = buf->base_buffer;
3298 /* If the buffer doesn't have a newline cache, return nil. */
3299 if (NILP (BVAR (buf, cache_long_scans))
3300 || buf->newline_cache == NULL)
3301 return Qnil;
3303 /* find_newline can only work on the current buffer. */
3304 if (old != NULL)
3305 set_buffer_internal_1 (buf);
3307 /* How many newlines are there according to the cache? */
3308 find_newline (BEGV, BEGV_BYTE, ZV, ZV_BYTE,
3309 TYPE_MAXIMUM (ptrdiff_t), &shortage, NULL, true);
3310 nl_count_cache = TYPE_MAXIMUM (ptrdiff_t) - shortage;
3312 /* Create vector and populate it. */
3313 cache_newlines = make_uninit_vector (nl_count_cache);
3315 if (nl_count_cache)
3317 for (from = BEGV, found = from, i = 0; from < ZV; from = found, i++)
3319 ptrdiff_t from_byte = CHAR_TO_BYTE (from);
3321 found = find_newline (from, from_byte, 0, -1, 1, &shortage,
3322 NULL, true);
3323 if (shortage != 0 || i >= nl_count_cache)
3324 break;
3325 ASET (cache_newlines, i, make_number (found - 1));
3327 /* Fill the rest of slots with an invalid position. */
3328 for ( ; i < nl_count_cache; i++)
3329 ASET (cache_newlines, i, make_number (-1));
3332 /* Now do the same, but without using the cache. */
3333 find_newline1 (BEGV, BEGV_BYTE, ZV, ZV_BYTE,
3334 TYPE_MAXIMUM (ptrdiff_t), &shortage, NULL, true);
3335 nl_count_buf = TYPE_MAXIMUM (ptrdiff_t) - shortage;
3336 buf_newlines = make_uninit_vector (nl_count_buf);
3337 if (nl_count_buf)
3339 for (from = BEGV, found = from, i = 0; from < ZV; from = found, i++)
3341 ptrdiff_t from_byte = CHAR_TO_BYTE (from);
3343 found = find_newline1 (from, from_byte, 0, -1, 1, &shortage,
3344 NULL, true);
3345 if (shortage != 0 || i >= nl_count_buf)
3346 break;
3347 ASET (buf_newlines, i, make_number (found - 1));
3349 for ( ; i < nl_count_buf; i++)
3350 ASET (buf_newlines, i, make_number (-1));
3353 /* Construct the value and return it. */
3354 val = make_uninit_vector (2);
3355 ASET (val, 0, cache_newlines);
3356 ASET (val, 1, buf_newlines);
3358 if (old != NULL)
3359 set_buffer_internal_1 (old);
3360 return val;
3363 void
3364 syms_of_search (void)
3366 register int i;
3368 for (i = 0; i < REGEXP_CACHE_SIZE; ++i)
3370 searchbufs[i].buf.allocated = 100;
3371 searchbufs[i].buf.buffer = xmalloc (100);
3372 searchbufs[i].buf.fastmap = searchbufs[i].fastmap;
3373 searchbufs[i].regexp = Qnil;
3374 searchbufs[i].f_whitespace_regexp = Qnil;
3375 searchbufs[i].syntax_table = Qnil;
3376 staticpro (&searchbufs[i].regexp);
3377 staticpro (&searchbufs[i].f_whitespace_regexp);
3378 staticpro (&searchbufs[i].syntax_table);
3379 searchbufs[i].next = (i == REGEXP_CACHE_SIZE-1 ? 0 : &searchbufs[i+1]);
3381 searchbuf_head = &searchbufs[0];
3383 /* Error condition used for failing searches. */
3384 DEFSYM (Qsearch_failed, "search-failed");
3386 /* Error condition used for failing searches started by user, i.e.,
3387 where failure should not invoke the debugger. */
3388 DEFSYM (Quser_search_failed, "user-search-failed");
3390 /* Error condition signaled when regexp compile_pattern fails. */
3391 DEFSYM (Qinvalid_regexp, "invalid-regexp");
3393 Fput (Qsearch_failed, Qerror_conditions,
3394 listn (CONSTYPE_PURE, 2, Qsearch_failed, Qerror));
3395 Fput (Qsearch_failed, Qerror_message,
3396 build_pure_c_string ("Search failed"));
3398 Fput (Quser_search_failed, Qerror_conditions,
3399 listn (CONSTYPE_PURE, 4,
3400 Quser_search_failed, Quser_error, Qsearch_failed, Qerror));
3401 Fput (Quser_search_failed, Qerror_message,
3402 build_pure_c_string ("Search failed"));
3404 Fput (Qinvalid_regexp, Qerror_conditions,
3405 listn (CONSTYPE_PURE, 2, Qinvalid_regexp, Qerror));
3406 Fput (Qinvalid_regexp, Qerror_message,
3407 build_pure_c_string ("Invalid regexp"));
3409 last_thing_searched = Qnil;
3410 staticpro (&last_thing_searched);
3412 saved_last_thing_searched = Qnil;
3413 staticpro (&saved_last_thing_searched);
3415 DEFVAR_LISP ("search-spaces-regexp", Vsearch_spaces_regexp,
3416 doc: /* Regexp to substitute for bunches of spaces in regexp search.
3417 Some commands use this for user-specified regexps.
3418 Spaces that occur inside character classes or repetition operators
3419 or other such regexp constructs are not replaced with this.
3420 A value of nil (which is the normal value) means treat spaces literally. */);
3421 Vsearch_spaces_regexp = Qnil;
3423 DEFSYM (Qinhibit_changing_match_data, "inhibit-changing-match-data");
3424 DEFVAR_LISP ("inhibit-changing-match-data", Vinhibit_changing_match_data,
3425 doc: /* Internal use only.
3426 If non-nil, the primitive searching and matching functions
3427 such as `looking-at', `string-match', `re-search-forward', etc.,
3428 do not set the match data. The proper way to use this variable
3429 is to bind it with `let' around a small expression. */);
3430 Vinhibit_changing_match_data = Qnil;
3432 defsubr (&Slooking_at);
3433 defsubr (&Sposix_looking_at);
3434 defsubr (&Sstring_match);
3435 defsubr (&Sposix_string_match);
3436 defsubr (&Ssearch_forward);
3437 defsubr (&Ssearch_backward);
3438 defsubr (&Sre_search_forward);
3439 defsubr (&Sre_search_backward);
3440 defsubr (&Sposix_search_forward);
3441 defsubr (&Sposix_search_backward);
3442 defsubr (&Sreplace_match);
3443 defsubr (&Smatch_beginning);
3444 defsubr (&Smatch_end);
3445 defsubr (&Smatch_data);
3446 defsubr (&Sset_match_data);
3447 defsubr (&Sregexp_quote);
3448 defsubr (&Snewline_cache_check);