1 /* String search routines for GNU Emacs.
2 Copyright (C) 1985, 86,87,93,94,97,98, 1999 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"
31 #include "intervals.h"
33 #include <sys/types.h>
36 #define min(a, b) ((a) < (b) ? (a) : (b))
37 #define max(a, b) ((a) > (b) ? (a) : (b))
39 #define REGEXP_CACHE_SIZE 20
41 /* If the regexp is non-nil, then the buffer contains the compiled form
42 of that regexp, suitable for searching. */
45 struct regexp_cache
*next
;
47 struct re_pattern_buffer buf
;
49 /* Nonzero means regexp was compiled to do full POSIX backtracking. */
53 /* The instances of that struct. */
54 struct regexp_cache searchbufs
[REGEXP_CACHE_SIZE
];
56 /* The head of the linked list; points to the most recently used buffer. */
57 struct regexp_cache
*searchbuf_head
;
60 /* Every call to re_match, etc., must pass &search_regs as the regs
61 argument unless you can show it is unnecessary (i.e., if re_match
62 is certainly going to be called again before region-around-match
65 Since the registers are now dynamically allocated, we need to make
66 sure not to refer to the Nth register before checking that it has
67 been allocated by checking search_regs.num_regs.
69 The regex code keeps track of whether it has allocated the search
70 buffer using bits in the re_pattern_buffer. This means that whenever
71 you compile a new pattern, it completely forgets whether it has
72 allocated any registers, and will allocate new registers the next
73 time you call a searching or matching function. Therefore, we need
74 to call re_set_registers after compiling a new pattern or after
75 setting the match registers, so that the regex functions will be
76 able to free or re-allocate it properly. */
77 static struct re_registers search_regs
;
79 /* The buffer in which the last search was performed, or
80 Qt if the last search was done in a string;
81 Qnil if no searching has been done yet. */
82 static Lisp_Object last_thing_searched
;
84 /* error condition signaled when regexp compile_pattern fails */
86 Lisp_Object Qinvalid_regexp
;
88 static void set_search_regs ();
89 static void save_search_regs ();
90 static int simple_search ();
91 static int boyer_moore ();
92 static int search_buffer ();
97 error ("Stack overflow in regexp matcher");
106 /* Compile a regexp and signal a Lisp error if anything goes wrong.
107 PATTERN is the pattern to compile.
108 CP is the place to put the result.
109 TRANSLATE is a translation table for ignoring case, or nil for none.
110 REGP is the structure that says where to store the "register"
111 values that will result from matching this pattern.
112 If it is 0, we should compile the pattern not to record any
113 subexpression bounds.
114 POSIX is nonzero if we want full backtracking (POSIX style)
115 for this pattern. 0 means backtrack only enough to get a valid match.
116 MULTIBYTE is nonzero if we want to handle multibyte characters in
117 PATTERN. 0 means all multibyte characters are recognized just as
118 sequences of binary data. */
121 compile_pattern_1 (cp
, pattern
, translate
, regp
, posix
, multibyte
)
122 struct regexp_cache
*cp
;
124 Lisp_Object translate
;
125 struct re_registers
*regp
;
129 unsigned char *raw_pattern
;
130 int raw_pattern_size
;
134 /* MULTIBYTE says whether the text to be searched is multibyte.
135 We must convert PATTERN to match that, or we will not really
136 find things right. */
138 if (multibyte
== STRING_MULTIBYTE (pattern
))
140 raw_pattern
= (unsigned char *) XSTRING (pattern
)->data
;
141 raw_pattern_size
= STRING_BYTES (XSTRING (pattern
));
145 raw_pattern_size
= count_size_as_multibyte (XSTRING (pattern
)->data
,
146 XSTRING (pattern
)->size
);
147 raw_pattern
= (unsigned char *) alloca (raw_pattern_size
+ 1);
148 copy_text (XSTRING (pattern
)->data
, raw_pattern
,
149 XSTRING (pattern
)->size
, 0, 1);
153 /* Converting multibyte to single-byte.
155 ??? Perhaps this conversion should be done in a special way
156 by subtracting nonascii-insert-offset from each non-ASCII char,
157 so that only the multibyte chars which really correspond to
158 the chosen single-byte character set can possibly match. */
159 raw_pattern_size
= XSTRING (pattern
)->size
;
160 raw_pattern
= (unsigned char *) alloca (raw_pattern_size
+ 1);
161 copy_text (XSTRING (pattern
)->data
, raw_pattern
,
162 STRING_BYTES (XSTRING (pattern
)), 1, 0);
166 cp
->buf
.translate
= (! NILP (translate
) ? translate
: make_number (0));
168 cp
->buf
.multibyte
= multibyte
;
170 old
= re_set_syntax (RE_SYNTAX_EMACS
171 | (posix
? 0 : RE_NO_POSIX_BACKTRACKING
));
172 val
= (char *) re_compile_pattern ((char *)raw_pattern
,
173 raw_pattern_size
, &cp
->buf
);
177 Fsignal (Qinvalid_regexp
, Fcons (build_string (val
), Qnil
));
179 cp
->regexp
= Fcopy_sequence (pattern
);
182 /* Shrink each compiled regexp buffer in the cache
183 to the size actually used right now.
184 This is called from garbage collection. */
187 shrink_regexp_cache ()
189 struct regexp_cache
*cp
, **cpp
;
191 for (cp
= searchbuf_head
; cp
!= 0; cp
= cp
->next
)
193 cp
->buf
.allocated
= cp
->buf
.used
;
195 = (unsigned char *) realloc (cp
->buf
.buffer
, cp
->buf
.used
);
199 /* Compile a regexp if necessary, but first check to see if there's one in
201 PATTERN is the pattern to compile.
202 TRANSLATE is a translation table for ignoring case, or nil for none.
203 REGP is the structure that says where to store the "register"
204 values that will result from matching this pattern.
205 If it is 0, we should compile the pattern not to record any
206 subexpression bounds.
207 POSIX is nonzero if we want full backtracking (POSIX style)
208 for this pattern. 0 means backtrack only enough to get a valid match. */
210 struct re_pattern_buffer
*
211 compile_pattern (pattern
, regp
, translate
, posix
, multibyte
)
213 struct re_registers
*regp
;
214 Lisp_Object translate
;
215 int posix
, multibyte
;
217 struct regexp_cache
*cp
, **cpp
;
219 for (cpp
= &searchbuf_head
; ; cpp
= &cp
->next
)
222 /* Entries are initialized to nil, and may be set to nil by
223 compile_pattern_1 if the pattern isn't valid. Don't apply
224 XSTRING in those cases. However, compile_pattern_1 is only
225 applied to the cache entry we pick here to reuse. So nil
226 should never appear before a non-nil entry. */
227 if (cp
->regexp
== Qnil
)
229 if (XSTRING (cp
->regexp
)->size
== XSTRING (pattern
)->size
230 && !NILP (Fstring_equal (cp
->regexp
, pattern
))
231 && EQ (cp
->buf
.translate
, (! NILP (translate
) ? translate
: make_number (0)))
232 && cp
->posix
== posix
233 && cp
->buf
.multibyte
== multibyte
)
236 /* If we're at the end of the cache, compile into the nil cell
237 we found, or the last (least recently used) cell with a
242 compile_pattern_1 (cp
, pattern
, translate
, regp
, posix
, multibyte
);
247 /* When we get here, cp (aka *cpp) contains the compiled pattern,
248 either because we found it in the cache or because we just compiled it.
249 Move it to the front of the queue to mark it as most recently used. */
251 cp
->next
= searchbuf_head
;
254 /* Advise the searching functions about the space we have allocated
255 for register data. */
257 re_set_registers (&cp
->buf
, regp
, regp
->num_regs
, regp
->start
, regp
->end
);
262 /* Error condition used for failing searches */
263 Lisp_Object Qsearch_failed
;
269 Fsignal (Qsearch_failed
, Fcons (arg
, Qnil
));
274 looking_at_1 (string
, posix
)
279 unsigned char *p1
, *p2
;
282 struct re_pattern_buffer
*bufp
;
284 if (running_asynch_code
)
287 CHECK_STRING (string
, 0);
288 bufp
= compile_pattern (string
, &search_regs
,
289 (!NILP (current_buffer
->case_fold_search
)
290 ? DOWNCASE_TABLE
: Qnil
),
292 !NILP (current_buffer
->enable_multibyte_characters
));
295 QUIT
; /* Do a pending quit right away, to avoid paradoxical behavior */
297 /* Get pointers and sizes of the two strings
298 that make up the visible portion of the buffer. */
301 s1
= GPT_BYTE
- BEGV_BYTE
;
303 s2
= ZV_BYTE
- GPT_BYTE
;
307 s2
= ZV_BYTE
- BEGV_BYTE
;
312 s1
= ZV_BYTE
- BEGV_BYTE
;
316 re_match_object
= Qnil
;
318 i
= re_match_2 (bufp
, (char *) p1
, s1
, (char *) p2
, s2
,
319 PT_BYTE
- BEGV_BYTE
, &search_regs
,
320 ZV_BYTE
- BEGV_BYTE
);
326 val
= (0 <= i
? Qt
: Qnil
);
328 for (i
= 0; i
< search_regs
.num_regs
; i
++)
329 if (search_regs
.start
[i
] >= 0)
332 = BYTE_TO_CHAR (search_regs
.start
[i
] + BEGV_BYTE
);
334 = BYTE_TO_CHAR (search_regs
.end
[i
] + BEGV_BYTE
);
336 XSETBUFFER (last_thing_searched
, current_buffer
);
340 DEFUN ("looking-at", Flooking_at
, Slooking_at
, 1, 1, 0,
341 "Return t if text after point matches regular expression REGEXP.\n\
342 This function modifies the match data that `match-beginning',\n\
343 `match-end' and `match-data' access; save and restore the match\n\
344 data if you want to preserve them.")
348 return looking_at_1 (regexp
, 0);
351 DEFUN ("posix-looking-at", Fposix_looking_at
, Sposix_looking_at
, 1, 1, 0,
352 "Return t if text after point matches regular expression REGEXP.\n\
353 Find the longest match, in accord with Posix regular expression rules.\n\
354 This function modifies the match data that `match-beginning',\n\
355 `match-end' and `match-data' access; save and restore the match\n\
356 data if you want to preserve them.")
360 return looking_at_1 (regexp
, 1);
364 string_match_1 (regexp
, string
, start
, posix
)
365 Lisp_Object regexp
, string
, start
;
369 struct re_pattern_buffer
*bufp
;
373 if (running_asynch_code
)
376 CHECK_STRING (regexp
, 0);
377 CHECK_STRING (string
, 1);
380 pos
= 0, pos_byte
= 0;
383 int len
= XSTRING (string
)->size
;
385 CHECK_NUMBER (start
, 2);
387 if (pos
< 0 && -pos
<= len
)
389 else if (0 > pos
|| pos
> len
)
390 args_out_of_range (string
, start
);
391 pos_byte
= string_char_to_byte (string
, pos
);
394 bufp
= compile_pattern (regexp
, &search_regs
,
395 (!NILP (current_buffer
->case_fold_search
)
396 ? DOWNCASE_TABLE
: Qnil
),
398 STRING_MULTIBYTE (string
));
400 re_match_object
= string
;
402 val
= re_search (bufp
, (char *) XSTRING (string
)->data
,
403 STRING_BYTES (XSTRING (string
)), pos_byte
,
404 STRING_BYTES (XSTRING (string
)) - pos_byte
,
407 last_thing_searched
= Qt
;
410 if (val
< 0) return Qnil
;
412 for (i
= 0; i
< search_regs
.num_regs
; i
++)
413 if (search_regs
.start
[i
] >= 0)
416 = string_byte_to_char (string
, search_regs
.start
[i
]);
418 = string_byte_to_char (string
, search_regs
.end
[i
]);
421 return make_number (string_byte_to_char (string
, val
));
424 DEFUN ("string-match", Fstring_match
, Sstring_match
, 2, 3, 0,
425 "Return index of start of first match for REGEXP in STRING, or nil.\n\
426 Case is ignored if `case-fold-search' is non-nil in the current buffer.\n\
427 If third arg START is non-nil, start search at that index in STRING.\n\
428 For index of first char beyond the match, do (match-end 0).\n\
429 `match-end' and `match-beginning' also give indices of substrings\n\
430 matched by parenthesis constructs in the pattern.")
431 (regexp
, string
, start
)
432 Lisp_Object regexp
, string
, start
;
434 return string_match_1 (regexp
, string
, start
, 0);
437 DEFUN ("posix-string-match", Fposix_string_match
, Sposix_string_match
, 2, 3, 0,
438 "Return index of start of first match for REGEXP in STRING, or nil.\n\
439 Find the longest match, in accord with Posix regular expression rules.\n\
440 Case is ignored if `case-fold-search' is non-nil in the current buffer.\n\
441 If third arg START is non-nil, start search at that index in STRING.\n\
442 For index of first char beyond the match, do (match-end 0).\n\
443 `match-end' and `match-beginning' also give indices of substrings\n\
444 matched by parenthesis constructs in the pattern.")
445 (regexp
, string
, start
)
446 Lisp_Object regexp
, string
, start
;
448 return string_match_1 (regexp
, string
, start
, 1);
451 /* Match REGEXP against STRING, searching all of STRING,
452 and return the index of the match, or negative on failure.
453 This does not clobber the match data. */
456 fast_string_match (regexp
, string
)
457 Lisp_Object regexp
, string
;
460 struct re_pattern_buffer
*bufp
;
462 bufp
= compile_pattern (regexp
, 0, Qnil
,
463 0, STRING_MULTIBYTE (string
));
465 re_match_object
= string
;
467 val
= re_search (bufp
, (char *) XSTRING (string
)->data
,
468 STRING_BYTES (XSTRING (string
)), 0,
469 STRING_BYTES (XSTRING (string
)), 0);
474 /* Match REGEXP against STRING, searching all of STRING ignoring case,
475 and return the index of the match, or negative on failure.
476 This does not clobber the match data.
477 We assume that STRING contains single-byte characters. */
479 extern Lisp_Object Vascii_downcase_table
;
482 fast_c_string_match_ignore_case (regexp
, string
)
487 struct re_pattern_buffer
*bufp
;
488 int len
= strlen (string
);
490 regexp
= string_make_unibyte (regexp
);
491 re_match_object
= Qt
;
492 bufp
= compile_pattern (regexp
, 0,
493 Vascii_downcase_table
, 0,
496 val
= re_search (bufp
, string
, len
, 0, len
, 0);
501 /* The newline cache: remembering which sections of text have no newlines. */
503 /* If the user has requested newline caching, make sure it's on.
504 Otherwise, make sure it's off.
505 This is our cheezy way of associating an action with the change of
506 state of a buffer-local variable. */
508 newline_cache_on_off (buf
)
511 if (NILP (buf
->cache_long_line_scans
))
513 /* It should be off. */
514 if (buf
->newline_cache
)
516 free_region_cache (buf
->newline_cache
);
517 buf
->newline_cache
= 0;
522 /* It should be on. */
523 if (buf
->newline_cache
== 0)
524 buf
->newline_cache
= new_region_cache ();
529 /* Search for COUNT instances of the character TARGET between START and END.
531 If COUNT is positive, search forwards; END must be >= START.
532 If COUNT is negative, search backwards for the -COUNTth instance;
533 END must be <= START.
534 If COUNT is zero, do anything you please; run rogue, for all I care.
536 If END is zero, use BEGV or ZV instead, as appropriate for the
537 direction indicated by COUNT.
539 If we find COUNT instances, set *SHORTAGE to zero, and return the
540 position after the COUNTth match. Note that for reverse motion
541 this is not the same as the usual convention for Emacs motion commands.
543 If we don't find COUNT instances before reaching END, set *SHORTAGE
544 to the number of TARGETs left unfound, and return END.
546 If ALLOW_QUIT is non-zero, set immediate_quit. That's good to do
547 except when inside redisplay. */
550 scan_buffer (target
, start
, end
, count
, shortage
, allow_quit
)
557 struct region_cache
*newline_cache
;
568 if (! end
) end
= BEGV
;
571 newline_cache_on_off (current_buffer
);
572 newline_cache
= current_buffer
->newline_cache
;
577 immediate_quit
= allow_quit
;
582 /* Our innermost scanning loop is very simple; it doesn't know
583 about gaps, buffer ends, or the newline cache. ceiling is
584 the position of the last character before the next such
585 obstacle --- the last character the dumb search loop should
587 int ceiling_byte
= CHAR_TO_BYTE (end
) - 1;
588 int start_byte
= CHAR_TO_BYTE (start
);
591 /* If we're looking for a newline, consult the newline cache
592 to see where we can avoid some scanning. */
593 if (target
== '\n' && newline_cache
)
597 while (region_cache_forward
598 (current_buffer
, newline_cache
, start_byte
, &next_change
))
599 start_byte
= next_change
;
600 immediate_quit
= allow_quit
;
602 /* START should never be after END. */
603 if (start_byte
> ceiling_byte
)
604 start_byte
= ceiling_byte
;
606 /* Now the text after start is an unknown region, and
607 next_change is the position of the next known region. */
608 ceiling_byte
= min (next_change
- 1, ceiling_byte
);
611 /* The dumb loop can only scan text stored in contiguous
612 bytes. BUFFER_CEILING_OF returns the last character
613 position that is contiguous, so the ceiling is the
614 position after that. */
615 tem
= BUFFER_CEILING_OF (start_byte
);
616 ceiling_byte
= min (tem
, ceiling_byte
);
619 /* The termination address of the dumb loop. */
620 register unsigned char *ceiling_addr
621 = BYTE_POS_ADDR (ceiling_byte
) + 1;
622 register unsigned char *cursor
623 = BYTE_POS_ADDR (start_byte
);
624 unsigned char *base
= cursor
;
626 while (cursor
< ceiling_addr
)
628 unsigned char *scan_start
= cursor
;
631 while (*cursor
!= target
&& ++cursor
< ceiling_addr
)
634 /* If we're looking for newlines, cache the fact that
635 the region from start to cursor is free of them. */
636 if (target
== '\n' && newline_cache
)
637 know_region_cache (current_buffer
, newline_cache
,
638 start_byte
+ scan_start
- base
,
639 start_byte
+ cursor
- base
);
641 /* Did we find the target character? */
642 if (cursor
< ceiling_addr
)
647 return BYTE_TO_CHAR (start_byte
+ cursor
- base
+ 1);
653 start
= BYTE_TO_CHAR (start_byte
+ cursor
- base
);
659 /* The last character to check before the next obstacle. */
660 int ceiling_byte
= CHAR_TO_BYTE (end
);
661 int start_byte
= CHAR_TO_BYTE (start
);
664 /* Consult the newline cache, if appropriate. */
665 if (target
== '\n' && newline_cache
)
669 while (region_cache_backward
670 (current_buffer
, newline_cache
, start_byte
, &next_change
))
671 start_byte
= next_change
;
672 immediate_quit
= allow_quit
;
674 /* Start should never be at or before end. */
675 if (start_byte
<= ceiling_byte
)
676 start_byte
= ceiling_byte
+ 1;
678 /* Now the text before start is an unknown region, and
679 next_change is the position of the next known region. */
680 ceiling_byte
= max (next_change
, ceiling_byte
);
683 /* Stop scanning before the gap. */
684 tem
= BUFFER_FLOOR_OF (start_byte
- 1);
685 ceiling_byte
= max (tem
, ceiling_byte
);
688 /* The termination address of the dumb loop. */
689 register unsigned char *ceiling_addr
= BYTE_POS_ADDR (ceiling_byte
);
690 register unsigned char *cursor
= BYTE_POS_ADDR (start_byte
- 1);
691 unsigned char *base
= cursor
;
693 while (cursor
>= ceiling_addr
)
695 unsigned char *scan_start
= cursor
;
697 while (*cursor
!= target
&& --cursor
>= ceiling_addr
)
700 /* If we're looking for newlines, cache the fact that
701 the region from after the cursor to start is free of them. */
702 if (target
== '\n' && newline_cache
)
703 know_region_cache (current_buffer
, newline_cache
,
704 start_byte
+ cursor
- base
,
705 start_byte
+ scan_start
- base
);
707 /* Did we find the target character? */
708 if (cursor
>= ceiling_addr
)
713 return BYTE_TO_CHAR (start_byte
+ cursor
- base
);
719 start
= BYTE_TO_CHAR (start_byte
+ cursor
- base
);
725 *shortage
= count
* direction
;
729 /* Search for COUNT instances of a line boundary, which means either a
730 newline or (if selective display enabled) a carriage return.
731 Start at START. If COUNT is negative, search backwards.
733 We report the resulting position by calling TEMP_SET_PT_BOTH.
735 If we find COUNT instances. we position after (always after,
736 even if scanning backwards) the COUNTth match, and return 0.
738 If we don't find COUNT instances before reaching the end of the
739 buffer (or the beginning, if scanning backwards), we return
740 the number of line boundaries left unfound, and position at
741 the limit we bumped up against.
743 If ALLOW_QUIT is non-zero, set immediate_quit. That's good to do
744 except in special cases. */
747 scan_newline (start
, start_byte
, limit
, limit_byte
, count
, allow_quit
)
748 int start
, start_byte
;
749 int limit
, limit_byte
;
753 int direction
= ((count
> 0) ? 1 : -1);
755 register unsigned char *cursor
;
758 register int ceiling
;
759 register unsigned char *ceiling_addr
;
761 int old_immediate_quit
= immediate_quit
;
763 /* If we are not in selective display mode,
764 check only for newlines. */
765 int selective_display
= (!NILP (current_buffer
->selective_display
)
766 && !INTEGERP (current_buffer
->selective_display
));
768 /* The code that follows is like scan_buffer
769 but checks for either newline or carriage return. */
774 start_byte
= CHAR_TO_BYTE (start
);
778 while (start_byte
< limit_byte
)
780 ceiling
= BUFFER_CEILING_OF (start_byte
);
781 ceiling
= min (limit_byte
- 1, ceiling
);
782 ceiling_addr
= BYTE_POS_ADDR (ceiling
) + 1;
783 base
= (cursor
= BYTE_POS_ADDR (start_byte
));
786 while (*cursor
!= '\n' && ++cursor
!= ceiling_addr
)
789 if (cursor
!= ceiling_addr
)
793 immediate_quit
= old_immediate_quit
;
794 start_byte
= start_byte
+ cursor
- base
+ 1;
795 start
= BYTE_TO_CHAR (start_byte
);
796 TEMP_SET_PT_BOTH (start
, start_byte
);
800 if (++cursor
== ceiling_addr
)
806 start_byte
+= cursor
- base
;
811 while (start_byte
> limit_byte
)
813 ceiling
= BUFFER_FLOOR_OF (start_byte
- 1);
814 ceiling
= max (limit_byte
, ceiling
);
815 ceiling_addr
= BYTE_POS_ADDR (ceiling
) - 1;
816 base
= (cursor
= BYTE_POS_ADDR (start_byte
- 1) + 1);
819 while (--cursor
!= ceiling_addr
&& *cursor
!= '\n')
822 if (cursor
!= ceiling_addr
)
826 immediate_quit
= old_immediate_quit
;
827 /* Return the position AFTER the match we found. */
828 start_byte
= start_byte
+ cursor
- base
+ 1;
829 start
= BYTE_TO_CHAR (start_byte
);
830 TEMP_SET_PT_BOTH (start
, start_byte
);
837 /* Here we add 1 to compensate for the last decrement
838 of CURSOR, which took it past the valid range. */
839 start_byte
+= cursor
- base
+ 1;
843 TEMP_SET_PT_BOTH (limit
, limit_byte
);
844 immediate_quit
= old_immediate_quit
;
846 return count
* direction
;
850 find_next_newline_no_quit (from
, cnt
)
851 register int from
, cnt
;
853 return scan_buffer ('\n', from
, 0, cnt
, (int *) 0, 0);
856 /* Like find_next_newline, but returns position before the newline,
857 not after, and only search up to TO. This isn't just
858 find_next_newline (...)-1, because you might hit TO. */
861 find_before_next_newline (from
, to
, cnt
)
865 int pos
= scan_buffer ('\n', from
, to
, cnt
, &shortage
, 1);
873 /* Subroutines of Lisp buffer search functions. */
876 search_command (string
, bound
, noerror
, count
, direction
, RE
, posix
)
877 Lisp_Object string
, bound
, noerror
, count
;
888 CHECK_NUMBER (count
, 3);
892 CHECK_STRING (string
, 0);
896 lim
= ZV
, lim_byte
= ZV_BYTE
;
898 lim
= BEGV
, lim_byte
= BEGV_BYTE
;
902 CHECK_NUMBER_COERCE_MARKER (bound
, 1);
904 if (n
> 0 ? lim
< PT
: lim
> PT
)
905 error ("Invalid search bound (wrong side of point)");
907 lim
= ZV
, lim_byte
= ZV_BYTE
;
909 lim
= BEGV
, lim_byte
= BEGV_BYTE
;
911 lim_byte
= CHAR_TO_BYTE (lim
);
914 np
= search_buffer (string
, PT
, PT_BYTE
, lim
, lim_byte
, n
, RE
,
915 (!NILP (current_buffer
->case_fold_search
)
916 ? current_buffer
->case_canon_table
918 (!NILP (current_buffer
->case_fold_search
)
919 ? current_buffer
->case_eqv_table
925 return signal_failure (string
);
926 if (!EQ (noerror
, Qt
))
928 if (lim
< BEGV
|| lim
> ZV
)
930 SET_PT_BOTH (lim
, lim_byte
);
932 #if 0 /* This would be clean, but maybe programs depend on
933 a value of nil here. */
941 if (np
< BEGV
|| np
> ZV
)
946 return make_number (np
);
949 /* Return 1 if REGEXP it matches just one constant string. */
952 trivial_regexp_p (regexp
)
955 int len
= STRING_BYTES (XSTRING (regexp
));
956 unsigned char *s
= XSTRING (regexp
)->data
;
962 case '.': case '*': case '+': case '?': case '[': case '^': case '$':
969 case '|': case '(': case ')': case '`': case '\'': case 'b':
970 case 'B': case '<': case '>': case 'w': case 'W': case 's':
972 case 'c': case 'C': /* for categoryspec and notcategoryspec */
973 case '1': case '2': case '3': case '4': case '5':
974 case '6': case '7': case '8': case '9':
982 /* Search for the n'th occurrence of STRING in the current buffer,
983 starting at position POS and stopping at position LIM,
984 treating STRING as a literal string if RE is false or as
985 a regular expression if RE is true.
987 If N is positive, searching is forward and LIM must be greater than POS.
988 If N is negative, searching is backward and LIM must be less than POS.
990 Returns -x if x occurrences remain to be found (x > 0),
991 or else the position at the beginning of the Nth occurrence
992 (if searching backward) or the end (if searching forward).
994 POSIX is nonzero if we want full backtracking (POSIX style)
995 for this pattern. 0 means backtrack only enough to get a valid match. */
997 #define TRANSLATE(out, trt, d) \
1003 temp = Faref (trt, make_number (d)); \
1004 if (INTEGERP (temp)) \
1005 out = XINT (temp); \
1015 search_buffer (string
, pos
, pos_byte
, lim
, lim_byte
, n
,
1016 RE
, trt
, inverse_trt
, posix
)
1025 Lisp_Object inverse_trt
;
1028 int len
= XSTRING (string
)->size
;
1029 int len_byte
= STRING_BYTES (XSTRING (string
));
1032 if (running_asynch_code
)
1033 save_search_regs ();
1035 /* Searching 0 times means don't move. */
1036 /* Null string is found at starting position. */
1037 if (len
== 0 || n
== 0)
1039 set_search_regs (pos
, 0);
1043 if (RE
&& !trivial_regexp_p (string
))
1045 unsigned char *p1
, *p2
;
1047 struct re_pattern_buffer
*bufp
;
1049 bufp
= compile_pattern (string
, &search_regs
, trt
, posix
,
1050 !NILP (current_buffer
->enable_multibyte_characters
));
1052 immediate_quit
= 1; /* Quit immediately if user types ^G,
1053 because letting this function finish
1054 can take too long. */
1055 QUIT
; /* Do a pending quit right away,
1056 to avoid paradoxical behavior */
1057 /* Get pointers and sizes of the two strings
1058 that make up the visible portion of the buffer. */
1061 s1
= GPT_BYTE
- BEGV_BYTE
;
1063 s2
= ZV_BYTE
- GPT_BYTE
;
1067 s2
= ZV_BYTE
- BEGV_BYTE
;
1072 s1
= ZV_BYTE
- BEGV_BYTE
;
1075 re_match_object
= Qnil
;
1080 val
= re_search_2 (bufp
, (char *) p1
, s1
, (char *) p2
, s2
,
1081 pos_byte
- BEGV_BYTE
, lim_byte
- pos_byte
,
1083 /* Don't allow match past current point */
1084 pos_byte
- BEGV_BYTE
);
1087 matcher_overflow ();
1091 pos_byte
= search_regs
.start
[0] + BEGV_BYTE
;
1092 for (i
= 0; i
< search_regs
.num_regs
; i
++)
1093 if (search_regs
.start
[i
] >= 0)
1095 search_regs
.start
[i
]
1096 = BYTE_TO_CHAR (search_regs
.start
[i
] + BEGV_BYTE
);
1098 = BYTE_TO_CHAR (search_regs
.end
[i
] + BEGV_BYTE
);
1100 XSETBUFFER (last_thing_searched
, current_buffer
);
1101 /* Set pos to the new position. */
1102 pos
= search_regs
.start
[0];
1114 val
= re_search_2 (bufp
, (char *) p1
, s1
, (char *) p2
, s2
,
1115 pos_byte
- BEGV_BYTE
, lim_byte
- pos_byte
,
1117 lim_byte
- BEGV_BYTE
);
1120 matcher_overflow ();
1124 pos_byte
= search_regs
.end
[0] + BEGV_BYTE
;
1125 for (i
= 0; i
< search_regs
.num_regs
; i
++)
1126 if (search_regs
.start
[i
] >= 0)
1128 search_regs
.start
[i
]
1129 = BYTE_TO_CHAR (search_regs
.start
[i
] + BEGV_BYTE
);
1131 = BYTE_TO_CHAR (search_regs
.end
[i
] + BEGV_BYTE
);
1133 XSETBUFFER (last_thing_searched
, current_buffer
);
1134 pos
= search_regs
.end
[0];
1146 else /* non-RE case */
1148 unsigned char *raw_pattern
, *pat
;
1149 int raw_pattern_size
;
1150 int raw_pattern_size_byte
;
1151 unsigned char *patbuf
;
1152 int multibyte
= !NILP (current_buffer
->enable_multibyte_characters
);
1153 unsigned char *base_pat
= XSTRING (string
)->data
;
1154 int charset_base
= -1;
1155 int boyer_moore_ok
= 1;
1157 /* MULTIBYTE says whether the text to be searched is multibyte.
1158 We must convert PATTERN to match that, or we will not really
1159 find things right. */
1161 if (multibyte
== STRING_MULTIBYTE (string
))
1163 raw_pattern
= (unsigned char *) XSTRING (string
)->data
;
1164 raw_pattern_size
= XSTRING (string
)->size
;
1165 raw_pattern_size_byte
= STRING_BYTES (XSTRING (string
));
1169 raw_pattern_size
= XSTRING (string
)->size
;
1170 raw_pattern_size_byte
1171 = count_size_as_multibyte (XSTRING (string
)->data
,
1173 raw_pattern
= (unsigned char *) alloca (raw_pattern_size_byte
+ 1);
1174 copy_text (XSTRING (string
)->data
, raw_pattern
,
1175 XSTRING (string
)->size
, 0, 1);
1179 /* Converting multibyte to single-byte.
1181 ??? Perhaps this conversion should be done in a special way
1182 by subtracting nonascii-insert-offset from each non-ASCII char,
1183 so that only the multibyte chars which really correspond to
1184 the chosen single-byte character set can possibly match. */
1185 raw_pattern_size
= XSTRING (string
)->size
;
1186 raw_pattern_size_byte
= XSTRING (string
)->size
;
1187 raw_pattern
= (unsigned char *) alloca (raw_pattern_size
+ 1);
1188 copy_text (XSTRING (string
)->data
, raw_pattern
,
1189 STRING_BYTES (XSTRING (string
)), 1, 0);
1192 /* Copy and optionally translate the pattern. */
1193 len
= raw_pattern_size
;
1194 len_byte
= raw_pattern_size_byte
;
1195 patbuf
= (unsigned char *) alloca (len_byte
);
1197 base_pat
= raw_pattern
;
1202 unsigned char str
[MAX_MULTIBYTE_LENGTH
];
1203 int c
, translated
, inverse
;
1204 int in_charlen
, charlen
;
1206 /* If we got here and the RE flag is set, it's because we're
1207 dealing with a regexp known to be trivial, so the backslash
1208 just quotes the next character. */
1209 if (RE
&& *base_pat
== '\\')
1216 c
= STRING_CHAR_AND_LENGTH (base_pat
, len_byte
, in_charlen
);
1218 /* Translate the character, if requested. */
1219 TRANSLATE (translated
, trt
, c
);
1220 /* If translation changed the byte-length, go back
1221 to the original character. */
1222 charlen
= CHAR_STRING (translated
, str
);
1223 if (in_charlen
!= charlen
)
1226 charlen
= CHAR_STRING (c
, str
);
1229 /* If we are searching for something strange,
1230 an invalid multibyte code, don't use boyer-moore. */
1231 if (! ASCII_BYTE_P (translated
)
1232 && (charlen
== 1 /* 8bit code */
1233 || charlen
!= in_charlen
/* invalid multibyte code */
1237 TRANSLATE (inverse
, inverse_trt
, c
);
1239 /* Did this char actually get translated?
1240 Would any other char get translated into it? */
1241 if (translated
!= c
|| inverse
!= c
)
1243 /* Keep track of which character set row
1244 contains the characters that need translation. */
1245 int charset_base_code
= c
& ~CHAR_FIELD3_MASK
;
1246 if (charset_base
== -1)
1247 charset_base
= charset_base_code
;
1248 else if (charset_base
!= charset_base_code
)
1249 /* If two different rows appear, needing translation,
1250 then we cannot use boyer_moore search. */
1254 /* Store this character into the translated pattern. */
1255 bcopy (str
, pat
, charlen
);
1257 base_pat
+= in_charlen
;
1258 len_byte
-= in_charlen
;
1263 /* Unibyte buffer. */
1269 /* If we got here and the RE flag is set, it's because we're
1270 dealing with a regexp known to be trivial, so the backslash
1271 just quotes the next character. */
1272 if (RE
&& *base_pat
== '\\')
1278 TRANSLATE (translated
, trt
, c
);
1279 *pat
++ = translated
;
1283 len_byte
= pat
- patbuf
;
1284 len
= raw_pattern_size
;
1285 pat
= base_pat
= patbuf
;
1288 return boyer_moore (n
, pat
, len
, len_byte
, trt
, inverse_trt
,
1289 pos
, pos_byte
, lim
, lim_byte
,
1292 return simple_search (n
, pat
, len
, len_byte
, trt
,
1293 pos
, pos_byte
, lim
, lim_byte
);
1297 /* Do a simple string search N times for the string PAT,
1298 whose length is LEN/LEN_BYTE,
1299 from buffer position POS/POS_BYTE until LIM/LIM_BYTE.
1300 TRT is the translation table.
1302 Return the character position where the match is found.
1303 Otherwise, if M matches remained to be found, return -M.
1305 This kind of search works regardless of what is in PAT and
1306 regardless of what is in TRT. It is used in cases where
1307 boyer_moore cannot work. */
1310 simple_search (n
, pat
, len
, len_byte
, trt
, pos
, pos_byte
, lim
, lim_byte
)
1318 int multibyte
= ! NILP (current_buffer
->enable_multibyte_characters
);
1319 int forward
= n
> 0;
1321 if (lim
> pos
&& multibyte
)
1326 /* Try matching at position POS. */
1328 int this_pos_byte
= pos_byte
;
1330 int this_len_byte
= len_byte
;
1331 unsigned char *p
= pat
;
1332 if (pos
+ len
> lim
)
1335 while (this_len
> 0)
1337 int charlen
, buf_charlen
;
1340 pat_ch
= STRING_CHAR_AND_LENGTH (p
, this_len_byte
, charlen
);
1341 buf_ch
= STRING_CHAR_AND_LENGTH (BYTE_POS_ADDR (this_pos_byte
),
1342 ZV_BYTE
- this_pos_byte
,
1344 TRANSLATE (buf_ch
, trt
, buf_ch
);
1346 if (buf_ch
!= pat_ch
)
1349 this_len_byte
-= charlen
;
1353 this_pos_byte
+= buf_charlen
;
1360 pos_byte
+= len_byte
;
1364 INC_BOTH (pos
, pos_byte
);
1374 /* Try matching at position POS. */
1377 unsigned char *p
= pat
;
1379 if (pos
+ len
> lim
)
1382 while (this_len
> 0)
1385 int buf_ch
= FETCH_BYTE (this_pos
);
1386 TRANSLATE (buf_ch
, trt
, buf_ch
);
1388 if (buf_ch
!= pat_ch
)
1406 /* Backwards search. */
1407 else if (lim
< pos
&& multibyte
)
1412 /* Try matching at position POS. */
1413 int this_pos
= pos
- len
;
1414 int this_pos_byte
= pos_byte
- len_byte
;
1416 int this_len_byte
= len_byte
;
1417 unsigned char *p
= pat
;
1419 if (pos
- len
< lim
)
1422 while (this_len
> 0)
1424 int charlen
, buf_charlen
;
1427 pat_ch
= STRING_CHAR_AND_LENGTH (p
, this_len_byte
, charlen
);
1428 buf_ch
= STRING_CHAR_AND_LENGTH (BYTE_POS_ADDR (this_pos_byte
),
1429 ZV_BYTE
- this_pos_byte
,
1431 TRANSLATE (buf_ch
, trt
, buf_ch
);
1433 if (buf_ch
!= pat_ch
)
1436 this_len_byte
-= charlen
;
1439 this_pos_byte
+= buf_charlen
;
1446 pos_byte
-= len_byte
;
1450 DEC_BOTH (pos
, pos_byte
);
1460 /* Try matching at position POS. */
1461 int this_pos
= pos
- len
;
1463 unsigned char *p
= pat
;
1465 if (pos
- len
< lim
)
1468 while (this_len
> 0)
1471 int buf_ch
= FETCH_BYTE (this_pos
);
1472 TRANSLATE (buf_ch
, trt
, buf_ch
);
1474 if (buf_ch
!= pat_ch
)
1496 set_search_regs ((multibyte
? pos_byte
: pos
) - len_byte
, len_byte
);
1498 set_search_regs (multibyte
? pos_byte
: pos
, len_byte
);
1508 /* Do Boyer-Moore search N times for the string PAT,
1509 whose length is LEN/LEN_BYTE,
1510 from buffer position POS/POS_BYTE until LIM/LIM_BYTE.
1511 DIRECTION says which direction we search in.
1512 TRT and INVERSE_TRT are translation tables.
1514 This kind of search works if all the characters in PAT that have
1515 nontrivial translation are the same aside from the last byte. This
1516 makes it possible to translate just the last byte of a character,
1517 and do so after just a simple test of the context.
1519 If that criterion is not satisfied, do not call this function. */
1522 boyer_moore (n
, base_pat
, len
, len_byte
, trt
, inverse_trt
,
1523 pos
, pos_byte
, lim
, lim_byte
, charset_base
)
1525 unsigned char *base_pat
;
1528 Lisp_Object inverse_trt
;
1533 int direction
= ((n
> 0) ? 1 : -1);
1534 register int dirlen
;
1535 int infinity
, limit
, k
, stride_for_teases
;
1536 register int *BM_tab
;
1538 register unsigned char *cursor
, *p_limit
;
1540 unsigned char *pat
, *pat_end
;
1541 int multibyte
= ! NILP (current_buffer
->enable_multibyte_characters
);
1543 unsigned char simple_translate
[0400];
1544 int translate_prev_byte
;
1545 int translate_anteprev_byte
;
1548 int BM_tab_space
[0400];
1549 BM_tab
= &BM_tab_space
[0];
1551 BM_tab
= (int *) alloca (0400 * sizeof (int));
1553 /* The general approach is that we are going to maintain that we know */
1554 /* the first (closest to the present position, in whatever direction */
1555 /* we're searching) character that could possibly be the last */
1556 /* (furthest from present position) character of a valid match. We */
1557 /* advance the state of our knowledge by looking at that character */
1558 /* and seeing whether it indeed matches the last character of the */
1559 /* pattern. If it does, we take a closer look. If it does not, we */
1560 /* move our pointer (to putative last characters) as far as is */
1561 /* logically possible. This amount of movement, which I call a */
1562 /* stride, will be the length of the pattern if the actual character */
1563 /* appears nowhere in the pattern, otherwise it will be the distance */
1564 /* from the last occurrence of that character to the end of the */
1566 /* As a coding trick, an enormous stride is coded into the table for */
1567 /* characters that match the last character. This allows use of only */
1568 /* a single test, a test for having gone past the end of the */
1569 /* permissible match region, to test for both possible matches (when */
1570 /* the stride goes past the end immediately) and failure to */
1571 /* match (where you get nudged past the end one stride at a time). */
1573 /* Here we make a "mickey mouse" BM table. The stride of the search */
1574 /* is determined only by the last character of the putative match. */
1575 /* If that character does not match, we will stride the proper */
1576 /* distance to propose a match that superimposes it on the last */
1577 /* instance of a character that matches it (per trt), or misses */
1578 /* it entirely if there is none. */
1580 dirlen
= len_byte
* direction
;
1581 infinity
= dirlen
- (lim_byte
+ pos_byte
+ len_byte
+ len_byte
) * direction
;
1583 /* Record position after the end of the pattern. */
1584 pat_end
= base_pat
+ len_byte
;
1585 /* BASE_PAT points to a character that we start scanning from.
1586 It is the first character in a forward search,
1587 the last character in a backward search. */
1589 base_pat
= pat_end
- 1;
1591 BM_tab_base
= BM_tab
;
1593 j
= dirlen
; /* to get it in a register */
1594 /* A character that does not appear in the pattern induces a */
1595 /* stride equal to the pattern length. */
1596 while (BM_tab_base
!= BM_tab
)
1604 /* We use this for translation, instead of TRT itself.
1605 We fill this in to handle the characters that actually
1606 occur in the pattern. Others don't matter anyway! */
1607 bzero (simple_translate
, sizeof simple_translate
);
1608 for (i
= 0; i
< 0400; i
++)
1609 simple_translate
[i
] = i
;
1612 while (i
!= infinity
)
1614 unsigned char *ptr
= base_pat
+ i
;
1622 int this_translated
= 1;
1625 /* Is *PTR the last byte of a character? */
1626 && (pat_end
- ptr
== 1 || CHAR_HEAD_P (ptr
[1])))
1628 unsigned char *charstart
= ptr
;
1629 while (! CHAR_HEAD_P (*charstart
))
1631 untranslated
= STRING_CHAR (charstart
, ptr
- charstart
+ 1);
1632 if (charset_base
== (untranslated
& ~CHAR_FIELD3_MASK
))
1634 TRANSLATE (ch
, trt
, untranslated
);
1635 if (! CHAR_HEAD_P (*ptr
))
1637 translate_prev_byte
= ptr
[-1];
1638 if (! CHAR_HEAD_P (translate_prev_byte
))
1639 translate_anteprev_byte
= ptr
[-2];
1644 this_translated
= 0;
1648 else if (!multibyte
)
1649 TRANSLATE (ch
, trt
, *ptr
);
1653 this_translated
= 0;
1657 j
= ((unsigned char) ch
) | 0200;
1659 j
= (unsigned char) ch
;
1662 stride_for_teases
= BM_tab
[j
];
1664 BM_tab
[j
] = dirlen
- i
;
1665 /* A translation table is accompanied by its inverse -- see */
1666 /* comment following downcase_table for details */
1667 if (this_translated
)
1669 int starting_ch
= ch
;
1673 TRANSLATE (ch
, inverse_trt
, ch
);
1675 j
= ((unsigned char) ch
) | 0200;
1677 j
= (unsigned char) ch
;
1679 /* For all the characters that map into CH,
1680 set up simple_translate to map the last byte
1682 simple_translate
[j
] = starting_j
;
1683 if (ch
== starting_ch
)
1685 BM_tab
[j
] = dirlen
- i
;
1694 stride_for_teases
= BM_tab
[j
];
1695 BM_tab
[j
] = dirlen
- i
;
1697 /* stride_for_teases tells how much to stride if we get a */
1698 /* match on the far character but are subsequently */
1699 /* disappointed, by recording what the stride would have been */
1700 /* for that character if the last character had been */
1703 infinity
= dirlen
- infinity
;
1704 pos_byte
+= dirlen
- ((direction
> 0) ? direction
: 0);
1705 /* loop invariant - POS_BYTE points at where last char (first
1706 char if reverse) of pattern would align in a possible match. */
1710 unsigned char *tail_end_ptr
;
1712 /* It's been reported that some (broken) compiler thinks that
1713 Boolean expressions in an arithmetic context are unsigned.
1714 Using an explicit ?1:0 prevents this. */
1715 if ((lim_byte
- pos_byte
- ((direction
> 0) ? 1 : 0)) * direction
1717 return (n
* (0 - direction
));
1718 /* First we do the part we can by pointers (maybe nothing) */
1721 limit
= pos_byte
- dirlen
+ direction
;
1724 limit
= BUFFER_CEILING_OF (limit
);
1725 /* LIMIT is now the last (not beyond-last!) value POS_BYTE
1726 can take on without hitting edge of buffer or the gap. */
1727 limit
= min (limit
, pos_byte
+ 20000);
1728 limit
= min (limit
, lim_byte
- 1);
1732 limit
= BUFFER_FLOOR_OF (limit
);
1733 /* LIMIT is now the last (not beyond-last!) value POS_BYTE
1734 can take on without hitting edge of buffer or the gap. */
1735 limit
= max (limit
, pos_byte
- 20000);
1736 limit
= max (limit
, lim_byte
);
1738 tail_end
= BUFFER_CEILING_OF (pos_byte
) + 1;
1739 tail_end_ptr
= BYTE_POS_ADDR (tail_end
);
1741 if ((limit
- pos_byte
) * direction
> 20)
1745 p_limit
= BYTE_POS_ADDR (limit
);
1746 p2
= (cursor
= BYTE_POS_ADDR (pos_byte
));
1747 /* In this loop, pos + cursor - p2 is the surrogate for pos */
1748 while (1) /* use one cursor setting as long as i can */
1750 if (direction
> 0) /* worth duplicating */
1752 /* Use signed comparison if appropriate
1753 to make cursor+infinity sure to be > p_limit.
1754 Assuming that the buffer lies in a range of addresses
1755 that are all "positive" (as ints) or all "negative",
1756 either kind of comparison will work as long
1757 as we don't step by infinity. So pick the kind
1758 that works when we do step by infinity. */
1759 if ((EMACS_INT
) (p_limit
+ infinity
) > (EMACS_INT
) p_limit
)
1760 while ((EMACS_INT
) cursor
<= (EMACS_INT
) p_limit
)
1761 cursor
+= BM_tab
[*cursor
];
1763 while ((EMACS_UINT
) cursor
<= (EMACS_UINT
) p_limit
)
1764 cursor
+= BM_tab
[*cursor
];
1768 if ((EMACS_INT
) (p_limit
+ infinity
) < (EMACS_INT
) p_limit
)
1769 while ((EMACS_INT
) cursor
>= (EMACS_INT
) p_limit
)
1770 cursor
+= BM_tab
[*cursor
];
1772 while ((EMACS_UINT
) cursor
>= (EMACS_UINT
) p_limit
)
1773 cursor
+= BM_tab
[*cursor
];
1775 /* If you are here, cursor is beyond the end of the searched region. */
1776 /* This can happen if you match on the far character of the pattern, */
1777 /* because the "stride" of that character is infinity, a number able */
1778 /* to throw you well beyond the end of the search. It can also */
1779 /* happen if you fail to match within the permitted region and would */
1780 /* otherwise try a character beyond that region */
1781 if ((cursor
- p_limit
) * direction
<= len_byte
)
1782 break; /* a small overrun is genuine */
1783 cursor
-= infinity
; /* large overrun = hit */
1784 i
= dirlen
- direction
;
1787 while ((i
-= direction
) + direction
!= 0)
1790 cursor
-= direction
;
1791 /* Translate only the last byte of a character. */
1793 || ((cursor
== tail_end_ptr
1794 || CHAR_HEAD_P (cursor
[1]))
1795 && (CHAR_HEAD_P (cursor
[0])
1796 || (translate_prev_byte
== cursor
[-1]
1797 && (CHAR_HEAD_P (translate_prev_byte
)
1798 || translate_anteprev_byte
== cursor
[-2])))))
1799 ch
= simple_translate
[*cursor
];
1808 while ((i
-= direction
) + direction
!= 0)
1810 cursor
-= direction
;
1811 if (pat
[i
] != *cursor
)
1815 cursor
+= dirlen
- i
- direction
; /* fix cursor */
1816 if (i
+ direction
== 0)
1820 cursor
-= direction
;
1822 position
= pos_byte
+ cursor
- p2
+ ((direction
> 0)
1823 ? 1 - len_byte
: 0);
1824 set_search_regs (position
, len_byte
);
1826 if ((n
-= direction
) != 0)
1827 cursor
+= dirlen
; /* to resume search */
1829 return ((direction
> 0)
1830 ? search_regs
.end
[0] : search_regs
.start
[0]);
1833 cursor
+= stride_for_teases
; /* <sigh> we lose - */
1835 pos_byte
+= cursor
- p2
;
1838 /* Now we'll pick up a clump that has to be done the hard */
1839 /* way because it covers a discontinuity */
1841 limit
= ((direction
> 0)
1842 ? BUFFER_CEILING_OF (pos_byte
- dirlen
+ 1)
1843 : BUFFER_FLOOR_OF (pos_byte
- dirlen
- 1));
1844 limit
= ((direction
> 0)
1845 ? min (limit
+ len_byte
, lim_byte
- 1)
1846 : max (limit
- len_byte
, lim_byte
));
1847 /* LIMIT is now the last value POS_BYTE can have
1848 and still be valid for a possible match. */
1851 /* This loop can be coded for space rather than */
1852 /* speed because it will usually run only once. */
1853 /* (the reach is at most len + 21, and typically */
1854 /* does not exceed len) */
1855 while ((limit
- pos_byte
) * direction
>= 0)
1856 pos_byte
+= BM_tab
[FETCH_BYTE (pos_byte
)];
1857 /* now run the same tests to distinguish going off the */
1858 /* end, a match or a phony match. */
1859 if ((pos_byte
- limit
) * direction
<= len_byte
)
1860 break; /* ran off the end */
1861 /* Found what might be a match.
1862 Set POS_BYTE back to last (first if reverse) pos. */
1863 pos_byte
-= infinity
;
1864 i
= dirlen
- direction
;
1865 while ((i
-= direction
) + direction
!= 0)
1869 pos_byte
-= direction
;
1870 ptr
= BYTE_POS_ADDR (pos_byte
);
1871 /* Translate only the last byte of a character. */
1873 || ((ptr
== tail_end_ptr
1874 || CHAR_HEAD_P (ptr
[1]))
1875 && (CHAR_HEAD_P (ptr
[0])
1876 || (translate_prev_byte
== ptr
[-1]
1877 && (CHAR_HEAD_P (translate_prev_byte
)
1878 || translate_anteprev_byte
== ptr
[-2])))))
1879 ch
= simple_translate
[*ptr
];
1885 /* Above loop has moved POS_BYTE part or all the way
1886 back to the first pos (last pos if reverse).
1887 Set it once again at the last (first if reverse) char. */
1888 pos_byte
+= dirlen
- i
- direction
;
1889 if (i
+ direction
== 0)
1892 pos_byte
-= direction
;
1894 position
= pos_byte
+ ((direction
> 0) ? 1 - len_byte
: 0);
1896 set_search_regs (position
, len_byte
);
1898 if ((n
-= direction
) != 0)
1899 pos_byte
+= dirlen
; /* to resume search */
1901 return ((direction
> 0)
1902 ? search_regs
.end
[0] : search_regs
.start
[0]);
1905 pos_byte
+= stride_for_teases
;
1908 /* We have done one clump. Can we continue? */
1909 if ((lim_byte
- pos_byte
) * direction
< 0)
1910 return ((0 - n
) * direction
);
1912 return BYTE_TO_CHAR (pos_byte
);
1915 /* Record beginning BEG_BYTE and end BEG_BYTE + NBYTES
1916 for the overall match just found in the current buffer.
1917 Also clear out the match data for registers 1 and up. */
1920 set_search_regs (beg_byte
, nbytes
)
1921 int beg_byte
, nbytes
;
1925 /* Make sure we have registers in which to store
1926 the match position. */
1927 if (search_regs
.num_regs
== 0)
1929 search_regs
.start
= (regoff_t
*) xmalloc (2 * sizeof (regoff_t
));
1930 search_regs
.end
= (regoff_t
*) xmalloc (2 * sizeof (regoff_t
));
1931 search_regs
.num_regs
= 2;
1934 /* Clear out the other registers. */
1935 for (i
= 1; i
< search_regs
.num_regs
; i
++)
1937 search_regs
.start
[i
] = -1;
1938 search_regs
.end
[i
] = -1;
1941 search_regs
.start
[0] = BYTE_TO_CHAR (beg_byte
);
1942 search_regs
.end
[0] = BYTE_TO_CHAR (beg_byte
+ nbytes
);
1943 XSETBUFFER (last_thing_searched
, current_buffer
);
1946 /* Given a string of words separated by word delimiters,
1947 compute a regexp that matches those exact words
1948 separated by arbitrary punctuation. */
1954 register unsigned char *p
, *o
;
1955 register int i
, i_byte
, len
, punct_count
= 0, word_count
= 0;
1960 CHECK_STRING (string
, 0);
1961 p
= XSTRING (string
)->data
;
1962 len
= XSTRING (string
)->size
;
1964 for (i
= 0, i_byte
= 0; i
< len
; )
1968 if (STRING_MULTIBYTE (string
))
1969 FETCH_STRING_CHAR_ADVANCE (c
, string
, i
, i_byte
);
1971 c
= XSTRING (string
)->data
[i
++];
1973 if (SYNTAX (c
) != Sword
)
1976 if (i
> 0 && SYNTAX (prev_c
) == Sword
)
1983 if (SYNTAX (prev_c
) == Sword
)
1986 return build_string ("");
1988 adjust
= - punct_count
+ 5 * (word_count
- 1) + 4;
1989 if (STRING_MULTIBYTE (string
))
1990 val
= make_uninit_multibyte_string (len
+ adjust
,
1991 STRING_BYTES (XSTRING (string
))
1994 val
= make_uninit_string (len
+ adjust
);
1996 o
= XSTRING (val
)->data
;
2001 for (i
= 0, i_byte
= 0; i
< len
; )
2004 int i_byte_orig
= i_byte
;
2006 if (STRING_MULTIBYTE (string
))
2007 FETCH_STRING_CHAR_ADVANCE (c
, string
, i
, i_byte
);
2010 c
= XSTRING (string
)->data
[i
++];
2014 if (SYNTAX (c
) == Sword
)
2016 bcopy (&XSTRING (string
)->data
[i_byte_orig
], o
,
2017 i_byte
- i_byte_orig
);
2018 o
+= i_byte
- i_byte_orig
;
2020 else if (i
> 0 && SYNTAX (prev_c
) == Sword
&& --word_count
)
2038 DEFUN ("search-backward", Fsearch_backward
, Ssearch_backward
, 1, 4,
2039 "MSearch backward: ",
2040 "Search backward from point for STRING.\n\
2041 Set point to the beginning of the occurrence found, and return point.\n\
2042 An optional second argument bounds the search; it is a buffer position.\n\
2043 The match found must not extend before that position.\n\
2044 Optional third argument, if t, means if fail just return nil (no error).\n\
2045 If not nil and not t, position at limit of search and return nil.\n\
2046 Optional fourth argument is repeat count--search for successive occurrences.\n\
2047 See also the functions `match-beginning', `match-end' and `replace-match'.")
2048 (string
, bound
, noerror
, count
)
2049 Lisp_Object string
, bound
, noerror
, count
;
2051 return search_command (string
, bound
, noerror
, count
, -1, 0, 0);
2054 DEFUN ("search-forward", Fsearch_forward
, Ssearch_forward
, 1, 4, "MSearch: ",
2055 "Search forward from point for STRING.\n\
2056 Set point to the end of the occurrence found, and return point.\n\
2057 An optional second argument bounds the search; it is a buffer position.\n\
2058 The match found must not extend after that position. nil is equivalent\n\
2060 Optional third argument, if t, means if fail just return nil (no error).\n\
2061 If not nil and not t, move to limit of search and return nil.\n\
2062 Optional fourth argument is repeat count--search for successive occurrences.\n\
2063 See also the functions `match-beginning', `match-end' and `replace-match'.")
2064 (string
, bound
, noerror
, count
)
2065 Lisp_Object string
, bound
, noerror
, count
;
2067 return search_command (string
, bound
, noerror
, count
, 1, 0, 0);
2070 DEFUN ("word-search-backward", Fword_search_backward
, Sword_search_backward
, 1, 4,
2071 "sWord search backward: ",
2072 "Search backward from point for STRING, ignoring differences in punctuation.\n\
2073 Set point to the beginning of the occurrence found, and return point.\n\
2074 An optional second argument bounds the search; it is a buffer position.\n\
2075 The match found must not extend before that position.\n\
2076 Optional third argument, if t, means if fail just return nil (no error).\n\
2077 If not nil and not t, move to limit of search and return nil.\n\
2078 Optional fourth argument is repeat count--search for successive occurrences.")
2079 (string
, bound
, noerror
, count
)
2080 Lisp_Object string
, bound
, noerror
, count
;
2082 return search_command (wordify (string
), bound
, noerror
, count
, -1, 1, 0);
2085 DEFUN ("word-search-forward", Fword_search_forward
, Sword_search_forward
, 1, 4,
2087 "Search forward from point for STRING, ignoring differences in punctuation.\n\
2088 Set point to the end of the occurrence found, and return point.\n\
2089 An optional second argument bounds the search; it is a buffer position.\n\
2090 The match found must not extend after that position.\n\
2091 Optional third argument, if t, means if fail just return nil (no error).\n\
2092 If not nil and not t, move to limit of search and return nil.\n\
2093 Optional fourth argument is repeat count--search for successive occurrences.")
2094 (string
, bound
, noerror
, count
)
2095 Lisp_Object string
, bound
, noerror
, count
;
2097 return search_command (wordify (string
), bound
, noerror
, count
, 1, 1, 0);
2100 DEFUN ("re-search-backward", Fre_search_backward
, Sre_search_backward
, 1, 4,
2101 "sRE search backward: ",
2102 "Search backward from point for match for regular expression REGEXP.\n\
2103 Set point to the beginning of the match, and return point.\n\
2104 The match found is the one starting last in the buffer\n\
2105 and yet ending before the origin of the search.\n\
2106 An optional second argument bounds the search; it is a buffer position.\n\
2107 The match found must start at or after that position.\n\
2108 Optional third argument, if t, means if fail just return nil (no error).\n\
2109 If not nil and not t, move to limit of search and return nil.\n\
2110 Optional fourth argument is repeat count--search for successive occurrences.\n\
2111 See also the functions `match-beginning', `match-end' and `replace-match'.")
2112 (regexp
, bound
, noerror
, count
)
2113 Lisp_Object regexp
, bound
, noerror
, count
;
2115 return search_command (regexp
, bound
, noerror
, count
, -1, 1, 0);
2118 DEFUN ("re-search-forward", Fre_search_forward
, Sre_search_forward
, 1, 4,
2120 "Search forward from point for regular expression REGEXP.\n\
2121 Set point to the end of the occurrence found, and return point.\n\
2122 An optional second argument bounds the search; it is a buffer position.\n\
2123 The match found must not extend after that position.\n\
2124 Optional third argument, if t, means if fail just return nil (no error).\n\
2125 If not nil and not t, move to limit of search and return nil.\n\
2126 Optional fourth argument is repeat count--search for successive occurrences.\n\
2127 See also the functions `match-beginning', `match-end' and `replace-match'.")
2128 (regexp
, bound
, noerror
, count
)
2129 Lisp_Object regexp
, bound
, noerror
, count
;
2131 return search_command (regexp
, bound
, noerror
, count
, 1, 1, 0);
2134 DEFUN ("posix-search-backward", Fposix_search_backward
, Sposix_search_backward
, 1, 4,
2135 "sPosix search backward: ",
2136 "Search backward from point for match for regular expression REGEXP.\n\
2137 Find the longest match in accord with Posix regular expression rules.\n\
2138 Set point to the beginning of the match, and return point.\n\
2139 The match found is the one starting last in the buffer\n\
2140 and yet ending before the origin of the search.\n\
2141 An optional second argument bounds the search; it is a buffer position.\n\
2142 The match found must start at or after that position.\n\
2143 Optional third argument, if t, means if fail just return nil (no error).\n\
2144 If not nil and not t, move to limit of search and return nil.\n\
2145 Optional fourth argument is repeat count--search for successive occurrences.\n\
2146 See also the functions `match-beginning', `match-end' and `replace-match'.")
2147 (regexp
, bound
, noerror
, count
)
2148 Lisp_Object regexp
, bound
, noerror
, count
;
2150 return search_command (regexp
, bound
, noerror
, count
, -1, 1, 1);
2153 DEFUN ("posix-search-forward", Fposix_search_forward
, Sposix_search_forward
, 1, 4,
2155 "Search forward from point for regular expression REGEXP.\n\
2156 Find the longest match in accord with Posix regular expression rules.\n\
2157 Set point to the end of the occurrence found, and return point.\n\
2158 An optional second argument bounds the search; it is a buffer position.\n\
2159 The match found must not extend after that position.\n\
2160 Optional third argument, if t, means if fail just return nil (no error).\n\
2161 If not nil and not t, move to limit of search and return nil.\n\
2162 Optional fourth argument is repeat count--search for successive occurrences.\n\
2163 See also the functions `match-beginning', `match-end' and `replace-match'.")
2164 (regexp
, bound
, noerror
, count
)
2165 Lisp_Object regexp
, bound
, noerror
, count
;
2167 return search_command (regexp
, bound
, noerror
, count
, 1, 1, 1);
2170 DEFUN ("replace-match", Freplace_match
, Sreplace_match
, 1, 5, 0,
2171 "Replace text matched by last search with NEWTEXT.\n\
2172 If second arg FIXEDCASE is non-nil, do not alter case of replacement text.\n\
2173 Otherwise maybe capitalize the whole text, or maybe just word initials,\n\
2174 based on the replaced text.\n\
2175 If the replaced text has only capital letters\n\
2176 and has at least one multiletter word, convert NEWTEXT to all caps.\n\
2177 If the replaced text has at least one word starting with a capital letter,\n\
2178 then capitalize each word in NEWTEXT.\n\n\
2179 If third arg LITERAL is non-nil, insert NEWTEXT literally.\n\
2180 Otherwise treat `\\' as special:\n\
2181 `\\&' in NEWTEXT means substitute original matched text.\n\
2182 `\\N' means substitute what matched the Nth `\\(...\\)'.\n\
2183 If Nth parens didn't match, substitute nothing.\n\
2184 `\\\\' means insert one `\\'.\n\
2185 FIXEDCASE and LITERAL are optional arguments.\n\
2186 Leaves point at end of replacement text.\n\
2188 The optional fourth argument STRING can be a string to modify.\n\
2189 In that case, this function creates and returns a new string\n\
2190 which is made by replacing the part of STRING that was matched.\n\
2192 The optional fifth argument SUBEXP specifies a subexpression of the match.\n\
2193 It says to replace just that subexpression instead of the whole match.\n\
2194 This is useful only after a regular expression search or match\n\
2195 since only regular expressions have distinguished subexpressions.")
2196 (newtext
, fixedcase
, literal
, string
, subexp
)
2197 Lisp_Object newtext
, fixedcase
, literal
, string
, subexp
;
2199 enum { nochange
, all_caps
, cap_initial
} case_action
;
2200 register int pos
, pos_byte
;
2201 int some_multiletter_word
;
2204 int some_nonuppercase_initial
;
2205 register int c
, prevc
;
2208 int opoint
, newpoint
;
2210 CHECK_STRING (newtext
, 0);
2212 if (! NILP (string
))
2213 CHECK_STRING (string
, 4);
2215 case_action
= nochange
; /* We tried an initialization */
2216 /* but some C compilers blew it */
2218 if (search_regs
.num_regs
<= 0)
2219 error ("replace-match called before any match found");
2225 CHECK_NUMBER (subexp
, 3);
2226 sub
= XINT (subexp
);
2227 if (sub
< 0 || sub
>= search_regs
.num_regs
)
2228 args_out_of_range (subexp
, make_number (search_regs
.num_regs
));
2233 if (search_regs
.start
[sub
] < BEGV
2234 || search_regs
.start
[sub
] > search_regs
.end
[sub
]
2235 || search_regs
.end
[sub
] > ZV
)
2236 args_out_of_range (make_number (search_regs
.start
[sub
]),
2237 make_number (search_regs
.end
[sub
]));
2241 if (search_regs
.start
[sub
] < 0
2242 || search_regs
.start
[sub
] > search_regs
.end
[sub
]
2243 || search_regs
.end
[sub
] > XSTRING (string
)->size
)
2244 args_out_of_range (make_number (search_regs
.start
[sub
]),
2245 make_number (search_regs
.end
[sub
]));
2248 if (NILP (fixedcase
))
2250 /* Decide how to casify by examining the matched text. */
2253 pos
= search_regs
.start
[sub
];
2254 last
= search_regs
.end
[sub
];
2257 pos_byte
= CHAR_TO_BYTE (pos
);
2259 pos_byte
= string_char_to_byte (string
, pos
);
2262 case_action
= all_caps
;
2264 /* some_multiletter_word is set nonzero if any original word
2265 is more than one letter long. */
2266 some_multiletter_word
= 0;
2268 some_nonuppercase_initial
= 0;
2275 c
= FETCH_CHAR (pos_byte
);
2276 INC_BOTH (pos
, pos_byte
);
2279 FETCH_STRING_CHAR_ADVANCE (c
, string
, pos
, pos_byte
);
2283 /* Cannot be all caps if any original char is lower case */
2286 if (SYNTAX (prevc
) != Sword
)
2287 some_nonuppercase_initial
= 1;
2289 some_multiletter_word
= 1;
2291 else if (!NOCASEP (c
))
2294 if (SYNTAX (prevc
) != Sword
)
2297 some_multiletter_word
= 1;
2301 /* If the initial is a caseless word constituent,
2302 treat that like a lowercase initial. */
2303 if (SYNTAX (prevc
) != Sword
)
2304 some_nonuppercase_initial
= 1;
2310 /* Convert to all caps if the old text is all caps
2311 and has at least one multiletter word. */
2312 if (! some_lowercase
&& some_multiletter_word
)
2313 case_action
= all_caps
;
2314 /* Capitalize each word, if the old text has all capitalized words. */
2315 else if (!some_nonuppercase_initial
&& some_multiletter_word
)
2316 case_action
= cap_initial
;
2317 else if (!some_nonuppercase_initial
&& some_uppercase
)
2318 /* Should x -> yz, operating on X, give Yz or YZ?
2319 We'll assume the latter. */
2320 case_action
= all_caps
;
2322 case_action
= nochange
;
2325 /* Do replacement in a string. */
2328 Lisp_Object before
, after
;
2330 before
= Fsubstring (string
, make_number (0),
2331 make_number (search_regs
.start
[sub
]));
2332 after
= Fsubstring (string
, make_number (search_regs
.end
[sub
]), Qnil
);
2334 /* Substitute parts of the match into NEWTEXT
2339 int lastpos_byte
= 0;
2340 /* We build up the substituted string in ACCUM. */
2343 int length
= STRING_BYTES (XSTRING (newtext
));
2347 for (pos_byte
= 0, pos
= 0; pos_byte
< length
;)
2351 int delbackslash
= 0;
2353 FETCH_STRING_CHAR_ADVANCE (c
, newtext
, pos
, pos_byte
);
2357 FETCH_STRING_CHAR_ADVANCE (c
, newtext
, pos
, pos_byte
);
2360 substart
= search_regs
.start
[sub
];
2361 subend
= search_regs
.end
[sub
];
2363 else if (c
>= '1' && c
<= '9' && c
<= search_regs
.num_regs
+ '0')
2365 if (search_regs
.start
[c
- '0'] >= 0)
2367 substart
= search_regs
.start
[c
- '0'];
2368 subend
= search_regs
.end
[c
- '0'];
2374 error ("Invalid use of `\\' in replacement text");
2378 if (pos
- 2 != lastpos
)
2379 middle
= substring_both (newtext
, lastpos
,
2381 pos
- 2, pos_byte
- 2);
2384 accum
= concat3 (accum
, middle
,
2386 make_number (substart
),
2387 make_number (subend
)));
2389 lastpos_byte
= pos_byte
;
2391 else if (delbackslash
)
2393 middle
= substring_both (newtext
, lastpos
,
2395 pos
- 1, pos_byte
- 1);
2397 accum
= concat2 (accum
, middle
);
2399 lastpos_byte
= pos_byte
;
2404 middle
= substring_both (newtext
, lastpos
,
2410 newtext
= concat2 (accum
, middle
);
2413 /* Do case substitution in NEWTEXT if desired. */
2414 if (case_action
== all_caps
)
2415 newtext
= Fupcase (newtext
);
2416 else if (case_action
== cap_initial
)
2417 newtext
= Fupcase_initials (newtext
);
2419 return concat3 (before
, newtext
, after
);
2422 /* Record point, the move (quietly) to the start of the match. */
2423 if (PT
>= search_regs
.end
[sub
])
2425 else if (PT
> search_regs
.start
[sub
])
2426 opoint
= search_regs
.end
[sub
] - ZV
;
2430 TEMP_SET_PT (search_regs
.start
[sub
]);
2432 /* We insert the replacement text before the old text, and then
2433 delete the original text. This means that markers at the
2434 beginning or end of the original will float to the corresponding
2435 position in the replacement. */
2436 if (!NILP (literal
))
2437 Finsert_and_inherit (1, &newtext
);
2440 int length
= STRING_BYTES (XSTRING (newtext
));
2441 unsigned char *substed
;
2442 int substed_alloc_size
, substed_len
;
2444 substed_alloc_size
= length
* 2 + 100;
2445 substed
= (unsigned char *) xmalloc (substed_alloc_size
+ 1);
2448 /* Go thru NEWTEXT, producing the actual text to insert in SUBSTED. */
2450 for (pos_byte
= 0, pos
= 0; pos_byte
< length
;)
2452 unsigned char str
[MAX_MULTIBYTE_LENGTH
];
2453 unsigned char *add_stuff
;
2457 FETCH_STRING_CHAR_ADVANCE (c
, newtext
, pos
, pos_byte
);
2459 /* Either set ADD_STUFF and ADD_LEN to the text to put in SUBSTED,
2460 or set IDX to a match index, which means put that part
2461 of the buffer text into SUBSTED. */
2465 FETCH_STRING_CHAR_ADVANCE (c
, newtext
, pos
, pos_byte
);
2468 else if (c
>= '1' && c
<= '9' && c
<= search_regs
.num_regs
+ '0')
2470 if (search_regs
.start
[c
- '0'] >= 1)
2474 add_len
= 1, add_stuff
= "\\";
2476 error ("Invalid use of `\\' in replacement text");
2480 add_len
= CHAR_STRING (c
, str
);
2484 /* If we want to copy part of a previous match,
2485 set up ADD_STUFF and ADD_LEN to point to it. */
2488 int begbyte
= CHAR_TO_BYTE (search_regs
.start
[idx
]);
2489 add_len
= CHAR_TO_BYTE (search_regs
.end
[idx
]) - begbyte
;
2490 if (search_regs
.start
[idx
] < GPT
&& GPT
< search_regs
.end
[idx
])
2491 move_gap (search_regs
.start
[idx
]);
2492 add_stuff
= BYTE_POS_ADDR (begbyte
);
2495 /* Now the stuff we want to add to SUBSTED
2496 is invariably ADD_LEN bytes starting at ADD_STUFF. */
2498 /* Make sure SUBSTED is big enough. */
2499 if (substed_len
+ add_len
>= substed_alloc_size
)
2501 substed_alloc_size
= substed_len
+ add_len
+ 500;
2502 substed
= (unsigned char *) xrealloc (substed
,
2503 substed_alloc_size
+ 1);
2506 /* Now add to the end of SUBSTED. */
2507 bcopy (add_stuff
, substed
+ substed_len
, add_len
);
2508 substed_len
+= add_len
;
2511 /* Now insert what we accumulated. */
2512 insert_and_inherit (substed
, substed_len
);
2517 inslen
= PT
- (search_regs
.start
[sub
]);
2518 del_range (search_regs
.start
[sub
] + inslen
, search_regs
.end
[sub
] + inslen
);
2520 if (case_action
== all_caps
)
2521 Fupcase_region (make_number (PT
- inslen
), make_number (PT
));
2522 else if (case_action
== cap_initial
)
2523 Fupcase_initials_region (make_number (PT
- inslen
), make_number (PT
));
2527 /* Put point back where it was in the text. */
2529 TEMP_SET_PT (opoint
+ ZV
);
2531 TEMP_SET_PT (opoint
);
2533 /* Now move point "officially" to the start of the inserted replacement. */
2534 move_if_not_intangible (newpoint
);
2540 match_limit (num
, beginningp
)
2546 CHECK_NUMBER (num
, 0);
2548 if (n
< 0 || n
>= search_regs
.num_regs
)
2549 args_out_of_range (num
, make_number (search_regs
.num_regs
));
2550 if (search_regs
.num_regs
<= 0
2551 || search_regs
.start
[n
] < 0)
2553 return (make_number ((beginningp
) ? search_regs
.start
[n
]
2554 : search_regs
.end
[n
]));
2557 DEFUN ("match-beginning", Fmatch_beginning
, Smatch_beginning
, 1, 1, 0,
2558 "Return position of start of text matched by last search.\n\
2559 SUBEXP, a number, specifies which parenthesized expression in the last\n\
2561 Value is nil if SUBEXPth pair didn't match, or there were less than\n\
2563 Zero means the entire text matched by the whole regexp or whole string.")
2567 return match_limit (subexp
, 1);
2570 DEFUN ("match-end", Fmatch_end
, Smatch_end
, 1, 1, 0,
2571 "Return position of end of text matched by last search.\n\
2572 SUBEXP, a number, specifies which parenthesized expression in the last\n\
2574 Value is nil if SUBEXPth pair didn't match, or there were less than\n\
2576 Zero means the entire text matched by the whole regexp or whole string.")
2580 return match_limit (subexp
, 0);
2583 DEFUN ("match-data", Fmatch_data
, Smatch_data
, 0, 2, 0,
2584 "Return a list containing all info on what the last search matched.\n\
2585 Element 2N is `(match-beginning N)'; element 2N + 1 is `(match-end N)'.\n\
2586 All the elements are markers or nil (nil if the Nth pair didn't match)\n\
2587 if the last match was on a buffer; integers or nil if a string was matched.\n\
2588 Use `store-match-data' to reinstate the data in this list.\n\
2590 If INTEGERS (the optional first argument) is non-nil, always use integers\n\
2591 \(rather than markers) to represent buffer positions.\n\
2592 If REUSE is a list, reuse it as part of the value. If REUSE is long enough\n\
2593 to hold all the values, and if INTEGERS is non-nil, no consing is done.")
2595 Lisp_Object integers
, reuse
;
2597 Lisp_Object tail
, prev
;
2601 if (NILP (last_thing_searched
))
2604 data
= (Lisp_Object
*) alloca ((2 * search_regs
.num_regs
)
2605 * sizeof (Lisp_Object
));
2608 for (i
= 0; i
< search_regs
.num_regs
; i
++)
2610 int start
= search_regs
.start
[i
];
2613 if (EQ (last_thing_searched
, Qt
)
2614 || ! NILP (integers
))
2616 XSETFASTINT (data
[2 * i
], start
);
2617 XSETFASTINT (data
[2 * i
+ 1], search_regs
.end
[i
]);
2619 else if (BUFFERP (last_thing_searched
))
2621 data
[2 * i
] = Fmake_marker ();
2622 Fset_marker (data
[2 * i
],
2623 make_number (start
),
2624 last_thing_searched
);
2625 data
[2 * i
+ 1] = Fmake_marker ();
2626 Fset_marker (data
[2 * i
+ 1],
2627 make_number (search_regs
.end
[i
]),
2628 last_thing_searched
);
2631 /* last_thing_searched must always be Qt, a buffer, or Qnil. */
2637 data
[2 * i
] = data
[2 * i
+ 1] = Qnil
;
2640 /* If REUSE is not usable, cons up the values and return them. */
2641 if (! CONSP (reuse
))
2642 return Flist (2 * len
+ 2, data
);
2644 /* If REUSE is a list, store as many value elements as will fit
2645 into the elements of REUSE. */
2646 for (i
= 0, tail
= reuse
; CONSP (tail
);
2647 i
++, tail
= XCDR (tail
))
2649 if (i
< 2 * len
+ 2)
2650 XCAR (tail
) = data
[i
];
2656 /* If we couldn't fit all value elements into REUSE,
2657 cons up the rest of them and add them to the end of REUSE. */
2658 if (i
< 2 * len
+ 2)
2659 XCDR (prev
) = Flist (2 * len
+ 2 - i
, data
+ i
);
2665 DEFUN ("set-match-data", Fset_match_data
, Sset_match_data
, 1, 1, 0,
2666 "Set internal data on last search match from elements of LIST.\n\
2667 LIST should have been created by calling `match-data' previously.")
2669 register Lisp_Object list
;
2672 register Lisp_Object marker
;
2674 if (running_asynch_code
)
2675 save_search_regs ();
2677 if (!CONSP (list
) && !NILP (list
))
2678 list
= wrong_type_argument (Qconsp
, list
);
2680 /* Unless we find a marker with a buffer in LIST, assume that this
2681 match data came from a string. */
2682 last_thing_searched
= Qt
;
2684 /* Allocate registers if they don't already exist. */
2686 int length
= XFASTINT (Flength (list
)) / 2;
2688 if (length
> search_regs
.num_regs
)
2690 if (search_regs
.num_regs
== 0)
2693 = (regoff_t
*) xmalloc (length
* sizeof (regoff_t
));
2695 = (regoff_t
*) xmalloc (length
* sizeof (regoff_t
));
2700 = (regoff_t
*) xrealloc (search_regs
.start
,
2701 length
* sizeof (regoff_t
));
2703 = (regoff_t
*) xrealloc (search_regs
.end
,
2704 length
* sizeof (regoff_t
));
2707 search_regs
.num_regs
= length
;
2711 for (i
= 0; i
< search_regs
.num_regs
; i
++)
2713 marker
= Fcar (list
);
2716 search_regs
.start
[i
] = -1;
2721 if (MARKERP (marker
))
2723 if (XMARKER (marker
)->buffer
== 0)
2724 XSETFASTINT (marker
, 0);
2726 XSETBUFFER (last_thing_searched
, XMARKER (marker
)->buffer
);
2729 CHECK_NUMBER_COERCE_MARKER (marker
, 0);
2730 search_regs
.start
[i
] = XINT (marker
);
2733 marker
= Fcar (list
);
2734 if (MARKERP (marker
) && XMARKER (marker
)->buffer
== 0)
2735 XSETFASTINT (marker
, 0);
2737 CHECK_NUMBER_COERCE_MARKER (marker
, 0);
2738 search_regs
.end
[i
] = XINT (marker
);
2746 /* If non-zero the match data have been saved in saved_search_regs
2747 during the execution of a sentinel or filter. */
2748 static int search_regs_saved
;
2749 static struct re_registers saved_search_regs
;
2751 /* Called from Flooking_at, Fstring_match, search_buffer, Fstore_match_data
2752 if asynchronous code (filter or sentinel) is running. */
2756 if (!search_regs_saved
)
2758 saved_search_regs
.num_regs
= search_regs
.num_regs
;
2759 saved_search_regs
.start
= search_regs
.start
;
2760 saved_search_regs
.end
= search_regs
.end
;
2761 search_regs
.num_regs
= 0;
2762 search_regs
.start
= 0;
2763 search_regs
.end
= 0;
2765 search_regs_saved
= 1;
2769 /* Called upon exit from filters and sentinels. */
2771 restore_match_data ()
2773 if (search_regs_saved
)
2775 if (search_regs
.num_regs
> 0)
2777 xfree (search_regs
.start
);
2778 xfree (search_regs
.end
);
2780 search_regs
.num_regs
= saved_search_regs
.num_regs
;
2781 search_regs
.start
= saved_search_regs
.start
;
2782 search_regs
.end
= saved_search_regs
.end
;
2784 search_regs_saved
= 0;
2788 /* Quote a string to inactivate reg-expr chars */
2790 DEFUN ("regexp-quote", Fregexp_quote
, Sregexp_quote
, 1, 1, 0,
2791 "Return a regexp string which matches exactly STRING and nothing else.")
2795 register unsigned char *in
, *out
, *end
;
2796 register unsigned char *temp
;
2797 int backslashes_added
= 0;
2799 CHECK_STRING (string
, 0);
2801 temp
= (unsigned char *) alloca (STRING_BYTES (XSTRING (string
)) * 2);
2803 /* Now copy the data into the new string, inserting escapes. */
2805 in
= XSTRING (string
)->data
;
2806 end
= in
+ STRING_BYTES (XSTRING (string
));
2809 for (; in
!= end
; in
++)
2811 if (*in
== '[' || *in
== ']'
2812 || *in
== '*' || *in
== '.' || *in
== '\\'
2813 || *in
== '?' || *in
== '+'
2814 || *in
== '^' || *in
== '$')
2815 *out
++ = '\\', backslashes_added
++;
2819 return make_specified_string (temp
,
2820 XSTRING (string
)->size
+ backslashes_added
,
2822 STRING_MULTIBYTE (string
));
2830 for (i
= 0; i
< REGEXP_CACHE_SIZE
; ++i
)
2832 searchbufs
[i
].buf
.allocated
= 100;
2833 searchbufs
[i
].buf
.buffer
= (unsigned char *) malloc (100);
2834 searchbufs
[i
].buf
.fastmap
= searchbufs
[i
].fastmap
;
2835 searchbufs
[i
].regexp
= Qnil
;
2836 staticpro (&searchbufs
[i
].regexp
);
2837 searchbufs
[i
].next
= (i
== REGEXP_CACHE_SIZE
-1 ? 0 : &searchbufs
[i
+1]);
2839 searchbuf_head
= &searchbufs
[0];
2841 Qsearch_failed
= intern ("search-failed");
2842 staticpro (&Qsearch_failed
);
2843 Qinvalid_regexp
= intern ("invalid-regexp");
2844 staticpro (&Qinvalid_regexp
);
2846 Fput (Qsearch_failed
, Qerror_conditions
,
2847 Fcons (Qsearch_failed
, Fcons (Qerror
, Qnil
)));
2848 Fput (Qsearch_failed
, Qerror_message
,
2849 build_string ("Search failed"));
2851 Fput (Qinvalid_regexp
, Qerror_conditions
,
2852 Fcons (Qinvalid_regexp
, Fcons (Qerror
, Qnil
)));
2853 Fput (Qinvalid_regexp
, Qerror_message
,
2854 build_string ("Invalid regexp"));
2856 last_thing_searched
= Qnil
;
2857 staticpro (&last_thing_searched
);
2859 defsubr (&Slooking_at
);
2860 defsubr (&Sposix_looking_at
);
2861 defsubr (&Sstring_match
);
2862 defsubr (&Sposix_string_match
);
2863 defsubr (&Ssearch_forward
);
2864 defsubr (&Ssearch_backward
);
2865 defsubr (&Sword_search_forward
);
2866 defsubr (&Sword_search_backward
);
2867 defsubr (&Sre_search_forward
);
2868 defsubr (&Sre_search_backward
);
2869 defsubr (&Sposix_search_forward
);
2870 defsubr (&Sposix_search_backward
);
2871 defsubr (&Sreplace_match
);
2872 defsubr (&Smatch_beginning
);
2873 defsubr (&Smatch_end
);
2874 defsubr (&Smatch_data
);
2875 defsubr (&Sset_match_data
);
2876 defsubr (&Sregexp_quote
);