(free_fontset_data): Don't free null pointer.
[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 123{
d451e4db 124 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));
d451e4db
RS
134 val = (char *) re_compile_pattern ((char *) XSTRING (pattern)->data,
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)
b0eba991 228 ? XCHAR_TABLE (DOWNCASE_TABLE)->contents : 0),
b819a390 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 }
8bb43c28
RS
252
253 re_match_object = Qnil;
ca1d1d23 254
487282dc 255 i = re_match_2 (bufp, (char *) p1, s1, (char *) p2, s2,
6ec8bbd2 256 PT - BEGV, &search_regs,
ca1d1d23
JB
257 ZV - BEGV);
258 if (i == -2)
259 matcher_overflow ();
260
261 val = (0 <= i ? Qt : Qnil);
4746118a 262 for (i = 0; i < search_regs.num_regs; i++)
ca1d1d23
JB
263 if (search_regs.start[i] >= 0)
264 {
265 search_regs.start[i] += BEGV;
266 search_regs.end[i] += BEGV;
267 }
a3668d92 268 XSETBUFFER (last_thing_searched, current_buffer);
ca1d1d23
JB
269 immediate_quit = 0;
270 return val;
271}
272
b819a390 273DEFUN ("looking-at", Flooking_at, Slooking_at, 1, 1, 0,
94f94972 274 "Return t if text after point matches regular expression REGEXP.\n\
b819a390
RS
275This function modifies the match data that `match-beginning',\n\
276`match-end' and `match-data' access; save and restore the match\n\
277data if you want to preserve them.")
94f94972
RS
278 (regexp)
279 Lisp_Object regexp;
b819a390 280{
94f94972 281 return looking_at_1 (regexp, 0);
b819a390
RS
282}
283
284DEFUN ("posix-looking-at", Fposix_looking_at, Sposix_looking_at, 1, 1, 0,
94f94972 285 "Return t if text after point matches regular expression REGEXP.\n\
b819a390
RS
286Find the longest match, in accord with Posix regular expression rules.\n\
287This function modifies the match data that `match-beginning',\n\
288`match-end' and `match-data' access; save and restore the match\n\
289data if you want to preserve them.")
94f94972
RS
290 (regexp)
291 Lisp_Object regexp;
b819a390 292{
94f94972 293 return looking_at_1 (regexp, 1);
b819a390
RS
294}
295\f
296static Lisp_Object
297string_match_1 (regexp, string, start, posix)
ca1d1d23 298 Lisp_Object regexp, string, start;
b819a390 299 int posix;
ca1d1d23
JB
300{
301 int val;
302 int s;
487282dc 303 struct re_pattern_buffer *bufp;
ca1d1d23 304
7074fde6
FP
305 if (running_asynch_code)
306 save_search_regs ();
307
ca1d1d23
JB
308 CHECK_STRING (regexp, 0);
309 CHECK_STRING (string, 1);
310
311 if (NILP (start))
312 s = 0;
313 else
314 {
315 int len = XSTRING (string)->size;
316
317 CHECK_NUMBER (start, 2);
318 s = XINT (start);
319 if (s < 0 && -s <= len)
26faf9f4 320 s = len + s;
ca1d1d23
JB
321 else if (0 > s || s > len)
322 args_out_of_range (string, start);
323 }
324
487282dc
KH
325 bufp = compile_pattern (regexp, &search_regs,
326 (!NILP (current_buffer->case_fold_search)
b0eba991 327 ? XCHAR_TABLE (DOWNCASE_TABLE)->contents : 0),
24b704fa 328 posix);
ca1d1d23 329 immediate_quit = 1;
8bb43c28
RS
330 re_match_object = string;
331
487282dc 332 val = re_search (bufp, (char *) XSTRING (string)->data,
ca1d1d23
JB
333 XSTRING (string)->size, s, XSTRING (string)->size - s,
334 &search_regs);
335 immediate_quit = 0;
daa37602 336 last_thing_searched = Qt;
ca1d1d23
JB
337 if (val == -2)
338 matcher_overflow ();
339 if (val < 0) return Qnil;
340 return make_number (val);
341}
e59a8453 342
b819a390
RS
343DEFUN ("string-match", Fstring_match, Sstring_match, 2, 3, 0,
344 "Return index of start of first match for REGEXP in STRING, or nil.\n\
345If third arg START is non-nil, start search at that index in STRING.\n\
346For index of first char beyond the match, do (match-end 0).\n\
347`match-end' and `match-beginning' also give indices of substrings\n\
348matched by parenthesis constructs in the pattern.")
349 (regexp, string, start)
350 Lisp_Object regexp, string, start;
351{
352 return string_match_1 (regexp, string, start, 0);
353}
354
355DEFUN ("posix-string-match", Fposix_string_match, Sposix_string_match, 2, 3, 0,
356 "Return index of start of first match for REGEXP in STRING, or nil.\n\
357Find the longest match, in accord with Posix regular expression rules.\n\
358If third arg START is non-nil, start search at that index in STRING.\n\
359For index of first char beyond the match, do (match-end 0).\n\
360`match-end' and `match-beginning' also give indices of substrings\n\
361matched by parenthesis constructs in the pattern.")
362 (regexp, string, start)
363 Lisp_Object regexp, string, start;
364{
365 return string_match_1 (regexp, string, start, 1);
366}
367
e59a8453
RS
368/* Match REGEXP against STRING, searching all of STRING,
369 and return the index of the match, or negative on failure.
370 This does not clobber the match data. */
371
372int
373fast_string_match (regexp, string)
374 Lisp_Object regexp, string;
375{
376 int val;
487282dc 377 struct re_pattern_buffer *bufp;
e59a8453 378
b819a390 379 bufp = compile_pattern (regexp, 0, 0, 0);
e59a8453 380 immediate_quit = 1;
8bb43c28
RS
381 re_match_object = string;
382
487282dc 383 val = re_search (bufp, (char *) XSTRING (string)->data,
e59a8453
RS
384 XSTRING (string)->size, 0, XSTRING (string)->size,
385 0);
386 immediate_quit = 0;
387 return val;
388}
5679531d
KH
389
390/* Match REGEXP against STRING, searching all of STRING ignoring case,
391 and return the index of the match, or negative on failure.
392 This does not clobber the match data. */
393
394extern Lisp_Object Vascii_downcase_table;
395
396int
b4577c63 397fast_c_string_match_ignore_case (regexp, string)
5679531d
KH
398 Lisp_Object regexp;
399 char *string;
400{
401 int val;
402 struct re_pattern_buffer *bufp;
403 int len = strlen (string);
404
b4577c63 405 re_match_object = Qt;
5679531d
KH
406 bufp = compile_pattern (regexp, 0,
407 XCHAR_TABLE (Vascii_downcase_table)->contents, 0);
408 immediate_quit = 1;
409 val = re_search (bufp, string, len, 0, len, 0);
410 immediate_quit = 0;
411 return val;
412}
ca1d1d23 413\f
9169c321
JB
414/* max and min. */
415
416static int
417max (a, b)
418 int a, b;
419{
420 return ((a > b) ? a : b);
421}
422
423static int
424min (a, b)
425 int a, b;
426{
427 return ((a < b) ? a : b);
428}
429
430\f
431/* The newline cache: remembering which sections of text have no newlines. */
432
433/* If the user has requested newline caching, make sure it's on.
434 Otherwise, make sure it's off.
435 This is our cheezy way of associating an action with the change of
436 state of a buffer-local variable. */
437static void
438newline_cache_on_off (buf)
439 struct buffer *buf;
440{
441 if (NILP (buf->cache_long_line_scans))
442 {
443 /* It should be off. */
444 if (buf->newline_cache)
445 {
446 free_region_cache (buf->newline_cache);
447 buf->newline_cache = 0;
448 }
449 }
450 else
451 {
452 /* It should be on. */
453 if (buf->newline_cache == 0)
454 buf->newline_cache = new_region_cache ();
455 }
456}
457
458\f
459/* Search for COUNT instances of the character TARGET between START and END.
460
461 If COUNT is positive, search forwards; END must be >= START.
462 If COUNT is negative, search backwards for the -COUNTth instance;
463 END must be <= START.
464 If COUNT is zero, do anything you please; run rogue, for all I care.
465
466 If END is zero, use BEGV or ZV instead, as appropriate for the
467 direction indicated by COUNT.
ffd56f97
JB
468
469 If we find COUNT instances, set *SHORTAGE to zero, and return the
5bfe95c9
RS
470 position after the COUNTth match. Note that for reverse motion
471 this is not the same as the usual convention for Emacs motion commands.
ffd56f97 472
9169c321
JB
473 If we don't find COUNT instances before reaching END, set *SHORTAGE
474 to the number of TARGETs left unfound, and return END.
ffd56f97 475
087a5f81
RS
476 If ALLOW_QUIT is non-zero, set immediate_quit. That's good to do
477 except when inside redisplay. */
478
9169c321
JB
479scan_buffer (target, start, end, count, shortage, allow_quit)
480 register int target;
481 int start, end;
482 int count;
483 int *shortage;
087a5f81 484 int allow_quit;
ca1d1d23 485{
9169c321
JB
486 struct region_cache *newline_cache;
487 int direction;
ffd56f97 488
9169c321
JB
489 if (count > 0)
490 {
491 direction = 1;
492 if (! end) end = ZV;
493 }
494 else
495 {
496 direction = -1;
497 if (! end) end = BEGV;
498 }
ffd56f97 499
9169c321
JB
500 newline_cache_on_off (current_buffer);
501 newline_cache = current_buffer->newline_cache;
ca1d1d23
JB
502
503 if (shortage != 0)
504 *shortage = 0;
505
087a5f81 506 immediate_quit = allow_quit;
ca1d1d23 507
ffd56f97 508 if (count > 0)
9169c321 509 while (start != end)
ca1d1d23 510 {
9169c321
JB
511 /* Our innermost scanning loop is very simple; it doesn't know
512 about gaps, buffer ends, or the newline cache. ceiling is
513 the position of the last character before the next such
514 obstacle --- the last character the dumb search loop should
515 examine. */
516 register int ceiling = end - 1;
517
518 /* If we're looking for a newline, consult the newline cache
519 to see where we can avoid some scanning. */
520 if (target == '\n' && newline_cache)
521 {
522 int next_change;
523 immediate_quit = 0;
524 while (region_cache_forward
525 (current_buffer, newline_cache, start, &next_change))
526 start = next_change;
cbe0db0d 527 immediate_quit = allow_quit;
9169c321
JB
528
529 /* start should never be after end. */
530 if (start >= end)
531 start = end - 1;
532
533 /* Now the text after start is an unknown region, and
534 next_change is the position of the next known region. */
535 ceiling = min (next_change - 1, ceiling);
536 }
537
538 /* The dumb loop can only scan text stored in contiguous
539 bytes. BUFFER_CEILING_OF returns the last character
540 position that is contiguous, so the ceiling is the
541 position after that. */
542 ceiling = min (BUFFER_CEILING_OF (start), ceiling);
543
544 {
545 /* The termination address of the dumb loop. */
5679531d
KH
546 register unsigned char *ceiling_addr = POS_ADDR (ceiling) + 1;
547 register unsigned char *cursor = POS_ADDR (start);
9169c321
JB
548 unsigned char *base = cursor;
549
550 while (cursor < ceiling_addr)
551 {
552 unsigned char *scan_start = cursor;
553
554 /* The dumb loop. */
555 while (*cursor != target && ++cursor < ceiling_addr)
556 ;
557
558 /* If we're looking for newlines, cache the fact that
559 the region from start to cursor is free of them. */
560 if (target == '\n' && newline_cache)
561 know_region_cache (current_buffer, newline_cache,
562 start + scan_start - base,
563 start + cursor - base);
564
565 /* Did we find the target character? */
566 if (cursor < ceiling_addr)
567 {
568 if (--count == 0)
569 {
570 immediate_quit = 0;
571 return (start + cursor - base + 1);
572 }
573 cursor++;
574 }
575 }
576
577 start += cursor - base;
578 }
ca1d1d23
JB
579 }
580 else
9169c321
JB
581 while (start > end)
582 {
583 /* The last character to check before the next obstacle. */
584 register int ceiling = end;
585
586 /* Consult the newline cache, if appropriate. */
587 if (target == '\n' && newline_cache)
588 {
589 int next_change;
590 immediate_quit = 0;
591 while (region_cache_backward
592 (current_buffer, newline_cache, start, &next_change))
593 start = next_change;
cbe0db0d 594 immediate_quit = allow_quit;
9169c321
JB
595
596 /* Start should never be at or before end. */
597 if (start <= end)
598 start = end + 1;
599
600 /* Now the text before start is an unknown region, and
601 next_change is the position of the next known region. */
602 ceiling = max (next_change, ceiling);
603 }
604
605 /* Stop scanning before the gap. */
606 ceiling = max (BUFFER_FLOOR_OF (start - 1), ceiling);
607
608 {
609 /* The termination address of the dumb loop. */
5679531d
KH
610 register unsigned char *ceiling_addr = POS_ADDR (ceiling);
611 register unsigned char *cursor = POS_ADDR (start - 1);
9169c321
JB
612 unsigned char *base = cursor;
613
614 while (cursor >= ceiling_addr)
615 {
616 unsigned char *scan_start = cursor;
617
618 while (*cursor != target && --cursor >= ceiling_addr)
619 ;
620
621 /* If we're looking for newlines, cache the fact that
622 the region from after the cursor to start is free of them. */
623 if (target == '\n' && newline_cache)
624 know_region_cache (current_buffer, newline_cache,
625 start + cursor - base,
626 start + scan_start - base);
627
628 /* Did we find the target character? */
629 if (cursor >= ceiling_addr)
630 {
631 if (++count >= 0)
632 {
633 immediate_quit = 0;
634 return (start + cursor - base);
635 }
636 cursor--;
637 }
638 }
639
640 start += cursor - base;
641 }
642 }
643
ca1d1d23
JB
644 immediate_quit = 0;
645 if (shortage != 0)
ffd56f97 646 *shortage = count * direction;
9169c321 647 return start;
ca1d1d23
JB
648}
649
63fa018d
RS
650int
651find_next_newline_no_quit (from, cnt)
652 register int from, cnt;
653{
9169c321 654 return scan_buffer ('\n', from, 0, cnt, (int *) 0, 0);
63fa018d
RS
655}
656
ca1d1d23
JB
657int
658find_next_newline (from, cnt)
659 register int from, cnt;
660{
9169c321
JB
661 return scan_buffer ('\n', from, 0, cnt, (int *) 0, 1);
662}
663
664
665/* Like find_next_newline, but returns position before the newline,
666 not after, and only search up to TO. This isn't just
667 find_next_newline (...)-1, because you might hit TO. */
668int
669find_before_next_newline (from, to, cnt)
cbe0db0d 670 int from, to, cnt;
9169c321
JB
671{
672 int shortage;
673 int pos = scan_buffer ('\n', from, to, cnt, &shortage, 1);
674
675 if (shortage == 0)
676 pos--;
677
678 return pos;
ca1d1d23
JB
679}
680\f
ca1d1d23
JB
681/* Subroutines of Lisp buffer search functions. */
682
683static Lisp_Object
b819a390 684search_command (string, bound, noerror, count, direction, RE, posix)
ca1d1d23
JB
685 Lisp_Object string, bound, noerror, count;
686 int direction;
687 int RE;
b819a390 688 int posix;
ca1d1d23
JB
689{
690 register int np;
691 int lim;
692 int n = direction;
693
694 if (!NILP (count))
695 {
696 CHECK_NUMBER (count, 3);
697 n *= XINT (count);
698 }
699
700 CHECK_STRING (string, 0);
701 if (NILP (bound))
702 lim = n > 0 ? ZV : BEGV;
703 else
704 {
705 CHECK_NUMBER_COERCE_MARKER (bound, 1);
706 lim = XINT (bound);
6ec8bbd2 707 if (n > 0 ? lim < PT : lim > PT)
ca1d1d23
JB
708 error ("Invalid search bound (wrong side of point)");
709 if (lim > ZV)
710 lim = ZV;
711 if (lim < BEGV)
712 lim = BEGV;
713 }
714
6ec8bbd2 715 np = search_buffer (string, PT, lim, n, RE,
ca1d1d23 716 (!NILP (current_buffer->case_fold_search)
b1428bd8
RS
717 ? XCHAR_TABLE (current_buffer->case_canon_table)->contents
718 : 0),
ca1d1d23 719 (!NILP (current_buffer->case_fold_search)
b1428bd8
RS
720 ? XCHAR_TABLE (current_buffer->case_eqv_table)->contents
721 : 0),
b819a390 722 posix);
ca1d1d23
JB
723 if (np <= 0)
724 {
725 if (NILP (noerror))
726 return signal_failure (string);
727 if (!EQ (noerror, Qt))
728 {
729 if (lim < BEGV || lim > ZV)
730 abort ();
a5f217b8
RS
731 SET_PT (lim);
732 return Qnil;
733#if 0 /* This would be clean, but maybe programs depend on
734 a value of nil here. */
481399bf 735 np = lim;
a5f217b8 736#endif
ca1d1d23 737 }
481399bf
RS
738 else
739 return Qnil;
ca1d1d23
JB
740 }
741
742 if (np < BEGV || np > ZV)
743 abort ();
744
745 SET_PT (np);
746
747 return make_number (np);
748}
749\f
b6d6a51c
KH
750static int
751trivial_regexp_p (regexp)
752 Lisp_Object regexp;
753{
754 int len = XSTRING (regexp)->size;
755 unsigned char *s = XSTRING (regexp)->data;
756 unsigned char c;
757 while (--len >= 0)
758 {
759 switch (*s++)
760 {
761 case '.': case '*': case '+': case '?': case '[': case '^': case '$':
762 return 0;
763 case '\\':
764 if (--len < 0)
765 return 0;
766 switch (*s++)
767 {
768 case '|': case '(': case ')': case '`': case '\'': case 'b':
769 case 'B': case '<': case '>': case 'w': case 'W': case 's':
866f60fd 770 case 'S': case '=':
5679531d 771 case 'c': case 'C': /* for categoryspec and notcategoryspec */
866f60fd 772 case '1': case '2': case '3': case '4': case '5':
b6d6a51c
KH
773 case '6': case '7': case '8': case '9':
774 return 0;
775 }
776 }
777 }
778 return 1;
779}
780
ca325161 781/* Search for the n'th occurrence of STRING in the current buffer,
ca1d1d23 782 starting at position POS and stopping at position LIM,
b819a390 783 treating STRING as a literal string if RE is false or as
ca1d1d23
JB
784 a regular expression if RE is true.
785
786 If N is positive, searching is forward and LIM must be greater than POS.
787 If N is negative, searching is backward and LIM must be less than POS.
788
789 Returns -x if only N-x occurrences found (x > 0),
790 or else the position at the beginning of the Nth occurrence
b819a390
RS
791 (if searching backward) or the end (if searching forward).
792
793 POSIX is nonzero if we want full backtracking (POSIX style)
794 for this pattern. 0 means backtrack only enough to get a valid match. */
ca1d1d23 795
b819a390
RS
796static int
797search_buffer (string, pos, lim, n, RE, trt, inverse_trt, posix)
ca1d1d23
JB
798 Lisp_Object string;
799 int pos;
800 int lim;
801 int n;
802 int RE;
b1428bd8
RS
803 Lisp_Object *trt;
804 Lisp_Object *inverse_trt;
b819a390 805 int posix;
ca1d1d23
JB
806{
807 int len = XSTRING (string)->size;
808 unsigned char *base_pat = XSTRING (string)->data;
809 register int *BM_tab;
810 int *BM_tab_base;
811 register int direction = ((n > 0) ? 1 : -1);
812 register int dirlen;
813 int infinity, limit, k, stride_for_teases;
814 register unsigned char *pat, *cursor, *p_limit;
815 register int i, j;
816 unsigned char *p1, *p2;
817 int s1, s2;
818
7074fde6
FP
819 if (running_asynch_code)
820 save_search_regs ();
821
ca1d1d23 822 /* Null string is found at starting position. */
3f57a499 823 if (len == 0)
ca325161
RS
824 {
825 set_search_regs (pos, 0);
826 return pos;
827 }
3f57a499
RS
828
829 /* Searching 0 times means don't move. */
830 if (n == 0)
ca1d1d23
JB
831 return pos;
832
b6d6a51c 833 if (RE && !trivial_regexp_p (string))
ca1d1d23 834 {
487282dc
KH
835 struct re_pattern_buffer *bufp;
836
b1428bd8 837 bufp = compile_pattern (string, &search_regs, trt, posix);
ca1d1d23 838
ca1d1d23
JB
839 immediate_quit = 1; /* Quit immediately if user types ^G,
840 because letting this function finish
841 can take too long. */
842 QUIT; /* Do a pending quit right away,
843 to avoid paradoxical behavior */
844 /* Get pointers and sizes of the two strings
845 that make up the visible portion of the buffer. */
846
847 p1 = BEGV_ADDR;
848 s1 = GPT - BEGV;
849 p2 = GAP_END_ADDR;
850 s2 = ZV - GPT;
851 if (s1 < 0)
852 {
853 p2 = p1;
854 s2 = ZV - BEGV;
855 s1 = 0;
856 }
857 if (s2 < 0)
858 {
859 s1 = ZV - BEGV;
860 s2 = 0;
861 }
8bb43c28
RS
862 re_match_object = Qnil;
863
ca1d1d23
JB
864 while (n < 0)
865 {
42db823b 866 int val;
487282dc 867 val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
42db823b
RS
868 pos - BEGV, lim - pos, &search_regs,
869 /* Don't allow match past current point */
870 pos - BEGV);
ca1d1d23 871 if (val == -2)
b6d6a51c
KH
872 {
873 matcher_overflow ();
874 }
ca1d1d23
JB
875 if (val >= 0)
876 {
877 j = BEGV;
4746118a 878 for (i = 0; i < search_regs.num_regs; i++)
ca1d1d23
JB
879 if (search_regs.start[i] >= 0)
880 {
881 search_regs.start[i] += j;
882 search_regs.end[i] += j;
883 }
a3668d92 884 XSETBUFFER (last_thing_searched, current_buffer);
ca1d1d23
JB
885 /* Set pos to the new position. */
886 pos = search_regs.start[0];
887 }
888 else
889 {
890 immediate_quit = 0;
891 return (n);
892 }
893 n++;
894 }
895 while (n > 0)
896 {
42db823b 897 int val;
487282dc 898 val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
42db823b
RS
899 pos - BEGV, lim - pos, &search_regs,
900 lim - BEGV);
ca1d1d23 901 if (val == -2)
b6d6a51c
KH
902 {
903 matcher_overflow ();
904 }
ca1d1d23
JB
905 if (val >= 0)
906 {
907 j = BEGV;
4746118a 908 for (i = 0; i < search_regs.num_regs; i++)
ca1d1d23
JB
909 if (search_regs.start[i] >= 0)
910 {
911 search_regs.start[i] += j;
912 search_regs.end[i] += j;
913 }
a3668d92 914 XSETBUFFER (last_thing_searched, current_buffer);
ca1d1d23
JB
915 pos = search_regs.end[0];
916 }
917 else
918 {
919 immediate_quit = 0;
920 return (0 - n);
921 }
922 n--;
923 }
924 immediate_quit = 0;
925 return (pos);
926 }
927 else /* non-RE case */
928 {
929#ifdef C_ALLOCA
930 int BM_tab_space[0400];
931 BM_tab = &BM_tab_space[0];
932#else
933 BM_tab = (int *) alloca (0400 * sizeof (int));
934#endif
b6d6a51c
KH
935 {
936 unsigned char *patbuf = (unsigned char *) alloca (len);
937 pat = patbuf;
938 while (--len >= 0)
939 {
940 /* If we got here and the RE flag is set, it's because we're
941 dealing with a regexp known to be trivial, so the backslash
942 just quotes the next character. */
943 if (RE && *base_pat == '\\')
944 {
945 len--;
946 base_pat++;
947 }
2fd7a4a4 948 *pat++ = (trt ? XINT (trt[*base_pat++]) : *base_pat++);
b6d6a51c
KH
949 }
950 len = pat - patbuf;
951 pat = base_pat = patbuf;
952 }
ca1d1d23
JB
953 /* The general approach is that we are going to maintain that we know */
954 /* the first (closest to the present position, in whatever direction */
955 /* we're searching) character that could possibly be the last */
956 /* (furthest from present position) character of a valid match. We */
957 /* advance the state of our knowledge by looking at that character */
958 /* and seeing whether it indeed matches the last character of the */
959 /* pattern. If it does, we take a closer look. If it does not, we */
960 /* move our pointer (to putative last characters) as far as is */
961 /* logically possible. This amount of movement, which I call a */
962 /* stride, will be the length of the pattern if the actual character */
963 /* appears nowhere in the pattern, otherwise it will be the distance */
964 /* from the last occurrence of that character to the end of the */
965 /* pattern. */
966 /* As a coding trick, an enormous stride is coded into the table for */
967 /* characters that match the last character. This allows use of only */
968 /* a single test, a test for having gone past the end of the */
969 /* permissible match region, to test for both possible matches (when */
970 /* the stride goes past the end immediately) and failure to */
971 /* match (where you get nudged past the end one stride at a time). */
972
973 /* Here we make a "mickey mouse" BM table. The stride of the search */
974 /* is determined only by the last character of the putative match. */
975 /* If that character does not match, we will stride the proper */
976 /* distance to propose a match that superimposes it on the last */
977 /* instance of a character that matches it (per trt), or misses */
978 /* it entirely if there is none. */
979
980 dirlen = len * direction;
981 infinity = dirlen - (lim + pos + len + len) * direction;
982 if (direction < 0)
983 pat = (base_pat += len - 1);
984 BM_tab_base = BM_tab;
985 BM_tab += 0400;
986 j = dirlen; /* to get it in a register */
987 /* A character that does not appear in the pattern induces a */
988 /* stride equal to the pattern length. */
989 while (BM_tab_base != BM_tab)
990 {
991 *--BM_tab = j;
992 *--BM_tab = j;
993 *--BM_tab = j;
994 *--BM_tab = j;
995 }
996 i = 0;
997 while (i != infinity)
998 {
999 j = pat[i]; i += direction;
1000 if (i == dirlen) i = infinity;
8d505039 1001 if (trt != 0)
ca1d1d23 1002 {
2fd7a4a4 1003 k = (j = XINT (trt[j]));
ca1d1d23
JB
1004 if (i == infinity)
1005 stride_for_teases = BM_tab[j];
1006 BM_tab[j] = dirlen - i;
1007 /* A translation table is accompanied by its inverse -- see */
1008 /* comment following downcase_table for details */
2fd7a4a4 1009 while ((j = (unsigned char) XINT (inverse_trt[j])) != k)
ca1d1d23
JB
1010 BM_tab[j] = dirlen - i;
1011 }
1012 else
1013 {
1014 if (i == infinity)
1015 stride_for_teases = BM_tab[j];
1016 BM_tab[j] = dirlen - i;
1017 }
1018 /* stride_for_teases tells how much to stride if we get a */
1019 /* match on the far character but are subsequently */
1020 /* disappointed, by recording what the stride would have been */
1021 /* for that character if the last character had been */
1022 /* different. */
1023 }
1024 infinity = dirlen - infinity;
1025 pos += dirlen - ((direction > 0) ? direction : 0);
1026 /* loop invariant - pos points at where last char (first char if reverse)
1027 of pattern would align in a possible match. */
1028 while (n != 0)
1029 {
b2c71fb4
KH
1030 /* It's been reported that some (broken) compiler thinks that
1031 Boolean expressions in an arithmetic context are unsigned.
1032 Using an explicit ?1:0 prevents this. */
1033 if ((lim - pos - ((direction > 0) ? 1 : 0)) * direction < 0)
ca1d1d23
JB
1034 return (n * (0 - direction));
1035 /* First we do the part we can by pointers (maybe nothing) */
1036 QUIT;
1037 pat = base_pat;
1038 limit = pos - dirlen + direction;
1039 limit = ((direction > 0)
1040 ? BUFFER_CEILING_OF (limit)
1041 : BUFFER_FLOOR_OF (limit));
1042 /* LIMIT is now the last (not beyond-last!) value
1043 POS can take on without hitting edge of buffer or the gap. */
1044 limit = ((direction > 0)
1045 ? min (lim - 1, min (limit, pos + 20000))
1046 : max (lim, max (limit, pos - 20000)));
1047 if ((limit - pos) * direction > 20)
1048 {
5679531d
KH
1049 p_limit = POS_ADDR (limit);
1050 p2 = (cursor = POS_ADDR (pos));
ca1d1d23
JB
1051 /* In this loop, pos + cursor - p2 is the surrogate for pos */
1052 while (1) /* use one cursor setting as long as i can */
1053 {
1054 if (direction > 0) /* worth duplicating */
1055 {
1056 /* Use signed comparison if appropriate
1057 to make cursor+infinity sure to be > p_limit.
1058 Assuming that the buffer lies in a range of addresses
1059 that are all "positive" (as ints) or all "negative",
1060 either kind of comparison will work as long
1061 as we don't step by infinity. So pick the kind
1062 that works when we do step by infinity. */
8d505039 1063 if ((EMACS_INT) (p_limit + infinity) > (EMACS_INT) p_limit)
9fa17f93 1064 while ((EMACS_INT) cursor <= (EMACS_INT) p_limit)
ca1d1d23
JB
1065 cursor += BM_tab[*cursor];
1066 else
45b248b4 1067 while ((EMACS_UINT) cursor <= (EMACS_UINT) p_limit)
ca1d1d23
JB
1068 cursor += BM_tab[*cursor];
1069 }
1070 else
1071 {
8d505039
RS
1072 if ((EMACS_INT) (p_limit + infinity) < (EMACS_INT) p_limit)
1073 while ((EMACS_INT) cursor >= (EMACS_INT) p_limit)
ca1d1d23
JB
1074 cursor += BM_tab[*cursor];
1075 else
45b248b4 1076 while ((EMACS_UINT) cursor >= (EMACS_UINT) p_limit)
ca1d1d23
JB
1077 cursor += BM_tab[*cursor];
1078 }
1079/* If you are here, cursor is beyond the end of the searched region. */
1080 /* This can happen if you match on the far character of the pattern, */
1081 /* because the "stride" of that character is infinity, a number able */
1082 /* to throw you well beyond the end of the search. It can also */
1083 /* happen if you fail to match within the permitted region and would */
1084 /* otherwise try a character beyond that region */
1085 if ((cursor - p_limit) * direction <= len)
1086 break; /* a small overrun is genuine */
1087 cursor -= infinity; /* large overrun = hit */
1088 i = dirlen - direction;
8d505039 1089 if (trt != 0)
ca1d1d23
JB
1090 {
1091 while ((i -= direction) + direction != 0)
2fd7a4a4 1092 if (pat[i] != XINT (trt[*(cursor -= direction)]))
ca1d1d23
JB
1093 break;
1094 }
1095 else
1096 {
1097 while ((i -= direction) + direction != 0)
1098 if (pat[i] != *(cursor -= direction))
1099 break;
1100 }
1101 cursor += dirlen - i - direction; /* fix cursor */
1102 if (i + direction == 0)
1103 {
1104 cursor -= direction;
1113d9db 1105
ca325161
RS
1106 set_search_regs (pos + cursor - p2 + ((direction > 0)
1107 ? 1 - len : 0),
1108 len);
1109
ca1d1d23
JB
1110 if ((n -= direction) != 0)
1111 cursor += dirlen; /* to resume search */
1112 else
1113 return ((direction > 0)
1114 ? search_regs.end[0] : search_regs.start[0]);
1115 }
1116 else
1117 cursor += stride_for_teases; /* <sigh> we lose - */
1118 }
1119 pos += cursor - p2;
1120 }
1121 else
1122 /* Now we'll pick up a clump that has to be done the hard */
1123 /* way because it covers a discontinuity */
1124 {
1125 limit = ((direction > 0)
1126 ? BUFFER_CEILING_OF (pos - dirlen + 1)
1127 : BUFFER_FLOOR_OF (pos - dirlen - 1));
1128 limit = ((direction > 0)
1129 ? min (limit + len, lim - 1)
1130 : max (limit - len, lim));
1131 /* LIMIT is now the last value POS can have
1132 and still be valid for a possible match. */
1133 while (1)
1134 {
1135 /* This loop can be coded for space rather than */
1136 /* speed because it will usually run only once. */
1137 /* (the reach is at most len + 21, and typically */
1138 /* does not exceed len) */
1139 while ((limit - pos) * direction >= 0)
5679531d 1140 pos += BM_tab[FETCH_BYTE (pos)];
ca1d1d23 1141 /* now run the same tests to distinguish going off the */
eb8c3be9 1142 /* end, a match or a phony match. */
ca1d1d23
JB
1143 if ((pos - limit) * direction <= len)
1144 break; /* ran off the end */
1145 /* Found what might be a match.
1146 Set POS back to last (first if reverse) char pos. */
1147 pos -= infinity;
1148 i = dirlen - direction;
1149 while ((i -= direction) + direction != 0)
1150 {
1151 pos -= direction;
8d505039 1152 if (pat[i] != (trt != 0
2fd7a4a4 1153 ? XINT (trt[FETCH_BYTE (pos)])
5679531d 1154 : FETCH_BYTE (pos)))
ca1d1d23
JB
1155 break;
1156 }
1157 /* Above loop has moved POS part or all the way
1158 back to the first char pos (last char pos if reverse).
1159 Set it once again at the last (first if reverse) char. */
1160 pos += dirlen - i- direction;
1161 if (i + direction == 0)
1162 {
1163 pos -= direction;
1113d9db 1164
ca325161
RS
1165 set_search_regs (pos + ((direction > 0) ? 1 - len : 0),
1166 len);
1167
ca1d1d23
JB
1168 if ((n -= direction) != 0)
1169 pos += dirlen; /* to resume search */
1170 else
1171 return ((direction > 0)
1172 ? search_regs.end[0] : search_regs.start[0]);
1173 }
1174 else
1175 pos += stride_for_teases;
1176 }
1177 }
1178 /* We have done one clump. Can we continue? */
1179 if ((lim - pos) * direction < 0)
1180 return ((0 - n) * direction);
1181 }
1182 return pos;
1183 }
1184}
ca325161
RS
1185
1186/* Record beginning BEG and end BEG + LEN
1187 for a match just found in the current buffer. */
1188
1189static void
1190set_search_regs (beg, len)
1191 int beg, len;
1192{
1193 /* Make sure we have registers in which to store
1194 the match position. */
1195 if (search_regs.num_regs == 0)
1196 {
2d4a771a
RS
1197 search_regs.start = (regoff_t *) xmalloc (2 * sizeof (regoff_t));
1198 search_regs.end = (regoff_t *) xmalloc (2 * sizeof (regoff_t));
487282dc 1199 search_regs.num_regs = 2;
ca325161
RS
1200 }
1201
1202 search_regs.start[0] = beg;
1203 search_regs.end[0] = beg + len;
a3668d92 1204 XSETBUFFER (last_thing_searched, current_buffer);
ca325161 1205}
ca1d1d23
JB
1206\f
1207/* Given a string of words separated by word delimiters,
1208 compute a regexp that matches those exact words
1209 separated by arbitrary punctuation. */
1210
1211static Lisp_Object
1212wordify (string)
1213 Lisp_Object string;
1214{
1215 register unsigned char *p, *o;
1216 register int i, len, punct_count = 0, word_count = 0;
1217 Lisp_Object val;
1218
1219 CHECK_STRING (string, 0);
1220 p = XSTRING (string)->data;
1221 len = XSTRING (string)->size;
1222
1223 for (i = 0; i < len; i++)
1224 if (SYNTAX (p[i]) != Sword)
1225 {
1226 punct_count++;
1227 if (i > 0 && SYNTAX (p[i-1]) == Sword) word_count++;
1228 }
1229 if (SYNTAX (p[len-1]) == Sword) word_count++;
1230 if (!word_count) return build_string ("");
1231
1232 val = make_string (p, len - punct_count + 5 * (word_count - 1) + 4);
1233
1234 o = XSTRING (val)->data;
1235 *o++ = '\\';
1236 *o++ = 'b';
1237
1238 for (i = 0; i < len; i++)
1239 if (SYNTAX (p[i]) == Sword)
1240 *o++ = p[i];
1241 else if (i > 0 && SYNTAX (p[i-1]) == Sword && --word_count)
1242 {
1243 *o++ = '\\';
1244 *o++ = 'W';
1245 *o++ = '\\';
1246 *o++ = 'W';
1247 *o++ = '*';
1248 }
1249
1250 *o++ = '\\';
1251 *o++ = 'b';
1252
1253 return val;
1254}
1255\f
1256DEFUN ("search-backward", Fsearch_backward, Ssearch_backward, 1, 4,
6af43974 1257 "MSearch backward: ",
ca1d1d23
JB
1258 "Search backward from point for STRING.\n\
1259Set point to the beginning of the occurrence found, and return point.\n\
1260An optional second argument bounds the search; it is a buffer position.\n\
1261The match found must not extend before that position.\n\
1262Optional third argument, if t, means if fail just return nil (no error).\n\
1263 If not nil and not t, position at limit of search and return nil.\n\
1264Optional fourth argument is repeat count--search for successive occurrences.\n\
1265See also the functions `match-beginning', `match-end' and `replace-match'.")
1266 (string, bound, noerror, count)
1267 Lisp_Object string, bound, noerror, count;
1268{
b819a390 1269 return search_command (string, bound, noerror, count, -1, 0, 0);
ca1d1d23
JB
1270}
1271
6af43974 1272DEFUN ("search-forward", Fsearch_forward, Ssearch_forward, 1, 4, "MSearch: ",
ca1d1d23
JB
1273 "Search forward from point for STRING.\n\
1274Set point to the end of the occurrence found, and return point.\n\
1275An optional second argument bounds the search; it is a buffer position.\n\
1276The match found must not extend after that position. nil is equivalent\n\
1277 to (point-max).\n\
1278Optional third argument, if t, means if fail just return nil (no error).\n\
1279 If not nil and not t, move to limit of search and return nil.\n\
1280Optional fourth argument is repeat count--search for successive occurrences.\n\
1281See also the functions `match-beginning', `match-end' and `replace-match'.")
1282 (string, bound, noerror, count)
1283 Lisp_Object string, bound, noerror, count;
1284{
b819a390 1285 return search_command (string, bound, noerror, count, 1, 0, 0);
ca1d1d23
JB
1286}
1287
1288DEFUN ("word-search-backward", Fword_search_backward, Sword_search_backward, 1, 4,
1289 "sWord search backward: ",
1290 "Search backward from point for STRING, ignoring differences in punctuation.\n\
1291Set point to the beginning of the occurrence found, and return point.\n\
1292An optional second argument bounds the search; it is a buffer position.\n\
1293The match found must not extend before that position.\n\
1294Optional third argument, if t, means if fail just return nil (no error).\n\
1295 If not nil and not t, move to limit of search and return nil.\n\
1296Optional fourth argument is repeat count--search for successive occurrences.")
1297 (string, bound, noerror, count)
1298 Lisp_Object string, bound, noerror, count;
1299{
b819a390 1300 return search_command (wordify (string), bound, noerror, count, -1, 1, 0);
ca1d1d23
JB
1301}
1302
1303DEFUN ("word-search-forward", Fword_search_forward, Sword_search_forward, 1, 4,
1304 "sWord search: ",
1305 "Search forward from point for STRING, ignoring differences in punctuation.\n\
1306Set point to the end of the occurrence found, and return point.\n\
1307An optional second argument bounds the search; it is a buffer position.\n\
1308The match found must not extend after that position.\n\
1309Optional third argument, if t, means if fail just return nil (no error).\n\
1310 If not nil and not t, move to limit of search and return nil.\n\
1311Optional fourth argument is repeat count--search for successive occurrences.")
1312 (string, bound, noerror, count)
1313 Lisp_Object string, bound, noerror, count;
1314{
b819a390 1315 return search_command (wordify (string), bound, noerror, count, 1, 1, 0);
ca1d1d23
JB
1316}
1317
1318DEFUN ("re-search-backward", Fre_search_backward, Sre_search_backward, 1, 4,
1319 "sRE search backward: ",
1320 "Search backward from point for match for regular expression REGEXP.\n\
1321Set point to the beginning of the match, and return point.\n\
1322The match found is the one starting last in the buffer\n\
19c0a730 1323and yet ending before the origin of the search.\n\
ca1d1d23
JB
1324An optional second argument bounds the search; it is a buffer position.\n\
1325The match found must start at or after that position.\n\
1326Optional third argument, if t, means if fail just return nil (no error).\n\
1327 If not nil and not t, move to limit of search and return nil.\n\
1328Optional fourth argument is repeat count--search for successive occurrences.\n\
1329See also the functions `match-beginning', `match-end' and `replace-match'.")
19c0a730
KH
1330 (regexp, bound, noerror, count)
1331 Lisp_Object regexp, bound, noerror, count;
ca1d1d23 1332{
b819a390 1333 return search_command (regexp, bound, noerror, count, -1, 1, 0);
ca1d1d23
JB
1334}
1335
1336DEFUN ("re-search-forward", Fre_search_forward, Sre_search_forward, 1, 4,
1337 "sRE search: ",
1338 "Search forward from point for regular expression REGEXP.\n\
1339Set point to the end of the occurrence found, and return point.\n\
1340An optional second argument bounds the search; it is a buffer position.\n\
1341The match found must not extend after that position.\n\
1342Optional third argument, if t, means if fail just return nil (no error).\n\
1343 If not nil and not t, move to limit of search and return nil.\n\
1344Optional fourth argument is repeat count--search for successive occurrences.\n\
1345See also the functions `match-beginning', `match-end' and `replace-match'.")
19c0a730
KH
1346 (regexp, bound, noerror, count)
1347 Lisp_Object regexp, bound, noerror, count;
ca1d1d23 1348{
b819a390
RS
1349 return search_command (regexp, bound, noerror, count, 1, 1, 0);
1350}
1351
1352DEFUN ("posix-search-backward", Fposix_search_backward, Sposix_search_backward, 1, 4,
1353 "sPosix search backward: ",
1354 "Search backward from point for match for regular expression REGEXP.\n\
1355Find the longest match in accord with Posix regular expression rules.\n\
1356Set point to the beginning of the match, and return point.\n\
1357The match found is the one starting last in the buffer\n\
1358and yet ending before the origin of the search.\n\
1359An optional second argument bounds the search; it is a buffer position.\n\
1360The match found must start at or after that position.\n\
1361Optional third argument, if t, means if fail just return nil (no error).\n\
1362 If not nil and not t, move to limit of search and return nil.\n\
1363Optional fourth argument is repeat count--search for successive occurrences.\n\
1364See also the functions `match-beginning', `match-end' and `replace-match'.")
1365 (regexp, bound, noerror, count)
1366 Lisp_Object regexp, bound, noerror, count;
1367{
1368 return search_command (regexp, bound, noerror, count, -1, 1, 1);
1369}
1370
1371DEFUN ("posix-search-forward", Fposix_search_forward, Sposix_search_forward, 1, 4,
1372 "sPosix search: ",
1373 "Search forward from point for regular expression REGEXP.\n\
1374Find the longest match in accord with Posix regular expression rules.\n\
1375Set point to the end of the occurrence found, and return point.\n\
1376An optional second argument bounds the search; it is a buffer position.\n\
1377The match found must not extend after that position.\n\
1378Optional third argument, if t, means if fail just return nil (no error).\n\
1379 If not nil and not t, move to limit of search and return nil.\n\
1380Optional fourth argument is repeat count--search for successive occurrences.\n\
1381See also the functions `match-beginning', `match-end' and `replace-match'.")
1382 (regexp, bound, noerror, count)
1383 Lisp_Object regexp, bound, noerror, count;
1384{
1385 return search_command (regexp, bound, noerror, count, 1, 1, 1);
ca1d1d23
JB
1386}
1387\f
d7a5ad5f 1388DEFUN ("replace-match", Freplace_match, Sreplace_match, 1, 5, 0,
ca1d1d23
JB
1389 "Replace text matched by last search with NEWTEXT.\n\
1390If second arg FIXEDCASE is non-nil, do not alter case of replacement text.\n\
5b9cf4b2
RS
1391Otherwise maybe capitalize the whole text, or maybe just word initials,\n\
1392based on the replaced text.\n\
1393If the replaced text has only capital letters\n\
1394and has at least one multiletter word, convert NEWTEXT to all caps.\n\
1395If the replaced text has at least one word starting with a capital letter,\n\
1396then capitalize each word in NEWTEXT.\n\n\
ca1d1d23
JB
1397If third arg LITERAL is non-nil, insert NEWTEXT literally.\n\
1398Otherwise treat `\\' as special:\n\
1399 `\\&' in NEWTEXT means substitute original matched text.\n\
1400 `\\N' means substitute what matched the Nth `\\(...\\)'.\n\
1401 If Nth parens didn't match, substitute nothing.\n\
1402 `\\\\' means insert one `\\'.\n\
1113d9db 1403FIXEDCASE and LITERAL are optional arguments.\n\
080c45fd
RS
1404Leaves point at end of replacement text.\n\
1405\n\
1406The optional fourth argument STRING can be a string to modify.\n\
1407In that case, this function creates and returns a new string\n\
d7a5ad5f
RS
1408which is made by replacing the part of STRING that was matched.\n\
1409\n\
1410The optional fifth argument SUBEXP specifies a subexpression of the match.\n\
1411It says to replace just that subexpression instead of the whole match.\n\
1412This is useful only after a regular expression search or match\n\
1413since only regular expressions have distinguished subexpressions.")
1414 (newtext, fixedcase, literal, string, subexp)
1415 Lisp_Object newtext, fixedcase, literal, string, subexp;
ca1d1d23
JB
1416{
1417 enum { nochange, all_caps, cap_initial } case_action;
1418 register int pos, last;
1419 int some_multiletter_word;
97832bd0 1420 int some_lowercase;
73dc8771 1421 int some_uppercase;
208767c3 1422 int some_nonuppercase_initial;
ca1d1d23
JB
1423 register int c, prevc;
1424 int inslen;
d7a5ad5f 1425 int sub;
3e18eecf 1426 int opoint, newpoint;
ca1d1d23 1427
16fdc568 1428 CHECK_STRING (newtext, 0);
ca1d1d23 1429
080c45fd
RS
1430 if (! NILP (string))
1431 CHECK_STRING (string, 4);
1432
ca1d1d23
JB
1433 case_action = nochange; /* We tried an initialization */
1434 /* but some C compilers blew it */
4746118a
JB
1435
1436 if (search_regs.num_regs <= 0)
1437 error ("replace-match called before any match found");
1438
d7a5ad5f
RS
1439 if (NILP (subexp))
1440 sub = 0;
1441 else
1442 {
1443 CHECK_NUMBER (subexp, 3);
1444 sub = XINT (subexp);
1445 if (sub < 0 || sub >= search_regs.num_regs)
1446 args_out_of_range (subexp, make_number (search_regs.num_regs));
1447 }
1448
080c45fd
RS
1449 if (NILP (string))
1450 {
d7a5ad5f
RS
1451 if (search_regs.start[sub] < BEGV
1452 || search_regs.start[sub] > search_regs.end[sub]
1453 || search_regs.end[sub] > ZV)
1454 args_out_of_range (make_number (search_regs.start[sub]),
1455 make_number (search_regs.end[sub]));
080c45fd
RS
1456 }
1457 else
1458 {
d7a5ad5f
RS
1459 if (search_regs.start[sub] < 0
1460 || search_regs.start[sub] > search_regs.end[sub]
1461 || search_regs.end[sub] > XSTRING (string)->size)
1462 args_out_of_range (make_number (search_regs.start[sub]),
1463 make_number (search_regs.end[sub]));
080c45fd 1464 }
ca1d1d23
JB
1465
1466 if (NILP (fixedcase))
1467 {
1468 /* Decide how to casify by examining the matched text. */
1469
d7a5ad5f 1470 last = search_regs.end[sub];
ca1d1d23
JB
1471 prevc = '\n';
1472 case_action = all_caps;
1473
1474 /* some_multiletter_word is set nonzero if any original word
1475 is more than one letter long. */
1476 some_multiletter_word = 0;
97832bd0 1477 some_lowercase = 0;
208767c3 1478 some_nonuppercase_initial = 0;
73dc8771 1479 some_uppercase = 0;
ca1d1d23 1480
d7a5ad5f 1481 for (pos = search_regs.start[sub]; pos < last; pos++)
ca1d1d23 1482 {
080c45fd 1483 if (NILP (string))
5679531d 1484 c = FETCH_BYTE (pos);
080c45fd
RS
1485 else
1486 c = XSTRING (string)->data[pos];
1487
ca1d1d23
JB
1488 if (LOWERCASEP (c))
1489 {
1490 /* Cannot be all caps if any original char is lower case */
1491
97832bd0 1492 some_lowercase = 1;
ca1d1d23 1493 if (SYNTAX (prevc) != Sword)
208767c3 1494 some_nonuppercase_initial = 1;
ca1d1d23
JB
1495 else
1496 some_multiletter_word = 1;
1497 }
1498 else if (!NOCASEP (c))
1499 {
73dc8771 1500 some_uppercase = 1;
97832bd0 1501 if (SYNTAX (prevc) != Sword)
c4d460ce 1502 ;
97832bd0 1503 else
ca1d1d23
JB
1504 some_multiletter_word = 1;
1505 }
208767c3
RS
1506 else
1507 {
1508 /* If the initial is a caseless word constituent,
1509 treat that like a lowercase initial. */
1510 if (SYNTAX (prevc) != Sword)
1511 some_nonuppercase_initial = 1;
1512 }
ca1d1d23
JB
1513
1514 prevc = c;
1515 }
1516
97832bd0
RS
1517 /* Convert to all caps if the old text is all caps
1518 and has at least one multiletter word. */
1519 if (! some_lowercase && some_multiletter_word)
1520 case_action = all_caps;
c4d460ce 1521 /* Capitalize each word, if the old text has all capitalized words. */
208767c3 1522 else if (!some_nonuppercase_initial && some_multiletter_word)
ca1d1d23 1523 case_action = cap_initial;
208767c3 1524 else if (!some_nonuppercase_initial && some_uppercase)
73dc8771
KH
1525 /* Should x -> yz, operating on X, give Yz or YZ?
1526 We'll assume the latter. */
1527 case_action = all_caps;
97832bd0
RS
1528 else
1529 case_action = nochange;
ca1d1d23
JB
1530 }
1531
080c45fd
RS
1532 /* Do replacement in a string. */
1533 if (!NILP (string))
1534 {
1535 Lisp_Object before, after;
1536
1537 before = Fsubstring (string, make_number (0),
d7a5ad5f
RS
1538 make_number (search_regs.start[sub]));
1539 after = Fsubstring (string, make_number (search_regs.end[sub]), Qnil);
080c45fd 1540
636a5e28
RS
1541 /* Substitute parts of the match into NEWTEXT
1542 if desired. */
080c45fd
RS
1543 if (NILP (literal))
1544 {
1545 int lastpos = -1;
1546 /* We build up the substituted string in ACCUM. */
1547 Lisp_Object accum;
1548 Lisp_Object middle;
1549
1550 accum = Qnil;
1551
1552 for (pos = 0; pos < XSTRING (newtext)->size; pos++)
1553 {
1554 int substart = -1;
1555 int subend;
1e79ec24 1556 int delbackslash = 0;
080c45fd
RS
1557
1558 c = XSTRING (newtext)->data[pos];
1559 if (c == '\\')
1560 {
1561 c = XSTRING (newtext)->data[++pos];
1562 if (c == '&')
1563 {
d7a5ad5f
RS
1564 substart = search_regs.start[sub];
1565 subend = search_regs.end[sub];
080c45fd
RS
1566 }
1567 else if (c >= '1' && c <= '9' && c <= search_regs.num_regs + '0')
1568 {
ad10348f 1569 if (search_regs.start[c - '0'] >= 0)
080c45fd
RS
1570 {
1571 substart = search_regs.start[c - '0'];
1572 subend = search_regs.end[c - '0'];
1573 }
1574 }
1e79ec24
KH
1575 else if (c == '\\')
1576 delbackslash = 1;
636a5e28
RS
1577 else
1578 error ("Invalid use of `\\' in replacement text");
080c45fd
RS
1579 }
1580 if (substart >= 0)
1581 {
1582 if (pos - 1 != lastpos + 1)
1e79ec24
KH
1583 middle = Fsubstring (newtext,
1584 make_number (lastpos + 1),
1585 make_number (pos - 1));
080c45fd
RS
1586 else
1587 middle = Qnil;
1588 accum = concat3 (accum, middle,
1589 Fsubstring (string, make_number (substart),
1590 make_number (subend)));
1591 lastpos = pos;
1592 }
1e79ec24
KH
1593 else if (delbackslash)
1594 {
1595 middle = Fsubstring (newtext, make_number (lastpos + 1),
1596 make_number (pos));
1597 accum = concat2 (accum, middle);
1598 lastpos = pos;
1599 }
080c45fd
RS
1600 }
1601
1602 if (pos != lastpos + 1)
1e79ec24
KH
1603 middle = Fsubstring (newtext, make_number (lastpos + 1),
1604 make_number (pos));
080c45fd
RS
1605 else
1606 middle = Qnil;
1607
1608 newtext = concat2 (accum, middle);
1609 }
1610
636a5e28 1611 /* Do case substitution in NEWTEXT if desired. */
080c45fd
RS
1612 if (case_action == all_caps)
1613 newtext = Fupcase (newtext);
1614 else if (case_action == cap_initial)
2b2eead9 1615 newtext = Fupcase_initials (newtext);
080c45fd
RS
1616
1617 return concat3 (before, newtext, after);
1618 }
1619
b0eba991
RS
1620 /* Record point, the move (quietly) to the start of the match. */
1621 if (PT > search_regs.start[sub])
1622 opoint = PT - ZV;
1623 else
1624 opoint = PT;
1625
1626 temp_set_point (search_regs.start[sub], current_buffer);
1627
9a76659d
JB
1628 /* We insert the replacement text before the old text, and then
1629 delete the original text. This means that markers at the
1630 beginning or end of the original will float to the corresponding
1631 position in the replacement. */
ca1d1d23 1632 if (!NILP (literal))
16fdc568 1633 Finsert_and_inherit (1, &newtext);
ca1d1d23
JB
1634 else
1635 {
1636 struct gcpro gcpro1;
16fdc568 1637 GCPRO1 (newtext);
ca1d1d23 1638
16fdc568 1639 for (pos = 0; pos < XSTRING (newtext)->size; pos++)
ca1d1d23 1640 {
6ec8bbd2 1641 int offset = PT - search_regs.start[sub];
9a76659d 1642
16fdc568 1643 c = XSTRING (newtext)->data[pos];
ca1d1d23
JB
1644 if (c == '\\')
1645 {
16fdc568 1646 c = XSTRING (newtext)->data[++pos];
ca1d1d23 1647 if (c == '&')
9a76659d
JB
1648 Finsert_buffer_substring
1649 (Fcurrent_buffer (),
d7a5ad5f
RS
1650 make_number (search_regs.start[sub] + offset),
1651 make_number (search_regs.end[sub] + offset));
78445046 1652 else if (c >= '1' && c <= '9' && c <= search_regs.num_regs + '0')
ca1d1d23
JB
1653 {
1654 if (search_regs.start[c - '0'] >= 1)
9a76659d
JB
1655 Finsert_buffer_substring
1656 (Fcurrent_buffer (),
1657 make_number (search_regs.start[c - '0'] + offset),
1658 make_number (search_regs.end[c - '0'] + offset));
ca1d1d23 1659 }
636a5e28 1660 else if (c == '\\')
ca1d1d23 1661 insert_char (c);
636a5e28
RS
1662 else
1663 error ("Invalid use of `\\' in replacement text");
ca1d1d23
JB
1664 }
1665 else
1666 insert_char (c);
1667 }
1668 UNGCPRO;
1669 }
1670
6ec8bbd2 1671 inslen = PT - (search_regs.start[sub]);
d7a5ad5f 1672 del_range (search_regs.start[sub] + inslen, search_regs.end[sub] + inslen);
ca1d1d23
JB
1673
1674 if (case_action == all_caps)
6ec8bbd2 1675 Fupcase_region (make_number (PT - inslen), make_number (PT));
ca1d1d23 1676 else if (case_action == cap_initial)
6ec8bbd2 1677 Fupcase_initials_region (make_number (PT - inslen), make_number (PT));
b0eba991 1678
3e18eecf
RS
1679 newpoint = PT;
1680
b0eba991 1681 /* Put point back where it was in the text. */
8d808a65 1682 if (opoint <= 0)
b0eba991
RS
1683 temp_set_point (opoint + ZV, current_buffer);
1684 else
1685 temp_set_point (opoint, current_buffer);
1686
1687 /* Now move point "officially" to the start of the inserted replacement. */
3e18eecf 1688 move_if_not_intangible (newpoint);
b0eba991 1689
ca1d1d23
JB
1690 return Qnil;
1691}
1692\f
1693static Lisp_Object
1694match_limit (num, beginningp)
1695 Lisp_Object num;
1696 int beginningp;
1697{
1698 register int n;
1699
1700 CHECK_NUMBER (num, 0);
1701 n = XINT (num);
4746118a
JB
1702 if (n < 0 || n >= search_regs.num_regs)
1703 args_out_of_range (num, make_number (search_regs.num_regs));
1704 if (search_regs.num_regs <= 0
1705 || search_regs.start[n] < 0)
ca1d1d23
JB
1706 return Qnil;
1707 return (make_number ((beginningp) ? search_regs.start[n]
1708 : search_regs.end[n]));
1709}
1710
1711DEFUN ("match-beginning", Fmatch_beginning, Smatch_beginning, 1, 1, 0,
1712 "Return position of start of text matched by last search.\n\
5806161b
EN
1713SUBEXP, a number, specifies which parenthesized expression in the last\n\
1714 regexp.\n\
1715Value is nil if SUBEXPth pair didn't match, or there were less than\n\
1716 SUBEXP pairs.\n\
ca1d1d23 1717Zero means the entire text matched by the whole regexp or whole string.")
5806161b
EN
1718 (subexp)
1719 Lisp_Object subexp;
ca1d1d23 1720{
5806161b 1721 return match_limit (subexp, 1);
ca1d1d23
JB
1722}
1723
1724DEFUN ("match-end", Fmatch_end, Smatch_end, 1, 1, 0,
1725 "Return position of end of text matched by last search.\n\
5806161b
EN
1726SUBEXP, a number, specifies which parenthesized expression in the last\n\
1727 regexp.\n\
1728Value is nil if SUBEXPth pair didn't match, or there were less than\n\
1729 SUBEXP pairs.\n\
ca1d1d23 1730Zero means the entire text matched by the whole regexp or whole string.")
5806161b
EN
1731 (subexp)
1732 Lisp_Object subexp;
ca1d1d23 1733{
5806161b 1734 return match_limit (subexp, 0);
ca1d1d23
JB
1735}
1736
56256c2a 1737DEFUN ("match-data", Fmatch_data, Smatch_data, 0, 2, 0,
ca1d1d23
JB
1738 "Return a list containing all info on what the last search matched.\n\
1739Element 2N is `(match-beginning N)'; element 2N + 1 is `(match-end N)'.\n\
1740All the elements are markers or nil (nil if the Nth pair didn't match)\n\
1741if the last match was on a buffer; integers or nil if a string was matched.\n\
56256c2a
RS
1742Use `store-match-data' to reinstate the data in this list.\n\
1743\n\
1744If INTEGERS (the optional first argument) is non-nil, always use integers\n\
8ca821e9 1745\(rather than markers) to represent buffer positions.\n\
56256c2a
RS
1746If REUSE is a list, reuse it as part of the value. If REUSE is long enough\n\
1747to hold all the values, and if INTEGERS is non-nil, no consing is done.")
1748 (integers, reuse)
1749 Lisp_Object integers, reuse;
ca1d1d23 1750{
56256c2a 1751 Lisp_Object tail, prev;
4746118a 1752 Lisp_Object *data;
ca1d1d23
JB
1753 int i, len;
1754
daa37602 1755 if (NILP (last_thing_searched))
c36bcf1b 1756 return Qnil;
daa37602 1757
4746118a
JB
1758 data = (Lisp_Object *) alloca ((2 * search_regs.num_regs)
1759 * sizeof (Lisp_Object));
1760
ca1d1d23 1761 len = -1;
4746118a 1762 for (i = 0; i < search_regs.num_regs; i++)
ca1d1d23
JB
1763 {
1764 int start = search_regs.start[i];
1765 if (start >= 0)
1766 {
56256c2a
RS
1767 if (EQ (last_thing_searched, Qt)
1768 || ! NILP (integers))
ca1d1d23 1769 {
c235cce7
KH
1770 XSETFASTINT (data[2 * i], start);
1771 XSETFASTINT (data[2 * i + 1], search_regs.end[i]);
ca1d1d23 1772 }
0ed62dc7 1773 else if (BUFFERP (last_thing_searched))
ca1d1d23
JB
1774 {
1775 data[2 * i] = Fmake_marker ();
daa37602
JB
1776 Fset_marker (data[2 * i],
1777 make_number (start),
1778 last_thing_searched);
ca1d1d23
JB
1779 data[2 * i + 1] = Fmake_marker ();
1780 Fset_marker (data[2 * i + 1],
daa37602
JB
1781 make_number (search_regs.end[i]),
1782 last_thing_searched);
ca1d1d23 1783 }
daa37602
JB
1784 else
1785 /* last_thing_searched must always be Qt, a buffer, or Qnil. */
1786 abort ();
1787
ca1d1d23
JB
1788 len = i;
1789 }
1790 else
1791 data[2 * i] = data [2 * i + 1] = Qnil;
1792 }
56256c2a
RS
1793
1794 /* If REUSE is not usable, cons up the values and return them. */
1795 if (! CONSP (reuse))
1796 return Flist (2 * len + 2, data);
1797
1798 /* If REUSE is a list, store as many value elements as will fit
1799 into the elements of REUSE. */
1800 for (i = 0, tail = reuse; CONSP (tail);
1801 i++, tail = XCONS (tail)->cdr)
1802 {
1803 if (i < 2 * len + 2)
1804 XCONS (tail)->car = data[i];
1805 else
1806 XCONS (tail)->car = Qnil;
1807 prev = tail;
1808 }
1809
1810 /* If we couldn't fit all value elements into REUSE,
1811 cons up the rest of them and add them to the end of REUSE. */
1812 if (i < 2 * len + 2)
1813 XCONS (prev)->cdr = Flist (2 * len + 2 - i, data + i);
1814
1815 return reuse;
ca1d1d23
JB
1816}
1817
1818
1819DEFUN ("store-match-data", Fstore_match_data, Sstore_match_data, 1, 1, 0,
1820 "Set internal data on last search match from elements of LIST.\n\
1821LIST should have been created by calling `match-data' previously.")
1822 (list)
1823 register Lisp_Object list;
1824{
1825 register int i;
1826 register Lisp_Object marker;
1827
7074fde6
FP
1828 if (running_asynch_code)
1829 save_search_regs ();
1830
ca1d1d23 1831 if (!CONSP (list) && !NILP (list))
b37902c8 1832 list = wrong_type_argument (Qconsp, list);
ca1d1d23 1833
daa37602
JB
1834 /* Unless we find a marker with a buffer in LIST, assume that this
1835 match data came from a string. */
1836 last_thing_searched = Qt;
1837
4746118a
JB
1838 /* Allocate registers if they don't already exist. */
1839 {
d084e942 1840 int length = XFASTINT (Flength (list)) / 2;
4746118a
JB
1841
1842 if (length > search_regs.num_regs)
1843 {
1113d9db
JB
1844 if (search_regs.num_regs == 0)
1845 {
1846 search_regs.start
1847 = (regoff_t *) xmalloc (length * sizeof (regoff_t));
1848 search_regs.end
1849 = (regoff_t *) xmalloc (length * sizeof (regoff_t));
1850 }
4746118a 1851 else
1113d9db
JB
1852 {
1853 search_regs.start
1854 = (regoff_t *) xrealloc (search_regs.start,
1855 length * sizeof (regoff_t));
1856 search_regs.end
1857 = (regoff_t *) xrealloc (search_regs.end,
1858 length * sizeof (regoff_t));
1859 }
4746118a 1860
487282dc 1861 search_regs.num_regs = length;
4746118a
JB
1862 }
1863 }
1864
1865 for (i = 0; i < search_regs.num_regs; i++)
ca1d1d23
JB
1866 {
1867 marker = Fcar (list);
1868 if (NILP (marker))
1869 {
1870 search_regs.start[i] = -1;
1871 list = Fcdr (list);
1872 }
1873 else
1874 {
0ed62dc7 1875 if (MARKERP (marker))
daa37602
JB
1876 {
1877 if (XMARKER (marker)->buffer == 0)
c235cce7 1878 XSETFASTINT (marker, 0);
daa37602 1879 else
a3668d92 1880 XSETBUFFER (last_thing_searched, XMARKER (marker)->buffer);
daa37602 1881 }
ca1d1d23
JB
1882
1883 CHECK_NUMBER_COERCE_MARKER (marker, 0);
1884 search_regs.start[i] = XINT (marker);
1885 list = Fcdr (list);
1886
1887 marker = Fcar (list);
0ed62dc7 1888 if (MARKERP (marker) && XMARKER (marker)->buffer == 0)
c235cce7 1889 XSETFASTINT (marker, 0);
ca1d1d23
JB
1890
1891 CHECK_NUMBER_COERCE_MARKER (marker, 0);
1892 search_regs.end[i] = XINT (marker);
1893 }
1894 list = Fcdr (list);
1895 }
1896
1897 return Qnil;
1898}
1899
7074fde6
FP
1900/* If non-zero the match data have been saved in saved_search_regs
1901 during the execution of a sentinel or filter. */
75ebf74b 1902static int search_regs_saved;
7074fde6
FP
1903static struct re_registers saved_search_regs;
1904
1905/* Called from Flooking_at, Fstring_match, search_buffer, Fstore_match_data
1906 if asynchronous code (filter or sentinel) is running. */
1907static void
1908save_search_regs ()
1909{
1910 if (!search_regs_saved)
1911 {
1912 saved_search_regs.num_regs = search_regs.num_regs;
1913 saved_search_regs.start = search_regs.start;
1914 saved_search_regs.end = search_regs.end;
1915 search_regs.num_regs = 0;
2d4a771a
RS
1916 search_regs.start = 0;
1917 search_regs.end = 0;
7074fde6
FP
1918
1919 search_regs_saved = 1;
1920 }
1921}
1922
1923/* Called upon exit from filters and sentinels. */
1924void
1925restore_match_data ()
1926{
1927 if (search_regs_saved)
1928 {
1929 if (search_regs.num_regs > 0)
1930 {
1931 xfree (search_regs.start);
1932 xfree (search_regs.end);
1933 }
1934 search_regs.num_regs = saved_search_regs.num_regs;
1935 search_regs.start = saved_search_regs.start;
1936 search_regs.end = saved_search_regs.end;
1937
1938 search_regs_saved = 0;
1939 }
1940}
1941
ca1d1d23
JB
1942/* Quote a string to inactivate reg-expr chars */
1943
1944DEFUN ("regexp-quote", Fregexp_quote, Sregexp_quote, 1, 1, 0,
1945 "Return a regexp string which matches exactly STRING and nothing else.")
5806161b
EN
1946 (string)
1947 Lisp_Object string;
ca1d1d23
JB
1948{
1949 register unsigned char *in, *out, *end;
1950 register unsigned char *temp;
1951
5806161b 1952 CHECK_STRING (string, 0);
ca1d1d23 1953
5806161b 1954 temp = (unsigned char *) alloca (XSTRING (string)->size * 2);
ca1d1d23
JB
1955
1956 /* Now copy the data into the new string, inserting escapes. */
1957
5806161b
EN
1958 in = XSTRING (string)->data;
1959 end = in + XSTRING (string)->size;
ca1d1d23
JB
1960 out = temp;
1961
1962 for (; in != end; in++)
1963 {
1964 if (*in == '[' || *in == ']'
1965 || *in == '*' || *in == '.' || *in == '\\'
1966 || *in == '?' || *in == '+'
1967 || *in == '^' || *in == '$')
1968 *out++ = '\\';
1969 *out++ = *in;
1970 }
1971
1972 return make_string (temp, out - temp);
1973}
1974\f
1975syms_of_search ()
1976{
1977 register int i;
1978
487282dc
KH
1979 for (i = 0; i < REGEXP_CACHE_SIZE; ++i)
1980 {
1981 searchbufs[i].buf.allocated = 100;
1982 searchbufs[i].buf.buffer = (unsigned char *) malloc (100);
1983 searchbufs[i].buf.fastmap = searchbufs[i].fastmap;
1984 searchbufs[i].regexp = Qnil;
1985 staticpro (&searchbufs[i].regexp);
1986 searchbufs[i].next = (i == REGEXP_CACHE_SIZE-1 ? 0 : &searchbufs[i+1]);
1987 }
1988 searchbuf_head = &searchbufs[0];
ca1d1d23
JB
1989
1990 Qsearch_failed = intern ("search-failed");
1991 staticpro (&Qsearch_failed);
1992 Qinvalid_regexp = intern ("invalid-regexp");
1993 staticpro (&Qinvalid_regexp);
1994
1995 Fput (Qsearch_failed, Qerror_conditions,
1996 Fcons (Qsearch_failed, Fcons (Qerror, Qnil)));
1997 Fput (Qsearch_failed, Qerror_message,
1998 build_string ("Search failed"));
1999
2000 Fput (Qinvalid_regexp, Qerror_conditions,
2001 Fcons (Qinvalid_regexp, Fcons (Qerror, Qnil)));
2002 Fput (Qinvalid_regexp, Qerror_message,
2003 build_string ("Invalid regexp"));
2004
daa37602
JB
2005 last_thing_searched = Qnil;
2006 staticpro (&last_thing_searched);
2007
ca1d1d23 2008 defsubr (&Slooking_at);
b819a390
RS
2009 defsubr (&Sposix_looking_at);
2010 defsubr (&Sstring_match);
2011 defsubr (&Sposix_string_match);
ca1d1d23
JB
2012 defsubr (&Ssearch_forward);
2013 defsubr (&Ssearch_backward);
2014 defsubr (&Sword_search_forward);
2015 defsubr (&Sword_search_backward);
2016 defsubr (&Sre_search_forward);
2017 defsubr (&Sre_search_backward);
b819a390
RS
2018 defsubr (&Sposix_search_forward);
2019 defsubr (&Sposix_search_backward);
ca1d1d23
JB
2020 defsubr (&Sreplace_match);
2021 defsubr (&Smatch_beginning);
2022 defsubr (&Smatch_end);
2023 defsubr (&Smatch_data);
2024 defsubr (&Sstore_match_data);
2025 defsubr (&Sregexp_quote);
2026}