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