(Fdelete_window): Handle deleting a parent of the selected window.
[bpt/emacs.git] / src / search.c
CommitLineData
ca1d1d23 1/* String search routines for GNU Emacs.
c6c5df7f 2 Copyright (C) 1985, 1986, 1987, 1993 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
8the Free Software Foundation; either version 1, or (at your option)
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
18the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
19
20
21#include "config.h"
22#include "lisp.h"
23#include "syntax.h"
24#include "buffer.h"
25#include "commands.h"
9ac0d9e0 26#include "blockinput.h"
4746118a 27
ca1d1d23
JB
28#include <sys/types.h>
29#include "regex.h"
30
31#define max(a, b) ((a) > (b) ? (a) : (b))
32#define min(a, b) ((a) < (b) ? (a) : (b))
33
34/* We compile regexps into this buffer and then use it for searching. */
35
36struct re_pattern_buffer searchbuf;
37
38char search_fastmap[0400];
39
40/* Last regexp we compiled */
41
42Lisp_Object last_regexp;
43
4746118a
JB
44/* Every call to re_match, etc., must pass &search_regs as the regs
45 argument unless you can show it is unnecessary (i.e., if re_match
46 is certainly going to be called again before region-around-match
47 can be called).
48
49 Since the registers are now dynamically allocated, we need to make
50 sure not to refer to the Nth register before checking that it has
1113d9db
JB
51 been allocated by checking search_regs.num_regs.
52
53 The regex code keeps track of whether it has allocated the search
54 buffer using bits in searchbuf. This means that whenever you
55 compile a new pattern, it completely forgets whether it has
56 allocated any registers, and will allocate new registers the next
57 time you call a searching or matching function. Therefore, we need
58 to call re_set_registers after compiling a new pattern or after
59 setting the match registers, so that the regex functions will be
60 able to free or re-allocate it properly. */
ca1d1d23
JB
61static struct re_registers search_regs;
62
daa37602
JB
63/* The buffer in which the last search was performed, or
64 Qt if the last search was done in a string;
65 Qnil if no searching has been done yet. */
66static Lisp_Object last_thing_searched;
ca1d1d23
JB
67
68/* error condition signalled when regexp compile_pattern fails */
69
70Lisp_Object Qinvalid_regexp;
71
72static void
73matcher_overflow ()
74{
75 error ("Stack overflow in regexp matcher");
76}
77
78#ifdef __STDC__
79#define CONST const
80#else
81#define CONST
82#endif
83
84/* Compile a regexp and signal a Lisp error if anything goes wrong. */
85
1113d9db 86compile_pattern (pattern, bufp, regp, translate)
ca1d1d23
JB
87 Lisp_Object pattern;
88 struct re_pattern_buffer *bufp;
1113d9db 89 struct re_registers *regp;
ca1d1d23
JB
90 char *translate;
91{
92 CONST char *val;
93 Lisp_Object dummy;
94
95 if (EQ (pattern, last_regexp)
96 && translate == bufp->translate)
97 return;
1113d9db 98
ca1d1d23
JB
99 last_regexp = Qnil;
100 bufp->translate = translate;
9ac0d9e0 101 BLOCK_INPUT;
ca1d1d23
JB
102 val = re_compile_pattern ((char *) XSTRING (pattern)->data,
103 XSTRING (pattern)->size,
104 bufp);
9ac0d9e0 105 UNBLOCK_INPUT;
ca1d1d23
JB
106 if (val)
107 {
108 dummy = build_string (val);
109 while (1)
110 Fsignal (Qinvalid_regexp, Fcons (dummy, Qnil));
111 }
1113d9db 112
ca1d1d23 113 last_regexp = pattern;
1113d9db
JB
114
115 /* Advise the searching functions about the space we have allocated
116 for register data. */
9ac0d9e0 117 BLOCK_INPUT;
ebb9e16f
JB
118 if (regp)
119 re_set_registers (bufp, regp, regp->num_regs, regp->start, regp->end);
9ac0d9e0 120 UNBLOCK_INPUT;
1113d9db 121
ca1d1d23
JB
122 return;
123}
124
125/* Error condition used for failing searches */
126Lisp_Object Qsearch_failed;
127
128Lisp_Object
129signal_failure (arg)
130 Lisp_Object arg;
131{
132 Fsignal (Qsearch_failed, Fcons (arg, Qnil));
133 return Qnil;
134}
135\f
136DEFUN ("looking-at", Flooking_at, Slooking_at, 1, 1, 0,
e065a56e
JB
137 "Return t if text after point matches regular expression PAT.\n\
138This function modifies the match data that `match-beginning',\n\
139`match-end' and `match-data' access; save and restore the match\n\
fe99283d 140data if you want to preserve them.")
ca1d1d23
JB
141 (string)
142 Lisp_Object string;
143{
144 Lisp_Object val;
145 unsigned char *p1, *p2;
146 int s1, s2;
147 register int i;
148
149 CHECK_STRING (string, 0);
1113d9db 150 compile_pattern (string, &searchbuf, &search_regs,
ca1d1d23
JB
151 !NILP (current_buffer->case_fold_search) ? DOWNCASE_TABLE : 0);
152
153 immediate_quit = 1;
154 QUIT; /* Do a pending quit right away, to avoid paradoxical behavior */
155
156 /* Get pointers and sizes of the two strings
157 that make up the visible portion of the buffer. */
158
159 p1 = BEGV_ADDR;
160 s1 = GPT - BEGV;
161 p2 = GAP_END_ADDR;
162 s2 = ZV - GPT;
163 if (s1 < 0)
164 {
165 p2 = p1;
166 s2 = ZV - BEGV;
167 s1 = 0;
168 }
169 if (s2 < 0)
170 {
171 s1 = ZV - BEGV;
172 s2 = 0;
173 }
174
175 i = re_match_2 (&searchbuf, (char *) p1, s1, (char *) p2, s2,
176 point - BEGV, &search_regs,
177 ZV - BEGV);
178 if (i == -2)
179 matcher_overflow ();
180
181 val = (0 <= i ? Qt : Qnil);
4746118a 182 for (i = 0; i < search_regs.num_regs; i++)
ca1d1d23
JB
183 if (search_regs.start[i] >= 0)
184 {
185 search_regs.start[i] += BEGV;
186 search_regs.end[i] += BEGV;
187 }
daa37602 188 XSET (last_thing_searched, Lisp_Buffer, current_buffer);
ca1d1d23
JB
189 immediate_quit = 0;
190 return val;
191}
192
193DEFUN ("string-match", Fstring_match, Sstring_match, 2, 3, 0,
194 "Return index of start of first match for REGEXP in STRING, or nil.\n\
195If third arg START is non-nil, start search at that index in STRING.\n\
196For index of first char beyond the match, do (match-end 0).\n\
197`match-end' and `match-beginning' also give indices of substrings\n\
198matched by parenthesis constructs in the pattern.")
199 (regexp, string, start)
200 Lisp_Object regexp, string, start;
201{
202 int val;
203 int s;
204
205 CHECK_STRING (regexp, 0);
206 CHECK_STRING (string, 1);
207
208 if (NILP (start))
209 s = 0;
210 else
211 {
212 int len = XSTRING (string)->size;
213
214 CHECK_NUMBER (start, 2);
215 s = XINT (start);
216 if (s < 0 && -s <= len)
217 s = len - s;
218 else if (0 > s || s > len)
219 args_out_of_range (string, start);
220 }
221
1113d9db 222 compile_pattern (regexp, &searchbuf, &search_regs,
ca1d1d23
JB
223 !NILP (current_buffer->case_fold_search) ? DOWNCASE_TABLE : 0);
224 immediate_quit = 1;
225 val = re_search (&searchbuf, (char *) XSTRING (string)->data,
226 XSTRING (string)->size, s, XSTRING (string)->size - s,
227 &search_regs);
228 immediate_quit = 0;
daa37602 229 last_thing_searched = Qt;
ca1d1d23
JB
230 if (val == -2)
231 matcher_overflow ();
232 if (val < 0) return Qnil;
233 return make_number (val);
234}
e59a8453
RS
235
236/* Match REGEXP against STRING, searching all of STRING,
237 and return the index of the match, or negative on failure.
238 This does not clobber the match data. */
239
240int
241fast_string_match (regexp, string)
242 Lisp_Object regexp, string;
243{
244 int val;
245
246 compile_pattern (regexp, &searchbuf, 0, 0);
247 immediate_quit = 1;
248 val = re_search (&searchbuf, (char *) XSTRING (string)->data,
249 XSTRING (string)->size, 0, XSTRING (string)->size,
250 0);
251 immediate_quit = 0;
252 return val;
253}
ca1d1d23 254\f
ffd56f97
JB
255/* Search for COUNT instances of the character TARGET, starting at START.
256 If COUNT is negative, search backwards.
257
258 If we find COUNT instances, set *SHORTAGE to zero, and return the
5bfe95c9
RS
259 position after the COUNTth match. Note that for reverse motion
260 this is not the same as the usual convention for Emacs motion commands.
ffd56f97
JB
261
262 If we don't find COUNT instances before reaching the end of the
263 buffer (or the beginning, if scanning backwards), set *SHORTAGE to
264 the number of TARGETs left unfound, and return the end of the
265 buffer we bumped up against. */
266
267scan_buffer (target, start, count, shortage)
268 int *shortage, start;
269 register int count, target;
ca1d1d23 270{
ffd56f97
JB
271 int limit = ((count > 0) ? ZV - 1 : BEGV);
272 int direction = ((count > 0) ? 1 : -1);
273
274 register unsigned char *cursor;
ca1d1d23 275 unsigned char *base;
ffd56f97
JB
276
277 register int ceiling;
278 register unsigned char *ceiling_addr;
ca1d1d23
JB
279
280 if (shortage != 0)
281 *shortage = 0;
282
283 immediate_quit = 1;
284
ffd56f97
JB
285 if (count > 0)
286 while (start != limit + 1)
ca1d1d23 287 {
ffd56f97
JB
288 ceiling = BUFFER_CEILING_OF (start);
289 ceiling = min (limit, ceiling);
290 ceiling_addr = &FETCH_CHAR (ceiling) + 1;
291 base = (cursor = &FETCH_CHAR (start));
ca1d1d23
JB
292 while (1)
293 {
ffd56f97 294 while (*cursor != target && ++cursor != ceiling_addr)
ca1d1d23 295 ;
ffd56f97 296 if (cursor != ceiling_addr)
ca1d1d23 297 {
ffd56f97 298 if (--count == 0)
ca1d1d23
JB
299 {
300 immediate_quit = 0;
ffd56f97 301 return (start + cursor - base + 1);
ca1d1d23
JB
302 }
303 else
ffd56f97 304 if (++cursor == ceiling_addr)
ca1d1d23
JB
305 break;
306 }
307 else
308 break;
309 }
ffd56f97 310 start += cursor - base;
ca1d1d23
JB
311 }
312 else
313 {
ffd56f97
JB
314 start--; /* first character we scan */
315 while (start > limit - 1)
316 { /* we WILL scan under start */
317 ceiling = BUFFER_FLOOR_OF (start);
318 ceiling = max (limit, ceiling);
319 ceiling_addr = &FETCH_CHAR (ceiling) - 1;
320 base = (cursor = &FETCH_CHAR (start));
ca1d1d23
JB
321 cursor++;
322 while (1)
323 {
ffd56f97 324 while (--cursor != ceiling_addr && *cursor != target)
ca1d1d23 325 ;
ffd56f97 326 if (cursor != ceiling_addr)
ca1d1d23 327 {
ffd56f97 328 if (++count == 0)
ca1d1d23
JB
329 {
330 immediate_quit = 0;
ffd56f97 331 return (start + cursor - base + 1);
ca1d1d23
JB
332 }
333 }
334 else
335 break;
336 }
ffd56f97 337 start += cursor - base;
ca1d1d23
JB
338 }
339 }
340 immediate_quit = 0;
341 if (shortage != 0)
ffd56f97
JB
342 *shortage = count * direction;
343 return (start + ((direction == 1 ? 0 : 1)));
ca1d1d23
JB
344}
345
346int
347find_next_newline (from, cnt)
348 register int from, cnt;
349{
350 return (scan_buffer ('\n', from, cnt, (int *) 0));
351}
352\f
c1dc99a1
JB
353Lisp_Object skip_chars ();
354
ca1d1d23
JB
355DEFUN ("skip-chars-forward", Fskip_chars_forward, Sskip_chars_forward, 1, 2, 0,
356 "Move point forward, stopping before a char not in CHARS, or at position LIM.\n\
357CHARS is like the inside of a `[...]' in a regular expression\n\
358except that `]' is never special and `\\' quotes `^', `-' or `\\'.\n\
359Thus, with arg \"a-zA-Z\", this skips letters stopping before first nonletter.\n\
c1dc99a1
JB
360With arg \"^a-zA-Z\", skips nonletters stopping before first letter.\n\
361Returns the distance traveled, either zero or positive.")
ca1d1d23
JB
362 (string, lim)
363 Lisp_Object string, lim;
364{
17431c60 365 return skip_chars (1, 0, string, lim);
ca1d1d23
JB
366}
367
368DEFUN ("skip-chars-backward", Fskip_chars_backward, Sskip_chars_backward, 1, 2, 0,
369 "Move point backward, stopping after a char not in CHARS, or at position LIM.\n\
c1dc99a1
JB
370See `skip-chars-forward' for details.\n\
371Returns the distance traveled, either zero or negative.")
ca1d1d23
JB
372 (string, lim)
373 Lisp_Object string, lim;
374{
17431c60
RS
375 return skip_chars (0, 0, string, lim);
376}
377
378DEFUN ("skip-syntax-forward", Fskip_syntax_forward, Sskip_syntax_forward, 1, 2, 0,
379 "Move point forward across chars in specified syntax classes.\n\
380SYNTAX is a string of syntax code characters.\n\
381Stop before a char whose syntax is not in SYNTAX, or at position LIM.\n\
382If SYNTAX starts with ^, skip characters whose syntax is NOT in SYNTAX.\n\
383This function returns the distance traveled, either zero or positive.")
384 (syntax, lim)
385 Lisp_Object syntax, lim;
386{
387 return skip_chars (1, 1, syntax, lim);
388}
389
390DEFUN ("skip-syntax-backward", Fskip_syntax_backward, Sskip_syntax_backward, 1, 2, 0,
391 "Move point backward across chars in specified syntax classes.\n\
392SYNTAX is a string of syntax code characters.\n\
393Stop on reaching a char whose syntax is not in SYNTAX, or at position LIM.\n\
394If SYNTAX starts with ^, skip characters whose syntax is NOT in SYNTAX.\n\
395This function returns the distance traveled, either zero or negative.")
396 (syntax, lim)
397 Lisp_Object syntax, lim;
398{
399 return skip_chars (0, 1, syntax, lim);
ca1d1d23
JB
400}
401
c1dc99a1 402Lisp_Object
17431c60
RS
403skip_chars (forwardp, syntaxp, string, lim)
404 int forwardp, syntaxp;
ca1d1d23
JB
405 Lisp_Object string, lim;
406{
407 register unsigned char *p, *pend;
408 register unsigned char c;
409 unsigned char fastmap[0400];
410 int negate = 0;
411 register int i;
412
413 CHECK_STRING (string, 0);
414
415 if (NILP (lim))
416 XSET (lim, Lisp_Int, forwardp ? ZV : BEGV);
417 else
418 CHECK_NUMBER_COERCE_MARKER (lim, 1);
419
420#if 0 /* This breaks some things... jla. */
421 /* In any case, don't allow scan outside bounds of buffer. */
422 if (XFASTINT (lim) > ZV)
423 XFASTINT (lim) = ZV;
424 if (XFASTINT (lim) < BEGV)
425 XFASTINT (lim) = BEGV;
426#endif
427
428 p = XSTRING (string)->data;
429 pend = p + XSTRING (string)->size;
430 bzero (fastmap, sizeof fastmap);
431
432 if (p != pend && *p == '^')
433 {
434 negate = 1; p++;
435 }
436
17431c60
RS
437 /* Find the characters specified and set their elements of fastmap.
438 If syntaxp, each character counts as itself.
439 Otherwise, handle backslashes and ranges specially */
ca1d1d23
JB
440
441 while (p != pend)
442 {
443 c = *p++;
17431c60
RS
444 if (syntaxp)
445 fastmap[c] = 1;
446 else
ca1d1d23 447 {
17431c60 448 if (c == '\\')
ca1d1d23 449 {
17431c60
RS
450 if (p == pend) break;
451 c = *p++;
452 }
453 if (p != pend && *p == '-')
454 {
455 p++;
456 if (p == pend) break;
457 while (c <= *p)
458 {
459 fastmap[c] = 1;
460 c++;
461 }
462 p++;
ca1d1d23 463 }
17431c60
RS
464 else
465 fastmap[c] = 1;
ca1d1d23 466 }
ca1d1d23
JB
467 }
468
469 /* If ^ was the first character, complement the fastmap. */
470
471 if (negate)
472 for (i = 0; i < sizeof fastmap; i++)
473 fastmap[i] ^= 1;
474
c1dc99a1
JB
475 {
476 int start_point = point;
477
478 immediate_quit = 1;
17431c60 479 if (syntaxp)
c1dc99a1 480 {
17431c60
RS
481
482 if (forwardp)
483 {
484 while (point < XINT (lim)
485 && fastmap[(unsigned char) syntax_code_spec[(int) SYNTAX (FETCH_CHAR (point))]])
486 SET_PT (point + 1);
487 }
488 else
489 {
490 while (point > XINT (lim)
491 && fastmap[(unsigned char) syntax_code_spec[(int) SYNTAX (FETCH_CHAR (point - 1))]])
492 SET_PT (point - 1);
493 }
c1dc99a1
JB
494 }
495 else
496 {
17431c60
RS
497 if (forwardp)
498 {
499 while (point < XINT (lim) && fastmap[FETCH_CHAR (point)])
500 SET_PT (point + 1);
501 }
502 else
503 {
504 while (point > XINT (lim) && fastmap[FETCH_CHAR (point - 1)])
505 SET_PT (point - 1);
506 }
c1dc99a1
JB
507 }
508 immediate_quit = 0;
509
510 return make_number (point - start_point);
511 }
ca1d1d23
JB
512}
513\f
514/* Subroutines of Lisp buffer search functions. */
515
516static Lisp_Object
517search_command (string, bound, noerror, count, direction, RE)
518 Lisp_Object string, bound, noerror, count;
519 int direction;
520 int RE;
521{
522 register int np;
523 int lim;
524 int n = direction;
525
526 if (!NILP (count))
527 {
528 CHECK_NUMBER (count, 3);
529 n *= XINT (count);
530 }
531
532 CHECK_STRING (string, 0);
533 if (NILP (bound))
534 lim = n > 0 ? ZV : BEGV;
535 else
536 {
537 CHECK_NUMBER_COERCE_MARKER (bound, 1);
538 lim = XINT (bound);
539 if (n > 0 ? lim < point : lim > point)
540 error ("Invalid search bound (wrong side of point)");
541 if (lim > ZV)
542 lim = ZV;
543 if (lim < BEGV)
544 lim = BEGV;
545 }
546
547 np = search_buffer (string, point, lim, n, RE,
548 (!NILP (current_buffer->case_fold_search)
549 ? XSTRING (current_buffer->case_canon_table)->data : 0),
550 (!NILP (current_buffer->case_fold_search)
551 ? XSTRING (current_buffer->case_eqv_table)->data : 0));
552 if (np <= 0)
553 {
554 if (NILP (noerror))
555 return signal_failure (string);
556 if (!EQ (noerror, Qt))
557 {
558 if (lim < BEGV || lim > ZV)
559 abort ();
a5f217b8
RS
560 SET_PT (lim);
561 return Qnil;
562#if 0 /* This would be clean, but maybe programs depend on
563 a value of nil here. */
481399bf 564 np = lim;
a5f217b8 565#endif
ca1d1d23 566 }
481399bf
RS
567 else
568 return Qnil;
ca1d1d23
JB
569 }
570
571 if (np < BEGV || np > ZV)
572 abort ();
573
574 SET_PT (np);
575
576 return make_number (np);
577}
578\f
579/* search for the n'th occurrence of STRING in the current buffer,
580 starting at position POS and stopping at position LIM,
581 treating PAT as a literal string if RE is false or as
582 a regular expression if RE is true.
583
584 If N is positive, searching is forward and LIM must be greater than POS.
585 If N is negative, searching is backward and LIM must be less than POS.
586
587 Returns -x if only N-x occurrences found (x > 0),
588 or else the position at the beginning of the Nth occurrence
589 (if searching backward) or the end (if searching forward). */
590
591search_buffer (string, pos, lim, n, RE, trt, inverse_trt)
592 Lisp_Object string;
593 int pos;
594 int lim;
595 int n;
596 int RE;
597 register unsigned char *trt;
598 register unsigned char *inverse_trt;
599{
600 int len = XSTRING (string)->size;
601 unsigned char *base_pat = XSTRING (string)->data;
602 register int *BM_tab;
603 int *BM_tab_base;
604 register int direction = ((n > 0) ? 1 : -1);
605 register int dirlen;
606 int infinity, limit, k, stride_for_teases;
607 register unsigned char *pat, *cursor, *p_limit;
608 register int i, j;
609 unsigned char *p1, *p2;
610 int s1, s2;
611
612 /* Null string is found at starting position. */
613 if (!len)
614 return pos;
615
616 if (RE)
1113d9db 617 compile_pattern (string, &searchbuf, &search_regs, (char *) trt);
ca1d1d23
JB
618
619 if (RE /* Here we detect whether the */
620 /* generality of an RE search is */
621 /* really needed. */
622 /* first item is "exact match" */
4746118a 623 && *(searchbuf.buffer) == (char) RE_EXACTN_VALUE
ca1d1d23
JB
624 && searchbuf.buffer[1] + 2 == searchbuf.used) /*first is ONLY item */
625 {
626 RE = 0; /* can do straight (non RE) search */
627 pat = (base_pat = (unsigned char *) searchbuf.buffer + 2);
628 /* trt already applied */
629 len = searchbuf.used - 2;
630 }
631 else if (!RE)
632 {
633 pat = (unsigned char *) alloca (len);
634
635 for (i = len; i--;) /* Copy the pattern; apply trt */
636 *pat++ = (((int) trt) ? trt [*base_pat++] : *base_pat++);
637 pat -= len; base_pat = pat;
638 }
639
640 if (RE)
641 {
642 immediate_quit = 1; /* Quit immediately if user types ^G,
643 because letting this function finish
644 can take too long. */
645 QUIT; /* Do a pending quit right away,
646 to avoid paradoxical behavior */
647 /* Get pointers and sizes of the two strings
648 that make up the visible portion of the buffer. */
649
650 p1 = BEGV_ADDR;
651 s1 = GPT - BEGV;
652 p2 = GAP_END_ADDR;
653 s2 = ZV - GPT;
654 if (s1 < 0)
655 {
656 p2 = p1;
657 s2 = ZV - BEGV;
658 s1 = 0;
659 }
660 if (s2 < 0)
661 {
662 s1 = ZV - BEGV;
663 s2 = 0;
664 }
665 while (n < 0)
666 {
42db823b 667 int val;
42db823b
RS
668 val = re_search_2 (&searchbuf, (char *) p1, s1, (char *) p2, s2,
669 pos - BEGV, lim - pos, &search_regs,
670 /* Don't allow match past current point */
671 pos - BEGV);
ca1d1d23
JB
672 if (val == -2)
673 matcher_overflow ();
674 if (val >= 0)
675 {
676 j = BEGV;
4746118a 677 for (i = 0; i < search_regs.num_regs; i++)
ca1d1d23
JB
678 if (search_regs.start[i] >= 0)
679 {
680 search_regs.start[i] += j;
681 search_regs.end[i] += j;
682 }
daa37602 683 XSET (last_thing_searched, Lisp_Buffer, current_buffer);
ca1d1d23
JB
684 /* Set pos to the new position. */
685 pos = search_regs.start[0];
686 }
687 else
688 {
689 immediate_quit = 0;
690 return (n);
691 }
692 n++;
693 }
694 while (n > 0)
695 {
42db823b 696 int val;
42db823b
RS
697 val = re_search_2 (&searchbuf, (char *) p1, s1, (char *) p2, s2,
698 pos - BEGV, lim - pos, &search_regs,
699 lim - BEGV);
ca1d1d23
JB
700 if (val == -2)
701 matcher_overflow ();
702 if (val >= 0)
703 {
704 j = BEGV;
4746118a 705 for (i = 0; i < search_regs.num_regs; i++)
ca1d1d23
JB
706 if (search_regs.start[i] >= 0)
707 {
708 search_regs.start[i] += j;
709 search_regs.end[i] += j;
710 }
daa37602 711 XSET (last_thing_searched, Lisp_Buffer, current_buffer);
ca1d1d23
JB
712 pos = search_regs.end[0];
713 }
714 else
715 {
716 immediate_quit = 0;
717 return (0 - n);
718 }
719 n--;
720 }
721 immediate_quit = 0;
722 return (pos);
723 }
724 else /* non-RE case */
725 {
726#ifdef C_ALLOCA
727 int BM_tab_space[0400];
728 BM_tab = &BM_tab_space[0];
729#else
730 BM_tab = (int *) alloca (0400 * sizeof (int));
731#endif
732 /* The general approach is that we are going to maintain that we know */
733 /* the first (closest to the present position, in whatever direction */
734 /* we're searching) character that could possibly be the last */
735 /* (furthest from present position) character of a valid match. We */
736 /* advance the state of our knowledge by looking at that character */
737 /* and seeing whether it indeed matches the last character of the */
738 /* pattern. If it does, we take a closer look. If it does not, we */
739 /* move our pointer (to putative last characters) as far as is */
740 /* logically possible. This amount of movement, which I call a */
741 /* stride, will be the length of the pattern if the actual character */
742 /* appears nowhere in the pattern, otherwise it will be the distance */
743 /* from the last occurrence of that character to the end of the */
744 /* pattern. */
745 /* As a coding trick, an enormous stride is coded into the table for */
746 /* characters that match the last character. This allows use of only */
747 /* a single test, a test for having gone past the end of the */
748 /* permissible match region, to test for both possible matches (when */
749 /* the stride goes past the end immediately) and failure to */
750 /* match (where you get nudged past the end one stride at a time). */
751
752 /* Here we make a "mickey mouse" BM table. The stride of the search */
753 /* is determined only by the last character of the putative match. */
754 /* If that character does not match, we will stride the proper */
755 /* distance to propose a match that superimposes it on the last */
756 /* instance of a character that matches it (per trt), or misses */
757 /* it entirely if there is none. */
758
759 dirlen = len * direction;
760 infinity = dirlen - (lim + pos + len + len) * direction;
761 if (direction < 0)
762 pat = (base_pat += len - 1);
763 BM_tab_base = BM_tab;
764 BM_tab += 0400;
765 j = dirlen; /* to get it in a register */
766 /* A character that does not appear in the pattern induces a */
767 /* stride equal to the pattern length. */
768 while (BM_tab_base != BM_tab)
769 {
770 *--BM_tab = j;
771 *--BM_tab = j;
772 *--BM_tab = j;
773 *--BM_tab = j;
774 }
775 i = 0;
776 while (i != infinity)
777 {
778 j = pat[i]; i += direction;
779 if (i == dirlen) i = infinity;
780 if ((int) trt)
781 {
782 k = (j = trt[j]);
783 if (i == infinity)
784 stride_for_teases = BM_tab[j];
785 BM_tab[j] = dirlen - i;
786 /* A translation table is accompanied by its inverse -- see */
787 /* comment following downcase_table for details */
788 while ((j = inverse_trt[j]) != k)
789 BM_tab[j] = dirlen - i;
790 }
791 else
792 {
793 if (i == infinity)
794 stride_for_teases = BM_tab[j];
795 BM_tab[j] = dirlen - i;
796 }
797 /* stride_for_teases tells how much to stride if we get a */
798 /* match on the far character but are subsequently */
799 /* disappointed, by recording what the stride would have been */
800 /* for that character if the last character had been */
801 /* different. */
802 }
803 infinity = dirlen - infinity;
804 pos += dirlen - ((direction > 0) ? direction : 0);
805 /* loop invariant - pos points at where last char (first char if reverse)
806 of pattern would align in a possible match. */
807 while (n != 0)
808 {
809 if ((lim - pos - (direction > 0)) * direction < 0)
810 return (n * (0 - direction));
811 /* First we do the part we can by pointers (maybe nothing) */
812 QUIT;
813 pat = base_pat;
814 limit = pos - dirlen + direction;
815 limit = ((direction > 0)
816 ? BUFFER_CEILING_OF (limit)
817 : BUFFER_FLOOR_OF (limit));
818 /* LIMIT is now the last (not beyond-last!) value
819 POS can take on without hitting edge of buffer or the gap. */
820 limit = ((direction > 0)
821 ? min (lim - 1, min (limit, pos + 20000))
822 : max (lim, max (limit, pos - 20000)));
823 if ((limit - pos) * direction > 20)
824 {
825 p_limit = &FETCH_CHAR (limit);
826 p2 = (cursor = &FETCH_CHAR (pos));
827 /* In this loop, pos + cursor - p2 is the surrogate for pos */
828 while (1) /* use one cursor setting as long as i can */
829 {
830 if (direction > 0) /* worth duplicating */
831 {
832 /* Use signed comparison if appropriate
833 to make cursor+infinity sure to be > p_limit.
834 Assuming that the buffer lies in a range of addresses
835 that are all "positive" (as ints) or all "negative",
836 either kind of comparison will work as long
837 as we don't step by infinity. So pick the kind
838 that works when we do step by infinity. */
839 if ((int) (p_limit + infinity) > (int) p_limit)
840 while ((int) cursor <= (int) p_limit)
841 cursor += BM_tab[*cursor];
842 else
843 while ((unsigned int) cursor <= (unsigned int) p_limit)
844 cursor += BM_tab[*cursor];
845 }
846 else
847 {
848 if ((int) (p_limit + infinity) < (int) p_limit)
849 while ((int) cursor >= (int) p_limit)
850 cursor += BM_tab[*cursor];
851 else
852 while ((unsigned int) cursor >= (unsigned int) p_limit)
853 cursor += BM_tab[*cursor];
854 }
855/* If you are here, cursor is beyond the end of the searched region. */
856 /* This can happen if you match on the far character of the pattern, */
857 /* because the "stride" of that character is infinity, a number able */
858 /* to throw you well beyond the end of the search. It can also */
859 /* happen if you fail to match within the permitted region and would */
860 /* otherwise try a character beyond that region */
861 if ((cursor - p_limit) * direction <= len)
862 break; /* a small overrun is genuine */
863 cursor -= infinity; /* large overrun = hit */
864 i = dirlen - direction;
865 if ((int) trt)
866 {
867 while ((i -= direction) + direction != 0)
868 if (pat[i] != trt[*(cursor -= direction)])
869 break;
870 }
871 else
872 {
873 while ((i -= direction) + direction != 0)
874 if (pat[i] != *(cursor -= direction))
875 break;
876 }
877 cursor += dirlen - i - direction; /* fix cursor */
878 if (i + direction == 0)
879 {
880 cursor -= direction;
1113d9db
JB
881
882 /* Make sure we have registers in which to store
883 the match position. */
884 if (search_regs.num_regs == 0)
885 {
886 regoff_t *starts, *ends;
887
888 starts =
889 (regoff_t *) xmalloc (2 * sizeof (regoff_t));
890 ends =
891 (regoff_t *) xmalloc (2 * sizeof (regoff_t));
9ac0d9e0 892 BLOCK_INPUT;
1113d9db
JB
893 re_set_registers (&searchbuf,
894 &search_regs,
895 2, starts, ends);
9ac0d9e0 896 UNBLOCK_INPUT;
1113d9db
JB
897 }
898
ca1d1d23
JB
899 search_regs.start[0]
900 = pos + cursor - p2 + ((direction > 0)
901 ? 1 - len : 0);
902 search_regs.end[0] = len + search_regs.start[0];
daa37602 903 XSET (last_thing_searched, Lisp_Buffer, current_buffer);
ca1d1d23
JB
904 if ((n -= direction) != 0)
905 cursor += dirlen; /* to resume search */
906 else
907 return ((direction > 0)
908 ? search_regs.end[0] : search_regs.start[0]);
909 }
910 else
911 cursor += stride_for_teases; /* <sigh> we lose - */
912 }
913 pos += cursor - p2;
914 }
915 else
916 /* Now we'll pick up a clump that has to be done the hard */
917 /* way because it covers a discontinuity */
918 {
919 limit = ((direction > 0)
920 ? BUFFER_CEILING_OF (pos - dirlen + 1)
921 : BUFFER_FLOOR_OF (pos - dirlen - 1));
922 limit = ((direction > 0)
923 ? min (limit + len, lim - 1)
924 : max (limit - len, lim));
925 /* LIMIT is now the last value POS can have
926 and still be valid for a possible match. */
927 while (1)
928 {
929 /* This loop can be coded for space rather than */
930 /* speed because it will usually run only once. */
931 /* (the reach is at most len + 21, and typically */
932 /* does not exceed len) */
933 while ((limit - pos) * direction >= 0)
934 pos += BM_tab[FETCH_CHAR(pos)];
935 /* now run the same tests to distinguish going off the */
eb8c3be9 936 /* end, a match or a phony match. */
ca1d1d23
JB
937 if ((pos - limit) * direction <= len)
938 break; /* ran off the end */
939 /* Found what might be a match.
940 Set POS back to last (first if reverse) char pos. */
941 pos -= infinity;
942 i = dirlen - direction;
943 while ((i -= direction) + direction != 0)
944 {
945 pos -= direction;
946 if (pat[i] != (((int) trt)
947 ? trt[FETCH_CHAR(pos)]
948 : FETCH_CHAR (pos)))
949 break;
950 }
951 /* Above loop has moved POS part or all the way
952 back to the first char pos (last char pos if reverse).
953 Set it once again at the last (first if reverse) char. */
954 pos += dirlen - i- direction;
955 if (i + direction == 0)
956 {
957 pos -= direction;
1113d9db
JB
958
959 /* Make sure we have registers in which to store
960 the match position. */
961 if (search_regs.num_regs == 0)
962 {
963 regoff_t *starts, *ends;
964
965 starts =
966 (regoff_t *) xmalloc (2 * sizeof (regoff_t));
967 ends =
968 (regoff_t *) xmalloc (2 * sizeof (regoff_t));
9ac0d9e0 969 BLOCK_INPUT;
1113d9db
JB
970 re_set_registers (&searchbuf,
971 &search_regs,
972 2, starts, ends);
9ac0d9e0 973 UNBLOCK_INPUT;
1113d9db
JB
974 }
975
ca1d1d23
JB
976 search_regs.start[0]
977 = pos + ((direction > 0) ? 1 - len : 0);
978 search_regs.end[0] = len + search_regs.start[0];
daa37602 979 XSET (last_thing_searched, Lisp_Buffer, current_buffer);
ca1d1d23
JB
980 if ((n -= direction) != 0)
981 pos += dirlen; /* to resume search */
982 else
983 return ((direction > 0)
984 ? search_regs.end[0] : search_regs.start[0]);
985 }
986 else
987 pos += stride_for_teases;
988 }
989 }
990 /* We have done one clump. Can we continue? */
991 if ((lim - pos) * direction < 0)
992 return ((0 - n) * direction);
993 }
994 return pos;
995 }
996}
997\f
998/* Given a string of words separated by word delimiters,
999 compute a regexp that matches those exact words
1000 separated by arbitrary punctuation. */
1001
1002static Lisp_Object
1003wordify (string)
1004 Lisp_Object string;
1005{
1006 register unsigned char *p, *o;
1007 register int i, len, punct_count = 0, word_count = 0;
1008 Lisp_Object val;
1009
1010 CHECK_STRING (string, 0);
1011 p = XSTRING (string)->data;
1012 len = XSTRING (string)->size;
1013
1014 for (i = 0; i < len; i++)
1015 if (SYNTAX (p[i]) != Sword)
1016 {
1017 punct_count++;
1018 if (i > 0 && SYNTAX (p[i-1]) == Sword) word_count++;
1019 }
1020 if (SYNTAX (p[len-1]) == Sword) word_count++;
1021 if (!word_count) return build_string ("");
1022
1023 val = make_string (p, len - punct_count + 5 * (word_count - 1) + 4);
1024
1025 o = XSTRING (val)->data;
1026 *o++ = '\\';
1027 *o++ = 'b';
1028
1029 for (i = 0; i < len; i++)
1030 if (SYNTAX (p[i]) == Sword)
1031 *o++ = p[i];
1032 else if (i > 0 && SYNTAX (p[i-1]) == Sword && --word_count)
1033 {
1034 *o++ = '\\';
1035 *o++ = 'W';
1036 *o++ = '\\';
1037 *o++ = 'W';
1038 *o++ = '*';
1039 }
1040
1041 *o++ = '\\';
1042 *o++ = 'b';
1043
1044 return val;
1045}
1046\f
1047DEFUN ("search-backward", Fsearch_backward, Ssearch_backward, 1, 4,
1048 "sSearch backward: ",
1049 "Search backward from point for STRING.\n\
1050Set point to the beginning of the occurrence found, and return point.\n\
1051An optional second argument bounds the search; it is a buffer position.\n\
1052The match found must not extend before that position.\n\
1053Optional third argument, if t, means if fail just return nil (no error).\n\
1054 If not nil and not t, position at limit of search and return nil.\n\
1055Optional fourth argument is repeat count--search for successive occurrences.\n\
1056See also the functions `match-beginning', `match-end' and `replace-match'.")
1057 (string, bound, noerror, count)
1058 Lisp_Object string, bound, noerror, count;
1059{
1060 return search_command (string, bound, noerror, count, -1, 0);
1061}
1062
1063DEFUN ("search-forward", Fsearch_forward, Ssearch_forward, 1, 4, "sSearch: ",
1064 "Search forward from point for STRING.\n\
1065Set point to the end of the occurrence found, and return point.\n\
1066An optional second argument bounds the search; it is a buffer position.\n\
1067The match found must not extend after that position. nil is equivalent\n\
1068 to (point-max).\n\
1069Optional third argument, if t, means if fail just return nil (no error).\n\
1070 If not nil and not t, move to limit of search and return nil.\n\
1071Optional fourth argument is repeat count--search for successive occurrences.\n\
1072See also the functions `match-beginning', `match-end' and `replace-match'.")
1073 (string, bound, noerror, count)
1074 Lisp_Object string, bound, noerror, count;
1075{
1076 return search_command (string, bound, noerror, count, 1, 0);
1077}
1078
1079DEFUN ("word-search-backward", Fword_search_backward, Sword_search_backward, 1, 4,
1080 "sWord search backward: ",
1081 "Search backward from point for STRING, ignoring differences in punctuation.\n\
1082Set point to the beginning of the occurrence found, and return point.\n\
1083An optional second argument bounds the search; it is a buffer position.\n\
1084The match found must not extend before that position.\n\
1085Optional third argument, if t, means if fail just return nil (no error).\n\
1086 If not nil and not t, move to limit of search and return nil.\n\
1087Optional fourth argument is repeat count--search for successive occurrences.")
1088 (string, bound, noerror, count)
1089 Lisp_Object string, bound, noerror, count;
1090{
1091 return search_command (wordify (string), bound, noerror, count, -1, 1);
1092}
1093
1094DEFUN ("word-search-forward", Fword_search_forward, Sword_search_forward, 1, 4,
1095 "sWord search: ",
1096 "Search forward from point for STRING, ignoring differences in punctuation.\n\
1097Set point to the end of the occurrence found, and return point.\n\
1098An optional second argument bounds the search; it is a buffer position.\n\
1099The match found must not extend after that position.\n\
1100Optional third argument, if t, means if fail just return nil (no error).\n\
1101 If not nil and not t, move to limit of search and return nil.\n\
1102Optional fourth argument is repeat count--search for successive occurrences.")
1103 (string, bound, noerror, count)
1104 Lisp_Object string, bound, noerror, count;
1105{
1106 return search_command (wordify (string), bound, noerror, count, 1, 1);
1107}
1108
1109DEFUN ("re-search-backward", Fre_search_backward, Sre_search_backward, 1, 4,
1110 "sRE search backward: ",
1111 "Search backward from point for match for regular expression REGEXP.\n\
1112Set point to the beginning of the match, and return point.\n\
1113The match found is the one starting last in the buffer\n\
1114and yet ending before the place the origin of the search.\n\
1115An optional second argument bounds the search; it is a buffer position.\n\
1116The match found must start at or after that position.\n\
1117Optional third argument, if t, means if fail just return nil (no error).\n\
1118 If not nil and not t, move to limit of search and return nil.\n\
1119Optional fourth argument is repeat count--search for successive occurrences.\n\
1120See also the functions `match-beginning', `match-end' and `replace-match'.")
1121 (string, bound, noerror, count)
1122 Lisp_Object string, bound, noerror, count;
1123{
1124 return search_command (string, bound, noerror, count, -1, 1);
1125}
1126
1127DEFUN ("re-search-forward", Fre_search_forward, Sre_search_forward, 1, 4,
1128 "sRE search: ",
1129 "Search forward from point for regular expression REGEXP.\n\
1130Set point to the end of the occurrence found, and return point.\n\
1131An optional second argument bounds the search; it is a buffer position.\n\
1132The match found must not extend after that position.\n\
1133Optional third argument, if t, means if fail just return nil (no error).\n\
1134 If not nil and not t, move to limit of search and return nil.\n\
1135Optional fourth argument is repeat count--search for successive occurrences.\n\
1136See also the functions `match-beginning', `match-end' and `replace-match'.")
1137 (string, bound, noerror, count)
1138 Lisp_Object string, bound, noerror, count;
1139{
1140 return search_command (string, bound, noerror, count, 1, 1);
1141}
1142\f
1143DEFUN ("replace-match", Freplace_match, Sreplace_match, 1, 3, 0,
1144 "Replace text matched by last search with NEWTEXT.\n\
1145If second arg FIXEDCASE is non-nil, do not alter case of replacement text.\n\
1146Otherwise convert to all caps or cap initials, like replaced text.\n\
1147If third arg LITERAL is non-nil, insert NEWTEXT literally.\n\
1148Otherwise treat `\\' as special:\n\
1149 `\\&' in NEWTEXT means substitute original matched text.\n\
1150 `\\N' means substitute what matched the Nth `\\(...\\)'.\n\
1151 If Nth parens didn't match, substitute nothing.\n\
1152 `\\\\' means insert one `\\'.\n\
1113d9db 1153FIXEDCASE and LITERAL are optional arguments.\n\
ca1d1d23
JB
1154Leaves point at end of replacement text.")
1155 (string, fixedcase, literal)
1156 Lisp_Object string, fixedcase, literal;
1157{
1158 enum { nochange, all_caps, cap_initial } case_action;
1159 register int pos, last;
1160 int some_multiletter_word;
97832bd0
RS
1161 int some_lowercase;
1162 int some_uppercase_initial;
ca1d1d23
JB
1163 register int c, prevc;
1164 int inslen;
1165
1166 CHECK_STRING (string, 0);
1167
1168 case_action = nochange; /* We tried an initialization */
1169 /* but some C compilers blew it */
4746118a
JB
1170
1171 if (search_regs.num_regs <= 0)
1172 error ("replace-match called before any match found");
1173
ca1d1d23
JB
1174 if (search_regs.start[0] < BEGV
1175 || search_regs.start[0] > search_regs.end[0]
1176 || search_regs.end[0] > ZV)
97832bd0
RS
1177 args_out_of_range (make_number (search_regs.start[0]),
1178 make_number (search_regs.end[0]));
ca1d1d23
JB
1179
1180 if (NILP (fixedcase))
1181 {
1182 /* Decide how to casify by examining the matched text. */
1183
1184 last = search_regs.end[0];
1185 prevc = '\n';
1186 case_action = all_caps;
1187
1188 /* some_multiletter_word is set nonzero if any original word
1189 is more than one letter long. */
1190 some_multiletter_word = 0;
97832bd0
RS
1191 some_lowercase = 0;
1192 some_uppercase_initial = 0;
ca1d1d23
JB
1193
1194 for (pos = search_regs.start[0]; pos < last; pos++)
1195 {
1196 c = FETCH_CHAR (pos);
1197 if (LOWERCASEP (c))
1198 {
1199 /* Cannot be all caps if any original char is lower case */
1200
97832bd0 1201 some_lowercase = 1;
ca1d1d23 1202 if (SYNTAX (prevc) != Sword)
97832bd0 1203 ;
ca1d1d23
JB
1204 else
1205 some_multiletter_word = 1;
1206 }
1207 else if (!NOCASEP (c))
1208 {
97832bd0
RS
1209 if (SYNTAX (prevc) != Sword)
1210 some_uppercase_initial = 1;
1211 else
ca1d1d23
JB
1212 some_multiletter_word = 1;
1213 }
1214
1215 prevc = c;
1216 }
1217
97832bd0
RS
1218 /* Convert to all caps if the old text is all caps
1219 and has at least one multiletter word. */
1220 if (! some_lowercase && some_multiletter_word)
1221 case_action = all_caps;
1222 /* Capitalize each word, if the old text has a capitalized word. */
1223 else if (some_uppercase_initial)
ca1d1d23 1224 case_action = cap_initial;
97832bd0
RS
1225 else
1226 case_action = nochange;
ca1d1d23
JB
1227 }
1228
9a76659d
JB
1229 /* We insert the replacement text before the old text, and then
1230 delete the original text. This means that markers at the
1231 beginning or end of the original will float to the corresponding
1232 position in the replacement. */
1233 SET_PT (search_regs.start[0]);
ca1d1d23
JB
1234 if (!NILP (literal))
1235 Finsert (1, &string);
1236 else
1237 {
1238 struct gcpro gcpro1;
1239 GCPRO1 (string);
1240
1241 for (pos = 0; pos < XSTRING (string)->size; pos++)
1242 {
9a76659d
JB
1243 int offset = point - search_regs.start[0];
1244
ca1d1d23
JB
1245 c = XSTRING (string)->data[pos];
1246 if (c == '\\')
1247 {
1248 c = XSTRING (string)->data[++pos];
1249 if (c == '&')
9a76659d
JB
1250 Finsert_buffer_substring
1251 (Fcurrent_buffer (),
1252 make_number (search_regs.start[0] + offset),
1253 make_number (search_regs.end[0] + offset));
4746118a 1254 else if (c >= '1' && c <= search_regs.num_regs + '0')
ca1d1d23
JB
1255 {
1256 if (search_regs.start[c - '0'] >= 1)
9a76659d
JB
1257 Finsert_buffer_substring
1258 (Fcurrent_buffer (),
1259 make_number (search_regs.start[c - '0'] + offset),
1260 make_number (search_regs.end[c - '0'] + offset));
ca1d1d23
JB
1261 }
1262 else
1263 insert_char (c);
1264 }
1265 else
1266 insert_char (c);
1267 }
1268 UNGCPRO;
1269 }
1270
9a76659d
JB
1271 inslen = point - (search_regs.start[0]);
1272 del_range (search_regs.start[0] + inslen, search_regs.end[0] + inslen);
ca1d1d23
JB
1273
1274 if (case_action == all_caps)
1275 Fupcase_region (make_number (point - inslen), make_number (point));
1276 else if (case_action == cap_initial)
1277 upcase_initials_region (make_number (point - inslen), make_number (point));
1278 return Qnil;
1279}
1280\f
1281static Lisp_Object
1282match_limit (num, beginningp)
1283 Lisp_Object num;
1284 int beginningp;
1285{
1286 register int n;
1287
1288 CHECK_NUMBER (num, 0);
1289 n = XINT (num);
4746118a
JB
1290 if (n < 0 || n >= search_regs.num_regs)
1291 args_out_of_range (num, make_number (search_regs.num_regs));
1292 if (search_regs.num_regs <= 0
1293 || search_regs.start[n] < 0)
ca1d1d23
JB
1294 return Qnil;
1295 return (make_number ((beginningp) ? search_regs.start[n]
1296 : search_regs.end[n]));
1297}
1298
1299DEFUN ("match-beginning", Fmatch_beginning, Smatch_beginning, 1, 1, 0,
1300 "Return position of start of text matched by last search.\n\
1301ARG, a number, specifies which parenthesized expression in the last regexp.\n\
1302 Value is nil if ARGth pair didn't match, or there were less than ARG pairs.\n\
1303Zero means the entire text matched by the whole regexp or whole string.")
1304 (num)
1305 Lisp_Object num;
1306{
1307 return match_limit (num, 1);
1308}
1309
1310DEFUN ("match-end", Fmatch_end, Smatch_end, 1, 1, 0,
1311 "Return position of end of text matched by last search.\n\
1312ARG, a number, specifies which parenthesized expression in the last regexp.\n\
1313 Value is nil if ARGth pair didn't match, or there were less than ARG pairs.\n\
1314Zero means the entire text matched by the whole regexp or whole string.")
1315 (num)
1316 Lisp_Object num;
1317{
1318 return match_limit (num, 0);
1319}
1320
1321DEFUN ("match-data", Fmatch_data, Smatch_data, 0, 0, 0,
1322 "Return a list containing all info on what the last search matched.\n\
1323Element 2N is `(match-beginning N)'; element 2N + 1 is `(match-end N)'.\n\
1324All the elements are markers or nil (nil if the Nth pair didn't match)\n\
1325if the last match was on a buffer; integers or nil if a string was matched.\n\
1326Use `store-match-data' to reinstate the data in this list.")
1327 ()
1328{
4746118a 1329 Lisp_Object *data;
ca1d1d23
JB
1330 int i, len;
1331
daa37602
JB
1332 if (NILP (last_thing_searched))
1333 error ("match-data called before any match found");
1334
4746118a
JB
1335 data = (Lisp_Object *) alloca ((2 * search_regs.num_regs)
1336 * sizeof (Lisp_Object));
1337
ca1d1d23 1338 len = -1;
4746118a 1339 for (i = 0; i < search_regs.num_regs; i++)
ca1d1d23
JB
1340 {
1341 int start = search_regs.start[i];
1342 if (start >= 0)
1343 {
daa37602 1344 if (EQ (last_thing_searched, Qt))
ca1d1d23
JB
1345 {
1346 XFASTINT (data[2 * i]) = start;
1347 XFASTINT (data[2 * i + 1]) = search_regs.end[i];
1348 }
daa37602 1349 else if (XTYPE (last_thing_searched) == Lisp_Buffer)
ca1d1d23
JB
1350 {
1351 data[2 * i] = Fmake_marker ();
daa37602
JB
1352 Fset_marker (data[2 * i],
1353 make_number (start),
1354 last_thing_searched);
ca1d1d23
JB
1355 data[2 * i + 1] = Fmake_marker ();
1356 Fset_marker (data[2 * i + 1],
daa37602
JB
1357 make_number (search_regs.end[i]),
1358 last_thing_searched);
ca1d1d23 1359 }
daa37602
JB
1360 else
1361 /* last_thing_searched must always be Qt, a buffer, or Qnil. */
1362 abort ();
1363
ca1d1d23
JB
1364 len = i;
1365 }
1366 else
1367 data[2 * i] = data [2 * i + 1] = Qnil;
1368 }
1369 return Flist (2 * len + 2, data);
1370}
1371
1372
1373DEFUN ("store-match-data", Fstore_match_data, Sstore_match_data, 1, 1, 0,
1374 "Set internal data on last search match from elements of LIST.\n\
1375LIST should have been created by calling `match-data' previously.")
1376 (list)
1377 register Lisp_Object list;
1378{
1379 register int i;
1380 register Lisp_Object marker;
1381
1382 if (!CONSP (list) && !NILP (list))
b37902c8 1383 list = wrong_type_argument (Qconsp, list);
ca1d1d23 1384
daa37602
JB
1385 /* Unless we find a marker with a buffer in LIST, assume that this
1386 match data came from a string. */
1387 last_thing_searched = Qt;
1388
4746118a
JB
1389 /* Allocate registers if they don't already exist. */
1390 {
d084e942 1391 int length = XFASTINT (Flength (list)) / 2;
4746118a
JB
1392
1393 if (length > search_regs.num_regs)
1394 {
1113d9db
JB
1395 if (search_regs.num_regs == 0)
1396 {
1397 search_regs.start
1398 = (regoff_t *) xmalloc (length * sizeof (regoff_t));
1399 search_regs.end
1400 = (regoff_t *) xmalloc (length * sizeof (regoff_t));
1401 }
4746118a 1402 else
1113d9db
JB
1403 {
1404 search_regs.start
1405 = (regoff_t *) xrealloc (search_regs.start,
1406 length * sizeof (regoff_t));
1407 search_regs.end
1408 = (regoff_t *) xrealloc (search_regs.end,
1409 length * sizeof (regoff_t));
1410 }
4746118a 1411
9ac0d9e0 1412 BLOCK_INPUT;
1113d9db
JB
1413 re_set_registers (&searchbuf, &search_regs, length,
1414 search_regs.start, search_regs.end);
9ac0d9e0 1415 UNBLOCK_INPUT;
4746118a
JB
1416 }
1417 }
1418
1419 for (i = 0; i < search_regs.num_regs; i++)
ca1d1d23
JB
1420 {
1421 marker = Fcar (list);
1422 if (NILP (marker))
1423 {
1424 search_regs.start[i] = -1;
1425 list = Fcdr (list);
1426 }
1427 else
1428 {
daa37602
JB
1429 if (XTYPE (marker) == Lisp_Marker)
1430 {
1431 if (XMARKER (marker)->buffer == 0)
1432 XFASTINT (marker) = 0;
1433 else
1434 XSET (last_thing_searched, Lisp_Buffer,
1435 XMARKER (marker)->buffer);
1436 }
ca1d1d23
JB
1437
1438 CHECK_NUMBER_COERCE_MARKER (marker, 0);
1439 search_regs.start[i] = XINT (marker);
1440 list = Fcdr (list);
1441
1442 marker = Fcar (list);
1443 if (XTYPE (marker) == Lisp_Marker
1444 && XMARKER (marker)->buffer == 0)
1445 XFASTINT (marker) = 0;
1446
1447 CHECK_NUMBER_COERCE_MARKER (marker, 0);
1448 search_regs.end[i] = XINT (marker);
1449 }
1450 list = Fcdr (list);
1451 }
1452
1453 return Qnil;
1454}
1455
1456/* Quote a string to inactivate reg-expr chars */
1457
1458DEFUN ("regexp-quote", Fregexp_quote, Sregexp_quote, 1, 1, 0,
1459 "Return a regexp string which matches exactly STRING and nothing else.")
1460 (str)
1461 Lisp_Object str;
1462{
1463 register unsigned char *in, *out, *end;
1464 register unsigned char *temp;
1465
1466 CHECK_STRING (str, 0);
1467
1468 temp = (unsigned char *) alloca (XSTRING (str)->size * 2);
1469
1470 /* Now copy the data into the new string, inserting escapes. */
1471
1472 in = XSTRING (str)->data;
1473 end = in + XSTRING (str)->size;
1474 out = temp;
1475
1476 for (; in != end; in++)
1477 {
1478 if (*in == '[' || *in == ']'
1479 || *in == '*' || *in == '.' || *in == '\\'
1480 || *in == '?' || *in == '+'
1481 || *in == '^' || *in == '$')
1482 *out++ = '\\';
1483 *out++ = *in;
1484 }
1485
1486 return make_string (temp, out - temp);
1487}
1488\f
1489syms_of_search ()
1490{
1491 register int i;
1492
1493 searchbuf.allocated = 100;
8c0e7b73 1494 searchbuf.buffer = (unsigned char *) malloc (searchbuf.allocated);
ca1d1d23
JB
1495 searchbuf.fastmap = search_fastmap;
1496
1497 Qsearch_failed = intern ("search-failed");
1498 staticpro (&Qsearch_failed);
1499 Qinvalid_regexp = intern ("invalid-regexp");
1500 staticpro (&Qinvalid_regexp);
1501
1502 Fput (Qsearch_failed, Qerror_conditions,
1503 Fcons (Qsearch_failed, Fcons (Qerror, Qnil)));
1504 Fput (Qsearch_failed, Qerror_message,
1505 build_string ("Search failed"));
1506
1507 Fput (Qinvalid_regexp, Qerror_conditions,
1508 Fcons (Qinvalid_regexp, Fcons (Qerror, Qnil)));
1509 Fput (Qinvalid_regexp, Qerror_message,
1510 build_string ("Invalid regexp"));
1511
1512 last_regexp = Qnil;
1513 staticpro (&last_regexp);
1514
daa37602
JB
1515 last_thing_searched = Qnil;
1516 staticpro (&last_thing_searched);
1517
ca1d1d23
JB
1518 defsubr (&Sstring_match);
1519 defsubr (&Slooking_at);
1520 defsubr (&Sskip_chars_forward);
1521 defsubr (&Sskip_chars_backward);
17431c60
RS
1522 defsubr (&Sskip_syntax_forward);
1523 defsubr (&Sskip_syntax_backward);
ca1d1d23
JB
1524 defsubr (&Ssearch_forward);
1525 defsubr (&Ssearch_backward);
1526 defsubr (&Sword_search_forward);
1527 defsubr (&Sword_search_backward);
1528 defsubr (&Sre_search_forward);
1529 defsubr (&Sre_search_backward);
1530 defsubr (&Sreplace_match);
1531 defsubr (&Smatch_beginning);
1532 defsubr (&Smatch_end);
1533 defsubr (&Smatch_data);
1534 defsubr (&Sstore_match_data);
1535 defsubr (&Sregexp_quote);
1536}