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