; Merge from origin/emacs-25
[emacs.git] / src / search.c
blob33cb02aa7af5361acba86f4008a068ea69f1ee6d
1 /* String search routines for GNU Emacs.
3 Copyright (C) 1985-1987, 1993-1994, 1997-1999, 2001-2017 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 <http://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 unsigned char str[MAX_MULTIBYTE_LENGTH];
1808 int cblen = CHAR_STRING (char_base, str);
1810 translate_prev_byte1 = str[cblen - 2];
1811 if (cblen > 2)
1813 translate_prev_byte2 = str[cblen - 3];
1814 if (cblen > 3)
1815 translate_prev_byte3 = str[cblen - 4];
1819 i = 0;
1820 while (i != dirlen)
1822 unsigned char *ptr = base_pat + i;
1823 i += direction;
1824 if (! NILP (trt))
1826 /* If the byte currently looking at is the last of a
1827 character to check case-equivalents, set CH to that
1828 character. An ASCII character and a non-ASCII character
1829 matching with CHAR_BASE are to be checked. */
1830 int ch = -1;
1832 if (ASCII_CHAR_P (*ptr) || ! multibyte)
1833 ch = *ptr;
1834 else if (char_base
1835 && ((pat_end - ptr) == 1 || CHAR_HEAD_P (ptr[1])))
1837 unsigned char *charstart = ptr - 1;
1839 while (! (CHAR_HEAD_P (*charstart)))
1840 charstart--;
1841 ch = STRING_CHAR (charstart);
1842 if (char_base != (ch & ~0x3F))
1843 ch = -1;
1846 if (ch >= 0200 && multibyte)
1847 j = (ch & 0x3F) | 0200;
1848 else
1849 j = *ptr;
1851 if (i == dirlen)
1852 stride_for_teases = BM_tab[j];
1854 BM_tab[j] = dirlen - i;
1855 /* A translation table is accompanied by its inverse -- see
1856 comment following downcase_table for details. */
1857 if (ch >= 0)
1859 int starting_ch = ch;
1860 int starting_j = j;
1862 while (1)
1864 TRANSLATE (ch, inverse_trt, ch);
1865 if (ch >= 0200 && multibyte)
1866 j = (ch & 0x3F) | 0200;
1867 else
1868 j = ch;
1870 /* For all the characters that map into CH,
1871 set up simple_translate to map the last byte
1872 into STARTING_J. */
1873 simple_translate[j] = starting_j;
1874 if (ch == starting_ch)
1875 break;
1876 BM_tab[j] = dirlen - i;
1880 else
1882 j = *ptr;
1884 if (i == dirlen)
1885 stride_for_teases = BM_tab[j];
1886 BM_tab[j] = dirlen - i;
1888 /* stride_for_teases tells how much to stride if we get a
1889 match on the far character but are subsequently
1890 disappointed, by recording what the stride would have been
1891 for that character if the last character had been
1892 different. */
1894 pos_byte += dirlen - ((direction > 0) ? direction : 0);
1895 /* loop invariant - POS_BYTE points at where last char (first
1896 char if reverse) of pattern would align in a possible match. */
1897 while (n != 0)
1899 ptrdiff_t tail_end;
1900 unsigned char *tail_end_ptr;
1902 /* It's been reported that some (broken) compiler thinks that
1903 Boolean expressions in an arithmetic context are unsigned.
1904 Using an explicit ?1:0 prevents this. */
1905 if ((lim_byte - pos_byte - ((direction > 0) ? 1 : 0)) * direction
1906 < 0)
1907 return (n * (0 - direction));
1908 /* First we do the part we can by pointers (maybe nothing) */
1909 maybe_quit ();
1910 pat = base_pat;
1911 limit = pos_byte - dirlen + direction;
1912 if (direction > 0)
1914 limit = BUFFER_CEILING_OF (limit);
1915 /* LIMIT is now the last (not beyond-last!) value POS_BYTE
1916 can take on without hitting edge of buffer or the gap. */
1917 limit = min (limit, pos_byte + 20000);
1918 limit = min (limit, lim_byte - 1);
1920 else
1922 limit = BUFFER_FLOOR_OF (limit);
1923 /* LIMIT is now the last (not beyond-last!) value POS_BYTE
1924 can take on without hitting edge of buffer or the gap. */
1925 limit = max (limit, pos_byte - 20000);
1926 limit = max (limit, lim_byte);
1928 tail_end = BUFFER_CEILING_OF (pos_byte) + 1;
1929 tail_end_ptr = BYTE_POS_ADDR (tail_end);
1931 if ((limit - pos_byte) * direction > 20)
1933 unsigned char *p2;
1935 p_limit = BYTE_POS_ADDR (limit);
1936 p2 = (cursor = BYTE_POS_ADDR (pos_byte));
1937 /* In this loop, pos + cursor - p2 is the surrogate for pos. */
1938 while (1) /* use one cursor setting as long as i can */
1940 if (direction > 0) /* worth duplicating */
1942 while (cursor <= p_limit)
1944 if (BM_tab[*cursor] == 0)
1945 goto hit;
1946 cursor += BM_tab[*cursor];
1949 else
1951 while (cursor >= p_limit)
1953 if (BM_tab[*cursor] == 0)
1954 goto hit;
1955 cursor += BM_tab[*cursor];
1958 /* If you are here, cursor is beyond the end of the
1959 searched region. You fail to match within the
1960 permitted region and would otherwise try a character
1961 beyond that region. */
1962 break;
1964 hit:
1965 i = dirlen - direction;
1966 if (! NILP (trt))
1968 while ((i -= direction) + direction != 0)
1970 int ch;
1971 cursor -= direction;
1972 /* Translate only the last byte of a character. */
1973 if (! multibyte
1974 || ((cursor == tail_end_ptr
1975 || CHAR_HEAD_P (cursor[1]))
1976 && (CHAR_HEAD_P (cursor[0])
1977 /* Check if this is the last byte of
1978 a translatable character. */
1979 || (translate_prev_byte1 == cursor[-1]
1980 && (CHAR_HEAD_P (translate_prev_byte1)
1981 || (translate_prev_byte2 == cursor[-2]
1982 && (CHAR_HEAD_P (translate_prev_byte2)
1983 || (translate_prev_byte3 == cursor[-3]))))))))
1984 ch = simple_translate[*cursor];
1985 else
1986 ch = *cursor;
1987 if (pat[i] != ch)
1988 break;
1991 else
1993 while ((i -= direction) + direction != 0)
1995 cursor -= direction;
1996 if (pat[i] != *cursor)
1997 break;
2000 cursor += dirlen - i - direction; /* fix cursor */
2001 if (i + direction == 0)
2003 ptrdiff_t position, start, end;
2004 #ifdef REL_ALLOC
2005 ptrdiff_t cursor_off;
2006 #endif
2008 cursor -= direction;
2010 position = pos_byte + cursor - p2 + ((direction > 0)
2011 ? 1 - len_byte : 0);
2012 #ifdef REL_ALLOC
2013 /* set_search_regs might call malloc, which could
2014 cause ralloc.c relocate buffer text. We need to
2015 update pointers into buffer text due to that. */
2016 cursor_off = cursor - p2;
2017 #endif
2018 set_search_regs (position, len_byte);
2019 #ifdef REL_ALLOC
2020 p_limit = BYTE_POS_ADDR (limit);
2021 p2 = BYTE_POS_ADDR (pos_byte);
2022 cursor = p2 + cursor_off;
2023 #endif
2025 if (NILP (Vinhibit_changing_match_data))
2027 start = search_regs.start[0];
2028 end = search_regs.end[0];
2030 else
2031 /* If Vinhibit_changing_match_data is non-nil,
2032 search_regs will not be changed. So let's
2033 compute start and end here. */
2035 start = BYTE_TO_CHAR (position);
2036 end = BYTE_TO_CHAR (position + len_byte);
2039 if ((n -= direction) != 0)
2040 cursor += dirlen; /* to resume search */
2041 else
2042 return direction > 0 ? end : start;
2044 else
2045 cursor += stride_for_teases; /* <sigh> we lose - */
2047 pos_byte += cursor - p2;
2049 else
2050 /* Now we'll pick up a clump that has to be done the hard
2051 way because it covers a discontinuity. */
2053 limit = ((direction > 0)
2054 ? BUFFER_CEILING_OF (pos_byte - dirlen + 1)
2055 : BUFFER_FLOOR_OF (pos_byte - dirlen - 1));
2056 limit = ((direction > 0)
2057 ? min (limit + len_byte, lim_byte - 1)
2058 : max (limit - len_byte, lim_byte));
2059 /* LIMIT is now the last value POS_BYTE can have
2060 and still be valid for a possible match. */
2061 while (1)
2063 /* This loop can be coded for space rather than
2064 speed because it will usually run only once.
2065 (the reach is at most len + 21, and typically
2066 does not exceed len). */
2067 while ((limit - pos_byte) * direction >= 0)
2069 int ch = FETCH_BYTE (pos_byte);
2070 if (BM_tab[ch] == 0)
2071 goto hit2;
2072 pos_byte += BM_tab[ch];
2074 break; /* ran off the end */
2076 hit2:
2077 /* Found what might be a match. */
2078 i = dirlen - direction;
2079 while ((i -= direction) + direction != 0)
2081 int ch;
2082 unsigned char *ptr;
2083 pos_byte -= direction;
2084 ptr = BYTE_POS_ADDR (pos_byte);
2085 /* Translate only the last byte of a character. */
2086 if (! multibyte
2087 || ((ptr == tail_end_ptr
2088 || CHAR_HEAD_P (ptr[1]))
2089 && (CHAR_HEAD_P (ptr[0])
2090 /* Check if this is the last byte of a
2091 translatable character. */
2092 || (translate_prev_byte1 == ptr[-1]
2093 && (CHAR_HEAD_P (translate_prev_byte1)
2094 || (translate_prev_byte2 == ptr[-2]
2095 && (CHAR_HEAD_P (translate_prev_byte2)
2096 || translate_prev_byte3 == ptr[-3])))))))
2097 ch = simple_translate[*ptr];
2098 else
2099 ch = *ptr;
2100 if (pat[i] != ch)
2101 break;
2103 /* Above loop has moved POS_BYTE part or all the way
2104 back to the first pos (last pos if reverse).
2105 Set it once again at the last (first if reverse) char. */
2106 pos_byte += dirlen - i - direction;
2107 if (i + direction == 0)
2109 ptrdiff_t position, start, end;
2110 pos_byte -= direction;
2112 position = pos_byte + ((direction > 0) ? 1 - len_byte : 0);
2113 set_search_regs (position, len_byte);
2115 if (NILP (Vinhibit_changing_match_data))
2117 start = search_regs.start[0];
2118 end = search_regs.end[0];
2120 else
2121 /* If Vinhibit_changing_match_data is non-nil,
2122 search_regs will not be changed. So let's
2123 compute start and end here. */
2125 start = BYTE_TO_CHAR (position);
2126 end = BYTE_TO_CHAR (position + len_byte);
2129 if ((n -= direction) != 0)
2130 pos_byte += dirlen; /* to resume search */
2131 else
2132 return direction > 0 ? end : start;
2134 else
2135 pos_byte += stride_for_teases;
2138 /* We have done one clump. Can we continue? */
2139 if ((lim_byte - pos_byte) * direction < 0)
2140 return ((0 - n) * direction);
2142 return BYTE_TO_CHAR (pos_byte);
2145 /* Record beginning BEG_BYTE and end BEG_BYTE + NBYTES
2146 for the overall match just found in the current buffer.
2147 Also clear out the match data for registers 1 and up. */
2149 static void
2150 set_search_regs (ptrdiff_t beg_byte, ptrdiff_t nbytes)
2152 ptrdiff_t i;
2154 if (!NILP (Vinhibit_changing_match_data))
2155 return;
2157 /* Make sure we have registers in which to store
2158 the match position. */
2159 if (search_regs.num_regs == 0)
2161 search_regs.start = xmalloc (2 * sizeof (regoff_t));
2162 search_regs.end = xmalloc (2 * sizeof (regoff_t));
2163 search_regs.num_regs = 2;
2166 /* Clear out the other registers. */
2167 for (i = 1; i < search_regs.num_regs; i++)
2169 search_regs.start[i] = -1;
2170 search_regs.end[i] = -1;
2173 search_regs.start[0] = BYTE_TO_CHAR (beg_byte);
2174 search_regs.end[0] = BYTE_TO_CHAR (beg_byte + nbytes);
2175 XSETBUFFER (last_thing_searched, current_buffer);
2178 DEFUN ("search-backward", Fsearch_backward, Ssearch_backward, 1, 4,
2179 "MSearch backward: ",
2180 doc: /* Search backward from point for STRING.
2181 Set point to the beginning of the occurrence found, and return point.
2182 An optional second argument bounds the search; it is a buffer position.
2183 The match found must not begin before that position. A value of nil
2184 means search to the beginning of the accessible portion of the buffer.
2185 Optional third argument, if t, means if fail just return nil (no error).
2186 If not nil and not t, position at limit of search and return nil.
2187 Optional fourth argument COUNT, if a positive number, means to search
2188 for COUNT successive occurrences. If COUNT is negative, search
2189 forward, instead of backward, for -COUNT occurrences. A value of
2190 nil means the same as 1.
2191 With COUNT positive, the match found is the COUNTth to last one (or
2192 last, if COUNT is 1 or nil) in the buffer located entirely before
2193 the origin of the search; correspondingly with COUNT negative.
2195 Search case-sensitivity is determined by the value of the variable
2196 `case-fold-search', which see.
2198 See also the functions `match-beginning', `match-end' and `replace-match'. */)
2199 (Lisp_Object string, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
2201 return search_command (string, bound, noerror, count, -1, 0, 0);
2204 DEFUN ("search-forward", Fsearch_forward, Ssearch_forward, 1, 4, "MSearch: ",
2205 doc: /* Search forward from point for STRING.
2206 Set point to the end of the occurrence found, and return point.
2207 An optional second argument bounds the search; it is a buffer position.
2208 The match found must not end after that position. A value of nil
2209 means search to the end of the accessible portion of the buffer.
2210 Optional third argument, if t, means if fail just return nil (no error).
2211 If not nil and not t, move to limit of search and return nil.
2212 Optional fourth argument COUNT, if a positive number, means to search
2213 for COUNT successive occurrences. If COUNT is negative, search
2214 backward, instead of forward, for -COUNT occurrences. A value of
2215 nil means the same as 1.
2216 With COUNT positive, the match found is the COUNTth one (or first,
2217 if COUNT is 1 or nil) in the buffer located entirely after the
2218 origin of the search; correspondingly with COUNT negative.
2220 Search case-sensitivity is determined by the value of the variable
2221 `case-fold-search', which see.
2223 See also the functions `match-beginning', `match-end' and `replace-match'. */)
2224 (Lisp_Object string, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
2226 return search_command (string, bound, noerror, count, 1, 0, 0);
2229 DEFUN ("re-search-backward", Fre_search_backward, Sre_search_backward, 1, 4,
2230 "sRE search backward: ",
2231 doc: /* Search backward from point for match for regular expression REGEXP.
2232 Set point to the beginning of the occurrence found, and return point.
2233 An optional second argument bounds the search; it is a buffer position.
2234 The match found must not begin before that position. A value of nil
2235 means search to the beginning of the accessible portion of the buffer.
2236 Optional third argument, if t, means if fail just return nil (no error).
2237 If not nil and not t, position at limit of search and return nil.
2238 Optional fourth argument COUNT, if a positive number, means to search
2239 for COUNT successive occurrences. If COUNT is negative, search
2240 forward, instead of backward, for -COUNT occurrences. A value of
2241 nil means the same as 1.
2242 With COUNT positive, the match found is the COUNTth to last one (or
2243 last, if COUNT is 1 or nil) in the buffer located entirely before
2244 the origin of the search; correspondingly with COUNT negative.
2246 Search case-sensitivity is determined by the value of the variable
2247 `case-fold-search', which see.
2249 See also the functions `match-beginning', `match-end', `match-string',
2250 and `replace-match'. */)
2251 (Lisp_Object regexp, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
2253 return search_command (regexp, bound, noerror, count, -1, 1, 0);
2256 DEFUN ("re-search-forward", Fre_search_forward, Sre_search_forward, 1, 4,
2257 "sRE search: ",
2258 doc: /* Search forward from point for regular expression REGEXP.
2259 Set point to the end of the occurrence found, and return point.
2260 An optional second argument bounds the search; it is a buffer position.
2261 The match found must not end after that position. A value of nil
2262 means search to the end of the accessible portion of the buffer.
2263 Optional third argument, if t, means if fail just return nil (no error).
2264 If not nil and not t, move to limit of search and return nil.
2265 Optional fourth argument COUNT, if a positive number, means to search
2266 for COUNT successive occurrences. If COUNT is negative, search
2267 backward, instead of forward, for -COUNT occurrences. A value of
2268 nil means the same as 1.
2269 With COUNT positive, the match found is the COUNTth one (or first,
2270 if COUNT is 1 or nil) in the buffer located entirely after the
2271 origin of the search; correspondingly with COUNT negative.
2273 Search case-sensitivity is determined by the value of the variable
2274 `case-fold-search', which see.
2276 See also the functions `match-beginning', `match-end', `match-string',
2277 and `replace-match'. */)
2278 (Lisp_Object regexp, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
2280 return search_command (regexp, bound, noerror, count, 1, 1, 0);
2283 DEFUN ("posix-search-backward", Fposix_search_backward, Sposix_search_backward, 1, 4,
2284 "sPosix search backward: ",
2285 doc: /* Search backward from point for match for regular expression REGEXP.
2286 Find the longest match in accord with Posix regular expression rules.
2287 Set point to the beginning of the occurrence found, and return point.
2288 An optional second argument bounds the search; it is a buffer position.
2289 The match found must not begin before that position. A value of nil
2290 means search to the beginning of the accessible portion of the buffer.
2291 Optional third argument, if t, means if fail just return nil (no error).
2292 If not nil and not t, position at limit of search and return nil.
2293 Optional fourth argument COUNT, if a positive number, means to search
2294 for COUNT successive occurrences. If COUNT is negative, search
2295 forward, instead of backward, for -COUNT occurrences. A value of
2296 nil means the same as 1.
2297 With COUNT positive, the match found is the COUNTth to last one (or
2298 last, if COUNT is 1 or nil) in the buffer located entirely before
2299 the origin of the search; correspondingly with COUNT negative.
2301 Search case-sensitivity is determined by the value of the variable
2302 `case-fold-search', which see.
2304 See also the functions `match-beginning', `match-end', `match-string',
2305 and `replace-match'. */)
2306 (Lisp_Object regexp, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
2308 return search_command (regexp, bound, noerror, count, -1, 1, 1);
2311 DEFUN ("posix-search-forward", Fposix_search_forward, Sposix_search_forward, 1, 4,
2312 "sPosix search: ",
2313 doc: /* Search forward from point for regular expression REGEXP.
2314 Find the longest match in accord with Posix regular expression rules.
2315 Set point to the end of the occurrence found, and return point.
2316 An optional second argument bounds the search; it is a buffer position.
2317 The match found must not end after that position. A value of nil
2318 means search to the end of the accessible portion of the buffer.
2319 Optional third argument, if t, means if fail just return nil (no error).
2320 If not nil and not t, move to limit of search and return nil.
2321 Optional fourth argument COUNT, if a positive number, means to search
2322 for COUNT successive occurrences. If COUNT is negative, search
2323 backward, instead of forward, for -COUNT occurrences. A value of
2324 nil means the same as 1.
2325 With COUNT positive, the match found is the COUNTth one (or first,
2326 if COUNT is 1 or nil) in the buffer located entirely after the
2327 origin of the search; correspondingly with COUNT negative.
2329 Search case-sensitivity is determined by the value of the variable
2330 `case-fold-search', which see.
2332 See also the functions `match-beginning', `match-end', `match-string',
2333 and `replace-match'. */)
2334 (Lisp_Object regexp, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
2336 return search_command (regexp, bound, noerror, count, 1, 1, 1);
2339 DEFUN ("replace-match", Freplace_match, Sreplace_match, 1, 5, 0,
2340 doc: /* Replace text matched by last search with NEWTEXT.
2341 Leave point at the end of the replacement text.
2343 If optional second arg FIXEDCASE is non-nil, do not alter the case of
2344 the replacement text. Otherwise, maybe capitalize the whole text, or
2345 maybe just word initials, based on the replaced text. If the replaced
2346 text has only capital letters and has at least one multiletter word,
2347 convert NEWTEXT to all caps. Otherwise if all words are capitalized
2348 in the replaced text, capitalize each word in NEWTEXT.
2350 If optional third arg LITERAL is non-nil, insert NEWTEXT literally.
2351 Otherwise treat `\\' as special:
2352 `\\&' in NEWTEXT means substitute original matched text.
2353 `\\N' means substitute what matched the Nth `\\(...\\)'.
2354 If Nth parens didn't match, substitute nothing.
2355 `\\\\' means insert one `\\'.
2356 `\\?' is treated literally
2357 (for compatibility with `query-replace-regexp').
2358 Any other character following `\\' signals an error.
2359 Case conversion does not apply to these substitutions.
2361 If optional fourth argument STRING is non-nil, it should be a string
2362 to act on; this should be the string on which the previous match was
2363 done via `string-match'. In this case, `replace-match' creates and
2364 returns a new string, made by copying STRING and replacing the part of
2365 STRING that was matched (the original STRING itself is not altered).
2367 The optional fifth argument SUBEXP specifies a subexpression;
2368 it says to replace just that subexpression with NEWTEXT,
2369 rather than replacing the entire matched text.
2370 This is, in a vague sense, the inverse of using `\\N' in NEWTEXT;
2371 `\\N' copies subexp N into NEWTEXT, but using N as SUBEXP puts
2372 NEWTEXT in place of subexp N.
2373 This is useful only after a regular expression search or match,
2374 since only regular expressions have distinguished subexpressions. */)
2375 (Lisp_Object newtext, Lisp_Object fixedcase, Lisp_Object literal, Lisp_Object string, Lisp_Object subexp)
2377 enum { nochange, all_caps, cap_initial } case_action;
2378 ptrdiff_t pos, pos_byte;
2379 bool some_multiletter_word;
2380 bool some_lowercase;
2381 bool some_uppercase;
2382 bool some_nonuppercase_initial;
2383 int c, prevc;
2384 ptrdiff_t sub;
2385 ptrdiff_t opoint, newpoint;
2387 CHECK_STRING (newtext);
2389 if (! NILP (string))
2390 CHECK_STRING (string);
2392 case_action = nochange; /* We tried an initialization */
2393 /* but some C compilers blew it */
2395 if (search_regs.num_regs <= 0)
2396 error ("`replace-match' called before any match found");
2398 if (NILP (subexp))
2399 sub = 0;
2400 else
2402 CHECK_NUMBER (subexp);
2403 if (! (0 <= XINT (subexp) && XINT (subexp) < search_regs.num_regs))
2404 args_out_of_range (subexp, make_number (search_regs.num_regs));
2405 sub = XINT (subexp);
2408 if (NILP (string))
2410 if (search_regs.start[sub] < BEGV
2411 || search_regs.start[sub] > search_regs.end[sub]
2412 || search_regs.end[sub] > ZV)
2413 args_out_of_range (make_number (search_regs.start[sub]),
2414 make_number (search_regs.end[sub]));
2416 else
2418 if (search_regs.start[sub] < 0
2419 || search_regs.start[sub] > search_regs.end[sub]
2420 || search_regs.end[sub] > SCHARS (string))
2421 args_out_of_range (make_number (search_regs.start[sub]),
2422 make_number (search_regs.end[sub]));
2425 if (NILP (fixedcase))
2427 /* Decide how to casify by examining the matched text. */
2428 ptrdiff_t last;
2430 pos = search_regs.start[sub];
2431 last = search_regs.end[sub];
2433 if (NILP (string))
2434 pos_byte = CHAR_TO_BYTE (pos);
2435 else
2436 pos_byte = string_char_to_byte (string, pos);
2438 prevc = '\n';
2439 case_action = all_caps;
2441 /* some_multiletter_word is set nonzero if any original word
2442 is more than one letter long. */
2443 some_multiletter_word = 0;
2444 some_lowercase = 0;
2445 some_nonuppercase_initial = 0;
2446 some_uppercase = 0;
2448 while (pos < last)
2450 if (NILP (string))
2452 c = FETCH_CHAR_AS_MULTIBYTE (pos_byte);
2453 INC_BOTH (pos, pos_byte);
2455 else
2456 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c, string, pos, pos_byte);
2458 if (lowercasep (c))
2460 /* Cannot be all caps if any original char is lower case */
2462 some_lowercase = 1;
2463 if (SYNTAX (prevc) != Sword)
2464 some_nonuppercase_initial = 1;
2465 else
2466 some_multiletter_word = 1;
2468 else if (uppercasep (c))
2470 some_uppercase = 1;
2471 if (SYNTAX (prevc) != Sword)
2473 else
2474 some_multiletter_word = 1;
2476 else
2478 /* If the initial is a caseless word constituent,
2479 treat that like a lowercase initial. */
2480 if (SYNTAX (prevc) != Sword)
2481 some_nonuppercase_initial = 1;
2484 prevc = c;
2487 /* Convert to all caps if the old text is all caps
2488 and has at least one multiletter word. */
2489 if (! some_lowercase && some_multiletter_word)
2490 case_action = all_caps;
2491 /* Capitalize each word, if the old text has all capitalized words. */
2492 else if (!some_nonuppercase_initial && some_multiletter_word)
2493 case_action = cap_initial;
2494 else if (!some_nonuppercase_initial && some_uppercase)
2495 /* Should x -> yz, operating on X, give Yz or YZ?
2496 We'll assume the latter. */
2497 case_action = all_caps;
2498 else
2499 case_action = nochange;
2502 /* Do replacement in a string. */
2503 if (!NILP (string))
2505 Lisp_Object before, after;
2507 before = Fsubstring (string, make_number (0),
2508 make_number (search_regs.start[sub]));
2509 after = Fsubstring (string, make_number (search_regs.end[sub]), Qnil);
2511 /* Substitute parts of the match into NEWTEXT
2512 if desired. */
2513 if (NILP (literal))
2515 ptrdiff_t lastpos = 0;
2516 ptrdiff_t lastpos_byte = 0;
2517 /* We build up the substituted string in ACCUM. */
2518 Lisp_Object accum;
2519 Lisp_Object middle;
2520 ptrdiff_t length = SBYTES (newtext);
2522 accum = Qnil;
2524 for (pos_byte = 0, pos = 0; pos_byte < length;)
2526 ptrdiff_t substart = -1;
2527 ptrdiff_t subend = 0;
2528 bool delbackslash = 0;
2530 FETCH_STRING_CHAR_ADVANCE (c, newtext, pos, pos_byte);
2532 if (c == '\\')
2534 FETCH_STRING_CHAR_ADVANCE (c, newtext, pos, pos_byte);
2536 if (c == '&')
2538 substart = search_regs.start[sub];
2539 subend = search_regs.end[sub];
2541 else if (c >= '1' && c <= '9')
2543 if (c - '0' < search_regs.num_regs
2544 && search_regs.start[c - '0'] >= 0)
2546 substart = search_regs.start[c - '0'];
2547 subend = search_regs.end[c - '0'];
2549 else
2551 /* If that subexp did not match,
2552 replace \\N with nothing. */
2553 substart = 0;
2554 subend = 0;
2557 else if (c == '\\')
2558 delbackslash = 1;
2559 else if (c != '?')
2560 error ("Invalid use of `\\' in replacement text");
2562 if (substart >= 0)
2564 if (pos - 2 != lastpos)
2565 middle = substring_both (newtext, lastpos,
2566 lastpos_byte,
2567 pos - 2, pos_byte - 2);
2568 else
2569 middle = Qnil;
2570 accum = concat3 (accum, middle,
2571 Fsubstring (string,
2572 make_number (substart),
2573 make_number (subend)));
2574 lastpos = pos;
2575 lastpos_byte = pos_byte;
2577 else if (delbackslash)
2579 middle = substring_both (newtext, lastpos,
2580 lastpos_byte,
2581 pos - 1, pos_byte - 1);
2583 accum = concat2 (accum, middle);
2584 lastpos = pos;
2585 lastpos_byte = pos_byte;
2589 if (pos != lastpos)
2590 middle = substring_both (newtext, lastpos,
2591 lastpos_byte,
2592 pos, pos_byte);
2593 else
2594 middle = Qnil;
2596 newtext = concat2 (accum, middle);
2599 /* Do case substitution in NEWTEXT if desired. */
2600 if (case_action == all_caps)
2601 newtext = Fupcase (newtext);
2602 else if (case_action == cap_initial)
2603 newtext = Fupcase_initials (newtext);
2605 return concat3 (before, newtext, after);
2608 /* Record point, then move (quietly) to the start of the match. */
2609 if (PT >= search_regs.end[sub])
2610 opoint = PT - ZV;
2611 else if (PT > search_regs.start[sub])
2612 opoint = search_regs.end[sub] - ZV;
2613 else
2614 opoint = PT;
2616 /* If we want non-literal replacement,
2617 perform substitution on the replacement string. */
2618 if (NILP (literal))
2620 ptrdiff_t length = SBYTES (newtext);
2621 unsigned char *substed;
2622 ptrdiff_t substed_alloc_size, substed_len;
2623 bool buf_multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
2624 bool str_multibyte = STRING_MULTIBYTE (newtext);
2625 bool really_changed = 0;
2627 substed_alloc_size = (length <= (STRING_BYTES_BOUND - 100) / 2
2628 ? length * 2 + 100
2629 : STRING_BYTES_BOUND);
2630 substed = xmalloc (substed_alloc_size);
2631 substed_len = 0;
2633 /* Go thru NEWTEXT, producing the actual text to insert in
2634 SUBSTED while adjusting multibyteness to that of the current
2635 buffer. */
2637 for (pos_byte = 0, pos = 0; pos_byte < length;)
2639 unsigned char str[MAX_MULTIBYTE_LENGTH];
2640 const unsigned char *add_stuff = NULL;
2641 ptrdiff_t add_len = 0;
2642 ptrdiff_t idx = -1;
2643 ptrdiff_t begbyte;
2645 if (str_multibyte)
2647 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, newtext, pos, pos_byte);
2648 if (!buf_multibyte)
2649 c = CHAR_TO_BYTE8 (c);
2651 else
2653 /* Note that we don't have to increment POS. */
2654 c = SREF (newtext, pos_byte++);
2655 if (buf_multibyte)
2656 MAKE_CHAR_MULTIBYTE (c);
2659 /* Either set ADD_STUFF and ADD_LEN to the text to put in SUBSTED,
2660 or set IDX to a match index, which means put that part
2661 of the buffer text into SUBSTED. */
2663 if (c == '\\')
2665 really_changed = 1;
2667 if (str_multibyte)
2669 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, newtext,
2670 pos, pos_byte);
2671 if (!buf_multibyte && !ASCII_CHAR_P (c))
2672 c = CHAR_TO_BYTE8 (c);
2674 else
2676 c = SREF (newtext, pos_byte++);
2677 if (buf_multibyte)
2678 MAKE_CHAR_MULTIBYTE (c);
2681 if (c == '&')
2682 idx = sub;
2683 else if (c >= '1' && c <= '9' && c - '0' < search_regs.num_regs)
2685 if (search_regs.start[c - '0'] >= 1)
2686 idx = c - '0';
2688 else if (c == '\\')
2689 add_len = 1, add_stuff = (unsigned char *) "\\";
2690 else
2692 xfree (substed);
2693 error ("Invalid use of `\\' in replacement text");
2696 else
2698 add_len = CHAR_STRING (c, str);
2699 add_stuff = str;
2702 /* If we want to copy part of a previous match,
2703 set up ADD_STUFF and ADD_LEN to point to it. */
2704 if (idx >= 0)
2706 begbyte = CHAR_TO_BYTE (search_regs.start[idx]);
2707 add_len = CHAR_TO_BYTE (search_regs.end[idx]) - begbyte;
2708 if (search_regs.start[idx] < GPT && GPT < search_regs.end[idx])
2709 move_gap_both (search_regs.start[idx], begbyte);
2712 /* Now the stuff we want to add to SUBSTED
2713 is invariably ADD_LEN bytes starting at ADD_STUFF. */
2715 /* Make sure SUBSTED is big enough. */
2716 if (substed_alloc_size - substed_len < add_len)
2717 substed =
2718 xpalloc (substed, &substed_alloc_size,
2719 add_len - (substed_alloc_size - substed_len),
2720 STRING_BYTES_BOUND, 1);
2722 /* We compute this after the call to xpalloc, because that
2723 could cause buffer text be relocated when ralloc.c is used. */
2724 if (idx >= 0)
2725 add_stuff = BYTE_POS_ADDR (begbyte);
2727 /* Now add to the end of SUBSTED. */
2728 if (add_stuff)
2730 memcpy (substed + substed_len, add_stuff, add_len);
2731 substed_len += add_len;
2735 if (really_changed)
2736 newtext = make_specified_string ((const char *) substed, -1,
2737 substed_len, buf_multibyte);
2738 xfree (substed);
2741 /* The functions below modify the buffer, so they could trigger
2742 various modification hooks (see signal_before_change and
2743 signal_after_change). If these hooks clobber the match data we
2744 error out since otherwise this will result in confusing bugs. */
2745 ptrdiff_t sub_start = search_regs.start[sub];
2746 ptrdiff_t sub_end = search_regs.end[sub];
2747 unsigned num_regs = search_regs.num_regs;
2748 newpoint = search_regs.start[sub] + SCHARS (newtext);
2750 /* Replace the old text with the new in the cleanest possible way. */
2751 replace_range (search_regs.start[sub], search_regs.end[sub],
2752 newtext, 1, 0, 1, 1);
2753 /* Update saved data to match adjustment made by replace_range. */
2755 ptrdiff_t change = newpoint - sub_end;
2756 if (sub_start >= sub_end)
2757 sub_start += change;
2758 sub_end += change;
2761 if (case_action == all_caps)
2762 Fupcase_region (make_number (search_regs.start[sub]),
2763 make_number (newpoint),
2764 Qnil);
2765 else if (case_action == cap_initial)
2766 Fupcase_initials_region (make_number (search_regs.start[sub]),
2767 make_number (newpoint));
2769 if (search_regs.start[sub] != sub_start
2770 || search_regs.end[sub] != sub_end
2771 || search_regs.num_regs != num_regs)
2772 error ("Match data clobbered by buffer modification hooks");
2774 /* Put point back where it was in the text. */
2775 if (opoint <= 0)
2776 TEMP_SET_PT (opoint + ZV);
2777 else
2778 TEMP_SET_PT (opoint);
2780 /* Now move point "officially" to the start of the inserted replacement. */
2781 move_if_not_intangible (newpoint);
2783 return Qnil;
2786 static Lisp_Object
2787 match_limit (Lisp_Object num, bool beginningp)
2789 EMACS_INT n;
2791 CHECK_NUMBER (num);
2792 n = XINT (num);
2793 if (n < 0)
2794 args_out_of_range (num, make_number (0));
2795 if (search_regs.num_regs <= 0)
2796 error ("No match data, because no search succeeded");
2797 if (n >= search_regs.num_regs
2798 || search_regs.start[n] < 0)
2799 return Qnil;
2800 return (make_number ((beginningp) ? search_regs.start[n]
2801 : search_regs.end[n]));
2804 DEFUN ("match-beginning", Fmatch_beginning, Smatch_beginning, 1, 1, 0,
2805 doc: /* Return position of start of text matched by last search.
2806 SUBEXP, a number, specifies which parenthesized expression in the last
2807 regexp.
2808 Value is nil if SUBEXPth pair didn't match, or there were less than
2809 SUBEXP pairs.
2810 Zero means the entire text matched by the whole regexp or whole string.
2812 Return value is undefined if the last search failed. */)
2813 (Lisp_Object subexp)
2815 return match_limit (subexp, 1);
2818 DEFUN ("match-end", Fmatch_end, Smatch_end, 1, 1, 0,
2819 doc: /* Return position of end of text matched by last search.
2820 SUBEXP, a number, specifies which parenthesized expression in the last
2821 regexp.
2822 Value is nil if SUBEXPth pair didn't match, or there were less than
2823 SUBEXP pairs.
2824 Zero means the entire text matched by the whole regexp or whole string.
2826 Return value is undefined if the last search failed. */)
2827 (Lisp_Object subexp)
2829 return match_limit (subexp, 0);
2832 DEFUN ("match-data", Fmatch_data, Smatch_data, 0, 3, 0,
2833 doc: /* Return a list describing what the last search matched.
2834 Element 2N is `(match-beginning N)'; element 2N + 1 is `(match-end N)'.
2835 All the elements are markers or nil (nil if the Nth pair didn't match)
2836 if the last match was on a buffer; integers or nil if a string was matched.
2837 Use `set-match-data' to reinstate the data in this list.
2839 If INTEGERS (the optional first argument) is non-nil, always use
2840 integers (rather than markers) to represent buffer positions. In
2841 this case, and if the last match was in a buffer, the buffer will get
2842 stored as one additional element at the end of the list.
2844 If REUSE is a list, reuse it as part of the value. If REUSE is long
2845 enough to hold all the values, and if INTEGERS is non-nil, no consing
2846 is done.
2848 If optional third arg RESEAT is non-nil, any previous markers on the
2849 REUSE list will be modified to point to nowhere.
2851 Return value is undefined if the last search failed. */)
2852 (Lisp_Object integers, Lisp_Object reuse, Lisp_Object reseat)
2854 Lisp_Object tail, prev;
2855 Lisp_Object *data;
2856 ptrdiff_t i, len;
2858 if (!NILP (reseat))
2859 for (tail = reuse; CONSP (tail); tail = XCDR (tail))
2860 if (MARKERP (XCAR (tail)))
2862 unchain_marker (XMARKER (XCAR (tail)));
2863 XSETCAR (tail, Qnil);
2866 if (NILP (last_thing_searched))
2867 return Qnil;
2869 prev = Qnil;
2871 USE_SAFE_ALLOCA;
2872 SAFE_NALLOCA (data, 1, 2 * search_regs.num_regs + 1);
2874 len = 0;
2875 for (i = 0; i < search_regs.num_regs; i++)
2877 ptrdiff_t start = search_regs.start[i];
2878 if (start >= 0)
2880 if (EQ (last_thing_searched, Qt)
2881 || ! NILP (integers))
2883 XSETFASTINT (data[2 * i], start);
2884 XSETFASTINT (data[2 * i + 1], search_regs.end[i]);
2886 else if (BUFFERP (last_thing_searched))
2888 data[2 * i] = Fmake_marker ();
2889 Fset_marker (data[2 * i],
2890 make_number (start),
2891 last_thing_searched);
2892 data[2 * i + 1] = Fmake_marker ();
2893 Fset_marker (data[2 * i + 1],
2894 make_number (search_regs.end[i]),
2895 last_thing_searched);
2897 else
2898 /* last_thing_searched must always be Qt, a buffer, or Qnil. */
2899 emacs_abort ();
2901 len = 2 * i + 2;
2903 else
2904 data[2 * i] = data[2 * i + 1] = Qnil;
2907 if (BUFFERP (last_thing_searched) && !NILP (integers))
2909 data[len] = last_thing_searched;
2910 len++;
2913 /* If REUSE is not usable, cons up the values and return them. */
2914 if (! CONSP (reuse))
2915 reuse = Flist (len, data);
2916 else
2918 /* If REUSE is a list, store as many value elements as will fit
2919 into the elements of REUSE. */
2920 for (i = 0, tail = reuse; CONSP (tail);
2921 i++, tail = XCDR (tail))
2923 if (i < len)
2924 XSETCAR (tail, data[i]);
2925 else
2926 XSETCAR (tail, Qnil);
2927 prev = tail;
2930 /* If we couldn't fit all value elements into REUSE,
2931 cons up the rest of them and add them to the end of REUSE. */
2932 if (i < len)
2933 XSETCDR (prev, Flist (len - i, data + i));
2936 SAFE_FREE ();
2937 return reuse;
2940 /* We used to have an internal use variant of `reseat' described as:
2942 If RESEAT is `evaporate', put the markers back on the free list
2943 immediately. No other references to the markers must exist in this
2944 case, so it is used only internally on the unwind stack and
2945 save-match-data from Lisp.
2947 But it was ill-conceived: those supposedly-internal markers get exposed via
2948 the undo-list, so freeing them here is unsafe. */
2950 DEFUN ("set-match-data", Fset_match_data, Sset_match_data, 1, 2, 0,
2951 doc: /* Set internal data on last search match from elements of LIST.
2952 LIST should have been created by calling `match-data' previously.
2954 If optional arg RESEAT is non-nil, make markers on LIST point nowhere. */)
2955 (register Lisp_Object list, Lisp_Object reseat)
2957 ptrdiff_t i;
2958 register Lisp_Object marker;
2960 if (running_asynch_code)
2961 save_search_regs ();
2963 CHECK_LIST (list);
2965 /* Unless we find a marker with a buffer or an explicit buffer
2966 in LIST, assume that this match data came from a string. */
2967 last_thing_searched = Qt;
2969 /* Allocate registers if they don't already exist. */
2971 EMACS_INT length = XFASTINT (Flength (list)) / 2;
2973 if (length > search_regs.num_regs)
2975 ptrdiff_t num_regs = search_regs.num_regs;
2976 if (PTRDIFF_MAX < length)
2977 memory_full (SIZE_MAX);
2978 search_regs.start =
2979 xpalloc (search_regs.start, &num_regs, length - num_regs,
2980 min (PTRDIFF_MAX, UINT_MAX), sizeof (regoff_t));
2981 search_regs.end =
2982 xrealloc (search_regs.end, num_regs * sizeof (regoff_t));
2984 for (i = search_regs.num_regs; i < num_regs; i++)
2985 search_regs.start[i] = -1;
2987 search_regs.num_regs = num_regs;
2990 for (i = 0; CONSP (list); i++)
2992 marker = XCAR (list);
2993 if (BUFFERP (marker))
2995 last_thing_searched = marker;
2996 break;
2998 if (i >= length)
2999 break;
3000 if (NILP (marker))
3002 search_regs.start[i] = -1;
3003 list = XCDR (list);
3005 else
3007 Lisp_Object from;
3008 Lisp_Object m;
3010 m = marker;
3011 if (MARKERP (marker))
3013 if (XMARKER (marker)->buffer == 0)
3014 XSETFASTINT (marker, 0);
3015 else
3016 XSETBUFFER (last_thing_searched, XMARKER (marker)->buffer);
3019 CHECK_NUMBER_COERCE_MARKER (marker);
3020 from = marker;
3022 if (!NILP (reseat) && MARKERP (m))
3024 unchain_marker (XMARKER (m));
3025 XSETCAR (list, Qnil);
3028 if ((list = XCDR (list), !CONSP (list)))
3029 break;
3031 m = marker = XCAR (list);
3033 if (MARKERP (marker) && XMARKER (marker)->buffer == 0)
3034 XSETFASTINT (marker, 0);
3036 CHECK_NUMBER_COERCE_MARKER (marker);
3037 if ((XINT (from) < 0
3038 ? TYPE_MINIMUM (regoff_t) <= XINT (from)
3039 : XINT (from) <= TYPE_MAXIMUM (regoff_t))
3040 && (XINT (marker) < 0
3041 ? TYPE_MINIMUM (regoff_t) <= XINT (marker)
3042 : XINT (marker) <= TYPE_MAXIMUM (regoff_t)))
3044 search_regs.start[i] = XINT (from);
3045 search_regs.end[i] = XINT (marker);
3047 else
3049 search_regs.start[i] = -1;
3052 if (!NILP (reseat) && MARKERP (m))
3054 unchain_marker (XMARKER (m));
3055 XSETCAR (list, Qnil);
3058 list = XCDR (list);
3061 for (; i < search_regs.num_regs; i++)
3062 search_regs.start[i] = -1;
3065 return Qnil;
3068 /* If true the match data have been saved in saved_search_regs
3069 during the execution of a sentinel or filter. */
3070 /* static bool search_regs_saved; */
3071 /* static struct re_registers saved_search_regs; */
3072 /* static Lisp_Object saved_last_thing_searched; */
3074 /* Called from Flooking_at, Fstring_match, search_buffer, Fstore_match_data
3075 if asynchronous code (filter or sentinel) is running. */
3076 static void
3077 save_search_regs (void)
3079 if (!search_regs_saved)
3081 saved_search_regs.num_regs = search_regs.num_regs;
3082 saved_search_regs.start = search_regs.start;
3083 saved_search_regs.end = search_regs.end;
3084 saved_last_thing_searched = last_thing_searched;
3085 last_thing_searched = Qnil;
3086 search_regs.num_regs = 0;
3087 search_regs.start = 0;
3088 search_regs.end = 0;
3090 search_regs_saved = 1;
3094 /* Called upon exit from filters and sentinels. */
3095 void
3096 restore_search_regs (void)
3098 if (search_regs_saved)
3100 if (search_regs.num_regs > 0)
3102 xfree (search_regs.start);
3103 xfree (search_regs.end);
3105 search_regs.num_regs = saved_search_regs.num_regs;
3106 search_regs.start = saved_search_regs.start;
3107 search_regs.end = saved_search_regs.end;
3108 last_thing_searched = saved_last_thing_searched;
3109 saved_last_thing_searched = Qnil;
3110 search_regs_saved = 0;
3114 /* Called from replace-match via replace_range. */
3115 void
3116 update_search_regs (ptrdiff_t oldstart, ptrdiff_t oldend, ptrdiff_t newend)
3118 /* Adjust search data for this change. */
3119 ptrdiff_t change = newend - oldend;
3120 ptrdiff_t i;
3122 for (i = 0; i < search_regs.num_regs; i++)
3124 if (search_regs.start[i] >= oldend)
3125 search_regs.start[i] += change;
3126 else if (search_regs.start[i] > oldstart)
3127 search_regs.start[i] = oldstart;
3128 if (search_regs.end[i] >= oldend)
3129 search_regs.end[i] += change;
3130 else if (search_regs.end[i] > oldstart)
3131 search_regs.end[i] = oldstart;
3135 static void
3136 unwind_set_match_data (Lisp_Object list)
3138 /* It is NOT ALWAYS safe to free (evaporate) the markers immediately. */
3139 Fset_match_data (list, Qt);
3142 /* Called to unwind protect the match data. */
3143 void
3144 record_unwind_save_match_data (void)
3146 record_unwind_protect (unwind_set_match_data,
3147 Fmatch_data (Qnil, Qnil, Qnil));
3150 /* Quote a string to deactivate reg-expr chars */
3152 DEFUN ("regexp-quote", Fregexp_quote, Sregexp_quote, 1, 1, 0,
3153 doc: /* Return a regexp string which matches exactly STRING and nothing else. */)
3154 (Lisp_Object string)
3156 char *in, *out, *end;
3157 char *temp;
3158 ptrdiff_t backslashes_added = 0;
3160 CHECK_STRING (string);
3162 USE_SAFE_ALLOCA;
3163 SAFE_NALLOCA (temp, 2, SBYTES (string));
3165 /* Now copy the data into the new string, inserting escapes. */
3167 in = SSDATA (string);
3168 end = in + SBYTES (string);
3169 out = temp;
3171 for (; in != end; in++)
3173 if (*in == '['
3174 || *in == '*' || *in == '.' || *in == '\\'
3175 || *in == '?' || *in == '+'
3176 || *in == '^' || *in == '$')
3177 *out++ = '\\', backslashes_added++;
3178 *out++ = *in;
3181 Lisp_Object result
3182 = make_specified_string (temp,
3183 SCHARS (string) + backslashes_added,
3184 out - temp,
3185 STRING_MULTIBYTE (string));
3186 SAFE_FREE ();
3187 return result;
3190 /* Like find_newline, but doesn't use the cache, and only searches forward. */
3191 static ptrdiff_t
3192 find_newline1 (ptrdiff_t start, ptrdiff_t start_byte, ptrdiff_t end,
3193 ptrdiff_t end_byte, ptrdiff_t count, ptrdiff_t *shortage,
3194 ptrdiff_t *bytepos, bool allow_quit)
3196 if (count > 0)
3198 if (!end)
3199 end = ZV, end_byte = ZV_BYTE;
3201 else
3203 if (!end)
3204 end = BEGV, end_byte = BEGV_BYTE;
3206 if (end_byte == -1)
3207 end_byte = CHAR_TO_BYTE (end);
3209 if (shortage != 0)
3210 *shortage = 0;
3212 if (count > 0)
3213 while (start != end)
3215 /* Our innermost scanning loop is very simple; it doesn't know
3216 about gaps, buffer ends, or the newline cache. ceiling is
3217 the position of the last character before the next such
3218 obstacle --- the last character the dumb search loop should
3219 examine. */
3220 ptrdiff_t tem, ceiling_byte = end_byte - 1;
3222 if (start_byte == -1)
3223 start_byte = CHAR_TO_BYTE (start);
3225 /* The dumb loop can only scan text stored in contiguous
3226 bytes. BUFFER_CEILING_OF returns the last character
3227 position that is contiguous, so the ceiling is the
3228 position after that. */
3229 tem = BUFFER_CEILING_OF (start_byte);
3230 ceiling_byte = min (tem, ceiling_byte);
3233 /* The termination address of the dumb loop. */
3234 unsigned char *lim_addr = BYTE_POS_ADDR (ceiling_byte) + 1;
3235 ptrdiff_t lim_byte = ceiling_byte + 1;
3237 /* Nonpositive offsets (relative to LIM_ADDR and LIM_BYTE)
3238 of the base, the cursor, and the next line. */
3239 ptrdiff_t base = start_byte - lim_byte;
3240 ptrdiff_t cursor, next;
3242 for (cursor = base; cursor < 0; cursor = next)
3244 /* The dumb loop. */
3245 unsigned char *nl = memchr (lim_addr + cursor, '\n', - cursor);
3246 next = nl ? nl - lim_addr : 0;
3248 if (! nl)
3249 break;
3250 next++;
3252 if (--count == 0)
3254 if (bytepos)
3255 *bytepos = lim_byte + next;
3256 return BYTE_TO_CHAR (lim_byte + next);
3258 if (allow_quit)
3259 maybe_quit ();
3262 start_byte = lim_byte;
3263 start = BYTE_TO_CHAR (start_byte);
3267 if (shortage)
3268 *shortage = count;
3269 if (bytepos)
3271 *bytepos = start_byte == -1 ? CHAR_TO_BYTE (start) : start_byte;
3272 eassert (*bytepos == CHAR_TO_BYTE (start));
3274 return start;
3277 DEFUN ("newline-cache-check", Fnewline_cache_check, Snewline_cache_check,
3278 0, 1, 0,
3279 doc: /* Check the newline cache of BUFFER against buffer contents.
3281 BUFFER defaults to the current buffer.
3283 Value is an array of 2 sub-arrays of buffer positions for newlines,
3284 the first based on the cache, the second based on actually scanning
3285 the buffer. If the buffer doesn't have a cache, the value is nil. */)
3286 (Lisp_Object buffer)
3288 struct buffer *buf, *old = NULL;
3289 ptrdiff_t shortage, nl_count_cache, nl_count_buf;
3290 Lisp_Object cache_newlines, buf_newlines, val;
3291 ptrdiff_t from, found, i;
3293 if (NILP (buffer))
3294 buf = current_buffer;
3295 else
3297 CHECK_BUFFER (buffer);
3298 buf = XBUFFER (buffer);
3299 old = current_buffer;
3301 if (buf->base_buffer)
3302 buf = buf->base_buffer;
3304 /* If the buffer doesn't have a newline cache, return nil. */
3305 if (NILP (BVAR (buf, cache_long_scans))
3306 || buf->newline_cache == NULL)
3307 return Qnil;
3309 /* find_newline can only work on the current buffer. */
3310 if (old != NULL)
3311 set_buffer_internal_1 (buf);
3313 /* How many newlines are there according to the cache? */
3314 find_newline (BEGV, BEGV_BYTE, ZV, ZV_BYTE,
3315 TYPE_MAXIMUM (ptrdiff_t), &shortage, NULL, true);
3316 nl_count_cache = TYPE_MAXIMUM (ptrdiff_t) - shortage;
3318 /* Create vector and populate it. */
3319 cache_newlines = make_uninit_vector (nl_count_cache);
3321 if (nl_count_cache)
3323 for (from = BEGV, found = from, i = 0; from < ZV; from = found, i++)
3325 ptrdiff_t from_byte = CHAR_TO_BYTE (from);
3327 found = find_newline (from, from_byte, 0, -1, 1, &shortage,
3328 NULL, true);
3329 if (shortage != 0 || i >= nl_count_cache)
3330 break;
3331 ASET (cache_newlines, i, make_number (found - 1));
3333 /* Fill the rest of slots with an invalid position. */
3334 for ( ; i < nl_count_cache; i++)
3335 ASET (cache_newlines, i, make_number (-1));
3338 /* Now do the same, but without using the cache. */
3339 find_newline1 (BEGV, BEGV_BYTE, ZV, ZV_BYTE,
3340 TYPE_MAXIMUM (ptrdiff_t), &shortage, NULL, true);
3341 nl_count_buf = TYPE_MAXIMUM (ptrdiff_t) - shortage;
3342 buf_newlines = make_uninit_vector (nl_count_buf);
3343 if (nl_count_buf)
3345 for (from = BEGV, found = from, i = 0; from < ZV; from = found, i++)
3347 ptrdiff_t from_byte = CHAR_TO_BYTE (from);
3349 found = find_newline1 (from, from_byte, 0, -1, 1, &shortage,
3350 NULL, true);
3351 if (shortage != 0 || i >= nl_count_buf)
3352 break;
3353 ASET (buf_newlines, i, make_number (found - 1));
3355 for ( ; i < nl_count_buf; i++)
3356 ASET (buf_newlines, i, make_number (-1));
3359 /* Construct the value and return it. */
3360 val = make_uninit_vector (2);
3361 ASET (val, 0, cache_newlines);
3362 ASET (val, 1, buf_newlines);
3364 if (old != NULL)
3365 set_buffer_internal_1 (old);
3366 return val;
3369 void
3370 syms_of_search (void)
3372 register int i;
3374 for (i = 0; i < REGEXP_CACHE_SIZE; ++i)
3376 searchbufs[i].buf.allocated = 100;
3377 searchbufs[i].buf.buffer = xmalloc (100);
3378 searchbufs[i].buf.fastmap = searchbufs[i].fastmap;
3379 searchbufs[i].regexp = Qnil;
3380 searchbufs[i].f_whitespace_regexp = Qnil;
3381 searchbufs[i].syntax_table = Qnil;
3382 staticpro (&searchbufs[i].regexp);
3383 staticpro (&searchbufs[i].f_whitespace_regexp);
3384 staticpro (&searchbufs[i].syntax_table);
3385 searchbufs[i].next = (i == REGEXP_CACHE_SIZE-1 ? 0 : &searchbufs[i+1]);
3387 searchbuf_head = &searchbufs[0];
3389 /* Error condition used for failing searches. */
3390 DEFSYM (Qsearch_failed, "search-failed");
3392 /* Error condition signaled when regexp compile_pattern fails. */
3393 DEFSYM (Qinvalid_regexp, "invalid-regexp");
3395 Fput (Qsearch_failed, Qerror_conditions,
3396 listn (CONSTYPE_PURE, 2, Qsearch_failed, Qerror));
3397 Fput (Qsearch_failed, Qerror_message,
3398 build_pure_c_string ("Search failed"));
3400 Fput (Qinvalid_regexp, Qerror_conditions,
3401 listn (CONSTYPE_PURE, 2, Qinvalid_regexp, Qerror));
3402 Fput (Qinvalid_regexp, Qerror_message,
3403 build_pure_c_string ("Invalid regexp"));
3405 last_thing_searched = Qnil;
3406 staticpro (&last_thing_searched);
3408 saved_last_thing_searched = Qnil;
3409 staticpro (&saved_last_thing_searched);
3411 DEFVAR_LISP ("search-spaces-regexp", Vsearch_spaces_regexp,
3412 doc: /* Regexp to substitute for bunches of spaces in regexp search.
3413 Some commands use this for user-specified regexps.
3414 Spaces that occur inside character classes or repetition operators
3415 or other such regexp constructs are not replaced with this.
3416 A value of nil (which is the normal value) means treat spaces literally. */);
3417 Vsearch_spaces_regexp = Qnil;
3419 DEFSYM (Qinhibit_changing_match_data, "inhibit-changing-match-data");
3420 DEFVAR_LISP ("inhibit-changing-match-data", Vinhibit_changing_match_data,
3421 doc: /* Internal use only.
3422 If non-nil, the primitive searching and matching functions
3423 such as `looking-at', `string-match', `re-search-forward', etc.,
3424 do not set the match data. The proper way to use this variable
3425 is to bind it with `let' around a small expression. */);
3426 Vinhibit_changing_match_data = Qnil;
3428 defsubr (&Slooking_at);
3429 defsubr (&Sposix_looking_at);
3430 defsubr (&Sstring_match);
3431 defsubr (&Sposix_string_match);
3432 defsubr (&Ssearch_forward);
3433 defsubr (&Ssearch_backward);
3434 defsubr (&Sre_search_forward);
3435 defsubr (&Sre_search_backward);
3436 defsubr (&Sposix_search_forward);
3437 defsubr (&Sposix_search_backward);
3438 defsubr (&Sreplace_match);
3439 defsubr (&Smatch_beginning);
3440 defsubr (&Smatch_end);
3441 defsubr (&Smatch_data);
3442 defsubr (&Sset_match_data);
3443 defsubr (&Sregexp_quote);
3444 defsubr (&Snewline_cache_check);