(Vpreloaded_file_list): New variable.
[emacs.git] / src / search.c
blob790f35fd62603d85b498ea21d2fea788b716e221
1 /* String search routines for GNU Emacs.
2 Copyright (C) 1985, 1986, 1987, 1993, 1994 Free Software Foundation, Inc.
4 This file is part of GNU Emacs.
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.
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.
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. */
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"
32 #include <sys/types.h>
33 #include "regex.h"
35 #define REGEXP_CACHE_SIZE 20
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
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;
49 /* The instances of that struct. */
50 struct regexp_cache searchbufs[REGEXP_CACHE_SIZE];
52 /* The head of the linked list; points to the most recently used buffer. */
53 struct regexp_cache *searchbuf_head;
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).
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.
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;
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;
80 /* error condition signaled when regexp compile_pattern fails */
82 Lisp_Object Qinvalid_regexp;
84 static void set_search_regs ();
85 static void save_search_regs ();
87 static int search_buffer ();
89 static void
90 matcher_overflow ()
92 error ("Stack overflow in regexp matcher");
95 #ifdef __STDC__
96 #define CONST const
97 #else
98 #define CONST
99 #endif
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. */
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;
124 CONST char *val;
125 reg_syntax_t old;
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));
141 cp->regexp = Fcopy_sequence (pattern);
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. */
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;
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);
167 for (cpp = &searchbuf_head; ; cpp = &cp->next)
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;
177 /* If we're at the end of the cache, compile into the last cell. */
178 if (cp->next == 0)
180 compile_pattern_1 (cp, pattern, translate, regp, posix, multibyte);
181 break;
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;
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);
197 return &cp->buf;
200 /* Error condition used for failing searches */
201 Lisp_Object Qsearch_failed;
203 Lisp_Object
204 signal_failure (arg)
205 Lisp_Object arg;
207 Fsignal (Qsearch_failed, Fcons (arg, Qnil));
208 return Qnil;
211 static Lisp_Object
212 looking_at_1 (string, posix)
213 Lisp_Object string;
214 int posix;
216 Lisp_Object val;
217 unsigned char *p1, *p2;
218 int s1, s2;
219 register int i;
220 struct re_pattern_buffer *bufp;
222 if (running_asynch_code)
223 save_search_regs ();
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);
231 immediate_quit = 1;
232 QUIT; /* Do a pending quit right away, to avoid paradoxical behavior */
234 /* Get pointers and sizes of the two strings
235 that make up the visible portion of the buffer. */
237 p1 = BEGV_ADDR;
238 s1 = GPT - BEGV;
239 p2 = GAP_END_ADDR;
240 s2 = ZV - GPT;
241 if (s1 < 0)
243 p2 = p1;
244 s2 = ZV - BEGV;
245 s1 = 0;
247 if (s2 < 0)
249 s1 = ZV - BEGV;
250 s2 = 0;
253 re_match_object = Qnil;
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 ();
261 val = (0 <= i ? Qt : Qnil);
262 for (i = 0; i < search_regs.num_regs; i++)
263 if (search_regs.start[i] >= 0)
265 search_regs.start[i] += BEGV;
266 search_regs.end[i] += BEGV;
268 XSETBUFFER (last_thing_searched, current_buffer);
269 immediate_quit = 0;
270 return val;
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;
281 return looking_at_1 (regexp, 0);
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;
293 return looking_at_1 (regexp, 1);
296 static Lisp_Object
297 string_match_1 (regexp, string, start, posix)
298 Lisp_Object regexp, string, start;
299 int posix;
301 int val;
302 int s;
303 struct re_pattern_buffer *bufp;
305 if (running_asynch_code)
306 save_search_regs ();
308 CHECK_STRING (regexp, 0);
309 CHECK_STRING (string, 1);
311 if (NILP (start))
312 s = 0;
313 else
315 int len = XSTRING (string)->size;
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);
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;
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);
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;
352 return string_match_1 (regexp, string, start, 0);
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;
365 return string_match_1 (regexp, string, start, 1);
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. */
373 fast_string_match (regexp, string)
374 Lisp_Object regexp, string;
376 int val;
377 struct re_pattern_buffer *bufp;
379 bufp = compile_pattern (regexp, 0, 0, 0);
380 immediate_quit = 1;
381 re_match_object = string;
383 val = re_search (bufp, (char *) XSTRING (string)->data,
384 XSTRING (string)->size, 0, XSTRING (string)->size,
386 immediate_quit = 0;
387 return val;
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. */
394 extern Lisp_Object Vascii_downcase_table;
397 fast_c_string_match_ignore_case (regexp, string)
398 Lisp_Object regexp;
399 char *string;
401 int val;
402 struct re_pattern_buffer *bufp;
403 int len = strlen (string);
405 re_match_object = Qt;
406 bufp = compile_pattern (regexp, 0,
407 XCHAR_TABLE (Vascii_downcase_table)->contents, 0);
408 immediate_quit = 1;
409 val = re_search (bufp, string, len, 0, len, 0);
410 immediate_quit = 0;
411 return val;
414 /* max and min. */
416 static int
417 max (a, b)
418 int a, b;
420 return ((a > b) ? a : b);
423 static int
424 min (a, b)
425 int a, b;
427 return ((a < b) ? a : b);
431 /* The newline cache: remembering which sections of text have no newlines. */
433 /* If the user has requested newline caching, make sure it's on.
434 Otherwise, make sure it's off.
435 This is our cheezy way of associating an action with the change of
436 state of a buffer-local variable. */
437 static void
438 newline_cache_on_off (buf)
439 struct buffer *buf;
441 if (NILP (buf->cache_long_line_scans))
443 /* It should be off. */
444 if (buf->newline_cache)
446 free_region_cache (buf->newline_cache);
447 buf->newline_cache = 0;
450 else
452 /* It should be on. */
453 if (buf->newline_cache == 0)
454 buf->newline_cache = new_region_cache ();
459 /* Search for COUNT instances of the character TARGET between START and END.
461 If COUNT is positive, search forwards; END must be >= START.
462 If COUNT is negative, search backwards for the -COUNTth instance;
463 END must be <= START.
464 If COUNT is zero, do anything you please; run rogue, for all I care.
466 If END is zero, use BEGV or ZV instead, as appropriate for the
467 direction indicated by COUNT.
469 If we find COUNT instances, set *SHORTAGE to zero, and return the
470 position after the COUNTth match. Note that for reverse motion
471 this is not the same as the usual convention for Emacs motion commands.
473 If we don't find COUNT instances before reaching END, set *SHORTAGE
474 to the number of TARGETs left unfound, and return END.
476 If ALLOW_QUIT is non-zero, set immediate_quit. That's good to do
477 except when inside redisplay. */
479 scan_buffer (target, start, end, count, shortage, allow_quit)
480 register int target;
481 int start, end;
482 int count;
483 int *shortage;
484 int allow_quit;
486 struct region_cache *newline_cache;
487 int direction;
489 if (count > 0)
491 direction = 1;
492 if (! end) end = ZV;
494 else
496 direction = -1;
497 if (! end) end = BEGV;
500 newline_cache_on_off (current_buffer);
501 newline_cache = current_buffer->newline_cache;
503 if (shortage != 0)
504 *shortage = 0;
506 immediate_quit = allow_quit;
508 if (count > 0)
509 while (start != end)
511 /* Our innermost scanning loop is very simple; it doesn't know
512 about gaps, buffer ends, or the newline cache. ceiling is
513 the position of the last character before the next such
514 obstacle --- the last character the dumb search loop should
515 examine. */
516 register int ceiling = end - 1;
518 /* If we're looking for a newline, consult the newline cache
519 to see where we can avoid some scanning. */
520 if (target == '\n' && newline_cache)
522 int next_change;
523 immediate_quit = 0;
524 while (region_cache_forward
525 (current_buffer, newline_cache, start, &next_change))
526 start = next_change;
527 immediate_quit = allow_quit;
529 /* start should never be after end. */
530 if (start >= end)
531 start = end - 1;
533 /* Now the text after start is an unknown region, and
534 next_change is the position of the next known region. */
535 ceiling = min (next_change - 1, ceiling);
538 /* The dumb loop can only scan text stored in contiguous
539 bytes. BUFFER_CEILING_OF returns the last character
540 position that is contiguous, so the ceiling is the
541 position after that. */
542 ceiling = min (BUFFER_CEILING_OF (start), ceiling);
545 /* The termination address of the dumb loop. */
546 register unsigned char *ceiling_addr = POS_ADDR (ceiling) + 1;
547 register unsigned char *cursor = POS_ADDR (start);
548 unsigned char *base = cursor;
550 while (cursor < ceiling_addr)
552 unsigned char *scan_start = cursor;
554 /* The dumb loop. */
555 while (*cursor != target && ++cursor < ceiling_addr)
558 /* If we're looking for newlines, cache the fact that
559 the region from start to cursor is free of them. */
560 if (target == '\n' && newline_cache)
561 know_region_cache (current_buffer, newline_cache,
562 start + scan_start - base,
563 start + cursor - base);
565 /* Did we find the target character? */
566 if (cursor < ceiling_addr)
568 if (--count == 0)
570 immediate_quit = 0;
571 return (start + cursor - base + 1);
573 cursor++;
577 start += cursor - base;
580 else
581 while (start > end)
583 /* The last character to check before the next obstacle. */
584 register int ceiling = end;
586 /* Consult the newline cache, if appropriate. */
587 if (target == '\n' && newline_cache)
589 int next_change;
590 immediate_quit = 0;
591 while (region_cache_backward
592 (current_buffer, newline_cache, start, &next_change))
593 start = next_change;
594 immediate_quit = allow_quit;
596 /* Start should never be at or before end. */
597 if (start <= end)
598 start = end + 1;
600 /* Now the text before start is an unknown region, and
601 next_change is the position of the next known region. */
602 ceiling = max (next_change, ceiling);
605 /* Stop scanning before the gap. */
606 ceiling = max (BUFFER_FLOOR_OF (start - 1), ceiling);
609 /* The termination address of the dumb loop. */
610 register unsigned char *ceiling_addr = POS_ADDR (ceiling);
611 register unsigned char *cursor = POS_ADDR (start - 1);
612 unsigned char *base = cursor;
614 while (cursor >= ceiling_addr)
616 unsigned char *scan_start = cursor;
618 while (*cursor != target && --cursor >= ceiling_addr)
621 /* If we're looking for newlines, cache the fact that
622 the region from after the cursor to start is free of them. */
623 if (target == '\n' && newline_cache)
624 know_region_cache (current_buffer, newline_cache,
625 start + cursor - base,
626 start + scan_start - base);
628 /* Did we find the target character? */
629 if (cursor >= ceiling_addr)
631 if (++count >= 0)
633 immediate_quit = 0;
634 return (start + cursor - base);
636 cursor--;
640 start += cursor - base;
644 immediate_quit = 0;
645 if (shortage != 0)
646 *shortage = count * direction;
647 return start;
651 find_next_newline_no_quit (from, cnt)
652 register int from, cnt;
654 return scan_buffer ('\n', from, 0, cnt, (int *) 0, 0);
658 find_next_newline (from, cnt)
659 register int from, cnt;
661 return scan_buffer ('\n', from, 0, cnt, (int *) 0, 1);
665 /* Like find_next_newline, but returns position before the newline,
666 not after, and only search up to TO. This isn't just
667 find_next_newline (...)-1, because you might hit TO. */
669 find_before_next_newline (from, to, cnt)
670 int from, to, cnt;
672 int shortage;
673 int pos = scan_buffer ('\n', from, to, cnt, &shortage, 1);
675 if (shortage == 0)
676 pos--;
678 return pos;
681 /* Subroutines of Lisp buffer search functions. */
683 static Lisp_Object
684 search_command (string, bound, noerror, count, direction, RE, posix)
685 Lisp_Object string, bound, noerror, count;
686 int direction;
687 int RE;
688 int posix;
690 register int np;
691 int lim;
692 int n = direction;
694 if (!NILP (count))
696 CHECK_NUMBER (count, 3);
697 n *= XINT (count);
700 CHECK_STRING (string, 0);
701 if (NILP (bound))
702 lim = n > 0 ? ZV : BEGV;
703 else
705 CHECK_NUMBER_COERCE_MARKER (bound, 1);
706 lim = XINT (bound);
707 if (n > 0 ? lim < PT : lim > PT)
708 error ("Invalid search bound (wrong side of point)");
709 if (lim > ZV)
710 lim = ZV;
711 if (lim < BEGV)
712 lim = BEGV;
715 np = search_buffer (string, PT, lim, n, RE,
716 (!NILP (current_buffer->case_fold_search)
717 ? XCHAR_TABLE (current_buffer->case_canon_table)->contents
718 : 0),
719 (!NILP (current_buffer->case_fold_search)
720 ? XCHAR_TABLE (current_buffer->case_eqv_table)->contents
721 : 0),
722 posix);
723 if (np <= 0)
725 if (NILP (noerror))
726 return signal_failure (string);
727 if (!EQ (noerror, Qt))
729 if (lim < BEGV || lim > ZV)
730 abort ();
731 SET_PT (lim);
732 return Qnil;
733 #if 0 /* This would be clean, but maybe programs depend on
734 a value of nil here. */
735 np = lim;
736 #endif
738 else
739 return Qnil;
742 if (np < BEGV || np > ZV)
743 abort ();
745 SET_PT (np);
747 return make_number (np);
750 static int
751 trivial_regexp_p (regexp)
752 Lisp_Object regexp;
754 int len = XSTRING (regexp)->size;
755 unsigned char *s = XSTRING (regexp)->data;
756 unsigned char c;
757 while (--len >= 0)
759 switch (*s++)
761 case '.': case '*': case '+': case '?': case '[': case '^': case '$':
762 return 0;
763 case '\\':
764 if (--len < 0)
765 return 0;
766 switch (*s++)
768 case '|': case '(': case ')': case '`': case '\'': case 'b':
769 case 'B': case '<': case '>': case 'w': case 'W': case 's':
770 case 'S': case '=':
771 case 'c': case 'C': /* for categoryspec and notcategoryspec */
772 case '1': case '2': case '3': case '4': case '5':
773 case '6': case '7': case '8': case '9':
774 return 0;
778 return 1;
781 /* Search for the n'th occurrence of STRING in the current buffer,
782 starting at position POS and stopping at position LIM,
783 treating STRING as a literal string if RE is false or as
784 a regular expression if RE is true.
786 If N is positive, searching is forward and LIM must be greater than POS.
787 If N is negative, searching is backward and LIM must be less than POS.
789 Returns -x if only N-x occurrences found (x > 0),
790 or else the position at the beginning of the Nth occurrence
791 (if searching backward) or the end (if searching forward).
793 POSIX is nonzero if we want full backtracking (POSIX style)
794 for this pattern. 0 means backtrack only enough to get a valid match. */
796 static int
797 search_buffer (string, pos, lim, n, RE, trt, inverse_trt, posix)
798 Lisp_Object string;
799 int pos;
800 int lim;
801 int n;
802 int RE;
803 Lisp_Object *trt;
804 Lisp_Object *inverse_trt;
805 int posix;
807 int len = XSTRING (string)->size;
808 unsigned char *base_pat = XSTRING (string)->data;
809 register int *BM_tab;
810 int *BM_tab_base;
811 register int direction = ((n > 0) ? 1 : -1);
812 register int dirlen;
813 int infinity, limit, k, stride_for_teases;
814 register unsigned char *pat, *cursor, *p_limit;
815 register int i, j;
816 unsigned char *p1, *p2;
817 int s1, s2;
819 if (running_asynch_code)
820 save_search_regs ();
822 /* Null string is found at starting position. */
823 if (len == 0)
825 set_search_regs (pos, 0);
826 return pos;
829 /* Searching 0 times means don't move. */
830 if (n == 0)
831 return pos;
833 if (RE && !trivial_regexp_p (string))
835 struct re_pattern_buffer *bufp;
837 bufp = compile_pattern (string, &search_regs, trt, posix);
839 immediate_quit = 1; /* Quit immediately if user types ^G,
840 because letting this function finish
841 can take too long. */
842 QUIT; /* Do a pending quit right away,
843 to avoid paradoxical behavior */
844 /* Get pointers and sizes of the two strings
845 that make up the visible portion of the buffer. */
847 p1 = BEGV_ADDR;
848 s1 = GPT - BEGV;
849 p2 = GAP_END_ADDR;
850 s2 = ZV - GPT;
851 if (s1 < 0)
853 p2 = p1;
854 s2 = ZV - BEGV;
855 s1 = 0;
857 if (s2 < 0)
859 s1 = ZV - BEGV;
860 s2 = 0;
862 re_match_object = Qnil;
864 while (n < 0)
866 int val;
867 val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
868 pos - BEGV, lim - pos, &search_regs,
869 /* Don't allow match past current point */
870 pos - BEGV);
871 if (val == -2)
873 matcher_overflow ();
875 if (val >= 0)
877 j = BEGV;
878 for (i = 0; i < search_regs.num_regs; i++)
879 if (search_regs.start[i] >= 0)
881 search_regs.start[i] += j;
882 search_regs.end[i] += j;
884 XSETBUFFER (last_thing_searched, current_buffer);
885 /* Set pos to the new position. */
886 pos = search_regs.start[0];
888 else
890 immediate_quit = 0;
891 return (n);
893 n++;
895 while (n > 0)
897 int val;
898 val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
899 pos - BEGV, lim - pos, &search_regs,
900 lim - BEGV);
901 if (val == -2)
903 matcher_overflow ();
905 if (val >= 0)
907 j = BEGV;
908 for (i = 0; i < search_regs.num_regs; i++)
909 if (search_regs.start[i] >= 0)
911 search_regs.start[i] += j;
912 search_regs.end[i] += j;
914 XSETBUFFER (last_thing_searched, current_buffer);
915 pos = search_regs.end[0];
917 else
919 immediate_quit = 0;
920 return (0 - n);
922 n--;
924 immediate_quit = 0;
925 return (pos);
927 else /* non-RE case */
929 #ifdef C_ALLOCA
930 int BM_tab_space[0400];
931 BM_tab = &BM_tab_space[0];
932 #else
933 BM_tab = (int *) alloca (0400 * sizeof (int));
934 #endif
936 unsigned char *patbuf = (unsigned char *) alloca (len);
937 pat = patbuf;
938 while (--len >= 0)
940 /* If we got here and the RE flag is set, it's because we're
941 dealing with a regexp known to be trivial, so the backslash
942 just quotes the next character. */
943 if (RE && *base_pat == '\\')
945 len--;
946 base_pat++;
948 *pat++ = (trt ? XINT (trt[*base_pat++]) : *base_pat++);
950 len = pat - patbuf;
951 pat = base_pat = patbuf;
953 /* The general approach is that we are going to maintain that we know */
954 /* the first (closest to the present position, in whatever direction */
955 /* we're searching) character that could possibly be the last */
956 /* (furthest from present position) character of a valid match. We */
957 /* advance the state of our knowledge by looking at that character */
958 /* and seeing whether it indeed matches the last character of the */
959 /* pattern. If it does, we take a closer look. If it does not, we */
960 /* move our pointer (to putative last characters) as far as is */
961 /* logically possible. This amount of movement, which I call a */
962 /* stride, will be the length of the pattern if the actual character */
963 /* appears nowhere in the pattern, otherwise it will be the distance */
964 /* from the last occurrence of that character to the end of the */
965 /* pattern. */
966 /* As a coding trick, an enormous stride is coded into the table for */
967 /* characters that match the last character. This allows use of only */
968 /* a single test, a test for having gone past the end of the */
969 /* permissible match region, to test for both possible matches (when */
970 /* the stride goes past the end immediately) and failure to */
971 /* match (where you get nudged past the end one stride at a time). */
973 /* Here we make a "mickey mouse" BM table. The stride of the search */
974 /* is determined only by the last character of the putative match. */
975 /* If that character does not match, we will stride the proper */
976 /* distance to propose a match that superimposes it on the last */
977 /* instance of a character that matches it (per trt), or misses */
978 /* it entirely if there is none. */
980 dirlen = len * direction;
981 infinity = dirlen - (lim + pos + len + len) * direction;
982 if (direction < 0)
983 pat = (base_pat += len - 1);
984 BM_tab_base = BM_tab;
985 BM_tab += 0400;
986 j = dirlen; /* to get it in a register */
987 /* A character that does not appear in the pattern induces a */
988 /* stride equal to the pattern length. */
989 while (BM_tab_base != BM_tab)
991 *--BM_tab = j;
992 *--BM_tab = j;
993 *--BM_tab = j;
994 *--BM_tab = j;
996 i = 0;
997 while (i != infinity)
999 j = pat[i]; i += direction;
1000 if (i == dirlen) i = infinity;
1001 if (trt != 0)
1003 k = (j = XINT (trt[j]));
1004 if (i == infinity)
1005 stride_for_teases = BM_tab[j];
1006 BM_tab[j] = dirlen - i;
1007 /* A translation table is accompanied by its inverse -- see */
1008 /* comment following downcase_table for details */
1009 while ((j = (unsigned char) XINT (inverse_trt[j])) != k)
1010 BM_tab[j] = dirlen - i;
1012 else
1014 if (i == infinity)
1015 stride_for_teases = BM_tab[j];
1016 BM_tab[j] = dirlen - i;
1018 /* stride_for_teases tells how much to stride if we get a */
1019 /* match on the far character but are subsequently */
1020 /* disappointed, by recording what the stride would have been */
1021 /* for that character if the last character had been */
1022 /* different. */
1024 infinity = dirlen - infinity;
1025 pos += dirlen - ((direction > 0) ? direction : 0);
1026 /* loop invariant - pos points at where last char (first char if reverse)
1027 of pattern would align in a possible match. */
1028 while (n != 0)
1030 /* It's been reported that some (broken) compiler thinks that
1031 Boolean expressions in an arithmetic context are unsigned.
1032 Using an explicit ?1:0 prevents this. */
1033 if ((lim - pos - ((direction > 0) ? 1 : 0)) * direction < 0)
1034 return (n * (0 - direction));
1035 /* First we do the part we can by pointers (maybe nothing) */
1036 QUIT;
1037 pat = base_pat;
1038 limit = pos - dirlen + direction;
1039 limit = ((direction > 0)
1040 ? BUFFER_CEILING_OF (limit)
1041 : BUFFER_FLOOR_OF (limit));
1042 /* LIMIT is now the last (not beyond-last!) value
1043 POS can take on without hitting edge of buffer or the gap. */
1044 limit = ((direction > 0)
1045 ? min (lim - 1, min (limit, pos + 20000))
1046 : max (lim, max (limit, pos - 20000)));
1047 if ((limit - pos) * direction > 20)
1049 p_limit = POS_ADDR (limit);
1050 p2 = (cursor = POS_ADDR (pos));
1051 /* In this loop, pos + cursor - p2 is the surrogate for pos */
1052 while (1) /* use one cursor setting as long as i can */
1054 if (direction > 0) /* worth duplicating */
1056 /* Use signed comparison if appropriate
1057 to make cursor+infinity sure to be > p_limit.
1058 Assuming that the buffer lies in a range of addresses
1059 that are all "positive" (as ints) or all "negative",
1060 either kind of comparison will work as long
1061 as we don't step by infinity. So pick the kind
1062 that works when we do step by infinity. */
1063 if ((EMACS_INT) (p_limit + infinity) > (EMACS_INT) p_limit)
1064 while ((EMACS_INT) cursor <= (EMACS_INT) p_limit)
1065 cursor += BM_tab[*cursor];
1066 else
1067 while ((EMACS_UINT) cursor <= (EMACS_UINT) p_limit)
1068 cursor += BM_tab[*cursor];
1070 else
1072 if ((EMACS_INT) (p_limit + infinity) < (EMACS_INT) p_limit)
1073 while ((EMACS_INT) cursor >= (EMACS_INT) p_limit)
1074 cursor += BM_tab[*cursor];
1075 else
1076 while ((EMACS_UINT) cursor >= (EMACS_UINT) p_limit)
1077 cursor += BM_tab[*cursor];
1079 /* If you are here, cursor is beyond the end of the searched region. */
1080 /* This can happen if you match on the far character of the pattern, */
1081 /* because the "stride" of that character is infinity, a number able */
1082 /* to throw you well beyond the end of the search. It can also */
1083 /* happen if you fail to match within the permitted region and would */
1084 /* otherwise try a character beyond that region */
1085 if ((cursor - p_limit) * direction <= len)
1086 break; /* a small overrun is genuine */
1087 cursor -= infinity; /* large overrun = hit */
1088 i = dirlen - direction;
1089 if (trt != 0)
1091 while ((i -= direction) + direction != 0)
1092 if (pat[i] != XINT (trt[*(cursor -= direction)]))
1093 break;
1095 else
1097 while ((i -= direction) + direction != 0)
1098 if (pat[i] != *(cursor -= direction))
1099 break;
1101 cursor += dirlen - i - direction; /* fix cursor */
1102 if (i + direction == 0)
1104 cursor -= direction;
1106 set_search_regs (pos + cursor - p2 + ((direction > 0)
1107 ? 1 - len : 0),
1108 len);
1110 if ((n -= direction) != 0)
1111 cursor += dirlen; /* to resume search */
1112 else
1113 return ((direction > 0)
1114 ? search_regs.end[0] : search_regs.start[0]);
1116 else
1117 cursor += stride_for_teases; /* <sigh> we lose - */
1119 pos += cursor - p2;
1121 else
1122 /* Now we'll pick up a clump that has to be done the hard */
1123 /* way because it covers a discontinuity */
1125 limit = ((direction > 0)
1126 ? BUFFER_CEILING_OF (pos - dirlen + 1)
1127 : BUFFER_FLOOR_OF (pos - dirlen - 1));
1128 limit = ((direction > 0)
1129 ? min (limit + len, lim - 1)
1130 : max (limit - len, lim));
1131 /* LIMIT is now the last value POS can have
1132 and still be valid for a possible match. */
1133 while (1)
1135 /* This loop can be coded for space rather than */
1136 /* speed because it will usually run only once. */
1137 /* (the reach is at most len + 21, and typically */
1138 /* does not exceed len) */
1139 while ((limit - pos) * direction >= 0)
1140 pos += BM_tab[FETCH_BYTE (pos)];
1141 /* now run the same tests to distinguish going off the */
1142 /* end, a match or a phony match. */
1143 if ((pos - limit) * direction <= len)
1144 break; /* ran off the end */
1145 /* Found what might be a match.
1146 Set POS back to last (first if reverse) char pos. */
1147 pos -= infinity;
1148 i = dirlen - direction;
1149 while ((i -= direction) + direction != 0)
1151 pos -= direction;
1152 if (pat[i] != (trt != 0
1153 ? XINT (trt[FETCH_BYTE (pos)])
1154 : FETCH_BYTE (pos)))
1155 break;
1157 /* Above loop has moved POS part or all the way
1158 back to the first char pos (last char pos if reverse).
1159 Set it once again at the last (first if reverse) char. */
1160 pos += dirlen - i- direction;
1161 if (i + direction == 0)
1163 pos -= direction;
1165 set_search_regs (pos + ((direction > 0) ? 1 - len : 0),
1166 len);
1168 if ((n -= direction) != 0)
1169 pos += dirlen; /* to resume search */
1170 else
1171 return ((direction > 0)
1172 ? search_regs.end[0] : search_regs.start[0]);
1174 else
1175 pos += stride_for_teases;
1178 /* We have done one clump. Can we continue? */
1179 if ((lim - pos) * direction < 0)
1180 return ((0 - n) * direction);
1182 return pos;
1186 /* Record beginning BEG and end BEG + LEN
1187 for a match just found in the current buffer. */
1189 static void
1190 set_search_regs (beg, len)
1191 int beg, len;
1193 /* Make sure we have registers in which to store
1194 the match position. */
1195 if (search_regs.num_regs == 0)
1197 search_regs.start = (regoff_t *) xmalloc (2 * sizeof (regoff_t));
1198 search_regs.end = (regoff_t *) xmalloc (2 * sizeof (regoff_t));
1199 search_regs.num_regs = 2;
1202 search_regs.start[0] = beg;
1203 search_regs.end[0] = beg + len;
1204 XSETBUFFER (last_thing_searched, current_buffer);
1207 /* Given a string of words separated by word delimiters,
1208 compute a regexp that matches those exact words
1209 separated by arbitrary punctuation. */
1211 static Lisp_Object
1212 wordify (string)
1213 Lisp_Object string;
1215 register unsigned char *p, *o;
1216 register int i, len, punct_count = 0, word_count = 0;
1217 Lisp_Object val;
1219 CHECK_STRING (string, 0);
1220 p = XSTRING (string)->data;
1221 len = XSTRING (string)->size;
1223 for (i = 0; i < len; i++)
1224 if (SYNTAX (p[i]) != Sword)
1226 punct_count++;
1227 if (i > 0 && SYNTAX (p[i-1]) == Sword) word_count++;
1229 if (SYNTAX (p[len-1]) == Sword) word_count++;
1230 if (!word_count) return build_string ("");
1232 val = make_string (p, len - punct_count + 5 * (word_count - 1) + 4);
1234 o = XSTRING (val)->data;
1235 *o++ = '\\';
1236 *o++ = 'b';
1238 for (i = 0; i < len; i++)
1239 if (SYNTAX (p[i]) == Sword)
1240 *o++ = p[i];
1241 else if (i > 0 && SYNTAX (p[i-1]) == Sword && --word_count)
1243 *o++ = '\\';
1244 *o++ = 'W';
1245 *o++ = '\\';
1246 *o++ = 'W';
1247 *o++ = '*';
1250 *o++ = '\\';
1251 *o++ = 'b';
1253 return val;
1256 DEFUN ("search-backward", Fsearch_backward, Ssearch_backward, 1, 4,
1257 "sSearch backward: ",
1258 "Search backward from point for STRING.\n\
1259 Set point to the beginning of the occurrence found, and return point.\n\
1260 An optional second argument bounds the search; it is a buffer position.\n\
1261 The match found must not extend before that position.\n\
1262 Optional third argument, if t, means if fail just return nil (no error).\n\
1263 If not nil and not t, position at limit of search and return nil.\n\
1264 Optional fourth argument is repeat count--search for successive occurrences.\n\
1265 See also the functions `match-beginning', `match-end' and `replace-match'.")
1266 (string, bound, noerror, count)
1267 Lisp_Object string, bound, noerror, count;
1269 return search_command (string, bound, noerror, count, -1, 0, 0);
1272 DEFUN ("search-forward", Fsearch_forward, Ssearch_forward, 1, 4, "sSearch: ",
1273 "Search forward from point for STRING.\n\
1274 Set point to the end of the occurrence found, and return point.\n\
1275 An optional second argument bounds the search; it is a buffer position.\n\
1276 The match found must not extend after that position. nil is equivalent\n\
1277 to (point-max).\n\
1278 Optional third argument, if t, means if fail just return nil (no error).\n\
1279 If not nil and not t, move to limit of search and return nil.\n\
1280 Optional fourth argument is repeat count--search for successive occurrences.\n\
1281 See also the functions `match-beginning', `match-end' and `replace-match'.")
1282 (string, bound, noerror, count)
1283 Lisp_Object string, bound, noerror, count;
1285 return search_command (string, bound, noerror, count, 1, 0, 0);
1288 DEFUN ("word-search-backward", Fword_search_backward, Sword_search_backward, 1, 4,
1289 "sWord search backward: ",
1290 "Search backward from point for STRING, ignoring differences in punctuation.\n\
1291 Set point to the beginning of the occurrence found, and return point.\n\
1292 An optional second argument bounds the search; it is a buffer position.\n\
1293 The match found must not extend before that position.\n\
1294 Optional third argument, if t, means if fail just return nil (no error).\n\
1295 If not nil and not t, move to limit of search and return nil.\n\
1296 Optional fourth argument is repeat count--search for successive occurrences.")
1297 (string, bound, noerror, count)
1298 Lisp_Object string, bound, noerror, count;
1300 return search_command (wordify (string), bound, noerror, count, -1, 1, 0);
1303 DEFUN ("word-search-forward", Fword_search_forward, Sword_search_forward, 1, 4,
1304 "sWord search: ",
1305 "Search forward from point for STRING, ignoring differences in punctuation.\n\
1306 Set point to the end of the occurrence found, and return point.\n\
1307 An optional second argument bounds the search; it is a buffer position.\n\
1308 The match found must not extend after that position.\n\
1309 Optional third argument, if t, means if fail just return nil (no error).\n\
1310 If not nil and not t, move to limit of search and return nil.\n\
1311 Optional fourth argument is repeat count--search for successive occurrences.")
1312 (string, bound, noerror, count)
1313 Lisp_Object string, bound, noerror, count;
1315 return search_command (wordify (string), bound, noerror, count, 1, 1, 0);
1318 DEFUN ("re-search-backward", Fre_search_backward, Sre_search_backward, 1, 4,
1319 "sRE search backward: ",
1320 "Search backward from point for match for regular expression REGEXP.\n\
1321 Set point to the beginning of the match, and return point.\n\
1322 The match found is the one starting last in the buffer\n\
1323 and yet ending before the origin of the search.\n\
1324 An optional second argument bounds the search; it is a buffer position.\n\
1325 The match found must start at or after that position.\n\
1326 Optional third argument, if t, means if fail just return nil (no error).\n\
1327 If not nil and not t, move to limit of search and return nil.\n\
1328 Optional fourth argument is repeat count--search for successive occurrences.\n\
1329 See also the functions `match-beginning', `match-end' and `replace-match'.")
1330 (regexp, bound, noerror, count)
1331 Lisp_Object regexp, bound, noerror, count;
1333 return search_command (regexp, bound, noerror, count, -1, 1, 0);
1336 DEFUN ("re-search-forward", Fre_search_forward, Sre_search_forward, 1, 4,
1337 "sRE search: ",
1338 "Search forward from point for regular expression REGEXP.\n\
1339 Set point to the end of the occurrence found, and return point.\n\
1340 An optional second argument bounds the search; it is a buffer position.\n\
1341 The match found must not extend after that position.\n\
1342 Optional third argument, if t, means if fail just return nil (no error).\n\
1343 If not nil and not t, move to limit of search and return nil.\n\
1344 Optional fourth argument is repeat count--search for successive occurrences.\n\
1345 See also the functions `match-beginning', `match-end' and `replace-match'.")
1346 (regexp, bound, noerror, count)
1347 Lisp_Object regexp, bound, noerror, count;
1349 return search_command (regexp, bound, noerror, count, 1, 1, 0);
1352 DEFUN ("posix-search-backward", Fposix_search_backward, Sposix_search_backward, 1, 4,
1353 "sPosix search backward: ",
1354 "Search backward from point for match for regular expression REGEXP.\n\
1355 Find the longest match in accord with Posix regular expression rules.\n\
1356 Set point to the beginning of the match, and return point.\n\
1357 The match found is the one starting last in the buffer\n\
1358 and yet ending before the origin of the search.\n\
1359 An optional second argument bounds the search; it is a buffer position.\n\
1360 The match found must start at or after that position.\n\
1361 Optional third argument, if t, means if fail just return nil (no error).\n\
1362 If not nil and not t, move to limit of search and return nil.\n\
1363 Optional fourth argument is repeat count--search for successive occurrences.\n\
1364 See also the functions `match-beginning', `match-end' and `replace-match'.")
1365 (regexp, bound, noerror, count)
1366 Lisp_Object regexp, bound, noerror, count;
1368 return search_command (regexp, bound, noerror, count, -1, 1, 1);
1371 DEFUN ("posix-search-forward", Fposix_search_forward, Sposix_search_forward, 1, 4,
1372 "sPosix search: ",
1373 "Search forward from point for regular expression REGEXP.\n\
1374 Find the longest match in accord with Posix regular expression rules.\n\
1375 Set point to the end of the occurrence found, and return point.\n\
1376 An optional second argument bounds the search; it is a buffer position.\n\
1377 The match found must not extend after that position.\n\
1378 Optional third argument, if t, means if fail just return nil (no error).\n\
1379 If not nil and not t, move to limit of search and return nil.\n\
1380 Optional fourth argument is repeat count--search for successive occurrences.\n\
1381 See also the functions `match-beginning', `match-end' and `replace-match'.")
1382 (regexp, bound, noerror, count)
1383 Lisp_Object regexp, bound, noerror, count;
1385 return search_command (regexp, bound, noerror, count, 1, 1, 1);
1388 DEFUN ("replace-match", Freplace_match, Sreplace_match, 1, 5, 0,
1389 "Replace text matched by last search with NEWTEXT.\n\
1390 If second arg FIXEDCASE is non-nil, do not alter case of replacement text.\n\
1391 Otherwise maybe capitalize the whole text, or maybe just word initials,\n\
1392 based on the replaced text.\n\
1393 If the replaced text has only capital letters\n\
1394 and has at least one multiletter word, convert NEWTEXT to all caps.\n\
1395 If the replaced text has at least one word starting with a capital letter,\n\
1396 then capitalize each word in NEWTEXT.\n\n\
1397 If third arg LITERAL is non-nil, insert NEWTEXT literally.\n\
1398 Otherwise treat `\\' as special:\n\
1399 `\\&' in NEWTEXT means substitute original matched text.\n\
1400 `\\N' means substitute what matched the Nth `\\(...\\)'.\n\
1401 If Nth parens didn't match, substitute nothing.\n\
1402 `\\\\' means insert one `\\'.\n\
1403 FIXEDCASE and LITERAL are optional arguments.\n\
1404 Leaves point at end of replacement text.\n\
1406 The optional fourth argument STRING can be a string to modify.\n\
1407 In that case, this function creates and returns a new string\n\
1408 which is made by replacing the part of STRING that was matched.\n\
1410 The optional fifth argument SUBEXP specifies a subexpression of the match.\n\
1411 It says to replace just that subexpression instead of the whole match.\n\
1412 This is useful only after a regular expression search or match\n\
1413 since only regular expressions have distinguished subexpressions.")
1414 (newtext, fixedcase, literal, string, subexp)
1415 Lisp_Object newtext, fixedcase, literal, string, subexp;
1417 enum { nochange, all_caps, cap_initial } case_action;
1418 register int pos, last;
1419 int some_multiletter_word;
1420 int some_lowercase;
1421 int some_uppercase;
1422 int some_nonuppercase_initial;
1423 register int c, prevc;
1424 int inslen;
1425 int sub;
1426 int opoint, newpoint;
1428 CHECK_STRING (newtext, 0);
1430 if (! NILP (string))
1431 CHECK_STRING (string, 4);
1433 case_action = nochange; /* We tried an initialization */
1434 /* but some C compilers blew it */
1436 if (search_regs.num_regs <= 0)
1437 error ("replace-match called before any match found");
1439 if (NILP (subexp))
1440 sub = 0;
1441 else
1443 CHECK_NUMBER (subexp, 3);
1444 sub = XINT (subexp);
1445 if (sub < 0 || sub >= search_regs.num_regs)
1446 args_out_of_range (subexp, make_number (search_regs.num_regs));
1449 if (NILP (string))
1451 if (search_regs.start[sub] < BEGV
1452 || search_regs.start[sub] > search_regs.end[sub]
1453 || search_regs.end[sub] > ZV)
1454 args_out_of_range (make_number (search_regs.start[sub]),
1455 make_number (search_regs.end[sub]));
1457 else
1459 if (search_regs.start[sub] < 0
1460 || search_regs.start[sub] > search_regs.end[sub]
1461 || search_regs.end[sub] > XSTRING (string)->size)
1462 args_out_of_range (make_number (search_regs.start[sub]),
1463 make_number (search_regs.end[sub]));
1466 if (NILP (fixedcase))
1468 /* Decide how to casify by examining the matched text. */
1470 last = search_regs.end[sub];
1471 prevc = '\n';
1472 case_action = all_caps;
1474 /* some_multiletter_word is set nonzero if any original word
1475 is more than one letter long. */
1476 some_multiletter_word = 0;
1477 some_lowercase = 0;
1478 some_nonuppercase_initial = 0;
1479 some_uppercase = 0;
1481 for (pos = search_regs.start[sub]; pos < last; pos++)
1483 if (NILP (string))
1484 c = FETCH_BYTE (pos);
1485 else
1486 c = XSTRING (string)->data[pos];
1488 if (LOWERCASEP (c))
1490 /* Cannot be all caps if any original char is lower case */
1492 some_lowercase = 1;
1493 if (SYNTAX (prevc) != Sword)
1494 some_nonuppercase_initial = 1;
1495 else
1496 some_multiletter_word = 1;
1498 else if (!NOCASEP (c))
1500 some_uppercase = 1;
1501 if (SYNTAX (prevc) != Sword)
1503 else
1504 some_multiletter_word = 1;
1506 else
1508 /* If the initial is a caseless word constituent,
1509 treat that like a lowercase initial. */
1510 if (SYNTAX (prevc) != Sword)
1511 some_nonuppercase_initial = 1;
1514 prevc = c;
1517 /* Convert to all caps if the old text is all caps
1518 and has at least one multiletter word. */
1519 if (! some_lowercase && some_multiletter_word)
1520 case_action = all_caps;
1521 /* Capitalize each word, if the old text has all capitalized words. */
1522 else if (!some_nonuppercase_initial && some_multiletter_word)
1523 case_action = cap_initial;
1524 else if (!some_nonuppercase_initial && some_uppercase)
1525 /* Should x -> yz, operating on X, give Yz or YZ?
1526 We'll assume the latter. */
1527 case_action = all_caps;
1528 else
1529 case_action = nochange;
1532 /* Do replacement in a string. */
1533 if (!NILP (string))
1535 Lisp_Object before, after;
1537 before = Fsubstring (string, make_number (0),
1538 make_number (search_regs.start[sub]));
1539 after = Fsubstring (string, make_number (search_regs.end[sub]), Qnil);
1541 /* Substitute parts of the match into NEWTEXT
1542 if desired. */
1543 if (NILP (literal))
1545 int lastpos = -1;
1546 /* We build up the substituted string in ACCUM. */
1547 Lisp_Object accum;
1548 Lisp_Object middle;
1550 accum = Qnil;
1552 for (pos = 0; pos < XSTRING (newtext)->size; pos++)
1554 int substart = -1;
1555 int subend;
1556 int delbackslash = 0;
1558 c = XSTRING (newtext)->data[pos];
1559 if (c == '\\')
1561 c = XSTRING (newtext)->data[++pos];
1562 if (c == '&')
1564 substart = search_regs.start[sub];
1565 subend = search_regs.end[sub];
1567 else if (c >= '1' && c <= '9' && c <= search_regs.num_regs + '0')
1569 if (search_regs.start[c - '0'] >= 0)
1571 substart = search_regs.start[c - '0'];
1572 subend = search_regs.end[c - '0'];
1575 else if (c == '\\')
1576 delbackslash = 1;
1577 else
1578 error ("Invalid use of `\\' in replacement text");
1580 if (substart >= 0)
1582 if (pos - 1 != lastpos + 1)
1583 middle = Fsubstring (newtext,
1584 make_number (lastpos + 1),
1585 make_number (pos - 1));
1586 else
1587 middle = Qnil;
1588 accum = concat3 (accum, middle,
1589 Fsubstring (string, make_number (substart),
1590 make_number (subend)));
1591 lastpos = pos;
1593 else if (delbackslash)
1595 middle = Fsubstring (newtext, make_number (lastpos + 1),
1596 make_number (pos));
1597 accum = concat2 (accum, middle);
1598 lastpos = pos;
1602 if (pos != lastpos + 1)
1603 middle = Fsubstring (newtext, make_number (lastpos + 1),
1604 make_number (pos));
1605 else
1606 middle = Qnil;
1608 newtext = concat2 (accum, middle);
1611 /* Do case substitution in NEWTEXT if desired. */
1612 if (case_action == all_caps)
1613 newtext = Fupcase (newtext);
1614 else if (case_action == cap_initial)
1615 newtext = Fupcase_initials (newtext);
1617 return concat3 (before, newtext, after);
1620 /* Record point, the move (quietly) to the start of the match. */
1621 if (PT > search_regs.start[sub])
1622 opoint = PT - ZV;
1623 else
1624 opoint = PT;
1626 temp_set_point (search_regs.start[sub], current_buffer);
1628 /* We insert the replacement text before the old text, and then
1629 delete the original text. This means that markers at the
1630 beginning or end of the original will float to the corresponding
1631 position in the replacement. */
1632 if (!NILP (literal))
1633 Finsert_and_inherit (1, &newtext);
1634 else
1636 struct gcpro gcpro1;
1637 GCPRO1 (newtext);
1639 for (pos = 0; pos < XSTRING (newtext)->size; pos++)
1641 int offset = PT - search_regs.start[sub];
1643 c = XSTRING (newtext)->data[pos];
1644 if (c == '\\')
1646 c = XSTRING (newtext)->data[++pos];
1647 if (c == '&')
1648 Finsert_buffer_substring
1649 (Fcurrent_buffer (),
1650 make_number (search_regs.start[sub] + offset),
1651 make_number (search_regs.end[sub] + offset));
1652 else if (c >= '1' && c <= '9' && c <= search_regs.num_regs + '0')
1654 if (search_regs.start[c - '0'] >= 1)
1655 Finsert_buffer_substring
1656 (Fcurrent_buffer (),
1657 make_number (search_regs.start[c - '0'] + offset),
1658 make_number (search_regs.end[c - '0'] + offset));
1660 else if (c == '\\')
1661 insert_char (c);
1662 else
1663 error ("Invalid use of `\\' in replacement text");
1665 else
1666 insert_char (c);
1668 UNGCPRO;
1671 inslen = PT - (search_regs.start[sub]);
1672 del_range (search_regs.start[sub] + inslen, search_regs.end[sub] + inslen);
1674 if (case_action == all_caps)
1675 Fupcase_region (make_number (PT - inslen), make_number (PT));
1676 else if (case_action == cap_initial)
1677 Fupcase_initials_region (make_number (PT - inslen), make_number (PT));
1679 newpoint = PT;
1681 /* Put point back where it was in the text. */
1682 if (opoint <= 0)
1683 temp_set_point (opoint + ZV, current_buffer);
1684 else
1685 temp_set_point (opoint, current_buffer);
1687 /* Now move point "officially" to the start of the inserted replacement. */
1688 move_if_not_intangible (newpoint);
1690 return Qnil;
1693 static Lisp_Object
1694 match_limit (num, beginningp)
1695 Lisp_Object num;
1696 int beginningp;
1698 register int n;
1700 CHECK_NUMBER (num, 0);
1701 n = XINT (num);
1702 if (n < 0 || n >= search_regs.num_regs)
1703 args_out_of_range (num, make_number (search_regs.num_regs));
1704 if (search_regs.num_regs <= 0
1705 || search_regs.start[n] < 0)
1706 return Qnil;
1707 return (make_number ((beginningp) ? search_regs.start[n]
1708 : search_regs.end[n]));
1711 DEFUN ("match-beginning", Fmatch_beginning, Smatch_beginning, 1, 1, 0,
1712 "Return position of start of text matched by last search.\n\
1713 SUBEXP, a number, specifies which parenthesized expression in the last\n\
1714 regexp.\n\
1715 Value is nil if SUBEXPth pair didn't match, or there were less than\n\
1716 SUBEXP pairs.\n\
1717 Zero means the entire text matched by the whole regexp or whole string.")
1718 (subexp)
1719 Lisp_Object subexp;
1721 return match_limit (subexp, 1);
1724 DEFUN ("match-end", Fmatch_end, Smatch_end, 1, 1, 0,
1725 "Return position of end of text matched by last search.\n\
1726 SUBEXP, a number, specifies which parenthesized expression in the last\n\
1727 regexp.\n\
1728 Value is nil if SUBEXPth pair didn't match, or there were less than\n\
1729 SUBEXP pairs.\n\
1730 Zero means the entire text matched by the whole regexp or whole string.")
1731 (subexp)
1732 Lisp_Object subexp;
1734 return match_limit (subexp, 0);
1737 DEFUN ("match-data", Fmatch_data, Smatch_data, 0, 2, 0,
1738 "Return a list containing all info on what the last search matched.\n\
1739 Element 2N is `(match-beginning N)'; element 2N + 1 is `(match-end N)'.\n\
1740 All the elements are markers or nil (nil if the Nth pair didn't match)\n\
1741 if the last match was on a buffer; integers or nil if a string was matched.\n\
1742 Use `store-match-data' to reinstate the data in this list.\n\
1744 If INTEGERS (the optional first argument) is non-nil, always use integers\n\
1745 \(rather than markers) to represent buffer positions.\n\
1746 If REUSE is a list, reuse it as part of the value. If REUSE is long enough\n\
1747 to hold all the values, and if INTEGERS is non-nil, no consing is done.")
1748 (integers, reuse)
1749 Lisp_Object integers, reuse;
1751 Lisp_Object tail, prev;
1752 Lisp_Object *data;
1753 int i, len;
1755 if (NILP (last_thing_searched))
1756 return Qnil;
1758 data = (Lisp_Object *) alloca ((2 * search_regs.num_regs)
1759 * sizeof (Lisp_Object));
1761 len = -1;
1762 for (i = 0; i < search_regs.num_regs; i++)
1764 int start = search_regs.start[i];
1765 if (start >= 0)
1767 if (EQ (last_thing_searched, Qt)
1768 || ! NILP (integers))
1770 XSETFASTINT (data[2 * i], start);
1771 XSETFASTINT (data[2 * i + 1], search_regs.end[i]);
1773 else if (BUFFERP (last_thing_searched))
1775 data[2 * i] = Fmake_marker ();
1776 Fset_marker (data[2 * i],
1777 make_number (start),
1778 last_thing_searched);
1779 data[2 * i + 1] = Fmake_marker ();
1780 Fset_marker (data[2 * i + 1],
1781 make_number (search_regs.end[i]),
1782 last_thing_searched);
1784 else
1785 /* last_thing_searched must always be Qt, a buffer, or Qnil. */
1786 abort ();
1788 len = i;
1790 else
1791 data[2 * i] = data [2 * i + 1] = Qnil;
1794 /* If REUSE is not usable, cons up the values and return them. */
1795 if (! CONSP (reuse))
1796 return Flist (2 * len + 2, data);
1798 /* If REUSE is a list, store as many value elements as will fit
1799 into the elements of REUSE. */
1800 for (i = 0, tail = reuse; CONSP (tail);
1801 i++, tail = XCONS (tail)->cdr)
1803 if (i < 2 * len + 2)
1804 XCONS (tail)->car = data[i];
1805 else
1806 XCONS (tail)->car = Qnil;
1807 prev = tail;
1810 /* If we couldn't fit all value elements into REUSE,
1811 cons up the rest of them and add them to the end of REUSE. */
1812 if (i < 2 * len + 2)
1813 XCONS (prev)->cdr = Flist (2 * len + 2 - i, data + i);
1815 return reuse;
1819 DEFUN ("store-match-data", Fstore_match_data, Sstore_match_data, 1, 1, 0,
1820 "Set internal data on last search match from elements of LIST.\n\
1821 LIST should have been created by calling `match-data' previously.")
1822 (list)
1823 register Lisp_Object list;
1825 register int i;
1826 register Lisp_Object marker;
1828 if (running_asynch_code)
1829 save_search_regs ();
1831 if (!CONSP (list) && !NILP (list))
1832 list = wrong_type_argument (Qconsp, list);
1834 /* Unless we find a marker with a buffer in LIST, assume that this
1835 match data came from a string. */
1836 last_thing_searched = Qt;
1838 /* Allocate registers if they don't already exist. */
1840 int length = XFASTINT (Flength (list)) / 2;
1842 if (length > search_regs.num_regs)
1844 if (search_regs.num_regs == 0)
1846 search_regs.start
1847 = (regoff_t *) xmalloc (length * sizeof (regoff_t));
1848 search_regs.end
1849 = (regoff_t *) xmalloc (length * sizeof (regoff_t));
1851 else
1853 search_regs.start
1854 = (regoff_t *) xrealloc (search_regs.start,
1855 length * sizeof (regoff_t));
1856 search_regs.end
1857 = (regoff_t *) xrealloc (search_regs.end,
1858 length * sizeof (regoff_t));
1861 search_regs.num_regs = length;
1865 for (i = 0; i < search_regs.num_regs; i++)
1867 marker = Fcar (list);
1868 if (NILP (marker))
1870 search_regs.start[i] = -1;
1871 list = Fcdr (list);
1873 else
1875 if (MARKERP (marker))
1877 if (XMARKER (marker)->buffer == 0)
1878 XSETFASTINT (marker, 0);
1879 else
1880 XSETBUFFER (last_thing_searched, XMARKER (marker)->buffer);
1883 CHECK_NUMBER_COERCE_MARKER (marker, 0);
1884 search_regs.start[i] = XINT (marker);
1885 list = Fcdr (list);
1887 marker = Fcar (list);
1888 if (MARKERP (marker) && XMARKER (marker)->buffer == 0)
1889 XSETFASTINT (marker, 0);
1891 CHECK_NUMBER_COERCE_MARKER (marker, 0);
1892 search_regs.end[i] = XINT (marker);
1894 list = Fcdr (list);
1897 return Qnil;
1900 /* If non-zero the match data have been saved in saved_search_regs
1901 during the execution of a sentinel or filter. */
1902 static int search_regs_saved;
1903 static struct re_registers saved_search_regs;
1905 /* Called from Flooking_at, Fstring_match, search_buffer, Fstore_match_data
1906 if asynchronous code (filter or sentinel) is running. */
1907 static void
1908 save_search_regs ()
1910 if (!search_regs_saved)
1912 saved_search_regs.num_regs = search_regs.num_regs;
1913 saved_search_regs.start = search_regs.start;
1914 saved_search_regs.end = search_regs.end;
1915 search_regs.num_regs = 0;
1916 search_regs.start = 0;
1917 search_regs.end = 0;
1919 search_regs_saved = 1;
1923 /* Called upon exit from filters and sentinels. */
1924 void
1925 restore_match_data ()
1927 if (search_regs_saved)
1929 if (search_regs.num_regs > 0)
1931 xfree (search_regs.start);
1932 xfree (search_regs.end);
1934 search_regs.num_regs = saved_search_regs.num_regs;
1935 search_regs.start = saved_search_regs.start;
1936 search_regs.end = saved_search_regs.end;
1938 search_regs_saved = 0;
1942 /* Quote a string to inactivate reg-expr chars */
1944 DEFUN ("regexp-quote", Fregexp_quote, Sregexp_quote, 1, 1, 0,
1945 "Return a regexp string which matches exactly STRING and nothing else.")
1946 (string)
1947 Lisp_Object string;
1949 register unsigned char *in, *out, *end;
1950 register unsigned char *temp;
1952 CHECK_STRING (string, 0);
1954 temp = (unsigned char *) alloca (XSTRING (string)->size * 2);
1956 /* Now copy the data into the new string, inserting escapes. */
1958 in = XSTRING (string)->data;
1959 end = in + XSTRING (string)->size;
1960 out = temp;
1962 for (; in != end; in++)
1964 if (*in == '[' || *in == ']'
1965 || *in == '*' || *in == '.' || *in == '\\'
1966 || *in == '?' || *in == '+'
1967 || *in == '^' || *in == '$')
1968 *out++ = '\\';
1969 *out++ = *in;
1972 return make_string (temp, out - temp);
1975 syms_of_search ()
1977 register int i;
1979 for (i = 0; i < REGEXP_CACHE_SIZE; ++i)
1981 searchbufs[i].buf.allocated = 100;
1982 searchbufs[i].buf.buffer = (unsigned char *) malloc (100);
1983 searchbufs[i].buf.fastmap = searchbufs[i].fastmap;
1984 searchbufs[i].regexp = Qnil;
1985 staticpro (&searchbufs[i].regexp);
1986 searchbufs[i].next = (i == REGEXP_CACHE_SIZE-1 ? 0 : &searchbufs[i+1]);
1988 searchbuf_head = &searchbufs[0];
1990 Qsearch_failed = intern ("search-failed");
1991 staticpro (&Qsearch_failed);
1992 Qinvalid_regexp = intern ("invalid-regexp");
1993 staticpro (&Qinvalid_regexp);
1995 Fput (Qsearch_failed, Qerror_conditions,
1996 Fcons (Qsearch_failed, Fcons (Qerror, Qnil)));
1997 Fput (Qsearch_failed, Qerror_message,
1998 build_string ("Search failed"));
2000 Fput (Qinvalid_regexp, Qerror_conditions,
2001 Fcons (Qinvalid_regexp, Fcons (Qerror, Qnil)));
2002 Fput (Qinvalid_regexp, Qerror_message,
2003 build_string ("Invalid regexp"));
2005 last_thing_searched = Qnil;
2006 staticpro (&last_thing_searched);
2008 defsubr (&Slooking_at);
2009 defsubr (&Sposix_looking_at);
2010 defsubr (&Sstring_match);
2011 defsubr (&Sposix_string_match);
2012 defsubr (&Ssearch_forward);
2013 defsubr (&Ssearch_backward);
2014 defsubr (&Sword_search_forward);
2015 defsubr (&Sword_search_backward);
2016 defsubr (&Sre_search_forward);
2017 defsubr (&Sre_search_backward);
2018 defsubr (&Sposix_search_forward);
2019 defsubr (&Sposix_search_backward);
2020 defsubr (&Sreplace_match);
2021 defsubr (&Smatch_beginning);
2022 defsubr (&Smatch_end);
2023 defsubr (&Smatch_data);
2024 defsubr (&Sstore_match_data);
2025 defsubr (&Sregexp_quote);