]> code.delx.au - gnu-emacs/blob - lisp/isearch.el
; Refer to version 25.2 rather than 26.1.
[gnu-emacs] / lisp / isearch.el
1 ;;; isearch.el --- incremental search minor mode
2
3 ;; Copyright (C) 1992-1997, 1999-2016 Free Software Foundation, Inc.
4
5 ;; Author: Daniel LaLiberte <liberte@cs.uiuc.edu>
6 ;; Maintainer: emacs-devel@gnu.org
7 ;; Keywords: matching
8 ;; Package: emacs
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26
27 ;; Instructions
28
29 ;; For programmed use of isearch-mode, e.g. calling (isearch-forward),
30 ;; isearch-mode behaves modally and does not return until the search
31 ;; is completed. It uses a recursive-edit to behave this way.
32
33 ;; The key bindings active within isearch-mode are defined below in
34 ;; `isearch-mode-map'. Also see minibuffer-local-isearch-map
35 ;; for bindings active during `isearch-edit-string'.
36
37 ;; isearch-mode should work even if you switch windows with the mouse,
38 ;; in which case isearch-mode is terminated automatically before the
39 ;; switch.
40
41 ;; The search ring and completion commands automatically put you in
42 ;; the minibuffer to edit the string. This gives you a chance to
43 ;; modify the search string before executing the search. There are
44 ;; three commands to terminate the editing: C-s and C-r exit the
45 ;; minibuffer and search forward and reverse respectively, while C-m
46 ;; exits and searches in the last search direction.
47
48 ;; Exiting immediately from isearch uses isearch-edit-string instead
49 ;; of nonincremental-search, if search-nonincremental-instead is non-nil.
50 ;; The name of this option should probably be changed if we decide to
51 ;; keep the behavior. No point in forcing nonincremental search until
52 ;; the last possible moment.
53
54 ;;; Code:
55
56 (eval-when-compile (require 'cl-lib))
57 \f
58 ;; Some additional options and constants.
59
60 (defgroup isearch nil
61 "Incremental search minor mode."
62 :link '(emacs-commentary-link "isearch")
63 :link '(custom-manual "(emacs)Incremental Search")
64 :prefix "isearch-"
65 :prefix "search-"
66 :group 'matching)
67
68
69 (defcustom search-exit-option t
70 "Non-nil means random control characters terminate incremental search."
71 :type 'boolean)
72
73 (defcustom search-slow-window-lines 1
74 "Number of lines in slow search display windows.
75 These are the short windows used during incremental search on slow terminals.
76 Negative means put the slow search window at the top (normally it's at bottom)
77 and the value is minus the number of lines."
78 :type 'integer)
79
80 (defcustom search-slow-speed 1200
81 "Highest terminal speed at which to use \"slow\" style incremental search.
82 This is the style where a one-line window is created to show the line
83 that the search has reached."
84 :type 'integer)
85
86 (defcustom search-upper-case 'not-yanks
87 "If non-nil, upper case chars disable case fold searching.
88 That is, upper and lower case chars must match exactly.
89 This applies no matter where the chars come from, but does not
90 apply to chars in regexps that are prefixed with `\\'.
91 If this value is `not-yanks', text yanked into the search string
92 in Isearch mode is always downcased."
93 :type '(choice (const :tag "off" nil)
94 (const not-yanks)
95 (other :tag "on" t)))
96
97 (defcustom search-nonincremental-instead t
98 "If non-nil, do a nonincremental search instead of exiting immediately.
99 This affects the behavior of `isearch-exit' and any key bound to that
100 command: if this variable is nil, `isearch-exit' always exits the search;
101 if the value is non-nil, and the search string is empty, `isearch-exit'
102 starts a nonincremental search instead. (Actually, `isearch-edit-string'
103 is called to let you enter the search string, and RET terminates editing
104 and does a nonincremental search.)"
105 :type 'boolean)
106
107 (defcustom search-whitespace-regexp (purecopy "\\s-+")
108 "If non-nil, regular expression to match a sequence of whitespace chars.
109 When you enter a space or spaces in the incremental search, it
110 will match any sequence matched by this regexp. As an exception,
111 spaces are treated normally in regexp incremental search if they
112 occur in a regexp construct like [...] or *, + or ?.
113
114 If the value is a string, it applies to both ordinary and
115 regexp incremental search. If the value is nil, or
116 `isearch-lax-whitespace' is nil for ordinary incremental search, or
117 `isearch-regexp-lax-whitespace' is nil for regexp incremental search,
118 then each space you type matches literally, against one space.
119
120 You might want to use something like \"[ \\t\\r\\n]+\" instead.
121 In the Customization buffer, that is `[' followed by a space,
122 a tab, a carriage return (control-M), a newline, and `]+'."
123 :type '(choice (const :tag "Match Spaces Literally" nil)
124 regexp)
125 :version "24.3")
126
127 (defcustom search-invisible 'open
128 "If t incremental search/query-replace can match hidden text.
129 A nil value means don't match invisible text.
130 When the value is `open', if the text matched is made invisible by
131 an overlay having an `invisible' property and that overlay has a property
132 `isearch-open-invisible', then incremental search will show the contents.
133 \(This applies when using `outline.el' and `hideshow.el'.)
134
135 To temporarily change the value for an active incremental search,
136 use \\<isearch-mode-map>\\[isearch-toggle-invisible].
137
138 See also the related option `isearch-hide-immediately'.
139
140 See also `reveal-mode' if you want overlays to automatically be opened
141 whenever point is in one of them."
142 :type '(choice (const :tag "Match hidden text" t)
143 (const :tag "Open overlays" open)
144 (const :tag "Don't match hidden text" nil)))
145
146 (defcustom isearch-hide-immediately t
147 "If non-nil, re-hide an invisible match right away.
148 This variable makes a difference when `search-invisible' is set to `open'.
149 If non-nil, invisible matches are re-hidden as soon as the match moves
150 off the invisible text surrounding the match.
151 If nil then do not re-hide opened invisible text when the match moves.
152 Whatever the value, all opened invisible text is hidden again after exiting
153 the search, with the exception of the last successful match, if any."
154 :type 'boolean)
155
156 (defcustom isearch-resume-in-command-history nil
157 "If non-nil, `isearch-resume' commands are added to the command history.
158 This allows you to resume earlier Isearch sessions through the
159 command history."
160 :type 'boolean)
161
162 (defvar isearch-mode-hook nil
163 "Function(s) to call after starting up an incremental search.")
164
165 (defvar isearch-update-post-hook nil
166 "Function(s) to call after isearch has found matches in the buffer.")
167
168 (defvar isearch-mode-end-hook nil
169 "Function(s) to call after terminating an incremental search.
170 When these functions are called, `isearch-mode-end-hook-quit'
171 is non-nil if the user quits the search.")
172
173 (defvar isearch-mode-end-hook-quit nil
174 "Non-nil while running `isearch-mode-end-hook' if the user quits the search.")
175
176 (defvar isearch-message-function nil
177 "Function to call to display the search prompt.
178 If nil, use function `isearch-message'.")
179
180 (defvar isearch-wrap-function nil
181 "Function to call to wrap the search when search is failed.
182 If nil, move point to the beginning of the buffer for a forward search,
183 or to the end of the buffer for a backward search.")
184
185 (defvar isearch-push-state-function nil
186 "Function to save a function restoring the mode-specific Isearch state
187 to the search status stack.")
188
189 (defvar isearch-filter-predicate #'isearch-filter-visible
190 "Predicate that filters the search hits that would normally be available.
191 Search hits that dissatisfy the predicate are skipped. The function
192 has two arguments: the positions of start and end of text matched by
193 the search. If this function returns nil, continue searching without
194 stopping at this match.
195 If you use `add-function' to modify this variable, you can use the
196 `isearch-message-prefix' advice property to specify the prefix string
197 displayed in the search message.")
198
199 ;; Search ring.
200
201 (defvar search-ring nil
202 "List of search string sequences.")
203 (defvar regexp-search-ring nil
204 "List of regular expression search string sequences.")
205
206 (defcustom search-ring-max 16
207 "Maximum length of search ring before oldest elements are thrown away."
208 :type 'integer)
209 (defcustom regexp-search-ring-max 16
210 "Maximum length of regexp search ring before oldest elements are thrown away."
211 :type 'integer)
212
213 (defvar search-ring-yank-pointer nil
214 "Index in `search-ring' of last string reused.
215 It is nil if none yet.")
216 (defvar regexp-search-ring-yank-pointer nil
217 "Index in `regexp-search-ring' of last string reused.
218 It is nil if none yet.")
219
220 (defcustom search-ring-update nil
221 "Non-nil if advancing or retreating in the search ring should cause search.
222 Default value, nil, means edit the string instead."
223 :type 'boolean)
224
225 (autoload 'char-fold-to-regexp "char-fold")
226
227 (defcustom search-default-mode nil
228 "Default mode to use when starting isearch.
229 Value is nil, t, or a function.
230
231 If nil, default to literal searches (note that `case-fold-search'
232 and `isearch-lax-whitespace' may still be applied).\\<isearch-mode-map>
233 If t, default to regexp searches (as if typing `\\[isearch-toggle-regexp]' during
234 isearch).
235
236 If a function, use that function as an `isearch-regexp-function'.
237 Example functions (and the keys to toggle them during isearch)
238 are `word-search-regexp' \(`\\[isearch-toggle-word]'), `isearch-symbol-regexp'
239 \(`\\[isearch-toggle-symbol]'), and `char-fold-to-regexp' \(`\\[isearch-toggle-char-fold]')."
240 ;; :type is set below by `isearch-define-mode-toggle'.
241 :type '(choice (const :tag "Literal search" nil)
242 (const :tag "Regexp search" t)
243 (function :tag "Other"))
244 :version "25.1")
245
246 ;;; isearch highlight customization.
247
248 (defcustom search-highlight t
249 "Non-nil means incremental search highlights the current match."
250 :type 'boolean)
251
252 (defface isearch
253 '((((class color) (min-colors 88) (background light))
254 ;; The background must not be too dark, for that means
255 ;; the character is hard to see when the cursor is there.
256 (:background "magenta3" :foreground "lightskyblue1"))
257 (((class color) (min-colors 88) (background dark))
258 (:background "palevioletred2" :foreground "brown4"))
259 (((class color) (min-colors 16))
260 (:background "magenta4" :foreground "cyan1"))
261 (((class color) (min-colors 8))
262 (:background "magenta4" :foreground "cyan1"))
263 (t (:inverse-video t)))
264 "Face for highlighting Isearch matches."
265 :group 'isearch
266 :group 'basic-faces)
267 (defvar isearch-face 'isearch)
268
269 (defface isearch-fail
270 '((((class color) (min-colors 88) (background light))
271 (:background "RosyBrown1"))
272 (((class color) (min-colors 88) (background dark))
273 (:background "red4"))
274 (((class color) (min-colors 16))
275 (:background "red"))
276 (((class color) (min-colors 8))
277 (:background "red"))
278 (((class color grayscale))
279 :foreground "grey")
280 (t (:inverse-video t)))
281 "Face for highlighting failed part in Isearch echo-area message."
282 :version "23.1")
283
284 (defcustom isearch-lazy-highlight t
285 "Controls the lazy-highlighting during incremental search.
286 When non-nil, all text in the buffer matching the current search
287 string is highlighted lazily (see `lazy-highlight-initial-delay'
288 and `lazy-highlight-interval')."
289 :type 'boolean
290 :group 'lazy-highlight
291 :group 'isearch)
292
293 ;;; Lazy highlight customization.
294
295 (defgroup lazy-highlight nil
296 "Lazy highlighting feature for matching strings."
297 :prefix "lazy-highlight-"
298 :version "21.1"
299 :group 'isearch
300 :group 'matching)
301
302 (define-obsolete-variable-alias 'isearch-lazy-highlight-cleanup
303 'lazy-highlight-cleanup
304 "22.1")
305
306 (defcustom lazy-highlight-cleanup t
307 "Controls whether to remove extra highlighting after a search.
308 If this is nil, extra highlighting can be \"manually\" removed with
309 \\[lazy-highlight-cleanup]."
310 :type 'boolean
311 :group 'lazy-highlight)
312
313 (define-obsolete-variable-alias 'isearch-lazy-highlight-initial-delay
314 'lazy-highlight-initial-delay
315 "22.1")
316
317 (defcustom lazy-highlight-initial-delay 0.25
318 "Seconds to wait before beginning to lazily highlight all matches."
319 :type 'number
320 :group 'lazy-highlight)
321
322 (define-obsolete-variable-alias 'isearch-lazy-highlight-interval
323 'lazy-highlight-interval
324 "22.1")
325
326 (defcustom lazy-highlight-interval 0 ; 0.0625
327 "Seconds between lazily highlighting successive matches."
328 :type 'number
329 :group 'lazy-highlight)
330
331 (define-obsolete-variable-alias 'isearch-lazy-highlight-max-at-a-time
332 'lazy-highlight-max-at-a-time
333 "22.1")
334
335 (defcustom lazy-highlight-max-at-a-time 20
336 "Maximum matches to highlight at a time (for `lazy-highlight').
337 Larger values may reduce Isearch's responsiveness to user input;
338 smaller values make matches highlight slowly.
339 A value of nil means highlight all matches."
340 :type '(choice (const :tag "All" nil)
341 (integer :tag "Some"))
342 :group 'lazy-highlight)
343
344 (defface lazy-highlight
345 '((((class color) (min-colors 88) (background light))
346 (:background "paleturquoise"))
347 (((class color) (min-colors 88) (background dark))
348 (:background "paleturquoise4"))
349 (((class color) (min-colors 16))
350 (:background "turquoise3"))
351 (((class color) (min-colors 8))
352 (:background "turquoise3"))
353 (t (:underline t)))
354 "Face for lazy highlighting of matches other than the current one."
355 :group 'lazy-highlight
356 :group 'basic-faces)
357 (define-obsolete-face-alias 'isearch-lazy-highlight-face 'lazy-highlight "22.1")
358 (define-obsolete-variable-alias 'isearch-lazy-highlight-face
359 'lazy-highlight-face
360 "22.1")
361 (defvar lazy-highlight-face 'lazy-highlight)
362 \f
363 ;; Define isearch help map.
364
365 (defvar isearch-help-map
366 (let ((map (make-sparse-keymap)))
367 (define-key map (char-to-string help-char) 'isearch-help-for-help)
368 (define-key map [help] 'isearch-help-for-help)
369 (define-key map [f1] 'isearch-help-for-help)
370 (define-key map "?" 'isearch-help-for-help)
371 (define-key map "b" 'isearch-describe-bindings)
372 (define-key map "k" 'isearch-describe-key)
373 (define-key map "m" 'isearch-describe-mode)
374 (define-key map "q" 'help-quit)
375 map)
376 "Keymap for characters following the Help key for Isearch mode.")
377
378 (eval-when-compile (require 'help-macro))
379
380 (make-help-screen isearch-help-for-help-internal
381 (purecopy "Type a help option: [bkm] or ?")
382 "You have typed %THIS-KEY%, the help character. Type a Help option:
383 \(Type \\<help-map>\\[help-quit] to exit the Help command.)
384
385 b Display all Isearch key bindings.
386 k KEYS Display full documentation of Isearch key sequence.
387 m Display documentation of Isearch mode.
388
389 You can't type here other help keys available in the global help map,
390 but outside of this help window when you type them in Isearch mode,
391 they exit Isearch mode before displaying global help."
392 isearch-help-map)
393
394 (defvar isearch--display-help-action '(nil (inhibit-same-window . t)))
395
396 (defun isearch-help-for-help ()
397 "Display Isearch help menu."
398 (interactive)
399 (let ((display-buffer-overriding-action isearch--display-help-action))
400 (isearch-help-for-help-internal))
401 (isearch-update))
402
403 (defun isearch-describe-bindings ()
404 "Show a list of all keys defined in Isearch mode, and their definitions.
405 This is like `describe-bindings', but displays only Isearch keys."
406 (interactive)
407 (let ((display-buffer-overriding-action isearch--display-help-action))
408 (with-help-window "*Help*"
409 (with-current-buffer standard-output
410 (princ "Isearch Mode Bindings:\n")
411 (princ (substitute-command-keys "\\{isearch-mode-map}"))))))
412
413 (defun isearch-describe-key ()
414 "Display documentation of the function invoked by isearch key."
415 (interactive)
416 (let ((display-buffer-overriding-action isearch--display-help-action))
417 (call-interactively 'describe-key))
418 (isearch-update))
419
420 (defun isearch-describe-mode ()
421 "Display documentation of Isearch mode."
422 (interactive)
423 (let ((display-buffer-overriding-action isearch--display-help-action))
424 (describe-function 'isearch-forward))
425 (isearch-update))
426
427 (defalias 'isearch-mode-help 'isearch-describe-mode)
428
429 \f
430 ;; Define isearch-mode keymap.
431
432 (defvar isearch-mode-map
433 (let ((i 0)
434 (map (make-keymap)))
435 (or (char-table-p (nth 1 map))
436 (error "The initialization of isearch-mode-map must be updated"))
437 ;; Make all multibyte characters search for themselves.
438 (set-char-table-range (nth 1 map) (cons #x100 (max-char))
439 'isearch-printing-char)
440
441 ;; Single-byte printing chars extend the search string by default.
442 (setq i ?\s)
443 (while (< i 256)
444 (define-key map (vector i) 'isearch-printing-char)
445 (setq i (1+ i)))
446
447 ;; To handle local bindings with meta char prefix keys, define
448 ;; another full keymap. This must be done for any other prefix
449 ;; keys as well, one full keymap per char of the prefix key. It
450 ;; would be simpler to disable the global keymap, and/or have a
451 ;; default local key binding for any key not otherwise bound.
452 (let ((meta-map (make-sparse-keymap)))
453 (define-key map (char-to-string meta-prefix-char) meta-map))
454
455 ;; Several non-printing chars change the searching behavior.
456 (define-key map "\C-s" 'isearch-repeat-forward)
457 (define-key map "\C-r" 'isearch-repeat-backward)
458 ;; Define M-C-s and M-C-r like C-s and C-r so that the same key
459 ;; combinations can be used to repeat regexp isearches that can
460 ;; be used to start these searches.
461 (define-key map "\M-\C-s" 'isearch-repeat-forward)
462 (define-key map "\M-\C-r" 'isearch-repeat-backward)
463 (define-key map "\177" 'isearch-delete-char)
464 (define-key map [backspace] 'undefined) ;bug#20466.
465 (define-key map "\C-g" 'isearch-abort)
466
467 ;; This assumes \e is the meta-prefix-char.
468 (or (= ?\e meta-prefix-char)
469 (error "Inconsistency in isearch.el"))
470 (define-key map "\e\e\e" 'isearch-cancel)
471
472 (define-key map "\C-q" 'isearch-quote-char)
473
474 (define-key map "\r" 'isearch-exit)
475 (define-key map [return] 'isearch-exit)
476 (define-key map "\C-j" 'isearch-printing-char)
477 (define-key map "\t" 'isearch-printing-char)
478 (define-key map [?\S-\ ] 'isearch-printing-char)
479
480 (define-key map "\C-w" 'isearch-yank-word-or-char)
481 (define-key map "\M-\C-w" 'isearch-del-char)
482 (define-key map "\M-\C-y" 'isearch-yank-char)
483 (define-key map "\C-y" 'isearch-yank-kill)
484 (define-key map "\M-s\C-e" 'isearch-yank-line)
485
486 (define-key map (char-to-string help-char) isearch-help-map)
487 (define-key map [help] isearch-help-map)
488 (define-key map [f1] isearch-help-map)
489
490 (define-key map "\M-n" 'isearch-ring-advance)
491 (define-key map "\M-p" 'isearch-ring-retreat)
492 (define-key map "\M-y" 'isearch-yank-pop)
493
494 (define-key map "\M-\t" 'isearch-complete)
495
496 ;; Pass frame events transparently so they won't exit the search.
497 ;; In particular, if we have more than one display open, then a
498 ;; switch-frame might be generated by someone typing at another keyboard.
499 (define-key map [switch-frame] nil)
500 (define-key map [delete-frame] nil)
501 (define-key map [iconify-frame] nil)
502 (define-key map [make-frame-visible] nil)
503 (define-key map [mouse-movement] nil)
504 (define-key map [language-change] nil)
505
506 ;; For searching multilingual text.
507 (define-key map "\C-\\" 'isearch-toggle-input-method)
508 (define-key map "\C-^" 'isearch-toggle-specified-input-method)
509
510 ;; People expect to be able to paste with the mouse.
511 (define-key map [mouse-2] #'isearch-mouse-2)
512 (define-key map [down-mouse-2] nil)
513 (define-key map [xterm-paste] #'isearch-xterm-paste)
514
515 ;; Some bindings you may want to put in your isearch-mode-hook.
516 ;; Suggest some alternates...
517 (define-key map "\M-c" 'isearch-toggle-case-fold)
518 (define-key map "\M-r" 'isearch-toggle-regexp)
519 (define-key map "\M-e" 'isearch-edit-string)
520
521 (put 'isearch-edit-string :advertised-binding "\M-se")
522
523 (define-key map "\M-se" 'isearch-edit-string)
524 ;; More toggles defined by `isearch-define-mode-toggle'.
525
526 (define-key map [?\M-%] 'isearch-query-replace)
527 (define-key map [?\C-\M-%] 'isearch-query-replace-regexp)
528 (define-key map "\M-so" 'isearch-occur)
529 (define-key map "\M-shr" 'isearch-highlight-regexp)
530
531 ;; The key translations defined in the C-x 8 prefix should add
532 ;; characters to the search string. See iso-transl.el.
533 (define-key map "\C-x8\r" 'isearch-char-by-name)
534
535 map)
536 "Keymap for `isearch-mode'.")
537
538 (defvar minibuffer-local-isearch-map
539 (let ((map (make-sparse-keymap)))
540 (set-keymap-parent map minibuffer-local-map)
541 (define-key map "\r" 'exit-minibuffer)
542 (define-key map "\M-\t" 'isearch-complete-edit)
543 (define-key map "\C-s" 'isearch-forward-exit-minibuffer)
544 (define-key map "\C-r" 'isearch-reverse-exit-minibuffer)
545 (define-key map "\C-f" 'isearch-yank-char-in-minibuffer)
546 (define-key map [right] 'isearch-yank-char-in-minibuffer)
547 map)
548 "Keymap for editing Isearch strings in the minibuffer.")
549
550 ;; Internal variables declared globally for byte-compiler.
551 ;; These are all set with setq while isearching
552 ;; and bound locally while editing the search string.
553
554 (defvar isearch-forward nil) ; Searching in the forward direction.
555 (defvar isearch-regexp nil) ; Searching for a regexp.
556 (defvar isearch-regexp-function nil
557 "Regexp-based search mode for words/symbols.
558 If the value is a function (e.g. `isearch-symbol-regexp'), it is
559 called to convert a plain search string to a regexp used by
560 regexp search functions.
561 The symbol property `isearch-message-prefix' put on this function
562 specifies the prefix string displayed in the search message.
563
564 This variable is set and changed during isearch. To change the
565 default behaviour used for searches, see `search-default-mode'
566 instead.")
567 ;; We still support setting this to t for backwards compatibility.
568 (define-obsolete-variable-alias 'isearch-word
569 'isearch-regexp-function "25.1")
570
571 (defvar isearch-lax-whitespace t
572 "If non-nil, a space will match a sequence of whitespace chars.
573 When you enter a space or spaces in ordinary incremental search, it
574 will match any sequence matched by the regexp defined by the variable
575 `search-whitespace-regexp'. If the value is nil, each space you type
576 matches literally, against one space. You can toggle the value of this
577 variable by the command `isearch-toggle-lax-whitespace'.")
578
579 (defvar isearch-regexp-lax-whitespace nil
580 "If non-nil, a space will match a sequence of whitespace chars.
581 When you enter a space or spaces in regexp incremental search, it
582 will match any sequence matched by the regexp defined by the variable
583 `search-whitespace-regexp'. If the value is nil, each space you type
584 matches literally, against one space. You can toggle the value of this
585 variable by the command `isearch-toggle-lax-whitespace'.")
586
587 (defvar isearch-cmds nil
588 "Stack of search status elements.
589 Each element is an `isearch--state' struct where the slots are
590 [STRING MESSAGE POINT SUCCESS FORWARD OTHER-END WORD
591 ERROR WRAPPED BARRIER CASE-FOLD-SEARCH]")
592
593 (defvar isearch-string "") ; The current search string.
594 (defvar isearch-message "") ; text-char-description version of isearch-string
595
596 (defvar isearch-message-prefix-add nil) ; Additional text for the message prefix
597 (defvar isearch-message-suffix-add nil) ; Additional text for the message suffix
598
599 (defvar isearch-success t) ; Searching is currently successful.
600 (defvar isearch-error nil) ; Error message for failed search.
601 (defvar isearch-other-end nil) ; Start (end) of match if forward (backward).
602 (defvar isearch-wrapped nil) ; Searching restarted from the top (bottom).
603 (defvar isearch-barrier 0
604 "Recorded minimum/maximal point for the current search.")
605 (defvar isearch-just-started nil)
606 (defvar isearch-start-hscroll 0) ; hscroll when starting the search.
607
608 ;; case-fold-search while searching.
609 ;; either nil, t, or 'yes. 'yes means the same as t except that mixed
610 ;; case in the search string is ignored.
611 (defvar isearch-case-fold-search nil)
612
613 ;; search-invisible while searching.
614 ;; either nil, t, or 'open. 'open means the same as t except that
615 ;; opens hidden overlays.
616 (defvar isearch-invisible search-invisible)
617
618 (defvar isearch-last-case-fold-search nil)
619
620 ;; Used to save default value while isearch is active
621 (defvar isearch-original-minibuffer-message-timeout nil)
622
623 (defvar isearch-adjusted nil)
624 (defvar isearch-slow-terminal-mode nil)
625 ;; If t, using a small window.
626 (defvar isearch-small-window nil)
627 (defvar isearch-opoint 0)
628 ;; The window configuration active at the beginning of the search.
629 (defvar isearch-window-configuration nil)
630
631 ;; Flag to indicate a yank occurred, so don't move the cursor.
632 (defvar isearch-yank-flag nil)
633
634 ;; A function to be called after each input character is processed.
635 ;; (It is not called after characters that exit the search.)
636 ;; It is only set from an optional argument to `isearch-mode'.
637 (defvar isearch-op-fun nil)
638
639 ;; Is isearch-mode in a recursive edit for modal searching.
640 (defvar isearch-recursive-edit nil)
641
642 ;; Should isearch be terminated after doing one search?
643 (defvar isearch-nonincremental nil)
644
645 ;; New value of isearch-forward after isearch-edit-string.
646 (defvar isearch-new-forward nil)
647
648 ;; Accumulate here the overlays opened during searching.
649 (defvar isearch-opened-overlays nil)
650
651 ;; Non-nil if the string exists but is invisible.
652 (defvar isearch-hidden nil)
653
654 ;; The value of input-method-function when isearch is invoked.
655 (defvar isearch-input-method-function nil)
656
657 ;; A flag to tell if input-method-function is locally bound when
658 ;; isearch is invoked.
659 (defvar isearch-input-method-local-p nil)
660
661 (defvar isearch--saved-overriding-local-map nil)
662
663 ;; Minor-mode-alist changes - kind of redundant with the
664 ;; echo area, but if isearching in multiple windows, it can be useful.
665
666 (or (assq 'isearch-mode minor-mode-alist)
667 (nconc minor-mode-alist
668 (list '(isearch-mode isearch-mode))))
669
670 (defvar-local isearch-mode nil) ;; Name of the minor mode, if non-nil.
671
672 (define-key global-map "\C-s" 'isearch-forward)
673 (define-key esc-map "\C-s" 'isearch-forward-regexp)
674 (define-key global-map "\C-r" 'isearch-backward)
675 (define-key esc-map "\C-r" 'isearch-backward-regexp)
676 (define-key search-map "w" 'isearch-forward-word)
677 (define-key search-map "_" 'isearch-forward-symbol)
678 (define-key search-map "." 'isearch-forward-symbol-at-point)
679
680 ;; Entry points to isearch-mode.
681
682 (defun isearch-forward (&optional regexp-p no-recursive-edit)
683 "\
684 Do incremental search forward.
685 With a prefix argument, do an incremental regular expression search instead.
686 \\<isearch-mode-map>
687 As you type characters, they add to the search string and are found.
688 The following non-printing keys are bound in `isearch-mode-map'.
689
690 Type \\[isearch-delete-char] to cancel last input item from end of search string.
691 Type \\[isearch-exit] to exit, leaving point at location found.
692 Type LFD (C-j) to match end of line.
693 Type \\[isearch-repeat-forward] to search again forward,\
694 \\[isearch-repeat-backward] to search again backward.
695 Type \\[isearch-yank-word-or-char] to yank next word or character in buffer
696 onto the end of the search string, and search for it.
697 Type \\[isearch-del-char] to delete character from end of search string.
698 Type \\[isearch-yank-char] to yank char from buffer onto end of search\
699 string and search for it.
700 Type \\[isearch-yank-line] to yank rest of line onto end of search string\
701 and search for it.
702 Type \\[isearch-yank-kill] to yank the last string of killed text.
703 Type \\[isearch-yank-pop] to replace string just yanked into search prompt
704 with string killed before it.
705 Type \\[isearch-quote-char] to quote control character to search for it.
706 Type \\[isearch-char-by-name] to add a character to search by Unicode name,\
707 with completion.
708 \\[isearch-abort] while searching or when search has failed cancels input\
709 back to what has
710 been found successfully.
711 \\[isearch-abort] when search is successful aborts and moves point to\
712 starting point.
713
714 If you try to exit with the search string still empty, it invokes
715 nonincremental search.
716
717 Type \\[isearch-toggle-case-fold] to toggle search case-sensitivity.
718 Type \\[isearch-toggle-invisible] to toggle search in invisible text.
719 Type \\[isearch-toggle-regexp] to toggle regular-expression mode.
720 Type \\[isearch-toggle-word] to toggle word mode.
721 Type \\[isearch-toggle-symbol] to toggle symbol mode.
722 Type \\[isearch-toggle-char-fold] to toggle character folding.
723
724 Type \\[isearch-toggle-lax-whitespace] to toggle whitespace matching.
725 In incremental searches, a space or spaces normally matches any whitespace
726 defined by the variable `search-whitespace-regexp'; see also the variables
727 `isearch-lax-whitespace' and `isearch-regexp-lax-whitespace'.
728
729 Type \\[isearch-edit-string] to edit the search string in the minibuffer.
730
731 Also supported is a search ring of the previous 16 search strings.
732 Type \\[isearch-ring-advance] to search for the next item in the search ring.
733 Type \\[isearch-ring-retreat] to search for the previous item in the search\
734 ring.
735 Type \\[isearch-complete] to complete the search string using the search ring.
736
737 Type \\[isearch-query-replace] to run `query-replace' with string to\
738 replace from last search string.
739 Type \\[isearch-query-replace-regexp] to run `query-replace-regexp'\
740 with the last search string.
741 Type \\[isearch-occur] to run `occur' that shows\
742 the last search string.
743 Type \\[isearch-highlight-regexp] to run `highlight-regexp'\
744 that highlights the last search string.
745
746 Type \\[isearch-describe-bindings] to display all Isearch key bindings.
747 Type \\[isearch-describe-key] to display documentation of Isearch key.
748 Type \\[isearch-describe-mode] to display documentation of Isearch mode.
749
750 If an input method is turned on in the current buffer, that input
751 method is also active while you are typing characters to search.
752 To toggle the input method, type \\[isearch-toggle-input-method]. \
753 It also toggles the input
754 method in the current buffer.
755
756 To use a different input method for searching, type \
757 \\[isearch-toggle-specified-input-method],
758 and specify an input method you want to use.
759
760 The above keys, bound in `isearch-mode-map', are often controlled by
761 options; do \\[apropos] on search-.* to find them.
762 Other control and meta characters terminate the search
763 and are then executed normally (depending on `search-exit-option').
764 Likewise for function keys and mouse button events.
765
766 If this function is called non-interactively with a nil NO-RECURSIVE-EDIT,
767 it does not return to the calling function until the search is done.
768 See the function `isearch-mode' for more information."
769
770 (interactive "P\np")
771 (isearch-mode t (not (null regexp-p)) nil (not no-recursive-edit)))
772
773 (defun isearch-forward-regexp (&optional not-regexp no-recursive-edit)
774 "Do incremental search forward for regular expression.
775 With a prefix argument, do a regular string search instead.
776 Like ordinary incremental search except that your input is treated
777 as a regexp. See the command `isearch-forward' for more information.
778
779 In incremental searches, a space or spaces normally matches any
780 whitespace defined by the variable `search-whitespace-regexp'.
781 To search for a literal space and nothing else, enter C-q SPC.
782 To toggle whitespace matching, use `isearch-toggle-lax-whitespace'.
783 This command does not support character folding."
784 (interactive "P\np")
785 (isearch-mode t (null not-regexp) nil (not no-recursive-edit)))
786
787 (defun isearch-forward-word (&optional not-word no-recursive-edit)
788 "Do incremental search forward for a sequence of words.
789 With a prefix argument, do a regular string search instead.
790 Like ordinary incremental search except that your input is treated
791 as a sequence of words without regard to how the words are separated.
792 See the command `isearch-forward' for more information.
793 This command does not support character folding, and lax space matching
794 has no effect on it."
795 (interactive "P\np")
796 (isearch-mode t nil nil (not no-recursive-edit) (null not-word)))
797
798 (defun isearch-forward-symbol (&optional _not-symbol no-recursive-edit)
799 "Do incremental search forward for a symbol.
800 The prefix argument is currently unused.
801 Like ordinary incremental search except that your input is treated
802 as a symbol surrounded by symbol boundary constructs \\_< and \\_>.
803 See the command `isearch-forward' for more information.
804 This command does not support character folding, and lax space matching
805 has no effect on it."
806 (interactive "P\np")
807 (isearch-mode t nil nil (not no-recursive-edit) 'isearch-symbol-regexp))
808
809 (defun isearch-backward (&optional regexp-p no-recursive-edit)
810 "Do incremental search backward.
811 With a prefix argument, do a regular expression search instead.
812 See the command `isearch-forward' for more information."
813 (interactive "P\np")
814 (isearch-mode nil (not (null regexp-p)) nil (not no-recursive-edit)))
815
816 (defun isearch-backward-regexp (&optional not-regexp no-recursive-edit)
817 "Do incremental search backward for regular expression.
818 With a prefix argument, do a regular string search instead.
819 Like ordinary incremental search except that your input is treated
820 as a regexp. See the command `isearch-forward-regexp' for more information."
821 (interactive "P\np")
822 (isearch-mode nil (null not-regexp) nil (not no-recursive-edit)))
823
824 (defun isearch-forward-symbol-at-point ()
825 "Do incremental search forward for a symbol found near point.
826 Like ordinary incremental search except that the symbol found at point
827 is added to the search string initially as a regexp surrounded
828 by symbol boundary constructs \\_< and \\_>.
829 See the command `isearch-forward-symbol' for more information."
830 (interactive)
831 (isearch-forward-symbol nil 1)
832 (let ((bounds (find-tag-default-bounds)))
833 (cond
834 (bounds
835 (when (< (car bounds) (point))
836 (goto-char (car bounds)))
837 (isearch-yank-string
838 (buffer-substring-no-properties (car bounds) (cdr bounds))))
839 (t
840 (setq isearch-error "No symbol at point")
841 (isearch-push-state)
842 (isearch-update)))))
843
844 \f
845 ;; isearch-mode only sets up incremental search for the minor mode.
846 ;; All the work is done by the isearch-mode commands.
847
848 ;; Not used yet:
849 ;;(defvar isearch-commands '(isearch-forward isearch-backward
850 ;; isearch-forward-regexp isearch-backward-regexp)
851 ;; "List of commands for which isearch-mode does not recursive-edit.")
852
853 (defun isearch-mode (forward &optional regexp op-fun recursive-edit regexp-function)
854 "Start Isearch minor mode.
855 It is called by the function `isearch-forward' and other related functions.
856
857 The non-nil arg FORWARD means searching in the forward direction.
858
859 The non-nil arg REGEXP does an incremental regular expression search.
860
861 The arg OP-FUN is a function to be called after each input character
862 is processed. (It is not called after characters that exit the search.)
863
864 When the arg RECURSIVE-EDIT is non-nil, this function behaves modally and
865 does not return to the calling function until the search is completed.
866 To behave this way it enters a recursive-edit and exits it when done
867 isearching.
868
869 The arg REGEXP-FUNCTION, if non-nil, should be a function. It is
870 used to set the value of `isearch-regexp-function'."
871
872 ;; Initialize global vars.
873 (setq isearch-forward forward
874 isearch-regexp (or regexp
875 (and (not regexp-function)
876 (eq search-default-mode t)))
877 isearch-regexp-function (or regexp-function
878 (and (functionp search-default-mode)
879 (not regexp)
880 search-default-mode))
881 isearch-op-fun op-fun
882 isearch-last-case-fold-search isearch-case-fold-search
883 isearch-case-fold-search case-fold-search
884 isearch-invisible search-invisible
885 isearch-string ""
886 isearch-message ""
887 isearch-cmds nil
888 isearch-success t
889 isearch-wrapped nil
890 isearch-barrier (point)
891 isearch-adjusted nil
892 isearch-yank-flag nil
893 isearch-error nil
894 isearch-slow-terminal-mode (and (<= baud-rate search-slow-speed)
895 (> (window-height)
896 (* 4
897 (abs search-slow-window-lines))))
898 isearch-other-end nil
899 isearch-small-window nil
900 isearch-just-started t
901 isearch-start-hscroll (window-hscroll)
902
903 isearch-opoint (point)
904 search-ring-yank-pointer nil
905 isearch-opened-overlays nil
906 isearch-input-method-function input-method-function
907 isearch-input-method-local-p (local-variable-p 'input-method-function)
908 regexp-search-ring-yank-pointer nil
909
910 ;; Save the original value of `minibuffer-message-timeout', and
911 ;; set it to nil so that isearch's messages don't get timed out.
912 isearch-original-minibuffer-message-timeout minibuffer-message-timeout
913 minibuffer-message-timeout nil)
914
915 ;; We must bypass input method while reading key. When a user type
916 ;; printable character, appropriate input method is turned on in
917 ;; minibuffer to read multibyte characters.
918 (or isearch-input-method-local-p
919 (make-local-variable 'input-method-function))
920 (setq input-method-function nil)
921
922 (looking-at "")
923 (setq isearch-window-configuration
924 (if isearch-slow-terminal-mode (current-window-configuration) nil))
925
926 ;; Maybe make minibuffer frame visible and/or raise it.
927 (let ((frame (window-frame (minibuffer-window))))
928 (unless (memq (frame-live-p frame) '(nil t))
929 (unless (frame-visible-p frame)
930 (make-frame-visible frame))
931 (if minibuffer-auto-raise
932 (raise-frame frame))))
933
934 (setq isearch-mode " Isearch") ;; forward? regexp?
935 (force-mode-line-update)
936
937 (setq overriding-terminal-local-map isearch-mode-map)
938 (run-hooks 'isearch-mode-hook)
939 ;; Remember the initial map possibly modified
940 ;; by external packages in isearch-mode-hook. (Bug#16035)
941 (setq isearch--saved-overriding-local-map overriding-terminal-local-map)
942
943 ;; Pushing the initial state used to be before running isearch-mode-hook,
944 ;; but a hook might set `isearch-push-state-function' used in
945 ;; `isearch-push-state' to save mode-specific initial state. (Bug#4994)
946 (isearch-push-state)
947
948 (isearch-update)
949
950 (add-hook 'pre-command-hook 'isearch-pre-command-hook)
951 (add-hook 'post-command-hook 'isearch-post-command-hook)
952 (add-hook 'mouse-leave-buffer-hook 'isearch-done)
953 (add-hook 'kbd-macro-termination-hook 'isearch-done)
954
955 ;; isearch-mode can be made modal (in the sense of not returning to
956 ;; the calling function until searching is completed) by entering
957 ;; a recursive-edit and exiting it when done isearching.
958 (if recursive-edit
959 (let ((isearch-recursive-edit t))
960 (recursive-edit)))
961 isearch-success)
962
963
964 ;; Some high level utilities. Others below.
965 (defvar isearch--current-buffer nil)
966
967 (defun isearch-update ()
968 "This is called after every isearch command to update the display.
969 The second last thing it does is to run `isearch-update-post-hook'.
970 The last thing is to trigger a new round of lazy highlighting."
971 (unless (eq (current-buffer) isearch--current-buffer)
972 (when (buffer-live-p isearch--current-buffer)
973 (with-current-buffer isearch--current-buffer
974 (setq cursor-sensor-inhibit (delq 'isearch cursor-sensor-inhibit))))
975 (setq isearch--current-buffer (current-buffer))
976 (make-local-variable 'cursor-sensor-inhibit)
977 ;; Suspend things like cursor-intangible during Isearch so we can search
978 ;; even within intangible text.
979 (push 'isearch cursor-sensor-inhibit))
980
981 (if (and (null unread-command-events)
982 (null executing-kbd-macro))
983 (progn
984 (if (not (input-pending-p))
985 (funcall (or isearch-message-function #'isearch-message)))
986 (if (and isearch-slow-terminal-mode
987 (not (or isearch-small-window
988 (pos-visible-in-window-group-p))))
989 (let ((found-point (point)))
990 (setq isearch-small-window t)
991 (move-to-window-line 0)
992 (let ((window-min-height 1))
993 (split-window nil (if (< search-slow-window-lines 0)
994 (1+ (- search-slow-window-lines))
995 (- (window-height)
996 (1+ search-slow-window-lines)))))
997 (if (< search-slow-window-lines 0)
998 (progn (vertical-motion (- 1 search-slow-window-lines))
999 (set-window-start (next-window) (point))
1000 (set-window-hscroll (next-window)
1001 (window-hscroll))
1002 (set-window-hscroll (selected-window) 0))
1003 (other-window 1))
1004 (goto-char found-point))
1005 ;; Keep same hscrolling as at the start of the search when possible
1006 (let ((current-scroll (window-hscroll))
1007 visible-p)
1008 (set-window-hscroll (selected-window) isearch-start-hscroll)
1009 (setq visible-p (pos-visible-in-window-group-p nil nil t))
1010 (if (or (not visible-p)
1011 ;; When point is not visible because of hscroll,
1012 ;; pos-visible-in-window-group-p returns non-nil, but
1013 ;; the X coordinate it returns is 1 pixel beyond
1014 ;; the last visible one.
1015 (>= (car visible-p) (window-body-width nil t)))
1016 (set-window-hscroll (selected-window) current-scroll))))
1017 (if isearch-other-end
1018 (if (< isearch-other-end (point)) ; isearch-forward?
1019 (isearch-highlight isearch-other-end (point))
1020 (isearch-highlight (point) isearch-other-end))
1021 (isearch-dehighlight))))
1022 (setq ;; quit-flag nil not for isearch-mode
1023 isearch-adjusted nil
1024 isearch-yank-flag nil)
1025 ;; We must prevent the point moving to the end of composition when a
1026 ;; part of the composition has just been searched.
1027 (setq disable-point-adjustment t)
1028 (run-hooks 'isearch-update-post-hook)
1029 (when isearch-lazy-highlight
1030 (isearch-lazy-highlight-new-loop)))
1031
1032 (defun isearch-done (&optional nopush edit)
1033 "Exit Isearch mode.
1034 For successful search, pass no args.
1035 For a failing search, NOPUSH is t.
1036 For going to the minibuffer to edit the search string,
1037 NOPUSH is t and EDIT is t."
1038
1039 (if isearch-resume-in-command-history
1040 (let ((command `(isearch-resume ,isearch-string ,isearch-regexp
1041 ,isearch-regexp-function ,isearch-forward
1042 ,isearch-message
1043 ',isearch-case-fold-search)))
1044 (unless (equal (car command-history) command)
1045 (setq command-history (cons command command-history)))))
1046
1047 (remove-hook 'pre-command-hook 'isearch-pre-command-hook)
1048 (remove-hook 'post-command-hook 'isearch-post-command-hook)
1049 (remove-hook 'mouse-leave-buffer-hook 'isearch-done)
1050 (remove-hook 'kbd-macro-termination-hook 'isearch-done)
1051 (setq isearch-lazy-highlight-start nil)
1052 (with-current-buffer isearch--current-buffer
1053 (setq isearch--current-buffer nil)
1054 (setq cursor-sensor-inhibit (delq 'isearch cursor-sensor-inhibit)))
1055
1056 ;; Called by all commands that terminate isearch-mode.
1057 ;; If NOPUSH is non-nil, we don't push the string on the search ring.
1058 (setq overriding-terminal-local-map nil)
1059 ;; (setq pre-command-hook isearch-old-pre-command-hook) ; for lemacs
1060 (setq minibuffer-message-timeout isearch-original-minibuffer-message-timeout)
1061 (isearch-dehighlight)
1062 (lazy-highlight-cleanup lazy-highlight-cleanup)
1063 (let ((found-start (window-group-start))
1064 (found-point (point)))
1065 (when isearch-window-configuration
1066 (set-window-configuration isearch-window-configuration)
1067 (if isearch-small-window
1068 (goto-char found-point)
1069 ;; set-window-configuration clobbers window-start; restore it.
1070 ;; This has an annoying side effect of clearing the last_modiff
1071 ;; field of the window, which can cause unwanted scrolling,
1072 ;; so don't do it unless truly necessary.
1073 (set-window-group-start (selected-window) found-start t))))
1074
1075 (setq isearch-mode nil)
1076 (if isearch-input-method-local-p
1077 (setq input-method-function isearch-input-method-function)
1078 (kill-local-variable 'input-method-function))
1079
1080 (force-mode-line-update)
1081
1082 ;; If we ended in the middle of some intangible text,
1083 ;; move to the further end of that intangible text.
1084 (let ((after (if (eobp) nil
1085 (get-text-property (point) 'intangible)))
1086 (before (if (bobp) nil
1087 (get-text-property (1- (point)) 'intangible))))
1088 (when (and before after (eq before after))
1089 (goto-char
1090 (if isearch-forward
1091 (next-single-property-change (point) 'intangible)
1092 (previous-single-property-change (point) 'intangible)))))
1093
1094 (if (and (> (length isearch-string) 0) (not nopush))
1095 ;; Update the ring data.
1096 (isearch-update-ring isearch-string isearch-regexp))
1097
1098 (let ((isearch-mode-end-hook-quit (and nopush (not edit))))
1099 (run-hooks 'isearch-mode-end-hook))
1100
1101 ;; If there was movement, mark the starting position.
1102 ;; Maybe should test difference between and set mark only if > threshold.
1103 (if (/= (point) isearch-opoint)
1104 (or (and transient-mark-mode mark-active)
1105 (progn
1106 (push-mark isearch-opoint t)
1107 (or executing-kbd-macro (> (minibuffer-depth) 0) edit
1108 (message "Mark saved where search started")))))
1109
1110 (and (not edit) isearch-recursive-edit (exit-recursive-edit)))
1111
1112 (defun isearch-update-ring (string &optional regexp)
1113 "Add STRING to the beginning of the search ring.
1114 REGEXP if non-nil says use the regexp search ring."
1115 (add-to-history
1116 (if regexp 'regexp-search-ring 'search-ring)
1117 string
1118 (if regexp regexp-search-ring-max search-ring-max)))
1119
1120 ;; Switching buffers should first terminate isearch-mode.
1121 ;; ;; For Emacs 19, the frame switch event is handled.
1122 ;; (defun isearch-switch-frame-handler ()
1123 ;; (interactive) ;; Is this necessary?
1124 ;; ;; First terminate isearch-mode.
1125 ;; (isearch-done)
1126 ;; (isearch-clean-overlays)
1127 ;; (handle-switch-frame (car (cdr last-command-event))))
1128
1129 \f
1130 ;; The search status structure and stack.
1131
1132 (cl-defstruct (isearch--state
1133 (:constructor nil)
1134 (:copier nil)
1135 (:constructor isearch--get-state
1136 (&aux
1137 (string isearch-string)
1138 (message isearch-message)
1139 (point (point))
1140 (success isearch-success)
1141 (forward isearch-forward)
1142 (other-end isearch-other-end)
1143 (word isearch-regexp-function)
1144 (error isearch-error)
1145 (wrapped isearch-wrapped)
1146 (barrier isearch-barrier)
1147 (case-fold-search isearch-case-fold-search)
1148 (pop-fun (if isearch-push-state-function
1149 (funcall isearch-push-state-function))))))
1150 (string :read-only t)
1151 (message :read-only t)
1152 (point :read-only t)
1153 (success :read-only t)
1154 (forward :read-only t)
1155 (other-end :read-only t)
1156 (word :read-only t)
1157 (error :read-only t)
1158 (wrapped :read-only t)
1159 (barrier :read-only t)
1160 (case-fold-search :read-only t)
1161 (pop-fun :read-only t))
1162
1163 (defun isearch--set-state (cmd)
1164 (setq isearch-string (isearch--state-string cmd)
1165 isearch-message (isearch--state-message cmd)
1166 isearch-success (isearch--state-success cmd)
1167 isearch-forward (isearch--state-forward cmd)
1168 isearch-other-end (isearch--state-other-end cmd)
1169 isearch-regexp-function (isearch--state-word cmd)
1170 isearch-error (isearch--state-error cmd)
1171 isearch-wrapped (isearch--state-wrapped cmd)
1172 isearch-barrier (isearch--state-barrier cmd)
1173 isearch-case-fold-search (isearch--state-case-fold-search cmd))
1174 (if (functionp (isearch--state-pop-fun cmd))
1175 (funcall (isearch--state-pop-fun cmd) cmd))
1176 (goto-char (isearch--state-point cmd)))
1177
1178 (defun isearch-pop-state ()
1179 (setq isearch-cmds (cdr isearch-cmds))
1180 (isearch--set-state (car isearch-cmds)))
1181
1182 (defun isearch-push-state ()
1183 (push (isearch--get-state) isearch-cmds))
1184
1185 \f
1186 ;; Commands active while inside of the isearch minor mode.
1187
1188 (defun isearch-exit ()
1189 "Exit search normally.
1190 However, if this is the first command after starting incremental
1191 search and `search-nonincremental-instead' is non-nil, do a
1192 nonincremental search instead via `isearch-edit-string'."
1193 (interactive)
1194 (if (and search-nonincremental-instead
1195 (= 0 (length isearch-string)))
1196 (let ((isearch-nonincremental t))
1197 (isearch-edit-string)) ;; this calls isearch-done as well
1198 (isearch-done))
1199 (isearch-clean-overlays))
1200
1201 (defun isearch-fail-pos (&optional msg)
1202 "Return position of first mismatch in search string, or nil if none.
1203 If MSG is non-nil, use variable `isearch-message', otherwise `isearch-string'."
1204 (let ((cmds isearch-cmds)
1205 (curr-msg (if msg isearch-message isearch-string))
1206 succ-msg)
1207 (when (or (not isearch-success) isearch-error)
1208 (while (and cmds
1209 (or (not (isearch--state-success (car cmds)))
1210 (isearch--state-error (car cmds))))
1211 (pop cmds))
1212 (setq succ-msg (and cmds (if msg (isearch--state-message (car cmds))
1213 (isearch--state-string (car cmds)))))
1214 (if (and (stringp succ-msg)
1215 (< (length succ-msg) (length curr-msg))
1216 (equal succ-msg
1217 (substring curr-msg 0 (length succ-msg))))
1218 (length succ-msg)
1219 0))))
1220
1221 (defvar isearch-new-regexp-function nil
1222 "Holds the next `isearch-regexp-function' inside `with-isearch-suspended'.
1223 If this is set inside code wrapped by the macro
1224 `with-isearch-suspended', then the value set will be used as the
1225 `isearch-regexp-function' once isearch resumes.")
1226 (define-obsolete-variable-alias 'isearch-new-word
1227 'isearch-new-regexp-function "25.1")
1228
1229 (defmacro with-isearch-suspended (&rest body)
1230 "Exit Isearch mode, run BODY, and reinvoke the pending search.
1231 You can update the global isearch variables by setting new values to
1232 `isearch-new-string', `isearch-new-message', `isearch-new-forward',
1233 `isearch-new-regexp-function', `isearch-new-case-fold'."
1234 ;; This code is very hairy for several reasons, explained in the code.
1235 ;; Mainly, isearch-mode must be terminated while editing and then restarted.
1236 ;; If there were a way to catch any change of buffer from the minibuffer,
1237 ;; this could be simplified greatly.
1238 ;; Editing doesn't back up the search point. Should it?
1239 `(condition-case nil
1240 (progn
1241 (let ((isearch-nonincremental isearch-nonincremental)
1242
1243 ;; Locally bind all isearch global variables to protect them
1244 ;; from recursive isearching.
1245 ;; isearch-string -message and -forward are not bound
1246 ;; so they may be changed. Instead, save the values.
1247 (isearch-new-string isearch-string)
1248 (isearch-new-message isearch-message)
1249 (isearch-new-forward isearch-forward)
1250 (isearch-new-regexp-function isearch-regexp-function)
1251 (isearch-new-case-fold isearch-case-fold-search)
1252
1253 (isearch-regexp isearch-regexp)
1254 (isearch-op-fun isearch-op-fun)
1255 (isearch-cmds isearch-cmds)
1256 (isearch-success isearch-success)
1257 (isearch-wrapped isearch-wrapped)
1258 (isearch-barrier isearch-barrier)
1259 (isearch-adjusted isearch-adjusted)
1260 (isearch-yank-flag isearch-yank-flag)
1261 (isearch-error isearch-error)
1262
1263 (multi-isearch-file-list-new multi-isearch-file-list)
1264 (multi-isearch-buffer-list-new multi-isearch-buffer-list)
1265 (multi-isearch-next-buffer-function multi-isearch-next-buffer-current-function)
1266 (multi-isearch-current-buffer-new multi-isearch-current-buffer)
1267 ;;; Don't bind this. We want isearch-search, below, to set it.
1268 ;;; And the old value won't matter after that.
1269 ;;; (isearch-other-end isearch-other-end)
1270 ;;; Perhaps some of these other variables should be bound for a
1271 ;;; shorter period, ending before the next isearch-search.
1272 ;;; But there doesn't seem to be a real bug, so let's not risk it now.
1273 (isearch-opoint isearch-opoint)
1274 (isearch-slow-terminal-mode isearch-slow-terminal-mode)
1275 (isearch-small-window isearch-small-window)
1276 (isearch-recursive-edit isearch-recursive-edit)
1277 ;; Save current configuration so we can restore it here.
1278 (isearch-window-configuration (current-window-configuration))
1279
1280 ;; This could protect the index of the search rings,
1281 ;; but we can't reliably count the number of typed M-p
1282 ;; in `read-from-minibuffer' to adjust the index accordingly.
1283 ;; So when the following is commented out, `isearch-mode'
1284 ;; below resets the index to the predictable value nil.
1285 ;; (search-ring-yank-pointer search-ring-yank-pointer)
1286 ;; (regexp-search-ring-yank-pointer regexp-search-ring-yank-pointer)
1287
1288 ;; Temporarily restore `minibuffer-message-timeout'.
1289 (minibuffer-message-timeout
1290 isearch-original-minibuffer-message-timeout)
1291 (isearch-original-minibuffer-message-timeout
1292 isearch-original-minibuffer-message-timeout)
1293 old-point old-other-end)
1294
1295 ;; Actually terminate isearching until editing is done.
1296 ;; This is so that the user can do anything without failure,
1297 ;; like switch buffers and start another isearch, and return.
1298 (condition-case nil
1299 (isearch-done t t)
1300 (exit nil)) ; was recursive editing
1301
1302 ;; Save old point and isearch-other-end before reading from minibuffer
1303 ;; that can change their values.
1304 (setq old-point (point) old-other-end isearch-other-end)
1305
1306 (unwind-protect
1307 (progn ,@body)
1308
1309 ;; Always resume isearching by restarting it.
1310 (isearch-mode isearch-forward
1311 isearch-regexp
1312 isearch-op-fun
1313 nil
1314 isearch-regexp-function)
1315
1316 ;; Copy new local values to isearch globals
1317 (setq isearch-string isearch-new-string
1318 isearch-message isearch-new-message
1319 isearch-forward isearch-new-forward
1320 isearch-regexp-function isearch-new-regexp-function
1321 isearch-case-fold-search isearch-new-case-fold
1322 multi-isearch-current-buffer multi-isearch-current-buffer-new
1323 multi-isearch-file-list multi-isearch-file-list-new
1324 multi-isearch-buffer-list multi-isearch-buffer-list-new)
1325
1326 ;; Restore the minibuffer message before moving point.
1327 (funcall (or isearch-message-function #'isearch-message) nil t)
1328
1329 ;; Set point at the start (end) of old match if forward (backward),
1330 ;; so after exiting minibuffer isearch resumes at the start (end)
1331 ;; of this match and can find it again.
1332 (if (and old-other-end (eq old-point (point))
1333 (eq isearch-forward isearch-new-forward))
1334 (goto-char old-other-end)))
1335
1336 ;; Empty isearch-string means use default.
1337 (when (= 0 (length isearch-string))
1338 (setq isearch-string (or (car (if isearch-regexp
1339 regexp-search-ring
1340 search-ring))
1341 "")
1342
1343 isearch-message
1344 (mapconcat 'isearch-text-char-description
1345 isearch-string ""))
1346 ;; After taking the last element, adjust ring to previous one.
1347 (isearch-ring-adjust1 nil)))
1348
1349 ;; This used to push the state as of before this C-s, but it adds
1350 ;; an inconsistent state where part of variables are from the
1351 ;; previous search (e.g. `isearch-success'), and part of variables
1352 ;; are just entered from the minibuffer (e.g. `isearch-string').
1353 ;; (isearch-push-state)
1354
1355 ;; Reinvoke the pending search.
1356 (isearch-search)
1357 (isearch-push-state) ; this pushes the correct state
1358 (isearch-update)
1359 (if isearch-nonincremental
1360 (progn
1361 ;; (sit-for 1) ;; needed if isearch-done does: (message "")
1362 (isearch-done)
1363 ;; The search done message is confusing when the string
1364 ;; is empty, so erase it.
1365 (if (equal isearch-string "")
1366 (message "")))))
1367
1368 (quit ; handle abort-recursive-edit
1369 (isearch-abort) ;; outside of let to restore outside global values
1370 )))
1371
1372 (defvar minibuffer-history-symbol) ;; from external package gmhist.el
1373
1374 (defun isearch-edit-string ()
1375 "Edit the search string in the minibuffer.
1376 The following additional command keys are active while editing.
1377 \\<minibuffer-local-isearch-map>
1378 \\[exit-minibuffer] to resume incremental searching with the edited string.
1379 \\[isearch-forward-exit-minibuffer] to resume isearching forward.
1380 \\[isearch-reverse-exit-minibuffer] to resume isearching backward.
1381 \\[isearch-complete-edit] to complete the search string using the search ring."
1382 (interactive)
1383 (with-isearch-suspended
1384 (let* ((message-log-max nil)
1385 ;; Don't add a new search string to the search ring here
1386 ;; in `read-from-minibuffer'. It should be added only
1387 ;; by `isearch-update-ring' called from `isearch-done'.
1388 (history-add-new-input nil)
1389 ;; Binding minibuffer-history-symbol to nil is a work-around
1390 ;; for some incompatibility with gmhist.
1391 (minibuffer-history-symbol))
1392 (setq isearch-new-string
1393 (read-from-minibuffer
1394 (isearch-message-prefix nil isearch-nonincremental)
1395 (cons isearch-string (1+ (or (isearch-fail-pos)
1396 (length isearch-string))))
1397 minibuffer-local-isearch-map nil
1398 (if isearch-regexp
1399 (cons 'regexp-search-ring
1400 (1+ (or regexp-search-ring-yank-pointer -1)))
1401 (cons 'search-ring
1402 (1+ (or search-ring-yank-pointer -1))))
1403 nil t)
1404 isearch-new-message
1405 (mapconcat 'isearch-text-char-description
1406 isearch-new-string "")))))
1407
1408 (defun isearch-nonincremental-exit-minibuffer ()
1409 (interactive)
1410 (setq isearch-nonincremental t)
1411 (exit-minibuffer))
1412 ;; Changing the value of `isearch-nonincremental' has no effect here,
1413 ;; because `isearch-edit-string' ignores this change. Thus marked as obsolete.
1414 (make-obsolete 'isearch-nonincremental-exit-minibuffer 'exit-minibuffer "24.4")
1415
1416 (defun isearch-forward-exit-minibuffer ()
1417 "Resume isearching forward from the minibuffer that edits the search string."
1418 (interactive)
1419 (setq isearch-new-forward t)
1420 (exit-minibuffer))
1421
1422 (defun isearch-reverse-exit-minibuffer ()
1423 "Resume isearching backward from the minibuffer that edits the search string."
1424 (interactive)
1425 (setq isearch-new-forward nil)
1426 (exit-minibuffer))
1427
1428 (defun isearch-cancel ()
1429 "Terminate the search and go back to the starting point."
1430 (interactive)
1431 (if (and isearch-push-state-function isearch-cmds)
1432 ;; For defined push-state function, restore the first state.
1433 ;; This calls pop-state function and restores original point.
1434 (let ((isearch-cmds (last isearch-cmds)))
1435 (isearch--set-state (car isearch-cmds)))
1436 (goto-char isearch-opoint))
1437 (isearch-done t) ; Exit isearch..
1438 (isearch-clean-overlays)
1439 (signal 'quit nil)) ; ..and pass on quit signal.
1440
1441 (defun isearch-abort ()
1442 "Abort incremental search mode if searching is successful, signaling quit.
1443 Otherwise, revert to previous successful search and continue searching.
1444 Use `isearch-exit' to quit without signaling."
1445 (interactive)
1446 ;; (ding) signal instead below, if quitting
1447 (discard-input)
1448 (if (and isearch-success (not isearch-error))
1449 ;; If search is successful and has no incomplete regexp,
1450 ;; move back to starting point and really do quit.
1451 (progn
1452 (setq isearch-success nil)
1453 (isearch-cancel))
1454 ;; If search is failing, or has an incomplete regexp,
1455 ;; rub out until it is once more successful.
1456 (while (or (not isearch-success) isearch-error)
1457 (isearch-pop-state))
1458 (isearch-update)))
1459
1460 (defun isearch-repeat (direction)
1461 ;; Utility for isearch-repeat-forward and -backward.
1462 (if (eq isearch-forward (eq direction 'forward))
1463 ;; C-s in forward or C-r in reverse.
1464 (if (equal isearch-string "")
1465 ;; If search string is empty, use last one.
1466 (if (null (if isearch-regexp regexp-search-ring search-ring))
1467 (setq isearch-error "No previous search string")
1468 (setq isearch-string
1469 (car (if isearch-regexp regexp-search-ring search-ring))
1470 isearch-message
1471 (mapconcat 'isearch-text-char-description
1472 isearch-string "")
1473 isearch-case-fold-search isearch-last-case-fold-search)
1474 ;; After taking the last element, adjust ring to previous one.
1475 (isearch-ring-adjust1 nil))
1476 ;; If already have what to search for, repeat it.
1477 (or isearch-success
1478 (progn
1479 ;; Set isearch-wrapped before calling isearch-wrap-function
1480 (setq isearch-wrapped t)
1481 (if isearch-wrap-function
1482 (funcall isearch-wrap-function)
1483 (goto-char (if isearch-forward (point-min) (point-max)))))))
1484 ;; C-s in reverse or C-r in forward, change direction.
1485 (setq isearch-forward (not isearch-forward)
1486 isearch-success t))
1487
1488 (setq isearch-barrier (point)) ; For subsequent \| if regexp.
1489
1490 (if (equal isearch-string "")
1491 (setq isearch-success t)
1492 (if (and isearch-success
1493 (equal (point) isearch-other-end)
1494 (not isearch-just-started))
1495 ;; If repeating a search that found
1496 ;; an empty string, ensure we advance.
1497 (if (if isearch-forward (eobp) (bobp))
1498 ;; If there's nowhere to advance to, fail (and wrap next time).
1499 (progn
1500 (setq isearch-success nil)
1501 (ding))
1502 (forward-char (if isearch-forward 1 -1))
1503 (isearch-search))
1504 (isearch-search)))
1505
1506 (isearch-push-state)
1507 (isearch-update))
1508
1509 (defun isearch-repeat-forward ()
1510 "Repeat incremental search forwards."
1511 (interactive)
1512 (isearch-repeat 'forward))
1513
1514 (defun isearch-repeat-backward ()
1515 "Repeat incremental search backwards."
1516 (interactive)
1517 (isearch-repeat 'backward))
1518
1519 \f
1520 ;;; Toggles for `isearch-regexp-function' and `search-default-mode'.
1521 (defmacro isearch-define-mode-toggle (mode key function &optional docstring &rest body)
1522 "Define a command called `isearch-toggle-MODE' and bind it to `M-s KEY'.
1523 The first line of the command's docstring is auto-generated, the
1524 remainder may be provided in DOCSTRING.
1525 If FUNCTION is a symbol, this command first toggles the value of
1526 `isearch-regexp-function' between nil and FUNCTION. Also set the
1527 `isearch-message-prefix' property of FUNCTION.
1528 The command then executes BODY and updates the isearch prompt."
1529 (declare (indent defun))
1530 (let ((command-name (intern (format "isearch-toggle-%s" mode)))
1531 (key (concat "\M-s" key)))
1532 `(progn
1533 (defun ,command-name ()
1534 ,(format "Toggle %s searching on or off.%s" mode
1535 (if docstring (concat "\n" docstring) ""))
1536 (interactive)
1537 ,@(when function
1538 `((setq isearch-regexp-function
1539 (unless (eq isearch-regexp-function #',function)
1540 #',function))
1541 (setq isearch-regexp nil)))
1542 ,@body
1543 (setq isearch-success t isearch-adjusted t)
1544 (isearch-update))
1545 (define-key isearch-mode-map ,key #',command-name)
1546 ,@(when (and function (symbolp function))
1547 `((put ',function 'isearch-message-prefix ,(format "%s " mode))
1548 (put ',function :advertised-binding ,key)
1549 (cl-callf (lambda (types) (cons 'choice
1550 (cons '(const :tag ,(capitalize (format "%s search" mode)) ,function)
1551 (cdr types))))
1552 (get 'search-default-mode 'custom-type)))))))
1553
1554 (isearch-define-mode-toggle word "w" word-search-regexp "\
1555 Turning on word search turns off regexp mode.")
1556 (isearch-define-mode-toggle symbol "_" isearch-symbol-regexp "\
1557 Turning on symbol search turns off regexp mode.")
1558 (isearch-define-mode-toggle char-fold "'" char-fold-to-regexp "\
1559 Turning on character-folding turns off regexp mode.")
1560 (put 'char-fold-to-regexp 'isearch-message-prefix "char-fold ")
1561
1562 (isearch-define-mode-toggle regexp "r" nil nil
1563 (setq isearch-regexp (not isearch-regexp))
1564 (if isearch-regexp (setq isearch-regexp-function nil)))
1565
1566 (defun isearch--momentary-message (string)
1567 "Print STRING at the end of the isearch prompt for 1 second"
1568 (let ((message-log-max nil))
1569 (message "%s%s [%s]"
1570 (isearch-message-prefix nil isearch-nonincremental)
1571 isearch-message
1572 string))
1573 (sit-for 1))
1574
1575 (isearch-define-mode-toggle lax-whitespace " " nil
1576 "In ordinary search, toggles the value of the variable
1577 `isearch-lax-whitespace'. In regexp search, toggles the
1578 value of the variable `isearch-regexp-lax-whitespace'."
1579 (isearch--momentary-message
1580 (if (if isearch-regexp
1581 (setq isearch-regexp-lax-whitespace (not isearch-regexp-lax-whitespace))
1582 (setq isearch-lax-whitespace (not isearch-lax-whitespace)))
1583 "match spaces loosely"
1584 "match spaces literally")))
1585
1586 (isearch-define-mode-toggle case-fold "c" nil
1587 "Toggles the value of the variable `isearch-case-fold-search'."
1588 (isearch--momentary-message
1589 (if (setq isearch-case-fold-search
1590 (if isearch-case-fold-search nil 'yes))
1591 "case insensitive"
1592 "case sensitive")))
1593
1594 (isearch-define-mode-toggle invisible "i" nil
1595 "This determines whether to search inside invisible text or not.
1596 Toggles the variable `isearch-invisible' between values
1597 nil and a non-nil value of the option `search-invisible'
1598 \(or `open' if `search-invisible' is nil)."
1599 "match %svisible text"
1600 (isearch--momentary-message
1601 (if (setq isearch-invisible
1602 (if isearch-invisible
1603 nil (or search-invisible 'open)))
1604 "match invisible text"
1605 "match visible text")))
1606
1607 \f
1608 ;; Word search
1609
1610 (defun word-search-regexp (string &optional lax)
1611 "Return a regexp which matches words, ignoring punctuation.
1612 Given STRING, a string of words separated by word delimiters,
1613 compute a regexp that matches those exact words separated by
1614 arbitrary punctuation. If the string begins or ends in whitespace,
1615 the beginning or the end of the string matches arbitrary whitespace.
1616 Otherwise if LAX is non-nil, the beginning or the end of the string
1617 need not match a word boundary.
1618
1619 Used in `word-search-forward', `word-search-backward',
1620 `word-search-forward-lax', `word-search-backward-lax'."
1621 (cond
1622 ((equal string "") "")
1623 ((string-match-p "\\`\\W+\\'" string) "\\W+")
1624 (t (concat
1625 (if (string-match-p "\\`\\W" string) "\\W+"
1626 (unless lax "\\<"))
1627 (mapconcat 'regexp-quote (split-string string "\\W+" t) "\\W+")
1628 (if (string-match-p "\\W\\'" string) "\\W+"
1629 (unless lax "\\>"))))))
1630
1631 (defun word-search-backward (string &optional bound noerror count)
1632 "Search backward from point for STRING, ignoring differences in punctuation.
1633 Set point to the beginning of the occurrence found, and return point.
1634 An optional second argument bounds the search; it is a buffer position.
1635 The match found must not extend before that position.
1636 Optional third argument, if t, means if fail just return nil (no error).
1637 If not nil and not t, move to limit of search and return nil.
1638 Optional fourth argument is repeat count--search for successive occurrences.
1639
1640 Relies on the function `word-search-regexp' to convert a sequence
1641 of words in STRING to a regexp used to search words without regard
1642 to punctuation.
1643 This command does not support character folding, and lax space matching
1644 has no effect on it."
1645 (interactive "sWord search backward: ")
1646 (re-search-backward (word-search-regexp string nil) bound noerror count))
1647
1648 (defun word-search-forward (string &optional bound noerror count)
1649 "Search forward from point for STRING, ignoring differences in punctuation.
1650 Set point to the end of the occurrence found, and return point.
1651 An optional second argument bounds the search; it is a buffer position.
1652 The match found must not extend after that position.
1653 Optional third argument, if t, means if fail just return nil (no error).
1654 If not nil and not t, move to limit of search and return nil.
1655 Optional fourth argument is repeat count--search for successive occurrences.
1656
1657 Relies on the function `word-search-regexp' to convert a sequence
1658 of words in STRING to a regexp used to search words without regard
1659 to punctuation.
1660 This command does not support character folding, and lax space matching
1661 has no effect on it."
1662 (interactive "sWord search: ")
1663 (re-search-forward (word-search-regexp string nil) bound noerror count))
1664
1665 (defun word-search-backward-lax (string &optional bound noerror count)
1666 "Search backward from point for STRING, ignoring differences in punctuation.
1667 Set point to the beginning of the occurrence found, and return point.
1668
1669 Unlike `word-search-backward', the end of STRING need not match a word
1670 boundary, unless STRING ends in whitespace.
1671
1672 An optional second argument bounds the search; it is a buffer position.
1673 The match found must not extend before that position.
1674 Optional third argument, if t, means if fail just return nil (no error).
1675 If not nil and not t, move to limit of search and return nil.
1676 Optional fourth argument is repeat count--search for successive occurrences.
1677
1678 Relies on the function `word-search-regexp' to convert a sequence
1679 of words in STRING to a regexp used to search words without regard
1680 to punctuation.
1681 This command does not support character folding, and lax space matching
1682 has no effect on it."
1683 (interactive "sWord search backward: ")
1684 (re-search-backward (word-search-regexp string t) bound noerror count))
1685
1686 (defun word-search-forward-lax (string &optional bound noerror count)
1687 "Search forward from point for STRING, ignoring differences in punctuation.
1688 Set point to the end of the occurrence found, and return point.
1689
1690 Unlike `word-search-forward', the end of STRING need not match a word
1691 boundary, unless STRING ends in whitespace.
1692
1693 An optional second argument bounds the search; it is a buffer position.
1694 The match found must not extend after that position.
1695 Optional third argument, if t, means if fail just return nil (no error).
1696 If not nil and not t, move to limit of search and return nil.
1697 Optional fourth argument is repeat count--search for successive occurrences.
1698
1699 Relies on the function `word-search-regexp' to convert a sequence
1700 of words in STRING to a regexp used to search words without regard
1701 to punctuation.
1702 This command does not support character folding, and lax space matching
1703 has no effect on it."
1704 (interactive "sWord search: ")
1705 (re-search-forward (word-search-regexp string t) bound noerror count))
1706
1707 ;; Symbol search
1708
1709 (defun isearch-symbol-regexp (string &optional lax)
1710 "Return a regexp which matches STRING as a symbol.
1711 Creates a regexp where STRING is surrounded by symbol delimiters \\_< and \\_>.
1712 If there are more than one symbol, then compute a regexp that matches
1713 those exact symbols separated by non-symbol characters. If the string
1714 begins or ends in whitespace, the beginning or the end of the string
1715 matches arbitrary non-symbol whitespace. Otherwise if LAX is non-nil,
1716 the beginning or the end of the string need not match a symbol boundary."
1717 (let ((not-word-symbol-re
1718 ;; This regexp matches all syntaxes except word and symbol syntax.
1719 ;; FIXME: Replace it with something shorter if possible (bug#14602).
1720 "\\(?:\\s-\\|\\s.\\|\\s(\\|\\s)\\|\\s\"\\|\\s\\\\|\\s/\\|\\s$\\|\\s'\\|\\s<\\|\\s>\\|\\s@\\|\\s!\\|\\s|\\)+"))
1721 (cond
1722 ((equal string "") "")
1723 ((string-match-p (format "\\`%s\\'" not-word-symbol-re) string) not-word-symbol-re)
1724 (t (concat
1725 (if (string-match-p (format "\\`%s" not-word-symbol-re) string) not-word-symbol-re
1726 (unless lax "\\_<"))
1727 (mapconcat 'regexp-quote (split-string string not-word-symbol-re t) not-word-symbol-re)
1728 (if (string-match-p (format "%s\\'" not-word-symbol-re) string) not-word-symbol-re
1729 (unless lax "\\_>")))))))
1730
1731 (put 'isearch-symbol-regexp 'isearch-message-prefix "symbol ")
1732
1733 ;; Search with lax whitespace
1734
1735 (defun search-forward-lax-whitespace (string &optional bound noerror count)
1736 "Search forward for STRING, matching a sequence of whitespace chars."
1737 (let ((search-spaces-regexp search-whitespace-regexp))
1738 (re-search-forward (regexp-quote string) bound noerror count)))
1739
1740 (defun search-backward-lax-whitespace (string &optional bound noerror count)
1741 "Search backward for STRING, matching a sequence of whitespace chars."
1742 (let ((search-spaces-regexp search-whitespace-regexp))
1743 (re-search-backward (regexp-quote string) bound noerror count)))
1744
1745 (defun re-search-forward-lax-whitespace (regexp &optional bound noerror count)
1746 "Search forward for REGEXP, matching a sequence of whitespace chars."
1747 (let ((search-spaces-regexp search-whitespace-regexp))
1748 (re-search-forward regexp bound noerror count)))
1749
1750 (defun re-search-backward-lax-whitespace (regexp &optional bound noerror count)
1751 "Search backward for REGEXP, matching a sequence of whitespace chars."
1752 (let ((search-spaces-regexp search-whitespace-regexp))
1753 (re-search-backward regexp bound noerror count)))
1754
1755 (dolist (old '(re-search-forward-lax-whitespace search-backward-lax-whitespace
1756 search-forward-lax-whitespace re-search-backward-lax-whitespace))
1757 (make-obsolete old
1758 "instead, use (let ((search-spaces-regexp search-whitespace-regexp))
1759 (re-search-... ...))"
1760 "25.1"))
1761
1762 \f
1763 (defun isearch-query-replace (&optional arg regexp-flag)
1764 "Start `query-replace' with string to replace from last search string.
1765 The ARG (prefix arg if interactive), if non-nil, means replace
1766 only matches surrounded by word boundaries. A negative prefix
1767 arg means replace backward. Note that using the prefix arg
1768 is possible only when `isearch-allow-scroll' is non-nil or
1769 `isearch-allow-prefix' is non-nil, and it doesn't always provide the
1770 correct matches for `query-replace', so the preferred way to run word
1771 replacements from Isearch is `M-s w ... M-%'."
1772 (interactive
1773 (list current-prefix-arg))
1774 (barf-if-buffer-read-only)
1775 (if regexp-flag (setq isearch-regexp t))
1776 (let ((case-fold-search isearch-case-fold-search)
1777 ;; set `search-upper-case' to nil to not call
1778 ;; `isearch-no-upper-case-p' in `perform-replace'
1779 (search-upper-case nil)
1780 (search-invisible isearch-invisible)
1781 (replace-lax-whitespace
1782 isearch-lax-whitespace)
1783 (replace-regexp-lax-whitespace
1784 isearch-regexp-lax-whitespace)
1785 (delimited (and arg (not (eq arg '-))))
1786 (backward (and arg (eq arg '-)))
1787 ;; Set `isearch-recursive-edit' to nil to prevent calling
1788 ;; `exit-recursive-edit' in `isearch-done' that terminates
1789 ;; the execution of this command when it is non-nil.
1790 ;; We call `exit-recursive-edit' explicitly at the end below.
1791 (isearch-recursive-edit nil))
1792 (isearch-done nil t)
1793 (isearch-clean-overlays)
1794 (if (and isearch-other-end
1795 (if backward
1796 (> isearch-other-end (point))
1797 (< isearch-other-end (point)))
1798 (not (and transient-mark-mode mark-active
1799 (if backward
1800 (> (mark) (point))
1801 (< (mark) (point))))))
1802 (goto-char isearch-other-end))
1803 (set query-replace-from-history-variable
1804 (cons isearch-string
1805 (symbol-value query-replace-from-history-variable)))
1806 (perform-replace
1807 isearch-string
1808 (query-replace-read-to
1809 isearch-string
1810 (concat "Query replace"
1811 (isearch--describe-regexp-mode (or delimited isearch-regexp-function) t)
1812 (if backward " backward" "")
1813 (if (and transient-mark-mode mark-active) " in region" ""))
1814 isearch-regexp)
1815 t isearch-regexp (or delimited isearch-regexp-function) nil nil
1816 (if (and transient-mark-mode mark-active) (region-beginning))
1817 (if (and transient-mark-mode mark-active) (region-end))
1818 backward))
1819 (and isearch-recursive-edit (exit-recursive-edit)))
1820
1821 (defun isearch-query-replace-regexp (&optional arg)
1822 "Start `query-replace-regexp' with string to replace from last search string.
1823 See `isearch-query-replace' for more information."
1824 (interactive
1825 (list current-prefix-arg))
1826 (isearch-query-replace arg t))
1827
1828 (defun isearch-occur (regexp &optional nlines)
1829 "Run `occur' using the last search string as the regexp.
1830 Interactively, REGEXP is constructed using the search string from the
1831 last search command. NLINES has the same meaning as in `occur'.
1832
1833 If the last search command was a word search, REGEXP is computed from
1834 the search words, ignoring punctuation. If the last search
1835 command was a regular expression search, REGEXP is the regular
1836 expression used in that search. If the last search command searched
1837 for a literal string, REGEXP is constructed by quoting all the special
1838 characters in that string."
1839 (interactive
1840 (let* ((perform-collect (consp current-prefix-arg))
1841 (regexp (cond
1842 ((functionp isearch-regexp-function)
1843 (funcall isearch-regexp-function isearch-string))
1844 (isearch-regexp-function (word-search-regexp isearch-string))
1845 (isearch-regexp isearch-string)
1846 (t (regexp-quote isearch-string)))))
1847 (list regexp
1848 (if perform-collect
1849 ;; Perform collect operation
1850 (if (zerop (regexp-opt-depth regexp))
1851 ;; No subexpression so collect the entire match.
1852 "\\&"
1853 ;; Get the regexp for collection pattern.
1854 (let ((default (car occur-collect-regexp-history))
1855 regexp-collect)
1856 (with-isearch-suspended
1857 (setq regexp-collect
1858 (read-regexp
1859 (format "Regexp to collect (default %s): " default)
1860 default 'occur-collect-regexp-history)))
1861 regexp-collect))
1862 ;; Otherwise normal occur takes numerical prefix argument.
1863 (when current-prefix-arg
1864 (prefix-numeric-value current-prefix-arg))))))
1865 (let ((case-fold-search isearch-case-fold-search)
1866 ;; Set `search-upper-case' to nil to not call
1867 ;; `isearch-no-upper-case-p' in `occur-1'.
1868 (search-upper-case nil)
1869 (search-spaces-regexp
1870 (if (if isearch-regexp
1871 isearch-regexp-lax-whitespace
1872 isearch-lax-whitespace)
1873 search-whitespace-regexp)))
1874 (occur (if isearch-regexp-function
1875 (propertize regexp
1876 'isearch-string isearch-string
1877 'isearch-regexp-function-descr
1878 (isearch--describe-regexp-mode isearch-regexp-function))
1879 regexp)
1880 nlines)))
1881
1882 (declare-function hi-lock-read-face-name "hi-lock" ())
1883
1884 (defun isearch-highlight-regexp ()
1885 "Run `highlight-regexp' with regexp from the current search string.
1886 It exits Isearch mode and calls `hi-lock-face-buffer' with its regexp
1887 argument from the last search regexp or a quoted search string,
1888 and reads its face argument using `hi-lock-read-face-name'."
1889 (interactive)
1890 (let (
1891 ;; Set `isearch-recursive-edit' to nil to prevent calling
1892 ;; `exit-recursive-edit' in `isearch-done' that terminates
1893 ;; the execution of this command when it is non-nil.
1894 ;; We call `exit-recursive-edit' explicitly at the end below.
1895 (isearch-recursive-edit nil))
1896 (isearch-done nil t)
1897 (isearch-clean-overlays))
1898 (require 'hi-lock nil t)
1899 (let ((regexp (cond ((functionp isearch-regexp-function)
1900 (funcall isearch-regexp-function isearch-string))
1901 (isearch-regexp-function (word-search-regexp isearch-string))
1902 (isearch-regexp isearch-string)
1903 ((if (and (eq isearch-case-fold-search t)
1904 search-upper-case)
1905 (isearch-no-upper-case-p
1906 isearch-string isearch-regexp)
1907 isearch-case-fold-search)
1908 ;; Turn isearch-string into a case-insensitive
1909 ;; regexp.
1910 (mapconcat
1911 (lambda (c)
1912 (let ((s (string c)))
1913 (if (string-match "[[:alpha:]]" s)
1914 (format "[%s%s]" (upcase s) (downcase s))
1915 (regexp-quote s))))
1916 isearch-string ""))
1917 (t (regexp-quote isearch-string)))))
1918 (hi-lock-face-buffer regexp (hi-lock-read-face-name)))
1919 (and isearch-recursive-edit (exit-recursive-edit)))
1920
1921 \f
1922 (defun isearch-delete-char ()
1923 "Discard last input item and move point back.
1924 Last input means the last character or the last isearch command
1925 that added or deleted characters from the search string,
1926 moved point, toggled regexp mode or case-sensitivity, etc.
1927 If no previous match was done, just beep."
1928 (interactive)
1929 (if (null (cdr isearch-cmds))
1930 (ding)
1931 (isearch-pop-state))
1932 (isearch-update))
1933
1934 (defun isearch-del-char (&optional arg)
1935 "Delete character from end of search string and search again.
1936 Unlike `isearch-delete-char', it only deletes the last character,
1937 but doesn't cancel the effect of other isearch command.
1938 If search string is empty, just beep."
1939 (interactive "p")
1940 (if (= 0 (length isearch-string))
1941 (ding)
1942 (setq isearch-string (substring isearch-string 0
1943 (- (min (or arg 1)
1944 (length isearch-string))))
1945 isearch-message (mapconcat 'isearch-text-char-description
1946 isearch-string "")))
1947 ;; Do the following before moving point.
1948 (funcall (or isearch-message-function #'isearch-message) nil t)
1949 ;; Use the isearch-other-end as new starting point to be able
1950 ;; to find the remaining part of the search string again.
1951 ;; This is like what `isearch-search-and-update' does,
1952 ;; but currently it doesn't support deletion of characters
1953 ;; for the case where unsuccessful search may become successful
1954 ;; by deletion of characters.
1955 (if isearch-other-end (goto-char isearch-other-end))
1956 (isearch-search)
1957 (isearch-push-state)
1958 (isearch-update))
1959
1960 (defun isearch-yank-string (string)
1961 "Pull STRING into search string."
1962 ;; Downcase the string if not supposed to case-fold yanked strings.
1963 (if (and isearch-case-fold-search
1964 (eq 'not-yanks search-upper-case))
1965 (setq string (downcase string)))
1966 (if isearch-regexp (setq string (regexp-quote string)))
1967 ;; Don't move cursor in reverse search.
1968 (setq isearch-yank-flag t)
1969 (isearch-process-search-string
1970 string (mapconcat 'isearch-text-char-description string "")))
1971
1972 (defun isearch-yank-kill ()
1973 "Pull string from kill ring into search string."
1974 (interactive)
1975 (isearch-yank-string (current-kill 0)))
1976
1977 (defun isearch-yank-pop ()
1978 "Replace just-yanked search string with previously killed string."
1979 (interactive)
1980 (if (not (memq last-command '(isearch-yank-kill isearch-yank-pop)))
1981 ;; Fall back on `isearch-yank-kill' for the benefits of people
1982 ;; who are used to the old behavior of `M-y' in isearch mode. In
1983 ;; future, this fallback may be changed if we ever change
1984 ;; `yank-pop' to do something like the kill-ring-browser.
1985 (isearch-yank-kill)
1986 (isearch-pop-state)
1987 (isearch-yank-string (current-kill 1))))
1988
1989 (defun isearch-yank-x-selection ()
1990 "Pull current X selection into search string."
1991 (interactive)
1992 (isearch-yank-string (gui-get-selection))
1993 ;; If `gui-get-selection' returned the text from the active region,
1994 ;; then it "used" the mark which we should hence deactivate.
1995 (when select-active-regions (deactivate-mark)))
1996
1997
1998 (defun isearch-mouse-2 (click)
1999 "Handle mouse-2 in Isearch mode.
2000 For a click in the echo area, invoke `isearch-yank-x-selection'.
2001 Otherwise invoke whatever the calling mouse-2 command sequence
2002 is bound to outside of Isearch."
2003 (interactive "e")
2004 (let* ((w (posn-window (event-start click)))
2005 (overriding-terminal-local-map nil)
2006 (binding (key-binding (this-command-keys-vector) t)))
2007 (if (and (window-minibuffer-p w)
2008 (not (minibuffer-window-active-p w))) ; in echo area
2009 (isearch-yank-x-selection)
2010 (when (functionp binding)
2011 (call-interactively binding)))))
2012
2013 (declare-function xterm--pasted-text "term/xterm" ())
2014
2015 (defun isearch-xterm-paste ()
2016 "Pull terminal paste into search string."
2017 (interactive)
2018 (isearch-yank-string (xterm--pasted-text)))
2019
2020 (defun isearch-yank-internal (jumpform)
2021 "Pull the text from point to the point reached by JUMPFORM.
2022 JUMPFORM is a lambda expression that takes no arguments and returns
2023 a buffer position, possibly having moved point to that position.
2024 For example, it might move point forward by a word and return point,
2025 or it might return the position of the end of the line."
2026 (isearch-yank-string
2027 (save-excursion
2028 (and (not isearch-forward) isearch-other-end
2029 (goto-char isearch-other-end))
2030 (buffer-substring-no-properties (point) (funcall jumpform)))))
2031
2032 (defun isearch-yank-char-in-minibuffer (&optional arg)
2033 "Pull next character from buffer into end of search string in minibuffer."
2034 (interactive "p")
2035 (if (eobp)
2036 (insert
2037 (with-current-buffer (cadr (buffer-list))
2038 (buffer-substring-no-properties
2039 (point) (progn (forward-char arg) (point)))))
2040 (forward-char arg)))
2041
2042 (defun isearch-yank-char (&optional arg)
2043 "Pull next character from buffer into search string.
2044 If optional ARG is non-nil, pull in the next ARG characters."
2045 (interactive "p")
2046 (isearch-yank-internal (lambda () (forward-char arg) (point))))
2047
2048 (declare-function subword-forward "subword" (&optional arg))
2049 (defun isearch-yank-word-or-char ()
2050 "Pull next character, subword or word from buffer into search string.
2051 Subword is used when `subword-mode' is activated. "
2052 (interactive)
2053 (isearch-yank-internal
2054 (lambda ()
2055 (if (or (= (char-syntax (or (char-after) 0)) ?w)
2056 (= (char-syntax (or (char-after (1+ (point))) 0)) ?w))
2057 (if (or (and (boundp 'subword-mode) subword-mode)
2058 (and (boundp 'superword-mode) superword-mode))
2059 (subword-forward 1)
2060 (forward-word 1))
2061 (forward-char 1))
2062 (point))))
2063
2064 (defun isearch-yank-word (&optional arg)
2065 "Pull next word from buffer into search string.
2066 If optional ARG is non-nil, pull in the next ARG words."
2067 (interactive "p")
2068 (isearch-yank-internal (lambda () (forward-word arg) (point))))
2069
2070 (defun isearch-yank-line (&optional arg)
2071 "Pull rest of line from buffer into search string.
2072 If optional ARG is non-nil, yank the next ARG lines."
2073 (interactive "p")
2074 (isearch-yank-internal
2075 (lambda () (let ((inhibit-field-text-motion t))
2076 (line-end-position (if (eolp) (1+ arg) arg))))))
2077
2078 (defun isearch-char-by-name (&optional count)
2079 "Read a character by its Unicode name and add it to the search string.
2080 Completion is available like in `read-char-by-name' used by `insert-char'.
2081 With argument, add COUNT copies of the character."
2082 (interactive "p")
2083 (with-isearch-suspended
2084 (let ((char (read-char-by-name "Add character to search (Unicode name or hex): ")))
2085 (when char
2086 (let ((string (if (and (integerp count) (> count 1))
2087 (make-string count char)
2088 (char-to-string char))))
2089 (setq isearch-new-string (concat isearch-string string)
2090 isearch-new-message (concat isearch-message
2091 (mapconcat 'isearch-text-char-description
2092 string ""))))))))
2093
2094 (defun isearch-search-and-update ()
2095 ;; Do the search and update the display.
2096 (when (or isearch-success
2097 ;; Unsuccessful regexp search may become successful by
2098 ;; addition of characters which make isearch-string valid
2099 isearch-regexp
2100 ;; If the string was found but was completely invisible,
2101 ;; it might now be partly visible, so try again.
2102 (prog1 isearch-hidden (setq isearch-hidden nil)))
2103 ;; In reverse search, adding stuff at
2104 ;; the end may cause zero or many more chars to be
2105 ;; matched, in the string following point.
2106 ;; Allow all those possibilities without moving point as
2107 ;; long as the match does not extend past search origin.
2108 (if (and (not isearch-forward) (not isearch-adjusted)
2109 (condition-case ()
2110 (let ((case-fold-search isearch-case-fold-search))
2111 (if (and (eq case-fold-search t) search-upper-case)
2112 (setq case-fold-search
2113 (isearch-no-upper-case-p isearch-string isearch-regexp)))
2114 (looking-at (cond
2115 ((functionp isearch-regexp-function)
2116 (funcall isearch-regexp-function isearch-string t))
2117 (isearch-regexp-function (word-search-regexp isearch-string t))
2118 (isearch-regexp isearch-string)
2119 (t (regexp-quote isearch-string)))))
2120 (error nil))
2121 (or isearch-yank-flag
2122 (<= (match-end 0)
2123 (min isearch-opoint isearch-barrier))))
2124 (progn
2125 (setq isearch-success t
2126 isearch-error nil
2127 isearch-other-end (match-end 0))
2128 (if (and (eq isearch-case-fold-search t) search-upper-case)
2129 (setq isearch-case-fold-search
2130 (isearch-no-upper-case-p isearch-string isearch-regexp))))
2131 ;; Not regexp, not reverse, or no match at point.
2132 ;; Do the following before moving point.
2133 (funcall (or isearch-message-function #'isearch-message) nil t)
2134 (if (and isearch-other-end (not isearch-adjusted))
2135 (goto-char (if isearch-forward isearch-other-end
2136 (min isearch-opoint
2137 isearch-barrier
2138 (1+ isearch-other-end)))))
2139 (isearch-search)
2140 ))
2141 (isearch-push-state)
2142 (if isearch-op-fun (funcall isearch-op-fun))
2143 (isearch-update))
2144
2145
2146 ;; *, ?, }, and | chars can make a regexp more liberal.
2147 ;; They can make a regexp match sooner or make it succeed instead of failing.
2148 ;; So go back to place last successful search started
2149 ;; or to the last ^S/^R (barrier), whichever is nearer.
2150 ;; + needs no special handling because the string must match at least once.
2151
2152 (defun isearch-backslash (str)
2153 "Return t if STR ends in an odd number of backslashes."
2154 (= (mod (- (length str) (string-match "\\\\*\\'" str)) 2) 1))
2155
2156 (defun isearch-fallback (want-backslash &optional allow-invalid to-barrier)
2157 "Return point to previous successful match to allow regexp liberalization.
2158 \\<isearch-mode-map>
2159 Respects \\[isearch-repeat-forward] and \\[isearch-repeat-backward] by \
2160 stopping at `isearch-barrier' as needed.
2161
2162 Do nothing if a backslash is escaping the liberalizing character.
2163 If WANT-BACKSLASH is non-nil, invert this behavior (for \\} and \\|).
2164
2165 Do nothing if regexp has recently been invalid unless optional
2166 ALLOW-INVALID non-nil.
2167
2168 If optional TO-BARRIER non-nil, ignore previous matches and go exactly
2169 to the barrier."
2170 ;; (eq (not a) (not b)) makes all non-nil values equivalent
2171 (when (and isearch-regexp (eq (not (isearch-backslash isearch-string))
2172 (not want-backslash))
2173 ;; We have to check 2 stack frames because the last might be
2174 ;; invalid just because of a backslash.
2175 (or (not isearch-error)
2176 (not (isearch--state-error (cadr isearch-cmds)))
2177 allow-invalid))
2178 (if to-barrier
2179 (progn (goto-char isearch-barrier)
2180 (setq isearch-adjusted t))
2181 (let* ((stack isearch-cmds)
2182 (previous (cdr stack)) ; lookbelow in the stack
2183 (frame (car stack)))
2184 ;; Walk down the stack looking for a valid regexp (as of course only
2185 ;; they can be the previous successful match); this conveniently
2186 ;; removes all bracket-sets and groups that might be in the way, as
2187 ;; well as partial \{\} constructs that the code below leaves behind.
2188 ;; Also skip over postfix operators -- though horrid,
2189 ;; 'ab?\{5,6\}+\{1,2\}*' is perfectly valid.
2190 (while (and previous
2191 (or (isearch--state-error frame)
2192 (let* ((string (isearch--state-string frame))
2193 (lchar (aref string (1- (length string)))))
2194 ;; The operators aren't always operators; check
2195 ;; backslashes. This doesn't handle the case of
2196 ;; operators at the beginning of the regexp not
2197 ;; being special, but then we should fall back to
2198 ;; the barrier anyway because it's all optional.
2199 (if (isearch-backslash
2200 (isearch--state-string (car previous)))
2201 (eq lchar ?\})
2202 (memq lchar '(?* ?? ?+))))))
2203 (setq stack previous previous (cdr previous) frame (car stack)))
2204 (when stack
2205 ;; `stack' now refers the most recent valid regexp that is not at
2206 ;; all optional in its last term. Now dig one level deeper and find
2207 ;; what matched before that.
2208 (let ((last-other-end
2209 (or (and (car previous)
2210 (isearch--state-other-end (car previous)))
2211 isearch-barrier)))
2212 (goto-char (if isearch-forward
2213 (max last-other-end isearch-barrier)
2214 (min last-other-end isearch-barrier)))
2215 (setq isearch-adjusted t)))))))
2216
2217 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2218 ;; scrolling within Isearch mode. Alan Mackenzie (acm@muc.de), 2003/2/24
2219 ;;
2220 ;; The idea here is that certain vertical scrolling commands (like C-l
2221 ;; `recenter') should be usable WITHIN Isearch mode. For a command to be
2222 ;; suitable, it must NOT alter the buffer, swap to another buffer or frame,
2223 ;; tamper with isearch's state, or move point. It is unacceptable for the
2224 ;; search string to be scrolled out of the current window. If a command
2225 ;; attempts this, we scroll the text back again.
2226 ;;
2227 ;; We implement this feature with a property called `isearch-scroll'.
2228 ;; If a command's symbol has the value t for this property or for the
2229 ;; `scroll-command' property, it is a scrolling command. The feature
2230 ;; needs to be enabled by setting the customizable variable
2231 ;; `isearch-allow-scroll' to a non-nil value.
2232 ;;
2233 ;; The universal argument commands (e.g. C-u) in simple.el are marked
2234 ;; as scrolling commands, and isearch.el has been amended to allow
2235 ;; prefix arguments to be passed through to scrolling commands. Thus
2236 ;; M-0 C-l will scroll point to the top of the window.
2237 ;;
2238 ;; Horizontal scrolling commands are currently not catered for.
2239 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2240
2241 ;; Set the isearch-scroll property on some standard functions:
2242 ;; Scroll-bar functions:
2243 (if (fboundp 'scroll-bar-toolkit-scroll)
2244 (put 'scroll-bar-toolkit-scroll 'isearch-scroll t))
2245 (if (fboundp 'w32-handle-scroll-bar-event)
2246 (put 'w32-handle-scroll-bar-event 'isearch-scroll t))
2247
2248 ;; Commands which scroll the window (some scroll commands
2249 ;; already have the `scroll-command' property on them):
2250 (put 'recenter 'isearch-scroll t)
2251 (put 'recenter-top-bottom 'isearch-scroll t)
2252 (put 'reposition-window 'isearch-scroll t)
2253
2254 ;; Commands which act on the other window
2255 (put 'list-buffers 'isearch-scroll t)
2256 (put 'scroll-other-window 'isearch-scroll t)
2257 (put 'scroll-other-window-down 'isearch-scroll t)
2258 (put 'beginning-of-buffer-other-window 'isearch-scroll t)
2259 (put 'end-of-buffer-other-window 'isearch-scroll t)
2260
2261 ;; Commands which change the window layout
2262 (put 'delete-other-windows 'isearch-scroll t)
2263 (put 'balance-windows 'isearch-scroll t)
2264 (put 'split-window-right 'isearch-scroll t)
2265 (put 'split-window-below 'isearch-scroll t)
2266 (put 'enlarge-window 'isearch-scroll t)
2267
2268 ;; Aliases for split-window-*
2269 (put 'split-window-vertically 'isearch-scroll t)
2270 (put 'split-window-horizontally 'isearch-scroll t)
2271
2272 ;; Universal argument commands
2273 (put 'universal-argument 'isearch-scroll t)
2274 (put 'negative-argument 'isearch-scroll t)
2275 (put 'digit-argument 'isearch-scroll t)
2276
2277 (defcustom isearch-allow-scroll nil
2278 "Whether scrolling is allowed during incremental search.
2279 If non-nil, scrolling commands can be used in Isearch mode.
2280 However, the current match will never scroll offscreen.
2281 If nil, scrolling commands will first cancel Isearch mode."
2282 :type 'boolean
2283 :group 'isearch)
2284
2285 (defcustom isearch-allow-prefix t
2286 "Whether prefix arguments are allowed during incremental search.
2287 If non-nil, entering a prefix argument will not terminate the
2288 search. This option is ignored \(presumed t) when
2289 `isearch-allow-scroll' is set."
2290 :version "24.4"
2291 :type 'boolean
2292 :group 'isearch)
2293
2294 (defun isearch-string-out-of-window (isearch-point)
2295 "Test whether the search string is currently outside of the window.
2296 Return nil if it's completely visible, or if point is visible,
2297 together with as much of the search string as will fit; the symbol
2298 `above' if we need to scroll the text downwards; the symbol `below',
2299 if upwards."
2300 (let ((w-start (window-group-start))
2301 (w-end (window-group-end nil t))
2302 (w-L1 (save-excursion
2303 (save-selected-window (move-to-window-group-line 1) (point))))
2304 (w-L-1 (save-excursion
2305 (save-selected-window (move-to-window-group-line -1) (point))))
2306 start end) ; start and end of search string in buffer
2307 (if isearch-forward
2308 (setq end isearch-point start (or isearch-other-end isearch-point))
2309 (setq start isearch-point end (or isearch-other-end isearch-point)))
2310 (cond ((or (and (>= start w-start) (<= end w-end))
2311 (if isearch-forward
2312 (and (>= isearch-point w-L-1) (< isearch-point w-end)) ; point on Line -1
2313 (and (>= isearch-point w-start) (< isearch-point w-L1)))) ; point on Line 0
2314 nil)
2315 ((and (< start w-start)
2316 (< isearch-point w-L-1))
2317 'above)
2318 (t 'below))))
2319
2320 (defun isearch-back-into-window (above isearch-point)
2321 "Scroll the window to bring the search string back into view.
2322 Restore point to ISEARCH-POINT in the process. ABOVE is t when the
2323 search string is above the top of the window, nil when it is beneath
2324 the bottom."
2325 (let (start end)
2326 (if isearch-forward
2327 (setq end isearch-point start (or isearch-other-end isearch-point))
2328 (setq start isearch-point end (or isearch-other-end isearch-point)))
2329 (if above
2330 (progn
2331 (goto-char start)
2332 (recenter-window-group 0)
2333 (when (>= isearch-point (window-group-end nil t))
2334 (goto-char isearch-point)
2335 (recenter-window-group -1)))
2336 (goto-char end)
2337 (recenter-window-group -1)
2338 (when (< isearch-point (window-group-start))
2339 (goto-char isearch-point)
2340 (recenter-window-group 0))))
2341 (goto-char isearch-point))
2342
2343 (defvar isearch-pre-scroll-point nil)
2344
2345 (defun isearch-pre-command-hook ()
2346 "Decide whether to exit Isearch mode before executing the command.
2347 Don't exit Isearch if the key sequence that invoked this command
2348 is bound in `isearch-mode-map', or if the invoked command is
2349 a prefix argument command (when `isearch-allow-prefix' is non-nil),
2350 or it is a scrolling command (when `isearch-allow-scroll' is non-nil).
2351 Otherwise, exit Isearch (when `search-exit-option' is non-nil)
2352 before the command is executed globally with terminated Isearch."
2353 (let* ((key (this-single-command-keys))
2354 (main-event (aref key 0)))
2355 (cond
2356 ;; Don't exit Isearch if we're in the middle of some
2357 ;; `set-transient-map' thingy like `universal-argument--mode'.
2358 ((not (eq overriding-terminal-local-map isearch--saved-overriding-local-map)))
2359 ;; Don't exit Isearch for isearch key bindings.
2360 ((commandp (lookup-key isearch-mode-map key nil)))
2361 ;; Optionally edit the search string instead of exiting.
2362 ((eq search-exit-option 'edit)
2363 (setq this-command 'isearch-edit-string))
2364 ;; Handle a scrolling function or prefix argument.
2365 ((or (and isearch-allow-prefix
2366 (memq this-command '(universal-argument
2367 digit-argument negative-argument)))
2368 (and isearch-allow-scroll
2369 (symbolp this-command)
2370 (or (eq (get this-command 'isearch-scroll) t)
2371 (eq (get this-command 'scroll-command) t))))
2372 (when isearch-allow-scroll
2373 (setq isearch-pre-scroll-point (point))))
2374 ;; A mouse click on the isearch message starts editing the search string.
2375 ((and (eq (car-safe main-event) 'down-mouse-1)
2376 (window-minibuffer-p (posn-window (event-start main-event))))
2377 ;; Swallow the up-event.
2378 (read-event)
2379 (setq this-command 'isearch-edit-string))
2380 ;; Other characters terminate the search and are then executed normally.
2381 (search-exit-option
2382 (isearch-done)
2383 (isearch-clean-overlays))
2384 ;; If search-exit-option is nil, run the command without exiting Isearch.
2385 (t
2386 (isearch-process-search-string key key)))))
2387
2388 (defun isearch-post-command-hook ()
2389 (when isearch-pre-scroll-point
2390 (let ((ab-bel (isearch-string-out-of-window isearch-pre-scroll-point)))
2391 (if ab-bel
2392 (isearch-back-into-window (eq ab-bel 'above) isearch-pre-scroll-point)
2393 (goto-char isearch-pre-scroll-point)))
2394 (setq isearch-pre-scroll-point nil)
2395 (isearch-update)))
2396
2397 (defun isearch-quote-char (&optional count)
2398 "Quote special characters for incremental search.
2399 With argument, add COUNT copies of the character."
2400 (interactive "p")
2401 (let ((char (read-quoted-char (isearch-message t))))
2402 (unless (characterp char)
2403 (user-error "%s is not a valid character"
2404 (key-description (vector char))))
2405 ;; Assume character codes 0200 - 0377 stand for characters in some
2406 ;; single-byte character set, and convert them to Emacs
2407 ;; characters.
2408 (if (and isearch-regexp isearch-regexp-lax-whitespace (= char ?\s))
2409 (if (subregexp-context-p isearch-string (length isearch-string))
2410 (isearch-process-search-string "[ ]" " ")
2411 (isearch-process-search-char char count))
2412 ;; This used to assume character codes 0240 - 0377 stand for
2413 ;; characters in some single-byte character set, and converted them
2414 ;; to Emacs characters. But in 23.1 this feature is deprecated
2415 ;; in favor of inserting the corresponding Unicode characters.
2416 ;; (and enable-multibyte-characters
2417 ;; (>= char ?\200)
2418 ;; (<= char ?\377)
2419 ;; (setq char (unibyte-char-to-multibyte char)))
2420 (isearch-process-search-char char count))))
2421
2422 (defun isearch-printing-char (&optional char count)
2423 "Add this ordinary printing CHAR to the search string and search.
2424 With argument, add COUNT copies of the character."
2425 (interactive (list last-command-event
2426 (prefix-numeric-value current-prefix-arg)))
2427 (let ((char (or char last-command-event)))
2428 (if (= char ?\S-\ )
2429 (setq char ?\s))
2430 (if current-input-method
2431 (isearch-process-search-multibyte-characters char count)
2432 (isearch-process-search-char char count))))
2433
2434 (defun isearch-process-search-char (char &optional count)
2435 "Add CHAR to the search string, COUNT times.
2436 Search is updated accordingly."
2437 ;; * and ? are special in regexps when not preceded by \.
2438 ;; } and | are special in regexps when preceded by \.
2439 ;; Nothing special for + because it matches at least once.
2440 (cond
2441 ((memq char '(?* ??)) (isearch-fallback nil))
2442 ((eq char ?\}) (isearch-fallback t t))
2443 ((eq char ?|) (isearch-fallback t nil t)))
2444
2445 ;; Append the char(s) to the search string,
2446 ;; update the message and re-search.
2447 (let* ((string (if (and (integerp count) (> count 1))
2448 (make-string count char)
2449 (char-to-string char)))
2450 (message (if (>= char ?\200)
2451 string
2452 (mapconcat 'isearch-text-char-description string ""))))
2453 (isearch-process-search-string string message)))
2454
2455 (defun isearch-process-search-string (string message)
2456 (setq isearch-string (concat isearch-string string)
2457 isearch-message (concat isearch-message message))
2458 (isearch-search-and-update))
2459
2460 \f
2461 ;; Search Ring
2462
2463 (defun isearch-ring-adjust1 (advance)
2464 ;; Helper for isearch-ring-adjust
2465 (let* ((ring (if isearch-regexp regexp-search-ring search-ring))
2466 (length (length ring))
2467 (yank-pointer-name (if isearch-regexp
2468 'regexp-search-ring-yank-pointer
2469 'search-ring-yank-pointer))
2470 (yank-pointer (eval yank-pointer-name)))
2471 (if (zerop length)
2472 ()
2473 (set yank-pointer-name
2474 (setq yank-pointer
2475 (mod (+ (or yank-pointer (if advance 0 -1))
2476 (if advance -1 1))
2477 length)))
2478 (setq isearch-string (nth yank-pointer ring)
2479 isearch-message (mapconcat 'isearch-text-char-description
2480 isearch-string "")))))
2481
2482 (defun isearch-ring-adjust (advance)
2483 ;; Helper for isearch-ring-advance and isearch-ring-retreat
2484 (isearch-ring-adjust1 advance)
2485 (if search-ring-update
2486 (progn
2487 (funcall (or isearch-message-function #'isearch-message) nil t)
2488 (isearch-search)
2489 (isearch-push-state)
2490 (isearch-update))
2491 ;; Otherwise, edit the search string instead. Note that there is
2492 ;; no need to push the search state after isearch-edit-string here
2493 ;; since isearch-edit-string already pushes its state
2494 (isearch-edit-string)))
2495
2496 (defun isearch-ring-advance ()
2497 "Advance to the next search string in the ring."
2498 ;; This could be more general to handle a prefix arg, but who would use it.
2499 (interactive)
2500 (isearch-ring-adjust 'advance))
2501
2502 (defun isearch-ring-retreat ()
2503 "Retreat to the previous search string in the ring."
2504 (interactive)
2505 (isearch-ring-adjust nil))
2506
2507 (defun isearch-complete1 ()
2508 ;; Helper for isearch-complete and isearch-complete-edit
2509 ;; Return t if completion OK, nil if no completion exists.
2510 (let* ((ring (if isearch-regexp regexp-search-ring search-ring))
2511 (completion-ignore-case case-fold-search)
2512 (completion (try-completion isearch-string ring)))
2513 (cond
2514 ((eq completion t)
2515 ;; isearch-string stays the same
2516 t)
2517 ((or completion ; not nil, must be a string
2518 (= 0 (length isearch-string))) ; shouldn't have to say this
2519 (if (equal completion isearch-string) ;; no extension?
2520 (progn
2521 (if completion-auto-help
2522 (with-output-to-temp-buffer "*Isearch completions*"
2523 (display-completion-list
2524 (all-completions isearch-string ring))))
2525 t)
2526 (and completion
2527 (setq isearch-string completion))))
2528 (t
2529 (message "No completion") ; waits a second if in minibuffer
2530 nil))))
2531
2532 (defun isearch-complete ()
2533 "Complete the search string from the strings on the search ring.
2534 The completed string is then editable in the minibuffer.
2535 If there is no completion possible, say so and continue searching."
2536 (interactive)
2537 (if (isearch-complete1)
2538 (progn (setq isearch-message
2539 (mapconcat 'isearch-text-char-description
2540 isearch-string ""))
2541 (isearch-edit-string))
2542 ;; else
2543 (sit-for 1)
2544 (isearch-update)))
2545
2546 (defun isearch-complete-edit ()
2547 "Same as `isearch-complete' except in the minibuffer."
2548 (interactive)
2549 (setq isearch-string (field-string))
2550 (if (isearch-complete1)
2551 (progn
2552 (delete-field)
2553 (insert isearch-string))))
2554
2555 \f
2556 ;; Message string
2557
2558 (defun isearch-message (&optional c-q-hack ellipsis)
2559 ;; Generate and print the message string.
2560
2561 ;; N.B.: This function should always be called with point at the
2562 ;; search point, because in certain (rare) circumstances, undesired
2563 ;; scrolling can happen when point is elsewhere. These
2564 ;; circumstances are when follow-mode is active, the search string
2565 ;; spans two (or several) windows, and the message about to be
2566 ;; displayed will cause the echo area to expand.
2567 (let ((cursor-in-echo-area ellipsis)
2568 (m isearch-message)
2569 (fail-pos (isearch-fail-pos t)))
2570 ;; Highlight failed part
2571 (when fail-pos
2572 (setq m (copy-sequence m))
2573 (add-text-properties fail-pos (length m) '(face isearch-fail) m)
2574 ;; Highlight failed trailing whitespace
2575 (when (string-match " +$" m)
2576 (add-text-properties (match-beginning 0) (match-end 0)
2577 '(face trailing-whitespace) m)))
2578 (setq m (concat
2579 (isearch-message-prefix ellipsis isearch-nonincremental)
2580 m
2581 (isearch-message-suffix c-q-hack)))
2582 (if c-q-hack m (let ((message-log-max nil)) (message "%s" m)))))
2583
2584 (defun isearch--describe-regexp-mode (regexp-function &optional space-before)
2585 "Make a string for describing REGEXP-FUNCTION.
2586 If SPACE-BEFORE is non-nil, put a space before, instead of after,
2587 the word mode."
2588 (when (eq regexp-function t)
2589 (setq regexp-function #'word-search-regexp))
2590 (let ((description
2591 (cond
2592 ;; 1. Do not use a description on the default search mode,
2593 ;; but only if the default search mode is non-nil.
2594 ((or (and search-default-mode
2595 (equal search-default-mode regexp-function))
2596 ;; Special case where `search-default-mode' is t
2597 ;; (defaults to regexp searches).
2598 (and (eq search-default-mode t)
2599 (eq search-default-mode isearch-regexp))) "")
2600 ;; 2. Use the `isearch-message-prefix' set for
2601 ;; `regexp-function' if available.
2602 (regexp-function
2603 (and (symbolp regexp-function)
2604 (or (get regexp-function 'isearch-message-prefix)
2605 "")))
2606 ;; 3. Else if `isearch-regexp' is non-nil, set description
2607 ;; to "regexp ".
2608 (isearch-regexp "regexp ")
2609 ;; 4. Else if we're in literal mode (and if the default
2610 ;; mode is also not literal), describe it.
2611 ((functionp search-default-mode) "literal ")
2612 ;; 5. And finally, if none of the above is true, set the
2613 ;; description to an empty string.
2614 (t ""))))
2615 (if space-before
2616 ;; Move space from the end to the beginning.
2617 (replace-regexp-in-string "\\(.*\\) \\'" " \\1" description)
2618 description)))
2619 (define-obsolete-function-alias 'isearch--describe-word-mode
2620 'isearch--describe-regexp-mode "25.1")
2621
2622 (defun isearch-message-prefix (&optional ellipsis nonincremental)
2623 ;; If about to search, and previous search regexp was invalid,
2624 ;; check that it still is. If it is valid now,
2625 ;; let the message we display while searching say that it is valid.
2626 (and isearch-error ellipsis
2627 (condition-case ()
2628 (progn (re-search-forward isearch-string (point) t)
2629 (setq isearch-error nil))
2630 (error nil)))
2631 ;; If currently failing, display no ellipsis.
2632 (or isearch-success (setq ellipsis nil))
2633 (let ((m (concat (if isearch-success "" "failing ")
2634 (if isearch-adjusted "pending " "")
2635 (if (and isearch-wrapped
2636 (not isearch-wrap-function)
2637 (if isearch-forward
2638 (> (point) isearch-opoint)
2639 (< (point) isearch-opoint)))
2640 "over")
2641 (if isearch-wrapped "wrapped ")
2642 (let ((prefix ""))
2643 (advice-function-mapc
2644 (lambda (_ props)
2645 (let ((np (cdr (assq 'isearch-message-prefix props))))
2646 (if np (setq prefix (concat np prefix)))))
2647 isearch-filter-predicate)
2648 prefix)
2649 (isearch--describe-regexp-mode isearch-regexp-function)
2650 (cond
2651 (multi-isearch-file-list "multi-file ")
2652 (multi-isearch-buffer-list "multi-buffer ")
2653 (t ""))
2654 (or isearch-message-prefix-add "")
2655 (if nonincremental "search" "I-search")
2656 (if isearch-forward "" " backward")
2657 (if current-input-method
2658 ;; Input methods for RTL languages use RTL
2659 ;; characters for their title, and that messes
2660 ;; up the display of search text after the prompt.
2661 (bidi-string-mark-left-to-right
2662 (concat " [" current-input-method-title "]: "))
2663 ": ")
2664 )))
2665 (propertize (concat (upcase (substring m 0 1)) (substring m 1))
2666 'face 'minibuffer-prompt)))
2667
2668 (defun isearch-message-suffix (&optional c-q-hack)
2669 (concat (if c-q-hack "^Q" "")
2670 (if isearch-error
2671 (concat " [" isearch-error "]")
2672 "")
2673 (or isearch-message-suffix-add "")))
2674
2675 \f
2676 ;; Searching
2677
2678 (defvar isearch-search-fun-function 'isearch-search-fun-default
2679 "Non-default value overrides the behavior of `isearch-search-fun-default'.
2680 This variable's value should be a function, which will be called
2681 with no arguments, and should return a function that takes three
2682 arguments: STRING, BOUND, and NOERROR. STRING is the string to
2683 be searched for. See `re-search-forward' for the meaning of
2684 BOUND and NOERROR arguments.
2685
2686 This returned function will be used by `isearch-search-string' to
2687 search for the first occurrence of STRING.")
2688
2689 (defun isearch-search-fun ()
2690 "Return the function to use for the search.
2691 Can be changed via `isearch-search-fun-function' for special needs."
2692 (funcall (or isearch-search-fun-function 'isearch-search-fun-default)))
2693
2694 (defun isearch--lax-regexp-function-p ()
2695 "Non-nil if next regexp-function call should be lax."
2696 (not (or isearch-nonincremental
2697 (null (car isearch-cmds))
2698 (eq (length isearch-string)
2699 (length (isearch--state-string
2700 (car isearch-cmds)))))))
2701
2702 (defun isearch-search-fun-default ()
2703 "Return default functions to use for the search."
2704 (lambda (string &optional bound noerror count)
2705 ;; Use lax versions to not fail at the end of the word while
2706 ;; the user adds and removes characters in the search string
2707 ;; (or when using nonincremental word isearch)
2708 (let ((search-spaces-regexp (when (cond
2709 (isearch-regexp isearch-regexp-lax-whitespace)
2710 (t isearch-lax-whitespace))
2711 search-whitespace-regexp)))
2712 (condition-case er
2713 (funcall
2714 (if isearch-forward #'re-search-forward #'re-search-backward)
2715 (cond (isearch-regexp-function
2716 (let ((lax (isearch--lax-regexp-function-p)))
2717 (if (functionp isearch-regexp-function)
2718 (funcall isearch-regexp-function string lax)
2719 (word-search-regexp string lax))))
2720 (isearch-regexp string)
2721 (t (regexp-quote string)))
2722 bound noerror count)
2723 (search-failed
2724 (signal (car er)
2725 (let ((prefix (get isearch-regexp-function 'isearch-message-prefix)))
2726 (if (and isearch-regexp-function (stringp prefix))
2727 (list (format "%s [using %ssearch]" string prefix))
2728 (cdr er)))))))))
2729
2730 (defun isearch-search-string (string bound noerror)
2731 "Search for the first occurrence of STRING or its translation.
2732 STRING's characters are translated using `translation-table-for-input'
2733 if that is non-nil.
2734 If found, move point to the end of the occurrence,
2735 update the match data, and return point.
2736 An optional second argument bounds the search; it is a buffer position.
2737 The match found must not extend after that position.
2738 Optional third argument, if t, means if fail just return nil (no error).
2739 If not nil and not t, move to limit of search and return nil."
2740 (let* ((func (isearch-search-fun))
2741 (pos1 (save-excursion (funcall func string bound noerror)))
2742 pos2)
2743 (when (and
2744 ;; Avoid "obsolete" warnings for translation-table-for-input.
2745 (with-no-warnings
2746 (char-table-p translation-table-for-input))
2747 (multibyte-string-p string)
2748 ;; Minor optimization.
2749 (string-match-p "[^[:ascii:]]" string))
2750 (let ((translated
2751 (apply 'string
2752 (mapcar (lambda (c)
2753 (or
2754 ;; Avoid "obsolete" warnings for
2755 ;; translation-table-for-input.
2756 (with-no-warnings
2757 (aref translation-table-for-input c))
2758 c))
2759 string)))
2760 match-data)
2761 (when translated
2762 (save-match-data
2763 (save-excursion
2764 (if (setq pos2 (funcall func translated bound noerror))
2765 (setq match-data (match-data t)))))
2766 (when (and pos2
2767 (or (not pos1)
2768 (if isearch-forward (< pos2 pos1) (> pos2 pos1))))
2769 (setq pos1 pos2)
2770 (set-match-data match-data)))))
2771 (when pos1
2772 ;; When using multiple buffers isearch, switch to the new buffer here,
2773 ;; because `save-excursion' above doesn't allow doing it inside funcall.
2774 (if (and multi-isearch-next-buffer-current-function
2775 (buffer-live-p multi-isearch-current-buffer))
2776 (switch-to-buffer multi-isearch-current-buffer))
2777 (goto-char pos1)
2778 pos1)))
2779
2780 (defun isearch-search ()
2781 ;; Do the search with the current search string.
2782 (if (and (eq isearch-case-fold-search t) search-upper-case)
2783 (setq isearch-case-fold-search
2784 (isearch-no-upper-case-p isearch-string isearch-regexp)))
2785 (condition-case lossage
2786 (let ((inhibit-point-motion-hooks isearch-invisible)
2787 (inhibit-quit nil)
2788 (case-fold-search isearch-case-fold-search)
2789 (search-invisible isearch-invisible)
2790 (retry t))
2791 (setq isearch-error nil)
2792 (while retry
2793 (setq isearch-success
2794 (isearch-search-string isearch-string nil t))
2795 ;; Clear RETRY unless the search predicate says
2796 ;; to skip this search hit.
2797 (if (or (not isearch-success)
2798 (bobp) (eobp)
2799 (= (match-beginning 0) (match-end 0))
2800 (funcall isearch-filter-predicate
2801 (match-beginning 0) (match-end 0)))
2802 (setq retry nil)))
2803 (setq isearch-just-started nil)
2804 (if isearch-success
2805 (setq isearch-other-end
2806 (if isearch-forward (match-beginning 0) (match-end 0)))))
2807
2808 (quit (isearch-unread ?\C-g)
2809 (setq isearch-success nil))
2810
2811 (invalid-regexp
2812 (setq isearch-error (car (cdr lossage)))
2813 (cond
2814 ((string-match
2815 "\\`Premature \\|\\`Unmatched \\|\\`Invalid "
2816 isearch-error)
2817 (setq isearch-error "incomplete input"))
2818 ((and (not isearch-regexp)
2819 (string-match "\\`Regular expression too big" isearch-error))
2820 (cond
2821 (isearch-regexp-function
2822 (setq isearch-error "Too many words"))
2823 ((and isearch-lax-whitespace search-whitespace-regexp)
2824 (setq isearch-error "Too many spaces for whitespace matching"))))))
2825
2826 (search-failed
2827 (setq isearch-success nil)
2828 (setq isearch-error (nth 2 lossage)))
2829
2830 (error
2831 ;; stack overflow in regexp search.
2832 (setq isearch-error (format "%s" lossage))))
2833
2834 (if isearch-success
2835 nil
2836 ;; Ding if failed this time after succeeding last time.
2837 (and (isearch--state-success (car isearch-cmds))
2838 (ding))
2839 (if (functionp (isearch--state-pop-fun (car isearch-cmds)))
2840 (funcall (isearch--state-pop-fun (car isearch-cmds))
2841 (car isearch-cmds)))
2842 (goto-char (isearch--state-point (car isearch-cmds)))))
2843
2844
2845 ;; Called when opening an overlay, and we are still in isearch.
2846 (defun isearch-open-overlay-temporary (ov)
2847 (if (not (null (overlay-get ov 'isearch-open-invisible-temporary)))
2848 ;; Some modes would want to open the overlays temporary during
2849 ;; isearch in their own way, they should set the
2850 ;; `isearch-open-invisible-temporary' to a function doing this.
2851 (funcall (overlay-get ov 'isearch-open-invisible-temporary) ov nil)
2852 ;; Store the values for the `invisible' property, and then set it to nil.
2853 ;; This way the text hidden by this overlay becomes visible.
2854
2855 ;; In 19.34 this does not exist so I cannot test it.
2856 (overlay-put ov 'isearch-invisible (overlay-get ov 'invisible))
2857 (overlay-put ov 'invisible nil)))
2858
2859
2860 ;; This is called at the end of isearch. It will open the overlays
2861 ;; that contain the latest match. Obviously in case of a C-g the
2862 ;; point returns to the original location which surely is not contain
2863 ;; in any of these overlays, se we are safe in this case too.
2864 (defun isearch-open-necessary-overlays (ov)
2865 (let ((inside-overlay (and (> (point) (overlay-start ov))
2866 (<= (point) (overlay-end ov))))
2867 ;; If this exists it means that the overlay was opened using
2868 ;; this function, not by us tweaking the overlay properties.
2869 (fct-temp (overlay-get ov 'isearch-open-invisible-temporary)))
2870 (when (or inside-overlay (not fct-temp))
2871 ;; restore the values for the `invisible' properties.
2872 (overlay-put ov 'invisible (overlay-get ov 'isearch-invisible))
2873 (overlay-put ov 'isearch-invisible nil))
2874 (if inside-overlay
2875 (funcall (overlay-get ov 'isearch-open-invisible) ov)
2876 (if fct-temp
2877 (funcall fct-temp ov t)))))
2878
2879 ;; This is called when exiting isearch. It closes the temporary
2880 ;; opened overlays, except the ones that contain the latest match.
2881 (defun isearch-clean-overlays ()
2882 (when isearch-opened-overlays
2883 (mapc 'isearch-open-necessary-overlays isearch-opened-overlays)
2884 (setq isearch-opened-overlays nil)))
2885
2886
2887 (defun isearch-intersects-p (start0 end0 start1 end1)
2888 "Return t if regions START0..END0 and START1..END1 intersect."
2889 (or (and (>= start0 start1) (< start0 end1))
2890 (and (> end0 start1) (<= end0 end1))
2891 (and (>= start1 start0) (< start1 end0))
2892 (and (> end1 start0) (<= end1 end0))))
2893
2894
2895 ;; Verify if the current match is outside of each element of
2896 ;; `isearch-opened-overlays', if so close that overlay.
2897
2898 (defun isearch-close-unnecessary-overlays (begin end)
2899 (let ((overlays isearch-opened-overlays))
2900 (setq isearch-opened-overlays nil)
2901 (dolist (ov overlays)
2902 (if (isearch-intersects-p begin end (overlay-start ov) (overlay-end ov))
2903 (push ov isearch-opened-overlays)
2904 (let ((fct-temp (overlay-get ov 'isearch-open-invisible-temporary)))
2905 (if fct-temp
2906 ;; If this exists it means that the overlay was opened
2907 ;; using this function, not by us tweaking the overlay
2908 ;; properties.
2909 (funcall fct-temp ov t)
2910 (overlay-put ov 'invisible (overlay-get ov 'isearch-invisible))
2911 (overlay-put ov 'isearch-invisible nil)))))))
2912
2913
2914 (defun isearch-range-invisible (beg end)
2915 "Return t if all the text from BEG to END is invisible."
2916 (when (/= beg end)
2917 ;; Check that invisibility runs up to END.
2918 (save-excursion
2919 (goto-char beg)
2920 (let (;; can-be-opened keeps track if we can open some overlays.
2921 (can-be-opened (eq search-invisible 'open))
2922 ;; the list of overlays that could be opened
2923 (crt-overlays nil))
2924 (when (and can-be-opened isearch-hide-immediately)
2925 (isearch-close-unnecessary-overlays beg end))
2926 ;; If the following character is currently invisible,
2927 ;; skip all characters with that same `invisible' property value.
2928 ;; Do that over and over.
2929 (while (and (< (point) end) (invisible-p (point)))
2930 (if (invisible-p (get-text-property (point) 'invisible))
2931 (progn
2932 (goto-char (next-single-property-change (point) 'invisible
2933 nil end))
2934 ;; if text is hidden by an `invisible' text property
2935 ;; we cannot open it at all.
2936 (setq can-be-opened nil))
2937 (when can-be-opened
2938 (let ((overlays (overlays-at (point)))
2939 ov-list
2940 o
2941 invis-prop)
2942 (while overlays
2943 (setq o (car overlays)
2944 invis-prop (overlay-get o 'invisible))
2945 (if (invisible-p invis-prop)
2946 (if (overlay-get o 'isearch-open-invisible)
2947 (setq ov-list (cons o ov-list))
2948 ;; We found one overlay that cannot be
2949 ;; opened, that means the whole chunk
2950 ;; cannot be opened.
2951 (setq can-be-opened nil)))
2952 (setq overlays (cdr overlays)))
2953 (if can-be-opened
2954 ;; It makes sense to append to the open
2955 ;; overlays list only if we know that this is
2956 ;; t.
2957 (setq crt-overlays (append ov-list crt-overlays)))))
2958 (goto-char (next-overlay-change (point)))))
2959 ;; See if invisibility reaches up thru END.
2960 (if (>= (point) end)
2961 (if (and can-be-opened (consp crt-overlays))
2962 (progn
2963 (setq isearch-opened-overlays
2964 (append isearch-opened-overlays crt-overlays))
2965 (mapc 'isearch-open-overlay-temporary crt-overlays)
2966 nil)
2967 (setq isearch-hidden t)))))))
2968
2969 (defun isearch-filter-visible (beg end)
2970 "Test whether the current search hit is visible at least partially.
2971 Return non-nil if the text from BEG to END is visible to Isearch as
2972 determined by `isearch-range-invisible' unless invisible text can be
2973 searched too when `search-invisible' is t."
2974 (or (eq search-invisible t)
2975 (not (isearch-range-invisible beg end))))
2976
2977 \f
2978 ;; General utilities
2979
2980 (defun isearch-no-upper-case-p (string regexp-flag)
2981 "Return t if there are no upper case chars in STRING.
2982 If REGEXP-FLAG is non-nil, disregard letters preceded by `\\' (but not `\\\\')
2983 since they have special meaning in a regexp."
2984 (let (quote-flag (i 0) (len (length string)) found)
2985 (while (and (not found) (< i len))
2986 (let ((char (aref string i)))
2987 (if (and regexp-flag (eq char ?\\))
2988 (setq quote-flag (not quote-flag))
2989 (if (and (not quote-flag) (not (eq char (downcase char))))
2990 (setq found t))
2991 (setq quote-flag nil)))
2992 (setq i (1+ i)))
2993 (not (or found
2994 ;; Even if there's no uppercase char, we want to detect the use
2995 ;; of [:upper:] or [:lower:] char-class, which indicates
2996 ;; clearly that the user cares about case distinction.
2997 (and regexp-flag (string-match "\\[:\\(upp\\|low\\)er:]" string)
2998 (condition-case err
2999 (progn
3000 (string-match (substring string 0 (match-beginning 0))
3001 "")
3002 nil)
3003 (invalid-regexp
3004 (equal "Unmatched [ or [^" (cadr err)))))))))
3005
3006 ;; Portability functions to support various Emacs versions.
3007
3008 (defun isearch-text-char-description (c)
3009 (cond
3010 ((< c ?\s) (propertize
3011 (char-to-string c)
3012 'display (propertize (format "^%c" (+ c 64)) 'face 'escape-glyph)))
3013 ((= c ?\^?) (propertize
3014 (char-to-string c)
3015 'display (propertize "^?" 'face 'escape-glyph)))
3016 (t (char-to-string c))))
3017
3018 ;; General function to unread characters or events.
3019 ;; Also insert them in a keyboard macro being defined.
3020 (defun isearch-unread (&rest char-or-events)
3021 (mapc 'store-kbd-macro-event char-or-events)
3022 (setq unread-command-events
3023 (append char-or-events unread-command-events)))
3024
3025 \f
3026 ;; Highlighting
3027
3028 (defvar isearch-overlay nil)
3029
3030 (defun isearch-highlight (beg end)
3031 (if search-highlight
3032 (if isearch-overlay
3033 ;; Overlay already exists, just move it.
3034 (move-overlay isearch-overlay beg end (current-buffer))
3035 ;; Overlay doesn't exist, create it.
3036 (setq isearch-overlay (make-overlay beg end))
3037 ;; 1001 is higher than lazy's 1000 and ediff's 100+
3038 (overlay-put isearch-overlay 'priority 1001)
3039 (overlay-put isearch-overlay 'face isearch-face))))
3040
3041 (defun isearch-dehighlight ()
3042 (when isearch-overlay
3043 (delete-overlay isearch-overlay)))
3044 \f
3045 ;; isearch-lazy-highlight feature
3046 ;; by Bob Glickstein <http://www.zanshin.com/~bobg/>
3047
3048 ;; When active, *every* match for the current search string is
3049 ;; highlighted: the current one using the normal isearch match color
3050 ;; and all the others using `isearch-lazy-highlight'. The extra
3051 ;; highlighting makes it easier to anticipate where the cursor will
3052 ;; land each time you press C-s or C-r to repeat a pending search.
3053 ;; Highlighting of these additional matches happens in a deferred
3054 ;; fashion using "idle timers," so the cycles needed do not rob
3055 ;; isearch of its usual snappy response.
3056
3057 ;; IMPLEMENTATION NOTE: This depends on some isearch internals.
3058 ;; Specifically:
3059 ;; - `isearch-update' is expected to be called (at least) every time
3060 ;; the search string or window-start changes;
3061 ;; - `isearch-string' is expected to contain the current search
3062 ;; string as entered by the user;
3063 ;; - the type of the current search is expected to be given by
3064 ;; `isearch-regexp-function' and `isearch-regexp';
3065 ;; - the direction of the current search is expected to be given by
3066 ;; `isearch-forward';
3067 ;; - the variable `isearch-error' is expected to be true
3068 ;; only if `isearch-string' is an invalid regexp.
3069
3070 (defvar isearch-lazy-highlight-overlays nil)
3071 (defvar isearch-lazy-highlight-wrapped nil)
3072 (defvar isearch-lazy-highlight-start-limit nil)
3073 (defvar isearch-lazy-highlight-end-limit nil)
3074 (defvar isearch-lazy-highlight-start nil)
3075 (defvar isearch-lazy-highlight-end nil)
3076 (defvar isearch-lazy-highlight-timer nil)
3077 (defvar isearch-lazy-highlight-last-string nil)
3078 (defvar isearch-lazy-highlight-window nil)
3079 (defvar isearch-lazy-highlight-window-group nil)
3080 (defvar isearch-lazy-highlight-window-start nil)
3081 (defvar isearch-lazy-highlight-window-end nil)
3082 (defvar isearch-lazy-highlight-case-fold-search nil)
3083 (defvar isearch-lazy-highlight-regexp nil)
3084 (defvar isearch-lazy-highlight-lax-whitespace nil)
3085 (defvar isearch-lazy-highlight-regexp-lax-whitespace nil)
3086 (defvar isearch-lazy-highlight-regexp-function nil)
3087 (define-obsolete-variable-alias 'isearch-lazy-highlight-word
3088 'isearch-lazy-highlight-regexp-function "25.1")
3089 (defvar isearch-lazy-highlight-forward nil)
3090 (defvar isearch-lazy-highlight-error nil)
3091
3092 (defun lazy-highlight-cleanup (&optional force)
3093 "Stop lazy highlighting and remove extra highlighting from current buffer.
3094 FORCE non-nil means do it whether or not `lazy-highlight-cleanup'
3095 is nil. This function is called when exiting an incremental search if
3096 `lazy-highlight-cleanup' is non-nil."
3097 (interactive '(t))
3098 (if (or force lazy-highlight-cleanup)
3099 (while isearch-lazy-highlight-overlays
3100 (delete-overlay (car isearch-lazy-highlight-overlays))
3101 (setq isearch-lazy-highlight-overlays
3102 (cdr isearch-lazy-highlight-overlays))))
3103 (when isearch-lazy-highlight-timer
3104 (cancel-timer isearch-lazy-highlight-timer)
3105 (setq isearch-lazy-highlight-timer nil)))
3106
3107 (define-obsolete-function-alias 'isearch-lazy-highlight-cleanup
3108 'lazy-highlight-cleanup
3109 "22.1")
3110
3111 (defun isearch-lazy-highlight-new-loop (&optional beg end)
3112 "Cleanup any previous `lazy-highlight' loop and begin a new one.
3113 BEG and END specify the bounds within which highlighting should occur.
3114 This is called when `isearch-update' is invoked (which can cause the
3115 search string to change or the window to scroll). It is also used
3116 by other Emacs features."
3117 (when (and (null executing-kbd-macro)
3118 (sit-for 0) ;make sure (window-start) is credible
3119 (or (not (equal isearch-string
3120 isearch-lazy-highlight-last-string))
3121 (not (memq (selected-window)
3122 isearch-lazy-highlight-window-group))
3123 (not (eq isearch-lazy-highlight-case-fold-search
3124 isearch-case-fold-search))
3125 (not (eq isearch-lazy-highlight-regexp
3126 isearch-regexp))
3127 (not (eq isearch-lazy-highlight-regexp-function
3128 isearch-regexp-function))
3129 (not (eq isearch-lazy-highlight-lax-whitespace
3130 isearch-lax-whitespace))
3131 (not (eq isearch-lazy-highlight-regexp-lax-whitespace
3132 isearch-regexp-lax-whitespace))
3133 (not (= (window-group-start)
3134 isearch-lazy-highlight-window-start))
3135 (not (= (window-group-end) ; Window may have been split/joined.
3136 isearch-lazy-highlight-window-end))
3137 (not (eq isearch-forward
3138 isearch-lazy-highlight-forward))
3139 ;; In case we are recovering from an error.
3140 (not (equal isearch-error
3141 isearch-lazy-highlight-error))))
3142 ;; something important did indeed change
3143 (lazy-highlight-cleanup t) ;kill old loop & remove overlays
3144 (setq isearch-lazy-highlight-error isearch-error)
3145 ;; It used to check for `(not isearch-error)' here, but actually
3146 ;; lazy-highlighting might find matches to highlight even when
3147 ;; `isearch-error' is non-nil. (Bug#9918)
3148 (setq isearch-lazy-highlight-start-limit beg
3149 isearch-lazy-highlight-end-limit end)
3150 (setq isearch-lazy-highlight-window (selected-window)
3151 isearch-lazy-highlight-window-group (selected-window-group)
3152 isearch-lazy-highlight-window-start (window-group-start)
3153 isearch-lazy-highlight-window-end (window-group-end)
3154 ;; Start lazy-highlighting at the beginning of the found
3155 ;; match (`isearch-other-end'). If no match, use point.
3156 ;; One of the next two variables (depending on search direction)
3157 ;; is used to define the starting position of lazy-highlighting
3158 ;; and also to remember the current position of point between
3159 ;; calls of `isearch-lazy-highlight-update', and another variable
3160 ;; is used to define where the wrapped search must stop.
3161 isearch-lazy-highlight-start (or isearch-other-end (point))
3162 isearch-lazy-highlight-end (or isearch-other-end (point))
3163 isearch-lazy-highlight-wrapped nil
3164 isearch-lazy-highlight-last-string isearch-string
3165 isearch-lazy-highlight-case-fold-search isearch-case-fold-search
3166 isearch-lazy-highlight-regexp isearch-regexp
3167 isearch-lazy-highlight-lax-whitespace isearch-lax-whitespace
3168 isearch-lazy-highlight-regexp-lax-whitespace isearch-regexp-lax-whitespace
3169 isearch-lazy-highlight-regexp-function isearch-regexp-function
3170 isearch-lazy-highlight-forward isearch-forward)
3171 (unless (equal isearch-string "")
3172 (setq isearch-lazy-highlight-timer
3173 (run-with-idle-timer lazy-highlight-initial-delay nil
3174 'isearch-lazy-highlight-update)))))
3175
3176 (defun isearch-lazy-highlight-search ()
3177 "Search ahead for the next or previous match, for lazy highlighting.
3178 Attempt to do the search exactly the way the pending Isearch would."
3179 (condition-case nil
3180 (let ((case-fold-search isearch-lazy-highlight-case-fold-search)
3181 (isearch-regexp isearch-lazy-highlight-regexp)
3182 (isearch-regexp-function isearch-lazy-highlight-regexp-function)
3183 (isearch-lax-whitespace
3184 isearch-lazy-highlight-lax-whitespace)
3185 (isearch-regexp-lax-whitespace
3186 isearch-lazy-highlight-regexp-lax-whitespace)
3187 (isearch-forward isearch-lazy-highlight-forward)
3188 (search-invisible nil) ; don't match invisible text
3189 (retry t)
3190 (success nil)
3191 (bound (if isearch-lazy-highlight-forward
3192 (min (or isearch-lazy-highlight-end-limit (point-max))
3193 (if isearch-lazy-highlight-wrapped
3194 (+ isearch-lazy-highlight-start
3195 ;; Extend bound to match whole string at point
3196 (1- (length isearch-lazy-highlight-last-string)))
3197 (window-group-end)))
3198 (max (or isearch-lazy-highlight-start-limit (point-min))
3199 (if isearch-lazy-highlight-wrapped
3200 (- isearch-lazy-highlight-end
3201 ;; Extend bound to match whole string at point
3202 (1- (length isearch-lazy-highlight-last-string)))
3203 (window-group-start))))))
3204 ;; Use a loop like in `isearch-search'.
3205 (while retry
3206 (setq success (isearch-search-string
3207 isearch-lazy-highlight-last-string bound t))
3208 ;; Clear RETRY unless the search predicate says
3209 ;; to skip this search hit.
3210 (if (or (not success)
3211 (= (point) bound) ; like (bobp) (eobp) in `isearch-search'.
3212 (= (match-beginning 0) (match-end 0))
3213 (funcall isearch-filter-predicate
3214 (match-beginning 0) (match-end 0)))
3215 (setq retry nil)))
3216 success)
3217 (error nil)))
3218
3219 (defun isearch-lazy-highlight-update ()
3220 "Update highlighting of other matches for current search."
3221 (let ((max lazy-highlight-max-at-a-time)
3222 (looping t)
3223 nomore)
3224 (with-local-quit
3225 (save-selected-window
3226 (if (and (window-live-p isearch-lazy-highlight-window)
3227 (not (memq (selected-window) isearch-lazy-highlight-window-group)))
3228 (select-window isearch-lazy-highlight-window))
3229 (save-excursion
3230 (save-match-data
3231 (goto-char (if isearch-lazy-highlight-forward
3232 isearch-lazy-highlight-end
3233 isearch-lazy-highlight-start))
3234 (while looping
3235 (let ((found (isearch-lazy-highlight-search)))
3236 (when max
3237 (setq max (1- max))
3238 (if (<= max 0)
3239 (setq looping nil)))
3240 (if found
3241 (let ((mb (match-beginning 0))
3242 (me (match-end 0)))
3243 (if (= mb me) ;zero-length match
3244 (if isearch-lazy-highlight-forward
3245 (if (= mb (if isearch-lazy-highlight-wrapped
3246 isearch-lazy-highlight-start
3247 (window-group-end)))
3248 (setq found nil)
3249 (forward-char 1))
3250 (if (= mb (if isearch-lazy-highlight-wrapped
3251 isearch-lazy-highlight-end
3252 (window-group-start)))
3253 (setq found nil)
3254 (forward-char -1)))
3255
3256 ;; non-zero-length match
3257 (let ((ov (make-overlay mb me)))
3258 (push ov isearch-lazy-highlight-overlays)
3259 ;; 1000 is higher than ediff's 100+,
3260 ;; but lower than isearch main overlay's 1001
3261 (overlay-put ov 'priority 1000)
3262 (overlay-put ov 'face lazy-highlight-face)))
3263 ;(overlay-put ov 'window (selected-window))))
3264 ;; Remember the current position of point for
3265 ;; the next call of `isearch-lazy-highlight-update'
3266 ;; when `lazy-highlight-max-at-a-time' is too small.
3267 (if isearch-lazy-highlight-forward
3268 (setq isearch-lazy-highlight-end (point))
3269 (setq isearch-lazy-highlight-start (point)))))
3270
3271 ;; not found or zero-length match at the search bound
3272 (if (not found)
3273 (if isearch-lazy-highlight-wrapped
3274 (setq looping nil
3275 nomore t)
3276 (setq isearch-lazy-highlight-wrapped t)
3277 (if isearch-lazy-highlight-forward
3278 (progn
3279 (setq isearch-lazy-highlight-end (window-group-start))
3280 (goto-char (max (or isearch-lazy-highlight-start-limit (point-min))
3281 (window-group-start))))
3282 (setq isearch-lazy-highlight-start (window-group-end))
3283 (goto-char (min (or isearch-lazy-highlight-end-limit (point-max))
3284 (window-group-end))))))))
3285 (unless nomore
3286 (setq isearch-lazy-highlight-timer
3287 (run-at-time lazy-highlight-interval nil
3288 'isearch-lazy-highlight-update)))))))))
3289
3290 (defun isearch-resume (string regexp word forward message case-fold)
3291 "Resume an incremental search.
3292 STRING is the string or regexp searched for.
3293 REGEXP non-nil means the resumed search was a regexp search.
3294 WORD non-nil means resume a word search.
3295 FORWARD non-nil means resume a forward search.
3296 MESSAGE is the echo-area message recorded for the search resumed.
3297 CASE-FOLD non-nil means the search was case-insensitive."
3298 (isearch-mode forward regexp nil nil word)
3299 (setq isearch-string string
3300 isearch-message message
3301 isearch-case-fold-search case-fold)
3302 (isearch-search)
3303 (isearch-update))
3304
3305 ;;; isearch.el ends here