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