Contents in 1999-06-04-13 of release-21-2.
[chise/xemacs-chise.git.1] / lisp / minibuf.el
1 ;;; minibuf.el --- Minibuffer functions for XEmacs
2
3 ;; Copyright (C) 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
4 ;; Copyright (C) 1995 Tinker Systems
5 ;; Copyright (C) 1995, 1996 Ben Wing
6
7 ;; Author: Richard Mlynarik
8 ;; Created: 2-Oct-92
9 ;; Maintainer: XEmacs Development Team
10 ;; Keywords: internal, dumped
11
12 ;; This file is part of XEmacs.
13
14 ;; XEmacs is free software; you can redistribute it and/or modify it
15 ;; under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; any later version.
18
19 ;; XEmacs is distributed in the hope that it will be useful, but
20 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22 ;; General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with XEmacs; see the file COPYING.  If not, write to the
26 ;; Free Software Foundation, 59 Temple Place - Suite 330,
27 ;; Boston, MA 02111-1307, USA.
28
29 ;;; Synched up with: all the minibuffer history stuff is synched with
30 ;;; 19.30.  Not sure about the rest.
31
32 ;;; Commentary:
33
34 ;; This file is dumped with XEmacs.
35
36 ;; Written by Richard Mlynarik 2-Oct-92
37
38 ;; 06/11/1997 -  Use char-(after|before) instead of
39 ;;  (following|preceding)-char. -slb
40
41 ;;; Code:
42
43 (defgroup minibuffer nil
44   "Controling the behavior of the minibuffer."
45   :group 'environment)
46
47
48 (defcustom insert-default-directory t
49  "*Non-nil means when reading a filename start with default dir in minibuffer."
50  :type 'boolean
51  :group 'minibuffer)
52
53 (defcustom minibuffer-history-uniquify t
54   "*Non-nil means when adding an item to a minibuffer history, remove
55 previous occurances of the same item from the history list first,
56 rather than just consing the new element onto the front of the list."
57   :type 'boolean
58   :group 'minibuffer)
59
60 (defvar minibuffer-completion-table nil
61   "Alist or obarray used for completion in the minibuffer.
62 This becomes the ALIST argument to `try-completion' and `all-completions'.
63
64 The value may alternatively be a function, which is given three arguments:
65   STRING, the current buffer contents;
66   PREDICATE, the predicate for filtering possible matches;
67   CODE, which says what kind of things to do.
68 CODE can be nil, t or `lambda'.
69 nil means to return the best completion of STRING, nil if there is none,
70   or t if it is already a unique completion.
71 t means to return a list of all possible completions of STRING.
72 `lambda' means to return t if STRING is a valid completion as it stands.")
73
74 (defvar minibuffer-completion-predicate nil
75   "Within call to `completing-read', this holds the PREDICATE argument.")
76
77 (defvar minibuffer-completion-confirm nil
78   "Non-nil => demand confirmation of completion before exiting minibuffer.")
79
80 (defvar minibuffer-confirm-incomplete nil
81   "If true, then in contexts where completing-read allows answers which
82 are not valid completions, an extra RET must be typed to confirm the
83 response.  This is helpful for catching typos, etc.")
84
85 (defcustom completion-auto-help t
86   "*Non-nil means automatically provide help for invalid completion input."
87   :type 'boolean
88   :group 'minibuffer)
89
90 (defcustom enable-recursive-minibuffers nil
91   "*Non-nil means to allow minibuffer commands while in the minibuffer.
92 More precisely, this variable makes a difference when the minibuffer window
93 is the selected window.  If you are in some other window, minibuffer commands
94 are allowed even if a minibuffer is active."
95   :type 'boolean
96   :group 'minibuffer)
97
98 (defcustom minibuffer-max-depth 1
99   ;; See comment in #'minibuffer-max-depth-exceeded
100   "*Global maximum number of minibuffers allowed;
101 compare to enable-recursive-minibuffers, which is only consulted when the
102 minibuffer is reinvoked while it is the selected window."
103   :type '(choice integer
104                  (const :tag "Indefinite" nil))
105   :group 'minibuffer)
106
107 ;; Moved to C.  The minibuffer prompt must be setup before this is run
108 ;; and that can only be done from the C side.
109 ;(defvar minibuffer-setup-hook nil
110 ;  "Normal hook run just after entry to minibuffer.")
111
112 (defvar minibuffer-exit-hook nil
113   "Normal hook run just after exit from minibuffer.")
114
115 (defvar minibuffer-help-form nil
116   "Value that `help-form' takes on inside the minibuffer.")
117
118 (defvar minibuffer-default nil
119   "Default value for minibuffer input.")
120   
121 (defvar minibuffer-local-map
122   (let ((map (make-sparse-keymap 'minibuffer-local-map)))
123     map)
124   "Default keymap to use when reading from the minibuffer.")
125
126 (defvar minibuffer-local-completion-map
127   (let ((map (make-sparse-keymap 'minibuffer-local-completion-map)))
128     (set-keymap-parents map (list minibuffer-local-map))
129     map)
130   "Local keymap for minibuffer input with completion.")
131
132 (defvar minibuffer-local-must-match-map
133   (let ((map (make-sparse-keymap 'minibuffer-must-match-map)))
134     (set-keymap-parents map (list minibuffer-local-completion-map))
135     map)
136   "Local keymap for minibuffer input with completion, for exact match.")
137
138 ;; (define-key minibuffer-local-map "\C-g" 'abort-recursive-edit)
139 (define-key minibuffer-local-map "\C-g" 'minibuffer-keyboard-quit) ;; moved here from pending-del.el
140 (define-key minibuffer-local-map "\r" 'exit-minibuffer)
141 (define-key minibuffer-local-map "\n" 'exit-minibuffer)
142
143 ;; Historical crock.  Unused by anything but user code, if even that
144 ;(defvar minibuffer-local-ns-map
145 ;  (let ((map (make-sparse-keymap 'minibuffer-local-ns-map)))
146 ;    (set-keymap-parents map (list minibuffer-local-map))
147 ;    map)
148 ;  "Local keymap for the minibuffer when spaces are not allowed.")
149 ;(define-key minibuffer-local-ns-map [space] 'exit-minibuffer)
150 ;(define-key minibuffer-local-ns-map [tab] 'exit-minibuffer)
151 ;(define-key minibuffer-local-ns-map [?\?] 'self-insert-and-exit)
152
153 (define-key minibuffer-local-completion-map "\t" 'minibuffer-complete)
154 (define-key minibuffer-local-completion-map " " 'minibuffer-complete-word)
155 (define-key minibuffer-local-completion-map "?" 'minibuffer-completion-help)
156 (define-key minibuffer-local-must-match-map "\r" 'minibuffer-complete-and-exit)
157 (define-key minibuffer-local-must-match-map "\n" 'minibuffer-complete-and-exit)
158
159 (define-key minibuffer-local-map "\M-n" 'next-history-element)
160 (define-key minibuffer-local-map "\M-p" 'previous-history-element)
161 (define-key minibuffer-local-map '[next]  "\M-n")
162 (define-key minibuffer-local-map '[prior] "\M-p")
163 (define-key minibuffer-local-map "\M-r" 'previous-matching-history-element)
164 (define-key minibuffer-local-map "\M-s" 'next-matching-history-element)
165 (define-key minibuffer-local-must-match-map [next]
166   'next-complete-history-element)
167 (define-key minibuffer-local-must-match-map [prior]
168   'previous-complete-history-element)
169
170 ;; This is an experiment--make up and down arrows do history.
171 (define-key minibuffer-local-map [up] 'previous-history-element)
172 (define-key minibuffer-local-map [down] 'next-history-element)
173 (define-key minibuffer-local-completion-map [up] 'previous-history-element)
174 (define-key minibuffer-local-completion-map [down] 'next-history-element)
175 (define-key minibuffer-local-must-match-map [up] 'previous-history-element)
176 (define-key minibuffer-local-must-match-map [down] 'next-history-element)
177
178 (defvar read-expression-map (let ((map (make-sparse-keymap
179                                         'read-expression-map)))
180                               (set-keymap-parents map
181                                                   (list minibuffer-local-map))
182                               (define-key map "\M-\t" 'lisp-complete-symbol)
183                               map)
184   "Minibuffer keymap used for reading Lisp expressions.")
185
186 (defvar read-shell-command-map
187   (let ((map (make-sparse-keymap 'read-shell-command-map)))
188     (set-keymap-parents map (list minibuffer-local-map))
189     (define-key map "\t" 'comint-dynamic-complete)
190     (define-key map "\M-\t" 'comint-dynamic-complete)
191     (define-key map "\M-?" 'comint-dynamic-list-completions)
192     map)
193   "Minibuffer keymap used by shell-command and related commands.")
194
195 (defcustom use-dialog-box t
196   "*Variable controlling usage of the dialog box.
197 If nil, the dialog box will never be used, even in response to mouse events."
198   :type 'boolean
199   :group 'minibuffer)
200 \f
201 (defcustom minibuffer-electric-file-name-behavior t
202   "*If non-nil, slash and tilde in certain places cause immediate deletion.
203 These are the same places where this behavior would occur later on anyway,
204 in `substitute-in-file-name'."
205   :type 'boolean
206   :group 'minibuffer)
207
208 ;; originally by Stig@hackvan.com
209 (defun minibuffer-electric-separator ()
210   (interactive)
211   (let ((c last-command-char))
212     (and minibuffer-electric-file-name-behavior
213          (eq c directory-sep-char)
214          (eq c (char-before (point)))
215          (not (save-excursion
216               (goto-char (point-min))
217               (and (looking-at "/.+:~?[^/]*/.+")
218                    (re-search-forward "^/.+:~?[^/]*" nil t)
219                    (progn
220                      (delete-region (point) (point-max))
221                      t))))
222          (not (save-excursion
223                 (goto-char (point-min))
224                 (and (looking-at ".+://[^/]*/.+")
225                      (re-search-forward "^.+:/" nil t)
226                      (progn
227                        (delete-region (point) (point-max))
228                        t))))
229          ;; permit `//hostname/path/to/file'
230          (not (eq (point) (1+ (point-min))))
231          ;; permit `http://url/goes/here'
232          (or (not (eq ?: (char-after (- (point) 2))))
233              (eq ?/ (char-after (point-min))))
234        (delete-region (point-min) (point)))
235     (insert c)))
236
237 (defun minibuffer-electric-tilde ()
238   (interactive)
239   (and minibuffer-electric-file-name-behavior
240        (eq directory-sep-char (char-before (point)))
241        ;; permit URL's with //, for e.g. http://hostname/~user
242        (not (save-excursion (search-backward "//" nil t)))
243        (delete-region (point-min) (point)))
244   (insert ?~))
245
246
247 (defvar read-file-name-map
248   (let ((map (make-sparse-keymap 'read-file-name-map)))
249     (set-keymap-parents map (list minibuffer-local-completion-map))
250     (define-key map (vector directory-sep-char) 'minibuffer-electric-separator)
251     (define-key map "~" 'minibuffer-electric-tilde)
252     map
253     ))
254
255 (defvar read-file-name-must-match-map
256   (let ((map (make-sparse-keymap 'read-file-name-map)))
257     (set-keymap-parents map (list minibuffer-local-must-match-map))
258     (define-key map (vector directory-sep-char) 'minibuffer-electric-separator)
259     (define-key map "~" 'minibuffer-electric-tilde)
260     map
261     ))
262 \f
263 (defun minibuffer-keyboard-quit ()
264   "Abort recursive edit.
265 If `zmacs-regions' is true, and the zmacs region is active in this buffer,
266 then this key deactivates the region without beeping."
267   (interactive)
268   (if (and (region-active-p)
269            (eq (current-buffer) (zmacs-region-buffer)))
270       ;; pseudo-zmacs compatibility: don't beep if this ^G is simply
271       ;; deactivating the region.  If it is inactive, beep.
272       nil
273     (abort-recursive-edit)))
274 \f
275 ;;;; Guts of minibuffer invocation
276
277 ;;#### The only things remaining in C are
278 ;; "Vminibuf_prompt" and the display junk
279 ;;  "minibuf_prompt_width" and "minibuf_prompt_pix_width"
280 ;; Also "active_frame", though I suspect I could already
281 ;;   hack that in Lisp if I could make any sense of the
282 ;;   complete mess of frame/frame code in XEmacs.
283 ;; Vminibuf_prompt could easily be made Lisp-bindable.
284 ;;  I suspect that minibuf_prompt*_width are actually recomputed
285 ;;  by redisplay as needed -- or could be arranged to be so --
286 ;;  and that there could be need for read-minibuffer-internal to
287 ;;  save and restore them.
288 ;;#### The only other thing which read-from-minibuffer-internal does
289 ;;  which we can't presently do in Lisp is move the frame cursor
290 ;;  to the start of the minibuffer line as it returns.  This is
291 ;;  a rather nice touch and should be preserved -- probably by
292 ;;  providing some Lisp-level mechanism (extension to cursor-in-echo-area ?)
293 ;;  to effect it.
294
295
296 ;; Like reset_buffer in FSF's buffer.c
297 ;;  (Except that kill-all-local-variables doesn't nuke 'permanent-local
298 ;;   variables -- we preserve them, reset_buffer doesn't.)
299 (defun reset-buffer (buffer)
300   (with-current-buffer buffer
301     ;(if (fboundp 'unlock-buffer) (unlock-buffer))
302     (kill-all-local-variables)
303     (setq buffer-read-only nil)
304     ;; don't let read only text yanked into the minibuffer
305     ;; permanently wedge it.
306     (make-local-variable 'inhibit-read-only)
307     (setq inhibit-read-only t)
308     (erase-buffer)
309     ;(setq default-directory nil)
310     (setq buffer-file-name nil)
311     (setq buffer-file-truename nil)
312     (set-buffer-modified-p nil)
313     (setq buffer-backed-up nil)
314     (setq buffer-auto-save-file-name nil)
315     (set-buffer-dedicated-frame buffer nil)
316     buffer))
317
318 (defvar minibuffer-history-variable 'minibuffer-history
319   "History list symbol to add minibuffer values to.
320 Each minibuffer output is added with
321   (set minibuffer-history-variable
322        (cons STRING (symbol-value minibuffer-history-variable)))")
323 (defvar minibuffer-history-position)
324
325 ;; Added by hniksic:
326 (defvar initial-minibuffer-history-position)
327 (defvar current-minibuffer-contents)
328 (defvar current-minibuffer-point)
329
330 (defcustom minibuffer-history-minimum-string-length nil
331   "*If this variable is non-nil, a string will not be added to the
332 minibuffer history if its length is less than that value."
333   :type '(choice (const :tag "Any" nil)
334                  integer)
335   :group 'minibuffer)
336
337 (define-error 'input-error "Keyboard input error")
338
339 (put 'input-error 'display-error
340      #'(lambda (error-object stream)
341          (princ (cadr error-object) stream)))
342
343 (defun read-from-minibuffer (prompt &optional initial-contents
344                                     keymap
345                                     readp
346                                     history
347                                     abbrev-table)
348   "Read a string from the minibuffer, prompting with string PROMPT.
349 If optional second arg INITIAL-CONTENTS is non-nil, it is a string
350   to be inserted into the minibuffer before reading input.
351   If INITIAL-CONTENTS is (STRING . POSITION), the initial input
352   is STRING, but point is placed POSITION characters into the string.
353 Third arg KEYMAP is a keymap to use while reading;
354   if omitted or nil, the default is `minibuffer-local-map'.
355 If fourth arg READ is non-nil, then interpret the result as a lisp object
356   and return that object:
357   in other words, do `(car (read-from-string INPUT-STRING))'
358 Fifth arg HISTORY, if non-nil, specifies a history list
359   and optionally the initial position in the list.
360   It can be a symbol, which is the history list variable to use,
361   or it can be a cons cell (HISTVAR . HISTPOS).
362   In that case, HISTVAR is the history list variable to use,
363   and HISTPOS is the initial position (the position in the list
364   which INITIAL-CONTENTS corresponds to).
365   If HISTORY is `t', no history will be recorded.
366   Positions are counted starting from 1 at the beginning of the list.
367 Sixth arg ABBREV-TABLE, if non-nil, becomes the value of `local-abbrev-table'
368   in the minibuffer.
369
370 See also the variable completion-highlight-first-word-only for control over
371   completion display."
372   (if (and (not enable-recursive-minibuffers)
373            (> (minibuffer-depth) 0)
374            (eq (selected-window) (minibuffer-window)))
375       (error "Command attempted to use minibuffer while in minibuffer"))
376
377   (if (and minibuffer-max-depth
378            (> minibuffer-max-depth 0)
379            (>= (minibuffer-depth) minibuffer-max-depth))
380       (minibuffer-max-depth-exceeded))
381
382   ;; catch this error before the poor user has typed something...
383   (if history
384       (if (symbolp history)
385           (or (boundp history)
386               (error "History list %S is unbound" history))
387         (or (boundp (car history))
388             (error "History list %S is unbound" (car history)))))
389
390   (if (noninteractive)
391       (progn
392         ;; XEmacs in -batch mode calls minibuffer: print the prompt.
393         (message "%s" (gettext prompt))
394         ;;#### force-output
395
396         ;;#### Should this even be falling though to the code below?
397         ;;#### How does this stuff work now, anyway?
398         ))
399   (let* ((dir default-directory)
400          (owindow (selected-window))
401          (oframe (selected-frame))
402          (window (minibuffer-window))
403          (buffer (if (eq (minibuffer-depth) 0)
404                      (window-buffer window)
405                    (get-buffer-create (format " *Minibuf-%d"
406                                               (minibuffer-depth)))))
407          (frame (window-frame window))
408          (mconfig (if (eq frame (selected-frame))
409                       nil (current-window-configuration frame)))
410          (oconfig (current-window-configuration))
411          ;; dynamic scope sucks sucks sucks sucks sucks sucks.
412          ;; `M-x doctor' makes history a local variable, and thus
413          ;; our binding above is buffer-local and doesn't apply
414          ;; once we switch buffers!!!!  We demand better scope!
415          (_history_ history))
416     (unwind-protect
417          (progn
418            (set-buffer (reset-buffer buffer))
419            (setq default-directory dir)
420            (make-local-variable 'print-escape-newlines)
421            (setq print-escape-newlines t)
422            (make-local-variable 'current-minibuffer-contents)
423            (make-local-variable 'current-minibuffer-point)
424            (make-local-variable 'initial-minibuffer-history-position)
425            (setq current-minibuffer-contents ""
426                  current-minibuffer-point 1)
427            (if (not minibuffer-smart-completion-tracking-behavior)
428                nil
429              (make-local-variable 'mode-motion-hook)
430              (or mode-motion-hook
431                  ;;####disgusting
432                  (setq mode-motion-hook 'minibuffer-smart-mouse-tracker))
433              (make-local-variable 'mouse-track-click-hook)
434              (add-hook 'mouse-track-click-hook
435                        'minibuffer-smart-maybe-select-highlighted-completion))
436            (set-window-buffer window buffer)
437            (select-window window)
438            (set-window-hscroll window 0)
439            (buffer-enable-undo buffer)
440            (message nil)
441            (if initial-contents
442                (if (consp initial-contents)
443                    (progn
444                      (insert (car initial-contents))
445                      (goto-char (1+ (cdr initial-contents)))
446                      (setq current-minibuffer-contents (car initial-contents)
447                            current-minibuffer-point (cdr initial-contents)))
448                  (insert initial-contents)
449                  (setq current-minibuffer-contents initial-contents
450                        current-minibuffer-point (point))))
451            (use-local-map (help-keymap-with-help-key
452                            (or keymap minibuffer-local-map)
453                            minibuffer-help-form))
454            (let ((mouse-grabbed-buffer
455                   (and minibuffer-smart-completion-tracking-behavior
456                        (current-buffer)))
457                  (current-prefix-arg current-prefix-arg)
458 ;;                 (help-form minibuffer-help-form)
459                  (minibuffer-history-variable (cond ((not _history_)
460                                                      'minibuffer-history)
461                                                     ((consp _history_)
462                                                      (car _history_))
463                                                     (t
464                                                      _history_)))
465                  (minibuffer-history-position (cond ((consp _history_)
466                                                      (cdr _history_))
467                                                     (t
468                                                      0)))
469                  (minibuffer-scroll-window owindow))
470              (setq initial-minibuffer-history-position
471                    minibuffer-history-position)
472              (if abbrev-table
473                  (setq local-abbrev-table abbrev-table
474                        abbrev-mode t))
475              ;; This is now run from read-minibuffer-internal
476              ;(if minibuffer-setup-hook
477              ;    (run-hooks 'minibuffer-setup-hook))
478              ;(message nil)
479              (if (eq 't
480                      (catch 'exit
481                        (if (> (recursion-depth) (minibuffer-depth))
482                            (let ((standard-output t)
483                                  (standard-input t))
484                              (read-minibuffer-internal prompt))
485                            (read-minibuffer-internal prompt))))
486                  ;; Translate an "abort" (throw 'exit 't)
487                  ;;  into a real quit
488                  (signal 'quit '())
489                ;; return value
490                (let* ((val (progn (set-buffer buffer)
491                                   (if minibuffer-exit-hook
492                                       (run-hooks 'minibuffer-exit-hook))
493                                   (buffer-string)))
494                     (histval val)
495                       (err nil))
496                  (if readp
497                      (condition-case e
498                          (let ((v (read-from-string val)))
499                            (if (< (cdr v) (length val))
500                                (save-match-data
501                                  (or (string-match "[ \t\n]*\\'" val (cdr v))
502                                      (error "Trailing garbage following expression"))))
503                            (setq v (car v))
504                            ;; total total kludge
505                            (if (stringp v) (setq v (list 'quote v)))
506                            (setq val v))
507                        (end-of-file
508                         (setq err
509                               '(input-error "End of input before end of expression")))
510                        (error (setq err e))))
511                  ;; Add the value to the appropriate history list unless
512                  ;; it's already the most recent element, or it's only
513                  ;; two characters long.
514                  (if (and (symbolp minibuffer-history-variable)
515                           (boundp minibuffer-history-variable))
516                      (let ((list (symbol-value minibuffer-history-variable)))
517                        (or (eq list t)
518                            (null val)
519                            (and list (equal histval (car list)))
520                            (and (stringp val)
521                                 minibuffer-history-minimum-string-length
522                                 (< (length val)
523                                    minibuffer-history-minimum-string-length))
524                            (set minibuffer-history-variable
525                                 (if minibuffer-history-uniquify
526                                     (cons histval (remove histval list))
527                                   (cons histval list))))))
528                  (if err (signal (car err) (cdr err)))
529                  val))))
530       ;; stupid display code requires this for some reason
531       (set-buffer buffer)
532       (buffer-disable-undo buffer)
533       (setq buffer-read-only nil)
534       (erase-buffer)
535
536       ;; restore frame configurations
537       (if (and mconfig (frame-live-p oframe)
538                (eq frame (selected-frame)))
539           ;; if we changed frames (due to surrogate minibuffer),
540           ;; and we're still on the new frame, go back to the old one.
541           (select-frame oframe))
542       (if mconfig (set-window-configuration mconfig))
543       (set-window-configuration oconfig))))
544
545
546 (defun minibuffer-max-depth-exceeded ()
547   ;;
548   ;; This signals an error if an Nth minibuffer is invoked while N-1 are
549   ;; already active, whether the minibuffer window is selected or not.
550   ;; Since, under X, it's easy to jump out of the minibuffer (by doing M-x,
551   ;; getting distracted, and clicking elsewhere) many many novice users have
552   ;; had the problem of having multiple minibuffers build up, even to the
553   ;; point of exceeding max-lisp-eval-depth.  Since the variable
554   ;; enable-recursive-minibuffers historically/crockishly is only consulted
555   ;; when the minibuffer is currently active (like typing M-x M-x) it doesn't
556   ;; help in this situation.
557   ;;
558   ;; This routine also offers to edit .emacs for you to get rid of this
559   ;; complaint, like `disabled' commands do, since it's likely that non-novice
560   ;; users will be annoyed by this change, so we give them an easy way to get
561   ;; rid of it forever.
562   ;;
563   (beep t 'minibuffer-limit-exceeded)
564   (message
565    "Minibuffer already active: abort it with `^]', enable new one with `n': ")
566   (let ((char (let ((cursor-in-echo-area t)) ; #### doesn't always work??
567                 (read-char))))
568     (cond
569      ((eq char ?n)
570       (cond
571        ((y-or-n-p "Enable recursive minibuffers for other sessions too? ")
572         ;; This is completely disgusting, but it's basically what novice.el
573         ;; does.  This kind of thing should be generalized.
574         (setq minibuffer-max-depth nil)
575         (save-excursion
576           (set-buffer
577            (find-file-noselect
578             (substitute-in-file-name custom-file)))
579           (goto-char (point-min))
580           (if (re-search-forward
581                "^(setq minibuffer-max-depth \\([0-9]+\\|'?nil\\|'?()\\))\n"
582                nil t)
583               (delete-region (match-beginning 0 ) (match-end 0))
584             ;; Must have been disabled by default.
585             (goto-char (point-max)))
586           (insert"\n(setq minibuffer-max-depth nil)\n")
587           (save-buffer))
588         (message "Multiple minibuffers enabled")
589         (sit-for 1))))
590      ((eq char ?\1d)
591       (abort-recursive-edit))
592      (t
593       (error "Minibuffer already active")))))
594
595 \f
596 ;;;; Guts of minibuffer completion
597
598
599 ;; Used by minibuffer-do-completion
600 (defvar last-exact-completion)
601
602 (defun temp-minibuffer-message (m)
603   (let ((savemax (point-max)))
604     (save-excursion
605       (goto-char (point-max))
606       (message nil)
607       (insert m))
608     (let ((inhibit-quit t))
609       (sit-for 2)
610       (delete-region savemax (point-max))
611       ;;  If the user types a ^G while we're in sit-for, then quit-flag
612       ;;  gets set. In this case, we want that ^G to be interpreted
613       ;;  as a normal character, and act just like typeahead.
614       (if (and quit-flag (not unread-command-event))
615           (setq unread-command-event (character-to-event (quit-char))
616                 quit-flag nil)))))
617
618
619 ;; Determines whether buffer-string is an exact completion
620 (defun exact-minibuffer-completion-p (buffer-string)
621   (cond ((not minibuffer-completion-table)
622          ;; Empty alist
623          nil)
624         ((vectorp minibuffer-completion-table)
625          (let ((tem (intern-soft buffer-string
626                                  minibuffer-completion-table)))
627            (if (or tem
628                    (and (string-equal buffer-string "nil")
629                         ;; intern-soft loses for 'nil
630                         (catch 'found
631                           (mapatoms #'(lambda (s)
632                                         (if (string-equal
633                                              (symbol-name s)
634                                              buffer-string)
635                                             (throw 'found t)))
636                                     minibuffer-completion-table)
637                           nil)))
638                (if minibuffer-completion-predicate
639                    (funcall minibuffer-completion-predicate
640                             tem)
641                    t)
642                nil)))
643         ((and (consp minibuffer-completion-table)
644               ;;#### Emacs-Lisp truly sucks!
645               ;; lambda, autoload, etc
646               (not (symbolp (car minibuffer-completion-table))))
647          (if (not completion-ignore-case)
648              (assoc buffer-string minibuffer-completion-table)
649              (let ((s (upcase buffer-string))
650                    (tail minibuffer-completion-table)
651                    tem)
652                (while tail
653                  (setq tem (car (car tail)))
654                  (if (or (equal tem buffer-string)
655                          (equal tem s)
656                         (if tem (equal (upcase tem) s)))
657                      (setq s 'win
658                            tail nil)    ;exit
659                      (setq tail (cdr tail))))
660                (eq s 'win))))
661         (t
662          (funcall minibuffer-completion-table
663                   buffer-string
664                   minibuffer-completion-predicate
665                   'lambda)))
666   )
667
668 ;; 0 'none                 no possible completion
669 ;; 1 'unique               was already an exact and unique completion
670 ;; 3 'exact                was already an exact (but nonunique) completion
671 ;; NOT USED 'completed-exact-unique completed to an exact and completion
672 ;; 4 'completed-exact      completed to an exact (but nonunique) completion
673 ;; 5 'completed            some completion happened
674 ;; 6 'uncompleted          no completion happened
675 (defun minibuffer-do-completion-1 (buffer-string completion)
676   (cond ((not completion)
677          'none)
678         ((eq completion t)
679          ;; exact and unique match
680          'unique)
681         (t
682          ;; It did find a match.  Do we match some possibility exactly now?
683          (let ((completedp (not (string-equal completion buffer-string))))
684            (if completedp
685                (progn
686                  ;; Some completion happened
687                  (erase-buffer)
688                  (insert completion)
689                  (setq buffer-string completion)))
690            (if (exact-minibuffer-completion-p buffer-string)
691                ;; An exact completion was possible
692                (if completedp
693 ;; Since no callers need to know the difference, don't bother
694 ;;  with this (potentially expensive) discrimination.
695 ;;                 (if (eq (try-completion completion
696 ;;                                         minibuffer-completion-table
697 ;;                                         minibuffer-completion-predicate)
698 ;;                         't)
699 ;;                     'completed-exact-unique
700                        'completed-exact
701 ;;                     )
702                    'exact)
703                ;; Not an exact match
704                (if completedp
705                    'completed
706                    'uncompleted))))))
707
708
709 (defun minibuffer-do-completion (buffer-string)
710   (let* ((completion (try-completion buffer-string
711                                      minibuffer-completion-table
712                                      minibuffer-completion-predicate))
713          (status (minibuffer-do-completion-1 buffer-string completion))
714          (last last-exact-completion))
715     (setq last-exact-completion nil)
716     (cond ((eq status 'none)
717            ;; No completions
718            (ding nil 'no-completion)
719            (temp-minibuffer-message " [No match]"))
720           ((eq status 'unique)
721            )
722           (t
723            ;; It did find a match.  Do we match some possibility exactly now?
724            (if (not (string-equal completion buffer-string))
725                (progn
726                  ;; Some completion happened
727                  (erase-buffer)
728                  (insert completion)
729                  (setq buffer-string completion)))
730            (cond ((eq status 'exact)
731                   ;; If the last exact completion and this one were
732                   ;;  the same, it means we've already given a
733                   ;;  "Complete but not unique" message and that the
734                   ;;  user's hit TAB again, so now we give help.
735                   (setq last-exact-completion completion)
736                   (if (equal buffer-string last)
737                       (minibuffer-completion-help)))
738                  ((eq status 'uncompleted)
739                   (if completion-auto-help
740                       (minibuffer-completion-help)
741                       (temp-minibuffer-message " [Next char not unique]")))
742                  (t
743                   nil))))
744     status))
745
746 \f
747 ;;;; completing-read
748
749 (defun completing-read (prompt table
750                         &optional predicate require-match
751                                   initial-contents history)
752   "Read a string in the minibuffer, with completion.
753 Args: PROMPT, TABLE, PREDICATE, REQUIRE-MATCH, INITIAL-CONTENTS, HISTORY.
754 PROMPT is a string to prompt with; normally it ends in a colon and a space.
755 TABLE is an alist whose elements' cars are strings, or an obarray.
756 PREDICATE limits completion to a subset of TABLE.
757 See `try-completion' for more details on completion, TABLE, and PREDICATE.
758 If REQUIRE-MATCH is non-nil, the user is not allowed to exit unless
759  the input is (or completes to) an element of TABLE or is null.
760  If it is also not t, Return does not exit if it does non-null completion.
761 If INITIAL-CONTENTS is non-nil, insert it in the minibuffer initially.
762   If it is (STRING . POSITION), the initial input
763   is STRING, but point is placed POSITION characters into the string.
764 HISTORY, if non-nil, specifies a history list
765   and optionally the initial position in the list.
766   It can be a symbol, which is the history list variable to use,
767   or it can be a cons cell (HISTVAR . HISTPOS).
768   In that case, HISTVAR is the history list variable to use,
769   and HISTPOS is the initial position (the position in the list
770   which INITIAL-CONTENTS corresponds to).
771   If HISTORY is `t', no history will be recorded.
772   Positions are counted starting from 1 at the beginning of the list.
773 Completion ignores case if the ambient value of
774   `completion-ignore-case' is non-nil."
775   (let ((minibuffer-completion-table table)
776         (minibuffer-completion-predicate predicate)
777         (minibuffer-completion-confirm (if (eq require-match 't) nil t))
778         (last-exact-completion nil))
779     (read-from-minibuffer prompt
780                           initial-contents
781                           (if (not require-match)
782                               minibuffer-local-completion-map
783                               minibuffer-local-must-match-map)
784                           nil
785                           history)))
786
787 \f
788 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
789 ;;;;                   Minibuffer completion commands                   ;;;;
790 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
791
792
793 (defun minibuffer-complete ()
794   "Complete the minibuffer contents as far as possible.
795 Return nil if there is no valid completion, else t.
796 If no characters can be completed, display a list of possible completions.
797 If you repeat this command after it displayed such a list,
798 scroll the window of possible completions."
799   (interactive)
800   ;; If the previous command was not this, then mark the completion
801   ;;  buffer obsolete.
802   (or (eq last-command this-command)
803       (setq minibuffer-scroll-window nil))
804   (let ((window minibuffer-scroll-window))
805     (if (and window (windowp window) (window-buffer window)
806              (buffer-name (window-buffer window)))
807         ;; If there's a fresh completion window with a live buffer
808         ;;  and this command is repeated, scroll that window.
809         (let ((obuf (current-buffer)))
810           (unwind-protect
811               (progn
812                 (set-buffer (window-buffer window))
813                 (if (pos-visible-in-window-p (point-max) window)
814                     ;; If end is in view, scroll up to the beginning.
815                     (set-window-start window (point-min))
816                   ;; Else scroll down one frame.
817                   (scroll-other-window)))
818             (set-buffer obuf))
819           nil)
820       (let ((status (minibuffer-do-completion (buffer-string))))
821         (if (eq status 'none)
822             nil
823           (progn
824             (cond ((eq status 'unique)
825                    (temp-minibuffer-message
826                     " [Sole completion]"))
827                   ((eq status 'exact)
828                    (temp-minibuffer-message
829                     " [Complete, but not unique]")))
830             t))))))
831
832
833 (defun minibuffer-complete-and-exit ()
834   "Complete the minibuffer contents, and maybe exit.
835 Exit if the name is valid with no completion needed.
836 If name was completed to a valid match,
837 a repetition of this command will exit."
838   (interactive)
839   (if (= (point-min) (point-max))
840       ;; Crockishly allow user to specify null string
841       (throw 'exit nil))
842   (let ((buffer-string (buffer-string)))
843     ;; Short-cut -- don't call minibuffer-do-completion if we already
844     ;;  have an (possibly nonunique) exact completion.
845     (if (exact-minibuffer-completion-p buffer-string)
846         (throw 'exit nil))
847     (let ((status (minibuffer-do-completion buffer-string)))
848       (if (or (eq status 'unique)
849               (eq status 'exact)
850               (if (or (eq status 'completed-exact)
851                       (eq status 'completed-exact-unique))
852                   (if minibuffer-completion-confirm
853                       (progn (temp-minibuffer-message " [Confirm]")
854                              nil)
855                       t)))
856           (throw 'exit nil)))))
857
858
859 (defun self-insert-and-exit ()
860   "Terminate minibuffer input."
861   (interactive)
862   (self-insert-command 1)
863   (throw 'exit nil))
864
865 (defun exit-minibuffer ()
866   "Terminate this minibuffer argument.
867 If minibuffer-confirm-incomplete is true, and we are in a completing-read
868 of some kind, and the contents of the minibuffer is not an existing
869 completion, requires an additional RET before the minibuffer will be exited
870 \(assuming that RET was the character that invoked this command:
871 the character in question must be typed again)."
872   (interactive)
873   (if (not minibuffer-confirm-incomplete)
874       (throw 'exit nil))
875   (let ((buffer-string (buffer-string)))
876     (if (exact-minibuffer-completion-p buffer-string)
877         (throw 'exit nil))
878     (let ((completion (if (not minibuffer-completion-table)
879                           t
880                           (try-completion buffer-string
881                                           minibuffer-completion-table
882                                           minibuffer-completion-predicate))))
883       (if (or (eq completion 't)
884               ;; Crockishly allow user to specify null string
885               (string-equal buffer-string ""))
886           (throw 'exit nil))
887       (if completion ;; rewritten for I18N3 snarfing
888           (temp-minibuffer-message " [incomplete; confirm]")
889         (temp-minibuffer-message " [no completions; confirm]"))
890       (let ((event (let ((inhibit-quit t))
891                      (prog1
892                          (next-command-event)
893                        (setq quit-flag nil)))))
894         (cond ((equal event last-command-event)
895                (throw 'exit nil))
896               ((equal (quit-char) (event-to-character event))
897                ;; Minibuffer abort.
898                (throw 'exit t)))
899         (dispatch-event event)))))
900 \f
901 ;;;; minibuffer-complete-word
902
903
904 ;;;#### I think I have done this correctly; it certainly is simpler
905 ;;;#### than what the C code seemed to be trying to do.
906 (defun minibuffer-complete-word ()
907   "Complete the minibuffer contents at most a single word.
908 After one word is completed as much as possible, a space or hyphen
909 is added, provided that matches some possible completion.
910 Return nil if there is no valid completion, else t."
911   (interactive)
912   (let* ((buffer-string (buffer-string))
913          (completion (try-completion buffer-string
914                                      minibuffer-completion-table
915                                      minibuffer-completion-predicate))
916          (status (minibuffer-do-completion-1 buffer-string completion)))
917     (cond ((eq status 'none)
918            (ding nil 'no-completion)
919            (temp-minibuffer-message " [No match]")
920            nil)
921           ((eq status 'unique)
922            ;; New message, only in this new Lisp code
923            (temp-minibuffer-message " [Sole completion]")
924            t)
925           (t
926            (cond ((or (eq status 'uncompleted)
927                       (eq status 'exact))
928                   (let ((foo #'(lambda (s)
929                                  (condition-case nil
930                                      (if (try-completion
931                                           (concat buffer-string s)
932                                           minibuffer-completion-table
933                                           minibuffer-completion-predicate)
934                                          (progn
935                                            (goto-char (point-max))
936                                            (insert s)
937                                            t)
938                                        nil)
939                                    (error nil))))
940                         (char last-command-char))
941                     ;; Try to complete by adding a word-delimiter
942                     (or (and (characterp char) (> char 0)
943                              (funcall foo (char-to-string char)))
944                         (and (not (eq char ?\ ))
945                              (funcall foo " "))
946                         (and (not (eq char ?\-))
947                              (funcall foo "-"))
948                         (progn
949                           (if completion-auto-help
950                               (minibuffer-completion-help)
951                               ;; New message, only in this new Lisp code
952                             ;; rewritten for I18N3 snarfing
953                             (if (eq status 'exact)
954                                 (temp-minibuffer-message
955                                  " [Complete, but not unique]")
956                               (temp-minibuffer-message " [Ambiguous]")))
957                           nil))))
958                  (t
959                   (erase-buffer)
960                   (insert completion)
961                   ;; First word-break in stuff found by completion
962                   (goto-char (point-min))
963                   (let ((len (length buffer-string))
964                         n)
965                     (if (and (< len (length completion))
966                              (catch 'match
967                                (setq n 0)
968                                (while (< n len)
969                                  (if (char-equal
970                                        (upcase (aref buffer-string n))
971                                        (upcase (aref completion n)))
972                                      (setq n (1+ n))
973                                      (throw 'match nil)))
974                                t)
975                              (progn
976                                (goto-char (point-min))
977                                (forward-char len)
978                                (re-search-forward "\\W" nil t)))
979                         (delete-region (point) (point-max))
980                         (goto-char (point-max))))
981                   t))))))
982 \f
983 \f
984 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
985 ;;;;                      "Smart minibuffer" hackery                    ;;;;
986 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
987
988 ;;; ("Kludgy minibuffer hackery" is perhaps a better name)
989
990 ;; This works by setting `mouse-grabbed-buffer' to the minibuffer,
991 ;; defining button2 in the minibuffer keymap to
992 ;; `minibuffer-smart-select-highlighted-completion', and setting the
993 ;; mode-motion-hook of the minibuffer to `minibuffer-mouse-tracker'.
994 ;; By setting `mouse-grabbed-buffer', the minibuffer's keymap and
995 ;; mode-motion-hook apply (for mouse motion and presses) no matter
996 ;; what buffer the mouse is over.  Then, `minibuffer-mouse-tracker'
997 ;; examines the text under the mouse looking for something that looks
998 ;; like a completion, and causes it to be highlighted, and
999 ;; `minibuffer-smart-select-highlighted-completion' looks for a
1000 ;; flagged completion under the mouse and inserts it.  This has the
1001 ;; following advantages:
1002 ;;
1003 ;; -- filenames and such in any buffer can be inserted by clicking,
1004 ;;    not just completions
1005 ;;
1006 ;; but the following disadvantages:
1007 ;;
1008 ;; -- unless you're aware of the "filename in any buffer" feature,
1009 ;;    the fact that strings in arbitrary buffers get highlighted appears
1010 ;;    as a bug
1011 ;; -- mouse motion can cause ange-ftp actions -- bad bad bad.
1012 ;;
1013 ;; There's some hackery in minibuffer-mouse-tracker to try to avoid the
1014 ;; ange-ftp stuff, but it doesn't work.
1015 ;;
1016
1017 (defcustom minibuffer-smart-completion-tracking-behavior nil
1018   "*If non-nil, look for completions under mouse in all buffers.
1019 This allows you to click on something that looks like a completion
1020 and have it selected, regardless of what buffer it is in.
1021
1022 This is not enabled by default because
1023
1024 -- The \"mysterious\" highlighting in normal buffers is confusing to
1025    people not expecting it, and looks like a bug
1026 -- If ange-ftp is enabled, this tracking sometimes causes ange-ftp
1027    action as a result of mouse motion, which is *bad bad bad*.
1028    Hopefully this bug will be fixed at some point."
1029   :type 'boolean
1030   :group 'minibuffer)
1031
1032 (defun minibuffer-smart-mouse-tracker (event)
1033   ;; Used as the mode-motion-hook of the minibuffer window, which is the
1034   ;; value of `mouse-grabbed-buffer' while the minibuffer is active.  If
1035   ;; the word under the mouse is a valid minibuffer completion, then it
1036   ;; is highlighted.
1037   ;;
1038   ;; We do some special voodoo when we're reading a pathname, because
1039   ;; the way filename completion works is funny.  Possibly there's some
1040   ;; more general way this could be dealt with...
1041   ;;
1042   ;; We do some further voodoo when reading a pathname that is an
1043   ;; ange-ftp or efs path, because causing FTP activity as a result of
1044   ;; mouse motion is a really bad time.
1045   ;;
1046   (and minibuffer-smart-completion-tracking-behavior
1047        (event-point event)
1048        ;; avoid conflict with display-completion-list extents
1049        (not (extent-at (event-point event)
1050                        (event-buffer event)
1051                        'list-mode-item))
1052        (let ((filename-kludge-p (eq minibuffer-completion-table
1053                                     'read-file-name-internal)))
1054          (mode-motion-highlight-internal
1055           event
1056           #'(lambda () (default-mouse-track-beginning-of-word
1057                          (if filename-kludge-p 'nonwhite t)))
1058           #'(lambda ()
1059               (let ((p (point))
1060                     (string ""))
1061                 (default-mouse-track-end-of-word
1062                   (if filename-kludge-p 'nonwhite t))
1063                 (if (and (/= p (point)) minibuffer-completion-table)
1064                     (setq string (buffer-substring p (point))))
1065                 (if (string-match "\\`[ \t\n]*\\'" string)
1066                     (goto-char p)
1067                   (if filename-kludge-p
1068                       (setq string (minibuffer-smart-select-kludge-filename
1069                                     string)))
1070                   ;; try-completion bogusly returns a string even when
1071                   ;; that string is complete if that string is also a
1072                   ;; prefix for other completions.  This means that we
1073                   ;; can't just do the obvious thing, (eq t
1074                   ;; (try-completion ...)).
1075                   (let (comp)
1076                     (if (and filename-kludge-p
1077                              ;; #### evil evil evil evil
1078                              (or (and (fboundp 'ange-ftp-ftp-path)
1079                                       (ange-ftp-ftp-path string))
1080                                  (and (fboundp 'efs-ftp-path)
1081                                       (efs-ftp-path string))))
1082                         (setq comp t)
1083                       (setq comp
1084                             (try-completion string
1085                                             minibuffer-completion-table
1086                                             minibuffer-completion-predicate)))
1087                     (or (eq comp t)
1088                         (and (equal comp string)
1089                              (or (null minibuffer-completion-predicate)
1090                                  (stringp
1091                                   minibuffer-completion-predicate) ; ???
1092                                  (funcall minibuffer-completion-predicate
1093                                           (if (vectorp
1094                                                minibuffer-completion-table)
1095                                               (intern-soft
1096                                                string
1097                                                minibuffer-completion-table)
1098                                             string))))
1099                         (goto-char p))))))))))
1100
1101 (defun minibuffer-smart-select-kludge-filename (string)
1102   (save-excursion
1103     (set-buffer mouse-grabbed-buffer) ; the minibuf
1104     (let ((kludge-string (concat (buffer-string) string)))
1105       (if (or (and (fboundp 'ange-ftp-ftp-path)
1106                    (ange-ftp-ftp-path kludge-string))
1107                (and (fboundp 'efs-ftp-path) (efs-ftp-path kludge-string)))
1108            ;; #### evil evil evil, but more so.
1109            string
1110          (append-expand-filename (buffer-string) string)))))
1111
1112 (defun minibuffer-smart-select-highlighted-completion (event)
1113   "Select the highlighted text under the mouse as a minibuffer response.
1114 When the minibuffer is being used to prompt the user for a completion,
1115 any valid completions which are visible on the frame will highlight
1116 when the mouse moves over them.  Clicking \\<minibuffer-local-map>\
1117 \\[minibuffer-smart-select-highlighted-completion] will select the
1118 highlighted completion under the mouse.
1119
1120 If the mouse is clicked while not over a highlighted completion,
1121 then the global binding of \\[minibuffer-smart-select-highlighted-completion] \
1122 will be executed instead.  In this\nway you can get at the normal global \
1123 behavior of \\[minibuffer-smart-select-highlighted-completion] as well as
1124 the special minibuffer behavior."
1125   (interactive "e")
1126   (if minibuffer-smart-completion-tracking-behavior
1127       (minibuffer-smart-select-highlighted-completion-1 event t)
1128     (let ((command (lookup-key global-map
1129                                (vector current-mouse-event))))
1130       (if command (call-interactively command)))))
1131
1132 (defun minibuffer-smart-select-highlighted-completion-1 (event global-p)
1133   (let* ((filename-kludge-p (eq minibuffer-completion-table
1134                                 'read-file-name-internal))
1135          completion
1136          command-p
1137          (evpoint (event-point event))
1138          (evextent (and evpoint (extent-at evpoint (event-buffer event)
1139                                            'list-mode-item))))
1140     (if evextent
1141         ;; avoid conflict with display-completion-list extents.
1142         ;; if we find one, do that behavior instead.
1143         (list-mode-item-selected-1 evextent event)
1144       (save-excursion
1145         (let* ((buffer (window-buffer (event-window event)))
1146                (p (event-point event))
1147                (extent (and p (extent-at p buffer 'mouse-face))))
1148           (set-buffer buffer)
1149           (if (not (and (extent-live-p extent)
1150                         (eq (extent-object extent) (current-buffer))
1151                         (not (extent-detached-p extent))))
1152               (setq command-p t)
1153             ;; ...else user has selected a highlighted completion.
1154             (setq completion
1155                   (buffer-substring (extent-start-position extent)
1156                                     (extent-end-position extent)))
1157             (if filename-kludge-p
1158                 (setq completion (minibuffer-smart-select-kludge-filename
1159                                   completion)))
1160             ;; remove the extent so that it's not hanging around in
1161             ;; *Completions*
1162             (detach-extent extent)
1163             (set-buffer mouse-grabbed-buffer)
1164             (erase-buffer)
1165             (insert completion))))
1166       ;; we need to execute the command or do the throw outside of the
1167       ;; save-excursion.
1168       (cond ((and command-p global-p)
1169              (let ((command (lookup-key global-map
1170                                         (vector current-mouse-event))))
1171                (if command
1172                    (call-interactively command)
1173                  (if minibuffer-completion-table
1174                      (error
1175                       "Highlighted words are valid completions.  You may select one.")
1176                    (error "no completions")))))
1177             ((not command-p)
1178              ;; things get confused if the minibuffer is terminated while
1179              ;; not selected.
1180              (select-window (minibuffer-window))
1181              (if (and filename-kludge-p (file-directory-p completion))
1182                  ;; if the user clicked middle on a directory name, display the
1183                  ;; files in that directory.
1184                  (progn
1185                    (goto-char (point-max))
1186                    (minibuffer-completion-help))
1187                ;; otherwise, terminate input
1188                (throw 'exit nil)))))))
1189
1190 (defun minibuffer-smart-maybe-select-highlighted-completion
1191   (event &optional click-count)
1192   "Like minibuffer-smart-select-highlighted-completion but does nothing if
1193 there is no completion (as opposed to executing the global binding).  Useful
1194 as the value of `mouse-track-click-hook'."
1195   (interactive "e")
1196   (minibuffer-smart-select-highlighted-completion-1 event nil))
1197
1198 (define-key minibuffer-local-map 'button2
1199   'minibuffer-smart-select-highlighted-completion)
1200
1201 \f
1202 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1203 ;;;;                         Minibuffer History                         ;;;;
1204 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1205
1206 (defvar minibuffer-history '()
1207   "Default minibuffer history list.
1208 This is used for all minibuffer input except when an alternate history
1209 list is specified.")
1210
1211 ;; Some other history lists:
1212 ;;
1213 (defvar minibuffer-history-search-history '())
1214 (defvar function-history '())
1215 (defvar variable-history '())
1216 (defvar buffer-history '())
1217 (defvar shell-command-history '())
1218 (defvar file-name-history '())
1219
1220 (defvar read-expression-history nil)
1221
1222 (defvar minibuffer-history-sexp-flag nil ;weird FSF Emacs kludge
1223   "Non-nil when doing history operations on `command-history'.
1224 More generally, indicates that the history list being acted on
1225 contains expressions rather than strings.")
1226
1227 (defun previous-matching-history-element (regexp n)
1228   "Find the previous history element that matches REGEXP.
1229 \(Previous history elements refer to earlier actions.)
1230 With prefix argument N, search for Nth previous match.
1231 If N is negative, find the next or Nth next match."
1232   (interactive
1233    (let ((enable-recursive-minibuffers t)
1234          (minibuffer-history-sexp-flag nil))
1235      (if (eq 't (symbol-value minibuffer-history-variable))
1236          (error "History is not being recorded in this context"))
1237      (list (read-from-minibuffer "Previous element matching (regexp): "
1238                                  (car minibuffer-history-search-history)
1239                                  minibuffer-local-map
1240                                  nil
1241                                  'minibuffer-history-search-history)
1242            (prefix-numeric-value current-prefix-arg))))
1243   (let ((history (symbol-value minibuffer-history-variable))
1244         prevpos
1245         (pos minibuffer-history-position))
1246     (if (eq history t)
1247         (error "History is not being recorded in this context"))
1248     (while (/= n 0)
1249       (setq prevpos pos)
1250       (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1251       (if (= pos prevpos)
1252           (if (= pos 1) ;; rewritten for I18N3 snarfing
1253               (error "No later matching history item")
1254             (error "No earlier matching history item")))
1255       (if (string-match regexp
1256                         (if minibuffer-history-sexp-flag
1257                             (let ((print-level nil))
1258                               (prin1-to-string (nth (1- pos) history)))
1259                             (nth (1- pos) history)))
1260           (setq n (+ n (if (< n 0) 1 -1)))))
1261     (setq minibuffer-history-position pos)
1262     (setq current-minibuffer-contents (buffer-string)
1263           current-minibuffer-point (point))
1264     (erase-buffer)
1265     (let ((elt (nth (1- pos) history)))
1266       (insert (if minibuffer-history-sexp-flag
1267                   (let ((print-level nil))
1268                     (prin1-to-string elt))
1269                   elt)))
1270       (goto-char (point-min)))
1271   (if (or (eq (car (car command-history)) 'previous-matching-history-element)
1272           (eq (car (car command-history)) 'next-matching-history-element))
1273       (setq command-history (cdr command-history))))
1274
1275 (defun next-matching-history-element (regexp n)
1276   "Find the next history element that matches REGEXP.
1277 \(The next history element refers to a more recent action.)
1278 With prefix argument N, search for Nth next match.
1279 If N is negative, find the previous or Nth previous match."
1280   (interactive
1281    (let ((enable-recursive-minibuffers t)
1282          (minibuffer-history-sexp-flag nil))
1283      (if (eq t (symbol-value minibuffer-history-variable))
1284          (error "History is not being recorded in this context"))
1285      (list (read-from-minibuffer "Next element matching (regexp): "
1286                                  (car minibuffer-history-search-history)
1287                                  minibuffer-local-map
1288                                  nil
1289                                  'minibuffer-history-search-history)
1290            (prefix-numeric-value current-prefix-arg))))
1291   (previous-matching-history-element regexp (- n)))
1292
1293 (defun next-history-element (n)
1294   "Insert the next element of the minibuffer history into the minibuffer."
1295   (interactive "p")
1296   (if (eq 't (symbol-value minibuffer-history-variable))
1297       (error "History is not being recorded in this context"))
1298   (unless (zerop n)
1299     (when (eq minibuffer-history-position
1300               initial-minibuffer-history-position)
1301       (setq current-minibuffer-contents (buffer-string)
1302             current-minibuffer-point (point)))
1303     (let ((narg (- minibuffer-history-position n))
1304           (minimum (if minibuffer-default -1 0)))
1305       (cond ((< narg minimum)
1306              (error "No following item in %s" minibuffer-history-variable))
1307             ((> narg (length (symbol-value minibuffer-history-variable)))
1308              (error "No preceding item in %s" minibuffer-history-variable)))
1309       (erase-buffer)
1310       (setq minibuffer-history-position narg)
1311       (if (eq narg initial-minibuffer-history-position)
1312           (progn
1313             (insert current-minibuffer-contents)
1314             (goto-char current-minibuffer-point))
1315         (let ((elt (if (>= narg 0)
1316                        (nth (1- minibuffer-history-position)
1317                             (symbol-value minibuffer-history-variable))
1318                      minibuffer-default)))
1319           (insert
1320            (if (not (stringp elt))
1321                (let ((print-level nil))
1322                  (condition-case nil
1323                      (let ((print-readably t)
1324                            (print-escape-newlines t))
1325                        (prin1-to-string elt))
1326                    (error (prin1-to-string elt))))
1327              elt)))
1328         ;; FSF has point-min here.
1329         (goto-char (point-max))))))
1330
1331 (defun previous-history-element (n)
1332   "Insert the previous element of the minibuffer history into the minibuffer."
1333   (interactive "p")
1334   (next-history-element (- n)))
1335
1336 (defun next-complete-history-element (n)
1337   "Get next element of history which is a completion of minibuffer contents."
1338   (interactive "p")
1339   (let ((point-at-start (point)))
1340     (next-matching-history-element
1341      (concat "^" (regexp-quote (buffer-substring (point-min) (point)))) n)
1342     ;; next-matching-history-element always puts us at (point-min).
1343     ;; Move to the position we were at before changing the buffer contents.
1344     ;; This is still sensical, because the text before point has not changed.
1345     (goto-char point-at-start)))
1346
1347 (defun previous-complete-history-element (n)
1348   "Get previous element of history which is a completion of minibuffer contents."
1349   (interactive "p")
1350   (next-complete-history-element (- n)))
1351
1352 \f
1353 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1354 ;;;;                reading various things from a minibuffer            ;;;;
1355 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1356
1357 (defun read-expression (prompt &optional initial-contents history)
1358   "Return a Lisp object read using the minibuffer.
1359 Prompt with PROMPT.  If non-nil, optional second arg INITIAL-CONTENTS
1360 is a string to insert in the minibuffer before reading.
1361 Third arg HISTORY, if non-nil, specifies a history list."
1362   (let ((minibuffer-history-sexp-flag t)
1363         ;; Semi-kludge to get around M-x C-x o M-ESC trying to do completion.
1364         (minibuffer-completion-table nil))
1365     (read-from-minibuffer prompt
1366                           initial-contents
1367                           read-expression-map
1368                           t
1369                           (or history 'read-expression-history)
1370                           lisp-mode-abbrev-table)))
1371
1372 (defun read-string (prompt &optional initial-contents history)
1373   "Return a string from the minibuffer, prompting with string PROMPT.
1374 If non-nil, optional second arg INITIAL-CONTENTS is a string to insert
1375 in the minibuffer before reading.
1376 Third arg HISTORY, if non-nil, specifies a history list."
1377   (let ((minibuffer-completion-table nil))
1378     (read-from-minibuffer prompt
1379                           initial-contents
1380                           minibuffer-local-map
1381                           nil history)))
1382
1383 (defun eval-minibuffer (prompt &optional initial-contents history)
1384   "Return value of Lisp expression read using the minibuffer.
1385 Prompt with PROMPT.  If non-nil, optional second arg INITIAL-CONTENTS
1386 is a string to insert in the minibuffer before reading.
1387 Third arg HISTORY, if non-nil, specifies a history list."
1388   (eval (read-expression prompt initial-contents history)))
1389
1390 ;; The name `command-history' is already taken
1391 (defvar read-command-history '())
1392
1393 (defun read-command (prompt)
1394   "Read the name of a command and return as a symbol.
1395 Prompts with PROMPT."
1396   (intern (completing-read prompt obarray 'commandp t nil
1397                            ;; 'command-history is not right here: that's a
1398                            ;; list of evalable forms, not a history list.
1399                            'read-command-history
1400                            )))
1401
1402 (defun read-function (prompt)
1403   "Read the name of a function and return as a symbol.
1404 Prompts with PROMPT."
1405   (intern (completing-read prompt obarray 'fboundp t nil
1406                            'function-history)))
1407
1408 (defun read-variable (prompt)
1409   "Read the name of a user variable and return it as a symbol.
1410 Prompts with PROMPT.
1411 A user variable is one whose documentation starts with a `*' character."
1412   (intern (completing-read prompt obarray 'user-variable-p t nil
1413                            'variable-history)))
1414
1415 (defun read-buffer (prompt &optional default require-match)
1416   "Read the name of a buffer and return as a string.
1417 Prompts with PROMPT.  Optional second arg DEFAULT is value to return if user
1418 enters an empty line.  If optional third arg REQUIRE-MATCH is non-nil,
1419 only existing buffer names are allowed."
1420   (let ((prompt (if default
1421                     (format "%s(default %s) "
1422                             (gettext prompt) (if (bufferp default)
1423                                                  (buffer-name default)
1424                                                default))
1425                     prompt))
1426         (alist (mapcar #'(lambda (b) (cons (buffer-name b) b))
1427                        (buffer-list)))
1428         result)
1429     (while (progn
1430              (setq result (completing-read prompt alist nil require-match
1431                                            nil 'buffer-history))
1432              (cond ((not (equal result ""))
1433                     nil)
1434                    ((not require-match)
1435                     (setq result default)
1436                     nil)
1437                    ((not default)
1438                     t)
1439                    ((not (get-buffer default))
1440                     t)
1441                    (t
1442                     (setq result default)
1443                     nil))))
1444     (if (bufferp result)
1445         (buffer-name result)
1446       result)))
1447
1448 (defun read-number (prompt &optional integers-only)
1449   "Read a number from the minibuffer."
1450   (let ((pred (if integers-only 'integerp 'numberp))
1451         num)
1452     (while (not (funcall pred num))
1453       (setq num (condition-case ()
1454                     (let ((minibuffer-completion-table nil))
1455                       (read-from-minibuffer
1456                        prompt (if num (prin1-to-string num)) nil t
1457                        t)) ;no history
1458                   (input-error nil)
1459                   (invalid-read-syntax nil)
1460                   (end-of-file nil)))
1461       (or (funcall pred num) (beep)))
1462     num))
1463
1464 (defun read-shell-command (prompt &optional initial-input history)
1465   "Just like read-string, but uses read-shell-command-map:
1466 \\{read-shell-command-map}"
1467   (let ((minibuffer-completion-table nil))
1468     (read-from-minibuffer prompt initial-input read-shell-command-map
1469                           nil (or history 'shell-command-history))))
1470
1471 \f
1472 ;;; This read-file-name stuff probably belongs in files.el
1473
1474 ;; Quote "$" as "$$" to get it past substitute-in-file-name
1475 (defun un-substitute-in-file-name (string)
1476   (let ((regexp "\\$")
1477         (olen (length string))
1478         new
1479         n o ch)
1480     (if (not (string-match regexp string))
1481         string
1482       (setq n 1)
1483       (while (string-match regexp string (match-end 0))
1484         (setq n (1+ n)))
1485       (setq new (make-string (+ olen n) ?$))
1486       (setq n 0 o 0)
1487       (while (< o olen)
1488         (setq ch (aref string o))
1489         (aset new n ch)
1490         (setq o (1+ o) n (1+ n))
1491         (if (eq ch ?$)
1492             ;; already aset by make-string initial-value
1493             (setq n (1+ n))))
1494       new)))
1495
1496 (defun read-file-name-2 (history prompt dir default
1497                                  must-match initial-contents
1498                                  completer)
1499   (if (not dir)
1500       (setq dir default-directory))
1501   (setq dir (abbreviate-file-name dir t))
1502   (let* ((insert (cond ((and (not insert-default-directory)
1503                              (not initial-contents))
1504                         "")
1505                        (initial-contents
1506                         (cons (un-substitute-in-file-name
1507                                (concat dir initial-contents))
1508                               (length dir)))
1509                        (t
1510                         (un-substitute-in-file-name dir))))
1511          (val 
1512                 ;;  Hateful, broken, case-sensitive un*x
1513 ;;;                 (completing-read prompt
1514 ;;;                                  completer
1515 ;;;                                  dir
1516 ;;;                                  must-match
1517 ;;;                                  insert
1518 ;;;                                  history)
1519           ;; #### - this is essentially the guts of completing read.
1520           ;; There should be an elegant way to pass a pair of keymaps to
1521           ;; completing read, but this will do for now.  All sins are
1522           ;; relative.  --Stig
1523           (let ((minibuffer-completion-table completer)
1524                 (minibuffer-completion-predicate dir)
1525                 (minibuffer-completion-confirm (if (eq must-match 't)
1526                                                    nil t))
1527                 (last-exact-completion nil))
1528             (read-from-minibuffer prompt
1529                                   insert
1530                                   (if (not must-match)
1531                                       read-file-name-map
1532                                     read-file-name-must-match-map)
1533                                   nil
1534                                   history))
1535               ))
1536 ;;;     ;; Kludge!  Put "/foo/bar" on history rather than "/default//foo/bar"
1537 ;;;     (let ((hist (cond ((not history) 'minibuffer-history)
1538 ;;;                       ((consp history) (car history))
1539 ;;;                       (t history))))
1540 ;;;       (if (and val
1541 ;;;                hist
1542 ;;;                (not (eq hist 't))
1543 ;;;                (boundp hist)
1544 ;;;                (equal (car-safe (symbol-value hist)) val))
1545 ;;;           (let ((e (condition-case nil
1546 ;;;                        (expand-file-name val)
1547 ;;;                      (error nil))))
1548 ;;;             (if (and e (not (equal e val)))
1549 ;;;                 (set hist (cons e (cdr (symbol-value hist))))))))
1550
1551     (cond ((not val)
1552            (error "No file name specified"))
1553           ((and default
1554                 (equal val (if (consp insert) (car insert) insert)))
1555            default)
1556           (t
1557            (substitute-in-file-name val)))))
1558
1559 ;; #### this function should use minibuffer-completion-table
1560 ;; or something.  But that is sloooooow.
1561 ;; #### all this shit needs better documentation!!!!!!!!
1562 (defun read-file-name-activate-callback (event extent dir-p)
1563   ;; used as the activate-callback of the filename list items
1564   ;; in the completion buffer, in place of default-choose-completion.
1565   ;; if a regular file was selected, we call default-choose-completion
1566   ;; (which just inserts the string in the minibuffer and calls
1567   ;; exit-minibuffer).  If a directory was selected, we display
1568   ;; the contents of the directory.
1569   (let* ((file (extent-string extent))
1570          (completion-buf (extent-object extent))
1571          (minibuf (symbol-value-in-buffer 'completion-reference-buffer
1572                                           completion-buf))
1573          (in-dir (file-name-directory (buffer-substring nil nil minibuf)))
1574          (full (expand-file-name file in-dir)))
1575     (if (not (file-directory-p full))
1576         (default-choose-completion event extent minibuf)
1577       (erase-buffer minibuf)
1578       (insert-string (file-name-as-directory
1579                       (abbreviate-file-name full t)) minibuf)
1580       (reset-buffer completion-buf)
1581       (let ((standard-output completion-buf))
1582         (display-completion-list
1583          (delete "." (directory-files full nil nil nil (if dir-p 'directory)))
1584          :user-data dir-p
1585          :reference-buffer minibuf
1586          :activate-callback 'read-file-name-activate-callback)
1587         (goto-char (point-min) completion-buf)))))
1588
1589 (defun read-file-name-1 (history prompt dir default
1590                                  must-match initial-contents
1591                                  completer)
1592   (if (should-use-dialog-box-p)
1593       ;; this calls read-file-name-2
1594       (mouse-read-file-name-1 history prompt dir default must-match
1595                               initial-contents completer)
1596     (let ((rfhookfun
1597            (lambda ()
1598              ;; #### SCREAM!  Create a `file-system-ignore-case'
1599              ;; function, so this kind of stuff is generalized!
1600              (and (eq system-type 'windows-nt)
1601                   (set (make-local-variable 'completion-ignore-case) t))
1602              (set
1603               (make-local-variable
1604                'completion-display-completion-list-function)
1605               #'(lambda (completions)
1606                   (display-completion-list
1607                    completions
1608                    :user-data (not (eq completer 'read-file-name-internal))
1609                    :activate-callback
1610                    'read-file-name-activate-callback)))
1611              ;; kludge!
1612              (remove-hook 'minibuffer-setup-hook rfhookfun)
1613              )))
1614       (unwind-protect
1615           (progn
1616             (add-hook 'minibuffer-setup-hook rfhookfun)
1617             (read-file-name-2 history prompt dir default must-match
1618                               initial-contents completer))
1619         (remove-hook 'minibuffer-setup-hook rfhookfun)))))
1620
1621 (defun read-file-name (prompt
1622                        &optional dir default must-match initial-contents
1623                        history)
1624   "Read file name, prompting with PROMPT and completing in directory DIR.
1625 This will prompt with a dialog box if appropriate, according to
1626  `should-use-dialog-box-p'.
1627 Value is not expanded---you must call `expand-file-name' yourself.
1628 Value is subject to interpreted by substitute-in-file-name however.
1629 Default name to DEFAULT if user enters a null string.
1630  (If DEFAULT is omitted, the visited file name is used,
1631   except that if INITIAL-CONTENTS is specified, that combined with DIR is
1632   used.)
1633 Fourth arg MUST-MATCH non-nil means require existing file's name.
1634  Non-nil and non-t means also require confirmation after completion.
1635 Fifth arg INITIAL-CONTENTS specifies text to start with.
1636 Sixth arg HISTORY specifies the history list to use.  Default is
1637  `file-name-history'.
1638 DIR defaults to current buffer's directory default."
1639   (read-file-name-1
1640    (or history 'file-name-history)
1641    prompt dir (or default
1642                   (if initial-contents (expand-file-name initial-contents dir)
1643                     buffer-file-name))
1644    must-match initial-contents
1645    ;; A separate function (not an anonymous lambda-expression)
1646    ;; and passed as a symbol because of disgusting kludges in various
1647    ;; places which do stuff like (let ((filename-kludge-p (eq minibuffer-completion-table 'read-file-name-internal))) ...)
1648    'read-file-name-internal))
1649
1650 (defun read-directory-name (prompt
1651                             &optional dir default must-match initial-contents
1652                             history)
1653   "Read directory name, prompting with PROMPT and completing in directory DIR.
1654 This will prompt with a dialog box if appropriate, according to
1655  `should-use-dialog-box-p'.
1656 Value is not expanded---you must call `expand-file-name' yourself.
1657 Value is subject to interpreted by substitute-in-file-name however.
1658 Default name to DEFAULT if user enters a null string.
1659  (If DEFAULT is omitted, the current buffer's default directory is used.)
1660 Fourth arg MUST-MATCH non-nil means require existing directory's name.
1661  Non-nil and non-t means also require confirmation after completion.
1662 Fifth arg INITIAL-CONTENTS specifies text to start with.
1663 Sixth arg HISTORY specifies the history list to use.  Default is
1664  `file-name-history'.
1665 DIR defaults to current buffer's directory default."
1666   (read-file-name-1
1667     (or history 'file-name-history)
1668     prompt dir (or default default-directory) must-match initial-contents
1669     'read-directory-name-internal))
1670
1671
1672 ;; Environment-variable and ~username completion hack
1673 (defun read-file-name-internal-1 (string dir action completer)
1674   (if (not (string-match
1675             "\\([^$]\\|\\`\\)\\(\\$\\$\\)*\\$\\([A-Za-z0-9_]*\\|{[^}]*\\)\\'"
1676             string))
1677       ;; Not doing environment-variable completion hack
1678       (let* ((orig (if (equal string "") nil string))
1679              (sstring (if orig (substitute-in-file-name string) string))
1680              (specdir (if orig (file-name-directory sstring) nil))
1681              (name    (if orig (file-name-nondirectory sstring) string))
1682              (direct  (if specdir (expand-file-name specdir dir) dir)))
1683         ;; ~username completion
1684         (if (and (fboundp 'user-name-completion-1)
1685                  (string-match "^[~]" name))
1686             (let ((user (substring name 1)))
1687               (cond ((eq action 'lambda)
1688                      (file-directory-p name))
1689                     ((eq action 't)
1690                      ;; all completions
1691                      (mapcar #'(lambda (p) (concat "~" p))
1692                              (user-name-all-completions user)))
1693                     (t;; 'nil
1694                      ;; complete
1695                      (let* ((val+uniq (user-name-completion-1 user))
1696                             (val  (car val+uniq))
1697                             (uniq (cdr val+uniq)))
1698                        (cond ((stringp val)
1699                               (if uniq
1700                                   (file-name-as-directory (concat "~" val))
1701                                 (concat "~" val)))
1702                              ((eq val t)
1703                               (file-name-as-directory name))
1704                              (t nil))))))
1705           (funcall completer
1706                    action
1707                    orig
1708                    sstring
1709                    specdir
1710                    direct
1711                    name)))
1712       ;; An odd number of trailing $'s
1713       (let* ((start (match-beginning 3))
1714              (env (substring string
1715                              (cond ((= start (length string))
1716                                     ;; "...$"
1717                                     start)
1718                                    ((= (aref string start) ?{)
1719                                     ;; "...${..."
1720                                     (1+ start))
1721                                    (t
1722                                     start))))
1723              (head (substring string 0 (1- start)))
1724              (alist #'(lambda ()
1725                         (mapcar #'(lambda (x)
1726                                     (cons (substring x 0 (string-match "=" x))
1727                                           nil))
1728                                 process-environment))))
1729
1730         (cond ((eq action 'lambda)
1731                nil)
1732               ((eq action 't)
1733                ;; all completions
1734                (mapcar #'(lambda (p)
1735                            (if (and (> (length p) 0)
1736                                     ;;#### Unix-specific
1737                                     ;;####  -- need absolute-pathname-p
1738                                     (/= (aref p 0) ?/))
1739                                (concat "$" p)
1740                              (concat head "$" p)))
1741                        (all-completions env (funcall alist))))
1742               (t ;; nil
1743                ;; complete
1744                (let* ((e (funcall alist))
1745                       (val (try-completion env e)))
1746                  (cond ((stringp val)
1747                         (if (string-match "[^A-Za-z0-9_]" val)
1748                             (concat head
1749                                     "${" val
1750                                     ;; completed uniquely?
1751                                     (if (eq (try-completion val e) 't)
1752                                         "}" ""))
1753                             (concat head "$" val)))
1754                        ((eql val 't)
1755                         (concat head
1756                                 (un-substitute-in-file-name (getenv env))))
1757                        (t nil))))))))
1758
1759
1760 (defun read-file-name-internal (string dir action)
1761   (read-file-name-internal-1
1762    string dir action
1763    #'(lambda (action orig string specdir dir name)
1764       (cond ((eq action 'lambda)
1765              (if (not orig)
1766                  nil
1767                (let ((sstring (condition-case nil
1768                                   (expand-file-name string)
1769                                 (error nil))))
1770                  (if (not sstring)
1771                      ;; Some pathname syntax error in string
1772                      nil
1773                      (file-exists-p sstring)))))
1774             ((eq action 't)
1775              ;; all completions
1776              (mapcar #'un-substitute-in-file-name
1777                      (file-name-all-completions name dir)))
1778             (t;; nil
1779              ;; complete
1780              (let* ((d (or dir default-directory))
1781                     (val (file-name-completion name d)))
1782                (if (and (eq val 't)
1783                         (not (null completion-ignored-extensions)))
1784                    ;;#### (file-name-completion "foo") returns 't
1785                    ;;   when both "foo" and "foo~" exist and the latter
1786                    ;;   is "pruned" by completion-ignored-extensions.
1787                    ;; I think this is a bug in file-name-completion.
1788                    (setq val (let ((completion-ignored-extensions '()))
1789                                (file-name-completion name d))))
1790                (if (stringp val)
1791                    (un-substitute-in-file-name (if specdir
1792                                                    (concat specdir val)
1793                                                    val))
1794                    (let ((tem (un-substitute-in-file-name string)))
1795                      (if (not (equal tem orig))
1796                          ;; substitute-in-file-name did something
1797                          tem
1798                          val)))))))))
1799
1800 (defun read-directory-name-internal (string dir action)
1801   (read-file-name-internal-1
1802    string dir action
1803    #'(lambda (action orig string specdir dir name)
1804       (let* ((dirs #'(lambda (fn)
1805                        (let ((l (if (equal name "")
1806                                     (directory-files
1807                                      dir
1808                                      nil
1809                                      ""
1810                                      nil
1811                                      'directories)
1812                                   (directory-files
1813                                    dir
1814                                    nil
1815                                    (concat "\\`" (regexp-quote name))
1816                                    nil
1817                                    'directories))))
1818                          (mapcar fn
1819                                  ;; Wretched unix
1820                                  (delete "." l))))))
1821         (cond ((eq action 'lambda)
1822                ;; complete?
1823                (if (not orig)
1824                    nil
1825                  (file-directory-p string)))
1826               ((eq action 't)
1827                ;; all completions
1828                (funcall dirs #'(lambda (n)
1829                                  (un-substitute-in-file-name
1830                                   (file-name-as-directory n)))))
1831               (t
1832                ;; complete
1833                (let ((val (try-completion
1834                            name
1835                            (funcall dirs
1836                                     #'(lambda (n)
1837                                         (list (file-name-as-directory
1838                                                n)))))))
1839                  (if (stringp val)
1840                      (un-substitute-in-file-name (if specdir
1841                                                      (concat specdir val)
1842                                                    val))
1843                    (let ((tem (un-substitute-in-file-name string)))
1844                      (if (not (equal tem orig))
1845                          ;; substitute-in-file-name did something
1846                          tem
1847                        val))))))))))
1848
1849 (defun append-expand-filename (file-string string)
1850   "Append STRING to FILE-STRING differently depending on whether STRING
1851 is a username (~string), an environment variable ($string),
1852 or a filename (/string).  The resultant string is returned with the
1853 environment variable or username expanded and resolved to indicate
1854 whether it is a file(/result) or a directory (/result/)."
1855   (let ((file
1856          (cond ((string-match "\\([~$]\\)\\([^~$/]*\\)$" file-string)
1857                 (cond ((string= (substring file-string
1858                                            (match-beginning 1)
1859                                            (match-end 1)) "~")
1860                        (concat (substring file-string 0 (match-end 1))
1861                                string))
1862                       (t (substitute-in-file-name
1863                           (concat (substring file-string 0 (match-end 1))
1864                                   string)))))
1865                (t (concat (file-name-directory
1866                            (substitute-in-file-name file-string)) string))))
1867         result)
1868
1869     (cond ((stringp (setq result (and (file-exists-p (expand-file-name file))
1870                                       (read-file-name-internal
1871                                        (condition-case nil
1872                                            (expand-file-name file)
1873                                          (error file))
1874                                        "" nil))))
1875            result)
1876           (t file))))
1877
1878 (defun mouse-file-display-completion-list (window dir minibuf user-data)
1879   (let ((standard-output (window-buffer window)))
1880     (condition-case nil
1881         (display-completion-list
1882          (directory-files dir nil nil nil t)
1883          :window-width (* 2 (window-width window))
1884          :activate-callback
1885          'mouse-read-file-name-activate-callback
1886          :user-data user-data
1887          :reference-buffer minibuf
1888          :help-string "")
1889       (t nil))))
1890
1891 (defun mouse-directory-display-completion-list (window dir minibuf user-data)
1892   (let ((standard-output (window-buffer window)))
1893     (condition-case nil
1894         (display-completion-list
1895          (delete "." (directory-files dir nil nil nil 1))
1896          :window-width (window-width window)
1897          :activate-callback
1898          'mouse-read-file-name-activate-callback
1899          :user-data user-data
1900          :reference-buffer minibuf
1901          :help-string "")
1902       (t nil))))
1903
1904 (defun mouse-read-file-name-activate-callback (event extent user-data)
1905   (let* ((file (extent-string extent))
1906          (minibuf (symbol-value-in-buffer 'completion-reference-buffer
1907                                           (extent-object extent)))
1908          (in-dir (buffer-substring nil nil minibuf))
1909          (full (expand-file-name file in-dir))
1910          (filebuf (nth 0 user-data))
1911          (dirbuff (nth 1 user-data))
1912          (filewin (nth 2 user-data))
1913          (dirwin (nth 3 user-data)))
1914     (if (file-regular-p full)
1915         (default-choose-completion event extent minibuf)
1916       (erase-buffer minibuf)
1917       (insert-string (file-name-as-directory
1918                       (abbreviate-file-name full t)) minibuf)
1919       (reset-buffer filebuf)
1920       (if (not dirbuff)
1921           (mouse-directory-display-completion-list filewin full minibuf
1922                                                    user-data)
1923         (mouse-file-display-completion-list filewin full minibuf user-data)
1924         (reset-buffer dirbuff)
1925         (mouse-directory-display-completion-list dirwin full minibuf
1926                                                  user-data)))))
1927
1928 ;; this is rather cheesified but gets the job done.
1929 (defun mouse-read-file-name-1 (history prompt dir default
1930                                  must-match initial-contents
1931                                  completer)
1932   (let* ((file-p (eq 'read-file-name-internal completer))
1933          (filebuf (get-buffer-create "*Completions*"))
1934          (dirbuff (and file-p (generate-new-buffer " *mouse-read-file*")))
1935          (butbuff (generate-new-buffer " *mouse-read-file*"))
1936          (frame (make-dialog-frame))
1937          filewin dirwin
1938          user-data)
1939     (unwind-protect
1940         (progn
1941           (reset-buffer filebuf)
1942           (select-frame frame)
1943           (let ((window-min-height 1))
1944             ;; #### should be 2 not 3, but that causes
1945             ;; "window too small to split" errors for some
1946             ;; people (but not for me ...) There's a more
1947             ;; fundamental bug somewhere.
1948             (split-window nil (- (frame-height frame) 3)))
1949           (if file-p
1950               (progn
1951                 (split-window-horizontally 16)
1952                 (setq filewin (frame-rightmost-window frame)
1953                       dirwin (frame-leftmost-window frame))
1954                 (set-window-buffer filewin filebuf)
1955                 (set-window-buffer dirwin dirbuff))
1956             (setq filewin (frame-highest-window frame))
1957             (set-window-buffer filewin filebuf))
1958           (setq user-data (list filebuf dirbuff filewin dirwin))
1959           (set-window-buffer (frame-lowest-window frame) butbuff)
1960           (set-buffer butbuff)
1961           (when dir
1962             (setq default-directory dir))
1963           (when (featurep 'scrollbar)
1964             (set-specifier scrollbar-width 0 butbuff))
1965           (insert "                 ")
1966           (insert-gui-button (make-gui-button "OK"
1967                                               (lambda (foo)
1968                                                 (exit-minibuffer))))
1969           (insert "                 ")
1970           (insert-gui-button (make-gui-button "Cancel"
1971                                               (lambda (foo)
1972                                                 (abort-recursive-edit))))
1973           (let ((rfhookfun
1974                  (lambda ()
1975                    (if (not file-p)
1976                        (mouse-directory-display-completion-list
1977                         filewin dir (current-buffer) user-data)
1978                      (mouse-file-display-completion-list filewin dir
1979                                                          (current-buffer)
1980                                                          user-data)
1981                      (mouse-directory-display-completion-list dirwin dir
1982                                                               (current-buffer)
1983                                                               user-data))
1984                    (set
1985                     (make-local-variable
1986                      'completion-display-completion-list-function)
1987                     #'(lambda (completions)
1988                         (display-completion-list
1989                          completions
1990                          :help-string ""
1991                          :activate-callback
1992                          'mouse-read-file-name-activate-callback
1993                          :user-data user-data)))
1994                    ;; kludge!
1995                    (remove-hook 'minibuffer-setup-hook rfhookfun)
1996                    ))
1997                 (rfcshookfun
1998                  ;; kludge!
1999                  ;; #### I really need to flesh out the object
2000                  ;; hierarchy better to avoid these kludges.
2001                  (lambda ()
2002                    (save-excursion
2003                      (set-buffer standard-output)
2004                      (setq truncate-lines t)))))
2005             (unwind-protect
2006                 (progn
2007                   (add-hook 'minibuffer-setup-hook rfhookfun)
2008                   (add-hook 'completion-setup-hook rfcshookfun)
2009                   (read-file-name-2 history prompt dir default
2010                                     must-match initial-contents
2011                                     completer))
2012               (remove-hook 'minibuffer-setup-hook rfhookfun)
2013               (remove-hook 'completion-setup-hook rfcshookfun))))
2014       (delete-frame frame)
2015       (kill-buffer filebuf)
2016       (kill-buffer butbuff)
2017       (and dirbuff (kill-buffer dirbuff)))))
2018
2019 (defun read-face (prompt &optional must-match)
2020   "Read the name of a face from the minibuffer and return it as a symbol."
2021   (intern (completing-read prompt obarray 'find-face must-match)))
2022
2023 ;; #### - wrong place for this variable?  Exactly.  We probably want
2024 ;; `color-list' to be a console method, so `tty-color-list' becomes
2025 ;; obsolete, and `read-color-completion-table' conses (mapcar #'list
2026 ;; (color-list)), optionally caching the results.
2027
2028 ;; Ben wanted all of the possibilities from the `configure' script used
2029 ;; here, but I think this is way too many.  I already trimmed the R4 variants
2030 ;; and a few obvious losers from the list.  --Stig
2031 (defvar x-library-search-path '("/usr/X11R6/lib/X11/"
2032                                 "/usr/X11R5/lib/X11/"
2033                                 "/usr/lib/X11R6/X11/"
2034                                 "/usr/lib/X11R5/X11/"
2035                                 "/usr/local/X11R6/lib/X11/"
2036                                 "/usr/local/X11R5/lib/X11/"
2037                                 "/usr/local/lib/X11R6/X11/"
2038                                 "/usr/local/lib/X11R5/X11/"
2039                                 "/usr/X11/lib/X11/"
2040                                 "/usr/lib/X11/"
2041                                 "/usr/local/lib/X11/"
2042                                 "/usr/X386/lib/X11/"
2043                                 "/usr/x386/lib/X11/"
2044                                 "/usr/XFree86/lib/X11/"
2045                                 "/usr/unsupported/lib/X11/"
2046                                 "/usr/athena/lib/X11/"
2047                                 "/usr/local/x11r5/lib/X11/"
2048                                 "/usr/lpp/Xamples/lib/X11/"
2049                                 "/usr/openwin/lib/X11/"
2050                                 "/usr/openwin/share/lib/X11/")
2051   "Search path used by `read-color' to find rgb.txt.")
2052
2053 (defvar x-read-color-completion-table)
2054
2055 (defun read-color-completion-table ()
2056   (case (device-type)
2057     ;; #### Evil device-type dependency
2058     (x
2059      (if (boundp 'x-read-color-completion-table)
2060          x-read-color-completion-table
2061        (let ((rgb-file (locate-file "rgb.txt" x-library-search-path))
2062              clist color p)
2063          (if (not rgb-file)
2064              ;; prevents multiple searches for rgb.txt if we can't find it
2065              (setq x-read-color-completion-table nil)
2066            (with-current-buffer (get-buffer-create " *colors*")
2067              (reset-buffer (current-buffer))
2068              (insert-file-contents rgb-file)
2069              (while (not (eobp))
2070                ;; skip over comments
2071                (while (looking-at "^!")
2072                  (end-of-line)
2073                  (forward-char 1))
2074                (skip-chars-forward "0-9 \t")
2075                (setq p (point))
2076                (end-of-line)
2077                (setq color (buffer-substring p (point))
2078                      clist (cons (list color) clist))
2079                ;; Ugh.  If we want to be able to complete the lowercase form
2080                ;; of the color name, we need to add it twice!  Yuck.
2081                (let ((dcase (downcase color)))
2082                  (or (string= dcase color)
2083                      (push (list dcase) clist)))
2084                (forward-char 1))
2085              (kill-buffer (current-buffer))))
2086          (setq x-read-color-completion-table clist)
2087          x-read-color-completion-table)))
2088     (mswindows
2089      (mapcar #'list (mswindows-color-list)))
2090     (tty
2091      (mapcar #'list (tty-color-list)))))
2092
2093 (defun read-color (prompt &optional must-match initial-contents)
2094   "Read the name of a color from the minibuffer.
2095 On X devices, this uses `x-library-search-path' to find rgb.txt in order
2096  to build a completion table.
2097 On TTY devices, this uses `tty-color-list'.
2098 On mswindows devices, this uses `mswindows-color-list'."
2099   (let ((table (read-color-completion-table)))
2100     (completing-read prompt table nil (and table must-match)
2101                      initial-contents)))
2102
2103 \f
2104 ;; #### The doc string for read-non-nil-coding system gets lost if we
2105 ;; only include these if the mule feature is present.  Strangely,
2106 ;; read-coding-system doesn't.
2107
2108 ;;(if (featurep 'mule)
2109
2110 (defun read-coding-system (prompt)
2111   "Read a coding-system (or nil) from the minibuffer.
2112 Prompting with string PROMPT."
2113   (intern (completing-read prompt obarray 'find-coding-system t)))
2114
2115 (defun read-non-nil-coding-system (prompt)
2116   "Read a non-nil coding-system from the minibuffer.
2117 Prompt with string PROMPT."
2118   (let ((retval (intern "")))
2119     (while (= 0 (length (symbol-name retval)))
2120       (setq retval (intern (completing-read prompt obarray
2121                                             'find-coding-system
2122                                             t))))
2123     retval))
2124
2125 ;;) ;; end of (featurep 'mule)
2126
2127 \f
2128
2129 (defcustom force-dialog-box-use nil
2130   "*If non-nil, always use a dialog box for asking questions, if possible.
2131 You should *bind* this, not set it.  This is useful if you're doing
2132 something mousy but which wasn't actually invoked using the mouse."
2133   :type 'boolean
2134   :group 'minibuffer)
2135
2136 ;; We include this here rather than dialog.el so it is defined
2137 ;; even when dialog boxes are not present.
2138 (defun should-use-dialog-box-p ()
2139   "If non-nil, questions should be asked with a dialog box instead of the
2140 minibuffer.  This looks at `last-command-event' to see if it was a mouse
2141 event, and checks whether dialog-support exists and the current device
2142 supports dialog boxes.
2143
2144 The dialog box is totally disabled if the variable `use-dialog-box'
2145 is set to nil."
2146   (and (featurep 'dialog)
2147        (device-on-window-system-p)
2148        use-dialog-box
2149        (or force-dialog-box-use
2150            (button-press-event-p last-command-event)
2151            (button-release-event-p last-command-event)
2152            (misc-user-event-p last-command-event))))
2153
2154 ;;; minibuf.el ends here