(line-number-display-limit): Doc fix.
[bpt/emacs.git] / src / search.c
CommitLineData
ca1d1d23 1/* String search routines for GNU Emacs.
31c8f881 2 Copyright (C) 1985, 86, 87, 93, 94, 97, 1998 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>
dfcf069d
AS
23#ifdef STDC_HEADERS
24#include <stdlib.h>
25#endif
ca1d1d23
JB
26#include "lisp.h"
27#include "syntax.h"
5679531d 28#include "category.h"
ca1d1d23 29#include "buffer.h"
5679531d 30#include "charset.h"
9169c321 31#include "region-cache.h"
ca1d1d23 32#include "commands.h"
9ac0d9e0 33#include "blockinput.h"
bf1760bb 34#include "intervals.h"
4746118a 35
ca1d1d23
JB
36#include <sys/types.h>
37#include "regex.h"
38
67ce527d
KH
39#define min(a, b) ((a) < (b) ? (a) : (b))
40#define max(a, b) ((a) > (b) ? (a) : (b))
41
1d288aef 42#define REGEXP_CACHE_SIZE 20
ca1d1d23 43
487282dc
KH
44/* If the regexp is non-nil, then the buffer contains the compiled form
45 of that regexp, suitable for searching. */
1d288aef
RS
46struct regexp_cache
47{
487282dc
KH
48 struct regexp_cache *next;
49 Lisp_Object regexp;
50 struct re_pattern_buffer buf;
51 char fastmap[0400];
b819a390
RS
52 /* Nonzero means regexp was compiled to do full POSIX backtracking. */
53 char posix;
487282dc 54};
ca1d1d23 55
487282dc
KH
56/* The instances of that struct. */
57struct regexp_cache searchbufs[REGEXP_CACHE_SIZE];
ca1d1d23 58
487282dc
KH
59/* The head of the linked list; points to the most recently used buffer. */
60struct regexp_cache *searchbuf_head;
ca1d1d23 61
ca1d1d23 62
4746118a
JB
63/* Every call to re_match, etc., must pass &search_regs as the regs
64 argument unless you can show it is unnecessary (i.e., if re_match
65 is certainly going to be called again before region-around-match
66 can be called).
67
68 Since the registers are now dynamically allocated, we need to make
69 sure not to refer to the Nth register before checking that it has
1113d9db
JB
70 been allocated by checking search_regs.num_regs.
71
72 The regex code keeps track of whether it has allocated the search
487282dc
KH
73 buffer using bits in the re_pattern_buffer. This means that whenever
74 you compile a new pattern, it completely forgets whether it has
1113d9db
JB
75 allocated any registers, and will allocate new registers the next
76 time you call a searching or matching function. Therefore, we need
77 to call re_set_registers after compiling a new pattern or after
78 setting the match registers, so that the regex functions will be
79 able to free or re-allocate it properly. */
ca1d1d23
JB
80static struct re_registers search_regs;
81
daa37602
JB
82/* The buffer in which the last search was performed, or
83 Qt if the last search was done in a string;
84 Qnil if no searching has been done yet. */
85static Lisp_Object last_thing_searched;
ca1d1d23 86
8e6208c5 87/* error condition signaled when regexp compile_pattern fails */
ca1d1d23
JB
88
89Lisp_Object Qinvalid_regexp;
90
ca325161 91static void set_search_regs ();
044f81f1 92static void save_search_regs ();
facdc750
RS
93static int simple_search ();
94static int boyer_moore ();
b819a390
RS
95static int search_buffer ();
96
ca1d1d23
JB
97static void
98matcher_overflow ()
99{
100 error ("Stack overflow in regexp matcher");
101}
102
103#ifdef __STDC__
104#define CONST const
105#else
106#define CONST
107#endif
108
b819a390
RS
109/* Compile a regexp and signal a Lisp error if anything goes wrong.
110 PATTERN is the pattern to compile.
111 CP is the place to put the result.
facdc750 112 TRANSLATE is a translation table for ignoring case, or nil for none.
b819a390
RS
113 REGP is the structure that says where to store the "register"
114 values that will result from matching this pattern.
115 If it is 0, we should compile the pattern not to record any
116 subexpression bounds.
117 POSIX is nonzero if we want full backtracking (POSIX style)
5679531d
KH
118 for this pattern. 0 means backtrack only enough to get a valid match.
119 MULTIBYTE is nonzero if we want to handle multibyte characters in
120 PATTERN. 0 means all multibyte characters are recognized just as
121 sequences of binary data. */
ca1d1d23 122
487282dc 123static void
5679531d 124compile_pattern_1 (cp, pattern, translate, regp, posix, multibyte)
487282dc 125 struct regexp_cache *cp;
ca1d1d23 126 Lisp_Object pattern;
facdc750 127 Lisp_Object translate;
487282dc 128 struct re_registers *regp;
b819a390 129 int posix;
5679531d 130 int multibyte;
ca1d1d23 131{
7276d3d8 132 unsigned char *raw_pattern;
f8bd51c4 133 int raw_pattern_size;
d451e4db 134 char *val;
b819a390 135 reg_syntax_t old;
ca1d1d23 136
f8bd51c4
KH
137 /* MULTIBYTE says whether the text to be searched is multibyte.
138 We must convert PATTERN to match that, or we will not really
139 find things right. */
140
141 if (multibyte == STRING_MULTIBYTE (pattern))
142 {
7276d3d8 143 raw_pattern = (unsigned char *) XSTRING (pattern)->data;
fc932ac6 144 raw_pattern_size = STRING_BYTES (XSTRING (pattern));
f8bd51c4
KH
145 }
146 else if (multibyte)
147 {
148 raw_pattern_size = count_size_as_multibyte (XSTRING (pattern)->data,
149 XSTRING (pattern)->size);
7276d3d8 150 raw_pattern = (unsigned char *) alloca (raw_pattern_size + 1);
f8bd51c4
KH
151 copy_text (XSTRING (pattern)->data, raw_pattern,
152 XSTRING (pattern)->size, 0, 1);
153 }
154 else
155 {
156 /* Converting multibyte to single-byte.
157
158 ??? Perhaps this conversion should be done in a special way
159 by subtracting nonascii-insert-offset from each non-ASCII char,
160 so that only the multibyte chars which really correspond to
161 the chosen single-byte character set can possibly match. */
162 raw_pattern_size = XSTRING (pattern)->size;
7276d3d8 163 raw_pattern = (unsigned char *) alloca (raw_pattern_size + 1);
f8bd51c4 164 copy_text (XSTRING (pattern)->data, raw_pattern,
fc932ac6 165 STRING_BYTES (XSTRING (pattern)), 1, 0);
f8bd51c4
KH
166 }
167
487282dc 168 cp->regexp = Qnil;
59fab369 169 cp->buf.translate = (! NILP (translate) ? translate : make_number (0));
b819a390 170 cp->posix = posix;
5679531d 171 cp->buf.multibyte = multibyte;
9ac0d9e0 172 BLOCK_INPUT;
b819a390
RS
173 old = re_set_syntax (RE_SYNTAX_EMACS
174 | (posix ? 0 : RE_NO_POSIX_BACKTRACKING));
7276d3d8
RS
175 val = (char *) re_compile_pattern ((char *)raw_pattern,
176 raw_pattern_size, &cp->buf);
b819a390 177 re_set_syntax (old);
9ac0d9e0 178 UNBLOCK_INPUT;
ca1d1d23 179 if (val)
487282dc 180 Fsignal (Qinvalid_regexp, Fcons (build_string (val), Qnil));
1113d9db 181
487282dc 182 cp->regexp = Fcopy_sequence (pattern);
487282dc
KH
183}
184
6efc7887
RS
185/* Shrink each compiled regexp buffer in the cache
186 to the size actually used right now.
187 This is called from garbage collection. */
188
189void
190shrink_regexp_cache ()
191{
192 struct regexp_cache *cp, **cpp;
193
194 for (cp = searchbuf_head; cp != 0; cp = cp->next)
195 {
196 cp->buf.allocated = cp->buf.used;
197 cp->buf.buffer
198 = (unsigned char *) realloc (cp->buf.buffer, cp->buf.used);
199 }
200}
201
487282dc 202/* Compile a regexp if necessary, but first check to see if there's one in
b819a390
RS
203 the cache.
204 PATTERN is the pattern to compile.
facdc750 205 TRANSLATE is a translation table for ignoring case, or nil for none.
b819a390
RS
206 REGP is the structure that says where to store the "register"
207 values that will result from matching this pattern.
208 If it is 0, we should compile the pattern not to record any
209 subexpression bounds.
210 POSIX is nonzero if we want full backtracking (POSIX style)
211 for this pattern. 0 means backtrack only enough to get a valid match. */
487282dc
KH
212
213struct re_pattern_buffer *
0c8533c6 214compile_pattern (pattern, regp, translate, posix, multibyte)
487282dc
KH
215 Lisp_Object pattern;
216 struct re_registers *regp;
facdc750 217 Lisp_Object translate;
0c8533c6 218 int posix, multibyte;
487282dc
KH
219{
220 struct regexp_cache *cp, **cpp;
221
222 for (cpp = &searchbuf_head; ; cpp = &cp->next)
223 {
224 cp = *cpp;
1d288aef
RS
225 if (XSTRING (cp->regexp)->size == XSTRING (pattern)->size
226 && !NILP (Fstring_equal (cp->regexp, pattern))
59fab369 227 && EQ (cp->buf.translate, (! NILP (translate) ? translate : make_number (0)))
5679531d
KH
228 && cp->posix == posix
229 && cp->buf.multibyte == multibyte)
487282dc
KH
230 break;
231
232 /* If we're at the end of the cache, compile into the last cell. */
233 if (cp->next == 0)
234 {
5679531d 235 compile_pattern_1 (cp, pattern, translate, regp, posix, multibyte);
487282dc
KH
236 break;
237 }
238 }
239
240 /* When we get here, cp (aka *cpp) contains the compiled pattern,
241 either because we found it in the cache or because we just compiled it.
242 Move it to the front of the queue to mark it as most recently used. */
243 *cpp = cp->next;
244 cp->next = searchbuf_head;
245 searchbuf_head = cp;
1113d9db 246
6639708c
RS
247 /* Advise the searching functions about the space we have allocated
248 for register data. */
249 if (regp)
250 re_set_registers (&cp->buf, regp, regp->num_regs, regp->start, regp->end);
251
487282dc 252 return &cp->buf;
ca1d1d23
JB
253}
254
255/* Error condition used for failing searches */
256Lisp_Object Qsearch_failed;
257
258Lisp_Object
259signal_failure (arg)
260 Lisp_Object arg;
261{
262 Fsignal (Qsearch_failed, Fcons (arg, Qnil));
263 return Qnil;
264}
265\f
b819a390
RS
266static Lisp_Object
267looking_at_1 (string, posix)
ca1d1d23 268 Lisp_Object string;
b819a390 269 int posix;
ca1d1d23
JB
270{
271 Lisp_Object val;
272 unsigned char *p1, *p2;
273 int s1, s2;
274 register int i;
487282dc 275 struct re_pattern_buffer *bufp;
ca1d1d23 276
7074fde6
FP
277 if (running_asynch_code)
278 save_search_regs ();
279
ca1d1d23 280 CHECK_STRING (string, 0);
487282dc
KH
281 bufp = compile_pattern (string, &search_regs,
282 (!NILP (current_buffer->case_fold_search)
facdc750 283 ? DOWNCASE_TABLE : Qnil),
0c8533c6
RS
284 posix,
285 !NILP (current_buffer->enable_multibyte_characters));
ca1d1d23
JB
286
287 immediate_quit = 1;
288 QUIT; /* Do a pending quit right away, to avoid paradoxical behavior */
289
290 /* Get pointers and sizes of the two strings
291 that make up the visible portion of the buffer. */
292
293 p1 = BEGV_ADDR;
fa8ed3e0 294 s1 = GPT_BYTE - BEGV_BYTE;
ca1d1d23 295 p2 = GAP_END_ADDR;
fa8ed3e0 296 s2 = ZV_BYTE - GPT_BYTE;
ca1d1d23
JB
297 if (s1 < 0)
298 {
299 p2 = p1;
fa8ed3e0 300 s2 = ZV_BYTE - BEGV_BYTE;
ca1d1d23
JB
301 s1 = 0;
302 }
303 if (s2 < 0)
304 {
fa8ed3e0 305 s1 = ZV_BYTE - BEGV_BYTE;
ca1d1d23
JB
306 s2 = 0;
307 }
8bb43c28
RS
308
309 re_match_object = Qnil;
ca1d1d23 310
487282dc 311 i = re_match_2 (bufp, (char *) p1, s1, (char *) p2, s2,
fa8ed3e0
RS
312 PT_BYTE - BEGV_BYTE, &search_regs,
313 ZV_BYTE - BEGV_BYTE);
ca1d1d23
JB
314 if (i == -2)
315 matcher_overflow ();
316
317 val = (0 <= i ? Qt : Qnil);
fa8ed3e0
RS
318 if (i >= 0)
319 for (i = 0; i < search_regs.num_regs; i++)
320 if (search_regs.start[i] >= 0)
321 {
322 search_regs.start[i]
323 = BYTE_TO_CHAR (search_regs.start[i] + BEGV_BYTE);
324 search_regs.end[i]
325 = BYTE_TO_CHAR (search_regs.end[i] + BEGV_BYTE);
326 }
a3668d92 327 XSETBUFFER (last_thing_searched, current_buffer);
ca1d1d23
JB
328 immediate_quit = 0;
329 return val;
330}
331
b819a390 332DEFUN ("looking-at", Flooking_at, Slooking_at, 1, 1, 0,
94f94972 333 "Return t if text after point matches regular expression REGEXP.\n\
b819a390
RS
334This function modifies the match data that `match-beginning',\n\
335`match-end' and `match-data' access; save and restore the match\n\
336data if you want to preserve them.")
94f94972
RS
337 (regexp)
338 Lisp_Object regexp;
b819a390 339{
94f94972 340 return looking_at_1 (regexp, 0);
b819a390
RS
341}
342
343DEFUN ("posix-looking-at", Fposix_looking_at, Sposix_looking_at, 1, 1, 0,
94f94972 344 "Return t if text after point matches regular expression REGEXP.\n\
b819a390
RS
345Find the longest match, in accord with Posix regular expression rules.\n\
346This function modifies the match data that `match-beginning',\n\
347`match-end' and `match-data' access; save and restore the match\n\
348data if you want to preserve them.")
94f94972
RS
349 (regexp)
350 Lisp_Object regexp;
b819a390 351{
94f94972 352 return looking_at_1 (regexp, 1);
b819a390
RS
353}
354\f
355static Lisp_Object
356string_match_1 (regexp, string, start, posix)
ca1d1d23 357 Lisp_Object regexp, string, start;
b819a390 358 int posix;
ca1d1d23
JB
359{
360 int val;
487282dc 361 struct re_pattern_buffer *bufp;
0c8533c6
RS
362 int pos, pos_byte;
363 int i;
ca1d1d23 364
7074fde6
FP
365 if (running_asynch_code)
366 save_search_regs ();
367
ca1d1d23
JB
368 CHECK_STRING (regexp, 0);
369 CHECK_STRING (string, 1);
370
371 if (NILP (start))
0c8533c6 372 pos = 0, pos_byte = 0;
ca1d1d23
JB
373 else
374 {
375 int len = XSTRING (string)->size;
376
377 CHECK_NUMBER (start, 2);
0c8533c6
RS
378 pos = XINT (start);
379 if (pos < 0 && -pos <= len)
380 pos = len + pos;
381 else if (0 > pos || pos > len)
ca1d1d23 382 args_out_of_range (string, start);
0c8533c6 383 pos_byte = string_char_to_byte (string, pos);
ca1d1d23
JB
384 }
385
487282dc
KH
386 bufp = compile_pattern (regexp, &search_regs,
387 (!NILP (current_buffer->case_fold_search)
facdc750 388 ? DOWNCASE_TABLE : Qnil),
0c8533c6
RS
389 posix,
390 STRING_MULTIBYTE (string));
ca1d1d23 391 immediate_quit = 1;
8bb43c28
RS
392 re_match_object = string;
393
487282dc 394 val = re_search (bufp, (char *) XSTRING (string)->data,
fc932ac6
RS
395 STRING_BYTES (XSTRING (string)), pos_byte,
396 STRING_BYTES (XSTRING (string)) - pos_byte,
ca1d1d23
JB
397 &search_regs);
398 immediate_quit = 0;
daa37602 399 last_thing_searched = Qt;
ca1d1d23
JB
400 if (val == -2)
401 matcher_overflow ();
402 if (val < 0) return Qnil;
0c8533c6
RS
403
404 for (i = 0; i < search_regs.num_regs; i++)
405 if (search_regs.start[i] >= 0)
406 {
407 search_regs.start[i]
408 = string_byte_to_char (string, search_regs.start[i]);
409 search_regs.end[i]
410 = string_byte_to_char (string, search_regs.end[i]);
411 }
412
413 return make_number (string_byte_to_char (string, val));
ca1d1d23 414}
e59a8453 415
b819a390
RS
416DEFUN ("string-match", Fstring_match, Sstring_match, 2, 3, 0,
417 "Return index of start of first match for REGEXP in STRING, or nil.\n\
21e01890 418Case is ignored if `case-fold-search' is non-nil in the current buffer.\n\
b819a390
RS
419If third arg START is non-nil, start search at that index in STRING.\n\
420For index of first char beyond the match, do (match-end 0).\n\
421`match-end' and `match-beginning' also give indices of substrings\n\
422matched by parenthesis constructs in the pattern.")
423 (regexp, string, start)
424 Lisp_Object regexp, string, start;
425{
426 return string_match_1 (regexp, string, start, 0);
427}
428
429DEFUN ("posix-string-match", Fposix_string_match, Sposix_string_match, 2, 3, 0,
430 "Return index of start of first match for REGEXP in STRING, or nil.\n\
431Find the longest match, in accord with Posix regular expression rules.\n\
21e01890 432Case is ignored if `case-fold-search' is non-nil in the current buffer.\n\
b819a390
RS
433If third arg START is non-nil, start search at that index in STRING.\n\
434For index of first char beyond the match, do (match-end 0).\n\
435`match-end' and `match-beginning' also give indices of substrings\n\
436matched by parenthesis constructs in the pattern.")
437 (regexp, string, start)
438 Lisp_Object regexp, string, start;
439{
440 return string_match_1 (regexp, string, start, 1);
441}
442
e59a8453
RS
443/* Match REGEXP against STRING, searching all of STRING,
444 and return the index of the match, or negative on failure.
445 This does not clobber the match data. */
446
447int
448fast_string_match (regexp, string)
449 Lisp_Object regexp, string;
450{
451 int val;
487282dc 452 struct re_pattern_buffer *bufp;
e59a8453 453
facdc750
RS
454 bufp = compile_pattern (regexp, 0, Qnil,
455 0, STRING_MULTIBYTE (string));
e59a8453 456 immediate_quit = 1;
8bb43c28
RS
457 re_match_object = string;
458
487282dc 459 val = re_search (bufp, (char *) XSTRING (string)->data,
fc932ac6
RS
460 STRING_BYTES (XSTRING (string)), 0,
461 STRING_BYTES (XSTRING (string)), 0);
e59a8453
RS
462 immediate_quit = 0;
463 return val;
464}
5679531d
KH
465
466/* Match REGEXP against STRING, searching all of STRING ignoring case,
467 and return the index of the match, or negative on failure.
0c8533c6
RS
468 This does not clobber the match data.
469 We assume that STRING contains single-byte characters. */
5679531d
KH
470
471extern Lisp_Object Vascii_downcase_table;
472
473int
b4577c63 474fast_c_string_match_ignore_case (regexp, string)
5679531d
KH
475 Lisp_Object regexp;
476 char *string;
477{
478 int val;
479 struct re_pattern_buffer *bufp;
480 int len = strlen (string);
481
0c8533c6 482 regexp = string_make_unibyte (regexp);
b4577c63 483 re_match_object = Qt;
5679531d 484 bufp = compile_pattern (regexp, 0,
facdc750 485 Vascii_downcase_table, 0,
f8bd51c4 486 0);
5679531d
KH
487 immediate_quit = 1;
488 val = re_search (bufp, string, len, 0, len, 0);
489 immediate_quit = 0;
490 return val;
491}
ca1d1d23 492\f
9169c321
JB
493/* The newline cache: remembering which sections of text have no newlines. */
494
495/* If the user has requested newline caching, make sure it's on.
496 Otherwise, make sure it's off.
497 This is our cheezy way of associating an action with the change of
498 state of a buffer-local variable. */
499static void
500newline_cache_on_off (buf)
501 struct buffer *buf;
502{
503 if (NILP (buf->cache_long_line_scans))
504 {
505 /* It should be off. */
506 if (buf->newline_cache)
507 {
508 free_region_cache (buf->newline_cache);
509 buf->newline_cache = 0;
510 }
511 }
512 else
513 {
514 /* It should be on. */
515 if (buf->newline_cache == 0)
516 buf->newline_cache = new_region_cache ();
517 }
518}
519
520\f
521/* Search for COUNT instances of the character TARGET between START and END.
522
523 If COUNT is positive, search forwards; END must be >= START.
524 If COUNT is negative, search backwards for the -COUNTth instance;
525 END must be <= START.
526 If COUNT is zero, do anything you please; run rogue, for all I care.
527
528 If END is zero, use BEGV or ZV instead, as appropriate for the
529 direction indicated by COUNT.
ffd56f97
JB
530
531 If we find COUNT instances, set *SHORTAGE to zero, and return the
5bfe95c9
RS
532 position after the COUNTth match. Note that for reverse motion
533 this is not the same as the usual convention for Emacs motion commands.
ffd56f97 534
9169c321
JB
535 If we don't find COUNT instances before reaching END, set *SHORTAGE
536 to the number of TARGETs left unfound, and return END.
ffd56f97 537
087a5f81
RS
538 If ALLOW_QUIT is non-zero, set immediate_quit. That's good to do
539 except when inside redisplay. */
540
dfcf069d 541int
9169c321
JB
542scan_buffer (target, start, end, count, shortage, allow_quit)
543 register int target;
544 int start, end;
545 int count;
546 int *shortage;
087a5f81 547 int allow_quit;
ca1d1d23 548{
9169c321
JB
549 struct region_cache *newline_cache;
550 int direction;
ffd56f97 551
9169c321
JB
552 if (count > 0)
553 {
554 direction = 1;
555 if (! end) end = ZV;
556 }
557 else
558 {
559 direction = -1;
560 if (! end) end = BEGV;
561 }
ffd56f97 562
9169c321
JB
563 newline_cache_on_off (current_buffer);
564 newline_cache = current_buffer->newline_cache;
ca1d1d23
JB
565
566 if (shortage != 0)
567 *shortage = 0;
568
087a5f81 569 immediate_quit = allow_quit;
ca1d1d23 570
ffd56f97 571 if (count > 0)
9169c321 572 while (start != end)
ca1d1d23 573 {
9169c321
JB
574 /* Our innermost scanning loop is very simple; it doesn't know
575 about gaps, buffer ends, or the newline cache. ceiling is
576 the position of the last character before the next such
577 obstacle --- the last character the dumb search loop should
578 examine. */
fa8ed3e0
RS
579 int ceiling_byte = CHAR_TO_BYTE (end) - 1;
580 int start_byte = CHAR_TO_BYTE (start);
67ce527d 581 int tem;
9169c321
JB
582
583 /* If we're looking for a newline, consult the newline cache
584 to see where we can avoid some scanning. */
585 if (target == '\n' && newline_cache)
586 {
587 int next_change;
588 immediate_quit = 0;
589 while (region_cache_forward
fa8ed3e0
RS
590 (current_buffer, newline_cache, start_byte, &next_change))
591 start_byte = next_change;
cbe0db0d 592 immediate_quit = allow_quit;
9169c321 593
fa8ed3e0
RS
594 /* START should never be after END. */
595 if (start_byte > ceiling_byte)
596 start_byte = ceiling_byte;
9169c321
JB
597
598 /* Now the text after start is an unknown region, and
599 next_change is the position of the next known region. */
fa8ed3e0 600 ceiling_byte = min (next_change - 1, ceiling_byte);
9169c321
JB
601 }
602
603 /* The dumb loop can only scan text stored in contiguous
604 bytes. BUFFER_CEILING_OF returns the last character
605 position that is contiguous, so the ceiling is the
606 position after that. */
67ce527d
KH
607 tem = BUFFER_CEILING_OF (start_byte);
608 ceiling_byte = min (tem, ceiling_byte);
9169c321
JB
609
610 {
611 /* The termination address of the dumb loop. */
fa8ed3e0
RS
612 register unsigned char *ceiling_addr
613 = BYTE_POS_ADDR (ceiling_byte) + 1;
614 register unsigned char *cursor
615 = BYTE_POS_ADDR (start_byte);
9169c321
JB
616 unsigned char *base = cursor;
617
618 while (cursor < ceiling_addr)
619 {
620 unsigned char *scan_start = cursor;
621
622 /* The dumb loop. */
623 while (*cursor != target && ++cursor < ceiling_addr)
624 ;
625
626 /* If we're looking for newlines, cache the fact that
627 the region from start to cursor is free of them. */
628 if (target == '\n' && newline_cache)
629 know_region_cache (current_buffer, newline_cache,
fa8ed3e0
RS
630 start_byte + scan_start - base,
631 start_byte + cursor - base);
9169c321
JB
632
633 /* Did we find the target character? */
634 if (cursor < ceiling_addr)
635 {
636 if (--count == 0)
637 {
638 immediate_quit = 0;
fa8ed3e0 639 return BYTE_TO_CHAR (start_byte + cursor - base + 1);
9169c321
JB
640 }
641 cursor++;
642 }
643 }
644
fa8ed3e0 645 start = BYTE_TO_CHAR (start_byte + cursor - base);
9169c321 646 }
ca1d1d23
JB
647 }
648 else
9169c321
JB
649 while (start > end)
650 {
651 /* The last character to check before the next obstacle. */
fa8ed3e0
RS
652 int ceiling_byte = CHAR_TO_BYTE (end);
653 int start_byte = CHAR_TO_BYTE (start);
67ce527d 654 int tem;
9169c321
JB
655
656 /* Consult the newline cache, if appropriate. */
657 if (target == '\n' && newline_cache)
658 {
659 int next_change;
660 immediate_quit = 0;
661 while (region_cache_backward
fa8ed3e0
RS
662 (current_buffer, newline_cache, start_byte, &next_change))
663 start_byte = next_change;
cbe0db0d 664 immediate_quit = allow_quit;
9169c321
JB
665
666 /* Start should never be at or before end. */
fa8ed3e0
RS
667 if (start_byte <= ceiling_byte)
668 start_byte = ceiling_byte + 1;
9169c321
JB
669
670 /* Now the text before start is an unknown region, and
671 next_change is the position of the next known region. */
fa8ed3e0 672 ceiling_byte = max (next_change, ceiling_byte);
9169c321
JB
673 }
674
675 /* Stop scanning before the gap. */
67ce527d
KH
676 tem = BUFFER_FLOOR_OF (start_byte - 1);
677 ceiling_byte = max (tem, ceiling_byte);
9169c321
JB
678
679 {
680 /* The termination address of the dumb loop. */
fa8ed3e0
RS
681 register unsigned char *ceiling_addr = BYTE_POS_ADDR (ceiling_byte);
682 register unsigned char *cursor = BYTE_POS_ADDR (start_byte - 1);
9169c321
JB
683 unsigned char *base = cursor;
684
685 while (cursor >= ceiling_addr)
686 {
687 unsigned char *scan_start = cursor;
688
689 while (*cursor != target && --cursor >= ceiling_addr)
690 ;
691
692 /* If we're looking for newlines, cache the fact that
693 the region from after the cursor to start is free of them. */
694 if (target == '\n' && newline_cache)
695 know_region_cache (current_buffer, newline_cache,
fa8ed3e0
RS
696 start_byte + cursor - base,
697 start_byte + scan_start - base);
9169c321
JB
698
699 /* Did we find the target character? */
700 if (cursor >= ceiling_addr)
701 {
702 if (++count >= 0)
703 {
704 immediate_quit = 0;
fa8ed3e0 705 return BYTE_TO_CHAR (start_byte + cursor - base);
9169c321
JB
706 }
707 cursor--;
708 }
709 }
710
fa8ed3e0 711 start = BYTE_TO_CHAR (start_byte + cursor - base);
9169c321
JB
712 }
713 }
714
ca1d1d23
JB
715 immediate_quit = 0;
716 if (shortage != 0)
ffd56f97 717 *shortage = count * direction;
9169c321 718 return start;
ca1d1d23 719}
fa8ed3e0
RS
720\f
721/* Search for COUNT instances of a line boundary, which means either a
722 newline or (if selective display enabled) a carriage return.
723 Start at START. If COUNT is negative, search backwards.
724
725 We report the resulting position by calling TEMP_SET_PT_BOTH.
726
727 If we find COUNT instances. we position after (always after,
728 even if scanning backwards) the COUNTth match, and return 0.
729
730 If we don't find COUNT instances before reaching the end of the
731 buffer (or the beginning, if scanning backwards), we return
732 the number of line boundaries left unfound, and position at
733 the limit we bumped up against.
734
735 If ALLOW_QUIT is non-zero, set immediate_quit. That's good to do
d5d57b92 736 except in special cases. */
ca1d1d23 737
63fa018d 738int
fa8ed3e0
RS
739scan_newline (start, start_byte, limit, limit_byte, count, allow_quit)
740 int start, start_byte;
741 int limit, limit_byte;
742 register int count;
743 int allow_quit;
63fa018d 744{
fa8ed3e0
RS
745 int direction = ((count > 0) ? 1 : -1);
746
747 register unsigned char *cursor;
748 unsigned char *base;
749
750 register int ceiling;
751 register unsigned char *ceiling_addr;
752
d5d57b92
RS
753 int old_immediate_quit = immediate_quit;
754
fa8ed3e0
RS
755 /* If we are not in selective display mode,
756 check only for newlines. */
757 int selective_display = (!NILP (current_buffer->selective_display)
758 && !INTEGERP (current_buffer->selective_display));
759
760 /* The code that follows is like scan_buffer
761 but checks for either newline or carriage return. */
762
d5d57b92
RS
763 if (allow_quit)
764 immediate_quit++;
fa8ed3e0
RS
765
766 start_byte = CHAR_TO_BYTE (start);
767
768 if (count > 0)
769 {
770 while (start_byte < limit_byte)
771 {
772 ceiling = BUFFER_CEILING_OF (start_byte);
773 ceiling = min (limit_byte - 1, ceiling);
774 ceiling_addr = BYTE_POS_ADDR (ceiling) + 1;
775 base = (cursor = BYTE_POS_ADDR (start_byte));
776 while (1)
777 {
778 while (*cursor != '\n' && ++cursor != ceiling_addr)
779 ;
780
781 if (cursor != ceiling_addr)
782 {
783 if (--count == 0)
784 {
d5d57b92 785 immediate_quit = old_immediate_quit;
fa8ed3e0
RS
786 start_byte = start_byte + cursor - base + 1;
787 start = BYTE_TO_CHAR (start_byte);
788 TEMP_SET_PT_BOTH (start, start_byte);
789 return 0;
790 }
791 else
792 if (++cursor == ceiling_addr)
793 break;
794 }
795 else
796 break;
797 }
798 start_byte += cursor - base;
799 }
800 }
801 else
802 {
fa8ed3e0
RS
803 while (start_byte > limit_byte)
804 {
805 ceiling = BUFFER_FLOOR_OF (start_byte - 1);
806 ceiling = max (limit_byte, ceiling);
807 ceiling_addr = BYTE_POS_ADDR (ceiling) - 1;
808 base = (cursor = BYTE_POS_ADDR (start_byte - 1) + 1);
809 while (1)
810 {
811 while (--cursor != ceiling_addr && *cursor != '\n')
812 ;
813
814 if (cursor != ceiling_addr)
815 {
816 if (++count == 0)
817 {
d5d57b92 818 immediate_quit = old_immediate_quit;
fa8ed3e0
RS
819 /* Return the position AFTER the match we found. */
820 start_byte = start_byte + cursor - base + 1;
821 start = BYTE_TO_CHAR (start_byte);
822 TEMP_SET_PT_BOTH (start, start_byte);
823 return 0;
824 }
825 }
826 else
827 break;
828 }
829 /* Here we add 1 to compensate for the last decrement
830 of CURSOR, which took it past the valid range. */
831 start_byte += cursor - base + 1;
832 }
833 }
834
835 TEMP_SET_PT_BOTH (limit, limit_byte);
d5d57b92 836 immediate_quit = old_immediate_quit;
fa8ed3e0
RS
837
838 return count * direction;
63fa018d
RS
839}
840
ca1d1d23 841int
fa8ed3e0 842find_next_newline_no_quit (from, cnt)
ca1d1d23
JB
843 register int from, cnt;
844{
fa8ed3e0 845 return scan_buffer ('\n', from, 0, cnt, (int *) 0, 0);
9169c321
JB
846}
847
9169c321
JB
848/* Like find_next_newline, but returns position before the newline,
849 not after, and only search up to TO. This isn't just
850 find_next_newline (...)-1, because you might hit TO. */
fa8ed3e0 851
9169c321
JB
852int
853find_before_next_newline (from, to, cnt)
cbe0db0d 854 int from, to, cnt;
9169c321
JB
855{
856 int shortage;
857 int pos = scan_buffer ('\n', from, to, cnt, &shortage, 1);
858
859 if (shortage == 0)
860 pos--;
861
862 return pos;
ca1d1d23
JB
863}
864\f
ca1d1d23
JB
865/* Subroutines of Lisp buffer search functions. */
866
867static Lisp_Object
b819a390 868search_command (string, bound, noerror, count, direction, RE, posix)
ca1d1d23
JB
869 Lisp_Object string, bound, noerror, count;
870 int direction;
871 int RE;
b819a390 872 int posix;
ca1d1d23
JB
873{
874 register int np;
9f43ad85 875 int lim, lim_byte;
ca1d1d23
JB
876 int n = direction;
877
878 if (!NILP (count))
879 {
880 CHECK_NUMBER (count, 3);
881 n *= XINT (count);
882 }
883
884 CHECK_STRING (string, 0);
885 if (NILP (bound))
9f43ad85
RS
886 {
887 if (n > 0)
888 lim = ZV, lim_byte = ZV_BYTE;
889 else
890 lim = BEGV, lim_byte = BEGV_BYTE;
891 }
ca1d1d23
JB
892 else
893 {
894 CHECK_NUMBER_COERCE_MARKER (bound, 1);
895 lim = XINT (bound);
6ec8bbd2 896 if (n > 0 ? lim < PT : lim > PT)
ca1d1d23
JB
897 error ("Invalid search bound (wrong side of point)");
898 if (lim > ZV)
9f43ad85 899 lim = ZV, lim_byte = ZV_BYTE;
588d2fd5 900 else if (lim < BEGV)
9f43ad85 901 lim = BEGV, lim_byte = BEGV_BYTE;
588d2fd5
KH
902 else
903 lim_byte = CHAR_TO_BYTE (lim);
ca1d1d23
JB
904 }
905
9f43ad85 906 np = search_buffer (string, PT, PT_BYTE, lim, lim_byte, n, RE,
ca1d1d23 907 (!NILP (current_buffer->case_fold_search)
facdc750 908 ? current_buffer->case_canon_table
3135e9fd 909 : Qnil),
ca1d1d23 910 (!NILP (current_buffer->case_fold_search)
facdc750 911 ? current_buffer->case_eqv_table
3135e9fd 912 : Qnil),
b819a390 913 posix);
ca1d1d23
JB
914 if (np <= 0)
915 {
916 if (NILP (noerror))
917 return signal_failure (string);
918 if (!EQ (noerror, Qt))
919 {
920 if (lim < BEGV || lim > ZV)
921 abort ();
9f43ad85 922 SET_PT_BOTH (lim, lim_byte);
a5f217b8
RS
923 return Qnil;
924#if 0 /* This would be clean, but maybe programs depend on
925 a value of nil here. */
481399bf 926 np = lim;
a5f217b8 927#endif
ca1d1d23 928 }
481399bf
RS
929 else
930 return Qnil;
ca1d1d23
JB
931 }
932
933 if (np < BEGV || np > ZV)
934 abort ();
935
936 SET_PT (np);
937
938 return make_number (np);
939}
940\f
fa8ed3e0
RS
941/* Return 1 if REGEXP it matches just one constant string. */
942
b6d6a51c
KH
943static int
944trivial_regexp_p (regexp)
945 Lisp_Object regexp;
946{
fc932ac6 947 int len = STRING_BYTES (XSTRING (regexp));
b6d6a51c
KH
948 unsigned char *s = XSTRING (regexp)->data;
949 unsigned char c;
950 while (--len >= 0)
951 {
952 switch (*s++)
953 {
954 case '.': case '*': case '+': case '?': case '[': case '^': case '$':
955 return 0;
956 case '\\':
957 if (--len < 0)
958 return 0;
959 switch (*s++)
960 {
961 case '|': case '(': case ')': case '`': case '\'': case 'b':
962 case 'B': case '<': case '>': case 'w': case 'W': case 's':
866f60fd 963 case 'S': case '=':
5679531d 964 case 'c': case 'C': /* for categoryspec and notcategoryspec */
866f60fd 965 case '1': case '2': case '3': case '4': case '5':
b6d6a51c
KH
966 case '6': case '7': case '8': case '9':
967 return 0;
968 }
969 }
970 }
971 return 1;
972}
973
ca325161 974/* Search for the n'th occurrence of STRING in the current buffer,
ca1d1d23 975 starting at position POS and stopping at position LIM,
b819a390 976 treating STRING as a literal string if RE is false or as
ca1d1d23
JB
977 a regular expression if RE is true.
978
979 If N is positive, searching is forward and LIM must be greater than POS.
980 If N is negative, searching is backward and LIM must be less than POS.
981
facdc750 982 Returns -x if x occurrences remain to be found (x > 0),
ca1d1d23 983 or else the position at the beginning of the Nth occurrence
b819a390
RS
984 (if searching backward) or the end (if searching forward).
985
986 POSIX is nonzero if we want full backtracking (POSIX style)
987 for this pattern. 0 means backtrack only enough to get a valid match. */
ca1d1d23 988
aff2ce94
RS
989#define TRANSLATE(out, trt, d) \
990do \
991 { \
992 if (! NILP (trt)) \
993 { \
994 Lisp_Object temp; \
995 temp = Faref (trt, make_number (d)); \
996 if (INTEGERP (temp)) \
997 out = XINT (temp); \
998 else \
999 out = d; \
1000 } \
1001 else \
1002 out = d; \
1003 } \
1004while (0)
facdc750 1005
b819a390 1006static int
9f43ad85
RS
1007search_buffer (string, pos, pos_byte, lim, lim_byte, n,
1008 RE, trt, inverse_trt, posix)
ca1d1d23
JB
1009 Lisp_Object string;
1010 int pos;
9f43ad85 1011 int pos_byte;
ca1d1d23 1012 int lim;
9f43ad85 1013 int lim_byte;
ca1d1d23
JB
1014 int n;
1015 int RE;
facdc750
RS
1016 Lisp_Object trt;
1017 Lisp_Object inverse_trt;
b819a390 1018 int posix;
ca1d1d23
JB
1019{
1020 int len = XSTRING (string)->size;
fc932ac6 1021 int len_byte = STRING_BYTES (XSTRING (string));
facdc750 1022 register int i;
ca1d1d23 1023
7074fde6
FP
1024 if (running_asynch_code)
1025 save_search_regs ();
1026
a7e4cdde 1027 /* Searching 0 times means don't move. */
ca1d1d23 1028 /* Null string is found at starting position. */
a7e4cdde 1029 if (len == 0 || n == 0)
ca325161
RS
1030 {
1031 set_search_regs (pos, 0);
1032 return pos;
1033 }
3f57a499 1034
b6d6a51c 1035 if (RE && !trivial_regexp_p (string))
ca1d1d23 1036 {
facdc750
RS
1037 unsigned char *p1, *p2;
1038 int s1, s2;
487282dc
KH
1039 struct re_pattern_buffer *bufp;
1040
0c8533c6
RS
1041 bufp = compile_pattern (string, &search_regs, trt, posix,
1042 !NILP (current_buffer->enable_multibyte_characters));
ca1d1d23 1043
ca1d1d23
JB
1044 immediate_quit = 1; /* Quit immediately if user types ^G,
1045 because letting this function finish
1046 can take too long. */
1047 QUIT; /* Do a pending quit right away,
1048 to avoid paradoxical behavior */
1049 /* Get pointers and sizes of the two strings
1050 that make up the visible portion of the buffer. */
1051
1052 p1 = BEGV_ADDR;
fa8ed3e0 1053 s1 = GPT_BYTE - BEGV_BYTE;
ca1d1d23 1054 p2 = GAP_END_ADDR;
fa8ed3e0 1055 s2 = ZV_BYTE - GPT_BYTE;
ca1d1d23
JB
1056 if (s1 < 0)
1057 {
1058 p2 = p1;
fa8ed3e0 1059 s2 = ZV_BYTE - BEGV_BYTE;
ca1d1d23
JB
1060 s1 = 0;
1061 }
1062 if (s2 < 0)
1063 {
fa8ed3e0 1064 s1 = ZV_BYTE - BEGV_BYTE;
ca1d1d23
JB
1065 s2 = 0;
1066 }
8bb43c28
RS
1067 re_match_object = Qnil;
1068
ca1d1d23
JB
1069 while (n < 0)
1070 {
42db823b 1071 int val;
487282dc 1072 val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
4996330b
KH
1073 pos_byte - BEGV_BYTE, lim_byte - pos_byte,
1074 &search_regs,
42db823b 1075 /* Don't allow match past current point */
4996330b 1076 pos_byte - BEGV_BYTE);
ca1d1d23 1077 if (val == -2)
b6d6a51c
KH
1078 {
1079 matcher_overflow ();
1080 }
ca1d1d23
JB
1081 if (val >= 0)
1082 {
26aff150 1083 pos_byte = search_regs.start[0] + BEGV_BYTE;
4746118a 1084 for (i = 0; i < search_regs.num_regs; i++)
ca1d1d23
JB
1085 if (search_regs.start[i] >= 0)
1086 {
fa8ed3e0
RS
1087 search_regs.start[i]
1088 = BYTE_TO_CHAR (search_regs.start[i] + BEGV_BYTE);
1089 search_regs.end[i]
1090 = BYTE_TO_CHAR (search_regs.end[i] + BEGV_BYTE);
ca1d1d23 1091 }
a3668d92 1092 XSETBUFFER (last_thing_searched, current_buffer);
ca1d1d23
JB
1093 /* Set pos to the new position. */
1094 pos = search_regs.start[0];
1095 }
1096 else
1097 {
1098 immediate_quit = 0;
1099 return (n);
1100 }
1101 n++;
1102 }
1103 while (n > 0)
1104 {
42db823b 1105 int val;
487282dc 1106 val = re_search_2 (bufp, (char *) p1, s1, (char *) p2, s2,
4996330b
KH
1107 pos_byte - BEGV_BYTE, lim_byte - pos_byte,
1108 &search_regs,
1109 lim_byte - BEGV_BYTE);
ca1d1d23 1110 if (val == -2)
b6d6a51c
KH
1111 {
1112 matcher_overflow ();
1113 }
ca1d1d23
JB
1114 if (val >= 0)
1115 {
26aff150 1116 pos_byte = search_regs.end[0] + BEGV_BYTE;
4746118a 1117 for (i = 0; i < search_regs.num_regs; i++)
ca1d1d23
JB
1118 if (search_regs.start[i] >= 0)
1119 {
fa8ed3e0
RS
1120 search_regs.start[i]
1121 = BYTE_TO_CHAR (search_regs.start[i] + BEGV_BYTE);
1122 search_regs.end[i]
1123 = BYTE_TO_CHAR (search_regs.end[i] + BEGV_BYTE);
ca1d1d23 1124 }
a3668d92 1125 XSETBUFFER (last_thing_searched, current_buffer);
ca1d1d23
JB
1126 pos = search_regs.end[0];
1127 }
1128 else
1129 {
1130 immediate_quit = 0;
1131 return (0 - n);
1132 }
1133 n--;
1134 }
1135 immediate_quit = 0;
1136 return (pos);
1137 }
1138 else /* non-RE case */
1139 {
facdc750
RS
1140 unsigned char *raw_pattern, *pat;
1141 int raw_pattern_size;
1142 int raw_pattern_size_byte;
1143 unsigned char *patbuf;
1144 int multibyte = !NILP (current_buffer->enable_multibyte_characters);
1145 unsigned char *base_pat = XSTRING (string)->data;
1146 int charset_base = -1;
040272ce 1147 int boyer_moore_ok = 1;
facdc750
RS
1148
1149 /* MULTIBYTE says whether the text to be searched is multibyte.
1150 We must convert PATTERN to match that, or we will not really
1151 find things right. */
1152
1153 if (multibyte == STRING_MULTIBYTE (string))
1154 {
7276d3d8 1155 raw_pattern = (unsigned char *) XSTRING (string)->data;
facdc750 1156 raw_pattern_size = XSTRING (string)->size;
fc932ac6 1157 raw_pattern_size_byte = STRING_BYTES (XSTRING (string));
facdc750
RS
1158 }
1159 else if (multibyte)
1160 {
1161 raw_pattern_size = XSTRING (string)->size;
1162 raw_pattern_size_byte
1163 = count_size_as_multibyte (XSTRING (string)->data,
1164 raw_pattern_size);
7276d3d8 1165 raw_pattern = (unsigned char *) alloca (raw_pattern_size_byte + 1);
facdc750
RS
1166 copy_text (XSTRING (string)->data, raw_pattern,
1167 XSTRING (string)->size, 0, 1);
1168 }
1169 else
1170 {
1171 /* Converting multibyte to single-byte.
1172
1173 ??? Perhaps this conversion should be done in a special way
1174 by subtracting nonascii-insert-offset from each non-ASCII char,
1175 so that only the multibyte chars which really correspond to
1176 the chosen single-byte character set can possibly match. */
1177 raw_pattern_size = XSTRING (string)->size;
1178 raw_pattern_size_byte = XSTRING (string)->size;
7276d3d8 1179 raw_pattern = (unsigned char *) alloca (raw_pattern_size + 1);
facdc750 1180 copy_text (XSTRING (string)->data, raw_pattern,
fc932ac6 1181 STRING_BYTES (XSTRING (string)), 1, 0);
facdc750
RS
1182 }
1183
1184 /* Copy and optionally translate the pattern. */
1185 len = raw_pattern_size;
1186 len_byte = raw_pattern_size_byte;
1187 patbuf = (unsigned char *) alloca (len_byte);
1188 pat = patbuf;
1189 base_pat = raw_pattern;
1190 if (multibyte)
1191 {
1192 while (--len >= 0)
1193 {
1194 unsigned char workbuf[4], *str;
aff2ce94 1195 int c, translated, inverse;
facdc750
RS
1196 int in_charlen, charlen;
1197
1198 /* If we got here and the RE flag is set, it's because we're
1199 dealing with a regexp known to be trivial, so the backslash
1200 just quotes the next character. */
1201 if (RE && *base_pat == '\\')
1202 {
1203 len--;
1204 len_byte--;
1205 base_pat++;
1206 }
1207
1208 c = STRING_CHAR_AND_LENGTH (base_pat, len_byte, in_charlen);
040272ce 1209
facdc750 1210 /* Translate the character, if requested. */
aff2ce94 1211 TRANSLATE (translated, trt, c);
facdc750
RS
1212 /* If translation changed the byte-length, go back
1213 to the original character. */
1214 charlen = CHAR_STRING (translated, workbuf, str);
1215 if (in_charlen != charlen)
1216 {
1217 translated = c;
1218 charlen = CHAR_STRING (c, workbuf, str);
1219 }
1220
5ffaf437
RS
1221 /* If we are searching for something strange,
1222 an invalid multibyte code, don't use boyer-moore. */
1223 if (! ASCII_BYTE_P (translated)
1224 && (charlen == 1 /* 8bit code */
1225 || charlen != in_charlen /* invalid multibyte code */
1226 ))
1227 boyer_moore_ok = 0;
1228
aff2ce94
RS
1229 TRANSLATE (inverse, inverse_trt, c);
1230
facdc750
RS
1231 /* Did this char actually get translated?
1232 Would any other char get translated into it? */
aff2ce94 1233 if (translated != c || inverse != c)
facdc750
RS
1234 {
1235 /* Keep track of which character set row
1236 contains the characters that need translation. */
5ffaf437 1237 int charset_base_code = c & ~CHAR_FIELD3_MASK;
facdc750
RS
1238 if (charset_base == -1)
1239 charset_base = charset_base_code;
1240 else if (charset_base != charset_base_code)
1241 /* If two different rows appear, needing translation,
1242 then we cannot use boyer_moore search. */
040272ce
KH
1243 boyer_moore_ok = 0;
1244 /* ??? Handa: this must do boyer_moore_ok = 0
facdc750 1245 if c is a composite character. */
aff2ce94 1246 }
facdc750
RS
1247
1248 /* Store this character into the translated pattern. */
1249 bcopy (str, pat, charlen);
1250 pat += charlen;
1251 base_pat += in_charlen;
1252 len_byte -= in_charlen;
1253 }
1254 }
1255 else
1256 {
040272ce
KH
1257 /* Unibyte buffer. */
1258 charset_base = 0;
facdc750
RS
1259 while (--len >= 0)
1260 {
040272ce 1261 int c, translated;
facdc750
RS
1262
1263 /* If we got here and the RE flag is set, it's because we're
1264 dealing with a regexp known to be trivial, so the backslash
1265 just quotes the next character. */
1266 if (RE && *base_pat == '\\')
1267 {
1268 len--;
1269 base_pat++;
1270 }
1271 c = *base_pat++;
aff2ce94 1272 TRANSLATE (translated, trt, c);
facdc750
RS
1273 *pat++ = translated;
1274 }
1275 }
1276
1277 len_byte = pat - patbuf;
1278 len = raw_pattern_size;
1279 pat = base_pat = patbuf;
1280
040272ce 1281 if (boyer_moore_ok)
facdc750 1282 return boyer_moore (n, pat, len, len_byte, trt, inverse_trt,
aff2ce94
RS
1283 pos, pos_byte, lim, lim_byte,
1284 charset_base);
facdc750
RS
1285 else
1286 return simple_search (n, pat, len, len_byte, trt,
1287 pos, pos_byte, lim, lim_byte);
1288 }
1289}
1290\f
1291/* Do a simple string search N times for the string PAT,
1292 whose length is LEN/LEN_BYTE,
1293 from buffer position POS/POS_BYTE until LIM/LIM_BYTE.
1294 TRT is the translation table.
f8bd51c4 1295
facdc750
RS
1296 Return the character position where the match is found.
1297 Otherwise, if M matches remained to be found, return -M.
f8bd51c4 1298
facdc750
RS
1299 This kind of search works regardless of what is in PAT and
1300 regardless of what is in TRT. It is used in cases where
1301 boyer_moore cannot work. */
1302
1303static int
1304simple_search (n, pat, len, len_byte, trt, pos, pos_byte, lim, lim_byte)
1305 int n;
1306 unsigned char *pat;
1307 int len, len_byte;
1308 Lisp_Object trt;
1309 int pos, pos_byte;
1310 int lim, lim_byte;
1311{
1312 int multibyte = ! NILP (current_buffer->enable_multibyte_characters);
ab228c24 1313 int forward = n > 0;
facdc750
RS
1314
1315 if (lim > pos && multibyte)
1316 while (n > 0)
1317 {
1318 while (1)
f8bd51c4 1319 {
facdc750
RS
1320 /* Try matching at position POS. */
1321 int this_pos = pos;
1322 int this_pos_byte = pos_byte;
1323 int this_len = len;
1324 int this_len_byte = len_byte;
1325 unsigned char *p = pat;
1326 if (pos + len > lim)
1327 goto stop;
1328
1329 while (this_len > 0)
1330 {
1331 int charlen, buf_charlen;
ab228c24 1332 int pat_ch, buf_ch;
facdc750 1333
ab228c24 1334 pat_ch = STRING_CHAR_AND_LENGTH (p, this_len_byte, charlen);
facdc750
RS
1335 buf_ch = STRING_CHAR_AND_LENGTH (BYTE_POS_ADDR (this_pos_byte),
1336 ZV_BYTE - this_pos_byte,
1337 buf_charlen);
aff2ce94 1338 TRANSLATE (buf_ch, trt, buf_ch);
facdc750
RS
1339
1340 if (buf_ch != pat_ch)
1341 break;
ab228c24
RS
1342
1343 this_len_byte -= charlen;
1344 this_len--;
1345 p += charlen;
1346
1347 this_pos_byte += buf_charlen;
1348 this_pos++;
facdc750
RS
1349 }
1350
1351 if (this_len == 0)
1352 {
1353 pos += len;
1354 pos_byte += len_byte;
1355 break;
1356 }
1357
1358 INC_BOTH (pos, pos_byte);
f8bd51c4 1359 }
facdc750
RS
1360
1361 n--;
1362 }
1363 else if (lim > pos)
1364 while (n > 0)
1365 {
1366 while (1)
f8bd51c4 1367 {
facdc750
RS
1368 /* Try matching at position POS. */
1369 int this_pos = pos;
1370 int this_len = len;
1371 unsigned char *p = pat;
1372
1373 if (pos + len > lim)
1374 goto stop;
1375
1376 while (this_len > 0)
1377 {
1378 int pat_ch = *p++;
1379 int buf_ch = FETCH_BYTE (this_pos);
aff2ce94 1380 TRANSLATE (buf_ch, trt, buf_ch);
facdc750
RS
1381
1382 if (buf_ch != pat_ch)
1383 break;
ab228c24
RS
1384
1385 this_len--;
1386 this_pos++;
facdc750
RS
1387 }
1388
1389 if (this_len == 0)
1390 {
1391 pos += len;
1392 break;
1393 }
1394
1395 pos++;
f8bd51c4 1396 }
facdc750
RS
1397
1398 n--;
1399 }
1400 /* Backwards search. */
1401 else if (lim < pos && multibyte)
1402 while (n < 0)
1403 {
1404 while (1)
f8bd51c4 1405 {
facdc750
RS
1406 /* Try matching at position POS. */
1407 int this_pos = pos - len;
1408 int this_pos_byte = pos_byte - len_byte;
1409 int this_len = len;
1410 int this_len_byte = len_byte;
1411 unsigned char *p = pat;
1412
1413 if (pos - len < lim)
1414 goto stop;
1415
1416 while (this_len > 0)
1417 {
1418 int charlen, buf_charlen;
ab228c24 1419 int pat_ch, buf_ch;
facdc750 1420
ab228c24 1421 pat_ch = STRING_CHAR_AND_LENGTH (p, this_len_byte, charlen);
facdc750
RS
1422 buf_ch = STRING_CHAR_AND_LENGTH (BYTE_POS_ADDR (this_pos_byte),
1423 ZV_BYTE - this_pos_byte,
1424 buf_charlen);
aff2ce94 1425 TRANSLATE (buf_ch, trt, buf_ch);
facdc750
RS
1426
1427 if (buf_ch != pat_ch)
1428 break;
ab228c24
RS
1429
1430 this_len_byte -= charlen;
1431 this_len--;
1432 p += charlen;
1433 this_pos_byte += buf_charlen;
1434 this_pos++;
facdc750
RS
1435 }
1436
1437 if (this_len == 0)
1438 {
1439 pos -= len;
1440 pos_byte -= len_byte;
1441 break;
1442 }
1443
1444 DEC_BOTH (pos, pos_byte);
f8bd51c4
KH
1445 }
1446
facdc750
RS
1447 n++;
1448 }
1449 else if (lim < pos)
1450 while (n < 0)
1451 {
1452 while (1)
b6d6a51c 1453 {
facdc750
RS
1454 /* Try matching at position POS. */
1455 int this_pos = pos - len;
1456 int this_len = len;
1457 unsigned char *p = pat;
1458
1459 if (pos - len < lim)
1460 goto stop;
1461
1462 while (this_len > 0)
1463 {
1464 int pat_ch = *p++;
1465 int buf_ch = FETCH_BYTE (this_pos);
aff2ce94 1466 TRANSLATE (buf_ch, trt, buf_ch);
facdc750
RS
1467
1468 if (buf_ch != pat_ch)
1469 break;
ab228c24
RS
1470 this_len--;
1471 this_pos++;
facdc750
RS
1472 }
1473
1474 if (this_len == 0)
b6d6a51c 1475 {
facdc750
RS
1476 pos -= len;
1477 break;
b6d6a51c 1478 }
facdc750
RS
1479
1480 pos--;
b6d6a51c 1481 }
facdc750
RS
1482
1483 n++;
b6d6a51c 1484 }
facdc750
RS
1485
1486 stop:
1487 if (n == 0)
aff2ce94 1488 {
ab228c24
RS
1489 if (forward)
1490 set_search_regs ((multibyte ? pos_byte : pos) - len_byte, len_byte);
1491 else
1492 set_search_regs (multibyte ? pos_byte : pos, len_byte);
aff2ce94
RS
1493
1494 return pos;
1495 }
facdc750
RS
1496 else if (n > 0)
1497 return -n;
1498 else
1499 return n;
1500}
1501\f
1502/* Do Boyer-Moore search N times for the string PAT,
1503 whose length is LEN/LEN_BYTE,
1504 from buffer position POS/POS_BYTE until LIM/LIM_BYTE.
1505 DIRECTION says which direction we search in.
1506 TRT and INVERSE_TRT are translation tables.
1507
1508 This kind of search works if all the characters in PAT that have
1509 nontrivial translation are the same aside from the last byte. This
1510 makes it possible to translate just the last byte of a character,
1511 and do so after just a simple test of the context.
1512
1513 If that criterion is not satisfied, do not call this function. */
1514
1515static int
1516boyer_moore (n, base_pat, len, len_byte, trt, inverse_trt,
aff2ce94 1517 pos, pos_byte, lim, lim_byte, charset_base)
facdc750
RS
1518 int n;
1519 unsigned char *base_pat;
1520 int len, len_byte;
1521 Lisp_Object trt;
1522 Lisp_Object inverse_trt;
1523 int pos, pos_byte;
1524 int lim, lim_byte;
aff2ce94 1525 int charset_base;
facdc750
RS
1526{
1527 int direction = ((n > 0) ? 1 : -1);
1528 register int dirlen;
1529 int infinity, limit, k, stride_for_teases;
1530 register int *BM_tab;
1531 int *BM_tab_base;
1532 register unsigned char *cursor, *p_limit;
1533 register int i, j;
cb6792d2 1534 unsigned char *pat, *pat_end;
facdc750
RS
1535 int multibyte = ! NILP (current_buffer->enable_multibyte_characters);
1536
1537 unsigned char simple_translate[0400];
1538 int translate_prev_byte;
1539 int translate_anteprev_byte;
1540
1541#ifdef C_ALLOCA
1542 int BM_tab_space[0400];
1543 BM_tab = &BM_tab_space[0];
1544#else
1545 BM_tab = (int *) alloca (0400 * sizeof (int));
1546#endif
1547 /* The general approach is that we are going to maintain that we know */
1548 /* the first (closest to the present position, in whatever direction */
1549 /* we're searching) character that could possibly be the last */
1550 /* (furthest from present position) character of a valid match. We */
1551 /* advance the state of our knowledge by looking at that character */
1552 /* and seeing whether it indeed matches the last character of the */
1553 /* pattern. If it does, we take a closer look. If it does not, we */
1554 /* move our pointer (to putative last characters) as far as is */
1555 /* logically possible. This amount of movement, which I call a */
1556 /* stride, will be the length of the pattern if the actual character */
1557 /* appears nowhere in the pattern, otherwise it will be the distance */
1558 /* from the last occurrence of that character to the end of the */
1559 /* pattern. */
1560 /* As a coding trick, an enormous stride is coded into the table for */
1561 /* characters that match the last character. This allows use of only */
1562 /* a single test, a test for having gone past the end of the */
1563 /* permissible match region, to test for both possible matches (when */
1564 /* the stride goes past the end immediately) and failure to */
1565 /* match (where you get nudged past the end one stride at a time). */
1566
1567 /* Here we make a "mickey mouse" BM table. The stride of the search */
1568 /* is determined only by the last character of the putative match. */
1569 /* If that character does not match, we will stride the proper */
1570 /* distance to propose a match that superimposes it on the last */
1571 /* instance of a character that matches it (per trt), or misses */
1572 /* it entirely if there is none. */
1573
1574 dirlen = len_byte * direction;
1575 infinity = dirlen - (lim_byte + pos_byte + len_byte + len_byte) * direction;
cb6792d2
RS
1576
1577 /* Record position after the end of the pattern. */
1578 pat_end = base_pat + len_byte;
1579 /* BASE_PAT points to a character that we start scanning from.
1580 It is the first character in a forward search,
1581 the last character in a backward search. */
facdc750 1582 if (direction < 0)
cb6792d2
RS
1583 base_pat = pat_end - 1;
1584
facdc750
RS
1585 BM_tab_base = BM_tab;
1586 BM_tab += 0400;
1587 j = dirlen; /* to get it in a register */
1588 /* A character that does not appear in the pattern induces a */
1589 /* stride equal to the pattern length. */
1590 while (BM_tab_base != BM_tab)
1591 {
1592 *--BM_tab = j;
1593 *--BM_tab = j;
1594 *--BM_tab = j;
1595 *--BM_tab = j;
1596 }
1597
1598 /* We use this for translation, instead of TRT itself.
1599 We fill this in to handle the characters that actually
1600 occur in the pattern. Others don't matter anyway! */
1601 bzero (simple_translate, sizeof simple_translate);
1602 for (i = 0; i < 0400; i++)
1603 simple_translate[i] = i;
1604
1605 i = 0;
1606 while (i != infinity)
1607 {
cb6792d2 1608 unsigned char *ptr = base_pat + i;
facdc750
RS
1609 i += direction;
1610 if (i == dirlen)
1611 i = infinity;
1612 if (! NILP (trt))
ca1d1d23 1613 {
facdc750 1614 int ch;
aff2ce94 1615 int untranslated;
facdc750
RS
1616 int this_translated = 1;
1617
1618 if (multibyte
cb6792d2
RS
1619 /* Is *PTR the last byte of a character? */
1620 && (pat_end - ptr == 1 || CHAR_HEAD_P (ptr[1])))
ca1d1d23 1621 {
facdc750
RS
1622 unsigned char *charstart = ptr;
1623 while (! CHAR_HEAD_P (*charstart))
1624 charstart--;
aff2ce94 1625 untranslated = STRING_CHAR (charstart, ptr - charstart + 1);
6397418a 1626 if (charset_base == (untranslated & ~CHAR_FIELD3_MASK))
facdc750 1627 {
ab228c24 1628 TRANSLATE (ch, trt, untranslated);
aff2ce94
RS
1629 if (! CHAR_HEAD_P (*ptr))
1630 {
1631 translate_prev_byte = ptr[-1];
1632 if (! CHAR_HEAD_P (translate_prev_byte))
1633 translate_anteprev_byte = ptr[-2];
1634 }
facdc750 1635 }
aff2ce94 1636 else
ab228c24
RS
1637 {
1638 this_translated = 0;
1639 ch = *ptr;
1640 }
ca1d1d23 1641 }
facdc750 1642 else if (!multibyte)
aff2ce94 1643 TRANSLATE (ch, trt, *ptr);
ca1d1d23
JB
1644 else
1645 {
facdc750
RS
1646 ch = *ptr;
1647 this_translated = 0;
ca1d1d23 1648 }
facdc750 1649
ab228c24
RS
1650 if (ch > 0400)
1651 j = ((unsigned char) ch) | 0200;
1652 else
1653 j = (unsigned char) ch;
1654
facdc750
RS
1655 if (i == infinity)
1656 stride_for_teases = BM_tab[j];
ab228c24 1657
facdc750
RS
1658 BM_tab[j] = dirlen - i;
1659 /* A translation table is accompanied by its inverse -- see */
1660 /* comment following downcase_table for details */
1661 if (this_translated)
ab228c24
RS
1662 {
1663 int starting_ch = ch;
1664 int starting_j = j;
1665 while (1)
1666 {
1667 TRANSLATE (ch, inverse_trt, ch);
1668 if (ch > 0400)
1669 j = ((unsigned char) ch) | 0200;
1670 else
1671 j = (unsigned char) ch;
1672
1673 /* For all the characters that map into CH,
1674 set up simple_translate to map the last byte
1675 into STARTING_J. */
1676 simple_translate[j] = starting_j;
1677 if (ch == starting_ch)
1678 break;
1679 BM_tab[j] = dirlen - i;
1680 }
1681 }
facdc750
RS
1682 }
1683 else
1684 {
1685 j = *ptr;
1686
1687 if (i == infinity)
1688 stride_for_teases = BM_tab[j];
1689 BM_tab[j] = dirlen - i;
ca1d1d23 1690 }
facdc750
RS
1691 /* stride_for_teases tells how much to stride if we get a */
1692 /* match on the far character but are subsequently */
1693 /* disappointed, by recording what the stride would have been */
1694 /* for that character if the last character had been */
1695 /* different. */
1696 }
1697 infinity = dirlen - infinity;
1698 pos_byte += dirlen - ((direction > 0) ? direction : 0);
1699 /* loop invariant - POS_BYTE points at where last char (first
1700 char if reverse) of pattern would align in a possible match. */
1701 while (n != 0)
1702 {
1703 int tail_end;
1704 unsigned char *tail_end_ptr;
1705
1706 /* It's been reported that some (broken) compiler thinks that
1707 Boolean expressions in an arithmetic context are unsigned.
1708 Using an explicit ?1:0 prevents this. */
1709 if ((lim_byte - pos_byte - ((direction > 0) ? 1 : 0)) * direction
1710 < 0)
1711 return (n * (0 - direction));
1712 /* First we do the part we can by pointers (maybe nothing) */
1713 QUIT;
1714 pat = base_pat;
1715 limit = pos_byte - dirlen + direction;
67ce527d
KH
1716 if (direction > 0)
1717 {
1718 limit = BUFFER_CEILING_OF (limit);
1719 /* LIMIT is now the last (not beyond-last!) value POS_BYTE
1720 can take on without hitting edge of buffer or the gap. */
1721 limit = min (limit, pos_byte + 20000);
1722 limit = min (limit, lim_byte - 1);
1723 }
1724 else
1725 {
1726 limit = BUFFER_FLOOR_OF (limit);
1727 /* LIMIT is now the last (not beyond-last!) value POS_BYTE
1728 can take on without hitting edge of buffer or the gap. */
1729 limit = max (limit, pos_byte - 20000);
1730 limit = max (limit, lim_byte);
1731 }
facdc750
RS
1732 tail_end = BUFFER_CEILING_OF (pos_byte) + 1;
1733 tail_end_ptr = BYTE_POS_ADDR (tail_end);
1734
1735 if ((limit - pos_byte) * direction > 20)
ca1d1d23 1736 {
facdc750
RS
1737 unsigned char *p2;
1738
1739 p_limit = BYTE_POS_ADDR (limit);
1740 p2 = (cursor = BYTE_POS_ADDR (pos_byte));
1741 /* In this loop, pos + cursor - p2 is the surrogate for pos */
1742 while (1) /* use one cursor setting as long as i can */
ca1d1d23 1743 {
facdc750 1744 if (direction > 0) /* worth duplicating */
ca1d1d23 1745 {
facdc750
RS
1746 /* Use signed comparison if appropriate
1747 to make cursor+infinity sure to be > p_limit.
1748 Assuming that the buffer lies in a range of addresses
1749 that are all "positive" (as ints) or all "negative",
1750 either kind of comparison will work as long
1751 as we don't step by infinity. So pick the kind
1752 that works when we do step by infinity. */
1753 if ((EMACS_INT) (p_limit + infinity) > (EMACS_INT) p_limit)
1754 while ((EMACS_INT) cursor <= (EMACS_INT) p_limit)
1755 cursor += BM_tab[*cursor];
ca1d1d23 1756 else
facdc750
RS
1757 while ((EMACS_UINT) cursor <= (EMACS_UINT) p_limit)
1758 cursor += BM_tab[*cursor];
1759 }
1760 else
1761 {
1762 if ((EMACS_INT) (p_limit + infinity) < (EMACS_INT) p_limit)
1763 while ((EMACS_INT) cursor >= (EMACS_INT) p_limit)
1764 cursor += BM_tab[*cursor];
1765 else
1766 while ((EMACS_UINT) cursor >= (EMACS_UINT) p_limit)
1767 cursor += BM_tab[*cursor];
1768 }
ca1d1d23 1769/* If you are here, cursor is beyond the end of the searched region. */
facdc750
RS
1770/* This can happen if you match on the far character of the pattern, */
1771/* because the "stride" of that character is infinity, a number able */
1772/* to throw you well beyond the end of the search. It can also */
1773/* happen if you fail to match within the permitted region and would */
1774/* otherwise try a character beyond that region */
1775 if ((cursor - p_limit) * direction <= len_byte)
1776 break; /* a small overrun is genuine */
1777 cursor -= infinity; /* large overrun = hit */
1778 i = dirlen - direction;
1779 if (! NILP (trt))
1780 {
1781 while ((i -= direction) + direction != 0)
ca1d1d23 1782 {
facdc750
RS
1783 int ch;
1784 cursor -= direction;
1785 /* Translate only the last byte of a character. */
1786 if (! multibyte
1787 || ((cursor == tail_end_ptr
1788 || CHAR_HEAD_P (cursor[1]))
1789 && (CHAR_HEAD_P (cursor[0])
1790 || (translate_prev_byte == cursor[-1]
1791 && (CHAR_HEAD_P (translate_prev_byte)
1792 || translate_anteprev_byte == cursor[-2])))))
1793 ch = simple_translate[*cursor];
1794 else
1795 ch = *cursor;
1796 if (pat[i] != ch)
1797 break;
ca1d1d23 1798 }
facdc750
RS
1799 }
1800 else
1801 {
1802 while ((i -= direction) + direction != 0)
ca1d1d23 1803 {
facdc750
RS
1804 cursor -= direction;
1805 if (pat[i] != *cursor)
1806 break;
ca1d1d23 1807 }
facdc750
RS
1808 }
1809 cursor += dirlen - i - direction; /* fix cursor */
1810 if (i + direction == 0)
1811 {
1812 int position;
0c8533c6 1813
facdc750 1814 cursor -= direction;
1113d9db 1815
facdc750
RS
1816 position = pos_byte + cursor - p2 + ((direction > 0)
1817 ? 1 - len_byte : 0);
1818 set_search_regs (position, len_byte);
ca325161 1819
facdc750
RS
1820 if ((n -= direction) != 0)
1821 cursor += dirlen; /* to resume search */
ca1d1d23 1822 else
facdc750
RS
1823 return ((direction > 0)
1824 ? search_regs.end[0] : search_regs.start[0]);
ca1d1d23 1825 }
facdc750
RS
1826 else
1827 cursor += stride_for_teases; /* <sigh> we lose - */
ca1d1d23 1828 }
facdc750
RS
1829 pos_byte += cursor - p2;
1830 }
1831 else
1832 /* Now we'll pick up a clump that has to be done the hard */
1833 /* way because it covers a discontinuity */
1834 {
1835 limit = ((direction > 0)
1836 ? BUFFER_CEILING_OF (pos_byte - dirlen + 1)
1837 : BUFFER_FLOOR_OF (pos_byte - dirlen - 1));
1838 limit = ((direction > 0)
1839 ? min (limit + len_byte, lim_byte - 1)
1840 : max (limit - len_byte, lim_byte));
1841 /* LIMIT is now the last value POS_BYTE can have
1842 and still be valid for a possible match. */
1843 while (1)
ca1d1d23 1844 {
facdc750
RS
1845 /* This loop can be coded for space rather than */
1846 /* speed because it will usually run only once. */
1847 /* (the reach is at most len + 21, and typically */
1848 /* does not exceed len) */
1849 while ((limit - pos_byte) * direction >= 0)
1850 pos_byte += BM_tab[FETCH_BYTE (pos_byte)];
1851 /* now run the same tests to distinguish going off the */
1852 /* end, a match or a phony match. */
1853 if ((pos_byte - limit) * direction <= len_byte)
1854 break; /* ran off the end */
1855 /* Found what might be a match.
1856 Set POS_BYTE back to last (first if reverse) pos. */
1857 pos_byte -= infinity;
1858 i = dirlen - direction;
1859 while ((i -= direction) + direction != 0)
ca1d1d23 1860 {
facdc750
RS
1861 int ch;
1862 unsigned char *ptr;
1863 pos_byte -= direction;
1864 ptr = BYTE_POS_ADDR (pos_byte);
1865 /* Translate only the last byte of a character. */
1866 if (! multibyte
1867 || ((ptr == tail_end_ptr
1868 || CHAR_HEAD_P (ptr[1]))
1869 && (CHAR_HEAD_P (ptr[0])
1870 || (translate_prev_byte == ptr[-1]
1871 && (CHAR_HEAD_P (translate_prev_byte)
1872 || translate_anteprev_byte == ptr[-2])))))
1873 ch = simple_translate[*ptr];
1874 else
1875 ch = *ptr;
1876 if (pat[i] != ch)
1877 break;
1878 }
1879 /* Above loop has moved POS_BYTE part or all the way
1880 back to the first pos (last pos if reverse).
1881 Set it once again at the last (first if reverse) char. */
1882 pos_byte += dirlen - i- direction;
1883 if (i + direction == 0)
1884 {
1885 int position;
1886 pos_byte -= direction;
1113d9db 1887
facdc750 1888 position = pos_byte + ((direction > 0) ? 1 - len_byte : 0);
0c8533c6 1889
facdc750 1890 set_search_regs (position, len_byte);
ca325161 1891
facdc750
RS
1892 if ((n -= direction) != 0)
1893 pos_byte += dirlen; /* to resume search */
ca1d1d23 1894 else
facdc750
RS
1895 return ((direction > 0)
1896 ? search_regs.end[0] : search_regs.start[0]);
ca1d1d23 1897 }
facdc750
RS
1898 else
1899 pos_byte += stride_for_teases;
1900 }
1901 }
1902 /* We have done one clump. Can we continue? */
1903 if ((lim_byte - pos_byte) * direction < 0)
1904 return ((0 - n) * direction);
ca1d1d23 1905 }
facdc750 1906 return BYTE_TO_CHAR (pos_byte);
ca1d1d23 1907}
ca325161 1908
fa8ed3e0 1909/* Record beginning BEG_BYTE and end BEG_BYTE + NBYTES
a7e4cdde
RS
1910 for the overall match just found in the current buffer.
1911 Also clear out the match data for registers 1 and up. */
ca325161
RS
1912
1913static void
fa8ed3e0
RS
1914set_search_regs (beg_byte, nbytes)
1915 int beg_byte, nbytes;
ca325161 1916{
a7e4cdde
RS
1917 int i;
1918
ca325161
RS
1919 /* Make sure we have registers in which to store
1920 the match position. */
1921 if (search_regs.num_regs == 0)
1922 {
2d4a771a
RS
1923 search_regs.start = (regoff_t *) xmalloc (2 * sizeof (regoff_t));
1924 search_regs.end = (regoff_t *) xmalloc (2 * sizeof (regoff_t));
487282dc 1925 search_regs.num_regs = 2;
ca325161
RS
1926 }
1927
a7e4cdde
RS
1928 /* Clear out the other registers. */
1929 for (i = 1; i < search_regs.num_regs; i++)
1930 {
1931 search_regs.start[i] = -1;
1932 search_regs.end[i] = -1;
1933 }
1934
fa8ed3e0
RS
1935 search_regs.start[0] = BYTE_TO_CHAR (beg_byte);
1936 search_regs.end[0] = BYTE_TO_CHAR (beg_byte + nbytes);
a3668d92 1937 XSETBUFFER (last_thing_searched, current_buffer);
ca325161 1938}
ca1d1d23
JB
1939\f
1940/* Given a string of words separated by word delimiters,
1941 compute a regexp that matches those exact words
1942 separated by arbitrary punctuation. */
1943
1944static Lisp_Object
1945wordify (string)
1946 Lisp_Object string;
1947{
1948 register unsigned char *p, *o;
0c8533c6 1949 register int i, i_byte, len, punct_count = 0, word_count = 0;
ca1d1d23 1950 Lisp_Object val;
0c8533c6
RS
1951 int prev_c = 0;
1952 int adjust;
ca1d1d23
JB
1953
1954 CHECK_STRING (string, 0);
1955 p = XSTRING (string)->data;
1956 len = XSTRING (string)->size;
1957
0c8533c6
RS
1958 for (i = 0, i_byte = 0; i < len; )
1959 {
1960 int c;
1961
1962 if (STRING_MULTIBYTE (string))
1963 FETCH_STRING_CHAR_ADVANCE (c, string, i, i_byte);
1964 else
1965 c = XSTRING (string)->data[i++];
1966
1967 if (SYNTAX (c) != Sword)
1968 {
1969 punct_count++;
1970 if (i > 0 && SYNTAX (prev_c) == Sword)
1971 word_count++;
1972 }
ca1d1d23 1973
0c8533c6
RS
1974 prev_c = c;
1975 }
1976
1977 if (SYNTAX (prev_c) == Sword)
1978 word_count++;
1979 if (!word_count)
1980 return build_string ("");
1981
1982 adjust = - punct_count + 5 * (word_count - 1) + 4;
8a2df937
RS
1983 if (STRING_MULTIBYTE (string))
1984 val = make_uninit_multibyte_string (len + adjust,
1985 STRING_BYTES (XSTRING (string))
1986 + adjust);
1987 else
1988 val = make_uninit_string (len + adjust);
ca1d1d23
JB
1989
1990 o = XSTRING (val)->data;
1991 *o++ = '\\';
1992 *o++ = 'b';
1e9582d4 1993 prev_c = 0;
ca1d1d23 1994
1e9582d4
RS
1995 for (i = 0, i_byte = 0; i < len; )
1996 {
1997 int c;
1998 int i_byte_orig = i_byte;
1999
2000 if (STRING_MULTIBYTE (string))
2001 FETCH_STRING_CHAR_ADVANCE (c, string, i, i_byte);
2002 else
8a2df937
RS
2003 {
2004 c = XSTRING (string)->data[i++];
2005 i_byte++;
2006 }
1e9582d4
RS
2007
2008 if (SYNTAX (c) == Sword)
2009 {
2010 bcopy (&XSTRING (string)->data[i_byte_orig], o,
2011 i_byte - i_byte_orig);
2012 o += i_byte - i_byte_orig;
2013 }
2014 else if (i > 0 && SYNTAX (prev_c) == Sword && --word_count)
2015 {
2016 *o++ = '\\';
2017 *o++ = 'W';
2018 *o++ = '\\';
2019 *o++ = 'W';
2020 *o++ = '*';
2021 }
2022
2023 prev_c = c;
2024 }
ca1d1d23
JB
2025
2026 *o++ = '\\';
2027 *o++ = 'b';
2028
2029 return val;
2030}
2031\f
2032DEFUN ("search-backward", Fsearch_backward, Ssearch_backward, 1, 4,
6af43974 2033 "MSearch backward: ",
ca1d1d23
JB
2034 "Search backward from point for STRING.\n\
2035Set point to the beginning of the occurrence found, and return point.\n\
2036An optional second argument bounds the search; it is a buffer position.\n\
2037The match found must not extend before that position.\n\
2038Optional third argument, if t, means if fail just return nil (no error).\n\
2039 If not nil and not t, position at limit of search and return nil.\n\
2040Optional fourth argument is repeat count--search for successive occurrences.\n\
2041See also the functions `match-beginning', `match-end' and `replace-match'.")
2042 (string, bound, noerror, count)
2043 Lisp_Object string, bound, noerror, count;
2044{
b819a390 2045 return search_command (string, bound, noerror, count, -1, 0, 0);
ca1d1d23
JB
2046}
2047
6af43974 2048DEFUN ("search-forward", Fsearch_forward, Ssearch_forward, 1, 4, "MSearch: ",
ca1d1d23
JB
2049 "Search forward from point for STRING.\n\
2050Set point to the end of the occurrence found, and return point.\n\
2051An optional second argument bounds the search; it is a buffer position.\n\
2052The match found must not extend after that position. nil is equivalent\n\
2053 to (point-max).\n\
2054Optional third argument, if t, means if fail just return nil (no error).\n\
2055 If not nil and not t, move to limit of search and return nil.\n\
2056Optional fourth argument is repeat count--search for successive occurrences.\n\
2057See also the functions `match-beginning', `match-end' and `replace-match'.")
2058 (string, bound, noerror, count)
2059 Lisp_Object string, bound, noerror, count;
2060{
b819a390 2061 return search_command (string, bound, noerror, count, 1, 0, 0);
ca1d1d23
JB
2062}
2063
2064DEFUN ("word-search-backward", Fword_search_backward, Sword_search_backward, 1, 4,
2065 "sWord search backward: ",
2066 "Search backward from point for STRING, ignoring differences in punctuation.\n\
2067Set point to the beginning of the occurrence found, and return point.\n\
2068An optional second argument bounds the search; it is a buffer position.\n\
2069The match found must not extend before that position.\n\
2070Optional third argument, if t, means if fail just return nil (no error).\n\
2071 If not nil and not t, move to limit of search and return nil.\n\
2072Optional fourth argument is repeat count--search for successive occurrences.")
2073 (string, bound, noerror, count)
2074 Lisp_Object string, bound, noerror, count;
2075{
b819a390 2076 return search_command (wordify (string), bound, noerror, count, -1, 1, 0);
ca1d1d23
JB
2077}
2078
2079DEFUN ("word-search-forward", Fword_search_forward, Sword_search_forward, 1, 4,
2080 "sWord search: ",
2081 "Search forward from point for STRING, ignoring differences in punctuation.\n\
2082Set point to the end of the occurrence found, and return point.\n\
2083An optional second argument bounds the search; it is a buffer position.\n\
2084The match found must not extend after that position.\n\
2085Optional third argument, if t, means if fail just return nil (no error).\n\
2086 If not nil and not t, move to limit of search and return nil.\n\
2087Optional fourth argument is repeat count--search for successive occurrences.")
2088 (string, bound, noerror, count)
2089 Lisp_Object string, bound, noerror, count;
2090{
b819a390 2091 return search_command (wordify (string), bound, noerror, count, 1, 1, 0);
ca1d1d23
JB
2092}
2093
2094DEFUN ("re-search-backward", Fre_search_backward, Sre_search_backward, 1, 4,
2095 "sRE search backward: ",
2096 "Search backward from point for match for regular expression REGEXP.\n\
2097Set point to the beginning of the match, and return point.\n\
2098The match found is the one starting last in the buffer\n\
19c0a730 2099and yet ending before the origin of the search.\n\
ca1d1d23
JB
2100An optional second argument bounds the search; it is a buffer position.\n\
2101The match found must start at or after that position.\n\
2102Optional third argument, if t, means if fail just return nil (no error).\n\
2103 If not nil and not t, move to limit of search and return nil.\n\
2104Optional fourth argument is repeat count--search for successive occurrences.\n\
2105See also the functions `match-beginning', `match-end' and `replace-match'.")
19c0a730
KH
2106 (regexp, bound, noerror, count)
2107 Lisp_Object regexp, bound, noerror, count;
ca1d1d23 2108{
b819a390 2109 return search_command (regexp, bound, noerror, count, -1, 1, 0);
ca1d1d23
JB
2110}
2111
2112DEFUN ("re-search-forward", Fre_search_forward, Sre_search_forward, 1, 4,
2113 "sRE search: ",
2114 "Search forward from point for regular expression REGEXP.\n\
2115Set point to the end of the occurrence found, and return point.\n\
2116An optional second argument bounds the search; it is a buffer position.\n\
2117The match found must not extend after that position.\n\
2118Optional third argument, if t, means if fail just return nil (no error).\n\
2119 If not nil and not t, move to limit of search and return nil.\n\
2120Optional fourth argument is repeat count--search for successive occurrences.\n\
2121See also the functions `match-beginning', `match-end' and `replace-match'.")
19c0a730
KH
2122 (regexp, bound, noerror, count)
2123 Lisp_Object regexp, bound, noerror, count;
ca1d1d23 2124{
b819a390
RS
2125 return search_command (regexp, bound, noerror, count, 1, 1, 0);
2126}
2127
2128DEFUN ("posix-search-backward", Fposix_search_backward, Sposix_search_backward, 1, 4,
2129 "sPosix search backward: ",
2130 "Search backward from point for match for regular expression REGEXP.\n\
2131Find the longest match in accord with Posix regular expression rules.\n\
2132Set point to the beginning of the match, and return point.\n\
2133The match found is the one starting last in the buffer\n\
2134and yet ending before the origin of the search.\n\
2135An optional second argument bounds the search; it is a buffer position.\n\
2136The match found must start at or after that position.\n\
2137Optional third argument, if t, means if fail just return nil (no error).\n\
2138 If not nil and not t, move to limit of search and return nil.\n\
2139Optional fourth argument is repeat count--search for successive occurrences.\n\
2140See also the functions `match-beginning', `match-end' and `replace-match'.")
2141 (regexp, bound, noerror, count)
2142 Lisp_Object regexp, bound, noerror, count;
2143{
2144 return search_command (regexp, bound, noerror, count, -1, 1, 1);
2145}
2146
2147DEFUN ("posix-search-forward", Fposix_search_forward, Sposix_search_forward, 1, 4,
2148 "sPosix search: ",
2149 "Search forward from point for regular expression REGEXP.\n\
2150Find the longest match in accord with Posix regular expression rules.\n\
2151Set point to the end of the occurrence found, and return point.\n\
2152An optional second argument bounds the search; it is a buffer position.\n\
2153The match found must not extend after that position.\n\
2154Optional third argument, if t, means if fail just return nil (no error).\n\
2155 If not nil and not t, move to limit of search and return nil.\n\
2156Optional fourth argument is repeat count--search for successive occurrences.\n\
2157See also the functions `match-beginning', `match-end' and `replace-match'.")
2158 (regexp, bound, noerror, count)
2159 Lisp_Object regexp, bound, noerror, count;
2160{
2161 return search_command (regexp, bound, noerror, count, 1, 1, 1);
ca1d1d23
JB
2162}
2163\f
d7a5ad5f 2164DEFUN ("replace-match", Freplace_match, Sreplace_match, 1, 5, 0,
ca1d1d23
JB
2165 "Replace text matched by last search with NEWTEXT.\n\
2166If second arg FIXEDCASE is non-nil, do not alter case of replacement text.\n\
5b9cf4b2
RS
2167Otherwise maybe capitalize the whole text, or maybe just word initials,\n\
2168based on the replaced text.\n\
2169If the replaced text has only capital letters\n\
2170and has at least one multiletter word, convert NEWTEXT to all caps.\n\
2171If the replaced text has at least one word starting with a capital letter,\n\
2172then capitalize each word in NEWTEXT.\n\n\
ca1d1d23
JB
2173If third arg LITERAL is non-nil, insert NEWTEXT literally.\n\
2174Otherwise treat `\\' as special:\n\
2175 `\\&' in NEWTEXT means substitute original matched text.\n\
2176 `\\N' means substitute what matched the Nth `\\(...\\)'.\n\
2177 If Nth parens didn't match, substitute nothing.\n\
2178 `\\\\' means insert one `\\'.\n\
1113d9db 2179FIXEDCASE and LITERAL are optional arguments.\n\
080c45fd
RS
2180Leaves point at end of replacement text.\n\
2181\n\
2182The optional fourth argument STRING can be a string to modify.\n\
2183In that case, this function creates and returns a new string\n\
d7a5ad5f
RS
2184which is made by replacing the part of STRING that was matched.\n\
2185\n\
2186The optional fifth argument SUBEXP specifies a subexpression of the match.\n\
2187It says to replace just that subexpression instead of the whole match.\n\
2188This is useful only after a regular expression search or match\n\
2189since only regular expressions have distinguished subexpressions.")
2190 (newtext, fixedcase, literal, string, subexp)
2191 Lisp_Object newtext, fixedcase, literal, string, subexp;
ca1d1d23
JB
2192{
2193 enum { nochange, all_caps, cap_initial } case_action;
ac3b28b1 2194 register int pos, pos_byte;
ca1d1d23 2195 int some_multiletter_word;
97832bd0 2196 int some_lowercase;
73dc8771 2197 int some_uppercase;
208767c3 2198 int some_nonuppercase_initial;
ca1d1d23
JB
2199 register int c, prevc;
2200 int inslen;
d7a5ad5f 2201 int sub;
3e18eecf 2202 int opoint, newpoint;
ca1d1d23 2203
16fdc568 2204 CHECK_STRING (newtext, 0);
ca1d1d23 2205
080c45fd
RS
2206 if (! NILP (string))
2207 CHECK_STRING (string, 4);
2208
ca1d1d23
JB
2209 case_action = nochange; /* We tried an initialization */
2210 /* but some C compilers blew it */
4746118a
JB
2211
2212 if (search_regs.num_regs <= 0)
2213 error ("replace-match called before any match found");
2214
d7a5ad5f
RS
2215 if (NILP (subexp))
2216 sub = 0;
2217 else
2218 {
2219 CHECK_NUMBER (subexp, 3);
2220 sub = XINT (subexp);
2221 if (sub < 0 || sub >= search_regs.num_regs)
2222 args_out_of_range (subexp, make_number (search_regs.num_regs));
2223 }
2224
080c45fd
RS
2225 if (NILP (string))
2226 {
d7a5ad5f
RS
2227 if (search_regs.start[sub] < BEGV
2228 || search_regs.start[sub] > search_regs.end[sub]
2229 || search_regs.end[sub] > ZV)
2230 args_out_of_range (make_number (search_regs.start[sub]),
2231 make_number (search_regs.end[sub]));
080c45fd
RS
2232 }
2233 else
2234 {
d7a5ad5f
RS
2235 if (search_regs.start[sub] < 0
2236 || search_regs.start[sub] > search_regs.end[sub]
2237 || search_regs.end[sub] > XSTRING (string)->size)
2238 args_out_of_range (make_number (search_regs.start[sub]),
2239 make_number (search_regs.end[sub]));
080c45fd 2240 }
ca1d1d23
JB
2241
2242 if (NILP (fixedcase))
2243 {
2244 /* Decide how to casify by examining the matched text. */
ac3b28b1 2245 int last;
ca1d1d23 2246
ac3b28b1
KH
2247 pos = search_regs.start[sub];
2248 last = search_regs.end[sub];
fa8ed3e0
RS
2249
2250 if (NILP (string))
ac3b28b1 2251 pos_byte = CHAR_TO_BYTE (pos);
fa8ed3e0 2252 else
ac3b28b1 2253 pos_byte = string_char_to_byte (string, pos);
fa8ed3e0 2254
ca1d1d23
JB
2255 prevc = '\n';
2256 case_action = all_caps;
2257
2258 /* some_multiletter_word is set nonzero if any original word
2259 is more than one letter long. */
2260 some_multiletter_word = 0;
97832bd0 2261 some_lowercase = 0;
208767c3 2262 some_nonuppercase_initial = 0;
73dc8771 2263 some_uppercase = 0;
ca1d1d23 2264
ac3b28b1 2265 while (pos < last)
ca1d1d23 2266 {
080c45fd 2267 if (NILP (string))
ac3b28b1
KH
2268 {
2269 c = FETCH_CHAR (pos_byte);
2270 INC_BOTH (pos, pos_byte);
2271 }
080c45fd 2272 else
ac3b28b1 2273 FETCH_STRING_CHAR_ADVANCE (c, string, pos, pos_byte);
080c45fd 2274
ca1d1d23
JB
2275 if (LOWERCASEP (c))
2276 {
2277 /* Cannot be all caps if any original char is lower case */
2278
97832bd0 2279 some_lowercase = 1;
ca1d1d23 2280 if (SYNTAX (prevc) != Sword)
208767c3 2281 some_nonuppercase_initial = 1;
ca1d1d23
JB
2282 else
2283 some_multiletter_word = 1;
2284 }
2285 else if (!NOCASEP (c))
2286 {
73dc8771 2287 some_uppercase = 1;
97832bd0 2288 if (SYNTAX (prevc) != Sword)
c4d460ce 2289 ;
97832bd0 2290 else
ca1d1d23
JB
2291 some_multiletter_word = 1;
2292 }
208767c3
RS
2293 else
2294 {
2295 /* If the initial is a caseless word constituent,
2296 treat that like a lowercase initial. */
2297 if (SYNTAX (prevc) != Sword)
2298 some_nonuppercase_initial = 1;
2299 }
ca1d1d23
JB
2300
2301 prevc = c;
2302 }
2303
97832bd0
RS
2304 /* Convert to all caps if the old text is all caps
2305 and has at least one multiletter word. */
2306 if (! some_lowercase && some_multiletter_word)
2307 case_action = all_caps;
c4d460ce 2308 /* Capitalize each word, if the old text has all capitalized words. */
208767c3 2309 else if (!some_nonuppercase_initial && some_multiletter_word)
ca1d1d23 2310 case_action = cap_initial;
208767c3 2311 else if (!some_nonuppercase_initial && some_uppercase)
73dc8771
KH
2312 /* Should x -> yz, operating on X, give Yz or YZ?
2313 We'll assume the latter. */
2314 case_action = all_caps;
97832bd0
RS
2315 else
2316 case_action = nochange;
ca1d1d23
JB
2317 }
2318
080c45fd
RS
2319 /* Do replacement in a string. */
2320 if (!NILP (string))
2321 {
2322 Lisp_Object before, after;
2323
2324 before = Fsubstring (string, make_number (0),
d7a5ad5f
RS
2325 make_number (search_regs.start[sub]));
2326 after = Fsubstring (string, make_number (search_regs.end[sub]), Qnil);
080c45fd 2327
636a5e28
RS
2328 /* Substitute parts of the match into NEWTEXT
2329 if desired. */
080c45fd
RS
2330 if (NILP (literal))
2331 {
d131e79c
RS
2332 int lastpos = 0;
2333 int lastpos_byte = 0;
080c45fd
RS
2334 /* We build up the substituted string in ACCUM. */
2335 Lisp_Object accum;
2336 Lisp_Object middle;
ac3b28b1 2337 int length = STRING_BYTES (XSTRING (newtext));
080c45fd
RS
2338
2339 accum = Qnil;
2340
ac3b28b1 2341 for (pos_byte = 0, pos = 0; pos_byte < length;)
080c45fd
RS
2342 {
2343 int substart = -1;
2344 int subend;
1e79ec24 2345 int delbackslash = 0;
080c45fd 2346
0c8533c6
RS
2347 FETCH_STRING_CHAR_ADVANCE (c, newtext, pos, pos_byte);
2348
080c45fd
RS
2349 if (c == '\\')
2350 {
0c8533c6 2351 FETCH_STRING_CHAR_ADVANCE (c, newtext, pos, pos_byte);
080c45fd
RS
2352 if (c == '&')
2353 {
d7a5ad5f
RS
2354 substart = search_regs.start[sub];
2355 subend = search_regs.end[sub];
080c45fd
RS
2356 }
2357 else if (c >= '1' && c <= '9' && c <= search_regs.num_regs + '0')
2358 {
ad10348f 2359 if (search_regs.start[c - '0'] >= 0)
080c45fd
RS
2360 {
2361 substart = search_regs.start[c - '0'];
2362 subend = search_regs.end[c - '0'];
2363 }
2364 }
1e79ec24
KH
2365 else if (c == '\\')
2366 delbackslash = 1;
636a5e28
RS
2367 else
2368 error ("Invalid use of `\\' in replacement text");
080c45fd
RS
2369 }
2370 if (substart >= 0)
2371 {
d131e79c
RS
2372 if (pos - 2 != lastpos)
2373 middle = substring_both (newtext, lastpos,
2374 lastpos_byte,
2375 pos - 2, pos_byte - 2);
080c45fd
RS
2376 else
2377 middle = Qnil;
2378 accum = concat3 (accum, middle,
0c8533c6
RS
2379 Fsubstring (string,
2380 make_number (substart),
080c45fd
RS
2381 make_number (subend)));
2382 lastpos = pos;
0c8533c6 2383 lastpos_byte = pos_byte;
080c45fd 2384 }
1e79ec24
KH
2385 else if (delbackslash)
2386 {
d131e79c
RS
2387 middle = substring_both (newtext, lastpos,
2388 lastpos_byte,
2389 pos - 1, pos_byte - 1);
0c8533c6 2390
1e79ec24
KH
2391 accum = concat2 (accum, middle);
2392 lastpos = pos;
0c8533c6 2393 lastpos_byte = pos_byte;
1e79ec24 2394 }
080c45fd
RS
2395 }
2396
d131e79c
RS
2397 if (pos != lastpos)
2398 middle = substring_both (newtext, lastpos,
2399 lastpos_byte,
0c8533c6 2400 pos, pos_byte);
080c45fd
RS
2401 else
2402 middle = Qnil;
2403
2404 newtext = concat2 (accum, middle);
2405 }
2406
636a5e28 2407 /* Do case substitution in NEWTEXT if desired. */
080c45fd
RS
2408 if (case_action == all_caps)
2409 newtext = Fupcase (newtext);
2410 else if (case_action == cap_initial)
2b2eead9 2411 newtext = Fupcase_initials (newtext);
080c45fd
RS
2412
2413 return concat3 (before, newtext, after);
2414 }
2415
b0eba991 2416 /* Record point, the move (quietly) to the start of the match. */
9160906f 2417 if (PT >= search_regs.end[sub])
b0eba991 2418 opoint = PT - ZV;
9160906f
RS
2419 else if (PT > search_regs.start[sub])
2420 opoint = search_regs.end[sub] - ZV;
b0eba991
RS
2421 else
2422 opoint = PT;
2423
fa8ed3e0 2424 TEMP_SET_PT (search_regs.start[sub]);
b0eba991 2425
9a76659d
JB
2426 /* We insert the replacement text before the old text, and then
2427 delete the original text. This means that markers at the
2428 beginning or end of the original will float to the corresponding
2429 position in the replacement. */
ca1d1d23 2430 if (!NILP (literal))
16fdc568 2431 Finsert_and_inherit (1, &newtext);
ca1d1d23
JB
2432 else
2433 {
2434 struct gcpro gcpro1;
ac3b28b1
KH
2435 int length = STRING_BYTES (XSTRING (newtext));
2436
16fdc568 2437 GCPRO1 (newtext);
ca1d1d23 2438
ac3b28b1 2439 for (pos_byte = 0, pos = 0; pos_byte < length;)
ca1d1d23 2440 {
6ec8bbd2 2441 int offset = PT - search_regs.start[sub];
9a76659d 2442
ac3b28b1
KH
2443 FETCH_STRING_CHAR_ADVANCE (c, newtext, pos, pos_byte);
2444
ca1d1d23
JB
2445 if (c == '\\')
2446 {
ac3b28b1 2447 FETCH_STRING_CHAR_ADVANCE (c, newtext, pos, pos_byte);
ca1d1d23 2448 if (c == '&')
9a76659d
JB
2449 Finsert_buffer_substring
2450 (Fcurrent_buffer (),
d7a5ad5f
RS
2451 make_number (search_regs.start[sub] + offset),
2452 make_number (search_regs.end[sub] + offset));
78445046 2453 else if (c >= '1' && c <= '9' && c <= search_regs.num_regs + '0')
ca1d1d23
JB
2454 {
2455 if (search_regs.start[c - '0'] >= 1)
9a76659d
JB
2456 Finsert_buffer_substring
2457 (Fcurrent_buffer (),
2458 make_number (search_regs.start[c - '0'] + offset),
2459 make_number (search_regs.end[c - '0'] + offset));
ca1d1d23 2460 }
636a5e28 2461 else if (c == '\\')
ca1d1d23 2462 insert_char (c);
636a5e28
RS
2463 else
2464 error ("Invalid use of `\\' in replacement text");
ca1d1d23
JB
2465 }
2466 else
2467 insert_char (c);
2468 }
2469 UNGCPRO;
2470 }
2471
6ec8bbd2 2472 inslen = PT - (search_regs.start[sub]);
d7a5ad5f 2473 del_range (search_regs.start[sub] + inslen, search_regs.end[sub] + inslen);
ca1d1d23
JB
2474
2475 if (case_action == all_caps)
6ec8bbd2 2476 Fupcase_region (make_number (PT - inslen), make_number (PT));
ca1d1d23 2477 else if (case_action == cap_initial)
6ec8bbd2 2478 Fupcase_initials_region (make_number (PT - inslen), make_number (PT));
b0eba991 2479
3e18eecf
RS
2480 newpoint = PT;
2481
b0eba991 2482 /* Put point back where it was in the text. */
8d808a65 2483 if (opoint <= 0)
fa8ed3e0 2484 TEMP_SET_PT (opoint + ZV);
b0eba991 2485 else
fa8ed3e0 2486 TEMP_SET_PT (opoint);
b0eba991
RS
2487
2488 /* Now move point "officially" to the start of the inserted replacement. */
3e18eecf 2489 move_if_not_intangible (newpoint);
b0eba991 2490
ca1d1d23
JB
2491 return Qnil;
2492}
2493\f
2494static Lisp_Object
2495match_limit (num, beginningp)
2496 Lisp_Object num;
2497 int beginningp;
2498{
2499 register int n;
2500
2501 CHECK_NUMBER (num, 0);
2502 n = XINT (num);
4746118a
JB
2503 if (n < 0 || n >= search_regs.num_regs)
2504 args_out_of_range (num, make_number (search_regs.num_regs));
2505 if (search_regs.num_regs <= 0
2506 || search_regs.start[n] < 0)
ca1d1d23
JB
2507 return Qnil;
2508 return (make_number ((beginningp) ? search_regs.start[n]
2509 : search_regs.end[n]));
2510}
2511
2512DEFUN ("match-beginning", Fmatch_beginning, Smatch_beginning, 1, 1, 0,
2513 "Return position of start of text matched by last search.\n\
5806161b
EN
2514SUBEXP, a number, specifies which parenthesized expression in the last\n\
2515 regexp.\n\
2516Value is nil if SUBEXPth pair didn't match, or there were less than\n\
2517 SUBEXP pairs.\n\
ca1d1d23 2518Zero means the entire text matched by the whole regexp or whole string.")
5806161b
EN
2519 (subexp)
2520 Lisp_Object subexp;
ca1d1d23 2521{
5806161b 2522 return match_limit (subexp, 1);
ca1d1d23
JB
2523}
2524
2525DEFUN ("match-end", Fmatch_end, Smatch_end, 1, 1, 0,
2526 "Return position of end of text matched by last search.\n\
5806161b
EN
2527SUBEXP, a number, specifies which parenthesized expression in the last\n\
2528 regexp.\n\
2529Value is nil if SUBEXPth pair didn't match, or there were less than\n\
2530 SUBEXP pairs.\n\
ca1d1d23 2531Zero means the entire text matched by the whole regexp or whole string.")
5806161b
EN
2532 (subexp)
2533 Lisp_Object subexp;
ca1d1d23 2534{
5806161b 2535 return match_limit (subexp, 0);
ca1d1d23
JB
2536}
2537
56256c2a 2538DEFUN ("match-data", Fmatch_data, Smatch_data, 0, 2, 0,
ca1d1d23
JB
2539 "Return a list containing all info on what the last search matched.\n\
2540Element 2N is `(match-beginning N)'; element 2N + 1 is `(match-end N)'.\n\
2541All the elements are markers or nil (nil if the Nth pair didn't match)\n\
2542if the last match was on a buffer; integers or nil if a string was matched.\n\
56256c2a
RS
2543Use `store-match-data' to reinstate the data in this list.\n\
2544\n\
2545If INTEGERS (the optional first argument) is non-nil, always use integers\n\
8ca821e9 2546\(rather than markers) to represent buffer positions.\n\
56256c2a
RS
2547If REUSE is a list, reuse it as part of the value. If REUSE is long enough\n\
2548to hold all the values, and if INTEGERS is non-nil, no consing is done.")
2549 (integers, reuse)
2550 Lisp_Object integers, reuse;
ca1d1d23 2551{
56256c2a 2552 Lisp_Object tail, prev;
4746118a 2553 Lisp_Object *data;
ca1d1d23
JB
2554 int i, len;
2555
daa37602 2556 if (NILP (last_thing_searched))
c36bcf1b 2557 return Qnil;
daa37602 2558
4746118a
JB
2559 data = (Lisp_Object *) alloca ((2 * search_regs.num_regs)
2560 * sizeof (Lisp_Object));
2561
ca1d1d23 2562 len = -1;
4746118a 2563 for (i = 0; i < search_regs.num_regs; i++)
ca1d1d23
JB
2564 {
2565 int start = search_regs.start[i];
2566 if (start >= 0)
2567 {
56256c2a
RS
2568 if (EQ (last_thing_searched, Qt)
2569 || ! NILP (integers))
ca1d1d23 2570 {
c235cce7
KH
2571 XSETFASTINT (data[2 * i], start);
2572 XSETFASTINT (data[2 * i + 1], search_regs.end[i]);
ca1d1d23 2573 }
0ed62dc7 2574 else if (BUFFERP (last_thing_searched))
ca1d1d23
JB
2575 {
2576 data[2 * i] = Fmake_marker ();
daa37602
JB
2577 Fset_marker (data[2 * i],
2578 make_number (start),
2579 last_thing_searched);
ca1d1d23
JB
2580 data[2 * i + 1] = Fmake_marker ();
2581 Fset_marker (data[2 * i + 1],
daa37602
JB
2582 make_number (search_regs.end[i]),
2583 last_thing_searched);
ca1d1d23 2584 }
daa37602
JB
2585 else
2586 /* last_thing_searched must always be Qt, a buffer, or Qnil. */
2587 abort ();
2588
ca1d1d23
JB
2589 len = i;
2590 }
2591 else
2592 data[2 * i] = data [2 * i + 1] = Qnil;
2593 }
56256c2a
RS
2594
2595 /* If REUSE is not usable, cons up the values and return them. */
2596 if (! CONSP (reuse))
2597 return Flist (2 * len + 2, data);
2598
2599 /* If REUSE is a list, store as many value elements as will fit
2600 into the elements of REUSE. */
2601 for (i = 0, tail = reuse; CONSP (tail);
2602 i++, tail = XCONS (tail)->cdr)
2603 {
2604 if (i < 2 * len + 2)
2605 XCONS (tail)->car = data[i];
2606 else
2607 XCONS (tail)->car = Qnil;
2608 prev = tail;
2609 }
2610
2611 /* If we couldn't fit all value elements into REUSE,
2612 cons up the rest of them and add them to the end of REUSE. */
2613 if (i < 2 * len + 2)
2614 XCONS (prev)->cdr = Flist (2 * len + 2 - i, data + i);
2615
2616 return reuse;
ca1d1d23
JB
2617}
2618
2619
3f1c005b 2620DEFUN ("set-match-data", Fset_match_data, Sset_match_data, 1, 1, 0,
ca1d1d23
JB
2621 "Set internal data on last search match from elements of LIST.\n\
2622LIST should have been created by calling `match-data' previously.")
2623 (list)
2624 register Lisp_Object list;
2625{
2626 register int i;
2627 register Lisp_Object marker;
2628
7074fde6
FP
2629 if (running_asynch_code)
2630 save_search_regs ();
2631
ca1d1d23 2632 if (!CONSP (list) && !NILP (list))
b37902c8 2633 list = wrong_type_argument (Qconsp, list);
ca1d1d23 2634
daa37602
JB
2635 /* Unless we find a marker with a buffer in LIST, assume that this
2636 match data came from a string. */
2637 last_thing_searched = Qt;
2638
4746118a
JB
2639 /* Allocate registers if they don't already exist. */
2640 {
d084e942 2641 int length = XFASTINT (Flength (list)) / 2;
4746118a
JB
2642
2643 if (length > search_regs.num_regs)
2644 {
1113d9db
JB
2645 if (search_regs.num_regs == 0)
2646 {
2647 search_regs.start
2648 = (regoff_t *) xmalloc (length * sizeof (regoff_t));
2649 search_regs.end
2650 = (regoff_t *) xmalloc (length * sizeof (regoff_t));
2651 }
4746118a 2652 else
1113d9db
JB
2653 {
2654 search_regs.start
2655 = (regoff_t *) xrealloc (search_regs.start,
2656 length * sizeof (regoff_t));
2657 search_regs.end
2658 = (regoff_t *) xrealloc (search_regs.end,
2659 length * sizeof (regoff_t));
2660 }
4746118a 2661
487282dc 2662 search_regs.num_regs = length;
4746118a
JB
2663 }
2664 }
2665
2666 for (i = 0; i < search_regs.num_regs; i++)
ca1d1d23
JB
2667 {
2668 marker = Fcar (list);
2669 if (NILP (marker))
2670 {
2671 search_regs.start[i] = -1;
2672 list = Fcdr (list);
2673 }
2674 else
2675 {
0ed62dc7 2676 if (MARKERP (marker))
daa37602
JB
2677 {
2678 if (XMARKER (marker)->buffer == 0)
c235cce7 2679 XSETFASTINT (marker, 0);
daa37602 2680 else
a3668d92 2681 XSETBUFFER (last_thing_searched, XMARKER (marker)->buffer);
daa37602 2682 }
ca1d1d23
JB
2683
2684 CHECK_NUMBER_COERCE_MARKER (marker, 0);
2685 search_regs.start[i] = XINT (marker);
2686 list = Fcdr (list);
2687
2688 marker = Fcar (list);
0ed62dc7 2689 if (MARKERP (marker) && XMARKER (marker)->buffer == 0)
c235cce7 2690 XSETFASTINT (marker, 0);
ca1d1d23
JB
2691
2692 CHECK_NUMBER_COERCE_MARKER (marker, 0);
2693 search_regs.end[i] = XINT (marker);
2694 }
2695 list = Fcdr (list);
2696 }
2697
2698 return Qnil;
2699}
2700
7074fde6
FP
2701/* If non-zero the match data have been saved in saved_search_regs
2702 during the execution of a sentinel or filter. */
75ebf74b 2703static int search_regs_saved;
7074fde6
FP
2704static struct re_registers saved_search_regs;
2705
2706/* Called from Flooking_at, Fstring_match, search_buffer, Fstore_match_data
2707 if asynchronous code (filter or sentinel) is running. */
2708static void
2709save_search_regs ()
2710{
2711 if (!search_regs_saved)
2712 {
2713 saved_search_regs.num_regs = search_regs.num_regs;
2714 saved_search_regs.start = search_regs.start;
2715 saved_search_regs.end = search_regs.end;
2716 search_regs.num_regs = 0;
2d4a771a
RS
2717 search_regs.start = 0;
2718 search_regs.end = 0;
7074fde6
FP
2719
2720 search_regs_saved = 1;
2721 }
2722}
2723
2724/* Called upon exit from filters and sentinels. */
2725void
2726restore_match_data ()
2727{
2728 if (search_regs_saved)
2729 {
2730 if (search_regs.num_regs > 0)
2731 {
2732 xfree (search_regs.start);
2733 xfree (search_regs.end);
2734 }
2735 search_regs.num_regs = saved_search_regs.num_regs;
2736 search_regs.start = saved_search_regs.start;
2737 search_regs.end = saved_search_regs.end;
2738
2739 search_regs_saved = 0;
2740 }
2741}
2742
ca1d1d23
JB
2743/* Quote a string to inactivate reg-expr chars */
2744
2745DEFUN ("regexp-quote", Fregexp_quote, Sregexp_quote, 1, 1, 0,
2746 "Return a regexp string which matches exactly STRING and nothing else.")
5806161b
EN
2747 (string)
2748 Lisp_Object string;
ca1d1d23
JB
2749{
2750 register unsigned char *in, *out, *end;
2751 register unsigned char *temp;
0c8533c6 2752 int backslashes_added = 0;
ca1d1d23 2753
5806161b 2754 CHECK_STRING (string, 0);
ca1d1d23 2755
fc932ac6 2756 temp = (unsigned char *) alloca (STRING_BYTES (XSTRING (string)) * 2);
ca1d1d23
JB
2757
2758 /* Now copy the data into the new string, inserting escapes. */
2759
5806161b 2760 in = XSTRING (string)->data;
fc932ac6 2761 end = in + STRING_BYTES (XSTRING (string));
ca1d1d23
JB
2762 out = temp;
2763
2764 for (; in != end; in++)
2765 {
2766 if (*in == '[' || *in == ']'
2767 || *in == '*' || *in == '.' || *in == '\\'
2768 || *in == '?' || *in == '+'
2769 || *in == '^' || *in == '$')
0c8533c6 2770 *out++ = '\\', backslashes_added++;
ca1d1d23
JB
2771 *out++ = *in;
2772 }
2773
3f8100f1 2774 return make_specified_string (temp,
0c8533c6 2775 XSTRING (string)->size + backslashes_added,
3f8100f1
RS
2776 out - temp,
2777 STRING_MULTIBYTE (string));
ca1d1d23
JB
2778}
2779\f
dfcf069d 2780void
ca1d1d23
JB
2781syms_of_search ()
2782{
2783 register int i;
2784
487282dc
KH
2785 for (i = 0; i < REGEXP_CACHE_SIZE; ++i)
2786 {
2787 searchbufs[i].buf.allocated = 100;
2788 searchbufs[i].buf.buffer = (unsigned char *) malloc (100);
2789 searchbufs[i].buf.fastmap = searchbufs[i].fastmap;
2790 searchbufs[i].regexp = Qnil;
2791 staticpro (&searchbufs[i].regexp);
2792 searchbufs[i].next = (i == REGEXP_CACHE_SIZE-1 ? 0 : &searchbufs[i+1]);
2793 }
2794 searchbuf_head = &searchbufs[0];
ca1d1d23
JB
2795
2796 Qsearch_failed = intern ("search-failed");
2797 staticpro (&Qsearch_failed);
2798 Qinvalid_regexp = intern ("invalid-regexp");
2799 staticpro (&Qinvalid_regexp);
2800
2801 Fput (Qsearch_failed, Qerror_conditions,
2802 Fcons (Qsearch_failed, Fcons (Qerror, Qnil)));
2803 Fput (Qsearch_failed, Qerror_message,
2804 build_string ("Search failed"));
2805
2806 Fput (Qinvalid_regexp, Qerror_conditions,
2807 Fcons (Qinvalid_regexp, Fcons (Qerror, Qnil)));
2808 Fput (Qinvalid_regexp, Qerror_message,
2809 build_string ("Invalid regexp"));
2810
daa37602
JB
2811 last_thing_searched = Qnil;
2812 staticpro (&last_thing_searched);
2813
ca1d1d23 2814 defsubr (&Slooking_at);
b819a390
RS
2815 defsubr (&Sposix_looking_at);
2816 defsubr (&Sstring_match);
2817 defsubr (&Sposix_string_match);
ca1d1d23
JB
2818 defsubr (&Ssearch_forward);
2819 defsubr (&Ssearch_backward);
2820 defsubr (&Sword_search_forward);
2821 defsubr (&Sword_search_backward);
2822 defsubr (&Sre_search_forward);
2823 defsubr (&Sre_search_backward);
b819a390
RS
2824 defsubr (&Sposix_search_forward);
2825 defsubr (&Sposix_search_backward);
ca1d1d23
JB
2826 defsubr (&Sreplace_match);
2827 defsubr (&Smatch_beginning);
2828 defsubr (&Smatch_end);
2829 defsubr (&Smatch_data);
3f1c005b 2830 defsubr (&Sset_match_data);
ca1d1d23
JB
2831 defsubr (&Sregexp_quote);
2832}