]> code.delx.au - gnu-emacs/blob - src/search.c
(Freplace_match): If opoint is 0, that's relative to ZV.
[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 ? XCHAR_TABLE (DOWNCASE_TABLE)->contents : 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 ? XCHAR_TABLE (DOWNCASE_TABLE)->contents : 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 ? XINT (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 = XINT (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) XINT (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] != XINT (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 ? XINT (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 int opoint, newpoint;
1426
1427 CHECK_STRING (newtext, 0);
1428
1429 if (! NILP (string))
1430 CHECK_STRING (string, 4);
1431
1432 case_action = nochange; /* We tried an initialization */
1433 /* but some C compilers blew it */
1434
1435 if (search_regs.num_regs <= 0)
1436 error ("replace-match called before any match found");
1437
1438 if (NILP (subexp))
1439 sub = 0;
1440 else
1441 {
1442 CHECK_NUMBER (subexp, 3);
1443 sub = XINT (subexp);
1444 if (sub < 0 || sub >= search_regs.num_regs)
1445 args_out_of_range (subexp, make_number (search_regs.num_regs));
1446 }
1447
1448 if (NILP (string))
1449 {
1450 if (search_regs.start[sub] < BEGV
1451 || search_regs.start[sub] > search_regs.end[sub]
1452 || search_regs.end[sub] > ZV)
1453 args_out_of_range (make_number (search_regs.start[sub]),
1454 make_number (search_regs.end[sub]));
1455 }
1456 else
1457 {
1458 if (search_regs.start[sub] < 0
1459 || search_regs.start[sub] > search_regs.end[sub]
1460 || search_regs.end[sub] > XSTRING (string)->size)
1461 args_out_of_range (make_number (search_regs.start[sub]),
1462 make_number (search_regs.end[sub]));
1463 }
1464
1465 if (NILP (fixedcase))
1466 {
1467 /* Decide how to casify by examining the matched text. */
1468
1469 last = search_regs.end[sub];
1470 prevc = '\n';
1471 case_action = all_caps;
1472
1473 /* some_multiletter_word is set nonzero if any original word
1474 is more than one letter long. */
1475 some_multiletter_word = 0;
1476 some_lowercase = 0;
1477 some_nonuppercase_initial = 0;
1478 some_uppercase = 0;
1479
1480 for (pos = search_regs.start[sub]; pos < last; pos++)
1481 {
1482 if (NILP (string))
1483 c = FETCH_BYTE (pos);
1484 else
1485 c = XSTRING (string)->data[pos];
1486
1487 if (LOWERCASEP (c))
1488 {
1489 /* Cannot be all caps if any original char is lower case */
1490
1491 some_lowercase = 1;
1492 if (SYNTAX (prevc) != Sword)
1493 some_nonuppercase_initial = 1;
1494 else
1495 some_multiletter_word = 1;
1496 }
1497 else if (!NOCASEP (c))
1498 {
1499 some_uppercase = 1;
1500 if (SYNTAX (prevc) != Sword)
1501 ;
1502 else
1503 some_multiletter_word = 1;
1504 }
1505 else
1506 {
1507 /* If the initial is a caseless word constituent,
1508 treat that like a lowercase initial. */
1509 if (SYNTAX (prevc) != Sword)
1510 some_nonuppercase_initial = 1;
1511 }
1512
1513 prevc = c;
1514 }
1515
1516 /* Convert to all caps if the old text is all caps
1517 and has at least one multiletter word. */
1518 if (! some_lowercase && some_multiletter_word)
1519 case_action = all_caps;
1520 /* Capitalize each word, if the old text has all capitalized words. */
1521 else if (!some_nonuppercase_initial && some_multiletter_word)
1522 case_action = cap_initial;
1523 else if (!some_nonuppercase_initial && some_uppercase)
1524 /* Should x -> yz, operating on X, give Yz or YZ?
1525 We'll assume the latter. */
1526 case_action = all_caps;
1527 else
1528 case_action = nochange;
1529 }
1530
1531 /* Do replacement in a string. */
1532 if (!NILP (string))
1533 {
1534 Lisp_Object before, after;
1535
1536 before = Fsubstring (string, make_number (0),
1537 make_number (search_regs.start[sub]));
1538 after = Fsubstring (string, make_number (search_regs.end[sub]), Qnil);
1539
1540 /* Substitute parts of the match into NEWTEXT
1541 if desired. */
1542 if (NILP (literal))
1543 {
1544 int lastpos = -1;
1545 /* We build up the substituted string in ACCUM. */
1546 Lisp_Object accum;
1547 Lisp_Object middle;
1548
1549 accum = Qnil;
1550
1551 for (pos = 0; pos < XSTRING (newtext)->size; pos++)
1552 {
1553 int substart = -1;
1554 int subend;
1555 int delbackslash = 0;
1556
1557 c = XSTRING (newtext)->data[pos];
1558 if (c == '\\')
1559 {
1560 c = XSTRING (newtext)->data[++pos];
1561 if (c == '&')
1562 {
1563 substart = search_regs.start[sub];
1564 subend = search_regs.end[sub];
1565 }
1566 else if (c >= '1' && c <= '9' && c <= search_regs.num_regs + '0')
1567 {
1568 if (search_regs.start[c - '0'] >= 0)
1569 {
1570 substart = search_regs.start[c - '0'];
1571 subend = search_regs.end[c - '0'];
1572 }
1573 }
1574 else if (c == '\\')
1575 delbackslash = 1;
1576 else
1577 error ("Invalid use of `\\' in replacement text");
1578 }
1579 if (substart >= 0)
1580 {
1581 if (pos - 1 != lastpos + 1)
1582 middle = Fsubstring (newtext,
1583 make_number (lastpos + 1),
1584 make_number (pos - 1));
1585 else
1586 middle = Qnil;
1587 accum = concat3 (accum, middle,
1588 Fsubstring (string, make_number (substart),
1589 make_number (subend)));
1590 lastpos = pos;
1591 }
1592 else if (delbackslash)
1593 {
1594 middle = Fsubstring (newtext, make_number (lastpos + 1),
1595 make_number (pos));
1596 accum = concat2 (accum, middle);
1597 lastpos = pos;
1598 }
1599 }
1600
1601 if (pos != lastpos + 1)
1602 middle = Fsubstring (newtext, make_number (lastpos + 1),
1603 make_number (pos));
1604 else
1605 middle = Qnil;
1606
1607 newtext = concat2 (accum, middle);
1608 }
1609
1610 /* Do case substitution in NEWTEXT if desired. */
1611 if (case_action == all_caps)
1612 newtext = Fupcase (newtext);
1613 else if (case_action == cap_initial)
1614 newtext = Fupcase_initials (newtext);
1615
1616 return concat3 (before, newtext, after);
1617 }
1618
1619 /* Record point, the move (quietly) to the start of the match. */
1620 if (PT > search_regs.start[sub])
1621 opoint = PT - ZV;
1622 else
1623 opoint = PT;
1624
1625 temp_set_point (search_regs.start[sub], current_buffer);
1626
1627 /* We insert the replacement text before the old text, and then
1628 delete the original text. This means that markers at the
1629 beginning or end of the original will float to the corresponding
1630 position in the replacement. */
1631 if (!NILP (literal))
1632 Finsert_and_inherit (1, &newtext);
1633 else
1634 {
1635 struct gcpro gcpro1;
1636 GCPRO1 (newtext);
1637
1638 for (pos = 0; pos < XSTRING (newtext)->size; pos++)
1639 {
1640 int offset = PT - search_regs.start[sub];
1641
1642 c = XSTRING (newtext)->data[pos];
1643 if (c == '\\')
1644 {
1645 c = XSTRING (newtext)->data[++pos];
1646 if (c == '&')
1647 Finsert_buffer_substring
1648 (Fcurrent_buffer (),
1649 make_number (search_regs.start[sub] + offset),
1650 make_number (search_regs.end[sub] + offset));
1651 else if (c >= '1' && c <= '9' && c <= search_regs.num_regs + '0')
1652 {
1653 if (search_regs.start[c - '0'] >= 1)
1654 Finsert_buffer_substring
1655 (Fcurrent_buffer (),
1656 make_number (search_regs.start[c - '0'] + offset),
1657 make_number (search_regs.end[c - '0'] + offset));
1658 }
1659 else if (c == '\\')
1660 insert_char (c);
1661 else
1662 error ("Invalid use of `\\' in replacement text");
1663 }
1664 else
1665 insert_char (c);
1666 }
1667 UNGCPRO;
1668 }
1669
1670 inslen = PT - (search_regs.start[sub]);
1671 del_range (search_regs.start[sub] + inslen, search_regs.end[sub] + inslen);
1672
1673 if (case_action == all_caps)
1674 Fupcase_region (make_number (PT - inslen), make_number (PT));
1675 else if (case_action == cap_initial)
1676 Fupcase_initials_region (make_number (PT - inslen), make_number (PT));
1677
1678 newpoint = PT;
1679
1680 /* Put point back where it was in the text. */
1681 if (opoint <= 0)
1682 temp_set_point (opoint + ZV, current_buffer);
1683 else
1684 temp_set_point (opoint, current_buffer);
1685
1686 /* Now move point "officially" to the start of the inserted replacement. */
1687 move_if_not_intangible (newpoint);
1688
1689 return Qnil;
1690 }
1691 \f
1692 static Lisp_Object
1693 match_limit (num, beginningp)
1694 Lisp_Object num;
1695 int beginningp;
1696 {
1697 register int n;
1698
1699 CHECK_NUMBER (num, 0);
1700 n = XINT (num);
1701 if (n < 0 || n >= search_regs.num_regs)
1702 args_out_of_range (num, make_number (search_regs.num_regs));
1703 if (search_regs.num_regs <= 0
1704 || search_regs.start[n] < 0)
1705 return Qnil;
1706 return (make_number ((beginningp) ? search_regs.start[n]
1707 : search_regs.end[n]));
1708 }
1709
1710 DEFUN ("match-beginning", Fmatch_beginning, Smatch_beginning, 1, 1, 0,
1711 "Return position of start of text matched by last search.\n\
1712 SUBEXP, a number, specifies which parenthesized expression in the last\n\
1713 regexp.\n\
1714 Value is nil if SUBEXPth pair didn't match, or there were less than\n\
1715 SUBEXP pairs.\n\
1716 Zero means the entire text matched by the whole regexp or whole string.")
1717 (subexp)
1718 Lisp_Object subexp;
1719 {
1720 return match_limit (subexp, 1);
1721 }
1722
1723 DEFUN ("match-end", Fmatch_end, Smatch_end, 1, 1, 0,
1724 "Return position of end of text matched by last search.\n\
1725 SUBEXP, a number, specifies which parenthesized expression in the last\n\
1726 regexp.\n\
1727 Value is nil if SUBEXPth pair didn't match, or there were less than\n\
1728 SUBEXP pairs.\n\
1729 Zero means the entire text matched by the whole regexp or whole string.")
1730 (subexp)
1731 Lisp_Object subexp;
1732 {
1733 return match_limit (subexp, 0);
1734 }
1735
1736 DEFUN ("match-data", Fmatch_data, Smatch_data, 0, 2, 0,
1737 "Return a list containing all info on what the last search matched.\n\
1738 Element 2N is `(match-beginning N)'; element 2N + 1 is `(match-end N)'.\n\
1739 All the elements are markers or nil (nil if the Nth pair didn't match)\n\
1740 if the last match was on a buffer; integers or nil if a string was matched.\n\
1741 Use `store-match-data' to reinstate the data in this list.\n\
1742 \n\
1743 If INTEGERS (the optional first argument) is non-nil, always use integers\n\
1744 \(rather than markers) to represent buffer positions.\n\
1745 If REUSE is a list, reuse it as part of the value. If REUSE is long enough\n\
1746 to hold all the values, and if INTEGERS is non-nil, no consing is done.")
1747 (integers, reuse)
1748 Lisp_Object integers, reuse;
1749 {
1750 Lisp_Object tail, prev;
1751 Lisp_Object *data;
1752 int i, len;
1753
1754 if (NILP (last_thing_searched))
1755 return Qnil;
1756
1757 data = (Lisp_Object *) alloca ((2 * search_regs.num_regs)
1758 * sizeof (Lisp_Object));
1759
1760 len = -1;
1761 for (i = 0; i < search_regs.num_regs; i++)
1762 {
1763 int start = search_regs.start[i];
1764 if (start >= 0)
1765 {
1766 if (EQ (last_thing_searched, Qt)
1767 || ! NILP (integers))
1768 {
1769 XSETFASTINT (data[2 * i], start);
1770 XSETFASTINT (data[2 * i + 1], search_regs.end[i]);
1771 }
1772 else if (BUFFERP (last_thing_searched))
1773 {
1774 data[2 * i] = Fmake_marker ();
1775 Fset_marker (data[2 * i],
1776 make_number (start),
1777 last_thing_searched);
1778 data[2 * i + 1] = Fmake_marker ();
1779 Fset_marker (data[2 * i + 1],
1780 make_number (search_regs.end[i]),
1781 last_thing_searched);
1782 }
1783 else
1784 /* last_thing_searched must always be Qt, a buffer, or Qnil. */
1785 abort ();
1786
1787 len = i;
1788 }
1789 else
1790 data[2 * i] = data [2 * i + 1] = Qnil;
1791 }
1792
1793 /* If REUSE is not usable, cons up the values and return them. */
1794 if (! CONSP (reuse))
1795 return Flist (2 * len + 2, data);
1796
1797 /* If REUSE is a list, store as many value elements as will fit
1798 into the elements of REUSE. */
1799 for (i = 0, tail = reuse; CONSP (tail);
1800 i++, tail = XCONS (tail)->cdr)
1801 {
1802 if (i < 2 * len + 2)
1803 XCONS (tail)->car = data[i];
1804 else
1805 XCONS (tail)->car = Qnil;
1806 prev = tail;
1807 }
1808
1809 /* If we couldn't fit all value elements into REUSE,
1810 cons up the rest of them and add them to the end of REUSE. */
1811 if (i < 2 * len + 2)
1812 XCONS (prev)->cdr = Flist (2 * len + 2 - i, data + i);
1813
1814 return reuse;
1815 }
1816
1817
1818 DEFUN ("store-match-data", Fstore_match_data, Sstore_match_data, 1, 1, 0,
1819 "Set internal data on last search match from elements of LIST.\n\
1820 LIST should have been created by calling `match-data' previously.")
1821 (list)
1822 register Lisp_Object list;
1823 {
1824 register int i;
1825 register Lisp_Object marker;
1826
1827 if (running_asynch_code)
1828 save_search_regs ();
1829
1830 if (!CONSP (list) && !NILP (list))
1831 list = wrong_type_argument (Qconsp, list);
1832
1833 /* Unless we find a marker with a buffer in LIST, assume that this
1834 match data came from a string. */
1835 last_thing_searched = Qt;
1836
1837 /* Allocate registers if they don't already exist. */
1838 {
1839 int length = XFASTINT (Flength (list)) / 2;
1840
1841 if (length > search_regs.num_regs)
1842 {
1843 if (search_regs.num_regs == 0)
1844 {
1845 search_regs.start
1846 = (regoff_t *) xmalloc (length * sizeof (regoff_t));
1847 search_regs.end
1848 = (regoff_t *) xmalloc (length * sizeof (regoff_t));
1849 }
1850 else
1851 {
1852 search_regs.start
1853 = (regoff_t *) xrealloc (search_regs.start,
1854 length * sizeof (regoff_t));
1855 search_regs.end
1856 = (regoff_t *) xrealloc (search_regs.end,
1857 length * sizeof (regoff_t));
1858 }
1859
1860 search_regs.num_regs = length;
1861 }
1862 }
1863
1864 for (i = 0; i < search_regs.num_regs; i++)
1865 {
1866 marker = Fcar (list);
1867 if (NILP (marker))
1868 {
1869 search_regs.start[i] = -1;
1870 list = Fcdr (list);
1871 }
1872 else
1873 {
1874 if (MARKERP (marker))
1875 {
1876 if (XMARKER (marker)->buffer == 0)
1877 XSETFASTINT (marker, 0);
1878 else
1879 XSETBUFFER (last_thing_searched, XMARKER (marker)->buffer);
1880 }
1881
1882 CHECK_NUMBER_COERCE_MARKER (marker, 0);
1883 search_regs.start[i] = XINT (marker);
1884 list = Fcdr (list);
1885
1886 marker = Fcar (list);
1887 if (MARKERP (marker) && XMARKER (marker)->buffer == 0)
1888 XSETFASTINT (marker, 0);
1889
1890 CHECK_NUMBER_COERCE_MARKER (marker, 0);
1891 search_regs.end[i] = XINT (marker);
1892 }
1893 list = Fcdr (list);
1894 }
1895
1896 return Qnil;
1897 }
1898
1899 /* If non-zero the match data have been saved in saved_search_regs
1900 during the execution of a sentinel or filter. */
1901 static int search_regs_saved;
1902 static struct re_registers saved_search_regs;
1903
1904 /* Called from Flooking_at, Fstring_match, search_buffer, Fstore_match_data
1905 if asynchronous code (filter or sentinel) is running. */
1906 static void
1907 save_search_regs ()
1908 {
1909 if (!search_regs_saved)
1910 {
1911 saved_search_regs.num_regs = search_regs.num_regs;
1912 saved_search_regs.start = search_regs.start;
1913 saved_search_regs.end = search_regs.end;
1914 search_regs.num_regs = 0;
1915 search_regs.start = 0;
1916 search_regs.end = 0;
1917
1918 search_regs_saved = 1;
1919 }
1920 }
1921
1922 /* Called upon exit from filters and sentinels. */
1923 void
1924 restore_match_data ()
1925 {
1926 if (search_regs_saved)
1927 {
1928 if (search_regs.num_regs > 0)
1929 {
1930 xfree (search_regs.start);
1931 xfree (search_regs.end);
1932 }
1933 search_regs.num_regs = saved_search_regs.num_regs;
1934 search_regs.start = saved_search_regs.start;
1935 search_regs.end = saved_search_regs.end;
1936
1937 search_regs_saved = 0;
1938 }
1939 }
1940
1941 /* Quote a string to inactivate reg-expr chars */
1942
1943 DEFUN ("regexp-quote", Fregexp_quote, Sregexp_quote, 1, 1, 0,
1944 "Return a regexp string which matches exactly STRING and nothing else.")
1945 (string)
1946 Lisp_Object string;
1947 {
1948 register unsigned char *in, *out, *end;
1949 register unsigned char *temp;
1950
1951 CHECK_STRING (string, 0);
1952
1953 temp = (unsigned char *) alloca (XSTRING (string)->size * 2);
1954
1955 /* Now copy the data into the new string, inserting escapes. */
1956
1957 in = XSTRING (string)->data;
1958 end = in + XSTRING (string)->size;
1959 out = temp;
1960
1961 for (; in != end; in++)
1962 {
1963 if (*in == '[' || *in == ']'
1964 || *in == '*' || *in == '.' || *in == '\\'
1965 || *in == '?' || *in == '+'
1966 || *in == '^' || *in == '$')
1967 *out++ = '\\';
1968 *out++ = *in;
1969 }
1970
1971 return make_string (temp, out - temp);
1972 }
1973 \f
1974 syms_of_search ()
1975 {
1976 register int i;
1977
1978 for (i = 0; i < REGEXP_CACHE_SIZE; ++i)
1979 {
1980 searchbufs[i].buf.allocated = 100;
1981 searchbufs[i].buf.buffer = (unsigned char *) malloc (100);
1982 searchbufs[i].buf.fastmap = searchbufs[i].fastmap;
1983 searchbufs[i].regexp = Qnil;
1984 staticpro (&searchbufs[i].regexp);
1985 searchbufs[i].next = (i == REGEXP_CACHE_SIZE-1 ? 0 : &searchbufs[i+1]);
1986 }
1987 searchbuf_head = &searchbufs[0];
1988
1989 Qsearch_failed = intern ("search-failed");
1990 staticpro (&Qsearch_failed);
1991 Qinvalid_regexp = intern ("invalid-regexp");
1992 staticpro (&Qinvalid_regexp);
1993
1994 Fput (Qsearch_failed, Qerror_conditions,
1995 Fcons (Qsearch_failed, Fcons (Qerror, Qnil)));
1996 Fput (Qsearch_failed, Qerror_message,
1997 build_string ("Search failed"));
1998
1999 Fput (Qinvalid_regexp, Qerror_conditions,
2000 Fcons (Qinvalid_regexp, Fcons (Qerror, Qnil)));
2001 Fput (Qinvalid_regexp, Qerror_message,
2002 build_string ("Invalid regexp"));
2003
2004 last_thing_searched = Qnil;
2005 staticpro (&last_thing_searched);
2006
2007 defsubr (&Slooking_at);
2008 defsubr (&Sposix_looking_at);
2009 defsubr (&Sstring_match);
2010 defsubr (&Sposix_string_match);
2011 defsubr (&Ssearch_forward);
2012 defsubr (&Ssearch_backward);
2013 defsubr (&Sword_search_forward);
2014 defsubr (&Sword_search_backward);
2015 defsubr (&Sre_search_forward);
2016 defsubr (&Sre_search_backward);
2017 defsubr (&Sposix_search_forward);
2018 defsubr (&Sposix_search_backward);
2019 defsubr (&Sreplace_match);
2020 defsubr (&Smatch_beginning);
2021 defsubr (&Smatch_end);
2022 defsubr (&Smatch_data);
2023 defsubr (&Sstore_match_data);
2024 defsubr (&Sregexp_quote);
2025 }