1;;; isearch.el --- incremental search minor mode
2
3;; Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1999, 2000,
4;;   2001, 2002, 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
5
6;; Author: Daniel LaLiberte <liberte@cs.uiuc.edu>
7;; Maintainer: FSF
8;; Keywords: matching
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 2, or (at your option)
15;; 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; see the file COPYING.  If not, write to the
24;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25;; Boston, MA 02110-1301, USA.
26
27;;; Commentary:
28
29;; Instructions
30
31;; For programmed use of isearch-mode, e.g. calling (isearch-forward),
32;; isearch-mode behaves modally and does not return until the search
33;; is completed.  It uses a recursive-edit to behave this way.
34
35;; The key bindings active within isearch-mode are defined below in
36;; `isearch-mode-map' which is given bindings close to the default
37;; characters of the original isearch.el.  With `isearch-mode',
38;; however, you can bind multi-character keys and it should be easier
39;; to add new commands.  One bug though: keys with meta-prefix cannot
40;; be longer than two chars.  Also see minibuffer-local-isearch-map
41;; for bindings active during `isearch-edit-string'.
42
43;; isearch-mode should work even if you switch windows with the mouse,
44;; in which case isearch-mode is terminated automatically before the
45;; switch.
46
47;; The search ring and completion commands automatically put you in
48;; the minibuffer to edit the string.  This gives you a chance to
49;; modify the search string before executing the search.  There are
50;; three commands to terminate the editing: C-s and C-r exit the
51;; minibuffer and search forward and reverse respectively, while C-m
52;; exits and does a nonincremental search.
53
54;; Exiting immediately from isearch uses isearch-edit-string instead
55;; of nonincremental-search, if search-nonincremental-instead is non-nil.
56;; The name of this option should probably be changed if we decide to
57;; keep the behavior.  No point in forcing nonincremental search until
58;; the last possible moment.
59
60;;; Code:
61
62
63;; Some additional options and constants.
64
65(defgroup isearch nil
66  "Incremental search minor mode."
67  :link '(emacs-commentary-link "isearch")
68  :link '(custom-manual "(emacs)Incremental Search")
69  :prefix "isearch-"
70  :prefix "search-"
71  :group 'matching)
72
73
74(defcustom search-exit-option t
75  "*Non-nil means random control characters terminate incremental search."
76  :type 'boolean
77  :group 'isearch)
78
79(defcustom search-slow-window-lines 1
80  "*Number of lines in slow search display windows.
81These are the short windows used during incremental search on slow terminals.
82Negative means put the slow search window at the top (normally it's at bottom)
83and the value is minus the number of lines."
84  :type 'integer
85  :group 'isearch)
86
87(defcustom search-slow-speed 1200
88  "*Highest terminal speed at which to use \"slow\" style incremental search.
89This is the style where a one-line window is created to show the line
90that the search has reached."
91  :type 'integer
92  :group 'isearch)
93
94(defcustom search-upper-case 'not-yanks
95  "*If non-nil, upper case chars disable case fold searching.
96That is, upper and lower case chars must match exactly.
97This applies no matter where the chars come from, but does not
98apply to chars in regexps that are prefixed with `\\'.
99If this value is `not-yanks', yanked text is always downcased."
100  :type '(choice (const :tag "off" nil)
101		 (const not-yanks)
102		 (other :tag "on" t))
103  :group 'isearch)
104
105(defcustom search-nonincremental-instead t
106  "*If non-nil, do a nonincremental search instead if exiting immediately.
107Actually, `isearch-edit-string' is called to let you enter the search
108string, and RET terminates editing and does a nonincremental search."
109  :type 'boolean
110  :group 'isearch)
111
112(defcustom search-whitespace-regexp "\\s-+"
113  "*If non-nil, regular expression to match a sequence of whitespace chars.
114This applies to regular expression incremental search.
115When you put a space or spaces in the incremental regexp, it stands for
116this, unless it is inside of a regexp construct such as [...] or *, + or ?.
117You might want to use something like \"[ \\t\\r\\n]+\" instead.
118In the Customization buffer, that is `[' followed by a space,
119a tab, a carriage return (control-M), a newline, and `]+'.
120
121When this is nil, each space you type matches literally, against one space."
122  :type '(choice (const :tag "Find Spaces Literally" nil)
123		 regexp)
124  :group 'isearch)
125
126(defcustom search-invisible 'open
127  "If t incremental search can match hidden text.
128A nil value means don't match invisible text.
129When the value is `open', if the text matched is made invisible by
130an overlay having an `invisible' property and that overlay has a property
131`isearch-open-invisible', then incremental search will show the contents.
132\(This applies when using `outline.el' and `hideshow.el'.)
133See also `reveal-mode' if you want overlays to automatically be opened
134whenever point is in one of them."
135  :type '(choice (const :tag "Match hidden text" t)
136		 (const :tag "Open overlays" open)
137		 (const :tag "Don't match hidden text" nil))
138  :group 'isearch)
139
140(defcustom isearch-hide-immediately t
141  "If non-nil, re-hide an invisible match right away.
142This variable makes a difference when `search-invisible' is set to `open'.
143It means that after search makes some invisible text visible
144to show the match, it makes the text invisible again when the match moves.
145Ordinarily the text becomes invisible again at the end of the search."
146  :type 'boolean
147  :group 'isearch)
148
149(defcustom isearch-resume-in-command-history nil
150  "*If non-nil, `isearch-resume' commands are added to the command history.
151This allows you to resume earlier isearch sessions through the
152command history."
153  :type 'boolean
154  :group 'isearch)
155
156(defvar isearch-mode-hook nil
157  "Function(s) to call after starting up an incremental search.")
158
159(defvar isearch-mode-end-hook nil
160  "Function(s) to call after terminating an incremental search.
161When these functions are called, `isearch-mode-end-hook-quit'
162is non-nil if the user quit the search.")
163
164(defvar isearch-mode-end-hook-quit nil
165  "Non-nil while running `isearch-mode-end-hook' if user quit the search.")
166
167(defvar isearch-wrap-function nil
168  "Function to call to wrap the search when search is failed.
169If nil, move point to the beginning of the buffer for a forward search,
170or to the end of the buffer for a backward search.")
171
172(defvar isearch-push-state-function nil
173  "Function to save a function restoring the mode-specific isearch state
174to the search status stack.")
175
176;; Search ring.
177
178(defvar search-ring nil
179  "List of search string sequences.")
180(defvar regexp-search-ring nil
181  "List of regular expression search string sequences.")
182
183(defcustom search-ring-max 16
184  "*Maximum length of search ring before oldest elements are thrown away."
185  :type 'integer
186  :group 'isearch)
187(defcustom regexp-search-ring-max 16
188  "*Maximum length of regexp search ring before oldest elements are thrown away."
189  :type 'integer
190  :group 'isearch)
191
192(defvar search-ring-yank-pointer nil
193  "Index in `search-ring' of last string reused.
194It is nil if none yet.")
195(defvar regexp-search-ring-yank-pointer nil
196  "Index in `regexp-search-ring' of last string reused.
197It is nil if none yet.")
198
199(defcustom search-ring-update nil
200  "*Non-nil if advancing or retreating in the search ring should cause search.
201Default value, nil, means edit the string instead."
202  :type 'boolean
203  :group 'isearch)
204
205;;; isearch highlight customization.
206
207(defcustom search-highlight t
208  "*Non-nil means incremental search highlights the current match."
209  :type 'boolean
210  :group 'isearch)
211
212(defface isearch
213  '((((class color) (min-colors 88) (background light))
214     ;; The background must not be too dark, for that means
215     ;; the character is hard to see when the cursor is there.
216     (:background "magenta3" :foreground "lightskyblue1"))
217    (((class color) (min-colors 88) (background dark))
218     (:background "palevioletred2" :foreground "brown4"))
219    (((class color) (min-colors 16))
220     (:background "magenta4" :foreground "cyan1"))
221    (((class color) (min-colors 8))
222     (:background "magenta4" :foreground "cyan1"))
223    (t (:inverse-video t)))
224  "Face for highlighting Isearch matches."
225  :group 'isearch
226  :group 'basic-faces)
227(defvar isearch 'isearch)
228
229(defcustom isearch-lazy-highlight t
230  "*Controls the lazy-highlighting during incremental search.
231When non-nil, all text in the buffer matching the current search
232string is highlighted lazily (see `lazy-highlight-initial-delay'
233and `lazy-highlight-interval')."
234  :type 'boolean
235  :group 'lazy-highlight
236  :group 'isearch)
237
238;;; Lazy highlight customization.
239
240(defgroup lazy-highlight nil
241  "Lazy highlighting feature for matching strings."
242  :prefix "lazy-highlight-"
243  :version "21.1"
244  :group 'isearch
245  :group 'matching)
246
247(defcustom lazy-highlight-cleanup t
248  "*Controls whether to remove extra highlighting after a search.
249If this is nil, extra highlighting can be \"manually\" removed with
250\\[lazy-highlight-cleanup]."
251  :type 'boolean
252  :group 'lazy-highlight)
253(define-obsolete-variable-alias 'isearch-lazy-highlight-cleanup
254                                'lazy-highlight-cleanup
255                                "22.1")
256
257(defcustom lazy-highlight-initial-delay 0.25
258  "*Seconds to wait before beginning to lazily highlight all matches."
259  :type 'number
260  :group 'lazy-highlight)
261(define-obsolete-variable-alias 'isearch-lazy-highlight-initial-delay
262                                'lazy-highlight-initial-delay
263                                "22.1")
264
265(defcustom lazy-highlight-interval 0 ; 0.0625
266  "*Seconds between lazily highlighting successive matches."
267  :type 'number
268  :group 'lazy-highlight)
269(define-obsolete-variable-alias 'isearch-lazy-highlight-interval
270                                'lazy-highlight-interval
271                                "22.1")
272
273(defcustom lazy-highlight-max-at-a-time 20
274  "*Maximum matches to highlight at a time (for `lazy-highlight').
275Larger values may reduce isearch's responsiveness to user input;
276smaller values make matches highlight slowly.
277A value of nil means highlight all matches."
278  :type '(choice (const :tag "All" nil)
279		 (integer :tag "Some"))
280  :group 'lazy-highlight)
281(define-obsolete-variable-alias 'isearch-lazy-highlight-max-at-a-time
282                                'lazy-highlight-max-at-a-time
283                                "22.1")
284
285(defface lazy-highlight
286  '((((class color) (min-colors 88) (background light))
287     (:background "paleturquoise"))
288    (((class color) (min-colors 88) (background dark))
289     (:background "paleturquoise4"))
290    (((class color) (min-colors 16))
291     (:background "turquoise3"))
292    (((class color) (min-colors 8))
293     (:background "turquoise3"))
294    (t (:underline t)))
295  "Face for lazy highlighting of matches other than the current one."
296  :group 'lazy-highlight
297  :group 'basic-faces)
298(put 'isearch-lazy-highlight-face 'face-alias 'lazy-highlight)
299(defvar lazy-highlight-face 'lazy-highlight)
300(define-obsolete-variable-alias 'isearch-lazy-highlight-face
301                                'lazy-highlight-face
302                                "22.1")
303
304;; Define isearch-mode keymap.
305
306(defvar isearch-mode-map
307  (let* ((i 0)
308	 (map (make-keymap)))
309    (or (vectorp (nth 1 map))
310	(char-table-p (nth 1 map))
311	(error "The initialization of isearch-mode-map must be updated"))
312    ;; Make all multibyte characters search for themselves.
313    (let ((l (generic-character-list))
314	  (table (nth 1 map)))
315      (while l
316	(set-char-table-default table (car l) 'isearch-printing-char)
317	(setq l (cdr l))))
318    ;; Make function keys, etc, which aren't bound to a scrolling-function
319    ;; exit the search.
320    (define-key map [t] 'isearch-other-control-char)
321    ;; Control chars, by default, end isearch mode transparently.
322    ;; We need these explicit definitions because, in a dense keymap,
323    ;; the binding for t does not affect characters.
324    ;; We use a dense keymap to save space.
325    (while (< i ?\s)
326      (define-key map (make-string 1 i) 'isearch-other-control-char)
327      (setq i (1+ i)))
328
329    ;; Single-byte printing chars extend the search string by default.
330    (setq i ?\s)
331    (while (< i 256)
332      (define-key map (vector i) 'isearch-printing-char)
333      (setq i (1+ i)))
334
335    ;; To handle local bindings with meta char prefix keys, define
336    ;; another full keymap.  This must be done for any other prefix
337    ;; keys as well, one full keymap per char of the prefix key.  It
338    ;; would be simpler to disable the global keymap, and/or have a
339    ;; default local key binding for any key not otherwise bound.
340    (let ((meta-map (make-sparse-keymap)))
341      (define-key map (char-to-string meta-prefix-char) meta-map)
342      (define-key map [escape] meta-map))
343    (define-key map (vector meta-prefix-char t) 'isearch-other-meta-char)
344
345    ;; Several non-printing chars change the searching behavior.
346    (define-key map "\C-s" 'isearch-repeat-forward)
347    (define-key map "\C-r" 'isearch-repeat-backward)
348    ;; Define M-C-s and M-C-r like C-s and C-r so that the same key
349    ;; combinations can be used to repeat regexp isearches that can
350    ;; be used to start these searches.
351    (define-key map "\M-\C-s" 'isearch-repeat-forward)
352    (define-key map "\M-\C-r" 'isearch-repeat-backward)
353    (define-key map "\177" 'isearch-delete-char)
354    (define-key map "\C-g" 'isearch-abort)
355
356    ;; This assumes \e is the meta-prefix-char.
357    (or (= ?\e meta-prefix-char)
358	(error "Inconsistency in isearch.el"))
359    (define-key map "\e\e\e" 'isearch-cancel)
360    (define-key map  [escape escape escape] 'isearch-cancel)
361
362    (define-key map "\C-q" 'isearch-quote-char)
363
364    (define-key map "\r" 'isearch-exit)
365    (define-key map "\C-j" 'isearch-printing-char)
366    (define-key map "\t" 'isearch-printing-char)
367    (define-key map [?\S-\ ] 'isearch-printing-char)
368
369    (define-key map    "\C-w" 'isearch-yank-word-or-char)
370    (define-key map "\M-\C-w" 'isearch-del-char)
371    (define-key map "\M-\C-y" 'isearch-yank-char)
372    (define-key map    "\C-y" 'isearch-yank-line)
373
374    ;; Turned off because I find I expect to get the global definition--rms.
375    ;; ;; Instead bind C-h to special help command for isearch-mode.
376    ;; (define-key map "\C-h" 'isearch-mode-help)
377
378    (define-key map "\M-n" 'isearch-ring-advance)
379    (define-key map "\M-p" 'isearch-ring-retreat)
380    (define-key map "\M-y" 'isearch-yank-kill)
381
382    (define-key map "\M-\t" 'isearch-complete)
383
384    ;; Pass frame events transparently so they won't exit the search.
385    ;; In particular, if we have more than one display open, then a
386    ;; switch-frame might be generated by someone typing at another keyboard.
387    (define-key map [switch-frame] nil)
388    (define-key map [delete-frame] nil)
389    (define-key map [iconify-frame] nil)
390    (define-key map [make-frame-visible] nil)
391    (define-key map [mouse-movement] nil)
392    (define-key map [language-change] nil)
393
394    ;; For searching multilingual text.
395    (define-key map "\C-\\" 'isearch-toggle-input-method)
396    (define-key map "\C-^" 'isearch-toggle-specified-input-method)
397
398    ;; People expect to be able to paste with the mouse.
399    (define-key map [mouse-2] #'isearch-mouse-2)
400    (define-key map [down-mouse-2] nil)
401
402    ;; Some bindings you may want to put in your isearch-mode-hook.
403    ;; Suggest some alternates...
404    (define-key map "\M-c" 'isearch-toggle-case-fold)
405    (define-key map "\M-r" 'isearch-toggle-regexp)
406    (define-key map "\M-e" 'isearch-edit-string)
407
408    (define-key map [?\M-%] 'isearch-query-replace)
409    (define-key map [?\C-\M-%] 'isearch-query-replace-regexp)
410
411    map)
412  "Keymap for `isearch-mode'.")
413
414(defvar minibuffer-local-isearch-map
415  (let ((map (make-sparse-keymap)))
416    (set-keymap-parent map minibuffer-local-map)
417    (define-key map "\r"    'isearch-nonincremental-exit-minibuffer)
418    (define-key map "\M-\t" 'isearch-complete-edit)
419    (define-key map "\C-s"  'isearch-forward-exit-minibuffer)
420    (define-key map "\C-r"  'isearch-reverse-exit-minibuffer)
421    (define-key map "\C-f"  'isearch-yank-char-in-minibuffer)
422    (define-key map [right] 'isearch-yank-char-in-minibuffer)
423    map)
424  "Keymap for editing isearch strings in the minibuffer.")
425
426;; Internal variables declared globally for byte-compiler.
427;; These are all set with setq while isearching
428;; and bound locally while editing the search string.
429
430(defvar isearch-forward nil)	; Searching in the forward direction.
431(defvar isearch-regexp nil)	; Searching for a regexp.
432(defvar isearch-word nil)	; Searching for words.
433(defvar isearch-hidden nil) ; Non-nil if the string exists but is invisible.
434
435(defvar isearch-cmds nil
436  "Stack of search status sets.
437Each set is a vector of the form:
438 [STRING MESSAGE POINT SUCCESS FORWARD OTHER-END WORD
439  INVALID-REGEXP WRAPPED BARRIER WITHIN-BRACKETS CASE-FOLD-SEARCH]")
440
441(defvar isearch-string "")  ; The current search string.
442(defvar isearch-message "") ; text-char-description version of isearch-string
443
444(defvar isearch-success t)	; Searching is currently successful.
445(defvar isearch-error nil)	; Error message for failed search.
446(defvar isearch-other-end nil)	; Start (end) of match if forward (backward).
447(defvar isearch-wrapped nil)	; Searching restarted from the top (bottom).
448(defvar isearch-barrier 0)
449(defvar isearch-just-started nil)
450(defvar isearch-start-hscroll 0)	; hscroll when starting the search.
451
452; case-fold-search while searching.
453;   either nil, t, or 'yes.  'yes means the same as t except that mixed
454;   case in the search string is ignored.
455(defvar isearch-case-fold-search nil)
456
457(defvar isearch-last-case-fold-search nil)
458
459;; Used to save default value while isearch is active
460(defvar isearch-original-minibuffer-message-timeout nil)
461
462(defvar isearch-adjusted nil)
463(defvar isearch-slow-terminal-mode nil)
464;; If t, using a small window.
465(defvar isearch-small-window nil)
466(defvar isearch-opoint 0)
467;; The window configuration active at the beginning of the search.
468(defvar isearch-window-configuration nil)
469
470;; Flag to indicate a yank occurred, so don't move the cursor.
471(defvar isearch-yank-flag nil)
472
473;; A function to be called after each input character is processed.
474;; (It is not called after characters that exit the search.)
475;; It is only set from an optional argument to `isearch-mode'.
476(defvar isearch-op-fun nil)
477
478;;  Is isearch-mode in a recursive edit for modal searching.
479(defvar isearch-recursive-edit nil)
480
481;; Should isearch be terminated after doing one search?
482(defvar isearch-nonincremental nil)
483
484;; New value of isearch-forward after isearch-edit-string.
485(defvar isearch-new-forward nil)
486
487;; Accumulate here the overlays opened during searching.
488(defvar isearch-opened-overlays nil)
489
490;; The value of input-method-function when isearch is invoked.
491(defvar isearch-input-method-function nil)
492
493;; A flag to tell if input-method-function is locally bound when
494;; isearch is invoked.
495(defvar isearch-input-method-local-p nil)
496
497;; Minor-mode-alist changes - kind of redundant with the
498;; echo area, but if isearching in multiple windows, it can be useful.
499
500(or (assq 'isearch-mode minor-mode-alist)
501    (nconc minor-mode-alist
502	   (list '(isearch-mode isearch-mode))))
503
504(defvar isearch-mode nil) ;; Name of the minor mode, if non-nil.
505(make-variable-buffer-local 'isearch-mode)
506
507(define-key global-map "\C-s" 'isearch-forward)
508(define-key esc-map "\C-s" 'isearch-forward-regexp)
509(define-key global-map "\C-r" 'isearch-backward)
510(define-key esc-map "\C-r" 'isearch-backward-regexp)
511
512;; Entry points to isearch-mode.
513
514(defun isearch-forward (&optional regexp-p no-recursive-edit)
515  "\
516Do incremental search forward.
517With a prefix argument, do an incremental regular expression search instead.
518\\<isearch-mode-map>
519As you type characters, they add to the search string and are found.
520The following non-printing keys are bound in `isearch-mode-map'.
521
522Type \\[isearch-delete-char] to cancel last input item from end of search string.
523Type \\[isearch-exit] to exit, leaving point at location found.
524Type LFD (C-j) to match end of line.
525Type \\[isearch-repeat-forward] to search again forward,\
526 \\[isearch-repeat-backward] to search again backward.
527Type \\[isearch-yank-word-or-char] to yank next word or character in buffer
528  onto the end of the search string, and search for it.
529Type \\[isearch-del-char] to delete character from end of search string.
530Type \\[isearch-yank-char] to yank char from buffer onto end of search\
531 string and search for it.
532Type \\[isearch-yank-line] to yank rest of line onto end of search string\
533 and search for it.
534Type \\[isearch-yank-kill] to yank the last string of killed text.
535Type \\[isearch-quote-char] to quote control character to search for it.
536\\[isearch-abort] while searching or when search has failed cancels input\
537 back to what has
538 been found successfully.
539\\[isearch-abort] when search is successful aborts and moves point to\
540 starting point.
541
542If you try to exit with the search string still empty, it invokes
543 nonincremental search.
544
545Type \\[isearch-query-replace] to start `query-replace' with string to\
546 replace from last search string.
547Type \\[isearch-query-replace-regexp] to start `query-replace-regexp'\
548 with string to replace from last search string.
549
550Type \\[isearch-toggle-case-fold] to toggle search case-sensitivity.
551Type \\[isearch-toggle-regexp] to toggle regular-expression mode.
552Type \\[isearch-edit-string] to edit the search string in the minibuffer.
553
554Also supported is a search ring of the previous 16 search strings.
555Type \\[isearch-ring-advance] to search for the next item in the search ring.
556Type \\[isearch-ring-retreat] to search for the previous item in the search\
557 ring.
558Type \\[isearch-complete] to complete the search string using the search ring.
559
560If an input method is turned on in the current buffer, that input
561method is also active while you are typing characters to search.  To
562toggle the input method, type \\[isearch-toggle-input-method].  It
563also toggles the input method in the current buffer.
564
565To use a different input method for searching, type
566\\[isearch-toggle-specified-input-method], and specify an input method
567you want to use.
568
569The above keys, bound in `isearch-mode-map', are often controlled by
570 options; do \\[apropos] on search-.* to find them.
571Other control and meta characters terminate the search
572 and are then executed normally (depending on `search-exit-option').
573Likewise for function keys and mouse button events.
574
575If this function is called non-interactively, it does not return to
576the calling function until the search is done."
577
578  (interactive "P\np")
579  (isearch-mode t (not (null regexp-p)) nil (not no-recursive-edit)))
580
581(defun isearch-forward-regexp (&optional not-regexp no-recursive-edit)
582  "\
583Do incremental search forward for regular expression.
584With a prefix argument, do a regular string search instead.
585Like ordinary incremental search except that your input
586is treated as a regexp.  See \\[isearch-forward] for more info.
587
588In regexp incremental searches, a space or spaces normally matches
589any whitespace (the variable `search-whitespace-regexp' controls
590precisely what that means).  If you want to search for a literal space
591and nothing else, enter C-q SPC."
592  (interactive "P\np")
593  (isearch-mode t (null not-regexp) nil (not no-recursive-edit)))
594
595(defun isearch-backward (&optional regexp-p no-recursive-edit)
596  "\
597Do incremental search backward.
598With a prefix argument, do a regular expression search instead.
599See \\[isearch-forward] for more information."
600  (interactive "P\np")
601  (isearch-mode nil (not (null regexp-p)) nil (not no-recursive-edit)))
602
603(defun isearch-backward-regexp (&optional not-regexp no-recursive-edit)
604  "\
605Do incremental search backward for regular expression.
606With a prefix argument, do a regular string search instead.
607Like ordinary incremental search except that your input
608is treated as a regexp.  See \\[isearch-forward] for more info."
609  (interactive "P\np")
610  (isearch-mode nil (null not-regexp) nil (not no-recursive-edit)))
611
612
613(defun isearch-mode-help ()
614  (interactive)
615  (describe-function 'isearch-forward)
616  (isearch-update))
617
618
619;; isearch-mode only sets up incremental search for the minor mode.
620;; All the work is done by the isearch-mode commands.
621
622;; Not used yet:
623;;(defvar isearch-commands '(isearch-forward isearch-backward
624;;			     isearch-forward-regexp isearch-backward-regexp)
625;;  "List of commands for which isearch-mode does not recursive-edit.")
626
627
628(defun isearch-mode (forward &optional regexp op-fun recursive-edit word-p)
629  "Start isearch minor mode.  Called by `isearch-forward', etc.
630
631\\{isearch-mode-map}"
632
633  ;; Initialize global vars.
634  (setq isearch-forward forward
635	isearch-regexp regexp
636	isearch-word word-p
637	isearch-op-fun op-fun
638	isearch-last-case-fold-search isearch-case-fold-search
639	isearch-case-fold-search case-fold-search
640	isearch-string ""
641	isearch-message ""
642	isearch-cmds nil
643	isearch-success t
644	isearch-wrapped nil
645	isearch-barrier (point)
646	isearch-adjusted nil
647	isearch-yank-flag nil
648	isearch-error nil
649	isearch-slow-terminal-mode (and (<= baud-rate search-slow-speed)
650					(> (window-height)
651					   (* 4
652					      (abs search-slow-window-lines))))
653	isearch-other-end nil
654	isearch-small-window nil
655	isearch-just-started t
656	isearch-start-hscroll (window-hscroll)
657
658	isearch-opoint (point)
659	search-ring-yank-pointer nil
660	isearch-opened-overlays nil
661	isearch-input-method-function input-method-function
662	isearch-input-method-local-p (local-variable-p 'input-method-function)
663	regexp-search-ring-yank-pointer nil
664
665	;; Save the original value of `minibuffer-message-timeout', and
666	;; set it to nil so that isearch's messages don't get timed out.
667	isearch-original-minibuffer-message-timeout minibuffer-message-timeout
668	minibuffer-message-timeout nil)
669
670  ;; We must bypass input method while reading key.  When a user type
671  ;; printable character, appropriate input method is turned on in
672  ;; minibuffer to read multibyte characters.
673  (or isearch-input-method-local-p
674      (make-local-variable 'input-method-function))
675  (setq input-method-function nil)
676
677  (looking-at "")
678  (setq isearch-window-configuration
679	(if isearch-slow-terminal-mode (current-window-configuration) nil))
680
681  ;; Maybe make minibuffer frame visible and/or raise it.
682  (let ((frame (window-frame (minibuffer-window))))
683    (unless (memq (frame-live-p frame) '(nil t))
684      (unless (frame-visible-p frame)
685	(make-frame-visible frame))
686      (if minibuffer-auto-raise
687	  (raise-frame frame))))
688
689  (setq	isearch-mode " Isearch")  ;; forward? regexp?
690  (force-mode-line-update)
691
692  (isearch-push-state)
693
694  (setq overriding-terminal-local-map isearch-mode-map)
695  (isearch-update)
696  (run-hooks 'isearch-mode-hook)
697
698  (add-hook 'mouse-leave-buffer-hook 'isearch-done)
699  (add-hook 'kbd-macro-termination-hook 'isearch-done)
700
701  ;; isearch-mode can be made modal (in the sense of not returning to
702  ;; the calling function until searching is completed) by entering
703  ;; a recursive-edit and exiting it when done isearching.
704  (if recursive-edit
705      (let ((isearch-recursive-edit t))
706	(recursive-edit)))
707  isearch-success)
708
709
710;; Some high level utilities.  Others below.
711
712(defun isearch-update ()
713  ;; Called after each command to update the display.
714  (if (and (null unread-command-events)
715	   (null executing-kbd-macro))
716      (progn
717        (if (not (input-pending-p))
718            (isearch-message))
719        (if (and isearch-slow-terminal-mode
720                 (not (or isearch-small-window
721                          (pos-visible-in-window-p))))
722            (let ((found-point (point)))
723              (setq isearch-small-window t)
724              (move-to-window-line 0)
725              (let ((window-min-height 1))
726                (split-window nil (if (< search-slow-window-lines 0)
727                                      (1+ (- search-slow-window-lines))
728                                    (- (window-height)
729                                       (1+ search-slow-window-lines)))))
730              (if (< search-slow-window-lines 0)
731                  (progn (vertical-motion (- 1 search-slow-window-lines))
732                         (set-window-start (next-window) (point))
733                         (set-window-hscroll (next-window)
734                                             (window-hscroll))
735                         (set-window-hscroll (selected-window) 0))
736                (other-window 1))
737              (goto-char found-point))
738	  ;; Keep same hscrolling as at the start of the search when possible
739	  (let ((current-scroll (window-hscroll)))
740	    (set-window-hscroll (selected-window) isearch-start-hscroll)
741	    (unless (pos-visible-in-window-p)
742	      (set-window-hscroll (selected-window) current-scroll))))
743	(if isearch-other-end
744            (if (< isearch-other-end (point)) ; isearch-forward?
745                (isearch-highlight isearch-other-end (point))
746              (isearch-highlight (point) isearch-other-end))
747          (isearch-dehighlight))
748        ))
749  (setq ;; quit-flag nil  not for isearch-mode
750   isearch-adjusted nil
751   isearch-yank-flag nil)
752  (when isearch-lazy-highlight
753    (isearch-lazy-highlight-new-loop))
754  ;; We must prevent the point moving to the end of composition when a
755  ;; part of the composition has just been searched.
756  (setq disable-point-adjustment t))
757
758(defun isearch-done (&optional nopush edit)
759  "Exit Isearch mode.
760For successful search, pass no args.
761For a failing search, NOPUSH is t.
762For going to the minibuffer to edit the search string,
763NOPUSH is t and EDIT is t."
764
765  (if isearch-resume-in-command-history
766      (let ((command `(isearch-resume ,isearch-string ,isearch-regexp
767				      ,isearch-word ,isearch-forward
768				      ,isearch-message
769				      ',isearch-case-fold-search)))
770	(unless (equal (car command-history) command)
771	  (setq command-history (cons command command-history)))))
772
773  (remove-hook 'mouse-leave-buffer-hook 'isearch-done)
774  (remove-hook 'kbd-macro-termination-hook 'isearch-done)
775  (setq isearch-lazy-highlight-start nil)
776
777  ;; Called by all commands that terminate isearch-mode.
778  ;; If NOPUSH is non-nil, we don't push the string on the search ring.
779  (setq overriding-terminal-local-map nil)
780  ;; (setq pre-command-hook isearch-old-pre-command-hook) ; for lemacs
781  (setq minibuffer-message-timeout isearch-original-minibuffer-message-timeout)
782  (isearch-dehighlight)
783  (lazy-highlight-cleanup lazy-highlight-cleanup)
784  (let ((found-start (window-start (selected-window)))
785	(found-point (point)))
786    (when isearch-window-configuration
787      (set-window-configuration isearch-window-configuration)
788      (if isearch-small-window
789	  (goto-char found-point)
790	;; set-window-configuration clobbers window-start; restore it.
791	;; This has an annoying side effect of clearing the last_modiff
792	;; field of the window, which can cause unwanted scrolling,
793	;; so don't do it unless truly necessary.
794	(set-window-start (selected-window) found-start t))))
795
796  (setq isearch-mode nil)
797  (if isearch-input-method-local-p
798      (setq input-method-function isearch-input-method-function)
799    (kill-local-variable 'input-method-function))
800
801  (force-mode-line-update)
802
803  ;; If we ended in the middle of some intangible text,
804  ;; move to the further end of that intangible text.
805  (let ((after (if (eobp) nil
806		 (get-text-property (point) 'intangible)))
807	(before (if (bobp) nil
808		  (get-text-property (1- (point)) 'intangible))))
809    (when (and before after (eq before after))
810      (if isearch-forward
811	  (goto-char (next-single-property-change (point) 'intangible))
812	(goto-char (previous-single-property-change (point) 'intangible)))))
813
814  (if (and (> (length isearch-string) 0) (not nopush))
815      ;; Update the ring data.
816      (isearch-update-ring isearch-string isearch-regexp))
817
818  (let ((isearch-mode-end-hook-quit (and nopush (not edit))))
819    (run-hooks 'isearch-mode-end-hook))
820
821  ;; If there was movement, mark the starting position.
822  ;; Maybe should test difference between and set mark iff > threshold.
823  (if (/= (point) isearch-opoint)
824      (or (and transient-mark-mode mark-active)
825	  (progn
826	    (push-mark isearch-opoint t)
827	    (or executing-kbd-macro (> (minibuffer-depth) 0)
828		(message "Mark saved where search started")))))
829
830  (and (not edit) isearch-recursive-edit (exit-recursive-edit)))
831
832(defun isearch-update-ring (string &optional regexp)
833  "Add STRING to the beginning of the search ring.
834REGEXP if non-nil says use the regexp search ring."
835  (add-to-history
836   (if regexp 'regexp-search-ring 'search-ring)
837   string
838   (if regexp regexp-search-ring-max search-ring-max)))
839
840;; Switching buffers should first terminate isearch-mode.
841;; ;; For Emacs 19, the frame switch event is handled.
842;; (defun isearch-switch-frame-handler ()
843;;   (interactive) ;; Is this necessary?
844;;   ;; First terminate isearch-mode.
845;;   (isearch-done)
846;;   (isearch-clean-overlays)
847;;   (handle-switch-frame (car (cdr last-command-char))))
848
849
850;; The search status structure and stack.
851
852(defsubst isearch-string-state (frame)
853  "Return the search string in FRAME."
854  (aref frame 0))
855(defsubst isearch-message-state (frame)
856  "Return the search string to display to the user in FRAME."
857  (aref frame 1))
858(defsubst isearch-point-state (frame)
859  "Return the point in FRAME."
860  (aref frame 2))
861(defsubst isearch-success-state (frame)
862  "Return the success flag in FRAME."
863  (aref frame 3))
864(defsubst isearch-forward-state (frame)
865  "Return the searching-forward flag in FRAME."
866  (aref frame 4))
867(defsubst isearch-other-end-state (frame)
868  "Return the other end of the match in FRAME."
869  (aref frame 5))
870(defsubst isearch-word-state (frame)
871  "Return the search-by-word flag in FRAME."
872  (aref frame 6))
873(defsubst isearch-error-state (frame)
874  "Return the regexp error message in FRAME, or nil if its regexp is valid."
875  (aref frame 7))
876(defsubst isearch-wrapped-state (frame)
877  "Return the search-wrapped flag in FRAME."
878  (aref frame 8))
879(defsubst isearch-barrier-state (frame)
880  "Return the barrier value in FRAME."
881  (aref frame 9))
882(defsubst isearch-case-fold-search-state (frame)
883  "Return the case-folding flag in FRAME."
884  (aref frame 10))
885(defsubst isearch-pop-fun-state (frame)
886  "Return the function restoring the mode-specific isearch state in FRAME."
887  (aref frame 11))
888
889(defun isearch-top-state ()
890  (let ((cmd (car isearch-cmds)))
891    (setq isearch-string (isearch-string-state cmd)
892	  isearch-message (isearch-message-state cmd)
893	  isearch-success (isearch-success-state cmd)
894	  isearch-forward (isearch-forward-state cmd)
895	  isearch-other-end (isearch-other-end-state cmd)
896	  isearch-word (isearch-word-state cmd)
897	  isearch-error (isearch-error-state cmd)
898	  isearch-wrapped (isearch-wrapped-state cmd)
899	  isearch-barrier (isearch-barrier-state cmd)
900	  isearch-case-fold-search (isearch-case-fold-search-state cmd))
901    (if (functionp (isearch-pop-fun-state cmd))
902	(funcall (isearch-pop-fun-state cmd) cmd))
903    (goto-char (isearch-point-state cmd))))
904
905(defun isearch-pop-state ()
906  (setq isearch-cmds (cdr isearch-cmds))
907  (isearch-top-state))
908
909(defun isearch-push-state ()
910  (setq isearch-cmds
911	(cons (vector isearch-string isearch-message (point)
912		      isearch-success isearch-forward isearch-other-end
913		      isearch-word
914		      isearch-error isearch-wrapped isearch-barrier
915		      isearch-case-fold-search
916		      (if isearch-push-state-function
917			  (funcall isearch-push-state-function)))
918	      isearch-cmds)))
919
920
921;; Commands active while inside of the isearch minor mode.
922
923(defun isearch-exit ()
924  "Exit search normally.
925However, if this is the first command after starting incremental
926search and `search-nonincremental-instead' is non-nil, do a
927nonincremental search instead via `isearch-edit-string'."
928  (interactive)
929  (if (and search-nonincremental-instead
930	   (= 0 (length isearch-string)))
931      (let ((isearch-nonincremental t))
932	(isearch-edit-string)))
933  (isearch-done)
934  (isearch-clean-overlays))
935
936
937(defun isearch-edit-string ()
938  "Edit the search string in the minibuffer.
939The following additional command keys are active while editing.
940\\<minibuffer-local-isearch-map>
941\\[exit-minibuffer] to resume incremental searching with the edited string.
942\\[isearch-nonincremental-exit-minibuffer] to do one nonincremental search.
943\\[isearch-forward-exit-minibuffer] to resume isearching forward.
944\\[isearch-reverse-exit-minibuffer] to resume isearching backward.
945\\[isearch-complete-edit] to complete the search string using the search ring.
946\\<isearch-mode-map>
947If first char entered is \\[isearch-yank-word-or-char], then do word search instead."
948
949  ;; This code is very hairy for several reasons, explained in the code.
950  ;; Mainly, isearch-mode must be terminated while editing and then restarted.
951  ;; If there were a way to catch any change of buffer from the minibuffer,
952  ;; this could be simplified greatly.
953  ;; Editing doesn't back up the search point.  Should it?
954  (interactive)
955  (condition-case err
956      (progn
957	(let ((isearch-nonincremental isearch-nonincremental)
958
959	      ;; Locally bind all isearch global variables to protect them
960	      ;; from recursive isearching.
961	      ;; isearch-string -message and -forward are not bound
962	      ;; so they may be changed.  Instead, save the values.
963	      (isearch-new-string isearch-string)
964	      (isearch-new-message isearch-message)
965	      (isearch-new-forward isearch-forward)
966	      (isearch-new-word isearch-word)
967
968	      (isearch-regexp isearch-regexp)
969	      (isearch-op-fun isearch-op-fun)
970	      (isearch-cmds isearch-cmds)
971	      (isearch-success isearch-success)
972	      (isearch-wrapped isearch-wrapped)
973	      (isearch-barrier isearch-barrier)
974	      (isearch-adjusted isearch-adjusted)
975	      (isearch-yank-flag isearch-yank-flag)
976	      (isearch-error isearch-error)
977  ;;; Don't bind this.  We want isearch-search, below, to set it.
978  ;;; And the old value won't matter after that.
979  ;;;	    (isearch-other-end isearch-other-end)
980  ;;; Perhaps some of these other variables should be bound for a
981  ;;; shorter period, ending before the next isearch-search.
982  ;;; But there doesn't seem to be a real bug, so let's not risk it now.
983	      (isearch-opoint isearch-opoint)
984	      (isearch-slow-terminal-mode isearch-slow-terminal-mode)
985	      (isearch-small-window isearch-small-window)
986	      (isearch-recursive-edit isearch-recursive-edit)
987	      ;; Save current configuration so we can restore it here.
988	      (isearch-window-configuration (current-window-configuration))
989
990	      ;; Temporarily restore `minibuffer-message-timeout'.
991	      (minibuffer-message-timeout
992	       isearch-original-minibuffer-message-timeout)
993	      (isearch-original-minibuffer-message-timeout
994	       isearch-original-minibuffer-message-timeout)
995	      )
996
997	  ;; Actually terminate isearching until editing is done.
998	  ;; This is so that the user can do anything without failure,
999	  ;; like switch buffers and start another isearch, and return.
1000	  (condition-case err
1001	      (isearch-done t t)
1002	    (exit nil))			; was recursive editing
1003
1004	  (isearch-message) ;; for read-char
1005	  (unwind-protect
1006	      (let* (;; Why does following read-char echo?
1007		     ;;(echo-keystrokes 0) ;; not needed with above message
1008		     (e (let ((cursor-in-echo-area t))
1009			  (read-event)))
1010		     ;; Binding minibuffer-history-symbol to nil is a work-around
1011		     ;; for some incompatibility with gmhist.
1012		     (minibuffer-history-symbol)
1013		     (message-log-max nil))
1014		;; If the first character the user types when we prompt them
1015		;; for a string is the yank-word character, then go into
1016		;; word-search mode.  Otherwise unread that character and
1017		;; read a key the normal way.
1018		;; Word search does not apply (yet) to regexp searches,
1019		;; no check is made here.
1020		(message "%s" (isearch-message-prefix nil nil t))
1021		(if (memq (lookup-key isearch-mode-map (vector e))
1022			  '(isearch-yank-word
1023			    isearch-yank-word-or-char))
1024		    (setq isearch-word t;; so message-prefix is right
1025			  isearch-new-word t)
1026		  (cancel-kbd-macro-events)
1027		  (isearch-unread e))
1028		(setq cursor-in-echo-area nil)
1029		(setq isearch-new-string
1030                      (read-from-minibuffer
1031                       (isearch-message-prefix nil nil isearch-nonincremental)
1032                       isearch-string
1033                       minibuffer-local-isearch-map nil
1034                       (if isearch-regexp 'regexp-search-ring 'search-ring)
1035                       nil t)
1036		      isearch-new-message
1037		      (mapconcat 'isearch-text-char-description
1038				 isearch-new-string "")))
1039	    ;; Always resume isearching by restarting it.
1040	    (isearch-mode isearch-forward
1041			  isearch-regexp
1042			  isearch-op-fun
1043			  nil
1044			  isearch-word)
1045
1046	    ;; Copy new local values to isearch globals
1047	    (setq isearch-string isearch-new-string
1048		  isearch-message isearch-new-message
1049		  isearch-forward isearch-new-forward
1050		  isearch-word isearch-new-word))
1051
1052	  ;; Empty isearch-string means use default.
1053	  (if (= 0 (length isearch-string))
1054	      (setq isearch-string (or (car (if isearch-regexp
1055						regexp-search-ring
1056					      search-ring))
1057				       "")
1058
1059		    isearch-message
1060		    (mapconcat 'isearch-text-char-description
1061			       isearch-string ""))
1062	    ;; This used to set the last search string,
1063	    ;; but I think it is not right to do that here.
1064	    ;; Only the string actually used should be saved.
1065	    ))
1066
1067	;; Push the state as of before this C-s.
1068	(isearch-push-state)
1069
1070	;; Reinvoke the pending search.
1071	(isearch-search)
1072	(isearch-update)
1073	(if isearch-nonincremental
1074	    (progn
1075	      ;; (sit-for 1) ;; needed if isearch-done does: (message "")
1076	      (isearch-done)
1077	      ;; The search done message is confusing when the string
1078	      ;; is empty, so erase it.
1079	      (if (equal isearch-string "")
1080		  (message "")))))
1081
1082    (quit  ; handle abort-recursive-edit
1083     (isearch-abort)  ;; outside of let to restore outside global values
1084     )))
1085
1086(defun isearch-nonincremental-exit-minibuffer ()
1087  (interactive)
1088  (setq isearch-nonincremental t)
1089  (exit-minibuffer))
1090
1091(defun isearch-forward-exit-minibuffer ()
1092  (interactive)
1093  (setq isearch-new-forward t)
1094  (exit-minibuffer))
1095
1096(defun isearch-reverse-exit-minibuffer ()
1097  (interactive)
1098  (setq isearch-new-forward nil)
1099  (exit-minibuffer))
1100
1101(defun isearch-cancel ()
1102  "Terminate the search and go back to the starting point."
1103  (interactive)
1104  (if (functionp (isearch-pop-fun-state (car (last isearch-cmds))))
1105      (funcall (isearch-pop-fun-state (car (last isearch-cmds)))
1106               (car (last isearch-cmds))))
1107  (goto-char isearch-opoint)
1108  (isearch-done t)                      ; exit isearch
1109  (isearch-clean-overlays)
1110  (signal 'quit nil))                   ; and pass on quit signal
1111
1112(defun isearch-abort ()
1113  "Abort incremental search mode if searching is successful, signaling quit.
1114Otherwise, revert to previous successful search and continue searching.
1115Use `isearch-exit' to quit without signaling."
1116  (interactive)
1117;;  (ding)  signal instead below, if quitting
1118  (discard-input)
1119  (if isearch-success
1120      ;; If search is successful, move back to starting point
1121      ;; and really do quit.
1122      (progn
1123        (setq isearch-success nil)
1124        (isearch-cancel))
1125    ;; If search is failing, or has an incomplete regexp,
1126    ;; rub out until it is once more successful.
1127    (while (or (not isearch-success) isearch-error)
1128      (isearch-pop-state))
1129    (isearch-update)))
1130
1131(defun isearch-repeat (direction)
1132  ;; Utility for isearch-repeat-forward and -backward.
1133  (if (eq isearch-forward (eq direction 'forward))
1134      ;; C-s in forward or C-r in reverse.
1135      (if (equal isearch-string "")
1136	  ;; If search string is empty, use last one.
1137	  (if (null (if isearch-regexp regexp-search-ring search-ring))
1138	      (setq isearch-error "No previous search string")
1139	    (setq isearch-string
1140		  (if isearch-regexp
1141		      (car regexp-search-ring)
1142		    (car search-ring))
1143		  isearch-message
1144		  (mapconcat 'isearch-text-char-description
1145			     isearch-string "")
1146		  isearch-case-fold-search isearch-last-case-fold-search))
1147	;; If already have what to search for, repeat it.
1148	(or isearch-success
1149	    (progn
1150	      ;; Set isearch-wrapped before calling isearch-wrap-function
1151	      (setq isearch-wrapped t)
1152	      (if isearch-wrap-function
1153		  (funcall isearch-wrap-function)
1154	        (goto-char (if isearch-forward (point-min) (point-max)))))))
1155    ;; C-s in reverse or C-r in forward, change direction.
1156    (setq isearch-forward (not isearch-forward)
1157	  isearch-success t))
1158
1159  (setq isearch-barrier (point)) ; For subsequent \| if regexp.
1160
1161  (if (equal isearch-string "")
1162      (setq isearch-success t)
1163    (if (and isearch-success
1164	     (equal (point) isearch-other-end)
1165	     (not isearch-just-started))
1166	;; If repeating a search that found
1167	;; an empty string, ensure we advance.
1168	(if (if isearch-forward (eobp) (bobp))
1169	    ;; If there's nowhere to advance to, fail (and wrap next time).
1170	    (progn
1171	      (setq isearch-success nil)
1172	      (ding))
1173	  (forward-char (if isearch-forward 1 -1))
1174	  (isearch-search))
1175      (isearch-search)))
1176
1177  (isearch-push-state)
1178  (isearch-update))
1179
1180(defun isearch-repeat-forward ()
1181  "Repeat incremental search forwards."
1182  (interactive)
1183  (isearch-repeat 'forward))
1184
1185(defun isearch-repeat-backward ()
1186  "Repeat incremental search backwards."
1187  (interactive)
1188  (isearch-repeat 'backward))
1189
1190(defun isearch-toggle-regexp ()
1191  "Toggle regexp searching on or off."
1192  ;; The status stack is left unchanged.
1193  (interactive)
1194  (setq isearch-regexp (not isearch-regexp))
1195  (if isearch-regexp (setq isearch-word nil))
1196  (setq isearch-success t isearch-adjusted t)
1197  (isearch-update))
1198
1199(defun isearch-toggle-case-fold ()
1200  "Toggle case folding in searching on or off."
1201  (interactive)
1202  (setq isearch-case-fold-search
1203	(if isearch-case-fold-search nil 'yes))
1204  (let ((message-log-max nil))
1205    (message "%s%s [case %ssensitive]"
1206	     (isearch-message-prefix nil nil isearch-nonincremental)
1207	     isearch-message
1208	     (if isearch-case-fold-search "in" "")))
1209  (setq isearch-success t isearch-adjusted t)
1210  (sit-for 1)
1211  (isearch-update))
1212
1213(defun isearch-query-replace (&optional regexp-flag)
1214  "Start query-replace with string to replace from last search string."
1215  (interactive)
1216  (barf-if-buffer-read-only)
1217  (if regexp-flag (setq isearch-regexp t))
1218  (let ((case-fold-search isearch-case-fold-search))
1219    (isearch-done)
1220    (isearch-clean-overlays)
1221    (if (and isearch-other-end
1222	     (< isearch-other-end (point))
1223             (not (and transient-mark-mode mark-active
1224                       (< (mark) (point)))))
1225        (goto-char isearch-other-end))
1226    (set query-replace-from-history-variable
1227         (cons isearch-string
1228               (symbol-value query-replace-from-history-variable)))
1229    (perform-replace
1230     isearch-string
1231     (query-replace-read-to
1232      isearch-string
1233      (if isearch-regexp "Query replace regexp" "Query replace")
1234      isearch-regexp)
1235     t isearch-regexp isearch-word nil nil
1236     (if (and transient-mark-mode mark-active) (region-beginning))
1237     (if (and transient-mark-mode mark-active) (region-end)))))
1238
1239(defun isearch-query-replace-regexp ()
1240  "Start query-replace-regexp with string to replace from last search string."
1241  (interactive)
1242  (isearch-query-replace t))
1243
1244
1245(defun isearch-delete-char ()
1246  "Discard last input item and move point back.
1247If no previous match was done, just beep."
1248  (interactive)
1249  (if (null (cdr isearch-cmds))
1250      (ding)
1251    (isearch-pop-state))
1252  (isearch-update))
1253
1254(defun isearch-del-char (&optional arg)
1255  "Delete character from end of search string and search again.
1256If search string is empty, just beep."
1257  (interactive "p")
1258  (if (= 0 (length isearch-string))
1259      (ding)
1260    (setq isearch-string (substring isearch-string 0 (- (or arg 1)))
1261          isearch-message (mapconcat 'isearch-text-char-description
1262                                     isearch-string "")
1263          ;; Don't move cursor in reverse search.
1264          isearch-yank-flag t))
1265  (isearch-search-and-update))
1266
1267(defun isearch-yank-string (string)
1268  "Pull STRING into search string."
1269  ;; Downcase the string if not supposed to case-fold yanked strings.
1270  (if (and isearch-case-fold-search
1271	   (eq 'not-yanks search-upper-case))
1272      (setq string (downcase string)))
1273  (if isearch-regexp (setq string (regexp-quote string)))
1274  (setq isearch-string (concat isearch-string string)
1275	isearch-message
1276	(concat isearch-message
1277		(mapconcat 'isearch-text-char-description
1278			   string ""))
1279	;; Don't move cursor in reverse search.
1280	isearch-yank-flag t)
1281  (isearch-search-and-update))
1282
1283(defun isearch-yank-kill ()
1284  "Pull string from kill ring into search string."
1285  (interactive)
1286  (isearch-yank-string (current-kill 0)))
1287
1288(defun isearch-yank-x-selection ()
1289  "Pull current X selection into search string."
1290  (interactive)
1291  (isearch-yank-string (x-get-selection)))
1292
1293
1294(defun isearch-mouse-2 (click)
1295  "Handle mouse-2 in Isearch mode.
1296For a click in the echo area, invoke `isearch-yank-x-selection'.
1297Otherwise invoke whatever the calling mouse-2 command sequence
1298is bound to outside of Isearch."
1299  (interactive "e")
1300  (let* ((w (posn-window (event-start click)))
1301	 (overriding-terminal-local-map nil)
1302	 (binding (key-binding (this-command-keys-vector) t)))
1303    (if (and (window-minibuffer-p w)
1304	     (not (minibuffer-window-active-p w))) ; in echo area
1305	(isearch-yank-x-selection)
1306      (when (functionp binding)
1307	(call-interactively binding)))))
1308
1309(defun isearch-yank-internal (jumpform)
1310  "Pull the text from point to the point reached by JUMPFORM.
1311JUMPFORM is a lambda expression that takes no arguments and returns a
1312buffer position, possibly having moved point to that position.  For
1313example, it might move point forward by a word and return point, or it
1314might return the position of the end of the line."
1315  (isearch-yank-string
1316   (save-excursion
1317     (and (not isearch-forward) isearch-other-end
1318	  (goto-char isearch-other-end))
1319     (buffer-substring-no-properties (point) (funcall jumpform)))))
1320
1321(defun isearch-yank-char-in-minibuffer (&optional arg)
1322  "Pull next character from buffer into end of search string in minibuffer."
1323  (interactive "p")
1324  (if (eobp)
1325      (insert
1326       (save-excursion
1327         (set-buffer (cadr (buffer-list)))
1328         (buffer-substring-no-properties
1329          (point) (progn (forward-char arg) (point)))))
1330    (forward-char arg)))
1331
1332(defun isearch-yank-char (&optional arg)
1333  "Pull next character from buffer into search string."
1334  (interactive "p")
1335  (isearch-yank-internal (lambda () (forward-char arg) (point))))
1336
1337(defun isearch-yank-word-or-char ()
1338  "Pull next character or word from buffer into search string."
1339  (interactive)
1340  (isearch-yank-internal
1341   (lambda ()
1342     (if (or (= (char-syntax (or (char-after) 0)) ?w)
1343             (= (char-syntax (or (char-after (1+ (point))) 0)) ?w))
1344         (forward-word 1)
1345       (forward-char 1)) (point))))
1346
1347(defun isearch-yank-word ()
1348  "Pull next word from buffer into search string."
1349  (interactive)
1350  (isearch-yank-internal (lambda () (forward-word 1) (point))))
1351
1352(defun isearch-yank-line ()
1353  "Pull rest of line from buffer into search string."
1354  (interactive)
1355  (isearch-yank-internal
1356   (lambda () (let ((inhibit-field-text-motion t))
1357		(line-end-position (if (eolp) 2 1))))))
1358
1359(defun isearch-search-and-update ()
1360  ;; Do the search and update the display.
1361  (when (or isearch-success
1362	    ;; Unsuccessful regexp search may become successful by
1363	    ;; addition of characters which make isearch-string valid
1364	    isearch-regexp
1365	    ;; If the string was found but was completely invisible,
1366	    ;; it might now be partly visible, so try again.
1367	    (prog1 isearch-hidden (setq isearch-hidden nil)))
1368    ;; In reverse search, adding stuff at
1369    ;; the end may cause zero or many more chars to be
1370    ;; matched, in the string following point.
1371    ;; Allow all those possibilities without moving point as
1372    ;; long as the match does not extend past search origin.
1373    (if (and (not isearch-forward) (not isearch-adjusted)
1374	     (condition-case ()
1375		 (let ((case-fold-search isearch-case-fold-search))
1376		   (if (and (eq case-fold-search t) search-upper-case)
1377		       (setq case-fold-search
1378			     (isearch-no-upper-case-p isearch-string isearch-regexp)))
1379		   (looking-at (if isearch-regexp isearch-string
1380				 (regexp-quote isearch-string))))
1381	       (error nil))
1382	     (or isearch-yank-flag
1383		 (<= (match-end 0)
1384		     (min isearch-opoint isearch-barrier))))
1385	(progn
1386	  (setq isearch-success t
1387		isearch-error nil
1388		isearch-other-end (match-end 0))
1389	  (if (and (eq isearch-case-fold-search t) search-upper-case)
1390	      (setq isearch-case-fold-search
1391		    (isearch-no-upper-case-p isearch-string isearch-regexp))))
1392      ;; Not regexp, not reverse, or no match at point.
1393      (if (and isearch-other-end (not isearch-adjusted))
1394	  (goto-char (if isearch-forward isearch-other-end
1395		       (min isearch-opoint
1396			    isearch-barrier
1397			    (1+ isearch-other-end)))))
1398      (isearch-search)
1399      ))
1400  (isearch-push-state)
1401  (if isearch-op-fun (funcall isearch-op-fun))
1402  (isearch-update))
1403
1404
1405;; *, ?, }, and | chars can make a regexp more liberal.
1406;; They can make a regexp match sooner or make it succeed instead of failing.
1407;; So go back to place last successful search started
1408;; or to the last ^S/^R (barrier), whichever is nearer.
1409;; + needs no special handling because the string must match at least once.
1410
1411(defun isearch-backslash (str)
1412  "Return t if STR ends in an odd number of backslashes."
1413  (= (mod (- (length str) (string-match "\\\\*\\'" str)) 2) 1))
1414
1415(defun isearch-fallback (want-backslash &optional allow-invalid to-barrier)
1416  "Return point to previous successful match to allow regexp liberalization.
1417\\<isearch-mode-map>
1418Respects \\[isearch-repeat-forward] and \\[isearch-repeat-backward] by
1419stopping at `isearch-barrier' as needed.
1420
1421Do nothing if a backslash is escaping the liberalizing character.
1422If WANT-BACKSLASH is non-nil, invert this behavior (for \\} and \\|).
1423
1424Do nothing if regexp has recently been invalid unless optional
1425ALLOW-INVALID non-nil.
1426
1427If optional TO-BARRIER non-nil, ignore previous matches and go exactly
1428to the barrier."
1429  ;; (eq (not a) (not b)) makes all non-nil values equivalent
1430  (when (and isearch-regexp (eq (not (isearch-backslash isearch-string))
1431				(not want-backslash))
1432	     ;; We have to check 2 stack frames because the last might be
1433	     ;; invalid just because of a backslash.
1434	     (or (not isearch-error)
1435		 (not (isearch-error-state (cadr isearch-cmds)))
1436		 allow-invalid))
1437    (if to-barrier
1438	(progn (goto-char isearch-barrier)
1439	       (setq isearch-adjusted t))
1440      (let* ((stack isearch-cmds)
1441	     (previous (cdr stack))	; lookbelow in the stack
1442	     (frame (car stack)))
1443	;; Walk down the stack looking for a valid regexp (as of course only
1444	;; they can be the previous successful match); this conveniently
1445	;; removes all bracket-sets and groups that might be in the way, as
1446	;; well as partial \{\} constructs that the code below leaves behind.
1447	;; Also skip over postfix operators -- though horrid,
1448	;; 'ab?\{5,6\}+\{1,2\}*' is perfectly legal.
1449	(while (and previous
1450		    (or (isearch-error-state frame)
1451			(let* ((string (isearch-string-state frame))
1452			       (lchar (aref string (1- (length string)))))
1453			  ;; The operators aren't always operators; check
1454			  ;; backslashes.  This doesn't handle the case of
1455			  ;; operators at the beginning of the regexp not
1456			  ;; being special, but then we should fall back to
1457			  ;; the barrier anyway because it's all optional.
1458			  (if (isearch-backslash
1459			       (isearch-string-state (car previous)))
1460			      (eq lchar ?\})
1461			    (memq lchar '(?* ?? ?+))))))
1462	  (setq stack previous previous (cdr previous) frame (car stack)))
1463	(when stack
1464	  ;; `stack' now refers the most recent valid regexp that is not at
1465	  ;; all optional in its last term.  Now dig one level deeper and find
1466	  ;; what matched before that.
1467	  (let ((last-other-end
1468		 (or (and (car previous)
1469			  (isearch-other-end-state (car previous)))
1470		     isearch-barrier)))
1471	    (goto-char (if isearch-forward
1472			   (max last-other-end isearch-barrier)
1473			 (min last-other-end isearch-barrier)))
1474	    (setq isearch-adjusted t)))))))
1475
1476(defun isearch-unread-key-sequence (keylist)
1477  "Unread the given key-sequence KEYLIST.
1478Scroll-bar or mode-line events are processed appropriately."
1479  (cancel-kbd-macro-events)
1480  (apply 'isearch-unread keylist)
1481  ;; If the event was a scroll-bar or mode-line click, the event will have
1482  ;; been prefixed by a symbol such as vertical-scroll-bar.  We must remove
1483  ;; it here, because this symbol will be attached to the event again next
1484  ;; time it gets read by read-key-sequence.
1485  ;;
1486  ;; (Old comment from isearch-other-meta-char: "Note that we don't have to
1487  ;; modify the event anymore in 21 because read_key_sequence no longer
1488  ;; modifies events to produce fake prefix keys.")
1489  (if (and (> (length keylist) 1)
1490           (symbolp (car keylist))
1491           (listp (cadr keylist))
1492           (not (numberp (posn-point
1493                          (event-start (cadr keylist)  )))))
1494      (pop unread-command-events)))
1495
1496;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1497;; scrolling within Isearch mode.  Alan Mackenzie (acm@muc.de), 2003/2/24
1498;;
1499;; The idea here is that certain vertical scrolling commands (like C-l
1500;; `recenter') should be usable WITHIN Isearch mode.  For a command to be
1501;; suitable, it must NOT alter the buffer, swap to another buffer or frame,
1502;; tamper with isearch's state, or move point.  It is unacceptable for the
1503;; search string to be scrolled out of the current window.  If a command
1504;; attempts this, we scroll the text back again.
1505;;
1506;; We implement this feature with a property called `isearch-scroll'.
1507;; If a command's symbol has the value t for this property it is a
1508;; scrolling command.  The feature needs to be enabled by setting the
1509;; customizable variable `isearch-allow-scroll' to a non-nil value.
1510;;
1511;; The universal argument commands (e.g. C-u) in simple.el are marked
1512;; as scrolling commands, and isearch.el has been amended to allow
1513;; prefix arguments to be passed through to scrolling commands.  Thus
1514;; M-0 C-l will scroll point to the top of the window.
1515;;
1516;; Horizontal scrolling commands are currently not catered for.
1517;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1518
1519;; Set the isearch-scroll property on some standard functions:
1520;; Scroll-bar functions:
1521(if (fboundp 'scroll-bar-toolkit-scroll)
1522    (put 'scroll-bar-toolkit-scroll 'isearch-scroll t))
1523(if (fboundp 'mac-handle-scroll-bar-event)
1524    (put 'mac-handle-scroll-bar-event 'isearch-scroll t))
1525(if (fboundp 'w32-handle-scroll-bar-event)
1526    (put 'w32-handle-scroll-bar-event 'isearch-scroll t))
1527
1528;; Commands which scroll the window:
1529(put 'recenter 'isearch-scroll t)
1530(put 'reposition-window 'isearch-scroll t)
1531(put 'scroll-up 'isearch-scroll t)
1532(put 'scroll-down 'isearch-scroll t)
1533
1534;; Commands which act on the other window
1535(put 'list-buffers 'isearch-scroll t)
1536(put 'scroll-other-window 'isearch-scroll t)
1537(put 'scroll-other-window-down 'isearch-scroll t)
1538(put 'beginning-of-buffer-other-window 'isearch-scroll t)
1539(put 'end-of-buffer-other-window 'isearch-scroll t)
1540
1541;; Commands which change the window layout
1542(put 'delete-other-windows 'isearch-scroll t)
1543(put 'balance-windows 'isearch-scroll t)
1544(put 'split-window-vertically 'isearch-scroll t)
1545(put 'split-window-horizontally 'isearch-scroll t)
1546(put 'enlarge-window 'isearch-scroll t)
1547
1548;; Universal argument commands
1549(put 'universal-argument 'isearch-scroll t)
1550(put 'negative-argument 'isearch-scroll t)
1551(put 'digit-argument 'isearch-scroll t)
1552
1553(defcustom isearch-allow-scroll nil
1554  "If non-nil, scrolling commands are allowed during incremental search."
1555  :type 'boolean
1556  :group 'isearch)
1557
1558(defun isearch-string-out-of-window (isearch-point)
1559  "Test whether the search string is currently outside of the window.
1560Return nil if it's completely visible, or if point is visible,
1561together with as much of the search string as will fit; the symbol
1562`above' if we need to scroll the text downwards; the symbol `below',
1563if upwards."
1564  (let ((w-start (window-start))
1565        (w-end (window-end nil t))
1566        (w-L1 (save-excursion (move-to-window-line 1) (point)))
1567        (w-L-1 (save-excursion (move-to-window-line -1) (point)))
1568        start end)                  ; start and end of search string in buffer
1569    (if isearch-forward
1570        (setq end isearch-point  start (or isearch-other-end isearch-point))
1571      (setq start isearch-point  end (or isearch-other-end isearch-point)))
1572    (cond ((or (and (>= start w-start) (<= end w-end))
1573               (if isearch-forward
1574                   (and (>= isearch-point w-L-1) (< isearch-point w-end)) ; point on Line -1
1575                 (and (>= isearch-point w-start) (< isearch-point w-L1)))) ; point on Line 0
1576           nil)
1577          ((and (< start w-start)
1578                (< isearch-point w-L-1))
1579           'above)
1580          (t 'below))))
1581
1582(defun isearch-back-into-window (above isearch-point)
1583  "Scroll the window to bring the search string back into view.
1584Restore point to ISEARCH-POINT in the process.  ABOVE is t when the
1585search string is above the top of the window, nil when it is beneath
1586the bottom."
1587  (let (start end)
1588    (if isearch-forward
1589        (setq end isearch-point  start (or isearch-other-end isearch-point))
1590      (setq start isearch-point  end (or isearch-other-end isearch-point)))
1591    (if above
1592        (progn
1593          (goto-char start)
1594          (recenter 0)
1595          (when (>= isearch-point (window-end nil t))
1596            (goto-char isearch-point)
1597            (recenter -1)))
1598      (goto-char end)
1599      (recenter -1)
1600      (when (< isearch-point (window-start))
1601        (goto-char isearch-point)
1602        (recenter 0))))
1603  (goto-char isearch-point))
1604
1605(defun isearch-reread-key-sequence-naturally (keylist)
1606  "Reread key sequence KEYLIST with Isearch mode's keymap deactivated.
1607Return the key sequence as a string/vector."
1608  (isearch-unread-key-sequence keylist)
1609  (let (overriding-terminal-local-map)
1610    (read-key-sequence nil)))  ; This will go through function-key-map, if nec.
1611
1612(defun isearch-lookup-scroll-key (key-seq)
1613  "If KEY-SEQ is bound to a scrolling command, return it as a symbol.
1614Otherwise return nil."
1615  (let* ((overriding-terminal-local-map nil)
1616         (binding (key-binding key-seq)))
1617    (and binding (symbolp binding) (commandp binding)
1618         (eq (get binding 'isearch-scroll) t)
1619         binding)))
1620
1621(defalias 'isearch-other-control-char 'isearch-other-meta-char)
1622
1623(defun isearch-other-meta-char (&optional arg)
1624  "Process a miscellaneous key sequence in Isearch mode.
1625
1626Try to convert the current key-sequence to something usable in Isearch
1627mode, either by converting it with `function-key-map', downcasing a
1628key with C-<upper case>, or finding a \"scrolling command\" bound to
1629it.  \(In the last case, we may have to read more events.)  If so,
1630either unread the converted sequence or execute the command.
1631
1632Otherwise, if `search-exit-option' is non-nil (the default) unread the
1633key-sequence and exit the search normally.  If it is the symbol
1634`edit', the search string is edited in the minibuffer and the meta
1635character is unread so that it applies to editing the string.
1636
1637ARG is the prefix argument.  It will be transmitted through to the
1638scrolling command or to the command whose key-sequence exits
1639Isearch mode."
1640  (interactive "P")
1641  (let* ((key (if current-prefix-arg    ; not nec the same as ARG
1642                  (substring (this-command-keys) universal-argument-num-events)
1643                (this-command-keys)))
1644	 (main-event (aref key 0))
1645	 (keylist (listify-key-sequence key))
1646         scroll-command isearch-point)
1647    (cond ((and (= (length key) 1)
1648		(let ((lookup (lookup-key function-key-map key)))
1649		  (not (or (null lookup) (integerp lookup)
1650			   (keymapp lookup)))))
1651	   ;; Handle a function key that translates into something else.
1652	   ;; If the key has a global definition too,
1653	   ;; exit and unread the key itself, so its global definition runs.
1654	   ;; Otherwise, unread the translation,
1655	   ;; so that the translated key takes effect within isearch.
1656	   (cancel-kbd-macro-events)
1657	   (if (lookup-key global-map key)
1658	       (progn
1659		 (isearch-done)
1660		 (apply 'isearch-unread keylist))
1661	     (setq keylist
1662		   (listify-key-sequence (lookup-key function-key-map key)))
1663	     (while keylist
1664	       (setq key (car keylist))
1665	       ;; If KEY is a printing char, we handle it here
1666	       ;; directly to avoid the input method and keyboard
1667	       ;; coding system translating it.
1668	       (if (and (integerp key)
1669			(>= key ?\s) (/= key 127) (< key 256))
1670		   (progn
1671		     (isearch-process-search-char key)
1672		     (setq keylist (cdr keylist)))
1673		 ;; As the remaining keys in KEYLIST can't be handled
1674		 ;; here, we must reread them.
1675		 (apply 'isearch-unread keylist)
1676		 (setq keylist nil)))))
1677	  (
1678	   ;; Handle an undefined shifted control character
1679	   ;; by downshifting it if that makes it defined.
1680	   ;; (As read-key-sequence would normally do,
1681	   ;; if we didn't have a default definition.)
1682	   (let ((mods (event-modifiers main-event)))
1683	     (and (integerp main-event)
1684		  (memq 'shift mods)
1685		  (memq 'control mods)
1686		  (not (memq (lookup-key isearch-mode-map
1687					 (let ((copy (copy-sequence key)))
1688					   (aset copy 0
1689						 (- main-event
1690						    (- ?\C-\S-a ?\C-a)))
1691					   copy)
1692					 nil)
1693			     '(nil
1694			       isearch-other-control-char)))))
1695	   (setcar keylist (- main-event (- ?\C-\S-a ?\C-a)))
1696	   (cancel-kbd-macro-events)
1697	   (apply 'isearch-unread keylist))
1698	  ((eq search-exit-option 'edit)
1699	   (apply 'isearch-unread keylist)
1700	   (isearch-edit-string))
1701          ;; Handle a scrolling function.
1702          ((and isearch-allow-scroll
1703                (progn (setq key (isearch-reread-key-sequence-naturally keylist))
1704                       (setq keylist (listify-key-sequence key))
1705                       (setq main-event (aref key 0))
1706                       (setq scroll-command (isearch-lookup-scroll-key key))))
1707           ;; From this point onwards, KEY, KEYLIST and MAIN-EVENT hold a
1708           ;; complete key sequence, possibly as modified by function-key-map,
1709           ;; not merely the one or two event fragment which invoked
1710           ;; isearch-other-meta-char in the first place.
1711           (setq isearch-point (point))
1712           (setq prefix-arg arg)
1713           (command-execute scroll-command)
1714           (let ((ab-bel (isearch-string-out-of-window isearch-point)))
1715             (if ab-bel
1716                 (isearch-back-into-window (eq ab-bel 'above) isearch-point)
1717               (goto-char isearch-point)))
1718           (isearch-update))
1719	  (search-exit-option
1720	   (let (window)
1721             (isearch-unread-key-sequence keylist)
1722             (setq main-event (car unread-command-events))
1723
1724	     ;; If we got a mouse click event, that event contains the
1725	     ;; window clicked on. maybe it was read with the buffer
1726	     ;; it was clicked on.  If so, that buffer, not the current one,
1727	     ;; is in isearch mode.  So end the search in that buffer.
1728
1729	     ;; ??? I have no idea what this if checks for, but it's
1730	     ;; obviously wrong for the case that a down-mouse event
1731	     ;; on another window invokes this function.  The event
1732	     ;; will contain the window clicked on and that window's
1733	     ;; buffer is certainly not always in Isearch mode.
1734	     ;;
1735	     ;; Leave the code in, but check for current buffer not
1736	     ;; being in Isearch mode for now, until someone tells
1737	     ;; what it's really supposed to do.
1738	     ;;
1739	     ;; --gerd 2001-08-10.
1740
1741	     (if (and (not isearch-mode)
1742		      (listp main-event)
1743		      (setq window (posn-window (event-start main-event)))
1744		      (windowp window)
1745		      (or (> (minibuffer-depth) 0)
1746			  (not (window-minibuffer-p window))))
1747		 (save-excursion
1748		   (set-buffer (window-buffer window))
1749		   (isearch-done)
1750		   (isearch-clean-overlays))
1751	       (isearch-done)
1752	       (isearch-clean-overlays)
1753               (setq prefix-arg arg))))
1754          (t;; otherwise nil
1755	   (isearch-process-search-string key key)))))
1756
1757(defun isearch-quote-char ()
1758  "Quote special characters for incremental search."
1759  (interactive)
1760  (let ((char (read-quoted-char (isearch-message t))))
1761    ;; Assume character codes 0200 - 0377 stand for characters in some
1762    ;; single-byte character set, and convert them to Emacs
1763    ;; characters.
1764    (if (and isearch-regexp (= char ?\s))
1765	(if (subregexp-context-p isearch-string (length isearch-string))
1766	    (isearch-process-search-string "[ ]" " ")
1767	  (isearch-process-search-char char))
1768      (and enable-multibyte-characters
1769	   (>= char ?\200)
1770	   (<= char ?\377)
1771	   (setq char (unibyte-char-to-multibyte char)))
1772      (isearch-process-search-char char))))
1773
1774(defun isearch-return-char ()
1775  "Convert return into newline for incremental search."
1776  (interactive)
1777  (isearch-process-search-char ?\n))
1778(make-obsolete 'isearch-return-char 'isearch-printing-char)
1779
1780(defun isearch-printing-char ()
1781  "Add this ordinary printing character to the search string and search."
1782  (interactive)
1783  (let ((char last-command-char))
1784    (if (= char ?\S-\ )
1785	(setq char ?\s))
1786    (if (and enable-multibyte-characters
1787	     (>= char ?\200)
1788	     (<= char ?\377))
1789	(if (keyboard-coding-system)
1790	    (isearch-process-search-multibyte-characters char)
1791	  (isearch-process-search-char (unibyte-char-to-multibyte char)))
1792      (if current-input-method
1793	  (isearch-process-search-multibyte-characters char)
1794	(isearch-process-search-char char)))))
1795
1796(defun isearch-process-search-char (char)
1797  ;; * and ? are special in regexps when not preceded by \.
1798  ;; } and | are special in regexps when preceded by \.
1799  ;; Nothing special for + because it matches at least once.
1800  (cond
1801   ((memq char '(?* ??)) (isearch-fallback nil))
1802   ((eq   char ?\})      (isearch-fallback t t))
1803   ((eq   char ?|)       (isearch-fallback t nil t)))
1804
1805  ;; Append the char to the search string, update the message and re-search.
1806  (isearch-process-search-string
1807   (char-to-string char)
1808   (if (>= char ?\200)
1809       (char-to-string char)
1810     (isearch-text-char-description char))))
1811
1812(defun isearch-process-search-string (string message)
1813  (setq isearch-string (concat isearch-string string)
1814	isearch-message (concat isearch-message message))
1815  (isearch-search-and-update))
1816
1817
1818;; Search Ring
1819
1820(defun isearch-ring-adjust1 (advance)
1821  ;; Helper for isearch-ring-adjust
1822  (let* ((ring (if isearch-regexp regexp-search-ring search-ring))
1823	 (length (length ring))
1824	 (yank-pointer-name (if isearch-regexp
1825				'regexp-search-ring-yank-pointer
1826			      'search-ring-yank-pointer))
1827	 (yank-pointer (eval yank-pointer-name)))
1828    (if (zerop length)
1829	()
1830      (set yank-pointer-name
1831	   (setq yank-pointer
1832		 (mod (+ (or yank-pointer 0)
1833			 (if advance -1 1))
1834		      length)))
1835      (setq isearch-string (nth yank-pointer ring)
1836	    isearch-message (mapconcat 'isearch-text-char-description
1837				       isearch-string "")))))
1838
1839(defun isearch-ring-adjust (advance)
1840  ;; Helper for isearch-ring-advance and isearch-ring-retreat
1841  (isearch-ring-adjust1 advance)
1842  (if search-ring-update
1843      (progn
1844	(isearch-search)
1845	(isearch-update))
1846    (isearch-edit-string)
1847    )
1848  (isearch-push-state))
1849
1850(defun isearch-ring-advance ()
1851  "Advance to the next search string in the ring."
1852  ;; This could be more general to handle a prefix arg, but who would use it.
1853  (interactive)
1854  (isearch-ring-adjust 'advance))
1855
1856(defun isearch-ring-retreat ()
1857  "Retreat to the previous search string in the ring."
1858  (interactive)
1859  (isearch-ring-adjust nil))
1860
1861(defun isearch-complete1 ()
1862  ;; Helper for isearch-complete and isearch-complete-edit
1863  ;; Return t if completion OK, nil if no completion exists.
1864  (let* ((ring (if isearch-regexp regexp-search-ring search-ring))
1865         (completion-ignore-case case-fold-search)
1866         (completion (try-completion isearch-string ring)))
1867    (cond
1868     ((eq completion t)
1869      ;; isearch-string stays the same
1870      t)
1871     ((or completion ; not nil, must be a string
1872	  (= 0 (length isearch-string))) ; shouldn't have to say this
1873      (if (equal completion isearch-string)  ;; no extension?
1874	  (progn
1875	    (if completion-auto-help
1876		(with-output-to-temp-buffer "*Isearch completions*"
1877		  (display-completion-list
1878		   (all-completions isearch-string ring))))
1879	    t)
1880	(and completion
1881	     (setq isearch-string completion))))
1882     (t
1883      (message "No completion") ; waits a second if in minibuffer
1884      nil))))
1885
1886(defun isearch-complete ()
1887  "Complete the search string from the strings on the search ring.
1888The completed string is then editable in the minibuffer.
1889If there is no completion possible, say so and continue searching."
1890  (interactive)
1891  (if (isearch-complete1)
1892      (progn (setq isearch-message
1893		   (mapconcat 'isearch-text-char-description
1894			      isearch-string ""))
1895	     (isearch-edit-string))
1896    ;; else
1897    (sit-for 1)
1898    (isearch-update)))
1899
1900(defun isearch-complete-edit ()
1901  "Same as `isearch-complete' except in the minibuffer."
1902  (interactive)
1903  (setq isearch-string (field-string))
1904  (if (isearch-complete1)
1905      (progn
1906	(delete-field)
1907	(insert isearch-string))))
1908
1909
1910;; Message string
1911
1912(defun isearch-message (&optional c-q-hack ellipsis)
1913  ;; Generate and print the message string.
1914  (let ((cursor-in-echo-area ellipsis)
1915	(m (concat
1916	    (isearch-message-prefix c-q-hack ellipsis isearch-nonincremental)
1917	    (if (and (not isearch-success)
1918                     (string-match " +$" isearch-message))
1919                (concat
1920                 (substring isearch-message 0 (match-beginning 0))
1921                 (propertize (substring isearch-message (match-beginning 0))
1922                             'face 'trailing-whitespace))
1923              isearch-message)
1924	    (isearch-message-suffix c-q-hack ellipsis)
1925	    )))
1926    (if c-q-hack
1927	m
1928      (let ((message-log-max nil))
1929	(message "%s" m)))))
1930
1931(defun isearch-message-prefix (&optional c-q-hack ellipsis nonincremental)
1932  ;; If about to search, and previous search regexp was invalid,
1933  ;; check that it still is.  If it is valid now,
1934  ;; let the message we display while searching say that it is valid.
1935  (and isearch-error ellipsis
1936       (condition-case ()
1937	   (progn (re-search-forward isearch-string (point) t)
1938		  (setq isearch-error nil))
1939	 (error nil)))
1940  ;; If currently failing, display no ellipsis.
1941  (or isearch-success (setq ellipsis nil))
1942  (let ((m (concat (if isearch-success "" "failing ")
1943		   (if isearch-adjusted "pending " "")
1944		   (if (and isearch-wrapped
1945			    (not isearch-wrap-function)
1946			    (if isearch-forward
1947				(> (point) isearch-opoint)
1948			      (< (point) isearch-opoint)))
1949		       "over")
1950		   (if isearch-wrapped "wrapped ")
1951		   (if isearch-word "word " "")
1952		   (if isearch-regexp "regexp " "")
1953		   (if nonincremental "search" "I-search")
1954		   (if isearch-forward "" " backward")
1955		   (if current-input-method
1956		       (concat " [" current-input-method-title "]: ")
1957		     ": ")
1958		   )))
1959    (propertize (concat (upcase (substring m 0 1)) (substring m 1))
1960		'face 'minibuffer-prompt)))
1961
1962(defun isearch-message-suffix (&optional c-q-hack ellipsis)
1963  (concat (if c-q-hack "^Q" "")
1964	  (if isearch-error
1965	      (concat " [" isearch-error "]")
1966	    "")))
1967
1968
1969;; Searching
1970
1971(defvar isearch-search-fun-function nil
1972  "Override `isearch-search-fun'.
1973This function should return the search function for isearch to use.
1974It will call this function with three arguments
1975as if it were `search-forward'.")
1976
1977(defun isearch-search-fun ()
1978  "Return the function to use for the search.
1979Can be changed via `isearch-search-fun-function' for special needs."
1980  (if isearch-search-fun-function
1981      (funcall isearch-search-fun-function)
1982    (cond
1983     (isearch-word
1984      (if isearch-forward 'word-search-forward 'word-search-backward))
1985     (isearch-regexp
1986      (if isearch-forward 're-search-forward 're-search-backward))
1987     (t
1988      (if isearch-forward 'search-forward 'search-backward)))))
1989
1990(defun isearch-search-string (string bound noerror)
1991  ;; Search for the first occurance of STRING or its translation.  If
1992  ;; found, move point to the end of the occurance, update
1993  ;; isearch-match-beg and isearch-match-end, and return point.
1994  (let ((func (isearch-search-fun))
1995	(len (length string))
1996	pos1 pos2)
1997    (setq pos1 (save-excursion (funcall func string bound noerror)))
1998    (if (and (char-table-p translation-table-for-input)
1999	     (> (string-bytes string) len))
2000	(let (translated match-data)
2001	  (dotimes (i len)
2002	    (let ((x (aref translation-table-for-input (aref string i))))
2003	      (when x
2004		(or translated (setq translated (copy-sequence string)))
2005		(aset translated i x))))
2006	  (when translated
2007	    (save-match-data
2008	      (save-excursion
2009		(if (setq pos2 (funcall func translated bound noerror))
2010		    (setq match-data (match-data t)))))
2011	    (when (and pos2
2012		       (or (not pos1)
2013			   (if isearch-forward (< pos2 pos1) (> pos2 pos1))))
2014	      (setq pos1 pos2)
2015	      (set-match-data match-data)))))
2016    (if pos1
2017	(goto-char pos1))
2018    pos1))
2019
2020(defun isearch-search ()
2021  ;; Do the search with the current search string.
2022  (isearch-message nil t)
2023  (if (and (eq isearch-case-fold-search t) search-upper-case)
2024      (setq isearch-case-fold-search
2025	    (isearch-no-upper-case-p isearch-string isearch-regexp)))
2026  (condition-case lossage
2027      (let ((inhibit-point-motion-hooks search-invisible)
2028	    (inhibit-quit nil)
2029	    (case-fold-search isearch-case-fold-search)
2030	    (search-spaces-regexp search-whitespace-regexp)
2031	    (retry t))
2032	(setq isearch-error nil)
2033	(while retry
2034	  (setq isearch-success
2035		(isearch-search-string isearch-string nil t))
2036	  ;; Clear RETRY unless we matched some invisible text
2037	  ;; and we aren't supposed to do that.
2038	  (if (or (eq search-invisible t)
2039		  (not isearch-success)
2040		  (bobp) (eobp)
2041		  (= (match-beginning 0) (match-end 0))
2042		  (not (isearch-range-invisible
2043			(match-beginning 0) (match-end 0))))
2044	      (setq retry nil)))
2045	(setq isearch-just-started nil)
2046	(if isearch-success
2047	    (setq isearch-other-end
2048		  (if isearch-forward (match-beginning 0) (match-end 0)))))
2049
2050    (quit (isearch-unread ?\C-g)
2051	  (setq isearch-success nil))
2052
2053    (invalid-regexp
2054     (setq isearch-error (car (cdr lossage)))
2055     (if (string-match
2056	  "\\`Premature \\|\\`Unmatched \\|\\`Invalid "
2057	  isearch-error)
2058	 (setq isearch-error "incomplete input")))
2059
2060    (search-failed
2061     (setq isearch-success nil)
2062     (setq isearch-error (nth 2 lossage)))
2063
2064    (error
2065     ;; stack overflow in regexp search.
2066     (setq isearch-error (format "%s" lossage))))
2067
2068  (if isearch-success
2069      nil
2070    ;; Ding if failed this time after succeeding last time.
2071    (and (isearch-success-state (car isearch-cmds))
2072	 (ding))
2073    (if (functionp (isearch-pop-fun-state (car isearch-cmds)))
2074        (funcall (isearch-pop-fun-state (car isearch-cmds)) (car isearch-cmds)))
2075    (goto-char (isearch-point-state (car isearch-cmds)))))
2076
2077
2078;; Called when opening an overlay, and we are still in isearch.
2079(defun isearch-open-overlay-temporary (ov)
2080  (if (not (null (overlay-get ov 'isearch-open-invisible-temporary)))
2081      ;; Some modes would want to open the overlays temporary during
2082      ;; isearch in their own way, they should set the
2083      ;; `isearch-open-invisible-temporary' to a function doing this.
2084      (funcall  (overlay-get ov 'isearch-open-invisible-temporary)  ov nil)
2085    ;; Store the values for the `invisible' and `intangible'
2086    ;; properties, and then set them to nil. This way the text hidden
2087    ;; by this overlay becomes visible.
2088
2089    ;; Do we really need to set the `intangible' property to t? Can we
2090    ;; have the point inside an overlay with an `intangible' property?
2091    ;; In 19.34 this does not exist so I cannot test it.
2092    (overlay-put ov 'isearch-invisible (overlay-get ov 'invisible))
2093    (overlay-put ov 'isearch-intangible (overlay-get ov 'intangible))
2094    (overlay-put ov 'invisible nil)
2095    (overlay-put ov 'intangible nil)))
2096
2097
2098;; This is called at the end of isearch.  It will open the overlays
2099;; that contain the latest match.  Obviously in case of a C-g the
2100;; point returns to the original location which surely is not contain
2101;; in any of these overlays, se we are safe in this case too.
2102(defun isearch-open-necessary-overlays (ov)
2103  (let ((inside-overlay (and  (> (point) (overlay-start ov))
2104			      (< (point) (overlay-end ov))))
2105	;; If this exists it means that the overlay was opened using
2106	;; this function, not by us tweaking the overlay properties.
2107	(fct-temp (overlay-get ov 'isearch-open-invisible-temporary)))
2108    (when (or inside-overlay (not fct-temp))
2109      ;; restore the values for the `invisible' and `intangible'
2110      ;; properties
2111      (overlay-put ov 'invisible (overlay-get ov 'isearch-invisible))
2112      (overlay-put ov 'intangible (overlay-get ov 'isearch-intangible))
2113      (overlay-put ov 'isearch-invisible nil)
2114      (overlay-put ov 'isearch-intangible nil))
2115    (if inside-overlay
2116	(funcall (overlay-get ov 'isearch-open-invisible)  ov)
2117      (if fct-temp
2118	  (funcall fct-temp ov t)))))
2119
2120;; This is called when exiting isearch. It closes the temporary
2121;; opened overlays, except the ones that contain the latest match.
2122(defun isearch-clean-overlays ()
2123  (when isearch-opened-overlays
2124    (mapc 'isearch-open-necessary-overlays isearch-opened-overlays)
2125    (setq isearch-opened-overlays nil)))
2126
2127
2128(defun isearch-intersects-p (start0 end0 start1 end1)
2129  "Return t if regions START0..END0 and START1..END1 intersect."
2130  (or (and (>= start0 start1) (<  start0 end1))
2131      (and (>  end0 start1)   (<= end0 end1))
2132      (and (>= start1 start0) (<  start1 end0))
2133      (and (>  end1 start0)   (<= end1 end0))))
2134
2135
2136;; Verify if the current match is outside of each element of
2137;; `isearch-opened-overlays', if so close that overlay.
2138
2139(defun isearch-close-unnecessary-overlays (begin end)
2140  (let ((overlays isearch-opened-overlays))
2141    (setq isearch-opened-overlays nil)
2142    (dolist (ov overlays)
2143      (if (isearch-intersects-p begin end (overlay-start ov) (overlay-end ov))
2144	  (push ov isearch-opened-overlays)
2145	(let ((fct-temp (overlay-get ov 'isearch-open-invisible-temporary)))
2146	  (if fct-temp
2147	      ;; If this exists it means that the overlay was opened
2148	      ;; using this function, not by us tweaking the overlay
2149	      ;; properties.
2150	      (funcall fct-temp ov t)
2151	    (overlay-put ov 'invisible (overlay-get ov 'isearch-invisible))
2152	    (overlay-put ov 'intangible (overlay-get ov 'isearch-intangible))
2153	    (overlay-put ov 'isearch-invisible nil)
2154	    (overlay-put ov 'isearch-intangible nil)))))))
2155
2156
2157(defun isearch-range-invisible (beg end)
2158  "Return t if all the text from BEG to END is invisible."
2159  (when (/= beg end)
2160    ;; Check that invisibility runs up to END.
2161    (save-excursion
2162      (goto-char beg)
2163      (let (;; can-be-opened keeps track if we can open some overlays.
2164	    (can-be-opened (eq search-invisible 'open))
2165	    ;; the list of overlays that could be opened
2166	    (crt-overlays nil))
2167	(when (and can-be-opened isearch-hide-immediately)
2168	  (isearch-close-unnecessary-overlays beg end))
2169	;; If the following character is currently invisible,
2170	;; skip all characters with that same `invisible' property value.
2171	;; Do that over and over.
2172	(while (and (< (point) end)
2173		    (let ((prop
2174			   (get-char-property (point) 'invisible)))
2175		      (if (eq buffer-invisibility-spec t)
2176			  prop
2177			(or (memq prop buffer-invisibility-spec)
2178			    (assq prop buffer-invisibility-spec)))))
2179	  (if (get-text-property (point) 'invisible)
2180	      (progn
2181		(goto-char (next-single-property-change (point) 'invisible
2182							nil end))
2183		;; if text is hidden by an `invisible' text property
2184		;; we cannot open it at all.
2185		(setq can-be-opened nil))
2186	    (when can-be-opened
2187	      (let ((overlays (overlays-at (point)))
2188		    ov-list
2189		    o
2190		    invis-prop)
2191		(while overlays
2192		  (setq o (car overlays)
2193			invis-prop (overlay-get o 'invisible))
2194		  (if (if (eq buffer-invisibility-spec t)
2195			  invis-prop
2196			(or (memq invis-prop buffer-invisibility-spec)
2197			    (assq invis-prop buffer-invisibility-spec)))
2198		      (if (overlay-get o 'isearch-open-invisible)
2199			  (setq ov-list (cons o ov-list))
2200			;; We found one overlay that cannot be
2201			;; opened, that means the whole chunk
2202			;; cannot be opened.
2203			(setq can-be-opened nil)))
2204		  (setq overlays (cdr overlays)))
2205		(if can-be-opened
2206		    ;; It makes sense to append to the open
2207		    ;; overlays list only if we know that this is
2208		    ;; t.
2209		    (setq crt-overlays (append ov-list crt-overlays)))))
2210	    (goto-char (next-overlay-change (point)))))
2211	;; See if invisibility reaches up thru END.
2212	(if (>= (point) end)
2213	    (if (and can-be-opened (consp crt-overlays))
2214		(progn
2215		  (setq isearch-opened-overlays
2216			(append isearch-opened-overlays crt-overlays))
2217		  (mapc 'isearch-open-overlay-temporary crt-overlays)
2218		  nil)
2219	      (setq isearch-hidden t)))))))
2220
2221
2222;; General utilities
2223
2224(defun isearch-no-upper-case-p (string regexp-flag)
2225  "Return t if there are no upper case chars in STRING.
2226If REGEXP-FLAG is non-nil, disregard letters preceded by `\\' (but not `\\\\')
2227since they have special meaning in a regexp."
2228  (let (quote-flag (i 0) (len (length string)) found)
2229    (while (and (not found) (< i len))
2230      (let ((char (aref string i)))
2231	(if (and regexp-flag (eq char ?\\))
2232	    (setq quote-flag (not quote-flag))
2233	  (if (and (not quote-flag) (not (eq char (downcase char))))
2234	      (setq found t))
2235	  (setq quote-flag nil)))
2236      (setq i (1+ i)))
2237    (not (or found
2238             ;; Even if there's no uppercase char, we want to detect the use
2239             ;; of [:upper:] or [:lower:] char-class, which indicates
2240             ;; clearly that the user cares about case distinction.
2241             (and regexp-flag (string-match "\\[:\\(upp\\|low\\)er:]" string)
2242                  (condition-case err
2243                      (progn
2244                        (string-match (substring string 0 (match-beginning 0))
2245                                      "")
2246                        nil)
2247                    (invalid-regexp
2248                     (equal "Unmatched [ or [^" (cadr err)))))))))
2249
2250;; Portability functions to support various Emacs versions.
2251
2252(defun isearch-text-char-description (c)
2253  (cond
2254   ((< c ?\s) (format "^%c" (+ c 64)))
2255   ((= c ?\^?) "^?")
2256   (t (char-to-string c))))
2257
2258;; General function to unread characters or events.
2259;; Also insert them in a keyboard macro being defined.
2260(defun isearch-unread (&rest char-or-events)
2261  (mapc 'store-kbd-macro-event char-or-events)
2262  (setq unread-command-events
2263	(append char-or-events unread-command-events)))
2264
2265
2266;; Highlighting
2267
2268(defvar isearch-overlay nil)
2269
2270(defun isearch-highlight (beg end)
2271  (if search-highlight
2272      (if isearch-overlay
2273	  ;; Overlay already exists, just move it.
2274	  (move-overlay isearch-overlay beg end (current-buffer))
2275	;; Overlay doesn't exist, create it.
2276	(setq isearch-overlay (make-overlay beg end))
2277	;; 1001 is higher than lazy's 1000 and ediff's 100+
2278	(overlay-put isearch-overlay 'priority 1001)
2279	(overlay-put isearch-overlay 'face isearch))))
2280
2281(defun isearch-dehighlight ()
2282  (when isearch-overlay
2283    (delete-overlay isearch-overlay)))
2284
2285;; isearch-lazy-highlight feature
2286;; by Bob Glickstein <http://www.zanshin.com/~bobg/>
2287
2288;; When active, *every* match for the current search string is
2289;; highlighted: the current one using the normal isearch match color
2290;; and all the others using `isearch-lazy-highlight'.  The extra
2291;; highlighting makes it easier to anticipate where the cursor will
2292;; land each time you press C-s or C-r to repeat a pending search.
2293;; Highlighting of these additional matches happens in a deferred
2294;; fashion using "idle timers," so the cycles needed do not rob
2295;; isearch of its usual snappy response.
2296
2297;; IMPLEMENTATION NOTE: This depends on some isearch internals.
2298;; Specifically:
2299;;  - `isearch-update' is expected to be called (at least) every time
2300;;    the search string or window-start changes;
2301;;  - `isearch-string' is expected to contain the current search
2302;;    string as entered by the user;
2303;;  - the type of the current search is expected to be given by
2304;;    `isearch-word' and `isearch-regexp';
2305;;  - the direction of the current search is expected to be given by
2306;;    `isearch-forward';
2307;;  - the variable `isearch-error' is expected to be true
2308;;    iff `isearch-string' is an invalid regexp.
2309
2310(defvar isearch-lazy-highlight-overlays nil)
2311(defvar isearch-lazy-highlight-wrapped nil)
2312(defvar isearch-lazy-highlight-start-limit nil)
2313(defvar isearch-lazy-highlight-end-limit nil)
2314(defvar isearch-lazy-highlight-start nil)
2315(defvar isearch-lazy-highlight-end nil)
2316(defvar isearch-lazy-highlight-timer nil)
2317(defvar isearch-lazy-highlight-last-string nil)
2318(defvar isearch-lazy-highlight-window nil)
2319(defvar isearch-lazy-highlight-window-start nil)
2320(defvar isearch-lazy-highlight-window-end nil)
2321(defvar isearch-lazy-highlight-case-fold-search nil)
2322(defvar isearch-lazy-highlight-regexp nil)
2323(defvar isearch-lazy-highlight-space-regexp nil)
2324
2325(defun lazy-highlight-cleanup (&optional force)
2326  "Stop lazy highlighting and remove extra highlighting from current buffer.
2327FORCE non-nil means do it whether or not `lazy-highlight-cleanup'
2328is nil.  This function is called when exiting an incremental search if
2329`lazy-highlight-cleanup' is non-nil."
2330  (interactive '(t))
2331  (if (or force lazy-highlight-cleanup)
2332      (while isearch-lazy-highlight-overlays
2333        (delete-overlay (car isearch-lazy-highlight-overlays))
2334        (setq isearch-lazy-highlight-overlays
2335              (cdr isearch-lazy-highlight-overlays))))
2336  (when isearch-lazy-highlight-timer
2337    (cancel-timer isearch-lazy-highlight-timer)
2338    (setq isearch-lazy-highlight-timer nil)))
2339
2340(define-obsolete-function-alias 'isearch-lazy-highlight-cleanup
2341                                'lazy-highlight-cleanup
2342                                "22.1")
2343
2344(defun isearch-lazy-highlight-new-loop (&optional beg end)
2345  "Cleanup any previous `lazy-highlight' loop and begin a new one.
2346BEG and END specify the bounds within which highlighting should occur.
2347This is called when `isearch-update' is invoked (which can cause the
2348search string to change or the window to scroll).  It is also used
2349by other Emacs features."
2350  (when (and (null executing-kbd-macro)
2351             (sit-for 0)         ;make sure (window-start) is credible
2352             (or (not (equal isearch-string
2353                             isearch-lazy-highlight-last-string))
2354                 (not (eq (selected-window)
2355                          isearch-lazy-highlight-window))
2356		 (not (eq isearch-lazy-highlight-case-fold-search
2357			  isearch-case-fold-search))
2358		 (not (eq isearch-lazy-highlight-regexp
2359			  isearch-regexp))
2360                 (not (= (window-start)
2361                         isearch-lazy-highlight-window-start))
2362                 (not (= (window-end)   ; Window may have been split/joined.
2363                         isearch-lazy-highlight-window-end))))
2364    ;; something important did indeed change
2365    (lazy-highlight-cleanup t) ;kill old loop & remove overlays
2366    (when (not isearch-error)
2367      (setq isearch-lazy-highlight-start-limit beg
2368	    isearch-lazy-highlight-end-limit end)
2369      (setq isearch-lazy-highlight-window       (selected-window)
2370            isearch-lazy-highlight-window-start (window-start)
2371            isearch-lazy-highlight-window-end   (window-end)
2372            isearch-lazy-highlight-start        (point)
2373            isearch-lazy-highlight-end          (point)
2374            isearch-lazy-highlight-last-string  isearch-string
2375	    isearch-lazy-highlight-case-fold-search isearch-case-fold-search
2376	    isearch-lazy-highlight-regexp	isearch-regexp
2377            isearch-lazy-highlight-wrapped      nil
2378	    isearch-lazy-highlight-space-regexp search-whitespace-regexp)
2379      (unless (equal isearch-string "")
2380	(setq isearch-lazy-highlight-timer
2381	      (run-with-idle-timer lazy-highlight-initial-delay nil
2382				   'isearch-lazy-highlight-update))))))
2383
2384(defun isearch-lazy-highlight-search ()
2385  "Search ahead for the next or previous match, for lazy highlighting.
2386Attempt to do the search exactly the way the pending isearch would."
2387  (let ((case-fold-search isearch-lazy-highlight-case-fold-search)
2388	(isearch-regexp isearch-lazy-highlight-regexp)
2389	(search-spaces-regexp isearch-lazy-highlight-space-regexp))
2390    (condition-case nil
2391	(isearch-search-string
2392		 isearch-lazy-highlight-last-string
2393		 (if isearch-forward
2394		     (min (or isearch-lazy-highlight-end-limit (point-max))
2395			  (if isearch-lazy-highlight-wrapped
2396			      isearch-lazy-highlight-start
2397			    (window-end)))
2398		   (max (or isearch-lazy-highlight-start-limit (point-min))
2399			(if isearch-lazy-highlight-wrapped
2400			    isearch-lazy-highlight-end
2401			  (window-start))))
2402		 t)
2403      (error nil))))
2404
2405(defun isearch-lazy-highlight-update ()
2406  "Update highlighting of other matches for current search."
2407  (let ((max lazy-highlight-max-at-a-time)
2408        (looping t)
2409        nomore)
2410    (with-local-quit
2411      (save-selected-window
2412	(if (and (window-live-p isearch-lazy-highlight-window)
2413		 (not (eq (selected-window) isearch-lazy-highlight-window)))
2414	    (select-window isearch-lazy-highlight-window))
2415	(save-excursion
2416	  (save-match-data
2417	    (goto-char (if isearch-forward
2418			   isearch-lazy-highlight-end
2419			 isearch-lazy-highlight-start))
2420	    (while looping
2421	      (let ((found (isearch-lazy-highlight-search)))
2422		(when max
2423		  (setq max (1- max))
2424		  (if (<= max 0)
2425		      (setq looping nil)))
2426		(if found
2427		    (let ((mb (match-beginning 0))
2428			  (me (match-end 0)))
2429		      (if (= mb me)	;zero-length match
2430			  (if isearch-forward
2431			      (if (= mb (if isearch-lazy-highlight-wrapped
2432					    isearch-lazy-highlight-start
2433					  (window-end)))
2434				  (setq found nil)
2435				(forward-char 1))
2436			    (if (= mb (if isearch-lazy-highlight-wrapped
2437					  isearch-lazy-highlight-end
2438					(window-start)))
2439				(setq found nil)
2440			      (forward-char -1)))
2441
2442			;; non-zero-length match
2443			(let ((ov (make-overlay mb me)))
2444			  (push ov isearch-lazy-highlight-overlays)
2445			  ;; 1000 is higher than ediff's 100+,
2446			  ;; but lower than isearch main overlay's 1001
2447			  (overlay-put ov 'priority 1000)
2448			  (overlay-put ov 'face lazy-highlight-face)
2449			  (overlay-put ov 'window (selected-window))))
2450		      (if isearch-forward
2451			  (setq isearch-lazy-highlight-end (point))
2452			(setq isearch-lazy-highlight-start (point)))))
2453
2454		;; not found or zero-length match at the search bound
2455		(if (not found)
2456		    (if isearch-lazy-highlight-wrapped
2457			(setq looping nil
2458			      nomore  t)
2459		      (setq isearch-lazy-highlight-wrapped t)
2460		      (if isearch-forward
2461			  (progn
2462			    (setq isearch-lazy-highlight-end (window-start))
2463			    (goto-char (max (or isearch-lazy-highlight-start-limit (point-min))
2464					    (window-start))))
2465			(setq isearch-lazy-highlight-start (window-end))
2466			(goto-char (min (or isearch-lazy-highlight-end-limit (point-max))
2467					(window-end))))))))
2468	    (unless nomore
2469	      (setq isearch-lazy-highlight-timer
2470		    (run-at-time lazy-highlight-interval nil
2471				 'isearch-lazy-highlight-update)))))))))
2472
2473(defun isearch-resume (search regexp word forward message case-fold)
2474  "Resume an incremental search.
2475SEARCH is the string or regexp searched for.
2476REGEXP non-nil means the resumed search was a regexp search.
2477WORD non-nil means resume a word search.
2478FORWARD non-nil means resume a forward search.
2479MESSAGE is the echo-area message recorded for the search resumed.
2480CASE-FOLD non-nil means the search was case-insensitive."
2481  (isearch-mode forward regexp nil nil word)
2482  (setq isearch-string search
2483	isearch-message message
2484	isearch-case-fold-search case-fold)
2485  (isearch-search))
2486
2487;; arch-tag: 74850515-f7d8-43a6-8a2c-ca90a4c1e675
2488;;; isearch.el ends here
2489