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