]> code.delx.au - gnu-emacs/blob - src/search.c
(LIBS_MACHINE): Add -lelf.
[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 re_match_object = Qnil;
254
255 i = re_match_2 (bufp, (char *) p1, s1, (char *) p2, s2,
256 PT - BEGV, &search_regs,
257 ZV - BEGV);
258 if (i == -2)
259 matcher_overflow ();
260
261 val = (0 <= i ? Qt : Qnil);
262 for (i = 0; i < search_regs.num_regs; i++)
263 if (search_regs.start[i] >= 0)
264 {
265 search_regs.start[i] += BEGV;
266 search_regs.end[i] += BEGV;
267 }
268 XSETBUFFER (last_thing_searched, current_buffer);
269 immediate_quit = 0;
270 return val;
271 }
272
273 DEFUN ("looking-at", Flooking_at, Slooking_at, 1, 1, 0,
274 "Return t if text after point matches regular expression REGEXP.\n\
275 This function modifies the match data that `match-beginning',\n\
276 `match-end' and `match-data' access; save and restore the match\n\
277 data if you want to preserve them.")
278 (regexp)
279 Lisp_Object regexp;
280 {
281 return looking_at_1 (regexp, 0);
282 }
283
284 DEFUN ("posix-looking-at", Fposix_looking_at, Sposix_looking_at, 1, 1, 0,
285 "Return t if text after point matches regular expression REGEXP.\n\
286 Find the longest match, in accord with Posix regular expression rules.\n\
287 This function modifies the match data that `match-beginning',\n\
288 `match-end' and `match-data' access; save and restore the match\n\
289 data if you want to preserve them.")
290 (regexp)
291 Lisp_Object regexp;
292 {
293 return looking_at_1 (regexp, 1);
294 }
295 \f
296 static Lisp_Object
297 string_match_1 (regexp, string, start, posix)
298 Lisp_Object regexp, string, start;
299 int posix;
300 {
301 int val;
302 int s;
303 struct re_pattern_buffer *bufp;
304
305 if (running_asynch_code)
306 save_search_regs ();
307
308 CHECK_STRING (regexp, 0);
309 CHECK_STRING (string, 1);
310
311 if (NILP (start))
312 s = 0;
313 else
314 {
315 int len = XSTRING (string)->size;
316
317 CHECK_NUMBER (start, 2);
318 s = XINT (start);
319 if (s < 0 && -s <= len)
320 s = len + s;
321 else if (0 > s || s > len)
322 args_out_of_range (string, start);
323 }
324
325 bufp = compile_pattern (regexp, &search_regs,
326 (!NILP (current_buffer->case_fold_search)
327 ? DOWNCASE_TABLE : 0),
328 posix);
329 immediate_quit = 1;
330 re_match_object = string;
331
332 val = re_search (bufp, (char *) XSTRING (string)->data,
333 XSTRING (string)->size, s, XSTRING (string)->size - s,
334 &search_regs);
335 immediate_quit = 0;
336 last_thing_searched = Qt;
337 if (val == -2)
338 matcher_overflow ();
339 if (val < 0) return Qnil;
340 return make_number (val);
341 }
342
343 DEFUN ("string-match", Fstring_match, Sstring_match, 2, 3, 0,
344 "Return index of start of first match for REGEXP in STRING, or nil.\n\
345 If third arg START is non-nil, start search at that index in STRING.\n\
346 For index of first char beyond the match, do (match-end 0).\n\
347 `match-end' and `match-beginning' also give indices of substrings\n\
348 matched by parenthesis constructs in the pattern.")
349 (regexp, string, start)
350 Lisp_Object regexp, string, start;
351 {
352 return string_match_1 (regexp, string, start, 0);
353 }
354
355 DEFUN ("posix-string-match", Fposix_string_match, Sposix_string_match, 2, 3, 0,
356 "Return index of start of first match for REGEXP in STRING, or nil.\n\
357 Find the longest match, in accord with Posix regular expression rules.\n\
358 If third arg START is non-nil, start search at that index in STRING.\n\
359 For index of first char beyond the match, do (match-end 0).\n\
360 `match-end' and `match-beginning' also give indices of substrings\n\
361 matched by parenthesis constructs in the pattern.")
362 (regexp, string, start)
363 Lisp_Object regexp, string, start;
364 {
365 return string_match_1 (regexp, string, start, 1);
366 }
367
368 /* Match REGEXP against STRING, searching all of STRING,
369 and return the index of the match, or negative on failure.
370 This does not clobber the match data. */
371
372 int
373 fast_string_match (regexp, string)
374 Lisp_Object regexp, string;
375 {
376 int val;
377 struct re_pattern_buffer *bufp;
378
379 bufp = compile_pattern (regexp, 0, 0, 0);
380 immediate_quit = 1;
381 re_match_object = string;
382
383 val = re_search (bufp, (char *) XSTRING (string)->data,
384 XSTRING (string)->size, 0, XSTRING (string)->size,
385 0);
386 immediate_quit = 0;
387 return val;
388 }
389
390 /* Match REGEXP against STRING, searching all of STRING ignoring case,
391 and return the index of the match, or negative on failure.
392 This does not clobber the match data. */
393
394 extern Lisp_Object Vascii_downcase_table;
395
396 int
397 fast_string_match_ignore_case (regexp, string)
398 Lisp_Object regexp;
399 char *string;
400 {
401 int val;
402 struct re_pattern_buffer *bufp;
403 int len = strlen (string);
404
405 bufp = compile_pattern (regexp, 0,
406 XCHAR_TABLE (Vascii_downcase_table)->contents, 0);
407 immediate_quit = 1;
408 val = re_search (bufp, string, len, 0, len, 0);
409 immediate_quit = 0;
410 return val;
411 }
412 \f
413 /* max and min. */
414
415 static int
416 max (a, b)
417 int a, b;
418 {
419 return ((a > b) ? a : b);
420 }
421
422 static int
423 min (a, b)
424 int a, b;
425 {
426 return ((a < b) ? a : b);
427 }
428
429 \f
430 /* The newline cache: remembering which sections of text have no newlines. */
431
432 /* If the user has requested newline caching, make sure it's on.
433 Otherwise, make sure it's off.
434 This is our cheezy way of associating an action with the change of
435 state of a buffer-local variable. */
436 static void
437 newline_cache_on_off (buf)
438 struct buffer *buf;
439 {
440 if (NILP (buf->cache_long_line_scans))
441 {
442 /* It should be off. */
443 if (buf->newline_cache)
444 {
445 free_region_cache (buf->newline_cache);
446 buf->newline_cache = 0;
447 }
448 }
449 else
450 {
451 /* It should be on. */
452 if (buf->newline_cache == 0)
453 buf->newline_cache = new_region_cache ();
454 }
455 }
456
457 \f
458 /* Search for COUNT instances of the character TARGET between START and END.
459
460 If COUNT is positive, search forwards; END must be >= START.
461 If COUNT is negative, search backwards for the -COUNTth instance;
462 END must be <= START.
463 If COUNT is zero, do anything you please; run rogue, for all I care.
464
465 If END is zero, use BEGV or ZV instead, as appropriate for the
466 direction indicated by COUNT.
467
468 If we find COUNT instances, set *SHORTAGE to zero, and return the
469 position after the COUNTth match. Note that for reverse motion
470 this is not the same as the usual convention for Emacs motion commands.
471
472 If we don't find COUNT instances before reaching END, set *SHORTAGE
473 to the number of TARGETs left unfound, and return END.
474
475 If ALLOW_QUIT is non-zero, set immediate_quit. That's good to do
476 except when inside redisplay. */
477
478 scan_buffer (target, start, end, count, shortage, allow_quit)
479 register int target;
480 int start, end;
481 int count;
482 int *shortage;
483 int allow_quit;
484 {
485 struct region_cache *newline_cache;
486 int direction;
487
488 if (count > 0)
489 {
490 direction = 1;
491 if (! end) end = ZV;
492 }
493 else
494 {
495 direction = -1;
496 if (! end) end = BEGV;
497 }
498
499 newline_cache_on_off (current_buffer);
500 newline_cache = current_buffer->newline_cache;
501
502 if (shortage != 0)
503 *shortage = 0;
504
505 immediate_quit = allow_quit;
506
507 if (count > 0)
508 while (start != end)
509 {
510 /* Our innermost scanning loop is very simple; it doesn't know
511 about gaps, buffer ends, or the newline cache. ceiling is
512 the position of the last character before the next such
513 obstacle --- the last character the dumb search loop should
514 examine. */
515 register int ceiling = end - 1;
516
517 /* If we're looking for a newline, consult the newline cache
518 to see where we can avoid some scanning. */
519 if (target == '\n' && newline_cache)
520 {
521 int next_change;
522 immediate_quit = 0;
523 while (region_cache_forward
524 (current_buffer, newline_cache, start, &next_change))
525 start = next_change;
526 immediate_quit = allow_quit;
527
528 /* start should never be after end. */
529 if (start >= end)
530 start = end - 1;
531
532 /* Now the text after start is an unknown region, and
533 next_change is the position of the next known region. */
534 ceiling = min (next_change - 1, ceiling);
535 }
536
537 /* The dumb loop can only scan text stored in contiguous
538 bytes. BUFFER_CEILING_OF returns the last character
539 position that is contiguous, so the ceiling is the
540 position after that. */
541 ceiling = min (BUFFER_CEILING_OF (start), ceiling);
542
543 {
544 /* The termination address of the dumb loop. */
545 register unsigned char *ceiling_addr = POS_ADDR (ceiling) + 1;
546 register unsigned char *cursor = POS_ADDR (start);
547 unsigned char *base = cursor;
548
549 while (cursor < ceiling_addr)
550 {
551 unsigned char *scan_start = cursor;
552
553 /* The dumb loop. */
554 while (*cursor != target && ++cursor < ceiling_addr)
555 ;
556
557 /* If we're looking for newlines, cache the fact that
558 the region from start to cursor is free of them. */
559 if (target == '\n' && newline_cache)
560 know_region_cache (current_buffer, newline_cache,
561 start + scan_start - base,
562 start + cursor - base);
563
564 /* Did we find the target character? */
565 if (cursor < ceiling_addr)
566 {
567 if (--count == 0)
568 {
569 immediate_quit = 0;
570 return (start + cursor - base + 1);
571 }
572 cursor++;
573 }
574 }
575
576 start += cursor - base;
577 }
578 }
579 else
580 while (start > end)
581 {
582 /* The last character to check before the next obstacle. */
583 register int ceiling = end;
584
585 /* Consult the newline cache, if appropriate. */
586 if (target == '\n' && newline_cache)
587 {
588 int next_change;
589 immediate_quit = 0;
590 while (region_cache_backward
591 (current_buffer, newline_cache, start, &next_change))
592 start = next_change;
593 immediate_quit = allow_quit;
594
595 /* Start should never be at or before end. */
596 if (start <= end)
597 start = end + 1;
598
599 /* Now the text before start is an unknown region, and
600 next_change is the position of the next known region. */
601 ceiling = max (next_change, ceiling);
602 }
603
604 /* Stop scanning before the gap. */
605 ceiling = max (BUFFER_FLOOR_OF (start - 1), ceiling);
606
607 {
608 /* The termination address of the dumb loop. */
609 register unsigned char *ceiling_addr = POS_ADDR (ceiling);
610 register unsigned char *cursor = POS_ADDR (start - 1);
611 unsigned char *base = cursor;
612
613 while (cursor >= ceiling_addr)
614 {
615 unsigned char *scan_start = cursor;
616
617 while (*cursor != target && --cursor >= ceiling_addr)
618 ;
619
620 /* If we're looking for newlines, cache the fact that
621 the region from after the cursor to start is free of them. */
622 if (target == '\n' && newline_cache)
623 know_region_cache (current_buffer, newline_cache,
624 start + cursor - base,
625 start + scan_start - base);
626
627 /* Did we find the target character? */
628 if (cursor >= ceiling_addr)
629 {
630 if (++count >= 0)
631 {
632 immediate_quit = 0;
633 return (start + cursor - base);
634 }
635 cursor--;
636 }
637 }
638
639 start += cursor - base;
640 }
641 }
642
643 immediate_quit = 0;
644 if (shortage != 0)
645 *shortage = count * direction;
646 return start;
647 }
648
649 int
650 find_next_newline_no_quit (from, cnt)
651 register int from, cnt;
652 {
653 return scan_buffer ('\n', from, 0, cnt, (int *) 0, 0);
654 }
655
656 int
657 find_next_newline (from, cnt)
658 register int from, cnt;
659 {
660 return scan_buffer ('\n', from, 0, cnt, (int *) 0, 1);
661 }
662
663
664 /* Like find_next_newline, but returns position before the newline,
665 not after, and only search up to TO. This isn't just
666 find_next_newline (...)-1, because you might hit TO. */
667 int
668 find_before_next_newline (from, to, cnt)
669 int from, to, cnt;
670 {
671 int shortage;
672 int pos = scan_buffer ('\n', from, to, cnt, &shortage, 1);
673
674 if (shortage == 0)
675 pos--;
676
677 return pos;
678 }
679 \f
680 /* Subroutines of Lisp buffer search functions. */
681
682 static Lisp_Object
683 search_command (string, bound, noerror, count, direction, RE, posix)
684 Lisp_Object string, bound, noerror, count;
685 int direction;
686 int RE;
687 int posix;
688 {
689 register int np;
690 int lim;
691 int n = direction;
692
693 if (!NILP (count))
694 {
695 CHECK_NUMBER (count, 3);
696 n *= XINT (count);
697 }
698
699 CHECK_STRING (string, 0);
700 if (NILP (bound))
701 lim = n > 0 ? ZV : BEGV;
702 else
703 {
704 CHECK_NUMBER_COERCE_MARKER (bound, 1);
705 lim = XINT (bound);
706 if (n > 0 ? lim < PT : lim > PT)
707 error ("Invalid search bound (wrong side of point)");
708 if (lim > ZV)
709 lim = ZV;
710 if (lim < BEGV)
711 lim = BEGV;
712 }
713
714 np = search_buffer (string, PT, lim, n, RE,
715 (!NILP (current_buffer->case_fold_search)
716 ? XCHAR_TABLE (current_buffer->case_canon_table)->contents
717 : 0),
718 (!NILP (current_buffer->case_fold_search)
719 ? XCHAR_TABLE (current_buffer->case_eqv_table)->contents
720 : 0),
721 posix);
722 if (np <= 0)
723 {
724 if (NILP (noerror))
725 return signal_failure (string);
726 if (!EQ (noerror, Qt))
727 {
728 if (lim < BEGV || lim > ZV)
729 abort ();
730 SET_PT (lim);
731 return Qnil;
732 #if 0 /* This would be clean, but maybe programs depend on
733 a value of nil here. */
734 np = lim;
735 #endif
736 }
737 else
738 return Qnil;
739 }
740
741 if (np < BEGV || np > ZV)
742 abort ();
743
744 SET_PT (np);
745
746 return make_number (np);
747 }
748 \f
749 static int
750 trivial_regexp_p (regexp)
751 Lisp_Object regexp;
752 {
753 int len = XSTRING (regexp)->size;
754 unsigned char *s = XSTRING (regexp)->data;
755 unsigned char c;
756 while (--len >= 0)
757 {
758 switch (*s++)
759 {
760 case '.': case '*': case '+': case '?': case '[': case '^': case '$':
761 return 0;
762 case '\\':
763 if (--len < 0)
764 return 0;
765 switch (*s++)
766 {
767 case '|': case '(': case ')': case '`': case '\'': case 'b':
768 case 'B': case '<': case '>': case 'w': case 'W': case 's':
769 case 'S': case '=':
770 case 'c': case 'C': /* for categoryspec and notcategoryspec */
771 case '1': case '2': case '3': case '4': case '5':
772 case '6': case '7': case '8': case '9':
773 return 0;
774 }
775 }
776 }
777 return 1;
778 }
779
780 /* Search for the n'th occurrence of STRING in the current buffer,
781 starting at position POS and stopping at position LIM,
782 treating STRING as a literal string if RE is false or as
783 a regular expression if RE is true.
784
785 If N is positive, searching is forward and LIM must be greater than POS.
786 If N is negative, searching is backward and LIM must be less than POS.
787
788 Returns -x if only N-x occurrences found (x > 0),
789 or else the position at the beginning of the Nth occurrence
790 (if searching backward) or the end (if searching forward).
791
792 POSIX is nonzero if we want full backtracking (POSIX style)
793 for this pattern. 0 means backtrack only enough to get a valid match. */
794
795 static int
796 search_buffer (string, pos, lim, n, RE, trt, inverse_trt, posix)
797 Lisp_Object string;
798 int pos;
799 int lim;
800 int n;
801 int RE;
802 Lisp_Object *trt;
803 Lisp_Object *inverse_trt;
804 int posix;
805 {
806 int len = XSTRING (string)->size;
807 unsigned char *base_pat = XSTRING (string)->data;
808 register int *BM_tab;
809 int *BM_tab_base;
810 register int direction = ((n > 0) ? 1 : -1);
811 register int dirlen;
812 int infinity, limit, k, stride_for_teases;
813 register unsigned char *pat, *cursor, *p_limit;
814 register int i, j;
815 unsigned char *p1, *p2;
816 int s1, s2;
817
818 if (running_asynch_code)
819 save_search_regs ();
820
821 /* Null string is found at starting position. */
822 if (len == 0)
823 {
824 set_search_regs (pos, 0);
825 return pos;
826 }
827
828 /* Searching 0 times means don't move. */
829 if (n == 0)
830 return pos;
831
832 if (RE && !trivial_regexp_p (string))
833 {
834 struct re_pattern_buffer *bufp;
835
836 bufp = compile_pattern (string, &search_regs, trt, posix);
837
838 immediate_quit = 1; /* Quit immediately if user types ^G,
839 because letting this function finish
840 can take too long. */
841 QUIT; /* Do a pending quit right away,
842 to avoid paradoxical behavior */
843 /* Get pointers and sizes of the two strings
844 that make up the visible portion of the buffer. */
845
846 p1 = BEGV_ADDR;
847 s1 = GPT - BEGV;
848 p2 = GAP_END_ADDR;
849 s2 = ZV - GPT;
850 if (s1 < 0)
851 {
852 p2 = p1;
853 s2 = ZV - BEGV;
854 s1 = 0;
855 }
856 if (s2 < 0)
857 {
858 s1 = ZV - BEGV;
859 s2 = 0;
860 }
861 re_match_object = Qnil;
862
863 while (n < 0)
864 {
865 int val;
866 val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
867 pos - BEGV, lim - pos, &search_regs,
868 /* Don't allow match past current point */
869 pos - BEGV);
870 if (val == -2)
871 {
872 matcher_overflow ();
873 }
874 if (val >= 0)
875 {
876 j = BEGV;
877 for (i = 0; i < search_regs.num_regs; i++)
878 if (search_regs.start[i] >= 0)
879 {
880 search_regs.start[i] += j;
881 search_regs.end[i] += j;
882 }
883 XSETBUFFER (last_thing_searched, current_buffer);
884 /* Set pos to the new position. */
885 pos = search_regs.start[0];
886 }
887 else
888 {
889 immediate_quit = 0;
890 return (n);
891 }
892 n++;
893 }
894 while (n > 0)
895 {
896 int val;
897 val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
898 pos - BEGV, lim - pos, &search_regs,
899 lim - BEGV);
900 if (val == -2)
901 {
902 matcher_overflow ();
903 }
904 if (val >= 0)
905 {
906 j = BEGV;
907 for (i = 0; i < search_regs.num_regs; i++)
908 if (search_regs.start[i] >= 0)
909 {
910 search_regs.start[i] += j;
911 search_regs.end[i] += j;
912 }
913 XSETBUFFER (last_thing_searched, current_buffer);
914 pos = search_regs.end[0];
915 }
916 else
917 {
918 immediate_quit = 0;
919 return (0 - n);
920 }
921 n--;
922 }
923 immediate_quit = 0;
924 return (pos);
925 }
926 else /* non-RE case */
927 {
928 #ifdef C_ALLOCA
929 int BM_tab_space[0400];
930 BM_tab = &BM_tab_space[0];
931 #else
932 BM_tab = (int *) alloca (0400 * sizeof (int));
933 #endif
934 {
935 unsigned char *patbuf = (unsigned char *) alloca (len);
936 pat = patbuf;
937 while (--len >= 0)
938 {
939 /* If we got here and the RE flag is set, it's because we're
940 dealing with a regexp known to be trivial, so the backslash
941 just quotes the next character. */
942 if (RE && *base_pat == '\\')
943 {
944 len--;
945 base_pat++;
946 }
947 *pat++ = (trt ? trt[*base_pat++] : *base_pat++);
948 }
949 len = pat - patbuf;
950 pat = base_pat = patbuf;
951 }
952 /* The general approach is that we are going to maintain that we know */
953 /* the first (closest to the present position, in whatever direction */
954 /* we're searching) character that could possibly be the last */
955 /* (furthest from present position) character of a valid match. We */
956 /* advance the state of our knowledge by looking at that character */
957 /* and seeing whether it indeed matches the last character of the */
958 /* pattern. If it does, we take a closer look. If it does not, we */
959 /* move our pointer (to putative last characters) as far as is */
960 /* logically possible. This amount of movement, which I call a */
961 /* stride, will be the length of the pattern if the actual character */
962 /* appears nowhere in the pattern, otherwise it will be the distance */
963 /* from the last occurrence of that character to the end of the */
964 /* pattern. */
965 /* As a coding trick, an enormous stride is coded into the table for */
966 /* characters that match the last character. This allows use of only */
967 /* a single test, a test for having gone past the end of the */
968 /* permissible match region, to test for both possible matches (when */
969 /* the stride goes past the end immediately) and failure to */
970 /* match (where you get nudged past the end one stride at a time). */
971
972 /* Here we make a "mickey mouse" BM table. The stride of the search */
973 /* is determined only by the last character of the putative match. */
974 /* If that character does not match, we will stride the proper */
975 /* distance to propose a match that superimposes it on the last */
976 /* instance of a character that matches it (per trt), or misses */
977 /* it entirely if there is none. */
978
979 dirlen = len * direction;
980 infinity = dirlen - (lim + pos + len + len) * direction;
981 if (direction < 0)
982 pat = (base_pat += len - 1);
983 BM_tab_base = BM_tab;
984 BM_tab += 0400;
985 j = dirlen; /* to get it in a register */
986 /* A character that does not appear in the pattern induces a */
987 /* stride equal to the pattern length. */
988 while (BM_tab_base != BM_tab)
989 {
990 *--BM_tab = j;
991 *--BM_tab = j;
992 *--BM_tab = j;
993 *--BM_tab = j;
994 }
995 i = 0;
996 while (i != infinity)
997 {
998 j = pat[i]; i += direction;
999 if (i == dirlen) i = infinity;
1000 if (trt != 0)
1001 {
1002 k = (j = trt[j]);
1003 if (i == infinity)
1004 stride_for_teases = BM_tab[j];
1005 BM_tab[j] = dirlen - i;
1006 /* A translation table is accompanied by its inverse -- see */
1007 /* comment following downcase_table for details */
1008 while ((j = (unsigned char) inverse_trt[j]) != k)
1009 BM_tab[j] = dirlen - i;
1010 }
1011 else
1012 {
1013 if (i == infinity)
1014 stride_for_teases = BM_tab[j];
1015 BM_tab[j] = dirlen - i;
1016 }
1017 /* stride_for_teases tells how much to stride if we get a */
1018 /* match on the far character but are subsequently */
1019 /* disappointed, by recording what the stride would have been */
1020 /* for that character if the last character had been */
1021 /* different. */
1022 }
1023 infinity = dirlen - infinity;
1024 pos += dirlen - ((direction > 0) ? direction : 0);
1025 /* loop invariant - pos points at where last char (first char if reverse)
1026 of pattern would align in a possible match. */
1027 while (n != 0)
1028 {
1029 /* It's been reported that some (broken) compiler thinks that
1030 Boolean expressions in an arithmetic context are unsigned.
1031 Using an explicit ?1:0 prevents this. */
1032 if ((lim - pos - ((direction > 0) ? 1 : 0)) * direction < 0)
1033 return (n * (0 - direction));
1034 /* First we do the part we can by pointers (maybe nothing) */
1035 QUIT;
1036 pat = base_pat;
1037 limit = pos - dirlen + direction;
1038 limit = ((direction > 0)
1039 ? BUFFER_CEILING_OF (limit)
1040 : BUFFER_FLOOR_OF (limit));
1041 /* LIMIT is now the last (not beyond-last!) value
1042 POS can take on without hitting edge of buffer or the gap. */
1043 limit = ((direction > 0)
1044 ? min (lim - 1, min (limit, pos + 20000))
1045 : max (lim, max (limit, pos - 20000)));
1046 if ((limit - pos) * direction > 20)
1047 {
1048 p_limit = POS_ADDR (limit);
1049 p2 = (cursor = POS_ADDR (pos));
1050 /* In this loop, pos + cursor - p2 is the surrogate for pos */
1051 while (1) /* use one cursor setting as long as i can */
1052 {
1053 if (direction > 0) /* worth duplicating */
1054 {
1055 /* Use signed comparison if appropriate
1056 to make cursor+infinity sure to be > p_limit.
1057 Assuming that the buffer lies in a range of addresses
1058 that are all "positive" (as ints) or all "negative",
1059 either kind of comparison will work as long
1060 as we don't step by infinity. So pick the kind
1061 that works when we do step by infinity. */
1062 if ((EMACS_INT) (p_limit + infinity) > (EMACS_INT) p_limit)
1063 while ((EMACS_INT) cursor <= (EMACS_INT) p_limit)
1064 cursor += BM_tab[*cursor];
1065 else
1066 while ((EMACS_UINT) cursor <= (EMACS_UINT) p_limit)
1067 cursor += BM_tab[*cursor];
1068 }
1069 else
1070 {
1071 if ((EMACS_INT) (p_limit + infinity) < (EMACS_INT) p_limit)
1072 while ((EMACS_INT) cursor >= (EMACS_INT) p_limit)
1073 cursor += BM_tab[*cursor];
1074 else
1075 while ((EMACS_UINT) cursor >= (EMACS_UINT) p_limit)
1076 cursor += BM_tab[*cursor];
1077 }
1078 /* If you are here, cursor is beyond the end of the searched region. */
1079 /* This can happen if you match on the far character of the pattern, */
1080 /* because the "stride" of that character is infinity, a number able */
1081 /* to throw you well beyond the end of the search. It can also */
1082 /* happen if you fail to match within the permitted region and would */
1083 /* otherwise try a character beyond that region */
1084 if ((cursor - p_limit) * direction <= len)
1085 break; /* a small overrun is genuine */
1086 cursor -= infinity; /* large overrun = hit */
1087 i = dirlen - direction;
1088 if (trt != 0)
1089 {
1090 while ((i -= direction) + direction != 0)
1091 if (pat[i] != trt[*(cursor -= direction)])
1092 break;
1093 }
1094 else
1095 {
1096 while ((i -= direction) + direction != 0)
1097 if (pat[i] != *(cursor -= direction))
1098 break;
1099 }
1100 cursor += dirlen - i - direction; /* fix cursor */
1101 if (i + direction == 0)
1102 {
1103 cursor -= direction;
1104
1105 set_search_regs (pos + cursor - p2 + ((direction > 0)
1106 ? 1 - len : 0),
1107 len);
1108
1109 if ((n -= direction) != 0)
1110 cursor += dirlen; /* to resume search */
1111 else
1112 return ((direction > 0)
1113 ? search_regs.end[0] : search_regs.start[0]);
1114 }
1115 else
1116 cursor += stride_for_teases; /* <sigh> we lose - */
1117 }
1118 pos += cursor - p2;
1119 }
1120 else
1121 /* Now we'll pick up a clump that has to be done the hard */
1122 /* way because it covers a discontinuity */
1123 {
1124 limit = ((direction > 0)
1125 ? BUFFER_CEILING_OF (pos - dirlen + 1)
1126 : BUFFER_FLOOR_OF (pos - dirlen - 1));
1127 limit = ((direction > 0)
1128 ? min (limit + len, lim - 1)
1129 : max (limit - len, lim));
1130 /* LIMIT is now the last value POS can have
1131 and still be valid for a possible match. */
1132 while (1)
1133 {
1134 /* This loop can be coded for space rather than */
1135 /* speed because it will usually run only once. */
1136 /* (the reach is at most len + 21, and typically */
1137 /* does not exceed len) */
1138 while ((limit - pos) * direction >= 0)
1139 pos += BM_tab[FETCH_BYTE (pos)];
1140 /* now run the same tests to distinguish going off the */
1141 /* end, a match or a phony match. */
1142 if ((pos - limit) * direction <= len)
1143 break; /* ran off the end */
1144 /* Found what might be a match.
1145 Set POS back to last (first if reverse) char pos. */
1146 pos -= infinity;
1147 i = dirlen - direction;
1148 while ((i -= direction) + direction != 0)
1149 {
1150 pos -= direction;
1151 if (pat[i] != (trt != 0
1152 ? trt[FETCH_BYTE (pos)]
1153 : FETCH_BYTE (pos)))
1154 break;
1155 }
1156 /* Above loop has moved POS part or all the way
1157 back to the first char pos (last char pos if reverse).
1158 Set it once again at the last (first if reverse) char. */
1159 pos += dirlen - i- direction;
1160 if (i + direction == 0)
1161 {
1162 pos -= direction;
1163
1164 set_search_regs (pos + ((direction > 0) ? 1 - len : 0),
1165 len);
1166
1167 if ((n -= direction) != 0)
1168 pos += dirlen; /* to resume search */
1169 else
1170 return ((direction > 0)
1171 ? search_regs.end[0] : search_regs.start[0]);
1172 }
1173 else
1174 pos += stride_for_teases;
1175 }
1176 }
1177 /* We have done one clump. Can we continue? */
1178 if ((lim - pos) * direction < 0)
1179 return ((0 - n) * direction);
1180 }
1181 return pos;
1182 }
1183 }
1184
1185 /* Record beginning BEG and end BEG + LEN
1186 for a match just found in the current buffer. */
1187
1188 static void
1189 set_search_regs (beg, len)
1190 int beg, len;
1191 {
1192 /* Make sure we have registers in which to store
1193 the match position. */
1194 if (search_regs.num_regs == 0)
1195 {
1196 search_regs.start = (regoff_t *) xmalloc (2 * sizeof (regoff_t));
1197 search_regs.end = (regoff_t *) xmalloc (2 * sizeof (regoff_t));
1198 search_regs.num_regs = 2;
1199 }
1200
1201 search_regs.start[0] = beg;
1202 search_regs.end[0] = beg + len;
1203 XSETBUFFER (last_thing_searched, current_buffer);
1204 }
1205 \f
1206 /* Given a string of words separated by word delimiters,
1207 compute a regexp that matches those exact words
1208 separated by arbitrary punctuation. */
1209
1210 static Lisp_Object
1211 wordify (string)
1212 Lisp_Object string;
1213 {
1214 register unsigned char *p, *o;
1215 register int i, len, punct_count = 0, word_count = 0;
1216 Lisp_Object val;
1217
1218 CHECK_STRING (string, 0);
1219 p = XSTRING (string)->data;
1220 len = XSTRING (string)->size;
1221
1222 for (i = 0; i < len; i++)
1223 if (SYNTAX (p[i]) != Sword)
1224 {
1225 punct_count++;
1226 if (i > 0 && SYNTAX (p[i-1]) == Sword) word_count++;
1227 }
1228 if (SYNTAX (p[len-1]) == Sword) word_count++;
1229 if (!word_count) return build_string ("");
1230
1231 val = make_string (p, len - punct_count + 5 * (word_count - 1) + 4);
1232
1233 o = XSTRING (val)->data;
1234 *o++ = '\\';
1235 *o++ = 'b';
1236
1237 for (i = 0; i < len; i++)
1238 if (SYNTAX (p[i]) == Sword)
1239 *o++ = p[i];
1240 else if (i > 0 && SYNTAX (p[i-1]) == Sword && --word_count)
1241 {
1242 *o++ = '\\';
1243 *o++ = 'W';
1244 *o++ = '\\';
1245 *o++ = 'W';
1246 *o++ = '*';
1247 }
1248
1249 *o++ = '\\';
1250 *o++ = 'b';
1251
1252 return val;
1253 }
1254 \f
1255 DEFUN ("search-backward", Fsearch_backward, Ssearch_backward, 1, 4,
1256 "sSearch backward: ",
1257 "Search backward from point for STRING.\n\
1258 Set point to the beginning of the occurrence found, and return point.\n\
1259 An optional second argument bounds the search; it is a buffer position.\n\
1260 The match found must not extend before that position.\n\
1261 Optional third argument, if t, means if fail just return nil (no error).\n\
1262 If not nil and not t, position at limit of search and return nil.\n\
1263 Optional fourth argument is repeat count--search for successive occurrences.\n\
1264 See also the functions `match-beginning', `match-end' and `replace-match'.")
1265 (string, bound, noerror, count)
1266 Lisp_Object string, bound, noerror, count;
1267 {
1268 return search_command (string, bound, noerror, count, -1, 0, 0);
1269 }
1270
1271 DEFUN ("search-forward", Fsearch_forward, Ssearch_forward, 1, 4, "sSearch: ",
1272 "Search forward from point for STRING.\n\
1273 Set point to the end of the occurrence found, and return point.\n\
1274 An optional second argument bounds the search; it is a buffer position.\n\
1275 The match found must not extend after that position. nil is equivalent\n\
1276 to (point-max).\n\
1277 Optional third argument, if t, means if fail just return nil (no error).\n\
1278 If not nil and not t, move to limit of search and return nil.\n\
1279 Optional fourth argument is repeat count--search for successive occurrences.\n\
1280 See also the functions `match-beginning', `match-end' and `replace-match'.")
1281 (string, bound, noerror, count)
1282 Lisp_Object string, bound, noerror, count;
1283 {
1284 return search_command (string, bound, noerror, count, 1, 0, 0);
1285 }
1286
1287 DEFUN ("word-search-backward", Fword_search_backward, Sword_search_backward, 1, 4,
1288 "sWord search backward: ",
1289 "Search backward from point for STRING, ignoring differences in punctuation.\n\
1290 Set point to the beginning of the occurrence found, and return point.\n\
1291 An optional second argument bounds the search; it is a buffer position.\n\
1292 The match found must not extend before that position.\n\
1293 Optional third argument, if t, means if fail just return nil (no error).\n\
1294 If not nil and not t, move to limit of search and return nil.\n\
1295 Optional fourth argument is repeat count--search for successive occurrences.")
1296 (string, bound, noerror, count)
1297 Lisp_Object string, bound, noerror, count;
1298 {
1299 return search_command (wordify (string), bound, noerror, count, -1, 1, 0);
1300 }
1301
1302 DEFUN ("word-search-forward", Fword_search_forward, Sword_search_forward, 1, 4,
1303 "sWord search: ",
1304 "Search forward from point for STRING, ignoring differences in punctuation.\n\
1305 Set point to the end of the occurrence found, and return point.\n\
1306 An optional second argument bounds the search; it is a buffer position.\n\
1307 The match found must not extend after that position.\n\
1308 Optional third argument, if t, means if fail just return nil (no error).\n\
1309 If not nil and not t, move to limit of search and return nil.\n\
1310 Optional fourth argument is repeat count--search for successive occurrences.")
1311 (string, bound, noerror, count)
1312 Lisp_Object string, bound, noerror, count;
1313 {
1314 return search_command (wordify (string), bound, noerror, count, 1, 1, 0);
1315 }
1316
1317 DEFUN ("re-search-backward", Fre_search_backward, Sre_search_backward, 1, 4,
1318 "sRE search backward: ",
1319 "Search backward from point for match for regular expression REGEXP.\n\
1320 Set point to the beginning of the match, and return point.\n\
1321 The match found is the one starting last in the buffer\n\
1322 and yet ending before the origin of the search.\n\
1323 An optional second argument bounds the search; it is a buffer position.\n\
1324 The match found must start at or after that position.\n\
1325 Optional third argument, if t, means if fail just return nil (no error).\n\
1326 If not nil and not t, move to limit of search and return nil.\n\
1327 Optional fourth argument is repeat count--search for successive occurrences.\n\
1328 See also the functions `match-beginning', `match-end' and `replace-match'.")
1329 (regexp, bound, noerror, count)
1330 Lisp_Object regexp, bound, noerror, count;
1331 {
1332 return search_command (regexp, bound, noerror, count, -1, 1, 0);
1333 }
1334
1335 DEFUN ("re-search-forward", Fre_search_forward, Sre_search_forward, 1, 4,
1336 "sRE search: ",
1337 "Search forward from point for regular expression REGEXP.\n\
1338 Set point to the end of the occurrence found, and return point.\n\
1339 An optional second argument bounds the search; it is a buffer position.\n\
1340 The match found must not extend after that position.\n\
1341 Optional third argument, if t, means if fail just return nil (no error).\n\
1342 If not nil and not t, move to limit of search and return nil.\n\
1343 Optional fourth argument is repeat count--search for successive occurrences.\n\
1344 See also the functions `match-beginning', `match-end' and `replace-match'.")
1345 (regexp, bound, noerror, count)
1346 Lisp_Object regexp, bound, noerror, count;
1347 {
1348 return search_command (regexp, bound, noerror, count, 1, 1, 0);
1349 }
1350
1351 DEFUN ("posix-search-backward", Fposix_search_backward, Sposix_search_backward, 1, 4,
1352 "sPosix search backward: ",
1353 "Search backward from point for match for regular expression REGEXP.\n\
1354 Find the longest match in accord with Posix regular expression rules.\n\
1355 Set point to the beginning of the match, and return point.\n\
1356 The match found is the one starting last in the buffer\n\
1357 and yet ending before the origin of the search.\n\
1358 An optional second argument bounds the search; it is a buffer position.\n\
1359 The match found must start at or after that position.\n\
1360 Optional third argument, if t, means if fail just return nil (no error).\n\
1361 If not nil and not t, move to limit of search and return nil.\n\
1362 Optional fourth argument is repeat count--search for successive occurrences.\n\
1363 See also the functions `match-beginning', `match-end' and `replace-match'.")
1364 (regexp, bound, noerror, count)
1365 Lisp_Object regexp, bound, noerror, count;
1366 {
1367 return search_command (regexp, bound, noerror, count, -1, 1, 1);
1368 }
1369
1370 DEFUN ("posix-search-forward", Fposix_search_forward, Sposix_search_forward, 1, 4,
1371 "sPosix search: ",
1372 "Search forward from point for regular expression REGEXP.\n\
1373 Find the longest match in accord with Posix regular expression rules.\n\
1374 Set point to the end of the occurrence found, and return point.\n\
1375 An optional second argument bounds the search; it is a buffer position.\n\
1376 The match found must not extend after that position.\n\
1377 Optional third argument, if t, means if fail just return nil (no error).\n\
1378 If not nil and not t, move to limit of search and return nil.\n\
1379 Optional fourth argument is repeat count--search for successive occurrences.\n\
1380 See also the functions `match-beginning', `match-end' and `replace-match'.")
1381 (regexp, bound, noerror, count)
1382 Lisp_Object regexp, bound, noerror, count;
1383 {
1384 return search_command (regexp, bound, noerror, count, 1, 1, 1);
1385 }
1386 \f
1387 DEFUN ("replace-match", Freplace_match, Sreplace_match, 1, 5, 0,
1388 "Replace text matched by last search with NEWTEXT.\n\
1389 If second arg FIXEDCASE is non-nil, do not alter case of replacement text.\n\
1390 Otherwise maybe capitalize the whole text, or maybe just word initials,\n\
1391 based on the replaced text.\n\
1392 If the replaced text has only capital letters\n\
1393 and has at least one multiletter word, convert NEWTEXT to all caps.\n\
1394 If the replaced text has at least one word starting with a capital letter,\n\
1395 then capitalize each word in NEWTEXT.\n\n\
1396 If third arg LITERAL is non-nil, insert NEWTEXT literally.\n\
1397 Otherwise treat `\\' as special:\n\
1398 `\\&' in NEWTEXT means substitute original matched text.\n\
1399 `\\N' means substitute what matched the Nth `\\(...\\)'.\n\
1400 If Nth parens didn't match, substitute nothing.\n\
1401 `\\\\' means insert one `\\'.\n\
1402 FIXEDCASE and LITERAL are optional arguments.\n\
1403 Leaves point at end of replacement text.\n\
1404 \n\
1405 The optional fourth argument STRING can be a string to modify.\n\
1406 In that case, this function creates and returns a new string\n\
1407 which is made by replacing the part of STRING that was matched.\n\
1408 \n\
1409 The optional fifth argument SUBEXP specifies a subexpression of the match.\n\
1410 It says to replace just that subexpression instead of the whole match.\n\
1411 This is useful only after a regular expression search or match\n\
1412 since only regular expressions have distinguished subexpressions.")
1413 (newtext, fixedcase, literal, string, subexp)
1414 Lisp_Object newtext, fixedcase, literal, string, subexp;
1415 {
1416 enum { nochange, all_caps, cap_initial } case_action;
1417 register int pos, last;
1418 int some_multiletter_word;
1419 int some_lowercase;
1420 int some_uppercase;
1421 int some_nonuppercase_initial;
1422 register int c, prevc;
1423 int inslen;
1424 int sub;
1425
1426 CHECK_STRING (newtext, 0);
1427
1428 if (! NILP (string))
1429 CHECK_STRING (string, 4);
1430
1431 case_action = nochange; /* We tried an initialization */
1432 /* but some C compilers blew it */
1433
1434 if (search_regs.num_regs <= 0)
1435 error ("replace-match called before any match found");
1436
1437 if (NILP (subexp))
1438 sub = 0;
1439 else
1440 {
1441 CHECK_NUMBER (subexp, 3);
1442 sub = XINT (subexp);
1443 if (sub < 0 || sub >= search_regs.num_regs)
1444 args_out_of_range (subexp, make_number (search_regs.num_regs));
1445 }
1446
1447 if (NILP (string))
1448 {
1449 if (search_regs.start[sub] < BEGV
1450 || search_regs.start[sub] > search_regs.end[sub]
1451 || search_regs.end[sub] > ZV)
1452 args_out_of_range (make_number (search_regs.start[sub]),
1453 make_number (search_regs.end[sub]));
1454 }
1455 else
1456 {
1457 if (search_regs.start[sub] < 0
1458 || search_regs.start[sub] > search_regs.end[sub]
1459 || search_regs.end[sub] > XSTRING (string)->size)
1460 args_out_of_range (make_number (search_regs.start[sub]),
1461 make_number (search_regs.end[sub]));
1462 }
1463
1464 if (NILP (fixedcase))
1465 {
1466 /* Decide how to casify by examining the matched text. */
1467
1468 last = search_regs.end[sub];
1469 prevc = '\n';
1470 case_action = all_caps;
1471
1472 /* some_multiletter_word is set nonzero if any original word
1473 is more than one letter long. */
1474 some_multiletter_word = 0;
1475 some_lowercase = 0;
1476 some_nonuppercase_initial = 0;
1477 some_uppercase = 0;
1478
1479 for (pos = search_regs.start[sub]; pos < last; pos++)
1480 {
1481 if (NILP (string))
1482 c = FETCH_BYTE (pos);
1483 else
1484 c = XSTRING (string)->data[pos];
1485
1486 if (LOWERCASEP (c))
1487 {
1488 /* Cannot be all caps if any original char is lower case */
1489
1490 some_lowercase = 1;
1491 if (SYNTAX (prevc) != Sword)
1492 some_nonuppercase_initial = 1;
1493 else
1494 some_multiletter_word = 1;
1495 }
1496 else if (!NOCASEP (c))
1497 {
1498 some_uppercase = 1;
1499 if (SYNTAX (prevc) != Sword)
1500 ;
1501 else
1502 some_multiletter_word = 1;
1503 }
1504 else
1505 {
1506 /* If the initial is a caseless word constituent,
1507 treat that like a lowercase initial. */
1508 if (SYNTAX (prevc) != Sword)
1509 some_nonuppercase_initial = 1;
1510 }
1511
1512 prevc = c;
1513 }
1514
1515 /* Convert to all caps if the old text is all caps
1516 and has at least one multiletter word. */
1517 if (! some_lowercase && some_multiletter_word)
1518 case_action = all_caps;
1519 /* Capitalize each word, if the old text has all capitalized words. */
1520 else if (!some_nonuppercase_initial && some_multiletter_word)
1521 case_action = cap_initial;
1522 else if (!some_nonuppercase_initial && some_uppercase)
1523 /* Should x -> yz, operating on X, give Yz or YZ?
1524 We'll assume the latter. */
1525 case_action = all_caps;
1526 else
1527 case_action = nochange;
1528 }
1529
1530 /* Do replacement in a string. */
1531 if (!NILP (string))
1532 {
1533 Lisp_Object before, after;
1534
1535 before = Fsubstring (string, make_number (0),
1536 make_number (search_regs.start[sub]));
1537 after = Fsubstring (string, make_number (search_regs.end[sub]), Qnil);
1538
1539 /* Substitute parts of the match into NEWTEXT
1540 if desired. */
1541 if (NILP (literal))
1542 {
1543 int lastpos = -1;
1544 /* We build up the substituted string in ACCUM. */
1545 Lisp_Object accum;
1546 Lisp_Object middle;
1547
1548 accum = Qnil;
1549
1550 for (pos = 0; pos < XSTRING (newtext)->size; pos++)
1551 {
1552 int substart = -1;
1553 int subend;
1554 int delbackslash = 0;
1555
1556 c = XSTRING (newtext)->data[pos];
1557 if (c == '\\')
1558 {
1559 c = XSTRING (newtext)->data[++pos];
1560 if (c == '&')
1561 {
1562 substart = search_regs.start[sub];
1563 subend = search_regs.end[sub];
1564 }
1565 else if (c >= '1' && c <= '9' && c <= search_regs.num_regs + '0')
1566 {
1567 if (search_regs.start[c - '0'] >= 0)
1568 {
1569 substart = search_regs.start[c - '0'];
1570 subend = search_regs.end[c - '0'];
1571 }
1572 }
1573 else if (c == '\\')
1574 delbackslash = 1;
1575 else
1576 error ("Invalid use of `\\' in replacement text");
1577 }
1578 if (substart >= 0)
1579 {
1580 if (pos - 1 != lastpos + 1)
1581 middle = Fsubstring (newtext,
1582 make_number (lastpos + 1),
1583 make_number (pos - 1));
1584 else
1585 middle = Qnil;
1586 accum = concat3 (accum, middle,
1587 Fsubstring (string, make_number (substart),
1588 make_number (subend)));
1589 lastpos = pos;
1590 }
1591 else if (delbackslash)
1592 {
1593 middle = Fsubstring (newtext, make_number (lastpos + 1),
1594 make_number (pos));
1595 accum = concat2 (accum, middle);
1596 lastpos = pos;
1597 }
1598 }
1599
1600 if (pos != lastpos + 1)
1601 middle = Fsubstring (newtext, make_number (lastpos + 1),
1602 make_number (pos));
1603 else
1604 middle = Qnil;
1605
1606 newtext = concat2 (accum, middle);
1607 }
1608
1609 /* Do case substitution in NEWTEXT if desired. */
1610 if (case_action == all_caps)
1611 newtext = Fupcase (newtext);
1612 else if (case_action == cap_initial)
1613 newtext = Fupcase_initials (newtext);
1614
1615 return concat3 (before, newtext, after);
1616 }
1617
1618 /* We insert the replacement text before the old text, and then
1619 delete the original text. This means that markers at the
1620 beginning or end of the original will float to the corresponding
1621 position in the replacement. */
1622 SET_PT (search_regs.start[sub]);
1623 if (!NILP (literal))
1624 Finsert_and_inherit (1, &newtext);
1625 else
1626 {
1627 struct gcpro gcpro1;
1628 GCPRO1 (newtext);
1629
1630 for (pos = 0; pos < XSTRING (newtext)->size; pos++)
1631 {
1632 int offset = PT - search_regs.start[sub];
1633
1634 c = XSTRING (newtext)->data[pos];
1635 if (c == '\\')
1636 {
1637 c = XSTRING (newtext)->data[++pos];
1638 if (c == '&')
1639 Finsert_buffer_substring
1640 (Fcurrent_buffer (),
1641 make_number (search_regs.start[sub] + offset),
1642 make_number (search_regs.end[sub] + offset));
1643 else if (c >= '1' && c <= '9' && c <= search_regs.num_regs + '0')
1644 {
1645 if (search_regs.start[c - '0'] >= 1)
1646 Finsert_buffer_substring
1647 (Fcurrent_buffer (),
1648 make_number (search_regs.start[c - '0'] + offset),
1649 make_number (search_regs.end[c - '0'] + offset));
1650 }
1651 else if (c == '\\')
1652 insert_char (c);
1653 else
1654 error ("Invalid use of `\\' in replacement text");
1655 }
1656 else
1657 insert_char (c);
1658 }
1659 UNGCPRO;
1660 }
1661
1662 inslen = PT - (search_regs.start[sub]);
1663 del_range (search_regs.start[sub] + inslen, search_regs.end[sub] + inslen);
1664
1665 if (case_action == all_caps)
1666 Fupcase_region (make_number (PT - inslen), make_number (PT));
1667 else if (case_action == cap_initial)
1668 Fupcase_initials_region (make_number (PT - inslen), make_number (PT));
1669 return Qnil;
1670 }
1671 \f
1672 static Lisp_Object
1673 match_limit (num, beginningp)
1674 Lisp_Object num;
1675 int beginningp;
1676 {
1677 register int n;
1678
1679 CHECK_NUMBER (num, 0);
1680 n = XINT (num);
1681 if (n < 0 || n >= search_regs.num_regs)
1682 args_out_of_range (num, make_number (search_regs.num_regs));
1683 if (search_regs.num_regs <= 0
1684 || search_regs.start[n] < 0)
1685 return Qnil;
1686 return (make_number ((beginningp) ? search_regs.start[n]
1687 : search_regs.end[n]));
1688 }
1689
1690 DEFUN ("match-beginning", Fmatch_beginning, Smatch_beginning, 1, 1, 0,
1691 "Return position of start of text matched by last search.\n\
1692 SUBEXP, a number, specifies which parenthesized expression in the last\n\
1693 regexp.\n\
1694 Value is nil if SUBEXPth pair didn't match, or there were less than\n\
1695 SUBEXP pairs.\n\
1696 Zero means the entire text matched by the whole regexp or whole string.")
1697 (subexp)
1698 Lisp_Object subexp;
1699 {
1700 return match_limit (subexp, 1);
1701 }
1702
1703 DEFUN ("match-end", Fmatch_end, Smatch_end, 1, 1, 0,
1704 "Return position of end of text matched by last search.\n\
1705 SUBEXP, a number, specifies which parenthesized expression in the last\n\
1706 regexp.\n\
1707 Value is nil if SUBEXPth pair didn't match, or there were less than\n\
1708 SUBEXP pairs.\n\
1709 Zero means the entire text matched by the whole regexp or whole string.")
1710 (subexp)
1711 Lisp_Object subexp;
1712 {
1713 return match_limit (subexp, 0);
1714 }
1715
1716 DEFUN ("match-data", Fmatch_data, Smatch_data, 0, 2, 0,
1717 "Return a list containing all info on what the last search matched.\n\
1718 Element 2N is `(match-beginning N)'; element 2N + 1 is `(match-end N)'.\n\
1719 All the elements are markers or nil (nil if the Nth pair didn't match)\n\
1720 if the last match was on a buffer; integers or nil if a string was matched.\n\
1721 Use `store-match-data' to reinstate the data in this list.\n\
1722 \n\
1723 If INTEGERS (the optional first argument) is non-nil, always use integers\n\
1724 \(rather than markers) to represent buffer positions.\n\
1725 If REUSE is a list, reuse it as part of the value. If REUSE is long enough\n\
1726 to hold all the values, and if INTEGERS is non-nil, no consing is done.")
1727 (integers, reuse)
1728 Lisp_Object integers, reuse;
1729 {
1730 Lisp_Object tail, prev;
1731 Lisp_Object *data;
1732 int i, len;
1733
1734 if (NILP (last_thing_searched))
1735 return Qnil;
1736
1737 data = (Lisp_Object *) alloca ((2 * search_regs.num_regs)
1738 * sizeof (Lisp_Object));
1739
1740 len = -1;
1741 for (i = 0; i < search_regs.num_regs; i++)
1742 {
1743 int start = search_regs.start[i];
1744 if (start >= 0)
1745 {
1746 if (EQ (last_thing_searched, Qt)
1747 || ! NILP (integers))
1748 {
1749 XSETFASTINT (data[2 * i], start);
1750 XSETFASTINT (data[2 * i + 1], search_regs.end[i]);
1751 }
1752 else if (BUFFERP (last_thing_searched))
1753 {
1754 data[2 * i] = Fmake_marker ();
1755 Fset_marker (data[2 * i],
1756 make_number (start),
1757 last_thing_searched);
1758 data[2 * i + 1] = Fmake_marker ();
1759 Fset_marker (data[2 * i + 1],
1760 make_number (search_regs.end[i]),
1761 last_thing_searched);
1762 }
1763 else
1764 /* last_thing_searched must always be Qt, a buffer, or Qnil. */
1765 abort ();
1766
1767 len = i;
1768 }
1769 else
1770 data[2 * i] = data [2 * i + 1] = Qnil;
1771 }
1772
1773 /* If REUSE is not usable, cons up the values and return them. */
1774 if (! CONSP (reuse))
1775 return Flist (2 * len + 2, data);
1776
1777 /* If REUSE is a list, store as many value elements as will fit
1778 into the elements of REUSE. */
1779 for (i = 0, tail = reuse; CONSP (tail);
1780 i++, tail = XCONS (tail)->cdr)
1781 {
1782 if (i < 2 * len + 2)
1783 XCONS (tail)->car = data[i];
1784 else
1785 XCONS (tail)->car = Qnil;
1786 prev = tail;
1787 }
1788
1789 /* If we couldn't fit all value elements into REUSE,
1790 cons up the rest of them and add them to the end of REUSE. */
1791 if (i < 2 * len + 2)
1792 XCONS (prev)->cdr = Flist (2 * len + 2 - i, data + i);
1793
1794 return reuse;
1795 }
1796
1797
1798 DEFUN ("store-match-data", Fstore_match_data, Sstore_match_data, 1, 1, 0,
1799 "Set internal data on last search match from elements of LIST.\n\
1800 LIST should have been created by calling `match-data' previously.")
1801 (list)
1802 register Lisp_Object list;
1803 {
1804 register int i;
1805 register Lisp_Object marker;
1806
1807 if (running_asynch_code)
1808 save_search_regs ();
1809
1810 if (!CONSP (list) && !NILP (list))
1811 list = wrong_type_argument (Qconsp, list);
1812
1813 /* Unless we find a marker with a buffer in LIST, assume that this
1814 match data came from a string. */
1815 last_thing_searched = Qt;
1816
1817 /* Allocate registers if they don't already exist. */
1818 {
1819 int length = XFASTINT (Flength (list)) / 2;
1820
1821 if (length > search_regs.num_regs)
1822 {
1823 if (search_regs.num_regs == 0)
1824 {
1825 search_regs.start
1826 = (regoff_t *) xmalloc (length * sizeof (regoff_t));
1827 search_regs.end
1828 = (regoff_t *) xmalloc (length * sizeof (regoff_t));
1829 }
1830 else
1831 {
1832 search_regs.start
1833 = (regoff_t *) xrealloc (search_regs.start,
1834 length * sizeof (regoff_t));
1835 search_regs.end
1836 = (regoff_t *) xrealloc (search_regs.end,
1837 length * sizeof (regoff_t));
1838 }
1839
1840 search_regs.num_regs = length;
1841 }
1842 }
1843
1844 for (i = 0; i < search_regs.num_regs; i++)
1845 {
1846 marker = Fcar (list);
1847 if (NILP (marker))
1848 {
1849 search_regs.start[i] = -1;
1850 list = Fcdr (list);
1851 }
1852 else
1853 {
1854 if (MARKERP (marker))
1855 {
1856 if (XMARKER (marker)->buffer == 0)
1857 XSETFASTINT (marker, 0);
1858 else
1859 XSETBUFFER (last_thing_searched, XMARKER (marker)->buffer);
1860 }
1861
1862 CHECK_NUMBER_COERCE_MARKER (marker, 0);
1863 search_regs.start[i] = XINT (marker);
1864 list = Fcdr (list);
1865
1866 marker = Fcar (list);
1867 if (MARKERP (marker) && XMARKER (marker)->buffer == 0)
1868 XSETFASTINT (marker, 0);
1869
1870 CHECK_NUMBER_COERCE_MARKER (marker, 0);
1871 search_regs.end[i] = XINT (marker);
1872 }
1873 list = Fcdr (list);
1874 }
1875
1876 return Qnil;
1877 }
1878
1879 /* If non-zero the match data have been saved in saved_search_regs
1880 during the execution of a sentinel or filter. */
1881 static int search_regs_saved;
1882 static struct re_registers saved_search_regs;
1883
1884 /* Called from Flooking_at, Fstring_match, search_buffer, Fstore_match_data
1885 if asynchronous code (filter or sentinel) is running. */
1886 static void
1887 save_search_regs ()
1888 {
1889 if (!search_regs_saved)
1890 {
1891 saved_search_regs.num_regs = search_regs.num_regs;
1892 saved_search_regs.start = search_regs.start;
1893 saved_search_regs.end = search_regs.end;
1894 search_regs.num_regs = 0;
1895 search_regs.start = 0;
1896 search_regs.end = 0;
1897
1898 search_regs_saved = 1;
1899 }
1900 }
1901
1902 /* Called upon exit from filters and sentinels. */
1903 void
1904 restore_match_data ()
1905 {
1906 if (search_regs_saved)
1907 {
1908 if (search_regs.num_regs > 0)
1909 {
1910 xfree (search_regs.start);
1911 xfree (search_regs.end);
1912 }
1913 search_regs.num_regs = saved_search_regs.num_regs;
1914 search_regs.start = saved_search_regs.start;
1915 search_regs.end = saved_search_regs.end;
1916
1917 search_regs_saved = 0;
1918 }
1919 }
1920
1921 /* Quote a string to inactivate reg-expr chars */
1922
1923 DEFUN ("regexp-quote", Fregexp_quote, Sregexp_quote, 1, 1, 0,
1924 "Return a regexp string which matches exactly STRING and nothing else.")
1925 (string)
1926 Lisp_Object string;
1927 {
1928 register unsigned char *in, *out, *end;
1929 register unsigned char *temp;
1930
1931 CHECK_STRING (string, 0);
1932
1933 temp = (unsigned char *) alloca (XSTRING (string)->size * 2);
1934
1935 /* Now copy the data into the new string, inserting escapes. */
1936
1937 in = XSTRING (string)->data;
1938 end = in + XSTRING (string)->size;
1939 out = temp;
1940
1941 for (; in != end; in++)
1942 {
1943 if (*in == '[' || *in == ']'
1944 || *in == '*' || *in == '.' || *in == '\\'
1945 || *in == '?' || *in == '+'
1946 || *in == '^' || *in == '$')
1947 *out++ = '\\';
1948 *out++ = *in;
1949 }
1950
1951 return make_string (temp, out - temp);
1952 }
1953 \f
1954 syms_of_search ()
1955 {
1956 register int i;
1957
1958 for (i = 0; i < REGEXP_CACHE_SIZE; ++i)
1959 {
1960 searchbufs[i].buf.allocated = 100;
1961 searchbufs[i].buf.buffer = (unsigned char *) malloc (100);
1962 searchbufs[i].buf.fastmap = searchbufs[i].fastmap;
1963 searchbufs[i].regexp = Qnil;
1964 staticpro (&searchbufs[i].regexp);
1965 searchbufs[i].next = (i == REGEXP_CACHE_SIZE-1 ? 0 : &searchbufs[i+1]);
1966 }
1967 searchbuf_head = &searchbufs[0];
1968
1969 Qsearch_failed = intern ("search-failed");
1970 staticpro (&Qsearch_failed);
1971 Qinvalid_regexp = intern ("invalid-regexp");
1972 staticpro (&Qinvalid_regexp);
1973
1974 Fput (Qsearch_failed, Qerror_conditions,
1975 Fcons (Qsearch_failed, Fcons (Qerror, Qnil)));
1976 Fput (Qsearch_failed, Qerror_message,
1977 build_string ("Search failed"));
1978
1979 Fput (Qinvalid_regexp, Qerror_conditions,
1980 Fcons (Qinvalid_regexp, Fcons (Qerror, Qnil)));
1981 Fput (Qinvalid_regexp, Qerror_message,
1982 build_string ("Invalid regexp"));
1983
1984 last_thing_searched = Qnil;
1985 staticpro (&last_thing_searched);
1986
1987 defsubr (&Slooking_at);
1988 defsubr (&Sposix_looking_at);
1989 defsubr (&Sstring_match);
1990 defsubr (&Sposix_string_match);
1991 defsubr (&Ssearch_forward);
1992 defsubr (&Ssearch_backward);
1993 defsubr (&Sword_search_forward);
1994 defsubr (&Sword_search_backward);
1995 defsubr (&Sre_search_forward);
1996 defsubr (&Sre_search_backward);
1997 defsubr (&Sposix_search_forward);
1998 defsubr (&Sposix_search_backward);
1999 defsubr (&Sreplace_match);
2000 defsubr (&Smatch_beginning);
2001 defsubr (&Smatch_end);
2002 defsubr (&Smatch_data);
2003 defsubr (&Sstore_match_data);
2004 defsubr (&Sregexp_quote);
2005 }