search.c 102 KB
Newer Older
Jim Blandy's avatar
Jim Blandy committed
1
/* String search routines for GNU Emacs.
2

Paul Eggert's avatar
Paul Eggert committed
3
Copyright (C) 1985-1987, 1993-1994, 1997-1999, 2001-2019 Free Software
4
Foundation, Inc.
Jim Blandy's avatar
Jim Blandy committed
5 6 7

This file is part of GNU Emacs.

8
GNU Emacs is free software: you can redistribute it and/or modify
Jim Blandy's avatar
Jim Blandy committed
9
it under the terms of the GNU General Public License as published by
10 11
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
Jim Blandy's avatar
Jim Blandy committed
12 13 14 15 16 17 18

GNU Emacs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
19
along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.  */
Jim Blandy's avatar
Jim Blandy committed
20 21


22
#include <config.h>
23

Jim Blandy's avatar
Jim Blandy committed
24
#include "lisp.h"
25
#include "character.h"
26
#include "buffer.h"
27
#include "syntax.h"
Kenichi Handa's avatar
Kenichi Handa committed
28
#include "charset.h"
29
#include "region-cache.h"
30
#include "blockinput.h"
31
#include "intervals.h"
Daniel Colascione's avatar
Daniel Colascione committed
32
#include "pdumper.h"
Jim Blandy's avatar
Jim Blandy committed
33

34
#include "regex-emacs.h"
Jim Blandy's avatar
Jim Blandy committed
35

36
#define REGEXP_CACHE_SIZE 20
Jim Blandy's avatar
Jim Blandy committed
37

38 39
/* If the regexp is non-nil, then the buffer contains the compiled form
   of that regexp, suitable for searching.  */
40 41
struct regexp_cache
{
42
  struct regexp_cache *next;
43
  Lisp_Object regexp, f_whitespace_regexp;
44
  /* Syntax table for which the regexp applies.  We need this because
45 46
     of character classes.  If this is t, then the compiled pattern is valid
     for any syntax-table.  */
47
  Lisp_Object syntax_table;
48 49
  struct re_pattern_buffer buf;
  char fastmap[0400];
50 51
  /* True means regexp was compiled to do full POSIX backtracking.  */
  bool posix;
52 53
  /* True means we're inside a buffer match.  */
  bool busy;
54
};
Jim Blandy's avatar
Jim Blandy committed
55

56
/* The instances of that struct.  */
57
static struct regexp_cache searchbufs[REGEXP_CACHE_SIZE];
Jim Blandy's avatar
Jim Blandy committed
58

59
/* The head of the linked list; points to the most recently used buffer.  */
60
static struct regexp_cache *searchbuf_head;
Jim Blandy's avatar
Jim Blandy committed
61

62
static void set_search_regs (ptrdiff_t, ptrdiff_t);
63
static void save_search_regs (void);
64 65 66 67 68 69 70 71
static EMACS_INT simple_search (EMACS_INT, unsigned char *, ptrdiff_t,
				ptrdiff_t, Lisp_Object, ptrdiff_t, ptrdiff_t,
                                ptrdiff_t, ptrdiff_t);
static EMACS_INT boyer_moore (EMACS_INT, unsigned char *, ptrdiff_t,
                              Lisp_Object, Lisp_Object, ptrdiff_t,
                              ptrdiff_t, int);
static EMACS_INT search_buffer (Lisp_Object, ptrdiff_t, ptrdiff_t,
                                ptrdiff_t, ptrdiff_t, EMACS_INT, int,
72
                                Lisp_Object, Lisp_Object, bool);
73

74 75
Lisp_Object re_match_object;

76
static AVOID
77
matcher_overflow (void)
Jim Blandy's avatar
Jim Blandy committed
78 79 80 81
{
  error ("Stack overflow in regexp matcher");
}

82 83 84 85 86 87 88 89 90 91 92
static void
freeze_buffer_relocation (void)
{
#ifdef REL_ALLOC
  /* Prevent ralloc.c from relocating the current buffer while
     searching it.  */
  r_alloc_inhibit_buffer_relocation (1);
  record_unwind_protect_int (r_alloc_inhibit_buffer_relocation, 0);
#endif
}

93 94 95
/* Compile a regexp and signal a Lisp error if anything goes wrong.
   PATTERN is the pattern to compile.
   CP is the place to put the result.
96
   TRANSLATE is a translation table for ignoring case, or nil for none.
97 98
   POSIX is true if we want full backtracking (POSIX style) for this pattern.
   False means backtrack only enough to get a valid match.
99 100

   The behavior also depends on Vsearch_spaces_regexp.  */
Jim Blandy's avatar
Jim Blandy committed
101

102
static void
103 104
compile_pattern_1 (struct regexp_cache *cp, Lisp_Object pattern,
		   Lisp_Object translate, bool posix)
Jim Blandy's avatar
Jim Blandy committed
105
{
106
  const char *whitespace_regexp;
107
  char *val;
Jim Blandy's avatar
Jim Blandy committed
108

109
  eassert (!cp->busy);
110
  cp->regexp = Qnil;
111
  cp->buf.translate = translate;
112
  cp->posix = posix;
113
  cp->buf.multibyte = STRING_MULTIBYTE (pattern);
Kenichi Handa's avatar
Kenichi Handa committed
114
  cp->buf.charset_unibyte = charset_unibyte;
115
  if (STRINGP (Vsearch_spaces_regexp))
116
    cp->f_whitespace_regexp = Vsearch_spaces_regexp;
117
  else
118
    cp->f_whitespace_regexp = Qnil;
119

120 121 122
  whitespace_regexp = STRINGP (Vsearch_spaces_regexp) ?
    SSDATA (Vsearch_spaces_regexp) : NULL;

Michal Nazarewicz's avatar
Michal Nazarewicz committed
123
  val = (char *) re_compile_pattern (SSDATA (pattern), SBYTES (pattern),
124
				     posix, whitespace_regexp, &cp->buf);
125

126 127
  /* If the compiled pattern hard codes some of the contents of the
     syntax-table, it can only be reused with *this* syntax table.  */
Tom Tromey's avatar
Tom Tromey committed
128
  cp->syntax_table = cp->buf.used_syntax ? BVAR (current_buffer, syntax_table) : Qt;
129

Jim Blandy's avatar
Jim Blandy committed
130
  if (val)
131
    xsignal1 (Qinvalid_regexp, build_string (val));
Jim Blandy's avatar
Jim Blandy committed
132

133 134 135
  cp->regexp = Fcopy_sequence (pattern);
}

136 137 138 139 140
/* Shrink each compiled regexp buffer in the cache
   to the size actually used right now.
   This is called from garbage collection.  */

void
141
shrink_regexp_cache (void)
142
{
143
  struct regexp_cache *cp;
144 145

  for (cp = searchbuf_head; cp != 0; cp = cp->next)
146 147 148 149 150
    if (!cp->busy)
      {
        cp->buf.allocated = cp->buf.used;
        cp->buf.buffer = xrealloc (cp->buf.buffer, cp->buf.used);
      }
151 152
}

153 154
/* Clear the regexp cache w.r.t. a particular syntax table,
   because it was changed.
155 156 157 158
   There is no danger of memory leak here because re_compile_pattern
   automagically manages the memory in each re_pattern_buffer struct,
   based on its `allocated' and `buffer' values.  */
void
159
clear_regexp_cache (void)
160 161 162 163
{
  int i;

  for (i = 0; i < REGEXP_CACHE_SIZE; ++i)
164 165
    /* It's tempting to compare with the syntax-table we've actually changed,
       but it's not sufficient because char-table inheritance means that
166
       modifying one syntax-table can change others at the same time.  */
167
    if (!searchbufs[i].busy && !EQ (searchbufs[i].syntax_table, Qt))
168
      searchbufs[i].regexp = Qnil;
169 170
}

171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
static void
unfreeze_pattern (void *arg)
{
  struct regexp_cache *searchbuf = arg;
  searchbuf->busy = false;
}

static void
freeze_pattern (struct regexp_cache *searchbuf)
{
  eassert (!searchbuf->busy);
  record_unwind_protect_ptr (unfreeze_pattern, searchbuf);
  searchbuf->busy = true;
}

186
/* Compile a regexp if necessary, but first check to see if there's one in
187 188
   the cache.
   PATTERN is the pattern to compile.
189
   TRANSLATE is a translation table for ignoring case, or nil for none.
190 191 192 193
   REGP is the structure that says where to store the "register"
   values that will result from matching this pattern.
   If it is 0, we should compile the pattern not to record any
   subexpression bounds.
194 195
   POSIX is true if we want full backtracking (POSIX style) for this pattern.
   False means backtrack only enough to get a valid match.  */
196

197
static struct regexp_cache *
198
compile_pattern (Lisp_Object pattern, struct re_registers *regp,
199
		 Lisp_Object translate, bool posix, bool multibyte)
200
{
201
  struct regexp_cache *cp, **cpp, **lru_nonbusy;
202

203
  for (cpp = &searchbuf_head, lru_nonbusy = NULL; ; cpp = &cp->next)
204 205
    {
      cp = *cpp;
206 207
      if (!cp->busy)
        lru_nonbusy = cpp;
208 209
      /* Entries are initialized to nil, and may be set to nil by
	 compile_pattern_1 if the pattern isn't valid.  Don't apply
Ken Raeburn's avatar
Ken Raeburn committed
210 211 212
	 string accessors in those cases.  However, compile_pattern_1
	 is only applied to the cache entry we pick here to reuse.  So
	 nil should never appear before a non-nil entry.  */
213
      if (NILP (cp->regexp))
214
	goto compile_it;
215
      if (SCHARS (cp->regexp) == SCHARS (pattern)
216
          && !cp->busy
217
	  && STRING_MULTIBYTE (cp->regexp) == STRING_MULTIBYTE (pattern)
218
	  && !NILP (Fstring_equal (cp->regexp, pattern))
219
	  && EQ (cp->buf.translate, translate)
Karl Heuer's avatar
Karl Heuer committed
220
	  && cp->posix == posix
221
	  && (EQ (cp->syntax_table, Qt)
Tom Tromey's avatar
Tom Tromey committed
222
	      || EQ (cp->syntax_table, BVAR (current_buffer, syntax_table)))
223
	  && !NILP (Fequal (cp->f_whitespace_regexp, Vsearch_spaces_regexp))
Kenichi Handa's avatar
Kenichi Handa committed
224
	  && cp->buf.charset_unibyte == charset_unibyte)
225 226
	break;

227 228
      /* If we're at the end of the cache, compile into the last
	 (least recently used) non-busy cell in the cache.  */
229 230
      if (cp->next == 0)
	{
231
          if (!lru_nonbusy)
232
            error ("Too much matching reentrancy");
233 234
          cpp = lru_nonbusy;
          cp = *cpp;
235
	compile_it:
236
          eassert (!cp->busy);
237
	  compile_pattern_1 (cp, pattern, translate, posix);
238 239 240 241 242 243 244 245 246 247
	  break;
	}
    }

  /* When we get here, cp (aka *cpp) contains the compiled pattern,
     either because we found it in the cache or because we just compiled it.
     Move it to the front of the queue to mark it as most recently used.  */
  *cpp = cp->next;
  cp->next = searchbuf_head;
  searchbuf_head = cp;
Jim Blandy's avatar
Jim Blandy committed
248

249 250 251 252 253
  /* Advise the searching functions about the space we have allocated
     for register data.  */
  if (regp)
    re_set_registers (&cp->buf, regp, regp->num_regs, regp->start, regp->end);

Juanma Barranquero's avatar
Juanma Barranquero committed
254
  /* The compiled pattern can be used both for multibyte and unibyte
Kenichi Handa's avatar
Kenichi Handa committed
255 256
     target.  But, we have to tell which the pattern is used for. */
  cp->buf.target_multibyte = multibyte;
257
  return cp;
Jim Blandy's avatar
Jim Blandy committed
258 259 260
}


261
static Lisp_Object
262
looking_at_1 (Lisp_Object string, bool posix)
Jim Blandy's avatar
Jim Blandy committed
263 264 265
{
  Lisp_Object val;
  unsigned char *p1, *p2;
266 267
  ptrdiff_t s1, s2;
  register ptrdiff_t i;
Jim Blandy's avatar
Jim Blandy committed
268

269 270 271
  if (running_asynch_code)
    save_search_regs ();

272 273
  /* This is so set_image_of_range_1 in regex-emacs.c can find the EQV
     table.  */
274
  set_char_table_extras (BVAR (current_buffer, case_canon_table), 2,
275
			 BVAR (current_buffer, case_eqv_table));
276

277
  CHECK_STRING (string);
278 279 280 281 282 283 284 285 286 287 288

  /* Snapshot in case Lisp changes the value.  */
  bool preserve_match_data = NILP (Vinhibit_changing_match_data);

  struct regexp_cache *cache_entry = compile_pattern (
    string,
    preserve_match_data ? &search_regs : NULL,
    (!NILP (BVAR (current_buffer, case_fold_search))
     ? BVAR (current_buffer, case_canon_table) : Qnil),
    posix,
    !NILP (BVAR (current_buffer, enable_multibyte_characters)));
Jim Blandy's avatar
Jim Blandy committed
289

Paul Eggert's avatar
Paul Eggert committed
290 291
  /* Do a pending quit right away, to avoid paradoxical behavior */
  maybe_quit ();
Jim Blandy's avatar
Jim Blandy committed
292

293 294
  /* Get pointers and sizes of the two strings
     that make up the visible portion of the buffer. */
Jim Blandy's avatar
Jim Blandy committed
295 296

  p1 = BEGV_ADDR;
297
  s1 = GPT_BYTE - BEGV_BYTE;
Jim Blandy's avatar
Jim Blandy committed
298
  p2 = GAP_END_ADDR;
299
  s2 = ZV_BYTE - GPT_BYTE;
Jim Blandy's avatar
Jim Blandy committed
300 301 302
  if (s1 < 0)
    {
      p2 = p1;
303
      s2 = ZV_BYTE - BEGV_BYTE;
Jim Blandy's avatar
Jim Blandy committed
304 305 306 307
      s1 = 0;
    }
  if (s2 < 0)
    {
308
      s1 = ZV_BYTE - BEGV_BYTE;
Jim Blandy's avatar
Jim Blandy committed
309 310
      s2 = 0;
    }
311

312
  ptrdiff_t count = SPECPDL_INDEX ();
313
  freeze_buffer_relocation ();
314 315 316
  freeze_pattern (cache_entry);
  re_match_object = Qnil;
  i = re_match_2 (&cache_entry->buf, (char *) p1, s1, (char *) p2, s2,
317
		  PT_BYTE - BEGV_BYTE,
318
		  preserve_match_data ? &search_regs : NULL,
319
		  ZV_BYTE - BEGV_BYTE);
320

Jim Blandy's avatar
Jim Blandy committed
321
  if (i == -2)
322 323 324 325
    {
      unbind_to (count, Qnil);
      matcher_overflow ();
    }
Jim Blandy's avatar
Jim Blandy committed
326

327
  val = (i >= 0 ? Qt : Qnil);
328
  if (preserve_match_data && i >= 0)
329
  {
330 331 332 333 334
    for (i = 0; i < search_regs.num_regs; i++)
      if (search_regs.start[i] >= 0)
	{
	  search_regs.start[i]
	    = BYTE_TO_CHAR (search_regs.start[i] + BEGV_BYTE);
335 336 337 338
         search_regs.end[i]
           = BYTE_TO_CHAR (search_regs.end[i] + BEGV_BYTE);
       }
    /* Set last_thing_searched only when match data is changed.  */
339
    XSETBUFFER (last_thing_searched, current_buffer);
340
  }
341

342
  return unbind_to (count, val);
Jim Blandy's avatar
Jim Blandy committed
343 344
}

345
DEFUN ("looking-at", Flooking_at, Slooking_at, 1, 1, 0,
346 347 348 349
       doc: /* Return t if text after point matches regular expression REGEXP.
This function modifies the match data that `match-beginning',
`match-end' and `match-data' access; save and restore the match
data if you want to preserve them.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
350
  (Lisp_Object regexp)
351
{
352
  return looking_at_1 (regexp, 0);
353 354 355
}

DEFUN ("posix-looking-at", Fposix_looking_at, Sposix_looking_at, 1, 1, 0,
356 357 358 359 360
       doc: /* Return t if text after point matches regular expression REGEXP.
Find the longest match, in accord with Posix regular expression rules.
This function modifies the match data that `match-beginning',
`match-end' and `match-data' access; save and restore the match
data if you want to preserve them.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
361
  (Lisp_Object regexp)
362
{
363
  return looking_at_1 (regexp, 1);
364 365 366
}

static Lisp_Object
367 368
string_match_1 (Lisp_Object regexp, Lisp_Object string, Lisp_Object start,
		bool posix)
Jim Blandy's avatar
Jim Blandy committed
369
{
370
  ptrdiff_t val;
371
  struct re_pattern_buffer *bufp;
372 373
  EMACS_INT pos;
  ptrdiff_t pos_byte, i;
Jim Blandy's avatar
Jim Blandy committed
374

375 376 377
  if (running_asynch_code)
    save_search_regs ();

378 379
  CHECK_STRING (regexp);
  CHECK_STRING (string);
Jim Blandy's avatar
Jim Blandy committed
380 381

  if (NILP (start))
382
    pos = 0, pos_byte = 0;
Jim Blandy's avatar
Jim Blandy committed
383 384
  else
    {
385
      ptrdiff_t len = SCHARS (string);
Jim Blandy's avatar
Jim Blandy committed
386

387
      CHECK_FIXNUM (start);
Tom Tromey's avatar
Tom Tromey committed
388
      pos = XFIXNUM (start);
389 390 391
      if (pos < 0 && -pos <= len)
	pos = len + pos;
      else if (0 > pos || pos > len)
Jim Blandy's avatar
Jim Blandy committed
392
	args_out_of_range (string, start);
393
      pos_byte = string_char_to_byte (string, pos);
Jim Blandy's avatar
Jim Blandy committed
394 395
    }

396 397
  /* This is so set_image_of_range_1 in regex-emacs.c can find the EQV
     table.  */
398
  set_char_table_extras (BVAR (current_buffer, case_canon_table), 2,
399
			 BVAR (current_buffer, case_eqv_table));
400

401 402 403 404 405 406 407
  bufp = &compile_pattern (regexp,
                           (NILP (Vinhibit_changing_match_data)
                            ? &search_regs : NULL),
                           (!NILP (BVAR (current_buffer, case_fold_search))
                            ? BVAR (current_buffer, case_canon_table) : Qnil),
                           posix,
                           STRING_MULTIBYTE (string))->buf;
408
  re_match_object = string;
409
  val = re_search (bufp, SSDATA (string),
410 411
		   SBYTES (string), pos_byte,
		   SBYTES (string) - pos_byte,
412 413 414 415 416 417 418
		   (NILP (Vinhibit_changing_match_data)
		    ? &search_regs : NULL));

  /* Set last_thing_searched only when match data is changed.  */
  if (NILP (Vinhibit_changing_match_data))
    last_thing_searched = Qt;

Jim Blandy's avatar
Jim Blandy committed
419 420 421
  if (val == -2)
    matcher_overflow ();
  if (val < 0) return Qnil;
422

423 424 425 426 427 428 429 430 431
  if (NILP (Vinhibit_changing_match_data))
    for (i = 0; i < search_regs.num_regs; i++)
      if (search_regs.start[i] >= 0)
	{
	  search_regs.start[i]
	    = string_byte_to_char (string, search_regs.start[i]);
	  search_regs.end[i]
	    = string_byte_to_char (string, search_regs.end[i]);
	}
432

433
  return make_fixnum (string_byte_to_char (string, val));
Jim Blandy's avatar
Jim Blandy committed
434
}
Richard M. Stallman's avatar
Richard M. Stallman committed
435

Paul Eggert's avatar
Paul Eggert committed
436
DEFUN ("string-match", Fstring_match, Sstring_match, 2, 3, 0,
437
       doc: /* Return index of start of first match for REGEXP in STRING, or nil.
Richard M. Stallman's avatar
Richard M. Stallman committed
438
Matching ignores case if `case-fold-search' is non-nil.
439 440 441
If third arg START is non-nil, start search at that index in STRING.
For index of first char beyond the match, do (match-end 0).
`match-end' and `match-beginning' also give indices of substrings
442 443 444 445
matched by parenthesis constructs in the pattern.

You can use the function `match-string' to extract the substrings
matched by the parenthesis constructions in REGEXP. */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
446
  (Lisp_Object regexp, Lisp_Object string, Lisp_Object start)
447 448 449 450 451
{
  return string_match_1 (regexp, string, start, 0);
}

DEFUN ("posix-string-match", Fposix_string_match, Sposix_string_match, 2, 3, 0,
452 453 454 455 456 457 458
       doc: /* Return index of start of first match for REGEXP in STRING, or nil.
Find the longest match, in accord with Posix regular expression rules.
Case is ignored if `case-fold-search' is non-nil in the current buffer.
If third arg START is non-nil, start search at that index in STRING.
For index of first char beyond the match, do (match-end 0).
`match-end' and `match-beginning' also give indices of substrings
matched by parenthesis constructs in the pattern.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
459
  (Lisp_Object regexp, Lisp_Object string, Lisp_Object start)
460 461 462 463
{
  return string_match_1 (regexp, string, start, 1);
}

464 465 466
/* Match REGEXP against STRING using translation table TABLE,
   searching all of STRING, and return the index of the match,
   or negative on failure.  This does not clobber the match data.  */
Richard M. Stallman's avatar
Richard M. Stallman committed
467

468
ptrdiff_t
469 470
fast_string_match_internal (Lisp_Object regexp, Lisp_Object string,
			    Lisp_Object table)
Richard M. Stallman's avatar
Richard M. Stallman committed
471
{
472
  ptrdiff_t val;
473
  struct re_pattern_buffer *bufp;
Richard M. Stallman's avatar
Richard M. Stallman committed
474

475 476
  bufp = &compile_pattern (regexp, 0, table,
                           0, STRING_MULTIBYTE (string))->buf;
477
  re_match_object = string;
478
  val = re_search (bufp, SSDATA (string),
479 480
		   SBYTES (string), 0,
		   SBYTES (string), 0);
Richard M. Stallman's avatar
Richard M. Stallman committed
481 482
  return val;
}
Karl Heuer's avatar
Karl Heuer committed
483 484 485

/* Match REGEXP against STRING, searching all of STRING ignoring case,
   and return the index of the match, or negative on failure.
486 487
   This does not clobber the match data.
   We assume that STRING contains single-byte characters.  */
Karl Heuer's avatar
Karl Heuer committed
488

489
ptrdiff_t
490 491
fast_c_string_match_ignore_case (Lisp_Object regexp,
				 const char *string, ptrdiff_t len)
Karl Heuer's avatar
Karl Heuer committed
492
{
493
  ptrdiff_t val;
Karl Heuer's avatar
Karl Heuer committed
494 495
  struct re_pattern_buffer *bufp;

496
  regexp = string_make_unibyte (regexp);
497 498 499
  bufp = &compile_pattern (regexp, 0,
                           Vascii_canon_table, 0,
                           0)->buf;
500
  re_match_object = Qt;
Karl Heuer's avatar
Karl Heuer committed
501 502 503
  val = re_search (bufp, string, len, 0, len, 0);
  return val;
}
504

505
/* Match REGEXP against the characters after POS to LIMIT, and return
506 507 508 509 510
   the number of matched characters.  If STRING is non-nil, match
   against the characters in it.  In that case, POS and LIMIT are
   indices into the string.  This function doesn't modify the match
   data.  */

511
ptrdiff_t
512 513
fast_looking_at (Lisp_Object regexp, ptrdiff_t pos, ptrdiff_t pos_byte,
		 ptrdiff_t limit, ptrdiff_t limit_byte, Lisp_Object string)
514
{
515
  bool multibyte;
516
  unsigned char *p1, *p2;
517 518
  ptrdiff_t s1, s2;
  ptrdiff_t len;
Juanma Barranquero's avatar
Juanma Barranquero committed
519

520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
  if (STRINGP (string))
    {
      if (pos_byte < 0)
	pos_byte = string_char_to_byte (string, pos);
      if (limit_byte < 0)
	limit_byte = string_char_to_byte (string, limit);
      p1 = NULL;
      s1 = 0;
      p2 = SDATA (string);
      s2 = SBYTES (string);
      multibyte = STRING_MULTIBYTE (string);
    }
  else
    {
      if (pos_byte < 0)
	pos_byte = CHAR_TO_BYTE (pos);
      if (limit_byte < 0)
	limit_byte = CHAR_TO_BYTE (limit);
      pos_byte -= BEGV_BYTE;
      limit_byte -= BEGV_BYTE;
      p1 = BEGV_ADDR;
      s1 = GPT_BYTE - BEGV_BYTE;
      p2 = GAP_END_ADDR;
      s2 = ZV_BYTE - GPT_BYTE;
      if (s1 < 0)
	{
	  p2 = p1;
	  s2 = ZV_BYTE - BEGV_BYTE;
	  s1 = 0;
	}
      if (s2 < 0)
	{
	  s1 = ZV_BYTE - BEGV_BYTE;
	  s2 = 0;
	}
Tom Tromey's avatar
Tom Tromey committed
555
      multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
556 557
    }

558 559 560
  struct regexp_cache *cache_entry =
    compile_pattern (regexp, 0, Qnil, 0, multibyte);
  ptrdiff_t count = SPECPDL_INDEX ();
561
  freeze_buffer_relocation ();
562 563 564
  freeze_pattern (cache_entry);
  re_match_object = STRINGP (string) ? string : Qnil;
  len = re_match_2 (&cache_entry->buf, (char *) p1, s1, (char *) p2, s2,
565 566
		    pos_byte, NULL, limit_byte);

567
  unbind_to (count, Qnil);
568 569 570
  return len;
}

571 572 573

/* The newline cache: remembering which sections of text have no newlines.  */

574
/* If the user has requested the long scans caching, make sure it's on.
575 576 577
   Otherwise, make sure it's off.
   This is our cheezy way of associating an action with the change of
   state of a buffer-local variable.  */
578
static struct region_cache *
579
newline_cache_on_off (struct buffer *buf)
580
{
581 582 583 584 585 586 587 588 589 590 591 592 593 594
  struct buffer *base_buf = buf;
  bool indirect_p = false;

  if (buf->base_buffer)
    {
      base_buf = buf->base_buffer;
      indirect_p = true;
    }

  /* Don't turn on or off the cache in the base buffer, if the value
     of cache-long-scans of the base buffer is inconsistent with that.
     This is because doing so will just make the cache pure overhead,
     since if we turn it on via indirect buffer, it will be
     immediately turned off by its base buffer.  */
595
  if (NILP (BVAR (buf, cache_long_scans)))
596
    {
597 598 599 600 601 602 603 604 605 606 607
      if (!indirect_p
	  || NILP (BVAR (base_buf, cache_long_scans)))
	{
	  /* It should be off.  */
	  if (base_buf->newline_cache)
	    {
	      free_region_cache (base_buf->newline_cache);
	      base_buf->newline_cache = 0;
	    }
	}
      return NULL;
608 609 610
    }
  else
    {
611 612 613 614 615 616 617 618
      if (!indirect_p
	  || !NILP (BVAR (base_buf, cache_long_scans)))
	{
	  /* It should be on.  */
	  if (base_buf->newline_cache == 0)
	    base_buf->newline_cache = new_region_cache ();
	}
      return base_buf->newline_cache;
619 620 621 622
    }
}


623
/* Search for COUNT newlines between START/START_BYTE and END/END_BYTE.
624 625 626 627 628 629 630

   If COUNT is positive, search forwards; END must be >= START.
   If COUNT is negative, search backwards for the -COUNTth instance;
      END must be <= START.
   If COUNT is zero, do anything you please; run rogue, for all I care.

   If END is zero, use BEGV or ZV instead, as appropriate for the
631 632
   direction indicated by COUNT.  If START_BYTE is -1 it is unknown,
   and similarly for END_BYTE.
Jim Blandy's avatar
Jim Blandy committed
633

634
   If we find COUNT instances, set *COUNTED to COUNT, and return the
Richard M. Stallman's avatar
Richard M. Stallman committed
635
   position past the COUNTth match.  Note that for reverse motion
Richard M. Stallman's avatar
Richard M. Stallman committed
636
   this is not the same as the usual convention for Emacs motion commands.
Jim Blandy's avatar
Jim Blandy committed
637

638 639 640
   If we don't find COUNT instances before reaching END, set *COUNTED
   to the number of newlines left found (negated if COUNT is negative),
   and return END.
Jim Blandy's avatar
Jim Blandy committed
641

642 643 644
   If BYTEPOS is not NULL, set *BYTEPOS to the byte position corresponding
   to the returned character position.

Paul Eggert's avatar
Paul Eggert committed
645
   If ALLOW_QUIT, check for quitting.  That's good to do
646 647
   except when inside redisplay.  */

648
ptrdiff_t
649
find_newline (ptrdiff_t start, ptrdiff_t start_byte, ptrdiff_t end,
650
	      ptrdiff_t end_byte, ptrdiff_t count, ptrdiff_t *counted,
651
	      ptrdiff_t *bytepos, bool allow_quit)
Jim Blandy's avatar
Jim Blandy committed
652
{
653
  struct region_cache *newline_cache;
654
  struct buffer *cache_buffer;
Jim Blandy's avatar
Jim Blandy committed
655

656
  if (!end)
657
    {
658
      if (count > 0)
659
	end = ZV, end_byte = ZV_BYTE;
660
      else
661
	end = BEGV, end_byte = BEGV_BYTE;
662
    }
663 664
  if (end_byte == -1)
    end_byte = CHAR_TO_BYTE (end);
Jim Blandy's avatar
Jim Blandy committed
665

666 667 668 669 670
  newline_cache = newline_cache_on_off (current_buffer);
  if (current_buffer->base_buffer)
    cache_buffer = current_buffer->base_buffer;
  else
    cache_buffer = current_buffer;
Jim Blandy's avatar
Jim Blandy committed
671

672 673
  if (counted)
    *counted = count;
Jim Blandy's avatar
Jim Blandy committed
674

Jim Blandy's avatar
Jim Blandy committed
675
  if (count > 0)
676
    while (start != end)
Jim Blandy's avatar
Jim Blandy committed
677
      {
678 679 680 681 682
        /* Our innermost scanning loop is very simple; it doesn't know
           about gaps, buffer ends, or the newline cache.  ceiling is
           the position of the last character before the next such
           obstacle --- the last character the dumb search loop should
           examine.  */
683
	ptrdiff_t tem, ceiling_byte = end_byte - 1;
684

685 686
        /* If we're using the newline cache, consult it to see whether
           we can avoid some scanning.  */
687
        if (newline_cache)
688
          {
689
            ptrdiff_t next_change;
690 691 692 693 694 695 696 697 698 699
	    int result = 1;

            while (start < end && result)
	      {
		ptrdiff_t lim1;

		result = region_cache_forward (cache_buffer, newline_cache,
					       start, &next_change);
		if (result)
		  {
700 701 702 703 704 705
		    /* When the cache revalidation is deferred,
		       next-change might point beyond ZV, which will
		       cause assertion violation in CHAR_TO_BYTE below.
		       Limit next_change to ZV to avoid that.  */
		    if (next_change > ZV)
		      next_change = ZV;
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
		    start = next_change;
		    lim1 = next_change = end;
		  }
		else
		  lim1 = min (next_change, end);

		/* The cache returned zero for this region; see if
		   this is because the region is known and includes
		   only newlines.  While at that, count any newlines
		   we bump into, and exit if we found enough off them.  */
		start_byte = CHAR_TO_BYTE (start);
		while (start < lim1
		       && FETCH_BYTE (start_byte) == '\n')
		  {
		    start_byte++;
		    start++;
		    if (--count == 0)
		      {
			if (bytepos)
			  *bytepos = start_byte;
			return start;
		      }
		  }
		/* If we found a non-newline character before hitting
		   position where the cache will again return non-zero
		   (i.e. no newlines beyond that position), it means
		   this region is not yet known to the cache, and we
		   must resort to the "dumb loop" method.  */
		if (start < next_change && !result)
		  break;
		result = 1;
	      }
	    if (start >= end)
	      {
		start = end;
		start_byte = end_byte;
		break;
	      }
744

745 746 747
            /* START should never be after END.  */
            if (start_byte > ceiling_byte)
              start_byte = ceiling_byte;
748 749 750

            /* Now the text after start is an unknown region, and
               next_change is the position of the next known region. */
751
            ceiling_byte = min (CHAR_TO_BYTE (next_change) - 1, ceiling_byte);
752
          }
753
	else if (start_byte == -1)
754
	  start_byte = CHAR_TO_BYTE (start);
755 756 757 758 759

        /* The dumb loop can only scan text stored in contiguous
           bytes. BUFFER_CEILING_OF returns the last character
           position that is contiguous, so the ceiling is the
           position after that.  */
760 761
	tem = BUFFER_CEILING_OF (start_byte);
	ceiling_byte = min (tem, ceiling_byte);
762 763

        {
764
          /* The termination address of the dumb loop.  */
765 766
	  unsigned char *lim_addr = BYTE_POS_ADDR (ceiling_byte) + 1;
	  ptrdiff_t lim_byte = ceiling_byte + 1;
767

768 769 770 771 772 773 774
	  /* Nonpositive offsets (relative to LIM_ADDR and LIM_BYTE)
	     of the base, the cursor, and the next line.  */
	  ptrdiff_t base = start_byte - lim_byte;
	  ptrdiff_t cursor, next;

	  for (cursor = base; cursor < 0; cursor = next)
	    {
775
              /* The dumb loop.  */
776 777
	      unsigned char *nl = memchr (lim_addr + cursor, '\n', - cursor);
	      next = nl ? nl - lim_addr : 0;
778

779 780 781
              /* If we're using the newline cache, cache the fact that
                 the region we just traversed is free of newlines. */
              if (newline_cache && cursor != next)
782
		{
783
		  know_region_cache (cache_buffer, newline_cache,
784 785 786 787
				     BYTE_TO_CHAR (lim_byte + cursor),
				     BYTE_TO_CHAR (lim_byte + next));
		  /* know_region_cache can relocate buffer text.  */
		  lim_addr = BYTE_POS_ADDR (ceiling_byte) + 1;
788 789 790 791
		}

              if (! nl)
		break;
792
	      next++;
793 794 795

	      if (--count == 0)
		{
796
		  if (bytepos)
797 798
		    *bytepos = lim_byte + next;
		  return BYTE_TO_CHAR (lim_byte + next);
799
		}
Paul Eggert's avatar
Paul Eggert committed
800 801
	      if (allow_quit)
		maybe_quit ();
802 803
            }

804
	  start_byte = lim_byte;
805
	  start = BYTE_TO_CHAR (start_byte);
806
        }
Jim Blandy's avatar
Jim Blandy committed
807 808
      }
  else
809 810 811
    while (start > end)
      {
        /* The last character to check before the next obstacle.  */
812
	ptrdiff_t tem, ceiling_byte = end_byte;
813 814

        /* Consult the newline cache, if appropriate.  */
815
        if (newline_cache)
816
          {
817
            ptrdiff_t next_change;
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
	    int result = 1;

            while (start > end && result)
	      {
		ptrdiff_t lim1;

		result = region_cache_backward (cache_buffer, newline_cache,
						start, &next_change);
		if (result)
		  {
		    start = next_change;
		    lim1 = next_change = end;
		  }
		else
		  lim1 = max (next_change, end);
		start_byte = CHAR_TO_BYTE (start);
		while (start > lim1
		       && FETCH_BYTE (start_byte - 1) == '\n')
		  {
		    if (++count == 0)
		      {
			if (bytepos)
			  *bytepos = start_byte;
			return start;
		      }
		    start_byte--;
		    start--;
		  }
		if (start > next_change && !result)
		  break;
		result = 1;
	      }
	    if (start <= end)
	      {
		start = end;
		start_byte = end_byte;
		break;
	      }
856 857

            /* Start should never be at or before end.  */
858 859
            if (start_byte <= ceiling_byte)
              start_byte = ceiling_byte + 1;
860 861 862

            /* Now the text before start is an unknown region, and
               next_change is the position of the next known region. */
863
            ceiling_byte = max (CHAR_TO_BYTE (next_change), ceiling_byte);
864
          }
865
	else if (start_byte == -1)
866
	  start_byte = CHAR_TO_BYTE (start);
867 868

        /* Stop scanning before the gap.  */
869 870
	tem = BUFFER_FLOOR_OF (start_byte - 1);
	ceiling_byte = max (tem, ceiling_byte);
871 872 873

        {
          /* The termination address of the dumb loop.  */
874
	  unsigned char *ceiling_addr = BYTE_POS_ADDR (ceiling_byte);
875

876 877 878 879 880 881 882
	  /* Offsets (relative to CEILING_ADDR and CEILING_BYTE) of
	     the base, the cursor, and the previous line.  These
	     offsets are at least -1.  */
	  ptrdiff_t base = start_byte - ceiling_byte;
	  ptrdiff_t cursor, prev;

	  for (cursor = base; 0 < cursor; cursor = prev)
883
            {
884 885
	      unsigned char *nl = memrchr (ceiling_addr, '\n', cursor);
	      prev = nl ? nl - ceiling_addr : -1;
886 887

              /* If we're looking for newlines, cache the fact that
888
                 this line's region is free of them. */
889
              if (newline_cache && cursor != prev + 1)
890
		{
891
		  know_region_cache (cache_buffer, newline_cache,
892 893 894 895
				     BYTE_TO_CHAR (ceiling_byte + prev + 1),
				     BYTE_TO_CHAR (ceiling_byte + cursor));
		  /* know_region_cache can relocate buffer text.  */
		  ceiling_addr = BYTE_POS_ADDR (ceiling_byte);
896 897 898 899 900 901 902
		}

              if (! nl)
		break;

	      if (++count >= 0)
		{
903
		  if (bytepos)
904 905
		    *bytepos = ceiling_byte + prev + 1;
		  return BYTE_TO_CHAR (ceiling_byte + prev + 1);
906
		}
Paul Eggert's avatar
Paul Eggert committed
907 908
	      if (allow_quit)
		maybe_quit ();
909 910
            }

911
	  start_byte = ceiling_byte;
912
	  start = BYTE_TO_CHAR (start_byte);
913 914 915
        }
      }

916 917
  if (counted)
    *counted -= count;
918 919 920 921 922
  if (bytepos)
    {
      *bytepos = start_byte == -1 ? CHAR_TO_BYTE (start) : start_byte;
      eassert (*bytepos == CHAR_TO_BYTE (start));
    }
923
  return start;
Jim Blandy's avatar
Jim Blandy committed
924
}
925

926
/* Search for COUNT instances of a line boundary.
927 928 929 930 931
   Start at START.  If COUNT is negative, search backwards.

   We report the resulting position by calling TEMP_SET_PT_BOTH.

   If we find COUNT instances. we position after (always after,
932
   even if scanning backwards) the COUNTth match.
933 934

   If we don't find COUNT instances before reaching the end of the
935
   buffer (or the beginning, if scanning backwards), we position at
936 937
   the limit we bumped up against.

Paul Eggert's avatar
Paul Eggert committed
938
   If ALLOW_QUIT, check for quitting.  That's good to do
939
   except in special cases.  */
Jim Blandy's avatar
Jim Blandy committed
940

941
void
942 943
scan_newline (ptrdiff_t start, ptrdiff_t start_byte,
	      ptrdiff_t limit, ptrdiff_t limit_byte,
944
	      ptrdiff_t count, bool allow_quit)
945
{
946
  ptrdiff_t charpos, bytepos, counted;
947

948
  charpos = find_newline (start, start_byte, limit, limit_byte,
949 950
			  count, &counted, &bytepos, allow_quit);
  if (counted != count)
951
    TEMP_SET_PT_BOTH (limit, limit_byte);
952
  else
953
    TEMP_SET_PT_BOTH (charpos, bytepos);
954 955
}

956 957 958 959 960 961 962
/* Like above, but always scan from point and report the
   resulting position in *CHARPOS and *BYTEPOS.  */

ptrdiff_t
scan_newline_from_point (ptrdiff_t count, ptrdiff_t *charpos,
			 ptrdiff_t *bytepos)
{
963
  ptrdiff_t counted;
964 965 966

  if (count <= 0)
    *charpos = find_newline (PT, PT_BYTE, BEGV, BEGV_BYTE, count - 1,
967
			     &counted, bytepos, 1);
968 969
  else
    *charpos = find_newline (PT, PT_BYTE, ZV, ZV_BYTE, count,
970 971
			     &counted, bytepos, 1);
  return counted;
972 973
}

974
/* Like find_newline, but doesn't allow QUITting and doesn't return
975
   COUNTED.  */
976
ptrdiff_t
977 978
find_newline_no_quit (ptrdiff_t from, ptrdiff_t frombyte,
		      ptrdiff_t cnt, ptrdiff_t *bytepos)
Jim Blandy's avatar
Jim Blandy committed
979
{
980
  return find_newline (from, frombyte, 0, -1, cnt, NULL, bytepos, 0);
981 982
}

983 984 985
/* Like find_newline, but returns position before the newline, not
   after, and only search up to TO.
   This isn't just find_newline_no_quit (...)-1, because you might hit TO.  */
986

987
ptrdiff_t
988 989
find_before_next_newline (ptrdiff_t from, ptrdiff_t to,
			  ptrdiff_t cnt, ptrdiff_t *bytepos)
990
{
991 992
  ptrdiff_t counted;
  ptrdiff_t pos = find_newline (from, -1, to, -1, cnt, &counted, bytepos, 1);
993

994
  if (counted == cnt)
995 996 997 998 999 1000
    {
      if (bytepos)
	DEC_BOTH (pos, *bytepos);
      else
	pos--;
    }
1001
  return pos;
Jim Blandy's avatar
Jim Blandy committed
1002 1003 1004 1005 1006
}

/* Subroutines of Lisp buffer search functions. */

static Lisp_Object
1007
search_command (Lisp_Object string, Lisp_Object bound, Lisp_Object noerror,
1008
		Lisp_Object count, int direction, int RE, bool posix)
Jim Blandy's avatar
Jim Blandy committed
1009
{
1010
  EMACS_INT np;
1011 1012
  EMACS_INT lim;
  ptrdiff_t lim_byte;
1013
  EMACS_INT n = direction;
Jim Blandy's avatar
Jim Blandy committed
1014 1015 1016

  if (!NILP (count))
    {
1017
      CHECK_FIXNUM (count);
Tom Tromey's avatar
Tom Tromey committed
1018
      n *= XFIXNUM (count);
Jim Blandy's avatar
Jim Blandy committed
1019 1020
    }

1021
  CHECK_STRING (string);
Jim Blandy's avatar
Jim Blandy committed
1022
  if (NILP (bound))
1023