search.c 100 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-2016 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 <http://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"
Jim Blandy's avatar
Jim Blandy committed
32

Jim Blandy's avatar
Jim Blandy committed
33 34 35
#include <sys/types.h>
#include "regex.h"

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, 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
};
Jim Blandy's avatar
Jim Blandy committed
53

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

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


Jim Blandy's avatar
Jim Blandy committed
61 62 63 64 65 66 67
/* Every call to re_match, etc., must pass &search_regs as the regs
   argument unless you can show it is unnecessary (i.e., if re_match
   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
68 69 70
   been allocated by checking search_regs.num_regs.

   The regex code keeps track of whether it has allocated the search
71 72
   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
73 74 75 76 77
   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.  */
Jim Blandy's avatar
Jim Blandy committed
78 79
static struct re_registers search_regs;

Jim Blandy's avatar
Jim Blandy committed
80 81 82 83
/* 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.  */
static Lisp_Object last_thing_searched;
Jim Blandy's avatar
Jim Blandy committed
84

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

97
static _Noreturn void
98
matcher_overflow (void)
Jim Blandy's avatar
Jim Blandy committed
99 100 101 102
{
  error ("Stack overflow in regexp matcher");
}

103 104 105
/* 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.
106
   TRANSLATE is a translation table for ignoring case, or nil for none.
107 108
   POSIX is true if we want full backtracking (POSIX style) for this pattern.
   False means backtrack only enough to get a valid match.
109 110

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

112
static void
113 114
compile_pattern_1 (struct regexp_cache *cp, Lisp_Object pattern,
		   Lisp_Object translate, bool posix)
Jim Blandy's avatar
Jim Blandy committed
115
{
116
  const char *whitespace_regexp;
117
  char *val;
Jim Blandy's avatar
Jim Blandy committed
118

119
  cp->regexp = Qnil;
120
  cp->buf.translate = (! NILP (translate) ? translate : make_number (0));
121
  cp->posix = posix;
122
  cp->buf.multibyte = STRING_MULTIBYTE (pattern);
Kenichi Handa's avatar
Kenichi Handa committed
123
  cp->buf.charset_unibyte = charset_unibyte;
124 125 126 127 128
  if (STRINGP (Vsearch_spaces_regexp))
    cp->whitespace_regexp = Vsearch_spaces_regexp;
  else
    cp->whitespace_regexp = Qnil;

129 130 131 132 133
  /* rms: I think BLOCK_INPUT is not needed here any more,
     because regex.c defines malloc to call xmalloc.
     Using BLOCK_INPUT here means the debugger won't run if an error occurs.
     So let's turn it off.  */
  /*  BLOCK_INPUT;  */
134

135 136 137
  whitespace_regexp = STRINGP (Vsearch_spaces_regexp) ?
    SSDATA (Vsearch_spaces_regexp) : NULL;

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

141 142
  /* 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
143
  cp->syntax_table = cp->buf.used_syntax ? BVAR (current_buffer, syntax_table) : Qt;
144

145
  /* unblock_input ();  */
Jim Blandy's avatar
Jim Blandy committed
146
  if (val)
147
    xsignal1 (Qinvalid_regexp, build_string (val));
Jim Blandy's avatar
Jim Blandy committed
148

149 150 151
  cp->regexp = Fcopy_sequence (pattern);
}

152 153 154 155 156
/* Shrink each compiled regexp buffer in the cache
   to the size actually used right now.
   This is called from garbage collection.  */

void
157
shrink_regexp_cache (void)
158
{
159
  struct regexp_cache *cp;
160 161 162 163

  for (cp = searchbuf_head; cp != 0; cp = cp->next)
    {
      cp->buf.allocated = cp->buf.used;
164
      cp->buf.buffer = xrealloc (cp->buf.buffer, cp->buf.used);
165 166 167
    }
}

168 169
/* Clear the regexp cache w.r.t. a particular syntax table,
   because it was changed.
170 171 172 173
   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
174
clear_regexp_cache (void)
175 176 177 178
{
  int i;

  for (i = 0; i < REGEXP_CACHE_SIZE; ++i)
179 180
    /* It's tempting to compare with the syntax-table we've actually changed,
       but it's not sufficient because char-table inheritance means that
181 182 183
       modifying one syntax-table can change others at the same time.  */
    if (!EQ (searchbufs[i].syntax_table, Qt))
      searchbufs[i].regexp = Qnil;
184 185
}

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

struct re_pattern_buffer *
198
compile_pattern (Lisp_Object pattern, struct re_registers *regp,
199
		 Lisp_Object translate, bool posix, bool multibyte)
200 201 202 203 204 205
{
  struct regexp_cache *cp, **cpp;

  for (cpp = &searchbuf_head; ; cpp = &cp->next)
    {
      cp = *cpp;
206 207
      /* 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
208 209 210
	 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.  */
211
      if (NILP (cp->regexp))
212
	goto compile_it;
213
      if (SCHARS (cp->regexp) == SCHARS (pattern)
214
	  && STRING_MULTIBYTE (cp->regexp) == STRING_MULTIBYTE (pattern)
215
	  && !NILP (Fstring_equal (cp->regexp, pattern))
216
	  && EQ (cp->buf.translate, (! NILP (translate) ? translate : make_number (0)))
Karl Heuer's avatar
Karl Heuer committed
217
	  && cp->posix == posix
218
	  && (EQ (cp->syntax_table, Qt)
Tom Tromey's avatar
Tom Tromey committed
219
	      || EQ (cp->syntax_table, BVAR (current_buffer, syntax_table)))
Kenichi Handa's avatar
Kenichi Handa committed
220 221
	  && !NILP (Fequal (cp->whitespace_regexp, Vsearch_spaces_regexp))
	  && cp->buf.charset_unibyte == charset_unibyte)
222 223
	break;

224 225 226
      /* 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.  */
227 228
      if (cp->next == 0)
	{
229
	compile_it:
230
	  compile_pattern_1 (cp, pattern, translate, posix);
231 232 233 234 235 236 237 238 239 240
	  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
241

242 243 244 245 246
  /* 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
247
  /* The compiled pattern can be used both for multibyte and unibyte
Kenichi Handa's avatar
Kenichi Handa committed
248 249 250
     target.  But, we have to tell which the pattern is used for. */
  cp->buf.target_multibyte = multibyte;

251
  return &cp->buf;
Jim Blandy's avatar
Jim Blandy committed
252 253 254
}


255
static Lisp_Object
256
looking_at_1 (Lisp_Object string, bool posix)
Jim Blandy's avatar
Jim Blandy committed
257 258 259
{
  Lisp_Object val;
  unsigned char *p1, *p2;
260 261
  ptrdiff_t s1, s2;
  register ptrdiff_t i;
262
  struct re_pattern_buffer *bufp;
Jim Blandy's avatar
Jim Blandy committed
263

264 265 266
  if (running_asynch_code)
    save_search_regs ();

267
  /* This is so set_image_of_range_1 in regex.c can find the EQV table.  */
268
  set_char_table_extras (BVAR (current_buffer, case_canon_table), 2,
269
			 BVAR (current_buffer, case_eqv_table));
270

271
  CHECK_STRING (string);
272 273 274
  bufp = compile_pattern (string,
			  (NILP (Vinhibit_changing_match_data)
			   ? &search_regs : NULL),
Tom Tromey's avatar
Tom Tromey committed
275 276
			  (!NILP (BVAR (current_buffer, case_fold_search))
			   ? BVAR (current_buffer, case_canon_table) : Qnil),
277
			  posix,
Tom Tromey's avatar
Tom Tromey committed
278
			  !NILP (BVAR (current_buffer, enable_multibyte_characters)));
Jim Blandy's avatar
Jim Blandy committed
279 280 281 282 283 284 285 286

  immediate_quit = 1;
  QUIT;			/* Do a pending quit right away, to avoid paradoxical behavior */

  /* Get pointers and sizes of the two strings
     that make up the visible portion of the buffer. */

  p1 = BEGV_ADDR;
287
  s1 = GPT_BYTE - BEGV_BYTE;
Jim Blandy's avatar
Jim Blandy committed
288
  p2 = GAP_END_ADDR;
289
  s2 = ZV_BYTE - GPT_BYTE;
Jim Blandy's avatar
Jim Blandy committed
290 291 292
  if (s1 < 0)
    {
      p2 = p1;
293
      s2 = ZV_BYTE - BEGV_BYTE;
Jim Blandy's avatar
Jim Blandy committed
294 295 296 297
      s1 = 0;
    }
  if (s2 < 0)
    {
298
      s1 = ZV_BYTE - BEGV_BYTE;
Jim Blandy's avatar
Jim Blandy committed
299 300
      s2 = 0;
    }
301 302

  re_match_object = Qnil;
303

304
  i = re_match_2 (bufp, (char *) p1, s1, (char *) p2, s2,
305 306 307
		  PT_BYTE - BEGV_BYTE,
		  (NILP (Vinhibit_changing_match_data)
		   ? &search_regs : NULL),
308
		  ZV_BYTE - BEGV_BYTE);
309
  immediate_quit = 0;
310

Jim Blandy's avatar
Jim Blandy committed
311 312 313
  if (i == -2)
    matcher_overflow ();

314
  val = (i >= 0 ? Qt : Qnil);
315
  if (NILP (Vinhibit_changing_match_data) && i >= 0)
316
  {
317 318 319 320 321
    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);
322 323 324 325
         search_regs.end[i]
           = BYTE_TO_CHAR (search_regs.end[i] + BEGV_BYTE);
       }
    /* Set last_thing_searched only when match data is changed.  */
326
    XSETBUFFER (last_thing_searched, current_buffer);
327
  }
328

Jim Blandy's avatar
Jim Blandy committed
329 330 331
  return val;
}

332
DEFUN ("looking-at", Flooking_at, Slooking_at, 1, 1, 0,
333 334 335 336
       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
337
  (Lisp_Object regexp)
338
{
339
  return looking_at_1 (regexp, 0);
340 341 342
}

DEFUN ("posix-looking-at", Fposix_looking_at, Sposix_looking_at, 1, 1, 0,
343 344 345 346 347
       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
348
  (Lisp_Object regexp)
349
{
350
  return looking_at_1 (regexp, 1);
351 352 353
}

static Lisp_Object
354 355
string_match_1 (Lisp_Object regexp, Lisp_Object string, Lisp_Object start,
		bool posix)
Jim Blandy's avatar
Jim Blandy committed
356
{
357
  ptrdiff_t val;
358
  struct re_pattern_buffer *bufp;
359 360
  EMACS_INT pos;
  ptrdiff_t pos_byte, i;
Jim Blandy's avatar
Jim Blandy committed
361

362 363 364
  if (running_asynch_code)
    save_search_regs ();

365 366
  CHECK_STRING (regexp);
  CHECK_STRING (string);
Jim Blandy's avatar
Jim Blandy committed
367 368

  if (NILP (start))
369
    pos = 0, pos_byte = 0;
Jim Blandy's avatar
Jim Blandy committed
370 371
  else
    {
372
      ptrdiff_t len = SCHARS (string);
Jim Blandy's avatar
Jim Blandy committed
373

374
      CHECK_NUMBER (start);
375 376 377 378
      pos = XINT (start);
      if (pos < 0 && -pos <= len)
	pos = len + pos;
      else if (0 > pos || pos > len)
Jim Blandy's avatar
Jim Blandy committed
379
	args_out_of_range (string, start);
380
      pos_byte = string_char_to_byte (string, pos);
Jim Blandy's avatar
Jim Blandy committed
381 382
    }

383
  /* This is so set_image_of_range_1 in regex.c can find the EQV table.  */
384
  set_char_table_extras (BVAR (current_buffer, case_canon_table), 2,
385
			 BVAR (current_buffer, case_eqv_table));
386

387 388 389
  bufp = compile_pattern (regexp,
			  (NILP (Vinhibit_changing_match_data)
			   ? &search_regs : NULL),
Tom Tromey's avatar
Tom Tromey committed
390 391
			  (!NILP (BVAR (current_buffer, case_fold_search))
			   ? BVAR (current_buffer, case_canon_table) : Qnil),
392 393
			  posix,
			  STRING_MULTIBYTE (string));
Jim Blandy's avatar
Jim Blandy committed
394
  immediate_quit = 1;
395
  re_match_object = string;
396

397
  val = re_search (bufp, SSDATA (string),
398 399
		   SBYTES (string), pos_byte,
		   SBYTES (string) - pos_byte,
400 401
		   (NILP (Vinhibit_changing_match_data)
		    ? &search_regs : NULL));
Jim Blandy's avatar
Jim Blandy committed
402
  immediate_quit = 0;
403 404 405 406 407

  /* 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
408 409 410
  if (val == -2)
    matcher_overflow ();
  if (val < 0) return Qnil;
411

412 413 414 415 416 417 418 419 420
  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]);
	}
421 422

  return make_number (string_byte_to_char (string, val));
Jim Blandy's avatar
Jim Blandy committed
423
}
Richard M. Stallman's avatar
Richard M. Stallman committed
424

Paul Eggert's avatar
Paul Eggert committed
425
DEFUN ("string-match", Fstring_match, Sstring_match, 2, 3, 0,
426
       doc: /* Return index of start of first match for REGEXP in STRING, or nil.
Richard M. Stallman's avatar
Richard M. Stallman committed
427
Matching ignores case if `case-fold-search' is non-nil.
428 429 430
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
431 432 433 434
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
435
  (Lisp_Object regexp, Lisp_Object string, Lisp_Object start)
436 437 438 439 440
{
  return string_match_1 (regexp, string, start, 0);
}

DEFUN ("posix-string-match", Fposix_string_match, Sposix_string_match, 2, 3, 0,
441 442 443 444 445 446 447
       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
448
  (Lisp_Object regexp, Lisp_Object string, Lisp_Object start)
449 450 451 452
{
  return string_match_1 (regexp, string, start, 1);
}

453 454 455
/* 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
456

457
ptrdiff_t
458 459
fast_string_match_internal (Lisp_Object regexp, Lisp_Object string,
			    Lisp_Object table)
Richard M. Stallman's avatar
Richard M. Stallman committed
460
{
461
  ptrdiff_t val;
462
  struct re_pattern_buffer *bufp;
Richard M. Stallman's avatar
Richard M. Stallman committed
463

464
  bufp = compile_pattern (regexp, 0, table,
465
			  0, STRING_MULTIBYTE (string));
Richard M. Stallman's avatar
Richard M. Stallman committed
466
  immediate_quit = 1;
467
  re_match_object = string;
468

469
  val = re_search (bufp, SSDATA (string),
470 471
		   SBYTES (string), 0,
		   SBYTES (string), 0);
Richard M. Stallman's avatar
Richard M. Stallman committed
472 473 474
  immediate_quit = 0;
  return val;
}
Karl Heuer's avatar
Karl Heuer committed
475 476 477

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

481
ptrdiff_t
482 483
fast_c_string_match_ignore_case (Lisp_Object regexp,
				 const char *string, ptrdiff_t len)
Karl Heuer's avatar
Karl Heuer committed
484
{
485
  ptrdiff_t val;
Karl Heuer's avatar
Karl Heuer committed
486 487
  struct re_pattern_buffer *bufp;

488
  regexp = string_make_unibyte (regexp);
489
  re_match_object = Qt;
Karl Heuer's avatar
Karl Heuer committed
490
  bufp = compile_pattern (regexp, 0,
491
			  Vascii_canon_table, 0,
492
			  0);
Karl Heuer's avatar
Karl Heuer committed
493 494 495 496 497
  immediate_quit = 1;
  val = re_search (bufp, string, len, 0, len, 0);
  immediate_quit = 0;
  return val;
}
498

499
/* Match REGEXP against the characters after POS to LIMIT, and return
500 501 502 503 504
   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.  */

505
ptrdiff_t
506 507
fast_looking_at (Lisp_Object regexp, ptrdiff_t pos, ptrdiff_t pos_byte,
		 ptrdiff_t limit, ptrdiff_t limit_byte, Lisp_Object string)
508
{
509
  bool multibyte;
510 511
  struct re_pattern_buffer *buf;
  unsigned char *p1, *p2;
512 513
  ptrdiff_t s1, s2;
  ptrdiff_t len;
Juanma Barranquero's avatar
Juanma Barranquero committed
514

515 516 517 518 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
  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);
      re_match_object = 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;
	}
      re_match_object = Qnil;
Tom Tromey's avatar
Tom Tromey committed
552
      multibyte = ! NILP (BVAR (current_buffer, enable_multibyte_characters));
553 554 555 556 557 558 559 560 561 562 563
    }

  buf = compile_pattern (regexp, 0, Qnil, 0, multibyte);
  immediate_quit = 1;
  len = re_match_2 (buf, (char *) p1, s1, (char *) p2, s2,
		    pos_byte, NULL, limit_byte);
  immediate_quit = 0;

  return len;
}

564 565 566

/* The newline cache: remembering which sections of text have no newlines.  */

567
/* If the user has requested the long scans caching, make sure it's on.
568 569 570
   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.  */
571
static struct region_cache *
572
newline_cache_on_off (struct buffer *buf)
573
{
574 575 576 577 578 579 580 581 582 583 584 585 586 587
  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.  */
588
  if (NILP (BVAR (buf, cache_long_scans)))
589
    {
590 591 592 593 594 595 596 597 598 599 600
      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;
601 602 603
    }
  else
    {
604 605 606 607 608 609 610 611
      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;
612 613 614 615
    }
}


616
/* Search for COUNT newlines between START/START_BYTE and END/END_BYTE.
617 618 619 620 621 622 623 624

   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
   direction indicated by COUNT.
Jim Blandy's avatar
Jim Blandy committed
625 626

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

630
   If we don't find COUNT instances before reaching END, set *SHORTAGE
631
   to the number of newlines left unfound, and return END.
Jim Blandy's avatar
Jim Blandy committed
632

633 634 635
   If BYTEPOS is not NULL, set *BYTEPOS to the byte position corresponding
   to the returned character position.

636
   If ALLOW_QUIT, set immediate_quit.  That's good to do
637 638
   except when inside redisplay.  */

639
ptrdiff_t
640 641 642
find_newline (ptrdiff_t start, ptrdiff_t start_byte, ptrdiff_t end,
	      ptrdiff_t end_byte, ptrdiff_t count, ptrdiff_t *shortage,
	      ptrdiff_t *bytepos, bool allow_quit)
Jim Blandy's avatar
Jim Blandy committed
643
{
644
  struct region_cache *newline_cache;
645
  int direction;
646
  struct buffer *cache_buffer;
Jim Blandy's avatar
Jim Blandy committed
647

648 649 650
  if (count > 0)
    {
      direction = 1;
651 652
      if (!end)
	end = ZV, end_byte = ZV_BYTE;
653 654 655 656
    }
  else
    {
      direction = -1;
657
      if (!end)
658
	end = BEGV, end_byte = BEGV_BYTE;
659
    }
660 661
  if (end_byte == -1)
    end_byte = CHAR_TO_BYTE (end);
Jim Blandy's avatar
Jim Blandy committed
662

663 664 665 666 667
  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
668 669 670 671

  if (shortage != 0)
    *shortage = 0;

672
  immediate_quit = allow_quit;
Jim Blandy's avatar
Jim Blandy committed
673

Jim Blandy's avatar
Jim Blandy committed
674
  if (count > 0)
675
    while (start != end)
Jim Blandy's avatar
Jim Blandy committed
676
      {
677 678 679 680 681
        /* 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.  */
682
	ptrdiff_t tem, ceiling_byte = end_byte - 1;
683

684 685
        /* If we're using the newline cache, consult it to see whether
           we can avoid some scanning.  */
686
        if (newline_cache)
687
          {
688
            ptrdiff_t next_change;
689 690
	    int result = 1;

691
            immediate_quit = 0;
692 693 694 695 696 697 698 699
            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
            immediate_quit = allow_quit;
745

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

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

        /* 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.  */
761 762
	tem = BUFFER_CEILING_OF (start_byte);
	ceiling_byte = min (tem, ceiling_byte);
763 764

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

769 770 771 772 773 774 775
	  /* 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)
	    {
776
              /* The dumb loop.  */
777 778
	      unsigned char *nl = memchr (lim_addr + cursor, '\n', - cursor);
	      next = nl ? nl - lim_addr : 0;
779

780 781 782
              /* 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)
783
		{
784
		  know_region_cache (cache_buffer, newline_cache,
785 786 787 788
				     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;
789 790 791 792
		}

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

	      if (--count == 0)
		{
		  immediate_quit = 0;
798
		  if (bytepos)
799 800
		    *bytepos = lim_byte + next;
		  return BYTE_TO_CHAR (lim_byte + next);
801
		}
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
	    int result = 1;

820
            immediate_quit = 0;
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 856
            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;
	      }
857
            immediate_quit = allow_quit;
858 859

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

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

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

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

878 879 880 881 882 883 884
	  /* 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)
885
            {
886 887
	      unsigned char *nl = memrchr (ceiling_addr, '\n', cursor);
	      prev = nl ? nl - ceiling_addr : -1;
888 889

              /* If we're looking for newlines, cache the fact that