This commit was generated by cvs2svn to compensate for changes in r1705,
[chise/xemacs-chise.git.1] / lisp / isearch-mode.el
1 ;;; isearch-mode.el --- Incremental search minor mode.
2
3 ;; Copyright (C) 1992,93,94,95,96,97,98,1999 Free Software Foundation, Inc.
4
5 ;; Author: Daniel LaLiberte <liberte@cs.uiuc.edu>
6 ;; Maintainer: XEmacs Development Team
7 ;; Keywords: extensions, dumped
8
9 ;; This file is part of XEmacs.
10
11 ;; XEmacs is free software; you can redistribute it and/or modify it
12 ;; under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; XEmacs is distributed in the hope that it will be useful, but
17 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19 ;; General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with XEmacs; see the file COPYING.  If not, write to the
23 ;; Free Software Foundation, 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
25
26 ;;; Synched up with: FSF 20.4.
27
28 ;;; Commentary:
29
30 ;; Instructions
31
32 ;; Searching with isearch-mode.el should work just like isearch.el
33 ;; [the one from Emacs 18], except it is done in a temporary minor
34 ;; mode that terminates when you finish searching.
35
36 ;; For programmed use of isearch-mode, e.g. calling (isearch-forward),
37 ;; isearch-mode behaves modally and does not return until the search
38 ;; is completed.  It uses a recursive-edit to behave this way.  In
39 ;; that case, you should still be able switch buffers, so be careful
40 ;; not to get things confused.
41
42 ;; The key bindings active within isearch-mode are defined below in
43 ;; `isearch-mode-map' which is given bindings close to the default
44 ;; characters of the original isearch.el.  With `isearch-mode',
45 ;; however, you can bind multi-character keys and it should be easier
46 ;; to add new commands.  One bug though: keys with meta-prefix cannot
47 ;; be longer than two chars.  Also see minibuffer-local-isearch-map
48 ;; for bindings active during `isearch-edit-string'.
49
50 ;; The search ring and completion commands automatically put you in
51 ;; the minibuffer to edit the string.  This gives you a chance to
52 ;; modify the search string before executing the search.  There are
53 ;; three commands to terminate the editing: C-s and C-r exit the
54 ;; minibuffer and search forward and reverse respectively, while C-m
55 ;; exits and does a nonincremental search.
56
57 ;; Exiting immediately from isearch uses isearch-edit-string instead
58 ;; of nonincremental-search, if search-nonincremental-instead is non-nil.
59 ;; The name of this option should probably be changed if we decide to
60 ;; keep the behavior.  No point in forcing nonincremental search until
61 ;; the last possible moment.
62
63 ;; TODO
64 ;; - Integrate generalized command history to isearch-edit-string.
65 ;; - Think about incorporating query-replace.
66 ;; - Hooks and options for failed search.
67
68 ;;; Change Log:
69
70 ;; Changes before those recorded in ChangeLog:
71
72 ;; 20-aug-92  Hacked by jwz for Lucid Emacs 19.3.
73 ;;
74 ;; Revision 1.3  92/06/29  13:10:08  liberte
75 ;; Moved modal isearch-mode handling into isearch-mode.
76 ;; Got rid of buffer-local isearch variables.
77 ;; isearch-edit-string used by ring adjustments, completion, and
78 ;; nonincremental searching.  C-s and C-r are additional exit commands.
79 ;; Renamed all regex to regexp.
80 ;; Got rid of found-start and found-point globals.
81 ;; Generalized handling of upper-case chars.
82
83 ;; Revision 1.2  92/05/27  11:33:57  liberte
84 ;; Emacs version 19 has a search ring, which is supported here.
85 ;; Other fixes found in the version 19 isearch are included here.
86 ;;
87 ;; Also see variables search-caps-disable-folding,
88 ;; search-nonincremental-instead, search-whitespace-regexp, and
89 ;; commands isearch-toggle-regexp, isearch-edit-string.
90 ;;
91 ;; semi-modal isearching is supported.
92
93 ;; Changes for 1.1
94 ;; 3/18/92 Fixed invalid-regexp.
95 ;; 3/18/92 Fixed yanking in regexps.
96
97 ;;; Code:
98
99 \f
100 ;;;=========================================================================
101 ;;; User-accessible variables
102
103 (defgroup isearch nil
104   "Incremental search minor mode."
105   :prefix "search-"
106   :group 'matching)
107
108
109 (defcustom search-exit-option t
110   "*Non-nil means random control characters terminate incremental search."
111   :type 'boolean
112   :group 'isearch)
113
114 (defcustom search-slow-window-lines 1
115   "*Number of lines in slow search display windows.
116 These are the short windows used during incremental search on slow terminals.
117 Negative means put the slow search window at the top (normally it's at bottom)
118 and the value is minus the number of lines."
119   :type 'integer
120   :group 'isearch)
121
122 (defcustom search-slow-speed 1200
123   "*Highest terminal speed at which to use \"slow\" style incremental search.
124 This is the style where a one-line window is created to show the line
125 that the search has reached."
126   :type 'integer
127   :group 'isearch)
128
129 ;; We have `search-caps-disable-folding'.
130 ;(defcustom search-upper-case 'not-yanks
131 ;  "*If non-nil, upper case chars disable case fold searching.
132 ;That is, upper and lower case chars must match exactly.
133 ;This applies no matter where the chars come from, but does not
134 ;apply to chars in regexps that are prefixed with `\\'.
135 ;If this value is `not-yanks', yanked text is always downcased."
136 ;  :type '(choice (const :tag "off" nil)
137 ;                (const not-yanks)
138 ;                (other :tag "on" t))
139 ;  :group 'isearch)
140
141 (defcustom search-nonincremental-instead t
142   "*If non-nil, do a nonincremental search instead if exiting immediately.
143 Actually, `isearch-edit-string' is called to let you enter the search
144 string, and RET terminates editing and does a nonincremental search."
145   :type 'boolean
146   :group 'isearch)
147
148 ;; FSF default is "\\s-+", but I think our default is better so I'm
149 ;; leaving it.
150 (defcustom search-whitespace-regexp "\\(\\s-\\|[\n\r]\\)+"
151   "*If non-nil, regular expression to match a sequence of whitespace chars."
152   :type 'regexp
153   :group 'isearch)
154
155 (defcustom search-highlight t
156   "*Whether incremental search and query-replace should highlight
157 the text that currently matches the search string."
158   :type 'boolean
159   :group 'isearch)
160
161 ;; I think the name `search-highlight' makes more sense, both because
162 ;; of consistency with other search-* variables above, and because it
163 ;; also applies to query-replace.
164 (define-obsolete-variable-alias 'isearch-highlight 'search-highlight)
165
166 (defcustom search-invisible 'open
167   "If t incremental search can match hidden text.
168 nil means don't match invisible text.
169 If the value is `open', if the text matched is made invisible by
170 an overlay having an `invisible' property and that overlay has a property
171 `isearch-open-invisible', then incremental search will show the contents.
172 \(This applies when using `outline.el' and `hideshow.el'.)"
173   :type '(choice (const :tag "Match hidden text" t)
174                  (const :tag "Open overlays" open)
175                  (const :tag "Don't match hidden text" nil))
176   :group 'isearch)
177
178 (defcustom isearch-hide-immediately t
179   "If non-nil, re-hide an invisible match right away.
180 This variable makes a difference when `search-invisible' is set to `open'.
181 It means that after search makes some invisible text visible
182 to show the match, it makes the text invisible again when the match moves.
183 Ordinarily the text becomes invisible again at the end of the search."  
184   :type 'boolean 
185   :group 'isearch)
186
187 (defvar isearch-mode-hook nil
188   "Function(s) to call after starting up an incremental search.")
189
190 (defvar isearch-mode-end-hook nil
191   "Function(s) to call after terminating an incremental search.")
192
193 ;;;==================================================================
194 ;;; Search ring.
195
196 (defvar search-ring nil
197   "List of search string sequences.")
198 (defvar regexp-search-ring nil
199   "List of regular expression search string sequences.")
200
201 (defcustom search-ring-max 16
202   "*Maximum length of search ring before oldest elements are thrown away."
203   :type 'integer
204   :group 'isearch)
205 (defcustom regexp-search-ring-max 16
206   "*Maximum length of regexp search ring before oldest elements are thrown away."
207   :type 'integer
208   :group 'isearch)
209
210 ;; The important difference between pre-20.4-merge yank-pointers and
211 ;; current code is that the yank pointers positions used to be
212 ;; preserved across the isearch sessions.  I changed this because I
213 ;; think the FSF code is closer to how the feature is supposed to
214 ;; behave (read: to minibuffer histories.)
215 (defvar search-ring-yank-pointer nil
216   "Index in `search-ring' of last string reused.
217 nil if none yet.")
218 (defvar regexp-search-ring-yank-pointer nil
219   "Index in `regexp-search-ring' of last string reused.
220 nil if none yet.")
221
222 (defcustom search-ring-update nil
223   "*Non-nil if advancing or retreating in the search ring should cause search.
224 Default nil means edit the string from the search ring first."
225   :type 'boolean
226   :group 'isearch)
227
228 ;;;====================================================
229 ;;; Define isearch-mode keymap.
230
231 (defvar isearch-mode-map
232   (let ((map (make-keymap)))
233     (set-keymap-name map 'isearch-mode-map)
234
235     ;; Bind all printing characters to `isearch-printing-char'.
236     ;; This isn't normally necessary, but if a printing character were
237     ;; bound to something other than self-insert-command in global-map,
238     ;; then it would terminate the search and be executed without this.
239     (let ((i 32)
240           (str (make-string 1 0)))
241       (while (< i 127)
242         (aset str 0 i)
243         (define-key map str 'isearch-printing-char)
244         (setq i (1+ i))))
245
246     ;; Here FSF sets up various kludges to handle local bindings with
247     ;; meta char prefix keys.  We don't need isearch-other-meta-char
248     ;; because we handle things differently (via pre-command-hook).
249
250     ;; Several non-printing chars change the searching behavior.
251     ;;
252     (define-key map "\C-s" 'isearch-repeat-forward)
253     (define-key map "\M-\C-s" 'isearch-repeat-forward)
254     (define-key map "\C-r" 'isearch-repeat-backward)
255     (define-key map "\C-g" 'isearch-abort)
256
257     ;; I wish this worked...
258     ;(define-key map  [escape escape escape] 'isearch-cancel)
259     (define-key map [(meta escape) escape] 'isearch-cancel)
260
261     (define-key map "\C-q" 'isearch-quote-char)
262
263     (define-key map "\C-m" 'isearch-exit)
264     (define-key map "\C-j" 'isearch-printing-char)
265     (define-key map "\t" 'isearch-printing-char)
266     ;; I prefer our default.
267     ;(define-key map " " 'isearch-whitespace-chars)
268     (define-key map "\M- " 'isearch-whitespace-chars)
269
270     (define-key map "\C-w" 'isearch-yank-word)
271     (define-key map "\C-y" 'isearch-yank-line)
272     (define-key map "\M-y" 'isearch-yank-kill)
273
274     ;; Define keys for regexp chars * ? |.
275     ;; Nothing special for + because it matches at least once.
276     (define-key map "*" 'isearch-*-char)
277     (define-key map "?" 'isearch-*-char)
278     (define-key map "|" 'isearch-|-char)
279
280     ;; delete and backspace delete backward, f1 is help, and C-h can be either
281     (define-key map 'delete 'isearch-delete-char)
282     (define-key map 'backspace 'isearch-delete-char)
283     (define-key map '(control h) 'isearch-help-or-delete-char)
284     (define-key map 'f1 'isearch-mode-help)
285     (define-key map 'help 'isearch-mode-help)
286
287     (define-key map "\M-n" 'isearch-ring-advance)
288     (define-key map "\M-p" 'isearch-ring-retreat)
289     (define-key map "\M-\t" 'isearch-complete)
290
291     ;; I find this binding somewhat unintuitive, because it doesn't
292     ;; work if the mouse pointer is over the echo area -- it has to be
293     ;; over the search window.
294     (define-key map 'button2 'isearch-yank-selection)
295
296     map)
297   "Keymap for isearch-mode.")
298
299 ;; Some bindings you may want to put in your isearch-mode-hook.
300 ;; Suggest some alternates...
301 ;; (define-key isearch-mode-map "\C-t" 'isearch-toggle-case-fold)
302 ;; (define-key isearch-mode-map "\C-t" 'isearch-toggle-regexp)
303 ;; (define-key isearch-mode-map "\C-^" 'isearch-edit-string)
304
305 (defvar minibuffer-local-isearch-map
306   (let ((map (make-sparse-keymap)))
307     ;; #### - this should also be minor-mode-ified
308     (set-keymap-parents map (list minibuffer-local-map))
309     (set-keymap-name map 'minibuffer-local-isearch-map)
310
311     ;;#### This should just arrange to use the usual Emacs minibuffer histories
312     (define-key map "\r" 'isearch-nonincremental-exit-minibuffer)
313     (define-key map "\M-n" 'isearch-ring-advance-edit)
314     (define-key map "\M-p" 'isearch-ring-retreat-edit)
315     (define-key map 'down 'isearch-ring-advance-edit)
316     (define-key map 'up 'isearch-ring-retreat-edit)
317     (define-key map "\M-\t" 'isearch-complete-edit)
318     (define-key map "\C-s" 'isearch-forward-exit-minibuffer)
319     (define-key map "\C-r" 'isearch-reverse-exit-minibuffer)
320     map)
321   "Keymap for editing isearch strings in the minibuffer.")
322
323 ;;;========================================================
324 ;; Internal variables declared globally for byte-compiler.
325 ;; These are all set with setq while isearching
326 ;; and bound locally while editing the search string.
327
328 (defvar isearch-forward nil)    ; Searching in the forward direction.
329 (defvar isearch-regexp nil)     ; Searching for a regexp.
330 (defvar isearch-word nil)       ; Searching for words.
331
332 (defvar isearch-cmds nil)   ; Stack of search status sets.
333 (defvar isearch-string "")  ; The current search string.
334 (defvar isearch-message "") ; text-char-description version of isearch-string
335
336 (defvar isearch-success t)              ; Searching is currently successful.
337 (defvar isearch-invalid-regexp nil)     ; Regexp not well formed.
338 (defvar isearch-within-brackets nil)    ; Regexp has unclosed [.
339 (defvar isearch-other-end nil)  ; Start (end) of match if forward (backward).
340 (defvar isearch-wrapped nil)    ; Searching restarted from the top (bottom).
341 (defvar isearch-barrier 0)
342 (defvar isearch-just-started nil)
343 (defvar isearch-buffer nil)     ; the buffer we've frobbed the keymap of
344
345 (defvar isearch-case-fold-search nil)
346
347 ;; Need this for toggling case in isearch-toggle-case-fold.  When this
348 ;; is non-nil, the case-sensitiveness of the search is set by the
349 ;; user, and is may no longer be dynamically changed as per
350 ;; search-caps-disable-folding.
351 (defvar isearch-fixed-case nil)
352
353 (defvar isearch-adjusted nil)
354 (defvar isearch-slow-terminal-mode nil)
355 ;;; If t, using a small window.
356 (defvar isearch-small-window nil)
357 (defvar isearch-opoint 0)
358 ;;; The window configuration active at the beginning of the search.
359 (defvar isearch-window-configuration nil)
360 (defvar isearch-selected-frame nil)
361
362 ;; Flag to indicate a yank occurred, so don't move the cursor.
363 (defvar isearch-yank-flag nil)
364
365 ;;; A function to be called after each input character is processed.
366 ;;; (It is not called after characters that exit the search.)
367 ;;; It is only set from an optional argument to `isearch-mode'.
368 (defvar isearch-op-fun nil)
369
370 ;;;  Is isearch-mode in a recursive edit for modal searching.
371 (defvar isearch-recursive-edit nil)
372
373 ;;; Should isearch be terminated after doing one search?
374 (defvar isearch-nonincremental nil)
375
376 ;; New value of isearch-forward after isearch-edit-string.
377 (defvar isearch-new-forward nil)
378
379 ;; Accumulate here the extents unhidden during searching.
380 (defvar isearch-unhidden-extents nil)   ; in FSF: isearch-opened-overlays
381
382
383 ;;;==============================================================
384 ;; Minor-mode-alist changes - kind of redundant with the
385 ;; echo area, but if isearching in multiple windows, it can be useful.
386
387 (add-minor-mode 'isearch-mode 'isearch-mode)
388
389 (defvar isearch-mode nil) ;; Name of the minor mode, if non-nil.
390 (make-variable-buffer-local 'isearch-mode)
391
392 ;; We bind these in keydefs.el.
393 ;(define-key global-map "\C-s" 'isearch-forward)
394 ;(define-key global-map "\C-r" 'isearch-backward)
395 ;(define-key global-map "\M-\C-s" 'isearch-forward-regexp)
396 ;(define-key global-map "\M-\C-r" 'isearch-backward-regexp)
397
398 ;;;===============================================================
399 ;;; Entry points to isearch-mode.
400 ;;; These four functions should replace those in loaddefs.el
401 ;;; An alternative is to defalias isearch-forward etc to isearch-mode,
402 ;;; and look at this-command to set the options accordingly.
403
404 (defun isearch-forward (&optional regexp-p no-recursive-edit)
405   "\
406 Do incremental search forward.
407 With a prefix argument, do an incremental regular expression search instead.
408 \\<isearch-mode-map>
409 As you type characters, they add to the search string and are found.
410 The following non-printing keys are bound in `isearch-mode-map'.
411
412 Type \\[isearch-delete-char] to cancel characters from end of search string.
413 Type \\[isearch-exit] to exit, leaving point at location found.
414 Type LFD (C-j) to match end of line.
415 Type \\[isearch-repeat-forward] to search again forward,\
416  \\[isearch-repeat-backward] to search again backward.
417 Type \\[isearch-yank-word] to yank word from buffer onto end of search\
418  string and search for it.
419 Type \\[isearch-yank-line] to yank rest of line onto end of search string\
420  and search for it.
421 Type \\[isearch-yank-kill] to yank last killed text onto end of search string\
422  and search for it.
423 Type \\[isearch-quote-char] to quote control character to search for it.
424 Type \\[isearch-whitespace-chars] to match all whitespace chars in regexp.
425 \\[isearch-abort] while searching or when search has failed cancels input\
426  back to what has
427  been found successfully.
428 \\[isearch-abort] when search is successful aborts and moves point to\
429  starting point.
430
431 Also supported is a search ring of the previous 16 search strings.
432 Type \\[isearch-ring-advance] to search for the next item in the search ring.
433 Type \\[isearch-ring-retreat] to search for the previous item in the search\
434  ring.
435 Type \\[isearch-complete] to complete the search string using the search ring.
436
437 The above keys are bound in the isearch-mode-map.  To change the keys which
438  are special to isearch-mode, simply change the bindings in that map.
439
440 Other control and meta characters terminate the search
441  and are then executed normally (depending on `search-exit-option').
442
443 If this function is called non-interactively, it does not return to
444 the calling function until the search is done.
445
446 The bindings, more precisely:
447 \\{isearch-mode-map}"
448
449 ;; Non-standard bindings
450 ;; Type \\[isearch-toggle-regexp] to toggle regular expression with normal searching.
451 ;; Type \\[isearch-edit-string] to edit the search string in the minibuffer.
452 ;;  Terminate editing and return to incremental searching with CR.
453
454   (interactive "_P\np")
455   (isearch-mode t (not (null regexp-p)) nil (not no-recursive-edit)))
456
457 (defun isearch-forward-regexp (&optional not-regexp no-recursive-edit)
458   "\
459 Do incremental search forward for regular expression.
460 With a prefix argument, do a regular string search instead.
461 Like ordinary incremental search except that your input
462 is treated as a regexp.  See \\[isearch-forward] for more info."
463   (interactive "_P\np")
464   (isearch-mode t (null not-regexp) nil (not no-recursive-edit)))
465
466 (defun isearch-backward (&optional regexp-p no-recursive-edit)
467   "\
468 Do incremental search backward.
469 With a prefix argument, do a regular expression search instead.
470 See \\[isearch-forward] for more information."
471   (interactive "_P\np")
472   (isearch-mode nil (not (null regexp-p)) nil (not no-recursive-edit)))
473
474 (defun isearch-backward-regexp (&optional not-regexp no-recursive-edit)
475   "\
476 Do incremental search backward for regular expression.
477 With a prefix argument, do a regular string search instead.
478 Like ordinary incremental search except that your input
479 is treated as a regexp.  See \\[isearch-forward] for more info."
480   (interactive "_P\np")
481   (isearch-mode nil (null not-regexp) nil (not no-recursive-edit)))
482
483 ;; The problem here is that you can't scroll the help screen; as soon
484 ;; as you press a key, it's gone.  I don't know of a good way to fix
485 ;; it, though.  -hniksic
486 (defun isearch-mode-help ()
487   (interactive "_")
488   (let ((w (selected-window)))
489     (describe-function 'isearch-forward)
490     (select-window w))
491   (isearch-update))
492
493 \f
494 ;;;==================================================================
495 ;; isearch-mode only sets up incremental search for the minor mode.
496 ;; All the work is done by the isearch-mode commands.
497
498 (defun isearch-mode (forward &optional regexp op-fun recursive-edit word-p)
499   "Start isearch minor mode.  Called by `isearch-forward', etc.
500
501 \\{isearch-mode-map}"
502
503   (if executing-kbd-macro (setq recursive-edit nil))
504
505   (let ((inhibit-quit t)) ; don't leave things in an inconsistent state...
506
507     ;; Initialize global vars.
508     (setq isearch-buffer (current-buffer)
509           isearch-forward forward
510           isearch-regexp regexp
511           isearch-word word-p
512           isearch-op-fun op-fun
513           isearch-case-fold-search case-fold-search
514           isearch-fixed-case nil
515           isearch-string ""
516           isearch-message ""
517           isearch-cmds nil
518           isearch-success t
519           isearch-wrapped nil
520           isearch-barrier (point)
521           isearch-adjusted nil
522           isearch-yank-flag nil
523           isearch-invalid-regexp nil
524           isearch-within-brackets nil
525           isearch-slow-terminal-mode (and (<= (device-baud-rate)
526                                               search-slow-speed)
527                                           (> (window-height)
528                                              (* 4 search-slow-window-lines)))
529           isearch-other-end nil
530           isearch-small-window nil
531           isearch-just-started t
532
533           isearch-opoint (point)
534           search-ring-yank-pointer nil
535           regexp-search-ring-yank-pointer nil
536           isearch-unhidden-extents nil
537           isearch-window-configuration (current-window-configuration)
538
539           ;; #### What we really need is a buffer-local
540           ;; overriding-local-map.  See isearch-pre-command-hook for
541           ;; more details.
542           overriding-local-map (progn
543                                  (set-keymap-parents isearch-mode-map
544                                   (nconc (current-minor-mode-maps)
545                                          (and (current-local-map)
546                                               (list (current-local-map)))))
547                                  isearch-mode-map)
548           isearch-selected-frame (selected-frame)
549
550           )
551
552     ;; XEmacs change: without clearing the match data, sometimes old values
553     ;; of isearch-other-end get used.  Don't ask me why...
554     (store-match-data nil)
555
556     (add-hook 'pre-command-hook 'isearch-pre-command-hook)
557
558     (setq isearch-mode (gettext " Isearch"))
559     (redraw-modeline)
560
561     (isearch-push-state)
562
563     ) ; inhibit-quit is t before here
564
565   (isearch-update)
566   (run-hooks 'isearch-mode-hook)
567
568   ;; isearch-mode can be made modal (in the sense of not returning to
569   ;; the calling function until searching is completed) by entering
570   ;; a recursive-edit and exiting it when done isearching.
571   (if recursive-edit
572       (let ((isearch-recursive-edit t))
573         (recursive-edit)))
574   isearch-success)
575
576
577 ;;;====================================================
578 ;; Some high level utilities.  Others below.
579
580 (defun isearch-update ()
581   ;; Called after each command to update the display.
582   (if (null unread-command-events)
583       (progn
584         (if (not (input-pending-p))
585             (isearch-message))
586         (if (and isearch-slow-terminal-mode
587                  (not (or isearch-small-window
588                           (pos-visible-in-window-p))))
589             (let ((found-point (point)))
590               (setq isearch-small-window t)
591               (move-to-window-line 0)
592               (let ((window-min-height 1))
593                 (split-window nil (if (< search-slow-window-lines 0)
594                                       (1+ (- search-slow-window-lines))
595                                     (- (window-height)
596                                        (1+ search-slow-window-lines)))))
597               (if (< search-slow-window-lines 0)
598                   (progn (vertical-motion (- 1 search-slow-window-lines))
599                          (set-window-start (next-window) (point))
600                          (set-window-hscroll (next-window)
601                                              (window-hscroll))
602                          (set-window-hscroll (selected-window) 0))
603                 (other-window 1))
604               (goto-char found-point)))
605         (if isearch-other-end
606             (if (< isearch-other-end (point))
607                 (isearch-highlight isearch-other-end (point))
608               (isearch-highlight (point) isearch-other-end))
609           (isearch-dehighlight))
610         ))
611   (setq ;; quit-flag nil  not for isearch-mode
612    isearch-adjusted nil
613    isearch-yank-flag nil)
614   (isearch-highlight-all-update)
615   )
616
617
618 (defun isearch-done (&optional nopush edit)
619   ;; Called by all commands that terminate isearch-mode.
620   (let ((inhibit-quit t)) ; danger danger!
621     (if (and isearch-buffer (buffer-live-p isearch-buffer))
622         ;; Some loser process filter might have switched the window's
623         ;; buffer, so be sure to set these variables back in the
624         ;; buffer we frobbed them in.  But only if the buffer is still
625         ;; alive.
626         (with-current-buffer isearch-buffer
627           (setq overriding-local-map nil)
628           ;; Use remove-hook instead of just setting it to our saved value
629           ;; in case some process filter has created a buffer and modified
630           ;; the pre-command-hook in that buffer...  yeah, this is obscure,
631           ;; and yeah, I was getting screwed by it. -jwz
632           (remove-hook 'pre-command-hook 'isearch-pre-command-hook)
633           (set-keymap-parents isearch-mode-map nil)
634           (setq isearch-mode nil)
635           (redraw-modeline)
636           (isearch-dehighlight)
637           (isearch-highlight-all-cleanup)
638           (isearch-restore-invisible-extents nil nil)
639           ))
640
641     ;; it's not critical that this be inside inhibit-quit, but leaving
642     ;; things in small-window-mode would be bad.
643     (let ((found-start (window-start (selected-window)))
644           (found-point (point)))
645       (cond ((eq (selected-frame) isearch-selected-frame)
646              (set-window-configuration isearch-window-configuration)
647
648              (if isearch-small-window
649                  (goto-char found-point)
650                ;; Exiting the save-window-excursion clobbers
651                ;; window-start; restore it.
652                (set-window-start (selected-window) found-start t))))
653       ;; If there was movement, mark the starting position.
654       ;; Maybe should test difference between and set mark iff > threshold.
655       (if (and (buffer-live-p isearch-buffer)
656                (/= (point isearch-buffer) isearch-opoint))
657           ;; #### FSF doesn't do this if the region is active.  Should
658           ;; we do the same?
659           (progn
660             (push-mark isearch-opoint t nil isearch-buffer)
661             (or executing-kbd-macro (> (minibuffer-depth) 0)
662                 (display-message 'command "Mark saved where search started")))))
663     (setq isearch-buffer nil)
664     ) ; inhibit-quit is t before here
665
666   (if (and (> (length isearch-string) 0) (not nopush))
667       ;; Update the ring data.
668       (isearch-update-ring isearch-string isearch-regexp))
669
670   (run-hooks 'isearch-mode-end-hook)
671
672   (and (not edit) isearch-recursive-edit (exit-recursive-edit)))
673
674 (defun isearch-update-ring (string &optional regexp)
675   "Add STRING to the beginning of the search ring.
676 REGEXP says which ring to use."
677   (if regexp 
678       (if (or (null regexp-search-ring)
679               (not (string= string (car regexp-search-ring))))
680           (progn
681             (setq regexp-search-ring
682                   (cons string regexp-search-ring))
683             (if (> (length regexp-search-ring) regexp-search-ring-max)
684                 (setcdr (nthcdr (1- search-ring-max) regexp-search-ring)
685                         nil))))
686     (if (or (null search-ring)
687             (not (string= string (car search-ring))))
688         (progn
689           (setq search-ring (cons string search-ring))
690           (if (> (length search-ring) search-ring-max)
691               (setcdr (nthcdr (1- search-ring-max) search-ring) nil))))))
692
693 \f
694 ;;;====================================================
695 ;; Commands active while inside of the isearch minor mode.
696
697 (defun isearch-exit ()
698   "Exit search normally.
699 However, if this is the first command after starting incremental
700 search and `search-nonincremental-instead' is non-nil, do a
701 nonincremental search instead via `isearch-edit-string'."
702   (interactive)
703   (if (and search-nonincremental-instead
704            (= 0 (length isearch-string)))
705       (let ((isearch-nonincremental t)
706             ;; Highlighting only gets in the way of nonincremental
707             ;; search.
708             (search-highlight nil)
709             (isearch-highlight-all-matches nil))
710         (isearch-edit-string))
711     (isearch-done)))
712
713
714 (defun isearch-edit-string ()
715   "Edit the search string in the minibuffer.
716 The following additional command keys are active while editing.
717 \\<minibuffer-local-isearch-map>
718 \\[exit-minibuffer] to resume incremental searching with the edited string.
719 \\[isearch-nonincremental-exit-minibuffer] to do one nonincremental search.
720 \\[isearch-forward-exit-minibuffer] to resume isearching forward.
721 \\[isearch-reverse-exit-minibuffer] to resume isearching backward.
722 \\[isearch-ring-advance-edit] to replace the search string with the next item in the search ring.
723 \\[isearch-ring-retreat-edit] to replace the search string with the previous item in the search ring.
724 \\[isearch-complete-edit] to complete the search string using the search ring.
725 \\<isearch-mode-map>
726 If first char entered is \\[isearch-yank-word], then do word search instead."
727
728   ;; This code is very hairy for several reasons, explained in the code.
729   ;; Mainly, isearch-mode must be terminated while editing and then restarted.
730   ;; If there were a way to catch any change of buffer from the minibuffer,
731   ;; this could be simplified greatly.
732   ;; Editing doesn't back up the search point.  Should it?
733   (interactive)
734
735   (condition-case nil
736       (progn
737         (let ((isearch-nonincremental isearch-nonincremental)
738
739               ;; Locally bind all isearch global variables to protect them
740               ;; from recursive isearching.
741               ;; isearch-string -message and -forward are not bound
742               ;; so they may be changed.  Instead, save the values.
743               (isearch-new-string isearch-string)
744               (isearch-new-message isearch-message)
745               (isearch-new-forward isearch-forward)
746               (isearch-new-word isearch-word)
747
748               (isearch-regexp isearch-regexp)
749               (isearch-op-fun isearch-op-fun)
750               (isearch-cmds isearch-cmds)
751               (isearch-success isearch-success)
752               (isearch-wrapped isearch-wrapped)
753               (isearch-barrier isearch-barrier)
754               (isearch-adjusted isearch-adjusted)
755               (isearch-fixed-case isearch-fixed-case)
756               (isearch-yank-flag isearch-yank-flag)
757               (isearch-invalid-regexp isearch-invalid-regexp)
758               (isearch-within-brackets isearch-within-brackets)
759   ;;; Don't bind this.  We want isearch-search, below, to set it.
760   ;;; And the old value won't matter after that.
761   ;;;       (isearch-other-end isearch-other-end)
762               (isearch-opoint isearch-opoint)
763               (isearch-slow-terminal-mode isearch-slow-terminal-mode)
764               (isearch-small-window isearch-small-window)
765               (isearch-recursive-edit isearch-recursive-edit)
766               (isearch-window-configuration (current-window-configuration))
767               (isearch-selected-frame (selected-frame))
768               )
769           ;; Actually terminate isearching until editing is done.
770           ;; This is so that the user can do anything without failure,
771           ;; like switch buffers and start another isearch, and return.
772 ;;      (condition-case nil
773           (isearch-done t t)
774           ;;#### What does this mean?  There is no such condition!
775 ;;      (exit nil))                     ; was recursive editing
776
777           (unwind-protect
778               (progn
779                 ;; Fake the prompt message for the sake of
780                 ;; next-command-event below.
781                 (isearch-message)
782                 ;; If the first character the user types when we
783                 ;; prompt them for a string is the yank-word
784                 ;; character, then go into word-search mode.
785                 ;; Otherwise unread that character and read a string
786                 ;; the normal way.
787                 (let* ((cursor-in-echo-area t)
788                        (event (next-command-event)))
789                   (if (eq 'isearch-yank-word
790                           (lookup-key isearch-mode-map (vector event)))
791                       (setq isearch-word t;; so message-prefix is right
792                             isearch-new-word t)
793                     (setq unread-command-event event)))
794                 (setq isearch-new-string
795                       (read-from-minibuffer
796                        (isearch-message-prefix nil isearch-nonincremental)
797                        isearch-string
798                        minibuffer-local-isearch-map
799                        nil
800                        't               ;does its own history (but shouldn't)
801                        )
802                       isearch-new-message (mapconcat
803                                            'isearch-text-char-description
804                                            isearch-new-string "")))
805             ;; Always resume isearching by restarting it.
806             (isearch-mode isearch-forward
807                           isearch-regexp
808                           isearch-op-fun
809                           isearch-recursive-edit
810                           isearch-word)
811
812             ;; Copy new values in outer locals to isearch globals
813             (setq isearch-string isearch-new-string
814                   isearch-message isearch-new-message
815                   isearch-forward isearch-new-forward
816                   isearch-word isearch-new-word))
817
818           ;; Empty isearch-string means use default.
819           (if (= 0 (length isearch-string))
820               (setq isearch-string (or (car (if isearch-regexp
821                                                 regexp-search-ring
822                                               search-ring))
823                                        ""))))
824
825         ;; Reinvoke the pending search.
826         (isearch-push-state)
827         (isearch-search)
828         (isearch-update)
829         (if isearch-nonincremental (isearch-done)))
830
831     (quit  ; handle abort-recursive-edit
832      (isearch-abort)  ;; outside of let to restore outside global values
833      )))
834
835 (defun isearch-nonincremental-exit-minibuffer ()
836   (interactive)
837   (setq isearch-nonincremental t)
838   (exit-minibuffer))
839
840 (defun isearch-forward-exit-minibuffer ()
841   (interactive)
842   (setq isearch-new-forward t)
843   (exit-minibuffer))
844
845 (defun isearch-reverse-exit-minibuffer ()
846   (interactive)
847   (setq isearch-new-forward nil)
848   (exit-minibuffer))
849
850 (defun isearch-cancel ()
851   "Terminate the search and go back to the starting point."
852   (interactive)
853   (goto-char isearch-opoint)
854   (isearch-done t)
855   (signal 'quit '(isearch)))            ; and pass on quit signal
856
857 (defun isearch-abort ()
858   "Abort incremental search mode if searching is successful, signaling quit.
859 Otherwise, revert to previous successful search and continue searching.
860 Use `isearch-exit' to quit without signaling."
861   (interactive)
862 ;;  (ding)  signal instead below, if quitting
863   (discard-input)
864   (if isearch-success
865       ;; If search is successful, move back to starting point
866       ;; and really do quit.
867       (progn (goto-char isearch-opoint)
868              (setq isearch-success nil)
869              (isearch-done t)   ; exit isearch
870              (signal 'quit '(isearch)))  ; and pass on quit signal
871     ;; If search is failing, or has an incomplete regexp,
872     ;; rub out until it is once more successful.
873     (while (or (not isearch-success) isearch-invalid-regexp)
874       (isearch-pop-state))
875     (isearch-update)))
876
877 (defun isearch-repeat (direction)
878   ;; Utility for isearch-repeat-forward and -backward.
879   (if (eq isearch-forward (eq direction 'forward))
880       ;; C-s in forward or C-r in reverse.
881       (if (equal isearch-string "")
882           ;; If search string is empty, use last one.
883           (setq isearch-string
884                 (or (if isearch-regexp
885                         (car regexp-search-ring)
886                       (car search-ring))
887                     "")
888                 isearch-message
889                 (mapconcat 'isearch-text-char-description
890                            isearch-string ""))
891         ;; If already have what to search for, repeat it.
892         (or isearch-success
893             (progn
894               (goto-char (if isearch-forward (point-min) (point-max)))
895               (setq isearch-wrapped t))))
896     ;; C-s in reverse or C-r in forward, change direction.
897     (setq isearch-forward (not isearch-forward)))
898
899   (setq isearch-barrier (point)) ; For subsequent \| if regexp.
900
901   (if (equal isearch-string "")
902       (setq isearch-success t)
903     (if (and isearch-success (equal (match-end 0) (match-beginning 0))
904              (not isearch-just-started))
905         ;; If repeating a search that found
906         ;; an empty string, ensure we advance.
907         (if (if isearch-forward (eobp) (bobp))
908             ;; If there's nowhere to advance to, fail (and wrap next time).
909             (progn
910               (setq isearch-success nil)
911               (and executing-kbd-macro
912                    (not defining-kbd-macro)
913                    (isearch-done))
914               (ding nil 'isearch-failed))
915           (forward-char (if isearch-forward 1 -1))
916           (isearch-search))
917       (isearch-search)))
918
919   (isearch-push-state)
920   (isearch-update))
921
922 (defun isearch-repeat-forward ()
923   "Repeat incremental search forwards."
924   (interactive)
925   (isearch-repeat 'forward))
926
927 (defun isearch-repeat-backward ()
928   "Repeat incremental search backwards."
929   (interactive)
930   (isearch-repeat 'backward))
931
932 (defun isearch-toggle-regexp ()
933   "Toggle regexp searching on or off."
934   ;; The status stack is left unchanged.
935   (interactive)
936   (setq isearch-regexp (not isearch-regexp))
937   (if isearch-regexp (setq isearch-word nil))
938   (isearch-update))
939
940 (defun isearch-toggle-case-fold ()
941   "Toggle case folding in searching on or off."
942   (interactive)
943   (setq isearch-case-fold-search (if isearch-case-fold-search nil 'yes)
944         isearch-fixed-case t)
945   (lmessage 'progress "%s%s [case %ssensitive]"
946     (isearch-message-prefix)
947     isearch-message
948     (if isearch-case-fold-search "in" ""))
949   (setq isearch-adjusted t)
950   ;; Update the highlighting here so that it gets done before the
951   ;; one-second pause.
952   (isearch-highlight-all-update)
953   (sit-for 1)
954   (isearch-update))
955
956 (defun isearch-delete-char ()
957   "Discard last input item and move point back.
958 If no previous match was done, just beep."
959   (interactive)
960   (if (null (cdr isearch-cmds))
961       (ding nil 'isearch-quit)
962     (isearch-pop-state))
963   (isearch-update))
964
965 (defun isearch-help-or-delete-char ()
966   "Show Isearch help or delete backward in the search string.
967 Deletes when `delete-key-deletes-forward' is t and C-h is used for deleting
968 backwards."
969   (interactive)
970   (if (and delete-key-deletes-forward
971            (case (device-type)
972              ('tty (eq tty-erase-char ?\C-h))
973              ('x (not (x-keysym-on-keyboard-sans-modifiers-p 'backspace)))))
974       (isearch-delete-char)
975     (isearch-mode-help)))
976
977 ;; This is similar to FSF isearch-yank-string, but more general.
978 (defun isearch-yank (chunk)
979   ;; Helper for isearch-yank-* functions.  CHUNK can be a string or a
980   ;; function.
981   (let ((word (if (stringp chunk)
982                   chunk
983                 (save-excursion
984                   (and (not isearch-forward) isearch-other-end
985                        (goto-char isearch-other-end))
986                   (buffer-substring
987                    (point)
988                    (progn
989                      (funcall chunk)
990                      (point)))))))
991     ;; if configured so that typing upper-case characters turns off case
992     ;; folding, then downcase the string so that yanking an upper-case
993     ;; word doesn't mess with case-foldedness.
994     (if (and search-caps-disable-folding isearch-case-fold-search)
995         (setq word (downcase word)))
996     (if isearch-regexp (setq word (regexp-quote word)))
997     (setq isearch-string (concat isearch-string word)
998           isearch-message
999           (concat isearch-message
1000                   (mapconcat 'isearch-text-char-description
1001                              word ""))
1002           ;; Don't move cursor in reverse search.
1003           isearch-yank-flag t))
1004   (isearch-search-and-update))
1005
1006 (defun isearch-yank-word ()
1007   "Pull next word from buffer into search string."
1008   (interactive)
1009   (isearch-yank (function (lambda () (forward-word 1)))))
1010
1011 (defun isearch-yank-line ()
1012   "Pull rest of line from buffer into search string."
1013   (interactive)
1014   (isearch-yank 'end-of-line))
1015
1016 (defun isearch-yank-kill ()
1017   "Pull rest of line from kill ring into search string."
1018   (interactive)
1019   (isearch-yank (current-kill 0)))
1020
1021 (defun isearch-yank-sexp ()
1022   "Pull next expression from buffer into search string."
1023   (interactive)
1024   (isearch-yank 'forward-sexp))
1025
1026 (defun isearch-yank-selection ()
1027   "Pull the current selection into the search string."
1028   (interactive)
1029   (isearch-yank (get-selection)))
1030
1031 (defun isearch-yank-clipboard ()
1032   "Pull the current clipboard selection into the search string."
1033   (interactive)
1034   (isearch-yank (get-clipboard)))
1035
1036 (defun isearch-fix-case ()
1037   ;; The commented-out (and ...) form implies that, once
1038   ;; isearch-case-fold-search becomes nil due to a capital letter
1039   ;; typed in, it can never be restored to the original value.  In
1040   ;; that case, it's impossible to revert a case-sensitive search back
1041   ;; to case-insensitive.
1042   (if ;(and isearch-case-fold-search search-caps-disable-folding)
1043       (and case-fold-search
1044            ;; Make sure isearch-toggle-case-fold works.
1045            (not isearch-fixed-case)
1046            search-caps-disable-folding)
1047       (setq isearch-case-fold-search
1048             (no-upper-case-p isearch-string isearch-regexp)))
1049   (setq isearch-mode (if case-fold-search
1050                          (if isearch-case-fold-search
1051                              " Isearch"  ;As God Intended Mode
1052                            " ISeARch") ;Warn about evil case via StuDLYcAps.
1053                        " Isearch")))
1054
1055 (defun isearch-search-and-update ()
1056   ;; Do the search and update the display.
1057   (if (and (not isearch-success)
1058            ;; unsuccessful regexp search may become
1059            ;;  successful by addition of characters which
1060            ;;  make isearch-string valid
1061            (not isearch-regexp))
1062       nil
1063     ;; In reverse search, adding stuff at
1064     ;; the end may cause zero or many more chars to be
1065     ;; matched, in the string following point.
1066     ;; Allow all those possibilities without moving point as
1067     ;; long as the match does not extend past search origin.
1068     (if (and (not isearch-forward) (not isearch-adjusted)
1069              (condition-case ()
1070                  (progn
1071                    (isearch-fix-case)
1072                    (let ((case-fold-search isearch-case-fold-search))
1073                      (looking-at (if isearch-regexp isearch-string
1074                                    (regexp-quote isearch-string)))))
1075                (error nil))
1076              (or isearch-yank-flag
1077                  (<= (match-end 0)
1078                      (min isearch-opoint isearch-barrier))))
1079         (setq isearch-success t
1080               isearch-invalid-regexp nil
1081               isearch-within-brackets nil
1082               isearch-other-end (match-end 0))
1083       ;; Not regexp, not reverse, or no match at point.
1084       (if (and isearch-other-end (not isearch-adjusted))
1085           (goto-char (if isearch-forward isearch-other-end
1086                        (min isearch-opoint
1087                             isearch-barrier
1088                             (1+ isearch-other-end)))))
1089       (isearch-search)
1090       ))
1091   (isearch-push-state)
1092   (if isearch-op-fun (funcall isearch-op-fun))
1093   (isearch-update))
1094
1095
1096 ;; *, ?, and | chars can make a regexp more liberal.
1097 ;; They can make a regexp match sooner or make it succeed instead of failing.
1098 ;; So go back to place last successful search started
1099 ;; or to the last ^S/^R (barrier), whichever is nearer.
1100 ;; + needs no special handling because the string must match at least once.
1101
1102 (defun isearch-*-char ()
1103   "Handle * and ? specially in regexps."
1104   (interactive)
1105   (if isearch-regexp
1106       (let ((idx (length isearch-string)))
1107         (while (and (> idx 0)
1108                     (eq (aref isearch-string (1- idx)) ?\\))
1109           (setq idx (1- idx)))
1110         (when (= (mod (- (length isearch-string) idx) 2) 0)
1111           (setq isearch-adjusted t)
1112           ;; Get the isearch-other-end from before the last search.
1113           ;; We want to start from there,
1114           ;; so that we don't retreat farther than that.
1115           ;; (car isearch-cmds) is after last search;
1116           ;; (car (cdr isearch-cmds)) is from before it.
1117           (let ((cs (nth 5 (car (cdr isearch-cmds)))))
1118             (setq cs (or cs isearch-barrier))
1119             (goto-char
1120              (if isearch-forward
1121                  (max cs isearch-barrier)
1122                (min cs isearch-barrier)))))))
1123   (isearch-process-search-char last-command-event))
1124
1125
1126
1127 (defun isearch-|-char ()
1128   "If in regexp search, jump to the barrier."
1129   (interactive)
1130   (if isearch-regexp
1131       (progn
1132         (setq isearch-adjusted t)
1133         (goto-char isearch-barrier)))
1134   (isearch-process-search-char last-command-event))
1135
1136 ;; FSF:
1137 ;(defalias 'isearch-other-control-char 'isearch-other-meta-char)
1138 ;
1139 ;(defun isearch-other-meta-char ()
1140 ;...
1141 ;
1142
1143 (defun isearch-quote-char ()
1144   "Quote special characters for incremental search."
1145   (interactive)
1146   ;; #### Here FSF does some special conversion of chars in 0200-0377
1147   ;; range.  Maybe we should do the same.
1148   (isearch-process-search-char (read-quoted-char (isearch-message t))))
1149
1150 (defun isearch-return-char ()
1151   "Convert return into newline for incremental search.
1152 Obsolete."
1153   (interactive)
1154   (isearch-process-search-char ?\n))
1155
1156 (defun isearch-printing-char ()
1157   "Add this ordinary printing character to the search string and search."
1158   (interactive)
1159   (let ((event last-command-event))
1160     ;; If we are called by isearch-whitespace-chars because the
1161     ;; context disallows whitespace search (e.g. within brackets),
1162     ;; replace M-SPC with a space.  FSF has similar code.
1163     (and (eq this-command 'isearch-whitespace-chars)
1164          (null (event-to-character event))
1165          (setq event (character-to-event ?\ )))
1166     (isearch-process-search-char event)))
1167
1168 (defun isearch-whitespace-chars ()
1169   "Match all whitespace chars, if in regexp mode."
1170   ;; FSF docstring adds: "If you want to search for just a space, type
1171   ;; C-q SPC."  But we don't need the addition because we have a
1172   ;; different (better) default for the variable.
1173   (interactive)
1174   (if isearch-regexp
1175       (if (and search-whitespace-regexp (not isearch-within-brackets)
1176                (not isearch-invalid-regexp))
1177           (isearch-process-search-string search-whitespace-regexp " ")
1178         (isearch-printing-char))
1179     (progn
1180       ;; This way of doing word search doesn't correctly extend current search.
1181       ;;      (setq isearch-word t)
1182       ;;      (setq isearch-adjusted t)
1183       ;;      (goto-char isearch-barrier)
1184       (isearch-printing-char))))
1185
1186 (defun isearch-process-search-char (char)
1187   ;; Append the char to the search string, update the message and re-search.
1188   (isearch-process-search-string (isearch-char-to-string char)
1189                                  (isearch-text-char-description char)))
1190
1191 (defun isearch-process-search-string (string message)
1192   (setq isearch-string (concat isearch-string string)
1193         isearch-message (concat isearch-message message))
1194   (isearch-search-and-update))
1195
1196 \f
1197 ;;===========================================================
1198 ;; Search Ring
1199
1200 (defun isearch-ring-adjust1 (advance)
1201   ;; Helper for isearch-ring-adjust
1202   (let* ((ring (if isearch-regexp regexp-search-ring search-ring))
1203          (length (length ring))
1204          (yank-pointer-name (if isearch-regexp
1205                                 'regexp-search-ring-yank-pointer
1206                               'search-ring-yank-pointer))
1207          (yank-pointer (eval yank-pointer-name)))
1208     (if (zerop length)
1209         ()
1210       (set yank-pointer-name
1211            (setq yank-pointer
1212                  (mod (+ (or yank-pointer 0)
1213                          ;; XEmacs change
1214                          (if advance -1 (if yank-pointer 1 0)))
1215                       length)))
1216       (setq isearch-string (nth yank-pointer ring)
1217             isearch-message (mapconcat 'isearch-text-char-description
1218                                        isearch-string "")))))
1219
1220 (defun isearch-ring-adjust (advance)
1221   ;; Helper for isearch-ring-advance and isearch-ring-retreat
1222 ;  (if (cdr isearch-cmds)  ;; is there more than one thing on stack?
1223 ;      (isearch-pop-state))
1224   (isearch-ring-adjust1 advance)
1225   (if search-ring-update
1226       (progn
1227         (isearch-search)
1228         (isearch-update))
1229     (isearch-edit-string)
1230     )
1231   (isearch-push-state))
1232
1233 (defun isearch-ring-advance ()
1234   "Advance to the next search string in the ring."
1235   ;; This could be more general to handle a prefix arg, but who would use it.
1236   (interactive)
1237   (isearch-ring-adjust 'advance))
1238
1239 (defun isearch-ring-retreat ()
1240   "Retreat to the previous search string in the ring."
1241   (interactive)
1242   (isearch-ring-adjust nil))
1243
1244 (defun isearch-ring-advance-edit (n)
1245   "Insert the next element of the search history into the minibuffer."
1246   (interactive "p")
1247   (let* ((yank-pointer-name (if isearch-regexp
1248                                 'regexp-search-ring-yank-pointer
1249                               'search-ring-yank-pointer))
1250          (yank-pointer (eval yank-pointer-name))
1251          (ring (if isearch-regexp regexp-search-ring search-ring))
1252          (length (length ring)))
1253     (if (zerop length)
1254         ()
1255       (set yank-pointer-name
1256            (setq yank-pointer
1257                  (mod (- (or yank-pointer 0) n)
1258                       length)))
1259
1260       (erase-buffer)
1261       (insert (nth yank-pointer ring))
1262       (goto-char (point-max)))))
1263
1264 (defun isearch-ring-retreat-edit (n)
1265   "Inserts the previous element of the search history into the minibuffer."
1266   (interactive "p")
1267   (isearch-ring-advance-edit (- n)))
1268
1269 ;; Merging note: FSF comments out these functions and implements them
1270 ;; differently (see above), presumably because the versions below mess
1271 ;; with isearch-string, while what we really want them to do is simply
1272 ;; to insert the correct string to the minibuffer.
1273
1274 ;;(defun isearch-ring-adjust-edit (advance)
1275 ;;  "Use the next or previous search string in the ring while in minibuffer."
1276 ;;  (isearch-ring-adjust1 advance)
1277 ;;  (erase-buffer)
1278 ;;  (insert isearch-string))
1279
1280 ;;(defun isearch-ring-advance-edit ()
1281 ;;  (interactive)
1282 ;;  (isearch-ring-adjust-edit 'advance))
1283
1284 ;;(defun isearch-ring-retreat-edit ()
1285 ;;  "Retreat to the previous search string in the ring while in the minibuffer."
1286 ;;  (interactive)
1287 ;;  (isearch-ring-adjust-edit nil))
1288
1289
1290 (defun isearch-complete1 ()
1291   ;; Helper for isearch-complete and isearch-complete-edit
1292   ;; Return t if completion OK, nil if no completion exists.
1293   (let* ((ring (if isearch-regexp regexp-search-ring search-ring))
1294          (alist (mapcar (function (lambda (string) (list string))) ring))
1295          (completion-ignore-case case-fold-search)
1296          (completion (try-completion isearch-string alist)))
1297     (cond
1298      ((eq completion t)
1299       ;; isearch-string stays the same
1300       t)
1301      ((or completion ; not nil, must be a string
1302           (= 0 (length isearch-string))) ; shouldn't have to say this
1303       (if (equal completion isearch-string)  ;; no extension?
1304           (progn
1305             (if completion-auto-help
1306                 (with-output-to-temp-buffer "*Isearch completions*"
1307                   (display-completion-list
1308                    (all-completions isearch-string alist))))
1309             t)
1310         (and completion
1311              (setq isearch-string completion))))
1312      (t
1313       (temp-minibuffer-message "No completion")
1314       nil))))
1315
1316 (defun isearch-complete ()
1317   "Complete the search string from the strings on the search ring.
1318 The completed string is then editable in the minibuffer.
1319 If there is no completion possible, say so and continue searching."
1320   (interactive)
1321   (if (isearch-complete1)
1322       (isearch-edit-string)
1323     ;; else
1324     (sit-for 1)
1325     (isearch-update)))
1326
1327 (defun isearch-complete-edit ()
1328   "Same as `isearch-complete' except in the minibuffer."
1329   (interactive)
1330   (setq isearch-string (buffer-string))
1331   (if (isearch-complete1)
1332       (progn
1333         (erase-buffer)
1334         (insert isearch-string))))
1335
1336 \f
1337 ;;;==============================================================
1338 ;; The search status stack.
1339
1340 (defun isearch-top-state ()
1341   (let ((cmd (car isearch-cmds)))
1342     ;; #### Grr, this is so error-prone.  If you add something to
1343     ;; isearch-push-state, don't forget to update this.  I thought I'd
1344     ;; make a list of variables, and just do (mapcar* #'set vars
1345     ;; values), but the (point) thing would spoil it, leaving to more
1346     ;; complication.
1347     (setq isearch-string (car cmd)
1348           isearch-message (car (cdr cmd))
1349           isearch-success (nth 3 cmd)
1350           isearch-forward (nth 4 cmd)
1351           isearch-other-end (nth 5 cmd)
1352           isearch-word (nth 6 cmd)
1353           isearch-invalid-regexp (nth 7 cmd)
1354           isearch-wrapped (nth 8 cmd)
1355           isearch-barrier (nth 9 cmd)
1356           isearch-within-brackets (nth 10 cmd))
1357     (goto-char (car (cdr (cdr cmd))))))
1358
1359 (defun isearch-pop-state ()
1360   (pop isearch-cmds)
1361   (isearch-top-state)
1362
1363   ;; Make sure isearch-case-fold-search gets the correct value.  FSF
1364   ;; simply stores isearch-case-fold-search to isearch-cmds.  We
1365   ;; should probably do the same.
1366   (isearch-fix-case)
1367
1368   ;; Here, as well as in isearch-search we must deal with the point
1369   ;; landing at an invisible area which may need unhiding.
1370   (if (or (not (eq search-invisible 'open))
1371           (not isearch-hide-immediately))
1372       ;; If search-invisible is t, invisible text is just like any
1373       ;; other text.  If it is nil, it is always skipped and we can't
1374       ;; land inside.  In both cases, we don't need to do anything.
1375       ;;
1376       ;; Similarly, if isearch-hide-immediately is nil, needn't
1377       ;; re-hide the area here, and neither can we land back into a
1378       ;; hidden one.
1379       nil
1380     (when isearch-other-end
1381       ;; This will unhide the extents.
1382       (isearch-range-invisible (point) isearch-other-end))
1383     (isearch-restore-invisible-extents (point)
1384                                        (or isearch-other-end (point)))))
1385
1386 (defun isearch-push-state ()
1387   (setq isearch-cmds
1388         (cons (list isearch-string isearch-message (point)
1389                     isearch-success isearch-forward isearch-other-end
1390                     isearch-word
1391                     isearch-invalid-regexp isearch-wrapped isearch-barrier
1392                     isearch-within-brackets)
1393               isearch-cmds)))
1394
1395 \f
1396 ;;;==================================================================
1397 ;; Message string
1398
1399 (defun isearch-message (&optional c-q-hack ellipsis)
1400   ;; Generate and print the message string.
1401   (let ((cursor-in-echo-area ellipsis)
1402         (m (concat
1403             (isearch-message-prefix c-q-hack ellipsis isearch-nonincremental)
1404             isearch-message
1405             (isearch-message-suffix c-q-hack ellipsis)
1406             )))
1407     (if c-q-hack
1408         m
1409       (display-message 'progress (format "%s" m)))))
1410
1411 (defun isearch-message-prefix (&optional c-q-hack ellipsis nonincremental)
1412   ;; If about to search, and previous search regexp was invalid,
1413   ;; check that it still is.  If it is valid now,
1414   ;; let the message we display while searching say that it is valid.
1415   (and isearch-invalid-regexp ellipsis
1416        (condition-case ()
1417            (progn (re-search-forward isearch-string (point) t)
1418                   (setq isearch-invalid-regexp nil
1419                         isearch-within-brackets nil))
1420          (error nil)))
1421   ;; If currently failing, display no ellipsis.
1422   (or isearch-success (setq ellipsis nil))
1423   ;; #### - !  Emacs assembles strings all over the place, they can't
1424   ;; all be internationalized in the manner proposed below...  Add an
1425   ;; explicit call to `gettext' and have the string snarfer pluck the
1426   ;; english strings out of the comment below.  XEmacs is on a
1427   ;; purespace diet! -Stig
1428
1429   ;; The comment below is dead and buried, but it can be rebuilt if
1430   ;; necessary.  -hniksic
1431   (let ((m (concat (if isearch-success nil "failing ")
1432                    (if (and isearch-wrapped
1433                             (if isearch-forward
1434                                 (> (point) isearch-opoint)
1435                               (< (point) isearch-opoint)))
1436                        "overwrapped "
1437                      (if isearch-wrapped "wrapped "))
1438                    (if isearch-word "word ")
1439                    (if isearch-regexp "regexp ")
1440                    (if nonincremental "search" "I-search")
1441                    (if isearch-forward nil " backward")
1442                    ": "
1443                    )))
1444     (aset m 0 (upcase (aref m 0)))
1445     (gettext m)))
1446
1447 (defun isearch-message-suffix (&optional c-q-hack ellipsis)
1448   (concat (if c-q-hack "^Q" "")
1449           (if isearch-invalid-regexp
1450               (concat " [" isearch-invalid-regexp "]")
1451             "")))
1452
1453 ;;;(let ((i (logior (if isearch-success 32 0)
1454 ;;;                (if isearch-wrapped 16 0)
1455 ;;;                (if isearch-word     8 0)
1456 ;;;                (if isearch-regexp   4 0)
1457 ;;;                (if nonincremental   2 0)
1458 ;;;                (if isearch-forward  1 0))))
1459 ;;;  (cond
1460 ;;;   ((= i 63) (gettext "Wrapped word regexp search: "))              ; 111111
1461 ;;;   ...and so on, ad nauseam...
1462 ;;;   ((= i  0) (gettext "Failing I-search backward: "))               ; 000000
1463 ;;;   (t (error "Something's rotten")))))
1464
1465 \f
1466 ;;;========================================================
1467 ;;; Exiting
1468
1469 (put 'isearch-printing-char                     'isearch-command t)
1470 (put 'isearch-return-char                       'isearch-command t)
1471 (put 'isearch-repeat-forward                    'isearch-command t)
1472 (put 'isearch-repeat-backward                   'isearch-command t)
1473 (put 'isearch-delete-char                       'isearch-command t)
1474 (put 'isearch-help-or-delete-char               'isearch-command t)
1475 (put 'isearch-cancel                            'isearch-command t)
1476 (put 'isearch-abort                             'isearch-command t)
1477 (put 'isearch-quote-char                        'isearch-command t)
1478 (put 'isearch-exit                              'isearch-command t)
1479 (put 'isearch-printing-char                     'isearch-command t)
1480 (put 'isearch-printing-char                     'isearch-command t)
1481 (put 'isearch-yank-word                         'isearch-command t)
1482 (put 'isearch-yank-line                         'isearch-command t)
1483 (put 'isearch-yank-kill                         'isearch-command t)
1484 (put 'isearch-yank-sexp                         'isearch-command t)
1485 (put 'isearch-*-char                            'isearch-command t)
1486 (put 'isearch-*-char                            'isearch-command t)
1487 (put 'isearch-|-char                            'isearch-command t)
1488 (put 'isearch-toggle-regexp                     'isearch-command t)
1489 (put 'isearch-toggle-case-fold                  'isearch-command t)
1490 (put 'isearch-edit-string                       'isearch-command t)
1491 (put 'isearch-mode-help                         'isearch-command t)
1492 (put 'isearch-ring-advance                      'isearch-command t)
1493 (put 'isearch-ring-retreat                      'isearch-command t)
1494 (put 'isearch-ring-advance-edit                 'isearch-command t)
1495 (put 'isearch-ring-retreat-edit                 'isearch-command t)
1496 (put 'isearch-whitespace-chars                  'isearch-command t)
1497 (put 'isearch-complete                          'isearch-command t)
1498 (put 'isearch-complete-edit                     'isearch-command t)
1499 (put 'isearch-edit-string                       'isearch-command t)
1500 (put 'isearch-toggle-regexp                     'isearch-command t)
1501 (put 'isearch-forward-exit-minibuffer           'isearch-command t)
1502 (put 'isearch-reverse-exit-minibuffer           'isearch-command t)
1503 (put 'isearch-nonincremental-exit-minibuffer    'isearch-command t)
1504 (put 'isearch-yank-selection                    'isearch-command t)
1505 (put 'isearch-yank-clipboard                    'isearch-command t)
1506 (put 'isearch-yank-x-selection                  'isearch-command t)
1507 (put 'isearch-yank-x-clipboard                  'isearch-command t)
1508
1509 ;; scrolling the scrollbar should not terminate isearch.
1510
1511 ;; vertical scrollbar:
1512 (put 'scrollbar-line-up                         'isearch-command t)
1513 (put 'scrollbar-line-down                       'isearch-command t)
1514 (put 'scrollbar-page-up                         'isearch-command t)
1515 (put 'scrollbar-page-down                       'isearch-command t)
1516 (put 'scrollbar-to-top                          'isearch-command t)
1517 (put 'scrollbar-to-bottom                       'isearch-command t)
1518 (put 'scrollbar-vertical-drag                   'isearch-command t)
1519
1520 ;; horizontal scrollbar:
1521 (put 'scrollbar-char-left                       'isearch-command t)
1522 (put 'scrollbar-char-right                      'isearch-command t)
1523 (put 'scrollbar-page-left                       'isearch-command t)
1524 (put 'scrollbar-page-right                      'isearch-command t)
1525 (put 'scrollbar-to-left                         'isearch-command t)
1526 (put 'scrollbar-to-right                        'isearch-command t)
1527 (put 'scrollbar-horizontal-drag                 'isearch-command t)
1528
1529 (defun isearch-pre-command-hook ()
1530   ;;
1531   ;; For use as the value of `pre-command-hook' when isearch-mode is active.
1532   ;; If the command about to be executed is not one of the isearch commands,
1533   ;; then isearch-mode is turned off before that command is executed.
1534   ;;
1535   ;; If the command about to be executed is self-insert-command, or is a
1536   ;; keyboard macro of a single key sequence which is bound to self-insert-
1537   ;; command, then we add those chars to the search ring instead of inserting
1538   ;; them in the buffer.  In this way, the set of self-searching characters
1539   ;; need not be exhaustively enumerated, but is derived from other maps.
1540   ;;
1541   (cond ((not (eq (current-buffer) isearch-buffer))
1542          ;; If the buffer (likely meaning "frame") has changed, bail.
1543          ;; This can happen if the user types something into another
1544          ;; frame.  It can also happen if a proc filter has popped up
1545          ;; another buffer, which is arguably a bad thing for it to
1546          ;; have done, but the way in which isearch would have hosed
1547          ;; you in that case is unarguably even worse. -jwz
1548          (isearch-done)
1549
1550          ;; `this-command' is set according to the value of
1551          ;; `overriding-local-map', set by isearch-mode.  This is
1552          ;; wrong because that keymap makes sense only in isearch
1553          ;; buffer.  To make sure the right command is called, adjust
1554          ;; `this-command' to the appropriate value, now that
1555          ;; `isearch-done' has set `overriding-local-map' to nil.
1556
1557          ;; FSF does similar magic in `isearch-other-meta-char', which
1558          ;; is horribly complex.  I *hope* what we do works in all
1559          ;; cases.
1560          (setq this-command (key-binding (this-command-keys))))
1561         (t
1562          (isearch-maybe-frob-keyboard-macros)
1563          (if (and this-command
1564                   (symbolp this-command)
1565                   (get this-command 'isearch-command))
1566              nil ; then continue.
1567            (isearch-done)))))
1568
1569 (defun isearch-maybe-frob-keyboard-macros ()
1570   ;;
1571   ;; If the command about to be executed is `self-insert-command' then change
1572   ;; the command to `isearch-printing-char' instead, meaning add the last-
1573   ;; typed character to the search string.
1574   ;;
1575   ;; If `this-command' is a string or a vector (that is, a keyboard macro)
1576   ;; and it contains only one command, which is bound to self-insert-command,
1577   ;; then do the same thing as for self-inserting commands: arrange for that
1578   ;; character to be added to the search string.  If we didn't do this, then
1579   ;; typing a compose sequence (a la x-compose.el) would terminate the search
1580   ;; and insert the character, instead of searching for that character.
1581   ;;
1582   ;; We should continue doing this, since it's pretty much the behavior one
1583   ;; would expect, but it will stop being so necessary once key-translation-
1584   ;; map exists and is used by x-compose.el and things like it, since the
1585   ;; translation will have been done before we see the keys.
1586   ;;
1587   (cond ((eq this-command 'self-insert-command)
1588          (setq this-command 'isearch-printing-char))
1589         ((and (or (stringp this-command) (vectorp this-command))
1590               (eq (key-binding this-command) 'self-insert-command))
1591          (setq last-command-event (character-to-event (aref this-command 0))
1592                last-command-char (and (stringp this-command)
1593                                       (aref this-command 0))
1594                this-command 'isearch-printing-char))
1595         ))
1596
1597 \f
1598 ;;;========================================================
1599 ;;; Highlighting
1600
1601 (defvar isearch-extent nil)
1602
1603 ;; this face is initialized by faces.el since isearch is preloaded.
1604 ;(make-face 'isearch)
1605
1606 (defun isearch-make-extent (begin end)
1607   (let ((x (make-extent begin end (current-buffer))))
1608     ;; make the isearch extent always take precedence over any mouse-
1609     ;; highlighted extents we may be passing through, since isearch, being
1610     ;; modal, is more interesting (there's nothing they could do with a
1611     ;; mouse-highlighted extent while in the midst of a search anyway).
1612     (set-extent-priority x (+ mouse-highlight-priority 2))
1613     (set-extent-face x 'isearch)
1614     (setq isearch-extent x)))
1615
1616 (defun isearch-highlight (begin end)
1617   (if (null search-highlight)
1618       nil
1619     ;; make sure isearch-extent is in the current buffer
1620     (or (and (extentp isearch-extent)
1621              (extent-live-p isearch-extent))
1622         (isearch-make-extent begin end))
1623     (set-extent-endpoints isearch-extent begin end (current-buffer))))
1624
1625 ;; This used to have a TOTALLY flag that also deleted the extent.  I
1626 ;; don't think this is necessary any longer, as isearch-highlight can
1627 ;; simply move the extent to another buffer.  The IGNORED argument is
1628 ;; for the code that calls this function with an argument.  --hniksic
1629 (defun isearch-dehighlight (&optional ignored)
1630   (and search-highlight
1631        (extentp isearch-extent)
1632        (extent-live-p isearch-extent)
1633        (detach-extent isearch-extent)))
1634
1635 \f
1636 ;;;========================================================
1637 ;;; Searching
1638
1639 (defun isearch-search ()
1640   ;; Do the search with the current search string.
1641   (isearch-message nil t)
1642   (isearch-fix-case)
1643   (condition-case lossage
1644       (let ((inhibit-quit nil)
1645             (case-fold-search isearch-case-fold-search)
1646             (retry t))
1647         (if isearch-regexp (setq isearch-invalid-regexp nil))
1648         (setq isearch-within-brackets nil)
1649         (while retry
1650           (setq isearch-success
1651                 (funcall
1652                  (cond (isearch-word
1653                         (if isearch-forward
1654                             'word-search-forward 'word-search-backward))
1655                        (isearch-regexp
1656                         (if isearch-forward
1657                             're-search-forward 're-search-backward))
1658                        (t
1659                         (if isearch-forward 'search-forward 'search-backward)))
1660                  isearch-string nil t))
1661           ;; Clear RETRY unless we matched some invisible text
1662           ;; and we aren't supposed to do that.
1663           (if (or (eq search-invisible t)
1664                   (not isearch-success)
1665                   (bobp) (eobp)
1666                   (= (match-beginning 0) (match-end 0))
1667                   (not (isearch-range-invisible
1668                         (match-beginning 0) (match-end 0))))
1669               (setq retry nil)))
1670         (setq isearch-just-started nil)
1671         (when isearch-success
1672           (setq isearch-other-end
1673                 (if isearch-forward (match-beginning 0) (match-end 0)))
1674           (and isearch-hide-immediately
1675                (isearch-restore-invisible-extents (match-beginning 0)
1676                                                   (match-end 0)))))
1677
1678     (quit (setq unread-command-events (nconc unread-command-events
1679                                              (character-to-event (quit-char))))
1680           (setq isearch-success nil))
1681
1682     (invalid-regexp
1683      (setq isearch-invalid-regexp (car (cdr lossage)))
1684      (setq isearch-within-brackets (string-match "\\`Unmatched \\["
1685                                                  isearch-invalid-regexp))
1686      (if (string-match
1687           "\\`Premature \\|\\`Unmatched \\|\\`Invalid "
1688           isearch-invalid-regexp)
1689          (setq isearch-invalid-regexp (gettext "incomplete input"))))
1690     (error
1691      ;; stack overflow in regexp search.
1692      (setq isearch-invalid-regexp (car (cdr lossage)))))
1693
1694   (if isearch-success
1695       nil
1696
1697     ;; If we're being run inside a keyboard macro, then the call to
1698     ;; ding will signal an error (to terminate the macro).  We must
1699     ;; turn off isearch-mode first, so that we aren't still in isearch
1700     ;; mode after the macro exits.  Note that isearch-recursive-edit
1701     ;; must not be true if a keyboard macro is executing.
1702     (if (and executing-kbd-macro (not defining-kbd-macro))
1703         (progn
1704           (isearch-done)
1705           (ding nil 'isearch-failed)))
1706
1707     ;; Ding if failed this time after succeeding last time.
1708     (and (nth 3 (car isearch-cmds))
1709          (ding nil 'isearch-failed))
1710     (goto-char (nth 2 (car isearch-cmds)))))
1711
1712 ;; Replaced with isearch-edit-string.
1713 ;(defun nonincremental-search (forward regexp)
1714 ;...
1715
1716 (defun isearch-unhide-extent (extent)
1717   ;; Store the values for the `invisible' and `intangible'
1718   ;; properties, and then set them to nil. This way the text hidden
1719   ;; by this extent becomes visible.
1720   (put extent 'isearch-invisible (get extent 'invisible))
1721   (put extent 'isearch-intangible (get extent 'intangible))
1722   (put extent 'invisible nil)
1723   (put extent 'intangible nil))
1724
1725 (defun isearch-range-invisible (beg end)
1726   "Return t if all the text from BEG to END is invisible.
1727 Before that, if search-invisible is `open', unhide the extents with an
1728 `isearch-open-invisible' property."
1729   ;; isearch-search uses this to skip the extents that are invisible,
1730   ;; but don't have `isearch-open-invisible' set.  It is unclear
1731   ;; what's supposed to happen if only a part of [BEG, END) overlaps
1732   ;; the extent.
1733   (let (to-be-unhidden)
1734     (if (map-extents
1735          (lambda (extent ignored)
1736            (if (and (<= (extent-start-position extent) beg)
1737                     (>= (extent-end-position extent) end))
1738                ;; All of the region is covered by the extent.
1739                (if (and (eq search-invisible 'open)
1740                         (get extent 'isearch-open-invisible))
1741                    (progn
1742                      (push extent to-be-unhidden)
1743                      nil)               ; keep mapping
1744                  ;; We can't or won't unhide this extent, so we must
1745                  ;; skip the whole match.  We return from map-extents
1746                  ;; immediately.
1747                  t)
1748              ;; Else, keep looking.
1749              nil))
1750          nil beg end nil 'all-extents-closed 'invisible)
1751         ;; The whole match must be skipped.  Signal it by returning t
1752         ;; to the caller.
1753         t
1754       ;; If any extents need to be unhidden, unhide them.
1755       (mapc #'isearch-unhide-extent to-be-unhidden)
1756       ;; Will leave this assert for some time, to catch bugs.
1757       (assert (null (intersection to-be-unhidden isearch-unhidden-extents)))
1758       (setq isearch-unhidden-extents (nconc to-be-unhidden
1759                                             isearch-unhidden-extents))
1760       nil)))
1761
1762 (defun isearch-restore-extent (extent)
1763   (put extent 'invisible (get extent 'isearch-invisible))
1764   (put extent 'intangible (get extent 'isearch-intangible))
1765   (remprop extent 'isearch-invisible)
1766   (remprop extent 'isearch-intangible))
1767
1768 ;; FSF calls this function `isearch-clean-overlays'.
1769 (defun isearch-restore-invisible-extents (beg end)
1770   (cond
1771    ((null beg)
1772     ;; Delete all -- this is called at the end of isearch.
1773     (mapc #'isearch-restore-extent isearch-unhidden-extents)
1774     (setq isearch-unhidden-extents nil))
1775    (t
1776     ;; Extents that do not overlap the match area can be safely
1777     ;; restored to their hidden state.
1778     (setq isearch-unhidden-extents
1779           (delete-if (lambda (extent)
1780                        (unless (extent-in-region-p extent beg end
1781                                                    'all-extents-closed)
1782                          (isearch-restore-extent extent)
1783                          t))
1784                      isearch-unhidden-extents)))))
1785
1786 (defun isearch-no-upper-case-p (string)
1787   "Return t if there are no upper case chars in string.
1788 But upper case chars preceded by \\ do not count since they
1789 have special meaning in a regexp."
1790   ;; this incorrectly returns t for "\\\\A"
1791   (let ((case-fold-search nil))
1792     (not (string-match "\\(^\\|[^\\]\\)[A-Z]" string))))
1793 (make-obsolete 'isearch-no-upper-case-p 'no-upper-case-p)
1794
1795 ;; Portability functions to support various Emacs versions.
1796
1797 (defun isearch-char-to-string (c)
1798   (if (eventp c)
1799       (make-string 1 (event-to-character c nil nil t))
1800     (make-string 1 c)))
1801
1802 ;(defun isearch-text-char-description (c)
1803 ;  (isearch-char-to-string c))
1804
1805 (define-function 'isearch-text-char-description 'text-char-description)
1806
1807 ;; Used by etags.el and info.el
1808 (defmacro with-caps-disable-folding (string &rest body) "\
1809 Eval BODY with `case-fold-search' let to nil if STRING contains
1810 uppercase letters and `search-caps-disable-folding' is t."
1811   `(let ((case-fold-search
1812           (if (and case-fold-search search-caps-disable-folding)
1813               (isearch-no-upper-case-p ,string)
1814             case-fold-search)))
1815      ,@body))
1816 (make-obsolete 'with-caps-disable-folding 'with-search-caps-disable-folding)
1817 (put 'with-caps-disable-folding 'lisp-indent-function 1)
1818 (put 'with-caps-disable-folding 'edebug-form-spec '(form body))
1819
1820 \f
1821 ;;;========================================================
1822 ;;; Advanced highlighting
1823
1824 ;; When active, *every* visible match for the current search string is
1825 ;; highlighted: the current one using the normal isearch match color
1826 ;; and all the others using the `isearch-secondary' face.  The extra
1827 ;; highlighting makes it easier to anticipate where the cursor will
1828 ;; land each time you press C-s or C-r to repeat a pending search.
1829 ;; Only the matches visible at any point are highlighted -- when you
1830 ;; move through the buffer, the highlighting is readjusted.
1831
1832 ;; This is based on ideas from Bob Glickstein's `ishl' package.  It
1833 ;; has been merged with XEmacs by Darryl Okahata, and then completely
1834 ;; rewritten by Hrvoje Niksic.
1835
1836 ;; The code makes the following assumptions about the rest of this
1837 ;; file, so be careful when modifying it.
1838
1839 ;; * `isearch-highlight-all-update' should get called when the search
1840 ;;   string changes, or when the search advances.  This is done from
1841 ;;   `isearch-update'.
1842 ;; * `isearch-highlight-all-cleanup' should get called when the search
1843 ;;   is done.  This is performed in `isearch-done'.
1844 ;; * `isearch-string' is expected to contain the current search string
1845 ;;   as entered by the user.
1846 ;; * `isearch-opoint' is expected to contain the location where the
1847 ;;   current search began.
1848 ;; * the type of the current search is expected to be given by
1849 ;;   `isearch-word' and `isearch-regexp'.
1850 ;; * the variable `isearch-invalid-regexp' is expected to be true iff
1851 ;;   `isearch-string' is an invalid regexp.
1852
1853 (defcustom isearch-highlight-all-matches search-highlight
1854   "*Non-nil means highlight all visible matches."
1855   :type 'boolean
1856   :group 'isearch)
1857
1858 ;; We can't create this face here, as isearch.el is preloaded.
1859 ;; #### Think up a better name for this!
1860 ;(defface isearch-secondary '((t (:foreground "red3")))
1861 ;  "Face to use for highlighting all matches."
1862 ;  :group 'isearch)
1863
1864 (defvar isearch-highlight-extents nil)
1865 (defvar isearch-window-start nil)
1866 (defvar isearch-window-end nil)
1867 ;; We compare isearch-string and isearch-case-fold-search to saved
1868 ;; values for better efficiency.
1869 (defvar isearch-highlight-last-string nil)
1870 (defvar isearch-highlight-last-case-fold-search nil)
1871 (defvar isearch-highlight-last-regexp nil)
1872
1873 (defun isearch-delete-extents-in-range (start end)
1874   ;; Delete all highlighting extents that overlap [START, END).
1875   (setq isearch-highlight-extents
1876         (delete-if (lambda (extent)
1877                      (when (extent-in-region-p extent start end)
1878                        (delete-extent extent)
1879                        t))
1880                    isearch-highlight-extents)))
1881
1882 (defun isearch-highlight-all-cleanup ()
1883   ;; Stop lazily highlighting and remove extra highlighting from
1884   ;; buffer.
1885   (mapc #'delete-extent isearch-highlight-extents)
1886   (setq isearch-highlight-extents nil)
1887   (setq isearch-window-end nil
1888         isearch-highlight-last-string nil))
1889
1890 (defun isearch-highlight-all-update ()
1891   ;; Update the highlighting if necessary.  This needs to check if the
1892   ;; search string has changed, or if the window has changed position
1893   ;; in the buffer.
1894   (let ((need-start-over nil))
1895     ;; NB: we don't check for isearch-success because if the point is
1896     ;; after the last match, the search can be unsuccessful, and yet
1897     ;; there are things to highlight.
1898     (cond ((not isearch-highlight-all-matches))
1899           ((or (equal isearch-string "")
1900                isearch-invalid-regexp)
1901            (isearch-highlight-all-cleanup))
1902           ((not (eq isearch-case-fold-search
1903                     isearch-highlight-last-case-fold-search))
1904            ;; This case is usually caused by search string being
1905            ;; changed, which would be caught below, but it can also be
1906            ;; tripped using isearch-toggle-case-fold.
1907            (setq need-start-over t))
1908           ((not (eq isearch-regexp isearch-highlight-last-regexp))
1909            ;; Ditto for isearch-toggle-regexp.
1910            (setq need-start-over t))
1911           ((equal isearch-string isearch-highlight-last-string)
1912            ;; The search string is the same.  We need to do something
1913            ;; if our position has changed.
1914
1915            ;; It would be nice if we didn't have to do this; however,
1916            ;; window-start doesn't support a GUARANTEE flag, so we must
1917            ;; force redisplay to get the correct value for start and end
1918            ;; of window.
1919            (sit-for 0)
1920
1921            ;; Check whether our location has changed.
1922            (let ((start (window-start))
1923                  (end (min (window-end) (point-max))))
1924              (cond ((and (= start isearch-window-start)
1925                          (= end isearch-window-end))
1926                     ;; Our position is unchanged -- do nothing.
1927                     )
1928                    ((and (> start isearch-window-start)
1929                          (> end isearch-window-end)
1930                          (<= start isearch-window-end))
1931                     ;; We've migrated downward, but we overlap the old
1932                     ;; region.  Delete the old non-overlapping extents
1933                     ;; and fill in the rest.
1934                     (isearch-delete-extents-in-range isearch-window-start start)
1935                     (isearch-highlightify-region isearch-window-end end)
1936                     (setq isearch-window-start start
1937                           isearch-window-end   end))
1938                    ((and (<= start isearch-window-start)
1939                          (<= end isearch-window-end)
1940                          (> end isearch-window-start))
1941                     ;; We've migrated upward, but we overlap the old
1942                     ;; region.  Delete the old non-overlapping extents
1943                     ;; and fill in the rest.
1944                     (isearch-delete-extents-in-range
1945                      end isearch-window-end)
1946                     (isearch-highlightify-region start isearch-window-start)
1947                     (setq isearch-window-start start
1948                           isearch-window-end   end))
1949                    (t
1950                     ;; The regions don't overlap, or they overlap in a
1951                     ;; weird way.
1952                     (setq need-start-over t)))))
1953           (t
1954            ;; The search string has changed.
1955
1956            ;; If more input is pending, don't start over because
1957            ;; starting over forces redisplay, and that slows down
1958            ;; typing.
1959            (unless (input-pending-p)
1960              (setq need-start-over t))))
1961     (when need-start-over
1962       ;; Force redisplay before removing the old extents, in order to
1963       ;; avoid flicker.
1964       (sit-for 0)
1965       (isearch-highlight-all-cleanup)
1966       (setq isearch-window-start (window-start)
1967             isearch-window-end   (min (window-end) (point-max)))
1968       (isearch-highlightify-region isearch-window-start isearch-window-end))
1969
1970     (setq isearch-highlight-last-string isearch-string
1971           isearch-highlight-last-case-fold-search isearch-case-fold-search
1972           isearch-highlight-last-regexp isearch-regexp)))
1973
1974 (defun isearch-highlight-advance (string forwardp)
1975   ;; Search ahead for the next or previous match.  This is the same as
1976   ;; isearch-search, but without the extra baggage.  Maybe it should
1977   ;; be in a separate function.
1978   (let ((case-fold-search isearch-case-fold-search))
1979     (funcall (cond (isearch-word (if forwardp
1980                                      'word-search-forward
1981                                    'word-search-backward))
1982                    (isearch-regexp (if forwardp
1983                                        're-search-forward
1984                                      're-search-backward))
1985                    (t (if forwardp
1986                           'search-forward
1987                         'search-backward)))
1988              string nil t)))
1989
1990 (defun isearch-highlightify-region (start end)
1991   ;; Highlight all occurrences of isearch-string between START and
1992   ;; END.  To do this right, we have to search forward as long as
1993   ;; there are matches that overlap [START, END), and then search
1994   ;; backward the same way.
1995   (save-excursion
1996     (goto-char isearch-opoint)
1997     (let ((lastpoint (point)))
1998       (while (and (isearch-highlight-advance isearch-string t)
1999                   (/= lastpoint (point))
2000                   (< (match-beginning 0) end))
2001         (let ((extent (make-extent (match-beginning 0)
2002                                    (match-end 0))))
2003           (set-extent-priority extent (1+ mouse-highlight-priority))
2004           (put extent 'face 'isearch-secondary)
2005           (push extent isearch-highlight-extents))
2006         (setq lastpoint (point))))
2007     (goto-char isearch-opoint)
2008     (let ((lastpoint (point)))
2009       (while (and (isearch-highlight-advance isearch-string nil)
2010                   (/= lastpoint (point))
2011                   (>= (match-end 0) start))
2012         (let ((extent (make-extent (match-beginning 0)
2013                                    (match-end 0))))
2014           (set-extent-priority extent (1+ mouse-highlight-priority))
2015           (put extent 'face 'isearch-secondary)
2016           (push extent isearch-highlight-extents))
2017         (setq lastpoint (point))))))
2018
2019 ;;; isearch-mode.el ends here