; doc/emacs/misc.texi (Network Security): Fix typo.
[emacs.git] / src / search.c
blobccdb659776da9656c57e2e192835dd22478986eb
1 /* String search routines for GNU Emacs.
3 Copyright (C) 1985-1987, 1993-1994, 1997-1999, 2001-2018 Free Software
4 Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or (at
11 your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. */
22 #include <config.h>
24 #include "lisp.h"
25 #include "character.h"
26 #include "buffer.h"
27 #include "syntax.h"
28 #include "charset.h"
29 #include "region-cache.h"
30 #include "blockinput.h"
31 #include "intervals.h"
33 #include "regex.h"
35 #define REGEXP_CACHE_SIZE 20
37 /* If the regexp is non-nil, then the buffer contains the compiled form
38 of that regexp, suitable for searching. */
39 struct regexp_cache
41 struct regexp_cache *next;
42 Lisp_Object regexp, f_whitespace_regexp;
43 /* Syntax table for which the regexp applies. We need this because
44 of character classes. If this is t, then the compiled pattern is valid
45 for any syntax-table. */
46 Lisp_Object syntax_table;
47 struct re_pattern_buffer buf;
48 char fastmap[0400];
49 /* True means regexp was compiled to do full POSIX backtracking. */
50 bool posix;
51 /* True means we're inside a buffer match. */
52 bool busy;
55 /* The instances of that struct. */
56 static struct regexp_cache searchbufs[REGEXP_CACHE_SIZE];
58 /* The head of the linked list; points to the most recently used buffer. */
59 static struct regexp_cache *searchbuf_head;
62 /* Every call to re_match, etc., must pass &search_regs as the regs
63 argument unless you can show it is unnecessary (i.e., if re_match
64 is certainly going to be called again before region-around-match
65 can be called).
67 Since the registers are now dynamically allocated, we need to make
68 sure not to refer to the Nth register before checking that it has
69 been allocated by checking search_regs.num_regs.
71 The regex code keeps track of whether it has allocated the search
72 buffer using bits in the re_pattern_buffer. This means that whenever
73 you compile a new pattern, it completely forgets whether it has
74 allocated any registers, and will allocate new registers the next
75 time you call a searching or matching function. Therefore, we need
76 to call re_set_registers after compiling a new pattern or after
77 setting the match registers, so that the regex functions will be
78 able to free or re-allocate it properly. */
79 /* static struct re_registers search_regs; */
81 /* The buffer in which the last search was performed, or
82 Qt if the last search was done in a string;
83 Qnil if no searching has been done yet. */
84 /* static Lisp_Object last_thing_searched; */
86 static void set_search_regs (ptrdiff_t, ptrdiff_t);
87 static void save_search_regs (void);
88 static EMACS_INT simple_search (EMACS_INT, unsigned char *, ptrdiff_t,
89 ptrdiff_t, Lisp_Object, ptrdiff_t, ptrdiff_t,
90 ptrdiff_t, ptrdiff_t);
91 static EMACS_INT boyer_moore (EMACS_INT, unsigned char *, ptrdiff_t,
92 Lisp_Object, Lisp_Object, ptrdiff_t,
93 ptrdiff_t, int);
94 static EMACS_INT search_buffer (Lisp_Object, ptrdiff_t, ptrdiff_t,
95 ptrdiff_t, ptrdiff_t, EMACS_INT, int,
96 Lisp_Object, Lisp_Object, bool);
98 Lisp_Object re_match_object;
100 static _Noreturn void
101 matcher_overflow (void)
103 error ("Stack overflow in regexp matcher");
106 static void
107 freeze_buffer_relocation (void)
109 #ifdef REL_ALLOC
110 /* Prevent ralloc.c from relocating the current buffer while
111 searching it. */
112 r_alloc_inhibit_buffer_relocation (1);
113 record_unwind_protect_int (r_alloc_inhibit_buffer_relocation, 0);
114 #endif
117 /* Compile a regexp and signal a Lisp error if anything goes wrong.
118 PATTERN is the pattern to compile.
119 CP is the place to put the result.
120 TRANSLATE is a translation table for ignoring case, or nil for none.
121 POSIX is true if we want full backtracking (POSIX style) for this pattern.
122 False means backtrack only enough to get a valid match.
124 The behavior also depends on Vsearch_spaces_regexp. */
126 static void
127 compile_pattern_1 (struct regexp_cache *cp, Lisp_Object pattern,
128 Lisp_Object translate, bool posix)
130 const char *whitespace_regexp;
131 char *val;
133 eassert (!cp->busy);
134 cp->regexp = Qnil;
135 cp->buf.translate = (! NILP (translate) ? translate : make_number (0));
136 cp->posix = posix;
137 cp->buf.multibyte = STRING_MULTIBYTE (pattern);
138 cp->buf.charset_unibyte = charset_unibyte;
139 if (STRINGP (Vsearch_spaces_regexp))
140 cp->f_whitespace_regexp = Vsearch_spaces_regexp;
141 else
142 cp->f_whitespace_regexp = Qnil;
144 whitespace_regexp = STRINGP (Vsearch_spaces_regexp) ?
145 SSDATA (Vsearch_spaces_regexp) : NULL;
147 val = (char *) re_compile_pattern (SSDATA (pattern), SBYTES (pattern),
148 posix, whitespace_regexp, &cp->buf);
150 /* If the compiled pattern hard codes some of the contents of the
151 syntax-table, it can only be reused with *this* syntax table. */
152 cp->syntax_table = cp->buf.used_syntax ? BVAR (current_buffer, syntax_table) : Qt;
154 if (val)
155 xsignal1 (Qinvalid_regexp, build_string (val));
157 cp->regexp = Fcopy_sequence (pattern);
160 /* Shrink each compiled regexp buffer in the cache
161 to the size actually used right now.
162 This is called from garbage collection. */
164 void
165 shrink_regexp_cache (void)
167 struct regexp_cache *cp;
169 for (cp = searchbuf_head; cp != 0; cp = cp->next)
170 if (!cp->busy)
172 cp->buf.allocated = cp->buf.used;
173 cp->buf.buffer = xrealloc (cp->buf.buffer, cp->buf.used);
177 /* Clear the regexp cache w.r.t. a particular syntax table,
178 because it was changed.
179 There is no danger of memory leak here because re_compile_pattern
180 automagically manages the memory in each re_pattern_buffer struct,
181 based on its `allocated' and `buffer' values. */
182 void
183 clear_regexp_cache (void)
185 int i;
187 for (i = 0; i < REGEXP_CACHE_SIZE; ++i)
188 /* It's tempting to compare with the syntax-table we've actually changed,
189 but it's not sufficient because char-table inheritance means that
190 modifying one syntax-table can change others at the same time. */
191 if (!searchbufs[i].busy && !EQ (searchbufs[i].syntax_table, Qt))
192 searchbufs[i].regexp = Qnil;
195 static void
196 unfreeze_pattern (void *arg)
198 struct regexp_cache *searchbuf = arg;
199 searchbuf->busy = false;
202 static void
203 freeze_pattern (struct regexp_cache *searchbuf)
205 eassert (!searchbuf->busy);
206 record_unwind_protect_ptr (unfreeze_pattern, searchbuf);
207 searchbuf->busy = true;
210 /* Compile a regexp if necessary, but first check to see if there's one in
211 the cache.
212 PATTERN is the pattern to compile.
213 TRANSLATE is a translation table for ignoring case, or nil for none.
214 REGP is the structure that says where to store the "register"
215 values that will result from matching this pattern.
216 If it is 0, we should compile the pattern not to record any
217 subexpression bounds.
218 POSIX is true if we want full backtracking (POSIX style) for this pattern.
219 False means backtrack only enough to get a valid match. */
221 static struct regexp_cache *
222 compile_pattern (Lisp_Object pattern, struct re_registers *regp,
223 Lisp_Object translate, bool posix, bool multibyte)
225 struct regexp_cache *cp, **cpp;
227 for (cpp = &searchbuf_head; ; cpp = &cp->next)
229 cp = *cpp;
230 /* Entries are initialized to nil, and may be set to nil by
231 compile_pattern_1 if the pattern isn't valid. Don't apply
232 string accessors in those cases. However, compile_pattern_1
233 is only applied to the cache entry we pick here to reuse. So
234 nil should never appear before a non-nil entry. */
235 if (NILP (cp->regexp))
236 goto compile_it;
237 if (SCHARS (cp->regexp) == SCHARS (pattern)
238 && !cp->busy
239 && STRING_MULTIBYTE (cp->regexp) == STRING_MULTIBYTE (pattern)
240 && !NILP (Fstring_equal (cp->regexp, pattern))
241 && EQ (cp->buf.translate, (! NILP (translate) ? translate : make_number (0)))
242 && cp->posix == posix
243 && (EQ (cp->syntax_table, Qt)
244 || EQ (cp->syntax_table, BVAR (current_buffer, syntax_table)))
245 && !NILP (Fequal (cp->f_whitespace_regexp, Vsearch_spaces_regexp))
246 && cp->buf.charset_unibyte == charset_unibyte)
247 break;
249 /* If we're at the end of the cache, compile into the nil cell
250 we found, or the last (least recently used) cell with a
251 string value. */
252 if (cp->next == 0)
254 if (cp->busy)
255 error ("Too much matching reentrancy");
256 compile_it:
257 eassert (!cp->busy);
258 compile_pattern_1 (cp, pattern, translate, posix);
259 break;
263 /* When we get here, cp (aka *cpp) contains the compiled pattern,
264 either because we found it in the cache or because we just compiled it.
265 Move it to the front of the queue to mark it as most recently used. */
266 *cpp = cp->next;
267 cp->next = searchbuf_head;
268 searchbuf_head = cp;
270 /* Advise the searching functions about the space we have allocated
271 for register data. */
272 if (regp)
273 re_set_registers (&cp->buf, regp, regp->num_regs, regp->start, regp->end);
275 /* The compiled pattern can be used both for multibyte and unibyte
276 target. But, we have to tell which the pattern is used for. */
277 cp->buf.target_multibyte = multibyte;
278 return cp;
282 static Lisp_Object
283 looking_at_1 (Lisp_Object string, bool posix)
285 Lisp_Object val;
286 unsigned char *p1, *p2;
287 ptrdiff_t s1, s2;
288 register ptrdiff_t i;
290 if (running_asynch_code)
291 save_search_regs ();
293 /* This is so set_image_of_range_1 in regex.c can find the EQV table. */
294 set_char_table_extras (BVAR (current_buffer, case_canon_table), 2,
295 BVAR (current_buffer, case_eqv_table));
297 CHECK_STRING (string);
299 /* Snapshot in case Lisp changes the value. */
300 bool preserve_match_data = NILP (Vinhibit_changing_match_data);
302 struct regexp_cache *cache_entry = compile_pattern (
303 string,
304 preserve_match_data ? &search_regs : NULL,
305 (!NILP (BVAR (current_buffer, case_fold_search))
306 ? BVAR (current_buffer, case_canon_table) : Qnil),
307 posix,
308 !NILP (BVAR (current_buffer, enable_multibyte_characters)));
310 /* Do a pending quit right away, to avoid paradoxical behavior */
311 maybe_quit ();
313 /* Get pointers and sizes of the two strings
314 that make up the visible portion of the buffer. */
316 p1 = BEGV_ADDR;
317 s1 = GPT_BYTE - BEGV_BYTE;
318 p2 = GAP_END_ADDR;
319 s2 = ZV_BYTE - GPT_BYTE;
320 if (s1 < 0)
322 p2 = p1;
323 s2 = ZV_BYTE - BEGV_BYTE;
324 s1 = 0;
326 if (s2 < 0)
328 s1 = ZV_BYTE - BEGV_BYTE;
329 s2 = 0;
332 ptrdiff_t count = SPECPDL_INDEX ();
333 freeze_buffer_relocation ();
334 freeze_pattern (cache_entry);
335 re_match_object = Qnil;
336 i = re_match_2 (&cache_entry->buf, (char *) p1, s1, (char *) p2, s2,
337 PT_BYTE - BEGV_BYTE,
338 preserve_match_data ? &search_regs : NULL,
339 ZV_BYTE - BEGV_BYTE);
341 if (i == -2)
342 matcher_overflow ();
344 val = (i >= 0 ? Qt : Qnil);
345 if (preserve_match_data && i >= 0)
347 for (i = 0; i < search_regs.num_regs; i++)
348 if (search_regs.start[i] >= 0)
350 search_regs.start[i]
351 = BYTE_TO_CHAR (search_regs.start[i] + BEGV_BYTE);
352 search_regs.end[i]
353 = BYTE_TO_CHAR (search_regs.end[i] + BEGV_BYTE);
355 /* Set last_thing_searched only when match data is changed. */
356 XSETBUFFER (last_thing_searched, current_buffer);
359 return unbind_to (count, val);
362 DEFUN ("looking-at", Flooking_at, Slooking_at, 1, 1, 0,
363 doc: /* Return t if text after point matches regular expression REGEXP.
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, 0);
372 DEFUN ("posix-looking-at", Fposix_looking_at, Sposix_looking_at, 1, 1, 0,
373 doc: /* Return t if text after point matches regular expression REGEXP.
374 Find the longest match, in accord with Posix regular expression rules.
375 This function modifies the match data that `match-beginning',
376 `match-end' and `match-data' access; save and restore the match
377 data if you want to preserve them. */)
378 (Lisp_Object regexp)
380 return looking_at_1 (regexp, 1);
383 static Lisp_Object
384 string_match_1 (Lisp_Object regexp, Lisp_Object string, Lisp_Object start,
385 bool posix)
387 ptrdiff_t val;
388 struct re_pattern_buffer *bufp;
389 EMACS_INT pos;
390 ptrdiff_t pos_byte, i;
392 if (running_asynch_code)
393 save_search_regs ();
395 CHECK_STRING (regexp);
396 CHECK_STRING (string);
398 if (NILP (start))
399 pos = 0, pos_byte = 0;
400 else
402 ptrdiff_t len = SCHARS (string);
404 CHECK_NUMBER (start);
405 pos = XINT (start);
406 if (pos < 0 && -pos <= len)
407 pos = len + pos;
408 else if (0 > pos || pos > len)
409 args_out_of_range (string, start);
410 pos_byte = string_char_to_byte (string, pos);
413 /* This is so set_image_of_range_1 in regex.c can find the EQV table. */
414 set_char_table_extras (BVAR (current_buffer, case_canon_table), 2,
415 BVAR (current_buffer, case_eqv_table));
417 bufp = &compile_pattern (regexp,
418 (NILP (Vinhibit_changing_match_data)
419 ? &search_regs : NULL),
420 (!NILP (BVAR (current_buffer, case_fold_search))
421 ? BVAR (current_buffer, case_canon_table) : Qnil),
422 posix,
423 STRING_MULTIBYTE (string))->buf;
424 re_match_object = string;
425 val = re_search (bufp, SSDATA (string),
426 SBYTES (string), pos_byte,
427 SBYTES (string) - pos_byte,
428 (NILP (Vinhibit_changing_match_data)
429 ? &search_regs : NULL));
431 /* Set last_thing_searched only when match data is changed. */
432 if (NILP (Vinhibit_changing_match_data))
433 last_thing_searched = Qt;
435 if (val == -2)
436 matcher_overflow ();
437 if (val < 0) return Qnil;
439 if (NILP (Vinhibit_changing_match_data))
440 for (i = 0; i < search_regs.num_regs; i++)
441 if (search_regs.start[i] >= 0)
443 search_regs.start[i]
444 = string_byte_to_char (string, search_regs.start[i]);
445 search_regs.end[i]
446 = string_byte_to_char (string, search_regs.end[i]);
449 return make_number (string_byte_to_char (string, val));
452 DEFUN ("string-match", Fstring_match, Sstring_match, 2, 3, 0,
453 doc: /* Return index of start of first match for REGEXP in STRING, or nil.
454 Matching ignores case if `case-fold-search' is non-nil.
455 If third arg START is non-nil, start search at that index in STRING.
456 For index of first char beyond the match, do (match-end 0).
457 `match-end' and `match-beginning' also give indices of substrings
458 matched by parenthesis constructs in the pattern.
460 You can use the function `match-string' to extract the substrings
461 matched by the parenthesis constructions in REGEXP. */)
462 (Lisp_Object regexp, Lisp_Object string, Lisp_Object start)
464 return string_match_1 (regexp, string, start, 0);
467 DEFUN ("posix-string-match", Fposix_string_match, Sposix_string_match, 2, 3, 0,
468 doc: /* Return index of start of first match for REGEXP in STRING, or nil.
469 Find the longest match, in accord with Posix regular expression rules.
470 Case is ignored if `case-fold-search' is non-nil in the current buffer.
471 If third arg START is non-nil, start search at that index in STRING.
472 For index of first char beyond the match, do (match-end 0).
473 `match-end' and `match-beginning' also give indices of substrings
474 matched by parenthesis constructs in the pattern. */)
475 (Lisp_Object regexp, Lisp_Object string, Lisp_Object start)
477 return string_match_1 (regexp, string, start, 1);
480 /* Match REGEXP against STRING using translation table TABLE,
481 searching all of STRING, and return the index of the match,
482 or negative on failure. This does not clobber the match data. */
484 ptrdiff_t
485 fast_string_match_internal (Lisp_Object regexp, Lisp_Object string,
486 Lisp_Object table)
488 ptrdiff_t val;
489 struct re_pattern_buffer *bufp;
491 bufp = &compile_pattern (regexp, 0, table,
492 0, STRING_MULTIBYTE (string))->buf;
493 re_match_object = string;
494 val = re_search (bufp, SSDATA (string),
495 SBYTES (string), 0,
496 SBYTES (string), 0);
497 return val;
500 /* Match REGEXP against STRING, searching all of STRING ignoring case,
501 and return the index of the match, or negative on failure.
502 This does not clobber the match data.
503 We assume that STRING contains single-byte characters. */
505 ptrdiff_t
506 fast_c_string_match_ignore_case (Lisp_Object regexp,
507 const char *string, ptrdiff_t len)
509 ptrdiff_t val;
510 struct re_pattern_buffer *bufp;
512 regexp = string_make_unibyte (regexp);
513 bufp = &compile_pattern (regexp, 0,
514 Vascii_canon_table, 0,
515 0)->buf;
516 re_match_object = Qt;
517 val = re_search (bufp, string, len, 0, len, 0);
518 return val;
521 /* Match REGEXP against the characters after POS to LIMIT, and return
522 the number of matched characters. If STRING is non-nil, match
523 against the characters in it. In that case, POS and LIMIT are
524 indices into the string. This function doesn't modify the match
525 data. */
527 ptrdiff_t
528 fast_looking_at (Lisp_Object regexp, ptrdiff_t pos, ptrdiff_t pos_byte,
529 ptrdiff_t limit, ptrdiff_t limit_byte, Lisp_Object string)
531 bool multibyte;
532 unsigned char *p1, *p2;
533 ptrdiff_t s1, s2;
534 ptrdiff_t len;
536 if (STRINGP (string))
538 if (pos_byte < 0)
539 pos_byte = string_char_to_byte (string, pos);
540 if (limit_byte < 0)
541 limit_byte = string_char_to_byte (string, limit);
542 p1 = NULL;
543 s1 = 0;
544 p2 = SDATA (string);
545 s2 = SBYTES (string);
546 multibyte = STRING_MULTIBYTE (string);
548 else
550 if (pos_byte < 0)
551 pos_byte = CHAR_TO_BYTE (pos);
552 if (limit_byte < 0)
553 limit_byte = CHAR_TO_BYTE (limit);
554 pos_byte -= BEGV_BYTE;
555 limit_byte -= BEGV_BYTE;
556 p1 = BEGV_ADDR;
557 s1 = GPT_BYTE - BEGV_BYTE;
558 p2 = GAP_END_ADDR;
559 s2 = ZV_BYTE - GPT_BYTE;
560 if (s1 < 0)
562 p2 = p1;
563 s2 = ZV_BYTE - BEGV_BYTE;
564 s1 = 0;
566 if (s2 < 0)
568 s1 = ZV_BYTE - BEGV_BYTE;
569 s2 = 0;
571 multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
574 struct regexp_cache *cache_entry =
575 compile_pattern (regexp, 0, Qnil, 0, multibyte);
576 ptrdiff_t count = SPECPDL_INDEX ();
577 freeze_buffer_relocation ();
578 freeze_pattern (cache_entry);
579 re_match_object = STRINGP (string) ? string : Qnil;
580 len = re_match_2 (&cache_entry->buf, (char *) p1, s1, (char *) p2, s2,
581 pos_byte, NULL, limit_byte);
583 unbind_to (count, Qnil);
584 return len;
588 /* The newline cache: remembering which sections of text have no newlines. */
590 /* If the user has requested the long scans caching, make sure it's on.
591 Otherwise, make sure it's off.
592 This is our cheezy way of associating an action with the change of
593 state of a buffer-local variable. */
594 static struct region_cache *
595 newline_cache_on_off (struct buffer *buf)
597 struct buffer *base_buf = buf;
598 bool indirect_p = false;
600 if (buf->base_buffer)
602 base_buf = buf->base_buffer;
603 indirect_p = true;
606 /* Don't turn on or off the cache in the base buffer, if the value
607 of cache-long-scans of the base buffer is inconsistent with that.
608 This is because doing so will just make the cache pure overhead,
609 since if we turn it on via indirect buffer, it will be
610 immediately turned off by its base buffer. */
611 if (NILP (BVAR (buf, cache_long_scans)))
613 if (!indirect_p
614 || NILP (BVAR (base_buf, cache_long_scans)))
616 /* It should be off. */
617 if (base_buf->newline_cache)
619 free_region_cache (base_buf->newline_cache);
620 base_buf->newline_cache = 0;
623 return NULL;
625 else
627 if (!indirect_p
628 || !NILP (BVAR (base_buf, cache_long_scans)))
630 /* It should be on. */
631 if (base_buf->newline_cache == 0)
632 base_buf->newline_cache = new_region_cache ();
634 return base_buf->newline_cache;
639 /* Search for COUNT newlines between START/START_BYTE and END/END_BYTE.
641 If COUNT is positive, search forwards; END must be >= START.
642 If COUNT is negative, search backwards for the -COUNTth instance;
643 END must be <= START.
644 If COUNT is zero, do anything you please; run rogue, for all I care.
646 If END is zero, use BEGV or ZV instead, as appropriate for the
647 direction indicated by COUNT.
649 If we find COUNT instances, set *SHORTAGE to zero, and return the
650 position past the COUNTth match. Note that for reverse motion
651 this is not the same as the usual convention for Emacs motion commands.
653 If we don't find COUNT instances before reaching END, set *SHORTAGE
654 to the number of newlines left unfound, and return END.
656 If BYTEPOS is not NULL, set *BYTEPOS to the byte position corresponding
657 to the returned character position.
659 If ALLOW_QUIT, check for quitting. That's good to do
660 except when inside redisplay. */
662 ptrdiff_t
663 find_newline (ptrdiff_t start, ptrdiff_t start_byte, ptrdiff_t end,
664 ptrdiff_t end_byte, ptrdiff_t count, ptrdiff_t *shortage,
665 ptrdiff_t *bytepos, bool allow_quit)
667 struct region_cache *newline_cache;
668 int direction;
669 struct buffer *cache_buffer;
671 if (count > 0)
673 direction = 1;
674 if (!end)
675 end = ZV, end_byte = ZV_BYTE;
677 else
679 direction = -1;
680 if (!end)
681 end = BEGV, end_byte = BEGV_BYTE;
683 if (end_byte == -1)
684 end_byte = CHAR_TO_BYTE (end);
686 newline_cache = newline_cache_on_off (current_buffer);
687 if (current_buffer->base_buffer)
688 cache_buffer = current_buffer->base_buffer;
689 else
690 cache_buffer = current_buffer;
692 if (shortage != 0)
693 *shortage = 0;
695 if (count > 0)
696 while (start != end)
698 /* Our innermost scanning loop is very simple; it doesn't know
699 about gaps, buffer ends, or the newline cache. ceiling is
700 the position of the last character before the next such
701 obstacle --- the last character the dumb search loop should
702 examine. */
703 ptrdiff_t tem, ceiling_byte = end_byte - 1;
705 /* If we're using the newline cache, consult it to see whether
706 we can avoid some scanning. */
707 if (newline_cache)
709 ptrdiff_t next_change;
710 int result = 1;
712 while (start < end && result)
714 ptrdiff_t lim1;
716 result = region_cache_forward (cache_buffer, newline_cache,
717 start, &next_change);
718 if (result)
720 /* When the cache revalidation is deferred,
721 next-change might point beyond ZV, which will
722 cause assertion violation in CHAR_TO_BYTE below.
723 Limit next_change to ZV to avoid that. */
724 if (next_change > ZV)
725 next_change = ZV;
726 start = next_change;
727 lim1 = next_change = end;
729 else
730 lim1 = min (next_change, end);
732 /* The cache returned zero for this region; see if
733 this is because the region is known and includes
734 only newlines. While at that, count any newlines
735 we bump into, and exit if we found enough off them. */
736 start_byte = CHAR_TO_BYTE (start);
737 while (start < lim1
738 && FETCH_BYTE (start_byte) == '\n')
740 start_byte++;
741 start++;
742 if (--count == 0)
744 if (bytepos)
745 *bytepos = start_byte;
746 return start;
749 /* If we found a non-newline character before hitting
750 position where the cache will again return non-zero
751 (i.e. no newlines beyond that position), it means
752 this region is not yet known to the cache, and we
753 must resort to the "dumb loop" method. */
754 if (start < next_change && !result)
755 break;
756 result = 1;
758 if (start >= end)
760 start = end;
761 start_byte = end_byte;
762 break;
765 /* START should never be after END. */
766 if (start_byte > ceiling_byte)
767 start_byte = ceiling_byte;
769 /* Now the text after start is an unknown region, and
770 next_change is the position of the next known region. */
771 ceiling_byte = min (CHAR_TO_BYTE (next_change) - 1, ceiling_byte);
773 else if (start_byte == -1)
774 start_byte = CHAR_TO_BYTE (start);
776 /* The dumb loop can only scan text stored in contiguous
777 bytes. BUFFER_CEILING_OF returns the last character
778 position that is contiguous, so the ceiling is the
779 position after that. */
780 tem = BUFFER_CEILING_OF (start_byte);
781 ceiling_byte = min (tem, ceiling_byte);
784 /* The termination address of the dumb loop. */
785 unsigned char *lim_addr = BYTE_POS_ADDR (ceiling_byte) + 1;
786 ptrdiff_t lim_byte = ceiling_byte + 1;
788 /* Nonpositive offsets (relative to LIM_ADDR and LIM_BYTE)
789 of the base, the cursor, and the next line. */
790 ptrdiff_t base = start_byte - lim_byte;
791 ptrdiff_t cursor, next;
793 for (cursor = base; cursor < 0; cursor = next)
795 /* The dumb loop. */
796 unsigned char *nl = memchr (lim_addr + cursor, '\n', - cursor);
797 next = nl ? nl - lim_addr : 0;
799 /* If we're using the newline cache, cache the fact that
800 the region we just traversed is free of newlines. */
801 if (newline_cache && cursor != next)
803 know_region_cache (cache_buffer, newline_cache,
804 BYTE_TO_CHAR (lim_byte + cursor),
805 BYTE_TO_CHAR (lim_byte + next));
806 /* know_region_cache can relocate buffer text. */
807 lim_addr = BYTE_POS_ADDR (ceiling_byte) + 1;
810 if (! nl)
811 break;
812 next++;
814 if (--count == 0)
816 if (bytepos)
817 *bytepos = lim_byte + next;
818 return BYTE_TO_CHAR (lim_byte + next);
820 if (allow_quit)
821 maybe_quit ();
824 start_byte = lim_byte;
825 start = BYTE_TO_CHAR (start_byte);
828 else
829 while (start > end)
831 /* The last character to check before the next obstacle. */
832 ptrdiff_t tem, ceiling_byte = end_byte;
834 /* Consult the newline cache, if appropriate. */
835 if (newline_cache)
837 ptrdiff_t next_change;
838 int result = 1;
840 while (start > end && result)
842 ptrdiff_t lim1;
844 result = region_cache_backward (cache_buffer, newline_cache,
845 start, &next_change);
846 if (result)
848 start = next_change;
849 lim1 = next_change = end;
851 else
852 lim1 = max (next_change, end);
853 start_byte = CHAR_TO_BYTE (start);
854 while (start > lim1
855 && FETCH_BYTE (start_byte - 1) == '\n')
857 if (++count == 0)
859 if (bytepos)
860 *bytepos = start_byte;
861 return start;
863 start_byte--;
864 start--;
866 if (start > next_change && !result)
867 break;
868 result = 1;
870 if (start <= end)
872 start = end;
873 start_byte = end_byte;
874 break;
877 /* Start should never be at or before end. */
878 if (start_byte <= ceiling_byte)
879 start_byte = ceiling_byte + 1;
881 /* Now the text before start is an unknown region, and
882 next_change is the position of the next known region. */
883 ceiling_byte = max (CHAR_TO_BYTE (next_change), ceiling_byte);
885 else if (start_byte == -1)
886 start_byte = CHAR_TO_BYTE (start);
888 /* Stop scanning before the gap. */
889 tem = BUFFER_FLOOR_OF (start_byte - 1);
890 ceiling_byte = max (tem, ceiling_byte);
893 /* The termination address of the dumb loop. */
894 unsigned char *ceiling_addr = BYTE_POS_ADDR (ceiling_byte);
896 /* Offsets (relative to CEILING_ADDR and CEILING_BYTE) of
897 the base, the cursor, and the previous line. These
898 offsets are at least -1. */
899 ptrdiff_t base = start_byte - ceiling_byte;
900 ptrdiff_t cursor, prev;
902 for (cursor = base; 0 < cursor; cursor = prev)
904 unsigned char *nl = memrchr (ceiling_addr, '\n', cursor);
905 prev = nl ? nl - ceiling_addr : -1;
907 /* If we're looking for newlines, cache the fact that
908 this line's region is free of them. */
909 if (newline_cache && cursor != prev + 1)
911 know_region_cache (cache_buffer, newline_cache,
912 BYTE_TO_CHAR (ceiling_byte + prev + 1),
913 BYTE_TO_CHAR (ceiling_byte + cursor));
914 /* know_region_cache can relocate buffer text. */
915 ceiling_addr = BYTE_POS_ADDR (ceiling_byte);
918 if (! nl)
919 break;
921 if (++count >= 0)
923 if (bytepos)
924 *bytepos = ceiling_byte + prev + 1;
925 return BYTE_TO_CHAR (ceiling_byte + prev + 1);
927 if (allow_quit)
928 maybe_quit ();
931 start_byte = ceiling_byte;
932 start = BYTE_TO_CHAR (start_byte);
936 if (shortage)
937 *shortage = count * direction;
938 if (bytepos)
940 *bytepos = start_byte == -1 ? CHAR_TO_BYTE (start) : start_byte;
941 eassert (*bytepos == CHAR_TO_BYTE (start));
943 return start;
946 /* Search for COUNT instances of a line boundary.
947 Start at START. If COUNT is negative, search backwards.
949 We report the resulting position by calling TEMP_SET_PT_BOTH.
951 If we find COUNT instances. we position after (always after,
952 even if scanning backwards) the COUNTth match, and return 0.
954 If we don't find COUNT instances before reaching the end of the
955 buffer (or the beginning, if scanning backwards), we return
956 the number of line boundaries left unfound, and position at
957 the limit we bumped up against.
959 If ALLOW_QUIT, check for quitting. That's good to do
960 except in special cases. */
962 ptrdiff_t
963 scan_newline (ptrdiff_t start, ptrdiff_t start_byte,
964 ptrdiff_t limit, ptrdiff_t limit_byte,
965 ptrdiff_t count, bool allow_quit)
967 ptrdiff_t charpos, bytepos, shortage;
969 charpos = find_newline (start, start_byte, limit, limit_byte,
970 count, &shortage, &bytepos, allow_quit);
971 if (shortage)
972 TEMP_SET_PT_BOTH (limit, limit_byte);
973 else
974 TEMP_SET_PT_BOTH (charpos, bytepos);
975 return shortage;
978 /* Like above, but always scan from point and report the
979 resulting position in *CHARPOS and *BYTEPOS. */
981 ptrdiff_t
982 scan_newline_from_point (ptrdiff_t count, ptrdiff_t *charpos,
983 ptrdiff_t *bytepos)
985 ptrdiff_t shortage;
987 if (count <= 0)
988 *charpos = find_newline (PT, PT_BYTE, BEGV, BEGV_BYTE, count - 1,
989 &shortage, bytepos, 1);
990 else
991 *charpos = find_newline (PT, PT_BYTE, ZV, ZV_BYTE, count,
992 &shortage, bytepos, 1);
993 return shortage;
996 /* Like find_newline, but doesn't allow QUITting and doesn't return
997 SHORTAGE. */
998 ptrdiff_t
999 find_newline_no_quit (ptrdiff_t from, ptrdiff_t frombyte,
1000 ptrdiff_t cnt, ptrdiff_t *bytepos)
1002 return find_newline (from, frombyte, 0, -1, cnt, NULL, bytepos, 0);
1005 /* Like find_newline, but returns position before the newline, not
1006 after, and only search up to TO.
1007 This isn't just find_newline_no_quit (...)-1, because you might hit TO. */
1009 ptrdiff_t
1010 find_before_next_newline (ptrdiff_t from, ptrdiff_t to,
1011 ptrdiff_t cnt, ptrdiff_t *bytepos)
1013 ptrdiff_t shortage;
1014 ptrdiff_t pos = find_newline (from, -1, to, -1, cnt, &shortage, bytepos, 1);
1016 if (shortage == 0)
1018 if (bytepos)
1019 DEC_BOTH (pos, *bytepos);
1020 else
1021 pos--;
1023 return pos;
1026 /* Subroutines of Lisp buffer search functions. */
1028 static Lisp_Object
1029 search_command (Lisp_Object string, Lisp_Object bound, Lisp_Object noerror,
1030 Lisp_Object count, int direction, int RE, bool posix)
1032 EMACS_INT np;
1033 EMACS_INT lim;
1034 ptrdiff_t lim_byte;
1035 EMACS_INT n = direction;
1037 if (!NILP (count))
1039 CHECK_NUMBER (count);
1040 n *= XINT (count);
1043 CHECK_STRING (string);
1044 if (NILP (bound))
1046 if (n > 0)
1047 lim = ZV, lim_byte = ZV_BYTE;
1048 else
1049 lim = BEGV, lim_byte = BEGV_BYTE;
1051 else
1053 CHECK_NUMBER_COERCE_MARKER (bound);
1054 lim = XINT (bound);
1055 if (n > 0 ? lim < PT : lim > PT)
1056 error ("Invalid search bound (wrong side of point)");
1057 if (lim > ZV)
1058 lim = ZV, lim_byte = ZV_BYTE;
1059 else if (lim < BEGV)
1060 lim = BEGV, lim_byte = BEGV_BYTE;
1061 else
1062 lim_byte = CHAR_TO_BYTE (lim);
1065 /* This is so set_image_of_range_1 in regex.c can find the EQV table. */
1066 set_char_table_extras (BVAR (current_buffer, case_canon_table), 2,
1067 BVAR (current_buffer, case_eqv_table));
1069 np = search_buffer (string, PT, PT_BYTE, lim, lim_byte, n, RE,
1070 (!NILP (BVAR (current_buffer, case_fold_search))
1071 ? BVAR (current_buffer, case_canon_table)
1072 : Qnil),
1073 (!NILP (BVAR (current_buffer, case_fold_search))
1074 ? BVAR (current_buffer, case_eqv_table)
1075 : Qnil),
1076 posix);
1077 if (np <= 0)
1079 if (NILP (noerror))
1080 xsignal1 (Qsearch_failed, string);
1082 if (!EQ (noerror, Qt))
1084 eassert (BEGV <= lim && lim <= ZV);
1085 SET_PT_BOTH (lim, lim_byte);
1086 return Qnil;
1087 #if 0 /* This would be clean, but maybe programs depend on
1088 a value of nil here. */
1089 np = lim;
1090 #endif
1092 else
1093 return Qnil;
1096 eassert (BEGV <= np && np <= ZV);
1097 SET_PT (np);
1099 return make_number (np);
1102 /* Return true if REGEXP it matches just one constant string. */
1104 static bool
1105 trivial_regexp_p (Lisp_Object regexp)
1107 ptrdiff_t len = SBYTES (regexp);
1108 unsigned char *s = SDATA (regexp);
1109 while (--len >= 0)
1111 switch (*s++)
1113 case '.': case '*': case '+': case '?': case '[': case '^': case '$':
1114 return 0;
1115 case '\\':
1116 if (--len < 0)
1117 return 0;
1118 switch (*s++)
1120 case '|': case '(': case ')': case '`': case '\'': case 'b':
1121 case 'B': case '<': case '>': case 'w': case 'W': case 's':
1122 case 'S': case '=': case '{': case '}': case '_':
1123 case 'c': case 'C': /* for categoryspec and notcategoryspec */
1124 case '1': case '2': case '3': case '4': case '5':
1125 case '6': case '7': case '8': case '9':
1126 return 0;
1130 return 1;
1133 /* Search for the n'th occurrence of STRING in the current buffer,
1134 starting at position POS and stopping at position LIM,
1135 treating STRING as a literal string if RE is false or as
1136 a regular expression if RE is true.
1138 If N is positive, searching is forward and LIM must be greater than POS.
1139 If N is negative, searching is backward and LIM must be less than POS.
1141 Returns -x if x occurrences remain to be found (x > 0),
1142 or else the position at the beginning of the Nth occurrence
1143 (if searching backward) or the end (if searching forward).
1145 POSIX is nonzero if we want full backtracking (POSIX style)
1146 for this pattern. 0 means backtrack only enough to get a valid match. */
1148 #define TRANSLATE(out, trt, d) \
1149 do \
1151 if (! NILP (trt)) \
1153 Lisp_Object temp; \
1154 temp = Faref (trt, make_number (d)); \
1155 if (INTEGERP (temp)) \
1156 out = XINT (temp); \
1157 else \
1158 out = d; \
1160 else \
1161 out = d; \
1163 while (0)
1165 /* Only used in search_buffer, to record the end position of the match
1166 when searching regexps and SEARCH_REGS should not be changed
1167 (i.e. Vinhibit_changing_match_data is non-nil). */
1168 static struct re_registers search_regs_1;
1170 static EMACS_INT
1171 search_buffer_re (Lisp_Object string, ptrdiff_t pos, ptrdiff_t pos_byte,
1172 ptrdiff_t lim, ptrdiff_t lim_byte, EMACS_INT n,
1173 Lisp_Object trt, Lisp_Object inverse_trt, bool posix)
1175 unsigned char *p1, *p2;
1176 ptrdiff_t s1, s2;
1178 /* Snapshot in case Lisp changes the value. */
1179 bool preserve_match_data = NILP (Vinhibit_changing_match_data);
1181 struct regexp_cache *cache_entry =
1182 compile_pattern (string,
1183 preserve_match_data ? &search_regs : &search_regs_1,
1184 trt, posix,
1185 !NILP (BVAR (current_buffer, enable_multibyte_characters)));
1186 struct re_pattern_buffer *bufp = &cache_entry->buf;
1188 maybe_quit (); /* Do a pending quit right away,
1189 to avoid paradoxical behavior */
1190 /* Get pointers and sizes of the two strings
1191 that make up the visible portion of the buffer. */
1193 p1 = BEGV_ADDR;
1194 s1 = GPT_BYTE - BEGV_BYTE;
1195 p2 = GAP_END_ADDR;
1196 s2 = ZV_BYTE - GPT_BYTE;
1197 if (s1 < 0)
1199 p2 = p1;
1200 s2 = ZV_BYTE - BEGV_BYTE;
1201 s1 = 0;
1203 if (s2 < 0)
1205 s1 = ZV_BYTE - BEGV_BYTE;
1206 s2 = 0;
1209 ptrdiff_t count = SPECPDL_INDEX ();
1210 freeze_buffer_relocation ();
1211 freeze_pattern (cache_entry);
1213 while (n < 0)
1215 ptrdiff_t val;
1217 re_match_object = Qnil;
1218 val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
1219 pos_byte - BEGV_BYTE, lim_byte - pos_byte,
1220 preserve_match_data ? &search_regs : &search_regs_1,
1221 /* Don't allow match past current point */
1222 pos_byte - BEGV_BYTE);
1223 if (val == -2)
1225 matcher_overflow ();
1227 if (val >= 0)
1229 if (preserve_match_data)
1231 pos_byte = search_regs.start[0] + BEGV_BYTE;
1232 for (ptrdiff_t i = 0; i < search_regs.num_regs; i++)
1233 if (search_regs.start[i] >= 0)
1235 search_regs.start[i]
1236 = BYTE_TO_CHAR (search_regs.start[i] + BEGV_BYTE);
1237 search_regs.end[i]
1238 = BYTE_TO_CHAR (search_regs.end[i] + BEGV_BYTE);
1240 XSETBUFFER (last_thing_searched, current_buffer);
1241 /* Set pos to the new position. */
1242 pos = search_regs.start[0];
1244 else
1246 pos_byte = search_regs_1.start[0] + BEGV_BYTE;
1247 /* Set pos to the new position. */
1248 pos = BYTE_TO_CHAR (search_regs_1.start[0] + BEGV_BYTE);
1251 else
1253 unbind_to (count, Qnil);
1254 return (n);
1256 n++;
1257 maybe_quit ();
1259 while (n > 0)
1261 ptrdiff_t val;
1263 re_match_object = Qnil;
1264 val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
1265 pos_byte - BEGV_BYTE, lim_byte - pos_byte,
1266 preserve_match_data ? &search_regs : &search_regs_1,
1267 lim_byte - BEGV_BYTE);
1268 if (val == -2)
1270 matcher_overflow ();
1272 if (val >= 0)
1274 if (preserve_match_data)
1276 pos_byte = search_regs.end[0] + BEGV_BYTE;
1277 for (ptrdiff_t i = 0; i < search_regs.num_regs; i++)
1278 if (search_regs.start[i] >= 0)
1280 search_regs.start[i]
1281 = BYTE_TO_CHAR (search_regs.start[i] + BEGV_BYTE);
1282 search_regs.end[i]
1283 = BYTE_TO_CHAR (search_regs.end[i] + BEGV_BYTE);
1285 XSETBUFFER (last_thing_searched, current_buffer);
1286 pos = search_regs.end[0];
1288 else
1290 pos_byte = search_regs_1.end[0] + BEGV_BYTE;
1291 pos = BYTE_TO_CHAR (search_regs_1.end[0] + BEGV_BYTE);
1294 else
1296 unbind_to (count, Qnil);
1297 return (0 - n);
1299 n--;
1300 maybe_quit ();
1302 unbind_to (count, Qnil);
1303 return (pos);
1306 static EMACS_INT
1307 search_buffer_non_re (Lisp_Object string, ptrdiff_t pos,
1308 ptrdiff_t pos_byte, ptrdiff_t lim, ptrdiff_t lim_byte,
1309 EMACS_INT n, int RE, Lisp_Object trt, Lisp_Object inverse_trt,
1310 bool posix)
1312 unsigned char *raw_pattern, *pat;
1313 ptrdiff_t raw_pattern_size;
1314 ptrdiff_t raw_pattern_size_byte;
1315 unsigned char *patbuf;
1316 bool multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
1317 unsigned char *base_pat;
1318 /* Set to positive if we find a non-ASCII char that need
1319 translation. Otherwise set to zero later. */
1320 int char_base = -1;
1321 bool boyer_moore_ok = 1;
1322 USE_SAFE_ALLOCA;
1324 /* MULTIBYTE says whether the text to be searched is multibyte.
1325 We must convert PATTERN to match that, or we will not really
1326 find things right. */
1328 if (multibyte == STRING_MULTIBYTE (string))
1330 raw_pattern = SDATA (string);
1331 raw_pattern_size = SCHARS (string);
1332 raw_pattern_size_byte = SBYTES (string);
1334 else if (multibyte)
1336 raw_pattern_size = SCHARS (string);
1337 raw_pattern_size_byte
1338 = count_size_as_multibyte (SDATA (string),
1339 raw_pattern_size);
1340 raw_pattern = SAFE_ALLOCA (raw_pattern_size_byte + 1);
1341 copy_text (SDATA (string), raw_pattern,
1342 SCHARS (string), 0, 1);
1344 else
1346 /* Converting multibyte to single-byte.
1348 ??? Perhaps this conversion should be done in a special way
1349 by subtracting nonascii-insert-offset from each non-ASCII char,
1350 so that only the multibyte chars which really correspond to
1351 the chosen single-byte character set can possibly match. */
1352 raw_pattern_size = SCHARS (string);
1353 raw_pattern_size_byte = SCHARS (string);
1354 raw_pattern = SAFE_ALLOCA (raw_pattern_size + 1);
1355 copy_text (SDATA (string), raw_pattern,
1356 SBYTES (string), 1, 0);
1359 /* Copy and optionally translate the pattern. */
1360 ptrdiff_t len = raw_pattern_size;
1361 ptrdiff_t len_byte = raw_pattern_size_byte;
1362 SAFE_NALLOCA (patbuf, MAX_MULTIBYTE_LENGTH, len);
1363 pat = patbuf;
1364 base_pat = raw_pattern;
1365 if (multibyte)
1367 /* Fill patbuf by translated characters in STRING while
1368 checking if we can use boyer-moore search. If TRT is
1369 non-nil, we can use boyer-moore search only if TRT can be
1370 represented by the byte array of 256 elements. For that,
1371 all non-ASCII case-equivalents of all case-sensitive
1372 characters in STRING must belong to the same character
1373 group (two characters belong to the same group iff their
1374 multibyte forms are the same except for the last byte;
1375 i.e. every 64 characters form a group; U+0000..U+003F,
1376 U+0040..U+007F, U+0080..U+00BF, ...). */
1378 while (--len >= 0)
1380 unsigned char str_base[MAX_MULTIBYTE_LENGTH], *str;
1381 int c, translated, inverse;
1382 int in_charlen, charlen;
1384 /* If we got here and the RE flag is set, it's because we're
1385 dealing with a regexp known to be trivial, so the backslash
1386 just quotes the next character. */
1387 if (RE && *base_pat == '\\')
1389 len--;
1390 raw_pattern_size--;
1391 len_byte--;
1392 base_pat++;
1395 c = STRING_CHAR_AND_LENGTH (base_pat, in_charlen);
1397 if (NILP (trt))
1399 str = base_pat;
1400 charlen = in_charlen;
1402 else
1404 /* Translate the character. */
1405 TRANSLATE (translated, trt, c);
1406 charlen = CHAR_STRING (translated, str_base);
1407 str = str_base;
1409 /* Check if C has any other case-equivalents. */
1410 TRANSLATE (inverse, inverse_trt, c);
1411 /* If so, check if we can use boyer-moore. */
1412 if (c != inverse && boyer_moore_ok)
1414 /* Check if all equivalents belong to the same
1415 group of characters. Note that the check of C
1416 itself is done by the last iteration. */
1417 int this_char_base = -1;
1419 while (boyer_moore_ok)
1421 if (ASCII_CHAR_P (inverse))
1423 if (this_char_base > 0)
1424 boyer_moore_ok = 0;
1425 else
1426 this_char_base = 0;
1428 else if (CHAR_BYTE8_P (inverse))
1429 /* Boyer-moore search can't handle a
1430 translation of an eight-bit
1431 character. */
1432 boyer_moore_ok = 0;
1433 else if (this_char_base < 0)
1435 this_char_base = inverse & ~0x3F;
1436 if (char_base < 0)
1437 char_base = this_char_base;
1438 else if (this_char_base != char_base)
1439 boyer_moore_ok = 0;
1441 else if ((inverse & ~0x3F) != this_char_base)
1442 boyer_moore_ok = 0;
1443 if (c == inverse)
1444 break;
1445 TRANSLATE (inverse, inverse_trt, inverse);
1450 /* Store this character into the translated pattern. */
1451 memcpy (pat, str, charlen);
1452 pat += charlen;
1453 base_pat += in_charlen;
1454 len_byte -= in_charlen;
1457 /* If char_base is still negative we didn't find any translated
1458 non-ASCII characters. */
1459 if (char_base < 0)
1460 char_base = 0;
1462 else
1464 /* Unibyte buffer. */
1465 char_base = 0;
1466 while (--len >= 0)
1468 int c, translated, inverse;
1470 /* If we got here and the RE flag is set, it's because we're
1471 dealing with a regexp known to be trivial, so the backslash
1472 just quotes the next character. */
1473 if (RE && *base_pat == '\\')
1475 len--;
1476 raw_pattern_size--;
1477 base_pat++;
1479 c = *base_pat++;
1480 TRANSLATE (translated, trt, c);
1481 *pat++ = translated;
1482 /* Check that none of C's equivalents violates the
1483 assumptions of boyer_moore. */
1484 TRANSLATE (inverse, inverse_trt, c);
1485 while (1)
1487 if (inverse >= 0200)
1489 boyer_moore_ok = 0;
1490 break;
1492 if (c == inverse)
1493 break;
1494 TRANSLATE (inverse, inverse_trt, inverse);
1499 len_byte = pat - patbuf;
1500 pat = base_pat = patbuf;
1502 EMACS_INT result
1503 = (boyer_moore_ok
1504 ? boyer_moore (n, pat, len_byte, trt, inverse_trt,
1505 pos_byte, lim_byte,
1506 char_base)
1507 : simple_search (n, pat, raw_pattern_size, len_byte, trt,
1508 pos, pos_byte, lim, lim_byte));
1509 SAFE_FREE ();
1510 return result;
1513 static EMACS_INT
1514 search_buffer (Lisp_Object string, ptrdiff_t pos, ptrdiff_t pos_byte,
1515 ptrdiff_t lim, ptrdiff_t lim_byte, EMACS_INT n,
1516 int RE, Lisp_Object trt, Lisp_Object inverse_trt, bool posix)
1518 if (running_asynch_code)
1519 save_search_regs ();
1521 /* Searching 0 times means don't move. */
1522 /* Null string is found at starting position. */
1523 if (n == 0 || SCHARS (string) == 0)
1525 set_search_regs (pos_byte, 0);
1526 return pos;
1529 if (RE && !(trivial_regexp_p (string) && NILP (Vsearch_spaces_regexp)))
1530 pos = search_buffer_re (string, pos, pos_byte, lim, lim_byte,
1531 n, trt, inverse_trt, posix);
1532 else
1533 pos = search_buffer_non_re (string, pos, pos_byte, lim, lim_byte,
1534 n, RE, trt, inverse_trt, posix);
1536 return pos;
1539 /* Do a simple string search N times for the string PAT,
1540 whose length is LEN/LEN_BYTE,
1541 from buffer position POS/POS_BYTE until LIM/LIM_BYTE.
1542 TRT is the translation table.
1544 Return the character position where the match is found.
1545 Otherwise, if M matches remained to be found, return -M.
1547 This kind of search works regardless of what is in PAT and
1548 regardless of what is in TRT. It is used in cases where
1549 boyer_moore cannot work. */
1551 static EMACS_INT
1552 simple_search (EMACS_INT n, unsigned char *pat,
1553 ptrdiff_t len, ptrdiff_t len_byte, Lisp_Object trt,
1554 ptrdiff_t pos, ptrdiff_t pos_byte,
1555 ptrdiff_t lim, ptrdiff_t lim_byte)
1557 bool multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
1558 bool forward = n > 0;
1559 /* Number of buffer bytes matched. Note that this may be different
1560 from len_byte in a multibyte buffer. */
1561 ptrdiff_t match_byte = PTRDIFF_MIN;
1563 if (lim > pos && multibyte)
1564 while (n > 0)
1566 while (1)
1568 /* Try matching at position POS. */
1569 ptrdiff_t this_pos = pos;
1570 ptrdiff_t this_pos_byte = pos_byte;
1571 ptrdiff_t this_len = len;
1572 unsigned char *p = pat;
1573 if (pos + len > lim || pos_byte + len_byte > lim_byte)
1574 goto stop;
1576 while (this_len > 0)
1578 int charlen, buf_charlen;
1579 int pat_ch, buf_ch;
1581 pat_ch = STRING_CHAR_AND_LENGTH (p, charlen);
1582 buf_ch = STRING_CHAR_AND_LENGTH (BYTE_POS_ADDR (this_pos_byte),
1583 buf_charlen);
1584 TRANSLATE (buf_ch, trt, buf_ch);
1586 if (buf_ch != pat_ch)
1587 break;
1589 this_len--;
1590 p += charlen;
1592 this_pos_byte += buf_charlen;
1593 this_pos++;
1596 if (this_len == 0)
1598 match_byte = this_pos_byte - pos_byte;
1599 pos += len;
1600 pos_byte += match_byte;
1601 break;
1604 INC_BOTH (pos, pos_byte);
1607 n--;
1609 else if (lim > pos)
1610 while (n > 0)
1612 while (1)
1614 /* Try matching at position POS. */
1615 ptrdiff_t this_pos = pos;
1616 ptrdiff_t this_len = len;
1617 unsigned char *p = pat;
1619 if (pos + len > lim)
1620 goto stop;
1622 while (this_len > 0)
1624 int pat_ch = *p++;
1625 int buf_ch = FETCH_BYTE (this_pos);
1626 TRANSLATE (buf_ch, trt, buf_ch);
1628 if (buf_ch != pat_ch)
1629 break;
1631 this_len--;
1632 this_pos++;
1635 if (this_len == 0)
1637 match_byte = len;
1638 pos += len;
1639 break;
1642 pos++;
1645 n--;
1647 /* Backwards search. */
1648 else if (lim < pos && multibyte)
1649 while (n < 0)
1651 while (1)
1653 /* Try matching at position POS. */
1654 ptrdiff_t this_pos = pos;
1655 ptrdiff_t this_pos_byte = pos_byte;
1656 ptrdiff_t this_len = len;
1657 const unsigned char *p = pat + len_byte;
1659 if (this_pos - len < lim || (pos_byte - len_byte) < lim_byte)
1660 goto stop;
1662 while (this_len > 0)
1664 int pat_ch, buf_ch;
1666 DEC_BOTH (this_pos, this_pos_byte);
1667 PREV_CHAR_BOUNDARY (p, pat);
1668 pat_ch = STRING_CHAR (p);
1669 buf_ch = STRING_CHAR (BYTE_POS_ADDR (this_pos_byte));
1670 TRANSLATE (buf_ch, trt, buf_ch);
1672 if (buf_ch != pat_ch)
1673 break;
1675 this_len--;
1678 if (this_len == 0)
1680 match_byte = pos_byte - this_pos_byte;
1681 pos = this_pos;
1682 pos_byte = this_pos_byte;
1683 break;
1686 DEC_BOTH (pos, pos_byte);
1689 n++;
1691 else if (lim < pos)
1692 while (n < 0)
1694 while (1)
1696 /* Try matching at position POS. */
1697 ptrdiff_t this_pos = pos - len;
1698 ptrdiff_t this_len = len;
1699 unsigned char *p = pat;
1701 if (this_pos < lim)
1702 goto stop;
1704 while (this_len > 0)
1706 int pat_ch = *p++;
1707 int buf_ch = FETCH_BYTE (this_pos);
1708 TRANSLATE (buf_ch, trt, buf_ch);
1710 if (buf_ch != pat_ch)
1711 break;
1712 this_len--;
1713 this_pos++;
1716 if (this_len == 0)
1718 match_byte = len;
1719 pos -= len;
1720 break;
1723 pos--;
1726 n++;
1729 stop:
1730 if (n == 0)
1732 eassert (match_byte != PTRDIFF_MIN);
1733 if (forward)
1734 set_search_regs ((multibyte ? pos_byte : pos) - match_byte, match_byte);
1735 else
1736 set_search_regs (multibyte ? pos_byte : pos, match_byte);
1738 return pos;
1740 else if (n > 0)
1741 return -n;
1742 else
1743 return n;
1746 /* Do Boyer-Moore search N times for the string BASE_PAT,
1747 whose length is LEN_BYTE,
1748 from buffer position POS_BYTE until LIM_BYTE.
1749 DIRECTION says which direction we search in.
1750 TRT and INVERSE_TRT are translation tables.
1751 Characters in PAT are already translated by TRT.
1753 This kind of search works if all the characters in BASE_PAT that
1754 have nontrivial translation are the same aside from the last byte.
1755 This makes it possible to translate just the last byte of a
1756 character, and do so after just a simple test of the context.
1757 CHAR_BASE is nonzero if there is such a non-ASCII character.
1759 If that criterion is not satisfied, do not call this function. */
1761 static EMACS_INT
1762 boyer_moore (EMACS_INT n, unsigned char *base_pat,
1763 ptrdiff_t len_byte,
1764 Lisp_Object trt, Lisp_Object inverse_trt,
1765 ptrdiff_t pos_byte, ptrdiff_t lim_byte,
1766 int char_base)
1768 int direction = ((n > 0) ? 1 : -1);
1769 register ptrdiff_t dirlen;
1770 ptrdiff_t limit;
1771 int stride_for_teases = 0;
1772 int BM_tab[0400];
1773 register unsigned char *cursor, *p_limit;
1774 register ptrdiff_t i;
1775 register int j;
1776 unsigned char *pat, *pat_end;
1777 bool multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
1779 unsigned char simple_translate[0400];
1780 /* These are set to the preceding bytes of a byte to be translated
1781 if char_base is nonzero. As the maximum byte length of a
1782 multibyte character is 5, we have to check at most four previous
1783 bytes. */
1784 int translate_prev_byte1 = 0;
1785 int translate_prev_byte2 = 0;
1786 int translate_prev_byte3 = 0;
1788 /* The general approach is that we are going to maintain that we know
1789 the first (closest to the present position, in whatever direction
1790 we're searching) character that could possibly be the last
1791 (furthest from present position) character of a valid match. We
1792 advance the state of our knowledge by looking at that character
1793 and seeing whether it indeed matches the last character of the
1794 pattern. If it does, we take a closer look. If it does not, we
1795 move our pointer (to putative last characters) as far as is
1796 logically possible. This amount of movement, which I call a
1797 stride, will be the length of the pattern if the actual character
1798 appears nowhere in the pattern, otherwise it will be the distance
1799 from the last occurrence of that character to the end of the
1800 pattern. If the amount is zero we have a possible match. */
1802 /* Here we make a "mickey mouse" BM table. The stride of the search
1803 is determined only by the last character of the putative match.
1804 If that character does not match, we will stride the proper
1805 distance to propose a match that superimposes it on the last
1806 instance of a character that matches it (per trt), or misses
1807 it entirely if there is none. */
1809 dirlen = len_byte * direction;
1811 /* Record position after the end of the pattern. */
1812 pat_end = base_pat + len_byte;
1813 /* BASE_PAT points to a character that we start scanning from.
1814 It is the first character in a forward search,
1815 the last character in a backward search. */
1816 if (direction < 0)
1817 base_pat = pat_end - 1;
1819 /* A character that does not appear in the pattern induces a
1820 stride equal to the pattern length. */
1821 for (i = 0; i < 0400; i++)
1822 BM_tab[i] = dirlen;
1824 /* We use this for translation, instead of TRT itself.
1825 We fill this in to handle the characters that actually
1826 occur in the pattern. Others don't matter anyway! */
1827 for (i = 0; i < 0400; i++)
1828 simple_translate[i] = i;
1830 if (char_base)
1832 /* Setup translate_prev_byte1/2/3/4 from CHAR_BASE. Only a
1833 byte following them are the target of translation. */
1834 eassume (0x80 <= char_base && char_base <= MAX_CHAR);
1835 unsigned char str[MAX_MULTIBYTE_LENGTH];
1836 int cblen = CHAR_STRING (char_base, str);
1838 translate_prev_byte1 = str[cblen - 2];
1839 if (cblen > 2)
1841 translate_prev_byte2 = str[cblen - 3];
1842 if (cblen > 3)
1843 translate_prev_byte3 = str[cblen - 4];
1847 i = 0;
1848 while (i != dirlen)
1850 unsigned char *ptr = base_pat + i;
1851 i += direction;
1852 if (! NILP (trt))
1854 /* If the byte currently looking at is the last of a
1855 character to check case-equivalents, set CH to that
1856 character. An ASCII character and a non-ASCII character
1857 matching with CHAR_BASE are to be checked. */
1858 int ch = -1;
1860 if (ASCII_CHAR_P (*ptr) || ! multibyte)
1861 ch = *ptr;
1862 else if (char_base
1863 && ((pat_end - ptr) == 1 || CHAR_HEAD_P (ptr[1])))
1865 unsigned char *charstart = ptr - 1;
1867 while (! (CHAR_HEAD_P (*charstart)))
1868 charstart--;
1869 ch = STRING_CHAR (charstart);
1870 if (char_base != (ch & ~0x3F))
1871 ch = -1;
1874 if (ch >= 0200 && multibyte)
1875 j = (ch & 0x3F) | 0200;
1876 else
1877 j = *ptr;
1879 if (i == dirlen)
1880 stride_for_teases = BM_tab[j];
1882 BM_tab[j] = dirlen - i;
1883 /* A translation table is accompanied by its inverse -- see
1884 comment following downcase_table for details. */
1885 if (ch >= 0)
1887 int starting_ch = ch;
1888 int starting_j = j;
1890 while (1)
1892 TRANSLATE (ch, inverse_trt, ch);
1893 if (ch >= 0200 && multibyte)
1894 j = (ch & 0x3F) | 0200;
1895 else
1896 j = ch;
1898 /* For all the characters that map into CH,
1899 set up simple_translate to map the last byte
1900 into STARTING_J. */
1901 simple_translate[j] = starting_j;
1902 if (ch == starting_ch)
1903 break;
1904 BM_tab[j] = dirlen - i;
1908 else
1910 j = *ptr;
1912 if (i == dirlen)
1913 stride_for_teases = BM_tab[j];
1914 BM_tab[j] = dirlen - i;
1916 /* stride_for_teases tells how much to stride if we get a
1917 match on the far character but are subsequently
1918 disappointed, by recording what the stride would have been
1919 for that character if the last character had been
1920 different. */
1922 pos_byte += dirlen - ((direction > 0) ? direction : 0);
1923 /* loop invariant - POS_BYTE points at where last char (first
1924 char if reverse) of pattern would align in a possible match. */
1925 while (n != 0)
1927 ptrdiff_t tail_end;
1928 unsigned char *tail_end_ptr;
1930 /* It's been reported that some (broken) compiler thinks that
1931 Boolean expressions in an arithmetic context are unsigned.
1932 Using an explicit ?1:0 prevents this. */
1933 if ((lim_byte - pos_byte - ((direction > 0) ? 1 : 0)) * direction
1934 < 0)
1935 return (n * (0 - direction));
1936 /* First we do the part we can by pointers (maybe nothing) */
1937 maybe_quit ();
1938 pat = base_pat;
1939 limit = pos_byte - dirlen + direction;
1940 if (direction > 0)
1942 limit = BUFFER_CEILING_OF (limit);
1943 /* LIMIT is now the last (not beyond-last!) value POS_BYTE
1944 can take on without hitting edge of buffer or the gap. */
1945 limit = min (limit, pos_byte + 20000);
1946 limit = min (limit, lim_byte - 1);
1948 else
1950 limit = BUFFER_FLOOR_OF (limit);
1951 /* LIMIT is now the last (not beyond-last!) value POS_BYTE
1952 can take on without hitting edge of buffer or the gap. */
1953 limit = max (limit, pos_byte - 20000);
1954 limit = max (limit, lim_byte);
1956 tail_end = BUFFER_CEILING_OF (pos_byte) + 1;
1957 tail_end_ptr = BYTE_POS_ADDR (tail_end);
1959 if ((limit - pos_byte) * direction > 20)
1961 unsigned char *p2;
1963 p_limit = BYTE_POS_ADDR (limit);
1964 p2 = (cursor = BYTE_POS_ADDR (pos_byte));
1965 /* In this loop, pos + cursor - p2 is the surrogate for pos. */
1966 while (1) /* use one cursor setting as long as i can */
1968 if (direction > 0) /* worth duplicating */
1970 while (cursor <= p_limit)
1972 if (BM_tab[*cursor] == 0)
1973 goto hit;
1974 cursor += BM_tab[*cursor];
1977 else
1979 while (cursor >= p_limit)
1981 if (BM_tab[*cursor] == 0)
1982 goto hit;
1983 cursor += BM_tab[*cursor];
1986 /* If you are here, cursor is beyond the end of the
1987 searched region. You fail to match within the
1988 permitted region and would otherwise try a character
1989 beyond that region. */
1990 break;
1992 hit:
1993 i = dirlen - direction;
1994 if (! NILP (trt))
1996 while ((i -= direction) + direction != 0)
1998 int ch;
1999 cursor -= direction;
2000 /* Translate only the last byte of a character. */
2001 if (! multibyte
2002 || ((cursor == tail_end_ptr
2003 || CHAR_HEAD_P (cursor[1]))
2004 && (CHAR_HEAD_P (cursor[0])
2005 /* Check if this is the last byte of
2006 a translatable character. */
2007 || (translate_prev_byte1 == cursor[-1]
2008 && (CHAR_HEAD_P (translate_prev_byte1)
2009 || (translate_prev_byte2 == cursor[-2]
2010 && (CHAR_HEAD_P (translate_prev_byte2)
2011 || (translate_prev_byte3 == cursor[-3]))))))))
2012 ch = simple_translate[*cursor];
2013 else
2014 ch = *cursor;
2015 if (pat[i] != ch)
2016 break;
2019 else
2021 while ((i -= direction) + direction != 0)
2023 cursor -= direction;
2024 if (pat[i] != *cursor)
2025 break;
2028 cursor += dirlen - i - direction; /* fix cursor */
2029 if (i + direction == 0)
2031 ptrdiff_t position, start, end;
2032 #ifdef REL_ALLOC
2033 ptrdiff_t cursor_off;
2034 #endif
2036 cursor -= direction;
2038 position = pos_byte + cursor - p2 + ((direction > 0)
2039 ? 1 - len_byte : 0);
2040 #ifdef REL_ALLOC
2041 /* set_search_regs might call malloc, which could
2042 cause ralloc.c relocate buffer text. We need to
2043 update pointers into buffer text due to that. */
2044 cursor_off = cursor - p2;
2045 #endif
2046 set_search_regs (position, len_byte);
2047 #ifdef REL_ALLOC
2048 p_limit = BYTE_POS_ADDR (limit);
2049 p2 = BYTE_POS_ADDR (pos_byte);
2050 cursor = p2 + cursor_off;
2051 #endif
2053 if (NILP (Vinhibit_changing_match_data))
2055 start = search_regs.start[0];
2056 end = search_regs.end[0];
2058 else
2059 /* If Vinhibit_changing_match_data is non-nil,
2060 search_regs will not be changed. So let's
2061 compute start and end here. */
2063 start = BYTE_TO_CHAR (position);
2064 end = BYTE_TO_CHAR (position + len_byte);
2067 if ((n -= direction) != 0)
2068 cursor += dirlen; /* to resume search */
2069 else
2070 return direction > 0 ? end : start;
2072 else
2073 cursor += stride_for_teases; /* <sigh> we lose - */
2075 pos_byte += cursor - p2;
2077 else
2078 /* Now we'll pick up a clump that has to be done the hard
2079 way because it covers a discontinuity. */
2081 limit = ((direction > 0)
2082 ? BUFFER_CEILING_OF (pos_byte - dirlen + 1)
2083 : BUFFER_FLOOR_OF (pos_byte - dirlen - 1));
2084 limit = ((direction > 0)
2085 ? min (limit + len_byte, lim_byte - 1)
2086 : max (limit - len_byte, lim_byte));
2087 /* LIMIT is now the last value POS_BYTE can have
2088 and still be valid for a possible match. */
2089 while (1)
2091 /* This loop can be coded for space rather than
2092 speed because it will usually run only once.
2093 (the reach is at most len + 21, and typically
2094 does not exceed len). */
2095 while ((limit - pos_byte) * direction >= 0)
2097 int ch = FETCH_BYTE (pos_byte);
2098 if (BM_tab[ch] == 0)
2099 goto hit2;
2100 pos_byte += BM_tab[ch];
2102 break; /* ran off the end */
2104 hit2:
2105 /* Found what might be a match. */
2106 i = dirlen - direction;
2107 while ((i -= direction) + direction != 0)
2109 int ch;
2110 unsigned char *ptr;
2111 pos_byte -= direction;
2112 ptr = BYTE_POS_ADDR (pos_byte);
2113 /* Translate only the last byte of a character. */
2114 if (! multibyte
2115 || ((ptr == tail_end_ptr
2116 || CHAR_HEAD_P (ptr[1]))
2117 && (CHAR_HEAD_P (ptr[0])
2118 /* Check if this is the last byte of a
2119 translatable character. */
2120 || (translate_prev_byte1 == ptr[-1]
2121 && (CHAR_HEAD_P (translate_prev_byte1)
2122 || (translate_prev_byte2 == ptr[-2]
2123 && (CHAR_HEAD_P (translate_prev_byte2)
2124 || translate_prev_byte3 == ptr[-3])))))))
2125 ch = simple_translate[*ptr];
2126 else
2127 ch = *ptr;
2128 if (pat[i] != ch)
2129 break;
2131 /* Above loop has moved POS_BYTE part or all the way
2132 back to the first pos (last pos if reverse).
2133 Set it once again at the last (first if reverse) char. */
2134 pos_byte += dirlen - i - direction;
2135 if (i + direction == 0)
2137 ptrdiff_t position, start, end;
2138 pos_byte -= direction;
2140 position = pos_byte + ((direction > 0) ? 1 - len_byte : 0);
2141 set_search_regs (position, len_byte);
2143 if (NILP (Vinhibit_changing_match_data))
2145 start = search_regs.start[0];
2146 end = search_regs.end[0];
2148 else
2149 /* If Vinhibit_changing_match_data is non-nil,
2150 search_regs will not be changed. So let's
2151 compute start and end here. */
2153 start = BYTE_TO_CHAR (position);
2154 end = BYTE_TO_CHAR (position + len_byte);
2157 if ((n -= direction) != 0)
2158 pos_byte += dirlen; /* to resume search */
2159 else
2160 return direction > 0 ? end : start;
2162 else
2163 pos_byte += stride_for_teases;
2166 /* We have done one clump. Can we continue? */
2167 if ((lim_byte - pos_byte) * direction < 0)
2168 return ((0 - n) * direction);
2170 return BYTE_TO_CHAR (pos_byte);
2173 /* Record beginning BEG_BYTE and end BEG_BYTE + NBYTES
2174 for the overall match just found in the current buffer.
2175 Also clear out the match data for registers 1 and up. */
2177 static void
2178 set_search_regs (ptrdiff_t beg_byte, ptrdiff_t nbytes)
2180 ptrdiff_t i;
2182 if (!NILP (Vinhibit_changing_match_data))
2183 return;
2185 /* Make sure we have registers in which to store
2186 the match position. */
2187 if (search_regs.num_regs == 0)
2189 search_regs.start = xmalloc (2 * sizeof (regoff_t));
2190 search_regs.end = xmalloc (2 * sizeof (regoff_t));
2191 search_regs.num_regs = 2;
2194 /* Clear out the other registers. */
2195 for (i = 1; i < search_regs.num_regs; i++)
2197 search_regs.start[i] = -1;
2198 search_regs.end[i] = -1;
2201 search_regs.start[0] = BYTE_TO_CHAR (beg_byte);
2202 search_regs.end[0] = BYTE_TO_CHAR (beg_byte + nbytes);
2203 XSETBUFFER (last_thing_searched, current_buffer);
2206 DEFUN ("search-backward", Fsearch_backward, Ssearch_backward, 1, 4,
2207 "MSearch backward: ",
2208 doc: /* Search backward from point for STRING.
2209 Set point to the beginning of the occurrence found, and return point.
2210 An optional second argument bounds the search; it is a buffer position.
2211 The match found must not begin before that position. A value of nil
2212 means search to the beginning of the accessible portion of the buffer.
2213 Optional third argument, if t, means if fail just return nil (no error).
2214 If not nil and not t, position at limit of search and return nil.
2215 Optional fourth argument COUNT, if a positive number, means to search
2216 for COUNT successive occurrences. If COUNT is negative, search
2217 forward, instead of backward, for -COUNT occurrences. A value of
2218 nil means the same as 1.
2219 With COUNT positive, the match found is the COUNTth to last one (or
2220 last, if COUNT is 1 or nil) in the buffer located entirely before
2221 the origin of the search; correspondingly with COUNT negative.
2223 Search case-sensitivity is determined by the value of the variable
2224 `case-fold-search', which see.
2226 See also the functions `match-beginning', `match-end' and `replace-match'. */)
2227 (Lisp_Object string, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
2229 return search_command (string, bound, noerror, count, -1, 0, 0);
2232 DEFUN ("search-forward", Fsearch_forward, Ssearch_forward, 1, 4, "MSearch: ",
2233 doc: /* Search forward from point for STRING.
2234 Set point to the end of the occurrence found, and return point.
2235 An optional second argument bounds the search; it is a buffer position.
2236 The match found must not end after that position. A value of nil
2237 means search to the end of the accessible portion of the buffer.
2238 Optional third argument, if t, means if fail just return nil (no error).
2239 If not nil and not t, move to limit of search and return nil.
2240 Optional fourth argument COUNT, if a positive number, means to search
2241 for COUNT successive occurrences. If COUNT is negative, search
2242 backward, instead of forward, for -COUNT occurrences. A value of
2243 nil means the same as 1.
2244 With COUNT positive, the match found is the COUNTth one (or first,
2245 if COUNT is 1 or nil) in the buffer located entirely after the
2246 origin of the search; correspondingly with COUNT negative.
2248 Search case-sensitivity is determined by the value of the variable
2249 `case-fold-search', which see.
2251 See also the functions `match-beginning', `match-end' and `replace-match'. */)
2252 (Lisp_Object string, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
2254 return search_command (string, bound, noerror, count, 1, 0, 0);
2257 DEFUN ("re-search-backward", Fre_search_backward, Sre_search_backward, 1, 4,
2258 "sRE search backward: ",
2259 doc: /* Search backward from point for regular expression REGEXP.
2260 This function is almost identical to `re-search-forward', except that
2261 by default it searches backward instead of forward, and the sign of
2262 COUNT also indicates exactly the opposite searching direction.
2263 See `re-search-forward' for details.
2265 Note that searching backwards may give a shorter match than expected,
2266 because REGEXP is still matched in the forward direction. See Info
2267 anchor `(elisp) re-search-backward' for details. */)
2268 (Lisp_Object regexp, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
2270 return search_command (regexp, bound, noerror, count, -1, 1, 0);
2273 DEFUN ("re-search-forward", Fre_search_forward, Sre_search_forward, 1, 4,
2274 "sRE search: ",
2275 doc: /* Search forward from point for regular expression REGEXP.
2276 Set point to the end of the occurrence found, and return point.
2277 The optional second argument BOUND is a buffer position that bounds
2278 the search. The match found must not end after that position. A
2279 value of nil means search to the end of the accessible portion of
2280 the buffer.
2281 The optional third argument NOERROR indicates how errors are handled
2282 when the search fails. If it is nil or omitted, emit an error; if
2283 it is t, simply return nil and do nothing; if it is neither nil nor
2284 t, move to the limit of search and return nil.
2285 The optional fourth argument COUNT is a number that indicates the
2286 search direction and the number of occurrences to search for. If it
2287 is positive, search forward for COUNT successive occurrences; if it
2288 is negative, search backward, instead of forward, for -COUNT
2289 occurrences. A value of nil means the same as 1.
2290 With COUNT positive/negative, the match found is the COUNTth/-COUNTth
2291 one in the buffer located entirely after/before the origin of the
2292 search.
2294 Search case-sensitivity is determined by the value of the variable
2295 `case-fold-search', which see.
2297 See also the functions `match-beginning', `match-end', `match-string',
2298 and `replace-match'. */)
2299 (Lisp_Object regexp, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
2301 return search_command (regexp, bound, noerror, count, 1, 1, 0);
2304 DEFUN ("posix-search-backward", Fposix_search_backward, Sposix_search_backward, 1, 4,
2305 "sPosix search backward: ",
2306 doc: /* Search backward from point for match for regular expression REGEXP.
2307 Find the longest match in accord with Posix regular expression rules.
2308 Set point to the beginning of the occurrence found, and return point.
2309 An optional second argument bounds the search; it is a buffer position.
2310 The match found must not begin before that position. A value of nil
2311 means search to the beginning of the accessible portion of the buffer.
2312 Optional third argument, if t, means if fail just return nil (no error).
2313 If not nil and not t, position at limit of search and return nil.
2314 Optional fourth argument COUNT, if a positive number, means to search
2315 for COUNT successive occurrences. If COUNT is negative, search
2316 forward, instead of backward, for -COUNT occurrences. A value of
2317 nil means the same as 1.
2318 With COUNT positive, the match found is the COUNTth to last one (or
2319 last, if COUNT is 1 or nil) in the buffer located entirely before
2320 the origin of the search; correspondingly with COUNT negative.
2322 Search case-sensitivity is determined by the value of the variable
2323 `case-fold-search', which see.
2325 See also the functions `match-beginning', `match-end', `match-string',
2326 and `replace-match'. */)
2327 (Lisp_Object regexp, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
2329 return search_command (regexp, bound, noerror, count, -1, 1, 1);
2332 DEFUN ("posix-search-forward", Fposix_search_forward, Sposix_search_forward, 1, 4,
2333 "sPosix search: ",
2334 doc: /* Search forward from point for regular expression REGEXP.
2335 Find the longest match in accord with Posix regular expression rules.
2336 Set point to the end of the occurrence found, and return point.
2337 An optional second argument bounds the search; it is a buffer position.
2338 The match found must not end after that position. A value of nil
2339 means search to the end of the accessible portion of the buffer.
2340 Optional third argument, if t, means if fail just return nil (no error).
2341 If not nil and not t, move to limit of search and return nil.
2342 Optional fourth argument COUNT, if a positive number, means to search
2343 for COUNT successive occurrences. If COUNT is negative, search
2344 backward, instead of forward, for -COUNT occurrences. A value of
2345 nil means the same as 1.
2346 With COUNT positive, the match found is the COUNTth one (or first,
2347 if COUNT is 1 or nil) in the buffer located entirely after the
2348 origin of the search; correspondingly with COUNT negative.
2350 Search case-sensitivity is determined by the value of the variable
2351 `case-fold-search', which see.
2353 See also the functions `match-beginning', `match-end', `match-string',
2354 and `replace-match'. */)
2355 (Lisp_Object regexp, Lisp_Object bound, Lisp_Object noerror, Lisp_Object count)
2357 return search_command (regexp, bound, noerror, count, 1, 1, 1);
2360 DEFUN ("replace-match", Freplace_match, Sreplace_match, 1, 5, 0,
2361 doc: /* Replace text matched by last search with NEWTEXT.
2362 Leave point at the end of the replacement text.
2364 If optional second arg FIXEDCASE is non-nil, do not alter the case of
2365 the replacement text. Otherwise, maybe capitalize the whole text, or
2366 maybe just word initials, based on the replaced text. If the replaced
2367 text has only capital letters and has at least one multiletter word,
2368 convert NEWTEXT to all caps. Otherwise if all words are capitalized
2369 in the replaced text, capitalize each word in NEWTEXT.
2371 If optional third arg LITERAL is non-nil, insert NEWTEXT literally.
2372 Otherwise treat `\\' as special:
2373 `\\&' in NEWTEXT means substitute original matched text.
2374 `\\N' means substitute what matched the Nth `\\(...\\)'.
2375 If Nth parens didn't match, substitute nothing.
2376 `\\\\' means insert one `\\'.
2377 `\\?' is treated literally
2378 (for compatibility with `query-replace-regexp').
2379 Any other character following `\\' signals an error.
2380 Case conversion does not apply to these substitutions.
2382 If optional fourth argument STRING is non-nil, it should be a string
2383 to act on; this should be the string on which the previous match was
2384 done via `string-match'. In this case, `replace-match' creates and
2385 returns a new string, made by copying STRING and replacing the part of
2386 STRING that was matched (the original STRING itself is not altered).
2388 The optional fifth argument SUBEXP specifies a subexpression;
2389 it says to replace just that subexpression with NEWTEXT,
2390 rather than replacing the entire matched text.
2391 This is, in a vague sense, the inverse of using `\\N' in NEWTEXT;
2392 `\\N' copies subexp N into NEWTEXT, but using N as SUBEXP puts
2393 NEWTEXT in place of subexp N.
2394 This is useful only after a regular expression search or match,
2395 since only regular expressions have distinguished subexpressions. */)
2396 (Lisp_Object newtext, Lisp_Object fixedcase, Lisp_Object literal, Lisp_Object string, Lisp_Object subexp)
2398 enum { nochange, all_caps, cap_initial } case_action;
2399 ptrdiff_t pos, pos_byte;
2400 bool some_multiletter_word;
2401 bool some_lowercase;
2402 bool some_uppercase;
2403 bool some_nonuppercase_initial;
2404 int c, prevc;
2405 ptrdiff_t sub;
2406 ptrdiff_t opoint, newpoint;
2408 CHECK_STRING (newtext);
2410 if (! NILP (string))
2411 CHECK_STRING (string);
2413 case_action = nochange; /* We tried an initialization */
2414 /* but some C compilers blew it */
2416 if (search_regs.num_regs <= 0)
2417 error ("`replace-match' called before any match found");
2419 if (NILP (subexp))
2420 sub = 0;
2421 else
2423 CHECK_NUMBER (subexp);
2424 if (! (0 <= XINT (subexp) && XINT (subexp) < search_regs.num_regs))
2425 args_out_of_range (subexp, make_number (search_regs.num_regs));
2426 sub = XINT (subexp);
2429 if (NILP (string))
2431 if (search_regs.start[sub] < BEGV
2432 || search_regs.start[sub] > search_regs.end[sub]
2433 || search_regs.end[sub] > ZV)
2434 args_out_of_range (make_number (search_regs.start[sub]),
2435 make_number (search_regs.end[sub]));
2437 else
2439 if (search_regs.start[sub] < 0
2440 || search_regs.start[sub] > search_regs.end[sub]
2441 || search_regs.end[sub] > SCHARS (string))
2442 args_out_of_range (make_number (search_regs.start[sub]),
2443 make_number (search_regs.end[sub]));
2446 if (NILP (fixedcase))
2448 /* Decide how to casify by examining the matched text. */
2449 ptrdiff_t last;
2451 pos = search_regs.start[sub];
2452 last = search_regs.end[sub];
2454 if (NILP (string))
2455 pos_byte = CHAR_TO_BYTE (pos);
2456 else
2457 pos_byte = string_char_to_byte (string, pos);
2459 prevc = '\n';
2460 case_action = all_caps;
2462 /* some_multiletter_word is set nonzero if any original word
2463 is more than one letter long. */
2464 some_multiletter_word = 0;
2465 some_lowercase = 0;
2466 some_nonuppercase_initial = 0;
2467 some_uppercase = 0;
2469 while (pos < last)
2471 if (NILP (string))
2473 c = FETCH_CHAR_AS_MULTIBYTE (pos_byte);
2474 INC_BOTH (pos, pos_byte);
2476 else
2477 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c, string, pos, pos_byte);
2479 if (lowercasep (c))
2481 /* Cannot be all caps if any original char is lower case */
2483 some_lowercase = 1;
2484 if (SYNTAX (prevc) != Sword)
2485 some_nonuppercase_initial = 1;
2486 else
2487 some_multiletter_word = 1;
2489 else if (uppercasep (c))
2491 some_uppercase = 1;
2492 if (SYNTAX (prevc) != Sword)
2494 else
2495 some_multiletter_word = 1;
2497 else
2499 /* If the initial is a caseless word constituent,
2500 treat that like a lowercase initial. */
2501 if (SYNTAX (prevc) != Sword)
2502 some_nonuppercase_initial = 1;
2505 prevc = c;
2508 /* Convert to all caps if the old text is all caps
2509 and has at least one multiletter word. */
2510 if (! some_lowercase && some_multiletter_word)
2511 case_action = all_caps;
2512 /* Capitalize each word, if the old text has all capitalized words. */
2513 else if (!some_nonuppercase_initial && some_multiletter_word)
2514 case_action = cap_initial;
2515 else if (!some_nonuppercase_initial && some_uppercase)
2516 /* Should x -> yz, operating on X, give Yz or YZ?
2517 We'll assume the latter. */
2518 case_action = all_caps;
2519 else
2520 case_action = nochange;
2523 /* Do replacement in a string. */
2524 if (!NILP (string))
2526 Lisp_Object before, after;
2528 before = Fsubstring (string, make_number (0),
2529 make_number (search_regs.start[sub]));
2530 after = Fsubstring (string, make_number (search_regs.end[sub]), Qnil);
2532 /* Substitute parts of the match into NEWTEXT
2533 if desired. */
2534 if (NILP (literal))
2536 ptrdiff_t lastpos = 0;
2537 ptrdiff_t lastpos_byte = 0;
2538 /* We build up the substituted string in ACCUM. */
2539 Lisp_Object accum;
2540 Lisp_Object middle;
2541 ptrdiff_t length = SBYTES (newtext);
2543 accum = Qnil;
2545 for (pos_byte = 0, pos = 0; pos_byte < length;)
2547 ptrdiff_t substart = -1;
2548 ptrdiff_t subend = 0;
2549 bool delbackslash = 0;
2551 FETCH_STRING_CHAR_ADVANCE (c, newtext, pos, pos_byte);
2553 if (c == '\\')
2555 FETCH_STRING_CHAR_ADVANCE (c, newtext, pos, pos_byte);
2557 if (c == '&')
2559 substart = search_regs.start[sub];
2560 subend = search_regs.end[sub];
2562 else if (c >= '1' && c <= '9')
2564 if (c - '0' < search_regs.num_regs
2565 && search_regs.start[c - '0'] >= 0)
2567 substart = search_regs.start[c - '0'];
2568 subend = search_regs.end[c - '0'];
2570 else
2572 /* If that subexp did not match,
2573 replace \\N with nothing. */
2574 substart = 0;
2575 subend = 0;
2578 else if (c == '\\')
2579 delbackslash = 1;
2580 else if (c != '?')
2581 error ("Invalid use of `\\' in replacement text");
2583 if (substart >= 0)
2585 if (pos - 2 != lastpos)
2586 middle = substring_both (newtext, lastpos,
2587 lastpos_byte,
2588 pos - 2, pos_byte - 2);
2589 else
2590 middle = Qnil;
2591 accum = concat3 (accum, middle,
2592 Fsubstring (string,
2593 make_number (substart),
2594 make_number (subend)));
2595 lastpos = pos;
2596 lastpos_byte = pos_byte;
2598 else if (delbackslash)
2600 middle = substring_both (newtext, lastpos,
2601 lastpos_byte,
2602 pos - 1, pos_byte - 1);
2604 accum = concat2 (accum, middle);
2605 lastpos = pos;
2606 lastpos_byte = pos_byte;
2610 if (pos != lastpos)
2611 middle = substring_both (newtext, lastpos,
2612 lastpos_byte,
2613 pos, pos_byte);
2614 else
2615 middle = Qnil;
2617 newtext = concat2 (accum, middle);
2620 /* Do case substitution in NEWTEXT if desired. */
2621 if (case_action == all_caps)
2622 newtext = Fupcase (newtext);
2623 else if (case_action == cap_initial)
2624 newtext = Fupcase_initials (newtext);
2626 return concat3 (before, newtext, after);
2629 /* Record point, then move (quietly) to the start of the match. */
2630 if (PT >= search_regs.end[sub])
2631 opoint = PT - ZV;
2632 else if (PT > search_regs.start[sub])
2633 opoint = search_regs.end[sub] - ZV;
2634 else
2635 opoint = PT;
2637 /* If we want non-literal replacement,
2638 perform substitution on the replacement string. */
2639 if (NILP (literal))
2641 ptrdiff_t length = SBYTES (newtext);
2642 unsigned char *substed;
2643 ptrdiff_t substed_alloc_size, substed_len;
2644 bool buf_multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
2645 bool str_multibyte = STRING_MULTIBYTE (newtext);
2646 bool really_changed = 0;
2648 substed_alloc_size = (length <= (STRING_BYTES_BOUND - 100) / 2
2649 ? length * 2 + 100
2650 : STRING_BYTES_BOUND);
2651 substed = xmalloc (substed_alloc_size);
2652 substed_len = 0;
2654 /* Go thru NEWTEXT, producing the actual text to insert in
2655 SUBSTED while adjusting multibyteness to that of the current
2656 buffer. */
2658 for (pos_byte = 0, pos = 0; pos_byte < length;)
2660 unsigned char str[MAX_MULTIBYTE_LENGTH];
2661 const unsigned char *add_stuff = NULL;
2662 ptrdiff_t add_len = 0;
2663 ptrdiff_t idx = -1;
2664 ptrdiff_t begbyte UNINIT;
2666 if (str_multibyte)
2668 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, newtext, pos, pos_byte);
2669 if (!buf_multibyte)
2670 c = CHAR_TO_BYTE8 (c);
2672 else
2674 /* Note that we don't have to increment POS. */
2675 c = SREF (newtext, pos_byte++);
2676 if (buf_multibyte)
2677 MAKE_CHAR_MULTIBYTE (c);
2680 /* Either set ADD_STUFF and ADD_LEN to the text to put in SUBSTED,
2681 or set IDX to a match index, which means put that part
2682 of the buffer text into SUBSTED. */
2684 if (c == '\\')
2686 really_changed = 1;
2688 if (str_multibyte)
2690 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, newtext,
2691 pos, pos_byte);
2692 if (!buf_multibyte && !ASCII_CHAR_P (c))
2693 c = CHAR_TO_BYTE8 (c);
2695 else
2697 c = SREF (newtext, pos_byte++);
2698 if (buf_multibyte)
2699 MAKE_CHAR_MULTIBYTE (c);
2702 if (c == '&')
2703 idx = sub;
2704 else if (c >= '1' && c <= '9' && c - '0' < search_regs.num_regs)
2706 if (search_regs.start[c - '0'] >= 1)
2707 idx = c - '0';
2709 else if (c == '\\')
2710 add_len = 1, add_stuff = (unsigned char *) "\\";
2711 else
2713 xfree (substed);
2714 error ("Invalid use of `\\' in replacement text");
2717 else
2719 add_len = CHAR_STRING (c, str);
2720 add_stuff = str;
2723 /* If we want to copy part of a previous match,
2724 set up ADD_STUFF and ADD_LEN to point to it. */
2725 if (idx >= 0)
2727 begbyte = CHAR_TO_BYTE (search_regs.start[idx]);
2728 add_len = CHAR_TO_BYTE (search_regs.end[idx]) - begbyte;
2729 if (search_regs.start[idx] < GPT && GPT < search_regs.end[idx])
2730 move_gap_both (search_regs.start[idx], begbyte);
2733 /* Now the stuff we want to add to SUBSTED
2734 is invariably ADD_LEN bytes starting at ADD_STUFF. */
2736 /* Make sure SUBSTED is big enough. */
2737 if (substed_alloc_size - substed_len < add_len)
2738 substed =
2739 xpalloc (substed, &substed_alloc_size,
2740 add_len - (substed_alloc_size - substed_len),
2741 STRING_BYTES_BOUND, 1);
2743 /* We compute this after the call to xpalloc, because that
2744 could cause buffer text be relocated when ralloc.c is used. */
2745 if (idx >= 0)
2746 add_stuff = BYTE_POS_ADDR (begbyte);
2748 /* Now add to the end of SUBSTED. */
2749 if (add_stuff)
2751 memcpy (substed + substed_len, add_stuff, add_len);
2752 substed_len += add_len;
2756 if (really_changed)
2757 newtext = make_specified_string ((const char *) substed, -1,
2758 substed_len, buf_multibyte);
2759 xfree (substed);
2762 /* The functions below modify the buffer, so they could trigger
2763 various modification hooks (see signal_before_change and
2764 signal_after_change). If these hooks clobber the match data we
2765 error out since otherwise this will result in confusing bugs. */
2766 ptrdiff_t sub_start = search_regs.start[sub];
2767 ptrdiff_t sub_end = search_regs.end[sub];
2768 unsigned num_regs = search_regs.num_regs;
2769 newpoint = search_regs.start[sub] + SCHARS (newtext);
2771 /* Replace the old text with the new in the cleanest possible way. */
2772 replace_range (search_regs.start[sub], search_regs.end[sub],
2773 newtext, 1, 0, 1, 1);
2774 /* Update saved data to match adjustment made by replace_range. */
2776 ptrdiff_t change = newpoint - sub_end;
2777 if (sub_start >= sub_end)
2778 sub_start += change;
2779 sub_end += change;
2782 if (case_action == all_caps)
2783 Fupcase_region (make_number (search_regs.start[sub]),
2784 make_number (newpoint),
2785 Qnil);
2786 else if (case_action == cap_initial)
2787 Fupcase_initials_region (make_number (search_regs.start[sub]),
2788 make_number (newpoint));
2790 if (search_regs.start[sub] != sub_start
2791 || search_regs.end[sub] != sub_end
2792 || search_regs.num_regs != num_regs)
2793 error ("Match data clobbered by buffer modification hooks");
2795 /* Put point back where it was in the text. */
2796 if (opoint <= 0)
2797 TEMP_SET_PT (opoint + ZV);
2798 else
2799 TEMP_SET_PT (opoint);
2801 /* Now move point "officially" to the start of the inserted replacement. */
2802 move_if_not_intangible (newpoint);
2804 return Qnil;
2807 static Lisp_Object
2808 match_limit (Lisp_Object num, bool beginningp)
2810 EMACS_INT n;
2812 CHECK_NUMBER (num);
2813 n = XINT (num);
2814 if (n < 0)
2815 args_out_of_range (num, make_number (0));
2816 if (search_regs.num_regs <= 0)
2817 error ("No match data, because no search succeeded");
2818 if (n >= search_regs.num_regs
2819 || search_regs.start[n] < 0)
2820 return Qnil;
2821 return (make_number ((beginningp) ? search_regs.start[n]
2822 : search_regs.end[n]));
2825 DEFUN ("match-beginning", Fmatch_beginning, Smatch_beginning, 1, 1, 0,
2826 doc: /* Return position of start of text matched by last search.
2827 SUBEXP, a number, specifies which parenthesized expression in the last
2828 regexp.
2829 Value is nil if SUBEXPth pair didn't match, or there were less than
2830 SUBEXP pairs.
2831 Zero means the entire text matched by the whole regexp or whole string.
2833 Return value is undefined if the last search failed. */)
2834 (Lisp_Object subexp)
2836 return match_limit (subexp, 1);
2839 DEFUN ("match-end", Fmatch_end, Smatch_end, 1, 1, 0,
2840 doc: /* Return position of end of text matched by last search.
2841 SUBEXP, a number, specifies which parenthesized expression in the last
2842 regexp.
2843 Value is nil if SUBEXPth pair didn't match, or there were less than
2844 SUBEXP pairs.
2845 Zero means the entire text matched by the whole regexp or whole string.
2847 Return value is undefined if the last search failed. */)
2848 (Lisp_Object subexp)
2850 return match_limit (subexp, 0);
2853 DEFUN ("match-data", Fmatch_data, Smatch_data, 0, 3, 0,
2854 doc: /* Return a list describing what the last search matched.
2855 Element 2N is `(match-beginning N)'; element 2N + 1 is `(match-end N)'.
2856 All the elements are markers or nil (nil if the Nth pair didn't match)
2857 if the last match was on a buffer; integers or nil if a string was matched.
2858 Use `set-match-data' to reinstate the data in this list.
2860 If INTEGERS (the optional first argument) is non-nil, always use
2861 integers (rather than markers) to represent buffer positions. In
2862 this case, and if the last match was in a buffer, the buffer will get
2863 stored as one additional element at the end of the list.
2865 If REUSE is a list, reuse it as part of the value. If REUSE is long
2866 enough to hold all the values, and if INTEGERS is non-nil, no consing
2867 is done.
2869 If optional third arg RESEAT is non-nil, any previous markers on the
2870 REUSE list will be modified to point to nowhere.
2872 Return value is undefined if the last search failed. */)
2873 (Lisp_Object integers, Lisp_Object reuse, Lisp_Object reseat)
2875 Lisp_Object tail, prev;
2876 Lisp_Object *data;
2877 ptrdiff_t i, len;
2879 if (!NILP (reseat))
2880 for (tail = reuse; CONSP (tail); tail = XCDR (tail))
2881 if (MARKERP (XCAR (tail)))
2883 unchain_marker (XMARKER (XCAR (tail)));
2884 XSETCAR (tail, Qnil);
2887 if (NILP (last_thing_searched))
2888 return Qnil;
2890 prev = Qnil;
2892 USE_SAFE_ALLOCA;
2893 SAFE_NALLOCA (data, 1, 2 * search_regs.num_regs + 1);
2895 len = 0;
2896 for (i = 0; i < search_regs.num_regs; i++)
2898 ptrdiff_t start = search_regs.start[i];
2899 if (start >= 0)
2901 if (EQ (last_thing_searched, Qt)
2902 || ! NILP (integers))
2904 XSETFASTINT (data[2 * i], start);
2905 XSETFASTINT (data[2 * i + 1], search_regs.end[i]);
2907 else if (BUFFERP (last_thing_searched))
2909 data[2 * i] = Fmake_marker ();
2910 Fset_marker (data[2 * i],
2911 make_number (start),
2912 last_thing_searched);
2913 data[2 * i + 1] = Fmake_marker ();
2914 Fset_marker (data[2 * i + 1],
2915 make_number (search_regs.end[i]),
2916 last_thing_searched);
2918 else
2919 /* last_thing_searched must always be Qt, a buffer, or Qnil. */
2920 emacs_abort ();
2922 len = 2 * i + 2;
2924 else
2925 data[2 * i] = data[2 * i + 1] = Qnil;
2928 if (BUFFERP (last_thing_searched) && !NILP (integers))
2930 data[len] = last_thing_searched;
2931 len++;
2934 /* If REUSE is not usable, cons up the values and return them. */
2935 if (! CONSP (reuse))
2936 reuse = Flist (len, data);
2937 else
2939 /* If REUSE is a list, store as many value elements as will fit
2940 into the elements of REUSE. */
2941 for (i = 0, tail = reuse; CONSP (tail);
2942 i++, tail = XCDR (tail))
2944 if (i < len)
2945 XSETCAR (tail, data[i]);
2946 else
2947 XSETCAR (tail, Qnil);
2948 prev = tail;
2951 /* If we couldn't fit all value elements into REUSE,
2952 cons up the rest of them and add them to the end of REUSE. */
2953 if (i < len)
2954 XSETCDR (prev, Flist (len - i, data + i));
2957 SAFE_FREE ();
2958 return reuse;
2961 /* We used to have an internal use variant of `reseat' described as:
2963 If RESEAT is `evaporate', put the markers back on the free list
2964 immediately. No other references to the markers must exist in this
2965 case, so it is used only internally on the unwind stack and
2966 save-match-data from Lisp.
2968 But it was ill-conceived: those supposedly-internal markers get exposed via
2969 the undo-list, so freeing them here is unsafe. */
2971 DEFUN ("set-match-data", Fset_match_data, Sset_match_data, 1, 2, 0,
2972 doc: /* Set internal data on last search match from elements of LIST.
2973 LIST should have been created by calling `match-data' previously.
2975 If optional arg RESEAT is non-nil, make markers on LIST point nowhere. */)
2976 (register Lisp_Object list, Lisp_Object reseat)
2978 ptrdiff_t i;
2979 register Lisp_Object marker;
2981 if (running_asynch_code)
2982 save_search_regs ();
2984 CHECK_LIST (list);
2986 /* Unless we find a marker with a buffer or an explicit buffer
2987 in LIST, assume that this match data came from a string. */
2988 last_thing_searched = Qt;
2990 /* Allocate registers if they don't already exist. */
2992 EMACS_INT length = XFASTINT (Flength (list)) / 2;
2994 if (length > search_regs.num_regs)
2996 ptrdiff_t num_regs = search_regs.num_regs;
2997 if (PTRDIFF_MAX < length)
2998 memory_full (SIZE_MAX);
2999 search_regs.start =
3000 xpalloc (search_regs.start, &num_regs, length - num_regs,
3001 min (PTRDIFF_MAX, UINT_MAX), sizeof (regoff_t));
3002 search_regs.end =
3003 xrealloc (search_regs.end, num_regs * sizeof (regoff_t));
3005 for (i = search_regs.num_regs; i < num_regs; i++)
3006 search_regs.start[i] = -1;
3008 search_regs.num_regs = num_regs;
3011 for (i = 0; CONSP (list); i++)
3013 marker = XCAR (list);
3014 if (BUFFERP (marker))
3016 last_thing_searched = marker;
3017 break;
3019 if (i >= length)
3020 break;
3021 if (NILP (marker))
3023 search_regs.start[i] = -1;
3024 list = XCDR (list);
3026 else
3028 Lisp_Object from;
3029 Lisp_Object m;
3031 m = marker;
3032 if (MARKERP (marker))
3034 if (XMARKER (marker)->buffer == 0)
3035 XSETFASTINT (marker, 0);
3036 else
3037 XSETBUFFER (last_thing_searched, XMARKER (marker)->buffer);
3040 CHECK_NUMBER_COERCE_MARKER (marker);
3041 from = marker;
3043 if (!NILP (reseat) && MARKERP (m))
3045 unchain_marker (XMARKER (m));
3046 XSETCAR (list, Qnil);
3049 if ((list = XCDR (list), !CONSP (list)))
3050 break;
3052 m = marker = XCAR (list);
3054 if (MARKERP (marker) && XMARKER (marker)->buffer == 0)
3055 XSETFASTINT (marker, 0);
3057 CHECK_NUMBER_COERCE_MARKER (marker);
3058 if ((XINT (from) < 0
3059 ? TYPE_MINIMUM (regoff_t) <= XINT (from)
3060 : XINT (from) <= TYPE_MAXIMUM (regoff_t))
3061 && (XINT (marker) < 0
3062 ? TYPE_MINIMUM (regoff_t) <= XINT (marker)
3063 : XINT (marker) <= TYPE_MAXIMUM (regoff_t)))
3065 search_regs.start[i] = XINT (from);
3066 search_regs.end[i] = XINT (marker);
3068 else
3070 search_regs.start[i] = -1;
3073 if (!NILP (reseat) && MARKERP (m))
3075 unchain_marker (XMARKER (m));
3076 XSETCAR (list, Qnil);
3079 list = XCDR (list);
3082 for (; i < search_regs.num_regs; i++)
3083 search_regs.start[i] = -1;
3086 return Qnil;
3089 /* If true the match data have been saved in saved_search_regs
3090 during the execution of a sentinel or filter. */
3091 /* static bool search_regs_saved; */
3092 /* static struct re_registers saved_search_regs; */
3093 /* static Lisp_Object saved_last_thing_searched; */
3095 /* Called from Flooking_at, Fstring_match, search_buffer, Fstore_match_data
3096 if asynchronous code (filter or sentinel) is running. */
3097 static void
3098 save_search_regs (void)
3100 if (!search_regs_saved)
3102 saved_search_regs.num_regs = search_regs.num_regs;
3103 saved_search_regs.start = search_regs.start;
3104 saved_search_regs.end = search_regs.end;
3105 saved_last_thing_searched = last_thing_searched;
3106 last_thing_searched = Qnil;
3107 search_regs.num_regs = 0;
3108 search_regs.start = 0;
3109 search_regs.end = 0;
3111 search_regs_saved = 1;
3115 /* Called upon exit from filters and sentinels. */
3116 void
3117 restore_search_regs (void)
3119 if (search_regs_saved)
3121 if (search_regs.num_regs > 0)
3123 xfree (search_regs.start);
3124 xfree (search_regs.end);
3126 search_regs.num_regs = saved_search_regs.num_regs;
3127 search_regs.start = saved_search_regs.start;
3128 search_regs.end = saved_search_regs.end;
3129 last_thing_searched = saved_last_thing_searched;
3130 saved_last_thing_searched = Qnil;
3131 search_regs_saved = 0;
3135 /* Called from replace-match via replace_range. */
3136 void
3137 update_search_regs (ptrdiff_t oldstart, ptrdiff_t oldend, ptrdiff_t newend)
3139 /* Adjust search data for this change. */
3140 ptrdiff_t change = newend - oldend;
3141 ptrdiff_t i;
3143 for (i = 0; i < search_regs.num_regs; i++)
3145 if (search_regs.start[i] >= oldend)
3146 search_regs.start[i] += change;
3147 else if (search_regs.start[i] > oldstart)
3148 search_regs.start[i] = oldstart;
3149 if (search_regs.end[i] >= oldend)
3150 search_regs.end[i] += change;
3151 else if (search_regs.end[i] > oldstart)
3152 search_regs.end[i] = oldstart;
3156 static void
3157 unwind_set_match_data (Lisp_Object list)
3159 /* It is NOT ALWAYS safe to free (evaporate) the markers immediately. */
3160 Fset_match_data (list, Qt);
3163 /* Called to unwind protect the match data. */
3164 void
3165 record_unwind_save_match_data (void)
3167 record_unwind_protect (unwind_set_match_data,
3168 Fmatch_data (Qnil, Qnil, Qnil));
3171 /* Quote a string to deactivate reg-expr chars */
3173 DEFUN ("regexp-quote", Fregexp_quote, Sregexp_quote, 1, 1, 0,
3174 doc: /* Return a regexp string which matches exactly STRING and nothing else. */)
3175 (Lisp_Object string)
3177 char *in, *out, *end;
3178 char *temp;
3179 ptrdiff_t backslashes_added = 0;
3181 CHECK_STRING (string);
3183 USE_SAFE_ALLOCA;
3184 SAFE_NALLOCA (temp, 2, SBYTES (string));
3186 /* Now copy the data into the new string, inserting escapes. */
3188 in = SSDATA (string);
3189 end = in + SBYTES (string);
3190 out = temp;
3192 for (; in != end; in++)
3194 if (*in == '['
3195 || *in == '*' || *in == '.' || *in == '\\'
3196 || *in == '?' || *in == '+'
3197 || *in == '^' || *in == '$')
3198 *out++ = '\\', backslashes_added++;
3199 *out++ = *in;
3202 Lisp_Object result
3203 = make_specified_string (temp,
3204 SCHARS (string) + backslashes_added,
3205 out - temp,
3206 STRING_MULTIBYTE (string));
3207 SAFE_FREE ();
3208 return result;
3211 /* Like find_newline, but doesn't use the cache, and only searches forward. */
3212 static ptrdiff_t
3213 find_newline1 (ptrdiff_t start, ptrdiff_t start_byte, ptrdiff_t end,
3214 ptrdiff_t end_byte, ptrdiff_t count, ptrdiff_t *shortage,
3215 ptrdiff_t *bytepos, bool allow_quit)
3217 if (count > 0)
3219 if (!end)
3220 end = ZV, end_byte = ZV_BYTE;
3222 else
3224 if (!end)
3225 end = BEGV, end_byte = BEGV_BYTE;
3227 if (end_byte == -1)
3228 end_byte = CHAR_TO_BYTE (end);
3230 if (shortage != 0)
3231 *shortage = 0;
3233 if (count > 0)
3234 while (start != end)
3236 /* Our innermost scanning loop is very simple; it doesn't know
3237 about gaps, buffer ends, or the newline cache. ceiling is
3238 the position of the last character before the next such
3239 obstacle --- the last character the dumb search loop should
3240 examine. */
3241 ptrdiff_t tem, ceiling_byte = end_byte - 1;
3243 if (start_byte == -1)
3244 start_byte = CHAR_TO_BYTE (start);
3246 /* The dumb loop can only scan text stored in contiguous
3247 bytes. BUFFER_CEILING_OF returns the last character
3248 position that is contiguous, so the ceiling is the
3249 position after that. */
3250 tem = BUFFER_CEILING_OF (start_byte);
3251 ceiling_byte = min (tem, ceiling_byte);
3254 /* The termination address of the dumb loop. */
3255 unsigned char *lim_addr = BYTE_POS_ADDR (ceiling_byte) + 1;
3256 ptrdiff_t lim_byte = ceiling_byte + 1;
3258 /* Nonpositive offsets (relative to LIM_ADDR and LIM_BYTE)
3259 of the base, the cursor, and the next line. */
3260 ptrdiff_t base = start_byte - lim_byte;
3261 ptrdiff_t cursor, next;
3263 for (cursor = base; cursor < 0; cursor = next)
3265 /* The dumb loop. */
3266 unsigned char *nl = memchr (lim_addr + cursor, '\n', - cursor);
3267 next = nl ? nl - lim_addr : 0;
3269 if (! nl)
3270 break;
3271 next++;
3273 if (--count == 0)
3275 if (bytepos)
3276 *bytepos = lim_byte + next;
3277 return BYTE_TO_CHAR (lim_byte + next);
3279 if (allow_quit)
3280 maybe_quit ();
3283 start_byte = lim_byte;
3284 start = BYTE_TO_CHAR (start_byte);
3288 if (shortage)
3289 *shortage = count;
3290 if (bytepos)
3292 *bytepos = start_byte == -1 ? CHAR_TO_BYTE (start) : start_byte;
3293 eassert (*bytepos == CHAR_TO_BYTE (start));
3295 return start;
3298 DEFUN ("newline-cache-check", Fnewline_cache_check, Snewline_cache_check,
3299 0, 1, 0,
3300 doc: /* Check the newline cache of BUFFER against buffer contents.
3302 BUFFER defaults to the current buffer.
3304 Value is an array of 2 sub-arrays of buffer positions for newlines,
3305 the first based on the cache, the second based on actually scanning
3306 the buffer. If the buffer doesn't have a cache, the value is nil. */)
3307 (Lisp_Object buffer)
3309 struct buffer *buf, *old = NULL;
3310 ptrdiff_t shortage, nl_count_cache, nl_count_buf;
3311 Lisp_Object cache_newlines, buf_newlines, val;
3312 ptrdiff_t from, found, i;
3314 if (NILP (buffer))
3315 buf = current_buffer;
3316 else
3318 CHECK_BUFFER (buffer);
3319 buf = XBUFFER (buffer);
3320 old = current_buffer;
3322 if (buf->base_buffer)
3323 buf = buf->base_buffer;
3325 /* If the buffer doesn't have a newline cache, return nil. */
3326 if (NILP (BVAR (buf, cache_long_scans))
3327 || buf->newline_cache == NULL)
3328 return Qnil;
3330 /* find_newline can only work on the current buffer. */
3331 if (old != NULL)
3332 set_buffer_internal_1 (buf);
3334 /* How many newlines are there according to the cache? */
3335 find_newline (BEGV, BEGV_BYTE, ZV, ZV_BYTE,
3336 TYPE_MAXIMUM (ptrdiff_t), &shortage, NULL, true);
3337 nl_count_cache = TYPE_MAXIMUM (ptrdiff_t) - shortage;
3339 /* Create vector and populate it. */
3340 cache_newlines = make_uninit_vector (nl_count_cache);
3342 if (nl_count_cache)
3344 for (from = BEGV, found = from, i = 0; from < ZV; from = found, i++)
3346 ptrdiff_t from_byte = CHAR_TO_BYTE (from);
3348 found = find_newline (from, from_byte, 0, -1, 1, &shortage,
3349 NULL, true);
3350 if (shortage != 0 || i >= nl_count_cache)
3351 break;
3352 ASET (cache_newlines, i, make_number (found - 1));
3354 /* Fill the rest of slots with an invalid position. */
3355 for ( ; i < nl_count_cache; i++)
3356 ASET (cache_newlines, i, make_number (-1));
3359 /* Now do the same, but without using the cache. */
3360 find_newline1 (BEGV, BEGV_BYTE, ZV, ZV_BYTE,
3361 TYPE_MAXIMUM (ptrdiff_t), &shortage, NULL, true);
3362 nl_count_buf = TYPE_MAXIMUM (ptrdiff_t) - shortage;
3363 buf_newlines = make_uninit_vector (nl_count_buf);
3364 if (nl_count_buf)
3366 for (from = BEGV, found = from, i = 0; from < ZV; from = found, i++)
3368 ptrdiff_t from_byte = CHAR_TO_BYTE (from);
3370 found = find_newline1 (from, from_byte, 0, -1, 1, &shortage,
3371 NULL, true);
3372 if (shortage != 0 || i >= nl_count_buf)
3373 break;
3374 ASET (buf_newlines, i, make_number (found - 1));
3376 for ( ; i < nl_count_buf; i++)
3377 ASET (buf_newlines, i, make_number (-1));
3380 /* Construct the value and return it. */
3381 val = make_uninit_vector (2);
3382 ASET (val, 0, cache_newlines);
3383 ASET (val, 1, buf_newlines);
3385 if (old != NULL)
3386 set_buffer_internal_1 (old);
3387 return val;
3391 void
3392 syms_of_search (void)
3394 register int i;
3396 for (i = 0; i < REGEXP_CACHE_SIZE; ++i)
3398 searchbufs[i].buf.allocated = 100;
3399 searchbufs[i].buf.buffer = xmalloc (100);
3400 searchbufs[i].buf.fastmap = searchbufs[i].fastmap;
3401 searchbufs[i].regexp = Qnil;
3402 searchbufs[i].f_whitespace_regexp = Qnil;
3403 searchbufs[i].busy = false;
3404 searchbufs[i].syntax_table = Qnil;
3405 staticpro (&searchbufs[i].regexp);
3406 staticpro (&searchbufs[i].f_whitespace_regexp);
3407 staticpro (&searchbufs[i].syntax_table);
3408 searchbufs[i].next = (i == REGEXP_CACHE_SIZE-1 ? 0 : &searchbufs[i+1]);
3410 searchbuf_head = &searchbufs[0];
3412 /* Error condition used for failing searches. */
3413 DEFSYM (Qsearch_failed, "search-failed");
3415 /* Error condition used for failing searches started by user, i.e.,
3416 where failure should not invoke the debugger. */
3417 DEFSYM (Quser_search_failed, "user-search-failed");
3419 /* Error condition signaled when regexp compile_pattern fails. */
3420 DEFSYM (Qinvalid_regexp, "invalid-regexp");
3422 Fput (Qsearch_failed, Qerror_conditions,
3423 listn (CONSTYPE_PURE, 2, Qsearch_failed, Qerror));
3424 Fput (Qsearch_failed, Qerror_message,
3425 build_pure_c_string ("Search failed"));
3427 Fput (Quser_search_failed, Qerror_conditions,
3428 listn (CONSTYPE_PURE, 4,
3429 Quser_search_failed, Quser_error, Qsearch_failed, Qerror));
3430 Fput (Quser_search_failed, Qerror_message,
3431 build_pure_c_string ("Search failed"));
3433 Fput (Qinvalid_regexp, Qerror_conditions,
3434 listn (CONSTYPE_PURE, 2, Qinvalid_regexp, Qerror));
3435 Fput (Qinvalid_regexp, Qerror_message,
3436 build_pure_c_string ("Invalid regexp"));
3438 last_thing_searched = Qnil;
3439 staticpro (&last_thing_searched);
3441 saved_last_thing_searched = Qnil;
3442 staticpro (&saved_last_thing_searched);
3444 re_match_object = Qnil;
3445 staticpro (&re_match_object);
3447 DEFVAR_LISP ("search-spaces-regexp", Vsearch_spaces_regexp,
3448 doc: /* Regexp to substitute for bunches of spaces in regexp search.
3449 Some commands use this for user-specified regexps.
3450 Spaces that occur inside character classes or repetition operators
3451 or other such regexp constructs are not replaced with this.
3452 A value of nil (which is the normal value) means treat spaces literally. */);
3453 Vsearch_spaces_regexp = Qnil;
3455 DEFSYM (Qinhibit_changing_match_data, "inhibit-changing-match-data");
3456 DEFVAR_LISP ("inhibit-changing-match-data", Vinhibit_changing_match_data,
3457 doc: /* Internal use only.
3458 If non-nil, the primitive searching and matching functions
3459 such as `looking-at', `string-match', `re-search-forward', etc.,
3460 do not set the match data. The proper way to use this variable
3461 is to bind it with `let' around a small expression. */);
3462 Vinhibit_changing_match_data = Qnil;
3464 defsubr (&Slooking_at);
3465 defsubr (&Sposix_looking_at);
3466 defsubr (&Sstring_match);
3467 defsubr (&Sposix_string_match);
3468 defsubr (&Ssearch_forward);
3469 defsubr (&Ssearch_backward);
3470 defsubr (&Sre_search_forward);
3471 defsubr (&Sre_search_backward);
3472 defsubr (&Sposix_search_forward);
3473 defsubr (&Sposix_search_backward);
3474 defsubr (&Sreplace_match);
3475 defsubr (&Smatch_beginning);
3476 defsubr (&Smatch_end);
3477 defsubr (&Smatch_data);
3478 defsubr (&Sset_match_data);
3479 defsubr (&Sregexp_quote);
3480 defsubr (&Snewline_cache_check);