]> code.delx.au - gnu-emacs/blob - src/search.c
Fix previous change.
[gnu-emacs] / src / search.c
1 /* String search routines for GNU Emacs.
2 Copyright (C) 1985, 1986, 1987, 1993, 1994 Free Software Foundation, Inc.
3
4 This file is part of GNU Emacs.
5
6 GNU Emacs is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
10
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs; see the file COPYING. If not, write to
18 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
20
21
22 #include <config.h>
23 #include "lisp.h"
24 #include "syntax.h"
25 #include "category.h"
26 #include "buffer.h"
27 #include "charset.h"
28 #include "region-cache.h"
29 #include "commands.h"
30 #include "blockinput.h"
31
32 #include <sys/types.h>
33 #include "regex.h"
34
35 #define REGEXP_CACHE_SIZE 20
36
37 /* If the regexp is non-nil, then the buffer contains the compiled form
38 of that regexp, suitable for searching. */
39 struct regexp_cache
40 {
41 struct regexp_cache *next;
42 Lisp_Object regexp;
43 struct re_pattern_buffer buf;
44 char fastmap[0400];
45 /* Nonzero means regexp was compiled to do full POSIX backtracking. */
46 char posix;
47 };
48
49 /* The instances of that struct. */
50 struct regexp_cache searchbufs[REGEXP_CACHE_SIZE];
51
52 /* The head of the linked list; points to the most recently used buffer. */
53 struct regexp_cache *searchbuf_head;
54
55
56 /* Every call to re_match, etc., must pass &search_regs as the regs
57 argument unless you can show it is unnecessary (i.e., if re_match
58 is certainly going to be called again before region-around-match
59 can be called).
60
61 Since the registers are now dynamically allocated, we need to make
62 sure not to refer to the Nth register before checking that it has
63 been allocated by checking search_regs.num_regs.
64
65 The regex code keeps track of whether it has allocated the search
66 buffer using bits in the re_pattern_buffer. This means that whenever
67 you compile a new pattern, it completely forgets whether it has
68 allocated any registers, and will allocate new registers the next
69 time you call a searching or matching function. Therefore, we need
70 to call re_set_registers after compiling a new pattern or after
71 setting the match registers, so that the regex functions will be
72 able to free or re-allocate it properly. */
73 static struct re_registers search_regs;
74
75 /* The buffer in which the last search was performed, or
76 Qt if the last search was done in a string;
77 Qnil if no searching has been done yet. */
78 static Lisp_Object last_thing_searched;
79
80 /* error condition signaled when regexp compile_pattern fails */
81
82 Lisp_Object Qinvalid_regexp;
83
84 static void set_search_regs ();
85 static void save_search_regs ();
86
87 static int search_buffer ();
88
89 static void
90 matcher_overflow ()
91 {
92 error ("Stack overflow in regexp matcher");
93 }
94
95 #ifdef __STDC__
96 #define CONST const
97 #else
98 #define CONST
99 #endif
100
101 /* Compile a regexp and signal a Lisp error if anything goes wrong.
102 PATTERN is the pattern to compile.
103 CP is the place to put the result.
104 TRANSLATE is a translation table for ignoring case, or NULL for none.
105 REGP is the structure that says where to store the "register"
106 values that will result from matching this pattern.
107 If it is 0, we should compile the pattern not to record any
108 subexpression bounds.
109 POSIX is nonzero if we want full backtracking (POSIX style)
110 for this pattern. 0 means backtrack only enough to get a valid match.
111 MULTIBYTE is nonzero if we want to handle multibyte characters in
112 PATTERN. 0 means all multibyte characters are recognized just as
113 sequences of binary data. */
114
115 static void
116 compile_pattern_1 (cp, pattern, translate, regp, posix, multibyte)
117 struct regexp_cache *cp;
118 Lisp_Object pattern;
119 Lisp_Object *translate;
120 struct re_registers *regp;
121 int posix;
122 int multibyte;
123 {
124 CONST char *val;
125 reg_syntax_t old;
126
127 cp->regexp = Qnil;
128 cp->buf.translate = translate;
129 cp->posix = posix;
130 cp->buf.multibyte = multibyte;
131 BLOCK_INPUT;
132 old = re_set_syntax (RE_SYNTAX_EMACS
133 | (posix ? 0 : RE_NO_POSIX_BACKTRACKING));
134 val = (CONST char *) re_compile_pattern ((char *) XSTRING (pattern)->data,
135 XSTRING (pattern)->size, &cp->buf);
136 re_set_syntax (old);
137 UNBLOCK_INPUT;
138 if (val)
139 Fsignal (Qinvalid_regexp, Fcons (build_string (val), Qnil));
140
141 cp->regexp = Fcopy_sequence (pattern);
142 }
143
144 /* Compile a regexp if necessary, but first check to see if there's one in
145 the cache.
146 PATTERN is the pattern to compile.
147 TRANSLATE is a translation table for ignoring case, or NULL for none.
148 REGP is the structure that says where to store the "register"
149 values that will result from matching this pattern.
150 If it is 0, we should compile the pattern not to record any
151 subexpression bounds.
152 POSIX is nonzero if we want full backtracking (POSIX style)
153 for this pattern. 0 means backtrack only enough to get a valid match. */
154
155 struct re_pattern_buffer *
156 compile_pattern (pattern, regp, translate, posix)
157 Lisp_Object pattern;
158 struct re_registers *regp;
159 Lisp_Object *translate;
160 int posix;
161 {
162 struct regexp_cache *cp, **cpp;
163 /* Should we check it here, or add an argument `multibyte' to this
164 function? */
165 int multibyte = !NILP (current_buffer->enable_multibyte_characters);
166
167 for (cpp = &searchbuf_head; ; cpp = &cp->next)
168 {
169 cp = *cpp;
170 if (XSTRING (cp->regexp)->size == XSTRING (pattern)->size
171 && !NILP (Fstring_equal (cp->regexp, pattern))
172 && cp->buf.translate == translate
173 && cp->posix == posix
174 && cp->buf.multibyte == multibyte)
175 break;
176
177 /* If we're at the end of the cache, compile into the last cell. */
178 if (cp->next == 0)
179 {
180 compile_pattern_1 (cp, pattern, translate, regp, posix, multibyte);
181 break;
182 }
183 }
184
185 /* When we get here, cp (aka *cpp) contains the compiled pattern,
186 either because we found it in the cache or because we just compiled it.
187 Move it to the front of the queue to mark it as most recently used. */
188 *cpp = cp->next;
189 cp->next = searchbuf_head;
190 searchbuf_head = cp;
191
192 /* Advise the searching functions about the space we have allocated
193 for register data. */
194 if (regp)
195 re_set_registers (&cp->buf, regp, regp->num_regs, regp->start, regp->end);
196
197 return &cp->buf;
198 }
199
200 /* Error condition used for failing searches */
201 Lisp_Object Qsearch_failed;
202
203 Lisp_Object
204 signal_failure (arg)
205 Lisp_Object arg;
206 {
207 Fsignal (Qsearch_failed, Fcons (arg, Qnil));
208 return Qnil;
209 }
210 \f
211 static Lisp_Object
212 looking_at_1 (string, posix)
213 Lisp_Object string;
214 int posix;
215 {
216 Lisp_Object val;
217 unsigned char *p1, *p2;
218 int s1, s2;
219 register int i;
220 struct re_pattern_buffer *bufp;
221
222 if (running_asynch_code)
223 save_search_regs ();
224
225 CHECK_STRING (string, 0);
226 bufp = compile_pattern (string, &search_regs,
227 (!NILP (current_buffer->case_fold_search)
228 ? DOWNCASE_TABLE : 0),
229 posix);
230
231 immediate_quit = 1;
232 QUIT; /* Do a pending quit right away, to avoid paradoxical behavior */
233
234 /* Get pointers and sizes of the two strings
235 that make up the visible portion of the buffer. */
236
237 p1 = BEGV_ADDR;
238 s1 = GPT - BEGV;
239 p2 = GAP_END_ADDR;
240 s2 = ZV - GPT;
241 if (s1 < 0)
242 {
243 p2 = p1;
244 s2 = ZV - BEGV;
245 s1 = 0;
246 }
247 if (s2 < 0)
248 {
249 s1 = ZV - BEGV;
250 s2 = 0;
251 }
252
253 i = re_match_2 (bufp, (char *) p1, s1, (char *) p2, s2,
254 PT - BEGV, &search_regs,
255 ZV - BEGV);
256 if (i == -2)
257 matcher_overflow ();
258
259 val = (0 <= i ? Qt : Qnil);
260 for (i = 0; i < search_regs.num_regs; i++)
261 if (search_regs.start[i] >= 0)
262 {
263 search_regs.start[i] += BEGV;
264 search_regs.end[i] += BEGV;
265 }
266 XSETBUFFER (last_thing_searched, current_buffer);
267 immediate_quit = 0;
268 return val;
269 }
270
271 DEFUN ("looking-at", Flooking_at, Slooking_at, 1, 1, 0,
272 "Return t if text after point matches regular expression REGEXP.\n\
273 This function modifies the match data that `match-beginning',\n\
274 `match-end' and `match-data' access; save and restore the match\n\
275 data if you want to preserve them.")
276 (regexp)
277 Lisp_Object regexp;
278 {
279 return looking_at_1 (regexp, 0);
280 }
281
282 DEFUN ("posix-looking-at", Fposix_looking_at, Sposix_looking_at, 1, 1, 0,
283 "Return t if text after point matches regular expression REGEXP.\n\
284 Find the longest match, in accord with Posix regular expression rules.\n\
285 This function modifies the match data that `match-beginning',\n\
286 `match-end' and `match-data' access; save and restore the match\n\
287 data if you want to preserve them.")
288 (regexp)
289 Lisp_Object regexp;
290 {
291 return looking_at_1 (regexp, 1);
292 }
293 \f
294 static Lisp_Object
295 string_match_1 (regexp, string, start, posix)
296 Lisp_Object regexp, string, start;
297 int posix;
298 {
299 int val;
300 int s;
301 struct re_pattern_buffer *bufp;
302
303 if (running_asynch_code)
304 save_search_regs ();
305
306 CHECK_STRING (regexp, 0);
307 CHECK_STRING (string, 1);
308
309 if (NILP (start))
310 s = 0;
311 else
312 {
313 int len = XSTRING (string)->size;
314
315 CHECK_NUMBER (start, 2);
316 s = XINT (start);
317 if (s < 0 && -s <= len)
318 s = len + s;
319 else if (0 > s || s > len)
320 args_out_of_range (string, start);
321 }
322
323 bufp = compile_pattern (regexp, &search_regs,
324 (!NILP (current_buffer->case_fold_search)
325 ? DOWNCASE_TABLE : 0),
326 posix);
327 immediate_quit = 1;
328 val = re_search (bufp, (char *) XSTRING (string)->data,
329 XSTRING (string)->size, s, XSTRING (string)->size - s,
330 &search_regs);
331 immediate_quit = 0;
332 last_thing_searched = Qt;
333 if (val == -2)
334 matcher_overflow ();
335 if (val < 0) return Qnil;
336 return make_number (val);
337 }
338
339 DEFUN ("string-match", Fstring_match, Sstring_match, 2, 3, 0,
340 "Return index of start of first match for REGEXP in STRING, or nil.\n\
341 If third arg START is non-nil, start search at that index in STRING.\n\
342 For index of first char beyond the match, do (match-end 0).\n\
343 `match-end' and `match-beginning' also give indices of substrings\n\
344 matched by parenthesis constructs in the pattern.")
345 (regexp, string, start)
346 Lisp_Object regexp, string, start;
347 {
348 return string_match_1 (regexp, string, start, 0);
349 }
350
351 DEFUN ("posix-string-match", Fposix_string_match, Sposix_string_match, 2, 3, 0,
352 "Return index of start of first match for REGEXP in STRING, or nil.\n\
353 Find the longest match, in accord with Posix regular expression rules.\n\
354 If third arg START is non-nil, start search at that index in STRING.\n\
355 For index of first char beyond the match, do (match-end 0).\n\
356 `match-end' and `match-beginning' also give indices of substrings\n\
357 matched by parenthesis constructs in the pattern.")
358 (regexp, string, start)
359 Lisp_Object regexp, string, start;
360 {
361 return string_match_1 (regexp, string, start, 1);
362 }
363
364 /* Match REGEXP against STRING, searching all of STRING,
365 and return the index of the match, or negative on failure.
366 This does not clobber the match data. */
367
368 int
369 fast_string_match (regexp, string)
370 Lisp_Object regexp, string;
371 {
372 int val;
373 struct re_pattern_buffer *bufp;
374
375 bufp = compile_pattern (regexp, 0, 0, 0);
376 immediate_quit = 1;
377 val = re_search (bufp, (char *) XSTRING (string)->data,
378 XSTRING (string)->size, 0, XSTRING (string)->size,
379 0);
380 immediate_quit = 0;
381 return val;
382 }
383
384 /* Match REGEXP against STRING, searching all of STRING ignoring case,
385 and return the index of the match, or negative on failure.
386 This does not clobber the match data. */
387
388 extern Lisp_Object Vascii_downcase_table;
389
390 int
391 fast_string_match_ignore_case (regexp, string)
392 Lisp_Object regexp;
393 char *string;
394 {
395 int val;
396 struct re_pattern_buffer *bufp;
397 int len = strlen (string);
398
399 bufp = compile_pattern (regexp, 0,
400 XCHAR_TABLE (Vascii_downcase_table)->contents, 0);
401 immediate_quit = 1;
402 val = re_search (bufp, string, len, 0, len, 0);
403 immediate_quit = 0;
404 return val;
405 }
406 \f
407 /* max and min. */
408
409 static int
410 max (a, b)
411 int a, b;
412 {
413 return ((a > b) ? a : b);
414 }
415
416 static int
417 min (a, b)
418 int a, b;
419 {
420 return ((a < b) ? a : b);
421 }
422
423 \f
424 /* The newline cache: remembering which sections of text have no newlines. */
425
426 /* If the user has requested newline caching, make sure it's on.
427 Otherwise, make sure it's off.
428 This is our cheezy way of associating an action with the change of
429 state of a buffer-local variable. */
430 static void
431 newline_cache_on_off (buf)
432 struct buffer *buf;
433 {
434 if (NILP (buf->cache_long_line_scans))
435 {
436 /* It should be off. */
437 if (buf->newline_cache)
438 {
439 free_region_cache (buf->newline_cache);
440 buf->newline_cache = 0;
441 }
442 }
443 else
444 {
445 /* It should be on. */
446 if (buf->newline_cache == 0)
447 buf->newline_cache = new_region_cache ();
448 }
449 }
450
451 \f
452 /* Search for COUNT instances of the character TARGET between START and END.
453
454 If COUNT is positive, search forwards; END must be >= START.
455 If COUNT is negative, search backwards for the -COUNTth instance;
456 END must be <= START.
457 If COUNT is zero, do anything you please; run rogue, for all I care.
458
459 If END is zero, use BEGV or ZV instead, as appropriate for the
460 direction indicated by COUNT.
461
462 If we find COUNT instances, set *SHORTAGE to zero, and return the
463 position after the COUNTth match. Note that for reverse motion
464 this is not the same as the usual convention for Emacs motion commands.
465
466 If we don't find COUNT instances before reaching END, set *SHORTAGE
467 to the number of TARGETs left unfound, and return END.
468
469 If ALLOW_QUIT is non-zero, set immediate_quit. That's good to do
470 except when inside redisplay. */
471
472 scan_buffer (target, start, end, count, shortage, allow_quit)
473 register int target;
474 int start, end;
475 int count;
476 int *shortage;
477 int allow_quit;
478 {
479 struct region_cache *newline_cache;
480 int direction;
481
482 if (count > 0)
483 {
484 direction = 1;
485 if (! end) end = ZV;
486 }
487 else
488 {
489 direction = -1;
490 if (! end) end = BEGV;
491 }
492
493 newline_cache_on_off (current_buffer);
494 newline_cache = current_buffer->newline_cache;
495
496 if (shortage != 0)
497 *shortage = 0;
498
499 immediate_quit = allow_quit;
500
501 if (count > 0)
502 while (start != end)
503 {
504 /* Our innermost scanning loop is very simple; it doesn't know
505 about gaps, buffer ends, or the newline cache. ceiling is
506 the position of the last character before the next such
507 obstacle --- the last character the dumb search loop should
508 examine. */
509 register int ceiling = end - 1;
510
511 /* If we're looking for a newline, consult the newline cache
512 to see where we can avoid some scanning. */
513 if (target == '\n' && newline_cache)
514 {
515 int next_change;
516 immediate_quit = 0;
517 while (region_cache_forward
518 (current_buffer, newline_cache, start, &next_change))
519 start = next_change;
520 immediate_quit = allow_quit;
521
522 /* start should never be after end. */
523 if (start >= end)
524 start = end - 1;
525
526 /* Now the text after start is an unknown region, and
527 next_change is the position of the next known region. */
528 ceiling = min (next_change - 1, ceiling);
529 }
530
531 /* The dumb loop can only scan text stored in contiguous
532 bytes. BUFFER_CEILING_OF returns the last character
533 position that is contiguous, so the ceiling is the
534 position after that. */
535 ceiling = min (BUFFER_CEILING_OF (start), ceiling);
536
537 {
538 /* The termination address of the dumb loop. */
539 register unsigned char *ceiling_addr = POS_ADDR (ceiling) + 1;
540 register unsigned char *cursor = POS_ADDR (start);
541 unsigned char *base = cursor;
542
543 while (cursor < ceiling_addr)
544 {
545 unsigned char *scan_start = cursor;
546
547 /* The dumb loop. */
548 while (*cursor != target && ++cursor < ceiling_addr)
549 ;
550
551 /* If we're looking for newlines, cache the fact that
552 the region from start to cursor is free of them. */
553 if (target == '\n' && newline_cache)
554 know_region_cache (current_buffer, newline_cache,
555 start + scan_start - base,
556 start + cursor - base);
557
558 /* Did we find the target character? */
559 if (cursor < ceiling_addr)
560 {
561 if (--count == 0)
562 {
563 immediate_quit = 0;
564 return (start + cursor - base + 1);
565 }
566 cursor++;
567 }
568 }
569
570 start += cursor - base;
571 }
572 }
573 else
574 while (start > end)
575 {
576 /* The last character to check before the next obstacle. */
577 register int ceiling = end;
578
579 /* Consult the newline cache, if appropriate. */
580 if (target == '\n' && newline_cache)
581 {
582 int next_change;
583 immediate_quit = 0;
584 while (region_cache_backward
585 (current_buffer, newline_cache, start, &next_change))
586 start = next_change;
587 immediate_quit = allow_quit;
588
589 /* Start should never be at or before end. */
590 if (start <= end)
591 start = end + 1;
592
593 /* Now the text before start is an unknown region, and
594 next_change is the position of the next known region. */
595 ceiling = max (next_change, ceiling);
596 }
597
598 /* Stop scanning before the gap. */
599 ceiling = max (BUFFER_FLOOR_OF (start - 1), ceiling);
600
601 {
602 /* The termination address of the dumb loop. */
603 register unsigned char *ceiling_addr = POS_ADDR (ceiling);
604 register unsigned char *cursor = POS_ADDR (start - 1);
605 unsigned char *base = cursor;
606
607 while (cursor >= ceiling_addr)
608 {
609 unsigned char *scan_start = cursor;
610
611 while (*cursor != target && --cursor >= ceiling_addr)
612 ;
613
614 /* If we're looking for newlines, cache the fact that
615 the region from after the cursor to start is free of them. */
616 if (target == '\n' && newline_cache)
617 know_region_cache (current_buffer, newline_cache,
618 start + cursor - base,
619 start + scan_start - base);
620
621 /* Did we find the target character? */
622 if (cursor >= ceiling_addr)
623 {
624 if (++count >= 0)
625 {
626 immediate_quit = 0;
627 return (start + cursor - base);
628 }
629 cursor--;
630 }
631 }
632
633 start += cursor - base;
634 }
635 }
636
637 immediate_quit = 0;
638 if (shortage != 0)
639 *shortage = count * direction;
640 return start;
641 }
642
643 int
644 find_next_newline_no_quit (from, cnt)
645 register int from, cnt;
646 {
647 return scan_buffer ('\n', from, 0, cnt, (int *) 0, 0);
648 }
649
650 int
651 find_next_newline (from, cnt)
652 register int from, cnt;
653 {
654 return scan_buffer ('\n', from, 0, cnt, (int *) 0, 1);
655 }
656
657
658 /* Like find_next_newline, but returns position before the newline,
659 not after, and only search up to TO. This isn't just
660 find_next_newline (...)-1, because you might hit TO. */
661 int
662 find_before_next_newline (from, to, cnt)
663 int from, to, cnt;
664 {
665 int shortage;
666 int pos = scan_buffer ('\n', from, to, cnt, &shortage, 1);
667
668 if (shortage == 0)
669 pos--;
670
671 return pos;
672 }
673 \f
674 Lisp_Object skip_chars ();
675
676 DEFUN ("skip-chars-forward", Fskip_chars_forward, Sskip_chars_forward, 1, 2, 0,
677 "Move point forward, stopping before a char not in STRING, or at pos LIM.\n\
678 STRING is like the inside of a `[...]' in a regular expression\n\
679 except that `]' is never special and `\\' quotes `^', `-' or `\\'.\n\
680 Thus, with arg \"a-zA-Z\", this skips letters stopping before first nonletter.\n\
681 With arg \"^a-zA-Z\", skips nonletters stopping before first letter.\n\
682 Returns the distance traveled, either zero or positive.")
683 (string, lim)
684 Lisp_Object string, lim;
685 {
686 return skip_chars (1, 0, string, lim);
687 }
688
689 DEFUN ("skip-chars-backward", Fskip_chars_backward, Sskip_chars_backward, 1, 2, 0,
690 "Move point backward, stopping after a char not in STRING, or at pos LIM.\n\
691 See `skip-chars-forward' for details.\n\
692 Returns the distance traveled, either zero or negative.")
693 (string, lim)
694 Lisp_Object string, lim;
695 {
696 return skip_chars (0, 0, string, lim);
697 }
698
699 DEFUN ("skip-syntax-forward", Fskip_syntax_forward, Sskip_syntax_forward, 1, 2, 0,
700 "Move point forward across chars in specified syntax classes.\n\
701 SYNTAX is a string of syntax code characters.\n\
702 Stop before a char whose syntax is not in SYNTAX, or at position LIM.\n\
703 If SYNTAX starts with ^, skip characters whose syntax is NOT in SYNTAX.\n\
704 This function returns the distance traveled, either zero or positive.")
705 (syntax, lim)
706 Lisp_Object syntax, lim;
707 {
708 return skip_chars (1, 1, syntax, lim);
709 }
710
711 DEFUN ("skip-syntax-backward", Fskip_syntax_backward, Sskip_syntax_backward, 1, 2, 0,
712 "Move point backward across chars in specified syntax classes.\n\
713 SYNTAX is a string of syntax code characters.\n\
714 Stop on reaching a char whose syntax is not in SYNTAX, or at position LIM.\n\
715 If SYNTAX starts with ^, skip characters whose syntax is NOT in SYNTAX.\n\
716 This function returns the distance traveled, either zero or negative.")
717 (syntax, lim)
718 Lisp_Object syntax, lim;
719 {
720 return skip_chars (0, 1, syntax, lim);
721 }
722
723 Lisp_Object
724 skip_chars (forwardp, syntaxp, string, lim)
725 int forwardp, syntaxp;
726 Lisp_Object string, lim;
727 {
728 register unsigned char *p, *pend;
729 register unsigned char c;
730 register int ch;
731 unsigned char fastmap[0400];
732 /* If SYNTAXP is 0, STRING may contain multi-byte form of characters
733 of which codes don't fit in FASTMAP. In that case, we set the
734 first byte of multibyte form (i.e. base leading-code) in FASTMAP
735 and set the actual ranges of characters in CHAR_RANGES. In the
736 form "X-Y" of STRING, both X and Y must belong to the same
737 character set because a range striding across character sets is
738 meaningless. */
739 int *char_ranges
740 = (int *) alloca (XSTRING (string)->size * (sizeof (int)) * 2);
741 int n_char_ranges = 0;
742 int negate = 0;
743 register int i;
744
745 CHECK_STRING (string, 0);
746
747 if (NILP (lim))
748 XSETINT (lim, forwardp ? ZV : BEGV);
749 else
750 CHECK_NUMBER_COERCE_MARKER (lim, 1);
751
752 /* In any case, don't allow scan outside bounds of buffer. */
753 /* jla turned this off, for no known reason.
754 bfox turned the ZV part on, and rms turned the
755 BEGV part back on. */
756 if (XINT (lim) > ZV)
757 XSETFASTINT (lim, ZV);
758 if (XINT (lim) < BEGV)
759 XSETFASTINT (lim, BEGV);
760
761 p = XSTRING (string)->data;
762 pend = p + XSTRING (string)->size;
763 bzero (fastmap, sizeof fastmap);
764
765 if (p != pend && *p == '^')
766 {
767 negate = 1; p++;
768 }
769
770 /* Find the characters specified and set their elements of fastmap.
771 If syntaxp, each character counts as itself.
772 Otherwise, handle backslashes and ranges specially. */
773
774 while (p != pend)
775 {
776 c = *p;
777 ch = STRING_CHAR (p, pend - p);
778 p += BYTES_BY_CHAR_HEAD (*p);
779 if (syntaxp)
780 fastmap[syntax_spec_code[c]] = 1;
781 else
782 {
783 if (c == '\\')
784 {
785 if (p == pend) break;
786 c = *p++;
787 }
788 if (p != pend && *p == '-')
789 {
790 unsigned int ch2;
791
792 p++;
793 if (p == pend) break;
794 if (SINGLE_BYTE_CHAR_P (ch))
795 while (c <= *p)
796 {
797 fastmap[c] = 1;
798 c++;
799 }
800 else
801 {
802 fastmap[c] = 1; /* C is the base leading-code. */
803 ch2 = STRING_CHAR (p, pend - p);
804 if (ch <= ch2)
805 char_ranges[n_char_ranges++] = ch,
806 char_ranges[n_char_ranges++] = ch2;
807 }
808 p += BYTES_BY_CHAR_HEAD (*p);
809 }
810 else
811 {
812 fastmap[c] = 1;
813 if (!SINGLE_BYTE_CHAR_P (ch))
814 char_ranges[n_char_ranges++] = ch,
815 char_ranges[n_char_ranges++] = ch;
816 }
817 }
818 }
819
820 /* If ^ was the first character, complement the fastmap. In
821 addition, as all multibyte characters have possibility of
822 matching, set all entries for base leading codes, which is
823 harmless even if SYNTAXP is 1. */
824
825 if (negate)
826 for (i = 0; i < sizeof fastmap; i++)
827 {
828 if (!BASE_LEADING_CODE_P (i))
829 fastmap[i] ^= 1;
830 else
831 fastmap[i] = 1;
832 }
833
834 {
835 int start_point = PT;
836 int pos = PT;
837
838 immediate_quit = 1;
839 if (syntaxp)
840 {
841 if (forwardp)
842 {
843 while (pos < XINT (lim)
844 && fastmap[(int) SYNTAX (FETCH_CHAR (pos))])
845 INC_POS (pos);
846 }
847 else
848 {
849 while (pos > XINT (lim))
850 {
851 int savepos = pos;
852 DEC_POS (pos);
853 if (!fastmap[(int) SYNTAX (FETCH_CHAR (pos))])
854 {
855 pos = savepos;
856 break;
857 }
858 }
859 }
860 }
861 else
862 {
863 if (forwardp)
864 {
865 while (pos < XINT (lim) && fastmap[(c = FETCH_BYTE (pos))])
866 {
867 if (!BASE_LEADING_CODE_P (c))
868 pos++;
869 else if (n_char_ranges)
870 {
871 /* We much check CHAR_RANGES for a multibyte
872 character. */
873 ch = FETCH_MULTIBYTE_CHAR (pos);
874 for (i = 0; i < n_char_ranges; i += 2)
875 if ((ch >= char_ranges[i] && ch <= char_ranges[i + 1]))
876 break;
877 if (!(negate ^ (i < n_char_ranges)))
878 break;
879
880 INC_POS (pos);
881 }
882 else
883 {
884 if (!negate) break;
885 INC_POS (pos);
886 }
887 }
888 }
889 else
890 {
891 while (pos > XINT (lim))
892 {
893 int savepos = pos;
894 DEC_POS (pos);
895 if (fastmap[(c = FETCH_BYTE (pos))])
896 {
897 if (!BASE_LEADING_CODE_P (c))
898 ;
899 else if (n_char_ranges)
900 {
901 /* We much check CHAR_RANGES for a multibyte
902 character. */
903 ch = FETCH_MULTIBYTE_CHAR (pos);
904 for (i = 0; i < n_char_ranges; i += 2)
905 if (ch >= char_ranges[i] && ch <= char_ranges[i + 1])
906 break;
907 if (!(negate ^ (i < n_char_ranges)))
908 {
909 pos = savepos;
910 break;
911 }
912 }
913 else
914 if (!negate)
915 {
916 pos = savepos;
917 break;
918 }
919 }
920 else
921 {
922 pos = savepos;
923 break;
924 }
925 }
926 }
927 }
928 SET_PT (pos);
929 immediate_quit = 0;
930
931 return make_number (PT - start_point);
932 }
933 }
934 \f
935 /* Subroutines of Lisp buffer search functions. */
936
937 static Lisp_Object
938 search_command (string, bound, noerror, count, direction, RE, posix)
939 Lisp_Object string, bound, noerror, count;
940 int direction;
941 int RE;
942 int posix;
943 {
944 register int np;
945 int lim;
946 int n = direction;
947
948 if (!NILP (count))
949 {
950 CHECK_NUMBER (count, 3);
951 n *= XINT (count);
952 }
953
954 CHECK_STRING (string, 0);
955 if (NILP (bound))
956 lim = n > 0 ? ZV : BEGV;
957 else
958 {
959 CHECK_NUMBER_COERCE_MARKER (bound, 1);
960 lim = XINT (bound);
961 if (n > 0 ? lim < PT : lim > PT)
962 error ("Invalid search bound (wrong side of point)");
963 if (lim > ZV)
964 lim = ZV;
965 if (lim < BEGV)
966 lim = BEGV;
967 }
968
969 np = search_buffer (string, PT, lim, n, RE,
970 (!NILP (current_buffer->case_fold_search)
971 ? XCHAR_TABLE (current_buffer->case_canon_table)->contents
972 : 0),
973 (!NILP (current_buffer->case_fold_search)
974 ? XCHAR_TABLE (current_buffer->case_eqv_table)->contents
975 : 0),
976 posix);
977 if (np <= 0)
978 {
979 if (NILP (noerror))
980 return signal_failure (string);
981 if (!EQ (noerror, Qt))
982 {
983 if (lim < BEGV || lim > ZV)
984 abort ();
985 SET_PT (lim);
986 return Qnil;
987 #if 0 /* This would be clean, but maybe programs depend on
988 a value of nil here. */
989 np = lim;
990 #endif
991 }
992 else
993 return Qnil;
994 }
995
996 if (np < BEGV || np > ZV)
997 abort ();
998
999 SET_PT (np);
1000
1001 return make_number (np);
1002 }
1003 \f
1004 static int
1005 trivial_regexp_p (regexp)
1006 Lisp_Object regexp;
1007 {
1008 int len = XSTRING (regexp)->size;
1009 unsigned char *s = XSTRING (regexp)->data;
1010 unsigned char c;
1011 while (--len >= 0)
1012 {
1013 switch (*s++)
1014 {
1015 case '.': case '*': case '+': case '?': case '[': case '^': case '$':
1016 return 0;
1017 case '\\':
1018 if (--len < 0)
1019 return 0;
1020 switch (*s++)
1021 {
1022 case '|': case '(': case ')': case '`': case '\'': case 'b':
1023 case 'B': case '<': case '>': case 'w': case 'W': case 's':
1024 case 'S': case '=':
1025 case 'c': case 'C': /* for categoryspec and notcategoryspec */
1026 case '1': case '2': case '3': case '4': case '5':
1027 case '6': case '7': case '8': case '9':
1028 return 0;
1029 }
1030 }
1031 }
1032 return 1;
1033 }
1034
1035 /* Search for the n'th occurrence of STRING in the current buffer,
1036 starting at position POS and stopping at position LIM,
1037 treating STRING as a literal string if RE is false or as
1038 a regular expression if RE is true.
1039
1040 If N is positive, searching is forward and LIM must be greater than POS.
1041 If N is negative, searching is backward and LIM must be less than POS.
1042
1043 Returns -x if only N-x occurrences found (x > 0),
1044 or else the position at the beginning of the Nth occurrence
1045 (if searching backward) or the end (if searching forward).
1046
1047 POSIX is nonzero if we want full backtracking (POSIX style)
1048 for this pattern. 0 means backtrack only enough to get a valid match. */
1049
1050 static int
1051 search_buffer (string, pos, lim, n, RE, trt, inverse_trt, posix)
1052 Lisp_Object string;
1053 int pos;
1054 int lim;
1055 int n;
1056 int RE;
1057 Lisp_Object *trt;
1058 Lisp_Object *inverse_trt;
1059 int posix;
1060 {
1061 int len = XSTRING (string)->size;
1062 unsigned char *base_pat = XSTRING (string)->data;
1063 register int *BM_tab;
1064 int *BM_tab_base;
1065 register int direction = ((n > 0) ? 1 : -1);
1066 register int dirlen;
1067 int infinity, limit, k, stride_for_teases;
1068 register unsigned char *pat, *cursor, *p_limit;
1069 register int i, j;
1070 unsigned char *p1, *p2;
1071 int s1, s2;
1072
1073 if (running_asynch_code)
1074 save_search_regs ();
1075
1076 /* Null string is found at starting position. */
1077 if (len == 0)
1078 {
1079 set_search_regs (pos, 0);
1080 return pos;
1081 }
1082
1083 /* Searching 0 times means don't move. */
1084 if (n == 0)
1085 return pos;
1086
1087 if (RE && !trivial_regexp_p (string))
1088 {
1089 struct re_pattern_buffer *bufp;
1090
1091 bufp = compile_pattern (string, &search_regs, trt, posix);
1092
1093 immediate_quit = 1; /* Quit immediately if user types ^G,
1094 because letting this function finish
1095 can take too long. */
1096 QUIT; /* Do a pending quit right away,
1097 to avoid paradoxical behavior */
1098 /* Get pointers and sizes of the two strings
1099 that make up the visible portion of the buffer. */
1100
1101 p1 = BEGV_ADDR;
1102 s1 = GPT - BEGV;
1103 p2 = GAP_END_ADDR;
1104 s2 = ZV - GPT;
1105 if (s1 < 0)
1106 {
1107 p2 = p1;
1108 s2 = ZV - BEGV;
1109 s1 = 0;
1110 }
1111 if (s2 < 0)
1112 {
1113 s1 = ZV - BEGV;
1114 s2 = 0;
1115 }
1116 while (n < 0)
1117 {
1118 int val;
1119 val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
1120 pos - BEGV, lim - pos, &search_regs,
1121 /* Don't allow match past current point */
1122 pos - BEGV);
1123 if (val == -2)
1124 {
1125 matcher_overflow ();
1126 }
1127 if (val >= 0)
1128 {
1129 j = BEGV;
1130 for (i = 0; i < search_regs.num_regs; i++)
1131 if (search_regs.start[i] >= 0)
1132 {
1133 search_regs.start[i] += j;
1134 search_regs.end[i] += j;
1135 }
1136 XSETBUFFER (last_thing_searched, current_buffer);
1137 /* Set pos to the new position. */
1138 pos = search_regs.start[0];
1139 }
1140 else
1141 {
1142 immediate_quit = 0;
1143 return (n);
1144 }
1145 n++;
1146 }
1147 while (n > 0)
1148 {
1149 int val;
1150 val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
1151 pos - BEGV, lim - pos, &search_regs,
1152 lim - BEGV);
1153 if (val == -2)
1154 {
1155 matcher_overflow ();
1156 }
1157 if (val >= 0)
1158 {
1159 j = BEGV;
1160 for (i = 0; i < search_regs.num_regs; i++)
1161 if (search_regs.start[i] >= 0)
1162 {
1163 search_regs.start[i] += j;
1164 search_regs.end[i] += j;
1165 }
1166 XSETBUFFER (last_thing_searched, current_buffer);
1167 pos = search_regs.end[0];
1168 }
1169 else
1170 {
1171 immediate_quit = 0;
1172 return (0 - n);
1173 }
1174 n--;
1175 }
1176 immediate_quit = 0;
1177 return (pos);
1178 }
1179 else /* non-RE case */
1180 {
1181 #ifdef C_ALLOCA
1182 int BM_tab_space[0400];
1183 BM_tab = &BM_tab_space[0];
1184 #else
1185 BM_tab = (int *) alloca (0400 * sizeof (int));
1186 #endif
1187 {
1188 unsigned char *patbuf = (unsigned char *) alloca (len);
1189 pat = patbuf;
1190 while (--len >= 0)
1191 {
1192 /* If we got here and the RE flag is set, it's because we're
1193 dealing with a regexp known to be trivial, so the backslash
1194 just quotes the next character. */
1195 if (RE && *base_pat == '\\')
1196 {
1197 len--;
1198 base_pat++;
1199 }
1200 *pat++ = (trt ? trt[*base_pat++] : *base_pat++);
1201 }
1202 len = pat - patbuf;
1203 pat = base_pat = patbuf;
1204 }
1205 /* The general approach is that we are going to maintain that we know */
1206 /* the first (closest to the present position, in whatever direction */
1207 /* we're searching) character that could possibly be the last */
1208 /* (furthest from present position) character of a valid match. We */
1209 /* advance the state of our knowledge by looking at that character */
1210 /* and seeing whether it indeed matches the last character of the */
1211 /* pattern. If it does, we take a closer look. If it does not, we */
1212 /* move our pointer (to putative last characters) as far as is */
1213 /* logically possible. This amount of movement, which I call a */
1214 /* stride, will be the length of the pattern if the actual character */
1215 /* appears nowhere in the pattern, otherwise it will be the distance */
1216 /* from the last occurrence of that character to the end of the */
1217 /* pattern. */
1218 /* As a coding trick, an enormous stride is coded into the table for */
1219 /* characters that match the last character. This allows use of only */
1220 /* a single test, a test for having gone past the end of the */
1221 /* permissible match region, to test for both possible matches (when */
1222 /* the stride goes past the end immediately) and failure to */
1223 /* match (where you get nudged past the end one stride at a time). */
1224
1225 /* Here we make a "mickey mouse" BM table. The stride of the search */
1226 /* is determined only by the last character of the putative match. */
1227 /* If that character does not match, we will stride the proper */
1228 /* distance to propose a match that superimposes it on the last */
1229 /* instance of a character that matches it (per trt), or misses */
1230 /* it entirely if there is none. */
1231
1232 dirlen = len * direction;
1233 infinity = dirlen - (lim + pos + len + len) * direction;
1234 if (direction < 0)
1235 pat = (base_pat += len - 1);
1236 BM_tab_base = BM_tab;
1237 BM_tab += 0400;
1238 j = dirlen; /* to get it in a register */
1239 /* A character that does not appear in the pattern induces a */
1240 /* stride equal to the pattern length. */
1241 while (BM_tab_base != BM_tab)
1242 {
1243 *--BM_tab = j;
1244 *--BM_tab = j;
1245 *--BM_tab = j;
1246 *--BM_tab = j;
1247 }
1248 i = 0;
1249 while (i != infinity)
1250 {
1251 j = pat[i]; i += direction;
1252 if (i == dirlen) i = infinity;
1253 if (trt != 0)
1254 {
1255 k = (j = trt[j]);
1256 if (i == infinity)
1257 stride_for_teases = BM_tab[j];
1258 BM_tab[j] = dirlen - i;
1259 /* A translation table is accompanied by its inverse -- see */
1260 /* comment following downcase_table for details */
1261 while ((j = (unsigned char) inverse_trt[j]) != k)
1262 BM_tab[j] = dirlen - i;
1263 }
1264 else
1265 {
1266 if (i == infinity)
1267 stride_for_teases = BM_tab[j];
1268 BM_tab[j] = dirlen - i;
1269 }
1270 /* stride_for_teases tells how much to stride if we get a */
1271 /* match on the far character but are subsequently */
1272 /* disappointed, by recording what the stride would have been */
1273 /* for that character if the last character had been */
1274 /* different. */
1275 }
1276 infinity = dirlen - infinity;
1277 pos += dirlen - ((direction > 0) ? direction : 0);
1278 /* loop invariant - pos points at where last char (first char if reverse)
1279 of pattern would align in a possible match. */
1280 while (n != 0)
1281 {
1282 /* It's been reported that some (broken) compiler thinks that
1283 Boolean expressions in an arithmetic context are unsigned.
1284 Using an explicit ?1:0 prevents this. */
1285 if ((lim - pos - ((direction > 0) ? 1 : 0)) * direction < 0)
1286 return (n * (0 - direction));
1287 /* First we do the part we can by pointers (maybe nothing) */
1288 QUIT;
1289 pat = base_pat;
1290 limit = pos - dirlen + direction;
1291 limit = ((direction > 0)
1292 ? BUFFER_CEILING_OF (limit)
1293 : BUFFER_FLOOR_OF (limit));
1294 /* LIMIT is now the last (not beyond-last!) value
1295 POS can take on without hitting edge of buffer or the gap. */
1296 limit = ((direction > 0)
1297 ? min (lim - 1, min (limit, pos + 20000))
1298 : max (lim, max (limit, pos - 20000)));
1299 if ((limit - pos) * direction > 20)
1300 {
1301 p_limit = POS_ADDR (limit);
1302 p2 = (cursor = POS_ADDR (pos));
1303 /* In this loop, pos + cursor - p2 is the surrogate for pos */
1304 while (1) /* use one cursor setting as long as i can */
1305 {
1306 if (direction > 0) /* worth duplicating */
1307 {
1308 /* Use signed comparison if appropriate
1309 to make cursor+infinity sure to be > p_limit.
1310 Assuming that the buffer lies in a range of addresses
1311 that are all "positive" (as ints) or all "negative",
1312 either kind of comparison will work as long
1313 as we don't step by infinity. So pick the kind
1314 that works when we do step by infinity. */
1315 if ((EMACS_INT) (p_limit + infinity) > (EMACS_INT) p_limit)
1316 while ((EMACS_INT) cursor <= (EMACS_INT) p_limit)
1317 cursor += BM_tab[*cursor];
1318 else
1319 while ((EMACS_UINT) cursor <= (EMACS_UINT) p_limit)
1320 cursor += BM_tab[*cursor];
1321 }
1322 else
1323 {
1324 if ((EMACS_INT) (p_limit + infinity) < (EMACS_INT) p_limit)
1325 while ((EMACS_INT) cursor >= (EMACS_INT) p_limit)
1326 cursor += BM_tab[*cursor];
1327 else
1328 while ((EMACS_UINT) cursor >= (EMACS_UINT) p_limit)
1329 cursor += BM_tab[*cursor];
1330 }
1331 /* If you are here, cursor is beyond the end of the searched region. */
1332 /* This can happen if you match on the far character of the pattern, */
1333 /* because the "stride" of that character is infinity, a number able */
1334 /* to throw you well beyond the end of the search. It can also */
1335 /* happen if you fail to match within the permitted region and would */
1336 /* otherwise try a character beyond that region */
1337 if ((cursor - p_limit) * direction <= len)
1338 break; /* a small overrun is genuine */
1339 cursor -= infinity; /* large overrun = hit */
1340 i = dirlen - direction;
1341 if (trt != 0)
1342 {
1343 while ((i -= direction) + direction != 0)
1344 if (pat[i] != trt[*(cursor -= direction)])
1345 break;
1346 }
1347 else
1348 {
1349 while ((i -= direction) + direction != 0)
1350 if (pat[i] != *(cursor -= direction))
1351 break;
1352 }
1353 cursor += dirlen - i - direction; /* fix cursor */
1354 if (i + direction == 0)
1355 {
1356 cursor -= direction;
1357
1358 set_search_regs (pos + cursor - p2 + ((direction > 0)
1359 ? 1 - len : 0),
1360 len);
1361
1362 if ((n -= direction) != 0)
1363 cursor += dirlen; /* to resume search */
1364 else
1365 return ((direction > 0)
1366 ? search_regs.end[0] : search_regs.start[0]);
1367 }
1368 else
1369 cursor += stride_for_teases; /* <sigh> we lose - */
1370 }
1371 pos += cursor - p2;
1372 }
1373 else
1374 /* Now we'll pick up a clump that has to be done the hard */
1375 /* way because it covers a discontinuity */
1376 {
1377 limit = ((direction > 0)
1378 ? BUFFER_CEILING_OF (pos - dirlen + 1)
1379 : BUFFER_FLOOR_OF (pos - dirlen - 1));
1380 limit = ((direction > 0)
1381 ? min (limit + len, lim - 1)
1382 : max (limit - len, lim));
1383 /* LIMIT is now the last value POS can have
1384 and still be valid for a possible match. */
1385 while (1)
1386 {
1387 /* This loop can be coded for space rather than */
1388 /* speed because it will usually run only once. */
1389 /* (the reach is at most len + 21, and typically */
1390 /* does not exceed len) */
1391 while ((limit - pos) * direction >= 0)
1392 pos += BM_tab[FETCH_BYTE (pos)];
1393 /* now run the same tests to distinguish going off the */
1394 /* end, a match or a phony match. */
1395 if ((pos - limit) * direction <= len)
1396 break; /* ran off the end */
1397 /* Found what might be a match.
1398 Set POS back to last (first if reverse) char pos. */
1399 pos -= infinity;
1400 i = dirlen - direction;
1401 while ((i -= direction) + direction != 0)
1402 {
1403 pos -= direction;
1404 if (pat[i] != (trt != 0
1405 ? trt[FETCH_BYTE (pos)]
1406 : FETCH_BYTE (pos)))
1407 break;
1408 }
1409 /* Above loop has moved POS part or all the way
1410 back to the first char pos (last char pos if reverse).
1411 Set it once again at the last (first if reverse) char. */
1412 pos += dirlen - i- direction;
1413 if (i + direction == 0)
1414 {
1415 pos -= direction;
1416
1417 set_search_regs (pos + ((direction > 0) ? 1 - len : 0),
1418 len);
1419
1420 if ((n -= direction) != 0)
1421 pos += dirlen; /* to resume search */
1422 else
1423 return ((direction > 0)
1424 ? search_regs.end[0] : search_regs.start[0]);
1425 }
1426 else
1427 pos += stride_for_teases;
1428 }
1429 }
1430 /* We have done one clump. Can we continue? */
1431 if ((lim - pos) * direction < 0)
1432 return ((0 - n) * direction);
1433 }
1434 return pos;
1435 }
1436 }
1437
1438 /* Record beginning BEG and end BEG + LEN
1439 for a match just found in the current buffer. */
1440
1441 static void
1442 set_search_regs (beg, len)
1443 int beg, len;
1444 {
1445 /* Make sure we have registers in which to store
1446 the match position. */
1447 if (search_regs.num_regs == 0)
1448 {
1449 search_regs.start = (regoff_t *) xmalloc (2 * sizeof (regoff_t));
1450 search_regs.end = (regoff_t *) xmalloc (2 * sizeof (regoff_t));
1451 search_regs.num_regs = 2;
1452 }
1453
1454 search_regs.start[0] = beg;
1455 search_regs.end[0] = beg + len;
1456 XSETBUFFER (last_thing_searched, current_buffer);
1457 }
1458 \f
1459 /* Given a string of words separated by word delimiters,
1460 compute a regexp that matches those exact words
1461 separated by arbitrary punctuation. */
1462
1463 static Lisp_Object
1464 wordify (string)
1465 Lisp_Object string;
1466 {
1467 register unsigned char *p, *o;
1468 register int i, len, punct_count = 0, word_count = 0;
1469 Lisp_Object val;
1470
1471 CHECK_STRING (string, 0);
1472 p = XSTRING (string)->data;
1473 len = XSTRING (string)->size;
1474
1475 for (i = 0; i < len; i++)
1476 if (SYNTAX (p[i]) != Sword)
1477 {
1478 punct_count++;
1479 if (i > 0 && SYNTAX (p[i-1]) == Sword) word_count++;
1480 }
1481 if (SYNTAX (p[len-1]) == Sword) word_count++;
1482 if (!word_count) return build_string ("");
1483
1484 val = make_string (p, len - punct_count + 5 * (word_count - 1) + 4);
1485
1486 o = XSTRING (val)->data;
1487 *o++ = '\\';
1488 *o++ = 'b';
1489
1490 for (i = 0; i < len; i++)
1491 if (SYNTAX (p[i]) == Sword)
1492 *o++ = p[i];
1493 else if (i > 0 && SYNTAX (p[i-1]) == Sword && --word_count)
1494 {
1495 *o++ = '\\';
1496 *o++ = 'W';
1497 *o++ = '\\';
1498 *o++ = 'W';
1499 *o++ = '*';
1500 }
1501
1502 *o++ = '\\';
1503 *o++ = 'b';
1504
1505 return val;
1506 }
1507 \f
1508 DEFUN ("search-backward", Fsearch_backward, Ssearch_backward, 1, 4,
1509 "sSearch backward: ",
1510 "Search backward from point for STRING.\n\
1511 Set point to the beginning of the occurrence found, and return point.\n\
1512 An optional second argument bounds the search; it is a buffer position.\n\
1513 The match found must not extend before that position.\n\
1514 Optional third argument, if t, means if fail just return nil (no error).\n\
1515 If not nil and not t, position at limit of search and return nil.\n\
1516 Optional fourth argument is repeat count--search for successive occurrences.\n\
1517 See also the functions `match-beginning', `match-end' and `replace-match'.")
1518 (string, bound, noerror, count)
1519 Lisp_Object string, bound, noerror, count;
1520 {
1521 return search_command (string, bound, noerror, count, -1, 0, 0);
1522 }
1523
1524 DEFUN ("search-forward", Fsearch_forward, Ssearch_forward, 1, 4, "sSearch: ",
1525 "Search forward from point for STRING.\n\
1526 Set point to the end of the occurrence found, and return point.\n\
1527 An optional second argument bounds the search; it is a buffer position.\n\
1528 The match found must not extend after that position. nil is equivalent\n\
1529 to (point-max).\n\
1530 Optional third argument, if t, means if fail just return nil (no error).\n\
1531 If not nil and not t, move to limit of search and return nil.\n\
1532 Optional fourth argument is repeat count--search for successive occurrences.\n\
1533 See also the functions `match-beginning', `match-end' and `replace-match'.")
1534 (string, bound, noerror, count)
1535 Lisp_Object string, bound, noerror, count;
1536 {
1537 return search_command (string, bound, noerror, count, 1, 0, 0);
1538 }
1539
1540 DEFUN ("word-search-backward", Fword_search_backward, Sword_search_backward, 1, 4,
1541 "sWord search backward: ",
1542 "Search backward from point for STRING, ignoring differences in punctuation.\n\
1543 Set point to the beginning of the occurrence found, and return point.\n\
1544 An optional second argument bounds the search; it is a buffer position.\n\
1545 The match found must not extend before that position.\n\
1546 Optional third argument, if t, means if fail just return nil (no error).\n\
1547 If not nil and not t, move to limit of search and return nil.\n\
1548 Optional fourth argument is repeat count--search for successive occurrences.")
1549 (string, bound, noerror, count)
1550 Lisp_Object string, bound, noerror, count;
1551 {
1552 return search_command (wordify (string), bound, noerror, count, -1, 1, 0);
1553 }
1554
1555 DEFUN ("word-search-forward", Fword_search_forward, Sword_search_forward, 1, 4,
1556 "sWord search: ",
1557 "Search forward from point for STRING, ignoring differences in punctuation.\n\
1558 Set point to the end of the occurrence found, and return point.\n\
1559 An optional second argument bounds the search; it is a buffer position.\n\
1560 The match found must not extend after that position.\n\
1561 Optional third argument, if t, means if fail just return nil (no error).\n\
1562 If not nil and not t, move to limit of search and return nil.\n\
1563 Optional fourth argument is repeat count--search for successive occurrences.")
1564 (string, bound, noerror, count)
1565 Lisp_Object string, bound, noerror, count;
1566 {
1567 return search_command (wordify (string), bound, noerror, count, 1, 1, 0);
1568 }
1569
1570 DEFUN ("re-search-backward", Fre_search_backward, Sre_search_backward, 1, 4,
1571 "sRE search backward: ",
1572 "Search backward from point for match for regular expression REGEXP.\n\
1573 Set point to the beginning of the match, and return point.\n\
1574 The match found is the one starting last in the buffer\n\
1575 and yet ending before the origin of the search.\n\
1576 An optional second argument bounds the search; it is a buffer position.\n\
1577 The match found must start at or after that position.\n\
1578 Optional third argument, if t, means if fail just return nil (no error).\n\
1579 If not nil and not t, move to limit of search and return nil.\n\
1580 Optional fourth argument is repeat count--search for successive occurrences.\n\
1581 See also the functions `match-beginning', `match-end' and `replace-match'.")
1582 (regexp, bound, noerror, count)
1583 Lisp_Object regexp, bound, noerror, count;
1584 {
1585 return search_command (regexp, bound, noerror, count, -1, 1, 0);
1586 }
1587
1588 DEFUN ("re-search-forward", Fre_search_forward, Sre_search_forward, 1, 4,
1589 "sRE search: ",
1590 "Search forward from point for regular expression REGEXP.\n\
1591 Set point to the end of the occurrence found, and return point.\n\
1592 An optional second argument bounds the search; it is a buffer position.\n\
1593 The match found must not extend after that position.\n\
1594 Optional third argument, if t, means if fail just return nil (no error).\n\
1595 If not nil and not t, move to limit of search and return nil.\n\
1596 Optional fourth argument is repeat count--search for successive occurrences.\n\
1597 See also the functions `match-beginning', `match-end' and `replace-match'.")
1598 (regexp, bound, noerror, count)
1599 Lisp_Object regexp, bound, noerror, count;
1600 {
1601 return search_command (regexp, bound, noerror, count, 1, 1, 0);
1602 }
1603
1604 DEFUN ("posix-search-backward", Fposix_search_backward, Sposix_search_backward, 1, 4,
1605 "sPosix search backward: ",
1606 "Search backward from point for match for regular expression REGEXP.\n\
1607 Find the longest match in accord with Posix regular expression rules.\n\
1608 Set point to the beginning of the match, and return point.\n\
1609 The match found is the one starting last in the buffer\n\
1610 and yet ending before the origin of the search.\n\
1611 An optional second argument bounds the search; it is a buffer position.\n\
1612 The match found must start at or after that position.\n\
1613 Optional third argument, if t, means if fail just return nil (no error).\n\
1614 If not nil and not t, move to limit of search and return nil.\n\
1615 Optional fourth argument is repeat count--search for successive occurrences.\n\
1616 See also the functions `match-beginning', `match-end' and `replace-match'.")
1617 (regexp, bound, noerror, count)
1618 Lisp_Object regexp, bound, noerror, count;
1619 {
1620 return search_command (regexp, bound, noerror, count, -1, 1, 1);
1621 }
1622
1623 DEFUN ("posix-search-forward", Fposix_search_forward, Sposix_search_forward, 1, 4,
1624 "sPosix search: ",
1625 "Search forward from point for regular expression REGEXP.\n\
1626 Find the longest match in accord with Posix regular expression rules.\n\
1627 Set point to the end of the occurrence found, and return point.\n\
1628 An optional second argument bounds the search; it is a buffer position.\n\
1629 The match found must not extend after that position.\n\
1630 Optional third argument, if t, means if fail just return nil (no error).\n\
1631 If not nil and not t, move to limit of search and return nil.\n\
1632 Optional fourth argument is repeat count--search for successive occurrences.\n\
1633 See also the functions `match-beginning', `match-end' and `replace-match'.")
1634 (regexp, bound, noerror, count)
1635 Lisp_Object regexp, bound, noerror, count;
1636 {
1637 return search_command (regexp, bound, noerror, count, 1, 1, 1);
1638 }
1639 \f
1640 DEFUN ("replace-match", Freplace_match, Sreplace_match, 1, 5, 0,
1641 "Replace text matched by last search with NEWTEXT.\n\
1642 If second arg FIXEDCASE is non-nil, do not alter case of replacement text.\n\
1643 Otherwise maybe capitalize the whole text, or maybe just word initials,\n\
1644 based on the replaced text.\n\
1645 If the replaced text has only capital letters\n\
1646 and has at least one multiletter word, convert NEWTEXT to all caps.\n\
1647 If the replaced text has at least one word starting with a capital letter,\n\
1648 then capitalize each word in NEWTEXT.\n\n\
1649 If third arg LITERAL is non-nil, insert NEWTEXT literally.\n\
1650 Otherwise treat `\\' as special:\n\
1651 `\\&' in NEWTEXT means substitute original matched text.\n\
1652 `\\N' means substitute what matched the Nth `\\(...\\)'.\n\
1653 If Nth parens didn't match, substitute nothing.\n\
1654 `\\\\' means insert one `\\'.\n\
1655 FIXEDCASE and LITERAL are optional arguments.\n\
1656 Leaves point at end of replacement text.\n\
1657 \n\
1658 The optional fourth argument STRING can be a string to modify.\n\
1659 In that case, this function creates and returns a new string\n\
1660 which is made by replacing the part of STRING that was matched.\n\
1661 \n\
1662 The optional fifth argument SUBEXP specifies a subexpression of the match.\n\
1663 It says to replace just that subexpression instead of the whole match.\n\
1664 This is useful only after a regular expression search or match\n\
1665 since only regular expressions have distinguished subexpressions.")
1666 (newtext, fixedcase, literal, string, subexp)
1667 Lisp_Object newtext, fixedcase, literal, string, subexp;
1668 {
1669 enum { nochange, all_caps, cap_initial } case_action;
1670 register int pos, last;
1671 int some_multiletter_word;
1672 int some_lowercase;
1673 int some_uppercase;
1674 int some_nonuppercase_initial;
1675 register int c, prevc;
1676 int inslen;
1677 int sub;
1678
1679 CHECK_STRING (newtext, 0);
1680
1681 if (! NILP (string))
1682 CHECK_STRING (string, 4);
1683
1684 case_action = nochange; /* We tried an initialization */
1685 /* but some C compilers blew it */
1686
1687 if (search_regs.num_regs <= 0)
1688 error ("replace-match called before any match found");
1689
1690 if (NILP (subexp))
1691 sub = 0;
1692 else
1693 {
1694 CHECK_NUMBER (subexp, 3);
1695 sub = XINT (subexp);
1696 if (sub < 0 || sub >= search_regs.num_regs)
1697 args_out_of_range (subexp, make_number (search_regs.num_regs));
1698 }
1699
1700 if (NILP (string))
1701 {
1702 if (search_regs.start[sub] < BEGV
1703 || search_regs.start[sub] > search_regs.end[sub]
1704 || search_regs.end[sub] > ZV)
1705 args_out_of_range (make_number (search_regs.start[sub]),
1706 make_number (search_regs.end[sub]));
1707 }
1708 else
1709 {
1710 if (search_regs.start[sub] < 0
1711 || search_regs.start[sub] > search_regs.end[sub]
1712 || search_regs.end[sub] > XSTRING (string)->size)
1713 args_out_of_range (make_number (search_regs.start[sub]),
1714 make_number (search_regs.end[sub]));
1715 }
1716
1717 if (NILP (fixedcase))
1718 {
1719 /* Decide how to casify by examining the matched text. */
1720
1721 last = search_regs.end[sub];
1722 prevc = '\n';
1723 case_action = all_caps;
1724
1725 /* some_multiletter_word is set nonzero if any original word
1726 is more than one letter long. */
1727 some_multiletter_word = 0;
1728 some_lowercase = 0;
1729 some_nonuppercase_initial = 0;
1730 some_uppercase = 0;
1731
1732 for (pos = search_regs.start[sub]; pos < last; pos++)
1733 {
1734 if (NILP (string))
1735 c = FETCH_BYTE (pos);
1736 else
1737 c = XSTRING (string)->data[pos];
1738
1739 if (LOWERCASEP (c))
1740 {
1741 /* Cannot be all caps if any original char is lower case */
1742
1743 some_lowercase = 1;
1744 if (SYNTAX (prevc) != Sword)
1745 some_nonuppercase_initial = 1;
1746 else
1747 some_multiletter_word = 1;
1748 }
1749 else if (!NOCASEP (c))
1750 {
1751 some_uppercase = 1;
1752 if (SYNTAX (prevc) != Sword)
1753 ;
1754 else
1755 some_multiletter_word = 1;
1756 }
1757 else
1758 {
1759 /* If the initial is a caseless word constituent,
1760 treat that like a lowercase initial. */
1761 if (SYNTAX (prevc) != Sword)
1762 some_nonuppercase_initial = 1;
1763 }
1764
1765 prevc = c;
1766 }
1767
1768 /* Convert to all caps if the old text is all caps
1769 and has at least one multiletter word. */
1770 if (! some_lowercase && some_multiletter_word)
1771 case_action = all_caps;
1772 /* Capitalize each word, if the old text has all capitalized words. */
1773 else if (!some_nonuppercase_initial && some_multiletter_word)
1774 case_action = cap_initial;
1775 else if (!some_nonuppercase_initial && some_uppercase)
1776 /* Should x -> yz, operating on X, give Yz or YZ?
1777 We'll assume the latter. */
1778 case_action = all_caps;
1779 else
1780 case_action = nochange;
1781 }
1782
1783 /* Do replacement in a string. */
1784 if (!NILP (string))
1785 {
1786 Lisp_Object before, after;
1787
1788 before = Fsubstring (string, make_number (0),
1789 make_number (search_regs.start[sub]));
1790 after = Fsubstring (string, make_number (search_regs.end[sub]), Qnil);
1791
1792 /* Do case substitution into NEWTEXT if desired. */
1793 if (NILP (literal))
1794 {
1795 int lastpos = -1;
1796 /* We build up the substituted string in ACCUM. */
1797 Lisp_Object accum;
1798 Lisp_Object middle;
1799
1800 accum = Qnil;
1801
1802 for (pos = 0; pos < XSTRING (newtext)->size; pos++)
1803 {
1804 int substart = -1;
1805 int subend;
1806 int delbackslash = 0;
1807
1808 c = XSTRING (newtext)->data[pos];
1809 if (c == '\\')
1810 {
1811 c = XSTRING (newtext)->data[++pos];
1812 if (c == '&')
1813 {
1814 substart = search_regs.start[sub];
1815 subend = search_regs.end[sub];
1816 }
1817 else if (c >= '1' && c <= '9' && c <= search_regs.num_regs + '0')
1818 {
1819 if (search_regs.start[c - '0'] >= 0)
1820 {
1821 substart = search_regs.start[c - '0'];
1822 subend = search_regs.end[c - '0'];
1823 }
1824 }
1825 else if (c == '\\')
1826 delbackslash = 1;
1827 }
1828 if (substart >= 0)
1829 {
1830 if (pos - 1 != lastpos + 1)
1831 middle = Fsubstring (newtext,
1832 make_number (lastpos + 1),
1833 make_number (pos - 1));
1834 else
1835 middle = Qnil;
1836 accum = concat3 (accum, middle,
1837 Fsubstring (string, make_number (substart),
1838 make_number (subend)));
1839 lastpos = pos;
1840 }
1841 else if (delbackslash)
1842 {
1843 middle = Fsubstring (newtext, make_number (lastpos + 1),
1844 make_number (pos));
1845 accum = concat2 (accum, middle);
1846 lastpos = pos;
1847 }
1848 }
1849
1850 if (pos != lastpos + 1)
1851 middle = Fsubstring (newtext, make_number (lastpos + 1),
1852 make_number (pos));
1853 else
1854 middle = Qnil;
1855
1856 newtext = concat2 (accum, middle);
1857 }
1858
1859 if (case_action == all_caps)
1860 newtext = Fupcase (newtext);
1861 else if (case_action == cap_initial)
1862 newtext = Fupcase_initials (newtext);
1863
1864 return concat3 (before, newtext, after);
1865 }
1866
1867 /* We insert the replacement text before the old text, and then
1868 delete the original text. This means that markers at the
1869 beginning or end of the original will float to the corresponding
1870 position in the replacement. */
1871 SET_PT (search_regs.start[sub]);
1872 if (!NILP (literal))
1873 Finsert_and_inherit (1, &newtext);
1874 else
1875 {
1876 struct gcpro gcpro1;
1877 GCPRO1 (newtext);
1878
1879 for (pos = 0; pos < XSTRING (newtext)->size; pos++)
1880 {
1881 int offset = PT - search_regs.start[sub];
1882
1883 c = XSTRING (newtext)->data[pos];
1884 if (c == '\\')
1885 {
1886 c = XSTRING (newtext)->data[++pos];
1887 if (c == '&')
1888 Finsert_buffer_substring
1889 (Fcurrent_buffer (),
1890 make_number (search_regs.start[sub] + offset),
1891 make_number (search_regs.end[sub] + offset));
1892 else if (c >= '1' && c <= '9' && c <= search_regs.num_regs + '0')
1893 {
1894 if (search_regs.start[c - '0'] >= 1)
1895 Finsert_buffer_substring
1896 (Fcurrent_buffer (),
1897 make_number (search_regs.start[c - '0'] + offset),
1898 make_number (search_regs.end[c - '0'] + offset));
1899 }
1900 else
1901 insert_char (c);
1902 }
1903 else
1904 insert_char (c);
1905 }
1906 UNGCPRO;
1907 }
1908
1909 inslen = PT - (search_regs.start[sub]);
1910 del_range (search_regs.start[sub] + inslen, search_regs.end[sub] + inslen);
1911
1912 if (case_action == all_caps)
1913 Fupcase_region (make_number (PT - inslen), make_number (PT));
1914 else if (case_action == cap_initial)
1915 Fupcase_initials_region (make_number (PT - inslen), make_number (PT));
1916 return Qnil;
1917 }
1918 \f
1919 static Lisp_Object
1920 match_limit (num, beginningp)
1921 Lisp_Object num;
1922 int beginningp;
1923 {
1924 register int n;
1925
1926 CHECK_NUMBER (num, 0);
1927 n = XINT (num);
1928 if (n < 0 || n >= search_regs.num_regs)
1929 args_out_of_range (num, make_number (search_regs.num_regs));
1930 if (search_regs.num_regs <= 0
1931 || search_regs.start[n] < 0)
1932 return Qnil;
1933 return (make_number ((beginningp) ? search_regs.start[n]
1934 : search_regs.end[n]));
1935 }
1936
1937 DEFUN ("match-beginning", Fmatch_beginning, Smatch_beginning, 1, 1, 0,
1938 "Return position of start of text matched by last search.\n\
1939 SUBEXP, a number, specifies which parenthesized expression in the last\n\
1940 regexp.\n\
1941 Value is nil if SUBEXPth pair didn't match, or there were less than\n\
1942 SUBEXP pairs.\n\
1943 Zero means the entire text matched by the whole regexp or whole string.")
1944 (subexp)
1945 Lisp_Object subexp;
1946 {
1947 return match_limit (subexp, 1);
1948 }
1949
1950 DEFUN ("match-end", Fmatch_end, Smatch_end, 1, 1, 0,
1951 "Return position of end of text matched by last search.\n\
1952 SUBEXP, a number, specifies which parenthesized expression in the last\n\
1953 regexp.\n\
1954 Value is nil if SUBEXPth pair didn't match, or there were less than\n\
1955 SUBEXP pairs.\n\
1956 Zero means the entire text matched by the whole regexp or whole string.")
1957 (subexp)
1958 Lisp_Object subexp;
1959 {
1960 return match_limit (subexp, 0);
1961 }
1962
1963 DEFUN ("match-data", Fmatch_data, Smatch_data, 0, 2, 0,
1964 "Return a list containing all info on what the last search matched.\n\
1965 Element 2N is `(match-beginning N)'; element 2N + 1 is `(match-end N)'.\n\
1966 All the elements are markers or nil (nil if the Nth pair didn't match)\n\
1967 if the last match was on a buffer; integers or nil if a string was matched.\n\
1968 Use `store-match-data' to reinstate the data in this list.\n\
1969 \n\
1970 If INTEGERS (the optional first argument) is non-nil, always use integers\n\
1971 \(rather than markers) to represent buffer positions.\n\
1972 If REUSE is a list, reuse it as part of the value. If REUSE is long enough\n\
1973 to hold all the values, and if INTEGERS is non-nil, no consing is done.")
1974 (integers, reuse)
1975 Lisp_Object integers, reuse;
1976 {
1977 Lisp_Object tail, prev;
1978 Lisp_Object *data;
1979 int i, len;
1980
1981 if (NILP (last_thing_searched))
1982 return Qnil;
1983
1984 data = (Lisp_Object *) alloca ((2 * search_regs.num_regs)
1985 * sizeof (Lisp_Object));
1986
1987 len = -1;
1988 for (i = 0; i < search_regs.num_regs; i++)
1989 {
1990 int start = search_regs.start[i];
1991 if (start >= 0)
1992 {
1993 if (EQ (last_thing_searched, Qt)
1994 || ! NILP (integers))
1995 {
1996 XSETFASTINT (data[2 * i], start);
1997 XSETFASTINT (data[2 * i + 1], search_regs.end[i]);
1998 }
1999 else if (BUFFERP (last_thing_searched))
2000 {
2001 data[2 * i] = Fmake_marker ();
2002 Fset_marker (data[2 * i],
2003 make_number (start),
2004 last_thing_searched);
2005 data[2 * i + 1] = Fmake_marker ();
2006 Fset_marker (data[2 * i + 1],
2007 make_number (search_regs.end[i]),
2008 last_thing_searched);
2009 }
2010 else
2011 /* last_thing_searched must always be Qt, a buffer, or Qnil. */
2012 abort ();
2013
2014 len = i;
2015 }
2016 else
2017 data[2 * i] = data [2 * i + 1] = Qnil;
2018 }
2019
2020 /* If REUSE is not usable, cons up the values and return them. */
2021 if (! CONSP (reuse))
2022 return Flist (2 * len + 2, data);
2023
2024 /* If REUSE is a list, store as many value elements as will fit
2025 into the elements of REUSE. */
2026 for (i = 0, tail = reuse; CONSP (tail);
2027 i++, tail = XCONS (tail)->cdr)
2028 {
2029 if (i < 2 * len + 2)
2030 XCONS (tail)->car = data[i];
2031 else
2032 XCONS (tail)->car = Qnil;
2033 prev = tail;
2034 }
2035
2036 /* If we couldn't fit all value elements into REUSE,
2037 cons up the rest of them and add them to the end of REUSE. */
2038 if (i < 2 * len + 2)
2039 XCONS (prev)->cdr = Flist (2 * len + 2 - i, data + i);
2040
2041 return reuse;
2042 }
2043
2044
2045 DEFUN ("store-match-data", Fstore_match_data, Sstore_match_data, 1, 1, 0,
2046 "Set internal data on last search match from elements of LIST.\n\
2047 LIST should have been created by calling `match-data' previously.")
2048 (list)
2049 register Lisp_Object list;
2050 {
2051 register int i;
2052 register Lisp_Object marker;
2053
2054 if (running_asynch_code)
2055 save_search_regs ();
2056
2057 if (!CONSP (list) && !NILP (list))
2058 list = wrong_type_argument (Qconsp, list);
2059
2060 /* Unless we find a marker with a buffer in LIST, assume that this
2061 match data came from a string. */
2062 last_thing_searched = Qt;
2063
2064 /* Allocate registers if they don't already exist. */
2065 {
2066 int length = XFASTINT (Flength (list)) / 2;
2067
2068 if (length > search_regs.num_regs)
2069 {
2070 if (search_regs.num_regs == 0)
2071 {
2072 search_regs.start
2073 = (regoff_t *) xmalloc (length * sizeof (regoff_t));
2074 search_regs.end
2075 = (regoff_t *) xmalloc (length * sizeof (regoff_t));
2076 }
2077 else
2078 {
2079 search_regs.start
2080 = (regoff_t *) xrealloc (search_regs.start,
2081 length * sizeof (regoff_t));
2082 search_regs.end
2083 = (regoff_t *) xrealloc (search_regs.end,
2084 length * sizeof (regoff_t));
2085 }
2086
2087 search_regs.num_regs = length;
2088 }
2089 }
2090
2091 for (i = 0; i < search_regs.num_regs; i++)
2092 {
2093 marker = Fcar (list);
2094 if (NILP (marker))
2095 {
2096 search_regs.start[i] = -1;
2097 list = Fcdr (list);
2098 }
2099 else
2100 {
2101 if (MARKERP (marker))
2102 {
2103 if (XMARKER (marker)->buffer == 0)
2104 XSETFASTINT (marker, 0);
2105 else
2106 XSETBUFFER (last_thing_searched, XMARKER (marker)->buffer);
2107 }
2108
2109 CHECK_NUMBER_COERCE_MARKER (marker, 0);
2110 search_regs.start[i] = XINT (marker);
2111 list = Fcdr (list);
2112
2113 marker = Fcar (list);
2114 if (MARKERP (marker) && XMARKER (marker)->buffer == 0)
2115 XSETFASTINT (marker, 0);
2116
2117 CHECK_NUMBER_COERCE_MARKER (marker, 0);
2118 search_regs.end[i] = XINT (marker);
2119 }
2120 list = Fcdr (list);
2121 }
2122
2123 return Qnil;
2124 }
2125
2126 /* If non-zero the match data have been saved in saved_search_regs
2127 during the execution of a sentinel or filter. */
2128 static int search_regs_saved;
2129 static struct re_registers saved_search_regs;
2130
2131 /* Called from Flooking_at, Fstring_match, search_buffer, Fstore_match_data
2132 if asynchronous code (filter or sentinel) is running. */
2133 static void
2134 save_search_regs ()
2135 {
2136 if (!search_regs_saved)
2137 {
2138 saved_search_regs.num_regs = search_regs.num_regs;
2139 saved_search_regs.start = search_regs.start;
2140 saved_search_regs.end = search_regs.end;
2141 search_regs.num_regs = 0;
2142 search_regs.start = 0;
2143 search_regs.end = 0;
2144
2145 search_regs_saved = 1;
2146 }
2147 }
2148
2149 /* Called upon exit from filters and sentinels. */
2150 void
2151 restore_match_data ()
2152 {
2153 if (search_regs_saved)
2154 {
2155 if (search_regs.num_regs > 0)
2156 {
2157 xfree (search_regs.start);
2158 xfree (search_regs.end);
2159 }
2160 search_regs.num_regs = saved_search_regs.num_regs;
2161 search_regs.start = saved_search_regs.start;
2162 search_regs.end = saved_search_regs.end;
2163
2164 search_regs_saved = 0;
2165 }
2166 }
2167
2168 /* Quote a string to inactivate reg-expr chars */
2169
2170 DEFUN ("regexp-quote", Fregexp_quote, Sregexp_quote, 1, 1, 0,
2171 "Return a regexp string which matches exactly STRING and nothing else.")
2172 (string)
2173 Lisp_Object string;
2174 {
2175 register unsigned char *in, *out, *end;
2176 register unsigned char *temp;
2177
2178 CHECK_STRING (string, 0);
2179
2180 temp = (unsigned char *) alloca (XSTRING (string)->size * 2);
2181
2182 /* Now copy the data into the new string, inserting escapes. */
2183
2184 in = XSTRING (string)->data;
2185 end = in + XSTRING (string)->size;
2186 out = temp;
2187
2188 for (; in != end; in++)
2189 {
2190 if (*in == '[' || *in == ']'
2191 || *in == '*' || *in == '.' || *in == '\\'
2192 || *in == '?' || *in == '+'
2193 || *in == '^' || *in == '$')
2194 *out++ = '\\';
2195 *out++ = *in;
2196 }
2197
2198 return make_string (temp, out - temp);
2199 }
2200 \f
2201 syms_of_search ()
2202 {
2203 register int i;
2204
2205 for (i = 0; i < REGEXP_CACHE_SIZE; ++i)
2206 {
2207 searchbufs[i].buf.allocated = 100;
2208 searchbufs[i].buf.buffer = (unsigned char *) malloc (100);
2209 searchbufs[i].buf.fastmap = searchbufs[i].fastmap;
2210 searchbufs[i].regexp = Qnil;
2211 staticpro (&searchbufs[i].regexp);
2212 searchbufs[i].next = (i == REGEXP_CACHE_SIZE-1 ? 0 : &searchbufs[i+1]);
2213 }
2214 searchbuf_head = &searchbufs[0];
2215
2216 Qsearch_failed = intern ("search-failed");
2217 staticpro (&Qsearch_failed);
2218 Qinvalid_regexp = intern ("invalid-regexp");
2219 staticpro (&Qinvalid_regexp);
2220
2221 Fput (Qsearch_failed, Qerror_conditions,
2222 Fcons (Qsearch_failed, Fcons (Qerror, Qnil)));
2223 Fput (Qsearch_failed, Qerror_message,
2224 build_string ("Search failed"));
2225
2226 Fput (Qinvalid_regexp, Qerror_conditions,
2227 Fcons (Qinvalid_regexp, Fcons (Qerror, Qnil)));
2228 Fput (Qinvalid_regexp, Qerror_message,
2229 build_string ("Invalid regexp"));
2230
2231 last_thing_searched = Qnil;
2232 staticpro (&last_thing_searched);
2233
2234 defsubr (&Slooking_at);
2235 defsubr (&Sposix_looking_at);
2236 defsubr (&Sstring_match);
2237 defsubr (&Sposix_string_match);
2238 defsubr (&Sskip_chars_forward);
2239 defsubr (&Sskip_chars_backward);
2240 defsubr (&Sskip_syntax_forward);
2241 defsubr (&Sskip_syntax_backward);
2242 defsubr (&Ssearch_forward);
2243 defsubr (&Ssearch_backward);
2244 defsubr (&Sword_search_forward);
2245 defsubr (&Sword_search_backward);
2246 defsubr (&Sre_search_forward);
2247 defsubr (&Sre_search_backward);
2248 defsubr (&Sposix_search_forward);
2249 defsubr (&Sposix_search_backward);
2250 defsubr (&Sreplace_match);
2251 defsubr (&Smatch_beginning);
2252 defsubr (&Smatch_end);
2253 defsubr (&Smatch_data);
2254 defsubr (&Sstore_match_data);
2255 defsubr (&Sregexp_quote);
2256 }