(forms-file): Update for moved forms-d2.dat.
[emacs.git] / src / search.c
blob96daecb728e1193e78c1146c060a9f1400dc9fbd
1 /* String search routines for GNU Emacs.
2 Copyright (C) 1985, 1986, 1987, 1993, 1994, 1997, 1998, 1999, 2001, 2002,
3 2003, 2004, 2005, 2006, 2007, 2008
4 Free Software 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, or (at your option)
11 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; see the file COPYING. If not, write to
20 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 Boston, MA 02110-1301, USA. */
24 #include <config.h>
25 #include "lisp.h"
26 #include "syntax.h"
27 #include "category.h"
28 #include "buffer.h"
29 #include "character.h"
30 #include "charset.h"
31 #include "region-cache.h"
32 #include "commands.h"
33 #include "blockinput.h"
34 #include "intervals.h"
36 #include <sys/types.h>
37 #include "regex.h"
39 #define REGEXP_CACHE_SIZE 20
41 /* If the regexp is non-nil, then the buffer contains the compiled form
42 of that regexp, suitable for searching. */
43 struct regexp_cache
45 struct regexp_cache *next;
46 Lisp_Object regexp, whitespace_regexp;
47 /* Syntax table for which the regexp applies. We need this because
48 of character classes. If this is t, then the compiled pattern is valid
49 for any syntax-table. */
50 Lisp_Object syntax_table;
51 struct re_pattern_buffer buf;
52 char fastmap[0400];
53 /* Nonzero means regexp was compiled to do full POSIX backtracking. */
54 char posix;
57 /* The instances of that struct. */
58 struct regexp_cache searchbufs[REGEXP_CACHE_SIZE];
60 /* The head of the linked list; points to the most recently used buffer. */
61 struct regexp_cache *searchbuf_head;
64 /* Every call to re_match, etc., must pass &search_regs as the regs
65 argument unless you can show it is unnecessary (i.e., if re_match
66 is certainly going to be called again before region-around-match
67 can be called).
69 Since the registers are now dynamically allocated, we need to make
70 sure not to refer to the Nth register before checking that it has
71 been allocated by checking search_regs.num_regs.
73 The regex code keeps track of whether it has allocated the search
74 buffer using bits in the re_pattern_buffer. This means that whenever
75 you compile a new pattern, it completely forgets whether it has
76 allocated any registers, and will allocate new registers the next
77 time you call a searching or matching function. Therefore, we need
78 to call re_set_registers after compiling a new pattern or after
79 setting the match registers, so that the regex functions will be
80 able to free or re-allocate it properly. */
81 static struct re_registers search_regs;
83 /* The buffer in which the last search was performed, or
84 Qt if the last search was done in a string;
85 Qnil if no searching has been done yet. */
86 static Lisp_Object last_thing_searched;
88 /* error condition signaled when regexp compile_pattern fails */
90 Lisp_Object Qinvalid_regexp;
92 /* Error condition used for failing searches */
93 Lisp_Object Qsearch_failed;
95 Lisp_Object Vsearch_spaces_regexp;
97 /* If non-nil, the match data will not be changed during call to
98 searching or matching functions. This variable is for internal use
99 only. */
100 Lisp_Object Vinhibit_changing_match_data;
102 static void set_search_regs ();
103 static void save_search_regs ();
104 static int simple_search ();
105 static int boyer_moore ();
106 static int search_buffer ();
107 static void matcher_overflow () NO_RETURN;
109 static void
110 matcher_overflow ()
112 error ("Stack overflow in regexp matcher");
115 /* Compile a regexp and signal a Lisp error if anything goes wrong.
116 PATTERN is the pattern to compile.
117 CP is the place to put the result.
118 TRANSLATE is a translation table for ignoring case, or nil for none.
119 REGP is the structure that says where to store the "register"
120 values that will result from matching this pattern.
121 If it is 0, we should compile the pattern not to record any
122 subexpression bounds.
123 POSIX is nonzero if we want full backtracking (POSIX style)
124 for this pattern. 0 means backtrack only enough to get a valid match.
126 The behavior also depends on Vsearch_spaces_regexp. */
128 static void
129 compile_pattern_1 (cp, pattern, translate, regp, posix)
130 struct regexp_cache *cp;
131 Lisp_Object pattern;
132 Lisp_Object translate;
133 struct re_registers *regp;
134 int posix;
136 char *val;
137 reg_syntax_t old;
139 cp->regexp = Qnil;
140 cp->buf.translate = (! NILP (translate) ? translate : make_number (0));
141 cp->posix = posix;
142 cp->buf.multibyte = STRING_MULTIBYTE (pattern);
143 cp->buf.charset_unibyte = charset_unibyte;
144 if (STRINGP (Vsearch_spaces_regexp))
145 cp->whitespace_regexp = Vsearch_spaces_regexp;
146 else
147 cp->whitespace_regexp = Qnil;
149 /* rms: I think BLOCK_INPUT is not needed here any more,
150 because regex.c defines malloc to call xmalloc.
151 Using BLOCK_INPUT here means the debugger won't run if an error occurs.
152 So let's turn it off. */
153 /* BLOCK_INPUT; */
154 old = re_set_syntax (RE_SYNTAX_EMACS
155 | (posix ? 0 : RE_NO_POSIX_BACKTRACKING));
157 if (STRINGP (Vsearch_spaces_regexp))
158 re_set_whitespace_regexp (SDATA (Vsearch_spaces_regexp));
159 else
160 re_set_whitespace_regexp (NULL);
162 val = (char *) re_compile_pattern ((char *) SDATA (pattern),
163 SBYTES (pattern), &cp->buf);
165 /* If the compiled pattern hard codes some of the contents of the
166 syntax-table, it can only be reused with *this* syntax table. */
167 cp->syntax_table = cp->buf.used_syntax ? current_buffer->syntax_table : Qt;
169 re_set_whitespace_regexp (NULL);
171 re_set_syntax (old);
172 /* UNBLOCK_INPUT; */
173 if (val)
174 xsignal1 (Qinvalid_regexp, build_string (val));
176 cp->regexp = Fcopy_sequence (pattern);
179 /* Shrink each compiled regexp buffer in the cache
180 to the size actually used right now.
181 This is called from garbage collection. */
183 void
184 shrink_regexp_cache ()
186 struct regexp_cache *cp;
188 for (cp = searchbuf_head; cp != 0; cp = cp->next)
190 cp->buf.allocated = cp->buf.used;
191 cp->buf.buffer
192 = (unsigned char *) xrealloc (cp->buf.buffer, cp->buf.used);
196 /* Clear the regexp cache w.r.t. a particular syntax table,
197 because it was changed.
198 There is no danger of memory leak here because re_compile_pattern
199 automagically manages the memory in each re_pattern_buffer struct,
200 based on its `allocated' and `buffer' values. */
201 void
202 clear_regexp_cache ()
204 int i;
206 for (i = 0; i < REGEXP_CACHE_SIZE; ++i)
207 /* It's tempting to compare with the syntax-table we've actually changd,
208 but it's not sufficient because char-table inheritance mewans that
209 modifying one syntax-table can change others at the same time. */
210 if (!EQ (searchbufs[i].syntax_table, Qt))
211 searchbufs[i].regexp = Qnil;
214 /* Compile a regexp if necessary, but first check to see if there's one in
215 the cache.
216 PATTERN is the pattern to compile.
217 TRANSLATE is a translation table for ignoring case, or nil for none.
218 REGP is the structure that says where to store the "register"
219 values that will result from matching this pattern.
220 If it is 0, we should compile the pattern not to record any
221 subexpression bounds.
222 POSIX is nonzero if we want full backtracking (POSIX style)
223 for this pattern. 0 means backtrack only enough to get a valid match. */
225 struct re_pattern_buffer *
226 compile_pattern (pattern, regp, translate, posix, multibyte)
227 Lisp_Object pattern;
228 struct re_registers *regp;
229 Lisp_Object translate;
230 int posix, multibyte;
232 struct regexp_cache *cp, **cpp;
234 for (cpp = &searchbuf_head; ; cpp = &cp->next)
236 cp = *cpp;
237 /* Entries are initialized to nil, and may be set to nil by
238 compile_pattern_1 if the pattern isn't valid. Don't apply
239 string accessors in those cases. However, compile_pattern_1
240 is only applied to the cache entry we pick here to reuse. So
241 nil should never appear before a non-nil entry. */
242 if (NILP (cp->regexp))
243 goto compile_it;
244 if (SCHARS (cp->regexp) == SCHARS (pattern)
245 && STRING_MULTIBYTE (cp->regexp) == STRING_MULTIBYTE (pattern)
246 && !NILP (Fstring_equal (cp->regexp, pattern))
247 && EQ (cp->buf.translate, (! NILP (translate) ? translate : make_number (0)))
248 && cp->posix == posix
249 && (EQ (cp->syntax_table, Qt)
250 || EQ (cp->syntax_table, current_buffer->syntax_table))
251 && !NILP (Fequal (cp->whitespace_regexp, Vsearch_spaces_regexp))
252 && cp->buf.charset_unibyte == charset_unibyte)
253 break;
255 /* If we're at the end of the cache, compile into the nil cell
256 we found, or the last (least recently used) cell with a
257 string value. */
258 if (cp->next == 0)
260 compile_it:
261 compile_pattern_1 (cp, pattern, translate, regp, posix);
262 break;
266 /* When we get here, cp (aka *cpp) contains the compiled pattern,
267 either because we found it in the cache or because we just compiled it.
268 Move it to the front of the queue to mark it as most recently used. */
269 *cpp = cp->next;
270 cp->next = searchbuf_head;
271 searchbuf_head = cp;
273 /* Advise the searching functions about the space we have allocated
274 for register data. */
275 if (regp)
276 re_set_registers (&cp->buf, regp, regp->num_regs, regp->start, regp->end);
278 /* The compiled pattern can be used both for mulitbyte and unibyte
279 target. But, we have to tell which the pattern is used for. */
280 cp->buf.target_multibyte = multibyte;
282 return &cp->buf;
286 static Lisp_Object
287 looking_at_1 (string, posix)
288 Lisp_Object string;
289 int posix;
291 Lisp_Object val;
292 unsigned char *p1, *p2;
293 int s1, s2;
294 register int i;
295 struct re_pattern_buffer *bufp;
297 if (running_asynch_code)
298 save_search_regs ();
300 /* This is so set_image_of_range_1 in regex.c can find the EQV table. */
301 XCHAR_TABLE (current_buffer->case_canon_table)->extras[2]
302 = current_buffer->case_eqv_table;
304 CHECK_STRING (string);
305 bufp = compile_pattern (string,
306 (NILP (Vinhibit_changing_match_data)
307 ? &search_regs : NULL),
308 (!NILP (current_buffer->case_fold_search)
309 ? current_buffer->case_canon_table : Qnil),
310 posix,
311 !NILP (current_buffer->enable_multibyte_characters));
313 immediate_quit = 1;
314 QUIT; /* Do a pending quit right away, to avoid paradoxical behavior */
316 /* Get pointers and sizes of the two strings
317 that make up the visible portion of the buffer. */
319 p1 = BEGV_ADDR;
320 s1 = GPT_BYTE - BEGV_BYTE;
321 p2 = GAP_END_ADDR;
322 s2 = ZV_BYTE - GPT_BYTE;
323 if (s1 < 0)
325 p2 = p1;
326 s2 = ZV_BYTE - BEGV_BYTE;
327 s1 = 0;
329 if (s2 < 0)
331 s1 = ZV_BYTE - BEGV_BYTE;
332 s2 = 0;
335 re_match_object = Qnil;
337 i = re_match_2 (bufp, (char *) p1, s1, (char *) p2, s2,
338 PT_BYTE - BEGV_BYTE,
339 (NILP (Vinhibit_changing_match_data)
340 ? &search_regs : NULL),
341 ZV_BYTE - BEGV_BYTE);
342 immediate_quit = 0;
344 if (i == -2)
345 matcher_overflow ();
347 val = (0 <= i ? Qt : Qnil);
348 if (NILP (Vinhibit_changing_match_data) && i >= 0)
349 for (i = 0; i < search_regs.num_regs; i++)
350 if (search_regs.start[i] >= 0)
352 search_regs.start[i]
353 = BYTE_TO_CHAR (search_regs.start[i] + BEGV_BYTE);
354 search_regs.end[i]
355 = BYTE_TO_CHAR (search_regs.end[i] + BEGV_BYTE);
358 /* Set last_thing_searched only when match data is changed. */
359 if (NILP (Vinhibit_changing_match_data))
360 XSETBUFFER (last_thing_searched, current_buffer);
362 return val;
365 DEFUN ("looking-at", Flooking_at, Slooking_at, 1, 1, 0,
366 doc: /* Return t if text after point matches regular expression REGEXP.
367 This function modifies the match data that `match-beginning',
368 `match-end' and `match-data' access; save and restore the match
369 data if you want to preserve them. */)
370 (regexp)
371 Lisp_Object regexp;
373 return looking_at_1 (regexp, 0);
376 DEFUN ("posix-looking-at", Fposix_looking_at, Sposix_looking_at, 1, 1, 0,
377 doc: /* Return t if text after point matches regular expression REGEXP.
378 Find the longest match, in accord with Posix regular expression rules.
379 This function modifies the match data that `match-beginning',
380 `match-end' and `match-data' access; save and restore the match
381 data if you want to preserve them. */)
382 (regexp)
383 Lisp_Object regexp;
385 return looking_at_1 (regexp, 1);
388 static Lisp_Object
389 string_match_1 (regexp, string, start, posix)
390 Lisp_Object regexp, string, start;
391 int posix;
393 int val;
394 struct re_pattern_buffer *bufp;
395 int pos, pos_byte;
396 int i;
398 if (running_asynch_code)
399 save_search_regs ();
401 CHECK_STRING (regexp);
402 CHECK_STRING (string);
404 if (NILP (start))
405 pos = 0, pos_byte = 0;
406 else
408 int len = SCHARS (string);
410 CHECK_NUMBER (start);
411 pos = XINT (start);
412 if (pos < 0 && -pos <= len)
413 pos = len + pos;
414 else if (0 > pos || pos > len)
415 args_out_of_range (string, start);
416 pos_byte = string_char_to_byte (string, pos);
419 /* This is so set_image_of_range_1 in regex.c can find the EQV table. */
420 XCHAR_TABLE (current_buffer->case_canon_table)->extras[2]
421 = current_buffer->case_eqv_table;
423 bufp = compile_pattern (regexp,
424 (NILP (Vinhibit_changing_match_data)
425 ? &search_regs : NULL),
426 (!NILP (current_buffer->case_fold_search)
427 ? current_buffer->case_canon_table : Qnil),
428 posix,
429 STRING_MULTIBYTE (string));
430 immediate_quit = 1;
431 re_match_object = string;
433 val = re_search (bufp, (char *) SDATA (string),
434 SBYTES (string), pos_byte,
435 SBYTES (string) - pos_byte,
436 (NILP (Vinhibit_changing_match_data)
437 ? &search_regs : NULL));
438 immediate_quit = 0;
440 /* Set last_thing_searched only when match data is changed. */
441 if (NILP (Vinhibit_changing_match_data))
442 last_thing_searched = Qt;
444 if (val == -2)
445 matcher_overflow ();
446 if (val < 0) return Qnil;
448 if (NILP (Vinhibit_changing_match_data))
449 for (i = 0; i < search_regs.num_regs; i++)
450 if (search_regs.start[i] >= 0)
452 search_regs.start[i]
453 = string_byte_to_char (string, search_regs.start[i]);
454 search_regs.end[i]
455 = string_byte_to_char (string, search_regs.end[i]);
458 return make_number (string_byte_to_char (string, val));
461 DEFUN ("string-match", Fstring_match, Sstring_match, 2, 3, 0,
462 doc: /* Return index of start of first match for REGEXP in STRING, or nil.
463 Matching ignores case if `case-fold-search' is non-nil.
464 If third arg START is non-nil, start search at that index in STRING.
465 For index of first char beyond the match, do (match-end 0).
466 `match-end' and `match-beginning' also give indices of substrings
467 matched by parenthesis constructs in the pattern.
469 You can use the function `match-string' to extract the substrings
470 matched by the parenthesis constructions in REGEXP. */)
471 (regexp, string, start)
472 Lisp_Object regexp, string, start;
474 return string_match_1 (regexp, string, start, 0);
477 DEFUN ("posix-string-match", Fposix_string_match, Sposix_string_match, 2, 3, 0,
478 doc: /* Return index of start of first match for REGEXP in STRING, or nil.
479 Find the longest match, in accord with Posix regular expression rules.
480 Case is ignored if `case-fold-search' is non-nil in the current buffer.
481 If third arg START is non-nil, start search at that index in STRING.
482 For index of first char beyond the match, do (match-end 0).
483 `match-end' and `match-beginning' also give indices of substrings
484 matched by parenthesis constructs in the pattern. */)
485 (regexp, string, start)
486 Lisp_Object regexp, string, start;
488 return string_match_1 (regexp, string, start, 1);
491 /* Match REGEXP against STRING, searching all of STRING,
492 and return the index of the match, or negative on failure.
493 This does not clobber the match data. */
496 fast_string_match (regexp, string)
497 Lisp_Object regexp, string;
499 int val;
500 struct re_pattern_buffer *bufp;
502 bufp = compile_pattern (regexp, 0, Qnil,
503 0, STRING_MULTIBYTE (string));
504 immediate_quit = 1;
505 re_match_object = string;
507 val = re_search (bufp, (char *) SDATA (string),
508 SBYTES (string), 0,
509 SBYTES (string), 0);
510 immediate_quit = 0;
511 return val;
514 /* Match REGEXP against STRING, searching all of STRING ignoring case,
515 and return the index of the match, or negative on failure.
516 This does not clobber the match data.
517 We assume that STRING contains single-byte characters. */
519 extern Lisp_Object Vascii_downcase_table;
522 fast_c_string_match_ignore_case (regexp, string)
523 Lisp_Object regexp;
524 const char *string;
526 int val;
527 struct re_pattern_buffer *bufp;
528 int len = strlen (string);
530 regexp = string_make_unibyte (regexp);
531 re_match_object = Qt;
532 bufp = compile_pattern (regexp, 0,
533 Vascii_canon_table, 0,
535 immediate_quit = 1;
536 val = re_search (bufp, string, len, 0, len, 0);
537 immediate_quit = 0;
538 return val;
541 /* Like fast_string_match but ignore case. */
544 fast_string_match_ignore_case (regexp, string)
545 Lisp_Object regexp, string;
547 int val;
548 struct re_pattern_buffer *bufp;
550 bufp = compile_pattern (regexp, 0, Vascii_canon_table,
551 0, STRING_MULTIBYTE (string));
552 immediate_quit = 1;
553 re_match_object = string;
555 val = re_search (bufp, (char *) SDATA (string),
556 SBYTES (string), 0,
557 SBYTES (string), 0);
558 immediate_quit = 0;
559 return val;
562 /* The newline cache: remembering which sections of text have no newlines. */
564 /* If the user has requested newline caching, make sure it's on.
565 Otherwise, make sure it's off.
566 This is our cheezy way of associating an action with the change of
567 state of a buffer-local variable. */
568 static void
569 newline_cache_on_off (buf)
570 struct buffer *buf;
572 if (NILP (buf->cache_long_line_scans))
574 /* It should be off. */
575 if (buf->newline_cache)
577 free_region_cache (buf->newline_cache);
578 buf->newline_cache = 0;
581 else
583 /* It should be on. */
584 if (buf->newline_cache == 0)
585 buf->newline_cache = new_region_cache ();
590 /* Search for COUNT instances of the character TARGET between START and END.
592 If COUNT is positive, search forwards; END must be >= START.
593 If COUNT is negative, search backwards for the -COUNTth instance;
594 END must be <= START.
595 If COUNT is zero, do anything you please; run rogue, for all I care.
597 If END is zero, use BEGV or ZV instead, as appropriate for the
598 direction indicated by COUNT.
600 If we find COUNT instances, set *SHORTAGE to zero, and return the
601 position past the COUNTth match. Note that for reverse motion
602 this is not the same as the usual convention for Emacs motion commands.
604 If we don't find COUNT instances before reaching END, set *SHORTAGE
605 to the number of TARGETs left unfound, and return END.
607 If ALLOW_QUIT is non-zero, set immediate_quit. That's good to do
608 except when inside redisplay. */
611 scan_buffer (target, start, end, count, shortage, allow_quit)
612 register int target;
613 int start, end;
614 int count;
615 int *shortage;
616 int allow_quit;
618 struct region_cache *newline_cache;
619 int direction;
621 if (count > 0)
623 direction = 1;
624 if (! end) end = ZV;
626 else
628 direction = -1;
629 if (! end) end = BEGV;
632 newline_cache_on_off (current_buffer);
633 newline_cache = current_buffer->newline_cache;
635 if (shortage != 0)
636 *shortage = 0;
638 immediate_quit = allow_quit;
640 if (count > 0)
641 while (start != end)
643 /* Our innermost scanning loop is very simple; it doesn't know
644 about gaps, buffer ends, or the newline cache. ceiling is
645 the position of the last character before the next such
646 obstacle --- the last character the dumb search loop should
647 examine. */
648 int ceiling_byte = CHAR_TO_BYTE (end) - 1;
649 int start_byte = CHAR_TO_BYTE (start);
650 int tem;
652 /* If we're looking for a newline, consult the newline cache
653 to see where we can avoid some scanning. */
654 if (target == '\n' && newline_cache)
656 int next_change;
657 immediate_quit = 0;
658 while (region_cache_forward
659 (current_buffer, newline_cache, start_byte, &next_change))
660 start_byte = next_change;
661 immediate_quit = allow_quit;
663 /* START should never be after END. */
664 if (start_byte > ceiling_byte)
665 start_byte = ceiling_byte;
667 /* Now the text after start is an unknown region, and
668 next_change is the position of the next known region. */
669 ceiling_byte = min (next_change - 1, ceiling_byte);
672 /* The dumb loop can only scan text stored in contiguous
673 bytes. BUFFER_CEILING_OF returns the last character
674 position that is contiguous, so the ceiling is the
675 position after that. */
676 tem = BUFFER_CEILING_OF (start_byte);
677 ceiling_byte = min (tem, ceiling_byte);
680 /* The termination address of the dumb loop. */
681 register unsigned char *ceiling_addr
682 = BYTE_POS_ADDR (ceiling_byte) + 1;
683 register unsigned char *cursor
684 = BYTE_POS_ADDR (start_byte);
685 unsigned char *base = cursor;
687 while (cursor < ceiling_addr)
689 unsigned char *scan_start = cursor;
691 /* The dumb loop. */
692 while (*cursor != target && ++cursor < ceiling_addr)
695 /* If we're looking for newlines, cache the fact that
696 the region from start to cursor is free of them. */
697 if (target == '\n' && newline_cache)
698 know_region_cache (current_buffer, newline_cache,
699 start_byte + scan_start - base,
700 start_byte + cursor - base);
702 /* Did we find the target character? */
703 if (cursor < ceiling_addr)
705 if (--count == 0)
707 immediate_quit = 0;
708 return BYTE_TO_CHAR (start_byte + cursor - base + 1);
710 cursor++;
714 start = BYTE_TO_CHAR (start_byte + cursor - base);
717 else
718 while (start > end)
720 /* The last character to check before the next obstacle. */
721 int ceiling_byte = CHAR_TO_BYTE (end);
722 int start_byte = CHAR_TO_BYTE (start);
723 int tem;
725 /* Consult the newline cache, if appropriate. */
726 if (target == '\n' && newline_cache)
728 int next_change;
729 immediate_quit = 0;
730 while (region_cache_backward
731 (current_buffer, newline_cache, start_byte, &next_change))
732 start_byte = next_change;
733 immediate_quit = allow_quit;
735 /* Start should never be at or before end. */
736 if (start_byte <= ceiling_byte)
737 start_byte = ceiling_byte + 1;
739 /* Now the text before start is an unknown region, and
740 next_change is the position of the next known region. */
741 ceiling_byte = max (next_change, ceiling_byte);
744 /* Stop scanning before the gap. */
745 tem = BUFFER_FLOOR_OF (start_byte - 1);
746 ceiling_byte = max (tem, ceiling_byte);
749 /* The termination address of the dumb loop. */
750 register unsigned char *ceiling_addr = BYTE_POS_ADDR (ceiling_byte);
751 register unsigned char *cursor = BYTE_POS_ADDR (start_byte - 1);
752 unsigned char *base = cursor;
754 while (cursor >= ceiling_addr)
756 unsigned char *scan_start = cursor;
758 while (*cursor != target && --cursor >= ceiling_addr)
761 /* If we're looking for newlines, cache the fact that
762 the region from after the cursor to start is free of them. */
763 if (target == '\n' && newline_cache)
764 know_region_cache (current_buffer, newline_cache,
765 start_byte + cursor - base,
766 start_byte + scan_start - base);
768 /* Did we find the target character? */
769 if (cursor >= ceiling_addr)
771 if (++count >= 0)
773 immediate_quit = 0;
774 return BYTE_TO_CHAR (start_byte + cursor - base);
776 cursor--;
780 start = BYTE_TO_CHAR (start_byte + cursor - base);
784 immediate_quit = 0;
785 if (shortage != 0)
786 *shortage = count * direction;
787 return start;
790 /* Search for COUNT instances of a line boundary, which means either a
791 newline or (if selective display enabled) a carriage return.
792 Start at START. If COUNT is negative, search backwards.
794 We report the resulting position by calling TEMP_SET_PT_BOTH.
796 If we find COUNT instances. we position after (always after,
797 even if scanning backwards) the COUNTth match, and return 0.
799 If we don't find COUNT instances before reaching the end of the
800 buffer (or the beginning, if scanning backwards), we return
801 the number of line boundaries left unfound, and position at
802 the limit we bumped up against.
804 If ALLOW_QUIT is non-zero, set immediate_quit. That's good to do
805 except in special cases. */
808 scan_newline (start, start_byte, limit, limit_byte, count, allow_quit)
809 int start, start_byte;
810 int limit, limit_byte;
811 register int count;
812 int allow_quit;
814 int direction = ((count > 0) ? 1 : -1);
816 register unsigned char *cursor;
817 unsigned char *base;
819 register int ceiling;
820 register unsigned char *ceiling_addr;
822 int old_immediate_quit = immediate_quit;
824 /* The code that follows is like scan_buffer
825 but checks for either newline or carriage return. */
827 if (allow_quit)
828 immediate_quit++;
830 start_byte = CHAR_TO_BYTE (start);
832 if (count > 0)
834 while (start_byte < limit_byte)
836 ceiling = BUFFER_CEILING_OF (start_byte);
837 ceiling = min (limit_byte - 1, ceiling);
838 ceiling_addr = BYTE_POS_ADDR (ceiling) + 1;
839 base = (cursor = BYTE_POS_ADDR (start_byte));
840 while (1)
842 while (*cursor != '\n' && ++cursor != ceiling_addr)
845 if (cursor != ceiling_addr)
847 if (--count == 0)
849 immediate_quit = old_immediate_quit;
850 start_byte = start_byte + cursor - base + 1;
851 start = BYTE_TO_CHAR (start_byte);
852 TEMP_SET_PT_BOTH (start, start_byte);
853 return 0;
855 else
856 if (++cursor == ceiling_addr)
857 break;
859 else
860 break;
862 start_byte += cursor - base;
865 else
867 while (start_byte > limit_byte)
869 ceiling = BUFFER_FLOOR_OF (start_byte - 1);
870 ceiling = max (limit_byte, ceiling);
871 ceiling_addr = BYTE_POS_ADDR (ceiling) - 1;
872 base = (cursor = BYTE_POS_ADDR (start_byte - 1) + 1);
873 while (1)
875 while (--cursor != ceiling_addr && *cursor != '\n')
878 if (cursor != ceiling_addr)
880 if (++count == 0)
882 immediate_quit = old_immediate_quit;
883 /* Return the position AFTER the match we found. */
884 start_byte = start_byte + cursor - base + 1;
885 start = BYTE_TO_CHAR (start_byte);
886 TEMP_SET_PT_BOTH (start, start_byte);
887 return 0;
890 else
891 break;
893 /* Here we add 1 to compensate for the last decrement
894 of CURSOR, which took it past the valid range. */
895 start_byte += cursor - base + 1;
899 TEMP_SET_PT_BOTH (limit, limit_byte);
900 immediate_quit = old_immediate_quit;
902 return count * direction;
906 find_next_newline_no_quit (from, cnt)
907 register int from, cnt;
909 return scan_buffer ('\n', from, 0, cnt, (int *) 0, 0);
912 /* Like find_next_newline, but returns position before the newline,
913 not after, and only search up to TO. This isn't just
914 find_next_newline (...)-1, because you might hit TO. */
917 find_before_next_newline (from, to, cnt)
918 int from, to, cnt;
920 int shortage;
921 int pos = scan_buffer ('\n', from, to, cnt, &shortage, 1);
923 if (shortage == 0)
924 pos--;
926 return pos;
929 /* Subroutines of Lisp buffer search functions. */
931 static Lisp_Object
932 search_command (string, bound, noerror, count, direction, RE, posix)
933 Lisp_Object string, bound, noerror, count;
934 int direction;
935 int RE;
936 int posix;
938 register int np;
939 int lim, lim_byte;
940 int n = direction;
942 if (!NILP (count))
944 CHECK_NUMBER (count);
945 n *= XINT (count);
948 CHECK_STRING (string);
949 if (NILP (bound))
951 if (n > 0)
952 lim = ZV, lim_byte = ZV_BYTE;
953 else
954 lim = BEGV, lim_byte = BEGV_BYTE;
956 else
958 CHECK_NUMBER_COERCE_MARKER (bound);
959 lim = XINT (bound);
960 if (n > 0 ? lim < PT : lim > PT)
961 error ("Invalid search bound (wrong side of point)");
962 if (lim > ZV)
963 lim = ZV, lim_byte = ZV_BYTE;
964 else if (lim < BEGV)
965 lim = BEGV, lim_byte = BEGV_BYTE;
966 else
967 lim_byte = CHAR_TO_BYTE (lim);
970 /* This is so set_image_of_range_1 in regex.c can find the EQV table. */
971 XCHAR_TABLE (current_buffer->case_canon_table)->extras[2]
972 = current_buffer->case_eqv_table;
974 np = search_buffer (string, PT, PT_BYTE, lim, lim_byte, n, RE,
975 (!NILP (current_buffer->case_fold_search)
976 ? current_buffer->case_canon_table
977 : Qnil),
978 (!NILP (current_buffer->case_fold_search)
979 ? current_buffer->case_eqv_table
980 : Qnil),
981 posix);
982 if (np <= 0)
984 if (NILP (noerror))
985 xsignal1 (Qsearch_failed, string);
987 if (!EQ (noerror, Qt))
989 if (lim < BEGV || lim > ZV)
990 abort ();
991 SET_PT_BOTH (lim, lim_byte);
992 return Qnil;
993 #if 0 /* This would be clean, but maybe programs depend on
994 a value of nil here. */
995 np = lim;
996 #endif
998 else
999 return Qnil;
1002 if (np < BEGV || np > ZV)
1003 abort ();
1005 SET_PT (np);
1007 return make_number (np);
1010 /* Return 1 if REGEXP it matches just one constant string. */
1012 static int
1013 trivial_regexp_p (regexp)
1014 Lisp_Object regexp;
1016 int len = SBYTES (regexp);
1017 unsigned char *s = SDATA (regexp);
1018 while (--len >= 0)
1020 switch (*s++)
1022 case '.': case '*': case '+': case '?': case '[': case '^': case '$':
1023 return 0;
1024 case '\\':
1025 if (--len < 0)
1026 return 0;
1027 switch (*s++)
1029 case '|': case '(': case ')': case '`': case '\'': case 'b':
1030 case 'B': case '<': case '>': case 'w': case 'W': case 's':
1031 case 'S': case '=': case '{': case '}': case '_':
1032 case 'c': case 'C': /* for categoryspec and notcategoryspec */
1033 case '1': case '2': case '3': case '4': case '5':
1034 case '6': case '7': case '8': case '9':
1035 return 0;
1039 return 1;
1042 /* Search for the n'th occurrence of STRING in the current buffer,
1043 starting at position POS and stopping at position LIM,
1044 treating STRING as a literal string if RE is false or as
1045 a regular expression if RE is true.
1047 If N is positive, searching is forward and LIM must be greater than POS.
1048 If N is negative, searching is backward and LIM must be less than POS.
1050 Returns -x if x occurrences remain to be found (x > 0),
1051 or else the position at the beginning of the Nth occurrence
1052 (if searching backward) or the end (if searching forward).
1054 POSIX is nonzero if we want full backtracking (POSIX style)
1055 for this pattern. 0 means backtrack only enough to get a valid match. */
1057 #define TRANSLATE(out, trt, d) \
1058 do \
1060 if (! NILP (trt)) \
1062 Lisp_Object temp; \
1063 temp = Faref (trt, make_number (d)); \
1064 if (INTEGERP (temp)) \
1065 out = XINT (temp); \
1066 else \
1067 out = d; \
1069 else \
1070 out = d; \
1072 while (0)
1074 /* Only used in search_buffer, to record the end position of the match
1075 when searching regexps and SEARCH_REGS should not be changed
1076 (i.e. Vinhibit_changing_match_data is non-nil). */
1077 static struct re_registers search_regs_1;
1079 static int
1080 search_buffer (string, pos, pos_byte, lim, lim_byte, n,
1081 RE, trt, inverse_trt, posix)
1082 Lisp_Object string;
1083 int pos;
1084 int pos_byte;
1085 int lim;
1086 int lim_byte;
1087 int n;
1088 int RE;
1089 Lisp_Object trt;
1090 Lisp_Object inverse_trt;
1091 int posix;
1093 int len = SCHARS (string);
1094 int len_byte = SBYTES (string);
1095 register int i;
1097 if (running_asynch_code)
1098 save_search_regs ();
1100 /* Searching 0 times means don't move. */
1101 /* Null string is found at starting position. */
1102 if (len == 0 || n == 0)
1104 set_search_regs (pos_byte, 0);
1105 return pos;
1108 if (RE && !(trivial_regexp_p (string) && NILP (Vsearch_spaces_regexp)))
1110 unsigned char *p1, *p2;
1111 int s1, s2;
1112 struct re_pattern_buffer *bufp;
1114 bufp = compile_pattern (string,
1115 (NILP (Vinhibit_changing_match_data)
1116 ? &search_regs : &search_regs_1),
1117 trt, posix,
1118 !NILP (current_buffer->enable_multibyte_characters));
1120 immediate_quit = 1; /* Quit immediately if user types ^G,
1121 because letting this function finish
1122 can take too long. */
1123 QUIT; /* Do a pending quit right away,
1124 to avoid paradoxical behavior */
1125 /* Get pointers and sizes of the two strings
1126 that make up the visible portion of the buffer. */
1128 p1 = BEGV_ADDR;
1129 s1 = GPT_BYTE - BEGV_BYTE;
1130 p2 = GAP_END_ADDR;
1131 s2 = ZV_BYTE - GPT_BYTE;
1132 if (s1 < 0)
1134 p2 = p1;
1135 s2 = ZV_BYTE - BEGV_BYTE;
1136 s1 = 0;
1138 if (s2 < 0)
1140 s1 = ZV_BYTE - BEGV_BYTE;
1141 s2 = 0;
1143 re_match_object = Qnil;
1145 while (n < 0)
1147 int val;
1148 val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
1149 pos_byte - BEGV_BYTE, lim_byte - pos_byte,
1150 (NILP (Vinhibit_changing_match_data)
1151 ? &search_regs : &search_regs_1),
1152 /* Don't allow match past current point */
1153 pos_byte - BEGV_BYTE);
1154 if (val == -2)
1156 matcher_overflow ();
1158 if (val >= 0)
1160 if (NILP (Vinhibit_changing_match_data))
1162 pos_byte = search_regs.start[0] + BEGV_BYTE;
1163 for (i = 0; i < search_regs.num_regs; i++)
1164 if (search_regs.start[i] >= 0)
1166 search_regs.start[i]
1167 = BYTE_TO_CHAR (search_regs.start[i] + BEGV_BYTE);
1168 search_regs.end[i]
1169 = BYTE_TO_CHAR (search_regs.end[i] + BEGV_BYTE);
1171 XSETBUFFER (last_thing_searched, current_buffer);
1172 /* Set pos to the new position. */
1173 pos = search_regs.start[0];
1175 else
1177 pos_byte = search_regs_1.start[0] + BEGV_BYTE;
1178 /* Set pos to the new position. */
1179 pos = BYTE_TO_CHAR (search_regs_1.start[0] + BEGV_BYTE);
1182 else
1184 immediate_quit = 0;
1185 return (n);
1187 n++;
1189 while (n > 0)
1191 int val;
1192 val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
1193 pos_byte - BEGV_BYTE, lim_byte - pos_byte,
1194 (NILP (Vinhibit_changing_match_data)
1195 ? &search_regs : &search_regs_1),
1196 lim_byte - BEGV_BYTE);
1197 if (val == -2)
1199 matcher_overflow ();
1201 if (val >= 0)
1203 if (NILP (Vinhibit_changing_match_data))
1205 pos_byte = search_regs.end[0] + BEGV_BYTE;
1206 for (i = 0; i < search_regs.num_regs; i++)
1207 if (search_regs.start[i] >= 0)
1209 search_regs.start[i]
1210 = BYTE_TO_CHAR (search_regs.start[i] + BEGV_BYTE);
1211 search_regs.end[i]
1212 = BYTE_TO_CHAR (search_regs.end[i] + BEGV_BYTE);
1214 XSETBUFFER (last_thing_searched, current_buffer);
1215 pos = search_regs.end[0];
1217 else
1219 pos_byte = search_regs_1.end[0] + BEGV_BYTE;
1220 pos = BYTE_TO_CHAR (search_regs_1.end[0] + BEGV_BYTE);
1223 else
1225 immediate_quit = 0;
1226 return (0 - n);
1228 n--;
1230 immediate_quit = 0;
1231 return (pos);
1233 else /* non-RE case */
1235 unsigned char *raw_pattern, *pat;
1236 int raw_pattern_size;
1237 int raw_pattern_size_byte;
1238 unsigned char *patbuf;
1239 int multibyte = !NILP (current_buffer->enable_multibyte_characters);
1240 unsigned char *base_pat;
1241 /* Set to positive if we find a non-ASCII char that need
1242 translation. Otherwise set to zero later. */
1243 int char_base = -1;
1244 int boyer_moore_ok = 1;
1246 /* MULTIBYTE says whether the text to be searched is multibyte.
1247 We must convert PATTERN to match that, or we will not really
1248 find things right. */
1250 if (multibyte == STRING_MULTIBYTE (string))
1252 raw_pattern = (unsigned char *) SDATA (string);
1253 raw_pattern_size = SCHARS (string);
1254 raw_pattern_size_byte = SBYTES (string);
1256 else if (multibyte)
1258 raw_pattern_size = SCHARS (string);
1259 raw_pattern_size_byte
1260 = count_size_as_multibyte (SDATA (string),
1261 raw_pattern_size);
1262 raw_pattern = (unsigned char *) alloca (raw_pattern_size_byte + 1);
1263 copy_text (SDATA (string), raw_pattern,
1264 SCHARS (string), 0, 1);
1266 else
1268 /* Converting multibyte to single-byte.
1270 ??? Perhaps this conversion should be done in a special way
1271 by subtracting nonascii-insert-offset from each non-ASCII char,
1272 so that only the multibyte chars which really correspond to
1273 the chosen single-byte character set can possibly match. */
1274 raw_pattern_size = SCHARS (string);
1275 raw_pattern_size_byte = SCHARS (string);
1276 raw_pattern = (unsigned char *) alloca (raw_pattern_size + 1);
1277 copy_text (SDATA (string), raw_pattern,
1278 SBYTES (string), 1, 0);
1281 /* Copy and optionally translate the pattern. */
1282 len = raw_pattern_size;
1283 len_byte = raw_pattern_size_byte;
1284 patbuf = (unsigned char *) alloca (len * MAX_MULTIBYTE_LENGTH);
1285 pat = patbuf;
1286 base_pat = raw_pattern;
1287 if (multibyte)
1289 /* Fill patbuf by translated characters in STRING while
1290 checking if we can use boyer-moore search. If TRT is
1291 non-nil, we can use boyer-moore search only if TRT can be
1292 represented by the byte array of 256 elements. For that,
1293 all non-ASCII case-equivalents of all case-senstive
1294 characters in STRING must belong to the same charset and
1295 row. */
1297 while (--len >= 0)
1299 unsigned char str_base[MAX_MULTIBYTE_LENGTH], *str;
1300 int c, translated, inverse;
1301 int in_charlen, charlen;
1303 /* If we got here and the RE flag is set, it's because we're
1304 dealing with a regexp known to be trivial, so the backslash
1305 just quotes the next character. */
1306 if (RE && *base_pat == '\\')
1308 len--;
1309 raw_pattern_size--;
1310 len_byte--;
1311 base_pat++;
1314 c = STRING_CHAR_AND_LENGTH (base_pat, len_byte, in_charlen);
1316 if (NILP (trt))
1318 str = base_pat;
1319 charlen = in_charlen;
1321 else
1323 /* Translate the character. */
1324 TRANSLATE (translated, trt, c);
1325 charlen = CHAR_STRING (translated, str_base);
1326 str = str_base;
1328 /* Check if C has any other case-equivalents. */
1329 TRANSLATE (inverse, inverse_trt, c);
1330 /* If so, check if we can use boyer-moore. */
1331 if (c != inverse && boyer_moore_ok)
1333 /* Check if all equivalents belong to the same
1334 group of characters. Note that the check of C
1335 itself is done by the last iteration. */
1336 int this_char_base = -1;
1338 while (boyer_moore_ok)
1340 if (ASCII_BYTE_P (inverse))
1342 if (this_char_base > 0)
1343 boyer_moore_ok = 0;
1344 else
1346 this_char_base = 0;
1347 if (char_base < 0)
1348 char_base = this_char_base;
1351 else if (CHAR_BYTE8_P (inverse))
1352 /* Boyer-moore search can't handle a
1353 translation of an eight-bit
1354 character. */
1355 boyer_moore_ok = 0;
1356 else if (this_char_base < 0)
1358 this_char_base = inverse & ~0x3F;
1359 if (char_base < 0)
1360 char_base = this_char_base;
1361 else if (char_base > 0
1362 && this_char_base != char_base)
1363 boyer_moore_ok = 0;
1365 else if ((inverse & ~0x3F) != this_char_base)
1366 boyer_moore_ok = 0;
1367 if (c == inverse)
1368 break;
1369 TRANSLATE (inverse, inverse_trt, inverse);
1373 if (char_base < 0)
1374 char_base = 0;
1376 /* Store this character into the translated pattern. */
1377 bcopy (str, pat, charlen);
1378 pat += charlen;
1379 base_pat += in_charlen;
1380 len_byte -= in_charlen;
1383 else
1385 /* Unibyte buffer. */
1386 char_base = 0;
1387 while (--len >= 0)
1389 int c, translated;
1391 /* If we got here and the RE flag is set, it's because we're
1392 dealing with a regexp known to be trivial, so the backslash
1393 just quotes the next character. */
1394 if (RE && *base_pat == '\\')
1396 len--;
1397 raw_pattern_size--;
1398 base_pat++;
1400 c = *base_pat++;
1401 TRANSLATE (translated, trt, c);
1402 *pat++ = translated;
1406 len_byte = pat - patbuf;
1407 len = raw_pattern_size;
1408 pat = base_pat = patbuf;
1410 if (boyer_moore_ok)
1411 return boyer_moore (n, pat, len, len_byte, trt, inverse_trt,
1412 pos, pos_byte, lim, lim_byte,
1413 char_base);
1414 else
1415 return simple_search (n, pat, len, len_byte, trt,
1416 pos, pos_byte, lim, lim_byte);
1420 /* Do a simple string search N times for the string PAT,
1421 whose length is LEN/LEN_BYTE,
1422 from buffer position POS/POS_BYTE until LIM/LIM_BYTE.
1423 TRT is the translation table.
1425 Return the character position where the match is found.
1426 Otherwise, if M matches remained to be found, return -M.
1428 This kind of search works regardless of what is in PAT and
1429 regardless of what is in TRT. It is used in cases where
1430 boyer_moore cannot work. */
1432 static int
1433 simple_search (n, pat, len, len_byte, trt, pos, pos_byte, lim, lim_byte)
1434 int n;
1435 unsigned char *pat;
1436 int len, len_byte;
1437 Lisp_Object trt;
1438 int pos, pos_byte;
1439 int lim, lim_byte;
1441 int multibyte = ! NILP (current_buffer->enable_multibyte_characters);
1442 int forward = n > 0;
1443 /* Number of buffer bytes matched. Note that this may be different
1444 from len_byte in a multibyte buffer. */
1445 int match_byte;
1447 if (lim > pos && multibyte)
1448 while (n > 0)
1450 while (1)
1452 /* Try matching at position POS. */
1453 int this_pos = pos;
1454 int this_pos_byte = pos_byte;
1455 int this_len = len;
1456 int this_len_byte = len_byte;
1457 unsigned char *p = pat;
1458 if (pos + len > lim || pos_byte + len_byte > lim_byte)
1459 goto stop;
1461 while (this_len > 0)
1463 int charlen, buf_charlen;
1464 int pat_ch, buf_ch;
1466 pat_ch = STRING_CHAR_AND_LENGTH (p, this_len_byte, charlen);
1467 buf_ch = STRING_CHAR_AND_LENGTH (BYTE_POS_ADDR (this_pos_byte),
1468 ZV_BYTE - this_pos_byte,
1469 buf_charlen);
1470 TRANSLATE (buf_ch, trt, buf_ch);
1472 if (buf_ch != pat_ch)
1473 break;
1475 this_len_byte -= charlen;
1476 this_len--;
1477 p += charlen;
1479 this_pos_byte += buf_charlen;
1480 this_pos++;
1483 if (this_len == 0)
1485 match_byte = this_pos_byte - pos_byte;
1486 pos += len;
1487 pos_byte += match_byte;
1488 break;
1491 INC_BOTH (pos, pos_byte);
1494 n--;
1496 else if (lim > pos)
1497 while (n > 0)
1499 while (1)
1501 /* Try matching at position POS. */
1502 int this_pos = pos;
1503 int this_len = len;
1504 unsigned char *p = pat;
1506 if (pos + len > lim)
1507 goto stop;
1509 while (this_len > 0)
1511 int pat_ch = *p++;
1512 int buf_ch = FETCH_BYTE (this_pos);
1513 TRANSLATE (buf_ch, trt, buf_ch);
1515 if (buf_ch != pat_ch)
1516 break;
1518 this_len--;
1519 this_pos++;
1522 if (this_len == 0)
1524 match_byte = len;
1525 pos += len;
1526 break;
1529 pos++;
1532 n--;
1534 /* Backwards search. */
1535 else if (lim < pos && multibyte)
1536 while (n < 0)
1538 while (1)
1540 /* Try matching at position POS. */
1541 int this_pos = pos - len;
1542 int this_pos_byte;
1543 int this_len = len;
1544 int this_len_byte = len_byte;
1545 unsigned char *p = pat;
1547 if (this_pos < lim || (pos_byte - len_byte) < lim_byte)
1548 goto stop;
1549 this_pos_byte = CHAR_TO_BYTE (this_pos);
1550 match_byte = pos_byte - this_pos_byte;
1552 while (this_len > 0)
1554 int charlen, buf_charlen;
1555 int pat_ch, buf_ch;
1557 pat_ch = STRING_CHAR_AND_LENGTH (p, this_len_byte, charlen);
1558 buf_ch = STRING_CHAR_AND_LENGTH (BYTE_POS_ADDR (this_pos_byte),
1559 ZV_BYTE - this_pos_byte,
1560 buf_charlen);
1561 TRANSLATE (buf_ch, trt, buf_ch);
1563 if (buf_ch != pat_ch)
1564 break;
1566 this_len_byte -= charlen;
1567 this_len--;
1568 p += charlen;
1569 this_pos_byte += buf_charlen;
1570 this_pos++;
1573 if (this_len == 0)
1575 pos -= len;
1576 pos_byte -= match_byte;
1577 break;
1580 DEC_BOTH (pos, pos_byte);
1583 n++;
1585 else if (lim < pos)
1586 while (n < 0)
1588 while (1)
1590 /* Try matching at position POS. */
1591 int this_pos = pos - len;
1592 int this_len = len;
1593 unsigned char *p = pat;
1595 if (this_pos < lim)
1596 goto stop;
1598 while (this_len > 0)
1600 int pat_ch = *p++;
1601 int buf_ch = FETCH_BYTE (this_pos);
1602 TRANSLATE (buf_ch, trt, buf_ch);
1604 if (buf_ch != pat_ch)
1605 break;
1606 this_len--;
1607 this_pos++;
1610 if (this_len == 0)
1612 match_byte = len;
1613 pos -= len;
1614 break;
1617 pos--;
1620 n++;
1623 stop:
1624 if (n == 0)
1626 if (forward)
1627 set_search_regs ((multibyte ? pos_byte : pos) - match_byte, match_byte);
1628 else
1629 set_search_regs (multibyte ? pos_byte : pos, match_byte);
1631 return pos;
1633 else if (n > 0)
1634 return -n;
1635 else
1636 return n;
1639 /* Do Boyer-Moore search N times for the string BASE_PAT,
1640 whose length is LEN/LEN_BYTE,
1641 from buffer position POS/POS_BYTE until LIM/LIM_BYTE.
1642 DIRECTION says which direction we search in.
1643 TRT and INVERSE_TRT are translation tables.
1644 Characters in PAT are already translated by TRT.
1646 This kind of search works if all the characters in BASE_PAT that
1647 have nontrivial translation are the same aside from the last byte.
1648 This makes it possible to translate just the last byte of a
1649 character, and do so after just a simple test of the context.
1650 CHAR_BASE is nonzero if there is such a non-ASCII character.
1652 If that criterion is not satisfied, do not call this function. */
1654 static int
1655 boyer_moore (n, base_pat, len, len_byte, trt, inverse_trt,
1656 pos, pos_byte, lim, lim_byte, char_base)
1657 int n;
1658 unsigned char *base_pat;
1659 int len, len_byte;
1660 Lisp_Object trt;
1661 Lisp_Object inverse_trt;
1662 int pos, pos_byte;
1663 int lim, lim_byte;
1664 int char_base;
1666 int direction = ((n > 0) ? 1 : -1);
1667 register int dirlen;
1668 int infinity, limit, stride_for_teases = 0;
1669 register int *BM_tab;
1670 int *BM_tab_base;
1671 register unsigned char *cursor, *p_limit;
1672 register int i, j;
1673 unsigned char *pat, *pat_end;
1674 int multibyte = ! NILP (current_buffer->enable_multibyte_characters);
1676 unsigned char simple_translate[0400];
1677 /* These are set to the preceding bytes of a byte to be translated
1678 if char_base is nonzero. As the maximum byte length of a
1679 multibyte character is 5, we have to check at most four previous
1680 bytes. */
1681 int translate_prev_byte1 = 0;
1682 int translate_prev_byte2 = 0;
1683 int translate_prev_byte3 = 0;
1684 int translate_prev_byte4 = 0;
1686 BM_tab = (int *) alloca (0400 * sizeof (int));
1688 /* The general approach is that we are going to maintain that we know */
1689 /* the first (closest to the present position, in whatever direction */
1690 /* we're searching) character that could possibly be the last */
1691 /* (furthest from present position) character of a valid match. We */
1692 /* advance the state of our knowledge by looking at that character */
1693 /* and seeing whether it indeed matches the last character of the */
1694 /* pattern. If it does, we take a closer look. If it does not, we */
1695 /* move our pointer (to putative last characters) as far as is */
1696 /* logically possible. This amount of movement, which I call a */
1697 /* stride, will be the length of the pattern if the actual character */
1698 /* appears nowhere in the pattern, otherwise it will be the distance */
1699 /* from the last occurrence of that character to the end of the */
1700 /* pattern. */
1701 /* As a coding trick, an enormous stride is coded into the table for */
1702 /* characters that match the last character. This allows use of only */
1703 /* a single test, a test for having gone past the end of the */
1704 /* permissible match region, to test for both possible matches (when */
1705 /* the stride goes past the end immediately) and failure to */
1706 /* match (where you get nudged past the end one stride at a time). */
1708 /* Here we make a "mickey mouse" BM table. The stride of the search */
1709 /* is determined only by the last character of the putative match. */
1710 /* If that character does not match, we will stride the proper */
1711 /* distance to propose a match that superimposes it on the last */
1712 /* instance of a character that matches it (per trt), or misses */
1713 /* it entirely if there is none. */
1715 dirlen = len_byte * direction;
1716 infinity = dirlen - (lim_byte + pos_byte + len_byte + len_byte) * direction;
1718 /* Record position after the end of the pattern. */
1719 pat_end = base_pat + len_byte;
1720 /* BASE_PAT points to a character that we start scanning from.
1721 It is the first character in a forward search,
1722 the last character in a backward search. */
1723 if (direction < 0)
1724 base_pat = pat_end - 1;
1726 BM_tab_base = BM_tab;
1727 BM_tab += 0400;
1728 j = dirlen; /* to get it in a register */
1729 /* A character that does not appear in the pattern induces a */
1730 /* stride equal to the pattern length. */
1731 while (BM_tab_base != BM_tab)
1733 *--BM_tab = j;
1734 *--BM_tab = j;
1735 *--BM_tab = j;
1736 *--BM_tab = j;
1739 /* We use this for translation, instead of TRT itself.
1740 We fill this in to handle the characters that actually
1741 occur in the pattern. Others don't matter anyway! */
1742 bzero (simple_translate, sizeof simple_translate);
1743 for (i = 0; i < 0400; i++)
1744 simple_translate[i] = i;
1746 if (char_base)
1748 /* Setup translate_prev_byte1/2/3/4 from CHAR_BASE. Only a
1749 byte following them are the target of translation. */
1750 unsigned char str[MAX_MULTIBYTE_LENGTH];
1751 int len = CHAR_STRING (char_base, str);
1753 translate_prev_byte1 = str[len - 2];
1754 if (len > 2)
1756 translate_prev_byte2 = str[len - 3];
1757 if (len > 3)
1759 translate_prev_byte3 = str[len - 4];
1760 if (len > 4)
1761 translate_prev_byte4 = str[len - 5];
1766 i = 0;
1767 while (i != infinity)
1769 unsigned char *ptr = base_pat + i;
1770 i += direction;
1771 if (i == dirlen)
1772 i = infinity;
1773 if (! NILP (trt))
1775 /* If the byte currently looking at is the last of a
1776 character to check case-equivalents, set CH to that
1777 character. An ASCII character and a non-ASCII character
1778 matching with CHAR_BASE are to be checked. */
1779 int ch = -1;
1781 if (ASCII_BYTE_P (*ptr) || ! multibyte)
1782 ch = *ptr;
1783 else if (char_base
1784 && ((pat_end - ptr) == 1 || CHAR_HEAD_P (ptr[1])))
1786 unsigned char *charstart = ptr - 1;
1788 while (! (CHAR_HEAD_P (*charstart)))
1789 charstart--;
1790 ch = STRING_CHAR (charstart, ptr - charstart + 1);
1791 if (char_base != (ch & ~0x3F))
1792 ch = -1;
1795 if (ch >= 0200)
1796 j = (ch & 0x3F) | 0200;
1797 else
1798 j = *ptr;
1800 if (i == infinity)
1801 stride_for_teases = BM_tab[j];
1803 BM_tab[j] = dirlen - i;
1804 /* A translation table is accompanied by its inverse -- see */
1805 /* comment following downcase_table for details */
1806 if (ch >= 0)
1808 int starting_ch = ch;
1809 int starting_j = j;
1811 while (1)
1813 TRANSLATE (ch, inverse_trt, ch);
1814 if (ch >= 0200)
1815 j = (ch & 0x3F) | 0200;
1816 else
1817 j = ch;
1819 /* For all the characters that map into CH,
1820 set up simple_translate to map the last byte
1821 into STARTING_J. */
1822 simple_translate[j] = starting_j;
1823 if (ch == starting_ch)
1824 break;
1825 BM_tab[j] = dirlen - i;
1829 else
1831 j = *ptr;
1833 if (i == infinity)
1834 stride_for_teases = BM_tab[j];
1835 BM_tab[j] = dirlen - i;
1837 /* stride_for_teases tells how much to stride if we get a */
1838 /* match on the far character but are subsequently */
1839 /* disappointed, by recording what the stride would have been */
1840 /* for that character if the last character had been */
1841 /* different. */
1843 infinity = dirlen - infinity;
1844 pos_byte += dirlen - ((direction > 0) ? direction : 0);
1845 /* loop invariant - POS_BYTE points at where last char (first
1846 char if reverse) of pattern would align in a possible match. */
1847 while (n != 0)
1849 int tail_end;
1850 unsigned char *tail_end_ptr;
1852 /* It's been reported that some (broken) compiler thinks that
1853 Boolean expressions in an arithmetic context are unsigned.
1854 Using an explicit ?1:0 prevents this. */
1855 if ((lim_byte - pos_byte - ((direction > 0) ? 1 : 0)) * direction
1856 < 0)
1857 return (n * (0 - direction));
1858 /* First we do the part we can by pointers (maybe nothing) */
1859 QUIT;
1860 pat = base_pat;
1861 limit = pos_byte - dirlen + direction;
1862 if (direction > 0)
1864 limit = BUFFER_CEILING_OF (limit);
1865 /* LIMIT is now the last (not beyond-last!) value POS_BYTE
1866 can take on without hitting edge of buffer or the gap. */
1867 limit = min (limit, pos_byte + 20000);
1868 limit = min (limit, lim_byte - 1);
1870 else
1872 limit = BUFFER_FLOOR_OF (limit);
1873 /* LIMIT is now the last (not beyond-last!) value POS_BYTE
1874 can take on without hitting edge of buffer or the gap. */
1875 limit = max (limit, pos_byte - 20000);
1876 limit = max (limit, lim_byte);
1878 tail_end = BUFFER_CEILING_OF (pos_byte) + 1;
1879 tail_end_ptr = BYTE_POS_ADDR (tail_end);
1881 if ((limit - pos_byte) * direction > 20)
1883 unsigned char *p2;
1885 p_limit = BYTE_POS_ADDR (limit);
1886 p2 = (cursor = BYTE_POS_ADDR (pos_byte));
1887 /* In this loop, pos + cursor - p2 is the surrogate for pos */
1888 while (1) /* use one cursor setting as long as i can */
1890 if (direction > 0) /* worth duplicating */
1892 /* Use signed comparison if appropriate
1893 to make cursor+infinity sure to be > p_limit.
1894 Assuming that the buffer lies in a range of addresses
1895 that are all "positive" (as ints) or all "negative",
1896 either kind of comparison will work as long
1897 as we don't step by infinity. So pick the kind
1898 that works when we do step by infinity. */
1899 if ((EMACS_INT) (p_limit + infinity) > (EMACS_INT) p_limit)
1900 while ((EMACS_INT) cursor <= (EMACS_INT) p_limit)
1901 cursor += BM_tab[*cursor];
1902 else
1903 while ((EMACS_UINT) cursor <= (EMACS_UINT) p_limit)
1904 cursor += BM_tab[*cursor];
1906 else
1908 if ((EMACS_INT) (p_limit + infinity) < (EMACS_INT) p_limit)
1909 while ((EMACS_INT) cursor >= (EMACS_INT) p_limit)
1910 cursor += BM_tab[*cursor];
1911 else
1912 while ((EMACS_UINT) cursor >= (EMACS_UINT) p_limit)
1913 cursor += BM_tab[*cursor];
1915 /* If you are here, cursor is beyond the end of the searched region. */
1916 /* This can happen if you match on the far character of the pattern, */
1917 /* because the "stride" of that character is infinity, a number able */
1918 /* to throw you well beyond the end of the search. It can also */
1919 /* happen if you fail to match within the permitted region and would */
1920 /* otherwise try a character beyond that region */
1921 if ((cursor - p_limit) * direction <= len_byte)
1922 break; /* a small overrun is genuine */
1923 cursor -= infinity; /* large overrun = hit */
1924 i = dirlen - direction;
1925 if (! NILP (trt))
1927 while ((i -= direction) + direction != 0)
1929 int ch;
1930 cursor -= direction;
1931 /* Translate only the last byte of a character. */
1932 if (! multibyte
1933 || ((cursor == tail_end_ptr
1934 || CHAR_HEAD_P (cursor[1]))
1935 && (CHAR_HEAD_P (cursor[0])
1936 /* Check if this is the last byte of
1937 a translable character. */
1938 || (translate_prev_byte1 == cursor[-1]
1939 && (CHAR_HEAD_P (translate_prev_byte1)
1940 || (translate_prev_byte2 == cursor[-2]
1941 && (CHAR_HEAD_P (translate_prev_byte2)
1942 || (translate_prev_byte3 == cursor[-3]))))))))
1943 ch = simple_translate[*cursor];
1944 else
1945 ch = *cursor;
1946 if (pat[i] != ch)
1947 break;
1950 else
1952 while ((i -= direction) + direction != 0)
1954 cursor -= direction;
1955 if (pat[i] != *cursor)
1956 break;
1959 cursor += dirlen - i - direction; /* fix cursor */
1960 if (i + direction == 0)
1962 int position, start, end;
1964 cursor -= direction;
1966 position = pos_byte + cursor - p2 + ((direction > 0)
1967 ? 1 - len_byte : 0);
1968 set_search_regs (position, len_byte);
1970 if (NILP (Vinhibit_changing_match_data))
1972 start = search_regs.start[0];
1973 end = search_regs.end[0];
1975 else
1976 /* If Vinhibit_changing_match_data is non-nil,
1977 search_regs will not be changed. So let's
1978 compute start and end here. */
1980 start = BYTE_TO_CHAR (position);
1981 end = BYTE_TO_CHAR (position + len_byte);
1984 if ((n -= direction) != 0)
1985 cursor += dirlen; /* to resume search */
1986 else
1987 return direction > 0 ? end : start;
1989 else
1990 cursor += stride_for_teases; /* <sigh> we lose - */
1992 pos_byte += cursor - p2;
1994 else
1995 /* Now we'll pick up a clump that has to be done the hard */
1996 /* way because it covers a discontinuity */
1998 limit = ((direction > 0)
1999 ? BUFFER_CEILING_OF (pos_byte - dirlen + 1)
2000 : BUFFER_FLOOR_OF (pos_byte - dirlen - 1));
2001 limit = ((direction > 0)
2002 ? min (limit + len_byte, lim_byte - 1)
2003 : max (limit - len_byte, lim_byte));
2004 /* LIMIT is now the last value POS_BYTE can have
2005 and still be valid for a possible match. */
2006 while (1)
2008 /* This loop can be coded for space rather than */
2009 /* speed because it will usually run only once. */
2010 /* (the reach is at most len + 21, and typically */
2011 /* does not exceed len) */
2012 while ((limit - pos_byte) * direction >= 0)
2013 pos_byte += BM_tab[FETCH_BYTE (pos_byte)];
2014 /* now run the same tests to distinguish going off the */
2015 /* end, a match or a phony match. */
2016 if ((pos_byte - limit) * direction <= len_byte)
2017 break; /* ran off the end */
2018 /* Found what might be a match.
2019 Set POS_BYTE back to last (first if reverse) pos. */
2020 pos_byte -= infinity;
2021 i = dirlen - direction;
2022 while ((i -= direction) + direction != 0)
2024 int ch;
2025 unsigned char *ptr;
2026 pos_byte -= direction;
2027 ptr = BYTE_POS_ADDR (pos_byte);
2028 /* Translate only the last byte of a character. */
2029 if (! multibyte
2030 || ((ptr == tail_end_ptr
2031 || CHAR_HEAD_P (ptr[1]))
2032 && (CHAR_HEAD_P (ptr[0])
2033 /* Check if this is the last byte of a
2034 translable character. */
2035 || (translate_prev_byte1 == ptr[-1]
2036 && (CHAR_HEAD_P (translate_prev_byte1)
2037 || (translate_prev_byte2 == ptr[-2]
2038 && (CHAR_HEAD_P (translate_prev_byte2)
2039 || translate_prev_byte3 == ptr[-3])))))))
2040 ch = simple_translate[*ptr];
2041 else
2042 ch = *ptr;
2043 if (pat[i] != ch)
2044 break;
2046 /* Above loop has moved POS_BYTE part or all the way
2047 back to the first pos (last pos if reverse).
2048 Set it once again at the last (first if reverse) char. */
2049 pos_byte += dirlen - i- direction;
2050 if (i + direction == 0)
2052 int position, start, end;
2053 pos_byte -= direction;
2055 position = pos_byte + ((direction > 0) ? 1 - len_byte : 0);
2056 set_search_regs (position, len_byte);
2058 if (NILP (Vinhibit_changing_match_data))
2060 start = search_regs.start[0];
2061 end = search_regs.end[0];
2063 else
2064 /* If Vinhibit_changing_match_data is non-nil,
2065 search_regs will not be changed. So let's
2066 compute start and end here. */
2068 start = BYTE_TO_CHAR (position);
2069 end = BYTE_TO_CHAR (position + len_byte);
2072 if ((n -= direction) != 0)
2073 pos_byte += dirlen; /* to resume search */
2074 else
2075 return direction > 0 ? end : start;
2077 else
2078 pos_byte += stride_for_teases;
2081 /* We have done one clump. Can we continue? */
2082 if ((lim_byte - pos_byte) * direction < 0)
2083 return ((0 - n) * direction);
2085 return BYTE_TO_CHAR (pos_byte);
2088 /* Record beginning BEG_BYTE and end BEG_BYTE + NBYTES
2089 for the overall match just found in the current buffer.
2090 Also clear out the match data for registers 1 and up. */
2092 static void
2093 set_search_regs (beg_byte, nbytes)
2094 int beg_byte, nbytes;
2096 int i;
2098 if (!NILP (Vinhibit_changing_match_data))
2099 return;
2101 /* Make sure we have registers in which to store
2102 the match position. */
2103 if (search_regs.num_regs == 0)
2105 search_regs.start = (regoff_t *) xmalloc (2 * sizeof (regoff_t));
2106 search_regs.end = (regoff_t *) xmalloc (2 * sizeof (regoff_t));
2107 search_regs.num_regs = 2;
2110 /* Clear out the other registers. */
2111 for (i = 1; i < search_regs.num_regs; i++)
2113 search_regs.start[i] = -1;
2114 search_regs.end[i] = -1;
2117 search_regs.start[0] = BYTE_TO_CHAR (beg_byte);
2118 search_regs.end[0] = BYTE_TO_CHAR (beg_byte + nbytes);
2119 XSETBUFFER (last_thing_searched, current_buffer);
2122 /* Given a string of words separated by word delimiters,
2123 compute a regexp that matches those exact words
2124 separated by arbitrary punctuation. */
2126 static Lisp_Object
2127 wordify (string)
2128 Lisp_Object string;
2130 register unsigned char *p, *o;
2131 register int i, i_byte, len, punct_count = 0, word_count = 0;
2132 Lisp_Object val;
2133 int prev_c = 0;
2134 int adjust;
2136 CHECK_STRING (string);
2137 p = SDATA (string);
2138 len = SCHARS (string);
2140 for (i = 0, i_byte = 0; i < len; )
2142 int c;
2144 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c, string, i, i_byte);
2146 if (SYNTAX (c) != Sword)
2148 punct_count++;
2149 if (i > 0 && SYNTAX (prev_c) == Sword)
2150 word_count++;
2153 prev_c = c;
2156 if (SYNTAX (prev_c) == Sword)
2157 word_count++;
2158 if (!word_count)
2159 return empty_unibyte_string;
2161 adjust = - punct_count + 5 * (word_count - 1) + 4;
2162 if (STRING_MULTIBYTE (string))
2163 val = make_uninit_multibyte_string (len + adjust,
2164 SBYTES (string)
2165 + adjust);
2166 else
2167 val = make_uninit_string (len + adjust);
2169 o = SDATA (val);
2170 *o++ = '\\';
2171 *o++ = 'b';
2172 prev_c = 0;
2174 for (i = 0, i_byte = 0; i < len; )
2176 int c;
2177 int i_byte_orig = i_byte;
2179 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c, string, i, i_byte);
2181 if (SYNTAX (c) == Sword)
2183 bcopy (SDATA (string) + i_byte_orig, o,
2184 i_byte - i_byte_orig);
2185 o += i_byte - i_byte_orig;
2187 else if (i > 0 && SYNTAX (prev_c) == Sword && --word_count)
2189 *o++ = '\\';
2190 *o++ = 'W';
2191 *o++ = '\\';
2192 *o++ = 'W';
2193 *o++ = '*';
2196 prev_c = c;
2199 *o++ = '\\';
2200 *o++ = 'b';
2202 return val;
2205 DEFUN ("search-backward", Fsearch_backward, Ssearch_backward, 1, 4,
2206 "MSearch backward: ",
2207 doc: /* Search backward from point for STRING.
2208 Set point to the beginning of the occurrence found, and return point.
2209 An optional second argument bounds the search; it is a buffer position.
2210 The match found must not extend before that position.
2211 Optional third argument, if t, means if fail just return nil (no error).
2212 If not nil and not t, position at limit of search and return nil.
2213 Optional fourth argument is repeat count--search for successive occurrences.
2215 Search case-sensitivity is determined by the value of the variable
2216 `case-fold-search', which see.
2218 See also the functions `match-beginning', `match-end' and `replace-match'. */)
2219 (string, bound, noerror, count)
2220 Lisp_Object string, bound, noerror, count;
2222 return search_command (string, bound, noerror, count, -1, 0, 0);
2225 DEFUN ("search-forward", Fsearch_forward, Ssearch_forward, 1, 4, "MSearch: ",
2226 doc: /* Search forward from point for STRING.
2227 Set point to the end of the occurrence found, and return point.
2228 An optional second argument bounds the search; it is a buffer position.
2229 The match found must not extend after that position. A value of nil is
2230 equivalent to (point-max).
2231 Optional third argument, if t, means if fail just return nil (no error).
2232 If not nil and not t, move to limit of search and return nil.
2233 Optional fourth argument is repeat count--search for successive occurrences.
2235 Search case-sensitivity is determined by the value of the variable
2236 `case-fold-search', which see.
2238 See also the functions `match-beginning', `match-end' and `replace-match'. */)
2239 (string, bound, noerror, count)
2240 Lisp_Object string, bound, noerror, count;
2242 return search_command (string, bound, noerror, count, 1, 0, 0);
2245 DEFUN ("word-search-backward", Fword_search_backward, Sword_search_backward, 1, 4,
2246 "sWord search backward: ",
2247 doc: /* Search backward from point for STRING, ignoring differences in punctuation.
2248 Set point to the beginning of the occurrence found, and return point.
2249 An optional second argument bounds the search; it is a buffer position.
2250 The match found must not extend before that position.
2251 Optional third argument, if t, means if fail just return nil (no error).
2252 If not nil and not t, move to limit of search and return nil.
2253 Optional fourth argument is repeat count--search for successive occurrences. */)
2254 (string, bound, noerror, count)
2255 Lisp_Object string, bound, noerror, count;
2257 return search_command (wordify (string), bound, noerror, count, -1, 1, 0);
2260 DEFUN ("word-search-forward", Fword_search_forward, Sword_search_forward, 1, 4,
2261 "sWord search: ",
2262 doc: /* Search forward from point for STRING, ignoring differences in punctuation.
2263 Set point to the end of the occurrence found, and return point.
2264 An optional second argument bounds the search; it is a buffer position.
2265 The match found must not extend after that position.
2266 Optional third argument, if t, means if fail just return nil (no error).
2267 If not nil and not t, move to limit of search and return nil.
2268 Optional fourth argument is repeat count--search for successive occurrences. */)
2269 (string, bound, noerror, count)
2270 Lisp_Object string, bound, noerror, count;
2272 return search_command (wordify (string), bound, noerror, count, 1, 1, 0);
2275 DEFUN ("re-search-backward", Fre_search_backward, Sre_search_backward, 1, 4,
2276 "sRE search backward: ",
2277 doc: /* Search backward from point for match for regular expression REGEXP.
2278 Set point to the beginning of the match, and return point.
2279 The match found is the one starting last in the buffer
2280 and yet ending before the origin of the search.
2281 An optional second argument bounds the search; it is a buffer position.
2282 The match found must start at or after that position.
2283 Optional third argument, if t, means if fail just return nil (no error).
2284 If not nil and not t, move to limit of search and return nil.
2285 Optional fourth argument is repeat count--search for successive occurrences.
2286 See also the functions `match-beginning', `match-end', `match-string',
2287 and `replace-match'. */)
2288 (regexp, bound, noerror, count)
2289 Lisp_Object regexp, bound, noerror, count;
2291 return search_command (regexp, bound, noerror, count, -1, 1, 0);
2294 DEFUN ("re-search-forward", Fre_search_forward, Sre_search_forward, 1, 4,
2295 "sRE search: ",
2296 doc: /* Search forward from point for regular expression REGEXP.
2297 Set point to the end of the occurrence found, and return point.
2298 An optional second argument bounds the search; it is a buffer position.
2299 The match found must not extend after that position.
2300 Optional third argument, if t, means if fail just return nil (no error).
2301 If not nil and not t, move to limit of search and return nil.
2302 Optional fourth argument is repeat count--search for successive occurrences.
2303 See also the functions `match-beginning', `match-end', `match-string',
2304 and `replace-match'. */)
2305 (regexp, bound, noerror, count)
2306 Lisp_Object regexp, bound, noerror, count;
2308 return search_command (regexp, bound, noerror, count, 1, 1, 0);
2311 DEFUN ("posix-search-backward", Fposix_search_backward, Sposix_search_backward, 1, 4,
2312 "sPosix search backward: ",
2313 doc: /* Search backward from point for match for regular expression REGEXP.
2314 Find the longest match in accord with Posix regular expression rules.
2315 Set point to the beginning of the match, and return point.
2316 The match found is the one starting last in the buffer
2317 and yet ending before the origin of the search.
2318 An optional second argument bounds the search; it is a buffer position.
2319 The match found must start at or after that position.
2320 Optional third argument, if t, means if fail just return nil (no error).
2321 If not nil and not t, move to limit of search and return nil.
2322 Optional fourth argument is repeat count--search for successive occurrences.
2323 See also the functions `match-beginning', `match-end', `match-string',
2324 and `replace-match'. */)
2325 (regexp, bound, noerror, count)
2326 Lisp_Object regexp, bound, noerror, count;
2328 return search_command (regexp, bound, noerror, count, -1, 1, 1);
2331 DEFUN ("posix-search-forward", Fposix_search_forward, Sposix_search_forward, 1, 4,
2332 "sPosix search: ",
2333 doc: /* Search forward from point for regular expression REGEXP.
2334 Find the longest match in accord with Posix regular expression rules.
2335 Set point to the end of the occurrence found, and return point.
2336 An optional second argument bounds the search; it is a buffer position.
2337 The match found must not extend after that position.
2338 Optional third argument, if t, means if fail just return nil (no error).
2339 If not nil and not t, move to limit of search and return nil.
2340 Optional fourth argument is repeat count--search for successive occurrences.
2341 See also the functions `match-beginning', `match-end', `match-string',
2342 and `replace-match'. */)
2343 (regexp, bound, noerror, count)
2344 Lisp_Object regexp, bound, noerror, count;
2346 return search_command (regexp, bound, noerror, count, 1, 1, 1);
2349 DEFUN ("replace-match", Freplace_match, Sreplace_match, 1, 5, 0,
2350 doc: /* Replace text matched by last search with NEWTEXT.
2351 Leave point at the end of the replacement text.
2353 If second arg FIXEDCASE is non-nil, do not alter case of replacement text.
2354 Otherwise maybe capitalize the whole text, or maybe just word initials,
2355 based on the replaced text.
2356 If the replaced text has only capital letters
2357 and has at least one multiletter word, convert NEWTEXT to all caps.
2358 Otherwise if all words are capitalized in the replaced text,
2359 capitalize each word in NEWTEXT.
2361 If third arg LITERAL is non-nil, insert NEWTEXT literally.
2362 Otherwise treat `\\' as special:
2363 `\\&' in NEWTEXT means substitute original matched text.
2364 `\\N' means substitute what matched the Nth `\\(...\\)'.
2365 If Nth parens didn't match, substitute nothing.
2366 `\\\\' means insert one `\\'.
2367 Case conversion does not apply to these substitutions.
2369 FIXEDCASE and LITERAL are optional arguments.
2371 The optional fourth argument STRING can be a string to modify.
2372 This is meaningful when the previous match was done against STRING,
2373 using `string-match'. When used this way, `replace-match'
2374 creates and returns a new string made by copying STRING and replacing
2375 the part of STRING that was matched.
2377 The optional fifth argument SUBEXP specifies a subexpression;
2378 it says to replace just that subexpression with NEWTEXT,
2379 rather than replacing the entire matched text.
2380 This is, in a vague sense, the inverse of using `\\N' in NEWTEXT;
2381 `\\N' copies subexp N into NEWTEXT, but using N as SUBEXP puts
2382 NEWTEXT in place of subexp N.
2383 This is useful only after a regular expression search or match,
2384 since only regular expressions have distinguished subexpressions. */)
2385 (newtext, fixedcase, literal, string, subexp)
2386 Lisp_Object newtext, fixedcase, literal, string, subexp;
2388 enum { nochange, all_caps, cap_initial } case_action;
2389 register int pos, pos_byte;
2390 int some_multiletter_word;
2391 int some_lowercase;
2392 int some_uppercase;
2393 int some_nonuppercase_initial;
2394 register int c, prevc;
2395 int sub;
2396 int opoint, newpoint;
2398 CHECK_STRING (newtext);
2400 if (! NILP (string))
2401 CHECK_STRING (string);
2403 case_action = nochange; /* We tried an initialization */
2404 /* but some C compilers blew it */
2406 if (search_regs.num_regs <= 0)
2407 error ("`replace-match' called before any match found");
2409 if (NILP (subexp))
2410 sub = 0;
2411 else
2413 CHECK_NUMBER (subexp);
2414 sub = XINT (subexp);
2415 if (sub < 0 || sub >= search_regs.num_regs)
2416 args_out_of_range (subexp, make_number (search_regs.num_regs));
2419 if (NILP (string))
2421 if (search_regs.start[sub] < BEGV
2422 || search_regs.start[sub] > search_regs.end[sub]
2423 || search_regs.end[sub] > ZV)
2424 args_out_of_range (make_number (search_regs.start[sub]),
2425 make_number (search_regs.end[sub]));
2427 else
2429 if (search_regs.start[sub] < 0
2430 || search_regs.start[sub] > search_regs.end[sub]
2431 || search_regs.end[sub] > SCHARS (string))
2432 args_out_of_range (make_number (search_regs.start[sub]),
2433 make_number (search_regs.end[sub]));
2436 if (NILP (fixedcase))
2438 /* Decide how to casify by examining the matched text. */
2439 int last;
2441 pos = search_regs.start[sub];
2442 last = search_regs.end[sub];
2444 if (NILP (string))
2445 pos_byte = CHAR_TO_BYTE (pos);
2446 else
2447 pos_byte = string_char_to_byte (string, pos);
2449 prevc = '\n';
2450 case_action = all_caps;
2452 /* some_multiletter_word is set nonzero if any original word
2453 is more than one letter long. */
2454 some_multiletter_word = 0;
2455 some_lowercase = 0;
2456 some_nonuppercase_initial = 0;
2457 some_uppercase = 0;
2459 while (pos < last)
2461 if (NILP (string))
2463 c = FETCH_CHAR_AS_MULTIBYTE (pos_byte);
2464 INC_BOTH (pos, pos_byte);
2466 else
2467 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c, string, pos, pos_byte);
2469 if (LOWERCASEP (c))
2471 /* Cannot be all caps if any original char is lower case */
2473 some_lowercase = 1;
2474 if (SYNTAX (prevc) != Sword)
2475 some_nonuppercase_initial = 1;
2476 else
2477 some_multiletter_word = 1;
2479 else if (UPPERCASEP (c))
2481 some_uppercase = 1;
2482 if (SYNTAX (prevc) != Sword)
2484 else
2485 some_multiletter_word = 1;
2487 else
2489 /* If the initial is a caseless word constituent,
2490 treat that like a lowercase initial. */
2491 if (SYNTAX (prevc) != Sword)
2492 some_nonuppercase_initial = 1;
2495 prevc = c;
2498 /* Convert to all caps if the old text is all caps
2499 and has at least one multiletter word. */
2500 if (! some_lowercase && some_multiletter_word)
2501 case_action = all_caps;
2502 /* Capitalize each word, if the old text has all capitalized words. */
2503 else if (!some_nonuppercase_initial && some_multiletter_word)
2504 case_action = cap_initial;
2505 else if (!some_nonuppercase_initial && some_uppercase)
2506 /* Should x -> yz, operating on X, give Yz or YZ?
2507 We'll assume the latter. */
2508 case_action = all_caps;
2509 else
2510 case_action = nochange;
2513 /* Do replacement in a string. */
2514 if (!NILP (string))
2516 Lisp_Object before, after;
2518 before = Fsubstring (string, make_number (0),
2519 make_number (search_regs.start[sub]));
2520 after = Fsubstring (string, make_number (search_regs.end[sub]), Qnil);
2522 /* Substitute parts of the match into NEWTEXT
2523 if desired. */
2524 if (NILP (literal))
2526 int lastpos = 0;
2527 int lastpos_byte = 0;
2528 /* We build up the substituted string in ACCUM. */
2529 Lisp_Object accum;
2530 Lisp_Object middle;
2531 int length = SBYTES (newtext);
2533 accum = Qnil;
2535 for (pos_byte = 0, pos = 0; pos_byte < length;)
2537 int substart = -1;
2538 int subend = 0;
2539 int delbackslash = 0;
2541 FETCH_STRING_CHAR_ADVANCE (c, newtext, pos, pos_byte);
2543 if (c == '\\')
2545 FETCH_STRING_CHAR_ADVANCE (c, newtext, pos, pos_byte);
2547 if (c == '&')
2549 substart = search_regs.start[sub];
2550 subend = search_regs.end[sub];
2552 else if (c >= '1' && c <= '9')
2554 if (search_regs.start[c - '0'] >= 0
2555 && c <= search_regs.num_regs + '0')
2557 substart = search_regs.start[c - '0'];
2558 subend = search_regs.end[c - '0'];
2560 else
2562 /* If that subexp did not match,
2563 replace \\N with nothing. */
2564 substart = 0;
2565 subend = 0;
2568 else if (c == '\\')
2569 delbackslash = 1;
2570 else
2571 error ("Invalid use of `\\' in replacement text");
2573 if (substart >= 0)
2575 if (pos - 2 != lastpos)
2576 middle = substring_both (newtext, lastpos,
2577 lastpos_byte,
2578 pos - 2, pos_byte - 2);
2579 else
2580 middle = Qnil;
2581 accum = concat3 (accum, middle,
2582 Fsubstring (string,
2583 make_number (substart),
2584 make_number (subend)));
2585 lastpos = pos;
2586 lastpos_byte = pos_byte;
2588 else if (delbackslash)
2590 middle = substring_both (newtext, lastpos,
2591 lastpos_byte,
2592 pos - 1, pos_byte - 1);
2594 accum = concat2 (accum, middle);
2595 lastpos = pos;
2596 lastpos_byte = pos_byte;
2600 if (pos != lastpos)
2601 middle = substring_both (newtext, lastpos,
2602 lastpos_byte,
2603 pos, pos_byte);
2604 else
2605 middle = Qnil;
2607 newtext = concat2 (accum, middle);
2610 /* Do case substitution in NEWTEXT if desired. */
2611 if (case_action == all_caps)
2612 newtext = Fupcase (newtext);
2613 else if (case_action == cap_initial)
2614 newtext = Fupcase_initials (newtext);
2616 return concat3 (before, newtext, after);
2619 /* Record point, then move (quietly) to the start of the match. */
2620 if (PT >= search_regs.end[sub])
2621 opoint = PT - ZV;
2622 else if (PT > search_regs.start[sub])
2623 opoint = search_regs.end[sub] - ZV;
2624 else
2625 opoint = PT;
2627 /* If we want non-literal replacement,
2628 perform substitution on the replacement string. */
2629 if (NILP (literal))
2631 int length = SBYTES (newtext);
2632 unsigned char *substed;
2633 int substed_alloc_size, substed_len;
2634 int buf_multibyte = !NILP (current_buffer->enable_multibyte_characters);
2635 int str_multibyte = STRING_MULTIBYTE (newtext);
2636 Lisp_Object rev_tbl;
2637 int really_changed = 0;
2639 rev_tbl = Qnil;
2641 substed_alloc_size = length * 2 + 100;
2642 substed = (unsigned char *) xmalloc (substed_alloc_size + 1);
2643 substed_len = 0;
2645 /* Go thru NEWTEXT, producing the actual text to insert in
2646 SUBSTED while adjusting multibyteness to that of the current
2647 buffer. */
2649 for (pos_byte = 0, pos = 0; pos_byte < length;)
2651 unsigned char str[MAX_MULTIBYTE_LENGTH];
2652 unsigned char *add_stuff = NULL;
2653 int add_len = 0;
2654 int idx = -1;
2656 if (str_multibyte)
2658 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, newtext, pos, pos_byte);
2659 if (!buf_multibyte)
2660 c = multibyte_char_to_unibyte (c, rev_tbl);
2662 else
2664 /* Note that we don't have to increment POS. */
2665 c = SREF (newtext, pos_byte++);
2666 if (buf_multibyte)
2667 c = unibyte_char_to_multibyte (c);
2670 /* Either set ADD_STUFF and ADD_LEN to the text to put in SUBSTED,
2671 or set IDX to a match index, which means put that part
2672 of the buffer text into SUBSTED. */
2674 if (c == '\\')
2676 really_changed = 1;
2678 if (str_multibyte)
2680 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, newtext,
2681 pos, pos_byte);
2682 if (!buf_multibyte && !ASCII_CHAR_P (c))
2683 c = multibyte_char_to_unibyte (c, rev_tbl);
2685 else
2687 c = SREF (newtext, pos_byte++);
2688 if (buf_multibyte)
2689 c = unibyte_char_to_multibyte (c);
2692 if (c == '&')
2693 idx = sub;
2694 else if (c >= '1' && c <= '9' && c <= search_regs.num_regs + '0')
2696 if (search_regs.start[c - '0'] >= 1)
2697 idx = c - '0';
2699 else if (c == '\\')
2700 add_len = 1, add_stuff = "\\";
2701 else
2703 xfree (substed);
2704 error ("Invalid use of `\\' in replacement text");
2707 else
2709 add_len = CHAR_STRING (c, str);
2710 add_stuff = str;
2713 /* If we want to copy part of a previous match,
2714 set up ADD_STUFF and ADD_LEN to point to it. */
2715 if (idx >= 0)
2717 int begbyte = CHAR_TO_BYTE (search_regs.start[idx]);
2718 add_len = CHAR_TO_BYTE (search_regs.end[idx]) - begbyte;
2719 if (search_regs.start[idx] < GPT && GPT < search_regs.end[idx])
2720 move_gap (search_regs.start[idx]);
2721 add_stuff = BYTE_POS_ADDR (begbyte);
2724 /* Now the stuff we want to add to SUBSTED
2725 is invariably ADD_LEN bytes starting at ADD_STUFF. */
2727 /* Make sure SUBSTED is big enough. */
2728 if (substed_len + add_len >= substed_alloc_size)
2730 substed_alloc_size = substed_len + add_len + 500;
2731 substed = (unsigned char *) xrealloc (substed,
2732 substed_alloc_size + 1);
2735 /* Now add to the end of SUBSTED. */
2736 if (add_stuff)
2738 bcopy (add_stuff, substed + substed_len, add_len);
2739 substed_len += add_len;
2743 if (really_changed)
2745 if (buf_multibyte)
2747 int nchars = multibyte_chars_in_text (substed, substed_len);
2749 newtext = make_multibyte_string (substed, nchars, substed_len);
2751 else
2752 newtext = make_unibyte_string (substed, substed_len);
2754 xfree (substed);
2757 /* Replace the old text with the new in the cleanest possible way. */
2758 replace_range (search_regs.start[sub], search_regs.end[sub],
2759 newtext, 1, 0, 1);
2760 newpoint = search_regs.start[sub] + SCHARS (newtext);
2762 if (case_action == all_caps)
2763 Fupcase_region (make_number (search_regs.start[sub]),
2764 make_number (newpoint));
2765 else if (case_action == cap_initial)
2766 Fupcase_initials_region (make_number (search_regs.start[sub]),
2767 make_number (newpoint));
2769 /* Adjust search data for this change. */
2771 int oldend = search_regs.end[sub];
2772 int oldstart = search_regs.start[sub];
2773 int change = newpoint - search_regs.end[sub];
2774 int i;
2776 for (i = 0; i < search_regs.num_regs; i++)
2778 if (search_regs.start[i] >= oldend)
2779 search_regs.start[i] += change;
2780 else if (search_regs.start[i] > oldstart)
2781 search_regs.start[i] = oldstart;
2782 if (search_regs.end[i] >= oldend)
2783 search_regs.end[i] += change;
2784 else if (search_regs.end[i] > oldstart)
2785 search_regs.end[i] = oldstart;
2789 /* Put point back where it was in the text. */
2790 if (opoint <= 0)
2791 TEMP_SET_PT (opoint + ZV);
2792 else
2793 TEMP_SET_PT (opoint);
2795 /* Now move point "officially" to the start of the inserted replacement. */
2796 move_if_not_intangible (newpoint);
2798 return Qnil;
2801 static Lisp_Object
2802 match_limit (num, beginningp)
2803 Lisp_Object num;
2804 int beginningp;
2806 register int n;
2808 CHECK_NUMBER (num);
2809 n = XINT (num);
2810 if (n < 0)
2811 args_out_of_range (num, make_number (0));
2812 if (search_regs.num_regs <= 0)
2813 error ("No match data, because no search succeeded");
2814 if (n >= search_regs.num_regs
2815 || search_regs.start[n] < 0)
2816 return Qnil;
2817 return (make_number ((beginningp) ? search_regs.start[n]
2818 : search_regs.end[n]));
2821 DEFUN ("match-beginning", Fmatch_beginning, Smatch_beginning, 1, 1, 0,
2822 doc: /* Return position of start of text matched by last search.
2823 SUBEXP, a number, specifies which parenthesized expression in the last
2824 regexp.
2825 Value is nil if SUBEXPth pair didn't match, or there were less than
2826 SUBEXP pairs.
2827 Zero means the entire text matched by the whole regexp or whole string. */)
2828 (subexp)
2829 Lisp_Object subexp;
2831 return match_limit (subexp, 1);
2834 DEFUN ("match-end", Fmatch_end, Smatch_end, 1, 1, 0,
2835 doc: /* Return position of end of text matched by last search.
2836 SUBEXP, a number, specifies which parenthesized expression in the last
2837 regexp.
2838 Value is nil if SUBEXPth pair didn't match, or there were less than
2839 SUBEXP pairs.
2840 Zero means the entire text matched by the whole regexp or whole string. */)
2841 (subexp)
2842 Lisp_Object subexp;
2844 return match_limit (subexp, 0);
2847 DEFUN ("match-data", Fmatch_data, Smatch_data, 0, 3, 0,
2848 doc: /* Return a list containing all info on what the last search matched.
2849 Element 2N is `(match-beginning N)'; element 2N + 1 is `(match-end N)'.
2850 All the elements are markers or nil (nil if the Nth pair didn't match)
2851 if the last match was on a buffer; integers or nil if a string was matched.
2852 Use `store-match-data' to reinstate the data in this list.
2854 If INTEGERS (the optional first argument) is non-nil, always use
2855 integers \(rather than markers) to represent buffer positions. In
2856 this case, and if the last match was in a buffer, the buffer will get
2857 stored as one additional element at the end of the list.
2859 If REUSE is a list, reuse it as part of the value. If REUSE is long
2860 enough to hold all the values, and if INTEGERS is non-nil, no consing
2861 is done.
2863 If optional third arg RESEAT is non-nil, any previous markers on the
2864 REUSE list will be modified to point to nowhere.
2866 Return value is undefined if the last search failed. */)
2867 (integers, reuse, reseat)
2868 Lisp_Object integers, reuse, reseat;
2870 Lisp_Object tail, prev;
2871 Lisp_Object *data;
2872 int i, len;
2874 if (!NILP (reseat))
2875 for (tail = reuse; CONSP (tail); tail = XCDR (tail))
2876 if (MARKERP (XCAR (tail)))
2878 unchain_marker (XMARKER (XCAR (tail)));
2879 XSETCAR (tail, Qnil);
2882 if (NILP (last_thing_searched))
2883 return Qnil;
2885 prev = Qnil;
2887 data = (Lisp_Object *) alloca ((2 * search_regs.num_regs + 1)
2888 * sizeof (Lisp_Object));
2890 len = 0;
2891 for (i = 0; i < search_regs.num_regs; i++)
2893 int start = search_regs.start[i];
2894 if (start >= 0)
2896 if (EQ (last_thing_searched, Qt)
2897 || ! NILP (integers))
2899 XSETFASTINT (data[2 * i], start);
2900 XSETFASTINT (data[2 * i + 1], search_regs.end[i]);
2902 else if (BUFFERP (last_thing_searched))
2904 data[2 * i] = Fmake_marker ();
2905 Fset_marker (data[2 * i],
2906 make_number (start),
2907 last_thing_searched);
2908 data[2 * i + 1] = Fmake_marker ();
2909 Fset_marker (data[2 * i + 1],
2910 make_number (search_regs.end[i]),
2911 last_thing_searched);
2913 else
2914 /* last_thing_searched must always be Qt, a buffer, or Qnil. */
2915 abort ();
2917 len = 2 * i + 2;
2919 else
2920 data[2 * i] = data[2 * i + 1] = Qnil;
2923 if (BUFFERP (last_thing_searched) && !NILP (integers))
2925 data[len] = last_thing_searched;
2926 len++;
2929 /* If REUSE is not usable, cons up the values and return them. */
2930 if (! CONSP (reuse))
2931 return Flist (len, data);
2933 /* If REUSE is a list, store as many value elements as will fit
2934 into the elements of REUSE. */
2935 for (i = 0, tail = reuse; CONSP (tail);
2936 i++, tail = XCDR (tail))
2938 if (i < len)
2939 XSETCAR (tail, data[i]);
2940 else
2941 XSETCAR (tail, Qnil);
2942 prev = tail;
2945 /* If we couldn't fit all value elements into REUSE,
2946 cons up the rest of them and add them to the end of REUSE. */
2947 if (i < len)
2948 XSETCDR (prev, Flist (len - i, data + i));
2950 return reuse;
2953 /* We used to have an internal use variant of `reseat' described as:
2955 If RESEAT is `evaporate', put the markers back on the free list
2956 immediately. No other references to the markers must exist in this
2957 case, so it is used only internally on the unwind stack and
2958 save-match-data from Lisp.
2960 But it was ill-conceived: those supposedly-internal markers get exposed via
2961 the undo-list, so freeing them here is unsafe. */
2963 DEFUN ("set-match-data", Fset_match_data, Sset_match_data, 1, 2, 0,
2964 doc: /* Set internal data on last search match from elements of LIST.
2965 LIST should have been created by calling `match-data' previously.
2967 If optional arg RESEAT is non-nil, make markers on LIST point nowhere. */)
2968 (list, reseat)
2969 register Lisp_Object list, reseat;
2971 register int i;
2972 register Lisp_Object marker;
2974 if (running_asynch_code)
2975 save_search_regs ();
2977 CHECK_LIST (list);
2979 /* Unless we find a marker with a buffer or an explicit buffer
2980 in LIST, assume that this match data came from a string. */
2981 last_thing_searched = Qt;
2983 /* Allocate registers if they don't already exist. */
2985 int length = XFASTINT (Flength (list)) / 2;
2987 if (length > search_regs.num_regs)
2989 if (search_regs.num_regs == 0)
2991 search_regs.start
2992 = (regoff_t *) xmalloc (length * sizeof (regoff_t));
2993 search_regs.end
2994 = (regoff_t *) xmalloc (length * sizeof (regoff_t));
2996 else
2998 search_regs.start
2999 = (regoff_t *) xrealloc (search_regs.start,
3000 length * sizeof (regoff_t));
3001 search_regs.end
3002 = (regoff_t *) xrealloc (search_regs.end,
3003 length * sizeof (regoff_t));
3006 for (i = search_regs.num_regs; i < length; i++)
3007 search_regs.start[i] = -1;
3009 search_regs.num_regs = length;
3012 for (i = 0; CONSP (list); i++)
3014 marker = XCAR (list);
3015 if (BUFFERP (marker))
3017 last_thing_searched = marker;
3018 break;
3020 if (i >= length)
3021 break;
3022 if (NILP (marker))
3024 search_regs.start[i] = -1;
3025 list = XCDR (list);
3027 else
3029 int from;
3030 Lisp_Object m;
3032 m = marker;
3033 if (MARKERP (marker))
3035 if (XMARKER (marker)->buffer == 0)
3036 XSETFASTINT (marker, 0);
3037 else
3038 XSETBUFFER (last_thing_searched, XMARKER (marker)->buffer);
3041 CHECK_NUMBER_COERCE_MARKER (marker);
3042 from = XINT (marker);
3044 if (!NILP (reseat) && MARKERP (m))
3046 unchain_marker (XMARKER (m));
3047 XSETCAR (list, Qnil);
3050 if ((list = XCDR (list), !CONSP (list)))
3051 break;
3053 m = marker = XCAR (list);
3055 if (MARKERP (marker) && XMARKER (marker)->buffer == 0)
3056 XSETFASTINT (marker, 0);
3058 CHECK_NUMBER_COERCE_MARKER (marker);
3059 search_regs.start[i] = from;
3060 search_regs.end[i] = XINT (marker);
3062 if (!NILP (reseat) && MARKERP (m))
3064 unchain_marker (XMARKER (m));
3065 XSETCAR (list, Qnil);
3068 list = XCDR (list);
3071 for (; i < search_regs.num_regs; i++)
3072 search_regs.start[i] = -1;
3075 return Qnil;
3078 /* If non-zero the match data have been saved in saved_search_regs
3079 during the execution of a sentinel or filter. */
3080 static int search_regs_saved;
3081 static struct re_registers saved_search_regs;
3082 static Lisp_Object saved_last_thing_searched;
3084 /* Called from Flooking_at, Fstring_match, search_buffer, Fstore_match_data
3085 if asynchronous code (filter or sentinel) is running. */
3086 static void
3087 save_search_regs ()
3089 if (!search_regs_saved)
3091 saved_search_regs.num_regs = search_regs.num_regs;
3092 saved_search_regs.start = search_regs.start;
3093 saved_search_regs.end = search_regs.end;
3094 saved_last_thing_searched = last_thing_searched;
3095 last_thing_searched = Qnil;
3096 search_regs.num_regs = 0;
3097 search_regs.start = 0;
3098 search_regs.end = 0;
3100 search_regs_saved = 1;
3104 /* Called upon exit from filters and sentinels. */
3105 void
3106 restore_search_regs ()
3108 if (search_regs_saved)
3110 if (search_regs.num_regs > 0)
3112 xfree (search_regs.start);
3113 xfree (search_regs.end);
3115 search_regs.num_regs = saved_search_regs.num_regs;
3116 search_regs.start = saved_search_regs.start;
3117 search_regs.end = saved_search_regs.end;
3118 last_thing_searched = saved_last_thing_searched;
3119 saved_last_thing_searched = Qnil;
3120 search_regs_saved = 0;
3124 static Lisp_Object
3125 unwind_set_match_data (list)
3126 Lisp_Object list;
3128 /* It is NOT ALWAYS safe to free (evaporate) the markers immediately. */
3129 return Fset_match_data (list, Qt);
3132 /* Called to unwind protect the match data. */
3133 void
3134 record_unwind_save_match_data ()
3136 record_unwind_protect (unwind_set_match_data,
3137 Fmatch_data (Qnil, Qnil, Qnil));
3140 /* Quote a string to inactivate reg-expr chars */
3142 DEFUN ("regexp-quote", Fregexp_quote, Sregexp_quote, 1, 1, 0,
3143 doc: /* Return a regexp string which matches exactly STRING and nothing else. */)
3144 (string)
3145 Lisp_Object string;
3147 register unsigned char *in, *out, *end;
3148 register unsigned char *temp;
3149 int backslashes_added = 0;
3151 CHECK_STRING (string);
3153 temp = (unsigned char *) alloca (SBYTES (string) * 2);
3155 /* Now copy the data into the new string, inserting escapes. */
3157 in = SDATA (string);
3158 end = in + SBYTES (string);
3159 out = temp;
3161 for (; in != end; in++)
3163 if (*in == '['
3164 || *in == '*' || *in == '.' || *in == '\\'
3165 || *in == '?' || *in == '+'
3166 || *in == '^' || *in == '$')
3167 *out++ = '\\', backslashes_added++;
3168 *out++ = *in;
3171 return make_specified_string (temp,
3172 SCHARS (string) + backslashes_added,
3173 out - temp,
3174 STRING_MULTIBYTE (string));
3177 void
3178 syms_of_search ()
3180 register int i;
3182 for (i = 0; i < REGEXP_CACHE_SIZE; ++i)
3184 searchbufs[i].buf.allocated = 100;
3185 searchbufs[i].buf.buffer = (unsigned char *) xmalloc (100);
3186 searchbufs[i].buf.fastmap = searchbufs[i].fastmap;
3187 searchbufs[i].regexp = Qnil;
3188 searchbufs[i].whitespace_regexp = Qnil;
3189 searchbufs[i].syntax_table = Qnil;
3190 staticpro (&searchbufs[i].regexp);
3191 staticpro (&searchbufs[i].whitespace_regexp);
3192 staticpro (&searchbufs[i].syntax_table);
3193 searchbufs[i].next = (i == REGEXP_CACHE_SIZE-1 ? 0 : &searchbufs[i+1]);
3195 searchbuf_head = &searchbufs[0];
3197 Qsearch_failed = intern ("search-failed");
3198 staticpro (&Qsearch_failed);
3199 Qinvalid_regexp = intern ("invalid-regexp");
3200 staticpro (&Qinvalid_regexp);
3202 Fput (Qsearch_failed, Qerror_conditions,
3203 Fcons (Qsearch_failed, Fcons (Qerror, Qnil)));
3204 Fput (Qsearch_failed, Qerror_message,
3205 build_string ("Search failed"));
3207 Fput (Qinvalid_regexp, Qerror_conditions,
3208 Fcons (Qinvalid_regexp, Fcons (Qerror, Qnil)));
3209 Fput (Qinvalid_regexp, Qerror_message,
3210 build_string ("Invalid regexp"));
3212 last_thing_searched = Qnil;
3213 staticpro (&last_thing_searched);
3215 saved_last_thing_searched = Qnil;
3216 staticpro (&saved_last_thing_searched);
3218 DEFVAR_LISP ("search-spaces-regexp", &Vsearch_spaces_regexp,
3219 doc: /* Regexp to substitute for bunches of spaces in regexp search.
3220 Some commands use this for user-specified regexps.
3221 Spaces that occur inside character classes or repetition operators
3222 or other such regexp constructs are not replaced with this.
3223 A value of nil (which is the normal value) means treat spaces literally. */);
3224 Vsearch_spaces_regexp = Qnil;
3226 DEFVAR_LISP ("inhibit-changing-match-data", &Vinhibit_changing_match_data,
3227 doc: /* Internal use only.
3228 If non-nil, the primitive searching and matching functions
3229 such as `looking-at', `string-match', `re-search-forward', etc.,
3230 do not set the match data. The proper way to use this variable
3231 is to bind it with `let' around a small expression. */);
3232 Vinhibit_changing_match_data = Qnil;
3234 defsubr (&Slooking_at);
3235 defsubr (&Sposix_looking_at);
3236 defsubr (&Sstring_match);
3237 defsubr (&Sposix_string_match);
3238 defsubr (&Ssearch_forward);
3239 defsubr (&Ssearch_backward);
3240 defsubr (&Sword_search_forward);
3241 defsubr (&Sword_search_backward);
3242 defsubr (&Sre_search_forward);
3243 defsubr (&Sre_search_backward);
3244 defsubr (&Sposix_search_forward);
3245 defsubr (&Sposix_search_backward);
3246 defsubr (&Sreplace_match);
3247 defsubr (&Smatch_beginning);
3248 defsubr (&Smatch_end);
3249 defsubr (&Smatch_data);
3250 defsubr (&Sset_match_data);
3251 defsubr (&Sregexp_quote);
3254 /* arch-tag: a6059d79-0552-4f14-a2cb-d379a4e3c78f
3255 (do not change this comment) */