*** empty log message ***
[emacs.git] / src / search.c
blob44795bd1dad2ca93b655c95b97fe0dc8122a5c30
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, 675 Mass Ave, Cambridge, MA 02139, USA. */
21 #include <config.h>
22 #include "lisp.h"
23 #include "syntax.h"
24 #include "buffer.h"
25 #include "region-cache.h"
26 #include "commands.h"
27 #include "blockinput.h"
29 #include <sys/types.h>
30 #include "regex.h"
32 #define REGEXP_CACHE_SIZE 5
34 /* If the regexp is non-nil, then the buffer contains the compiled form
35 of that regexp, suitable for searching. */
36 struct regexp_cache {
37 struct regexp_cache *next;
38 Lisp_Object regexp;
39 struct re_pattern_buffer buf;
40 char fastmap[0400];
41 /* Nonzero means regexp was compiled to do full POSIX backtracking. */
42 char posix;
45 /* The instances of that struct. */
46 struct regexp_cache searchbufs[REGEXP_CACHE_SIZE];
48 /* The head of the linked list; points to the most recently used buffer. */
49 struct regexp_cache *searchbuf_head;
52 /* Every call to re_match, etc., must pass &search_regs as the regs
53 argument unless you can show it is unnecessary (i.e., if re_match
54 is certainly going to be called again before region-around-match
55 can be called).
57 Since the registers are now dynamically allocated, we need to make
58 sure not to refer to the Nth register before checking that it has
59 been allocated by checking search_regs.num_regs.
61 The regex code keeps track of whether it has allocated the search
62 buffer using bits in the re_pattern_buffer. This means that whenever
63 you compile a new pattern, it completely forgets whether it has
64 allocated any registers, and will allocate new registers the next
65 time you call a searching or matching function. Therefore, we need
66 to call re_set_registers after compiling a new pattern or after
67 setting the match registers, so that the regex functions will be
68 able to free or re-allocate it properly. */
69 static struct re_registers search_regs;
71 /* The buffer in which the last search was performed, or
72 Qt if the last search was done in a string;
73 Qnil if no searching has been done yet. */
74 static Lisp_Object last_thing_searched;
76 /* error condition signalled when regexp compile_pattern fails */
78 Lisp_Object Qinvalid_regexp;
80 static void set_search_regs ();
81 static void save_search_regs ();
83 static int search_buffer ();
85 static void
86 matcher_overflow ()
88 error ("Stack overflow in regexp matcher");
91 #ifdef __STDC__
92 #define CONST const
93 #else
94 #define CONST
95 #endif
97 /* Compile a regexp and signal a Lisp error if anything goes wrong.
98 PATTERN is the pattern to compile.
99 CP is the place to put the result.
100 TRANSLATE is a translation table for ignoring case, or NULL for none.
101 REGP is the structure that says where to store the "register"
102 values that will result from matching this pattern.
103 If it is 0, we should compile the pattern not to record any
104 subexpression bounds.
105 POSIX is nonzero if we want full backtracking (POSIX style)
106 for this pattern. 0 means backtrack only enough to get a valid match. */
108 static void
109 compile_pattern_1 (cp, pattern, translate, regp, posix)
110 struct regexp_cache *cp;
111 Lisp_Object pattern;
112 char *translate;
113 struct re_registers *regp;
114 int posix;
116 CONST char *val;
117 reg_syntax_t old;
119 cp->regexp = Qnil;
120 cp->buf.translate = translate;
121 cp->posix = posix;
122 BLOCK_INPUT;
123 old = re_set_syntax (RE_SYNTAX_EMACS
124 | (posix ? 0 : RE_NO_POSIX_BACKTRACKING));
125 val = (CONST char *) re_compile_pattern ((char *) XSTRING (pattern)->data,
126 XSTRING (pattern)->size, &cp->buf);
127 re_set_syntax (old);
128 UNBLOCK_INPUT;
129 if (val)
130 Fsignal (Qinvalid_regexp, Fcons (build_string (val), Qnil));
132 cp->regexp = Fcopy_sequence (pattern);
135 /* Compile a regexp if necessary, but first check to see if there's one in
136 the cache.
137 PATTERN is the pattern to compile.
138 TRANSLATE is a translation table for ignoring case, or NULL for none.
139 REGP is the structure that says where to store the "register"
140 values that will result from matching this pattern.
141 If it is 0, we should compile the pattern not to record any
142 subexpression bounds.
143 POSIX is nonzero if we want full backtracking (POSIX style)
144 for this pattern. 0 means backtrack only enough to get a valid match. */
146 struct re_pattern_buffer *
147 compile_pattern (pattern, regp, translate, posix)
148 Lisp_Object pattern;
149 struct re_registers *regp;
150 char *translate;
151 int posix;
153 struct regexp_cache *cp, **cpp;
155 for (cpp = &searchbuf_head; ; cpp = &cp->next)
157 cp = *cpp;
158 if (!NILP (Fstring_equal (cp->regexp, pattern))
159 && cp->buf.translate == translate
160 && cp->posix == posix)
161 break;
163 /* If we're at the end of the cache, compile into the last cell. */
164 if (cp->next == 0)
166 compile_pattern_1 (cp, pattern, translate, regp, posix);
167 break;
171 /* When we get here, cp (aka *cpp) contains the compiled pattern,
172 either because we found it in the cache or because we just compiled it.
173 Move it to the front of the queue to mark it as most recently used. */
174 *cpp = cp->next;
175 cp->next = searchbuf_head;
176 searchbuf_head = cp;
178 /* Advise the searching functions about the space we have allocated
179 for register data. */
180 if (regp)
181 re_set_registers (&cp->buf, regp, regp->num_regs, regp->start, regp->end);
183 return &cp->buf;
186 /* Error condition used for failing searches */
187 Lisp_Object Qsearch_failed;
189 Lisp_Object
190 signal_failure (arg)
191 Lisp_Object arg;
193 Fsignal (Qsearch_failed, Fcons (arg, Qnil));
194 return Qnil;
197 static Lisp_Object
198 looking_at_1 (string, posix)
199 Lisp_Object string;
200 int posix;
202 Lisp_Object val;
203 unsigned char *p1, *p2;
204 int s1, s2;
205 register int i;
206 struct re_pattern_buffer *bufp;
208 if (running_asynch_code)
209 save_search_regs ();
211 CHECK_STRING (string, 0);
212 bufp = compile_pattern (string, &search_regs,
213 (!NILP (current_buffer->case_fold_search)
214 ? DOWNCASE_TABLE : 0),
215 posix);
217 immediate_quit = 1;
218 QUIT; /* Do a pending quit right away, to avoid paradoxical behavior */
220 /* Get pointers and sizes of the two strings
221 that make up the visible portion of the buffer. */
223 p1 = BEGV_ADDR;
224 s1 = GPT - BEGV;
225 p2 = GAP_END_ADDR;
226 s2 = ZV - GPT;
227 if (s1 < 0)
229 p2 = p1;
230 s2 = ZV - BEGV;
231 s1 = 0;
233 if (s2 < 0)
235 s1 = ZV - BEGV;
236 s2 = 0;
239 i = re_match_2 (bufp, (char *) p1, s1, (char *) p2, s2,
240 point - BEGV, &search_regs,
241 ZV - BEGV);
242 if (i == -2)
243 matcher_overflow ();
245 val = (0 <= i ? Qt : Qnil);
246 for (i = 0; i < search_regs.num_regs; i++)
247 if (search_regs.start[i] >= 0)
249 search_regs.start[i] += BEGV;
250 search_regs.end[i] += BEGV;
252 XSETBUFFER (last_thing_searched, current_buffer);
253 immediate_quit = 0;
254 return val;
257 DEFUN ("looking-at", Flooking_at, Slooking_at, 1, 1, 0,
258 "Return t if text after point matches regular expression REGEXP.\n\
259 This function modifies the match data that `match-beginning',\n\
260 `match-end' and `match-data' access; save and restore the match\n\
261 data if you want to preserve them.")
262 (regexp)
263 Lisp_Object regexp;
265 return looking_at_1 (regexp, 0);
268 DEFUN ("posix-looking-at", Fposix_looking_at, Sposix_looking_at, 1, 1, 0,
269 "Return t if text after point matches regular expression REGEXP.\n\
270 Find the longest match, in accord with Posix regular expression rules.\n\
271 This function modifies the match data that `match-beginning',\n\
272 `match-end' and `match-data' access; save and restore the match\n\
273 data if you want to preserve them.")
274 (regexp)
275 Lisp_Object regexp;
277 return looking_at_1 (regexp, 1);
280 static Lisp_Object
281 string_match_1 (regexp, string, start, posix)
282 Lisp_Object regexp, string, start;
283 int posix;
285 int val;
286 int s;
287 struct re_pattern_buffer *bufp;
289 if (running_asynch_code)
290 save_search_regs ();
292 CHECK_STRING (regexp, 0);
293 CHECK_STRING (string, 1);
295 if (NILP (start))
296 s = 0;
297 else
299 int len = XSTRING (string)->size;
301 CHECK_NUMBER (start, 2);
302 s = XINT (start);
303 if (s < 0 && -s <= len)
304 s = len + s;
305 else if (0 > s || s > len)
306 args_out_of_range (string, start);
309 bufp = compile_pattern (regexp, &search_regs,
310 (!NILP (current_buffer->case_fold_search)
311 ? DOWNCASE_TABLE : 0),
313 immediate_quit = 1;
314 val = re_search (bufp, (char *) XSTRING (string)->data,
315 XSTRING (string)->size, s, XSTRING (string)->size - s,
316 &search_regs);
317 immediate_quit = 0;
318 last_thing_searched = Qt;
319 if (val == -2)
320 matcher_overflow ();
321 if (val < 0) return Qnil;
322 return make_number (val);
325 DEFUN ("string-match", Fstring_match, Sstring_match, 2, 3, 0,
326 "Return index of start of first match for REGEXP in STRING, or nil.\n\
327 If third arg START is non-nil, start search at that index in STRING.\n\
328 For index of first char beyond the match, do (match-end 0).\n\
329 `match-end' and `match-beginning' also give indices of substrings\n\
330 matched by parenthesis constructs in the pattern.")
331 (regexp, string, start)
332 Lisp_Object regexp, string, start;
334 return string_match_1 (regexp, string, start, 0);
337 DEFUN ("posix-string-match", Fposix_string_match, Sposix_string_match, 2, 3, 0,
338 "Return index of start of first match for REGEXP in STRING, or nil.\n\
339 Find the longest match, in accord with Posix regular expression rules.\n\
340 If third arg START is non-nil, start search at that index in STRING.\n\
341 For index of first char beyond the match, do (match-end 0).\n\
342 `match-end' and `match-beginning' also give indices of substrings\n\
343 matched by parenthesis constructs in the pattern.")
344 (regexp, string, start)
345 Lisp_Object regexp, string, start;
347 return string_match_1 (regexp, string, start, 1);
350 /* Match REGEXP against STRING, searching all of STRING,
351 and return the index of the match, or negative on failure.
352 This does not clobber the match data. */
355 fast_string_match (regexp, string)
356 Lisp_Object regexp, string;
358 int val;
359 struct re_pattern_buffer *bufp;
361 bufp = compile_pattern (regexp, 0, 0, 0);
362 immediate_quit = 1;
363 val = re_search (bufp, (char *) XSTRING (string)->data,
364 XSTRING (string)->size, 0, XSTRING (string)->size,
366 immediate_quit = 0;
367 return val;
370 /* max and min. */
372 static int
373 max (a, b)
374 int a, b;
376 return ((a > b) ? a : b);
379 static int
380 min (a, b)
381 int a, b;
383 return ((a < b) ? a : b);
387 /* The newline cache: remembering which sections of text have no newlines. */
389 /* If the user has requested newline caching, make sure it's on.
390 Otherwise, make sure it's off.
391 This is our cheezy way of associating an action with the change of
392 state of a buffer-local variable. */
393 static void
394 newline_cache_on_off (buf)
395 struct buffer *buf;
397 if (NILP (buf->cache_long_line_scans))
399 /* It should be off. */
400 if (buf->newline_cache)
402 free_region_cache (buf->newline_cache);
403 buf->newline_cache = 0;
406 else
408 /* It should be on. */
409 if (buf->newline_cache == 0)
410 buf->newline_cache = new_region_cache ();
415 /* Search for COUNT instances of the character TARGET between START and END.
417 If COUNT is positive, search forwards; END must be >= START.
418 If COUNT is negative, search backwards for the -COUNTth instance;
419 END must be <= START.
420 If COUNT is zero, do anything you please; run rogue, for all I care.
422 If END is zero, use BEGV or ZV instead, as appropriate for the
423 direction indicated by COUNT.
425 If we find COUNT instances, set *SHORTAGE to zero, and return the
426 position after the COUNTth match. Note that for reverse motion
427 this is not the same as the usual convention for Emacs motion commands.
429 If we don't find COUNT instances before reaching END, set *SHORTAGE
430 to the number of TARGETs left unfound, and return END.
432 If ALLOW_QUIT is non-zero, set immediate_quit. That's good to do
433 except when inside redisplay. */
435 scan_buffer (target, start, end, count, shortage, allow_quit)
436 register int target;
437 int start, end;
438 int count;
439 int *shortage;
440 int allow_quit;
442 struct region_cache *newline_cache;
443 int direction;
445 if (count > 0)
447 direction = 1;
448 if (! end) end = ZV;
450 else
452 direction = -1;
453 if (! end) end = BEGV;
456 newline_cache_on_off (current_buffer);
457 newline_cache = current_buffer->newline_cache;
459 if (shortage != 0)
460 *shortage = 0;
462 immediate_quit = allow_quit;
464 if (count > 0)
465 while (start != end)
467 /* Our innermost scanning loop is very simple; it doesn't know
468 about gaps, buffer ends, or the newline cache. ceiling is
469 the position of the last character before the next such
470 obstacle --- the last character the dumb search loop should
471 examine. */
472 register int ceiling = end - 1;
474 /* If we're looking for a newline, consult the newline cache
475 to see where we can avoid some scanning. */
476 if (target == '\n' && newline_cache)
478 int next_change;
479 immediate_quit = 0;
480 while (region_cache_forward
481 (current_buffer, newline_cache, start, &next_change))
482 start = next_change;
483 immediate_quit = allow_quit;
485 /* start should never be after end. */
486 if (start >= end)
487 start = end - 1;
489 /* Now the text after start is an unknown region, and
490 next_change is the position of the next known region. */
491 ceiling = min (next_change - 1, ceiling);
494 /* The dumb loop can only scan text stored in contiguous
495 bytes. BUFFER_CEILING_OF returns the last character
496 position that is contiguous, so the ceiling is the
497 position after that. */
498 ceiling = min (BUFFER_CEILING_OF (start), ceiling);
501 /* The termination address of the dumb loop. */
502 register unsigned char *ceiling_addr = &FETCH_CHAR (ceiling) + 1;
503 register unsigned char *cursor = &FETCH_CHAR (start);
504 unsigned char *base = cursor;
506 while (cursor < ceiling_addr)
508 unsigned char *scan_start = cursor;
510 /* The dumb loop. */
511 while (*cursor != target && ++cursor < ceiling_addr)
514 /* If we're looking for newlines, cache the fact that
515 the region from start to cursor is free of them. */
516 if (target == '\n' && newline_cache)
517 know_region_cache (current_buffer, newline_cache,
518 start + scan_start - base,
519 start + cursor - base);
521 /* Did we find the target character? */
522 if (cursor < ceiling_addr)
524 if (--count == 0)
526 immediate_quit = 0;
527 return (start + cursor - base + 1);
529 cursor++;
533 start += cursor - base;
536 else
537 while (start > end)
539 /* The last character to check before the next obstacle. */
540 register int ceiling = end;
542 /* Consult the newline cache, if appropriate. */
543 if (target == '\n' && newline_cache)
545 int next_change;
546 immediate_quit = 0;
547 while (region_cache_backward
548 (current_buffer, newline_cache, start, &next_change))
549 start = next_change;
550 immediate_quit = allow_quit;
552 /* Start should never be at or before end. */
553 if (start <= end)
554 start = end + 1;
556 /* Now the text before start is an unknown region, and
557 next_change is the position of the next known region. */
558 ceiling = max (next_change, ceiling);
561 /* Stop scanning before the gap. */
562 ceiling = max (BUFFER_FLOOR_OF (start - 1), ceiling);
565 /* The termination address of the dumb loop. */
566 register unsigned char *ceiling_addr = &FETCH_CHAR (ceiling);
567 register unsigned char *cursor = &FETCH_CHAR (start - 1);
568 unsigned char *base = cursor;
570 while (cursor >= ceiling_addr)
572 unsigned char *scan_start = cursor;
574 while (*cursor != target && --cursor >= ceiling_addr)
577 /* If we're looking for newlines, cache the fact that
578 the region from after the cursor to start is free of them. */
579 if (target == '\n' && newline_cache)
580 know_region_cache (current_buffer, newline_cache,
581 start + cursor - base,
582 start + scan_start - base);
584 /* Did we find the target character? */
585 if (cursor >= ceiling_addr)
587 if (++count >= 0)
589 immediate_quit = 0;
590 return (start + cursor - base);
592 cursor--;
596 start += cursor - base;
600 immediate_quit = 0;
601 if (shortage != 0)
602 *shortage = count * direction;
603 return start;
607 find_next_newline_no_quit (from, cnt)
608 register int from, cnt;
610 return scan_buffer ('\n', from, 0, cnt, (int *) 0, 0);
614 find_next_newline (from, cnt)
615 register int from, cnt;
617 return scan_buffer ('\n', from, 0, cnt, (int *) 0, 1);
621 /* Like find_next_newline, but returns position before the newline,
622 not after, and only search up to TO. This isn't just
623 find_next_newline (...)-1, because you might hit TO. */
625 find_before_next_newline (from, to, cnt)
626 int from, to, cnt;
628 int shortage;
629 int pos = scan_buffer ('\n', from, to, cnt, &shortage, 1);
631 if (shortage == 0)
632 pos--;
634 return pos;
637 Lisp_Object skip_chars ();
639 DEFUN ("skip-chars-forward", Fskip_chars_forward, Sskip_chars_forward, 1, 2, 0,
640 "Move point forward, stopping before a char not in STRING, or at pos LIM.\n\
641 STRING is like the inside of a `[...]' in a regular expression\n\
642 except that `]' is never special and `\\' quotes `^', `-' or `\\'.\n\
643 Thus, with arg \"a-zA-Z\", this skips letters stopping before first nonletter.\n\
644 With arg \"^a-zA-Z\", skips nonletters stopping before first letter.\n\
645 Returns the distance traveled, either zero or positive.")
646 (string, lim)
647 Lisp_Object string, lim;
649 return skip_chars (1, 0, string, lim);
652 DEFUN ("skip-chars-backward", Fskip_chars_backward, Sskip_chars_backward, 1, 2, 0,
653 "Move point backward, stopping after a char not in STRING, or at pos LIM.\n\
654 See `skip-chars-forward' for details.\n\
655 Returns the distance traveled, either zero or negative.")
656 (string, lim)
657 Lisp_Object string, lim;
659 return skip_chars (0, 0, string, lim);
662 DEFUN ("skip-syntax-forward", Fskip_syntax_forward, Sskip_syntax_forward, 1, 2, 0,
663 "Move point forward across chars in specified syntax classes.\n\
664 SYNTAX is a string of syntax code characters.\n\
665 Stop before a char whose syntax is not in SYNTAX, or at position LIM.\n\
666 If SYNTAX starts with ^, skip characters whose syntax is NOT in SYNTAX.\n\
667 This function returns the distance traveled, either zero or positive.")
668 (syntax, lim)
669 Lisp_Object syntax, lim;
671 return skip_chars (1, 1, syntax, lim);
674 DEFUN ("skip-syntax-backward", Fskip_syntax_backward, Sskip_syntax_backward, 1, 2, 0,
675 "Move point backward across chars in specified syntax classes.\n\
676 SYNTAX is a string of syntax code characters.\n\
677 Stop on reaching a char whose syntax is not in SYNTAX, or at position LIM.\n\
678 If SYNTAX starts with ^, skip characters whose syntax is NOT in SYNTAX.\n\
679 This function returns the distance traveled, either zero or negative.")
680 (syntax, lim)
681 Lisp_Object syntax, lim;
683 return skip_chars (0, 1, syntax, lim);
686 Lisp_Object
687 skip_chars (forwardp, syntaxp, string, lim)
688 int forwardp, syntaxp;
689 Lisp_Object string, lim;
691 register unsigned char *p, *pend;
692 register unsigned char c;
693 unsigned char fastmap[0400];
694 int negate = 0;
695 register int i;
697 CHECK_STRING (string, 0);
699 if (NILP (lim))
700 XSETINT (lim, forwardp ? ZV : BEGV);
701 else
702 CHECK_NUMBER_COERCE_MARKER (lim, 1);
704 /* In any case, don't allow scan outside bounds of buffer. */
705 /* jla turned this off, for no known reason.
706 bfox turned the ZV part on, and rms turned the
707 BEGV part back on. */
708 if (XINT (lim) > ZV)
709 XSETFASTINT (lim, ZV);
710 if (XINT (lim) < BEGV)
711 XSETFASTINT (lim, BEGV);
713 p = XSTRING (string)->data;
714 pend = p + XSTRING (string)->size;
715 bzero (fastmap, sizeof fastmap);
717 if (p != pend && *p == '^')
719 negate = 1; p++;
722 /* Find the characters specified and set their elements of fastmap.
723 If syntaxp, each character counts as itself.
724 Otherwise, handle backslashes and ranges specially */
726 while (p != pend)
728 c = *p++;
729 if (syntaxp)
730 fastmap[c] = 1;
731 else
733 if (c == '\\')
735 if (p == pend) break;
736 c = *p++;
738 if (p != pend && *p == '-')
740 p++;
741 if (p == pend) break;
742 while (c <= *p)
744 fastmap[c] = 1;
745 c++;
747 p++;
749 else
750 fastmap[c] = 1;
754 if (syntaxp && fastmap['-'] != 0)
755 fastmap[' '] = 1;
757 /* If ^ was the first character, complement the fastmap. */
759 if (negate)
760 for (i = 0; i < sizeof fastmap; i++)
761 fastmap[i] ^= 1;
764 int start_point = point;
766 immediate_quit = 1;
767 if (syntaxp)
770 if (forwardp)
772 while (point < XINT (lim)
773 && fastmap[(unsigned char) syntax_code_spec[(int) SYNTAX (FETCH_CHAR (point))]])
774 SET_PT (point + 1);
776 else
778 while (point > XINT (lim)
779 && fastmap[(unsigned char) syntax_code_spec[(int) SYNTAX (FETCH_CHAR (point - 1))]])
780 SET_PT (point - 1);
783 else
785 if (forwardp)
787 while (point < XINT (lim) && fastmap[FETCH_CHAR (point)])
788 SET_PT (point + 1);
790 else
792 while (point > XINT (lim) && fastmap[FETCH_CHAR (point - 1)])
793 SET_PT (point - 1);
796 immediate_quit = 0;
798 return make_number (point - start_point);
802 /* Subroutines of Lisp buffer search functions. */
804 static Lisp_Object
805 search_command (string, bound, noerror, count, direction, RE, posix)
806 Lisp_Object string, bound, noerror, count;
807 int direction;
808 int RE;
809 int posix;
811 register int np;
812 int lim;
813 int n = direction;
815 if (!NILP (count))
817 CHECK_NUMBER (count, 3);
818 n *= XINT (count);
821 CHECK_STRING (string, 0);
822 if (NILP (bound))
823 lim = n > 0 ? ZV : BEGV;
824 else
826 CHECK_NUMBER_COERCE_MARKER (bound, 1);
827 lim = XINT (bound);
828 if (n > 0 ? lim < point : lim > point)
829 error ("Invalid search bound (wrong side of point)");
830 if (lim > ZV)
831 lim = ZV;
832 if (lim < BEGV)
833 lim = BEGV;
836 np = search_buffer (string, point, lim, n, RE,
837 (!NILP (current_buffer->case_fold_search)
838 ? XSTRING (current_buffer->case_canon_table)->data : 0),
839 (!NILP (current_buffer->case_fold_search)
840 ? XSTRING (current_buffer->case_eqv_table)->data : 0),
841 posix);
842 if (np <= 0)
844 if (NILP (noerror))
845 return signal_failure (string);
846 if (!EQ (noerror, Qt))
848 if (lim < BEGV || lim > ZV)
849 abort ();
850 SET_PT (lim);
851 return Qnil;
852 #if 0 /* This would be clean, but maybe programs depend on
853 a value of nil here. */
854 np = lim;
855 #endif
857 else
858 return Qnil;
861 if (np < BEGV || np > ZV)
862 abort ();
864 SET_PT (np);
866 return make_number (np);
869 static int
870 trivial_regexp_p (regexp)
871 Lisp_Object regexp;
873 int len = XSTRING (regexp)->size;
874 unsigned char *s = XSTRING (regexp)->data;
875 unsigned char c;
876 while (--len >= 0)
878 switch (*s++)
880 case '.': case '*': case '+': case '?': case '[': case '^': case '$':
881 return 0;
882 case '\\':
883 if (--len < 0)
884 return 0;
885 switch (*s++)
887 case '|': case '(': case ')': case '`': case '\'': case 'b':
888 case 'B': case '<': case '>': case 'w': case 'W': case 's':
889 case 'S': case '=':
890 case '1': case '2': case '3': case '4': case '5':
891 case '6': case '7': case '8': case '9':
892 return 0;
896 return 1;
899 /* Search for the n'th occurrence of STRING in the current buffer,
900 starting at position POS and stopping at position LIM,
901 treating STRING as a literal string if RE is false or as
902 a regular expression if RE is true.
904 If N is positive, searching is forward and LIM must be greater than POS.
905 If N is negative, searching is backward and LIM must be less than POS.
907 Returns -x if only N-x occurrences found (x > 0),
908 or else the position at the beginning of the Nth occurrence
909 (if searching backward) or the end (if searching forward).
911 POSIX is nonzero if we want full backtracking (POSIX style)
912 for this pattern. 0 means backtrack only enough to get a valid match. */
914 static int
915 search_buffer (string, pos, lim, n, RE, trt, inverse_trt, posix)
916 Lisp_Object string;
917 int pos;
918 int lim;
919 int n;
920 int RE;
921 register unsigned char *trt;
922 register unsigned char *inverse_trt;
923 int posix;
925 int len = XSTRING (string)->size;
926 unsigned char *base_pat = XSTRING (string)->data;
927 register int *BM_tab;
928 int *BM_tab_base;
929 register int direction = ((n > 0) ? 1 : -1);
930 register int dirlen;
931 int infinity, limit, k, stride_for_teases;
932 register unsigned char *pat, *cursor, *p_limit;
933 register int i, j;
934 unsigned char *p1, *p2;
935 int s1, s2;
937 if (running_asynch_code)
938 save_search_regs ();
940 /* Null string is found at starting position. */
941 if (len == 0)
943 set_search_regs (pos, 0);
944 return pos;
947 /* Searching 0 times means don't move. */
948 if (n == 0)
949 return pos;
951 if (RE && !trivial_regexp_p (string))
953 struct re_pattern_buffer *bufp;
955 bufp = compile_pattern (string, &search_regs, (char *) trt, posix);
957 immediate_quit = 1; /* Quit immediately if user types ^G,
958 because letting this function finish
959 can take too long. */
960 QUIT; /* Do a pending quit right away,
961 to avoid paradoxical behavior */
962 /* Get pointers and sizes of the two strings
963 that make up the visible portion of the buffer. */
965 p1 = BEGV_ADDR;
966 s1 = GPT - BEGV;
967 p2 = GAP_END_ADDR;
968 s2 = ZV - GPT;
969 if (s1 < 0)
971 p2 = p1;
972 s2 = ZV - BEGV;
973 s1 = 0;
975 if (s2 < 0)
977 s1 = ZV - BEGV;
978 s2 = 0;
980 while (n < 0)
982 int val;
983 val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
984 pos - BEGV, lim - pos, &search_regs,
985 /* Don't allow match past current point */
986 pos - BEGV);
987 if (val == -2)
989 matcher_overflow ();
991 if (val >= 0)
993 j = BEGV;
994 for (i = 0; i < search_regs.num_regs; i++)
995 if (search_regs.start[i] >= 0)
997 search_regs.start[i] += j;
998 search_regs.end[i] += j;
1000 XSETBUFFER (last_thing_searched, current_buffer);
1001 /* Set pos to the new position. */
1002 pos = search_regs.start[0];
1004 else
1006 immediate_quit = 0;
1007 return (n);
1009 n++;
1011 while (n > 0)
1013 int val;
1014 val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
1015 pos - BEGV, lim - pos, &search_regs,
1016 lim - BEGV);
1017 if (val == -2)
1019 matcher_overflow ();
1021 if (val >= 0)
1023 j = BEGV;
1024 for (i = 0; i < search_regs.num_regs; i++)
1025 if (search_regs.start[i] >= 0)
1027 search_regs.start[i] += j;
1028 search_regs.end[i] += j;
1030 XSETBUFFER (last_thing_searched, current_buffer);
1031 pos = search_regs.end[0];
1033 else
1035 immediate_quit = 0;
1036 return (0 - n);
1038 n--;
1040 immediate_quit = 0;
1041 return (pos);
1043 else /* non-RE case */
1045 #ifdef C_ALLOCA
1046 int BM_tab_space[0400];
1047 BM_tab = &BM_tab_space[0];
1048 #else
1049 BM_tab = (int *) alloca (0400 * sizeof (int));
1050 #endif
1052 unsigned char *patbuf = (unsigned char *) alloca (len);
1053 pat = patbuf;
1054 while (--len >= 0)
1056 /* If we got here and the RE flag is set, it's because we're
1057 dealing with a regexp known to be trivial, so the backslash
1058 just quotes the next character. */
1059 if (RE && *base_pat == '\\')
1061 len--;
1062 base_pat++;
1064 *pat++ = (trt ? trt[*base_pat++] : *base_pat++);
1066 len = pat - patbuf;
1067 pat = base_pat = patbuf;
1069 /* The general approach is that we are going to maintain that we know */
1070 /* the first (closest to the present position, in whatever direction */
1071 /* we're searching) character that could possibly be the last */
1072 /* (furthest from present position) character of a valid match. We */
1073 /* advance the state of our knowledge by looking at that character */
1074 /* and seeing whether it indeed matches the last character of the */
1075 /* pattern. If it does, we take a closer look. If it does not, we */
1076 /* move our pointer (to putative last characters) as far as is */
1077 /* logically possible. This amount of movement, which I call a */
1078 /* stride, will be the length of the pattern if the actual character */
1079 /* appears nowhere in the pattern, otherwise it will be the distance */
1080 /* from the last occurrence of that character to the end of the */
1081 /* pattern. */
1082 /* As a coding trick, an enormous stride is coded into the table for */
1083 /* characters that match the last character. This allows use of only */
1084 /* a single test, a test for having gone past the end of the */
1085 /* permissible match region, to test for both possible matches (when */
1086 /* the stride goes past the end immediately) and failure to */
1087 /* match (where you get nudged past the end one stride at a time). */
1089 /* Here we make a "mickey mouse" BM table. The stride of the search */
1090 /* is determined only by the last character of the putative match. */
1091 /* If that character does not match, we will stride the proper */
1092 /* distance to propose a match that superimposes it on the last */
1093 /* instance of a character that matches it (per trt), or misses */
1094 /* it entirely if there is none. */
1096 dirlen = len * direction;
1097 infinity = dirlen - (lim + pos + len + len) * direction;
1098 if (direction < 0)
1099 pat = (base_pat += len - 1);
1100 BM_tab_base = BM_tab;
1101 BM_tab += 0400;
1102 j = dirlen; /* to get it in a register */
1103 /* A character that does not appear in the pattern induces a */
1104 /* stride equal to the pattern length. */
1105 while (BM_tab_base != BM_tab)
1107 *--BM_tab = j;
1108 *--BM_tab = j;
1109 *--BM_tab = j;
1110 *--BM_tab = j;
1112 i = 0;
1113 while (i != infinity)
1115 j = pat[i]; i += direction;
1116 if (i == dirlen) i = infinity;
1117 if (trt != 0)
1119 k = (j = trt[j]);
1120 if (i == infinity)
1121 stride_for_teases = BM_tab[j];
1122 BM_tab[j] = dirlen - i;
1123 /* A translation table is accompanied by its inverse -- see */
1124 /* comment following downcase_table for details */
1125 while ((j = inverse_trt[j]) != k)
1126 BM_tab[j] = dirlen - i;
1128 else
1130 if (i == infinity)
1131 stride_for_teases = BM_tab[j];
1132 BM_tab[j] = dirlen - i;
1134 /* stride_for_teases tells how much to stride if we get a */
1135 /* match on the far character but are subsequently */
1136 /* disappointed, by recording what the stride would have been */
1137 /* for that character if the last character had been */
1138 /* different. */
1140 infinity = dirlen - infinity;
1141 pos += dirlen - ((direction > 0) ? direction : 0);
1142 /* loop invariant - pos points at where last char (first char if reverse)
1143 of pattern would align in a possible match. */
1144 while (n != 0)
1146 /* It's been reported that some (broken) compiler thinks that
1147 Boolean expressions in an arithmetic context are unsigned.
1148 Using an explicit ?1:0 prevents this. */
1149 if ((lim - pos - ((direction > 0) ? 1 : 0)) * direction < 0)
1150 return (n * (0 - direction));
1151 /* First we do the part we can by pointers (maybe nothing) */
1152 QUIT;
1153 pat = base_pat;
1154 limit = pos - dirlen + direction;
1155 limit = ((direction > 0)
1156 ? BUFFER_CEILING_OF (limit)
1157 : BUFFER_FLOOR_OF (limit));
1158 /* LIMIT is now the last (not beyond-last!) value
1159 POS can take on without hitting edge of buffer or the gap. */
1160 limit = ((direction > 0)
1161 ? min (lim - 1, min (limit, pos + 20000))
1162 : max (lim, max (limit, pos - 20000)));
1163 if ((limit - pos) * direction > 20)
1165 p_limit = &FETCH_CHAR (limit);
1166 p2 = (cursor = &FETCH_CHAR (pos));
1167 /* In this loop, pos + cursor - p2 is the surrogate for pos */
1168 while (1) /* use one cursor setting as long as i can */
1170 if (direction > 0) /* worth duplicating */
1172 /* Use signed comparison if appropriate
1173 to make cursor+infinity sure to be > p_limit.
1174 Assuming that the buffer lies in a range of addresses
1175 that are all "positive" (as ints) or all "negative",
1176 either kind of comparison will work as long
1177 as we don't step by infinity. So pick the kind
1178 that works when we do step by infinity. */
1179 if ((EMACS_INT) (p_limit + infinity) > (EMACS_INT) p_limit)
1180 while ((EMACS_INT) cursor <= (EMACS_INT) p_limit)
1181 cursor += BM_tab[*cursor];
1182 else
1183 while ((unsigned EMACS_INT) cursor <= (unsigned EMACS_INT) p_limit)
1184 cursor += BM_tab[*cursor];
1186 else
1188 if ((EMACS_INT) (p_limit + infinity) < (EMACS_INT) p_limit)
1189 while ((EMACS_INT) cursor >= (EMACS_INT) p_limit)
1190 cursor += BM_tab[*cursor];
1191 else
1192 while ((unsigned EMACS_INT) cursor >= (unsigned EMACS_INT) p_limit)
1193 cursor += BM_tab[*cursor];
1195 /* If you are here, cursor is beyond the end of the searched region. */
1196 /* This can happen if you match on the far character of the pattern, */
1197 /* because the "stride" of that character is infinity, a number able */
1198 /* to throw you well beyond the end of the search. It can also */
1199 /* happen if you fail to match within the permitted region and would */
1200 /* otherwise try a character beyond that region */
1201 if ((cursor - p_limit) * direction <= len)
1202 break; /* a small overrun is genuine */
1203 cursor -= infinity; /* large overrun = hit */
1204 i = dirlen - direction;
1205 if (trt != 0)
1207 while ((i -= direction) + direction != 0)
1208 if (pat[i] != trt[*(cursor -= direction)])
1209 break;
1211 else
1213 while ((i -= direction) + direction != 0)
1214 if (pat[i] != *(cursor -= direction))
1215 break;
1217 cursor += dirlen - i - direction; /* fix cursor */
1218 if (i + direction == 0)
1220 cursor -= direction;
1222 set_search_regs (pos + cursor - p2 + ((direction > 0)
1223 ? 1 - len : 0),
1224 len);
1226 if ((n -= direction) != 0)
1227 cursor += dirlen; /* to resume search */
1228 else
1229 return ((direction > 0)
1230 ? search_regs.end[0] : search_regs.start[0]);
1232 else
1233 cursor += stride_for_teases; /* <sigh> we lose - */
1235 pos += cursor - p2;
1237 else
1238 /* Now we'll pick up a clump that has to be done the hard */
1239 /* way because it covers a discontinuity */
1241 limit = ((direction > 0)
1242 ? BUFFER_CEILING_OF (pos - dirlen + 1)
1243 : BUFFER_FLOOR_OF (pos - dirlen - 1));
1244 limit = ((direction > 0)
1245 ? min (limit + len, lim - 1)
1246 : max (limit - len, lim));
1247 /* LIMIT is now the last value POS can have
1248 and still be valid for a possible match. */
1249 while (1)
1251 /* This loop can be coded for space rather than */
1252 /* speed because it will usually run only once. */
1253 /* (the reach is at most len + 21, and typically */
1254 /* does not exceed len) */
1255 while ((limit - pos) * direction >= 0)
1256 pos += BM_tab[FETCH_CHAR(pos)];
1257 /* now run the same tests to distinguish going off the */
1258 /* end, a match or a phony match. */
1259 if ((pos - limit) * direction <= len)
1260 break; /* ran off the end */
1261 /* Found what might be a match.
1262 Set POS back to last (first if reverse) char pos. */
1263 pos -= infinity;
1264 i = dirlen - direction;
1265 while ((i -= direction) + direction != 0)
1267 pos -= direction;
1268 if (pat[i] != (trt != 0
1269 ? trt[FETCH_CHAR(pos)]
1270 : FETCH_CHAR (pos)))
1271 break;
1273 /* Above loop has moved POS part or all the way
1274 back to the first char pos (last char pos if reverse).
1275 Set it once again at the last (first if reverse) char. */
1276 pos += dirlen - i- direction;
1277 if (i + direction == 0)
1279 pos -= direction;
1281 set_search_regs (pos + ((direction > 0) ? 1 - len : 0),
1282 len);
1284 if ((n -= direction) != 0)
1285 pos += dirlen; /* to resume search */
1286 else
1287 return ((direction > 0)
1288 ? search_regs.end[0] : search_regs.start[0]);
1290 else
1291 pos += stride_for_teases;
1294 /* We have done one clump. Can we continue? */
1295 if ((lim - pos) * direction < 0)
1296 return ((0 - n) * direction);
1298 return pos;
1302 /* Record beginning BEG and end BEG + LEN
1303 for a match just found in the current buffer. */
1305 static void
1306 set_search_regs (beg, len)
1307 int beg, len;
1309 /* Make sure we have registers in which to store
1310 the match position. */
1311 if (search_regs.num_regs == 0)
1313 search_regs.start = (regoff_t *) xmalloc (2 * sizeof (regoff_t));
1314 search_regs.end = (regoff_t *) xmalloc (2 * sizeof (regoff_t));
1315 search_regs.num_regs = 2;
1318 search_regs.start[0] = beg;
1319 search_regs.end[0] = beg + len;
1320 XSETBUFFER (last_thing_searched, current_buffer);
1323 /* Given a string of words separated by word delimiters,
1324 compute a regexp that matches those exact words
1325 separated by arbitrary punctuation. */
1327 static Lisp_Object
1328 wordify (string)
1329 Lisp_Object string;
1331 register unsigned char *p, *o;
1332 register int i, len, punct_count = 0, word_count = 0;
1333 Lisp_Object val;
1335 CHECK_STRING (string, 0);
1336 p = XSTRING (string)->data;
1337 len = XSTRING (string)->size;
1339 for (i = 0; i < len; i++)
1340 if (SYNTAX (p[i]) != Sword)
1342 punct_count++;
1343 if (i > 0 && SYNTAX (p[i-1]) == Sword) word_count++;
1345 if (SYNTAX (p[len-1]) == Sword) word_count++;
1346 if (!word_count) return build_string ("");
1348 val = make_string (p, len - punct_count + 5 * (word_count - 1) + 4);
1350 o = XSTRING (val)->data;
1351 *o++ = '\\';
1352 *o++ = 'b';
1354 for (i = 0; i < len; i++)
1355 if (SYNTAX (p[i]) == Sword)
1356 *o++ = p[i];
1357 else if (i > 0 && SYNTAX (p[i-1]) == Sword && --word_count)
1359 *o++ = '\\';
1360 *o++ = 'W';
1361 *o++ = '\\';
1362 *o++ = 'W';
1363 *o++ = '*';
1366 *o++ = '\\';
1367 *o++ = 'b';
1369 return val;
1372 DEFUN ("search-backward", Fsearch_backward, Ssearch_backward, 1, 4,
1373 "sSearch backward: ",
1374 "Search backward from point for STRING.\n\
1375 Set point to the beginning 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 before 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, position at 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 (string, bound, noerror, count)
1383 Lisp_Object string, bound, noerror, count;
1385 return search_command (string, bound, noerror, count, -1, 0, 0);
1388 DEFUN ("search-forward", Fsearch_forward, Ssearch_forward, 1, 4, "sSearch: ",
1389 "Search forward from point for STRING.\n\
1390 Set point to the end of the occurrence found, and return point.\n\
1391 An optional second argument bounds the search; it is a buffer position.\n\
1392 The match found must not extend after that position. nil is equivalent\n\
1393 to (point-max).\n\
1394 Optional third argument, if t, means if fail just return nil (no error).\n\
1395 If not nil and not t, move to limit of search and return nil.\n\
1396 Optional fourth argument is repeat count--search for successive occurrences.\n\
1397 See also the functions `match-beginning', `match-end' and `replace-match'.")
1398 (string, bound, noerror, count)
1399 Lisp_Object string, bound, noerror, count;
1401 return search_command (string, bound, noerror, count, 1, 0, 0);
1404 DEFUN ("word-search-backward", Fword_search_backward, Sword_search_backward, 1, 4,
1405 "sWord search backward: ",
1406 "Search backward from point for STRING, ignoring differences in punctuation.\n\
1407 Set point to the beginning of the occurrence found, and return point.\n\
1408 An optional second argument bounds the search; it is a buffer position.\n\
1409 The match found must not extend before that position.\n\
1410 Optional third argument, if t, means if fail just return nil (no error).\n\
1411 If not nil and not t, move to limit of search and return nil.\n\
1412 Optional fourth argument is repeat count--search for successive occurrences.")
1413 (string, bound, noerror, count)
1414 Lisp_Object string, bound, noerror, count;
1416 return search_command (wordify (string), bound, noerror, count, -1, 1, 0);
1419 DEFUN ("word-search-forward", Fword_search_forward, Sword_search_forward, 1, 4,
1420 "sWord search: ",
1421 "Search forward from point for STRING, ignoring differences in punctuation.\n\
1422 Set point to the end of the occurrence found, and return point.\n\
1423 An optional second argument bounds the search; it is a buffer position.\n\
1424 The match found must not extend after that position.\n\
1425 Optional third argument, if t, means if fail just return nil (no error).\n\
1426 If not nil and not t, move to limit of search and return nil.\n\
1427 Optional fourth argument is repeat count--search for successive occurrences.")
1428 (string, bound, noerror, count)
1429 Lisp_Object string, bound, noerror, count;
1431 return search_command (wordify (string), bound, noerror, count, 1, 1, 0);
1434 DEFUN ("re-search-backward", Fre_search_backward, Sre_search_backward, 1, 4,
1435 "sRE search backward: ",
1436 "Search backward from point for match for regular expression REGEXP.\n\
1437 Set point to the beginning of the match, and return point.\n\
1438 The match found is the one starting last in the buffer\n\
1439 and yet ending before the origin of the search.\n\
1440 An optional second argument bounds the search; it is a buffer position.\n\
1441 The match found must start at or after that position.\n\
1442 Optional third argument, if t, means if fail just return nil (no error).\n\
1443 If not nil and not t, move to limit of search and return nil.\n\
1444 Optional fourth argument is repeat count--search for successive occurrences.\n\
1445 See also the functions `match-beginning', `match-end' and `replace-match'.")
1446 (regexp, bound, noerror, count)
1447 Lisp_Object regexp, bound, noerror, count;
1449 return search_command (regexp, bound, noerror, count, -1, 1, 0);
1452 DEFUN ("re-search-forward", Fre_search_forward, Sre_search_forward, 1, 4,
1453 "sRE search: ",
1454 "Search forward from point for regular expression REGEXP.\n\
1455 Set point to the end of the occurrence found, and return point.\n\
1456 An optional second argument bounds the search; it is a buffer position.\n\
1457 The match found must not extend after that position.\n\
1458 Optional third argument, if t, means if fail just return nil (no error).\n\
1459 If not nil and not t, move to limit of search and return nil.\n\
1460 Optional fourth argument is repeat count--search for successive occurrences.\n\
1461 See also the functions `match-beginning', `match-end' and `replace-match'.")
1462 (regexp, bound, noerror, count)
1463 Lisp_Object regexp, bound, noerror, count;
1465 return search_command (regexp, bound, noerror, count, 1, 1, 0);
1468 DEFUN ("posix-search-backward", Fposix_search_backward, Sposix_search_backward, 1, 4,
1469 "sPosix search backward: ",
1470 "Search backward from point for match for regular expression REGEXP.\n\
1471 Find the longest match in accord with Posix regular expression rules.\n\
1472 Set point to the beginning of the match, and return point.\n\
1473 The match found is the one starting last in the buffer\n\
1474 and yet ending before the origin of the search.\n\
1475 An optional second argument bounds the search; it is a buffer position.\n\
1476 The match found must start at or after that position.\n\
1477 Optional third argument, if t, means if fail just return nil (no error).\n\
1478 If not nil and not t, move to limit of search and return nil.\n\
1479 Optional fourth argument is repeat count--search for successive occurrences.\n\
1480 See also the functions `match-beginning', `match-end' and `replace-match'.")
1481 (regexp, bound, noerror, count)
1482 Lisp_Object regexp, bound, noerror, count;
1484 return search_command (regexp, bound, noerror, count, -1, 1, 1);
1487 DEFUN ("posix-search-forward", Fposix_search_forward, Sposix_search_forward, 1, 4,
1488 "sPosix search: ",
1489 "Search forward from point for regular expression REGEXP.\n\
1490 Find the longest match in accord with Posix regular expression rules.\n\
1491 Set point to the end of the occurrence found, and return point.\n\
1492 An optional second argument bounds the search; it is a buffer position.\n\
1493 The match found must not extend after that position.\n\
1494 Optional third argument, if t, means if fail just return nil (no error).\n\
1495 If not nil and not t, move to limit of search and return nil.\n\
1496 Optional fourth argument is repeat count--search for successive occurrences.\n\
1497 See also the functions `match-beginning', `match-end' and `replace-match'.")
1498 (regexp, bound, noerror, count)
1499 Lisp_Object regexp, bound, noerror, count;
1501 return search_command (regexp, bound, noerror, count, 1, 1, 1);
1504 DEFUN ("replace-match", Freplace_match, Sreplace_match, 1, 5, 0,
1505 "Replace text matched by last search with NEWTEXT.\n\
1506 If second arg FIXEDCASE is non-nil, do not alter case of replacement text.\n\
1507 Otherwise maybe capitalize the whole text, or maybe just word initials,\n\
1508 based on the replaced text.\n\
1509 If the replaced text has only capital letters\n\
1510 and has at least one multiletter word, convert NEWTEXT to all caps.\n\
1511 If the replaced text has at least one word starting with a capital letter,\n\
1512 then capitalize each word in NEWTEXT.\n\n\
1513 If third arg LITERAL is non-nil, insert NEWTEXT literally.\n\
1514 Otherwise treat `\\' as special:\n\
1515 `\\&' in NEWTEXT means substitute original matched text.\n\
1516 `\\N' means substitute what matched the Nth `\\(...\\)'.\n\
1517 If Nth parens didn't match, substitute nothing.\n\
1518 `\\\\' means insert one `\\'.\n\
1519 FIXEDCASE and LITERAL are optional arguments.\n\
1520 Leaves point at end of replacement text.\n\
1522 The optional fourth argument STRING can be a string to modify.\n\
1523 In that case, this function creates and returns a new string\n\
1524 which is made by replacing the part of STRING that was matched.\n\
1526 The optional fifth argument SUBEXP specifies a subexpression of the match.\n\
1527 It says to replace just that subexpression instead of the whole match.\n\
1528 This is useful only after a regular expression search or match\n\
1529 since only regular expressions have distinguished subexpressions.")
1530 (newtext, fixedcase, literal, string, subexp)
1531 Lisp_Object newtext, fixedcase, literal, string, subexp;
1533 enum { nochange, all_caps, cap_initial } case_action;
1534 register int pos, last;
1535 int some_multiletter_word;
1536 int some_lowercase;
1537 int some_uppercase;
1538 int some_nonuppercase_initial;
1539 register int c, prevc;
1540 int inslen;
1541 int sub;
1543 CHECK_STRING (newtext, 0);
1545 if (! NILP (string))
1546 CHECK_STRING (string, 4);
1548 case_action = nochange; /* We tried an initialization */
1549 /* but some C compilers blew it */
1551 if (search_regs.num_regs <= 0)
1552 error ("replace-match called before any match found");
1554 if (NILP (subexp))
1555 sub = 0;
1556 else
1558 CHECK_NUMBER (subexp, 3);
1559 sub = XINT (subexp);
1560 if (sub < 0 || sub >= search_regs.num_regs)
1561 args_out_of_range (subexp, make_number (search_regs.num_regs));
1564 if (NILP (string))
1566 if (search_regs.start[sub] < BEGV
1567 || search_regs.start[sub] > search_regs.end[sub]
1568 || search_regs.end[sub] > ZV)
1569 args_out_of_range (make_number (search_regs.start[sub]),
1570 make_number (search_regs.end[sub]));
1572 else
1574 if (search_regs.start[sub] < 0
1575 || search_regs.start[sub] > search_regs.end[sub]
1576 || search_regs.end[sub] > XSTRING (string)->size)
1577 args_out_of_range (make_number (search_regs.start[sub]),
1578 make_number (search_regs.end[sub]));
1581 if (NILP (fixedcase))
1583 /* Decide how to casify by examining the matched text. */
1585 last = search_regs.end[sub];
1586 prevc = '\n';
1587 case_action = all_caps;
1589 /* some_multiletter_word is set nonzero if any original word
1590 is more than one letter long. */
1591 some_multiletter_word = 0;
1592 some_lowercase = 0;
1593 some_nonuppercase_initial = 0;
1594 some_uppercase = 0;
1596 for (pos = search_regs.start[sub]; pos < last; pos++)
1598 if (NILP (string))
1599 c = FETCH_CHAR (pos);
1600 else
1601 c = XSTRING (string)->data[pos];
1603 if (LOWERCASEP (c))
1605 /* Cannot be all caps if any original char is lower case */
1607 some_lowercase = 1;
1608 if (SYNTAX (prevc) != Sword)
1609 some_nonuppercase_initial = 1;
1610 else
1611 some_multiletter_word = 1;
1613 else if (!NOCASEP (c))
1615 some_uppercase = 1;
1616 if (SYNTAX (prevc) != Sword)
1618 else
1619 some_multiletter_word = 1;
1621 else
1623 /* If the initial is a caseless word constituent,
1624 treat that like a lowercase initial. */
1625 if (SYNTAX (prevc) != Sword)
1626 some_nonuppercase_initial = 1;
1629 prevc = c;
1632 /* Convert to all caps if the old text is all caps
1633 and has at least one multiletter word. */
1634 if (! some_lowercase && some_multiletter_word)
1635 case_action = all_caps;
1636 /* Capitalize each word, if the old text has all capitalized words. */
1637 else if (!some_nonuppercase_initial && some_multiletter_word)
1638 case_action = cap_initial;
1639 else if (!some_nonuppercase_initial && some_uppercase)
1640 /* Should x -> yz, operating on X, give Yz or YZ?
1641 We'll assume the latter. */
1642 case_action = all_caps;
1643 else
1644 case_action = nochange;
1647 /* Do replacement in a string. */
1648 if (!NILP (string))
1650 Lisp_Object before, after;
1652 before = Fsubstring (string, make_number (0),
1653 make_number (search_regs.start[sub]));
1654 after = Fsubstring (string, make_number (search_regs.end[sub]), Qnil);
1656 /* Do case substitution into NEWTEXT if desired. */
1657 if (NILP (literal))
1659 int lastpos = -1;
1660 /* We build up the substituted string in ACCUM. */
1661 Lisp_Object accum;
1662 Lisp_Object middle;
1664 accum = Qnil;
1666 for (pos = 0; pos < XSTRING (newtext)->size; pos++)
1668 int substart = -1;
1669 int subend;
1670 int delbackslash = 0;
1672 c = XSTRING (newtext)->data[pos];
1673 if (c == '\\')
1675 c = XSTRING (newtext)->data[++pos];
1676 if (c == '&')
1678 substart = search_regs.start[sub];
1679 subend = search_regs.end[sub];
1681 else if (c >= '1' && c <= '9' && c <= search_regs.num_regs + '0')
1683 if (search_regs.start[c - '0'] >= 0)
1685 substart = search_regs.start[c - '0'];
1686 subend = search_regs.end[c - '0'];
1689 else if (c == '\\')
1690 delbackslash = 1;
1692 if (substart >= 0)
1694 if (pos - 1 != lastpos + 1)
1695 middle = Fsubstring (newtext,
1696 make_number (lastpos + 1),
1697 make_number (pos - 1));
1698 else
1699 middle = Qnil;
1700 accum = concat3 (accum, middle,
1701 Fsubstring (string, make_number (substart),
1702 make_number (subend)));
1703 lastpos = pos;
1705 else if (delbackslash)
1707 middle = Fsubstring (newtext, make_number (lastpos + 1),
1708 make_number (pos));
1709 accum = concat2 (accum, middle);
1710 lastpos = pos;
1714 if (pos != lastpos + 1)
1715 middle = Fsubstring (newtext, make_number (lastpos + 1),
1716 make_number (pos));
1717 else
1718 middle = Qnil;
1720 newtext = concat2 (accum, middle);
1723 if (case_action == all_caps)
1724 newtext = Fupcase (newtext);
1725 else if (case_action == cap_initial)
1726 newtext = Fupcase_initials (newtext);
1728 return concat3 (before, newtext, after);
1731 /* We insert the replacement text before the old text, and then
1732 delete the original text. This means that markers at the
1733 beginning or end of the original will float to the corresponding
1734 position in the replacement. */
1735 SET_PT (search_regs.start[sub]);
1736 if (!NILP (literal))
1737 Finsert_and_inherit (1, &newtext);
1738 else
1740 struct gcpro gcpro1;
1741 GCPRO1 (newtext);
1743 for (pos = 0; pos < XSTRING (newtext)->size; pos++)
1745 int offset = point - search_regs.start[sub];
1747 c = XSTRING (newtext)->data[pos];
1748 if (c == '\\')
1750 c = XSTRING (newtext)->data[++pos];
1751 if (c == '&')
1752 Finsert_buffer_substring
1753 (Fcurrent_buffer (),
1754 make_number (search_regs.start[sub] + offset),
1755 make_number (search_regs.end[sub] + offset));
1756 else if (c >= '1' && c <= '9' && c <= search_regs.num_regs + '0')
1758 if (search_regs.start[c - '0'] >= 1)
1759 Finsert_buffer_substring
1760 (Fcurrent_buffer (),
1761 make_number (search_regs.start[c - '0'] + offset),
1762 make_number (search_regs.end[c - '0'] + offset));
1764 else
1765 insert_char (c);
1767 else
1768 insert_char (c);
1770 UNGCPRO;
1773 inslen = point - (search_regs.start[sub]);
1774 del_range (search_regs.start[sub] + inslen, search_regs.end[sub] + inslen);
1776 if (case_action == all_caps)
1777 Fupcase_region (make_number (point - inslen), make_number (point));
1778 else if (case_action == cap_initial)
1779 Fupcase_initials_region (make_number (point - inslen), make_number (point));
1780 return Qnil;
1783 static Lisp_Object
1784 match_limit (num, beginningp)
1785 Lisp_Object num;
1786 int beginningp;
1788 register int n;
1790 CHECK_NUMBER (num, 0);
1791 n = XINT (num);
1792 if (n < 0 || n >= search_regs.num_regs)
1793 args_out_of_range (num, make_number (search_regs.num_regs));
1794 if (search_regs.num_regs <= 0
1795 || search_regs.start[n] < 0)
1796 return Qnil;
1797 return (make_number ((beginningp) ? search_regs.start[n]
1798 : search_regs.end[n]));
1801 DEFUN ("match-beginning", Fmatch_beginning, Smatch_beginning, 1, 1, 0,
1802 "Return position of start of text matched by last search.\n\
1803 NUM specifies which parenthesized expression in the last regexp.\n\
1804 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.\n\
1805 Zero means the entire text matched by the whole regexp or whole string.")
1806 (num)
1807 Lisp_Object num;
1809 return match_limit (num, 1);
1812 DEFUN ("match-end", Fmatch_end, Smatch_end, 1, 1, 0,
1813 "Return position of end of text matched by last search.\n\
1814 ARG, a number, specifies which parenthesized expression in the last regexp.\n\
1815 Value is nil if ARGth pair didn't match, or there were less than ARG pairs.\n\
1816 Zero means the entire text matched by the whole regexp or whole string.")
1817 (num)
1818 Lisp_Object num;
1820 return match_limit (num, 0);
1823 DEFUN ("match-data", Fmatch_data, Smatch_data, 0, 0, 0,
1824 "Return a list containing all info on what the last search matched.\n\
1825 Element 2N is `(match-beginning N)'; element 2N + 1 is `(match-end N)'.\n\
1826 All the elements are markers or nil (nil if the Nth pair didn't match)\n\
1827 if the last match was on a buffer; integers or nil if a string was matched.\n\
1828 Use `store-match-data' to reinstate the data in this list.")
1831 Lisp_Object *data;
1832 int i, len;
1834 if (NILP (last_thing_searched))
1835 error ("match-data called before any match found");
1837 data = (Lisp_Object *) alloca ((2 * search_regs.num_regs)
1838 * sizeof (Lisp_Object));
1840 len = -1;
1841 for (i = 0; i < search_regs.num_regs; i++)
1843 int start = search_regs.start[i];
1844 if (start >= 0)
1846 if (EQ (last_thing_searched, Qt))
1848 XSETFASTINT (data[2 * i], start);
1849 XSETFASTINT (data[2 * i + 1], search_regs.end[i]);
1851 else if (BUFFERP (last_thing_searched))
1853 data[2 * i] = Fmake_marker ();
1854 Fset_marker (data[2 * i],
1855 make_number (start),
1856 last_thing_searched);
1857 data[2 * i + 1] = Fmake_marker ();
1858 Fset_marker (data[2 * i + 1],
1859 make_number (search_regs.end[i]),
1860 last_thing_searched);
1862 else
1863 /* last_thing_searched must always be Qt, a buffer, or Qnil. */
1864 abort ();
1866 len = i;
1868 else
1869 data[2 * i] = data [2 * i + 1] = Qnil;
1871 return Flist (2 * len + 2, data);
1875 DEFUN ("store-match-data", Fstore_match_data, Sstore_match_data, 1, 1, 0,
1876 "Set internal data on last search match from elements of LIST.\n\
1877 LIST should have been created by calling `match-data' previously.")
1878 (list)
1879 register Lisp_Object list;
1881 register int i;
1882 register Lisp_Object marker;
1884 if (running_asynch_code)
1885 save_search_regs ();
1887 if (!CONSP (list) && !NILP (list))
1888 list = wrong_type_argument (Qconsp, list);
1890 /* Unless we find a marker with a buffer in LIST, assume that this
1891 match data came from a string. */
1892 last_thing_searched = Qt;
1894 /* Allocate registers if they don't already exist. */
1896 int length = XFASTINT (Flength (list)) / 2;
1898 if (length > search_regs.num_regs)
1900 if (search_regs.num_regs == 0)
1902 search_regs.start
1903 = (regoff_t *) xmalloc (length * sizeof (regoff_t));
1904 search_regs.end
1905 = (regoff_t *) xmalloc (length * sizeof (regoff_t));
1907 else
1909 search_regs.start
1910 = (regoff_t *) xrealloc (search_regs.start,
1911 length * sizeof (regoff_t));
1912 search_regs.end
1913 = (regoff_t *) xrealloc (search_regs.end,
1914 length * sizeof (regoff_t));
1917 search_regs.num_regs = length;
1921 for (i = 0; i < search_regs.num_regs; i++)
1923 marker = Fcar (list);
1924 if (NILP (marker))
1926 search_regs.start[i] = -1;
1927 list = Fcdr (list);
1929 else
1931 if (MARKERP (marker))
1933 if (XMARKER (marker)->buffer == 0)
1934 XSETFASTINT (marker, 0);
1935 else
1936 XSETBUFFER (last_thing_searched, XMARKER (marker)->buffer);
1939 CHECK_NUMBER_COERCE_MARKER (marker, 0);
1940 search_regs.start[i] = XINT (marker);
1941 list = Fcdr (list);
1943 marker = Fcar (list);
1944 if (MARKERP (marker) && XMARKER (marker)->buffer == 0)
1945 XSETFASTINT (marker, 0);
1947 CHECK_NUMBER_COERCE_MARKER (marker, 0);
1948 search_regs.end[i] = XINT (marker);
1950 list = Fcdr (list);
1953 return Qnil;
1956 /* If non-zero the match data have been saved in saved_search_regs
1957 during the execution of a sentinel or filter. */
1958 static int search_regs_saved;
1959 static struct re_registers saved_search_regs;
1961 /* Called from Flooking_at, Fstring_match, search_buffer, Fstore_match_data
1962 if asynchronous code (filter or sentinel) is running. */
1963 static void
1964 save_search_regs ()
1966 if (!search_regs_saved)
1968 saved_search_regs.num_regs = search_regs.num_regs;
1969 saved_search_regs.start = search_regs.start;
1970 saved_search_regs.end = search_regs.end;
1971 search_regs.num_regs = 0;
1972 search_regs.start = 0;
1973 search_regs.end = 0;
1975 search_regs_saved = 1;
1979 /* Called upon exit from filters and sentinels. */
1980 void
1981 restore_match_data ()
1983 if (search_regs_saved)
1985 if (search_regs.num_regs > 0)
1987 xfree (search_regs.start);
1988 xfree (search_regs.end);
1990 search_regs.num_regs = saved_search_regs.num_regs;
1991 search_regs.start = saved_search_regs.start;
1992 search_regs.end = saved_search_regs.end;
1994 search_regs_saved = 0;
1998 /* Quote a string to inactivate reg-expr chars */
2000 DEFUN ("regexp-quote", Fregexp_quote, Sregexp_quote, 1, 1, 0,
2001 "Return a regexp string which matches exactly STRING and nothing else.")
2002 (str)
2003 Lisp_Object str;
2005 register unsigned char *in, *out, *end;
2006 register unsigned char *temp;
2008 CHECK_STRING (str, 0);
2010 temp = (unsigned char *) alloca (XSTRING (str)->size * 2);
2012 /* Now copy the data into the new string, inserting escapes. */
2014 in = XSTRING (str)->data;
2015 end = in + XSTRING (str)->size;
2016 out = temp;
2018 for (; in != end; in++)
2020 if (*in == '[' || *in == ']'
2021 || *in == '*' || *in == '.' || *in == '\\'
2022 || *in == '?' || *in == '+'
2023 || *in == '^' || *in == '$')
2024 *out++ = '\\';
2025 *out++ = *in;
2028 return make_string (temp, out - temp);
2031 syms_of_search ()
2033 register int i;
2035 for (i = 0; i < REGEXP_CACHE_SIZE; ++i)
2037 searchbufs[i].buf.allocated = 100;
2038 searchbufs[i].buf.buffer = (unsigned char *) malloc (100);
2039 searchbufs[i].buf.fastmap = searchbufs[i].fastmap;
2040 searchbufs[i].regexp = Qnil;
2041 staticpro (&searchbufs[i].regexp);
2042 searchbufs[i].next = (i == REGEXP_CACHE_SIZE-1 ? 0 : &searchbufs[i+1]);
2044 searchbuf_head = &searchbufs[0];
2046 Qsearch_failed = intern ("search-failed");
2047 staticpro (&Qsearch_failed);
2048 Qinvalid_regexp = intern ("invalid-regexp");
2049 staticpro (&Qinvalid_regexp);
2051 Fput (Qsearch_failed, Qerror_conditions,
2052 Fcons (Qsearch_failed, Fcons (Qerror, Qnil)));
2053 Fput (Qsearch_failed, Qerror_message,
2054 build_string ("Search failed"));
2056 Fput (Qinvalid_regexp, Qerror_conditions,
2057 Fcons (Qinvalid_regexp, Fcons (Qerror, Qnil)));
2058 Fput (Qinvalid_regexp, Qerror_message,
2059 build_string ("Invalid regexp"));
2061 last_thing_searched = Qnil;
2062 staticpro (&last_thing_searched);
2064 defsubr (&Slooking_at);
2065 defsubr (&Sposix_looking_at);
2066 defsubr (&Sstring_match);
2067 defsubr (&Sposix_string_match);
2068 defsubr (&Sskip_chars_forward);
2069 defsubr (&Sskip_chars_backward);
2070 defsubr (&Sskip_syntax_forward);
2071 defsubr (&Sskip_syntax_backward);
2072 defsubr (&Ssearch_forward);
2073 defsubr (&Ssearch_backward);
2074 defsubr (&Sword_search_forward);
2075 defsubr (&Sword_search_backward);
2076 defsubr (&Sre_search_forward);
2077 defsubr (&Sre_search_backward);
2078 defsubr (&Sposix_search_forward);
2079 defsubr (&Sposix_search_backward);
2080 defsubr (&Sreplace_match);
2081 defsubr (&Smatch_beginning);
2082 defsubr (&Smatch_end);
2083 defsubr (&Smatch_data);
2084 defsubr (&Sstore_match_data);
2085 defsubr (&Sregexp_quote);