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