]> code.delx.au - gnu-emacs/blob - src/search.c
Revision: miles@gnu.org--gnu-2005/emacs--unicode--0--patch-23
[gnu-emacs] / src / search.c
1 /* String search routines for GNU Emacs.
2 Copyright (C) 1985, 86,87,93,94,97,98, 1999, 2004
3 Free Software Foundation, Inc.
4
5 This file is part of GNU Emacs.
6
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
21
22
23 #include <config.h>
24 #include "lisp.h"
25 #include "syntax.h"
26 #include "category.h"
27 #include "buffer.h"
28 #include "character.h"
29 #include "region-cache.h"
30 #include "commands.h"
31 #include "blockinput.h"
32 #include "intervals.h"
33
34 #include <sys/types.h>
35 #include "regex.h"
36
37 #define REGEXP_CACHE_SIZE 20
38
39 /* If the regexp is non-nil, then the buffer contains the compiled form
40 of that regexp, suitable for searching. */
41 struct regexp_cache
42 {
43 struct regexp_cache *next;
44 Lisp_Object regexp, whitespace_regexp;
45 struct re_pattern_buffer buf;
46 char fastmap[0400];
47 /* Nonzero means regexp was compiled to do full POSIX backtracking. */
48 char posix;
49 };
50
51 /* The instances of that struct. */
52 struct regexp_cache searchbufs[REGEXP_CACHE_SIZE];
53
54 /* The head of the linked list; points to the most recently used buffer. */
55 struct regexp_cache *searchbuf_head;
56
57
58 /* Every call to re_match, etc., must pass &search_regs as the regs
59 argument unless you can show it is unnecessary (i.e., if re_match
60 is certainly going to be called again before region-around-match
61 can be called).
62
63 Since the registers are now dynamically allocated, we need to make
64 sure not to refer to the Nth register before checking that it has
65 been allocated by checking search_regs.num_regs.
66
67 The regex code keeps track of whether it has allocated the search
68 buffer using bits in the re_pattern_buffer. This means that whenever
69 you compile a new pattern, it completely forgets whether it has
70 allocated any registers, and will allocate new registers the next
71 time you call a searching or matching function. Therefore, we need
72 to call re_set_registers after compiling a new pattern or after
73 setting the match registers, so that the regex functions will be
74 able to free or re-allocate it properly. */
75 static struct re_registers search_regs;
76
77 /* The buffer in which the last search was performed, or
78 Qt if the last search was done in a string;
79 Qnil if no searching has been done yet. */
80 static Lisp_Object last_thing_searched;
81
82 /* error condition signaled when regexp compile_pattern fails */
83
84 Lisp_Object Qinvalid_regexp;
85
86 Lisp_Object Vsearch_spaces_regexp;
87
88 static void set_search_regs ();
89 static void save_search_regs ();
90 static int simple_search ();
91 static int boyer_moore ();
92 static int search_buffer ();
93
94 static void
95 matcher_overflow ()
96 {
97 error ("Stack overflow in regexp matcher");
98 }
99
100 /* Compile a regexp and signal a Lisp error if anything goes wrong.
101 PATTERN is the pattern to compile.
102 CP is the place to put the result.
103 TRANSLATE is a translation table for ignoring case, or nil for none.
104 REGP is the structure that says where to store the "register"
105 values that will result from matching this pattern.
106 If it is 0, we should compile the pattern not to record any
107 subexpression bounds.
108 POSIX is nonzero if we want full backtracking (POSIX style)
109 for this pattern. 0 means backtrack only enough to get a valid match.
110 MULTIBYTE is nonzero iff a target of match is a multibyte buffer or
111 string.
112
113 The behavior also depends on Vsearch_spaces_regexp. */
114
115 static void
116 compile_pattern_1 (cp, pattern, translate, regp, posix, multibyte)
117 struct regexp_cache *cp;
118 Lisp_Object pattern;
119 Lisp_Object translate;
120 struct re_registers *regp;
121 int posix;
122 int multibyte;
123 {
124 char *val;
125 reg_syntax_t old;
126
127 cp->regexp = Qnil;
128 cp->buf.translate = (! NILP (translate) ? translate : make_number (0));
129 cp->posix = posix;
130 cp->buf.multibyte = STRING_MULTIBYTE (pattern);
131 cp->buf.target_multibyte = multibyte;
132 cp->whitespace_regexp = Vsearch_spaces_regexp;
133 BLOCK_INPUT;
134 old = re_set_syntax (RE_SYNTAX_EMACS
135 | (posix ? 0 : RE_NO_POSIX_BACKTRACKING));
136 re_set_whitespace_regexp (NILP (Vsearch_spaces_regexp) ? NULL
137 : SDATA (Vsearch_spaces_regexp));
138
139 val = (char *) re_compile_pattern ((char *) SDATA (pattern),
140 SBYTES (pattern), &cp->buf);
141
142 re_set_whitespace_regexp (NULL);
143
144 re_set_syntax (old);
145 UNBLOCK_INPUT;
146 if (val)
147 Fsignal (Qinvalid_regexp, Fcons (build_string (val), Qnil));
148
149 cp->regexp = Fcopy_sequence (pattern);
150 }
151
152 /* Shrink each compiled regexp buffer in the cache
153 to the size actually used right now.
154 This is called from garbage collection. */
155
156 void
157 shrink_regexp_cache ()
158 {
159 struct regexp_cache *cp;
160
161 for (cp = searchbuf_head; cp != 0; cp = cp->next)
162 {
163 cp->buf.allocated = cp->buf.used;
164 cp->buf.buffer
165 = (unsigned char *) xrealloc (cp->buf.buffer, cp->buf.used);
166 }
167 }
168
169 /* Compile a regexp if necessary, but first check to see if there's one in
170 the cache.
171 PATTERN is the pattern to compile.
172 TRANSLATE is a translation table for ignoring case, or nil for none.
173 REGP is the structure that says where to store the "register"
174 values that will result from matching this pattern.
175 If it is 0, we should compile the pattern not to record any
176 subexpression bounds.
177 POSIX is nonzero if we want full backtracking (POSIX style)
178 for this pattern. 0 means backtrack only enough to get a valid match. */
179
180 struct re_pattern_buffer *
181 compile_pattern (pattern, regp, translate, posix, multibyte)
182 Lisp_Object pattern;
183 struct re_registers *regp;
184 Lisp_Object translate;
185 int posix, multibyte;
186 {
187 struct regexp_cache *cp, **cpp;
188
189 for (cpp = &searchbuf_head; ; cpp = &cp->next)
190 {
191 cp = *cpp;
192 /* Entries are initialized to nil, and may be set to nil by
193 compile_pattern_1 if the pattern isn't valid. Don't apply
194 string accessors in those cases. However, compile_pattern_1
195 is only applied to the cache entry we pick here to reuse. So
196 nil should never appear before a non-nil entry. */
197 if (NILP (cp->regexp))
198 goto compile_it;
199 if (SCHARS (cp->regexp) == SCHARS (pattern)
200 && STRING_MULTIBYTE (cp->regexp) == STRING_MULTIBYTE (pattern)
201 && !NILP (Fstring_equal (cp->regexp, pattern))
202 && EQ (cp->buf.translate, (! NILP (translate) ? translate : make_number (0)))
203 && cp->posix == posix
204 && cp->buf.target_multibyte == multibyte
205 && !NILP (Fequal (cp->whitespace_regexp, Vsearch_spaces_regexp)))
206 break;
207
208 /* If we're at the end of the cache, compile into the nil cell
209 we found, or the last (least recently used) cell with a
210 string value. */
211 if (cp->next == 0)
212 {
213 compile_it:
214 compile_pattern_1 (cp, pattern, translate, regp, posix, multibyte);
215 break;
216 }
217 }
218
219 /* When we get here, cp (aka *cpp) contains the compiled pattern,
220 either because we found it in the cache or because we just compiled it.
221 Move it to the front of the queue to mark it as most recently used. */
222 *cpp = cp->next;
223 cp->next = searchbuf_head;
224 searchbuf_head = cp;
225
226 /* Advise the searching functions about the space we have allocated
227 for register data. */
228 if (regp)
229 re_set_registers (&cp->buf, regp, regp->num_regs, regp->start, regp->end);
230
231 return &cp->buf;
232 }
233
234 /* Error condition used for failing searches */
235 Lisp_Object Qsearch_failed;
236
237 Lisp_Object
238 signal_failure (arg)
239 Lisp_Object arg;
240 {
241 Fsignal (Qsearch_failed, Fcons (arg, Qnil));
242 return Qnil;
243 }
244 \f
245 static Lisp_Object
246 looking_at_1 (string, posix)
247 Lisp_Object string;
248 int posix;
249 {
250 Lisp_Object val;
251 unsigned char *p1, *p2;
252 int s1, s2;
253 register int i;
254 struct re_pattern_buffer *bufp;
255
256 if (running_asynch_code)
257 save_search_regs ();
258
259 CHECK_STRING (string);
260 bufp = compile_pattern (string, &search_regs,
261 (!NILP (current_buffer->case_fold_search)
262 ? DOWNCASE_TABLE : Qnil),
263 posix,
264 !NILP (current_buffer->enable_multibyte_characters));
265
266 immediate_quit = 1;
267 QUIT; /* Do a pending quit right away, to avoid paradoxical behavior */
268
269 /* Get pointers and sizes of the two strings
270 that make up the visible portion of the buffer. */
271
272 p1 = BEGV_ADDR;
273 s1 = GPT_BYTE - BEGV_BYTE;
274 p2 = GAP_END_ADDR;
275 s2 = ZV_BYTE - GPT_BYTE;
276 if (s1 < 0)
277 {
278 p2 = p1;
279 s2 = ZV_BYTE - BEGV_BYTE;
280 s1 = 0;
281 }
282 if (s2 < 0)
283 {
284 s1 = ZV_BYTE - BEGV_BYTE;
285 s2 = 0;
286 }
287
288 re_match_object = Qnil;
289
290 i = re_match_2 (bufp, (char *) p1, s1, (char *) p2, s2,
291 PT_BYTE - BEGV_BYTE, &search_regs,
292 ZV_BYTE - BEGV_BYTE);
293 immediate_quit = 0;
294
295 if (i == -2)
296 matcher_overflow ();
297
298 val = (0 <= i ? Qt : Qnil);
299 if (i >= 0)
300 for (i = 0; i < search_regs.num_regs; i++)
301 if (search_regs.start[i] >= 0)
302 {
303 search_regs.start[i]
304 = BYTE_TO_CHAR (search_regs.start[i] + BEGV_BYTE);
305 search_regs.end[i]
306 = BYTE_TO_CHAR (search_regs.end[i] + BEGV_BYTE);
307 }
308 XSETBUFFER (last_thing_searched, current_buffer);
309 return val;
310 }
311
312 DEFUN ("looking-at", Flooking_at, Slooking_at, 1, 1, 0,
313 doc: /* Return t if text after point matches regular expression REGEXP.
314 This function modifies the match data that `match-beginning',
315 `match-end' and `match-data' access; save and restore the match
316 data if you want to preserve them. */)
317 (regexp)
318 Lisp_Object regexp;
319 {
320 return looking_at_1 (regexp, 0);
321 }
322
323 DEFUN ("posix-looking-at", Fposix_looking_at, Sposix_looking_at, 1, 1, 0,
324 doc: /* Return t if text after point matches regular expression REGEXP.
325 Find the longest match, in accord with Posix regular expression rules.
326 This function modifies the match data that `match-beginning',
327 `match-end' and `match-data' access; save and restore the match
328 data if you want to preserve them. */)
329 (regexp)
330 Lisp_Object regexp;
331 {
332 return looking_at_1 (regexp, 1);
333 }
334 \f
335 static Lisp_Object
336 string_match_1 (regexp, string, start, posix)
337 Lisp_Object regexp, string, start;
338 int posix;
339 {
340 int val;
341 struct re_pattern_buffer *bufp;
342 int pos, pos_byte;
343 int i;
344
345 if (running_asynch_code)
346 save_search_regs ();
347
348 CHECK_STRING (regexp);
349 CHECK_STRING (string);
350
351 if (NILP (start))
352 pos = 0, pos_byte = 0;
353 else
354 {
355 int len = SCHARS (string);
356
357 CHECK_NUMBER (start);
358 pos = XINT (start);
359 if (pos < 0 && -pos <= len)
360 pos = len + pos;
361 else if (0 > pos || pos > len)
362 args_out_of_range (string, start);
363 pos_byte = string_char_to_byte (string, pos);
364 }
365
366 bufp = compile_pattern (regexp, &search_regs,
367 (!NILP (current_buffer->case_fold_search)
368 ? DOWNCASE_TABLE : Qnil),
369 posix,
370 STRING_MULTIBYTE (string));
371 immediate_quit = 1;
372 re_match_object = string;
373
374 val = re_search (bufp, (char *) SDATA (string),
375 SBYTES (string), pos_byte,
376 SBYTES (string) - pos_byte,
377 &search_regs);
378 immediate_quit = 0;
379 last_thing_searched = Qt;
380 if (val == -2)
381 matcher_overflow ();
382 if (val < 0) return Qnil;
383
384 for (i = 0; i < search_regs.num_regs; i++)
385 if (search_regs.start[i] >= 0)
386 {
387 search_regs.start[i]
388 = string_byte_to_char (string, search_regs.start[i]);
389 search_regs.end[i]
390 = string_byte_to_char (string, search_regs.end[i]);
391 }
392
393 return make_number (string_byte_to_char (string, val));
394 }
395
396 DEFUN ("string-match", Fstring_match, Sstring_match, 2, 3, 0,
397 doc: /* Return index of start of first match for REGEXP in STRING, or nil.
398 Case is ignored if `case-fold-search' is non-nil in the current buffer.
399 If third arg START is non-nil, start search at that index in STRING.
400 For index of first char beyond the match, do (match-end 0).
401 `match-end' and `match-beginning' also give indices of substrings
402 matched by parenthesis constructs in the pattern.
403
404 You can use the function `match-string' to extract the substrings
405 matched by the parenthesis constructions in REGEXP. */)
406 (regexp, string, start)
407 Lisp_Object regexp, string, start;
408 {
409 return string_match_1 (regexp, string, start, 0);
410 }
411
412 DEFUN ("posix-string-match", Fposix_string_match, Sposix_string_match, 2, 3, 0,
413 doc: /* Return index of start of first match for REGEXP in STRING, or nil.
414 Find the longest match, in accord with Posix regular expression rules.
415 Case is ignored if `case-fold-search' is non-nil in the current buffer.
416 If third arg START is non-nil, start search at that index in STRING.
417 For index of first char beyond the match, do (match-end 0).
418 `match-end' and `match-beginning' also give indices of substrings
419 matched by parenthesis constructs in the pattern. */)
420 (regexp, string, start)
421 Lisp_Object regexp, string, start;
422 {
423 return string_match_1 (regexp, string, start, 1);
424 }
425
426 /* Match REGEXP against STRING, searching all of STRING,
427 and return the index of the match, or negative on failure.
428 This does not clobber the match data. */
429
430 int
431 fast_string_match (regexp, string)
432 Lisp_Object regexp, string;
433 {
434 int val;
435 struct re_pattern_buffer *bufp;
436
437 bufp = compile_pattern (regexp, 0, Qnil,
438 0, STRING_MULTIBYTE (string));
439 immediate_quit = 1;
440 re_match_object = string;
441
442 val = re_search (bufp, (char *) SDATA (string),
443 SBYTES (string), 0,
444 SBYTES (string), 0);
445 immediate_quit = 0;
446 return val;
447 }
448
449 /* Match REGEXP against STRING, searching all of STRING ignoring case,
450 and return the index of the match, or negative on failure.
451 This does not clobber the match data.
452 We assume that STRING contains single-byte characters. */
453
454 extern Lisp_Object Vascii_downcase_table;
455
456 int
457 fast_c_string_match_ignore_case (regexp, string)
458 Lisp_Object regexp;
459 const char *string;
460 {
461 int val;
462 struct re_pattern_buffer *bufp;
463 int len = strlen (string);
464
465 regexp = string_make_unibyte (regexp);
466 re_match_object = Qt;
467 bufp = compile_pattern (regexp, 0,
468 Vascii_downcase_table, 0,
469 0);
470 immediate_quit = 1;
471 val = re_search (bufp, string, len, 0, len, 0);
472 immediate_quit = 0;
473 return val;
474 }
475
476 /* Like fast_string_match but ignore case. */
477
478 int
479 fast_string_match_ignore_case (regexp, string)
480 Lisp_Object regexp, string;
481 {
482 int val;
483 struct re_pattern_buffer *bufp;
484
485 bufp = compile_pattern (regexp, 0, Vascii_downcase_table,
486 0, STRING_MULTIBYTE (string));
487 immediate_quit = 1;
488 re_match_object = string;
489
490 val = re_search (bufp, (char *) SDATA (string),
491 SBYTES (string), 0,
492 SBYTES (string), 0);
493 immediate_quit = 0;
494 return val;
495 }
496 \f
497 /* The newline cache: remembering which sections of text have no newlines. */
498
499 /* If the user has requested newline caching, make sure it's on.
500 Otherwise, make sure it's off.
501 This is our cheezy way of associating an action with the change of
502 state of a buffer-local variable. */
503 static void
504 newline_cache_on_off (buf)
505 struct buffer *buf;
506 {
507 if (NILP (buf->cache_long_line_scans))
508 {
509 /* It should be off. */
510 if (buf->newline_cache)
511 {
512 free_region_cache (buf->newline_cache);
513 buf->newline_cache = 0;
514 }
515 }
516 else
517 {
518 /* It should be on. */
519 if (buf->newline_cache == 0)
520 buf->newline_cache = new_region_cache ();
521 }
522 }
523
524 \f
525 /* Search for COUNT instances of the character TARGET between START and END.
526
527 If COUNT is positive, search forwards; END must be >= START.
528 If COUNT is negative, search backwards for the -COUNTth instance;
529 END must be <= START.
530 If COUNT is zero, do anything you please; run rogue, for all I care.
531
532 If END is zero, use BEGV or ZV instead, as appropriate for the
533 direction indicated by COUNT.
534
535 If we find COUNT instances, set *SHORTAGE to zero, and return the
536 position past the COUNTth match. Note that for reverse motion
537 this is not the same as the usual convention for Emacs motion commands.
538
539 If we don't find COUNT instances before reaching END, set *SHORTAGE
540 to the number of TARGETs left unfound, and return END.
541
542 If ALLOW_QUIT is non-zero, set immediate_quit. That's good to do
543 except when inside redisplay. */
544
545 int
546 scan_buffer (target, start, end, count, shortage, allow_quit)
547 register int target;
548 int start, end;
549 int count;
550 int *shortage;
551 int allow_quit;
552 {
553 struct region_cache *newline_cache;
554 int direction;
555
556 if (count > 0)
557 {
558 direction = 1;
559 if (! end) end = ZV;
560 }
561 else
562 {
563 direction = -1;
564 if (! end) end = BEGV;
565 }
566
567 newline_cache_on_off (current_buffer);
568 newline_cache = current_buffer->newline_cache;
569
570 if (shortage != 0)
571 *shortage = 0;
572
573 immediate_quit = allow_quit;
574
575 if (count > 0)
576 while (start != end)
577 {
578 /* Our innermost scanning loop is very simple; it doesn't know
579 about gaps, buffer ends, or the newline cache. ceiling is
580 the position of the last character before the next such
581 obstacle --- the last character the dumb search loop should
582 examine. */
583 int ceiling_byte = CHAR_TO_BYTE (end) - 1;
584 int start_byte = CHAR_TO_BYTE (start);
585 int tem;
586
587 /* If we're looking for a newline, consult the newline cache
588 to see where we can avoid some scanning. */
589 if (target == '\n' && newline_cache)
590 {
591 int next_change;
592 immediate_quit = 0;
593 while (region_cache_forward
594 (current_buffer, newline_cache, start_byte, &next_change))
595 start_byte = next_change;
596 immediate_quit = allow_quit;
597
598 /* START should never be after END. */
599 if (start_byte > ceiling_byte)
600 start_byte = ceiling_byte;
601
602 /* Now the text after start is an unknown region, and
603 next_change is the position of the next known region. */
604 ceiling_byte = min (next_change - 1, ceiling_byte);
605 }
606
607 /* The dumb loop can only scan text stored in contiguous
608 bytes. BUFFER_CEILING_OF returns the last character
609 position that is contiguous, so the ceiling is the
610 position after that. */
611 tem = BUFFER_CEILING_OF (start_byte);
612 ceiling_byte = min (tem, ceiling_byte);
613
614 {
615 /* The termination address of the dumb loop. */
616 register unsigned char *ceiling_addr
617 = BYTE_POS_ADDR (ceiling_byte) + 1;
618 register unsigned char *cursor
619 = BYTE_POS_ADDR (start_byte);
620 unsigned char *base = cursor;
621
622 while (cursor < ceiling_addr)
623 {
624 unsigned char *scan_start = cursor;
625
626 /* The dumb loop. */
627 while (*cursor != target && ++cursor < ceiling_addr)
628 ;
629
630 /* If we're looking for newlines, cache the fact that
631 the region from start to cursor is free of them. */
632 if (target == '\n' && newline_cache)
633 know_region_cache (current_buffer, newline_cache,
634 start_byte + scan_start - base,
635 start_byte + cursor - base);
636
637 /* Did we find the target character? */
638 if (cursor < ceiling_addr)
639 {
640 if (--count == 0)
641 {
642 immediate_quit = 0;
643 return BYTE_TO_CHAR (start_byte + cursor - base + 1);
644 }
645 cursor++;
646 }
647 }
648
649 start = BYTE_TO_CHAR (start_byte + cursor - base);
650 }
651 }
652 else
653 while (start > end)
654 {
655 /* The last character to check before the next obstacle. */
656 int ceiling_byte = CHAR_TO_BYTE (end);
657 int start_byte = CHAR_TO_BYTE (start);
658 int tem;
659
660 /* Consult the newline cache, if appropriate. */
661 if (target == '\n' && newline_cache)
662 {
663 int next_change;
664 immediate_quit = 0;
665 while (region_cache_backward
666 (current_buffer, newline_cache, start_byte, &next_change))
667 start_byte = next_change;
668 immediate_quit = allow_quit;
669
670 /* Start should never be at or before end. */
671 if (start_byte <= ceiling_byte)
672 start_byte = ceiling_byte + 1;
673
674 /* Now the text before start is an unknown region, and
675 next_change is the position of the next known region. */
676 ceiling_byte = max (next_change, ceiling_byte);
677 }
678
679 /* Stop scanning before the gap. */
680 tem = BUFFER_FLOOR_OF (start_byte - 1);
681 ceiling_byte = max (tem, ceiling_byte);
682
683 {
684 /* The termination address of the dumb loop. */
685 register unsigned char *ceiling_addr = BYTE_POS_ADDR (ceiling_byte);
686 register unsigned char *cursor = BYTE_POS_ADDR (start_byte - 1);
687 unsigned char *base = cursor;
688
689 while (cursor >= ceiling_addr)
690 {
691 unsigned char *scan_start = cursor;
692
693 while (*cursor != target && --cursor >= ceiling_addr)
694 ;
695
696 /* If we're looking for newlines, cache the fact that
697 the region from after the cursor to start is free of them. */
698 if (target == '\n' && newline_cache)
699 know_region_cache (current_buffer, newline_cache,
700 start_byte + cursor - base,
701 start_byte + scan_start - base);
702
703 /* Did we find the target character? */
704 if (cursor >= ceiling_addr)
705 {
706 if (++count >= 0)
707 {
708 immediate_quit = 0;
709 return BYTE_TO_CHAR (start_byte + cursor - base);
710 }
711 cursor--;
712 }
713 }
714
715 start = BYTE_TO_CHAR (start_byte + cursor - base);
716 }
717 }
718
719 immediate_quit = 0;
720 if (shortage != 0)
721 *shortage = count * direction;
722 return start;
723 }
724 \f
725 /* Search for COUNT instances of a line boundary, which means either a
726 newline or (if selective display enabled) a carriage return.
727 Start at START. If COUNT is negative, search backwards.
728
729 We report the resulting position by calling TEMP_SET_PT_BOTH.
730
731 If we find COUNT instances. we position after (always after,
732 even if scanning backwards) the COUNTth match, and return 0.
733
734 If we don't find COUNT instances before reaching the end of the
735 buffer (or the beginning, if scanning backwards), we return
736 the number of line boundaries left unfound, and position at
737 the limit we bumped up against.
738
739 If ALLOW_QUIT is non-zero, set immediate_quit. That's good to do
740 except in special cases. */
741
742 int
743 scan_newline (start, start_byte, limit, limit_byte, count, allow_quit)
744 int start, start_byte;
745 int limit, limit_byte;
746 register int count;
747 int allow_quit;
748 {
749 int direction = ((count > 0) ? 1 : -1);
750
751 register unsigned char *cursor;
752 unsigned char *base;
753
754 register int ceiling;
755 register unsigned char *ceiling_addr;
756
757 int old_immediate_quit = immediate_quit;
758
759 /* The code that follows is like scan_buffer
760 but checks for either newline or carriage return. */
761
762 if (allow_quit)
763 immediate_quit++;
764
765 start_byte = CHAR_TO_BYTE (start);
766
767 if (count > 0)
768 {
769 while (start_byte < limit_byte)
770 {
771 ceiling = BUFFER_CEILING_OF (start_byte);
772 ceiling = min (limit_byte - 1, ceiling);
773 ceiling_addr = BYTE_POS_ADDR (ceiling) + 1;
774 base = (cursor = BYTE_POS_ADDR (start_byte));
775 while (1)
776 {
777 while (*cursor != '\n' && ++cursor != ceiling_addr)
778 ;
779
780 if (cursor != ceiling_addr)
781 {
782 if (--count == 0)
783 {
784 immediate_quit = old_immediate_quit;
785 start_byte = start_byte + cursor - base + 1;
786 start = BYTE_TO_CHAR (start_byte);
787 TEMP_SET_PT_BOTH (start, start_byte);
788 return 0;
789 }
790 else
791 if (++cursor == ceiling_addr)
792 break;
793 }
794 else
795 break;
796 }
797 start_byte += cursor - base;
798 }
799 }
800 else
801 {
802 while (start_byte > limit_byte)
803 {
804 ceiling = BUFFER_FLOOR_OF (start_byte - 1);
805 ceiling = max (limit_byte, ceiling);
806 ceiling_addr = BYTE_POS_ADDR (ceiling) - 1;
807 base = (cursor = BYTE_POS_ADDR (start_byte - 1) + 1);
808 while (1)
809 {
810 while (--cursor != ceiling_addr && *cursor != '\n')
811 ;
812
813 if (cursor != ceiling_addr)
814 {
815 if (++count == 0)
816 {
817 immediate_quit = old_immediate_quit;
818 /* Return the position AFTER the match we found. */
819 start_byte = start_byte + cursor - base + 1;
820 start = BYTE_TO_CHAR (start_byte);
821 TEMP_SET_PT_BOTH (start, start_byte);
822 return 0;
823 }
824 }
825 else
826 break;
827 }
828 /* Here we add 1 to compensate for the last decrement
829 of CURSOR, which took it past the valid range. */
830 start_byte += cursor - base + 1;
831 }
832 }
833
834 TEMP_SET_PT_BOTH (limit, limit_byte);
835 immediate_quit = old_immediate_quit;
836
837 return count * direction;
838 }
839
840 int
841 find_next_newline_no_quit (from, cnt)
842 register int from, cnt;
843 {
844 return scan_buffer ('\n', from, 0, cnt, (int *) 0, 0);
845 }
846
847 /* Like find_next_newline, but returns position before the newline,
848 not after, and only search up to TO. This isn't just
849 find_next_newline (...)-1, because you might hit TO. */
850
851 int
852 find_before_next_newline (from, to, cnt)
853 int from, to, cnt;
854 {
855 int shortage;
856 int pos = scan_buffer ('\n', from, to, cnt, &shortage, 1);
857
858 if (shortage == 0)
859 pos--;
860
861 return pos;
862 }
863 \f
864 /* Subroutines of Lisp buffer search functions. */
865
866 static Lisp_Object
867 search_command (string, bound, noerror, count, direction, RE, posix)
868 Lisp_Object string, bound, noerror, count;
869 int direction;
870 int RE;
871 int posix;
872 {
873 register int np;
874 int lim, lim_byte;
875 int n = direction;
876
877 if (!NILP (count))
878 {
879 CHECK_NUMBER (count);
880 n *= XINT (count);
881 }
882
883 CHECK_STRING (string);
884 if (NILP (bound))
885 {
886 if (n > 0)
887 lim = ZV, lim_byte = ZV_BYTE;
888 else
889 lim = BEGV, lim_byte = BEGV_BYTE;
890 }
891 else
892 {
893 CHECK_NUMBER_COERCE_MARKER (bound);
894 lim = XINT (bound);
895 if (n > 0 ? lim < PT : lim > PT)
896 error ("Invalid search bound (wrong side of point)");
897 if (lim > ZV)
898 lim = ZV, lim_byte = ZV_BYTE;
899 else if (lim < BEGV)
900 lim = BEGV, lim_byte = BEGV_BYTE;
901 else
902 lim_byte = CHAR_TO_BYTE (lim);
903 }
904
905 np = search_buffer (string, PT, PT_BYTE, lim, lim_byte, n, RE,
906 (!NILP (current_buffer->case_fold_search)
907 ? current_buffer->case_canon_table
908 : Qnil),
909 (!NILP (current_buffer->case_fold_search)
910 ? current_buffer->case_eqv_table
911 : Qnil),
912 posix);
913 if (np <= 0)
914 {
915 if (NILP (noerror))
916 return signal_failure (string);
917 if (!EQ (noerror, Qt))
918 {
919 if (lim < BEGV || lim > ZV)
920 abort ();
921 SET_PT_BOTH (lim, lim_byte);
922 return Qnil;
923 #if 0 /* This would be clean, but maybe programs depend on
924 a value of nil here. */
925 np = lim;
926 #endif
927 }
928 else
929 return Qnil;
930 }
931
932 if (np < BEGV || np > ZV)
933 abort ();
934
935 SET_PT (np);
936
937 return make_number (np);
938 }
939 \f
940 /* Return 1 if REGEXP it matches just one constant string. */
941
942 static int
943 trivial_regexp_p (regexp)
944 Lisp_Object regexp;
945 {
946 int len = SBYTES (regexp);
947 unsigned char *s = SDATA (regexp);
948 while (--len >= 0)
949 {
950 switch (*s++)
951 {
952 case '.': case '*': case '+': case '?': case '[': case '^': case '$':
953 return 0;
954 case '\\':
955 if (--len < 0)
956 return 0;
957 switch (*s++)
958 {
959 case '|': case '(': case ')': case '`': case '\'': case 'b':
960 case 'B': case '<': case '>': case 'w': case 'W': case 's':
961 case 'S': case '=': case '{': case '}': case '_':
962 case 'c': case 'C': /* for categoryspec and notcategoryspec */
963 case '1': case '2': case '3': case '4': case '5':
964 case '6': case '7': case '8': case '9':
965 return 0;
966 }
967 }
968 }
969 return 1;
970 }
971
972 /* Search for the n'th occurrence of STRING in the current buffer,
973 starting at position POS and stopping at position LIM,
974 treating STRING as a literal string if RE is false or as
975 a regular expression if RE is true.
976
977 If N is positive, searching is forward and LIM must be greater than POS.
978 If N is negative, searching is backward and LIM must be less than POS.
979
980 Returns -x if x occurrences remain to be found (x > 0),
981 or else the position at the beginning of the Nth occurrence
982 (if searching backward) or the end (if searching forward).
983
984 POSIX is nonzero if we want full backtracking (POSIX style)
985 for this pattern. 0 means backtrack only enough to get a valid match. */
986
987 #define TRANSLATE(out, trt, d) \
988 do \
989 { \
990 if (! NILP (trt)) \
991 { \
992 Lisp_Object temp; \
993 temp = Faref (trt, make_number (d)); \
994 if (INTEGERP (temp)) \
995 out = XINT (temp); \
996 else \
997 out = d; \
998 } \
999 else \
1000 out = d; \
1001 } \
1002 while (0)
1003
1004 static int
1005 search_buffer (string, pos, pos_byte, lim, lim_byte, n,
1006 RE, trt, inverse_trt, posix)
1007 Lisp_Object string;
1008 int pos;
1009 int pos_byte;
1010 int lim;
1011 int lim_byte;
1012 int n;
1013 int RE;
1014 Lisp_Object trt;
1015 Lisp_Object inverse_trt;
1016 int posix;
1017 {
1018 int len = SCHARS (string);
1019 int len_byte = SBYTES (string);
1020 register int i;
1021
1022 if (running_asynch_code)
1023 save_search_regs ();
1024
1025 /* Searching 0 times means don't move. */
1026 /* Null string is found at starting position. */
1027 if (len == 0 || n == 0)
1028 {
1029 set_search_regs (pos_byte, 0);
1030 return pos;
1031 }
1032
1033 if (RE && !(trivial_regexp_p (string) && NILP (Vsearch_spaces_regexp)))
1034 {
1035 unsigned char *p1, *p2;
1036 int s1, s2;
1037 struct re_pattern_buffer *bufp;
1038
1039 bufp = compile_pattern (string, &search_regs, trt, posix,
1040 !NILP (current_buffer->enable_multibyte_characters));
1041
1042 immediate_quit = 1; /* Quit immediately if user types ^G,
1043 because letting this function finish
1044 can take too long. */
1045 QUIT; /* Do a pending quit right away,
1046 to avoid paradoxical behavior */
1047 /* Get pointers and sizes of the two strings
1048 that make up the visible portion of the buffer. */
1049
1050 p1 = BEGV_ADDR;
1051 s1 = GPT_BYTE - BEGV_BYTE;
1052 p2 = GAP_END_ADDR;
1053 s2 = ZV_BYTE - GPT_BYTE;
1054 if (s1 < 0)
1055 {
1056 p2 = p1;
1057 s2 = ZV_BYTE - BEGV_BYTE;
1058 s1 = 0;
1059 }
1060 if (s2 < 0)
1061 {
1062 s1 = ZV_BYTE - BEGV_BYTE;
1063 s2 = 0;
1064 }
1065 re_match_object = Qnil;
1066
1067 while (n < 0)
1068 {
1069 int val;
1070 val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
1071 pos_byte - BEGV_BYTE, lim_byte - pos_byte,
1072 &search_regs,
1073 /* Don't allow match past current point */
1074 pos_byte - BEGV_BYTE);
1075 if (val == -2)
1076 {
1077 matcher_overflow ();
1078 }
1079 if (val >= 0)
1080 {
1081 pos_byte = search_regs.start[0] + BEGV_BYTE;
1082 for (i = 0; i < search_regs.num_regs; i++)
1083 if (search_regs.start[i] >= 0)
1084 {
1085 search_regs.start[i]
1086 = BYTE_TO_CHAR (search_regs.start[i] + BEGV_BYTE);
1087 search_regs.end[i]
1088 = BYTE_TO_CHAR (search_regs.end[i] + BEGV_BYTE);
1089 }
1090 XSETBUFFER (last_thing_searched, current_buffer);
1091 /* Set pos to the new position. */
1092 pos = search_regs.start[0];
1093 }
1094 else
1095 {
1096 immediate_quit = 0;
1097 return (n);
1098 }
1099 n++;
1100 }
1101 while (n > 0)
1102 {
1103 int val;
1104 val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
1105 pos_byte - BEGV_BYTE, lim_byte - pos_byte,
1106 &search_regs,
1107 lim_byte - BEGV_BYTE);
1108 if (val == -2)
1109 {
1110 matcher_overflow ();
1111 }
1112 if (val >= 0)
1113 {
1114 pos_byte = search_regs.end[0] + BEGV_BYTE;
1115 for (i = 0; i < search_regs.num_regs; i++)
1116 if (search_regs.start[i] >= 0)
1117 {
1118 search_regs.start[i]
1119 = BYTE_TO_CHAR (search_regs.start[i] + BEGV_BYTE);
1120 search_regs.end[i]
1121 = BYTE_TO_CHAR (search_regs.end[i] + BEGV_BYTE);
1122 }
1123 XSETBUFFER (last_thing_searched, current_buffer);
1124 pos = search_regs.end[0];
1125 }
1126 else
1127 {
1128 immediate_quit = 0;
1129 return (0 - n);
1130 }
1131 n--;
1132 }
1133 immediate_quit = 0;
1134 return (pos);
1135 }
1136 else /* non-RE case */
1137 {
1138 unsigned char *raw_pattern, *pat;
1139 int raw_pattern_size;
1140 int raw_pattern_size_byte;
1141 unsigned char *patbuf;
1142 int multibyte = !NILP (current_buffer->enable_multibyte_characters);
1143 unsigned char *base_pat = SDATA (string);
1144 /* High bits of char; 0 for ASCII characters, (CHAR & ~0x3F)
1145 otherwise. Characters of the same high bits have the same
1146 sequence of bytes but last. To do the BM search, all
1147 characters in STRING must have the same high bits (including
1148 their case translations). */
1149 int char_high_bits = -1;
1150 int boyer_moore_ok = 1;
1151
1152 /* MULTIBYTE says whether the text to be searched is multibyte.
1153 We must convert PATTERN to match that, or we will not really
1154 find things right. */
1155
1156 if (multibyte == STRING_MULTIBYTE (string))
1157 {
1158 raw_pattern = (unsigned char *) SDATA (string);
1159 raw_pattern_size = SCHARS (string);
1160 raw_pattern_size_byte = SBYTES (string);
1161 }
1162 else if (multibyte)
1163 {
1164 raw_pattern_size = SCHARS (string);
1165 raw_pattern_size_byte
1166 = count_size_as_multibyte (SDATA (string),
1167 raw_pattern_size);
1168 raw_pattern = (unsigned char *) alloca (raw_pattern_size_byte + 1);
1169 copy_text (SDATA (string), raw_pattern,
1170 SCHARS (string), 0, 1);
1171 }
1172 else
1173 {
1174 /* Converting multibyte to single-byte.
1175
1176 ??? Perhaps this conversion should be done in a special way
1177 by subtracting nonascii-insert-offset from each non-ASCII char,
1178 so that only the multibyte chars which really correspond to
1179 the chosen single-byte character set can possibly match. */
1180 raw_pattern_size = SCHARS (string);
1181 raw_pattern_size_byte = SCHARS (string);
1182 raw_pattern = (unsigned char *) alloca (raw_pattern_size + 1);
1183 copy_text (SDATA (string), raw_pattern,
1184 SBYTES (string), 1, 0);
1185 }
1186
1187 /* Copy and optionally translate the pattern. */
1188 len = raw_pattern_size;
1189 len_byte = raw_pattern_size_byte;
1190 patbuf = (unsigned char *) alloca (len * MAX_MULTIBYTE_LENGTH);
1191 pat = patbuf;
1192 base_pat = raw_pattern;
1193 if (multibyte)
1194 {
1195 while (--len >= 0)
1196 {
1197 int c, translated, inverse;
1198 int in_charlen;
1199
1200 /* If we got here and the RE flag is set, it's because we're
1201 dealing with a regexp known to be trivial, so the backslash
1202 just quotes the next character. */
1203 if (RE && *base_pat == '\\')
1204 {
1205 len--;
1206 len_byte--;
1207 base_pat++;
1208 }
1209
1210 c = STRING_CHAR_AND_LENGTH (base_pat, len_byte, in_charlen);
1211
1212 /* Translate the character, if requested. */
1213 TRANSLATE (translated, trt, c);
1214 TRANSLATE (inverse, inverse_trt, c);
1215
1216 /* Did this char actually get translated?
1217 Would any other char get translated into it? */
1218 if (translated != c || inverse != c)
1219 {
1220 /* Keep track of which character set row
1221 contains the characters that need translation. */
1222 int this_high_bit = ASCII_CHAR_P (c) ? 0 : (c & ~0x3F);
1223 int c1 = inverse != c ? inverse : translated;
1224 int trt_high_bit = ASCII_CHAR_P (c1) ? 0 : (c1 & ~0x3F);
1225
1226 if (this_high_bit != trt_high_bit)
1227 boyer_moore_ok = 0;
1228 else if (char_high_bits == -1)
1229 char_high_bits = this_high_bit;
1230 else if (char_high_bits != this_high_bit)
1231 /* If two different rows appear, needing translation,
1232 then we cannot use boyer_moore search. */
1233 boyer_moore_ok = 0;
1234 }
1235
1236 /* Store this character into the translated pattern. */
1237 CHAR_STRING_ADVANCE (translated, pat);
1238 base_pat += in_charlen;
1239 len_byte -= in_charlen;
1240 }
1241 }
1242 else
1243 {
1244 /* Unibyte buffer. */
1245 char_high_bits = 0;
1246 while (--len >= 0)
1247 {
1248 int c, translated;
1249
1250 /* If we got here and the RE flag is set, it's because we're
1251 dealing with a regexp known to be trivial, so the backslash
1252 just quotes the next character. */
1253 if (RE && *base_pat == '\\')
1254 {
1255 len--;
1256 base_pat++;
1257 }
1258 c = *base_pat++;
1259 TRANSLATE (translated, trt, c);
1260 *pat++ = translated;
1261 }
1262 }
1263
1264 len_byte = pat - patbuf;
1265 len = raw_pattern_size;
1266 pat = base_pat = patbuf;
1267
1268 if (boyer_moore_ok)
1269 return boyer_moore (n, pat, len, len_byte, trt, inverse_trt,
1270 pos, pos_byte, lim, lim_byte,
1271 char_high_bits);
1272 else
1273 return simple_search (n, pat, len, len_byte, trt,
1274 pos, pos_byte, lim, lim_byte);
1275 }
1276 }
1277 \f
1278 /* Do a simple string search N times for the string PAT,
1279 whose length is LEN/LEN_BYTE,
1280 from buffer position POS/POS_BYTE until LIM/LIM_BYTE.
1281 TRT is the translation table.
1282
1283 Return the character position where the match is found.
1284 Otherwise, if M matches remained to be found, return -M.
1285
1286 This kind of search works regardless of what is in PAT and
1287 regardless of what is in TRT. It is used in cases where
1288 boyer_moore cannot work. */
1289
1290 static int
1291 simple_search (n, pat, len, len_byte, trt, pos, pos_byte, lim, lim_byte)
1292 int n;
1293 unsigned char *pat;
1294 int len, len_byte;
1295 Lisp_Object trt;
1296 int pos, pos_byte;
1297 int lim, lim_byte;
1298 {
1299 int multibyte = ! NILP (current_buffer->enable_multibyte_characters);
1300 int forward = n > 0;
1301
1302 if (lim > pos && multibyte)
1303 while (n > 0)
1304 {
1305 while (1)
1306 {
1307 /* Try matching at position POS. */
1308 int this_pos = pos;
1309 int this_pos_byte = pos_byte;
1310 int this_len = len;
1311 int this_len_byte = len_byte;
1312 unsigned char *p = pat;
1313 if (pos + len > lim)
1314 goto stop;
1315
1316 while (this_len > 0)
1317 {
1318 int charlen, buf_charlen;
1319 int pat_ch, buf_ch;
1320
1321 pat_ch = STRING_CHAR_AND_LENGTH (p, this_len_byte, charlen);
1322 buf_ch = STRING_CHAR_AND_LENGTH (BYTE_POS_ADDR (this_pos_byte),
1323 ZV_BYTE - this_pos_byte,
1324 buf_charlen);
1325 TRANSLATE (buf_ch, trt, buf_ch);
1326
1327 if (buf_ch != pat_ch)
1328 break;
1329
1330 this_len_byte -= charlen;
1331 this_len--;
1332 p += charlen;
1333
1334 this_pos_byte += buf_charlen;
1335 this_pos++;
1336 }
1337
1338 if (this_len == 0)
1339 {
1340 pos += len;
1341 pos_byte += len_byte;
1342 break;
1343 }
1344
1345 INC_BOTH (pos, pos_byte);
1346 }
1347
1348 n--;
1349 }
1350 else if (lim > pos)
1351 while (n > 0)
1352 {
1353 while (1)
1354 {
1355 /* Try matching at position POS. */
1356 int this_pos = pos;
1357 int this_len = len;
1358 unsigned char *p = pat;
1359
1360 if (pos + len > lim)
1361 goto stop;
1362
1363 while (this_len > 0)
1364 {
1365 int pat_ch = *p++;
1366 int buf_ch = FETCH_BYTE (this_pos);
1367 TRANSLATE (buf_ch, trt, buf_ch);
1368
1369 if (buf_ch != pat_ch)
1370 break;
1371
1372 this_len--;
1373 this_pos++;
1374 }
1375
1376 if (this_len == 0)
1377 {
1378 pos += len;
1379 break;
1380 }
1381
1382 pos++;
1383 }
1384
1385 n--;
1386 }
1387 /* Backwards search. */
1388 else if (lim < pos && multibyte)
1389 while (n < 0)
1390 {
1391 while (1)
1392 {
1393 /* Try matching at position POS. */
1394 int this_pos = pos - len;
1395 int this_pos_byte;
1396 int this_len = len;
1397 int this_len_byte = len_byte;
1398 unsigned char *p = pat;
1399
1400 if (pos - len < lim)
1401 goto stop;
1402 this_pos_byte = CHAR_TO_BYTE (this_pos);
1403
1404 while (this_len > 0)
1405 {
1406 int charlen, buf_charlen;
1407 int pat_ch, buf_ch;
1408
1409 pat_ch = STRING_CHAR_AND_LENGTH (p, this_len_byte, charlen);
1410 buf_ch = STRING_CHAR_AND_LENGTH (BYTE_POS_ADDR (this_pos_byte),
1411 ZV_BYTE - this_pos_byte,
1412 buf_charlen);
1413 TRANSLATE (buf_ch, trt, buf_ch);
1414
1415 if (buf_ch != pat_ch)
1416 break;
1417
1418 this_len_byte -= charlen;
1419 this_len--;
1420 p += charlen;
1421 this_pos_byte += buf_charlen;
1422 this_pos++;
1423 }
1424
1425 if (this_len == 0)
1426 {
1427 pos -= len;
1428 pos_byte -= len_byte;
1429 break;
1430 }
1431
1432 DEC_BOTH (pos, pos_byte);
1433 }
1434
1435 n++;
1436 }
1437 else if (lim < pos)
1438 while (n < 0)
1439 {
1440 while (1)
1441 {
1442 /* Try matching at position POS. */
1443 int this_pos = pos - len;
1444 int this_len = len;
1445 unsigned char *p = pat;
1446
1447 if (pos - len < lim)
1448 goto stop;
1449
1450 while (this_len > 0)
1451 {
1452 int pat_ch = *p++;
1453 int buf_ch = FETCH_BYTE (this_pos);
1454 TRANSLATE (buf_ch, trt, buf_ch);
1455
1456 if (buf_ch != pat_ch)
1457 break;
1458 this_len--;
1459 this_pos++;
1460 }
1461
1462 if (this_len == 0)
1463 {
1464 pos -= len;
1465 break;
1466 }
1467
1468 pos--;
1469 }
1470
1471 n++;
1472 }
1473
1474 stop:
1475 if (n == 0)
1476 {
1477 if (forward)
1478 set_search_regs ((multibyte ? pos_byte : pos) - len_byte, len_byte);
1479 else
1480 set_search_regs (multibyte ? pos_byte : pos, len_byte);
1481
1482 return pos;
1483 }
1484 else if (n > 0)
1485 return -n;
1486 else
1487 return n;
1488 }
1489 \f
1490 /* Do Boyer-Moore search N times for the string PAT,
1491 whose length is LEN/LEN_BYTE,
1492 from buffer position POS/POS_BYTE until LIM/LIM_BYTE.
1493 DIRECTION says which direction we search in.
1494 TRT and INVERSE_TRT are translation tables.
1495
1496 This kind of search works if all the characters in PAT that have
1497 nontrivial translation are the same aside from the last byte. This
1498 makes it possible to translate just the last byte of a character,
1499 and do so after just a simple test of the context.
1500
1501 If that criterion is not satisfied, do not call this function. */
1502
1503 static int
1504 boyer_moore (n, base_pat, len, len_byte, trt, inverse_trt,
1505 pos, pos_byte, lim, lim_byte, char_high_bits)
1506 int n;
1507 unsigned char *base_pat;
1508 int len, len_byte;
1509 Lisp_Object trt;
1510 Lisp_Object inverse_trt;
1511 int pos, pos_byte;
1512 int lim, lim_byte;
1513 int char_high_bits;
1514 {
1515 int direction = ((n > 0) ? 1 : -1);
1516 register int dirlen;
1517 int infinity, limit, stride_for_teases = 0;
1518 register int *BM_tab;
1519 int *BM_tab_base;
1520 register unsigned char *cursor, *p_limit;
1521 register int i, j;
1522 unsigned char *pat, *pat_end;
1523 int multibyte = ! NILP (current_buffer->enable_multibyte_characters);
1524
1525 unsigned char simple_translate[0400];
1526 int translate_prev_byte = 0;
1527 int translate_anteprev_byte = 0;
1528
1529 #ifdef C_ALLOCA
1530 int BM_tab_space[0400];
1531 BM_tab = &BM_tab_space[0];
1532 #else
1533 BM_tab = (int *) alloca (0400 * sizeof (int));
1534 #endif
1535 /* The general approach is that we are going to maintain that we know */
1536 /* the first (closest to the present position, in whatever direction */
1537 /* we're searching) character that could possibly be the last */
1538 /* (furthest from present position) character of a valid match. We */
1539 /* advance the state of our knowledge by looking at that character */
1540 /* and seeing whether it indeed matches the last character of the */
1541 /* pattern. If it does, we take a closer look. If it does not, we */
1542 /* move our pointer (to putative last characters) as far as is */
1543 /* logically possible. This amount of movement, which I call a */
1544 /* stride, will be the length of the pattern if the actual character */
1545 /* appears nowhere in the pattern, otherwise it will be the distance */
1546 /* from the last occurrence of that character to the end of the */
1547 /* pattern. */
1548 /* As a coding trick, an enormous stride is coded into the table for */
1549 /* characters that match the last character. This allows use of only */
1550 /* a single test, a test for having gone past the end of the */
1551 /* permissible match region, to test for both possible matches (when */
1552 /* the stride goes past the end immediately) and failure to */
1553 /* match (where you get nudged past the end one stride at a time). */
1554
1555 /* Here we make a "mickey mouse" BM table. The stride of the search */
1556 /* is determined only by the last character of the putative match. */
1557 /* If that character does not match, we will stride the proper */
1558 /* distance to propose a match that superimposes it on the last */
1559 /* instance of a character that matches it (per trt), or misses */
1560 /* it entirely if there is none. */
1561
1562 dirlen = len_byte * direction;
1563 infinity = dirlen - (lim_byte + pos_byte + len_byte + len_byte) * direction;
1564
1565 /* Record position after the end of the pattern. */
1566 pat_end = base_pat + len_byte;
1567 /* BASE_PAT points to a character that we start scanning from.
1568 It is the first character in a forward search,
1569 the last character in a backward search. */
1570 if (direction < 0)
1571 base_pat = pat_end - 1;
1572
1573 BM_tab_base = BM_tab;
1574 BM_tab += 0400;
1575 j = dirlen; /* to get it in a register */
1576 /* A character that does not appear in the pattern induces a */
1577 /* stride equal to the pattern length. */
1578 while (BM_tab_base != BM_tab)
1579 {
1580 *--BM_tab = j;
1581 *--BM_tab = j;
1582 *--BM_tab = j;
1583 *--BM_tab = j;
1584 }
1585
1586 /* We use this for translation, instead of TRT itself.
1587 We fill this in to handle the characters that actually
1588 occur in the pattern. Others don't matter anyway! */
1589 bzero (simple_translate, sizeof simple_translate);
1590 for (i = 0; i < 0400; i++)
1591 simple_translate[i] = i;
1592
1593 i = 0;
1594 while (i != infinity)
1595 {
1596 unsigned char *ptr = base_pat + i;
1597 i += direction;
1598 if (i == dirlen)
1599 i = infinity;
1600 if (! NILP (trt))
1601 {
1602 int ch;
1603 int untranslated;
1604 int this_translated = 1;
1605
1606 if (multibyte
1607 /* Is *PTR the last byte of a character? */
1608 && (pat_end - ptr == 1 || CHAR_HEAD_P (ptr[1])))
1609 {
1610 unsigned char *charstart = ptr;
1611 while (! CHAR_HEAD_P (*charstart))
1612 charstart--;
1613 untranslated = STRING_CHAR (charstart, ptr - charstart + 1);
1614 if (char_high_bits
1615 == (ASCII_CHAR_P (untranslated) ? 0 : untranslated & ~0x3F))
1616 {
1617 TRANSLATE (ch, trt, untranslated);
1618 if (! CHAR_HEAD_P (*ptr))
1619 {
1620 translate_prev_byte = ptr[-1];
1621 if (! CHAR_HEAD_P (translate_prev_byte))
1622 translate_anteprev_byte = ptr[-2];
1623 }
1624 }
1625 else
1626 {
1627 this_translated = 0;
1628 ch = *ptr;
1629 }
1630 }
1631 else if (!multibyte)
1632 TRANSLATE (ch, trt, *ptr);
1633 else
1634 {
1635 ch = *ptr;
1636 this_translated = 0;
1637 }
1638
1639 if (this_translated
1640 && ch >= 0200)
1641 j = (ch & 0x3F) | 0200;
1642 else
1643 j = (unsigned char) ch;
1644
1645 if (i == infinity)
1646 stride_for_teases = BM_tab[j];
1647
1648 BM_tab[j] = dirlen - i;
1649 /* A translation table is accompanied by its inverse -- see */
1650 /* comment following downcase_table for details */
1651 if (this_translated)
1652 {
1653 int starting_ch = ch;
1654 int starting_j = j;
1655 while (1)
1656 {
1657 TRANSLATE (ch, inverse_trt, ch);
1658 if (ch > 0200)
1659 j = (ch & 0x3F) | 0200;
1660 else
1661 j = (unsigned char) ch;
1662
1663 /* For all the characters that map into CH,
1664 set up simple_translate to map the last byte
1665 into STARTING_J. */
1666 simple_translate[j] = starting_j;
1667 if (ch == starting_ch)
1668 break;
1669 BM_tab[j] = dirlen - i;
1670 }
1671 }
1672 }
1673 else
1674 {
1675 j = *ptr;
1676
1677 if (i == infinity)
1678 stride_for_teases = BM_tab[j];
1679 BM_tab[j] = dirlen - i;
1680 }
1681 /* stride_for_teases tells how much to stride if we get a */
1682 /* match on the far character but are subsequently */
1683 /* disappointed, by recording what the stride would have been */
1684 /* for that character if the last character had been */
1685 /* different. */
1686 }
1687 infinity = dirlen - infinity;
1688 pos_byte += dirlen - ((direction > 0) ? direction : 0);
1689 /* loop invariant - POS_BYTE points at where last char (first
1690 char if reverse) of pattern would align in a possible match. */
1691 while (n != 0)
1692 {
1693 int tail_end;
1694 unsigned char *tail_end_ptr;
1695
1696 /* It's been reported that some (broken) compiler thinks that
1697 Boolean expressions in an arithmetic context are unsigned.
1698 Using an explicit ?1:0 prevents this. */
1699 if ((lim_byte - pos_byte - ((direction > 0) ? 1 : 0)) * direction
1700 < 0)
1701 return (n * (0 - direction));
1702 /* First we do the part we can by pointers (maybe nothing) */
1703 QUIT;
1704 pat = base_pat;
1705 limit = pos_byte - dirlen + direction;
1706 if (direction > 0)
1707 {
1708 limit = BUFFER_CEILING_OF (limit);
1709 /* LIMIT is now the last (not beyond-last!) value POS_BYTE
1710 can take on without hitting edge of buffer or the gap. */
1711 limit = min (limit, pos_byte + 20000);
1712 limit = min (limit, lim_byte - 1);
1713 }
1714 else
1715 {
1716 limit = BUFFER_FLOOR_OF (limit);
1717 /* LIMIT is now the last (not beyond-last!) value POS_BYTE
1718 can take on without hitting edge of buffer or the gap. */
1719 limit = max (limit, pos_byte - 20000);
1720 limit = max (limit, lim_byte);
1721 }
1722 tail_end = BUFFER_CEILING_OF (pos_byte) + 1;
1723 tail_end_ptr = BYTE_POS_ADDR (tail_end);
1724
1725 if ((limit - pos_byte) * direction > 20)
1726 {
1727 unsigned char *p2;
1728
1729 p_limit = BYTE_POS_ADDR (limit);
1730 p2 = (cursor = BYTE_POS_ADDR (pos_byte));
1731 /* In this loop, pos + cursor - p2 is the surrogate for pos */
1732 while (1) /* use one cursor setting as long as i can */
1733 {
1734 if (direction > 0) /* worth duplicating */
1735 {
1736 /* Use signed comparison if appropriate
1737 to make cursor+infinity sure to be > p_limit.
1738 Assuming that the buffer lies in a range of addresses
1739 that are all "positive" (as ints) or all "negative",
1740 either kind of comparison will work as long
1741 as we don't step by infinity. So pick the kind
1742 that works when we do step by infinity. */
1743 if ((EMACS_INT) (p_limit + infinity) > (EMACS_INT) p_limit)
1744 while ((EMACS_INT) cursor <= (EMACS_INT) p_limit)
1745 cursor += BM_tab[*cursor];
1746 else
1747 while ((EMACS_UINT) cursor <= (EMACS_UINT) p_limit)
1748 cursor += BM_tab[*cursor];
1749 }
1750 else
1751 {
1752 if ((EMACS_INT) (p_limit + infinity) < (EMACS_INT) p_limit)
1753 while ((EMACS_INT) cursor >= (EMACS_INT) p_limit)
1754 cursor += BM_tab[*cursor];
1755 else
1756 while ((EMACS_UINT) cursor >= (EMACS_UINT) p_limit)
1757 cursor += BM_tab[*cursor];
1758 }
1759 /* If you are here, cursor is beyond the end of the searched region. */
1760 /* This can happen if you match on the far character of the pattern, */
1761 /* because the "stride" of that character is infinity, a number able */
1762 /* to throw you well beyond the end of the search. It can also */
1763 /* happen if you fail to match within the permitted region and would */
1764 /* otherwise try a character beyond that region */
1765 if ((cursor - p_limit) * direction <= len_byte)
1766 break; /* a small overrun is genuine */
1767 cursor -= infinity; /* large overrun = hit */
1768 i = dirlen - direction;
1769 if (! NILP (trt))
1770 {
1771 while ((i -= direction) + direction != 0)
1772 {
1773 int ch;
1774 cursor -= direction;
1775 /* Translate only the last byte of a character. */
1776 if (! multibyte
1777 || ((cursor == tail_end_ptr
1778 || CHAR_HEAD_P (cursor[1]))
1779 && (CHAR_HEAD_P (cursor[0])
1780 || (translate_prev_byte == cursor[-1]
1781 && (CHAR_HEAD_P (translate_prev_byte)
1782 || translate_anteprev_byte == cursor[-2])))))
1783 ch = simple_translate[*cursor];
1784 else
1785 ch = *cursor;
1786 if (pat[i] != ch)
1787 break;
1788 }
1789 }
1790 else
1791 {
1792 while ((i -= direction) + direction != 0)
1793 {
1794 cursor -= direction;
1795 if (pat[i] != *cursor)
1796 break;
1797 }
1798 }
1799 cursor += dirlen - i - direction; /* fix cursor */
1800 if (i + direction == 0)
1801 {
1802 int position;
1803
1804 cursor -= direction;
1805
1806 position = pos_byte + cursor - p2 + ((direction > 0)
1807 ? 1 - len_byte : 0);
1808 set_search_regs (position, len_byte);
1809
1810 if ((n -= direction) != 0)
1811 cursor += dirlen; /* to resume search */
1812 else
1813 return ((direction > 0)
1814 ? search_regs.end[0] : search_regs.start[0]);
1815 }
1816 else
1817 cursor += stride_for_teases; /* <sigh> we lose - */
1818 }
1819 pos_byte += cursor - p2;
1820 }
1821 else
1822 /* Now we'll pick up a clump that has to be done the hard */
1823 /* way because it covers a discontinuity */
1824 {
1825 limit = ((direction > 0)
1826 ? BUFFER_CEILING_OF (pos_byte - dirlen + 1)
1827 : BUFFER_FLOOR_OF (pos_byte - dirlen - 1));
1828 limit = ((direction > 0)
1829 ? min (limit + len_byte, lim_byte - 1)
1830 : max (limit - len_byte, lim_byte));
1831 /* LIMIT is now the last value POS_BYTE can have
1832 and still be valid for a possible match. */
1833 while (1)
1834 {
1835 /* This loop can be coded for space rather than */
1836 /* speed because it will usually run only once. */
1837 /* (the reach is at most len + 21, and typically */
1838 /* does not exceed len) */
1839 while ((limit - pos_byte) * direction >= 0)
1840 pos_byte += BM_tab[FETCH_BYTE (pos_byte)];
1841 /* now run the same tests to distinguish going off the */
1842 /* end, a match or a phony match. */
1843 if ((pos_byte - limit) * direction <= len_byte)
1844 break; /* ran off the end */
1845 /* Found what might be a match.
1846 Set POS_BYTE back to last (first if reverse) pos. */
1847 pos_byte -= infinity;
1848 i = dirlen - direction;
1849 while ((i -= direction) + direction != 0)
1850 {
1851 int ch;
1852 unsigned char *ptr;
1853 pos_byte -= direction;
1854 ptr = BYTE_POS_ADDR (pos_byte);
1855 /* Translate only the last byte of a character. */
1856 if (! multibyte
1857 || ((ptr == tail_end_ptr
1858 || CHAR_HEAD_P (ptr[1]))
1859 && (CHAR_HEAD_P (ptr[0])
1860 || (translate_prev_byte == ptr[-1]
1861 && (CHAR_HEAD_P (translate_prev_byte)
1862 || translate_anteprev_byte == ptr[-2])))))
1863 ch = simple_translate[*ptr];
1864 else
1865 ch = *ptr;
1866 if (pat[i] != ch)
1867 break;
1868 }
1869 /* Above loop has moved POS_BYTE part or all the way
1870 back to the first pos (last pos if reverse).
1871 Set it once again at the last (first if reverse) char. */
1872 pos_byte += dirlen - i- direction;
1873 if (i + direction == 0)
1874 {
1875 int position;
1876 pos_byte -= direction;
1877
1878 position = pos_byte + ((direction > 0) ? 1 - len_byte : 0);
1879
1880 set_search_regs (position, len_byte);
1881
1882 if ((n -= direction) != 0)
1883 pos_byte += dirlen; /* to resume search */
1884 else
1885 return ((direction > 0)
1886 ? search_regs.end[0] : search_regs.start[0]);
1887 }
1888 else
1889 pos_byte += stride_for_teases;
1890 }
1891 }
1892 /* We have done one clump. Can we continue? */
1893 if ((lim_byte - pos_byte) * direction < 0)
1894 return ((0 - n) * direction);
1895 }
1896 return BYTE_TO_CHAR (pos_byte);
1897 }
1898
1899 /* Record beginning BEG_BYTE and end BEG_BYTE + NBYTES
1900 for the overall match just found in the current buffer.
1901 Also clear out the match data for registers 1 and up. */
1902
1903 static void
1904 set_search_regs (beg_byte, nbytes)
1905 int beg_byte, nbytes;
1906 {
1907 int i;
1908
1909 /* Make sure we have registers in which to store
1910 the match position. */
1911 if (search_regs.num_regs == 0)
1912 {
1913 search_regs.start = (regoff_t *) xmalloc (2 * sizeof (regoff_t));
1914 search_regs.end = (regoff_t *) xmalloc (2 * sizeof (regoff_t));
1915 search_regs.num_regs = 2;
1916 }
1917
1918 /* Clear out the other registers. */
1919 for (i = 1; i < search_regs.num_regs; i++)
1920 {
1921 search_regs.start[i] = -1;
1922 search_regs.end[i] = -1;
1923 }
1924
1925 search_regs.start[0] = BYTE_TO_CHAR (beg_byte);
1926 search_regs.end[0] = BYTE_TO_CHAR (beg_byte + nbytes);
1927 XSETBUFFER (last_thing_searched, current_buffer);
1928 }
1929 \f
1930 /* Given a string of words separated by word delimiters,
1931 compute a regexp that matches those exact words
1932 separated by arbitrary punctuation. */
1933
1934 static Lisp_Object
1935 wordify (string)
1936 Lisp_Object string;
1937 {
1938 register unsigned char *p, *o;
1939 register int i, i_byte, len, punct_count = 0, word_count = 0;
1940 Lisp_Object val;
1941 int prev_c = 0;
1942 int adjust;
1943
1944 CHECK_STRING (string);
1945 p = SDATA (string);
1946 len = SCHARS (string);
1947
1948 for (i = 0, i_byte = 0; i < len; )
1949 {
1950 int c;
1951
1952 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c, string, i, i_byte);
1953
1954 if (SYNTAX (c) != Sword)
1955 {
1956 punct_count++;
1957 if (i > 0 && SYNTAX (prev_c) == Sword)
1958 word_count++;
1959 }
1960
1961 prev_c = c;
1962 }
1963
1964 if (SYNTAX (prev_c) == Sword)
1965 word_count++;
1966 if (!word_count)
1967 return empty_string;
1968
1969 adjust = - punct_count + 5 * (word_count - 1) + 4;
1970 if (STRING_MULTIBYTE (string))
1971 val = make_uninit_multibyte_string (len + adjust,
1972 SBYTES (string)
1973 + adjust);
1974 else
1975 val = make_uninit_string (len + adjust);
1976
1977 o = SDATA (val);
1978 *o++ = '\\';
1979 *o++ = 'b';
1980 prev_c = 0;
1981
1982 for (i = 0, i_byte = 0; i < len; )
1983 {
1984 int c;
1985 int i_byte_orig = i_byte;
1986
1987 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c, string, i, i_byte);
1988
1989 if (SYNTAX (c) == Sword)
1990 {
1991 bcopy (SDATA (string) + i_byte_orig, o,
1992 i_byte - i_byte_orig);
1993 o += i_byte - i_byte_orig;
1994 }
1995 else if (i > 0 && SYNTAX (prev_c) == Sword && --word_count)
1996 {
1997 *o++ = '\\';
1998 *o++ = 'W';
1999 *o++ = '\\';
2000 *o++ = 'W';
2001 *o++ = '*';
2002 }
2003
2004 prev_c = c;
2005 }
2006
2007 *o++ = '\\';
2008 *o++ = 'b';
2009
2010 return val;
2011 }
2012 \f
2013 DEFUN ("search-backward", Fsearch_backward, Ssearch_backward, 1, 4,
2014 "MSearch backward: ",
2015 doc: /* Search backward from point for STRING.
2016 Set point to the beginning of the occurrence found, and return point.
2017 An optional second argument bounds the search; it is a buffer position.
2018 The match found must not extend before that position.
2019 Optional third argument, if t, means if fail just return nil (no error).
2020 If not nil and not t, position at limit of search and return nil.
2021 Optional fourth argument is repeat count--search for successive occurrences.
2022
2023 Search case-sensitivity is determined by the value of the variable
2024 `case-fold-search', which see.
2025
2026 See also the functions `match-beginning', `match-end' and `replace-match'. */)
2027 (string, bound, noerror, count)
2028 Lisp_Object string, bound, noerror, count;
2029 {
2030 return search_command (string, bound, noerror, count, -1, 0, 0);
2031 }
2032
2033 DEFUN ("search-forward", Fsearch_forward, Ssearch_forward, 1, 4, "MSearch: ",
2034 doc: /* Search forward from point for STRING.
2035 Set point to the end of the occurrence found, and return point.
2036 An optional second argument bounds the search; it is a buffer position.
2037 The match found must not extend after that position. nil is equivalent
2038 to (point-max).
2039 Optional third argument, if t, means if fail just return nil (no error).
2040 If not nil and not t, move to limit of search and return nil.
2041 Optional fourth argument is repeat count--search for successive occurrences.
2042
2043 Search case-sensitivity is determined by the value of the variable
2044 `case-fold-search', which see.
2045
2046 See also the functions `match-beginning', `match-end' and `replace-match'. */)
2047 (string, bound, noerror, count)
2048 Lisp_Object string, bound, noerror, count;
2049 {
2050 return search_command (string, bound, noerror, count, 1, 0, 0);
2051 }
2052
2053 DEFUN ("word-search-backward", Fword_search_backward, Sword_search_backward, 1, 4,
2054 "sWord search backward: ",
2055 doc: /* Search backward from point for STRING, ignoring differences in punctuation.
2056 Set point to the beginning of the occurrence found, and return point.
2057 An optional second argument bounds the search; it is a buffer position.
2058 The match found must not extend before that position.
2059 Optional third argument, if t, means if fail just return nil (no error).
2060 If not nil and not t, move to limit of search and return nil.
2061 Optional fourth argument is repeat count--search for successive occurrences. */)
2062 (string, bound, noerror, count)
2063 Lisp_Object string, bound, noerror, count;
2064 {
2065 return search_command (wordify (string), bound, noerror, count, -1, 1, 0);
2066 }
2067
2068 DEFUN ("word-search-forward", Fword_search_forward, Sword_search_forward, 1, 4,
2069 "sWord search: ",
2070 doc: /* Search forward from point for STRING, ignoring differences in punctuation.
2071 Set point to the end of the occurrence found, and return point.
2072 An optional second argument bounds the search; it is a buffer position.
2073 The match found must not extend after that position.
2074 Optional third argument, if t, means if fail just return nil (no error).
2075 If not nil and not t, move to limit of search and return nil.
2076 Optional fourth argument is repeat count--search for successive occurrences. */)
2077 (string, bound, noerror, count)
2078 Lisp_Object string, bound, noerror, count;
2079 {
2080 return search_command (wordify (string), bound, noerror, count, 1, 1, 0);
2081 }
2082
2083 DEFUN ("re-search-backward", Fre_search_backward, Sre_search_backward, 1, 4,
2084 "sRE search backward: ",
2085 doc: /* Search backward from point for match for regular expression REGEXP.
2086 Set point to the beginning of the match, and return point.
2087 The match found is the one starting last in the buffer
2088 and yet ending before the origin of the search.
2089 An optional second argument bounds the search; it is a buffer position.
2090 The match found must start at or after that position.
2091 Optional third argument, if t, means if fail just return nil (no error).
2092 If not nil and not t, move to limit of search and return nil.
2093 Optional fourth argument is repeat count--search for successive occurrences.
2094 See also the functions `match-beginning', `match-end', `match-string',
2095 and `replace-match'. */)
2096 (regexp, bound, noerror, count)
2097 Lisp_Object regexp, bound, noerror, count;
2098 {
2099 return search_command (regexp, bound, noerror, count, -1, 1, 0);
2100 }
2101
2102 DEFUN ("re-search-forward", Fre_search_forward, Sre_search_forward, 1, 4,
2103 "sRE search: ",
2104 doc: /* Search forward from point for regular expression REGEXP.
2105 Set point to the end of the occurrence found, and return point.
2106 An optional second argument bounds the search; it is a buffer position.
2107 The match found must not extend after that position.
2108 Optional third argument, if t, means if fail just return nil (no error).
2109 If not nil and not t, move to limit of search and return nil.
2110 Optional fourth argument is repeat count--search for successive occurrences.
2111 See also the functions `match-beginning', `match-end', `match-string',
2112 and `replace-match'. */)
2113 (regexp, bound, noerror, count)
2114 Lisp_Object regexp, bound, noerror, count;
2115 {
2116 return search_command (regexp, bound, noerror, count, 1, 1, 0);
2117 }
2118
2119 DEFUN ("posix-search-backward", Fposix_search_backward, Sposix_search_backward, 1, 4,
2120 "sPosix search backward: ",
2121 doc: /* Search backward from point for match for regular expression REGEXP.
2122 Find the longest match in accord with Posix regular expression rules.
2123 Set point to the beginning of the match, and return point.
2124 The match found is the one starting last in the buffer
2125 and yet ending before the origin of the search.
2126 An optional second argument bounds the search; it is a buffer position.
2127 The match found must start at or after that position.
2128 Optional third argument, if t, means if fail just return nil (no error).
2129 If not nil and not t, move to limit of search and return nil.
2130 Optional fourth argument is repeat count--search for successive occurrences.
2131 See also the functions `match-beginning', `match-end', `match-string',
2132 and `replace-match'. */)
2133 (regexp, bound, noerror, count)
2134 Lisp_Object regexp, bound, noerror, count;
2135 {
2136 return search_command (regexp, bound, noerror, count, -1, 1, 1);
2137 }
2138
2139 DEFUN ("posix-search-forward", Fposix_search_forward, Sposix_search_forward, 1, 4,
2140 "sPosix search: ",
2141 doc: /* Search forward from point for regular expression REGEXP.
2142 Find the longest match in accord with Posix regular expression rules.
2143 Set point to the end of the occurrence found, and return point.
2144 An optional second argument bounds the search; it is a buffer position.
2145 The match found must not extend after that position.
2146 Optional third argument, if t, means if fail just return nil (no error).
2147 If not nil and not t, move to limit of search and return nil.
2148 Optional fourth argument is repeat count--search for successive occurrences.
2149 See also the functions `match-beginning', `match-end', `match-string',
2150 and `replace-match'. */)
2151 (regexp, bound, noerror, count)
2152 Lisp_Object regexp, bound, noerror, count;
2153 {
2154 return search_command (regexp, bound, noerror, count, 1, 1, 1);
2155 }
2156 \f
2157 DEFUN ("replace-match", Freplace_match, Sreplace_match, 1, 5, 0,
2158 doc: /* Replace text matched by last search with NEWTEXT.
2159 Leave point at the end of the replacement text.
2160
2161 If second arg FIXEDCASE is non-nil, do not alter case of replacement text.
2162 Otherwise maybe capitalize the whole text, or maybe just word initials,
2163 based on the replaced text.
2164 If the replaced text has only capital letters
2165 and has at least one multiletter word, convert NEWTEXT to all caps.
2166 Otherwise if all words are capitalized in the replaced text,
2167 capitalize each word in NEWTEXT.
2168
2169 If third arg LITERAL is non-nil, insert NEWTEXT literally.
2170 Otherwise treat `\\' as special:
2171 `\\&' in NEWTEXT means substitute original matched text.
2172 `\\N' means substitute what matched the Nth `\\(...\\)'.
2173 If Nth parens didn't match, substitute nothing.
2174 `\\\\' means insert one `\\'.
2175 Case conversion does not apply to these substitutions.
2176
2177 FIXEDCASE and LITERAL are optional arguments.
2178
2179 The optional fourth argument STRING can be a string to modify.
2180 This is meaningful when the previous match was done against STRING,
2181 using `string-match'. When used this way, `replace-match'
2182 creates and returns a new string made by copying STRING and replacing
2183 the part of STRING that was matched.
2184
2185 The optional fifth argument SUBEXP specifies a subexpression;
2186 it says to replace just that subexpression with NEWTEXT,
2187 rather than replacing the entire matched text.
2188 This is, in a vague sense, the inverse of using `\\N' in NEWTEXT;
2189 `\\N' copies subexp N into NEWTEXT, but using N as SUBEXP puts
2190 NEWTEXT in place of subexp N.
2191 This is useful only after a regular expression search or match,
2192 since only regular expressions have distinguished subexpressions. */)
2193 (newtext, fixedcase, literal, string, subexp)
2194 Lisp_Object newtext, fixedcase, literal, string, subexp;
2195 {
2196 enum { nochange, all_caps, cap_initial } case_action;
2197 register int pos, pos_byte;
2198 int some_multiletter_word;
2199 int some_lowercase;
2200 int some_uppercase;
2201 int some_nonuppercase_initial;
2202 register int c, prevc;
2203 int sub;
2204 int opoint, newpoint;
2205
2206 CHECK_STRING (newtext);
2207
2208 if (! NILP (string))
2209 CHECK_STRING (string);
2210
2211 case_action = nochange; /* We tried an initialization */
2212 /* but some C compilers blew it */
2213
2214 if (search_regs.num_regs <= 0)
2215 error ("replace-match called before any match found");
2216
2217 if (NILP (subexp))
2218 sub = 0;
2219 else
2220 {
2221 CHECK_NUMBER (subexp);
2222 sub = XINT (subexp);
2223 if (sub < 0 || sub >= search_regs.num_regs)
2224 args_out_of_range (subexp, make_number (search_regs.num_regs));
2225 }
2226
2227 if (NILP (string))
2228 {
2229 if (search_regs.start[sub] < BEGV
2230 || search_regs.start[sub] > search_regs.end[sub]
2231 || search_regs.end[sub] > ZV)
2232 args_out_of_range (make_number (search_regs.start[sub]),
2233 make_number (search_regs.end[sub]));
2234 }
2235 else
2236 {
2237 if (search_regs.start[sub] < 0
2238 || search_regs.start[sub] > search_regs.end[sub]
2239 || search_regs.end[sub] > SCHARS (string))
2240 args_out_of_range (make_number (search_regs.start[sub]),
2241 make_number (search_regs.end[sub]));
2242 }
2243
2244 if (NILP (fixedcase))
2245 {
2246 /* Decide how to casify by examining the matched text. */
2247 int last;
2248
2249 pos = search_regs.start[sub];
2250 last = search_regs.end[sub];
2251
2252 if (NILP (string))
2253 pos_byte = CHAR_TO_BYTE (pos);
2254 else
2255 pos_byte = string_char_to_byte (string, pos);
2256
2257 prevc = '\n';
2258 case_action = all_caps;
2259
2260 /* some_multiletter_word is set nonzero if any original word
2261 is more than one letter long. */
2262 some_multiletter_word = 0;
2263 some_lowercase = 0;
2264 some_nonuppercase_initial = 0;
2265 some_uppercase = 0;
2266
2267 while (pos < last)
2268 {
2269 if (NILP (string))
2270 {
2271 c = FETCH_CHAR_AS_MULTIBYTE (pos_byte);
2272 INC_BOTH (pos, pos_byte);
2273 }
2274 else
2275 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c, string, pos, pos_byte);
2276
2277 if (LOWERCASEP (c))
2278 {
2279 /* Cannot be all caps if any original char is lower case */
2280
2281 some_lowercase = 1;
2282 if (SYNTAX (prevc) != Sword)
2283 some_nonuppercase_initial = 1;
2284 else
2285 some_multiletter_word = 1;
2286 }
2287 else if (!NOCASEP (c))
2288 {
2289 some_uppercase = 1;
2290 if (SYNTAX (prevc) != Sword)
2291 ;
2292 else
2293 some_multiletter_word = 1;
2294 }
2295 else
2296 {
2297 /* If the initial is a caseless word constituent,
2298 treat that like a lowercase initial. */
2299 if (SYNTAX (prevc) != Sword)
2300 some_nonuppercase_initial = 1;
2301 }
2302
2303 prevc = c;
2304 }
2305
2306 /* Convert to all caps if the old text is all caps
2307 and has at least one multiletter word. */
2308 if (! some_lowercase && some_multiletter_word)
2309 case_action = all_caps;
2310 /* Capitalize each word, if the old text has all capitalized words. */
2311 else if (!some_nonuppercase_initial && some_multiletter_word)
2312 case_action = cap_initial;
2313 else if (!some_nonuppercase_initial && some_uppercase)
2314 /* Should x -> yz, operating on X, give Yz or YZ?
2315 We'll assume the latter. */
2316 case_action = all_caps;
2317 else
2318 case_action = nochange;
2319 }
2320
2321 /* Do replacement in a string. */
2322 if (!NILP (string))
2323 {
2324 Lisp_Object before, after;
2325
2326 before = Fsubstring (string, make_number (0),
2327 make_number (search_regs.start[sub]));
2328 after = Fsubstring (string, make_number (search_regs.end[sub]), Qnil);
2329
2330 /* Substitute parts of the match into NEWTEXT
2331 if desired. */
2332 if (NILP (literal))
2333 {
2334 int lastpos = 0;
2335 int lastpos_byte = 0;
2336 /* We build up the substituted string in ACCUM. */
2337 Lisp_Object accum;
2338 Lisp_Object middle;
2339 int length = SBYTES (newtext);
2340
2341 accum = Qnil;
2342
2343 for (pos_byte = 0, pos = 0; pos_byte < length;)
2344 {
2345 int substart = -1;
2346 int subend = 0;
2347 int delbackslash = 0;
2348
2349 FETCH_STRING_CHAR_ADVANCE (c, newtext, pos, pos_byte);
2350
2351 if (c == '\\')
2352 {
2353 FETCH_STRING_CHAR_ADVANCE (c, newtext, pos, pos_byte);
2354
2355 if (c == '&')
2356 {
2357 substart = search_regs.start[sub];
2358 subend = search_regs.end[sub];
2359 }
2360 else if (c >= '1' && c <= '9')
2361 {
2362 if (search_regs.start[c - '0'] >= 0
2363 && c <= search_regs.num_regs + '0')
2364 {
2365 substart = search_regs.start[c - '0'];
2366 subend = search_regs.end[c - '0'];
2367 }
2368 else
2369 {
2370 /* If that subexp did not match,
2371 replace \\N with nothing. */
2372 substart = 0;
2373 subend = 0;
2374 }
2375 }
2376 else if (c == '\\')
2377 delbackslash = 1;
2378 else
2379 error ("Invalid use of `\\' in replacement text");
2380 }
2381 if (substart >= 0)
2382 {
2383 if (pos - 2 != lastpos)
2384 middle = substring_both (newtext, lastpos,
2385 lastpos_byte,
2386 pos - 2, pos_byte - 2);
2387 else
2388 middle = Qnil;
2389 accum = concat3 (accum, middle,
2390 Fsubstring (string,
2391 make_number (substart),
2392 make_number (subend)));
2393 lastpos = pos;
2394 lastpos_byte = pos_byte;
2395 }
2396 else if (delbackslash)
2397 {
2398 middle = substring_both (newtext, lastpos,
2399 lastpos_byte,
2400 pos - 1, pos_byte - 1);
2401
2402 accum = concat2 (accum, middle);
2403 lastpos = pos;
2404 lastpos_byte = pos_byte;
2405 }
2406 }
2407
2408 if (pos != lastpos)
2409 middle = substring_both (newtext, lastpos,
2410 lastpos_byte,
2411 pos, pos_byte);
2412 else
2413 middle = Qnil;
2414
2415 newtext = concat2 (accum, middle);
2416 }
2417
2418 /* Do case substitution in NEWTEXT if desired. */
2419 if (case_action == all_caps)
2420 newtext = Fupcase (newtext);
2421 else if (case_action == cap_initial)
2422 newtext = Fupcase_initials (newtext);
2423
2424 return concat3 (before, newtext, after);
2425 }
2426
2427 /* Record point, then move (quietly) to the start of the match. */
2428 if (PT >= search_regs.end[sub])
2429 opoint = PT - ZV;
2430 else if (PT > search_regs.start[sub])
2431 opoint = search_regs.end[sub] - ZV;
2432 else
2433 opoint = PT;
2434
2435 /* If we want non-literal replacement,
2436 perform substitution on the replacement string. */
2437 if (NILP (literal))
2438 {
2439 int length = SBYTES (newtext);
2440 unsigned char *substed;
2441 int substed_alloc_size, substed_len;
2442 int buf_multibyte = !NILP (current_buffer->enable_multibyte_characters);
2443 int str_multibyte = STRING_MULTIBYTE (newtext);
2444 Lisp_Object rev_tbl;
2445 int really_changed = 0;
2446
2447 rev_tbl = Qnil;
2448
2449 substed_alloc_size = length * 2 + 100;
2450 substed = (unsigned char *) xmalloc (substed_alloc_size + 1);
2451 substed_len = 0;
2452
2453 /* Go thru NEWTEXT, producing the actual text to insert in
2454 SUBSTED while adjusting multibyteness to that of the current
2455 buffer. */
2456
2457 for (pos_byte = 0, pos = 0; pos_byte < length;)
2458 {
2459 unsigned char str[MAX_MULTIBYTE_LENGTH];
2460 unsigned char *add_stuff = NULL;
2461 int add_len = 0;
2462 int idx = -1;
2463
2464 if (str_multibyte)
2465 {
2466 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, newtext, pos, pos_byte);
2467 if (!buf_multibyte)
2468 c = multibyte_char_to_unibyte (c, rev_tbl);
2469 }
2470 else
2471 {
2472 /* Note that we don't have to increment POS. */
2473 c = SREF (newtext, pos_byte++);
2474 if (buf_multibyte)
2475 c = unibyte_char_to_multibyte (c);
2476 }
2477
2478 /* Either set ADD_STUFF and ADD_LEN to the text to put in SUBSTED,
2479 or set IDX to a match index, which means put that part
2480 of the buffer text into SUBSTED. */
2481
2482 if (c == '\\')
2483 {
2484 really_changed = 1;
2485
2486 if (str_multibyte)
2487 {
2488 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, newtext,
2489 pos, pos_byte);
2490 if (!buf_multibyte && !ASCII_CHAR_P (c))
2491 c = multibyte_char_to_unibyte (c, rev_tbl);
2492 }
2493 else
2494 {
2495 c = SREF (newtext, pos_byte++);
2496 if (buf_multibyte)
2497 c = unibyte_char_to_multibyte (c);
2498 }
2499
2500 if (c == '&')
2501 idx = sub;
2502 else if (c >= '1' && c <= '9' && c <= search_regs.num_regs + '0')
2503 {
2504 if (search_regs.start[c - '0'] >= 1)
2505 idx = c - '0';
2506 }
2507 else if (c == '\\')
2508 add_len = 1, add_stuff = "\\";
2509 else
2510 {
2511 xfree (substed);
2512 error ("Invalid use of `\\' in replacement text");
2513 }
2514 }
2515 else
2516 {
2517 add_len = CHAR_STRING (c, str);
2518 add_stuff = str;
2519 }
2520
2521 /* If we want to copy part of a previous match,
2522 set up ADD_STUFF and ADD_LEN to point to it. */
2523 if (idx >= 0)
2524 {
2525 int begbyte = CHAR_TO_BYTE (search_regs.start[idx]);
2526 add_len = CHAR_TO_BYTE (search_regs.end[idx]) - begbyte;
2527 if (search_regs.start[idx] < GPT && GPT < search_regs.end[idx])
2528 move_gap (search_regs.start[idx]);
2529 add_stuff = BYTE_POS_ADDR (begbyte);
2530 }
2531
2532 /* Now the stuff we want to add to SUBSTED
2533 is invariably ADD_LEN bytes starting at ADD_STUFF. */
2534
2535 /* Make sure SUBSTED is big enough. */
2536 if (substed_len + add_len >= substed_alloc_size)
2537 {
2538 substed_alloc_size = substed_len + add_len + 500;
2539 substed = (unsigned char *) xrealloc (substed,
2540 substed_alloc_size + 1);
2541 }
2542
2543 /* Now add to the end of SUBSTED. */
2544 if (add_stuff)
2545 {
2546 bcopy (add_stuff, substed + substed_len, add_len);
2547 substed_len += add_len;
2548 }
2549 }
2550
2551 if (really_changed)
2552 {
2553 if (buf_multibyte)
2554 {
2555 int nchars = multibyte_chars_in_text (substed, substed_len);
2556
2557 newtext = make_multibyte_string (substed, nchars, substed_len);
2558 }
2559 else
2560 newtext = make_unibyte_string (substed, substed_len);
2561 }
2562 xfree (substed);
2563 }
2564
2565 /* Replace the old text with the new in the cleanest possible way. */
2566 replace_range (search_regs.start[sub], search_regs.end[sub],
2567 newtext, 1, 0, 1);
2568 newpoint = search_regs.start[sub] + SCHARS (newtext);
2569
2570 if (case_action == all_caps)
2571 Fupcase_region (make_number (search_regs.start[sub]),
2572 make_number (newpoint));
2573 else if (case_action == cap_initial)
2574 Fupcase_initials_region (make_number (search_regs.start[sub]),
2575 make_number (newpoint));
2576
2577 /* Adjust search data for this change. */
2578 {
2579 int oldend = search_regs.end[sub];
2580 int oldstart = search_regs.start[sub];
2581 int change = newpoint - search_regs.end[sub];
2582 int i;
2583
2584 for (i = 0; i < search_regs.num_regs; i++)
2585 {
2586 if (search_regs.start[i] >= oldend)
2587 search_regs.start[i] += change;
2588 else if (search_regs.start[i] > oldstart)
2589 search_regs.start[i] = oldstart;
2590 if (search_regs.end[i] >= oldend)
2591 search_regs.end[i] += change;
2592 else if (search_regs.end[i] > oldstart)
2593 search_regs.end[i] = oldstart;
2594 }
2595 }
2596
2597 /* Put point back where it was in the text. */
2598 if (opoint <= 0)
2599 TEMP_SET_PT (opoint + ZV);
2600 else
2601 TEMP_SET_PT (opoint);
2602
2603 /* Now move point "officially" to the start of the inserted replacement. */
2604 move_if_not_intangible (newpoint);
2605
2606 return Qnil;
2607 }
2608 \f
2609 static Lisp_Object
2610 match_limit (num, beginningp)
2611 Lisp_Object num;
2612 int beginningp;
2613 {
2614 register int n;
2615
2616 CHECK_NUMBER (num);
2617 n = XINT (num);
2618 if (n < 0)
2619 args_out_of_range (num, make_number (0));
2620 if (search_regs.num_regs <= 0)
2621 error ("No match data, because no search succeeded");
2622 if (n >= search_regs.num_regs
2623 || search_regs.start[n] < 0)
2624 return Qnil;
2625 return (make_number ((beginningp) ? search_regs.start[n]
2626 : search_regs.end[n]));
2627 }
2628
2629 DEFUN ("match-beginning", Fmatch_beginning, Smatch_beginning, 1, 1, 0,
2630 doc: /* Return position of start of text matched by last search.
2631 SUBEXP, a number, specifies which parenthesized expression in the last
2632 regexp.
2633 Value is nil if SUBEXPth pair didn't match, or there were less than
2634 SUBEXP pairs.
2635 Zero means the entire text matched by the whole regexp or whole string. */)
2636 (subexp)
2637 Lisp_Object subexp;
2638 {
2639 return match_limit (subexp, 1);
2640 }
2641
2642 DEFUN ("match-end", Fmatch_end, Smatch_end, 1, 1, 0,
2643 doc: /* Return position of end of text matched by last search.
2644 SUBEXP, a number, specifies which parenthesized expression in the last
2645 regexp.
2646 Value is nil if SUBEXPth pair didn't match, or there were less than
2647 SUBEXP pairs.
2648 Zero means the entire text matched by the whole regexp or whole string. */)
2649 (subexp)
2650 Lisp_Object subexp;
2651 {
2652 return match_limit (subexp, 0);
2653 }
2654
2655 DEFUN ("match-data", Fmatch_data, Smatch_data, 0, 2, 0,
2656 doc: /* Return a list containing all info on what the last search matched.
2657 Element 2N is `(match-beginning N)'; element 2N + 1 is `(match-end N)'.
2658 All the elements are markers or nil (nil if the Nth pair didn't match)
2659 if the last match was on a buffer; integers or nil if a string was matched.
2660 Use `store-match-data' to reinstate the data in this list.
2661
2662 If INTEGERS (the optional first argument) is non-nil, always use
2663 integers \(rather than markers) to represent buffer positions. In
2664 this case, and if the last match was in a buffer, the buffer will get
2665 stored as one additional element at the end of the list.
2666
2667 If REUSE is a list, reuse it as part of the value. If REUSE is long enough
2668 to hold all the values, and if INTEGERS is non-nil, no consing is done.
2669
2670 Return value is undefined if the last search failed. */)
2671 (integers, reuse)
2672 Lisp_Object integers, reuse;
2673 {
2674 Lisp_Object tail, prev;
2675 Lisp_Object *data;
2676 int i, len;
2677
2678 if (NILP (last_thing_searched))
2679 return Qnil;
2680
2681 prev = Qnil;
2682
2683 data = (Lisp_Object *) alloca ((2 * search_regs.num_regs + 1)
2684 * sizeof (Lisp_Object));
2685
2686 len = 0;
2687 for (i = 0; i < search_regs.num_regs; i++)
2688 {
2689 int start = search_regs.start[i];
2690 if (start >= 0)
2691 {
2692 if (EQ (last_thing_searched, Qt)
2693 || ! NILP (integers))
2694 {
2695 XSETFASTINT (data[2 * i], start);
2696 XSETFASTINT (data[2 * i + 1], search_regs.end[i]);
2697 }
2698 else if (BUFFERP (last_thing_searched))
2699 {
2700 data[2 * i] = Fmake_marker ();
2701 Fset_marker (data[2 * i],
2702 make_number (start),
2703 last_thing_searched);
2704 data[2 * i + 1] = Fmake_marker ();
2705 Fset_marker (data[2 * i + 1],
2706 make_number (search_regs.end[i]),
2707 last_thing_searched);
2708 }
2709 else
2710 /* last_thing_searched must always be Qt, a buffer, or Qnil. */
2711 abort ();
2712
2713 len = 2*(i+1);
2714 }
2715 else
2716 data[2 * i] = data [2 * i + 1] = Qnil;
2717 }
2718
2719 if (BUFFERP (last_thing_searched) && !NILP (integers))
2720 {
2721 data[len] = last_thing_searched;
2722 len++;
2723 }
2724
2725 /* If REUSE is not usable, cons up the values and return them. */
2726 if (! CONSP (reuse))
2727 return Flist (len, data);
2728
2729 /* If REUSE is a list, store as many value elements as will fit
2730 into the elements of REUSE. */
2731 for (i = 0, tail = reuse; CONSP (tail);
2732 i++, tail = XCDR (tail))
2733 {
2734 if (i < len)
2735 XSETCAR (tail, data[i]);
2736 else
2737 XSETCAR (tail, Qnil);
2738 prev = tail;
2739 }
2740
2741 /* If we couldn't fit all value elements into REUSE,
2742 cons up the rest of them and add them to the end of REUSE. */
2743 if (i < len)
2744 XSETCDR (prev, Flist (len - i, data + i));
2745
2746 return reuse;
2747 }
2748
2749
2750 DEFUN ("set-match-data", Fset_match_data, Sset_match_data, 1, 1, 0,
2751 doc: /* Set internal data on last search match from elements of LIST.
2752 LIST should have been created by calling `match-data' previously. */)
2753 (list)
2754 register Lisp_Object list;
2755 {
2756 register int i;
2757 register Lisp_Object marker;
2758
2759 if (running_asynch_code)
2760 save_search_regs ();
2761
2762 if (!CONSP (list) && !NILP (list))
2763 list = wrong_type_argument (Qconsp, list);
2764
2765 /* Unless we find a marker with a buffer or an explicit buffer
2766 in LIST, assume that this match data came from a string. */
2767 last_thing_searched = Qt;
2768
2769 /* Allocate registers if they don't already exist. */
2770 {
2771 int length = XFASTINT (Flength (list)) / 2;
2772
2773 if (length > search_regs.num_regs)
2774 {
2775 if (search_regs.num_regs == 0)
2776 {
2777 search_regs.start
2778 = (regoff_t *) xmalloc (length * sizeof (regoff_t));
2779 search_regs.end
2780 = (regoff_t *) xmalloc (length * sizeof (regoff_t));
2781 }
2782 else
2783 {
2784 search_regs.start
2785 = (regoff_t *) xrealloc (search_regs.start,
2786 length * sizeof (regoff_t));
2787 search_regs.end
2788 = (regoff_t *) xrealloc (search_regs.end,
2789 length * sizeof (regoff_t));
2790 }
2791
2792 for (i = search_regs.num_regs; i < length; i++)
2793 search_regs.start[i] = -1;
2794
2795 search_regs.num_regs = length;
2796 }
2797
2798 for (i = 0;; i++)
2799 {
2800 marker = Fcar (list);
2801 if (BUFFERP (marker))
2802 {
2803 last_thing_searched = marker;
2804 break;
2805 }
2806 if (i >= length)
2807 break;
2808 if (NILP (marker))
2809 {
2810 search_regs.start[i] = -1;
2811 list = Fcdr (list);
2812 }
2813 else
2814 {
2815 int from;
2816
2817 if (MARKERP (marker))
2818 {
2819 if (XMARKER (marker)->buffer == 0)
2820 XSETFASTINT (marker, 0);
2821 else
2822 XSETBUFFER (last_thing_searched, XMARKER (marker)->buffer);
2823 }
2824
2825 CHECK_NUMBER_COERCE_MARKER (marker);
2826 from = XINT (marker);
2827 list = Fcdr (list);
2828
2829 marker = Fcar (list);
2830 if (MARKERP (marker) && XMARKER (marker)->buffer == 0)
2831 XSETFASTINT (marker, 0);
2832
2833 CHECK_NUMBER_COERCE_MARKER (marker);
2834 search_regs.start[i] = from;
2835 search_regs.end[i] = XINT (marker);
2836 }
2837 list = Fcdr (list);
2838 }
2839
2840 for (; i < search_regs.num_regs; i++)
2841 search_regs.start[i] = -1;
2842 }
2843
2844 return Qnil;
2845 }
2846
2847 /* If non-zero the match data have been saved in saved_search_regs
2848 during the execution of a sentinel or filter. */
2849 static int search_regs_saved;
2850 static struct re_registers saved_search_regs;
2851 static Lisp_Object saved_last_thing_searched;
2852
2853 /* Called from Flooking_at, Fstring_match, search_buffer, Fstore_match_data
2854 if asynchronous code (filter or sentinel) is running. */
2855 static void
2856 save_search_regs ()
2857 {
2858 if (!search_regs_saved)
2859 {
2860 saved_search_regs.num_regs = search_regs.num_regs;
2861 saved_search_regs.start = search_regs.start;
2862 saved_search_regs.end = search_regs.end;
2863 saved_last_thing_searched = last_thing_searched;
2864 last_thing_searched = Qnil;
2865 search_regs.num_regs = 0;
2866 search_regs.start = 0;
2867 search_regs.end = 0;
2868
2869 search_regs_saved = 1;
2870 }
2871 }
2872
2873 /* Called upon exit from filters and sentinels. */
2874 void
2875 restore_match_data ()
2876 {
2877 if (search_regs_saved)
2878 {
2879 if (search_regs.num_regs > 0)
2880 {
2881 xfree (search_regs.start);
2882 xfree (search_regs.end);
2883 }
2884 search_regs.num_regs = saved_search_regs.num_regs;
2885 search_regs.start = saved_search_regs.start;
2886 search_regs.end = saved_search_regs.end;
2887 last_thing_searched = saved_last_thing_searched;
2888 saved_last_thing_searched = Qnil;
2889 search_regs_saved = 0;
2890 }
2891 }
2892
2893 /* Quote a string to inactivate reg-expr chars */
2894
2895 DEFUN ("regexp-quote", Fregexp_quote, Sregexp_quote, 1, 1, 0,
2896 doc: /* Return a regexp string which matches exactly STRING and nothing else. */)
2897 (string)
2898 Lisp_Object string;
2899 {
2900 register unsigned char *in, *out, *end;
2901 register unsigned char *temp;
2902 int backslashes_added = 0;
2903
2904 CHECK_STRING (string);
2905
2906 temp = (unsigned char *) alloca (SBYTES (string) * 2);
2907
2908 /* Now copy the data into the new string, inserting escapes. */
2909
2910 in = SDATA (string);
2911 end = in + SBYTES (string);
2912 out = temp;
2913
2914 for (; in != end; in++)
2915 {
2916 if (*in == '[' || *in == ']'
2917 || *in == '*' || *in == '.' || *in == '\\'
2918 || *in == '?' || *in == '+'
2919 || *in == '^' || *in == '$')
2920 *out++ = '\\', backslashes_added++;
2921 *out++ = *in;
2922 }
2923
2924 return make_specified_string (temp,
2925 SCHARS (string) + backslashes_added,
2926 out - temp,
2927 STRING_MULTIBYTE (string));
2928 }
2929 \f
2930 void
2931 syms_of_search ()
2932 {
2933 register int i;
2934
2935 for (i = 0; i < REGEXP_CACHE_SIZE; ++i)
2936 {
2937 searchbufs[i].buf.allocated = 100;
2938 searchbufs[i].buf.buffer = (unsigned char *) xmalloc (100);
2939 searchbufs[i].buf.fastmap = searchbufs[i].fastmap;
2940 searchbufs[i].regexp = Qnil;
2941 searchbufs[i].whitespace_regexp = Qnil;
2942 staticpro (&searchbufs[i].regexp);
2943 searchbufs[i].next = (i == REGEXP_CACHE_SIZE-1 ? 0 : &searchbufs[i+1]);
2944 }
2945 searchbuf_head = &searchbufs[0];
2946
2947 Qsearch_failed = intern ("search-failed");
2948 staticpro (&Qsearch_failed);
2949 Qinvalid_regexp = intern ("invalid-regexp");
2950 staticpro (&Qinvalid_regexp);
2951
2952 Fput (Qsearch_failed, Qerror_conditions,
2953 Fcons (Qsearch_failed, Fcons (Qerror, Qnil)));
2954 Fput (Qsearch_failed, Qerror_message,
2955 build_string ("Search failed"));
2956
2957 Fput (Qinvalid_regexp, Qerror_conditions,
2958 Fcons (Qinvalid_regexp, Fcons (Qerror, Qnil)));
2959 Fput (Qinvalid_regexp, Qerror_message,
2960 build_string ("Invalid regexp"));
2961
2962 last_thing_searched = Qnil;
2963 staticpro (&last_thing_searched);
2964
2965 saved_last_thing_searched = Qnil;
2966 staticpro (&saved_last_thing_searched);
2967
2968 DEFVAR_LISP ("search-spaces-regexp", &Vsearch_spaces_regexp,
2969 doc: /* Regexp to substitute for bunches of spaces in regexp search.
2970 Some commands use this for user-specified regexps.
2971 Spaces that occur inside character classes or repetition operators
2972 or other such regexp constructs are not replaced with this.
2973 A value of nil (which is the normal value) means treat spaces literally. */);
2974 Vsearch_spaces_regexp = Qnil;
2975
2976 defsubr (&Slooking_at);
2977 defsubr (&Sposix_looking_at);
2978 defsubr (&Sstring_match);
2979 defsubr (&Sposix_string_match);
2980 defsubr (&Ssearch_forward);
2981 defsubr (&Ssearch_backward);
2982 defsubr (&Sword_search_forward);
2983 defsubr (&Sword_search_backward);
2984 defsubr (&Sre_search_forward);
2985 defsubr (&Sre_search_backward);
2986 defsubr (&Sposix_search_forward);
2987 defsubr (&Sposix_search_backward);
2988 defsubr (&Sreplace_match);
2989 defsubr (&Smatch_beginning);
2990 defsubr (&Smatch_end);
2991 defsubr (&Smatch_data);
2992 defsubr (&Sset_match_data);
2993 defsubr (&Sregexp_quote);
2994 }
2995
2996 /* arch-tag: a6059d79-0552-4f14-a2cb-d379a4e3c78f
2997 (do not change this comment) */