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