search.c 104 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


63 64
/* Every call to re_search, etc., must pass &search_regs as the regs
   argument unless you can show it is unnecessary (i.e., if re_search
Jim Blandy's avatar
Jim Blandy committed
65 66 67 68 69
   is certainly going to be called again before region-around-match
   can be called).

   Since the registers are now dynamically allocated, we need to make
   sure not to refer to the Nth register before checking that it has
Jim Blandy's avatar
Jim Blandy committed
70 71 72
   been allocated by checking search_regs.num_regs.

   The regex code keeps track of whether it has allocated the search
73 74
   buffer using bits in the re_pattern_buffer.  This means that whenever
   you compile a new pattern, it completely forgets whether it has
Jim Blandy's avatar
Jim Blandy committed
75 76 77 78 79
   allocated any registers, and will allocate new registers the next
   time you call a searching or matching function.  Therefore, we need
   to call re_set_registers after compiling a new pattern or after
   setting the match registers, so that the regex functions will be
   able to free or re-allocate it properly.  */
80
/* static struct re_registers search_regs; */
Jim Blandy's avatar
Jim Blandy committed
81

Jim Blandy's avatar
Jim Blandy committed
82 83 84
/* The buffer in which the last search was performed, or
   Qt if the last search was done in a string;
   Qnil if no searching has been done yet.  */
85
/* static Lisp_Object last_thing_searched; */
Jim Blandy's avatar
Jim Blandy committed
86

87
static void set_search_regs (ptrdiff_t, ptrdiff_t);
88
static void save_search_regs (void);
89 90 91 92 93 94 95 96
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,
97
                                Lisp_Object, Lisp_Object, bool);
98

99 100
Lisp_Object re_match_object;

101
static _Noreturn void
102
matcher_overflow (void)
Jim Blandy's avatar
Jim Blandy committed
103 104 105 106
{
  error ("Stack overflow in regexp matcher");
}

107 108 109 110 111 112 113 114 115 116 117
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
}

118 119 120
/* 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.
121
   TRANSLATE is a translation table for ignoring case, or nil for none.
122 123
   POSIX is true if we want full backtracking (POSIX style) for this pattern.
   False means backtrack only enough to get a valid match.
124 125

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

127
static void
128 129
compile_pattern_1 (struct regexp_cache *cp, Lisp_Object pattern,
		   Lisp_Object translate, bool posix)
Jim Blandy's avatar
Jim Blandy committed
130
{
131
  const char *whitespace_regexp;
132
  char *val;
Jim Blandy's avatar
Jim Blandy committed
133

134
  eassert (!cp->busy);
135
  cp->regexp = Qnil;
136
  cp->buf.translate = translate;
137
  cp->posix = posix;
138
  cp->buf.multibyte = STRING_MULTIBYTE (pattern);
Kenichi Handa's avatar
Kenichi Handa committed
139
  cp->buf.charset_unibyte = charset_unibyte;
140
  if (STRINGP (Vsearch_spaces_regexp))
141
    cp->f_whitespace_regexp = Vsearch_spaces_regexp;
142
  else
143
    cp->f_whitespace_regexp = Qnil;
144

145 146 147
  whitespace_regexp = STRINGP (Vsearch_spaces_regexp) ?
    SSDATA (Vsearch_spaces_regexp) : NULL;

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

151 152
  /* 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
153
  cp->syntax_table = cp->buf.used_syntax ? BVAR (current_buffer, syntax_table) : Qt;
154

Jim Blandy's avatar
Jim Blandy committed
155
  if (val)
156
    xsignal1 (Qinvalid_regexp, build_string (val));
Jim Blandy's avatar
Jim Blandy committed
157

158 159 160
  cp->regexp = Fcopy_sequence (pattern);
}

161 162 163 164 165
/* Shrink each compiled regexp buffer in the cache
   to the size actually used right now.
   This is called from garbage collection.  */

void
166
shrink_regexp_cache (void)
167
{
168
  struct regexp_cache *cp;
169 170

  for (cp = searchbuf_head; cp != 0; cp = cp->next)
171 172 173 174 175
    if (!cp->busy)
      {
        cp->buf.allocated = cp->buf.used;
        cp->buf.buffer = xrealloc (cp->buf.buffer, cp->buf.used);
      }
176 177
}

178 179
/* Clear the regexp cache w.r.t. a particular syntax table,
   because it was changed.
180 181 182 183
   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
184
clear_regexp_cache (void)
185 186 187 188
{
  int i;

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

196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
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;
}

211
/* Compile a regexp if necessary, but first check to see if there's one in
212 213
   the cache.
   PATTERN is the pattern to compile.
214
   TRANSLATE is a translation table for ignoring case, or nil for none.
215 216 217 218
   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.
219 220
   POSIX is true if we want full backtracking (POSIX style) for this pattern.
   False means backtrack only enough to get a valid match.  */
221

222
static struct regexp_cache *
223
compile_pattern (Lisp_Object pattern, struct re_registers *regp,
224
		 Lisp_Object translate, bool posix, bool multibyte)
225 226 227 228 229 230
{
  struct regexp_cache *cp, **cpp;

  for (cpp = &searchbuf_head; ; cpp = &cp->next)
    {
      cp = *cpp;
231 232
      /* 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
233 234 235
	 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.  */
236
      if (NILP (cp->regexp))
237
	goto compile_it;
238
      if (SCHARS (cp->regexp) == SCHARS (pattern)
239
          && !cp->busy
240
	  && STRING_MULTIBYTE (cp->regexp) == STRING_MULTIBYTE (pattern)
241
	  && !NILP (Fstring_equal (cp->regexp, pattern))
242
	  && EQ (cp->buf.translate, translate)
Karl Heuer's avatar
Karl Heuer committed
243
	  && cp->posix == posix
244
	  && (EQ (cp->syntax_table, Qt)
Tom Tromey's avatar
Tom Tromey committed
245
	      || EQ (cp->syntax_table, BVAR (current_buffer, syntax_table)))
246
	  && !NILP (Fequal (cp->f_whitespace_regexp, Vsearch_spaces_regexp))
Kenichi Handa's avatar
Kenichi Handa committed
247
	  && cp->buf.charset_unibyte == charset_unibyte)
248 249
	break;

250 251 252
      /* If we're at the end of the cache, compile into the nil cell
	 we found, or the last (least recently used) cell with a
	 string value.  */
253 254
      if (cp->next == 0)
	{
255 256
          if (cp->busy)
            error ("Too much matching reentrancy");
257
	compile_it:
258
          eassert (!cp->busy);
259
	  compile_pattern_1 (cp, pattern, translate, posix);
260 261 262 263 264 265 266 267 268 269
	  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
270

271 272 273 274 275
  /* 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
276
  /* The compiled pattern can be used both for multibyte and unibyte
Kenichi Handa's avatar
Kenichi Handa committed
277 278
     target.  But, we have to tell which the pattern is used for. */
  cp->buf.target_multibyte = multibyte;
279
  return cp;
Jim Blandy's avatar
Jim Blandy committed
280 281 282
}


283
static Lisp_Object
284
looking_at_1 (Lisp_Object string, bool posix)
Jim Blandy's avatar
Jim Blandy committed
285 286 287
{
  Lisp_Object val;
  unsigned char *p1, *p2;
288 289
  ptrdiff_t s1, s2;
  register ptrdiff_t i;
Jim Blandy's avatar
Jim Blandy committed
290

291 292 293
  if (running_asynch_code)
    save_search_regs ();

294 295
  /* This is so set_image_of_range_1 in regex-emacs.c can find the EQV
     table.  */
296
  set_char_table_extras (BVAR (current_buffer, case_canon_table), 2,
297
			 BVAR (current_buffer, case_eqv_table));
298

299
  CHECK_STRING (string);
300 301 302 303 304 305 306 307 308 309 310

  /* 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
311

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

315 316
  /* Get pointers and sizes of the two strings
     that make up the visible portion of the buffer. */
Jim Blandy's avatar
Jim Blandy committed
317 318

  p1 = BEGV_ADDR;
319
  s1 = GPT_BYTE - BEGV_BYTE;
Jim Blandy's avatar
Jim Blandy committed
320
  p2 = GAP_END_ADDR;
321
  s2 = ZV_BYTE - GPT_BYTE;
Jim Blandy's avatar
Jim Blandy committed
322 323 324
  if (s1 < 0)
    {
      p2 = p1;
325
      s2 = ZV_BYTE - BEGV_BYTE;
Jim Blandy's avatar
Jim Blandy committed
326 327 328 329
      s1 = 0;
    }
  if (s2 < 0)
    {
330
      s1 = ZV_BYTE - BEGV_BYTE;
Jim Blandy's avatar
Jim Blandy committed
331 332
      s2 = 0;
    }
333

334
  ptrdiff_t count = SPECPDL_INDEX ();
335
  freeze_buffer_relocation ();
336 337 338
  freeze_pattern (cache_entry);
  re_match_object = Qnil;
  i = re_match_2 (&cache_entry->buf, (char *) p1, s1, (char *) p2, s2,
339
		  PT_BYTE - BEGV_BYTE,
340
		  preserve_match_data ? &search_regs : NULL,
341
		  ZV_BYTE - BEGV_BYTE);
342

Jim Blandy's avatar
Jim Blandy committed
343 344 345
  if (i == -2)
    matcher_overflow ();

346
  val = (i >= 0 ? Qt : Qnil);
347
  if (preserve_match_data && i >= 0)
348
  {
349 350 351 352 353
    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);
354 355 356 357
         search_regs.end[i]
           = BYTE_TO_CHAR (search_regs.end[i] + BEGV_BYTE);
       }
    /* Set last_thing_searched only when match data is changed.  */
358
    XSETBUFFER (last_thing_searched, current_buffer);
359
  }
360

361
  return unbind_to (count, val);
Jim Blandy's avatar
Jim Blandy committed
362 363
}

364
DEFUN ("looking-at", Flooking_at, Slooking_at, 1, 1, 0,
365 366 367 368
       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
369
  (Lisp_Object regexp)
370
{
371
  return looking_at_1 (regexp, 0);
372 373 374
}

DEFUN ("posix-looking-at", Fposix_looking_at, Sposix_looking_at, 1, 1, 0,
375 376 377 378 379
       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
380
  (Lisp_Object regexp)
381
{
382
  return looking_at_1 (regexp, 1);
383 384 385
}

static Lisp_Object
386 387
string_match_1 (Lisp_Object regexp, Lisp_Object string, Lisp_Object start,
		bool posix)
Jim Blandy's avatar
Jim Blandy committed
388
{
389
  ptrdiff_t val;
390
  struct re_pattern_buffer *bufp;
391 392
  EMACS_INT pos;
  ptrdiff_t pos_byte, i;
Jim Blandy's avatar
Jim Blandy committed
393

394 395 396
  if (running_asynch_code)
    save_search_regs ();

397 398
  CHECK_STRING (regexp);
  CHECK_STRING (string);
Jim Blandy's avatar
Jim Blandy committed
399 400

  if (NILP (start))
401
    pos = 0, pos_byte = 0;
Jim Blandy's avatar
Jim Blandy committed
402 403
  else
    {
404
      ptrdiff_t len = SCHARS (string);
Jim Blandy's avatar
Jim Blandy committed
405

406
      CHECK_FIXNUM (start);
Tom Tromey's avatar
Tom Tromey committed
407
      pos = XFIXNUM (start);
408 409 410
      if (pos < 0 && -pos <= len)
	pos = len + pos;
      else if (0 > pos || pos > len)
Jim Blandy's avatar
Jim Blandy committed
411
	args_out_of_range (string, start);
412
      pos_byte = string_char_to_byte (string, pos);
Jim Blandy's avatar
Jim Blandy committed
413 414
    }

415 416
  /* This is so set_image_of_range_1 in regex-emacs.c can find the EQV
     table.  */
417
  set_char_table_extras (BVAR (current_buffer, case_canon_table), 2,
418
			 BVAR (current_buffer, case_eqv_table));
419

420 421 422 423 424 425 426
  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;
427
  re_match_object = string;
428
  val = re_search (bufp, SSDATA (string),
429 430
		   SBYTES (string), pos_byte,
		   SBYTES (string) - pos_byte,
431 432 433 434 435 436 437
		   (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
438 439 440
  if (val == -2)
    matcher_overflow ();
  if (val < 0) return Qnil;
441

442 443 444 445 446 447 448 449 450
  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]);
	}
451

452
  return make_fixnum (string_byte_to_char (string, val));
Jim Blandy's avatar
Jim Blandy committed
453
}
Richard M. Stallman's avatar
Richard M. Stallman committed
454

Paul Eggert's avatar
Paul Eggert committed
455
DEFUN ("string-match", Fstring_match, Sstring_match, 2, 3, 0,
456
       doc: /* Return index of start of first match for REGEXP in STRING, or nil.
Richard M. Stallman's avatar
Richard M. Stallman committed
457
Matching ignores case if `case-fold-search' is non-nil.
458 459 460
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
461 462 463 464
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
465
  (Lisp_Object regexp, Lisp_Object string, Lisp_Object start)
466 467 468 469 470
{
  return string_match_1 (regexp, string, start, 0);
}

DEFUN ("posix-string-match", Fposix_string_match, Sposix_string_match, 2, 3, 0,
471 472 473 474 475 476 477
       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
478
  (Lisp_Object regexp, Lisp_Object string, Lisp_Object start)
479 480 481 482
{
  return string_match_1 (regexp, string, start, 1);
}

483 484 485
/* 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
486

487
ptrdiff_t
488 489
fast_string_match_internal (Lisp_Object regexp, Lisp_Object string,
			    Lisp_Object table)
Richard M. Stallman's avatar
Richard M. Stallman committed
490
{
491
  ptrdiff_t val;
492
  struct re_pattern_buffer *bufp;
Richard M. Stallman's avatar
Richard M. Stallman committed
493

494 495
  bufp = &compile_pattern (regexp, 0, table,
                           0, STRING_MULTIBYTE (string))->buf;
496
  re_match_object = string;
497
  val = re_search (bufp, SSDATA (string),
498 499
		   SBYTES (string), 0,
		   SBYTES (string), 0);
Richard M. Stallman's avatar
Richard M. Stallman committed
500 501
  return val;
}
Karl Heuer's avatar
Karl Heuer committed
502 503 504

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

508
ptrdiff_t
509 510
fast_c_string_match_ignore_case (Lisp_Object regexp,
				 const char *string, ptrdiff_t len)
Karl Heuer's avatar
Karl Heuer committed
511
{
512
  ptrdiff_t val;
Karl Heuer's avatar
Karl Heuer committed
513 514
  struct re_pattern_buffer *bufp;

515
  regexp = string_make_unibyte (regexp);
516 517 518
  bufp = &compile_pattern (regexp, 0,
                           Vascii_canon_table, 0,
                           0)->buf;
519
  re_match_object = Qt;
Karl Heuer's avatar
Karl Heuer committed
520 521 522
  val = re_search (bufp, string, len, 0, len, 0);
  return val;
}
523

524
/* Match REGEXP against the characters after POS to LIMIT, and return
525 526 527 528 529
   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.  */

530
ptrdiff_t
531 532
fast_looking_at (Lisp_Object regexp, ptrdiff_t pos, ptrdiff_t pos_byte,
		 ptrdiff_t limit, ptrdiff_t limit_byte, Lisp_Object string)
533
{
534
  bool multibyte;
535
  unsigned char *p1, *p2;
536 537
  ptrdiff_t s1, s2;
  ptrdiff_t len;
Juanma Barranquero's avatar
Juanma Barranquero committed
538

539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
  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
574
      multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
575 576
    }

577 578 579
  struct regexp_cache *cache_entry =
    compile_pattern (regexp, 0, Qnil, 0, multibyte);
  ptrdiff_t count = SPECPDL_INDEX ();
580
  freeze_buffer_relocation ();
581 582 583
  freeze_pattern (cache_entry);
  re_match_object = STRINGP (string) ? string : Qnil;
  len = re_match_2 (&cache_entry->buf, (char *) p1, s1, (char *) p2, s2,
584 585
		    pos_byte, NULL, limit_byte);

586
  unbind_to (count, Qnil);
587 588 589
  return len;
}

590 591 592

/* The newline cache: remembering which sections of text have no newlines.  */

593
/* If the user has requested the long scans caching, make sure it's on.
594 595 596
   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.  */
597
static struct region_cache *
598
newline_cache_on_off (struct buffer *buf)
599
{
600 601 602 603 604 605 606 607 608 609 610 611 612 613
  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.  */
614
  if (NILP (BVAR (buf, cache_long_scans)))
615
    {
616 617 618 619 620 621 622 623 624 625 626
      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;
627 628 629
    }
  else
    {
630 631 632 633 634 635 636 637
      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;
638 639 640 641
    }
}


642
/* Search for COUNT newlines between START/START_BYTE and END/END_BYTE.
643 644 645 646 647 648 649

   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
650 651
   direction indicated by COUNT.  If START_BYTE is -1 it is unknown,
   and similarly for END_BYTE.
Jim Blandy's avatar
Jim Blandy committed
652

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

657 658 659
   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
660

661 662 663
   If BYTEPOS is not NULL, set *BYTEPOS to the byte position corresponding
   to the returned character position.

Paul Eggert's avatar
Paul Eggert committed
664
   If ALLOW_QUIT, check for quitting.  That's good to do
665 666
   except when inside redisplay.  */

667
ptrdiff_t
668
find_newline (ptrdiff_t start, ptrdiff_t start_byte, ptrdiff_t end,
669
	      ptrdiff_t end_byte, ptrdiff_t count, ptrdiff_t *counted,
670
	      ptrdiff_t *bytepos, bool allow_quit)
Jim Blandy's avatar
Jim Blandy committed
671
{
672
  struct region_cache *newline_cache;
673
  struct buffer *cache_buffer;
Jim Blandy's avatar
Jim Blandy committed
674

675
  if (!end)
676
    {
677
      if (count > 0)
678
	end = ZV, end_byte = ZV_BYTE;
679
      else
680
	end = BEGV, end_byte = BEGV_BYTE;
681
    }
682 683
  if (end_byte == -1)
    end_byte = CHAR_TO_BYTE (end);
Jim Blandy's avatar
Jim Blandy committed
684

685 686 687 688 689
  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
690

691 692
  if (counted)
    *counted = count;
Jim Blandy's avatar
Jim Blandy committed
693

Jim Blandy's avatar
Jim Blandy committed
694
  if (count > 0)
695
    while (start != end)
Jim Blandy's avatar
Jim Blandy committed
696
      {
697 698 699 700 701
        /* 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.  */
702
	ptrdiff_t tem, ceiling_byte = end_byte - 1;
703

704 705
        /* If we're using the newline cache, consult it to see whether
           we can avoid some scanning.  */
706
        if (newline_cache)
707
          {
708
            ptrdiff_t next_change;
709 710 711 712 713 714 715 716 717 718
	    int result = 1;

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

		result = region_cache_forward (cache_buffer, newline_cache,
					       start, &next_change);
		if (result)
		  {
719 720 721 722 723 724
		    /* 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;
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
		    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;
	      }
763

764 765 766
            /* START should never be after END.  */
            if (start_byte > ceiling_byte)
              start_byte = ceiling_byte;
767 768 769

            /* Now the text after start is an unknown region, and
               next_change is the position of the next known region. */
770
            ceiling_byte = min (CHAR_TO_BYTE (next_change) - 1, ceiling_byte);
771
          }
772
	else if (start_byte == -1)
773
	  start_byte = CHAR_TO_BYTE (start);
774 775 776 777 778

        /* 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.  */
779 780
	tem = BUFFER_CEILING_OF (start_byte);
	ceiling_byte = min (tem, ceiling_byte);
781 782

        {
783
          /* The termination address of the dumb loop.  */
784 785
	  unsigned char *lim_addr = BYTE_POS_ADDR (ceiling_byte) + 1;
	  ptrdiff_t lim_byte = ceiling_byte + 1;
786

787 788 789 790 791 792 793
	  /* 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)
	    {
794
              /* The dumb loop.  */
795 796
	      unsigned char *nl = memchr (lim_addr + cursor, '\n', - cursor);
	      next = nl ? nl - lim_addr : 0;
797

798 799 800
              /* 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)
801
		{
802
		  know_region_cache (cache_buffer, newline_cache,
803 804 805 806
				     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;
807 808 809 810
		}

              if (! nl)
		break;
811
	      next++;
812 813 814

	      if (--count == 0)
		{
815
		  if (bytepos)
816 817
		    *bytepos = lim_byte + next;
		  return BYTE_TO_CHAR (lim_byte + next);
818
		}
Paul Eggert's avatar
Paul Eggert committed
819 820
	      if (allow_quit)
		maybe_quit ();
821 822
            }

823
	  start_byte = lim_byte;
824
	  start = BYTE_TO_CHAR (start_byte);
825
        }
Jim Blandy's avatar
Jim Blandy committed
826 827
      }
  else
828 829 830
    while (start > end)
      {
        /* The last character to check before the next obstacle.  */
831
	ptrdiff_t tem, ceiling_byte = end_byte;
832 833

        /* Consult the newline cache, if appropriate.  */
834
        if (newline_cache)
835
          {
836
            ptrdiff_t next_change;
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
	    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;
	      }
875 876

            /* Start should never be at or before end.  */
877 878
            if (start_byte <= ceiling_byte)
              start_byte = ceiling_byte + 1;
879 880 881

            /* Now the text before start is an unknown region, and
               next_change is the position of the next known region. */
882
            ceiling_byte = max (CHAR_TO_BYTE (next_change), ceiling_byte);
883
          }
884
	else if (start_byte == -1)
885
	  start_byte = CHAR_TO_BYTE (start);
886 887

        /* Stop scanning before the gap.  */
888 889
	tem = BUFFER_FLOOR_OF (start_byte - 1);
	ceiling_byte = max (tem, ceiling_byte);
890 891 892

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

895 896 897 898 899 900 901
	  /* 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)
902
            {
903 904
	      unsigned char *nl = memrchr (ceiling_addr, '\n', cursor);
	      prev = nl ? nl - ceiling_addr : -1;
905 906

              /* If we're looking for newlines, cache the fact that
907
                 this line's region is free of them. */
908
              if (newline_cache && cursor != prev + 1)
909
		{
910
		  know_region_cache (cache_buffer, newline_cache,
911 912 913 914
				     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);
915 916 917 918 919 920 921
		}

              if (! nl)
		break;

	      if (++count >= 0)
		{
922
		  if (bytepos)
923 924
		    *bytepos = ceiling_byte + prev + 1;
		  return BYTE_TO_CHAR (ceiling_byte + prev + 1);
925
		}
Paul Eggert's avatar
Paul Eggert committed
926 927
	      if (allow_quit)
		maybe_quit ();
928 929
            }

930
	  start_byte = ceiling_byte;
931
	  start = BYTE_TO_CHAR (start_byte);
932 933 934
        }
      }

935 936
  if (counted)
    *counted -= count;
937 938 939 940 941
  if (bytepos)
    {
      *bytepos = start_byte == -1 ? CHAR_TO_BYTE (start) : start_byte;
      eassert (*bytepos == CHAR_TO_BYTE (start));
    }
942
  return start;
Jim Blandy's avatar
Jim Blandy committed
943
}
944

945
/* Search for COUNT instances of a line boundary.