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