Minor improvement in section "Pages" of the usere manual
[emacs.git] / src / search.c
blob842e9309a2ed1e97d49bc9892a3c0ace25814882
1 /* String search routines for GNU Emacs.
3 Copyright (C) 1985-1987, 1993-1994, 1997-1999, 2001-2018 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.
2237 See `re-search-forward' for details. */)
2238 (Lisp_Object regexp, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
2240 return search_command (regexp, bound, noerror, count, -1, 1, 0);
2243 DEFUN ("re-search-forward", Fre_search_forward, Sre_search_forward, 1, 4,
2244 "sRE search: ",
2245 doc: /* Search forward from point for regular expression REGEXP.
2246 Set point to the end of the occurrence found, and return point.
2247 The optional second argument BOUND is a buffer position that bounds
2248 the search. The match found must not end after that position. A
2249 value of nil means search to the end of the accessible portion of
2250 the buffer.
2251 The optional third argument NOERROR indicates how errors are handled
2252 when the search fails. If it is nil or omitted, emit an error; if
2253 it is t, simply return nil and do nothing; if it is neither nil nor
2254 t, move to the limit of search and return nil.
2255 The optional fourth argument COUNT is a number that indicates the
2256 search direction and the number of occurrences to search for. If it
2257 is positive, search forward for COUNT successive occurrences; if it
2258 is negative, search backward, instead of forward, for -COUNT
2259 occurrences. A value of nil means the same as 1.
2260 With COUNT positive/negative, the match found is the COUNTth/-COUNTth
2261 one in the buffer located entirely after/before the origin of the
2262 search.
2264 Search case-sensitivity is determined by the value of the variable
2265 `case-fold-search', which see.
2267 See also the functions `match-beginning', `match-end', `match-string',
2268 and `replace-match'. */)
2269 (Lisp_Object regexp, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
2271 return search_command (regexp, bound, noerror, count, 1, 1, 0);
2274 DEFUN ("posix-search-backward", Fposix_search_backward, Sposix_search_backward, 1, 4,
2275 "sPosix search backward: ",
2276 doc: /* Search backward from point for match for regular expression REGEXP.
2277 Find the longest match in accord with Posix regular expression rules.
2278 Set point to the beginning of the occurrence found, and return point.
2279 An optional second argument bounds the search; it is a buffer position.
2280 The match found must not begin before that position. A value of nil
2281 means search to the beginning of the accessible portion of the buffer.
2282 Optional third argument, if t, means if fail just return nil (no error).
2283 If not nil and not t, position at limit of search and return nil.
2284 Optional fourth argument COUNT, if a positive number, means to search
2285 for COUNT successive occurrences. If COUNT is negative, search
2286 forward, instead of backward, for -COUNT occurrences. A value of
2287 nil means the same as 1.
2288 With COUNT positive, the match found is the COUNTth to last one (or
2289 last, if COUNT is 1 or nil) in the buffer located entirely before
2290 the origin of the search; correspondingly with COUNT negative.
2292 Search case-sensitivity is determined by the value of the variable
2293 `case-fold-search', which see.
2295 See also the functions `match-beginning', `match-end', `match-string',
2296 and `replace-match'. */)
2297 (Lisp_Object regexp, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
2299 return search_command (regexp, bound, noerror, count, -1, 1, 1);
2302 DEFUN ("posix-search-forward", Fposix_search_forward, Sposix_search_forward, 1, 4,
2303 "sPosix search: ",
2304 doc: /* Search forward from point for regular expression REGEXP.
2305 Find the longest match in accord with Posix regular expression rules.
2306 Set point to the end of the occurrence found, and return point.
2307 An optional second argument bounds the search; it is a buffer position.
2308 The match found must not end after that position. A value of nil
2309 means search to the end of the accessible portion of the buffer.
2310 Optional third argument, if t, means if fail just return nil (no error).
2311 If not nil and not t, move to limit of search and return nil.
2312 Optional fourth argument COUNT, if a positive number, means to search
2313 for COUNT successive occurrences. If COUNT is negative, search
2314 backward, instead of forward, for -COUNT occurrences. A value of
2315 nil means the same as 1.
2316 With COUNT positive, the match found is the COUNTth one (or first,
2317 if COUNT is 1 or nil) in the buffer located entirely after the
2318 origin of the search; correspondingly with COUNT negative.
2320 Search case-sensitivity is determined by the value of the variable
2321 `case-fold-search', which see.
2323 See also the functions `match-beginning', `match-end', `match-string',
2324 and `replace-match'. */)
2325 (Lisp_Object regexp, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
2327 return search_command (regexp, bound, noerror, count, 1, 1, 1);
2330 DEFUN ("replace-match", Freplace_match, Sreplace_match, 1, 5, 0,
2331 doc: /* Replace text matched by last search with NEWTEXT.
2332 Leave point at the end of the replacement text.
2334 If optional second arg FIXEDCASE is non-nil, do not alter the case of
2335 the replacement text. Otherwise, maybe capitalize the whole text, or
2336 maybe just word initials, based on the replaced text. If the replaced
2337 text has only capital letters and has at least one multiletter word,
2338 convert NEWTEXT to all caps. Otherwise if all words are capitalized
2339 in the replaced text, capitalize each word in NEWTEXT.
2341 If optional third arg LITERAL is non-nil, insert NEWTEXT literally.
2342 Otherwise treat `\\' as special:
2343 `\\&' in NEWTEXT means substitute original matched text.
2344 `\\N' means substitute what matched the Nth `\\(...\\)'.
2345 If Nth parens didn't match, substitute nothing.
2346 `\\\\' means insert one `\\'.
2347 `\\?' is treated literally
2348 (for compatibility with `query-replace-regexp').
2349 Any other character following `\\' signals an error.
2350 Case conversion does not apply to these substitutions.
2352 If optional fourth argument STRING is non-nil, it should be a string
2353 to act on; this should be the string on which the previous match was
2354 done via `string-match'. In this case, `replace-match' creates and
2355 returns a new string, made by copying STRING and replacing the part of
2356 STRING that was matched (the original STRING itself is not altered).
2358 The optional fifth argument SUBEXP specifies a subexpression;
2359 it says to replace just that subexpression with NEWTEXT,
2360 rather than replacing the entire matched text.
2361 This is, in a vague sense, the inverse of using `\\N' in NEWTEXT;
2362 `\\N' copies subexp N into NEWTEXT, but using N as SUBEXP puts
2363 NEWTEXT in place of subexp N.
2364 This is useful only after a regular expression search or match,
2365 since only regular expressions have distinguished subexpressions. */)
2366 (Lisp_Object newtext, Lisp_Object fixedcase, Lisp_Object literal, Lisp_Object string, Lisp_Object subexp)
2368 enum { nochange, all_caps, cap_initial } case_action;
2369 ptrdiff_t pos, pos_byte;
2370 bool some_multiletter_word;
2371 bool some_lowercase;
2372 bool some_uppercase;
2373 bool some_nonuppercase_initial;
2374 int c, prevc;
2375 ptrdiff_t sub;
2376 ptrdiff_t opoint, newpoint;
2378 CHECK_STRING (newtext);
2380 if (! NILP (string))
2381 CHECK_STRING (string);
2383 case_action = nochange; /* We tried an initialization */
2384 /* but some C compilers blew it */
2386 if (search_regs.num_regs <= 0)
2387 error ("`replace-match' called before any match found");
2389 if (NILP (subexp))
2390 sub = 0;
2391 else
2393 CHECK_NUMBER (subexp);
2394 if (! (0 <= XINT (subexp) && XINT (subexp) < search_regs.num_regs))
2395 args_out_of_range (subexp, make_number (search_regs.num_regs));
2396 sub = XINT (subexp);
2399 if (NILP (string))
2401 if (search_regs.start[sub] < BEGV
2402 || search_regs.start[sub] > search_regs.end[sub]
2403 || search_regs.end[sub] > ZV)
2404 args_out_of_range (make_number (search_regs.start[sub]),
2405 make_number (search_regs.end[sub]));
2407 else
2409 if (search_regs.start[sub] < 0
2410 || search_regs.start[sub] > search_regs.end[sub]
2411 || search_regs.end[sub] > SCHARS (string))
2412 args_out_of_range (make_number (search_regs.start[sub]),
2413 make_number (search_regs.end[sub]));
2416 if (NILP (fixedcase))
2418 /* Decide how to casify by examining the matched text. */
2419 ptrdiff_t last;
2421 pos = search_regs.start[sub];
2422 last = search_regs.end[sub];
2424 if (NILP (string))
2425 pos_byte = CHAR_TO_BYTE (pos);
2426 else
2427 pos_byte = string_char_to_byte (string, pos);
2429 prevc = '\n';
2430 case_action = all_caps;
2432 /* some_multiletter_word is set nonzero if any original word
2433 is more than one letter long. */
2434 some_multiletter_word = 0;
2435 some_lowercase = 0;
2436 some_nonuppercase_initial = 0;
2437 some_uppercase = 0;
2439 while (pos < last)
2441 if (NILP (string))
2443 c = FETCH_CHAR_AS_MULTIBYTE (pos_byte);
2444 INC_BOTH (pos, pos_byte);
2446 else
2447 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c, string, pos, pos_byte);
2449 if (lowercasep (c))
2451 /* Cannot be all caps if any original char is lower case */
2453 some_lowercase = 1;
2454 if (SYNTAX (prevc) != Sword)
2455 some_nonuppercase_initial = 1;
2456 else
2457 some_multiletter_word = 1;
2459 else if (uppercasep (c))
2461 some_uppercase = 1;
2462 if (SYNTAX (prevc) != Sword)
2464 else
2465 some_multiletter_word = 1;
2467 else
2469 /* If the initial is a caseless word constituent,
2470 treat that like a lowercase initial. */
2471 if (SYNTAX (prevc) != Sword)
2472 some_nonuppercase_initial = 1;
2475 prevc = c;
2478 /* Convert to all caps if the old text is all caps
2479 and has at least one multiletter word. */
2480 if (! some_lowercase && some_multiletter_word)
2481 case_action = all_caps;
2482 /* Capitalize each word, if the old text has all capitalized words. */
2483 else if (!some_nonuppercase_initial && some_multiletter_word)
2484 case_action = cap_initial;
2485 else if (!some_nonuppercase_initial && some_uppercase)
2486 /* Should x -> yz, operating on X, give Yz or YZ?
2487 We'll assume the latter. */
2488 case_action = all_caps;
2489 else
2490 case_action = nochange;
2493 /* Do replacement in a string. */
2494 if (!NILP (string))
2496 Lisp_Object before, after;
2498 before = Fsubstring (string, make_number (0),
2499 make_number (search_regs.start[sub]));
2500 after = Fsubstring (string, make_number (search_regs.end[sub]), Qnil);
2502 /* Substitute parts of the match into NEWTEXT
2503 if desired. */
2504 if (NILP (literal))
2506 ptrdiff_t lastpos = 0;
2507 ptrdiff_t lastpos_byte = 0;
2508 /* We build up the substituted string in ACCUM. */
2509 Lisp_Object accum;
2510 Lisp_Object middle;
2511 ptrdiff_t length = SBYTES (newtext);
2513 accum = Qnil;
2515 for (pos_byte = 0, pos = 0; pos_byte < length;)
2517 ptrdiff_t substart = -1;
2518 ptrdiff_t subend = 0;
2519 bool delbackslash = 0;
2521 FETCH_STRING_CHAR_ADVANCE (c, newtext, pos, pos_byte);
2523 if (c == '\\')
2525 FETCH_STRING_CHAR_ADVANCE (c, newtext, pos, pos_byte);
2527 if (c == '&')
2529 substart = search_regs.start[sub];
2530 subend = search_regs.end[sub];
2532 else if (c >= '1' && c <= '9')
2534 if (c - '0' < search_regs.num_regs
2535 && search_regs.start[c - '0'] >= 0)
2537 substart = search_regs.start[c - '0'];
2538 subend = search_regs.end[c - '0'];
2540 else
2542 /* If that subexp did not match,
2543 replace \\N with nothing. */
2544 substart = 0;
2545 subend = 0;
2548 else if (c == '\\')
2549 delbackslash = 1;
2550 else if (c != '?')
2551 error ("Invalid use of `\\' in replacement text");
2553 if (substart >= 0)
2555 if (pos - 2 != lastpos)
2556 middle = substring_both (newtext, lastpos,
2557 lastpos_byte,
2558 pos - 2, pos_byte - 2);
2559 else
2560 middle = Qnil;
2561 accum = concat3 (accum, middle,
2562 Fsubstring (string,
2563 make_number (substart),
2564 make_number (subend)));
2565 lastpos = pos;
2566 lastpos_byte = pos_byte;
2568 else if (delbackslash)
2570 middle = substring_both (newtext, lastpos,
2571 lastpos_byte,
2572 pos - 1, pos_byte - 1);
2574 accum = concat2 (accum, middle);
2575 lastpos = pos;
2576 lastpos_byte = pos_byte;
2580 if (pos != lastpos)
2581 middle = substring_both (newtext, lastpos,
2582 lastpos_byte,
2583 pos, pos_byte);
2584 else
2585 middle = Qnil;
2587 newtext = concat2 (accum, middle);
2590 /* Do case substitution in NEWTEXT if desired. */
2591 if (case_action == all_caps)
2592 newtext = Fupcase (newtext);
2593 else if (case_action == cap_initial)
2594 newtext = Fupcase_initials (newtext);
2596 return concat3 (before, newtext, after);
2599 /* Record point, then move (quietly) to the start of the match. */
2600 if (PT >= search_regs.end[sub])
2601 opoint = PT - ZV;
2602 else if (PT > search_regs.start[sub])
2603 opoint = search_regs.end[sub] - ZV;
2604 else
2605 opoint = PT;
2607 /* If we want non-literal replacement,
2608 perform substitution on the replacement string. */
2609 if (NILP (literal))
2611 ptrdiff_t length = SBYTES (newtext);
2612 unsigned char *substed;
2613 ptrdiff_t substed_alloc_size, substed_len;
2614 bool buf_multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
2615 bool str_multibyte = STRING_MULTIBYTE (newtext);
2616 bool really_changed = 0;
2618 substed_alloc_size = (length <= (STRING_BYTES_BOUND - 100) / 2
2619 ? length * 2 + 100
2620 : STRING_BYTES_BOUND);
2621 substed = xmalloc (substed_alloc_size);
2622 substed_len = 0;
2624 /* Go thru NEWTEXT, producing the actual text to insert in
2625 SUBSTED while adjusting multibyteness to that of the current
2626 buffer. */
2628 for (pos_byte = 0, pos = 0; pos_byte < length;)
2630 unsigned char str[MAX_MULTIBYTE_LENGTH];
2631 const unsigned char *add_stuff = NULL;
2632 ptrdiff_t add_len = 0;
2633 ptrdiff_t idx = -1;
2634 ptrdiff_t begbyte UNINIT;
2636 if (str_multibyte)
2638 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, newtext, pos, pos_byte);
2639 if (!buf_multibyte)
2640 c = CHAR_TO_BYTE8 (c);
2642 else
2644 /* Note that we don't have to increment POS. */
2645 c = SREF (newtext, pos_byte++);
2646 if (buf_multibyte)
2647 MAKE_CHAR_MULTIBYTE (c);
2650 /* Either set ADD_STUFF and ADD_LEN to the text to put in SUBSTED,
2651 or set IDX to a match index, which means put that part
2652 of the buffer text into SUBSTED. */
2654 if (c == '\\')
2656 really_changed = 1;
2658 if (str_multibyte)
2660 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, newtext,
2661 pos, pos_byte);
2662 if (!buf_multibyte && !ASCII_CHAR_P (c))
2663 c = CHAR_TO_BYTE8 (c);
2665 else
2667 c = SREF (newtext, pos_byte++);
2668 if (buf_multibyte)
2669 MAKE_CHAR_MULTIBYTE (c);
2672 if (c == '&')
2673 idx = sub;
2674 else if (c >= '1' && c <= '9' && c - '0' < search_regs.num_regs)
2676 if (search_regs.start[c - '0'] >= 1)
2677 idx = c - '0';
2679 else if (c == '\\')
2680 add_len = 1, add_stuff = (unsigned char *) "\\";
2681 else
2683 xfree (substed);
2684 error ("Invalid use of `\\' in replacement text");
2687 else
2689 add_len = CHAR_STRING (c, str);
2690 add_stuff = str;
2693 /* If we want to copy part of a previous match,
2694 set up ADD_STUFF and ADD_LEN to point to it. */
2695 if (idx >= 0)
2697 begbyte = CHAR_TO_BYTE (search_regs.start[idx]);
2698 add_len = CHAR_TO_BYTE (search_regs.end[idx]) - begbyte;
2699 if (search_regs.start[idx] < GPT && GPT < search_regs.end[idx])
2700 move_gap_both (search_regs.start[idx], begbyte);
2703 /* Now the stuff we want to add to SUBSTED
2704 is invariably ADD_LEN bytes starting at ADD_STUFF. */
2706 /* Make sure SUBSTED is big enough. */
2707 if (substed_alloc_size - substed_len < add_len)
2708 substed =
2709 xpalloc (substed, &substed_alloc_size,
2710 add_len - (substed_alloc_size - substed_len),
2711 STRING_BYTES_BOUND, 1);
2713 /* We compute this after the call to xpalloc, because that
2714 could cause buffer text be relocated when ralloc.c is used. */
2715 if (idx >= 0)
2716 add_stuff = BYTE_POS_ADDR (begbyte);
2718 /* Now add to the end of SUBSTED. */
2719 if (add_stuff)
2721 memcpy (substed + substed_len, add_stuff, add_len);
2722 substed_len += add_len;
2726 if (really_changed)
2727 newtext = make_specified_string ((const char *) substed, -1,
2728 substed_len, buf_multibyte);
2729 xfree (substed);
2732 /* The functions below modify the buffer, so they could trigger
2733 various modification hooks (see signal_before_change and
2734 signal_after_change). If these hooks clobber the match data we
2735 error out since otherwise this will result in confusing bugs. */
2736 ptrdiff_t sub_start = search_regs.start[sub];
2737 ptrdiff_t sub_end = search_regs.end[sub];
2738 unsigned num_regs = search_regs.num_regs;
2739 newpoint = search_regs.start[sub] + SCHARS (newtext);
2741 /* Replace the old text with the new in the cleanest possible way. */
2742 replace_range (search_regs.start[sub], search_regs.end[sub],
2743 newtext, 1, 0, 1, 1);
2744 /* Update saved data to match adjustment made by replace_range. */
2746 ptrdiff_t change = newpoint - sub_end;
2747 if (sub_start >= sub_end)
2748 sub_start += change;
2749 sub_end += change;
2752 if (case_action == all_caps)
2753 Fupcase_region (make_number (search_regs.start[sub]),
2754 make_number (newpoint),
2755 Qnil);
2756 else if (case_action == cap_initial)
2757 Fupcase_initials_region (make_number (search_regs.start[sub]),
2758 make_number (newpoint));
2760 if (search_regs.start[sub] != sub_start
2761 || search_regs.end[sub] != sub_end
2762 || search_regs.num_regs != num_regs)
2763 error ("Match data clobbered by buffer modification hooks");
2765 /* Put point back where it was in the text. */
2766 if (opoint <= 0)
2767 TEMP_SET_PT (opoint + ZV);
2768 else
2769 TEMP_SET_PT (opoint);
2771 /* Now move point "officially" to the start of the inserted replacement. */
2772 move_if_not_intangible (newpoint);
2774 return Qnil;
2777 static Lisp_Object
2778 match_limit (Lisp_Object num, bool beginningp)
2780 EMACS_INT n;
2782 CHECK_NUMBER (num);
2783 n = XINT (num);
2784 if (n < 0)
2785 args_out_of_range (num, make_number (0));
2786 if (search_regs.num_regs <= 0)
2787 error ("No match data, because no search succeeded");
2788 if (n >= search_regs.num_regs
2789 || search_regs.start[n] < 0)
2790 return Qnil;
2791 return (make_number ((beginningp) ? search_regs.start[n]
2792 : search_regs.end[n]));
2795 DEFUN ("match-beginning", Fmatch_beginning, Smatch_beginning, 1, 1, 0,
2796 doc: /* Return position of start of text matched by last search.
2797 SUBEXP, a number, specifies which parenthesized expression in the last
2798 regexp.
2799 Value is nil if SUBEXPth pair didn't match, or there were less than
2800 SUBEXP pairs.
2801 Zero means the entire text matched by the whole regexp or whole string.
2803 Return value is undefined if the last search failed. */)
2804 (Lisp_Object subexp)
2806 return match_limit (subexp, 1);
2809 DEFUN ("match-end", Fmatch_end, Smatch_end, 1, 1, 0,
2810 doc: /* Return position of end of text matched by last search.
2811 SUBEXP, a number, specifies which parenthesized expression in the last
2812 regexp.
2813 Value is nil if SUBEXPth pair didn't match, or there were less than
2814 SUBEXP pairs.
2815 Zero means the entire text matched by the whole regexp or whole string.
2817 Return value is undefined if the last search failed. */)
2818 (Lisp_Object subexp)
2820 return match_limit (subexp, 0);
2823 DEFUN ("match-data", Fmatch_data, Smatch_data, 0, 3, 0,
2824 doc: /* Return a list describing what the last search matched.
2825 Element 2N is `(match-beginning N)'; element 2N + 1 is `(match-end N)'.
2826 All the elements are markers or nil (nil if the Nth pair didn't match)
2827 if the last match was on a buffer; integers or nil if a string was matched.
2828 Use `set-match-data' to reinstate the data in this list.
2830 If INTEGERS (the optional first argument) is non-nil, always use
2831 integers (rather than markers) to represent buffer positions. In
2832 this case, and if the last match was in a buffer, the buffer will get
2833 stored as one additional element at the end of the list.
2835 If REUSE is a list, reuse it as part of the value. If REUSE is long
2836 enough to hold all the values, and if INTEGERS is non-nil, no consing
2837 is done.
2839 If optional third arg RESEAT is non-nil, any previous markers on the
2840 REUSE list will be modified to point to nowhere.
2842 Return value is undefined if the last search failed. */)
2843 (Lisp_Object integers, Lisp_Object reuse, Lisp_Object reseat)
2845 Lisp_Object tail, prev;
2846 Lisp_Object *data;
2847 ptrdiff_t i, len;
2849 if (!NILP (reseat))
2850 for (tail = reuse; CONSP (tail); tail = XCDR (tail))
2851 if (MARKERP (XCAR (tail)))
2853 unchain_marker (XMARKER (XCAR (tail)));
2854 XSETCAR (tail, Qnil);
2857 if (NILP (last_thing_searched))
2858 return Qnil;
2860 prev = Qnil;
2862 USE_SAFE_ALLOCA;
2863 SAFE_NALLOCA (data, 1, 2 * search_regs.num_regs + 1);
2865 len = 0;
2866 for (i = 0; i < search_regs.num_regs; i++)
2868 ptrdiff_t start = search_regs.start[i];
2869 if (start >= 0)
2871 if (EQ (last_thing_searched, Qt)
2872 || ! NILP (integers))
2874 XSETFASTINT (data[2 * i], start);
2875 XSETFASTINT (data[2 * i + 1], search_regs.end[i]);
2877 else if (BUFFERP (last_thing_searched))
2879 data[2 * i] = Fmake_marker ();
2880 Fset_marker (data[2 * i],
2881 make_number (start),
2882 last_thing_searched);
2883 data[2 * i + 1] = Fmake_marker ();
2884 Fset_marker (data[2 * i + 1],
2885 make_number (search_regs.end[i]),
2886 last_thing_searched);
2888 else
2889 /* last_thing_searched must always be Qt, a buffer, or Qnil. */
2890 emacs_abort ();
2892 len = 2 * i + 2;
2894 else
2895 data[2 * i] = data[2 * i + 1] = Qnil;
2898 if (BUFFERP (last_thing_searched) && !NILP (integers))
2900 data[len] = last_thing_searched;
2901 len++;
2904 /* If REUSE is not usable, cons up the values and return them. */
2905 if (! CONSP (reuse))
2906 reuse = Flist (len, data);
2907 else
2909 /* If REUSE is a list, store as many value elements as will fit
2910 into the elements of REUSE. */
2911 for (i = 0, tail = reuse; CONSP (tail);
2912 i++, tail = XCDR (tail))
2914 if (i < len)
2915 XSETCAR (tail, data[i]);
2916 else
2917 XSETCAR (tail, Qnil);
2918 prev = tail;
2921 /* If we couldn't fit all value elements into REUSE,
2922 cons up the rest of them and add them to the end of REUSE. */
2923 if (i < len)
2924 XSETCDR (prev, Flist (len - i, data + i));
2927 SAFE_FREE ();
2928 return reuse;
2931 /* We used to have an internal use variant of `reseat' described as:
2933 If RESEAT is `evaporate', put the markers back on the free list
2934 immediately. No other references to the markers must exist in this
2935 case, so it is used only internally on the unwind stack and
2936 save-match-data from Lisp.
2938 But it was ill-conceived: those supposedly-internal markers get exposed via
2939 the undo-list, so freeing them here is unsafe. */
2941 DEFUN ("set-match-data", Fset_match_data, Sset_match_data, 1, 2, 0,
2942 doc: /* Set internal data on last search match from elements of LIST.
2943 LIST should have been created by calling `match-data' previously.
2945 If optional arg RESEAT is non-nil, make markers on LIST point nowhere. */)
2946 (register Lisp_Object list, Lisp_Object reseat)
2948 ptrdiff_t i;
2949 register Lisp_Object marker;
2951 if (running_asynch_code)
2952 save_search_regs ();
2954 CHECK_LIST (list);
2956 /* Unless we find a marker with a buffer or an explicit buffer
2957 in LIST, assume that this match data came from a string. */
2958 last_thing_searched = Qt;
2960 /* Allocate registers if they don't already exist. */
2962 EMACS_INT length = XFASTINT (Flength (list)) / 2;
2964 if (length > search_regs.num_regs)
2966 ptrdiff_t num_regs = search_regs.num_regs;
2967 if (PTRDIFF_MAX < length)
2968 memory_full (SIZE_MAX);
2969 search_regs.start =
2970 xpalloc (search_regs.start, &num_regs, length - num_regs,
2971 min (PTRDIFF_MAX, UINT_MAX), sizeof (regoff_t));
2972 search_regs.end =
2973 xrealloc (search_regs.end, num_regs * sizeof (regoff_t));
2975 for (i = search_regs.num_regs; i < num_regs; i++)
2976 search_regs.start[i] = -1;
2978 search_regs.num_regs = num_regs;
2981 for (i = 0; CONSP (list); i++)
2983 marker = XCAR (list);
2984 if (BUFFERP (marker))
2986 last_thing_searched = marker;
2987 break;
2989 if (i >= length)
2990 break;
2991 if (NILP (marker))
2993 search_regs.start[i] = -1;
2994 list = XCDR (list);
2996 else
2998 Lisp_Object from;
2999 Lisp_Object m;
3001 m = marker;
3002 if (MARKERP (marker))
3004 if (XMARKER (marker)->buffer == 0)
3005 XSETFASTINT (marker, 0);
3006 else
3007 XSETBUFFER (last_thing_searched, XMARKER (marker)->buffer);
3010 CHECK_NUMBER_COERCE_MARKER (marker);
3011 from = marker;
3013 if (!NILP (reseat) && MARKERP (m))
3015 unchain_marker (XMARKER (m));
3016 XSETCAR (list, Qnil);
3019 if ((list = XCDR (list), !CONSP (list)))
3020 break;
3022 m = marker = XCAR (list);
3024 if (MARKERP (marker) && XMARKER (marker)->buffer == 0)
3025 XSETFASTINT (marker, 0);
3027 CHECK_NUMBER_COERCE_MARKER (marker);
3028 if ((XINT (from) < 0
3029 ? TYPE_MINIMUM (regoff_t) <= XINT (from)
3030 : XINT (from) <= TYPE_MAXIMUM (regoff_t))
3031 && (XINT (marker) < 0
3032 ? TYPE_MINIMUM (regoff_t) <= XINT (marker)
3033 : XINT (marker) <= TYPE_MAXIMUM (regoff_t)))
3035 search_regs.start[i] = XINT (from);
3036 search_regs.end[i] = XINT (marker);
3038 else
3040 search_regs.start[i] = -1;
3043 if (!NILP (reseat) && MARKERP (m))
3045 unchain_marker (XMARKER (m));
3046 XSETCAR (list, Qnil);
3049 list = XCDR (list);
3052 for (; i < search_regs.num_regs; i++)
3053 search_regs.start[i] = -1;
3056 return Qnil;
3059 /* If true the match data have been saved in saved_search_regs
3060 during the execution of a sentinel or filter. */
3061 /* static bool search_regs_saved; */
3062 /* static struct re_registers saved_search_regs; */
3063 /* static Lisp_Object saved_last_thing_searched; */
3065 /* Called from Flooking_at, Fstring_match, search_buffer, Fstore_match_data
3066 if asynchronous code (filter or sentinel) is running. */
3067 static void
3068 save_search_regs (void)
3070 if (!search_regs_saved)
3072 saved_search_regs.num_regs = search_regs.num_regs;
3073 saved_search_regs.start = search_regs.start;
3074 saved_search_regs.end = search_regs.end;
3075 saved_last_thing_searched = last_thing_searched;
3076 last_thing_searched = Qnil;
3077 search_regs.num_regs = 0;
3078 search_regs.start = 0;
3079 search_regs.end = 0;
3081 search_regs_saved = 1;
3085 /* Called upon exit from filters and sentinels. */
3086 void
3087 restore_search_regs (void)
3089 if (search_regs_saved)
3091 if (search_regs.num_regs > 0)
3093 xfree (search_regs.start);
3094 xfree (search_regs.end);
3096 search_regs.num_regs = saved_search_regs.num_regs;
3097 search_regs.start = saved_search_regs.start;
3098 search_regs.end = saved_search_regs.end;
3099 last_thing_searched = saved_last_thing_searched;
3100 saved_last_thing_searched = Qnil;
3101 search_regs_saved = 0;
3105 /* Called from replace-match via replace_range. */
3106 void
3107 update_search_regs (ptrdiff_t oldstart, ptrdiff_t oldend, ptrdiff_t newend)
3109 /* Adjust search data for this change. */
3110 ptrdiff_t change = newend - oldend;
3111 ptrdiff_t i;
3113 for (i = 0; i < search_regs.num_regs; i++)
3115 if (search_regs.start[i] >= oldend)
3116 search_regs.start[i] += change;
3117 else if (search_regs.start[i] > oldstart)
3118 search_regs.start[i] = oldstart;
3119 if (search_regs.end[i] >= oldend)
3120 search_regs.end[i] += change;
3121 else if (search_regs.end[i] > oldstart)
3122 search_regs.end[i] = oldstart;
3126 static void
3127 unwind_set_match_data (Lisp_Object list)
3129 /* It is NOT ALWAYS safe to free (evaporate) the markers immediately. */
3130 Fset_match_data (list, Qt);
3133 /* Called to unwind protect the match data. */
3134 void
3135 record_unwind_save_match_data (void)
3137 record_unwind_protect (unwind_set_match_data,
3138 Fmatch_data (Qnil, Qnil, Qnil));
3141 /* Quote a string to deactivate reg-expr chars */
3143 DEFUN ("regexp-quote", Fregexp_quote, Sregexp_quote, 1, 1, 0,
3144 doc: /* Return a regexp string which matches exactly STRING and nothing else. */)
3145 (Lisp_Object string)
3147 char *in, *out, *end;
3148 char *temp;
3149 ptrdiff_t backslashes_added = 0;
3151 CHECK_STRING (string);
3153 USE_SAFE_ALLOCA;
3154 SAFE_NALLOCA (temp, 2, SBYTES (string));
3156 /* Now copy the data into the new string, inserting escapes. */
3158 in = SSDATA (string);
3159 end = in + SBYTES (string);
3160 out = temp;
3162 for (; in != end; in++)
3164 if (*in == '['
3165 || *in == '*' || *in == '.' || *in == '\\'
3166 || *in == '?' || *in == '+'
3167 || *in == '^' || *in == '$')
3168 *out++ = '\\', backslashes_added++;
3169 *out++ = *in;
3172 Lisp_Object result
3173 = make_specified_string (temp,
3174 SCHARS (string) + backslashes_added,
3175 out - temp,
3176 STRING_MULTIBYTE (string));
3177 SAFE_FREE ();
3178 return result;
3181 /* Like find_newline, but doesn't use the cache, and only searches forward. */
3182 static ptrdiff_t
3183 find_newline1 (ptrdiff_t start, ptrdiff_t start_byte, ptrdiff_t end,
3184 ptrdiff_t end_byte, ptrdiff_t count, ptrdiff_t *shortage,
3185 ptrdiff_t *bytepos, bool allow_quit)
3187 if (count > 0)
3189 if (!end)
3190 end = ZV, end_byte = ZV_BYTE;
3192 else
3194 if (!end)
3195 end = BEGV, end_byte = BEGV_BYTE;
3197 if (end_byte == -1)
3198 end_byte = CHAR_TO_BYTE (end);
3200 if (shortage != 0)
3201 *shortage = 0;
3203 if (count > 0)
3204 while (start != end)
3206 /* Our innermost scanning loop is very simple; it doesn't know
3207 about gaps, buffer ends, or the newline cache. ceiling is
3208 the position of the last character before the next such
3209 obstacle --- the last character the dumb search loop should
3210 examine. */
3211 ptrdiff_t tem, ceiling_byte = end_byte - 1;
3213 if (start_byte == -1)
3214 start_byte = CHAR_TO_BYTE (start);
3216 /* The dumb loop can only scan text stored in contiguous
3217 bytes. BUFFER_CEILING_OF returns the last character
3218 position that is contiguous, so the ceiling is the
3219 position after that. */
3220 tem = BUFFER_CEILING_OF (start_byte);
3221 ceiling_byte = min (tem, ceiling_byte);
3224 /* The termination address of the dumb loop. */
3225 unsigned char *lim_addr = BYTE_POS_ADDR (ceiling_byte) + 1;
3226 ptrdiff_t lim_byte = ceiling_byte + 1;
3228 /* Nonpositive offsets (relative to LIM_ADDR and LIM_BYTE)
3229 of the base, the cursor, and the next line. */
3230 ptrdiff_t base = start_byte - lim_byte;
3231 ptrdiff_t cursor, next;
3233 for (cursor = base; cursor < 0; cursor = next)
3235 /* The dumb loop. */
3236 unsigned char *nl = memchr (lim_addr + cursor, '\n', - cursor);
3237 next = nl ? nl - lim_addr : 0;
3239 if (! nl)
3240 break;
3241 next++;
3243 if (--count == 0)
3245 if (bytepos)
3246 *bytepos = lim_byte + next;
3247 return BYTE_TO_CHAR (lim_byte + next);
3249 if (allow_quit)
3250 maybe_quit ();
3253 start_byte = lim_byte;
3254 start = BYTE_TO_CHAR (start_byte);
3258 if (shortage)
3259 *shortage = count;
3260 if (bytepos)
3262 *bytepos = start_byte == -1 ? CHAR_TO_BYTE (start) : start_byte;
3263 eassert (*bytepos == CHAR_TO_BYTE (start));
3265 return start;
3268 DEFUN ("newline-cache-check", Fnewline_cache_check, Snewline_cache_check,
3269 0, 1, 0,
3270 doc: /* Check the newline cache of BUFFER against buffer contents.
3272 BUFFER defaults to the current buffer.
3274 Value is an array of 2 sub-arrays of buffer positions for newlines,
3275 the first based on the cache, the second based on actually scanning
3276 the buffer. If the buffer doesn't have a cache, the value is nil. */)
3277 (Lisp_Object buffer)
3279 struct buffer *buf, *old = NULL;
3280 ptrdiff_t shortage, nl_count_cache, nl_count_buf;
3281 Lisp_Object cache_newlines, buf_newlines, val;
3282 ptrdiff_t from, found, i;
3284 if (NILP (buffer))
3285 buf = current_buffer;
3286 else
3288 CHECK_BUFFER (buffer);
3289 buf = XBUFFER (buffer);
3290 old = current_buffer;
3292 if (buf->base_buffer)
3293 buf = buf->base_buffer;
3295 /* If the buffer doesn't have a newline cache, return nil. */
3296 if (NILP (BVAR (buf, cache_long_scans))
3297 || buf->newline_cache == NULL)
3298 return Qnil;
3300 /* find_newline can only work on the current buffer. */
3301 if (old != NULL)
3302 set_buffer_internal_1 (buf);
3304 /* How many newlines are there according to the cache? */
3305 find_newline (BEGV, BEGV_BYTE, ZV, ZV_BYTE,
3306 TYPE_MAXIMUM (ptrdiff_t), &shortage, NULL, true);
3307 nl_count_cache = TYPE_MAXIMUM (ptrdiff_t) - shortage;
3309 /* Create vector and populate it. */
3310 cache_newlines = make_uninit_vector (nl_count_cache);
3312 if (nl_count_cache)
3314 for (from = BEGV, found = from, i = 0; from < ZV; from = found, i++)
3316 ptrdiff_t from_byte = CHAR_TO_BYTE (from);
3318 found = find_newline (from, from_byte, 0, -1, 1, &shortage,
3319 NULL, true);
3320 if (shortage != 0 || i >= nl_count_cache)
3321 break;
3322 ASET (cache_newlines, i, make_number (found - 1));
3324 /* Fill the rest of slots with an invalid position. */
3325 for ( ; i < nl_count_cache; i++)
3326 ASET (cache_newlines, i, make_number (-1));
3329 /* Now do the same, but without using the cache. */
3330 find_newline1 (BEGV, BEGV_BYTE, ZV, ZV_BYTE,
3331 TYPE_MAXIMUM (ptrdiff_t), &shortage, NULL, true);
3332 nl_count_buf = TYPE_MAXIMUM (ptrdiff_t) - shortage;
3333 buf_newlines = make_uninit_vector (nl_count_buf);
3334 if (nl_count_buf)
3336 for (from = BEGV, found = from, i = 0; from < ZV; from = found, i++)
3338 ptrdiff_t from_byte = CHAR_TO_BYTE (from);
3340 found = find_newline1 (from, from_byte, 0, -1, 1, &shortage,
3341 NULL, true);
3342 if (shortage != 0 || i >= nl_count_buf)
3343 break;
3344 ASET (buf_newlines, i, make_number (found - 1));
3346 for ( ; i < nl_count_buf; i++)
3347 ASET (buf_newlines, i, make_number (-1));
3350 /* Construct the value and return it. */
3351 val = make_uninit_vector (2);
3352 ASET (val, 0, cache_newlines);
3353 ASET (val, 1, buf_newlines);
3355 if (old != NULL)
3356 set_buffer_internal_1 (old);
3357 return val;
3360 void
3361 syms_of_search (void)
3363 register int i;
3365 for (i = 0; i < REGEXP_CACHE_SIZE; ++i)
3367 searchbufs[i].buf.allocated = 100;
3368 searchbufs[i].buf.buffer = xmalloc (100);
3369 searchbufs[i].buf.fastmap = searchbufs[i].fastmap;
3370 searchbufs[i].regexp = Qnil;
3371 searchbufs[i].f_whitespace_regexp = Qnil;
3372 searchbufs[i].syntax_table = Qnil;
3373 staticpro (&searchbufs[i].regexp);
3374 staticpro (&searchbufs[i].f_whitespace_regexp);
3375 staticpro (&searchbufs[i].syntax_table);
3376 searchbufs[i].next = (i == REGEXP_CACHE_SIZE-1 ? 0 : &searchbufs[i+1]);
3378 searchbuf_head = &searchbufs[0];
3380 /* Error condition used for failing searches. */
3381 DEFSYM (Qsearch_failed, "search-failed");
3383 /* Error condition used for failing searches started by user, i.e.,
3384 where failure should not invoke the debugger. */
3385 DEFSYM (Quser_search_failed, "user-search-failed");
3387 /* Error condition signaled when regexp compile_pattern fails. */
3388 DEFSYM (Qinvalid_regexp, "invalid-regexp");
3390 Fput (Qsearch_failed, Qerror_conditions,
3391 listn (CONSTYPE_PURE, 2, Qsearch_failed, Qerror));
3392 Fput (Qsearch_failed, Qerror_message,
3393 build_pure_c_string ("Search failed"));
3395 Fput (Quser_search_failed, Qerror_conditions,
3396 listn (CONSTYPE_PURE, 4,
3397 Quser_search_failed, Quser_error, Qsearch_failed, Qerror));
3398 Fput (Quser_search_failed, Qerror_message,
3399 build_pure_c_string ("Search failed"));
3401 Fput (Qinvalid_regexp, Qerror_conditions,
3402 listn (CONSTYPE_PURE, 2, Qinvalid_regexp, Qerror));
3403 Fput (Qinvalid_regexp, Qerror_message,
3404 build_pure_c_string ("Invalid regexp"));
3406 last_thing_searched = Qnil;
3407 staticpro (&last_thing_searched);
3409 saved_last_thing_searched = Qnil;
3410 staticpro (&saved_last_thing_searched);
3412 DEFVAR_LISP ("search-spaces-regexp", Vsearch_spaces_regexp,
3413 doc: /* Regexp to substitute for bunches of spaces in regexp search.
3414 Some commands use this for user-specified regexps.
3415 Spaces that occur inside character classes or repetition operators
3416 or other such regexp constructs are not replaced with this.
3417 A value of nil (which is the normal value) means treat spaces literally. */);
3418 Vsearch_spaces_regexp = Qnil;
3420 DEFSYM (Qinhibit_changing_match_data, "inhibit-changing-match-data");
3421 DEFVAR_LISP ("inhibit-changing-match-data", Vinhibit_changing_match_data,
3422 doc: /* Internal use only.
3423 If non-nil, the primitive searching and matching functions
3424 such as `looking-at', `string-match', `re-search-forward', etc.,
3425 do not set the match data. The proper way to use this variable
3426 is to bind it with `let' around a small expression. */);
3427 Vinhibit_changing_match_data = Qnil;
3429 defsubr (&Slooking_at);
3430 defsubr (&Sposix_looking_at);
3431 defsubr (&Sstring_match);
3432 defsubr (&Sposix_string_match);
3433 defsubr (&Ssearch_forward);
3434 defsubr (&Ssearch_backward);
3435 defsubr (&Sre_search_forward);
3436 defsubr (&Sre_search_backward);
3437 defsubr (&Sposix_search_forward);
3438 defsubr (&Sposix_search_backward);
3439 defsubr (&Sreplace_match);
3440 defsubr (&Smatch_beginning);
3441 defsubr (&Smatch_end);
3442 defsubr (&Smatch_data);
3443 defsubr (&Sset_match_data);
3444 defsubr (&Sregexp_quote);
3445 defsubr (&Snewline_cache_check);