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)
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. */
28 #include "region-cache.h"
30 #include "blockinput.h"
32 #include <sys/types.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. */
41 struct regexp_cache
*next
;
43 struct re_pattern_buffer buf
;
45 /* Nonzero means regexp was compiled to do full POSIX backtracking. */
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
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 ();
92 error ("Stack overflow in regexp matcher");
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. */
116 compile_pattern_1 (cp
, pattern
, translate
, regp
, posix
, multibyte
)
117 struct regexp_cache
*cp
;
119 Lisp_Object
*translate
;
120 struct re_registers
*regp
;
128 cp
->buf
.translate
= translate
;
130 cp
->buf
.multibyte
= multibyte
;
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
);
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
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
)
158 struct re_registers
*regp
;
159 Lisp_Object
*translate
;
162 struct regexp_cache
*cp
, **cpp
;
163 /* Should we check it here, or add an argument `multibyte' to this
165 int multibyte
= !NILP (current_buffer
->enable_multibyte_characters
);
167 for (cpp
= &searchbuf_head
; ; cpp
= &cp
->next
)
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
)
177 /* If we're at the end of the cache, compile into the last cell. */
180 compile_pattern_1 (cp
, pattern
, translate
, regp
, posix
, multibyte
);
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. */
189 cp
->next
= searchbuf_head
;
192 /* Advise the searching functions about the space we have allocated
193 for register data. */
195 re_set_registers (&cp
->buf
, regp
, regp
->num_regs
, regp
->start
, regp
->end
);
200 /* Error condition used for failing searches */
201 Lisp_Object Qsearch_failed
;
207 Fsignal (Qsearch_failed
, Fcons (arg
, Qnil
));
212 looking_at_1 (string
, posix
)
217 unsigned char *p1
, *p2
;
220 struct re_pattern_buffer
*bufp
;
222 if (running_asynch_code
)
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),
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. */
253 re_match_object
= Qnil
;
255 i
= re_match_2 (bufp
, (char *) p1
, s1
, (char *) p2
, s2
,
256 PT
- BEGV
, &search_regs
,
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
);
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.")
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.")
293 return looking_at_1 (regexp
, 1);
297 string_match_1 (regexp
, string
, start
, posix
)
298 Lisp_Object regexp
, string
, start
;
303 struct re_pattern_buffer
*bufp
;
305 if (running_asynch_code
)
308 CHECK_STRING (regexp
, 0);
309 CHECK_STRING (string
, 1);
315 int len
= XSTRING (string
)->size
;
317 CHECK_NUMBER (start
, 2);
319 if (s
< 0 && -s
<= len
)
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),
330 re_match_object
= string
;
332 val
= re_search (bufp
, (char *) XSTRING (string
)->data
,
333 XSTRING (string
)->size
, s
, XSTRING (string
)->size
- s
,
336 last_thing_searched
= Qt
;
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
;
377 struct re_pattern_buffer
*bufp
;
379 bufp
= compile_pattern (regexp
, 0, 0, 0);
381 re_match_object
= string
;
383 val
= re_search (bufp
, (char *) XSTRING (string
)->data
,
384 XSTRING (string
)->size
, 0, XSTRING (string
)->size
,
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
)
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);
409 val
= re_search (bufp
, string
, len
, 0, len
, 0);
420 return ((a
> b
) ? 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. */
438 newline_cache_on_off (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;
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
)
486 struct region_cache
*newline_cache
;
497 if (! end
) end
= BEGV
;
500 newline_cache_on_off (current_buffer
);
501 newline_cache
= current_buffer
->newline_cache
;
506 immediate_quit
= allow_quit
;
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
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
)
524 while (region_cache_forward
525 (current_buffer
, newline_cache
, start
, &next_change
))
527 immediate_quit
= allow_quit
;
529 /* start should never be after end. */
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
;
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
)
571 return (start
+ cursor
- base
+ 1);
577 start
+= cursor
- base
;
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
)
591 while (region_cache_backward
592 (current_buffer
, newline_cache
, start
, &next_change
))
594 immediate_quit
= allow_quit
;
596 /* Start should never be at or before end. */
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
)
634 return (start
+ cursor
- base
);
640 start
+= cursor
- base
;
646 *shortage
= count
* direction
;
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
)
673 int pos
= scan_buffer ('\n', from
, to
, cnt
, &shortage
, 1);
681 /* Subroutines of Lisp buffer search functions. */
684 search_command (string
, bound
, noerror
, count
, direction
, RE
, posix
)
685 Lisp_Object string
, bound
, noerror
, count
;
696 CHECK_NUMBER (count
, 3);
700 CHECK_STRING (string
, 0);
702 lim
= n
> 0 ? ZV
: BEGV
;
705 CHECK_NUMBER_COERCE_MARKER (bound
, 1);
707 if (n
> 0 ? lim
< PT
: lim
> PT
)
708 error ("Invalid search bound (wrong side of point)");
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
719 (!NILP (current_buffer
->case_fold_search
)
720 ? XCHAR_TABLE (current_buffer
->case_eqv_table
)->contents
726 return signal_failure (string
);
727 if (!EQ (noerror
, Qt
))
729 if (lim
< BEGV
|| lim
> ZV
)
733 #if 0 /* This would be clean, but maybe programs depend on
734 a value of nil here. */
742 if (np
< BEGV
|| np
> ZV
)
747 return make_number (np
);
751 trivial_regexp_p (regexp
)
754 int len
= XSTRING (regexp
)->size
;
755 unsigned char *s
= XSTRING (regexp
)->data
;
761 case '.': case '*': case '+': case '?': case '[': case '^': case '$':
768 case '|': case '(': case ')': case '`': case '\'': case 'b':
769 case 'B': case '<': case '>': case 'w': case 'W': case 's':
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':
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. */
797 search_buffer (string
, pos
, lim
, n
, RE
, trt
, inverse_trt
, posix
)
804 Lisp_Object
*inverse_trt
;
807 int len
= XSTRING (string
)->size
;
808 unsigned char *base_pat
= XSTRING (string
)->data
;
809 register int *BM_tab
;
811 register int direction
= ((n
> 0) ? 1 : -1);
813 int infinity
, limit
, k
, stride_for_teases
;
814 register unsigned char *pat
, *cursor
, *p_limit
;
816 unsigned char *p1
, *p2
;
819 if (running_asynch_code
)
822 /* Null string is found at starting position. */
825 set_search_regs (pos
, 0);
829 /* Searching 0 times means don't move. */
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. */
862 re_match_object
= Qnil
;
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 */
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];
898 val
= re_search_2 (bufp
, (char *) p1
, s1
, (char *) p2
, s2
,
899 pos
- BEGV
, lim
- pos
, &search_regs
,
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];
927 else /* non-RE case */
930 int BM_tab_space
[0400];
931 BM_tab
= &BM_tab_space
[0];
933 BM_tab
= (int *) alloca (0400 * sizeof (int));
936 unsigned char *patbuf
= (unsigned char *) alloca (len
);
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
== '\\')
948 *pat
++ = (trt
? XINT (trt
[*base_pat
++]) : *base_pat
++);
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 */
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
;
983 pat
= (base_pat
+= len
- 1);
984 BM_tab_base
= BM_tab
;
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
)
997 while (i
!= infinity
)
999 j
= pat
[i
]; i
+= direction
;
1000 if (i
== dirlen
) i
= infinity
;
1003 k
= (j
= XINT (trt
[j
]));
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
;
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 */
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. */
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) */
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
];
1067 while ((EMACS_UINT
) cursor
<= (EMACS_UINT
) p_limit
)
1068 cursor
+= BM_tab
[*cursor
];
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
];
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
;
1091 while ((i
-= direction
) + direction
!= 0)
1092 if (pat
[i
] != XINT (trt
[*(cursor
-= direction
)]))
1097 while ((i
-= direction
) + direction
!= 0)
1098 if (pat
[i
] != *(cursor
-= direction
))
1101 cursor
+= dirlen
- i
- direction
; /* fix cursor */
1102 if (i
+ direction
== 0)
1104 cursor
-= direction
;
1106 set_search_regs (pos
+ cursor
- p2
+ ((direction
> 0)
1110 if ((n
-= direction
) != 0)
1111 cursor
+= dirlen
; /* to resume search */
1113 return ((direction
> 0)
1114 ? search_regs
.end
[0] : search_regs
.start
[0]);
1117 cursor
+= stride_for_teases
; /* <sigh> we lose - */
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. */
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. */
1148 i
= dirlen
- direction
;
1149 while ((i
-= direction
) + direction
!= 0)
1152 if (pat
[i
] != (trt
!= 0
1153 ? XINT (trt
[FETCH_BYTE (pos
)])
1154 : FETCH_BYTE (pos
)))
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)
1165 set_search_regs (pos
+ ((direction
> 0) ? 1 - len
: 0),
1168 if ((n
-= direction
) != 0)
1169 pos
+= dirlen
; /* to resume search */
1171 return ((direction
> 0)
1172 ? search_regs
.end
[0] : search_regs
.start
[0]);
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
);
1186 /* Record beginning BEG and end BEG + LEN
1187 for a match just found in the current buffer. */
1190 set_search_regs (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. */
1215 register unsigned char *p
, *o
;
1216 register int i
, len
, punct_count
= 0, word_count
= 0;
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
)
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
;
1238 for (i
= 0; i
< len
; i
++)
1239 if (SYNTAX (p
[i
]) == Sword
)
1241 else if (i
> 0 && SYNTAX (p
[i
-1]) == Sword
&& --word_count
)
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\
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,
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,
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,
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
;
1422 int some_nonuppercase_initial
;
1423 register int c
, prevc
;
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");
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
));
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
]));
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
];
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;
1478 some_nonuppercase_initial
= 0;
1481 for (pos
= search_regs
.start
[sub
]; pos
< last
; pos
++)
1484 c
= FETCH_BYTE (pos
);
1486 c
= XSTRING (string
)->data
[pos
];
1490 /* Cannot be all caps if any original char is lower case */
1493 if (SYNTAX (prevc
) != Sword
)
1494 some_nonuppercase_initial
= 1;
1496 some_multiletter_word
= 1;
1498 else if (!NOCASEP (c
))
1501 if (SYNTAX (prevc
) != Sword
)
1504 some_multiletter_word
= 1;
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;
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
;
1529 case_action
= nochange
;
1532 /* Do replacement in a 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
1546 /* We build up the substituted string in ACCUM. */
1552 for (pos
= 0; pos
< XSTRING (newtext
)->size
; pos
++)
1556 int delbackslash
= 0;
1558 c
= XSTRING (newtext
)->data
[pos
];
1561 c
= XSTRING (newtext
)->data
[++pos
];
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'];
1578 error ("Invalid use of `\\' in replacement text");
1582 if (pos
- 1 != lastpos
+ 1)
1583 middle
= Fsubstring (newtext
,
1584 make_number (lastpos
+ 1),
1585 make_number (pos
- 1));
1588 accum
= concat3 (accum
, middle
,
1589 Fsubstring (string
, make_number (substart
),
1590 make_number (subend
)));
1593 else if (delbackslash
)
1595 middle
= Fsubstring (newtext
, make_number (lastpos
+ 1),
1597 accum
= concat2 (accum
, middle
);
1602 if (pos
!= lastpos
+ 1)
1603 middle
= Fsubstring (newtext
, make_number (lastpos
+ 1),
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
])
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
);
1636 struct gcpro gcpro1
;
1639 for (pos
= 0; pos
< XSTRING (newtext
)->size
; pos
++)
1641 int offset
= PT
- search_regs
.start
[sub
];
1643 c
= XSTRING (newtext
)->data
[pos
];
1646 c
= XSTRING (newtext
)->data
[++pos
];
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
));
1663 error ("Invalid use of `\\' in replacement text");
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
));
1681 /* Put point back where it was in the text. */
1683 temp_set_point (opoint
+ ZV
, current_buffer
);
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
);
1694 match_limit (num
, beginningp
)
1700 CHECK_NUMBER (num
, 0);
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)
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\
1715 Value is nil if SUBEXPth pair didn't match, or there were less than\n\
1717 Zero means the entire text matched by the whole regexp or whole string.")
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\
1728 Value is nil if SUBEXPth pair didn't match, or there were less than\n\
1730 Zero means the entire text matched by the whole regexp or whole string.")
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.")
1749 Lisp_Object integers
, reuse
;
1751 Lisp_Object tail
, prev
;
1755 if (NILP (last_thing_searched
))
1758 data
= (Lisp_Object
*) alloca ((2 * search_regs
.num_regs
)
1759 * sizeof (Lisp_Object
));
1762 for (i
= 0; i
< search_regs
.num_regs
; i
++)
1764 int start
= search_regs
.start
[i
];
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
);
1785 /* last_thing_searched must always be Qt, a buffer, or Qnil. */
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
];
1806 XCONS (tail
)->car
= Qnil
;
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
);
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.")
1823 register Lisp_Object list
;
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)
1847 = (regoff_t
*) xmalloc (length
* sizeof (regoff_t
));
1849 = (regoff_t
*) xmalloc (length
* sizeof (regoff_t
));
1854 = (regoff_t
*) xrealloc (search_regs
.start
,
1855 length
* sizeof (regoff_t
));
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
);
1870 search_regs
.start
[i
] = -1;
1875 if (MARKERP (marker
))
1877 if (XMARKER (marker
)->buffer
== 0)
1878 XSETFASTINT (marker
, 0);
1880 XSETBUFFER (last_thing_searched
, XMARKER (marker
)->buffer
);
1883 CHECK_NUMBER_COERCE_MARKER (marker
, 0);
1884 search_regs
.start
[i
] = XINT (marker
);
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
);
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. */
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. */
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.")
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
;
1962 for (; in
!= end
; in
++)
1964 if (*in
== '[' || *in
== ']'
1965 || *in
== '*' || *in
== '.' || *in
== '\\'
1966 || *in
== '?' || *in
== '+'
1967 || *in
== '^' || *in
== '$')
1972 return make_string (temp
, out
- temp
);
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
);