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 ? DOWNCASE_TABLE
: 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 i
= re_match_2 (bufp
, (char *) p1
, s1
, (char *) p2
, s2
,
254 PT
- BEGV
, &search_regs
,
259 val
= (0 <= i
? Qt
: Qnil
);
260 for (i
= 0; i
< search_regs
.num_regs
; i
++)
261 if (search_regs
.start
[i
] >= 0)
263 search_regs
.start
[i
] += BEGV
;
264 search_regs
.end
[i
] += BEGV
;
266 XSETBUFFER (last_thing_searched
, current_buffer
);
271 DEFUN ("looking-at", Flooking_at
, Slooking_at
, 1, 1, 0,
272 "Return t if text after point matches regular expression REGEXP.\n\
273 This function modifies the match data that `match-beginning',\n\
274 `match-end' and `match-data' access; save and restore the match\n\
275 data if you want to preserve them.")
279 return looking_at_1 (regexp
, 0);
282 DEFUN ("posix-looking-at", Fposix_looking_at
, Sposix_looking_at
, 1, 1, 0,
283 "Return t if text after point matches regular expression REGEXP.\n\
284 Find the longest match, in accord with Posix regular expression rules.\n\
285 This function modifies the match data that `match-beginning',\n\
286 `match-end' and `match-data' access; save and restore the match\n\
287 data if you want to preserve them.")
291 return looking_at_1 (regexp
, 1);
295 string_match_1 (regexp
, string
, start
, posix
)
296 Lisp_Object regexp
, string
, start
;
301 struct re_pattern_buffer
*bufp
;
303 if (running_asynch_code
)
306 CHECK_STRING (regexp
, 0);
307 CHECK_STRING (string
, 1);
313 int len
= XSTRING (string
)->size
;
315 CHECK_NUMBER (start
, 2);
317 if (s
< 0 && -s
<= len
)
319 else if (0 > s
|| s
> len
)
320 args_out_of_range (string
, start
);
323 bufp
= compile_pattern (regexp
, &search_regs
,
324 (!NILP (current_buffer
->case_fold_search
)
325 ? DOWNCASE_TABLE
: 0),
328 val
= re_search (bufp
, (char *) XSTRING (string
)->data
,
329 XSTRING (string
)->size
, s
, XSTRING (string
)->size
- s
,
332 last_thing_searched
= Qt
;
335 if (val
< 0) return Qnil
;
336 return make_number (val
);
339 DEFUN ("string-match", Fstring_match
, Sstring_match
, 2, 3, 0,
340 "Return index of start of first match for REGEXP in STRING, or nil.\n\
341 If third arg START is non-nil, start search at that index in STRING.\n\
342 For index of first char beyond the match, do (match-end 0).\n\
343 `match-end' and `match-beginning' also give indices of substrings\n\
344 matched by parenthesis constructs in the pattern.")
345 (regexp
, string
, start
)
346 Lisp_Object regexp
, string
, start
;
348 return string_match_1 (regexp
, string
, start
, 0);
351 DEFUN ("posix-string-match", Fposix_string_match
, Sposix_string_match
, 2, 3, 0,
352 "Return index of start of first match for REGEXP in STRING, or nil.\n\
353 Find the longest match, in accord with Posix regular expression rules.\n\
354 If third arg START is non-nil, start search at that index in STRING.\n\
355 For index of first char beyond the match, do (match-end 0).\n\
356 `match-end' and `match-beginning' also give indices of substrings\n\
357 matched by parenthesis constructs in the pattern.")
358 (regexp
, string
, start
)
359 Lisp_Object regexp
, string
, start
;
361 return string_match_1 (regexp
, string
, start
, 1);
364 /* Match REGEXP against STRING, searching all of STRING,
365 and return the index of the match, or negative on failure.
366 This does not clobber the match data. */
369 fast_string_match (regexp
, string
)
370 Lisp_Object regexp
, string
;
373 struct re_pattern_buffer
*bufp
;
375 bufp
= compile_pattern (regexp
, 0, 0, 0);
377 val
= re_search (bufp
, (char *) XSTRING (string
)->data
,
378 XSTRING (string
)->size
, 0, XSTRING (string
)->size
,
384 /* Match REGEXP against STRING, searching all of STRING ignoring case,
385 and return the index of the match, or negative on failure.
386 This does not clobber the match data. */
388 extern Lisp_Object Vascii_downcase_table
;
391 fast_string_match_ignore_case (regexp
, string
)
396 struct re_pattern_buffer
*bufp
;
397 int len
= strlen (string
);
399 bufp
= compile_pattern (regexp
, 0,
400 XCHAR_TABLE (Vascii_downcase_table
)->contents
, 0);
402 val
= re_search (bufp
, string
, len
, 0, len
, 0);
413 return ((a
> b
) ? a
: b
);
420 return ((a
< b
) ? a
: b
);
424 /* The newline cache: remembering which sections of text have no newlines. */
426 /* If the user has requested newline caching, make sure it's on.
427 Otherwise, make sure it's off.
428 This is our cheezy way of associating an action with the change of
429 state of a buffer-local variable. */
431 newline_cache_on_off (buf
)
434 if (NILP (buf
->cache_long_line_scans
))
436 /* It should be off. */
437 if (buf
->newline_cache
)
439 free_region_cache (buf
->newline_cache
);
440 buf
->newline_cache
= 0;
445 /* It should be on. */
446 if (buf
->newline_cache
== 0)
447 buf
->newline_cache
= new_region_cache ();
452 /* Search for COUNT instances of the character TARGET between START and END.
454 If COUNT is positive, search forwards; END must be >= START.
455 If COUNT is negative, search backwards for the -COUNTth instance;
456 END must be <= START.
457 If COUNT is zero, do anything you please; run rogue, for all I care.
459 If END is zero, use BEGV or ZV instead, as appropriate for the
460 direction indicated by COUNT.
462 If we find COUNT instances, set *SHORTAGE to zero, and return the
463 position after the COUNTth match. Note that for reverse motion
464 this is not the same as the usual convention for Emacs motion commands.
466 If we don't find COUNT instances before reaching END, set *SHORTAGE
467 to the number of TARGETs left unfound, and return END.
469 If ALLOW_QUIT is non-zero, set immediate_quit. That's good to do
470 except when inside redisplay. */
472 scan_buffer (target
, start
, end
, count
, shortage
, allow_quit
)
479 struct region_cache
*newline_cache
;
490 if (! end
) end
= BEGV
;
493 newline_cache_on_off (current_buffer
);
494 newline_cache
= current_buffer
->newline_cache
;
499 immediate_quit
= allow_quit
;
504 /* Our innermost scanning loop is very simple; it doesn't know
505 about gaps, buffer ends, or the newline cache. ceiling is
506 the position of the last character before the next such
507 obstacle --- the last character the dumb search loop should
509 register int ceiling
= end
- 1;
511 /* If we're looking for a newline, consult the newline cache
512 to see where we can avoid some scanning. */
513 if (target
== '\n' && newline_cache
)
517 while (region_cache_forward
518 (current_buffer
, newline_cache
, start
, &next_change
))
520 immediate_quit
= allow_quit
;
522 /* start should never be after end. */
526 /* Now the text after start is an unknown region, and
527 next_change is the position of the next known region. */
528 ceiling
= min (next_change
- 1, ceiling
);
531 /* The dumb loop can only scan text stored in contiguous
532 bytes. BUFFER_CEILING_OF returns the last character
533 position that is contiguous, so the ceiling is the
534 position after that. */
535 ceiling
= min (BUFFER_CEILING_OF (start
), ceiling
);
538 /* The termination address of the dumb loop. */
539 register unsigned char *ceiling_addr
= POS_ADDR (ceiling
) + 1;
540 register unsigned char *cursor
= POS_ADDR (start
);
541 unsigned char *base
= cursor
;
543 while (cursor
< ceiling_addr
)
545 unsigned char *scan_start
= cursor
;
548 while (*cursor
!= target
&& ++cursor
< ceiling_addr
)
551 /* If we're looking for newlines, cache the fact that
552 the region from start to cursor is free of them. */
553 if (target
== '\n' && newline_cache
)
554 know_region_cache (current_buffer
, newline_cache
,
555 start
+ scan_start
- base
,
556 start
+ cursor
- base
);
558 /* Did we find the target character? */
559 if (cursor
< ceiling_addr
)
564 return (start
+ cursor
- base
+ 1);
570 start
+= cursor
- base
;
576 /* The last character to check before the next obstacle. */
577 register int ceiling
= end
;
579 /* Consult the newline cache, if appropriate. */
580 if (target
== '\n' && newline_cache
)
584 while (region_cache_backward
585 (current_buffer
, newline_cache
, start
, &next_change
))
587 immediate_quit
= allow_quit
;
589 /* Start should never be at or before end. */
593 /* Now the text before start is an unknown region, and
594 next_change is the position of the next known region. */
595 ceiling
= max (next_change
, ceiling
);
598 /* Stop scanning before the gap. */
599 ceiling
= max (BUFFER_FLOOR_OF (start
- 1), ceiling
);
602 /* The termination address of the dumb loop. */
603 register unsigned char *ceiling_addr
= POS_ADDR (ceiling
);
604 register unsigned char *cursor
= POS_ADDR (start
- 1);
605 unsigned char *base
= cursor
;
607 while (cursor
>= ceiling_addr
)
609 unsigned char *scan_start
= cursor
;
611 while (*cursor
!= target
&& --cursor
>= ceiling_addr
)
614 /* If we're looking for newlines, cache the fact that
615 the region from after the cursor to start is free of them. */
616 if (target
== '\n' && newline_cache
)
617 know_region_cache (current_buffer
, newline_cache
,
618 start
+ cursor
- base
,
619 start
+ scan_start
- base
);
621 /* Did we find the target character? */
622 if (cursor
>= ceiling_addr
)
627 return (start
+ cursor
- base
);
633 start
+= cursor
- base
;
639 *shortage
= count
* direction
;
644 find_next_newline_no_quit (from
, cnt
)
645 register int from
, cnt
;
647 return scan_buffer ('\n', from
, 0, cnt
, (int *) 0, 0);
651 find_next_newline (from
, cnt
)
652 register int from
, cnt
;
654 return scan_buffer ('\n', from
, 0, cnt
, (int *) 0, 1);
658 /* Like find_next_newline, but returns position before the newline,
659 not after, and only search up to TO. This isn't just
660 find_next_newline (...)-1, because you might hit TO. */
662 find_before_next_newline (from
, to
, cnt
)
666 int pos
= scan_buffer ('\n', from
, to
, cnt
, &shortage
, 1);
674 Lisp_Object
skip_chars ();
676 DEFUN ("skip-chars-forward", Fskip_chars_forward
, Sskip_chars_forward
, 1, 2, 0,
677 "Move point forward, stopping before a char not in STRING, or at pos LIM.\n\
678 STRING is like the inside of a `[...]' in a regular expression\n\
679 except that `]' is never special and `\\' quotes `^', `-' or `\\'.\n\
680 Thus, with arg \"a-zA-Z\", this skips letters stopping before first nonletter.\n\
681 With arg \"^a-zA-Z\", skips nonletters stopping before first letter.\n\
682 Returns the distance traveled, either zero or positive.")
684 Lisp_Object string
, lim
;
686 return skip_chars (1, 0, string
, lim
);
689 DEFUN ("skip-chars-backward", Fskip_chars_backward
, Sskip_chars_backward
, 1, 2, 0,
690 "Move point backward, stopping after a char not in STRING, or at pos LIM.\n\
691 See `skip-chars-forward' for details.\n\
692 Returns the distance traveled, either zero or negative.")
694 Lisp_Object string
, lim
;
696 return skip_chars (0, 0, string
, lim
);
699 DEFUN ("skip-syntax-forward", Fskip_syntax_forward
, Sskip_syntax_forward
, 1, 2, 0,
700 "Move point forward across chars in specified syntax classes.\n\
701 SYNTAX is a string of syntax code characters.\n\
702 Stop before a char whose syntax is not in SYNTAX, or at position LIM.\n\
703 If SYNTAX starts with ^, skip characters whose syntax is NOT in SYNTAX.\n\
704 This function returns the distance traveled, either zero or positive.")
706 Lisp_Object syntax
, lim
;
708 return skip_chars (1, 1, syntax
, lim
);
711 DEFUN ("skip-syntax-backward", Fskip_syntax_backward
, Sskip_syntax_backward
, 1, 2, 0,
712 "Move point backward across chars in specified syntax classes.\n\
713 SYNTAX is a string of syntax code characters.\n\
714 Stop on reaching a char whose syntax is not in SYNTAX, or at position LIM.\n\
715 If SYNTAX starts with ^, skip characters whose syntax is NOT in SYNTAX.\n\
716 This function returns the distance traveled, either zero or negative.")
718 Lisp_Object syntax
, lim
;
720 return skip_chars (0, 1, syntax
, lim
);
724 skip_chars (forwardp
, syntaxp
, string
, lim
)
725 int forwardp
, syntaxp
;
726 Lisp_Object string
, lim
;
728 register unsigned char *p
, *pend
;
729 register unsigned char c
;
731 unsigned char fastmap
[0400];
732 /* If SYNTAXP is 0, STRING may contain multi-byte form of characters
733 of which codes don't fit in FASTMAP. In that case, we set the
734 first byte of multibyte form (i.e. base leading-code) in FASTMAP
735 and set the actual ranges of characters in CHAR_RANGES. In the
736 form "X-Y" of STRING, both X and Y must belong to the same
737 character set because a range striding across character sets is
740 = (int *) alloca (XSTRING (string
)->size
* (sizeof (int)) * 2);
741 int n_char_ranges
= 0;
745 CHECK_STRING (string
, 0);
748 XSETINT (lim
, forwardp
? ZV
: BEGV
);
750 CHECK_NUMBER_COERCE_MARKER (lim
, 1);
752 /* In any case, don't allow scan outside bounds of buffer. */
753 /* jla turned this off, for no known reason.
754 bfox turned the ZV part on, and rms turned the
755 BEGV part back on. */
757 XSETFASTINT (lim
, ZV
);
758 if (XINT (lim
) < BEGV
)
759 XSETFASTINT (lim
, BEGV
);
761 p
= XSTRING (string
)->data
;
762 pend
= p
+ XSTRING (string
)->size
;
763 bzero (fastmap
, sizeof fastmap
);
765 if (p
!= pend
&& *p
== '^')
770 /* Find the characters specified and set their elements of fastmap.
771 If syntaxp, each character counts as itself.
772 Otherwise, handle backslashes and ranges specially. */
777 ch
= STRING_CHAR (p
, pend
- p
);
778 p
+= BYTES_BY_CHAR_HEAD (*p
);
780 fastmap
[syntax_spec_code
[c
]] = 1;
785 if (p
== pend
) break;
788 if (p
!= pend
&& *p
== '-')
793 if (p
== pend
) break;
794 if (SINGLE_BYTE_CHAR_P (ch
))
802 fastmap
[c
] = 1; /* C is the base leading-code. */
803 ch2
= STRING_CHAR (p
, pend
- p
);
805 char_ranges
[n_char_ranges
++] = ch
,
806 char_ranges
[n_char_ranges
++] = ch2
;
808 p
+= BYTES_BY_CHAR_HEAD (*p
);
813 if (!SINGLE_BYTE_CHAR_P (ch
))
814 char_ranges
[n_char_ranges
++] = ch
,
815 char_ranges
[n_char_ranges
++] = ch
;
820 /* If ^ was the first character, complement the fastmap. In
821 addition, as all multibyte characters have possibility of
822 matching, set all entries for base leading codes, which is
823 harmless even if SYNTAXP is 1. */
826 for (i
= 0; i
< sizeof fastmap
; i
++)
828 if (!BASE_LEADING_CODE_P (i
))
835 int start_point
= PT
;
843 while (pos
< XINT (lim
)
844 && fastmap
[(int) SYNTAX (FETCH_CHAR (pos
))])
849 while (pos
> XINT (lim
))
853 if (!fastmap
[(int) SYNTAX (FETCH_CHAR (pos
))])
865 while (pos
< XINT (lim
) && fastmap
[(c
= FETCH_BYTE (pos
))])
867 if (!BASE_LEADING_CODE_P (c
))
869 else if (n_char_ranges
)
871 /* We much check CHAR_RANGES for a multibyte
873 ch
= FETCH_MULTIBYTE_CHAR (pos
);
874 for (i
= 0; i
< n_char_ranges
; i
+= 2)
875 if ((ch
>= char_ranges
[i
] && ch
<= char_ranges
[i
+ 1]))
877 if (!(negate
^ (i
< n_char_ranges
)))
891 while (pos
> XINT (lim
))
895 if (fastmap
[(c
= FETCH_BYTE (pos
))])
897 if (!BASE_LEADING_CODE_P (c
))
899 else if (n_char_ranges
)
901 /* We much check CHAR_RANGES for a multibyte
903 ch
= FETCH_MULTIBYTE_CHAR (pos
);
904 for (i
= 0; i
< n_char_ranges
; i
+= 2)
905 if (ch
>= char_ranges
[i
] && ch
<= char_ranges
[i
+ 1])
907 if (!(negate
^ (i
< n_char_ranges
)))
931 return make_number (PT
- start_point
);
935 /* Subroutines of Lisp buffer search functions. */
938 search_command (string
, bound
, noerror
, count
, direction
, RE
, posix
)
939 Lisp_Object string
, bound
, noerror
, count
;
950 CHECK_NUMBER (count
, 3);
954 CHECK_STRING (string
, 0);
956 lim
= n
> 0 ? ZV
: BEGV
;
959 CHECK_NUMBER_COERCE_MARKER (bound
, 1);
961 if (n
> 0 ? lim
< PT
: lim
> PT
)
962 error ("Invalid search bound (wrong side of point)");
969 np
= search_buffer (string
, PT
, lim
, n
, RE
,
970 (!NILP (current_buffer
->case_fold_search
)
971 ? XCHAR_TABLE (current_buffer
->case_canon_table
)->contents
973 (!NILP (current_buffer
->case_fold_search
)
974 ? XCHAR_TABLE (current_buffer
->case_eqv_table
)->contents
980 return signal_failure (string
);
981 if (!EQ (noerror
, Qt
))
983 if (lim
< BEGV
|| lim
> ZV
)
987 #if 0 /* This would be clean, but maybe programs depend on
988 a value of nil here. */
996 if (np
< BEGV
|| np
> ZV
)
1001 return make_number (np
);
1005 trivial_regexp_p (regexp
)
1008 int len
= XSTRING (regexp
)->size
;
1009 unsigned char *s
= XSTRING (regexp
)->data
;
1015 case '.': case '*': case '+': case '?': case '[': case '^': case '$':
1022 case '|': case '(': case ')': case '`': case '\'': case 'b':
1023 case 'B': case '<': case '>': case 'w': case 'W': case 's':
1025 case 'c': case 'C': /* for categoryspec and notcategoryspec */
1026 case '1': case '2': case '3': case '4': case '5':
1027 case '6': case '7': case '8': case '9':
1035 /* Search for the n'th occurrence of STRING in the current buffer,
1036 starting at position POS and stopping at position LIM,
1037 treating STRING as a literal string if RE is false or as
1038 a regular expression if RE is true.
1040 If N is positive, searching is forward and LIM must be greater than POS.
1041 If N is negative, searching is backward and LIM must be less than POS.
1043 Returns -x if only N-x occurrences found (x > 0),
1044 or else the position at the beginning of the Nth occurrence
1045 (if searching backward) or the end (if searching forward).
1047 POSIX is nonzero if we want full backtracking (POSIX style)
1048 for this pattern. 0 means backtrack only enough to get a valid match. */
1051 search_buffer (string
, pos
, lim
, n
, RE
, trt
, inverse_trt
, posix
)
1058 Lisp_Object
*inverse_trt
;
1061 int len
= XSTRING (string
)->size
;
1062 unsigned char *base_pat
= XSTRING (string
)->data
;
1063 register int *BM_tab
;
1065 register int direction
= ((n
> 0) ? 1 : -1);
1066 register int dirlen
;
1067 int infinity
, limit
, k
, stride_for_teases
;
1068 register unsigned char *pat
, *cursor
, *p_limit
;
1070 unsigned char *p1
, *p2
;
1073 if (running_asynch_code
)
1074 save_search_regs ();
1076 /* Null string is found at starting position. */
1079 set_search_regs (pos
, 0);
1083 /* Searching 0 times means don't move. */
1087 if (RE
&& !trivial_regexp_p (string
))
1089 struct re_pattern_buffer
*bufp
;
1091 bufp
= compile_pattern (string
, &search_regs
, trt
, posix
);
1093 immediate_quit
= 1; /* Quit immediately if user types ^G,
1094 because letting this function finish
1095 can take too long. */
1096 QUIT
; /* Do a pending quit right away,
1097 to avoid paradoxical behavior */
1098 /* Get pointers and sizes of the two strings
1099 that make up the visible portion of the buffer. */
1119 val
= re_search_2 (bufp
, (char *) p1
, s1
, (char *) p2
, s2
,
1120 pos
- BEGV
, lim
- pos
, &search_regs
,
1121 /* Don't allow match past current point */
1125 matcher_overflow ();
1130 for (i
= 0; i
< search_regs
.num_regs
; i
++)
1131 if (search_regs
.start
[i
] >= 0)
1133 search_regs
.start
[i
] += j
;
1134 search_regs
.end
[i
] += j
;
1136 XSETBUFFER (last_thing_searched
, current_buffer
);
1137 /* Set pos to the new position. */
1138 pos
= search_regs
.start
[0];
1150 val
= re_search_2 (bufp
, (char *) p1
, s1
, (char *) p2
, s2
,
1151 pos
- BEGV
, lim
- pos
, &search_regs
,
1155 matcher_overflow ();
1160 for (i
= 0; i
< search_regs
.num_regs
; i
++)
1161 if (search_regs
.start
[i
] >= 0)
1163 search_regs
.start
[i
] += j
;
1164 search_regs
.end
[i
] += j
;
1166 XSETBUFFER (last_thing_searched
, current_buffer
);
1167 pos
= search_regs
.end
[0];
1179 else /* non-RE case */
1182 int BM_tab_space
[0400];
1183 BM_tab
= &BM_tab_space
[0];
1185 BM_tab
= (int *) alloca (0400 * sizeof (int));
1188 unsigned char *patbuf
= (unsigned char *) alloca (len
);
1192 /* If we got here and the RE flag is set, it's because we're
1193 dealing with a regexp known to be trivial, so the backslash
1194 just quotes the next character. */
1195 if (RE
&& *base_pat
== '\\')
1200 *pat
++ = (trt
? trt
[*base_pat
++] : *base_pat
++);
1203 pat
= base_pat
= patbuf
;
1205 /* The general approach is that we are going to maintain that we know */
1206 /* the first (closest to the present position, in whatever direction */
1207 /* we're searching) character that could possibly be the last */
1208 /* (furthest from present position) character of a valid match. We */
1209 /* advance the state of our knowledge by looking at that character */
1210 /* and seeing whether it indeed matches the last character of the */
1211 /* pattern. If it does, we take a closer look. If it does not, we */
1212 /* move our pointer (to putative last characters) as far as is */
1213 /* logically possible. This amount of movement, which I call a */
1214 /* stride, will be the length of the pattern if the actual character */
1215 /* appears nowhere in the pattern, otherwise it will be the distance */
1216 /* from the last occurrence of that character to the end of the */
1218 /* As a coding trick, an enormous stride is coded into the table for */
1219 /* characters that match the last character. This allows use of only */
1220 /* a single test, a test for having gone past the end of the */
1221 /* permissible match region, to test for both possible matches (when */
1222 /* the stride goes past the end immediately) and failure to */
1223 /* match (where you get nudged past the end one stride at a time). */
1225 /* Here we make a "mickey mouse" BM table. The stride of the search */
1226 /* is determined only by the last character of the putative match. */
1227 /* If that character does not match, we will stride the proper */
1228 /* distance to propose a match that superimposes it on the last */
1229 /* instance of a character that matches it (per trt), or misses */
1230 /* it entirely if there is none. */
1232 dirlen
= len
* direction
;
1233 infinity
= dirlen
- (lim
+ pos
+ len
+ len
) * direction
;
1235 pat
= (base_pat
+= len
- 1);
1236 BM_tab_base
= BM_tab
;
1238 j
= dirlen
; /* to get it in a register */
1239 /* A character that does not appear in the pattern induces a */
1240 /* stride equal to the pattern length. */
1241 while (BM_tab_base
!= BM_tab
)
1249 while (i
!= infinity
)
1251 j
= pat
[i
]; i
+= direction
;
1252 if (i
== dirlen
) i
= infinity
;
1257 stride_for_teases
= BM_tab
[j
];
1258 BM_tab
[j
] = dirlen
- i
;
1259 /* A translation table is accompanied by its inverse -- see */
1260 /* comment following downcase_table for details */
1261 while ((j
= (unsigned char) inverse_trt
[j
]) != k
)
1262 BM_tab
[j
] = dirlen
- i
;
1267 stride_for_teases
= BM_tab
[j
];
1268 BM_tab
[j
] = dirlen
- i
;
1270 /* stride_for_teases tells how much to stride if we get a */
1271 /* match on the far character but are subsequently */
1272 /* disappointed, by recording what the stride would have been */
1273 /* for that character if the last character had been */
1276 infinity
= dirlen
- infinity
;
1277 pos
+= dirlen
- ((direction
> 0) ? direction
: 0);
1278 /* loop invariant - pos points at where last char (first char if reverse)
1279 of pattern would align in a possible match. */
1282 /* It's been reported that some (broken) compiler thinks that
1283 Boolean expressions in an arithmetic context are unsigned.
1284 Using an explicit ?1:0 prevents this. */
1285 if ((lim
- pos
- ((direction
> 0) ? 1 : 0)) * direction
< 0)
1286 return (n
* (0 - direction
));
1287 /* First we do the part we can by pointers (maybe nothing) */
1290 limit
= pos
- dirlen
+ direction
;
1291 limit
= ((direction
> 0)
1292 ? BUFFER_CEILING_OF (limit
)
1293 : BUFFER_FLOOR_OF (limit
));
1294 /* LIMIT is now the last (not beyond-last!) value
1295 POS can take on without hitting edge of buffer or the gap. */
1296 limit
= ((direction
> 0)
1297 ? min (lim
- 1, min (limit
, pos
+ 20000))
1298 : max (lim
, max (limit
, pos
- 20000)));
1299 if ((limit
- pos
) * direction
> 20)
1301 p_limit
= POS_ADDR (limit
);
1302 p2
= (cursor
= POS_ADDR (pos
));
1303 /* In this loop, pos + cursor - p2 is the surrogate for pos */
1304 while (1) /* use one cursor setting as long as i can */
1306 if (direction
> 0) /* worth duplicating */
1308 /* Use signed comparison if appropriate
1309 to make cursor+infinity sure to be > p_limit.
1310 Assuming that the buffer lies in a range of addresses
1311 that are all "positive" (as ints) or all "negative",
1312 either kind of comparison will work as long
1313 as we don't step by infinity. So pick the kind
1314 that works when we do step by infinity. */
1315 if ((EMACS_INT
) (p_limit
+ infinity
) > (EMACS_INT
) p_limit
)
1316 while ((EMACS_INT
) cursor
<= (EMACS_INT
) p_limit
)
1317 cursor
+= BM_tab
[*cursor
];
1319 while ((EMACS_UINT
) cursor
<= (EMACS_UINT
) p_limit
)
1320 cursor
+= BM_tab
[*cursor
];
1324 if ((EMACS_INT
) (p_limit
+ infinity
) < (EMACS_INT
) p_limit
)
1325 while ((EMACS_INT
) cursor
>= (EMACS_INT
) p_limit
)
1326 cursor
+= BM_tab
[*cursor
];
1328 while ((EMACS_UINT
) cursor
>= (EMACS_UINT
) p_limit
)
1329 cursor
+= BM_tab
[*cursor
];
1331 /* If you are here, cursor is beyond the end of the searched region. */
1332 /* This can happen if you match on the far character of the pattern, */
1333 /* because the "stride" of that character is infinity, a number able */
1334 /* to throw you well beyond the end of the search. It can also */
1335 /* happen if you fail to match within the permitted region and would */
1336 /* otherwise try a character beyond that region */
1337 if ((cursor
- p_limit
) * direction
<= len
)
1338 break; /* a small overrun is genuine */
1339 cursor
-= infinity
; /* large overrun = hit */
1340 i
= dirlen
- direction
;
1343 while ((i
-= direction
) + direction
!= 0)
1344 if (pat
[i
] != trt
[*(cursor
-= direction
)])
1349 while ((i
-= direction
) + direction
!= 0)
1350 if (pat
[i
] != *(cursor
-= direction
))
1353 cursor
+= dirlen
- i
- direction
; /* fix cursor */
1354 if (i
+ direction
== 0)
1356 cursor
-= direction
;
1358 set_search_regs (pos
+ cursor
- p2
+ ((direction
> 0)
1362 if ((n
-= direction
) != 0)
1363 cursor
+= dirlen
; /* to resume search */
1365 return ((direction
> 0)
1366 ? search_regs
.end
[0] : search_regs
.start
[0]);
1369 cursor
+= stride_for_teases
; /* <sigh> we lose - */
1374 /* Now we'll pick up a clump that has to be done the hard */
1375 /* way because it covers a discontinuity */
1377 limit
= ((direction
> 0)
1378 ? BUFFER_CEILING_OF (pos
- dirlen
+ 1)
1379 : BUFFER_FLOOR_OF (pos
- dirlen
- 1));
1380 limit
= ((direction
> 0)
1381 ? min (limit
+ len
, lim
- 1)
1382 : max (limit
- len
, lim
));
1383 /* LIMIT is now the last value POS can have
1384 and still be valid for a possible match. */
1387 /* This loop can be coded for space rather than */
1388 /* speed because it will usually run only once. */
1389 /* (the reach is at most len + 21, and typically */
1390 /* does not exceed len) */
1391 while ((limit
- pos
) * direction
>= 0)
1392 pos
+= BM_tab
[FETCH_BYTE (pos
)];
1393 /* now run the same tests to distinguish going off the */
1394 /* end, a match or a phony match. */
1395 if ((pos
- limit
) * direction
<= len
)
1396 break; /* ran off the end */
1397 /* Found what might be a match.
1398 Set POS back to last (first if reverse) char pos. */
1400 i
= dirlen
- direction
;
1401 while ((i
-= direction
) + direction
!= 0)
1404 if (pat
[i
] != (trt
!= 0
1405 ? trt
[FETCH_BYTE (pos
)]
1406 : FETCH_BYTE (pos
)))
1409 /* Above loop has moved POS part or all the way
1410 back to the first char pos (last char pos if reverse).
1411 Set it once again at the last (first if reverse) char. */
1412 pos
+= dirlen
- i
- direction
;
1413 if (i
+ direction
== 0)
1417 set_search_regs (pos
+ ((direction
> 0) ? 1 - len
: 0),
1420 if ((n
-= direction
) != 0)
1421 pos
+= dirlen
; /* to resume search */
1423 return ((direction
> 0)
1424 ? search_regs
.end
[0] : search_regs
.start
[0]);
1427 pos
+= stride_for_teases
;
1430 /* We have done one clump. Can we continue? */
1431 if ((lim
- pos
) * direction
< 0)
1432 return ((0 - n
) * direction
);
1438 /* Record beginning BEG and end BEG + LEN
1439 for a match just found in the current buffer. */
1442 set_search_regs (beg
, len
)
1445 /* Make sure we have registers in which to store
1446 the match position. */
1447 if (search_regs
.num_regs
== 0)
1449 search_regs
.start
= (regoff_t
*) xmalloc (2 * sizeof (regoff_t
));
1450 search_regs
.end
= (regoff_t
*) xmalloc (2 * sizeof (regoff_t
));
1451 search_regs
.num_regs
= 2;
1454 search_regs
.start
[0] = beg
;
1455 search_regs
.end
[0] = beg
+ len
;
1456 XSETBUFFER (last_thing_searched
, current_buffer
);
1459 /* Given a string of words separated by word delimiters,
1460 compute a regexp that matches those exact words
1461 separated by arbitrary punctuation. */
1467 register unsigned char *p
, *o
;
1468 register int i
, len
, punct_count
= 0, word_count
= 0;
1471 CHECK_STRING (string
, 0);
1472 p
= XSTRING (string
)->data
;
1473 len
= XSTRING (string
)->size
;
1475 for (i
= 0; i
< len
; i
++)
1476 if (SYNTAX (p
[i
]) != Sword
)
1479 if (i
> 0 && SYNTAX (p
[i
-1]) == Sword
) word_count
++;
1481 if (SYNTAX (p
[len
-1]) == Sword
) word_count
++;
1482 if (!word_count
) return build_string ("");
1484 val
= make_string (p
, len
- punct_count
+ 5 * (word_count
- 1) + 4);
1486 o
= XSTRING (val
)->data
;
1490 for (i
= 0; i
< len
; i
++)
1491 if (SYNTAX (p
[i
]) == Sword
)
1493 else if (i
> 0 && SYNTAX (p
[i
-1]) == Sword
&& --word_count
)
1508 DEFUN ("search-backward", Fsearch_backward
, Ssearch_backward
, 1, 4,
1509 "sSearch backward: ",
1510 "Search backward from point for STRING.\n\
1511 Set point to the beginning of the occurrence found, and return point.\n\
1512 An optional second argument bounds the search; it is a buffer position.\n\
1513 The match found must not extend before that position.\n\
1514 Optional third argument, if t, means if fail just return nil (no error).\n\
1515 If not nil and not t, position at limit of search and return nil.\n\
1516 Optional fourth argument is repeat count--search for successive occurrences.\n\
1517 See also the functions `match-beginning', `match-end' and `replace-match'.")
1518 (string
, bound
, noerror
, count
)
1519 Lisp_Object string
, bound
, noerror
, count
;
1521 return search_command (string
, bound
, noerror
, count
, -1, 0, 0);
1524 DEFUN ("search-forward", Fsearch_forward
, Ssearch_forward
, 1, 4, "sSearch: ",
1525 "Search forward from point for STRING.\n\
1526 Set point to the end of the occurrence found, and return point.\n\
1527 An optional second argument bounds the search; it is a buffer position.\n\
1528 The match found must not extend after that position. nil is equivalent\n\
1530 Optional third argument, if t, means if fail just return nil (no error).\n\
1531 If not nil and not t, move to limit of search and return nil.\n\
1532 Optional fourth argument is repeat count--search for successive occurrences.\n\
1533 See also the functions `match-beginning', `match-end' and `replace-match'.")
1534 (string
, bound
, noerror
, count
)
1535 Lisp_Object string
, bound
, noerror
, count
;
1537 return search_command (string
, bound
, noerror
, count
, 1, 0, 0);
1540 DEFUN ("word-search-backward", Fword_search_backward
, Sword_search_backward
, 1, 4,
1541 "sWord search backward: ",
1542 "Search backward from point for STRING, ignoring differences in punctuation.\n\
1543 Set point to the beginning of the occurrence found, and return point.\n\
1544 An optional second argument bounds the search; it is a buffer position.\n\
1545 The match found must not extend before that position.\n\
1546 Optional third argument, if t, means if fail just return nil (no error).\n\
1547 If not nil and not t, move to limit of search and return nil.\n\
1548 Optional fourth argument is repeat count--search for successive occurrences.")
1549 (string
, bound
, noerror
, count
)
1550 Lisp_Object string
, bound
, noerror
, count
;
1552 return search_command (wordify (string
), bound
, noerror
, count
, -1, 1, 0);
1555 DEFUN ("word-search-forward", Fword_search_forward
, Sword_search_forward
, 1, 4,
1557 "Search forward from point for STRING, ignoring differences in punctuation.\n\
1558 Set point to the end of the occurrence found, and return point.\n\
1559 An optional second argument bounds the search; it is a buffer position.\n\
1560 The match found must not extend after that position.\n\
1561 Optional third argument, if t, means if fail just return nil (no error).\n\
1562 If not nil and not t, move to limit of search and return nil.\n\
1563 Optional fourth argument is repeat count--search for successive occurrences.")
1564 (string
, bound
, noerror
, count
)
1565 Lisp_Object string
, bound
, noerror
, count
;
1567 return search_command (wordify (string
), bound
, noerror
, count
, 1, 1, 0);
1570 DEFUN ("re-search-backward", Fre_search_backward
, Sre_search_backward
, 1, 4,
1571 "sRE search backward: ",
1572 "Search backward from point for match for regular expression REGEXP.\n\
1573 Set point to the beginning of the match, and return point.\n\
1574 The match found is the one starting last in the buffer\n\
1575 and yet ending before the origin of the search.\n\
1576 An optional second argument bounds the search; it is a buffer position.\n\
1577 The match found must start at or after that position.\n\
1578 Optional third argument, if t, means if fail just return nil (no error).\n\
1579 If not nil and not t, move to limit of search and return nil.\n\
1580 Optional fourth argument is repeat count--search for successive occurrences.\n\
1581 See also the functions `match-beginning', `match-end' and `replace-match'.")
1582 (regexp
, bound
, noerror
, count
)
1583 Lisp_Object regexp
, bound
, noerror
, count
;
1585 return search_command (regexp
, bound
, noerror
, count
, -1, 1, 0);
1588 DEFUN ("re-search-forward", Fre_search_forward
, Sre_search_forward
, 1, 4,
1590 "Search forward from point for regular expression REGEXP.\n\
1591 Set point to the end of the occurrence found, and return point.\n\
1592 An optional second argument bounds the search; it is a buffer position.\n\
1593 The match found must not extend after that position.\n\
1594 Optional third argument, if t, means if fail just return nil (no error).\n\
1595 If not nil and not t, move to limit of search and return nil.\n\
1596 Optional fourth argument is repeat count--search for successive occurrences.\n\
1597 See also the functions `match-beginning', `match-end' and `replace-match'.")
1598 (regexp
, bound
, noerror
, count
)
1599 Lisp_Object regexp
, bound
, noerror
, count
;
1601 return search_command (regexp
, bound
, noerror
, count
, 1, 1, 0);
1604 DEFUN ("posix-search-backward", Fposix_search_backward
, Sposix_search_backward
, 1, 4,
1605 "sPosix search backward: ",
1606 "Search backward from point for match for regular expression REGEXP.\n\
1607 Find the longest match in accord with Posix regular expression rules.\n\
1608 Set point to the beginning of the match, and return point.\n\
1609 The match found is the one starting last in the buffer\n\
1610 and yet ending before the origin of the search.\n\
1611 An optional second argument bounds the search; it is a buffer position.\n\
1612 The match found must start at or after that position.\n\
1613 Optional third argument, if t, means if fail just return nil (no error).\n\
1614 If not nil and not t, move to limit of search and return nil.\n\
1615 Optional fourth argument is repeat count--search for successive occurrences.\n\
1616 See also the functions `match-beginning', `match-end' and `replace-match'.")
1617 (regexp
, bound
, noerror
, count
)
1618 Lisp_Object regexp
, bound
, noerror
, count
;
1620 return search_command (regexp
, bound
, noerror
, count
, -1, 1, 1);
1623 DEFUN ("posix-search-forward", Fposix_search_forward
, Sposix_search_forward
, 1, 4,
1625 "Search forward from point for regular expression REGEXP.\n\
1626 Find the longest match in accord with Posix regular expression rules.\n\
1627 Set point to the end of the occurrence found, and return point.\n\
1628 An optional second argument bounds the search; it is a buffer position.\n\
1629 The match found must not extend after that position.\n\
1630 Optional third argument, if t, means if fail just return nil (no error).\n\
1631 If not nil and not t, move to limit of search and return nil.\n\
1632 Optional fourth argument is repeat count--search for successive occurrences.\n\
1633 See also the functions `match-beginning', `match-end' and `replace-match'.")
1634 (regexp
, bound
, noerror
, count
)
1635 Lisp_Object regexp
, bound
, noerror
, count
;
1637 return search_command (regexp
, bound
, noerror
, count
, 1, 1, 1);
1640 DEFUN ("replace-match", Freplace_match
, Sreplace_match
, 1, 5, 0,
1641 "Replace text matched by last search with NEWTEXT.\n\
1642 If second arg FIXEDCASE is non-nil, do not alter case of replacement text.\n\
1643 Otherwise maybe capitalize the whole text, or maybe just word initials,\n\
1644 based on the replaced text.\n\
1645 If the replaced text has only capital letters\n\
1646 and has at least one multiletter word, convert NEWTEXT to all caps.\n\
1647 If the replaced text has at least one word starting with a capital letter,\n\
1648 then capitalize each word in NEWTEXT.\n\n\
1649 If third arg LITERAL is non-nil, insert NEWTEXT literally.\n\
1650 Otherwise treat `\\' as special:\n\
1651 `\\&' in NEWTEXT means substitute original matched text.\n\
1652 `\\N' means substitute what matched the Nth `\\(...\\)'.\n\
1653 If Nth parens didn't match, substitute nothing.\n\
1654 `\\\\' means insert one `\\'.\n\
1655 FIXEDCASE and LITERAL are optional arguments.\n\
1656 Leaves point at end of replacement text.\n\
1658 The optional fourth argument STRING can be a string to modify.\n\
1659 In that case, this function creates and returns a new string\n\
1660 which is made by replacing the part of STRING that was matched.\n\
1662 The optional fifth argument SUBEXP specifies a subexpression of the match.\n\
1663 It says to replace just that subexpression instead of the whole match.\n\
1664 This is useful only after a regular expression search or match\n\
1665 since only regular expressions have distinguished subexpressions.")
1666 (newtext
, fixedcase
, literal
, string
, subexp
)
1667 Lisp_Object newtext
, fixedcase
, literal
, string
, subexp
;
1669 enum { nochange
, all_caps
, cap_initial
} case_action
;
1670 register int pos
, last
;
1671 int some_multiletter_word
;
1674 int some_nonuppercase_initial
;
1675 register int c
, prevc
;
1679 CHECK_STRING (newtext
, 0);
1681 if (! NILP (string
))
1682 CHECK_STRING (string
, 4);
1684 case_action
= nochange
; /* We tried an initialization */
1685 /* but some C compilers blew it */
1687 if (search_regs
.num_regs
<= 0)
1688 error ("replace-match called before any match found");
1694 CHECK_NUMBER (subexp
, 3);
1695 sub
= XINT (subexp
);
1696 if (sub
< 0 || sub
>= search_regs
.num_regs
)
1697 args_out_of_range (subexp
, make_number (search_regs
.num_regs
));
1702 if (search_regs
.start
[sub
] < BEGV
1703 || search_regs
.start
[sub
] > search_regs
.end
[sub
]
1704 || search_regs
.end
[sub
] > ZV
)
1705 args_out_of_range (make_number (search_regs
.start
[sub
]),
1706 make_number (search_regs
.end
[sub
]));
1710 if (search_regs
.start
[sub
] < 0
1711 || search_regs
.start
[sub
] > search_regs
.end
[sub
]
1712 || search_regs
.end
[sub
] > XSTRING (string
)->size
)
1713 args_out_of_range (make_number (search_regs
.start
[sub
]),
1714 make_number (search_regs
.end
[sub
]));
1717 if (NILP (fixedcase
))
1719 /* Decide how to casify by examining the matched text. */
1721 last
= search_regs
.end
[sub
];
1723 case_action
= all_caps
;
1725 /* some_multiletter_word is set nonzero if any original word
1726 is more than one letter long. */
1727 some_multiletter_word
= 0;
1729 some_nonuppercase_initial
= 0;
1732 for (pos
= search_regs
.start
[sub
]; pos
< last
; pos
++)
1735 c
= FETCH_BYTE (pos
);
1737 c
= XSTRING (string
)->data
[pos
];
1741 /* Cannot be all caps if any original char is lower case */
1744 if (SYNTAX (prevc
) != Sword
)
1745 some_nonuppercase_initial
= 1;
1747 some_multiletter_word
= 1;
1749 else if (!NOCASEP (c
))
1752 if (SYNTAX (prevc
) != Sword
)
1755 some_multiletter_word
= 1;
1759 /* If the initial is a caseless word constituent,
1760 treat that like a lowercase initial. */
1761 if (SYNTAX (prevc
) != Sword
)
1762 some_nonuppercase_initial
= 1;
1768 /* Convert to all caps if the old text is all caps
1769 and has at least one multiletter word. */
1770 if (! some_lowercase
&& some_multiletter_word
)
1771 case_action
= all_caps
;
1772 /* Capitalize each word, if the old text has all capitalized words. */
1773 else if (!some_nonuppercase_initial
&& some_multiletter_word
)
1774 case_action
= cap_initial
;
1775 else if (!some_nonuppercase_initial
&& some_uppercase
)
1776 /* Should x -> yz, operating on X, give Yz or YZ?
1777 We'll assume the latter. */
1778 case_action
= all_caps
;
1780 case_action
= nochange
;
1783 /* Do replacement in a string. */
1786 Lisp_Object before
, after
;
1788 before
= Fsubstring (string
, make_number (0),
1789 make_number (search_regs
.start
[sub
]));
1790 after
= Fsubstring (string
, make_number (search_regs
.end
[sub
]), Qnil
);
1792 /* Do case substitution into NEWTEXT if desired. */
1796 /* We build up the substituted string in ACCUM. */
1802 for (pos
= 0; pos
< XSTRING (newtext
)->size
; pos
++)
1806 int delbackslash
= 0;
1808 c
= XSTRING (newtext
)->data
[pos
];
1811 c
= XSTRING (newtext
)->data
[++pos
];
1814 substart
= search_regs
.start
[sub
];
1815 subend
= search_regs
.end
[sub
];
1817 else if (c
>= '1' && c
<= '9' && c
<= search_regs
.num_regs
+ '0')
1819 if (search_regs
.start
[c
- '0'] >= 0)
1821 substart
= search_regs
.start
[c
- '0'];
1822 subend
= search_regs
.end
[c
- '0'];
1830 if (pos
- 1 != lastpos
+ 1)
1831 middle
= Fsubstring (newtext
,
1832 make_number (lastpos
+ 1),
1833 make_number (pos
- 1));
1836 accum
= concat3 (accum
, middle
,
1837 Fsubstring (string
, make_number (substart
),
1838 make_number (subend
)));
1841 else if (delbackslash
)
1843 middle
= Fsubstring (newtext
, make_number (lastpos
+ 1),
1845 accum
= concat2 (accum
, middle
);
1850 if (pos
!= lastpos
+ 1)
1851 middle
= Fsubstring (newtext
, make_number (lastpos
+ 1),
1856 newtext
= concat2 (accum
, middle
);
1859 if (case_action
== all_caps
)
1860 newtext
= Fupcase (newtext
);
1861 else if (case_action
== cap_initial
)
1862 newtext
= Fupcase_initials (newtext
);
1864 return concat3 (before
, newtext
, after
);
1867 /* We insert the replacement text before the old text, and then
1868 delete the original text. This means that markers at the
1869 beginning or end of the original will float to the corresponding
1870 position in the replacement. */
1871 SET_PT (search_regs
.start
[sub
]);
1872 if (!NILP (literal
))
1873 Finsert_and_inherit (1, &newtext
);
1876 struct gcpro gcpro1
;
1879 for (pos
= 0; pos
< XSTRING (newtext
)->size
; pos
++)
1881 int offset
= PT
- search_regs
.start
[sub
];
1883 c
= XSTRING (newtext
)->data
[pos
];
1886 c
= XSTRING (newtext
)->data
[++pos
];
1888 Finsert_buffer_substring
1889 (Fcurrent_buffer (),
1890 make_number (search_regs
.start
[sub
] + offset
),
1891 make_number (search_regs
.end
[sub
] + offset
));
1892 else if (c
>= '1' && c
<= '9' && c
<= search_regs
.num_regs
+ '0')
1894 if (search_regs
.start
[c
- '0'] >= 1)
1895 Finsert_buffer_substring
1896 (Fcurrent_buffer (),
1897 make_number (search_regs
.start
[c
- '0'] + offset
),
1898 make_number (search_regs
.end
[c
- '0'] + offset
));
1909 inslen
= PT
- (search_regs
.start
[sub
]);
1910 del_range (search_regs
.start
[sub
] + inslen
, search_regs
.end
[sub
] + inslen
);
1912 if (case_action
== all_caps
)
1913 Fupcase_region (make_number (PT
- inslen
), make_number (PT
));
1914 else if (case_action
== cap_initial
)
1915 Fupcase_initials_region (make_number (PT
- inslen
), make_number (PT
));
1920 match_limit (num
, beginningp
)
1926 CHECK_NUMBER (num
, 0);
1928 if (n
< 0 || n
>= search_regs
.num_regs
)
1929 args_out_of_range (num
, make_number (search_regs
.num_regs
));
1930 if (search_regs
.num_regs
<= 0
1931 || search_regs
.start
[n
] < 0)
1933 return (make_number ((beginningp
) ? search_regs
.start
[n
]
1934 : search_regs
.end
[n
]));
1937 DEFUN ("match-beginning", Fmatch_beginning
, Smatch_beginning
, 1, 1, 0,
1938 "Return position of start of text matched by last search.\n\
1939 SUBEXP, a number, specifies which parenthesized expression in the last\n\
1941 Value is nil if SUBEXPth pair didn't match, or there were less than\n\
1943 Zero means the entire text matched by the whole regexp or whole string.")
1947 return match_limit (subexp
, 1);
1950 DEFUN ("match-end", Fmatch_end
, Smatch_end
, 1, 1, 0,
1951 "Return position of end of text matched by last search.\n\
1952 SUBEXP, a number, specifies which parenthesized expression in the last\n\
1954 Value is nil if SUBEXPth pair didn't match, or there were less than\n\
1956 Zero means the entire text matched by the whole regexp or whole string.")
1960 return match_limit (subexp
, 0);
1963 DEFUN ("match-data", Fmatch_data
, Smatch_data
, 0, 2, 0,
1964 "Return a list containing all info on what the last search matched.\n\
1965 Element 2N is `(match-beginning N)'; element 2N + 1 is `(match-end N)'.\n\
1966 All the elements are markers or nil (nil if the Nth pair didn't match)\n\
1967 if the last match was on a buffer; integers or nil if a string was matched.\n\
1968 Use `store-match-data' to reinstate the data in this list.\n\
1970 If INTEGERS (the optional first argument) is non-nil, always use integers\n\
1971 \(rather than markers) to represent buffer positions.\n\
1972 If REUSE is a list, reuse it as part of the value. If REUSE is long enough\n\
1973 to hold all the values, and if INTEGERS is non-nil, no consing is done.")
1975 Lisp_Object integers
, reuse
;
1977 Lisp_Object tail
, prev
;
1981 if (NILP (last_thing_searched
))
1984 data
= (Lisp_Object
*) alloca ((2 * search_regs
.num_regs
)
1985 * sizeof (Lisp_Object
));
1988 for (i
= 0; i
< search_regs
.num_regs
; i
++)
1990 int start
= search_regs
.start
[i
];
1993 if (EQ (last_thing_searched
, Qt
)
1994 || ! NILP (integers
))
1996 XSETFASTINT (data
[2 * i
], start
);
1997 XSETFASTINT (data
[2 * i
+ 1], search_regs
.end
[i
]);
1999 else if (BUFFERP (last_thing_searched
))
2001 data
[2 * i
] = Fmake_marker ();
2002 Fset_marker (data
[2 * i
],
2003 make_number (start
),
2004 last_thing_searched
);
2005 data
[2 * i
+ 1] = Fmake_marker ();
2006 Fset_marker (data
[2 * i
+ 1],
2007 make_number (search_regs
.end
[i
]),
2008 last_thing_searched
);
2011 /* last_thing_searched must always be Qt, a buffer, or Qnil. */
2017 data
[2 * i
] = data
[2 * i
+ 1] = Qnil
;
2020 /* If REUSE is not usable, cons up the values and return them. */
2021 if (! CONSP (reuse
))
2022 return Flist (2 * len
+ 2, data
);
2024 /* If REUSE is a list, store as many value elements as will fit
2025 into the elements of REUSE. */
2026 for (i
= 0, tail
= reuse
; CONSP (tail
);
2027 i
++, tail
= XCONS (tail
)->cdr
)
2029 if (i
< 2 * len
+ 2)
2030 XCONS (tail
)->car
= data
[i
];
2032 XCONS (tail
)->car
= Qnil
;
2036 /* If we couldn't fit all value elements into REUSE,
2037 cons up the rest of them and add them to the end of REUSE. */
2038 if (i
< 2 * len
+ 2)
2039 XCONS (prev
)->cdr
= Flist (2 * len
+ 2 - i
, data
+ i
);
2045 DEFUN ("store-match-data", Fstore_match_data
, Sstore_match_data
, 1, 1, 0,
2046 "Set internal data on last search match from elements of LIST.\n\
2047 LIST should have been created by calling `match-data' previously.")
2049 register Lisp_Object list
;
2052 register Lisp_Object marker
;
2054 if (running_asynch_code
)
2055 save_search_regs ();
2057 if (!CONSP (list
) && !NILP (list
))
2058 list
= wrong_type_argument (Qconsp
, list
);
2060 /* Unless we find a marker with a buffer in LIST, assume that this
2061 match data came from a string. */
2062 last_thing_searched
= Qt
;
2064 /* Allocate registers if they don't already exist. */
2066 int length
= XFASTINT (Flength (list
)) / 2;
2068 if (length
> search_regs
.num_regs
)
2070 if (search_regs
.num_regs
== 0)
2073 = (regoff_t
*) xmalloc (length
* sizeof (regoff_t
));
2075 = (regoff_t
*) xmalloc (length
* sizeof (regoff_t
));
2080 = (regoff_t
*) xrealloc (search_regs
.start
,
2081 length
* sizeof (regoff_t
));
2083 = (regoff_t
*) xrealloc (search_regs
.end
,
2084 length
* sizeof (regoff_t
));
2087 search_regs
.num_regs
= length
;
2091 for (i
= 0; i
< search_regs
.num_regs
; i
++)
2093 marker
= Fcar (list
);
2096 search_regs
.start
[i
] = -1;
2101 if (MARKERP (marker
))
2103 if (XMARKER (marker
)->buffer
== 0)
2104 XSETFASTINT (marker
, 0);
2106 XSETBUFFER (last_thing_searched
, XMARKER (marker
)->buffer
);
2109 CHECK_NUMBER_COERCE_MARKER (marker
, 0);
2110 search_regs
.start
[i
] = XINT (marker
);
2113 marker
= Fcar (list
);
2114 if (MARKERP (marker
) && XMARKER (marker
)->buffer
== 0)
2115 XSETFASTINT (marker
, 0);
2117 CHECK_NUMBER_COERCE_MARKER (marker
, 0);
2118 search_regs
.end
[i
] = XINT (marker
);
2126 /* If non-zero the match data have been saved in saved_search_regs
2127 during the execution of a sentinel or filter. */
2128 static int search_regs_saved
;
2129 static struct re_registers saved_search_regs
;
2131 /* Called from Flooking_at, Fstring_match, search_buffer, Fstore_match_data
2132 if asynchronous code (filter or sentinel) is running. */
2136 if (!search_regs_saved
)
2138 saved_search_regs
.num_regs
= search_regs
.num_regs
;
2139 saved_search_regs
.start
= search_regs
.start
;
2140 saved_search_regs
.end
= search_regs
.end
;
2141 search_regs
.num_regs
= 0;
2142 search_regs
.start
= 0;
2143 search_regs
.end
= 0;
2145 search_regs_saved
= 1;
2149 /* Called upon exit from filters and sentinels. */
2151 restore_match_data ()
2153 if (search_regs_saved
)
2155 if (search_regs
.num_regs
> 0)
2157 xfree (search_regs
.start
);
2158 xfree (search_regs
.end
);
2160 search_regs
.num_regs
= saved_search_regs
.num_regs
;
2161 search_regs
.start
= saved_search_regs
.start
;
2162 search_regs
.end
= saved_search_regs
.end
;
2164 search_regs_saved
= 0;
2168 /* Quote a string to inactivate reg-expr chars */
2170 DEFUN ("regexp-quote", Fregexp_quote
, Sregexp_quote
, 1, 1, 0,
2171 "Return a regexp string which matches exactly STRING and nothing else.")
2175 register unsigned char *in
, *out
, *end
;
2176 register unsigned char *temp
;
2178 CHECK_STRING (string
, 0);
2180 temp
= (unsigned char *) alloca (XSTRING (string
)->size
* 2);
2182 /* Now copy the data into the new string, inserting escapes. */
2184 in
= XSTRING (string
)->data
;
2185 end
= in
+ XSTRING (string
)->size
;
2188 for (; in
!= end
; in
++)
2190 if (*in
== '[' || *in
== ']'
2191 || *in
== '*' || *in
== '.' || *in
== '\\'
2192 || *in
== '?' || *in
== '+'
2193 || *in
== '^' || *in
== '$')
2198 return make_string (temp
, out
- temp
);
2205 for (i
= 0; i
< REGEXP_CACHE_SIZE
; ++i
)
2207 searchbufs
[i
].buf
.allocated
= 100;
2208 searchbufs
[i
].buf
.buffer
= (unsigned char *) malloc (100);
2209 searchbufs
[i
].buf
.fastmap
= searchbufs
[i
].fastmap
;
2210 searchbufs
[i
].regexp
= Qnil
;
2211 staticpro (&searchbufs
[i
].regexp
);
2212 searchbufs
[i
].next
= (i
== REGEXP_CACHE_SIZE
-1 ? 0 : &searchbufs
[i
+1]);
2214 searchbuf_head
= &searchbufs
[0];
2216 Qsearch_failed
= intern ("search-failed");
2217 staticpro (&Qsearch_failed
);
2218 Qinvalid_regexp
= intern ("invalid-regexp");
2219 staticpro (&Qinvalid_regexp
);
2221 Fput (Qsearch_failed
, Qerror_conditions
,
2222 Fcons (Qsearch_failed
, Fcons (Qerror
, Qnil
)));
2223 Fput (Qsearch_failed
, Qerror_message
,
2224 build_string ("Search failed"));
2226 Fput (Qinvalid_regexp
, Qerror_conditions
,
2227 Fcons (Qinvalid_regexp
, Fcons (Qerror
, Qnil
)));
2228 Fput (Qinvalid_regexp
, Qerror_message
,
2229 build_string ("Invalid regexp"));
2231 last_thing_searched
= Qnil
;
2232 staticpro (&last_thing_searched
);
2234 defsubr (&Slooking_at
);
2235 defsubr (&Sposix_looking_at
);
2236 defsubr (&Sstring_match
);
2237 defsubr (&Sposix_string_match
);
2238 defsubr (&Sskip_chars_forward
);
2239 defsubr (&Sskip_chars_backward
);
2240 defsubr (&Sskip_syntax_forward
);
2241 defsubr (&Sskip_syntax_backward
);
2242 defsubr (&Ssearch_forward
);
2243 defsubr (&Ssearch_backward
);
2244 defsubr (&Sword_search_forward
);
2245 defsubr (&Sword_search_backward
);
2246 defsubr (&Sre_search_forward
);
2247 defsubr (&Sre_search_backward
);
2248 defsubr (&Sposix_search_forward
);
2249 defsubr (&Sposix_search_backward
);
2250 defsubr (&Sreplace_match
);
2251 defsubr (&Smatch_beginning
);
2252 defsubr (&Smatch_end
);
2253 defsubr (&Smatch_data
);
2254 defsubr (&Sstore_match_data
);
2255 defsubr (&Sregexp_quote
);