1 /* String search routines for GNU Emacs.
3 Copyright (C) 1985-1987, 1993-1994, 1997-1999, 2001-2019 Free Software
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or (at
11 your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 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/>. */
25 #include "character.h"
29 #include "region-cache.h"
30 #include "blockinput.h"
31 #include "intervals.h"
35 #define REGEXP_CACHE_SIZE 20
37 /* If the regexp is non-nil, then the buffer contains the compiled form
38 of that regexp, suitable for searching. */
41 struct regexp_cache
*next
;
42 Lisp_Object regexp
, f_whitespace_regexp
;
43 /* Syntax table for which the regexp applies. We need this because
44 of character classes. If this is t, then the compiled pattern is valid
45 for any syntax-table. */
46 Lisp_Object syntax_table
;
47 struct re_pattern_buffer buf
;
49 /* True means regexp was compiled to do full POSIX backtracking. */
53 /* The instances of that struct. */
54 static struct regexp_cache searchbufs
[REGEXP_CACHE_SIZE
];
56 /* The head of the linked list; points to the most recently used buffer. */
57 static struct regexp_cache
*searchbuf_head
;
60 /* Every call to re_match, etc., must pass &search_regs as the regs
61 argument unless you can show it is unnecessary (i.e., if re_match
62 is certainly going to be called again before region-around-match
65 Since the registers are now dynamically allocated, we need to make
66 sure not to refer to the Nth register before checking that it has
67 been allocated by checking search_regs.num_regs.
69 The regex code keeps track of whether it has allocated the search
70 buffer using bits in the re_pattern_buffer. This means that whenever
71 you compile a new pattern, it completely forgets whether it has
72 allocated any registers, and will allocate new registers the next
73 time you call a searching or matching function. Therefore, we need
74 to call re_set_registers after compiling a new pattern or after
75 setting the match registers, so that the regex functions will be
76 able to free or re-allocate it properly. */
77 /* static struct re_registers search_regs; */
79 /* The buffer in which the last search was performed, or
80 Qt if the last search was done in a string;
81 Qnil if no searching has been done yet. */
82 /* static Lisp_Object last_thing_searched; */
84 static void set_search_regs (ptrdiff_t, ptrdiff_t);
85 static void save_search_regs (void);
86 static EMACS_INT
simple_search (EMACS_INT
, unsigned char *, ptrdiff_t,
87 ptrdiff_t, Lisp_Object
, ptrdiff_t, ptrdiff_t,
88 ptrdiff_t, ptrdiff_t);
89 static EMACS_INT
boyer_moore (EMACS_INT
, unsigned char *, ptrdiff_t,
90 Lisp_Object
, Lisp_Object
, ptrdiff_t,
92 static EMACS_INT
search_buffer (Lisp_Object
, ptrdiff_t, ptrdiff_t,
93 ptrdiff_t, ptrdiff_t, EMACS_INT
, int,
94 Lisp_Object
, Lisp_Object
, bool);
97 matcher_overflow (void)
99 error ("Stack overflow in regexp matcher");
103 freeze_buffer_relocation (void)
106 /* Prevent ralloc.c from relocating the current buffer while
108 r_alloc_inhibit_buffer_relocation (1);
109 record_unwind_protect_int (r_alloc_inhibit_buffer_relocation
, 0);
114 thaw_buffer_relocation (void)
117 unbind_to (SPECPDL_INDEX () - 1, Qnil
);
121 /* Compile a regexp and signal a Lisp error if anything goes wrong.
122 PATTERN is the pattern to compile.
123 CP is the place to put the result.
124 TRANSLATE is a translation table for ignoring case, or nil for none.
125 POSIX is true if we want full backtracking (POSIX style) for this pattern.
126 False means backtrack only enough to get a valid match.
128 The behavior also depends on Vsearch_spaces_regexp. */
131 compile_pattern_1 (struct regexp_cache
*cp
, Lisp_Object pattern
,
132 Lisp_Object translate
, bool posix
)
134 const char *whitespace_regexp
;
138 cp
->buf
.translate
= (! NILP (translate
) ? translate
: make_number (0));
140 cp
->buf
.multibyte
= STRING_MULTIBYTE (pattern
);
141 cp
->buf
.charset_unibyte
= charset_unibyte
;
142 if (STRINGP (Vsearch_spaces_regexp
))
143 cp
->f_whitespace_regexp
= Vsearch_spaces_regexp
;
145 cp
->f_whitespace_regexp
= Qnil
;
147 /* rms: I think BLOCK_INPUT is not needed here any more,
148 because regex.c defines malloc to call xmalloc.
149 Using BLOCK_INPUT here means the debugger won't run if an error occurs.
150 So let's turn it off. */
153 whitespace_regexp
= STRINGP (Vsearch_spaces_regexp
) ?
154 SSDATA (Vsearch_spaces_regexp
) : NULL
;
156 val
= (char *) re_compile_pattern (SSDATA (pattern
), SBYTES (pattern
),
157 posix
, whitespace_regexp
, &cp
->buf
);
159 /* If the compiled pattern hard codes some of the contents of the
160 syntax-table, it can only be reused with *this* syntax table. */
161 cp
->syntax_table
= cp
->buf
.used_syntax
? BVAR (current_buffer
, syntax_table
) : Qt
;
163 /* unblock_input (); */
165 xsignal1 (Qinvalid_regexp
, build_string (val
));
167 cp
->regexp
= Fcopy_sequence (pattern
);
170 /* Shrink each compiled regexp buffer in the cache
171 to the size actually used right now.
172 This is called from garbage collection. */
175 shrink_regexp_cache (void)
177 struct regexp_cache
*cp
;
179 for (cp
= searchbuf_head
; cp
!= 0; cp
= cp
->next
)
181 cp
->buf
.allocated
= cp
->buf
.used
;
182 cp
->buf
.buffer
= xrealloc (cp
->buf
.buffer
, cp
->buf
.used
);
186 /* Clear the regexp cache w.r.t. a particular syntax table,
187 because it was changed.
188 There is no danger of memory leak here because re_compile_pattern
189 automagically manages the memory in each re_pattern_buffer struct,
190 based on its `allocated' and `buffer' values. */
192 clear_regexp_cache (void)
196 for (i
= 0; i
< REGEXP_CACHE_SIZE
; ++i
)
197 /* It's tempting to compare with the syntax-table we've actually changed,
198 but it's not sufficient because char-table inheritance means that
199 modifying one syntax-table can change others at the same time. */
200 if (!EQ (searchbufs
[i
].syntax_table
, Qt
))
201 searchbufs
[i
].regexp
= Qnil
;
204 /* Compile a regexp if necessary, but first check to see if there's one in
206 PATTERN is the pattern to compile.
207 TRANSLATE is a translation table for ignoring case, or nil for none.
208 REGP is the structure that says where to store the "register"
209 values that will result from matching this pattern.
210 If it is 0, we should compile the pattern not to record any
211 subexpression bounds.
212 POSIX is true if we want full backtracking (POSIX style) for this pattern.
213 False means backtrack only enough to get a valid match. */
215 struct re_pattern_buffer
*
216 compile_pattern (Lisp_Object pattern
, struct re_registers
*regp
,
217 Lisp_Object translate
, bool posix
, bool multibyte
)
219 struct regexp_cache
*cp
, **cpp
;
221 for (cpp
= &searchbuf_head
; ; cpp
= &cp
->next
)
224 /* Entries are initialized to nil, and may be set to nil by
225 compile_pattern_1 if the pattern isn't valid. Don't apply
226 string accessors in those cases. However, compile_pattern_1
227 is only applied to the cache entry we pick here to reuse. So
228 nil should never appear before a non-nil entry. */
229 if (NILP (cp
->regexp
))
231 if (SCHARS (cp
->regexp
) == SCHARS (pattern
)
232 && STRING_MULTIBYTE (cp
->regexp
) == STRING_MULTIBYTE (pattern
)
233 && !NILP (Fstring_equal (cp
->regexp
, pattern
))
234 && EQ (cp
->buf
.translate
, (! NILP (translate
) ? translate
: make_number (0)))
235 && cp
->posix
== posix
236 && (EQ (cp
->syntax_table
, Qt
)
237 || EQ (cp
->syntax_table
, BVAR (current_buffer
, syntax_table
)))
238 && !NILP (Fequal (cp
->f_whitespace_regexp
, Vsearch_spaces_regexp
))
239 && cp
->buf
.charset_unibyte
== charset_unibyte
)
242 /* If we're at the end of the cache, compile into the nil cell
243 we found, or the last (least recently used) cell with a
248 compile_pattern_1 (cp
, pattern
, translate
, posix
);
253 /* When we get here, cp (aka *cpp) contains the compiled pattern,
254 either because we found it in the cache or because we just compiled it.
255 Move it to the front of the queue to mark it as most recently used. */
257 cp
->next
= searchbuf_head
;
260 /* Advise the searching functions about the space we have allocated
261 for register data. */
263 re_set_registers (&cp
->buf
, regp
, regp
->num_regs
, regp
->start
, regp
->end
);
265 /* The compiled pattern can be used both for multibyte and unibyte
266 target. But, we have to tell which the pattern is used for. */
267 cp
->buf
.target_multibyte
= multibyte
;
274 looking_at_1 (Lisp_Object string
, bool posix
)
277 unsigned char *p1
, *p2
;
279 register ptrdiff_t i
;
280 struct re_pattern_buffer
*bufp
;
282 if (running_asynch_code
)
285 /* This is so set_image_of_range_1 in regex.c can find the EQV table. */
286 set_char_table_extras (BVAR (current_buffer
, case_canon_table
), 2,
287 BVAR (current_buffer
, case_eqv_table
));
289 CHECK_STRING (string
);
290 bufp
= compile_pattern (string
,
291 (NILP (Vinhibit_changing_match_data
)
292 ? &search_regs
: NULL
),
293 (!NILP (BVAR (current_buffer
, case_fold_search
))
294 ? BVAR (current_buffer
, case_canon_table
) : Qnil
),
296 !NILP (BVAR (current_buffer
, enable_multibyte_characters
)));
298 /* Do a pending quit right away, to avoid paradoxical behavior */
301 /* Get pointers and sizes of the two strings
302 that make up the visible portion of the buffer. */
305 s1
= GPT_BYTE
- BEGV_BYTE
;
307 s2
= ZV_BYTE
- GPT_BYTE
;
311 s2
= ZV_BYTE
- BEGV_BYTE
;
316 s1
= ZV_BYTE
- BEGV_BYTE
;
320 re_match_object
= Qnil
;
322 freeze_buffer_relocation ();
323 i
= re_match_2 (bufp
, (char *) p1
, s1
, (char *) p2
, s2
,
325 (NILP (Vinhibit_changing_match_data
)
326 ? &search_regs
: NULL
),
327 ZV_BYTE
- BEGV_BYTE
);
328 thaw_buffer_relocation ();
333 val
= (i
>= 0 ? Qt
: Qnil
);
334 if (NILP (Vinhibit_changing_match_data
) && i
>= 0)
336 for (i
= 0; i
< search_regs
.num_regs
; i
++)
337 if (search_regs
.start
[i
] >= 0)
340 = BYTE_TO_CHAR (search_regs
.start
[i
] + BEGV_BYTE
);
342 = BYTE_TO_CHAR (search_regs
.end
[i
] + BEGV_BYTE
);
344 /* Set last_thing_searched only when match data is changed. */
345 XSETBUFFER (last_thing_searched
, current_buffer
);
351 DEFUN ("looking-at", Flooking_at
, Slooking_at
, 1, 1, 0,
352 doc
: /* Return t if text after point matches regular expression REGEXP.
353 This function modifies the match data that `match-beginning',
354 `match-end' and `match-data' access; save and restore the match
355 data if you want to preserve them. */)
358 return looking_at_1 (regexp
, 0);
361 DEFUN ("posix-looking-at", Fposix_looking_at
, Sposix_looking_at
, 1, 1, 0,
362 doc
: /* Return t if text after point matches regular expression REGEXP.
363 Find the longest match, in accord with Posix regular expression rules.
364 This function modifies the match data that `match-beginning',
365 `match-end' and `match-data' access; save and restore the match
366 data if you want to preserve them. */)
369 return looking_at_1 (regexp
, 1);
373 string_match_1 (Lisp_Object regexp
, Lisp_Object string
, Lisp_Object start
,
377 struct re_pattern_buffer
*bufp
;
379 ptrdiff_t pos_byte
, i
;
381 if (running_asynch_code
)
384 CHECK_STRING (regexp
);
385 CHECK_STRING (string
);
388 pos
= 0, pos_byte
= 0;
391 ptrdiff_t len
= SCHARS (string
);
393 CHECK_NUMBER (start
);
395 if (pos
< 0 && -pos
<= len
)
397 else if (0 > pos
|| pos
> len
)
398 args_out_of_range (string
, start
);
399 pos_byte
= string_char_to_byte (string
, pos
);
402 /* This is so set_image_of_range_1 in regex.c can find the EQV table. */
403 set_char_table_extras (BVAR (current_buffer
, case_canon_table
), 2,
404 BVAR (current_buffer
, case_eqv_table
));
406 bufp
= compile_pattern (regexp
,
407 (NILP (Vinhibit_changing_match_data
)
408 ? &search_regs
: NULL
),
409 (!NILP (BVAR (current_buffer
, case_fold_search
))
410 ? BVAR (current_buffer
, case_canon_table
) : Qnil
),
412 STRING_MULTIBYTE (string
));
413 re_match_object
= string
;
415 val
= re_search (bufp
, SSDATA (string
),
416 SBYTES (string
), pos_byte
,
417 SBYTES (string
) - pos_byte
,
418 (NILP (Vinhibit_changing_match_data
)
419 ? &search_regs
: NULL
));
421 /* Set last_thing_searched only when match data is changed. */
422 if (NILP (Vinhibit_changing_match_data
))
423 last_thing_searched
= Qt
;
427 if (val
< 0) return Qnil
;
429 if (NILP (Vinhibit_changing_match_data
))
430 for (i
= 0; i
< search_regs
.num_regs
; i
++)
431 if (search_regs
.start
[i
] >= 0)
434 = string_byte_to_char (string
, search_regs
.start
[i
]);
436 = string_byte_to_char (string
, search_regs
.end
[i
]);
439 return make_number (string_byte_to_char (string
, val
));
442 DEFUN ("string-match", Fstring_match
, Sstring_match
, 2, 3, 0,
443 doc
: /* Return index of start of first match for REGEXP in STRING, or nil.
444 Matching ignores case if `case-fold-search' is non-nil.
445 If third arg START is non-nil, start search at that index in STRING.
446 For index of first char beyond the match, do (match-end 0).
447 `match-end' and `match-beginning' also give indices of substrings
448 matched by parenthesis constructs in the pattern.
450 You can use the function `match-string' to extract the substrings
451 matched by the parenthesis constructions in REGEXP. */)
452 (Lisp_Object regexp
, Lisp_Object string
, Lisp_Object start
)
454 return string_match_1 (regexp
, string
, start
, 0);
457 DEFUN ("posix-string-match", Fposix_string_match
, Sposix_string_match
, 2, 3, 0,
458 doc
: /* Return index of start of first match for REGEXP in STRING, or nil.
459 Find the longest match, in accord with Posix regular expression rules.
460 Case is ignored if `case-fold-search' is non-nil in the current buffer.
461 If third arg START is non-nil, start search at that index in STRING.
462 For index of first char beyond the match, do (match-end 0).
463 `match-end' and `match-beginning' also give indices of substrings
464 matched by parenthesis constructs in the pattern. */)
465 (Lisp_Object regexp
, Lisp_Object string
, Lisp_Object start
)
467 return string_match_1 (regexp
, string
, start
, 1);
470 /* Match REGEXP against STRING using translation table TABLE,
471 searching all of STRING, and return the index of the match,
472 or negative on failure. This does not clobber the match data. */
475 fast_string_match_internal (Lisp_Object regexp
, Lisp_Object string
,
479 struct re_pattern_buffer
*bufp
;
481 bufp
= compile_pattern (regexp
, 0, table
,
482 0, STRING_MULTIBYTE (string
));
483 re_match_object
= string
;
485 val
= re_search (bufp
, SSDATA (string
),
491 /* Match REGEXP against STRING, searching all of STRING ignoring case,
492 and return the index of the match, or negative on failure.
493 This does not clobber the match data.
494 We assume that STRING contains single-byte characters. */
497 fast_c_string_match_ignore_case (Lisp_Object regexp
,
498 const char *string
, ptrdiff_t len
)
501 struct re_pattern_buffer
*bufp
;
503 regexp
= string_make_unibyte (regexp
);
504 re_match_object
= Qt
;
505 bufp
= compile_pattern (regexp
, 0,
506 Vascii_canon_table
, 0,
508 val
= re_search (bufp
, string
, len
, 0, len
, 0);
512 /* Match REGEXP against the characters after POS to LIMIT, and return
513 the number of matched characters. If STRING is non-nil, match
514 against the characters in it. In that case, POS and LIMIT are
515 indices into the string. This function doesn't modify the match
519 fast_looking_at (Lisp_Object regexp
, ptrdiff_t pos
, ptrdiff_t pos_byte
,
520 ptrdiff_t limit
, ptrdiff_t limit_byte
, Lisp_Object string
)
523 struct re_pattern_buffer
*buf
;
524 unsigned char *p1
, *p2
;
528 if (STRINGP (string
))
531 pos_byte
= string_char_to_byte (string
, pos
);
533 limit_byte
= string_char_to_byte (string
, limit
);
537 s2
= SBYTES (string
);
538 re_match_object
= string
;
539 multibyte
= STRING_MULTIBYTE (string
);
544 pos_byte
= CHAR_TO_BYTE (pos
);
546 limit_byte
= CHAR_TO_BYTE (limit
);
547 pos_byte
-= BEGV_BYTE
;
548 limit_byte
-= BEGV_BYTE
;
550 s1
= GPT_BYTE
- BEGV_BYTE
;
552 s2
= ZV_BYTE
- GPT_BYTE
;
556 s2
= ZV_BYTE
- BEGV_BYTE
;
561 s1
= ZV_BYTE
- BEGV_BYTE
;
564 re_match_object
= Qnil
;
565 multibyte
= ! NILP (BVAR (current_buffer
, enable_multibyte_characters
));
568 buf
= compile_pattern (regexp
, 0, Qnil
, 0, multibyte
);
569 freeze_buffer_relocation ();
570 len
= re_match_2 (buf
, (char *) p1
, s1
, (char *) p2
, s2
,
571 pos_byte
, NULL
, limit_byte
);
572 thaw_buffer_relocation ();
578 /* The newline cache: remembering which sections of text have no newlines. */
580 /* If the user has requested the long scans caching, make sure it's on.
581 Otherwise, make sure it's off.
582 This is our cheezy way of associating an action with the change of
583 state of a buffer-local variable. */
584 static struct region_cache
*
585 newline_cache_on_off (struct buffer
*buf
)
587 struct buffer
*base_buf
= buf
;
588 bool indirect_p
= false;
590 if (buf
->base_buffer
)
592 base_buf
= buf
->base_buffer
;
596 /* Don't turn on or off the cache in the base buffer, if the value
597 of cache-long-scans of the base buffer is inconsistent with that.
598 This is because doing so will just make the cache pure overhead,
599 since if we turn it on via indirect buffer, it will be
600 immediately turned off by its base buffer. */
601 if (NILP (BVAR (buf
, cache_long_scans
)))
604 || NILP (BVAR (base_buf
, cache_long_scans
)))
606 /* It should be off. */
607 if (base_buf
->newline_cache
)
609 free_region_cache (base_buf
->newline_cache
);
610 base_buf
->newline_cache
= 0;
618 || !NILP (BVAR (base_buf
, cache_long_scans
)))
620 /* It should be on. */
621 if (base_buf
->newline_cache
== 0)
622 base_buf
->newline_cache
= new_region_cache ();
624 return base_buf
->newline_cache
;
629 /* Search for COUNT newlines between START/START_BYTE and END/END_BYTE.
631 If COUNT is positive, search forwards; END must be >= START.
632 If COUNT is negative, search backwards for the -COUNTth instance;
633 END must be <= START.
634 If COUNT is zero, do anything you please; run rogue, for all I care.
636 If END is zero, use BEGV or ZV instead, as appropriate for the
637 direction indicated by COUNT.
639 If we find COUNT instances, set *SHORTAGE to zero, and return the
640 position past the COUNTth match. Note that for reverse motion
641 this is not the same as the usual convention for Emacs motion commands.
643 If we don't find COUNT instances before reaching END, set *SHORTAGE
644 to the number of newlines left unfound, and return END.
646 If BYTEPOS is not NULL, set *BYTEPOS to the byte position corresponding
647 to the returned character position.
649 If ALLOW_QUIT, check for quitting. That's good to do
650 except when inside redisplay. */
653 find_newline (ptrdiff_t start
, ptrdiff_t start_byte
, ptrdiff_t end
,
654 ptrdiff_t end_byte
, ptrdiff_t count
, ptrdiff_t *shortage
,
655 ptrdiff_t *bytepos
, bool allow_quit
)
657 struct region_cache
*newline_cache
;
659 struct buffer
*cache_buffer
;
665 end
= ZV
, end_byte
= ZV_BYTE
;
671 end
= BEGV
, end_byte
= BEGV_BYTE
;
674 end_byte
= CHAR_TO_BYTE (end
);
676 newline_cache
= newline_cache_on_off (current_buffer
);
677 if (current_buffer
->base_buffer
)
678 cache_buffer
= current_buffer
->base_buffer
;
680 cache_buffer
= current_buffer
;
688 /* Our innermost scanning loop is very simple; it doesn't know
689 about gaps, buffer ends, or the newline cache. ceiling is
690 the position of the last character before the next such
691 obstacle --- the last character the dumb search loop should
693 ptrdiff_t tem
, ceiling_byte
= end_byte
- 1;
695 /* If we're using the newline cache, consult it to see whether
696 we can avoid some scanning. */
699 ptrdiff_t next_change
;
702 while (start
< end
&& result
)
706 result
= region_cache_forward (cache_buffer
, newline_cache
,
707 start
, &next_change
);
710 /* When the cache revalidation is deferred,
711 next-change might point beyond ZV, which will
712 cause assertion violation in CHAR_TO_BYTE below.
713 Limit next_change to ZV to avoid that. */
714 if (next_change
> ZV
)
717 lim1
= next_change
= end
;
720 lim1
= min (next_change
, end
);
722 /* The cache returned zero for this region; see if
723 this is because the region is known and includes
724 only newlines. While at that, count any newlines
725 we bump into, and exit if we found enough off them. */
726 start_byte
= CHAR_TO_BYTE (start
);
728 && FETCH_BYTE (start_byte
) == '\n')
735 *bytepos
= start_byte
;
739 /* If we found a non-newline character before hitting
740 position where the cache will again return non-zero
741 (i.e. no newlines beyond that position), it means
742 this region is not yet known to the cache, and we
743 must resort to the "dumb loop" method. */
744 if (start
< next_change
&& !result
)
751 start_byte
= end_byte
;
755 /* START should never be after END. */
756 if (start_byte
> ceiling_byte
)
757 start_byte
= ceiling_byte
;
759 /* Now the text after start is an unknown region, and
760 next_change is the position of the next known region. */
761 ceiling_byte
= min (CHAR_TO_BYTE (next_change
) - 1, ceiling_byte
);
763 else if (start_byte
== -1)
764 start_byte
= CHAR_TO_BYTE (start
);
766 /* The dumb loop can only scan text stored in contiguous
767 bytes. BUFFER_CEILING_OF returns the last character
768 position that is contiguous, so the ceiling is the
769 position after that. */
770 tem
= BUFFER_CEILING_OF (start_byte
);
771 ceiling_byte
= min (tem
, ceiling_byte
);
774 /* The termination address of the dumb loop. */
775 unsigned char *lim_addr
= BYTE_POS_ADDR (ceiling_byte
) + 1;
776 ptrdiff_t lim_byte
= ceiling_byte
+ 1;
778 /* Nonpositive offsets (relative to LIM_ADDR and LIM_BYTE)
779 of the base, the cursor, and the next line. */
780 ptrdiff_t base
= start_byte
- lim_byte
;
781 ptrdiff_t cursor
, next
;
783 for (cursor
= base
; cursor
< 0; cursor
= next
)
786 unsigned char *nl
= memchr (lim_addr
+ cursor
, '\n', - cursor
);
787 next
= nl
? nl
- lim_addr
: 0;
789 /* If we're using the newline cache, cache the fact that
790 the region we just traversed is free of newlines. */
791 if (newline_cache
&& cursor
!= next
)
793 know_region_cache (cache_buffer
, newline_cache
,
794 BYTE_TO_CHAR (lim_byte
+ cursor
),
795 BYTE_TO_CHAR (lim_byte
+ next
));
796 /* know_region_cache can relocate buffer text. */
797 lim_addr
= BYTE_POS_ADDR (ceiling_byte
) + 1;
807 *bytepos
= lim_byte
+ next
;
808 return BYTE_TO_CHAR (lim_byte
+ next
);
814 start_byte
= lim_byte
;
815 start
= BYTE_TO_CHAR (start_byte
);
821 /* The last character to check before the next obstacle. */
822 ptrdiff_t tem
, ceiling_byte
= end_byte
;
824 /* Consult the newline cache, if appropriate. */
827 ptrdiff_t next_change
;
830 while (start
> end
&& result
)
834 result
= region_cache_backward (cache_buffer
, newline_cache
,
835 start
, &next_change
);
839 lim1
= next_change
= end
;
842 lim1
= max (next_change
, end
);
843 start_byte
= CHAR_TO_BYTE (start
);
845 && FETCH_BYTE (start_byte
- 1) == '\n')
850 *bytepos
= start_byte
;
856 if (start
> next_change
&& !result
)
863 start_byte
= end_byte
;
867 /* Start should never be at or before end. */
868 if (start_byte
<= ceiling_byte
)
869 start_byte
= ceiling_byte
+ 1;
871 /* Now the text before start is an unknown region, and
872 next_change is the position of the next known region. */
873 ceiling_byte
= max (CHAR_TO_BYTE (next_change
), ceiling_byte
);
875 else if (start_byte
== -1)
876 start_byte
= CHAR_TO_BYTE (start
);
878 /* Stop scanning before the gap. */
879 tem
= BUFFER_FLOOR_OF (start_byte
- 1);
880 ceiling_byte
= max (tem
, ceiling_byte
);
883 /* The termination address of the dumb loop. */
884 unsigned char *ceiling_addr
= BYTE_POS_ADDR (ceiling_byte
);
886 /* Offsets (relative to CEILING_ADDR and CEILING_BYTE) of
887 the base, the cursor, and the previous line. These
888 offsets are at least -1. */
889 ptrdiff_t base
= start_byte
- ceiling_byte
;
890 ptrdiff_t cursor
, prev
;
892 for (cursor
= base
; 0 < cursor
; cursor
= prev
)
894 unsigned char *nl
= memrchr (ceiling_addr
, '\n', cursor
);
895 prev
= nl
? nl
- ceiling_addr
: -1;
897 /* If we're looking for newlines, cache the fact that
898 this line's region is free of them. */
899 if (newline_cache
&& cursor
!= prev
+ 1)
901 know_region_cache (cache_buffer
, newline_cache
,
902 BYTE_TO_CHAR (ceiling_byte
+ prev
+ 1),
903 BYTE_TO_CHAR (ceiling_byte
+ cursor
));
904 /* know_region_cache can relocate buffer text. */
905 ceiling_addr
= BYTE_POS_ADDR (ceiling_byte
);
914 *bytepos
= ceiling_byte
+ prev
+ 1;
915 return BYTE_TO_CHAR (ceiling_byte
+ prev
+ 1);
921 start_byte
= ceiling_byte
;
922 start
= BYTE_TO_CHAR (start_byte
);
927 *shortage
= count
* direction
;
930 *bytepos
= start_byte
== -1 ? CHAR_TO_BYTE (start
) : start_byte
;
931 eassert (*bytepos
== CHAR_TO_BYTE (start
));
936 /* Search for COUNT instances of a line boundary.
937 Start at START. If COUNT is negative, search backwards.
939 We report the resulting position by calling TEMP_SET_PT_BOTH.
941 If we find COUNT instances. we position after (always after,
942 even if scanning backwards) the COUNTth match, and return 0.
944 If we don't find COUNT instances before reaching the end of the
945 buffer (or the beginning, if scanning backwards), we return
946 the number of line boundaries left unfound, and position at
947 the limit we bumped up against.
949 If ALLOW_QUIT, check for quitting. That's good to do
950 except in special cases. */
953 scan_newline (ptrdiff_t start
, ptrdiff_t start_byte
,
954 ptrdiff_t limit
, ptrdiff_t limit_byte
,
955 ptrdiff_t count
, bool allow_quit
)
957 ptrdiff_t charpos
, bytepos
, shortage
;
959 charpos
= find_newline (start
, start_byte
, limit
, limit_byte
,
960 count
, &shortage
, &bytepos
, allow_quit
);
962 TEMP_SET_PT_BOTH (limit
, limit_byte
);
964 TEMP_SET_PT_BOTH (charpos
, bytepos
);
968 /* Like above, but always scan from point and report the
969 resulting position in *CHARPOS and *BYTEPOS. */
972 scan_newline_from_point (ptrdiff_t count
, ptrdiff_t *charpos
,
978 *charpos
= find_newline (PT
, PT_BYTE
, BEGV
, BEGV_BYTE
, count
- 1,
979 &shortage
, bytepos
, 1);
981 *charpos
= find_newline (PT
, PT_BYTE
, ZV
, ZV_BYTE
, count
,
982 &shortage
, bytepos
, 1);
986 /* Like find_newline, but doesn't allow QUITting and doesn't return
989 find_newline_no_quit (ptrdiff_t from
, ptrdiff_t frombyte
,
990 ptrdiff_t cnt
, ptrdiff_t *bytepos
)
992 return find_newline (from
, frombyte
, 0, -1, cnt
, NULL
, bytepos
, 0);
995 /* Like find_newline, but returns position before the newline, not
996 after, and only search up to TO.
997 This isn't just find_newline_no_quit (...)-1, because you might hit TO. */
1000 find_before_next_newline (ptrdiff_t from
, ptrdiff_t to
,
1001 ptrdiff_t cnt
, ptrdiff_t *bytepos
)
1004 ptrdiff_t pos
= find_newline (from
, -1, to
, -1, cnt
, &shortage
, bytepos
, 1);
1009 DEC_BOTH (pos
, *bytepos
);
1016 /* Subroutines of Lisp buffer search functions. */
1019 search_command (Lisp_Object string
, Lisp_Object bound
, Lisp_Object noerror
,
1020 Lisp_Object count
, int direction
, int RE
, bool posix
)
1025 EMACS_INT n
= direction
;
1029 CHECK_NUMBER (count
);
1033 CHECK_STRING (string
);
1037 lim
= ZV
, lim_byte
= ZV_BYTE
;
1039 lim
= BEGV
, lim_byte
= BEGV_BYTE
;
1043 CHECK_NUMBER_COERCE_MARKER (bound
);
1045 if (n
> 0 ? lim
< PT
: lim
> PT
)
1046 error ("Invalid search bound (wrong side of point)");
1048 lim
= ZV
, lim_byte
= ZV_BYTE
;
1049 else if (lim
< BEGV
)
1050 lim
= BEGV
, lim_byte
= BEGV_BYTE
;
1052 lim_byte
= CHAR_TO_BYTE (lim
);
1055 /* This is so set_image_of_range_1 in regex.c can find the EQV table. */
1056 set_char_table_extras (BVAR (current_buffer
, case_canon_table
), 2,
1057 BVAR (current_buffer
, case_eqv_table
));
1059 np
= search_buffer (string
, PT
, PT_BYTE
, lim
, lim_byte
, n
, RE
,
1060 (!NILP (BVAR (current_buffer
, case_fold_search
))
1061 ? BVAR (current_buffer
, case_canon_table
)
1063 (!NILP (BVAR (current_buffer
, case_fold_search
))
1064 ? BVAR (current_buffer
, case_eqv_table
)
1070 xsignal1 (Qsearch_failed
, string
);
1072 if (!EQ (noerror
, Qt
))
1074 eassert (BEGV
<= lim
&& lim
<= ZV
);
1075 SET_PT_BOTH (lim
, lim_byte
);
1077 #if 0 /* This would be clean, but maybe programs depend on
1078 a value of nil here. */
1086 eassert (BEGV
<= np
&& np
<= ZV
);
1089 return make_number (np
);
1092 /* Return true if REGEXP it matches just one constant string. */
1095 trivial_regexp_p (Lisp_Object regexp
)
1097 ptrdiff_t len
= SBYTES (regexp
);
1098 unsigned char *s
= SDATA (regexp
);
1103 case '.': case '*': case '+': case '?': case '[': case '^': case '$':
1110 case '|': case '(': case ')': case '`': case '\'': case 'b':
1111 case 'B': case '<': case '>': case 'w': case 'W': case 's':
1112 case 'S': case '=': case '{': case '}': case '_':
1113 case 'c': case 'C': /* for categoryspec and notcategoryspec */
1114 case '1': case '2': case '3': case '4': case '5':
1115 case '6': case '7': case '8': case '9':
1123 /* Search for the n'th occurrence of STRING in the current buffer,
1124 starting at position POS and stopping at position LIM,
1125 treating STRING as a literal string if RE is false or as
1126 a regular expression if RE is true.
1128 If N is positive, searching is forward and LIM must be greater than POS.
1129 If N is negative, searching is backward and LIM must be less than POS.
1131 Returns -x if x occurrences remain to be found (x > 0),
1132 or else the position at the beginning of the Nth occurrence
1133 (if searching backward) or the end (if searching forward).
1135 POSIX is nonzero if we want full backtracking (POSIX style)
1136 for this pattern. 0 means backtrack only enough to get a valid match. */
1138 #define TRANSLATE(out, trt, d) \
1144 temp = Faref (trt, make_number (d)); \
1145 if (INTEGERP (temp)) \
1146 out = XINT (temp); \
1155 /* Only used in search_buffer, to record the end position of the match
1156 when searching regexps and SEARCH_REGS should not be changed
1157 (i.e. Vinhibit_changing_match_data is non-nil). */
1158 static struct re_registers search_regs_1
;
1161 search_buffer (Lisp_Object string
, ptrdiff_t pos
, ptrdiff_t pos_byte
,
1162 ptrdiff_t lim
, ptrdiff_t lim_byte
, EMACS_INT n
,
1163 int RE
, Lisp_Object trt
, Lisp_Object inverse_trt
, bool posix
)
1165 ptrdiff_t len
= SCHARS (string
);
1166 ptrdiff_t len_byte
= SBYTES (string
);
1167 register ptrdiff_t i
;
1169 if (running_asynch_code
)
1170 save_search_regs ();
1172 /* Searching 0 times means don't move. */
1173 /* Null string is found at starting position. */
1174 if (len
== 0 || n
== 0)
1176 set_search_regs (pos_byte
, 0);
1180 if (RE
&& !(trivial_regexp_p (string
) && NILP (Vsearch_spaces_regexp
)))
1182 unsigned char *p1
, *p2
;
1184 struct re_pattern_buffer
*bufp
;
1186 bufp
= compile_pattern (string
,
1187 (NILP (Vinhibit_changing_match_data
)
1188 ? &search_regs
: &search_regs_1
),
1190 !NILP (BVAR (current_buffer
, enable_multibyte_characters
)));
1192 maybe_quit (); /* Do a pending quit right away,
1193 to avoid paradoxical behavior */
1194 /* Get pointers and sizes of the two strings
1195 that make up the visible portion of the buffer. */
1198 s1
= GPT_BYTE
- BEGV_BYTE
;
1200 s2
= ZV_BYTE
- GPT_BYTE
;
1204 s2
= ZV_BYTE
- BEGV_BYTE
;
1209 s1
= ZV_BYTE
- BEGV_BYTE
;
1212 re_match_object
= Qnil
;
1214 freeze_buffer_relocation ();
1220 val
= re_search_2 (bufp
, (char *) p1
, s1
, (char *) p2
, s2
,
1221 pos_byte
- BEGV_BYTE
, lim_byte
- pos_byte
,
1222 (NILP (Vinhibit_changing_match_data
)
1223 ? &search_regs
: &search_regs_1
),
1224 /* Don't allow match past current point */
1225 pos_byte
- BEGV_BYTE
);
1228 matcher_overflow ();
1232 if (NILP (Vinhibit_changing_match_data
))
1234 pos_byte
= search_regs
.start
[0] + BEGV_BYTE
;
1235 for (i
= 0; i
< search_regs
.num_regs
; i
++)
1236 if (search_regs
.start
[i
] >= 0)
1238 search_regs
.start
[i
]
1239 = BYTE_TO_CHAR (search_regs
.start
[i
] + BEGV_BYTE
);
1241 = BYTE_TO_CHAR (search_regs
.end
[i
] + BEGV_BYTE
);
1243 XSETBUFFER (last_thing_searched
, current_buffer
);
1244 /* Set pos to the new position. */
1245 pos
= search_regs
.start
[0];
1249 pos_byte
= search_regs_1
.start
[0] + BEGV_BYTE
;
1250 /* Set pos to the new position. */
1251 pos
= BYTE_TO_CHAR (search_regs_1
.start
[0] + BEGV_BYTE
);
1256 thaw_buffer_relocation ();
1266 val
= re_search_2 (bufp
, (char *) p1
, s1
, (char *) p2
, s2
,
1267 pos_byte
- BEGV_BYTE
, lim_byte
- pos_byte
,
1268 (NILP (Vinhibit_changing_match_data
)
1269 ? &search_regs
: &search_regs_1
),
1270 lim_byte
- BEGV_BYTE
);
1273 matcher_overflow ();
1277 if (NILP (Vinhibit_changing_match_data
))
1279 pos_byte
= search_regs
.end
[0] + BEGV_BYTE
;
1280 for (i
= 0; i
< search_regs
.num_regs
; i
++)
1281 if (search_regs
.start
[i
] >= 0)
1283 search_regs
.start
[i
]
1284 = BYTE_TO_CHAR (search_regs
.start
[i
] + BEGV_BYTE
);
1286 = BYTE_TO_CHAR (search_regs
.end
[i
] + BEGV_BYTE
);
1288 XSETBUFFER (last_thing_searched
, current_buffer
);
1289 pos
= search_regs
.end
[0];
1293 pos_byte
= search_regs_1
.end
[0] + BEGV_BYTE
;
1294 pos
= BYTE_TO_CHAR (search_regs_1
.end
[0] + BEGV_BYTE
);
1299 thaw_buffer_relocation ();
1305 thaw_buffer_relocation ();
1308 else /* non-RE case */
1310 unsigned char *raw_pattern
, *pat
;
1311 ptrdiff_t raw_pattern_size
;
1312 ptrdiff_t raw_pattern_size_byte
;
1313 unsigned char *patbuf
;
1314 bool multibyte
= !NILP (BVAR (current_buffer
, enable_multibyte_characters
));
1315 unsigned char *base_pat
;
1316 /* Set to positive if we find a non-ASCII char that need
1317 translation. Otherwise set to zero later. */
1319 bool boyer_moore_ok
= 1;
1322 /* MULTIBYTE says whether the text to be searched is multibyte.
1323 We must convert PATTERN to match that, or we will not really
1324 find things right. */
1326 if (multibyte
== STRING_MULTIBYTE (string
))
1328 raw_pattern
= SDATA (string
);
1329 raw_pattern_size
= SCHARS (string
);
1330 raw_pattern_size_byte
= SBYTES (string
);
1334 raw_pattern_size
= SCHARS (string
);
1335 raw_pattern_size_byte
1336 = count_size_as_multibyte (SDATA (string
),
1338 raw_pattern
= SAFE_ALLOCA (raw_pattern_size_byte
+ 1);
1339 copy_text (SDATA (string
), raw_pattern
,
1340 SCHARS (string
), 0, 1);
1344 /* Converting multibyte to single-byte. */
1345 raw_pattern_size
= SCHARS (string
);
1346 raw_pattern_size_byte
= SCHARS (string
);
1347 raw_pattern
= SAFE_ALLOCA (raw_pattern_size
+ 1);
1348 copy_text (SDATA (string
), raw_pattern
,
1349 SBYTES (string
), 1, 0);
1352 /* Copy and optionally translate the pattern. */
1353 len
= raw_pattern_size
;
1354 len_byte
= raw_pattern_size_byte
;
1355 SAFE_NALLOCA (patbuf
, MAX_MULTIBYTE_LENGTH
, len
);
1357 base_pat
= raw_pattern
;
1360 /* Fill patbuf by translated characters in STRING while
1361 checking if we can use boyer-moore search. If TRT is
1362 non-nil, we can use boyer-moore search only if TRT can be
1363 represented by the byte array of 256 elements. For that,
1364 all non-ASCII case-equivalents of all case-sensitive
1365 characters in STRING must belong to the same character
1366 group (two characters belong to the same group iff their
1367 multibyte forms are the same except for the last byte;
1368 i.e. every 64 characters form a group; U+0000..U+003F,
1369 U+0040..U+007F, U+0080..U+00BF, ...). */
1373 unsigned char str_base
[MAX_MULTIBYTE_LENGTH
], *str
;
1374 int c
, translated
, inverse
;
1375 int in_charlen
, charlen
;
1377 /* If we got here and the RE flag is set, it's because we're
1378 dealing with a regexp known to be trivial, so the backslash
1379 just quotes the next character. */
1380 if (RE
&& *base_pat
== '\\')
1388 c
= STRING_CHAR_AND_LENGTH (base_pat
, in_charlen
);
1393 charlen
= in_charlen
;
1397 /* Translate the character. */
1398 TRANSLATE (translated
, trt
, c
);
1399 charlen
= CHAR_STRING (translated
, str_base
);
1402 /* Check if C has any other case-equivalents. */
1403 TRANSLATE (inverse
, inverse_trt
, c
);
1404 /* If so, check if we can use boyer-moore. */
1405 if (c
!= inverse
&& boyer_moore_ok
)
1407 /* Check if all equivalents belong to the same
1408 group of characters. Note that the check of C
1409 itself is done by the last iteration. */
1410 int this_char_base
= -1;
1412 while (boyer_moore_ok
)
1414 if (ASCII_CHAR_P (inverse
))
1416 if (this_char_base
> 0)
1421 else if (CHAR_BYTE8_P (inverse
))
1422 /* Boyer-moore search can't handle a
1423 translation of an eight-bit
1426 else if (this_char_base
< 0)
1428 this_char_base
= inverse
& ~0x3F;
1430 char_base
= this_char_base
;
1431 else if (this_char_base
!= char_base
)
1434 else if ((inverse
& ~0x3F) != this_char_base
)
1438 TRANSLATE (inverse
, inverse_trt
, inverse
);
1443 /* Store this character into the translated pattern. */
1444 memcpy (pat
, str
, charlen
);
1446 base_pat
+= in_charlen
;
1447 len_byte
-= in_charlen
;
1450 /* If char_base is still negative we didn't find any translated
1451 non-ASCII characters. */
1457 /* Unibyte buffer. */
1461 int c
, translated
, inverse
;
1463 /* If we got here and the RE flag is set, it's because we're
1464 dealing with a regexp known to be trivial, so the backslash
1465 just quotes the next character. */
1466 if (RE
&& *base_pat
== '\\')
1473 TRANSLATE (translated
, trt
, c
);
1474 *pat
++ = translated
;
1475 /* Check that none of C's equivalents violates the
1476 assumptions of boyer_moore. */
1477 TRANSLATE (inverse
, inverse_trt
, c
);
1480 if (inverse
>= 0200)
1487 TRANSLATE (inverse
, inverse_trt
, inverse
);
1492 len_byte
= pat
- patbuf
;
1493 pat
= base_pat
= patbuf
;
1497 ? boyer_moore (n
, pat
, len_byte
, trt
, inverse_trt
,
1500 : simple_search (n
, pat
, raw_pattern_size
, len_byte
, trt
,
1501 pos
, pos_byte
, lim
, lim_byte
));
1507 /* Do a simple string search N times for the string PAT,
1508 whose length is LEN/LEN_BYTE,
1509 from buffer position POS/POS_BYTE until LIM/LIM_BYTE.
1510 TRT is the translation table.
1512 Return the character position where the match is found.
1513 Otherwise, if M matches remained to be found, return -M.
1515 This kind of search works regardless of what is in PAT and
1516 regardless of what is in TRT. It is used in cases where
1517 boyer_moore cannot work. */
1520 simple_search (EMACS_INT n
, unsigned char *pat
,
1521 ptrdiff_t len
, ptrdiff_t len_byte
, Lisp_Object trt
,
1522 ptrdiff_t pos
, ptrdiff_t pos_byte
,
1523 ptrdiff_t lim
, ptrdiff_t lim_byte
)
1525 bool multibyte
= ! NILP (BVAR (current_buffer
, enable_multibyte_characters
));
1526 bool forward
= n
> 0;
1527 /* Number of buffer bytes matched. Note that this may be different
1528 from len_byte in a multibyte buffer. */
1529 ptrdiff_t match_byte
= PTRDIFF_MIN
;
1531 if (lim
> pos
&& multibyte
)
1536 /* Try matching at position POS. */
1537 ptrdiff_t this_pos
= pos
;
1538 ptrdiff_t this_pos_byte
= pos_byte
;
1539 ptrdiff_t this_len
= len
;
1540 unsigned char *p
= pat
;
1541 if (pos
+ len
> lim
|| pos_byte
+ len_byte
> lim_byte
)
1544 while (this_len
> 0)
1546 int charlen
, buf_charlen
;
1549 pat_ch
= STRING_CHAR_AND_LENGTH (p
, charlen
);
1550 buf_ch
= STRING_CHAR_AND_LENGTH (BYTE_POS_ADDR (this_pos_byte
),
1552 TRANSLATE (buf_ch
, trt
, buf_ch
);
1554 if (buf_ch
!= pat_ch
)
1560 this_pos_byte
+= buf_charlen
;
1566 match_byte
= this_pos_byte
- pos_byte
;
1568 pos_byte
+= match_byte
;
1572 INC_BOTH (pos
, pos_byte
);
1582 /* Try matching at position POS. */
1583 ptrdiff_t this_pos
= pos
;
1584 ptrdiff_t this_len
= len
;
1585 unsigned char *p
= pat
;
1587 if (pos
+ len
> lim
)
1590 while (this_len
> 0)
1593 int buf_ch
= FETCH_BYTE (this_pos
);
1594 TRANSLATE (buf_ch
, trt
, buf_ch
);
1596 if (buf_ch
!= pat_ch
)
1615 /* Backwards search. */
1616 else if (lim
< pos
&& multibyte
)
1621 /* Try matching at position POS. */
1622 ptrdiff_t this_pos
= pos
;
1623 ptrdiff_t this_pos_byte
= pos_byte
;
1624 ptrdiff_t this_len
= len
;
1625 const unsigned char *p
= pat
+ len_byte
;
1627 if (this_pos
- len
< lim
|| (pos_byte
- len_byte
) < lim_byte
)
1630 while (this_len
> 0)
1634 DEC_BOTH (this_pos
, this_pos_byte
);
1635 PREV_CHAR_BOUNDARY (p
, pat
);
1636 pat_ch
= STRING_CHAR (p
);
1637 buf_ch
= STRING_CHAR (BYTE_POS_ADDR (this_pos_byte
));
1638 TRANSLATE (buf_ch
, trt
, buf_ch
);
1640 if (buf_ch
!= pat_ch
)
1648 match_byte
= pos_byte
- this_pos_byte
;
1650 pos_byte
= this_pos_byte
;
1654 DEC_BOTH (pos
, pos_byte
);
1664 /* Try matching at position POS. */
1665 ptrdiff_t this_pos
= pos
- len
;
1666 ptrdiff_t this_len
= len
;
1667 unsigned char *p
= pat
;
1672 while (this_len
> 0)
1675 int buf_ch
= FETCH_BYTE (this_pos
);
1676 TRANSLATE (buf_ch
, trt
, buf_ch
);
1678 if (buf_ch
!= pat_ch
)
1700 eassert (match_byte
!= PTRDIFF_MIN
);
1702 set_search_regs ((multibyte
? pos_byte
: pos
) - match_byte
, match_byte
);
1704 set_search_regs (multibyte
? pos_byte
: pos
, match_byte
);
1714 /* Do Boyer-Moore search N times for the string BASE_PAT,
1715 whose length is LEN_BYTE,
1716 from buffer position POS_BYTE until LIM_BYTE.
1717 DIRECTION says which direction we search in.
1718 TRT and INVERSE_TRT are translation tables.
1719 Characters in PAT are already translated by TRT.
1721 This kind of search works if all the characters in BASE_PAT that
1722 have nontrivial translation are the same aside from the last byte.
1723 This makes it possible to translate just the last byte of a
1724 character, and do so after just a simple test of the context.
1725 CHAR_BASE is nonzero if there is such a non-ASCII character.
1727 If that criterion is not satisfied, do not call this function. */
1730 boyer_moore (EMACS_INT n
, unsigned char *base_pat
,
1732 Lisp_Object trt
, Lisp_Object inverse_trt
,
1733 ptrdiff_t pos_byte
, ptrdiff_t lim_byte
,
1736 int direction
= ((n
> 0) ? 1 : -1);
1737 register ptrdiff_t dirlen
;
1739 int stride_for_teases
= 0;
1741 register unsigned char *cursor
, *p_limit
;
1742 register ptrdiff_t i
;
1744 unsigned char *pat
, *pat_end
;
1745 bool multibyte
= ! NILP (BVAR (current_buffer
, enable_multibyte_characters
));
1747 unsigned char simple_translate
[0400];
1748 /* These are set to the preceding bytes of a byte to be translated
1749 if char_base is nonzero. As the maximum byte length of a
1750 multibyte character is 5, we have to check at most four previous
1752 int translate_prev_byte1
= 0;
1753 int translate_prev_byte2
= 0;
1754 int translate_prev_byte3
= 0;
1756 /* The general approach is that we are going to maintain that we know
1757 the first (closest to the present position, in whatever direction
1758 we're searching) character that could possibly be the last
1759 (furthest from present position) character of a valid match. We
1760 advance the state of our knowledge by looking at that character
1761 and seeing whether it indeed matches the last character of the
1762 pattern. If it does, we take a closer look. If it does not, we
1763 move our pointer (to putative last characters) as far as is
1764 logically possible. This amount of movement, which I call a
1765 stride, will be the length of the pattern if the actual character
1766 appears nowhere in the pattern, otherwise it will be the distance
1767 from the last occurrence of that character to the end of the
1768 pattern. If the amount is zero we have a possible match. */
1770 /* Here we make a "mickey mouse" BM table. The stride of the search
1771 is determined only by the last character of the putative match.
1772 If that character does not match, we will stride the proper
1773 distance to propose a match that superimposes it on the last
1774 instance of a character that matches it (per trt), or misses
1775 it entirely if there is none. */
1777 dirlen
= len_byte
* direction
;
1779 /* Record position after the end of the pattern. */
1780 pat_end
= base_pat
+ len_byte
;
1781 /* BASE_PAT points to a character that we start scanning from.
1782 It is the first character in a forward search,
1783 the last character in a backward search. */
1785 base_pat
= pat_end
- 1;
1787 /* A character that does not appear in the pattern induces a
1788 stride equal to the pattern length. */
1789 for (i
= 0; i
< 0400; i
++)
1792 /* We use this for translation, instead of TRT itself.
1793 We fill this in to handle the characters that actually
1794 occur in the pattern. Others don't matter anyway! */
1795 for (i
= 0; i
< 0400; i
++)
1796 simple_translate
[i
] = i
;
1800 /* Setup translate_prev_byte1/2/3/4 from CHAR_BASE. Only a
1801 byte following them are the target of translation. */
1802 eassume (0x80 <= char_base
&& char_base
<= MAX_CHAR
);
1803 unsigned char str
[MAX_MULTIBYTE_LENGTH
];
1804 int cblen
= CHAR_STRING (char_base
, str
);
1806 translate_prev_byte1
= str
[cblen
- 2];
1809 translate_prev_byte2
= str
[cblen
- 3];
1811 translate_prev_byte3
= str
[cblen
- 4];
1818 unsigned char *ptr
= base_pat
+ i
;
1822 /* If the byte currently looking at is the last of a
1823 character to check case-equivalents, set CH to that
1824 character. An ASCII character and a non-ASCII character
1825 matching with CHAR_BASE are to be checked. */
1828 if (ASCII_CHAR_P (*ptr
) || ! multibyte
)
1831 && ((pat_end
- ptr
) == 1 || CHAR_HEAD_P (ptr
[1])))
1833 unsigned char *charstart
= ptr
- 1;
1835 while (! (CHAR_HEAD_P (*charstart
)))
1837 ch
= STRING_CHAR (charstart
);
1838 if (char_base
!= (ch
& ~0x3F))
1842 if (ch
>= 0200 && multibyte
)
1843 j
= (ch
& 0x3F) | 0200;
1848 stride_for_teases
= BM_tab
[j
];
1850 BM_tab
[j
] = dirlen
- i
;
1851 /* A translation table is accompanied by its inverse -- see
1852 comment following downcase_table for details. */
1855 int starting_ch
= ch
;
1860 TRANSLATE (ch
, inverse_trt
, ch
);
1861 if (ch
>= 0200 && multibyte
)
1862 j
= (ch
& 0x3F) | 0200;
1866 /* For all the characters that map into CH,
1867 set up simple_translate to map the last byte
1869 simple_translate
[j
] = starting_j
;
1870 if (ch
== starting_ch
)
1872 BM_tab
[j
] = dirlen
- i
;
1881 stride_for_teases
= BM_tab
[j
];
1882 BM_tab
[j
] = dirlen
- i
;
1884 /* stride_for_teases tells how much to stride if we get a
1885 match on the far character but are subsequently
1886 disappointed, by recording what the stride would have been
1887 for that character if the last character had been
1890 pos_byte
+= dirlen
- ((direction
> 0) ? direction
: 0);
1891 /* loop invariant - POS_BYTE points at where last char (first
1892 char if reverse) of pattern would align in a possible match. */
1896 unsigned char *tail_end_ptr
;
1898 /* It's been reported that some (broken) compiler thinks that
1899 Boolean expressions in an arithmetic context are unsigned.
1900 Using an explicit ?1:0 prevents this. */
1901 if ((lim_byte
- pos_byte
- ((direction
> 0) ? 1 : 0)) * direction
1903 return (n
* (0 - direction
));
1904 /* First we do the part we can by pointers (maybe nothing) */
1907 limit
= pos_byte
- dirlen
+ direction
;
1910 limit
= BUFFER_CEILING_OF (limit
);
1911 /* LIMIT is now the last (not beyond-last!) value POS_BYTE
1912 can take on without hitting edge of buffer or the gap. */
1913 limit
= min (limit
, pos_byte
+ 20000);
1914 limit
= min (limit
, lim_byte
- 1);
1918 limit
= BUFFER_FLOOR_OF (limit
);
1919 /* LIMIT is now the last (not beyond-last!) value POS_BYTE
1920 can take on without hitting edge of buffer or the gap. */
1921 limit
= max (limit
, pos_byte
- 20000);
1922 limit
= max (limit
, lim_byte
);
1924 tail_end
= BUFFER_CEILING_OF (pos_byte
) + 1;
1925 tail_end_ptr
= BYTE_POS_ADDR (tail_end
);
1927 if ((limit
- pos_byte
) * direction
> 20)
1931 p_limit
= BYTE_POS_ADDR (limit
);
1932 p2
= (cursor
= BYTE_POS_ADDR (pos_byte
));
1933 /* In this loop, pos + cursor - p2 is the surrogate for pos. */
1934 while (1) /* use one cursor setting as long as i can */
1936 if (direction
> 0) /* worth duplicating */
1938 while (cursor
<= p_limit
)
1940 if (BM_tab
[*cursor
] == 0)
1942 cursor
+= BM_tab
[*cursor
];
1947 while (cursor
>= p_limit
)
1949 if (BM_tab
[*cursor
] == 0)
1951 cursor
+= BM_tab
[*cursor
];
1954 /* If you are here, cursor is beyond the end of the
1955 searched region. You fail to match within the
1956 permitted region and would otherwise try a character
1957 beyond that region. */
1961 i
= dirlen
- direction
;
1964 while ((i
-= direction
) + direction
!= 0)
1967 cursor
-= direction
;
1968 /* Translate only the last byte of a character. */
1970 || ((cursor
== tail_end_ptr
1971 || CHAR_HEAD_P (cursor
[1]))
1972 && (CHAR_HEAD_P (cursor
[0])
1973 /* Check if this is the last byte of
1974 a translatable character. */
1975 || (translate_prev_byte1
== cursor
[-1]
1976 && (CHAR_HEAD_P (translate_prev_byte1
)
1977 || (translate_prev_byte2
== cursor
[-2]
1978 && (CHAR_HEAD_P (translate_prev_byte2
)
1979 || (translate_prev_byte3
== cursor
[-3]))))))))
1980 ch
= simple_translate
[*cursor
];
1989 while ((i
-= direction
) + direction
!= 0)
1991 cursor
-= direction
;
1992 if (pat
[i
] != *cursor
)
1996 cursor
+= dirlen
- i
- direction
; /* fix cursor */
1997 if (i
+ direction
== 0)
1999 ptrdiff_t position
, start
, end
;
2001 ptrdiff_t cursor_off
;
2004 cursor
-= direction
;
2006 position
= pos_byte
+ cursor
- p2
+ ((direction
> 0)
2007 ? 1 - len_byte
: 0);
2009 /* set_search_regs might call malloc, which could
2010 cause ralloc.c relocate buffer text. We need to
2011 update pointers into buffer text due to that. */
2012 cursor_off
= cursor
- p2
;
2014 set_search_regs (position
, len_byte
);
2016 p_limit
= BYTE_POS_ADDR (limit
);
2017 p2
= BYTE_POS_ADDR (pos_byte
);
2018 cursor
= p2
+ cursor_off
;
2021 if (NILP (Vinhibit_changing_match_data
))
2023 start
= search_regs
.start
[0];
2024 end
= search_regs
.end
[0];
2027 /* If Vinhibit_changing_match_data is non-nil,
2028 search_regs will not be changed. So let's
2029 compute start and end here. */
2031 start
= BYTE_TO_CHAR (position
);
2032 end
= BYTE_TO_CHAR (position
+ len_byte
);
2035 if ((n
-= direction
) != 0)
2036 cursor
+= dirlen
; /* to resume search */
2038 return direction
> 0 ? end
: start
;
2041 cursor
+= stride_for_teases
; /* <sigh> we lose - */
2043 pos_byte
+= cursor
- p2
;
2046 /* Now we'll pick up a clump that has to be done the hard
2047 way because it covers a discontinuity. */
2049 limit
= ((direction
> 0)
2050 ? BUFFER_CEILING_OF (pos_byte
- dirlen
+ 1)
2051 : BUFFER_FLOOR_OF (pos_byte
- dirlen
- 1));
2052 limit
= ((direction
> 0)
2053 ? min (limit
+ len_byte
, lim_byte
- 1)
2054 : max (limit
- len_byte
, lim_byte
));
2055 /* LIMIT is now the last value POS_BYTE can have
2056 and still be valid for a possible match. */
2059 /* This loop can be coded for space rather than
2060 speed because it will usually run only once.
2061 (the reach is at most len + 21, and typically
2062 does not exceed len). */
2063 while ((limit
- pos_byte
) * direction
>= 0)
2065 int ch
= FETCH_BYTE (pos_byte
);
2066 if (BM_tab
[ch
] == 0)
2068 pos_byte
+= BM_tab
[ch
];
2070 break; /* ran off the end */
2073 /* Found what might be a match. */
2074 i
= dirlen
- direction
;
2075 while ((i
-= direction
) + direction
!= 0)
2079 pos_byte
-= direction
;
2080 ptr
= BYTE_POS_ADDR (pos_byte
);
2081 /* Translate only the last byte of a character. */
2083 || ((ptr
== tail_end_ptr
2084 || CHAR_HEAD_P (ptr
[1]))
2085 && (CHAR_HEAD_P (ptr
[0])
2086 /* Check if this is the last byte of a
2087 translatable character. */
2088 || (translate_prev_byte1
== ptr
[-1]
2089 && (CHAR_HEAD_P (translate_prev_byte1
)
2090 || (translate_prev_byte2
== ptr
[-2]
2091 && (CHAR_HEAD_P (translate_prev_byte2
)
2092 || translate_prev_byte3
== ptr
[-3])))))))
2093 ch
= simple_translate
[*ptr
];
2099 /* Above loop has moved POS_BYTE part or all the way
2100 back to the first pos (last pos if reverse).
2101 Set it once again at the last (first if reverse) char. */
2102 pos_byte
+= dirlen
- i
- direction
;
2103 if (i
+ direction
== 0)
2105 ptrdiff_t position
, start
, end
;
2106 pos_byte
-= direction
;
2108 position
= pos_byte
+ ((direction
> 0) ? 1 - len_byte
: 0);
2109 set_search_regs (position
, len_byte
);
2111 if (NILP (Vinhibit_changing_match_data
))
2113 start
= search_regs
.start
[0];
2114 end
= search_regs
.end
[0];
2117 /* If Vinhibit_changing_match_data is non-nil,
2118 search_regs will not be changed. So let's
2119 compute start and end here. */
2121 start
= BYTE_TO_CHAR (position
);
2122 end
= BYTE_TO_CHAR (position
+ len_byte
);
2125 if ((n
-= direction
) != 0)
2126 pos_byte
+= dirlen
; /* to resume search */
2128 return direction
> 0 ? end
: start
;
2131 pos_byte
+= stride_for_teases
;
2134 /* We have done one clump. Can we continue? */
2135 if ((lim_byte
- pos_byte
) * direction
< 0)
2136 return ((0 - n
) * direction
);
2138 return BYTE_TO_CHAR (pos_byte
);
2141 /* Record beginning BEG_BYTE and end BEG_BYTE + NBYTES
2142 for the overall match just found in the current buffer.
2143 Also clear out the match data for registers 1 and up. */
2146 set_search_regs (ptrdiff_t beg_byte
, ptrdiff_t nbytes
)
2150 if (!NILP (Vinhibit_changing_match_data
))
2153 /* Make sure we have registers in which to store
2154 the match position. */
2155 if (search_regs
.num_regs
== 0)
2157 search_regs
.start
= xmalloc (2 * sizeof (regoff_t
));
2158 search_regs
.end
= xmalloc (2 * sizeof (regoff_t
));
2159 search_regs
.num_regs
= 2;
2162 /* Clear out the other registers. */
2163 for (i
= 1; i
< search_regs
.num_regs
; i
++)
2165 search_regs
.start
[i
] = -1;
2166 search_regs
.end
[i
] = -1;
2169 search_regs
.start
[0] = BYTE_TO_CHAR (beg_byte
);
2170 search_regs
.end
[0] = BYTE_TO_CHAR (beg_byte
+ nbytes
);
2171 XSETBUFFER (last_thing_searched
, current_buffer
);
2174 DEFUN ("search-backward", Fsearch_backward
, Ssearch_backward
, 1, 4,
2175 "MSearch backward: ",
2176 doc
: /* Search backward from point for STRING.
2177 Set point to the beginning of the occurrence found, and return point.
2178 An optional second argument bounds the search; it is a buffer position.
2179 The match found must not begin before that position. A value of nil
2180 means search to the beginning of the accessible portion of the buffer.
2181 Optional third argument, if t, means if fail just return nil (no error).
2182 If not nil and not t, position at limit of search and return nil.
2183 Optional fourth argument COUNT, if a positive number, means to search
2184 for COUNT successive occurrences. If COUNT is negative, search
2185 forward, instead of backward, for -COUNT occurrences. A value of
2186 nil means the same as 1.
2187 With COUNT positive, the match found is the COUNTth to last one (or
2188 last, if COUNT is 1 or nil) in the buffer located entirely before
2189 the origin of the search; correspondingly with COUNT negative.
2191 Search case-sensitivity is determined by the value of the variable
2192 `case-fold-search', which see.
2194 See also the functions `match-beginning', `match-end' and `replace-match'. */)
2195 (Lisp_Object string
, Lisp_Object bound
, Lisp_Object noerror
, Lisp_Object count
)
2197 return search_command (string
, bound
, noerror
, count
, -1, 0, 0);
2200 DEFUN ("search-forward", Fsearch_forward
, Ssearch_forward
, 1, 4, "MSearch: ",
2201 doc
: /* Search forward from point for STRING.
2202 Set point to the end of the occurrence found, and return point.
2203 An optional second argument bounds the search; it is a buffer position.
2204 The match found must not end after that position. A value of nil
2205 means search to the end of the accessible portion of the buffer.
2206 Optional third argument, if t, means if fail just return nil (no error).
2207 If not nil and not t, move to limit of search and return nil.
2208 Optional fourth argument COUNT, if a positive number, means to search
2209 for COUNT successive occurrences. If COUNT is negative, search
2210 backward, instead of forward, for -COUNT occurrences. A value of
2211 nil means the same as 1.
2212 With COUNT positive, the match found is the COUNTth one (or first,
2213 if COUNT is 1 or nil) in the buffer located entirely after the
2214 origin of the search; correspondingly with COUNT negative.
2216 Search case-sensitivity is determined by the value of the variable
2217 `case-fold-search', which see.
2219 See also the functions `match-beginning', `match-end' and `replace-match'. */)
2220 (Lisp_Object string
, Lisp_Object bound
, Lisp_Object noerror
, Lisp_Object count
)
2222 return search_command (string
, bound
, noerror
, count
, 1, 0, 0);
2225 DEFUN ("re-search-backward", Fre_search_backward
, Sre_search_backward
, 1, 4,
2226 "sRE search backward: ",
2227 doc
: /* Search backward from point for regular expression REGEXP.
2228 This function is almost identical to `re-search-forward', except that
2229 by default it searches backward instead of forward, and the sign of
2230 COUNT also indicates exactly the opposite searching direction.
2231 See `re-search-forward' for details.
2233 Note that searching backwards may give a shorter match than expected,
2234 because REGEXP is still matched in the forward direction. See Info
2235 anchor `(elisp) re-search-backward' for details. */)
2236 (Lisp_Object regexp
, Lisp_Object bound
, Lisp_Object noerror
, Lisp_Object count
)
2238 return search_command (regexp
, bound
, noerror
, count
, -1, 1, 0);
2241 DEFUN ("re-search-forward", Fre_search_forward
, Sre_search_forward
, 1, 4,
2243 doc
: /* Search forward from point for regular expression REGEXP.
2244 Set point to the end of the occurrence found, and return point.
2245 The optional second argument BOUND is a buffer position that bounds
2246 the search. The match found must not end after that position. A
2247 value of nil means search to the end of the accessible portion of
2249 The optional third argument NOERROR indicates how errors are handled
2250 when the search fails. If it is nil or omitted, emit an error; if
2251 it is t, simply return nil and do nothing; if it is neither nil nor
2252 t, move to the limit of search and return nil.
2253 The optional fourth argument COUNT is a number that indicates the
2254 search direction and the number of occurrences to search for. If it
2255 is positive, search forward for COUNT successive occurrences; if it
2256 is negative, search backward, instead of forward, for -COUNT
2257 occurrences. A value of nil means the same as 1.
2258 With COUNT positive/negative, the match found is the COUNTth/-COUNTth
2259 one in the buffer located entirely after/before the origin of the
2262 Search case-sensitivity is determined by the value of the variable
2263 `case-fold-search', which see.
2265 See also the functions `match-beginning', `match-end', `match-string',
2266 and `replace-match'. */)
2267 (Lisp_Object regexp
, Lisp_Object bound
, Lisp_Object noerror
, Lisp_Object count
)
2269 return search_command (regexp
, bound
, noerror
, count
, 1, 1, 0);
2272 DEFUN ("posix-search-backward", Fposix_search_backward
, Sposix_search_backward
, 1, 4,
2273 "sPosix search backward: ",
2274 doc
: /* Search backward from point for match for regular expression REGEXP.
2275 Find the longest match in accord with Posix regular expression rules.
2276 Set point to the beginning of the occurrence found, and return point.
2277 An optional second argument bounds the search; it is a buffer position.
2278 The match found must not begin before that position. A value of nil
2279 means search to the beginning of the accessible portion of the buffer.
2280 Optional third argument, if t, means if fail just return nil (no error).
2281 If not nil and not t, position at limit of search and return nil.
2282 Optional fourth argument COUNT, if a positive number, means to search
2283 for COUNT successive occurrences. If COUNT is negative, search
2284 forward, instead of backward, for -COUNT occurrences. A value of
2285 nil means the same as 1.
2286 With COUNT positive, the match found is the COUNTth to last one (or
2287 last, if COUNT is 1 or nil) in the buffer located entirely before
2288 the origin of the search; correspondingly with COUNT negative.
2290 Search case-sensitivity is determined by the value of the variable
2291 `case-fold-search', which see.
2293 See also the functions `match-beginning', `match-end', `match-string',
2294 and `replace-match'. */)
2295 (Lisp_Object regexp
, Lisp_Object bound
, Lisp_Object noerror
, Lisp_Object count
)
2297 return search_command (regexp
, bound
, noerror
, count
, -1, 1, 1);
2300 DEFUN ("posix-search-forward", Fposix_search_forward
, Sposix_search_forward
, 1, 4,
2302 doc
: /* Search forward from point for regular expression REGEXP.
2303 Find the longest match in accord with Posix regular expression rules.
2304 Set point to the end of the occurrence found, and return point.
2305 An optional second argument bounds the search; it is a buffer position.
2306 The match found must not end after that position. A value of nil
2307 means search to the end of the accessible portion of the buffer.
2308 Optional third argument, if t, means if fail just return nil (no error).
2309 If not nil and not t, move to limit of search and return nil.
2310 Optional fourth argument COUNT, if a positive number, means to search
2311 for COUNT successive occurrences. If COUNT is negative, search
2312 backward, instead of forward, for -COUNT occurrences. A value of
2313 nil means the same as 1.
2314 With COUNT positive, the match found is the COUNTth one (or first,
2315 if COUNT is 1 or nil) in the buffer located entirely after the
2316 origin of the search; correspondingly with COUNT negative.
2318 Search case-sensitivity is determined by the value of the variable
2319 `case-fold-search', which see.
2321 See also the functions `match-beginning', `match-end', `match-string',
2322 and `replace-match'. */)
2323 (Lisp_Object regexp
, Lisp_Object bound
, Lisp_Object noerror
, Lisp_Object count
)
2325 return search_command (regexp
, bound
, noerror
, count
, 1, 1, 1);
2328 DEFUN ("replace-match", Freplace_match
, Sreplace_match
, 1, 5, 0,
2329 doc
: /* Replace text matched by last search with NEWTEXT.
2330 Leave point at the end of the replacement text.
2332 If optional second arg FIXEDCASE is non-nil, do not alter the case of
2333 the replacement text. Otherwise, maybe capitalize the whole text, or
2334 maybe just word initials, based on the replaced text. If the replaced
2335 text has only capital letters and has at least one multiletter word,
2336 convert NEWTEXT to all caps. Otherwise if all words are capitalized
2337 in the replaced text, capitalize each word in NEWTEXT.
2339 If optional third arg LITERAL is non-nil, insert NEWTEXT literally.
2340 Otherwise treat `\\' as special:
2341 `\\&' in NEWTEXT means substitute original matched text.
2342 `\\N' means substitute what matched the Nth `\\(...\\)'.
2343 If Nth parens didn't match, substitute nothing.
2344 `\\\\' means insert one `\\'.
2345 `\\?' is treated literally
2346 (for compatibility with `query-replace-regexp').
2347 Any other character following `\\' signals an error.
2348 Case conversion does not apply to these substitutions.
2350 If optional fourth argument STRING is non-nil, it should be a string
2351 to act on; this should be the string on which the previous match was
2352 done via `string-match'. In this case, `replace-match' creates and
2353 returns a new string, made by copying STRING and replacing the part of
2354 STRING that was matched (the original STRING itself is not altered).
2356 The optional fifth argument SUBEXP specifies a subexpression;
2357 it says to replace just that subexpression with NEWTEXT,
2358 rather than replacing the entire matched text.
2359 This is, in a vague sense, the inverse of using `\\N' in NEWTEXT;
2360 `\\N' copies subexp N into NEWTEXT, but using N as SUBEXP puts
2361 NEWTEXT in place of subexp N.
2362 This is useful only after a regular expression search or match,
2363 since only regular expressions have distinguished subexpressions. */)
2364 (Lisp_Object newtext
, Lisp_Object fixedcase
, Lisp_Object literal
, Lisp_Object string
, Lisp_Object subexp
)
2366 enum { nochange
, all_caps
, cap_initial
} case_action
;
2367 ptrdiff_t pos
, pos_byte
;
2368 bool some_multiletter_word
;
2369 bool some_lowercase
;
2370 bool some_uppercase
;
2371 bool some_nonuppercase_initial
;
2374 ptrdiff_t opoint
, newpoint
;
2376 CHECK_STRING (newtext
);
2378 if (! NILP (string
))
2379 CHECK_STRING (string
);
2381 case_action
= nochange
; /* We tried an initialization */
2382 /* but some C compilers blew it */
2384 if (search_regs
.num_regs
<= 0)
2385 error ("`replace-match' called before any match found");
2391 CHECK_NUMBER (subexp
);
2392 if (! (0 <= XINT (subexp
) && XINT (subexp
) < search_regs
.num_regs
))
2393 args_out_of_range (subexp
, make_number (search_regs
.num_regs
));
2394 sub
= XINT (subexp
);
2399 if (search_regs
.start
[sub
] < BEGV
2400 || search_regs
.start
[sub
] > search_regs
.end
[sub
]
2401 || search_regs
.end
[sub
] > ZV
)
2402 args_out_of_range (make_number (search_regs
.start
[sub
]),
2403 make_number (search_regs
.end
[sub
]));
2407 if (search_regs
.start
[sub
] < 0
2408 || search_regs
.start
[sub
] > search_regs
.end
[sub
]
2409 || search_regs
.end
[sub
] > SCHARS (string
))
2410 args_out_of_range (make_number (search_regs
.start
[sub
]),
2411 make_number (search_regs
.end
[sub
]));
2414 if (NILP (fixedcase
))
2416 /* Decide how to casify by examining the matched text. */
2419 pos
= search_regs
.start
[sub
];
2420 last
= search_regs
.end
[sub
];
2423 pos_byte
= CHAR_TO_BYTE (pos
);
2425 pos_byte
= string_char_to_byte (string
, pos
);
2428 case_action
= all_caps
;
2430 /* some_multiletter_word is set nonzero if any original word
2431 is more than one letter long. */
2432 some_multiletter_word
= 0;
2434 some_nonuppercase_initial
= 0;
2441 c
= FETCH_CHAR_AS_MULTIBYTE (pos_byte
);
2442 INC_BOTH (pos
, pos_byte
);
2445 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c
, string
, pos
, pos_byte
);
2449 /* Cannot be all caps if any original char is lower case */
2452 if (SYNTAX (prevc
) != Sword
)
2453 some_nonuppercase_initial
= 1;
2455 some_multiletter_word
= 1;
2457 else if (uppercasep (c
))
2460 if (SYNTAX (prevc
) != Sword
)
2463 some_multiletter_word
= 1;
2467 /* If the initial is a caseless word constituent,
2468 treat that like a lowercase initial. */
2469 if (SYNTAX (prevc
) != Sword
)
2470 some_nonuppercase_initial
= 1;
2476 /* Convert to all caps if the old text is all caps
2477 and has at least one multiletter word. */
2478 if (! some_lowercase
&& some_multiletter_word
)
2479 case_action
= all_caps
;
2480 /* Capitalize each word, if the old text has all capitalized words. */
2481 else if (!some_nonuppercase_initial
&& some_multiletter_word
)
2482 case_action
= cap_initial
;
2483 else if (!some_nonuppercase_initial
&& some_uppercase
)
2484 /* Should x -> yz, operating on X, give Yz or YZ?
2485 We'll assume the latter. */
2486 case_action
= all_caps
;
2488 case_action
= nochange
;
2491 /* Do replacement in a string. */
2494 Lisp_Object before
, after
;
2496 before
= Fsubstring (string
, make_number (0),
2497 make_number (search_regs
.start
[sub
]));
2498 after
= Fsubstring (string
, make_number (search_regs
.end
[sub
]), Qnil
);
2500 /* Substitute parts of the match into NEWTEXT
2504 ptrdiff_t lastpos
= 0;
2505 ptrdiff_t lastpos_byte
= 0;
2506 /* We build up the substituted string in ACCUM. */
2509 ptrdiff_t length
= SBYTES (newtext
);
2513 for (pos_byte
= 0, pos
= 0; pos_byte
< length
;)
2515 ptrdiff_t substart
= -1;
2516 ptrdiff_t subend
= 0;
2517 bool delbackslash
= 0;
2519 FETCH_STRING_CHAR_ADVANCE (c
, newtext
, pos
, pos_byte
);
2523 FETCH_STRING_CHAR_ADVANCE (c
, newtext
, pos
, pos_byte
);
2527 substart
= search_regs
.start
[sub
];
2528 subend
= search_regs
.end
[sub
];
2530 else if (c
>= '1' && c
<= '9')
2532 if (c
- '0' < search_regs
.num_regs
2533 && search_regs
.start
[c
- '0'] >= 0)
2535 substart
= search_regs
.start
[c
- '0'];
2536 subend
= search_regs
.end
[c
- '0'];
2540 /* If that subexp did not match,
2541 replace \\N with nothing. */
2549 error ("Invalid use of `\\' in replacement text");
2553 if (pos
- 2 != lastpos
)
2554 middle
= substring_both (newtext
, lastpos
,
2556 pos
- 2, pos_byte
- 2);
2559 accum
= concat3 (accum
, middle
,
2561 make_number (substart
),
2562 make_number (subend
)));
2564 lastpos_byte
= pos_byte
;
2566 else if (delbackslash
)
2568 middle
= substring_both (newtext
, lastpos
,
2570 pos
- 1, pos_byte
- 1);
2572 accum
= concat2 (accum
, middle
);
2574 lastpos_byte
= pos_byte
;
2579 middle
= substring_both (newtext
, lastpos
,
2585 newtext
= concat2 (accum
, middle
);
2588 /* Do case substitution in NEWTEXT if desired. */
2589 if (case_action
== all_caps
)
2590 newtext
= Fupcase (newtext
);
2591 else if (case_action
== cap_initial
)
2592 newtext
= Fupcase_initials (newtext
);
2594 return concat3 (before
, newtext
, after
);
2597 /* Record point, then move (quietly) to the start of the match. */
2598 if (PT
>= search_regs
.end
[sub
])
2600 else if (PT
> search_regs
.start
[sub
])
2601 opoint
= search_regs
.end
[sub
] - ZV
;
2605 /* If we want non-literal replacement,
2606 perform substitution on the replacement string. */
2609 ptrdiff_t length
= SBYTES (newtext
);
2610 unsigned char *substed
;
2611 ptrdiff_t substed_alloc_size
, substed_len
;
2612 bool buf_multibyte
= !NILP (BVAR (current_buffer
, enable_multibyte_characters
));
2613 bool str_multibyte
= STRING_MULTIBYTE (newtext
);
2614 bool really_changed
= 0;
2616 substed_alloc_size
= (length
<= (STRING_BYTES_BOUND
- 100) / 2
2618 : STRING_BYTES_BOUND
);
2619 substed
= xmalloc (substed_alloc_size
);
2622 /* Go thru NEWTEXT, producing the actual text to insert in
2623 SUBSTED while adjusting multibyteness to that of the current
2626 for (pos_byte
= 0, pos
= 0; pos_byte
< length
;)
2628 unsigned char str
[MAX_MULTIBYTE_LENGTH
];
2629 const unsigned char *add_stuff
= NULL
;
2630 ptrdiff_t add_len
= 0;
2632 ptrdiff_t begbyte UNINIT
;
2636 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c
, newtext
, pos
, pos_byte
);
2638 c
= CHAR_TO_BYTE8 (c
);
2642 /* Note that we don't have to increment POS. */
2643 c
= SREF (newtext
, pos_byte
++);
2645 MAKE_CHAR_MULTIBYTE (c
);
2648 /* Either set ADD_STUFF and ADD_LEN to the text to put in SUBSTED,
2649 or set IDX to a match index, which means put that part
2650 of the buffer text into SUBSTED. */
2658 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c
, newtext
,
2660 if (!buf_multibyte
&& !ASCII_CHAR_P (c
))
2661 c
= CHAR_TO_BYTE8 (c
);
2665 c
= SREF (newtext
, pos_byte
++);
2667 MAKE_CHAR_MULTIBYTE (c
);
2672 else if (c
>= '1' && c
<= '9' && c
- '0' < search_regs
.num_regs
)
2674 if (search_regs
.start
[c
- '0'] >= 1)
2678 add_len
= 1, add_stuff
= (unsigned char *) "\\";
2682 error ("Invalid use of `\\' in replacement text");
2687 add_len
= CHAR_STRING (c
, str
);
2691 /* If we want to copy part of a previous match,
2692 set up ADD_STUFF and ADD_LEN to point to it. */
2695 begbyte
= CHAR_TO_BYTE (search_regs
.start
[idx
]);
2696 add_len
= CHAR_TO_BYTE (search_regs
.end
[idx
]) - begbyte
;
2697 if (search_regs
.start
[idx
] < GPT
&& GPT
< search_regs
.end
[idx
])
2698 move_gap_both (search_regs
.start
[idx
], begbyte
);
2701 /* Now the stuff we want to add to SUBSTED
2702 is invariably ADD_LEN bytes starting at ADD_STUFF. */
2704 /* Make sure SUBSTED is big enough. */
2705 if (substed_alloc_size
- substed_len
< add_len
)
2707 xpalloc (substed
, &substed_alloc_size
,
2708 add_len
- (substed_alloc_size
- substed_len
),
2709 STRING_BYTES_BOUND
, 1);
2711 /* We compute this after the call to xpalloc, because that
2712 could cause buffer text be relocated when ralloc.c is used. */
2714 add_stuff
= BYTE_POS_ADDR (begbyte
);
2716 /* Now add to the end of SUBSTED. */
2719 memcpy (substed
+ substed_len
, add_stuff
, add_len
);
2720 substed_len
+= add_len
;
2725 newtext
= make_specified_string ((const char *) substed
, -1,
2726 substed_len
, buf_multibyte
);
2730 /* The functions below modify the buffer, so they could trigger
2731 various modification hooks (see signal_before_change and
2732 signal_after_change). If these hooks clobber the match data we
2733 error out since otherwise this will result in confusing bugs. */
2734 ptrdiff_t sub_start
= search_regs
.start
[sub
];
2735 ptrdiff_t sub_end
= search_regs
.end
[sub
];
2736 unsigned num_regs
= search_regs
.num_regs
;
2737 newpoint
= search_regs
.start
[sub
] + SCHARS (newtext
);
2739 /* Replace the old text with the new in the cleanest possible way. */
2740 replace_range (search_regs
.start
[sub
], search_regs
.end
[sub
],
2741 newtext
, 1, 0, 1, 1);
2742 /* Update saved data to match adjustment made by replace_range. */
2744 ptrdiff_t change
= newpoint
- sub_end
;
2745 if (sub_start
>= sub_end
)
2746 sub_start
+= change
;
2750 if (case_action
== all_caps
)
2751 Fupcase_region (make_number (search_regs
.start
[sub
]),
2752 make_number (newpoint
),
2754 else if (case_action
== cap_initial
)
2755 Fupcase_initials_region (make_number (search_regs
.start
[sub
]),
2756 make_number (newpoint
));
2758 if (search_regs
.start
[sub
] != sub_start
2759 || search_regs
.end
[sub
] != sub_end
2760 || search_regs
.num_regs
!= num_regs
)
2761 error ("Match data clobbered by buffer modification hooks");
2763 /* Put point back where it was in the text. */
2765 TEMP_SET_PT (opoint
+ ZV
);
2767 TEMP_SET_PT (opoint
);
2769 /* Now move point "officially" to the start of the inserted replacement. */
2770 move_if_not_intangible (newpoint
);
2776 match_limit (Lisp_Object num
, bool beginningp
)
2783 args_out_of_range (num
, make_number (0));
2784 if (search_regs
.num_regs
<= 0)
2785 error ("No match data, because no search succeeded");
2786 if (n
>= search_regs
.num_regs
2787 || search_regs
.start
[n
] < 0)
2789 return (make_number ((beginningp
) ? search_regs
.start
[n
]
2790 : search_regs
.end
[n
]));
2793 DEFUN ("match-beginning", Fmatch_beginning
, Smatch_beginning
, 1, 1, 0,
2794 doc
: /* Return position of start of text matched by last search.
2795 SUBEXP, a number, specifies which parenthesized expression in the last
2797 Value is nil if SUBEXPth pair didn't match, or there were less than
2799 Zero means the entire text matched by the whole regexp or whole string.
2801 Return value is undefined if the last search failed. */)
2802 (Lisp_Object subexp
)
2804 return match_limit (subexp
, 1);
2807 DEFUN ("match-end", Fmatch_end
, Smatch_end
, 1, 1, 0,
2808 doc
: /* Return position of end of text matched by last search.
2809 SUBEXP, a number, specifies which parenthesized expression in the last
2811 Value is nil if SUBEXPth pair didn't match, or there were less than
2813 Zero means the entire text matched by the whole regexp or whole string.
2815 Return value is undefined if the last search failed. */)
2816 (Lisp_Object subexp
)
2818 return match_limit (subexp
, 0);
2821 DEFUN ("match-data", Fmatch_data
, Smatch_data
, 0, 3, 0,
2822 doc
: /* Return a list describing what the last search matched.
2823 Element 2N is `(match-beginning N)'; element 2N + 1 is `(match-end N)'.
2824 All the elements are markers or nil (nil if the Nth pair didn't match)
2825 if the last match was on a buffer; integers or nil if a string was matched.
2826 Use `set-match-data' to reinstate the data in this list.
2828 If INTEGERS (the optional first argument) is non-nil, always use
2829 integers (rather than markers) to represent buffer positions. In
2830 this case, and if the last match was in a buffer, the buffer will get
2831 stored as one additional element at the end of the list.
2833 If REUSE is a list, reuse it as part of the value. If REUSE is long
2834 enough to hold all the values, and if INTEGERS is non-nil, no consing
2837 If optional third arg RESEAT is non-nil, any previous markers on the
2838 REUSE list will be modified to point to nowhere.
2840 Return value is undefined if the last search failed. */)
2841 (Lisp_Object integers
, Lisp_Object reuse
, Lisp_Object reseat
)
2843 Lisp_Object tail
, prev
;
2848 for (tail
= reuse
; CONSP (tail
); tail
= XCDR (tail
))
2849 if (MARKERP (XCAR (tail
)))
2851 unchain_marker (XMARKER (XCAR (tail
)));
2852 XSETCAR (tail
, Qnil
);
2855 if (NILP (last_thing_searched
))
2861 SAFE_NALLOCA (data
, 1, 2 * search_regs
.num_regs
+ 1);
2864 for (i
= 0; i
< search_regs
.num_regs
; i
++)
2866 ptrdiff_t start
= search_regs
.start
[i
];
2869 if (EQ (last_thing_searched
, Qt
)
2870 || ! NILP (integers
))
2872 XSETFASTINT (data
[2 * i
], start
);
2873 XSETFASTINT (data
[2 * i
+ 1], search_regs
.end
[i
]);
2875 else if (BUFFERP (last_thing_searched
))
2877 data
[2 * i
] = Fmake_marker ();
2878 Fset_marker (data
[2 * i
],
2879 make_number (start
),
2880 last_thing_searched
);
2881 data
[2 * i
+ 1] = Fmake_marker ();
2882 Fset_marker (data
[2 * i
+ 1],
2883 make_number (search_regs
.end
[i
]),
2884 last_thing_searched
);
2887 /* last_thing_searched must always be Qt, a buffer, or Qnil. */
2893 data
[2 * i
] = data
[2 * i
+ 1] = Qnil
;
2896 if (BUFFERP (last_thing_searched
) && !NILP (integers
))
2898 data
[len
] = last_thing_searched
;
2902 /* If REUSE is not usable, cons up the values and return them. */
2903 if (! CONSP (reuse
))
2904 reuse
= Flist (len
, data
);
2907 /* If REUSE is a list, store as many value elements as will fit
2908 into the elements of REUSE. */
2909 for (i
= 0, tail
= reuse
; CONSP (tail
);
2910 i
++, tail
= XCDR (tail
))
2913 XSETCAR (tail
, data
[i
]);
2915 XSETCAR (tail
, Qnil
);
2919 /* If we couldn't fit all value elements into REUSE,
2920 cons up the rest of them and add them to the end of REUSE. */
2922 XSETCDR (prev
, Flist (len
- i
, data
+ i
));
2929 /* We used to have an internal use variant of `reseat' described as:
2931 If RESEAT is `evaporate', put the markers back on the free list
2932 immediately. No other references to the markers must exist in this
2933 case, so it is used only internally on the unwind stack and
2934 save-match-data from Lisp.
2936 But it was ill-conceived: those supposedly-internal markers get exposed via
2937 the undo-list, so freeing them here is unsafe. */
2939 DEFUN ("set-match-data", Fset_match_data
, Sset_match_data
, 1, 2, 0,
2940 doc
: /* Set internal data on last search match from elements of LIST.
2941 LIST should have been created by calling `match-data' previously.
2943 If optional arg RESEAT is non-nil, make markers on LIST point nowhere. */)
2944 (register Lisp_Object list
, Lisp_Object reseat
)
2947 register Lisp_Object marker
;
2949 if (running_asynch_code
)
2950 save_search_regs ();
2954 /* Unless we find a marker with a buffer or an explicit buffer
2955 in LIST, assume that this match data came from a string. */
2956 last_thing_searched
= Qt
;
2958 /* Allocate registers if they don't already exist. */
2960 EMACS_INT length
= XFASTINT (Flength (list
)) / 2;
2962 if (length
> search_regs
.num_regs
)
2964 ptrdiff_t num_regs
= search_regs
.num_regs
;
2965 if (PTRDIFF_MAX
< length
)
2966 memory_full (SIZE_MAX
);
2968 xpalloc (search_regs
.start
, &num_regs
, length
- num_regs
,
2969 min (PTRDIFF_MAX
, UINT_MAX
), sizeof (regoff_t
));
2971 xrealloc (search_regs
.end
, num_regs
* sizeof (regoff_t
));
2973 for (i
= search_regs
.num_regs
; i
< num_regs
; i
++)
2974 search_regs
.start
[i
] = -1;
2976 search_regs
.num_regs
= num_regs
;
2979 for (i
= 0; CONSP (list
); i
++)
2981 marker
= XCAR (list
);
2982 if (BUFFERP (marker
))
2984 last_thing_searched
= marker
;
2991 search_regs
.start
[i
] = -1;
3000 if (MARKERP (marker
))
3002 if (XMARKER (marker
)->buffer
== 0)
3003 XSETFASTINT (marker
, 0);
3005 XSETBUFFER (last_thing_searched
, XMARKER (marker
)->buffer
);
3008 CHECK_NUMBER_COERCE_MARKER (marker
);
3011 if (!NILP (reseat
) && MARKERP (m
))
3013 unchain_marker (XMARKER (m
));
3014 XSETCAR (list
, Qnil
);
3017 if ((list
= XCDR (list
), !CONSP (list
)))
3020 m
= marker
= XCAR (list
);
3022 if (MARKERP (marker
) && XMARKER (marker
)->buffer
== 0)
3023 XSETFASTINT (marker
, 0);
3025 CHECK_NUMBER_COERCE_MARKER (marker
);
3026 if ((XINT (from
) < 0
3027 ? TYPE_MINIMUM (regoff_t
) <= XINT (from
)
3028 : XINT (from
) <= TYPE_MAXIMUM (regoff_t
))
3029 && (XINT (marker
) < 0
3030 ? TYPE_MINIMUM (regoff_t
) <= XINT (marker
)
3031 : XINT (marker
) <= TYPE_MAXIMUM (regoff_t
)))
3033 search_regs
.start
[i
] = XINT (from
);
3034 search_regs
.end
[i
] = XINT (marker
);
3038 search_regs
.start
[i
] = -1;
3041 if (!NILP (reseat
) && MARKERP (m
))
3043 unchain_marker (XMARKER (m
));
3044 XSETCAR (list
, Qnil
);
3050 for (; i
< search_regs
.num_regs
; i
++)
3051 search_regs
.start
[i
] = -1;
3057 /* If true the match data have been saved in saved_search_regs
3058 during the execution of a sentinel or filter. */
3059 /* static bool search_regs_saved; */
3060 /* static struct re_registers saved_search_regs; */
3061 /* static Lisp_Object saved_last_thing_searched; */
3063 /* Called from Flooking_at, Fstring_match, search_buffer, Fstore_match_data
3064 if asynchronous code (filter or sentinel) is running. */
3066 save_search_regs (void)
3068 if (!search_regs_saved
)
3070 saved_search_regs
.num_regs
= search_regs
.num_regs
;
3071 saved_search_regs
.start
= search_regs
.start
;
3072 saved_search_regs
.end
= search_regs
.end
;
3073 saved_last_thing_searched
= last_thing_searched
;
3074 last_thing_searched
= Qnil
;
3075 search_regs
.num_regs
= 0;
3076 search_regs
.start
= 0;
3077 search_regs
.end
= 0;
3079 search_regs_saved
= 1;
3083 /* Called upon exit from filters and sentinels. */
3085 restore_search_regs (void)
3087 if (search_regs_saved
)
3089 if (search_regs
.num_regs
> 0)
3091 xfree (search_regs
.start
);
3092 xfree (search_regs
.end
);
3094 search_regs
.num_regs
= saved_search_regs
.num_regs
;
3095 search_regs
.start
= saved_search_regs
.start
;
3096 search_regs
.end
= saved_search_regs
.end
;
3097 last_thing_searched
= saved_last_thing_searched
;
3098 saved_last_thing_searched
= Qnil
;
3099 search_regs_saved
= 0;
3103 /* Called from replace-match via replace_range. */
3105 update_search_regs (ptrdiff_t oldstart
, ptrdiff_t oldend
, ptrdiff_t newend
)
3107 /* Adjust search data for this change. */
3108 ptrdiff_t change
= newend
- oldend
;
3111 for (i
= 0; i
< search_regs
.num_regs
; i
++)
3113 if (search_regs
.start
[i
] >= oldend
)
3114 search_regs
.start
[i
] += change
;
3115 else if (search_regs
.start
[i
] > oldstart
)
3116 search_regs
.start
[i
] = oldstart
;
3117 if (search_regs
.end
[i
] >= oldend
)
3118 search_regs
.end
[i
] += change
;
3119 else if (search_regs
.end
[i
] > oldstart
)
3120 search_regs
.end
[i
] = oldstart
;
3125 unwind_set_match_data (Lisp_Object list
)
3127 /* It is NOT ALWAYS safe to free (evaporate) the markers immediately. */
3128 Fset_match_data (list
, Qt
);
3131 /* Called to unwind protect the match data. */
3133 record_unwind_save_match_data (void)
3135 record_unwind_protect (unwind_set_match_data
,
3136 Fmatch_data (Qnil
, Qnil
, Qnil
));
3139 /* Quote a string to deactivate reg-expr chars */
3141 DEFUN ("regexp-quote", Fregexp_quote
, Sregexp_quote
, 1, 1, 0,
3142 doc
: /* Return a regexp string which matches exactly STRING and nothing else. */)
3143 (Lisp_Object string
)
3145 char *in
, *out
, *end
;
3147 ptrdiff_t backslashes_added
= 0;
3149 CHECK_STRING (string
);
3152 SAFE_NALLOCA (temp
, 2, SBYTES (string
));
3154 /* Now copy the data into the new string, inserting escapes. */
3156 in
= SSDATA (string
);
3157 end
= in
+ SBYTES (string
);
3160 for (; in
!= end
; in
++)
3163 || *in
== '*' || *in
== '.' || *in
== '\\'
3164 || *in
== '?' || *in
== '+'
3165 || *in
== '^' || *in
== '$')
3166 *out
++ = '\\', backslashes_added
++;
3171 = make_specified_string (temp
,
3172 SCHARS (string
) + backslashes_added
,
3174 STRING_MULTIBYTE (string
));
3179 /* Like find_newline, but doesn't use the cache, and only searches forward. */
3181 find_newline1 (ptrdiff_t start
, ptrdiff_t start_byte
, ptrdiff_t end
,
3182 ptrdiff_t end_byte
, ptrdiff_t count
, ptrdiff_t *shortage
,
3183 ptrdiff_t *bytepos
, bool allow_quit
)
3188 end
= ZV
, end_byte
= ZV_BYTE
;
3193 end
= BEGV
, end_byte
= BEGV_BYTE
;
3196 end_byte
= CHAR_TO_BYTE (end
);
3202 while (start
!= end
)
3204 /* Our innermost scanning loop is very simple; it doesn't know
3205 about gaps, buffer ends, or the newline cache. ceiling is
3206 the position of the last character before the next such
3207 obstacle --- the last character the dumb search loop should
3209 ptrdiff_t tem
, ceiling_byte
= end_byte
- 1;
3211 if (start_byte
== -1)
3212 start_byte
= CHAR_TO_BYTE (start
);
3214 /* The dumb loop can only scan text stored in contiguous
3215 bytes. BUFFER_CEILING_OF returns the last character
3216 position that is contiguous, so the ceiling is the
3217 position after that. */
3218 tem
= BUFFER_CEILING_OF (start_byte
);
3219 ceiling_byte
= min (tem
, ceiling_byte
);
3222 /* The termination address of the dumb loop. */
3223 unsigned char *lim_addr
= BYTE_POS_ADDR (ceiling_byte
) + 1;
3224 ptrdiff_t lim_byte
= ceiling_byte
+ 1;
3226 /* Nonpositive offsets (relative to LIM_ADDR and LIM_BYTE)
3227 of the base, the cursor, and the next line. */
3228 ptrdiff_t base
= start_byte
- lim_byte
;
3229 ptrdiff_t cursor
, next
;
3231 for (cursor
= base
; cursor
< 0; cursor
= next
)
3233 /* The dumb loop. */
3234 unsigned char *nl
= memchr (lim_addr
+ cursor
, '\n', - cursor
);
3235 next
= nl
? nl
- lim_addr
: 0;
3244 *bytepos
= lim_byte
+ next
;
3245 return BYTE_TO_CHAR (lim_byte
+ next
);
3251 start_byte
= lim_byte
;
3252 start
= BYTE_TO_CHAR (start_byte
);
3260 *bytepos
= start_byte
== -1 ? CHAR_TO_BYTE (start
) : start_byte
;
3261 eassert (*bytepos
== CHAR_TO_BYTE (start
));
3266 DEFUN ("newline-cache-check", Fnewline_cache_check
, Snewline_cache_check
,
3268 doc
: /* Check the newline cache of BUFFER against buffer contents.
3270 BUFFER defaults to the current buffer.
3272 Value is an array of 2 sub-arrays of buffer positions for newlines,
3273 the first based on the cache, the second based on actually scanning
3274 the buffer. If the buffer doesn't have a cache, the value is nil. */)
3275 (Lisp_Object buffer
)
3277 struct buffer
*buf
, *old
= NULL
;
3278 ptrdiff_t shortage
, nl_count_cache
, nl_count_buf
;
3279 Lisp_Object cache_newlines
, buf_newlines
, val
;
3280 ptrdiff_t from
, found
, i
;
3283 buf
= current_buffer
;
3286 CHECK_BUFFER (buffer
);
3287 buf
= XBUFFER (buffer
);
3288 old
= current_buffer
;
3290 if (buf
->base_buffer
)
3291 buf
= buf
->base_buffer
;
3293 /* If the buffer doesn't have a newline cache, return nil. */
3294 if (NILP (BVAR (buf
, cache_long_scans
))
3295 || buf
->newline_cache
== NULL
)
3298 /* find_newline can only work on the current buffer. */
3300 set_buffer_internal_1 (buf
);
3302 /* How many newlines are there according to the cache? */
3303 find_newline (BEGV
, BEGV_BYTE
, ZV
, ZV_BYTE
,
3304 TYPE_MAXIMUM (ptrdiff_t), &shortage
, NULL
, true);
3305 nl_count_cache
= TYPE_MAXIMUM (ptrdiff_t) - shortage
;
3307 /* Create vector and populate it. */
3308 cache_newlines
= make_uninit_vector (nl_count_cache
);
3312 for (from
= BEGV
, found
= from
, i
= 0; from
< ZV
; from
= found
, i
++)
3314 ptrdiff_t from_byte
= CHAR_TO_BYTE (from
);
3316 found
= find_newline (from
, from_byte
, 0, -1, 1, &shortage
,
3318 if (shortage
!= 0 || i
>= nl_count_cache
)
3320 ASET (cache_newlines
, i
, make_number (found
- 1));
3322 /* Fill the rest of slots with an invalid position. */
3323 for ( ; i
< nl_count_cache
; i
++)
3324 ASET (cache_newlines
, i
, make_number (-1));
3327 /* Now do the same, but without using the cache. */
3328 find_newline1 (BEGV
, BEGV_BYTE
, ZV
, ZV_BYTE
,
3329 TYPE_MAXIMUM (ptrdiff_t), &shortage
, NULL
, true);
3330 nl_count_buf
= TYPE_MAXIMUM (ptrdiff_t) - shortage
;
3331 buf_newlines
= make_uninit_vector (nl_count_buf
);
3334 for (from
= BEGV
, found
= from
, i
= 0; from
< ZV
; from
= found
, i
++)
3336 ptrdiff_t from_byte
= CHAR_TO_BYTE (from
);
3338 found
= find_newline1 (from
, from_byte
, 0, -1, 1, &shortage
,
3340 if (shortage
!= 0 || i
>= nl_count_buf
)
3342 ASET (buf_newlines
, i
, make_number (found
- 1));
3344 for ( ; i
< nl_count_buf
; i
++)
3345 ASET (buf_newlines
, i
, make_number (-1));
3348 /* Construct the value and return it. */
3349 val
= make_uninit_vector (2);
3350 ASET (val
, 0, cache_newlines
);
3351 ASET (val
, 1, buf_newlines
);
3354 set_buffer_internal_1 (old
);
3359 syms_of_search (void)
3363 for (i
= 0; i
< REGEXP_CACHE_SIZE
; ++i
)
3365 searchbufs
[i
].buf
.allocated
= 100;
3366 searchbufs
[i
].buf
.buffer
= xmalloc (100);
3367 searchbufs
[i
].buf
.fastmap
= searchbufs
[i
].fastmap
;
3368 searchbufs
[i
].regexp
= Qnil
;
3369 searchbufs
[i
].f_whitespace_regexp
= Qnil
;
3370 searchbufs
[i
].syntax_table
= Qnil
;
3371 staticpro (&searchbufs
[i
].regexp
);
3372 staticpro (&searchbufs
[i
].f_whitespace_regexp
);
3373 staticpro (&searchbufs
[i
].syntax_table
);
3374 searchbufs
[i
].next
= (i
== REGEXP_CACHE_SIZE
-1 ? 0 : &searchbufs
[i
+1]);
3376 searchbuf_head
= &searchbufs
[0];
3378 /* Error condition used for failing searches. */
3379 DEFSYM (Qsearch_failed
, "search-failed");
3381 /* Error condition used for failing searches started by user, i.e.,
3382 where failure should not invoke the debugger. */
3383 DEFSYM (Quser_search_failed
, "user-search-failed");
3385 /* Error condition signaled when regexp compile_pattern fails. */
3386 DEFSYM (Qinvalid_regexp
, "invalid-regexp");
3388 Fput (Qsearch_failed
, Qerror_conditions
,
3389 listn (CONSTYPE_PURE
, 2, Qsearch_failed
, Qerror
));
3390 Fput (Qsearch_failed
, Qerror_message
,
3391 build_pure_c_string ("Search failed"));
3393 Fput (Quser_search_failed
, Qerror_conditions
,
3394 listn (CONSTYPE_PURE
, 4,
3395 Quser_search_failed
, Quser_error
, Qsearch_failed
, Qerror
));
3396 Fput (Quser_search_failed
, Qerror_message
,
3397 build_pure_c_string ("Search failed"));
3399 Fput (Qinvalid_regexp
, Qerror_conditions
,
3400 listn (CONSTYPE_PURE
, 2, Qinvalid_regexp
, Qerror
));
3401 Fput (Qinvalid_regexp
, Qerror_message
,
3402 build_pure_c_string ("Invalid regexp"));
3404 last_thing_searched
= Qnil
;
3405 staticpro (&last_thing_searched
);
3407 saved_last_thing_searched
= Qnil
;
3408 staticpro (&saved_last_thing_searched
);
3410 DEFVAR_LISP ("search-spaces-regexp", Vsearch_spaces_regexp
,
3411 doc
: /* Regexp to substitute for bunches of spaces in regexp search.
3412 Some commands use this for user-specified regexps.
3413 Spaces that occur inside character classes or repetition operators
3414 or other such regexp constructs are not replaced with this.
3415 A value of nil (which is the normal value) means treat spaces literally. */);
3416 Vsearch_spaces_regexp
= Qnil
;
3418 DEFSYM (Qinhibit_changing_match_data
, "inhibit-changing-match-data");
3419 DEFVAR_LISP ("inhibit-changing-match-data", Vinhibit_changing_match_data
,
3420 doc
: /* Internal use only.
3421 If non-nil, the primitive searching and matching functions
3422 such as `looking-at', `string-match', `re-search-forward', etc.,
3423 do not set the match data. The proper way to use this variable
3424 is to bind it with `let' around a small expression. */);
3425 Vinhibit_changing_match_data
= Qnil
;
3427 defsubr (&Slooking_at
);
3428 defsubr (&Sposix_looking_at
);
3429 defsubr (&Sstring_match
);
3430 defsubr (&Sposix_string_match
);
3431 defsubr (&Ssearch_forward
);
3432 defsubr (&Ssearch_backward
);
3433 defsubr (&Sre_search_forward
);
3434 defsubr (&Sre_search_backward
);
3435 defsubr (&Sposix_search_forward
);
3436 defsubr (&Sposix_search_backward
);
3437 defsubr (&Sreplace_match
);
3438 defsubr (&Smatch_beginning
);
3439 defsubr (&Smatch_end
);
3440 defsubr (&Smatch_data
);
3441 defsubr (&Sset_match_data
);
3442 defsubr (&Sregexp_quote
);
3443 defsubr (&Snewline_cache_check
);