2000-06-05 Michael Kifer <kifer@cs.sunysb.edu>
[emacs.git] / src / search.c
blob246f9cbdf4dd6363449dd9237960c03eb6ce98ec
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)
9 any later version.
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs; see the file COPYING. If not, write to
18 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
22 #include <config.h>
23 #include "lisp.h"
24 #include "syntax.h"
25 #include "category.h"
26 #include "buffer.h"
27 #include "charset.h"
28 #include "region-cache.h"
29 #include "commands.h"
30 #include "blockinput.h"
31 #include "intervals.h"
33 #include <sys/types.h>
34 #include "regex.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. */
43 struct regexp_cache
45 struct regexp_cache *next;
46 Lisp_Object regexp;
47 struct re_pattern_buffer buf;
48 char fastmap[0400];
49 /* Nonzero means regexp was compiled to do full POSIX backtracking. */
50 char posix;
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
63 can be called).
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 ();
94 static void
95 matcher_overflow ()
97 error ("Stack overflow in regexp matcher");
100 /* Compile a regexp and signal a Lisp error if anything goes wrong.
101 PATTERN is the pattern to compile.
102 CP is the place to put the result.
103 TRANSLATE is a translation table for ignoring case, or nil for none.
104 REGP is the structure that says where to store the "register"
105 values that will result from matching this pattern.
106 If it is 0, we should compile the pattern not to record any
107 subexpression bounds.
108 POSIX is nonzero if we want full backtracking (POSIX style)
109 for this pattern. 0 means backtrack only enough to get a valid match.
110 MULTIBYTE is nonzero if we want to handle multibyte characters in
111 PATTERN. 0 means all multibyte characters are recognized just as
112 sequences of binary data. */
114 static void
115 compile_pattern_1 (cp, pattern, translate, regp, posix, multibyte)
116 struct regexp_cache *cp;
117 Lisp_Object pattern;
118 Lisp_Object translate;
119 struct re_registers *regp;
120 int posix;
121 int multibyte;
123 unsigned char *raw_pattern;
124 int raw_pattern_size;
125 char *val;
126 reg_syntax_t old;
128 /* MULTIBYTE says whether the text to be searched is multibyte.
129 We must convert PATTERN to match that, or we will not really
130 find things right. */
132 if (multibyte == STRING_MULTIBYTE (pattern))
134 raw_pattern = (unsigned char *) XSTRING (pattern)->data;
135 raw_pattern_size = STRING_BYTES (XSTRING (pattern));
137 else if (multibyte)
139 raw_pattern_size = count_size_as_multibyte (XSTRING (pattern)->data,
140 XSTRING (pattern)->size);
141 raw_pattern = (unsigned char *) alloca (raw_pattern_size + 1);
142 copy_text (XSTRING (pattern)->data, raw_pattern,
143 XSTRING (pattern)->size, 0, 1);
145 else
147 /* Converting multibyte to single-byte.
149 ??? Perhaps this conversion should be done in a special way
150 by subtracting nonascii-insert-offset from each non-ASCII char,
151 so that only the multibyte chars which really correspond to
152 the chosen single-byte character set can possibly match. */
153 raw_pattern_size = XSTRING (pattern)->size;
154 raw_pattern = (unsigned char *) alloca (raw_pattern_size + 1);
155 copy_text (XSTRING (pattern)->data, raw_pattern,
156 STRING_BYTES (XSTRING (pattern)), 1, 0);
159 cp->regexp = Qnil;
160 cp->buf.translate = (! NILP (translate) ? translate : make_number (0));
161 cp->posix = posix;
162 cp->buf.multibyte = multibyte;
163 BLOCK_INPUT;
164 old = re_set_syntax (RE_SYNTAX_EMACS
165 | (posix ? 0 : RE_NO_POSIX_BACKTRACKING));
166 val = (char *) re_compile_pattern ((char *)raw_pattern,
167 raw_pattern_size, &cp->buf);
168 re_set_syntax (old);
169 UNBLOCK_INPUT;
170 if (val)
171 Fsignal (Qinvalid_regexp, Fcons (build_string (val), Qnil));
173 cp->regexp = Fcopy_sequence (pattern);
176 /* Shrink each compiled regexp buffer in the cache
177 to the size actually used right now.
178 This is called from garbage collection. */
180 void
181 shrink_regexp_cache ()
183 struct regexp_cache *cp, **cpp;
185 for (cp = searchbuf_head; cp != 0; cp = cp->next)
187 cp->buf.allocated = cp->buf.used;
188 cp->buf.buffer
189 = (unsigned char *) realloc (cp->buf.buffer, cp->buf.used);
193 /* Compile a regexp if necessary, but first check to see if there's one in
194 the cache.
195 PATTERN is the pattern to compile.
196 TRANSLATE is a translation table for ignoring case, or nil for none.
197 REGP is the structure that says where to store the "register"
198 values that will result from matching this pattern.
199 If it is 0, we should compile the pattern not to record any
200 subexpression bounds.
201 POSIX is nonzero if we want full backtracking (POSIX style)
202 for this pattern. 0 means backtrack only enough to get a valid match. */
204 struct re_pattern_buffer *
205 compile_pattern (pattern, regp, translate, posix, multibyte)
206 Lisp_Object pattern;
207 struct re_registers *regp;
208 Lisp_Object translate;
209 int posix, multibyte;
211 struct regexp_cache *cp, **cpp;
213 for (cpp = &searchbuf_head; ; cpp = &cp->next)
215 cp = *cpp;
216 /* Entries are initialized to nil, and may be set to nil by
217 compile_pattern_1 if the pattern isn't valid. Don't apply
218 XSTRING in those cases. However, compile_pattern_1 is only
219 applied to the cache entry we pick here to reuse. So nil
220 should never appear before a non-nil entry. */
221 if (NILP (cp->regexp))
222 goto compile_it;
223 if (XSTRING (cp->regexp)->size == XSTRING (pattern)->size
224 && !NILP (Fstring_equal (cp->regexp, pattern))
225 && EQ (cp->buf.translate, (! NILP (translate) ? translate : make_number (0)))
226 && cp->posix == posix
227 && cp->buf.multibyte == multibyte)
228 break;
230 /* If we're at the end of the cache, compile into the nil cell
231 we found, or the last (least recently used) cell with a
232 string value. */
233 if (cp->next == 0)
235 compile_it:
236 compile_pattern_1 (cp, pattern, translate, regp, posix, multibyte);
237 break;
241 /* When we get here, cp (aka *cpp) contains the compiled pattern,
242 either because we found it in the cache or because we just compiled it.
243 Move it to the front of the queue to mark it as most recently used. */
244 *cpp = cp->next;
245 cp->next = searchbuf_head;
246 searchbuf_head = cp;
248 /* Advise the searching functions about the space we have allocated
249 for register data. */
250 if (regp)
251 re_set_registers (&cp->buf, regp, regp->num_regs, regp->start, regp->end);
253 return &cp->buf;
256 /* Error condition used for failing searches */
257 Lisp_Object Qsearch_failed;
259 Lisp_Object
260 signal_failure (arg)
261 Lisp_Object arg;
263 Fsignal (Qsearch_failed, Fcons (arg, Qnil));
264 return Qnil;
267 static Lisp_Object
268 looking_at_1 (string, posix)
269 Lisp_Object string;
270 int posix;
272 Lisp_Object val;
273 unsigned char *p1, *p2;
274 int s1, s2;
275 register int i;
276 struct re_pattern_buffer *bufp;
278 if (running_asynch_code)
279 save_search_regs ();
281 CHECK_STRING (string, 0);
282 bufp = compile_pattern (string, &search_regs,
283 (!NILP (current_buffer->case_fold_search)
284 ? DOWNCASE_TABLE : Qnil),
285 posix,
286 !NILP (current_buffer->enable_multibyte_characters));
288 immediate_quit = 1;
289 QUIT; /* Do a pending quit right away, to avoid paradoxical behavior */
291 /* Get pointers and sizes of the two strings
292 that make up the visible portion of the buffer. */
294 p1 = BEGV_ADDR;
295 s1 = GPT_BYTE - BEGV_BYTE;
296 p2 = GAP_END_ADDR;
297 s2 = ZV_BYTE - GPT_BYTE;
298 if (s1 < 0)
300 p2 = p1;
301 s2 = ZV_BYTE - BEGV_BYTE;
302 s1 = 0;
304 if (s2 < 0)
306 s1 = ZV_BYTE - BEGV_BYTE;
307 s2 = 0;
310 re_match_object = Qnil;
312 i = re_match_2 (bufp, (char *) p1, s1, (char *) p2, s2,
313 PT_BYTE - BEGV_BYTE, &search_regs,
314 ZV_BYTE - BEGV_BYTE);
315 immediate_quit = 0;
317 if (i == -2)
318 matcher_overflow ();
320 val = (0 <= i ? Qt : Qnil);
321 if (i >= 0)
322 for (i = 0; i < search_regs.num_regs; i++)
323 if (search_regs.start[i] >= 0)
325 search_regs.start[i]
326 = BYTE_TO_CHAR (search_regs.start[i] + BEGV_BYTE);
327 search_regs.end[i]
328 = BYTE_TO_CHAR (search_regs.end[i] + BEGV_BYTE);
330 XSETBUFFER (last_thing_searched, current_buffer);
331 return val;
334 DEFUN ("looking-at", Flooking_at, Slooking_at, 1, 1, 0,
335 "Return t if text after point matches regular expression REGEXP.\n\
336 This function modifies the match data that `match-beginning',\n\
337 `match-end' and `match-data' access; save and restore the match\n\
338 data if you want to preserve them.")
339 (regexp)
340 Lisp_Object regexp;
342 return looking_at_1 (regexp, 0);
345 DEFUN ("posix-looking-at", Fposix_looking_at, Sposix_looking_at, 1, 1, 0,
346 "Return t if text after point matches regular expression REGEXP.\n\
347 Find the longest match, in accord with Posix regular expression rules.\n\
348 This function modifies the match data that `match-beginning',\n\
349 `match-end' and `match-data' access; save and restore the match\n\
350 data if you want to preserve them.")
351 (regexp)
352 Lisp_Object regexp;
354 return looking_at_1 (regexp, 1);
357 static Lisp_Object
358 string_match_1 (regexp, string, start, posix)
359 Lisp_Object regexp, string, start;
360 int posix;
362 int val;
363 struct re_pattern_buffer *bufp;
364 int pos, pos_byte;
365 int i;
367 if (running_asynch_code)
368 save_search_regs ();
370 CHECK_STRING (regexp, 0);
371 CHECK_STRING (string, 1);
373 if (NILP (start))
374 pos = 0, pos_byte = 0;
375 else
377 int len = XSTRING (string)->size;
379 CHECK_NUMBER (start, 2);
380 pos = XINT (start);
381 if (pos < 0 && -pos <= len)
382 pos = len + pos;
383 else if (0 > pos || pos > len)
384 args_out_of_range (string, start);
385 pos_byte = string_char_to_byte (string, pos);
388 bufp = compile_pattern (regexp, &search_regs,
389 (!NILP (current_buffer->case_fold_search)
390 ? DOWNCASE_TABLE : Qnil),
391 posix,
392 STRING_MULTIBYTE (string));
393 immediate_quit = 1;
394 re_match_object = string;
396 val = re_search (bufp, (char *) XSTRING (string)->data,
397 STRING_BYTES (XSTRING (string)), pos_byte,
398 STRING_BYTES (XSTRING (string)) - pos_byte,
399 &search_regs);
400 immediate_quit = 0;
401 last_thing_searched = Qt;
402 if (val == -2)
403 matcher_overflow ();
404 if (val < 0) return Qnil;
406 for (i = 0; i < search_regs.num_regs; i++)
407 if (search_regs.start[i] >= 0)
409 search_regs.start[i]
410 = string_byte_to_char (string, search_regs.start[i]);
411 search_regs.end[i]
412 = string_byte_to_char (string, search_regs.end[i]);
415 return make_number (string_byte_to_char (string, val));
418 DEFUN ("string-match", Fstring_match, Sstring_match, 2, 3, 0,
419 "Return index of start of first match for REGEXP in STRING, or nil.\n\
420 Case is ignored if `case-fold-search' is non-nil in the current buffer.\n\
421 If third arg START is non-nil, start search at that index in STRING.\n\
422 For index of first char beyond the match, do (match-end 0).\n\
423 `match-end' and `match-beginning' also give indices of substrings\n\
424 matched by parenthesis constructs in the pattern.")
425 (regexp, string, start)
426 Lisp_Object regexp, string, start;
428 return string_match_1 (regexp, string, start, 0);
431 DEFUN ("posix-string-match", Fposix_string_match, Sposix_string_match, 2, 3, 0,
432 "Return index of start of first match for REGEXP in STRING, or nil.\n\
433 Find the longest match, in accord with Posix regular expression rules.\n\
434 Case is ignored if `case-fold-search' is non-nil in the current buffer.\n\
435 If third arg START is non-nil, start search at that index in STRING.\n\
436 For index of first char beyond the match, do (match-end 0).\n\
437 `match-end' and `match-beginning' also give indices of substrings\n\
438 matched by parenthesis constructs in the pattern.")
439 (regexp, string, start)
440 Lisp_Object regexp, string, start;
442 return string_match_1 (regexp, string, start, 1);
445 /* Match REGEXP against STRING, searching all of STRING,
446 and return the index of the match, or negative on failure.
447 This does not clobber the match data. */
450 fast_string_match (regexp, string)
451 Lisp_Object regexp, string;
453 int val;
454 struct re_pattern_buffer *bufp;
456 bufp = compile_pattern (regexp, 0, Qnil,
457 0, STRING_MULTIBYTE (string));
458 immediate_quit = 1;
459 re_match_object = string;
461 val = re_search (bufp, (char *) XSTRING (string)->data,
462 STRING_BYTES (XSTRING (string)), 0,
463 STRING_BYTES (XSTRING (string)), 0);
464 immediate_quit = 0;
465 return val;
468 /* Match REGEXP against STRING, searching all of STRING ignoring case,
469 and return the index of the match, or negative on failure.
470 This does not clobber the match data.
471 We assume that STRING contains single-byte characters. */
473 extern Lisp_Object Vascii_downcase_table;
476 fast_c_string_match_ignore_case (regexp, string)
477 Lisp_Object regexp;
478 char *string;
480 int val;
481 struct re_pattern_buffer *bufp;
482 int len = strlen (string);
484 regexp = string_make_unibyte (regexp);
485 re_match_object = Qt;
486 bufp = compile_pattern (regexp, 0,
487 Vascii_downcase_table, 0,
489 immediate_quit = 1;
490 val = re_search (bufp, string, len, 0, len, 0);
491 immediate_quit = 0;
492 return val;
495 /* The newline cache: remembering which sections of text have no newlines. */
497 /* If the user has requested newline caching, make sure it's on.
498 Otherwise, make sure it's off.
499 This is our cheezy way of associating an action with the change of
500 state of a buffer-local variable. */
501 static void
502 newline_cache_on_off (buf)
503 struct buffer *buf;
505 if (NILP (buf->cache_long_line_scans))
507 /* It should be off. */
508 if (buf->newline_cache)
510 free_region_cache (buf->newline_cache);
511 buf->newline_cache = 0;
514 else
516 /* It should be on. */
517 if (buf->newline_cache == 0)
518 buf->newline_cache = new_region_cache ();
523 /* Search for COUNT instances of the character TARGET between START and END.
525 If COUNT is positive, search forwards; END must be >= START.
526 If COUNT is negative, search backwards for the -COUNTth instance;
527 END must be <= START.
528 If COUNT is zero, do anything you please; run rogue, for all I care.
530 If END is zero, use BEGV or ZV instead, as appropriate for the
531 direction indicated by COUNT.
533 If we find COUNT instances, set *SHORTAGE to zero, and return the
534 position after the COUNTth match. Note that for reverse motion
535 this is not the same as the usual convention for Emacs motion commands.
537 If we don't find COUNT instances before reaching END, set *SHORTAGE
538 to the number of TARGETs left unfound, and return END.
540 If ALLOW_QUIT is non-zero, set immediate_quit. That's good to do
541 except when inside redisplay. */
544 scan_buffer (target, start, end, count, shortage, allow_quit)
545 register int target;
546 int start, end;
547 int count;
548 int *shortage;
549 int allow_quit;
551 struct region_cache *newline_cache;
552 int direction;
554 if (count > 0)
556 direction = 1;
557 if (! end) end = ZV;
559 else
561 direction = -1;
562 if (! end) end = BEGV;
565 newline_cache_on_off (current_buffer);
566 newline_cache = current_buffer->newline_cache;
568 if (shortage != 0)
569 *shortage = 0;
571 immediate_quit = allow_quit;
573 if (count > 0)
574 while (start != end)
576 /* Our innermost scanning loop is very simple; it doesn't know
577 about gaps, buffer ends, or the newline cache. ceiling is
578 the position of the last character before the next such
579 obstacle --- the last character the dumb search loop should
580 examine. */
581 int ceiling_byte = CHAR_TO_BYTE (end) - 1;
582 int start_byte = CHAR_TO_BYTE (start);
583 int tem;
585 /* If we're looking for a newline, consult the newline cache
586 to see where we can avoid some scanning. */
587 if (target == '\n' && newline_cache)
589 int next_change;
590 immediate_quit = 0;
591 while (region_cache_forward
592 (current_buffer, newline_cache, start_byte, &next_change))
593 start_byte = next_change;
594 immediate_quit = allow_quit;
596 /* START should never be after END. */
597 if (start_byte > ceiling_byte)
598 start_byte = ceiling_byte;
600 /* Now the text after start is an unknown region, and
601 next_change is the position of the next known region. */
602 ceiling_byte = min (next_change - 1, ceiling_byte);
605 /* The dumb loop can only scan text stored in contiguous
606 bytes. BUFFER_CEILING_OF returns the last character
607 position that is contiguous, so the ceiling is the
608 position after that. */
609 tem = BUFFER_CEILING_OF (start_byte);
610 ceiling_byte = min (tem, ceiling_byte);
613 /* The termination address of the dumb loop. */
614 register unsigned char *ceiling_addr
615 = BYTE_POS_ADDR (ceiling_byte) + 1;
616 register unsigned char *cursor
617 = BYTE_POS_ADDR (start_byte);
618 unsigned char *base = cursor;
620 while (cursor < ceiling_addr)
622 unsigned char *scan_start = cursor;
624 /* The dumb loop. */
625 while (*cursor != target && ++cursor < ceiling_addr)
628 /* If we're looking for newlines, cache the fact that
629 the region from start to cursor is free of them. */
630 if (target == '\n' && newline_cache)
631 know_region_cache (current_buffer, newline_cache,
632 start_byte + scan_start - base,
633 start_byte + cursor - base);
635 /* Did we find the target character? */
636 if (cursor < ceiling_addr)
638 if (--count == 0)
640 immediate_quit = 0;
641 return BYTE_TO_CHAR (start_byte + cursor - base + 1);
643 cursor++;
647 start = BYTE_TO_CHAR (start_byte + cursor - base);
650 else
651 while (start > end)
653 /* The last character to check before the next obstacle. */
654 int ceiling_byte = CHAR_TO_BYTE (end);
655 int start_byte = CHAR_TO_BYTE (start);
656 int tem;
658 /* Consult the newline cache, if appropriate. */
659 if (target == '\n' && newline_cache)
661 int next_change;
662 immediate_quit = 0;
663 while (region_cache_backward
664 (current_buffer, newline_cache, start_byte, &next_change))
665 start_byte = next_change;
666 immediate_quit = allow_quit;
668 /* Start should never be at or before end. */
669 if (start_byte <= ceiling_byte)
670 start_byte = ceiling_byte + 1;
672 /* Now the text before start is an unknown region, and
673 next_change is the position of the next known region. */
674 ceiling_byte = max (next_change, ceiling_byte);
677 /* Stop scanning before the gap. */
678 tem = BUFFER_FLOOR_OF (start_byte - 1);
679 ceiling_byte = max (tem, ceiling_byte);
682 /* The termination address of the dumb loop. */
683 register unsigned char *ceiling_addr = BYTE_POS_ADDR (ceiling_byte);
684 register unsigned char *cursor = BYTE_POS_ADDR (start_byte - 1);
685 unsigned char *base = cursor;
687 while (cursor >= ceiling_addr)
689 unsigned char *scan_start = cursor;
691 while (*cursor != target && --cursor >= ceiling_addr)
694 /* If we're looking for newlines, cache the fact that
695 the region from after the cursor to start is free of them. */
696 if (target == '\n' && newline_cache)
697 know_region_cache (current_buffer, newline_cache,
698 start_byte + cursor - base,
699 start_byte + scan_start - base);
701 /* Did we find the target character? */
702 if (cursor >= ceiling_addr)
704 if (++count >= 0)
706 immediate_quit = 0;
707 return BYTE_TO_CHAR (start_byte + cursor - base);
709 cursor--;
713 start = BYTE_TO_CHAR (start_byte + cursor - base);
717 immediate_quit = 0;
718 if (shortage != 0)
719 *shortage = count * direction;
720 return start;
723 /* Search for COUNT instances of a line boundary, which means either a
724 newline or (if selective display enabled) a carriage return.
725 Start at START. If COUNT is negative, search backwards.
727 We report the resulting position by calling TEMP_SET_PT_BOTH.
729 If we find COUNT instances. we position after (always after,
730 even if scanning backwards) the COUNTth match, and return 0.
732 If we don't find COUNT instances before reaching the end of the
733 buffer (or the beginning, if scanning backwards), we return
734 the number of line boundaries left unfound, and position at
735 the limit we bumped up against.
737 If ALLOW_QUIT is non-zero, set immediate_quit. That's good to do
738 except in special cases. */
741 scan_newline (start, start_byte, limit, limit_byte, count, allow_quit)
742 int start, start_byte;
743 int limit, limit_byte;
744 register int count;
745 int allow_quit;
747 int direction = ((count > 0) ? 1 : -1);
749 register unsigned char *cursor;
750 unsigned char *base;
752 register int ceiling;
753 register unsigned char *ceiling_addr;
755 int old_immediate_quit = immediate_quit;
757 /* If we are not in selective display mode,
758 check only for newlines. */
759 int selective_display = (!NILP (current_buffer->selective_display)
760 && !INTEGERP (current_buffer->selective_display));
762 /* The code that follows is like scan_buffer
763 but checks for either newline or carriage return. */
765 if (allow_quit)
766 immediate_quit++;
768 start_byte = CHAR_TO_BYTE (start);
770 if (count > 0)
772 while (start_byte < limit_byte)
774 ceiling = BUFFER_CEILING_OF (start_byte);
775 ceiling = min (limit_byte - 1, ceiling);
776 ceiling_addr = BYTE_POS_ADDR (ceiling) + 1;
777 base = (cursor = BYTE_POS_ADDR (start_byte));
778 while (1)
780 while (*cursor != '\n' && ++cursor != ceiling_addr)
783 if (cursor != ceiling_addr)
785 if (--count == 0)
787 immediate_quit = old_immediate_quit;
788 start_byte = start_byte + cursor - base + 1;
789 start = BYTE_TO_CHAR (start_byte);
790 TEMP_SET_PT_BOTH (start, start_byte);
791 return 0;
793 else
794 if (++cursor == ceiling_addr)
795 break;
797 else
798 break;
800 start_byte += cursor - base;
803 else
805 while (start_byte > limit_byte)
807 ceiling = BUFFER_FLOOR_OF (start_byte - 1);
808 ceiling = max (limit_byte, ceiling);
809 ceiling_addr = BYTE_POS_ADDR (ceiling) - 1;
810 base = (cursor = BYTE_POS_ADDR (start_byte - 1) + 1);
811 while (1)
813 while (--cursor != ceiling_addr && *cursor != '\n')
816 if (cursor != ceiling_addr)
818 if (++count == 0)
820 immediate_quit = old_immediate_quit;
821 /* Return the position AFTER the match we found. */
822 start_byte = start_byte + cursor - base + 1;
823 start = BYTE_TO_CHAR (start_byte);
824 TEMP_SET_PT_BOTH (start, start_byte);
825 return 0;
828 else
829 break;
831 /* Here we add 1 to compensate for the last decrement
832 of CURSOR, which took it past the valid range. */
833 start_byte += cursor - base + 1;
837 TEMP_SET_PT_BOTH (limit, limit_byte);
838 immediate_quit = old_immediate_quit;
840 return count * direction;
844 find_next_newline_no_quit (from, cnt)
845 register int from, cnt;
847 return scan_buffer ('\n', from, 0, cnt, (int *) 0, 0);
850 /* Like find_next_newline, but returns position before the newline,
851 not after, and only search up to TO. This isn't just
852 find_next_newline (...)-1, because you might hit TO. */
855 find_before_next_newline (from, to, cnt)
856 int from, to, cnt;
858 int shortage;
859 int pos = scan_buffer ('\n', from, to, cnt, &shortage, 1);
861 if (shortage == 0)
862 pos--;
864 return pos;
867 /* Subroutines of Lisp buffer search functions. */
869 static Lisp_Object
870 search_command (string, bound, noerror, count, direction, RE, posix)
871 Lisp_Object string, bound, noerror, count;
872 int direction;
873 int RE;
874 int posix;
876 register int np;
877 int lim, lim_byte;
878 int n = direction;
880 if (!NILP (count))
882 CHECK_NUMBER (count, 3);
883 n *= XINT (count);
886 CHECK_STRING (string, 0);
887 if (NILP (bound))
889 if (n > 0)
890 lim = ZV, lim_byte = ZV_BYTE;
891 else
892 lim = BEGV, lim_byte = BEGV_BYTE;
894 else
896 CHECK_NUMBER_COERCE_MARKER (bound, 1);
897 lim = XINT (bound);
898 if (n > 0 ? lim < PT : lim > PT)
899 error ("Invalid search bound (wrong side of point)");
900 if (lim > ZV)
901 lim = ZV, lim_byte = ZV_BYTE;
902 else if (lim < BEGV)
903 lim = BEGV, lim_byte = BEGV_BYTE;
904 else
905 lim_byte = CHAR_TO_BYTE (lim);
908 np = search_buffer (string, PT, PT_BYTE, lim, lim_byte, n, RE,
909 (!NILP (current_buffer->case_fold_search)
910 ? current_buffer->case_canon_table
911 : Qnil),
912 (!NILP (current_buffer->case_fold_search)
913 ? current_buffer->case_eqv_table
914 : Qnil),
915 posix);
916 if (np <= 0)
918 if (NILP (noerror))
919 return signal_failure (string);
920 if (!EQ (noerror, Qt))
922 if (lim < BEGV || lim > ZV)
923 abort ();
924 SET_PT_BOTH (lim, lim_byte);
925 return Qnil;
926 #if 0 /* This would be clean, but maybe programs depend on
927 a value of nil here. */
928 np = lim;
929 #endif
931 else
932 return Qnil;
935 if (np < BEGV || np > ZV)
936 abort ();
938 SET_PT (np);
940 return make_number (np);
943 /* Return 1 if REGEXP it matches just one constant string. */
945 static int
946 trivial_regexp_p (regexp)
947 Lisp_Object regexp;
949 int len = STRING_BYTES (XSTRING (regexp));
950 unsigned char *s = XSTRING (regexp)->data;
951 unsigned char c;
952 while (--len >= 0)
954 switch (*s++)
956 case '.': case '*': case '+': case '?': case '[': case '^': case '$':
957 return 0;
958 case '\\':
959 if (--len < 0)
960 return 0;
961 switch (*s++)
963 case '|': case '(': case ')': case '`': case '\'': case 'b':
964 case 'B': case '<': case '>': case 'w': case 'W': case 's':
965 case 'S': case '=':
966 case 'c': case 'C': /* for categoryspec and notcategoryspec */
967 case '1': case '2': case '3': case '4': case '5':
968 case '6': case '7': case '8': case '9':
969 return 0;
973 return 1;
976 /* Search for the n'th occurrence of STRING in the current buffer,
977 starting at position POS and stopping at position LIM,
978 treating STRING as a literal string if RE is false or as
979 a regular expression if RE is true.
981 If N is positive, searching is forward and LIM must be greater than POS.
982 If N is negative, searching is backward and LIM must be less than POS.
984 Returns -x if x occurrences remain to be found (x > 0),
985 or else the position at the beginning of the Nth occurrence
986 (if searching backward) or the end (if searching forward).
988 POSIX is nonzero if we want full backtracking (POSIX style)
989 for this pattern. 0 means backtrack only enough to get a valid match. */
991 #define TRANSLATE(out, trt, d) \
992 do \
994 if (! NILP (trt)) \
996 Lisp_Object temp; \
997 temp = Faref (trt, make_number (d)); \
998 if (INTEGERP (temp)) \
999 out = XINT (temp); \
1000 else \
1001 out = d; \
1003 else \
1004 out = d; \
1006 while (0)
1008 static int
1009 search_buffer (string, pos, pos_byte, lim, lim_byte, n,
1010 RE, trt, inverse_trt, posix)
1011 Lisp_Object string;
1012 int pos;
1013 int pos_byte;
1014 int lim;
1015 int lim_byte;
1016 int n;
1017 int RE;
1018 Lisp_Object trt;
1019 Lisp_Object inverse_trt;
1020 int posix;
1022 int len = XSTRING (string)->size;
1023 int len_byte = STRING_BYTES (XSTRING (string));
1024 register int i;
1026 if (running_asynch_code)
1027 save_search_regs ();
1029 /* Searching 0 times means don't move. */
1030 /* Null string is found at starting position. */
1031 if (len == 0 || n == 0)
1033 set_search_regs (pos, 0);
1034 return pos;
1037 if (RE && !trivial_regexp_p (string))
1039 unsigned char *p1, *p2;
1040 int s1, s2;
1041 struct re_pattern_buffer *bufp;
1043 bufp = compile_pattern (string, &search_regs, trt, posix,
1044 !NILP (current_buffer->enable_multibyte_characters));
1046 immediate_quit = 1; /* Quit immediately if user types ^G,
1047 because letting this function finish
1048 can take too long. */
1049 QUIT; /* Do a pending quit right away,
1050 to avoid paradoxical behavior */
1051 /* Get pointers and sizes of the two strings
1052 that make up the visible portion of the buffer. */
1054 p1 = BEGV_ADDR;
1055 s1 = GPT_BYTE - BEGV_BYTE;
1056 p2 = GAP_END_ADDR;
1057 s2 = ZV_BYTE - GPT_BYTE;
1058 if (s1 < 0)
1060 p2 = p1;
1061 s2 = ZV_BYTE - BEGV_BYTE;
1062 s1 = 0;
1064 if (s2 < 0)
1066 s1 = ZV_BYTE - BEGV_BYTE;
1067 s2 = 0;
1069 re_match_object = Qnil;
1071 while (n < 0)
1073 int val;
1074 val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
1075 pos_byte - BEGV_BYTE, lim_byte - pos_byte,
1076 &search_regs,
1077 /* Don't allow match past current point */
1078 pos_byte - BEGV_BYTE);
1079 if (val == -2)
1081 matcher_overflow ();
1083 if (val >= 0)
1085 pos_byte = search_regs.start[0] + BEGV_BYTE;
1086 for (i = 0; i < search_regs.num_regs; i++)
1087 if (search_regs.start[i] >= 0)
1089 search_regs.start[i]
1090 = BYTE_TO_CHAR (search_regs.start[i] + BEGV_BYTE);
1091 search_regs.end[i]
1092 = BYTE_TO_CHAR (search_regs.end[i] + BEGV_BYTE);
1094 XSETBUFFER (last_thing_searched, current_buffer);
1095 /* Set pos to the new position. */
1096 pos = search_regs.start[0];
1098 else
1100 immediate_quit = 0;
1101 return (n);
1103 n++;
1105 while (n > 0)
1107 int val;
1108 val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
1109 pos_byte - BEGV_BYTE, lim_byte - pos_byte,
1110 &search_regs,
1111 lim_byte - BEGV_BYTE);
1112 if (val == -2)
1114 matcher_overflow ();
1116 if (val >= 0)
1118 pos_byte = search_regs.end[0] + BEGV_BYTE;
1119 for (i = 0; i < search_regs.num_regs; i++)
1120 if (search_regs.start[i] >= 0)
1122 search_regs.start[i]
1123 = BYTE_TO_CHAR (search_regs.start[i] + BEGV_BYTE);
1124 search_regs.end[i]
1125 = BYTE_TO_CHAR (search_regs.end[i] + BEGV_BYTE);
1127 XSETBUFFER (last_thing_searched, current_buffer);
1128 pos = search_regs.end[0];
1130 else
1132 immediate_quit = 0;
1133 return (0 - n);
1135 n--;
1137 immediate_quit = 0;
1138 return (pos);
1140 else /* non-RE case */
1142 unsigned char *raw_pattern, *pat;
1143 int raw_pattern_size;
1144 int raw_pattern_size_byte;
1145 unsigned char *patbuf;
1146 int multibyte = !NILP (current_buffer->enable_multibyte_characters);
1147 unsigned char *base_pat = XSTRING (string)->data;
1148 int charset_base = -1;
1149 int boyer_moore_ok = 1;
1151 /* MULTIBYTE says whether the text to be searched is multibyte.
1152 We must convert PATTERN to match that, or we will not really
1153 find things right. */
1155 if (multibyte == STRING_MULTIBYTE (string))
1157 raw_pattern = (unsigned char *) XSTRING (string)->data;
1158 raw_pattern_size = XSTRING (string)->size;
1159 raw_pattern_size_byte = STRING_BYTES (XSTRING (string));
1161 else if (multibyte)
1163 raw_pattern_size = XSTRING (string)->size;
1164 raw_pattern_size_byte
1165 = count_size_as_multibyte (XSTRING (string)->data,
1166 raw_pattern_size);
1167 raw_pattern = (unsigned char *) alloca (raw_pattern_size_byte + 1);
1168 copy_text (XSTRING (string)->data, raw_pattern,
1169 XSTRING (string)->size, 0, 1);
1171 else
1173 /* Converting multibyte to single-byte.
1175 ??? Perhaps this conversion should be done in a special way
1176 by subtracting nonascii-insert-offset from each non-ASCII char,
1177 so that only the multibyte chars which really correspond to
1178 the chosen single-byte character set can possibly match. */
1179 raw_pattern_size = XSTRING (string)->size;
1180 raw_pattern_size_byte = XSTRING (string)->size;
1181 raw_pattern = (unsigned char *) alloca (raw_pattern_size + 1);
1182 copy_text (XSTRING (string)->data, raw_pattern,
1183 STRING_BYTES (XSTRING (string)), 1, 0);
1186 /* Copy and optionally translate the pattern. */
1187 len = raw_pattern_size;
1188 len_byte = raw_pattern_size_byte;
1189 patbuf = (unsigned char *) alloca (len_byte);
1190 pat = patbuf;
1191 base_pat = raw_pattern;
1192 if (multibyte)
1194 while (--len >= 0)
1196 unsigned char str[MAX_MULTIBYTE_LENGTH];
1197 int c, translated, inverse;
1198 int in_charlen, charlen;
1200 /* If we got here and the RE flag is set, it's because we're
1201 dealing with a regexp known to be trivial, so the backslash
1202 just quotes the next character. */
1203 if (RE && *base_pat == '\\')
1205 len--;
1206 len_byte--;
1207 base_pat++;
1210 c = STRING_CHAR_AND_LENGTH (base_pat, len_byte, in_charlen);
1212 /* Translate the character, if requested. */
1213 TRANSLATE (translated, trt, c);
1214 /* If translation changed the byte-length, go back
1215 to the original character. */
1216 charlen = CHAR_STRING (translated, str);
1217 if (in_charlen != charlen)
1219 translated = c;
1220 charlen = CHAR_STRING (c, str);
1223 /* If we are searching for something strange,
1224 an invalid multibyte code, don't use boyer-moore. */
1225 if (! ASCII_BYTE_P (translated)
1226 && (charlen == 1 /* 8bit code */
1227 || charlen != in_charlen /* invalid multibyte code */
1229 boyer_moore_ok = 0;
1231 TRANSLATE (inverse, inverse_trt, c);
1233 /* Did this char actually get translated?
1234 Would any other char get translated into it? */
1235 if (translated != c || inverse != c)
1237 /* Keep track of which character set row
1238 contains the characters that need translation. */
1239 int charset_base_code = c & ~CHAR_FIELD3_MASK;
1240 if (charset_base == -1)
1241 charset_base = charset_base_code;
1242 else if (charset_base != charset_base_code)
1243 /* If two different rows appear, needing translation,
1244 then we cannot use boyer_moore search. */
1245 boyer_moore_ok = 0;
1248 /* Store this character into the translated pattern. */
1249 bcopy (str, pat, charlen);
1250 pat += charlen;
1251 base_pat += in_charlen;
1252 len_byte -= in_charlen;
1255 else
1257 /* Unibyte buffer. */
1258 charset_base = 0;
1259 while (--len >= 0)
1261 int c, translated;
1263 /* If we got here and the RE flag is set, it's because we're
1264 dealing with a regexp known to be trivial, so the backslash
1265 just quotes the next character. */
1266 if (RE && *base_pat == '\\')
1268 len--;
1269 base_pat++;
1271 c = *base_pat++;
1272 TRANSLATE (translated, trt, c);
1273 *pat++ = translated;
1277 len_byte = pat - patbuf;
1278 len = raw_pattern_size;
1279 pat = base_pat = patbuf;
1281 if (boyer_moore_ok)
1282 return boyer_moore (n, pat, len, len_byte, trt, inverse_trt,
1283 pos, pos_byte, lim, lim_byte,
1284 charset_base);
1285 else
1286 return simple_search (n, pat, len, len_byte, trt,
1287 pos, pos_byte, lim, lim_byte);
1291 /* Do a simple string search N times for the string PAT,
1292 whose length is LEN/LEN_BYTE,
1293 from buffer position POS/POS_BYTE until LIM/LIM_BYTE.
1294 TRT is the translation table.
1296 Return the character position where the match is found.
1297 Otherwise, if M matches remained to be found, return -M.
1299 This kind of search works regardless of what is in PAT and
1300 regardless of what is in TRT. It is used in cases where
1301 boyer_moore cannot work. */
1303 static int
1304 simple_search (n, pat, len, len_byte, trt, pos, pos_byte, lim, lim_byte)
1305 int n;
1306 unsigned char *pat;
1307 int len, len_byte;
1308 Lisp_Object trt;
1309 int pos, pos_byte;
1310 int lim, lim_byte;
1312 int multibyte = ! NILP (current_buffer->enable_multibyte_characters);
1313 int forward = n > 0;
1315 if (lim > pos && multibyte)
1316 while (n > 0)
1318 while (1)
1320 /* Try matching at position POS. */
1321 int this_pos = pos;
1322 int this_pos_byte = pos_byte;
1323 int this_len = len;
1324 int this_len_byte = len_byte;
1325 unsigned char *p = pat;
1326 if (pos + len > lim)
1327 goto stop;
1329 while (this_len > 0)
1331 int charlen, buf_charlen;
1332 int pat_ch, buf_ch;
1334 pat_ch = STRING_CHAR_AND_LENGTH (p, this_len_byte, charlen);
1335 buf_ch = STRING_CHAR_AND_LENGTH (BYTE_POS_ADDR (this_pos_byte),
1336 ZV_BYTE - this_pos_byte,
1337 buf_charlen);
1338 TRANSLATE (buf_ch, trt, buf_ch);
1340 if (buf_ch != pat_ch)
1341 break;
1343 this_len_byte -= charlen;
1344 this_len--;
1345 p += charlen;
1347 this_pos_byte += buf_charlen;
1348 this_pos++;
1351 if (this_len == 0)
1353 pos += len;
1354 pos_byte += len_byte;
1355 break;
1358 INC_BOTH (pos, pos_byte);
1361 n--;
1363 else if (lim > pos)
1364 while (n > 0)
1366 while (1)
1368 /* Try matching at position POS. */
1369 int this_pos = pos;
1370 int this_len = len;
1371 unsigned char *p = pat;
1373 if (pos + len > lim)
1374 goto stop;
1376 while (this_len > 0)
1378 int pat_ch = *p++;
1379 int buf_ch = FETCH_BYTE (this_pos);
1380 TRANSLATE (buf_ch, trt, buf_ch);
1382 if (buf_ch != pat_ch)
1383 break;
1385 this_len--;
1386 this_pos++;
1389 if (this_len == 0)
1391 pos += len;
1392 break;
1395 pos++;
1398 n--;
1400 /* Backwards search. */
1401 else if (lim < pos && multibyte)
1402 while (n < 0)
1404 while (1)
1406 /* Try matching at position POS. */
1407 int this_pos = pos - len;
1408 int this_pos_byte = pos_byte - len_byte;
1409 int this_len = len;
1410 int this_len_byte = len_byte;
1411 unsigned char *p = pat;
1413 if (pos - len < lim)
1414 goto stop;
1416 while (this_len > 0)
1418 int charlen, buf_charlen;
1419 int pat_ch, buf_ch;
1421 pat_ch = STRING_CHAR_AND_LENGTH (p, this_len_byte, charlen);
1422 buf_ch = STRING_CHAR_AND_LENGTH (BYTE_POS_ADDR (this_pos_byte),
1423 ZV_BYTE - this_pos_byte,
1424 buf_charlen);
1425 TRANSLATE (buf_ch, trt, buf_ch);
1427 if (buf_ch != pat_ch)
1428 break;
1430 this_len_byte -= charlen;
1431 this_len--;
1432 p += charlen;
1433 this_pos_byte += buf_charlen;
1434 this_pos++;
1437 if (this_len == 0)
1439 pos -= len;
1440 pos_byte -= len_byte;
1441 break;
1444 DEC_BOTH (pos, pos_byte);
1447 n++;
1449 else if (lim < pos)
1450 while (n < 0)
1452 while (1)
1454 /* Try matching at position POS. */
1455 int this_pos = pos - len;
1456 int this_len = len;
1457 unsigned char *p = pat;
1459 if (pos - len < lim)
1460 goto stop;
1462 while (this_len > 0)
1464 int pat_ch = *p++;
1465 int buf_ch = FETCH_BYTE (this_pos);
1466 TRANSLATE (buf_ch, trt, buf_ch);
1468 if (buf_ch != pat_ch)
1469 break;
1470 this_len--;
1471 this_pos++;
1474 if (this_len == 0)
1476 pos -= len;
1477 break;
1480 pos--;
1483 n++;
1486 stop:
1487 if (n == 0)
1489 if (forward)
1490 set_search_regs ((multibyte ? pos_byte : pos) - len_byte, len_byte);
1491 else
1492 set_search_regs (multibyte ? pos_byte : pos, len_byte);
1494 return pos;
1496 else if (n > 0)
1497 return -n;
1498 else
1499 return n;
1502 /* Do Boyer-Moore search N times for the string PAT,
1503 whose length is LEN/LEN_BYTE,
1504 from buffer position POS/POS_BYTE until LIM/LIM_BYTE.
1505 DIRECTION says which direction we search in.
1506 TRT and INVERSE_TRT are translation tables.
1508 This kind of search works if all the characters in PAT that have
1509 nontrivial translation are the same aside from the last byte. This
1510 makes it possible to translate just the last byte of a character,
1511 and do so after just a simple test of the context.
1513 If that criterion is not satisfied, do not call this function. */
1515 static int
1516 boyer_moore (n, base_pat, len, len_byte, trt, inverse_trt,
1517 pos, pos_byte, lim, lim_byte, charset_base)
1518 int n;
1519 unsigned char *base_pat;
1520 int len, len_byte;
1521 Lisp_Object trt;
1522 Lisp_Object inverse_trt;
1523 int pos, pos_byte;
1524 int lim, lim_byte;
1525 int charset_base;
1527 int direction = ((n > 0) ? 1 : -1);
1528 register int dirlen;
1529 int infinity, limit, k, stride_for_teases;
1530 register int *BM_tab;
1531 int *BM_tab_base;
1532 register unsigned char *cursor, *p_limit;
1533 register int i, j;
1534 unsigned char *pat, *pat_end;
1535 int multibyte = ! NILP (current_buffer->enable_multibyte_characters);
1537 unsigned char simple_translate[0400];
1538 int translate_prev_byte;
1539 int translate_anteprev_byte;
1541 #ifdef C_ALLOCA
1542 int BM_tab_space[0400];
1543 BM_tab = &BM_tab_space[0];
1544 #else
1545 BM_tab = (int *) alloca (0400 * sizeof (int));
1546 #endif
1547 /* The general approach is that we are going to maintain that we know */
1548 /* the first (closest to the present position, in whatever direction */
1549 /* we're searching) character that could possibly be the last */
1550 /* (furthest from present position) character of a valid match. We */
1551 /* advance the state of our knowledge by looking at that character */
1552 /* and seeing whether it indeed matches the last character of the */
1553 /* pattern. If it does, we take a closer look. If it does not, we */
1554 /* move our pointer (to putative last characters) as far as is */
1555 /* logically possible. This amount of movement, which I call a */
1556 /* stride, will be the length of the pattern if the actual character */
1557 /* appears nowhere in the pattern, otherwise it will be the distance */
1558 /* from the last occurrence of that character to the end of the */
1559 /* pattern. */
1560 /* As a coding trick, an enormous stride is coded into the table for */
1561 /* characters that match the last character. This allows use of only */
1562 /* a single test, a test for having gone past the end of the */
1563 /* permissible match region, to test for both possible matches (when */
1564 /* the stride goes past the end immediately) and failure to */
1565 /* match (where you get nudged past the end one stride at a time). */
1567 /* Here we make a "mickey mouse" BM table. The stride of the search */
1568 /* is determined only by the last character of the putative match. */
1569 /* If that character does not match, we will stride the proper */
1570 /* distance to propose a match that superimposes it on the last */
1571 /* instance of a character that matches it (per trt), or misses */
1572 /* it entirely if there is none. */
1574 dirlen = len_byte * direction;
1575 infinity = dirlen - (lim_byte + pos_byte + len_byte + len_byte) * direction;
1577 /* Record position after the end of the pattern. */
1578 pat_end = base_pat + len_byte;
1579 /* BASE_PAT points to a character that we start scanning from.
1580 It is the first character in a forward search,
1581 the last character in a backward search. */
1582 if (direction < 0)
1583 base_pat = pat_end - 1;
1585 BM_tab_base = BM_tab;
1586 BM_tab += 0400;
1587 j = dirlen; /* to get it in a register */
1588 /* A character that does not appear in the pattern induces a */
1589 /* stride equal to the pattern length. */
1590 while (BM_tab_base != BM_tab)
1592 *--BM_tab = j;
1593 *--BM_tab = j;
1594 *--BM_tab = j;
1595 *--BM_tab = j;
1598 /* We use this for translation, instead of TRT itself.
1599 We fill this in to handle the characters that actually
1600 occur in the pattern. Others don't matter anyway! */
1601 bzero (simple_translate, sizeof simple_translate);
1602 for (i = 0; i < 0400; i++)
1603 simple_translate[i] = i;
1605 i = 0;
1606 while (i != infinity)
1608 unsigned char *ptr = base_pat + i;
1609 i += direction;
1610 if (i == dirlen)
1611 i = infinity;
1612 if (! NILP (trt))
1614 int ch;
1615 int untranslated;
1616 int this_translated = 1;
1618 if (multibyte
1619 /* Is *PTR the last byte of a character? */
1620 && (pat_end - ptr == 1 || CHAR_HEAD_P (ptr[1])))
1622 unsigned char *charstart = ptr;
1623 while (! CHAR_HEAD_P (*charstart))
1624 charstart--;
1625 untranslated = STRING_CHAR (charstart, ptr - charstart + 1);
1626 if (charset_base == (untranslated & ~CHAR_FIELD3_MASK))
1628 TRANSLATE (ch, trt, untranslated);
1629 if (! CHAR_HEAD_P (*ptr))
1631 translate_prev_byte = ptr[-1];
1632 if (! CHAR_HEAD_P (translate_prev_byte))
1633 translate_anteprev_byte = ptr[-2];
1636 else
1638 this_translated = 0;
1639 ch = *ptr;
1642 else if (!multibyte)
1643 TRANSLATE (ch, trt, *ptr);
1644 else
1646 ch = *ptr;
1647 this_translated = 0;
1650 if (ch > 0400)
1651 j = ((unsigned char) ch) | 0200;
1652 else
1653 j = (unsigned char) ch;
1655 if (i == infinity)
1656 stride_for_teases = BM_tab[j];
1658 BM_tab[j] = dirlen - i;
1659 /* A translation table is accompanied by its inverse -- see */
1660 /* comment following downcase_table for details */
1661 if (this_translated)
1663 int starting_ch = ch;
1664 int starting_j = j;
1665 while (1)
1667 TRANSLATE (ch, inverse_trt, ch);
1668 if (ch > 0400)
1669 j = ((unsigned char) ch) | 0200;
1670 else
1671 j = (unsigned char) ch;
1673 /* For all the characters that map into CH,
1674 set up simple_translate to map the last byte
1675 into STARTING_J. */
1676 simple_translate[j] = starting_j;
1677 if (ch == starting_ch)
1678 break;
1679 BM_tab[j] = dirlen - i;
1683 else
1685 j = *ptr;
1687 if (i == infinity)
1688 stride_for_teases = BM_tab[j];
1689 BM_tab[j] = dirlen - i;
1691 /* stride_for_teases tells how much to stride if we get a */
1692 /* match on the far character but are subsequently */
1693 /* disappointed, by recording what the stride would have been */
1694 /* for that character if the last character had been */
1695 /* different. */
1697 infinity = dirlen - infinity;
1698 pos_byte += dirlen - ((direction > 0) ? direction : 0);
1699 /* loop invariant - POS_BYTE points at where last char (first
1700 char if reverse) of pattern would align in a possible match. */
1701 while (n != 0)
1703 int tail_end;
1704 unsigned char *tail_end_ptr;
1706 /* It's been reported that some (broken) compiler thinks that
1707 Boolean expressions in an arithmetic context are unsigned.
1708 Using an explicit ?1:0 prevents this. */
1709 if ((lim_byte - pos_byte - ((direction > 0) ? 1 : 0)) * direction
1710 < 0)
1711 return (n * (0 - direction));
1712 /* First we do the part we can by pointers (maybe nothing) */
1713 QUIT;
1714 pat = base_pat;
1715 limit = pos_byte - dirlen + direction;
1716 if (direction > 0)
1718 limit = BUFFER_CEILING_OF (limit);
1719 /* LIMIT is now the last (not beyond-last!) value POS_BYTE
1720 can take on without hitting edge of buffer or the gap. */
1721 limit = min (limit, pos_byte + 20000);
1722 limit = min (limit, lim_byte - 1);
1724 else
1726 limit = BUFFER_FLOOR_OF (limit);
1727 /* LIMIT is now the last (not beyond-last!) value POS_BYTE
1728 can take on without hitting edge of buffer or the gap. */
1729 limit = max (limit, pos_byte - 20000);
1730 limit = max (limit, lim_byte);
1732 tail_end = BUFFER_CEILING_OF (pos_byte) + 1;
1733 tail_end_ptr = BYTE_POS_ADDR (tail_end);
1735 if ((limit - pos_byte) * direction > 20)
1737 unsigned char *p2;
1739 p_limit = BYTE_POS_ADDR (limit);
1740 p2 = (cursor = BYTE_POS_ADDR (pos_byte));
1741 /* In this loop, pos + cursor - p2 is the surrogate for pos */
1742 while (1) /* use one cursor setting as long as i can */
1744 if (direction > 0) /* worth duplicating */
1746 /* Use signed comparison if appropriate
1747 to make cursor+infinity sure to be > p_limit.
1748 Assuming that the buffer lies in a range of addresses
1749 that are all "positive" (as ints) or all "negative",
1750 either kind of comparison will work as long
1751 as we don't step by infinity. So pick the kind
1752 that works when we do step by infinity. */
1753 if ((EMACS_INT) (p_limit + infinity) > (EMACS_INT) p_limit)
1754 while ((EMACS_INT) cursor <= (EMACS_INT) p_limit)
1755 cursor += BM_tab[*cursor];
1756 else
1757 while ((EMACS_UINT) cursor <= (EMACS_UINT) p_limit)
1758 cursor += BM_tab[*cursor];
1760 else
1762 if ((EMACS_INT) (p_limit + infinity) < (EMACS_INT) p_limit)
1763 while ((EMACS_INT) cursor >= (EMACS_INT) p_limit)
1764 cursor += BM_tab[*cursor];
1765 else
1766 while ((EMACS_UINT) cursor >= (EMACS_UINT) p_limit)
1767 cursor += BM_tab[*cursor];
1769 /* If you are here, cursor is beyond the end of the searched region. */
1770 /* This can happen if you match on the far character of the pattern, */
1771 /* because the "stride" of that character is infinity, a number able */
1772 /* to throw you well beyond the end of the search. It can also */
1773 /* happen if you fail to match within the permitted region and would */
1774 /* otherwise try a character beyond that region */
1775 if ((cursor - p_limit) * direction <= len_byte)
1776 break; /* a small overrun is genuine */
1777 cursor -= infinity; /* large overrun = hit */
1778 i = dirlen - direction;
1779 if (! NILP (trt))
1781 while ((i -= direction) + direction != 0)
1783 int ch;
1784 cursor -= direction;
1785 /* Translate only the last byte of a character. */
1786 if (! multibyte
1787 || ((cursor == tail_end_ptr
1788 || CHAR_HEAD_P (cursor[1]))
1789 && (CHAR_HEAD_P (cursor[0])
1790 || (translate_prev_byte == cursor[-1]
1791 && (CHAR_HEAD_P (translate_prev_byte)
1792 || translate_anteprev_byte == cursor[-2])))))
1793 ch = simple_translate[*cursor];
1794 else
1795 ch = *cursor;
1796 if (pat[i] != ch)
1797 break;
1800 else
1802 while ((i -= direction) + direction != 0)
1804 cursor -= direction;
1805 if (pat[i] != *cursor)
1806 break;
1809 cursor += dirlen - i - direction; /* fix cursor */
1810 if (i + direction == 0)
1812 int position;
1814 cursor -= direction;
1816 position = pos_byte + cursor - p2 + ((direction > 0)
1817 ? 1 - len_byte : 0);
1818 set_search_regs (position, len_byte);
1820 if ((n -= direction) != 0)
1821 cursor += dirlen; /* to resume search */
1822 else
1823 return ((direction > 0)
1824 ? search_regs.end[0] : search_regs.start[0]);
1826 else
1827 cursor += stride_for_teases; /* <sigh> we lose - */
1829 pos_byte += cursor - p2;
1831 else
1832 /* Now we'll pick up a clump that has to be done the hard */
1833 /* way because it covers a discontinuity */
1835 limit = ((direction > 0)
1836 ? BUFFER_CEILING_OF (pos_byte - dirlen + 1)
1837 : BUFFER_FLOOR_OF (pos_byte - dirlen - 1));
1838 limit = ((direction > 0)
1839 ? min (limit + len_byte, lim_byte - 1)
1840 : max (limit - len_byte, lim_byte));
1841 /* LIMIT is now the last value POS_BYTE can have
1842 and still be valid for a possible match. */
1843 while (1)
1845 /* This loop can be coded for space rather than */
1846 /* speed because it will usually run only once. */
1847 /* (the reach is at most len + 21, and typically */
1848 /* does not exceed len) */
1849 while ((limit - pos_byte) * direction >= 0)
1850 pos_byte += BM_tab[FETCH_BYTE (pos_byte)];
1851 /* now run the same tests to distinguish going off the */
1852 /* end, a match or a phony match. */
1853 if ((pos_byte - limit) * direction <= len_byte)
1854 break; /* ran off the end */
1855 /* Found what might be a match.
1856 Set POS_BYTE back to last (first if reverse) pos. */
1857 pos_byte -= infinity;
1858 i = dirlen - direction;
1859 while ((i -= direction) + direction != 0)
1861 int ch;
1862 unsigned char *ptr;
1863 pos_byte -= direction;
1864 ptr = BYTE_POS_ADDR (pos_byte);
1865 /* Translate only the last byte of a character. */
1866 if (! multibyte
1867 || ((ptr == tail_end_ptr
1868 || CHAR_HEAD_P (ptr[1]))
1869 && (CHAR_HEAD_P (ptr[0])
1870 || (translate_prev_byte == ptr[-1]
1871 && (CHAR_HEAD_P (translate_prev_byte)
1872 || translate_anteprev_byte == ptr[-2])))))
1873 ch = simple_translate[*ptr];
1874 else
1875 ch = *ptr;
1876 if (pat[i] != ch)
1877 break;
1879 /* Above loop has moved POS_BYTE part or all the way
1880 back to the first pos (last pos if reverse).
1881 Set it once again at the last (first if reverse) char. */
1882 pos_byte += dirlen - i- direction;
1883 if (i + direction == 0)
1885 int position;
1886 pos_byte -= direction;
1888 position = pos_byte + ((direction > 0) ? 1 - len_byte : 0);
1890 set_search_regs (position, len_byte);
1892 if ((n -= direction) != 0)
1893 pos_byte += dirlen; /* to resume search */
1894 else
1895 return ((direction > 0)
1896 ? search_regs.end[0] : search_regs.start[0]);
1898 else
1899 pos_byte += stride_for_teases;
1902 /* We have done one clump. Can we continue? */
1903 if ((lim_byte - pos_byte) * direction < 0)
1904 return ((0 - n) * direction);
1906 return BYTE_TO_CHAR (pos_byte);
1909 /* Record beginning BEG_BYTE and end BEG_BYTE + NBYTES
1910 for the overall match just found in the current buffer.
1911 Also clear out the match data for registers 1 and up. */
1913 static void
1914 set_search_regs (beg_byte, nbytes)
1915 int beg_byte, nbytes;
1917 int i;
1919 /* Make sure we have registers in which to store
1920 the match position. */
1921 if (search_regs.num_regs == 0)
1923 search_regs.start = (regoff_t *) xmalloc (2 * sizeof (regoff_t));
1924 search_regs.end = (regoff_t *) xmalloc (2 * sizeof (regoff_t));
1925 search_regs.num_regs = 2;
1928 /* Clear out the other registers. */
1929 for (i = 1; i < search_regs.num_regs; i++)
1931 search_regs.start[i] = -1;
1932 search_regs.end[i] = -1;
1935 search_regs.start[0] = BYTE_TO_CHAR (beg_byte);
1936 search_regs.end[0] = BYTE_TO_CHAR (beg_byte + nbytes);
1937 XSETBUFFER (last_thing_searched, current_buffer);
1940 /* Given a string of words separated by word delimiters,
1941 compute a regexp that matches those exact words
1942 separated by arbitrary punctuation. */
1944 static Lisp_Object
1945 wordify (string)
1946 Lisp_Object string;
1948 register unsigned char *p, *o;
1949 register int i, i_byte, len, punct_count = 0, word_count = 0;
1950 Lisp_Object val;
1951 int prev_c = 0;
1952 int adjust;
1954 CHECK_STRING (string, 0);
1955 p = XSTRING (string)->data;
1956 len = XSTRING (string)->size;
1958 for (i = 0, i_byte = 0; i < len; )
1960 int c;
1962 FETCH_STRING_CHAR_ADVANCE (c, string, i, i_byte);
1964 if (SYNTAX (c) != Sword)
1966 punct_count++;
1967 if (i > 0 && SYNTAX (prev_c) == Sword)
1968 word_count++;
1971 prev_c = c;
1974 if (SYNTAX (prev_c) == Sword)
1975 word_count++;
1976 if (!word_count)
1977 return build_string ("");
1979 adjust = - punct_count + 5 * (word_count - 1) + 4;
1980 if (STRING_MULTIBYTE (string))
1981 val = make_uninit_multibyte_string (len + adjust,
1982 STRING_BYTES (XSTRING (string))
1983 + adjust);
1984 else
1985 val = make_uninit_string (len + adjust);
1987 o = XSTRING (val)->data;
1988 *o++ = '\\';
1989 *o++ = 'b';
1990 prev_c = 0;
1992 for (i = 0, i_byte = 0; i < len; )
1994 int c;
1995 int i_byte_orig = i_byte;
1997 FETCH_STRING_CHAR_ADVANCE (c, string, i, i_byte);
1999 if (SYNTAX (c) == Sword)
2001 bcopy (&XSTRING (string)->data[i_byte_orig], o,
2002 i_byte - i_byte_orig);
2003 o += i_byte - i_byte_orig;
2005 else if (i > 0 && SYNTAX (prev_c) == Sword && --word_count)
2007 *o++ = '\\';
2008 *o++ = 'W';
2009 *o++ = '\\';
2010 *o++ = 'W';
2011 *o++ = '*';
2014 prev_c = c;
2017 *o++ = '\\';
2018 *o++ = 'b';
2020 return val;
2023 DEFUN ("search-backward", Fsearch_backward, Ssearch_backward, 1, 4,
2024 "MSearch backward: ",
2025 "Search backward from point for STRING.\n\
2026 Set point to the beginning of the occurrence found, and return point.\n\
2027 An optional second argument bounds the search; it is a buffer position.\n\
2028 The match found must not extend before that position.\n\
2029 Optional third argument, if t, means if fail just return nil (no error).\n\
2030 If not nil and not t, position at limit of search and return nil.\n\
2031 Optional fourth argument is repeat count--search for successive occurrences.\n\
2032 See also the functions `match-beginning', `match-end' and `replace-match'.")
2033 (string, bound, noerror, count)
2034 Lisp_Object string, bound, noerror, count;
2036 return search_command (string, bound, noerror, count, -1, 0, 0);
2039 DEFUN ("search-forward", Fsearch_forward, Ssearch_forward, 1, 4, "MSearch: ",
2040 "Search forward from point for STRING.\n\
2041 Set point to the end 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 after that position. nil is equivalent\n\
2044 to (point-max).\n\
2045 Optional third argument, if t, means if fail just return nil (no error).\n\
2046 If not nil and not t, move to limit of search and return nil.\n\
2047 Optional fourth argument is repeat count--search for successive occurrences.\n\
2048 See also the functions `match-beginning', `match-end' and `replace-match'.")
2049 (string, bound, noerror, count)
2050 Lisp_Object string, bound, noerror, count;
2052 return search_command (string, bound, noerror, count, 1, 0, 0);
2055 DEFUN ("word-search-backward", Fword_search_backward, Sword_search_backward, 1, 4,
2056 "sWord search backward: ",
2057 "Search backward from point for STRING, ignoring differences in punctuation.\n\
2058 Set point to the beginning of the occurrence found, and return point.\n\
2059 An optional second argument bounds the search; it is a buffer position.\n\
2060 The match found must not extend before that position.\n\
2061 Optional third argument, if t, means if fail just return nil (no error).\n\
2062 If not nil and not t, move to limit of search and return nil.\n\
2063 Optional fourth argument is repeat count--search for successive occurrences.")
2064 (string, bound, noerror, count)
2065 Lisp_Object string, bound, noerror, count;
2067 return search_command (wordify (string), bound, noerror, count, -1, 1, 0);
2070 DEFUN ("word-search-forward", Fword_search_forward, Sword_search_forward, 1, 4,
2071 "sWord search: ",
2072 "Search forward from point for STRING, ignoring differences in punctuation.\n\
2073 Set point to the end 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 after 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 ("re-search-backward", Fre_search_backward, Sre_search_backward, 1, 4,
2086 "sRE search backward: ",
2087 "Search backward from point for match for regular expression REGEXP.\n\
2088 Set point to the beginning of the match, and return point.\n\
2089 The match found is the one starting last in the buffer\n\
2090 and yet ending before the origin of the search.\n\
2091 An optional second argument bounds the search; it is a buffer position.\n\
2092 The match found must start at or after that position.\n\
2093 Optional third argument, if t, means if fail just return nil (no error).\n\
2094 If not nil and not t, move to limit of search and return nil.\n\
2095 Optional fourth argument is repeat count--search for successive occurrences.\n\
2096 See also the functions `match-beginning', `match-end', `match-string',\n\
2097 and `replace-match'.")
2098 (regexp, bound, noerror, count)
2099 Lisp_Object regexp, bound, noerror, count;
2101 return search_command (regexp, bound, noerror, count, -1, 1, 0);
2104 DEFUN ("re-search-forward", Fre_search_forward, Sre_search_forward, 1, 4,
2105 "sRE search: ",
2106 "Search forward from point for regular expression REGEXP.\n\
2107 Set point to the end of the occurrence found, and return point.\n\
2108 An optional second argument bounds the search; it is a buffer position.\n\
2109 The match found must not extend after that position.\n\
2110 Optional third argument, if t, means if fail just return nil (no error).\n\
2111 If not nil and not t, move to limit of search and return nil.\n\
2112 Optional fourth argument is repeat count--search for successive occurrences.\n\
2113 See also the functions `match-beginning', `match-end', `match-string',\n\
2114 and `replace-match'.")
2115 (regexp, bound, noerror, count)
2116 Lisp_Object regexp, bound, noerror, count;
2118 return search_command (regexp, bound, noerror, count, 1, 1, 0);
2121 DEFUN ("posix-search-backward", Fposix_search_backward, Sposix_search_backward, 1, 4,
2122 "sPosix search backward: ",
2123 "Search backward from point for match for regular expression REGEXP.\n\
2124 Find the longest match in accord with Posix regular expression rules.\n\
2125 Set point to the beginning of the match, and return point.\n\
2126 The match found is the one starting last in the buffer\n\
2127 and yet ending before the origin of the search.\n\
2128 An optional second argument bounds the search; it is a buffer position.\n\
2129 The match found must start at or after that position.\n\
2130 Optional third argument, if t, means if fail just return nil (no error).\n\
2131 If not nil and not t, move to limit of search and return nil.\n\
2132 Optional fourth argument is repeat count--search for successive occurrences.\n\
2133 See also the functions `match-beginning', `match-end', `match-string',\n\
2134 and `replace-match'.")
2135 (regexp, bound, noerror, count)
2136 Lisp_Object regexp, bound, noerror, count;
2138 return search_command (regexp, bound, noerror, count, -1, 1, 1);
2141 DEFUN ("posix-search-forward", Fposix_search_forward, Sposix_search_forward, 1, 4,
2142 "sPosix search: ",
2143 "Search forward from point for regular expression REGEXP.\n\
2144 Find the longest match in accord with Posix regular expression rules.\n\
2145 Set point to the end of the occurrence found, and return point.\n\
2146 An optional second argument bounds the search; it is a buffer position.\n\
2147 The match found must not extend after that position.\n\
2148 Optional third argument, if t, means if fail just return nil (no error).\n\
2149 If not nil and not t, move to limit of search and return nil.\n\
2150 Optional fourth argument is repeat count--search for successive occurrences.\n\
2151 See also the functions `match-beginning', `match-end', `match-string',\n\
2152 and `replace-match'.")
2153 (regexp, bound, noerror, count)
2154 Lisp_Object regexp, bound, noerror, count;
2156 return search_command (regexp, bound, noerror, count, 1, 1, 1);
2159 DEFUN ("replace-match", Freplace_match, Sreplace_match, 1, 5, 0,
2160 "Replace text matched by last search with NEWTEXT.\n\
2161 If second arg FIXEDCASE is non-nil, do not alter case of replacement text.\n\
2162 Otherwise maybe capitalize the whole text, or maybe just word initials,\n\
2163 based on the replaced text.\n\
2164 If the replaced text has only capital letters\n\
2165 and has at least one multiletter word, convert NEWTEXT to all caps.\n\
2166 If the replaced text has at least one word starting with a capital letter,\n\
2167 then capitalize each word in NEWTEXT.\n\n\
2168 If third arg LITERAL is non-nil, insert NEWTEXT literally.\n\
2169 Otherwise treat `\\' as special:\n\
2170 `\\&' in NEWTEXT means substitute original matched text.\n\
2171 `\\N' means substitute what matched the Nth `\\(...\\)'.\n\
2172 If Nth parens didn't match, substitute nothing.\n\
2173 `\\\\' means insert one `\\'.\n\
2174 FIXEDCASE and LITERAL are optional arguments.\n\
2175 Leaves point at end of replacement text.\n\
2177 The optional fourth argument STRING can be a string to modify.\n\
2178 In that case, this function creates and returns a new string\n\
2179 which is made by replacing the part of STRING that was matched.\n\
2181 The optional fifth argument SUBEXP specifies a subexpression of the match.\n\
2182 It says to replace just that subexpression instead of the whole match.\n\
2183 This is useful only after a regular expression search or match\n\
2184 since only regular expressions have distinguished subexpressions.")
2185 (newtext, fixedcase, literal, string, subexp)
2186 Lisp_Object newtext, fixedcase, literal, string, subexp;
2188 enum { nochange, all_caps, cap_initial } case_action;
2189 register int pos, pos_byte;
2190 int some_multiletter_word;
2191 int some_lowercase;
2192 int some_uppercase;
2193 int some_nonuppercase_initial;
2194 register int c, prevc;
2195 int inslen;
2196 int sub;
2197 int opoint, newpoint;
2199 CHECK_STRING (newtext, 0);
2201 if (! NILP (string))
2202 CHECK_STRING (string, 4);
2204 case_action = nochange; /* We tried an initialization */
2205 /* but some C compilers blew it */
2207 if (search_regs.num_regs <= 0)
2208 error ("replace-match called before any match found");
2210 if (NILP (subexp))
2211 sub = 0;
2212 else
2214 CHECK_NUMBER (subexp, 3);
2215 sub = XINT (subexp);
2216 if (sub < 0 || sub >= search_regs.num_regs)
2217 args_out_of_range (subexp, make_number (search_regs.num_regs));
2220 if (NILP (string))
2222 if (search_regs.start[sub] < BEGV
2223 || search_regs.start[sub] > search_regs.end[sub]
2224 || search_regs.end[sub] > ZV)
2225 args_out_of_range (make_number (search_regs.start[sub]),
2226 make_number (search_regs.end[sub]));
2228 else
2230 if (search_regs.start[sub] < 0
2231 || search_regs.start[sub] > search_regs.end[sub]
2232 || search_regs.end[sub] > XSTRING (string)->size)
2233 args_out_of_range (make_number (search_regs.start[sub]),
2234 make_number (search_regs.end[sub]));
2237 if (NILP (fixedcase))
2239 /* Decide how to casify by examining the matched text. */
2240 int last;
2242 pos = search_regs.start[sub];
2243 last = search_regs.end[sub];
2245 if (NILP (string))
2246 pos_byte = CHAR_TO_BYTE (pos);
2247 else
2248 pos_byte = string_char_to_byte (string, pos);
2250 prevc = '\n';
2251 case_action = all_caps;
2253 /* some_multiletter_word is set nonzero if any original word
2254 is more than one letter long. */
2255 some_multiletter_word = 0;
2256 some_lowercase = 0;
2257 some_nonuppercase_initial = 0;
2258 some_uppercase = 0;
2260 while (pos < last)
2262 if (NILP (string))
2264 c = FETCH_CHAR (pos_byte);
2265 INC_BOTH (pos, pos_byte);
2267 else
2268 FETCH_STRING_CHAR_ADVANCE (c, string, pos, pos_byte);
2270 if (LOWERCASEP (c))
2272 /* Cannot be all caps if any original char is lower case */
2274 some_lowercase = 1;
2275 if (SYNTAX (prevc) != Sword)
2276 some_nonuppercase_initial = 1;
2277 else
2278 some_multiletter_word = 1;
2280 else if (!NOCASEP (c))
2282 some_uppercase = 1;
2283 if (SYNTAX (prevc) != Sword)
2285 else
2286 some_multiletter_word = 1;
2288 else
2290 /* If the initial is a caseless word constituent,
2291 treat that like a lowercase initial. */
2292 if (SYNTAX (prevc) != Sword)
2293 some_nonuppercase_initial = 1;
2296 prevc = c;
2299 /* Convert to all caps if the old text is all caps
2300 and has at least one multiletter word. */
2301 if (! some_lowercase && some_multiletter_word)
2302 case_action = all_caps;
2303 /* Capitalize each word, if the old text has all capitalized words. */
2304 else if (!some_nonuppercase_initial && some_multiletter_word)
2305 case_action = cap_initial;
2306 else if (!some_nonuppercase_initial && some_uppercase)
2307 /* Should x -> yz, operating on X, give Yz or YZ?
2308 We'll assume the latter. */
2309 case_action = all_caps;
2310 else
2311 case_action = nochange;
2314 /* Do replacement in a string. */
2315 if (!NILP (string))
2317 Lisp_Object before, after;
2319 before = Fsubstring (string, make_number (0),
2320 make_number (search_regs.start[sub]));
2321 after = Fsubstring (string, make_number (search_regs.end[sub]), Qnil);
2323 /* Substitute parts of the match into NEWTEXT
2324 if desired. */
2325 if (NILP (literal))
2327 int lastpos = 0;
2328 int lastpos_byte = 0;
2329 /* We build up the substituted string in ACCUM. */
2330 Lisp_Object accum;
2331 Lisp_Object middle;
2332 int length = STRING_BYTES (XSTRING (newtext));
2334 accum = Qnil;
2336 for (pos_byte = 0, pos = 0; pos_byte < length;)
2338 int substart = -1;
2339 int subend;
2340 int delbackslash = 0;
2342 FETCH_STRING_CHAR_ADVANCE (c, newtext, pos, pos_byte);
2344 if (c == '\\')
2346 FETCH_STRING_CHAR_ADVANCE (c, newtext, pos, pos_byte);
2348 if (c == '&')
2350 substart = search_regs.start[sub];
2351 subend = search_regs.end[sub];
2353 else if (c >= '1' && c <= '9' && c <= search_regs.num_regs + '0')
2355 if (search_regs.start[c - '0'] >= 0)
2357 substart = search_regs.start[c - '0'];
2358 subend = search_regs.end[c - '0'];
2361 else if (c == '\\')
2362 delbackslash = 1;
2363 else
2364 error ("Invalid use of `\\' in replacement text");
2366 if (substart >= 0)
2368 if (pos - 2 != lastpos)
2369 middle = substring_both (newtext, lastpos,
2370 lastpos_byte,
2371 pos - 2, pos_byte - 2);
2372 else
2373 middle = Qnil;
2374 accum = concat3 (accum, middle,
2375 Fsubstring (string,
2376 make_number (substart),
2377 make_number (subend)));
2378 lastpos = pos;
2379 lastpos_byte = pos_byte;
2381 else if (delbackslash)
2383 middle = substring_both (newtext, lastpos,
2384 lastpos_byte,
2385 pos - 1, pos_byte - 1);
2387 accum = concat2 (accum, middle);
2388 lastpos = pos;
2389 lastpos_byte = pos_byte;
2393 if (pos != lastpos)
2394 middle = substring_both (newtext, lastpos,
2395 lastpos_byte,
2396 pos, pos_byte);
2397 else
2398 middle = Qnil;
2400 newtext = concat2 (accum, middle);
2403 /* Do case substitution in NEWTEXT if desired. */
2404 if (case_action == all_caps)
2405 newtext = Fupcase (newtext);
2406 else if (case_action == cap_initial)
2407 newtext = Fupcase_initials (newtext);
2409 return concat3 (before, newtext, after);
2412 /* Record point, the move (quietly) to the start of the match. */
2413 if (PT >= search_regs.end[sub])
2414 opoint = PT - ZV;
2415 else if (PT > search_regs.start[sub])
2416 opoint = search_regs.end[sub] - ZV;
2417 else
2418 opoint = PT;
2420 TEMP_SET_PT (search_regs.start[sub]);
2422 /* We insert the replacement text before the old text, and then
2423 delete the original text. This means that markers at the
2424 beginning or end of the original will float to the corresponding
2425 position in the replacement. */
2426 if (!NILP (literal))
2427 Finsert_and_inherit (1, &newtext);
2428 else
2430 int length = STRING_BYTES (XSTRING (newtext));
2431 unsigned char *substed;
2432 int substed_alloc_size, substed_len;
2433 int buf_multibyte = !NILP (current_buffer->enable_multibyte_characters);
2434 int str_multibyte = STRING_MULTIBYTE (newtext);
2435 Lisp_Object rev_tbl;
2437 rev_tbl= (!buf_multibyte && CHAR_TABLE_P (Vnonascii_translation_table)
2438 ? Fchar_table_extra_slot (Vnonascii_translation_table,
2439 make_number (0))
2440 : Qnil);
2442 substed_alloc_size = length * 2 + 100;
2443 substed = (unsigned char *) xmalloc (substed_alloc_size + 1);
2444 substed_len = 0;
2446 /* Go thru NEWTEXT, producing the actual text to insert in
2447 SUBSTED while adjusting multibyteness to that of the current
2448 buffer. */
2450 for (pos_byte = 0, pos = 0; pos_byte < length;)
2452 unsigned char str[MAX_MULTIBYTE_LENGTH];
2453 unsigned char *add_stuff = NULL;
2454 int add_len = 0;
2455 int idx = -1;
2457 if (str_multibyte)
2459 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, newtext, pos, pos_byte);
2460 if (!buf_multibyte)
2461 c = multibyte_char_to_unibyte (c, rev_tbl);
2463 else
2465 /* Note that we don't have to increment POS. */
2466 c = XSTRING (newtext)->data[pos_byte++];
2467 if (buf_multibyte)
2468 c = unibyte_char_to_multibyte (c);
2471 /* Either set ADD_STUFF and ADD_LEN to the text to put in SUBSTED,
2472 or set IDX to a match index, which means put that part
2473 of the buffer text into SUBSTED. */
2475 if (c == '\\')
2477 if (str_multibyte)
2479 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, newtext,
2480 pos, pos_byte);
2481 if (!buf_multibyte && !SINGLE_BYTE_CHAR_P (c))
2482 c = multibyte_char_to_unibyte (c, rev_tbl);
2484 else
2486 c = XSTRING (newtext)->data[pos_byte++];
2487 if (buf_multibyte)
2488 c = unibyte_char_to_multibyte (c);
2491 if (c == '&')
2492 idx = sub;
2493 else if (c >= '1' && c <= '9' && c <= search_regs.num_regs + '0')
2495 if (search_regs.start[c - '0'] >= 1)
2496 idx = c - '0';
2498 else if (c == '\\')
2499 add_len = 1, add_stuff = "\\";
2500 else
2502 xfree (substed);
2503 error ("Invalid use of `\\' in replacement text");
2506 else
2508 add_len = CHAR_STRING (c, str);
2509 add_stuff = str;
2512 /* If we want to copy part of a previous match,
2513 set up ADD_STUFF and ADD_LEN to point to it. */
2514 if (idx >= 0)
2516 int begbyte = CHAR_TO_BYTE (search_regs.start[idx]);
2517 add_len = CHAR_TO_BYTE (search_regs.end[idx]) - begbyte;
2518 if (search_regs.start[idx] < GPT && GPT < search_regs.end[idx])
2519 move_gap (search_regs.start[idx]);
2520 add_stuff = BYTE_POS_ADDR (begbyte);
2523 /* Now the stuff we want to add to SUBSTED
2524 is invariably ADD_LEN bytes starting at ADD_STUFF. */
2526 /* Make sure SUBSTED is big enough. */
2527 if (substed_len + add_len >= substed_alloc_size)
2529 substed_alloc_size = substed_len + add_len + 500;
2530 substed = (unsigned char *) xrealloc (substed,
2531 substed_alloc_size + 1);
2534 /* Now add to the end of SUBSTED. */
2535 if (add_stuff)
2537 bcopy (add_stuff, substed + substed_len, add_len);
2538 substed_len += add_len;
2542 /* Now insert what we accumulated. */
2543 insert_and_inherit (substed, substed_len);
2545 xfree (substed);
2548 inslen = PT - (search_regs.start[sub]);
2549 del_range (search_regs.start[sub] + inslen, search_regs.end[sub] + inslen);
2551 if (case_action == all_caps)
2552 Fupcase_region (make_number (PT - inslen), make_number (PT));
2553 else if (case_action == cap_initial)
2554 Fupcase_initials_region (make_number (PT - inslen), make_number (PT));
2556 newpoint = PT;
2558 /* Put point back where it was in the text. */
2559 if (opoint <= 0)
2560 TEMP_SET_PT (opoint + ZV);
2561 else
2562 TEMP_SET_PT (opoint);
2564 /* Now move point "officially" to the start of the inserted replacement. */
2565 move_if_not_intangible (newpoint);
2567 return Qnil;
2570 static Lisp_Object
2571 match_limit (num, beginningp)
2572 Lisp_Object num;
2573 int beginningp;
2575 register int n;
2577 CHECK_NUMBER (num, 0);
2578 n = XINT (num);
2579 if (n < 0 || n >= search_regs.num_regs)
2580 args_out_of_range (num, make_number (search_regs.num_regs));
2581 if (search_regs.num_regs <= 0
2582 || search_regs.start[n] < 0)
2583 return Qnil;
2584 return (make_number ((beginningp) ? search_regs.start[n]
2585 : search_regs.end[n]));
2588 DEFUN ("match-beginning", Fmatch_beginning, Smatch_beginning, 1, 1, 0,
2589 "Return position of start of text matched by last search.\n\
2590 SUBEXP, a number, specifies which parenthesized expression in the last\n\
2591 regexp.\n\
2592 Value is nil if SUBEXPth pair didn't match, or there were less than\n\
2593 SUBEXP pairs.\n\
2594 Zero means the entire text matched by the whole regexp or whole string.")
2595 (subexp)
2596 Lisp_Object subexp;
2598 return match_limit (subexp, 1);
2601 DEFUN ("match-end", Fmatch_end, Smatch_end, 1, 1, 0,
2602 "Return position of end of text matched by last search.\n\
2603 SUBEXP, a number, specifies which parenthesized expression in the last\n\
2604 regexp.\n\
2605 Value is nil if SUBEXPth pair didn't match, or there were less than\n\
2606 SUBEXP pairs.\n\
2607 Zero means the entire text matched by the whole regexp or whole string.")
2608 (subexp)
2609 Lisp_Object subexp;
2611 return match_limit (subexp, 0);
2614 DEFUN ("match-data", Fmatch_data, Smatch_data, 0, 2, 0,
2615 "Return a list containing all info on what the last search matched.\n\
2616 Element 2N is `(match-beginning N)'; element 2N + 1 is `(match-end N)'.\n\
2617 All the elements are markers or nil (nil if the Nth pair didn't match)\n\
2618 if the last match was on a buffer; integers or nil if a string was matched.\n\
2619 Use `store-match-data' to reinstate the data in this list.\n\
2621 If INTEGERS (the optional first argument) is non-nil, always use integers\n\
2622 \(rather than markers) to represent buffer positions.\n\
2623 If REUSE is a list, reuse it as part of the value. If REUSE is long enough\n\
2624 to hold all the values, and if INTEGERS is non-nil, no consing is done.")
2625 (integers, reuse)
2626 Lisp_Object integers, reuse;
2628 Lisp_Object tail, prev;
2629 Lisp_Object *data;
2630 int i, len;
2632 if (NILP (last_thing_searched))
2633 return Qnil;
2635 data = (Lisp_Object *) alloca ((2 * search_regs.num_regs)
2636 * sizeof (Lisp_Object));
2638 len = -1;
2639 for (i = 0; i < search_regs.num_regs; i++)
2641 int start = search_regs.start[i];
2642 if (start >= 0)
2644 if (EQ (last_thing_searched, Qt)
2645 || ! NILP (integers))
2647 XSETFASTINT (data[2 * i], start);
2648 XSETFASTINT (data[2 * i + 1], search_regs.end[i]);
2650 else if (BUFFERP (last_thing_searched))
2652 data[2 * i] = Fmake_marker ();
2653 Fset_marker (data[2 * i],
2654 make_number (start),
2655 last_thing_searched);
2656 data[2 * i + 1] = Fmake_marker ();
2657 Fset_marker (data[2 * i + 1],
2658 make_number (search_regs.end[i]),
2659 last_thing_searched);
2661 else
2662 /* last_thing_searched must always be Qt, a buffer, or Qnil. */
2663 abort ();
2665 len = i;
2667 else
2668 data[2 * i] = data [2 * i + 1] = Qnil;
2671 /* If REUSE is not usable, cons up the values and return them. */
2672 if (! CONSP (reuse))
2673 return Flist (2 * len + 2, data);
2675 /* If REUSE is a list, store as many value elements as will fit
2676 into the elements of REUSE. */
2677 for (i = 0, tail = reuse; CONSP (tail);
2678 i++, tail = XCDR (tail))
2680 if (i < 2 * len + 2)
2681 XCAR (tail) = data[i];
2682 else
2683 XCAR (tail) = Qnil;
2684 prev = tail;
2687 /* If we couldn't fit all value elements into REUSE,
2688 cons up the rest of them and add them to the end of REUSE. */
2689 if (i < 2 * len + 2)
2690 XCDR (prev) = Flist (2 * len + 2 - i, data + i);
2692 return reuse;
2696 DEFUN ("set-match-data", Fset_match_data, Sset_match_data, 1, 1, 0,
2697 "Set internal data on last search match from elements of LIST.\n\
2698 LIST should have been created by calling `match-data' previously.")
2699 (list)
2700 register Lisp_Object list;
2702 register int i;
2703 register Lisp_Object marker;
2705 if (running_asynch_code)
2706 save_search_regs ();
2708 if (!CONSP (list) && !NILP (list))
2709 list = wrong_type_argument (Qconsp, list);
2711 /* Unless we find a marker with a buffer in LIST, assume that this
2712 match data came from a string. */
2713 last_thing_searched = Qt;
2715 /* Allocate registers if they don't already exist. */
2717 int length = XFASTINT (Flength (list)) / 2;
2719 if (length > search_regs.num_regs)
2721 if (search_regs.num_regs == 0)
2723 search_regs.start
2724 = (regoff_t *) xmalloc (length * sizeof (regoff_t));
2725 search_regs.end
2726 = (regoff_t *) xmalloc (length * sizeof (regoff_t));
2728 else
2730 search_regs.start
2731 = (regoff_t *) xrealloc (search_regs.start,
2732 length * sizeof (regoff_t));
2733 search_regs.end
2734 = (regoff_t *) xrealloc (search_regs.end,
2735 length * sizeof (regoff_t));
2738 search_regs.num_regs = length;
2742 for (i = 0; i < search_regs.num_regs; i++)
2744 marker = Fcar (list);
2745 if (NILP (marker))
2747 search_regs.start[i] = -1;
2748 list = Fcdr (list);
2750 else
2752 if (MARKERP (marker))
2754 if (XMARKER (marker)->buffer == 0)
2755 XSETFASTINT (marker, 0);
2756 else
2757 XSETBUFFER (last_thing_searched, XMARKER (marker)->buffer);
2760 CHECK_NUMBER_COERCE_MARKER (marker, 0);
2761 search_regs.start[i] = XINT (marker);
2762 list = Fcdr (list);
2764 marker = Fcar (list);
2765 if (MARKERP (marker) && XMARKER (marker)->buffer == 0)
2766 XSETFASTINT (marker, 0);
2768 CHECK_NUMBER_COERCE_MARKER (marker, 0);
2769 search_regs.end[i] = XINT (marker);
2771 list = Fcdr (list);
2774 return Qnil;
2777 /* If non-zero the match data have been saved in saved_search_regs
2778 during the execution of a sentinel or filter. */
2779 static int search_regs_saved;
2780 static struct re_registers saved_search_regs;
2782 /* Called from Flooking_at, Fstring_match, search_buffer, Fstore_match_data
2783 if asynchronous code (filter or sentinel) is running. */
2784 static void
2785 save_search_regs ()
2787 if (!search_regs_saved)
2789 saved_search_regs.num_regs = search_regs.num_regs;
2790 saved_search_regs.start = search_regs.start;
2791 saved_search_regs.end = search_regs.end;
2792 search_regs.num_regs = 0;
2793 search_regs.start = 0;
2794 search_regs.end = 0;
2796 search_regs_saved = 1;
2800 /* Called upon exit from filters and sentinels. */
2801 void
2802 restore_match_data ()
2804 if (search_regs_saved)
2806 if (search_regs.num_regs > 0)
2808 xfree (search_regs.start);
2809 xfree (search_regs.end);
2811 search_regs.num_regs = saved_search_regs.num_regs;
2812 search_regs.start = saved_search_regs.start;
2813 search_regs.end = saved_search_regs.end;
2815 search_regs_saved = 0;
2819 /* Quote a string to inactivate reg-expr chars */
2821 DEFUN ("regexp-quote", Fregexp_quote, Sregexp_quote, 1, 1, 0,
2822 "Return a regexp string which matches exactly STRING and nothing else.")
2823 (string)
2824 Lisp_Object string;
2826 register unsigned char *in, *out, *end;
2827 register unsigned char *temp;
2828 int backslashes_added = 0;
2830 CHECK_STRING (string, 0);
2832 temp = (unsigned char *) alloca (STRING_BYTES (XSTRING (string)) * 2);
2834 /* Now copy the data into the new string, inserting escapes. */
2836 in = XSTRING (string)->data;
2837 end = in + STRING_BYTES (XSTRING (string));
2838 out = temp;
2840 for (; in != end; in++)
2842 if (*in == '[' || *in == ']'
2843 || *in == '*' || *in == '.' || *in == '\\'
2844 || *in == '?' || *in == '+'
2845 || *in == '^' || *in == '$')
2846 *out++ = '\\', backslashes_added++;
2847 *out++ = *in;
2850 return make_specified_string (temp,
2851 XSTRING (string)->size + backslashes_added,
2852 out - temp,
2853 STRING_MULTIBYTE (string));
2856 void
2857 syms_of_search ()
2859 register int i;
2861 for (i = 0; i < REGEXP_CACHE_SIZE; ++i)
2863 searchbufs[i].buf.allocated = 100;
2864 searchbufs[i].buf.buffer = (unsigned char *) malloc (100);
2865 searchbufs[i].buf.fastmap = searchbufs[i].fastmap;
2866 searchbufs[i].regexp = Qnil;
2867 staticpro (&searchbufs[i].regexp);
2868 searchbufs[i].next = (i == REGEXP_CACHE_SIZE-1 ? 0 : &searchbufs[i+1]);
2870 searchbuf_head = &searchbufs[0];
2872 Qsearch_failed = intern ("search-failed");
2873 staticpro (&Qsearch_failed);
2874 Qinvalid_regexp = intern ("invalid-regexp");
2875 staticpro (&Qinvalid_regexp);
2877 Fput (Qsearch_failed, Qerror_conditions,
2878 Fcons (Qsearch_failed, Fcons (Qerror, Qnil)));
2879 Fput (Qsearch_failed, Qerror_message,
2880 build_string ("Search failed"));
2882 Fput (Qinvalid_regexp, Qerror_conditions,
2883 Fcons (Qinvalid_regexp, Fcons (Qerror, Qnil)));
2884 Fput (Qinvalid_regexp, Qerror_message,
2885 build_string ("Invalid regexp"));
2887 last_thing_searched = Qnil;
2888 staticpro (&last_thing_searched);
2890 defsubr (&Slooking_at);
2891 defsubr (&Sposix_looking_at);
2892 defsubr (&Sstring_match);
2893 defsubr (&Sposix_string_match);
2894 defsubr (&Ssearch_forward);
2895 defsubr (&Ssearch_backward);
2896 defsubr (&Sword_search_forward);
2897 defsubr (&Sword_search_backward);
2898 defsubr (&Sre_search_forward);
2899 defsubr (&Sre_search_backward);
2900 defsubr (&Sposix_search_forward);
2901 defsubr (&Sposix_search_backward);
2902 defsubr (&Sreplace_match);
2903 defsubr (&Smatch_beginning);
2904 defsubr (&Smatch_end);
2905 defsubr (&Smatch_data);
2906 defsubr (&Sset_match_data);
2907 defsubr (&Sregexp_quote);