(wait_reading_process_input): If wait_for_cell,
[bpt/emacs.git] / src / search.c
CommitLineData
ca1d1d23 1/* String search routines for GNU Emacs.
3a22ee35 2 Copyright (C) 1985, 1986, 1987, 1993, 1994 Free Software Foundation, Inc.
ca1d1d23
JB
3
4This file is part of GNU Emacs.
5
6GNU Emacs is free software; you can redistribute it and/or modify
7it under the terms of the GNU General Public License as published by
7c938215 8the Free Software Foundation; either version 2, or (at your option)
ca1d1d23
JB
9any later version.
10
11GNU Emacs is distributed in the hope that it will be useful,
12but WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14GNU General Public License for more details.
15
16You should have received a copy of the GNU General Public License
17along with GNU Emacs; see the file COPYING. If not, write to
3b7ad313
EN
18the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19Boston, MA 02111-1307, USA. */
ca1d1d23
JB
20
21
18160b98 22#include <config.h>
ca1d1d23
JB
23#include "lisp.h"
24#include "syntax.h"
5679531d 25#include "category.h"
ca1d1d23 26#include "buffer.h"
5679531d 27#include "charset.h"
9169c321 28#include "region-cache.h"
ca1d1d23 29#include "commands.h"
9ac0d9e0 30#include "blockinput.h"
4746118a 31
ca1d1d23
JB
32#include <sys/types.h>
33#include "regex.h"
34
1d288aef 35#define REGEXP_CACHE_SIZE 20
ca1d1d23 36
487282dc
KH
37/* If the regexp is non-nil, then the buffer contains the compiled form
38 of that regexp, suitable for searching. */
1d288aef
RS
39struct regexp_cache
40{
487282dc
KH
41 struct regexp_cache *next;
42 Lisp_Object regexp;
43 struct re_pattern_buffer buf;
44 char fastmap[0400];
b819a390
RS
45 /* Nonzero means regexp was compiled to do full POSIX backtracking. */
46 char posix;
487282dc 47};
ca1d1d23 48
487282dc
KH
49/* The instances of that struct. */
50struct regexp_cache searchbufs[REGEXP_CACHE_SIZE];
ca1d1d23 51
487282dc
KH
52/* The head of the linked list; points to the most recently used buffer. */
53struct regexp_cache *searchbuf_head;
ca1d1d23 54
ca1d1d23 55
4746118a
JB
56/* Every call to re_match, etc., must pass &search_regs as the regs
57 argument unless you can show it is unnecessary (i.e., if re_match
58 is certainly going to be called again before region-around-match
59 can be called).
60
61 Since the registers are now dynamically allocated, we need to make
62 sure not to refer to the Nth register before checking that it has
1113d9db
JB
63 been allocated by checking search_regs.num_regs.
64
65 The regex code keeps track of whether it has allocated the search
487282dc
KH
66 buffer using bits in the re_pattern_buffer. This means that whenever
67 you compile a new pattern, it completely forgets whether it has
1113d9db
JB
68 allocated any registers, and will allocate new registers the next
69 time you call a searching or matching function. Therefore, we need
70 to call re_set_registers after compiling a new pattern or after
71 setting the match registers, so that the regex functions will be
72 able to free or re-allocate it properly. */
ca1d1d23
JB
73static struct re_registers search_regs;
74
daa37602
JB
75/* The buffer in which the last search was performed, or
76 Qt if the last search was done in a string;
77 Qnil if no searching has been done yet. */
78static Lisp_Object last_thing_searched;
ca1d1d23 79
8e6208c5 80/* error condition signaled when regexp compile_pattern fails */
ca1d1d23
JB
81
82Lisp_Object Qinvalid_regexp;
83
ca325161 84static void set_search_regs ();
044f81f1 85static void save_search_regs ();
ca325161 86
b819a390
RS
87static int search_buffer ();
88
ca1d1d23
JB
89static void
90matcher_overflow ()
91{
92 error ("Stack overflow in regexp matcher");
93}
94
95#ifdef __STDC__
96#define CONST const
97#else
98#define CONST
99#endif
100
b819a390
RS
101/* Compile a regexp and signal a Lisp error if anything goes wrong.
102 PATTERN is the pattern to compile.
103 CP is the place to put the result.
104 TRANSLATE is a translation table for ignoring case, or NULL for none.
105 REGP is the structure that says where to store the "register"
106 values that will result from matching this pattern.
107 If it is 0, we should compile the pattern not to record any
108 subexpression bounds.
109 POSIX is nonzero if we want full backtracking (POSIX style)
5679531d
KH
110 for this pattern. 0 means backtrack only enough to get a valid match.
111 MULTIBYTE is nonzero if we want to handle multibyte characters in
112 PATTERN. 0 means all multibyte characters are recognized just as
113 sequences of binary data. */
ca1d1d23 114
487282dc 115static void
5679531d 116compile_pattern_1 (cp, pattern, translate, regp, posix, multibyte)
487282dc 117 struct regexp_cache *cp;
ca1d1d23 118 Lisp_Object pattern;
b1428bd8 119 Lisp_Object *translate;
487282dc 120 struct re_registers *regp;
b819a390 121 int posix;
5679531d 122 int multibyte;
ca1d1d23
JB
123{
124 CONST char *val;
b819a390 125 reg_syntax_t old;
ca1d1d23 126
487282dc
KH
127 cp->regexp = Qnil;
128 cp->buf.translate = translate;
b819a390 129 cp->posix = posix;
5679531d 130 cp->buf.multibyte = multibyte;
9ac0d9e0 131 BLOCK_INPUT;
b819a390
RS
132 old = re_set_syntax (RE_SYNTAX_EMACS
133 | (posix ? 0 : RE_NO_POSIX_BACKTRACKING));
b90d9e80 134 val = (CONST char *) re_compile_pattern ((char *) XSTRING (pattern)->data,
487282dc 135 XSTRING (pattern)->size, &cp->buf);
b819a390 136 re_set_syntax (old);
9ac0d9e0 137 UNBLOCK_INPUT;
ca1d1d23 138 if (val)
487282dc 139 Fsignal (Qinvalid_regexp, Fcons (build_string (val), Qnil));
1113d9db 140
487282dc 141 cp->regexp = Fcopy_sequence (pattern);
487282dc
KH
142}
143
144/* Compile a regexp if necessary, but first check to see if there's one in
b819a390
RS
145 the cache.
146 PATTERN is the pattern to compile.
147 TRANSLATE is a translation table for ignoring case, or NULL for none.
148 REGP is the structure that says where to store the "register"
149 values that will result from matching this pattern.
150 If it is 0, we should compile the pattern not to record any
151 subexpression bounds.
152 POSIX is nonzero if we want full backtracking (POSIX style)
153 for this pattern. 0 means backtrack only enough to get a valid match. */
487282dc
KH
154
155struct re_pattern_buffer *
b819a390 156compile_pattern (pattern, regp, translate, posix)
487282dc
KH
157 Lisp_Object pattern;
158 struct re_registers *regp;
b1428bd8 159 Lisp_Object *translate;
b819a390 160 int posix;
487282dc
KH
161{
162 struct regexp_cache *cp, **cpp;
5679531d
KH
163 /* Should we check it here, or add an argument `multibyte' to this
164 function? */
165 int multibyte = !NILP (current_buffer->enable_multibyte_characters);
487282dc
KH
166
167 for (cpp = &searchbuf_head; ; cpp = &cp->next)
168 {
169 cp = *cpp;
1d288aef
RS
170 if (XSTRING (cp->regexp)->size == XSTRING (pattern)->size
171 && !NILP (Fstring_equal (cp->regexp, pattern))
b819a390 172 && cp->buf.translate == translate
5679531d
KH
173 && cp->posix == posix
174 && cp->buf.multibyte == multibyte)
487282dc
KH
175 break;
176
177 /* If we're at the end of the cache, compile into the last cell. */
178 if (cp->next == 0)
179 {
5679531d 180 compile_pattern_1 (cp, pattern, translate, regp, posix, multibyte);
487282dc
KH
181 break;
182 }
183 }
184
185 /* When we get here, cp (aka *cpp) contains the compiled pattern,
186 either because we found it in the cache or because we just compiled it.
187 Move it to the front of the queue to mark it as most recently used. */
188 *cpp = cp->next;
189 cp->next = searchbuf_head;
190 searchbuf_head = cp;
1113d9db 191
6639708c
RS
192 /* Advise the searching functions about the space we have allocated
193 for register data. */
194 if (regp)
195 re_set_registers (&cp->buf, regp, regp->num_regs, regp->start, regp->end);
196
487282dc 197 return &cp->buf;
ca1d1d23
JB
198}
199
200/* Error condition used for failing searches */
201Lisp_Object Qsearch_failed;
202
203Lisp_Object
204signal_failure (arg)
205 Lisp_Object arg;
206{
207 Fsignal (Qsearch_failed, Fcons (arg, Qnil));
208 return Qnil;
209}
210\f
b819a390
RS
211static Lisp_Object
212looking_at_1 (string, posix)
ca1d1d23 213 Lisp_Object string;
b819a390 214 int posix;
ca1d1d23
JB
215{
216 Lisp_Object val;
217 unsigned char *p1, *p2;
218 int s1, s2;
219 register int i;
487282dc 220 struct re_pattern_buffer *bufp;
ca1d1d23 221
7074fde6
FP
222 if (running_asynch_code)
223 save_search_regs ();
224
ca1d1d23 225 CHECK_STRING (string, 0);
487282dc
KH
226 bufp = compile_pattern (string, &search_regs,
227 (!NILP (current_buffer->case_fold_search)
b819a390
RS
228 ? DOWNCASE_TABLE : 0),
229 posix);
ca1d1d23
JB
230
231 immediate_quit = 1;
232 QUIT; /* Do a pending quit right away, to avoid paradoxical behavior */
233
234 /* Get pointers and sizes of the two strings
235 that make up the visible portion of the buffer. */
236
237 p1 = BEGV_ADDR;
238 s1 = GPT - BEGV;
239 p2 = GAP_END_ADDR;
240 s2 = ZV - GPT;
241 if (s1 < 0)
242 {
243 p2 = p1;
244 s2 = ZV - BEGV;
245 s1 = 0;
246 }
247 if (s2 < 0)
248 {
249 s1 = ZV - BEGV;
250 s2 = 0;
251 }
252
487282dc 253 i = re_match_2 (bufp, (char *) p1, s1, (char *) p2, s2,
6ec8bbd2 254 PT - BEGV, &search_regs,
ca1d1d23
JB
255 ZV - BEGV);
256 if (i == -2)
257 matcher_overflow ();
258
259 val = (0 <= i ? Qt : Qnil);
4746118a 260 for (i = 0; i < search_regs.num_regs; i++)
ca1d1d23
JB
261 if (search_regs.start[i] >= 0)
262 {
263 search_regs.start[i] += BEGV;
264 search_regs.end[i] += BEGV;
265 }
a3668d92 266 XSETBUFFER (last_thing_searched, current_buffer);
ca1d1d23
JB
267 immediate_quit = 0;
268 return val;
269}
270
b819a390 271DEFUN ("looking-at", Flooking_at, Slooking_at, 1, 1, 0,
94f94972 272 "Return t if text after point matches regular expression REGEXP.\n\
b819a390
RS
273This function modifies the match data that `match-beginning',\n\
274`match-end' and `match-data' access; save and restore the match\n\
275data if you want to preserve them.")
94f94972
RS
276 (regexp)
277 Lisp_Object regexp;
b819a390 278{
94f94972 279 return looking_at_1 (regexp, 0);
b819a390
RS
280}
281
282DEFUN ("posix-looking-at", Fposix_looking_at, Sposix_looking_at, 1, 1, 0,
94f94972 283 "Return t if text after point matches regular expression REGEXP.\n\
b819a390
RS
284Find the longest match, in accord with Posix regular expression rules.\n\
285This function modifies the match data that `match-beginning',\n\
286`match-end' and `match-data' access; save and restore the match\n\
287data if you want to preserve them.")
94f94972
RS
288 (regexp)
289 Lisp_Object regexp;
b819a390 290{
94f94972 291 return looking_at_1 (regexp, 1);
b819a390
RS
292}
293\f
294static Lisp_Object
295string_match_1 (regexp, string, start, posix)
ca1d1d23 296 Lisp_Object regexp, string, start;
b819a390 297 int posix;
ca1d1d23
JB
298{
299 int val;
300 int s;
487282dc 301 struct re_pattern_buffer *bufp;
ca1d1d23 302
7074fde6
FP
303 if (running_asynch_code)
304 save_search_regs ();
305
ca1d1d23
JB
306 CHECK_STRING (regexp, 0);
307 CHECK_STRING (string, 1);
308
309 if (NILP (start))
310 s = 0;
311 else
312 {
313 int len = XSTRING (string)->size;
314
315 CHECK_NUMBER (start, 2);
316 s = XINT (start);
317 if (s < 0 && -s <= len)
26faf9f4 318 s = len + s;
ca1d1d23
JB
319 else if (0 > s || s > len)
320 args_out_of_range (string, start);
321 }
322
487282dc
KH
323 bufp = compile_pattern (regexp, &search_regs,
324 (!NILP (current_buffer->case_fold_search)
b819a390 325 ? DOWNCASE_TABLE : 0),
24b704fa 326 posix);
ca1d1d23 327 immediate_quit = 1;
487282dc 328 val = re_search (bufp, (char *) XSTRING (string)->data,
ca1d1d23
JB
329 XSTRING (string)->size, s, XSTRING (string)->size - s,
330 &search_regs);
331 immediate_quit = 0;
daa37602 332 last_thing_searched = Qt;
ca1d1d23
JB
333 if (val == -2)
334 matcher_overflow ();
335 if (val < 0) return Qnil;
336 return make_number (val);
337}
e59a8453 338
b819a390
RS
339DEFUN ("string-match", Fstring_match, Sstring_match, 2, 3, 0,
340 "Return index of start of first match for REGEXP in STRING, or nil.\n\
341If third arg START is non-nil, start search at that index in STRING.\n\
342For index of first char beyond the match, do (match-end 0).\n\
343`match-end' and `match-beginning' also give indices of substrings\n\
344matched by parenthesis constructs in the pattern.")
345 (regexp, string, start)
346 Lisp_Object regexp, string, start;
347{
348 return string_match_1 (regexp, string, start, 0);
349}
350
351DEFUN ("posix-string-match", Fposix_string_match, Sposix_string_match, 2, 3, 0,
352 "Return index of start of first match for REGEXP in STRING, or nil.\n\
353Find the longest match, in accord with Posix regular expression rules.\n\
354If third arg START is non-nil, start search at that index in STRING.\n\
355For index of first char beyond the match, do (match-end 0).\n\
356`match-end' and `match-beginning' also give indices of substrings\n\
357matched by parenthesis constructs in the pattern.")
358 (regexp, string, start)
359 Lisp_Object regexp, string, start;
360{
361 return string_match_1 (regexp, string, start, 1);
362}
363
e59a8453
RS
364/* Match REGEXP against STRING, searching all of STRING,
365 and return the index of the match, or negative on failure.
366 This does not clobber the match data. */
367
368int
369fast_string_match (regexp, string)
370 Lisp_Object regexp, string;
371{
372 int val;
487282dc 373 struct re_pattern_buffer *bufp;
e59a8453 374
b819a390 375 bufp = compile_pattern (regexp, 0, 0, 0);
e59a8453 376 immediate_quit = 1;
487282dc 377 val = re_search (bufp, (char *) XSTRING (string)->data,
e59a8453
RS
378 XSTRING (string)->size, 0, XSTRING (string)->size,
379 0);
380 immediate_quit = 0;
381 return val;
382}
5679531d
KH
383
384/* Match REGEXP against STRING, searching all of STRING ignoring case,
385 and return the index of the match, or negative on failure.
386 This does not clobber the match data. */
387
388extern Lisp_Object Vascii_downcase_table;
389
390int
391fast_string_match_ignore_case (regexp, string)
392 Lisp_Object regexp;
393 char *string;
394{
395 int val;
396 struct re_pattern_buffer *bufp;
397 int len = strlen (string);
398
399 bufp = compile_pattern (regexp, 0,
400 XCHAR_TABLE (Vascii_downcase_table)->contents, 0);
401 immediate_quit = 1;
402 val = re_search (bufp, string, len, 0, len, 0);
403 immediate_quit = 0;
404 return val;
405}
ca1d1d23 406\f
9169c321
JB
407/* max and min. */
408
409static int
410max (a, b)
411 int a, b;
412{
413 return ((a > b) ? a : b);
414}
415
416static int
417min (a, b)
418 int a, b;
419{
420 return ((a < b) ? a : b);
421}
422
423\f
424/* The newline cache: remembering which sections of text have no newlines. */
425
426/* If the user has requested newline caching, make sure it's on.
427 Otherwise, make sure it's off.
428 This is our cheezy way of associating an action with the change of
429 state of a buffer-local variable. */
430static void
431newline_cache_on_off (buf)
432 struct buffer *buf;
433{
434 if (NILP (buf->cache_long_line_scans))
435 {
436 /* It should be off. */
437 if (buf->newline_cache)
438 {
439 free_region_cache (buf->newline_cache);
440 buf->newline_cache = 0;
441 }
442 }
443 else
444 {
445 /* It should be on. */
446 if (buf->newline_cache == 0)
447 buf->newline_cache = new_region_cache ();
448 }
449}
450
451\f
452/* Search for COUNT instances of the character TARGET between START and END.
453
454 If COUNT is positive, search forwards; END must be >= START.
455 If COUNT is negative, search backwards for the -COUNTth instance;
456 END must be <= START.
457 If COUNT is zero, do anything you please; run rogue, for all I care.
458
459 If END is zero, use BEGV or ZV instead, as appropriate for the
460 direction indicated by COUNT.
ffd56f97
JB
461
462 If we find COUNT instances, set *SHORTAGE to zero, and return the
5bfe95c9
RS
463 position after the COUNTth match. Note that for reverse motion
464 this is not the same as the usual convention for Emacs motion commands.
ffd56f97 465
9169c321
JB
466 If we don't find COUNT instances before reaching END, set *SHORTAGE
467 to the number of TARGETs left unfound, and return END.
ffd56f97 468
087a5f81
RS
469 If ALLOW_QUIT is non-zero, set immediate_quit. That's good to do
470 except when inside redisplay. */
471
9169c321
JB
472scan_buffer (target, start, end, count, shortage, allow_quit)
473 register int target;
474 int start, end;
475 int count;
476 int *shortage;
087a5f81 477 int allow_quit;
ca1d1d23 478{
9169c321
JB
479 struct region_cache *newline_cache;
480 int direction;
ffd56f97 481
9169c321
JB
482 if (count > 0)
483 {
484 direction = 1;
485 if (! end) end = ZV;
486 }
487 else
488 {
489 direction = -1;
490 if (! end) end = BEGV;
491 }
ffd56f97 492
9169c321
JB
493 newline_cache_on_off (current_buffer);
494 newline_cache = current_buffer->newline_cache;
ca1d1d23
JB
495
496 if (shortage != 0)
497 *shortage = 0;
498
087a5f81 499 immediate_quit = allow_quit;
ca1d1d23 500
ffd56f97 501 if (count > 0)
9169c321 502 while (start != end)
ca1d1d23 503 {
9169c321
JB
504 /* Our innermost scanning loop is very simple; it doesn't know
505 about gaps, buffer ends, or the newline cache. ceiling is
506 the position of the last character before the next such
507 obstacle --- the last character the dumb search loop should
508 examine. */
509 register int ceiling = end - 1;
510
511 /* If we're looking for a newline, consult the newline cache
512 to see where we can avoid some scanning. */
513 if (target == '\n' && newline_cache)
514 {
515 int next_change;
516 immediate_quit = 0;
517 while (region_cache_forward
518 (current_buffer, newline_cache, start, &next_change))
519 start = next_change;
cbe0db0d 520 immediate_quit = allow_quit;
9169c321
JB
521
522 /* start should never be after end. */
523 if (start >= end)
524 start = end - 1;
525
526 /* Now the text after start is an unknown region, and
527 next_change is the position of the next known region. */
528 ceiling = min (next_change - 1, ceiling);
529 }
530
531 /* The dumb loop can only scan text stored in contiguous
532 bytes. BUFFER_CEILING_OF returns the last character
533 position that is contiguous, so the ceiling is the
534 position after that. */
535 ceiling = min (BUFFER_CEILING_OF (start), ceiling);
536
537 {
538 /* The termination address of the dumb loop. */
5679531d
KH
539 register unsigned char *ceiling_addr = POS_ADDR (ceiling) + 1;
540 register unsigned char *cursor = POS_ADDR (start);
9169c321
JB
541 unsigned char *base = cursor;
542
543 while (cursor < ceiling_addr)
544 {
545 unsigned char *scan_start = cursor;
546
547 /* The dumb loop. */
548 while (*cursor != target && ++cursor < ceiling_addr)
549 ;
550
551 /* If we're looking for newlines, cache the fact that
552 the region from start to cursor is free of them. */
553 if (target == '\n' && newline_cache)
554 know_region_cache (current_buffer, newline_cache,
555 start + scan_start - base,
556 start + cursor - base);
557
558 /* Did we find the target character? */
559 if (cursor < ceiling_addr)
560 {
561 if (--count == 0)
562 {
563 immediate_quit = 0;
564 return (start + cursor - base + 1);
565 }
566 cursor++;
567 }
568 }
569
570 start += cursor - base;
571 }
ca1d1d23
JB
572 }
573 else
9169c321
JB
574 while (start > end)
575 {
576 /* The last character to check before the next obstacle. */
577 register int ceiling = end;
578
579 /* Consult the newline cache, if appropriate. */
580 if (target == '\n' && newline_cache)
581 {
582 int next_change;
583 immediate_quit = 0;
584 while (region_cache_backward
585 (current_buffer, newline_cache, start, &next_change))
586 start = next_change;
cbe0db0d 587 immediate_quit = allow_quit;
9169c321
JB
588
589 /* Start should never be at or before end. */
590 if (start <= end)
591 start = end + 1;
592
593 /* Now the text before start is an unknown region, and
594 next_change is the position of the next known region. */
595 ceiling = max (next_change, ceiling);
596 }
597
598 /* Stop scanning before the gap. */
599 ceiling = max (BUFFER_FLOOR_OF (start - 1), ceiling);
600
601 {
602 /* The termination address of the dumb loop. */
5679531d
KH
603 register unsigned char *ceiling_addr = POS_ADDR (ceiling);
604 register unsigned char *cursor = POS_ADDR (start - 1);
9169c321
JB
605 unsigned char *base = cursor;
606
607 while (cursor >= ceiling_addr)
608 {
609 unsigned char *scan_start = cursor;
610
611 while (*cursor != target && --cursor >= ceiling_addr)
612 ;
613
614 /* If we're looking for newlines, cache the fact that
615 the region from after the cursor to start is free of them. */
616 if (target == '\n' && newline_cache)
617 know_region_cache (current_buffer, newline_cache,
618 start + cursor - base,
619 start + scan_start - base);
620
621 /* Did we find the target character? */
622 if (cursor >= ceiling_addr)
623 {
624 if (++count >= 0)
625 {
626 immediate_quit = 0;
627 return (start + cursor - base);
628 }
629 cursor--;
630 }
631 }
632
633 start += cursor - base;
634 }
635 }
636
ca1d1d23
JB
637 immediate_quit = 0;
638 if (shortage != 0)
ffd56f97 639 *shortage = count * direction;
9169c321 640 return start;
ca1d1d23
JB
641}
642
63fa018d
RS
643int
644find_next_newline_no_quit (from, cnt)
645 register int from, cnt;
646{
9169c321 647 return scan_buffer ('\n', from, 0, cnt, (int *) 0, 0);
63fa018d
RS
648}
649
ca1d1d23
JB
650int
651find_next_newline (from, cnt)
652 register int from, cnt;
653{
9169c321
JB
654 return scan_buffer ('\n', from, 0, cnt, (int *) 0, 1);
655}
656
657
658/* Like find_next_newline, but returns position before the newline,
659 not after, and only search up to TO. This isn't just
660 find_next_newline (...)-1, because you might hit TO. */
661int
662find_before_next_newline (from, to, cnt)
cbe0db0d 663 int from, to, cnt;
9169c321
JB
664{
665 int shortage;
666 int pos = scan_buffer ('\n', from, to, cnt, &shortage, 1);
667
668 if (shortage == 0)
669 pos--;
670
671 return pos;
ca1d1d23
JB
672}
673\f
c1dc99a1
JB
674Lisp_Object skip_chars ();
675
ca1d1d23 676DEFUN ("skip-chars-forward", Fskip_chars_forward, Sskip_chars_forward, 1, 2, 0,
3acb9a69
RS
677 "Move point forward, stopping before a char not in STRING, or at pos LIM.\n\
678STRING is like the inside of a `[...]' in a regular expression\n\
ca1d1d23
JB
679except that `]' is never special and `\\' quotes `^', `-' or `\\'.\n\
680Thus, with arg \"a-zA-Z\", this skips letters stopping before first nonletter.\n\
c1dc99a1
JB
681With arg \"^a-zA-Z\", skips nonletters stopping before first letter.\n\
682Returns the distance traveled, either zero or positive.")
ca1d1d23
JB
683 (string, lim)
684 Lisp_Object string, lim;
685{
17431c60 686 return skip_chars (1, 0, string, lim);
ca1d1d23
JB
687}
688
689DEFUN ("skip-chars-backward", Fskip_chars_backward, Sskip_chars_backward, 1, 2, 0,
3acb9a69 690 "Move point backward, stopping after a char not in STRING, or at pos LIM.\n\
c1dc99a1
JB
691See `skip-chars-forward' for details.\n\
692Returns the distance traveled, either zero or negative.")
ca1d1d23
JB
693 (string, lim)
694 Lisp_Object string, lim;
695{
17431c60
RS
696 return skip_chars (0, 0, string, lim);
697}
698
699DEFUN ("skip-syntax-forward", Fskip_syntax_forward, Sskip_syntax_forward, 1, 2, 0,
700 "Move point forward across chars in specified syntax classes.\n\
701SYNTAX is a string of syntax code characters.\n\
702Stop before a char whose syntax is not in SYNTAX, or at position LIM.\n\
703If SYNTAX starts with ^, skip characters whose syntax is NOT in SYNTAX.\n\
704This function returns the distance traveled, either zero or positive.")
705 (syntax, lim)
706 Lisp_Object syntax, lim;
707{
708 return skip_chars (1, 1, syntax, lim);
709}
710
711DEFUN ("skip-syntax-backward", Fskip_syntax_backward, Sskip_syntax_backward, 1, 2, 0,
712 "Move point backward across chars in specified syntax classes.\n\
713SYNTAX is a string of syntax code characters.\n\
714Stop on reaching a char whose syntax is not in SYNTAX, or at position LIM.\n\
715If SYNTAX starts with ^, skip characters whose syntax is NOT in SYNTAX.\n\
716This function returns the distance traveled, either zero or negative.")
717 (syntax, lim)
718 Lisp_Object syntax, lim;
719{
720 return skip_chars (0, 1, syntax, lim);
ca1d1d23
JB
721}
722
c1dc99a1 723Lisp_Object
17431c60
RS
724skip_chars (forwardp, syntaxp, string, lim)
725 int forwardp, syntaxp;
ca1d1d23
JB
726 Lisp_Object string, lim;
727{
728 register unsigned char *p, *pend;
729 register unsigned char c;
5679531d 730 register int ch;
ca1d1d23 731 unsigned char fastmap[0400];
5679531d
KH
732 /* If SYNTAXP is 0, STRING may contain multi-byte form of characters
733 of which codes don't fit in FASTMAP. In that case, we set the
734 first byte of multibyte form (i.e. base leading-code) in FASTMAP
735 and set the actual ranges of characters in CHAR_RANGES. In the
736 form "X-Y" of STRING, both X and Y must belong to the same
737 character set because a range striding across character sets is
738 meaningless. */
739 int *char_ranges
740 = (int *) alloca (XSTRING (string)->size * (sizeof (int)) * 2);
741 int n_char_ranges = 0;
ca1d1d23
JB
742 int negate = 0;
743 register int i;
1312cff5 744 int multibyte = !NILP (current_buffer->enable_multibyte_characters);
ca1d1d23
JB
745
746 CHECK_STRING (string, 0);
747
748 if (NILP (lim))
a3668d92 749 XSETINT (lim, forwardp ? ZV : BEGV);
ca1d1d23
JB
750 else
751 CHECK_NUMBER_COERCE_MARKER (lim, 1);
752
ca1d1d23 753 /* In any case, don't allow scan outside bounds of buffer. */
c5241910
RS
754 /* jla turned this off, for no known reason.
755 bfox turned the ZV part on, and rms turned the
756 BEGV part back on. */
757 if (XINT (lim) > ZV)
c235cce7 758 XSETFASTINT (lim, ZV);
c5241910 759 if (XINT (lim) < BEGV)
c235cce7 760 XSETFASTINT (lim, BEGV);
ca1d1d23
JB
761
762 p = XSTRING (string)->data;
763 pend = p + XSTRING (string)->size;
764 bzero (fastmap, sizeof fastmap);
765
766 if (p != pend && *p == '^')
767 {
768 negate = 1; p++;
769 }
770
17431c60
RS
771 /* Find the characters specified and set their elements of fastmap.
772 If syntaxp, each character counts as itself.
5679531d 773 Otherwise, handle backslashes and ranges specially. */
ca1d1d23
JB
774
775 while (p != pend)
776 {
5679531d 777 c = *p;
1312cff5
KH
778 if (multibyte)
779 {
780 ch = STRING_CHAR (p, pend - p);
781 p += BYTES_BY_CHAR_HEAD (*p);
782 }
783 else
784 {
785 ch = c;
786 p++;
787 }
17431c60 788 if (syntaxp)
5caa45d3 789 fastmap[syntax_spec_code[c]] = 1;
17431c60 790 else
ca1d1d23 791 {
17431c60 792 if (c == '\\')
ca1d1d23 793 {
17431c60
RS
794 if (p == pend) break;
795 c = *p++;
796 }
797 if (p != pend && *p == '-')
798 {
5679531d
KH
799 unsigned int ch2;
800
17431c60
RS
801 p++;
802 if (p == pend) break;
5679531d
KH
803 if (SINGLE_BYTE_CHAR_P (ch))
804 while (c <= *p)
805 {
806 fastmap[c] = 1;
807 c++;
808 }
809 else
17431c60 810 {
5679531d
KH
811 fastmap[c] = 1; /* C is the base leading-code. */
812 ch2 = STRING_CHAR (p, pend - p);
813 if (ch <= ch2)
814 char_ranges[n_char_ranges++] = ch,
815 char_ranges[n_char_ranges++] = ch2;
17431c60 816 }
1312cff5 817 p += multibyte ? BYTES_BY_CHAR_HEAD (*p) : 1;
ca1d1d23 818 }
17431c60 819 else
5679531d
KH
820 {
821 fastmap[c] = 1;
822 if (!SINGLE_BYTE_CHAR_P (ch))
823 char_ranges[n_char_ranges++] = ch,
824 char_ranges[n_char_ranges++] = ch;
825 }
ca1d1d23 826 }
ca1d1d23
JB
827 }
828
5679531d
KH
829 /* If ^ was the first character, complement the fastmap. In
830 addition, as all multibyte characters have possibility of
831 matching, set all entries for base leading codes, which is
832 harmless even if SYNTAXP is 1. */
ca1d1d23
JB
833
834 if (negate)
835 for (i = 0; i < sizeof fastmap; i++)
5679531d 836 {
1312cff5 837 if (!multibyte || !BASE_LEADING_CODE_P (i))
5679531d
KH
838 fastmap[i] ^= 1;
839 else
840 fastmap[i] = 1;
841 }
ca1d1d23 842
c1dc99a1 843 {
6ec8bbd2 844 int start_point = PT;
5caa45d3 845 int pos = PT;
c1dc99a1
JB
846
847 immediate_quit = 1;
17431c60 848 if (syntaxp)
c1dc99a1 849 {
17431c60
RS
850 if (forwardp)
851 {
1312cff5
KH
852 if (multibyte)
853 while (pos < XINT (lim)
854 && fastmap[(int) SYNTAX (FETCH_CHAR (pos))])
855 INC_POS (pos);
856 else
857 while (pos < XINT (lim)
858 && fastmap[(int) SYNTAX (FETCH_BYTE (pos))])
859 pos++;
17431c60
RS
860 }
861 else
862 {
1312cff5
KH
863 if (multibyte)
864 while (pos > XINT (lim))
865 {
866 int savepos = pos;
867 DEC_POS (pos);
868 if (!fastmap[(int) SYNTAX (FETCH_CHAR (pos))])
869 {
870 pos = savepos;
871 break;
872 }
873 }
874 else
875 while (pos > XINT (lim)
876 && fastmap[(int) SYNTAX (FETCH_BYTE (pos - 1))])
877 pos--;
17431c60 878 }
c1dc99a1
JB
879 }
880 else
881 {
17431c60
RS
882 if (forwardp)
883 {
1312cff5
KH
884 if (multibyte)
885 while (pos < XINT (lim) && fastmap[(c = FETCH_BYTE (pos))])
886 {
887 if (!BASE_LEADING_CODE_P (c))
888 pos++;
889 else if (n_char_ranges)
890 {
891 /* We much check CHAR_RANGES for a multibyte
892 character. */
893 ch = FETCH_MULTIBYTE_CHAR (pos);
894 for (i = 0; i < n_char_ranges; i += 2)
895 if ((ch >= char_ranges[i] && ch <= char_ranges[i + 1]))
896 break;
897 if (!(negate ^ (i < n_char_ranges)))
5679531d 898 break;
5679531d 899
1312cff5
KH
900 INC_POS (pos);
901 }
902 else
903 {
904 if (!negate) break;
905 INC_POS (pos);
906 }
907 }
908 else
909 while (pos < XINT (lim) && fastmap[FETCH_BYTE (pos)])
910 pos++;
17431c60
RS
911 }
912 else
913 {
1312cff5
KH
914 if (multibyte)
915 while (pos > XINT (lim))
916 {
917 int savepos = pos;
918 DEC_POS (pos);
919 if (fastmap[(c = FETCH_BYTE (pos))])
920 {
921 if (!BASE_LEADING_CODE_P (c))
922 ;
923 else if (n_char_ranges)
924 {
925 /* We much check CHAR_RANGES for a multibyte
926 character. */
927 ch = FETCH_MULTIBYTE_CHAR (pos);
928 for (i = 0; i < n_char_ranges; i += 2)
929 if (ch >= char_ranges[i] && ch <= char_ranges[i + 1])
930 break;
931 if (!(negate ^ (i < n_char_ranges)))
932 {
933 pos = savepos;
934 break;
935 }
936 }
937 else
938 if (!negate)
f73d78a2
KH
939 {
940 pos = savepos;
941 break;
942 }
1312cff5
KH
943 }
944 else
945 {
946 pos = savepos;
947 break;
948 }
949 }
950 else
951 while (pos > XINT (lim) && fastmap[FETCH_BYTE (pos - 1)])
952 pos--;
17431c60 953 }
c1dc99a1 954 }
1312cff5
KH
955 if (multibyte
956 /* INC_POS or DEC_POS might have moved POS over LIM. */
957 && (forwardp ? (pos > XINT (lim)) : (pos < XINT (lim))))
958 pos = XINT (lim);
959
5caa45d3 960 SET_PT (pos);
c1dc99a1
JB
961 immediate_quit = 0;
962
6ec8bbd2 963 return make_number (PT - start_point);
c1dc99a1 964 }
ca1d1d23
JB
965}
966\f
967/* Subroutines of Lisp buffer search functions. */
968
969static Lisp_Object
b819a390 970search_command (string, bound, noerror, count, direction, RE, posix)
ca1d1d23
JB
971 Lisp_Object string, bound, noerror, count;
972 int direction;
973 int RE;
b819a390 974 int posix;
ca1d1d23
JB
975{
976 register int np;
977 int lim;
978 int n = direction;
979
980 if (!NILP (count))
981 {
982 CHECK_NUMBER (count, 3);
983 n *= XINT (count);
984 }
985
986 CHECK_STRING (string, 0);
987 if (NILP (bound))
988 lim = n > 0 ? ZV : BEGV;
989 else
990 {
991 CHECK_NUMBER_COERCE_MARKER (bound, 1);
992 lim = XINT (bound);
6ec8bbd2 993 if (n > 0 ? lim < PT : lim > PT)
ca1d1d23
JB
994 error ("Invalid search bound (wrong side of point)");
995 if (lim > ZV)
996 lim = ZV;
997 if (lim < BEGV)
998 lim = BEGV;
999 }
1000
6ec8bbd2 1001 np = search_buffer (string, PT, lim, n, RE,
ca1d1d23 1002 (!NILP (current_buffer->case_fold_search)
b1428bd8
RS
1003 ? XCHAR_TABLE (current_buffer->case_canon_table)->contents
1004 : 0),
ca1d1d23 1005 (!NILP (current_buffer->case_fold_search)
b1428bd8
RS
1006 ? XCHAR_TABLE (current_buffer->case_eqv_table)->contents
1007 : 0),
b819a390 1008 posix);
ca1d1d23
JB
1009 if (np <= 0)
1010 {
1011 if (NILP (noerror))
1012 return signal_failure (string);
1013 if (!EQ (noerror, Qt))
1014 {
1015 if (lim < BEGV || lim > ZV)
1016 abort ();
a5f217b8
RS
1017 SET_PT (lim);
1018 return Qnil;
1019#if 0 /* This would be clean, but maybe programs depend on
1020 a value of nil here. */
481399bf 1021 np = lim;
a5f217b8 1022#endif
ca1d1d23 1023 }
481399bf
RS
1024 else
1025 return Qnil;
ca1d1d23
JB
1026 }
1027
1028 if (np < BEGV || np > ZV)
1029 abort ();
1030
1031 SET_PT (np);
1032
1033 return make_number (np);
1034}
1035\f
b6d6a51c
KH
1036static int
1037trivial_regexp_p (regexp)
1038 Lisp_Object regexp;
1039{
1040 int len = XSTRING (regexp)->size;
1041 unsigned char *s = XSTRING (regexp)->data;
1042 unsigned char c;
1043 while (--len >= 0)
1044 {
1045 switch (*s++)
1046 {
1047 case '.': case '*': case '+': case '?': case '[': case '^': case '$':
1048 return 0;
1049 case '\\':
1050 if (--len < 0)
1051 return 0;
1052 switch (*s++)
1053 {
1054 case '|': case '(': case ')': case '`': case '\'': case 'b':
1055 case 'B': case '<': case '>': case 'w': case 'W': case 's':
866f60fd 1056 case 'S': case '=':
5679531d 1057 case 'c': case 'C': /* for categoryspec and notcategoryspec */
866f60fd 1058 case '1': case '2': case '3': case '4': case '5':
b6d6a51c
KH
1059 case '6': case '7': case '8': case '9':
1060 return 0;
1061 }
1062 }
1063 }
1064 return 1;
1065}
1066
ca325161 1067/* Search for the n'th occurrence of STRING in the current buffer,
ca1d1d23 1068 starting at position POS and stopping at position LIM,
b819a390 1069 treating STRING as a literal string if RE is false or as
ca1d1d23
JB
1070 a regular expression if RE is true.
1071
1072 If N is positive, searching is forward and LIM must be greater than POS.
1073 If N is negative, searching is backward and LIM must be less than POS.
1074
1075 Returns -x if only N-x occurrences found (x > 0),
1076 or else the position at the beginning of the Nth occurrence
b819a390
RS
1077 (if searching backward) or the end (if searching forward).
1078
1079 POSIX is nonzero if we want full backtracking (POSIX style)
1080 for this pattern. 0 means backtrack only enough to get a valid match. */
ca1d1d23 1081
b819a390
RS
1082static int
1083search_buffer (string, pos, lim, n, RE, trt, inverse_trt, posix)
ca1d1d23
JB
1084 Lisp_Object string;
1085 int pos;
1086 int lim;
1087 int n;
1088 int RE;
b1428bd8
RS
1089 Lisp_Object *trt;
1090 Lisp_Object *inverse_trt;
b819a390 1091 int posix;
ca1d1d23
JB
1092{
1093 int len = XSTRING (string)->size;
1094 unsigned char *base_pat = XSTRING (string)->data;
1095 register int *BM_tab;
1096 int *BM_tab_base;
1097 register int direction = ((n > 0) ? 1 : -1);
1098 register int dirlen;
1099 int infinity, limit, k, stride_for_teases;
1100 register unsigned char *pat, *cursor, *p_limit;
1101 register int i, j;
1102 unsigned char *p1, *p2;
1103 int s1, s2;
1104
7074fde6
FP
1105 if (running_asynch_code)
1106 save_search_regs ();
1107
ca1d1d23 1108 /* Null string is found at starting position. */
3f57a499 1109 if (len == 0)
ca325161
RS
1110 {
1111 set_search_regs (pos, 0);
1112 return pos;
1113 }
3f57a499
RS
1114
1115 /* Searching 0 times means don't move. */
1116 if (n == 0)
ca1d1d23
JB
1117 return pos;
1118
b6d6a51c 1119 if (RE && !trivial_regexp_p (string))
ca1d1d23 1120 {
487282dc
KH
1121 struct re_pattern_buffer *bufp;
1122
b1428bd8 1123 bufp = compile_pattern (string, &search_regs, trt, posix);
ca1d1d23 1124
ca1d1d23
JB
1125 immediate_quit = 1; /* Quit immediately if user types ^G,
1126 because letting this function finish
1127 can take too long. */
1128 QUIT; /* Do a pending quit right away,
1129 to avoid paradoxical behavior */
1130 /* Get pointers and sizes of the two strings
1131 that make up the visible portion of the buffer. */
1132
1133 p1 = BEGV_ADDR;
1134 s1 = GPT - BEGV;
1135 p2 = GAP_END_ADDR;
1136 s2 = ZV - GPT;
1137 if (s1 < 0)
1138 {
1139 p2 = p1;
1140 s2 = ZV - BEGV;
1141 s1 = 0;
1142 }
1143 if (s2 < 0)
1144 {
1145 s1 = ZV - BEGV;
1146 s2 = 0;
1147 }
1148 while (n < 0)
1149 {
42db823b 1150 int val;
487282dc 1151 val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
42db823b
RS
1152 pos - BEGV, lim - pos, &search_regs,
1153 /* Don't allow match past current point */
1154 pos - BEGV);
ca1d1d23 1155 if (val == -2)
b6d6a51c
KH
1156 {
1157 matcher_overflow ();
1158 }
ca1d1d23
JB
1159 if (val >= 0)
1160 {
1161 j = BEGV;
4746118a 1162 for (i = 0; i < search_regs.num_regs; i++)
ca1d1d23
JB
1163 if (search_regs.start[i] >= 0)
1164 {
1165 search_regs.start[i] += j;
1166 search_regs.end[i] += j;
1167 }
a3668d92 1168 XSETBUFFER (last_thing_searched, current_buffer);
ca1d1d23
JB
1169 /* Set pos to the new position. */
1170 pos = search_regs.start[0];
1171 }
1172 else
1173 {
1174 immediate_quit = 0;
1175 return (n);
1176 }
1177 n++;
1178 }
1179 while (n > 0)
1180 {
42db823b 1181 int val;
487282dc 1182 val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
42db823b
RS
1183 pos - BEGV, lim - pos, &search_regs,
1184 lim - BEGV);
ca1d1d23 1185 if (val == -2)
b6d6a51c
KH
1186 {
1187 matcher_overflow ();
1188 }
ca1d1d23
JB
1189 if (val >= 0)
1190 {
1191 j = BEGV;
4746118a 1192 for (i = 0; i < search_regs.num_regs; i++)
ca1d1d23
JB
1193 if (search_regs.start[i] >= 0)
1194 {
1195 search_regs.start[i] += j;
1196 search_regs.end[i] += j;
1197 }
a3668d92 1198 XSETBUFFER (last_thing_searched, current_buffer);
ca1d1d23
JB
1199 pos = search_regs.end[0];
1200 }
1201 else
1202 {
1203 immediate_quit = 0;
1204 return (0 - n);
1205 }
1206 n--;
1207 }
1208 immediate_quit = 0;
1209 return (pos);
1210 }
1211 else /* non-RE case */
1212 {
1213#ifdef C_ALLOCA
1214 int BM_tab_space[0400];
1215 BM_tab = &BM_tab_space[0];
1216#else
1217 BM_tab = (int *) alloca (0400 * sizeof (int));
1218#endif
b6d6a51c
KH
1219 {
1220 unsigned char *patbuf = (unsigned char *) alloca (len);
1221 pat = patbuf;
1222 while (--len >= 0)
1223 {
1224 /* If we got here and the RE flag is set, it's because we're
1225 dealing with a regexp known to be trivial, so the backslash
1226 just quotes the next character. */
1227 if (RE && *base_pat == '\\')
1228 {
1229 len--;
1230 base_pat++;
1231 }
1232 *pat++ = (trt ? trt[*base_pat++] : *base_pat++);
1233 }
1234 len = pat - patbuf;
1235 pat = base_pat = patbuf;
1236 }
ca1d1d23
JB
1237 /* The general approach is that we are going to maintain that we know */
1238 /* the first (closest to the present position, in whatever direction */
1239 /* we're searching) character that could possibly be the last */
1240 /* (furthest from present position) character of a valid match. We */
1241 /* advance the state of our knowledge by looking at that character */
1242 /* and seeing whether it indeed matches the last character of the */
1243 /* pattern. If it does, we take a closer look. If it does not, we */
1244 /* move our pointer (to putative last characters) as far as is */
1245 /* logically possible. This amount of movement, which I call a */
1246 /* stride, will be the length of the pattern if the actual character */
1247 /* appears nowhere in the pattern, otherwise it will be the distance */
1248 /* from the last occurrence of that character to the end of the */
1249 /* pattern. */
1250 /* As a coding trick, an enormous stride is coded into the table for */
1251 /* characters that match the last character. This allows use of only */
1252 /* a single test, a test for having gone past the end of the */
1253 /* permissible match region, to test for both possible matches (when */
1254 /* the stride goes past the end immediately) and failure to */
1255 /* match (where you get nudged past the end one stride at a time). */
1256
1257 /* Here we make a "mickey mouse" BM table. The stride of the search */
1258 /* is determined only by the last character of the putative match. */
1259 /* If that character does not match, we will stride the proper */
1260 /* distance to propose a match that superimposes it on the last */
1261 /* instance of a character that matches it (per trt), or misses */
1262 /* it entirely if there is none. */
1263
1264 dirlen = len * direction;
1265 infinity = dirlen - (lim + pos + len + len) * direction;
1266 if (direction < 0)
1267 pat = (base_pat += len - 1);
1268 BM_tab_base = BM_tab;
1269 BM_tab += 0400;
1270 j = dirlen; /* to get it in a register */
1271 /* A character that does not appear in the pattern induces a */
1272 /* stride equal to the pattern length. */
1273 while (BM_tab_base != BM_tab)
1274 {
1275 *--BM_tab = j;
1276 *--BM_tab = j;
1277 *--BM_tab = j;
1278 *--BM_tab = j;
1279 }
1280 i = 0;
1281 while (i != infinity)
1282 {
1283 j = pat[i]; i += direction;
1284 if (i == dirlen) i = infinity;
8d505039 1285 if (trt != 0)
ca1d1d23
JB
1286 {
1287 k = (j = trt[j]);
1288 if (i == infinity)
1289 stride_for_teases = BM_tab[j];
1290 BM_tab[j] = dirlen - i;
1291 /* A translation table is accompanied by its inverse -- see */
1292 /* comment following downcase_table for details */
b1428bd8 1293 while ((j = (unsigned char) inverse_trt[j]) != k)
ca1d1d23
JB
1294 BM_tab[j] = dirlen - i;
1295 }
1296 else
1297 {
1298 if (i == infinity)
1299 stride_for_teases = BM_tab[j];
1300 BM_tab[j] = dirlen - i;
1301 }
1302 /* stride_for_teases tells how much to stride if we get a */
1303 /* match on the far character but are subsequently */
1304 /* disappointed, by recording what the stride would have been */
1305 /* for that character if the last character had been */
1306 /* different. */
1307 }
1308 infinity = dirlen - infinity;
1309 pos += dirlen - ((direction > 0) ? direction : 0);
1310 /* loop invariant - pos points at where last char (first char if reverse)
1311 of pattern would align in a possible match. */
1312 while (n != 0)
1313 {
b2c71fb4
KH
1314 /* It's been reported that some (broken) compiler thinks that
1315 Boolean expressions in an arithmetic context are unsigned.
1316 Using an explicit ?1:0 prevents this. */
1317 if ((lim - pos - ((direction > 0) ? 1 : 0)) * direction < 0)
ca1d1d23
JB
1318 return (n * (0 - direction));
1319 /* First we do the part we can by pointers (maybe nothing) */
1320 QUIT;
1321 pat = base_pat;
1322 limit = pos - dirlen + direction;
1323 limit = ((direction > 0)
1324 ? BUFFER_CEILING_OF (limit)
1325 : BUFFER_FLOOR_OF (limit));
1326 /* LIMIT is now the last (not beyond-last!) value
1327 POS can take on without hitting edge of buffer or the gap. */
1328 limit = ((direction > 0)
1329 ? min (lim - 1, min (limit, pos + 20000))
1330 : max (lim, max (limit, pos - 20000)));
1331 if ((limit - pos) * direction > 20)
1332 {
5679531d
KH
1333 p_limit = POS_ADDR (limit);
1334 p2 = (cursor = POS_ADDR (pos));
ca1d1d23
JB
1335 /* In this loop, pos + cursor - p2 is the surrogate for pos */
1336 while (1) /* use one cursor setting as long as i can */
1337 {
1338 if (direction > 0) /* worth duplicating */
1339 {
1340 /* Use signed comparison if appropriate
1341 to make cursor+infinity sure to be > p_limit.
1342 Assuming that the buffer lies in a range of addresses
1343 that are all "positive" (as ints) or all "negative",
1344 either kind of comparison will work as long
1345 as we don't step by infinity. So pick the kind
1346 that works when we do step by infinity. */
8d505039 1347 if ((EMACS_INT) (p_limit + infinity) > (EMACS_INT) p_limit)
9fa17f93 1348 while ((EMACS_INT) cursor <= (EMACS_INT) p_limit)
ca1d1d23
JB
1349 cursor += BM_tab[*cursor];
1350 else
45b248b4 1351 while ((EMACS_UINT) cursor <= (EMACS_UINT) p_limit)
ca1d1d23
JB
1352 cursor += BM_tab[*cursor];
1353 }
1354 else
1355 {
8d505039
RS
1356 if ((EMACS_INT) (p_limit + infinity) < (EMACS_INT) p_limit)
1357 while ((EMACS_INT) cursor >= (EMACS_INT) p_limit)
ca1d1d23
JB
1358 cursor += BM_tab[*cursor];
1359 else
45b248b4 1360 while ((EMACS_UINT) cursor >= (EMACS_UINT) p_limit)
ca1d1d23
JB
1361 cursor += BM_tab[*cursor];
1362 }
1363/* If you are here, cursor is beyond the end of the searched region. */
1364 /* This can happen if you match on the far character of the pattern, */
1365 /* because the "stride" of that character is infinity, a number able */
1366 /* to throw you well beyond the end of the search. It can also */
1367 /* happen if you fail to match within the permitted region and would */
1368 /* otherwise try a character beyond that region */
1369 if ((cursor - p_limit) * direction <= len)
1370 break; /* a small overrun is genuine */
1371 cursor -= infinity; /* large overrun = hit */
1372 i = dirlen - direction;
8d505039 1373 if (trt != 0)
ca1d1d23
JB
1374 {
1375 while ((i -= direction) + direction != 0)
1376 if (pat[i] != trt[*(cursor -= direction)])
1377 break;
1378 }
1379 else
1380 {
1381 while ((i -= direction) + direction != 0)
1382 if (pat[i] != *(cursor -= direction))
1383 break;
1384 }
1385 cursor += dirlen - i - direction; /* fix cursor */
1386 if (i + direction == 0)
1387 {
1388 cursor -= direction;
1113d9db 1389
ca325161
RS
1390 set_search_regs (pos + cursor - p2 + ((direction > 0)
1391 ? 1 - len : 0),
1392 len);
1393
ca1d1d23
JB
1394 if ((n -= direction) != 0)
1395 cursor += dirlen; /* to resume search */
1396 else
1397 return ((direction > 0)
1398 ? search_regs.end[0] : search_regs.start[0]);
1399 }
1400 else
1401 cursor += stride_for_teases; /* <sigh> we lose - */
1402 }
1403 pos += cursor - p2;
1404 }
1405 else
1406 /* Now we'll pick up a clump that has to be done the hard */
1407 /* way because it covers a discontinuity */
1408 {
1409 limit = ((direction > 0)
1410 ? BUFFER_CEILING_OF (pos - dirlen + 1)
1411 : BUFFER_FLOOR_OF (pos - dirlen - 1));
1412 limit = ((direction > 0)
1413 ? min (limit + len, lim - 1)
1414 : max (limit - len, lim));
1415 /* LIMIT is now the last value POS can have
1416 and still be valid for a possible match. */
1417 while (1)
1418 {
1419 /* This loop can be coded for space rather than */
1420 /* speed because it will usually run only once. */
1421 /* (the reach is at most len + 21, and typically */
1422 /* does not exceed len) */
1423 while ((limit - pos) * direction >= 0)
5679531d 1424 pos += BM_tab[FETCH_BYTE (pos)];
ca1d1d23 1425 /* now run the same tests to distinguish going off the */
eb8c3be9 1426 /* end, a match or a phony match. */
ca1d1d23
JB
1427 if ((pos - limit) * direction <= len)
1428 break; /* ran off the end */
1429 /* Found what might be a match.
1430 Set POS back to last (first if reverse) char pos. */
1431 pos -= infinity;
1432 i = dirlen - direction;
1433 while ((i -= direction) + direction != 0)
1434 {
1435 pos -= direction;
8d505039 1436 if (pat[i] != (trt != 0
5679531d
KH
1437 ? trt[FETCH_BYTE (pos)]
1438 : FETCH_BYTE (pos)))
ca1d1d23
JB
1439 break;
1440 }
1441 /* Above loop has moved POS part or all the way
1442 back to the first char pos (last char pos if reverse).
1443 Set it once again at the last (first if reverse) char. */
1444 pos += dirlen - i- direction;
1445 if (i + direction == 0)
1446 {
1447 pos -= direction;
1113d9db 1448
ca325161
RS
1449 set_search_regs (pos + ((direction > 0) ? 1 - len : 0),
1450 len);
1451
ca1d1d23
JB
1452 if ((n -= direction) != 0)
1453 pos += dirlen; /* to resume search */
1454 else
1455 return ((direction > 0)
1456 ? search_regs.end[0] : search_regs.start[0]);
1457 }
1458 else
1459 pos += stride_for_teases;
1460 }
1461 }
1462 /* We have done one clump. Can we continue? */
1463 if ((lim - pos) * direction < 0)
1464 return ((0 - n) * direction);
1465 }
1466 return pos;
1467 }
1468}
ca325161
RS
1469
1470/* Record beginning BEG and end BEG + LEN
1471 for a match just found in the current buffer. */
1472
1473static void
1474set_search_regs (beg, len)
1475 int beg, len;
1476{
1477 /* Make sure we have registers in which to store
1478 the match position. */
1479 if (search_regs.num_regs == 0)
1480 {
2d4a771a
RS
1481 search_regs.start = (regoff_t *) xmalloc (2 * sizeof (regoff_t));
1482 search_regs.end = (regoff_t *) xmalloc (2 * sizeof (regoff_t));
487282dc 1483 search_regs.num_regs = 2;
ca325161
RS
1484 }
1485
1486 search_regs.start[0] = beg;
1487 search_regs.end[0] = beg + len;
a3668d92 1488 XSETBUFFER (last_thing_searched, current_buffer);
ca325161 1489}
ca1d1d23
JB
1490\f
1491/* Given a string of words separated by word delimiters,
1492 compute a regexp that matches those exact words
1493 separated by arbitrary punctuation. */
1494
1495static Lisp_Object
1496wordify (string)
1497 Lisp_Object string;
1498{
1499 register unsigned char *p, *o;
1500 register int i, len, punct_count = 0, word_count = 0;
1501 Lisp_Object val;
1502
1503 CHECK_STRING (string, 0);
1504 p = XSTRING (string)->data;
1505 len = XSTRING (string)->size;
1506
1507 for (i = 0; i < len; i++)
1508 if (SYNTAX (p[i]) != Sword)
1509 {
1510 punct_count++;
1511 if (i > 0 && SYNTAX (p[i-1]) == Sword) word_count++;
1512 }
1513 if (SYNTAX (p[len-1]) == Sword) word_count++;
1514 if (!word_count) return build_string ("");
1515
1516 val = make_string (p, len - punct_count + 5 * (word_count - 1) + 4);
1517
1518 o = XSTRING (val)->data;
1519 *o++ = '\\';
1520 *o++ = 'b';
1521
1522 for (i = 0; i < len; i++)
1523 if (SYNTAX (p[i]) == Sword)
1524 *o++ = p[i];
1525 else if (i > 0 && SYNTAX (p[i-1]) == Sword && --word_count)
1526 {
1527 *o++ = '\\';
1528 *o++ = 'W';
1529 *o++ = '\\';
1530 *o++ = 'W';
1531 *o++ = '*';
1532 }
1533
1534 *o++ = '\\';
1535 *o++ = 'b';
1536
1537 return val;
1538}
1539\f
1540DEFUN ("search-backward", Fsearch_backward, Ssearch_backward, 1, 4,
1541 "sSearch backward: ",
1542 "Search backward from point for STRING.\n\
1543Set point to the beginning of the occurrence found, and return point.\n\
1544An optional second argument bounds the search; it is a buffer position.\n\
1545The match found must not extend before that position.\n\
1546Optional third argument, if t, means if fail just return nil (no error).\n\
1547 If not nil and not t, position at limit of search and return nil.\n\
1548Optional fourth argument is repeat count--search for successive occurrences.\n\
1549See also the functions `match-beginning', `match-end' and `replace-match'.")
1550 (string, bound, noerror, count)
1551 Lisp_Object string, bound, noerror, count;
1552{
b819a390 1553 return search_command (string, bound, noerror, count, -1, 0, 0);
ca1d1d23
JB
1554}
1555
1556DEFUN ("search-forward", Fsearch_forward, Ssearch_forward, 1, 4, "sSearch: ",
1557 "Search forward from point for STRING.\n\
1558Set point to the end of the occurrence found, and return point.\n\
1559An optional second argument bounds the search; it is a buffer position.\n\
1560The match found must not extend after that position. nil is equivalent\n\
1561 to (point-max).\n\
1562Optional third argument, if t, means if fail just return nil (no error).\n\
1563 If not nil and not t, move to limit of search and return nil.\n\
1564Optional fourth argument is repeat count--search for successive occurrences.\n\
1565See also the functions `match-beginning', `match-end' and `replace-match'.")
1566 (string, bound, noerror, count)
1567 Lisp_Object string, bound, noerror, count;
1568{
b819a390 1569 return search_command (string, bound, noerror, count, 1, 0, 0);
ca1d1d23
JB
1570}
1571
1572DEFUN ("word-search-backward", Fword_search_backward, Sword_search_backward, 1, 4,
1573 "sWord search backward: ",
1574 "Search backward from point for STRING, ignoring differences in punctuation.\n\
1575Set point to the beginning of the occurrence found, and return point.\n\
1576An optional second argument bounds the search; it is a buffer position.\n\
1577The match found must not extend before that position.\n\
1578Optional third argument, if t, means if fail just return nil (no error).\n\
1579 If not nil and not t, move to limit of search and return nil.\n\
1580Optional fourth argument is repeat count--search for successive occurrences.")
1581 (string, bound, noerror, count)
1582 Lisp_Object string, bound, noerror, count;
1583{
b819a390 1584 return search_command (wordify (string), bound, noerror, count, -1, 1, 0);
ca1d1d23
JB
1585}
1586
1587DEFUN ("word-search-forward", Fword_search_forward, Sword_search_forward, 1, 4,
1588 "sWord search: ",
1589 "Search forward from point for STRING, ignoring differences in punctuation.\n\
1590Set point to the end of the occurrence found, and return point.\n\
1591An optional second argument bounds the search; it is a buffer position.\n\
1592The match found must not extend after that position.\n\
1593Optional third argument, if t, means if fail just return nil (no error).\n\
1594 If not nil and not t, move to limit of search and return nil.\n\
1595Optional fourth argument is repeat count--search for successive occurrences.")
1596 (string, bound, noerror, count)
1597 Lisp_Object string, bound, noerror, count;
1598{
b819a390 1599 return search_command (wordify (string), bound, noerror, count, 1, 1, 0);
ca1d1d23
JB
1600}
1601
1602DEFUN ("re-search-backward", Fre_search_backward, Sre_search_backward, 1, 4,
1603 "sRE search backward: ",
1604 "Search backward from point for match for regular expression REGEXP.\n\
1605Set point to the beginning of the match, and return point.\n\
1606The match found is the one starting last in the buffer\n\
19c0a730 1607and yet ending before the origin of the search.\n\
ca1d1d23
JB
1608An optional second argument bounds the search; it is a buffer position.\n\
1609The match found must start at or after that position.\n\
1610Optional third argument, if t, means if fail just return nil (no error).\n\
1611 If not nil and not t, move to limit of search and return nil.\n\
1612Optional fourth argument is repeat count--search for successive occurrences.\n\
1613See also the functions `match-beginning', `match-end' and `replace-match'.")
19c0a730
KH
1614 (regexp, bound, noerror, count)
1615 Lisp_Object regexp, bound, noerror, count;
ca1d1d23 1616{
b819a390 1617 return search_command (regexp, bound, noerror, count, -1, 1, 0);
ca1d1d23
JB
1618}
1619
1620DEFUN ("re-search-forward", Fre_search_forward, Sre_search_forward, 1, 4,
1621 "sRE search: ",
1622 "Search forward from point for regular expression REGEXP.\n\
1623Set point to the end of the occurrence found, and return point.\n\
1624An optional second argument bounds the search; it is a buffer position.\n\
1625The match found must not extend after that position.\n\
1626Optional third argument, if t, means if fail just return nil (no error).\n\
1627 If not nil and not t, move to limit of search and return nil.\n\
1628Optional fourth argument is repeat count--search for successive occurrences.\n\
1629See also the functions `match-beginning', `match-end' and `replace-match'.")
19c0a730
KH
1630 (regexp, bound, noerror, count)
1631 Lisp_Object regexp, bound, noerror, count;
ca1d1d23 1632{
b819a390
RS
1633 return search_command (regexp, bound, noerror, count, 1, 1, 0);
1634}
1635
1636DEFUN ("posix-search-backward", Fposix_search_backward, Sposix_search_backward, 1, 4,
1637 "sPosix search backward: ",
1638 "Search backward from point for match for regular expression REGEXP.\n\
1639Find the longest match in accord with Posix regular expression rules.\n\
1640Set point to the beginning of the match, and return point.\n\
1641The match found is the one starting last in the buffer\n\
1642and yet ending before the origin of the search.\n\
1643An optional second argument bounds the search; it is a buffer position.\n\
1644The match found must start at or after that position.\n\
1645Optional third argument, if t, means if fail just return nil (no error).\n\
1646 If not nil and not t, move to limit of search and return nil.\n\
1647Optional fourth argument is repeat count--search for successive occurrences.\n\
1648See also the functions `match-beginning', `match-end' and `replace-match'.")
1649 (regexp, bound, noerror, count)
1650 Lisp_Object regexp, bound, noerror, count;
1651{
1652 return search_command (regexp, bound, noerror, count, -1, 1, 1);
1653}
1654
1655DEFUN ("posix-search-forward", Fposix_search_forward, Sposix_search_forward, 1, 4,
1656 "sPosix search: ",
1657 "Search forward from point for regular expression REGEXP.\n\
1658Find the longest match in accord with Posix regular expression rules.\n\
1659Set point to the end of the occurrence found, and return point.\n\
1660An optional second argument bounds the search; it is a buffer position.\n\
1661The match found must not extend after that position.\n\
1662Optional third argument, if t, means if fail just return nil (no error).\n\
1663 If not nil and not t, move to limit of search and return nil.\n\
1664Optional fourth argument is repeat count--search for successive occurrences.\n\
1665See also the functions `match-beginning', `match-end' and `replace-match'.")
1666 (regexp, bound, noerror, count)
1667 Lisp_Object regexp, bound, noerror, count;
1668{
1669 return search_command (regexp, bound, noerror, count, 1, 1, 1);
ca1d1d23
JB
1670}
1671\f
d7a5ad5f 1672DEFUN ("replace-match", Freplace_match, Sreplace_match, 1, 5, 0,
ca1d1d23
JB
1673 "Replace text matched by last search with NEWTEXT.\n\
1674If second arg FIXEDCASE is non-nil, do not alter case of replacement text.\n\
5b9cf4b2
RS
1675Otherwise maybe capitalize the whole text, or maybe just word initials,\n\
1676based on the replaced text.\n\
1677If the replaced text has only capital letters\n\
1678and has at least one multiletter word, convert NEWTEXT to all caps.\n\
1679If the replaced text has at least one word starting with a capital letter,\n\
1680then capitalize each word in NEWTEXT.\n\n\
ca1d1d23
JB
1681If third arg LITERAL is non-nil, insert NEWTEXT literally.\n\
1682Otherwise treat `\\' as special:\n\
1683 `\\&' in NEWTEXT means substitute original matched text.\n\
1684 `\\N' means substitute what matched the Nth `\\(...\\)'.\n\
1685 If Nth parens didn't match, substitute nothing.\n\
1686 `\\\\' means insert one `\\'.\n\
1113d9db 1687FIXEDCASE and LITERAL are optional arguments.\n\
080c45fd
RS
1688Leaves point at end of replacement text.\n\
1689\n\
1690The optional fourth argument STRING can be a string to modify.\n\
1691In that case, this function creates and returns a new string\n\
d7a5ad5f
RS
1692which is made by replacing the part of STRING that was matched.\n\
1693\n\
1694The optional fifth argument SUBEXP specifies a subexpression of the match.\n\
1695It says to replace just that subexpression instead of the whole match.\n\
1696This is useful only after a regular expression search or match\n\
1697since only regular expressions have distinguished subexpressions.")
1698 (newtext, fixedcase, literal, string, subexp)
1699 Lisp_Object newtext, fixedcase, literal, string, subexp;
ca1d1d23
JB
1700{
1701 enum { nochange, all_caps, cap_initial } case_action;
1702 register int pos, last;
1703 int some_multiletter_word;
97832bd0 1704 int some_lowercase;
73dc8771 1705 int some_uppercase;
208767c3 1706 int some_nonuppercase_initial;
ca1d1d23
JB
1707 register int c, prevc;
1708 int inslen;
d7a5ad5f 1709 int sub;
ca1d1d23 1710
16fdc568 1711 CHECK_STRING (newtext, 0);
ca1d1d23 1712
080c45fd
RS
1713 if (! NILP (string))
1714 CHECK_STRING (string, 4);
1715
ca1d1d23
JB
1716 case_action = nochange; /* We tried an initialization */
1717 /* but some C compilers blew it */
4746118a
JB
1718
1719 if (search_regs.num_regs <= 0)
1720 error ("replace-match called before any match found");
1721
d7a5ad5f
RS
1722 if (NILP (subexp))
1723 sub = 0;
1724 else
1725 {
1726 CHECK_NUMBER (subexp, 3);
1727 sub = XINT (subexp);
1728 if (sub < 0 || sub >= search_regs.num_regs)
1729 args_out_of_range (subexp, make_number (search_regs.num_regs));
1730 }
1731
080c45fd
RS
1732 if (NILP (string))
1733 {
d7a5ad5f
RS
1734 if (search_regs.start[sub] < BEGV
1735 || search_regs.start[sub] > search_regs.end[sub]
1736 || search_regs.end[sub] > ZV)
1737 args_out_of_range (make_number (search_regs.start[sub]),
1738 make_number (search_regs.end[sub]));
080c45fd
RS
1739 }
1740 else
1741 {
d7a5ad5f
RS
1742 if (search_regs.start[sub] < 0
1743 || search_regs.start[sub] > search_regs.end[sub]
1744 || search_regs.end[sub] > XSTRING (string)->size)
1745 args_out_of_range (make_number (search_regs.start[sub]),
1746 make_number (search_regs.end[sub]));
080c45fd 1747 }
ca1d1d23
JB
1748
1749 if (NILP (fixedcase))
1750 {
1751 /* Decide how to casify by examining the matched text. */
1752
d7a5ad5f 1753 last = search_regs.end[sub];
ca1d1d23
JB
1754 prevc = '\n';
1755 case_action = all_caps;
1756
1757 /* some_multiletter_word is set nonzero if any original word
1758 is more than one letter long. */
1759 some_multiletter_word = 0;
97832bd0 1760 some_lowercase = 0;
208767c3 1761 some_nonuppercase_initial = 0;
73dc8771 1762 some_uppercase = 0;
ca1d1d23 1763
d7a5ad5f 1764 for (pos = search_regs.start[sub]; pos < last; pos++)
ca1d1d23 1765 {
080c45fd 1766 if (NILP (string))
5679531d 1767 c = FETCH_BYTE (pos);
080c45fd
RS
1768 else
1769 c = XSTRING (string)->data[pos];
1770
ca1d1d23
JB
1771 if (LOWERCASEP (c))
1772 {
1773 /* Cannot be all caps if any original char is lower case */
1774
97832bd0 1775 some_lowercase = 1;
ca1d1d23 1776 if (SYNTAX (prevc) != Sword)
208767c3 1777 some_nonuppercase_initial = 1;
ca1d1d23
JB
1778 else
1779 some_multiletter_word = 1;
1780 }
1781 else if (!NOCASEP (c))
1782 {
73dc8771 1783 some_uppercase = 1;
97832bd0 1784 if (SYNTAX (prevc) != Sword)
c4d460ce 1785 ;
97832bd0 1786 else
ca1d1d23
JB
1787 some_multiletter_word = 1;
1788 }
208767c3
RS
1789 else
1790 {
1791 /* If the initial is a caseless word constituent,
1792 treat that like a lowercase initial. */
1793 if (SYNTAX (prevc) != Sword)
1794 some_nonuppercase_initial = 1;
1795 }
ca1d1d23
JB
1796
1797 prevc = c;
1798 }
1799
97832bd0
RS
1800 /* Convert to all caps if the old text is all caps
1801 and has at least one multiletter word. */
1802 if (! some_lowercase && some_multiletter_word)
1803 case_action = all_caps;
c4d460ce 1804 /* Capitalize each word, if the old text has all capitalized words. */
208767c3 1805 else if (!some_nonuppercase_initial && some_multiletter_word)
ca1d1d23 1806 case_action = cap_initial;
208767c3 1807 else if (!some_nonuppercase_initial && some_uppercase)
73dc8771
KH
1808 /* Should x -> yz, operating on X, give Yz or YZ?
1809 We'll assume the latter. */
1810 case_action = all_caps;
97832bd0
RS
1811 else
1812 case_action = nochange;
ca1d1d23
JB
1813 }
1814
080c45fd
RS
1815 /* Do replacement in a string. */
1816 if (!NILP (string))
1817 {
1818 Lisp_Object before, after;
1819
1820 before = Fsubstring (string, make_number (0),
d7a5ad5f
RS
1821 make_number (search_regs.start[sub]));
1822 after = Fsubstring (string, make_number (search_regs.end[sub]), Qnil);
080c45fd
RS
1823
1824 /* Do case substitution into NEWTEXT if desired. */
1825 if (NILP (literal))
1826 {
1827 int lastpos = -1;
1828 /* We build up the substituted string in ACCUM. */
1829 Lisp_Object accum;
1830 Lisp_Object middle;
1831
1832 accum = Qnil;
1833
1834 for (pos = 0; pos < XSTRING (newtext)->size; pos++)
1835 {
1836 int substart = -1;
1837 int subend;
1e79ec24 1838 int delbackslash = 0;
080c45fd
RS
1839
1840 c = XSTRING (newtext)->data[pos];
1841 if (c == '\\')
1842 {
1843 c = XSTRING (newtext)->data[++pos];
1844 if (c == '&')
1845 {
d7a5ad5f
RS
1846 substart = search_regs.start[sub];
1847 subend = search_regs.end[sub];
080c45fd
RS
1848 }
1849 else if (c >= '1' && c <= '9' && c <= search_regs.num_regs + '0')
1850 {
ad10348f 1851 if (search_regs.start[c - '0'] >= 0)
080c45fd
RS
1852 {
1853 substart = search_regs.start[c - '0'];
1854 subend = search_regs.end[c - '0'];
1855 }
1856 }
1e79ec24
KH
1857 else if (c == '\\')
1858 delbackslash = 1;
080c45fd
RS
1859 }
1860 if (substart >= 0)
1861 {
1862 if (pos - 1 != lastpos + 1)
1e79ec24
KH
1863 middle = Fsubstring (newtext,
1864 make_number (lastpos + 1),
1865 make_number (pos - 1));
080c45fd
RS
1866 else
1867 middle = Qnil;
1868 accum = concat3 (accum, middle,
1869 Fsubstring (string, make_number (substart),
1870 make_number (subend)));
1871 lastpos = pos;
1872 }
1e79ec24
KH
1873 else if (delbackslash)
1874 {
1875 middle = Fsubstring (newtext, make_number (lastpos + 1),
1876 make_number (pos));
1877 accum = concat2 (accum, middle);
1878 lastpos = pos;
1879 }
080c45fd
RS
1880 }
1881
1882 if (pos != lastpos + 1)
1e79ec24
KH
1883 middle = Fsubstring (newtext, make_number (lastpos + 1),
1884 make_number (pos));
080c45fd
RS
1885 else
1886 middle = Qnil;
1887
1888 newtext = concat2 (accum, middle);
1889 }
1890
1891 if (case_action == all_caps)
1892 newtext = Fupcase (newtext);
1893 else if (case_action == cap_initial)
2b2eead9 1894 newtext = Fupcase_initials (newtext);
080c45fd
RS
1895
1896 return concat3 (before, newtext, after);
1897 }
1898
9a76659d
JB
1899 /* We insert the replacement text before the old text, and then
1900 delete the original text. This means that markers at the
1901 beginning or end of the original will float to the corresponding
1902 position in the replacement. */
d7a5ad5f 1903 SET_PT (search_regs.start[sub]);
ca1d1d23 1904 if (!NILP (literal))
16fdc568 1905 Finsert_and_inherit (1, &newtext);
ca1d1d23
JB
1906 else
1907 {
1908 struct gcpro gcpro1;
16fdc568 1909 GCPRO1 (newtext);
ca1d1d23 1910
16fdc568 1911 for (pos = 0; pos < XSTRING (newtext)->size; pos++)
ca1d1d23 1912 {
6ec8bbd2 1913 int offset = PT - search_regs.start[sub];
9a76659d 1914
16fdc568 1915 c = XSTRING (newtext)->data[pos];
ca1d1d23
JB
1916 if (c == '\\')
1917 {
16fdc568 1918 c = XSTRING (newtext)->data[++pos];
ca1d1d23 1919 if (c == '&')
9a76659d
JB
1920 Finsert_buffer_substring
1921 (Fcurrent_buffer (),
d7a5ad5f
RS
1922 make_number (search_regs.start[sub] + offset),
1923 make_number (search_regs.end[sub] + offset));
78445046 1924 else if (c >= '1' && c <= '9' && c <= search_regs.num_regs + '0')
ca1d1d23
JB
1925 {
1926 if (search_regs.start[c - '0'] >= 1)
9a76659d
JB
1927 Finsert_buffer_substring
1928 (Fcurrent_buffer (),
1929 make_number (search_regs.start[c - '0'] + offset),
1930 make_number (search_regs.end[c - '0'] + offset));
ca1d1d23
JB
1931 }
1932 else
1933 insert_char (c);
1934 }
1935 else
1936 insert_char (c);
1937 }
1938 UNGCPRO;
1939 }
1940
6ec8bbd2 1941 inslen = PT - (search_regs.start[sub]);
d7a5ad5f 1942 del_range (search_regs.start[sub] + inslen, search_regs.end[sub] + inslen);
ca1d1d23
JB
1943
1944 if (case_action == all_caps)
6ec8bbd2 1945 Fupcase_region (make_number (PT - inslen), make_number (PT));
ca1d1d23 1946 else if (case_action == cap_initial)
6ec8bbd2 1947 Fupcase_initials_region (make_number (PT - inslen), make_number (PT));
ca1d1d23
JB
1948 return Qnil;
1949}
1950\f
1951static Lisp_Object
1952match_limit (num, beginningp)
1953 Lisp_Object num;
1954 int beginningp;
1955{
1956 register int n;
1957
1958 CHECK_NUMBER (num, 0);
1959 n = XINT (num);
4746118a
JB
1960 if (n < 0 || n >= search_regs.num_regs)
1961 args_out_of_range (num, make_number (search_regs.num_regs));
1962 if (search_regs.num_regs <= 0
1963 || search_regs.start[n] < 0)
ca1d1d23
JB
1964 return Qnil;
1965 return (make_number ((beginningp) ? search_regs.start[n]
1966 : search_regs.end[n]));
1967}
1968
1969DEFUN ("match-beginning", Fmatch_beginning, Smatch_beginning, 1, 1, 0,
1970 "Return position of start of text matched by last search.\n\
5806161b
EN
1971SUBEXP, a number, specifies which parenthesized expression in the last\n\
1972 regexp.\n\
1973Value is nil if SUBEXPth pair didn't match, or there were less than\n\
1974 SUBEXP pairs.\n\
ca1d1d23 1975Zero means the entire text matched by the whole regexp or whole string.")
5806161b
EN
1976 (subexp)
1977 Lisp_Object subexp;
ca1d1d23 1978{
5806161b 1979 return match_limit (subexp, 1);
ca1d1d23
JB
1980}
1981
1982DEFUN ("match-end", Fmatch_end, Smatch_end, 1, 1, 0,
1983 "Return position of end of text matched by last search.\n\
5806161b
EN
1984SUBEXP, a number, specifies which parenthesized expression in the last\n\
1985 regexp.\n\
1986Value is nil if SUBEXPth pair didn't match, or there were less than\n\
1987 SUBEXP pairs.\n\
ca1d1d23 1988Zero means the entire text matched by the whole regexp or whole string.")
5806161b
EN
1989 (subexp)
1990 Lisp_Object subexp;
ca1d1d23 1991{
5806161b 1992 return match_limit (subexp, 0);
ca1d1d23
JB
1993}
1994
56256c2a 1995DEFUN ("match-data", Fmatch_data, Smatch_data, 0, 2, 0,
ca1d1d23
JB
1996 "Return a list containing all info on what the last search matched.\n\
1997Element 2N is `(match-beginning N)'; element 2N + 1 is `(match-end N)'.\n\
1998All the elements are markers or nil (nil if the Nth pair didn't match)\n\
1999if the last match was on a buffer; integers or nil if a string was matched.\n\
56256c2a
RS
2000Use `store-match-data' to reinstate the data in this list.\n\
2001\n\
2002If INTEGERS (the optional first argument) is non-nil, always use integers\n\
8ca821e9 2003\(rather than markers) to represent buffer positions.\n\
56256c2a
RS
2004If REUSE is a list, reuse it as part of the value. If REUSE is long enough\n\
2005to hold all the values, and if INTEGERS is non-nil, no consing is done.")
2006 (integers, reuse)
2007 Lisp_Object integers, reuse;
ca1d1d23 2008{
56256c2a 2009 Lisp_Object tail, prev;
4746118a 2010 Lisp_Object *data;
ca1d1d23
JB
2011 int i, len;
2012
daa37602 2013 if (NILP (last_thing_searched))
c36bcf1b 2014 return Qnil;
daa37602 2015
4746118a
JB
2016 data = (Lisp_Object *) alloca ((2 * search_regs.num_regs)
2017 * sizeof (Lisp_Object));
2018
ca1d1d23 2019 len = -1;
4746118a 2020 for (i = 0; i < search_regs.num_regs; i++)
ca1d1d23
JB
2021 {
2022 int start = search_regs.start[i];
2023 if (start >= 0)
2024 {
56256c2a
RS
2025 if (EQ (last_thing_searched, Qt)
2026 || ! NILP (integers))
ca1d1d23 2027 {
c235cce7
KH
2028 XSETFASTINT (data[2 * i], start);
2029 XSETFASTINT (data[2 * i + 1], search_regs.end[i]);
ca1d1d23 2030 }
0ed62dc7 2031 else if (BUFFERP (last_thing_searched))
ca1d1d23
JB
2032 {
2033 data[2 * i] = Fmake_marker ();
daa37602
JB
2034 Fset_marker (data[2 * i],
2035 make_number (start),
2036 last_thing_searched);
ca1d1d23
JB
2037 data[2 * i + 1] = Fmake_marker ();
2038 Fset_marker (data[2 * i + 1],
daa37602
JB
2039 make_number (search_regs.end[i]),
2040 last_thing_searched);
ca1d1d23 2041 }
daa37602
JB
2042 else
2043 /* last_thing_searched must always be Qt, a buffer, or Qnil. */
2044 abort ();
2045
ca1d1d23
JB
2046 len = i;
2047 }
2048 else
2049 data[2 * i] = data [2 * i + 1] = Qnil;
2050 }
56256c2a
RS
2051
2052 /* If REUSE is not usable, cons up the values and return them. */
2053 if (! CONSP (reuse))
2054 return Flist (2 * len + 2, data);
2055
2056 /* If REUSE is a list, store as many value elements as will fit
2057 into the elements of REUSE. */
2058 for (i = 0, tail = reuse; CONSP (tail);
2059 i++, tail = XCONS (tail)->cdr)
2060 {
2061 if (i < 2 * len + 2)
2062 XCONS (tail)->car = data[i];
2063 else
2064 XCONS (tail)->car = Qnil;
2065 prev = tail;
2066 }
2067
2068 /* If we couldn't fit all value elements into REUSE,
2069 cons up the rest of them and add them to the end of REUSE. */
2070 if (i < 2 * len + 2)
2071 XCONS (prev)->cdr = Flist (2 * len + 2 - i, data + i);
2072
2073 return reuse;
ca1d1d23
JB
2074}
2075
2076
2077DEFUN ("store-match-data", Fstore_match_data, Sstore_match_data, 1, 1, 0,
2078 "Set internal data on last search match from elements of LIST.\n\
2079LIST should have been created by calling `match-data' previously.")
2080 (list)
2081 register Lisp_Object list;
2082{
2083 register int i;
2084 register Lisp_Object marker;
2085
7074fde6
FP
2086 if (running_asynch_code)
2087 save_search_regs ();
2088
ca1d1d23 2089 if (!CONSP (list) && !NILP (list))
b37902c8 2090 list = wrong_type_argument (Qconsp, list);
ca1d1d23 2091
daa37602
JB
2092 /* Unless we find a marker with a buffer in LIST, assume that this
2093 match data came from a string. */
2094 last_thing_searched = Qt;
2095
4746118a
JB
2096 /* Allocate registers if they don't already exist. */
2097 {
d084e942 2098 int length = XFASTINT (Flength (list)) / 2;
4746118a
JB
2099
2100 if (length > search_regs.num_regs)
2101 {
1113d9db
JB
2102 if (search_regs.num_regs == 0)
2103 {
2104 search_regs.start
2105 = (regoff_t *) xmalloc (length * sizeof (regoff_t));
2106 search_regs.end
2107 = (regoff_t *) xmalloc (length * sizeof (regoff_t));
2108 }
4746118a 2109 else
1113d9db
JB
2110 {
2111 search_regs.start
2112 = (regoff_t *) xrealloc (search_regs.start,
2113 length * sizeof (regoff_t));
2114 search_regs.end
2115 = (regoff_t *) xrealloc (search_regs.end,
2116 length * sizeof (regoff_t));
2117 }
4746118a 2118
487282dc 2119 search_regs.num_regs = length;
4746118a
JB
2120 }
2121 }
2122
2123 for (i = 0; i < search_regs.num_regs; i++)
ca1d1d23
JB
2124 {
2125 marker = Fcar (list);
2126 if (NILP (marker))
2127 {
2128 search_regs.start[i] = -1;
2129 list = Fcdr (list);
2130 }
2131 else
2132 {
0ed62dc7 2133 if (MARKERP (marker))
daa37602
JB
2134 {
2135 if (XMARKER (marker)->buffer == 0)
c235cce7 2136 XSETFASTINT (marker, 0);
daa37602 2137 else
a3668d92 2138 XSETBUFFER (last_thing_searched, XMARKER (marker)->buffer);
daa37602 2139 }
ca1d1d23
JB
2140
2141 CHECK_NUMBER_COERCE_MARKER (marker, 0);
2142 search_regs.start[i] = XINT (marker);
2143 list = Fcdr (list);
2144
2145 marker = Fcar (list);
0ed62dc7 2146 if (MARKERP (marker) && XMARKER (marker)->buffer == 0)
c235cce7 2147 XSETFASTINT (marker, 0);
ca1d1d23
JB
2148
2149 CHECK_NUMBER_COERCE_MARKER (marker, 0);
2150 search_regs.end[i] = XINT (marker);
2151 }
2152 list = Fcdr (list);
2153 }
2154
2155 return Qnil;
2156}
2157
7074fde6
FP
2158/* If non-zero the match data have been saved in saved_search_regs
2159 during the execution of a sentinel or filter. */
75ebf74b 2160static int search_regs_saved;
7074fde6
FP
2161static struct re_registers saved_search_regs;
2162
2163/* Called from Flooking_at, Fstring_match, search_buffer, Fstore_match_data
2164 if asynchronous code (filter or sentinel) is running. */
2165static void
2166save_search_regs ()
2167{
2168 if (!search_regs_saved)
2169 {
2170 saved_search_regs.num_regs = search_regs.num_regs;
2171 saved_search_regs.start = search_regs.start;
2172 saved_search_regs.end = search_regs.end;
2173 search_regs.num_regs = 0;
2d4a771a
RS
2174 search_regs.start = 0;
2175 search_regs.end = 0;
7074fde6
FP
2176
2177 search_regs_saved = 1;
2178 }
2179}
2180
2181/* Called upon exit from filters and sentinels. */
2182void
2183restore_match_data ()
2184{
2185 if (search_regs_saved)
2186 {
2187 if (search_regs.num_regs > 0)
2188 {
2189 xfree (search_regs.start);
2190 xfree (search_regs.end);
2191 }
2192 search_regs.num_regs = saved_search_regs.num_regs;
2193 search_regs.start = saved_search_regs.start;
2194 search_regs.end = saved_search_regs.end;
2195
2196 search_regs_saved = 0;
2197 }
2198}
2199
ca1d1d23
JB
2200/* Quote a string to inactivate reg-expr chars */
2201
2202DEFUN ("regexp-quote", Fregexp_quote, Sregexp_quote, 1, 1, 0,
2203 "Return a regexp string which matches exactly STRING and nothing else.")
5806161b
EN
2204 (string)
2205 Lisp_Object string;
ca1d1d23
JB
2206{
2207 register unsigned char *in, *out, *end;
2208 register unsigned char *temp;
2209
5806161b 2210 CHECK_STRING (string, 0);
ca1d1d23 2211
5806161b 2212 temp = (unsigned char *) alloca (XSTRING (string)->size * 2);
ca1d1d23
JB
2213
2214 /* Now copy the data into the new string, inserting escapes. */
2215
5806161b
EN
2216 in = XSTRING (string)->data;
2217 end = in + XSTRING (string)->size;
ca1d1d23
JB
2218 out = temp;
2219
2220 for (; in != end; in++)
2221 {
2222 if (*in == '[' || *in == ']'
2223 || *in == '*' || *in == '.' || *in == '\\'
2224 || *in == '?' || *in == '+'
2225 || *in == '^' || *in == '$')
2226 *out++ = '\\';
2227 *out++ = *in;
2228 }
2229
2230 return make_string (temp, out - temp);
2231}
2232\f
2233syms_of_search ()
2234{
2235 register int i;
2236
487282dc
KH
2237 for (i = 0; i < REGEXP_CACHE_SIZE; ++i)
2238 {
2239 searchbufs[i].buf.allocated = 100;
2240 searchbufs[i].buf.buffer = (unsigned char *) malloc (100);
2241 searchbufs[i].buf.fastmap = searchbufs[i].fastmap;
2242 searchbufs[i].regexp = Qnil;
2243 staticpro (&searchbufs[i].regexp);
2244 searchbufs[i].next = (i == REGEXP_CACHE_SIZE-1 ? 0 : &searchbufs[i+1]);
2245 }
2246 searchbuf_head = &searchbufs[0];
ca1d1d23
JB
2247
2248 Qsearch_failed = intern ("search-failed");
2249 staticpro (&Qsearch_failed);
2250 Qinvalid_regexp = intern ("invalid-regexp");
2251 staticpro (&Qinvalid_regexp);
2252
2253 Fput (Qsearch_failed, Qerror_conditions,
2254 Fcons (Qsearch_failed, Fcons (Qerror, Qnil)));
2255 Fput (Qsearch_failed, Qerror_message,
2256 build_string ("Search failed"));
2257
2258 Fput (Qinvalid_regexp, Qerror_conditions,
2259 Fcons (Qinvalid_regexp, Fcons (Qerror, Qnil)));
2260 Fput (Qinvalid_regexp, Qerror_message,
2261 build_string ("Invalid regexp"));
2262
daa37602
JB
2263 last_thing_searched = Qnil;
2264 staticpro (&last_thing_searched);
2265
ca1d1d23 2266 defsubr (&Slooking_at);
b819a390
RS
2267 defsubr (&Sposix_looking_at);
2268 defsubr (&Sstring_match);
2269 defsubr (&Sposix_string_match);
ca1d1d23
JB
2270 defsubr (&Sskip_chars_forward);
2271 defsubr (&Sskip_chars_backward);
17431c60
RS
2272 defsubr (&Sskip_syntax_forward);
2273 defsubr (&Sskip_syntax_backward);
ca1d1d23
JB
2274 defsubr (&Ssearch_forward);
2275 defsubr (&Ssearch_backward);
2276 defsubr (&Sword_search_forward);
2277 defsubr (&Sword_search_backward);
2278 defsubr (&Sre_search_forward);
2279 defsubr (&Sre_search_backward);
b819a390
RS
2280 defsubr (&Sposix_search_forward);
2281 defsubr (&Sposix_search_backward);
ca1d1d23
JB
2282 defsubr (&Sreplace_match);
2283 defsubr (&Smatch_beginning);
2284 defsubr (&Smatch_end);
2285 defsubr (&Smatch_data);
2286 defsubr (&Sstore_match_data);
2287 defsubr (&Sregexp_quote);
2288}