1 ;;; minibuffer.el --- Minibuffer completion functions
3 ;; Copyright (C) 2008 Free Software Foundation, Inc.
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
7 ;; This file is part of GNU Emacs.
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
14 ;; This program is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
24 ;; Names starting with "minibuffer--" are for functions and variables that
25 ;; are meant to be for internal use only.
28 ;; - envvar completion for file names breaks completion-base-size.
32 (eval-when-compile (require 'cl
))
34 ;;; Completion table manipulation
36 (defun apply-partially (fun &rest args
)
37 (lexical-let ((fun fun
) (args1 args
))
38 (lambda (&rest args2
) (apply fun
(append args1 args2
)))))
40 (defun complete-with-action (action table string pred
)
41 "Perform completion ACTION.
42 STRING is the string to complete.
43 TABLE is the completion table, which should not be a function.
44 PRED is a completion predicate.
45 ACTION can be one of nil, t or `lambda'."
46 ;; (assert (not (functionp table)))
49 ((null action
) 'try-completion
)
50 ((eq action t
) 'all-completions
)
54 (defun completion-table-dynamic (fun)
55 "Use function FUN as a dynamic completion table.
56 FUN is called with one argument, the string for which completion is required,
57 and it should return an alist containing all the intended possible
58 completions. This alist may be a full list of possible completions so that FUN
59 can ignore the value of its argument. If completion is performed in the
60 minibuffer, FUN will be called in the buffer from which the minibuffer was
63 The result of the `dynamic-completion-table' form is a function
64 that can be used as the ALIST argument to `try-completion' and
65 `all-completion'. See Info node `(elisp)Programmed Completion'."
66 (lexical-let ((fun fun
))
67 (lambda (string pred action
)
68 (with-current-buffer (let ((win (minibuffer-selected-window)))
69 (if (window-live-p win
) (window-buffer win
)
71 (complete-with-action action
(funcall fun string
) string pred
)))))
73 (defmacro lazy-completion-table
(var fun
)
74 "Initialize variable VAR as a lazy completion table.
75 If the completion table VAR is used for the first time (e.g., by passing VAR
76 as an argument to `try-completion'), the function FUN is called with no
77 arguments. FUN must return the completion table that will be stored in VAR.
78 If completion is requested in the minibuffer, FUN will be called in the buffer
79 from which the minibuffer was entered. The return value of
80 `lazy-completion-table' must be used to initialize the value of VAR.
82 You should give VAR a non-nil `risky-local-variable' property."
83 (declare (debug (symbolp lambda-expr
)))
84 (let ((str (make-symbol "string")))
85 `(completion-table-dynamic
87 (when (functionp ,var
)
91 (defun completion-table-with-context (prefix table string pred action
)
92 ;; TODO: add `suffix', and think about how we should support `pred'.
93 ;; Notice that `pred' is not a predicate when called from read-file-name.
94 ;; (if pred (setq pred (lexical-let ((pred pred))
95 ;; ;; FIXME: this doesn't work if `table' is an obarray.
96 ;; (lambda (s) (funcall pred (concat prefix s))))))
97 (let ((comp (complete-with-action action table string nil
))) ;; pred
102 (defun completion-table-with-terminator (terminator table string pred action
)
103 (let ((comp (complete-with-action action table string pred
)))
106 (concat string terminator
)
107 (if (and (stringp comp
)
108 (eq (complete-with-action action table comp pred
) t
))
109 (concat comp terminator
)
113 (defun completion-table-in-turn (a b
)
114 "Create a completion table that first tries completion in A and then in B.
115 A and B should not be costly (or side-effecting) expressions."
116 (lexical-let ((a a
) (b b
))
117 (lambda (string pred action
)
118 (or (complete-with-action action a string pred
)
119 (complete-with-action action b string pred
)))))
121 ;;; Minibuffer completion
123 (defgroup minibuffer nil
124 "Controlling the behavior of the minibuffer."
125 :link
'(custom-manual "(emacs)Minibuffer")
128 (defun minibuffer-message (message &rest args
)
129 "Temporarily display MESSAGE at the end of the minibuffer.
130 The text is displayed for `minibuffer-message-timeout' seconds,
131 or until the next input event arrives, whichever comes first.
132 Enclose MESSAGE in [...] if this is not yet the case.
133 If ARGS are provided, then pass MESSAGE through `format'."
134 ;; Clear out any old echo-area message to make way for our new thing.
136 (unless (and (null args
) (string-match "\\[.+\\]" message
))
137 (setq message
(concat " [" message
"]")))
138 (when args
(setq message
(apply 'format message args
)))
139 (let ((ol (make-overlay (point-max) (point-max) nil t t
)))
142 (overlay-put ol
'after-string message
)
143 (sit-for (or minibuffer-message-timeout
1000000)))
144 (delete-overlay ol
))))
146 (defun minibuffer-completion-contents ()
147 "Return the user input in a minibuffer before point as a string.
148 That is what completion commands operate on."
149 (buffer-substring (field-beginning) (point)))
151 (defun delete-minibuffer-contents ()
152 "Delete all user input in a minibuffer.
153 If the current buffer is not a minibuffer, erase its entire contents."
156 (defcustom completion-auto-help t
157 "Non-nil means automatically provide help for invalid completion input.
158 If the value is t the *Completion* buffer is displayed whenever completion
159 is requested but cannot be done.
160 If the value is `lazy', the *Completions* buffer is only displayed after
161 the second failed attempt to complete."
162 :type
'(choice (const nil
) (const t
) (const lazy
))
165 (defun minibuffer--bitset (modified completions exact
)
166 (logior (if modified
4 0)
170 (defun minibuffer--do-completion (&optional try-completion-function
)
171 "Do the completion and return a summary of what happened.
172 M = completion was performed, the text was Modified.
173 C = there were available Completions.
174 E = after completion we now have an Exact match.
177 000 0 no possible completion
178 001 1 was already an exact and unique completion
179 010 2 no completion happened
180 011 3 was already an exact completion
183 110 6 some completion happened
184 111 7 completed to an exact completion"
185 (let* ((beg (field-beginning))
186 (string (buffer-substring beg
(point)))
187 (completion (funcall (or try-completion-function
'try-completion
)
189 minibuffer-completion-table
190 minibuffer-completion-predicate
)))
193 (ding) (minibuffer-message "No match") (minibuffer--bitset nil nil nil
))
194 ((eq t completion
) (minibuffer--bitset nil nil t
)) ;Exact and unique match.
196 ;; `completed' should be t if some completion was done, which doesn't
197 ;; include simply changing the case of the entered string. However,
198 ;; for appearance, the string is rewritten if the case changes.
199 (let ((completed (not (eq t
(compare-strings completion nil nil
201 (unchanged (eq t
(compare-strings completion nil nil
202 string nil nil nil
))))
204 ;; Merge a trailing / in completion with a / after point.
205 ;; We used to only do it for word completion, but it seems to make
206 ;; sense for all completions.
207 (if (and (eq ?
/ (aref completion
(1- (length completion
))))
208 (< (point) (field-end))
209 (eq ?
/ (char-after)))
210 (setq completion
(substring completion
0 -
1)))
212 ;; Insert in minibuffer the chars we got.
215 (delete-region beg end
)))
217 (if (not (or unchanged completed
))
218 ;; The case of the string changed, but that's all. We're not sure
219 ;; whether this is a unique completion or not, so try again using
220 ;; the real case (this shouldn't recurse again, because the next
221 ;; time try-completion will return either t or the exact string).
222 (minibuffer--do-completion try-completion-function
)
224 ;; It did find a match. Do we match some possibility exactly now?
225 (let ((exact (test-completion (field-string)
226 minibuffer-completion-table
227 minibuffer-completion-predicate
)))
229 ;; Show the completion table, if requested.
232 (if (case completion-auto-help
233 (lazy (eq this-command last-command
))
234 (t completion-auto-help
))
235 (minibuffer-completion-help)
236 (minibuffer-message "Next char not unique")))
237 ;; If the last exact completion and this one were the same,
238 ;; it means we've already given a "Complete but not unique"
239 ;; message and the user's hit TAB again, so now we give him help.
240 ((eq this-command last-command
)
241 (if completion-auto-help
(minibuffer-completion-help)))))
243 (minibuffer--bitset completed t exact
))))))))
245 (defun minibuffer-complete ()
246 "Complete the minibuffer contents as far as possible.
247 Return nil if there is no valid completion, else t.
248 If no characters can be completed, display a list of possible completions.
249 If you repeat this command after it displayed such a list,
250 scroll the window of possible completions."
252 ;; If the previous command was not this,
253 ;; mark the completion buffer obsolete.
254 (unless (eq this-command last-command
)
255 (setq minibuffer-scroll-window nil
))
257 (let ((window minibuffer-scroll-window
))
258 ;; If there's a fresh completion window with a live buffer,
259 ;; and this command is repeated, scroll that window.
260 (if (window-live-p window
)
261 (with-current-buffer (window-buffer window
)
262 (if (pos-visible-in-window-p (point-max) window
)
263 ;; If end is in view, scroll up to the beginning.
264 (set-window-start window
(point-min) nil
)
265 ;; Else scroll down one screen.
266 (scroll-other-window))
269 (case (minibuffer--do-completion)
271 (1 (goto-char (field-end))
272 (minibuffer-message "Sole completion")
274 (3 (goto-char (field-end))
275 (minibuffer-message "Complete, but not unique")
279 (defun minibuffer-complete-and-exit ()
280 "If the minibuffer contents is a valid completion then exit.
281 Otherwise try to complete it. If completion leads to a valid completion,
282 a repetition of this command will exit."
285 ;; Allow user to specify null string
286 ((= (field-beginning) (field-end)) (exit-minibuffer))
287 ((test-completion (field-string)
288 minibuffer-completion-table
289 minibuffer-completion-predicate
)
290 (when completion-ignore-case
291 ;; Fixup case of the field, if necessary.
292 (let* ((string (field-string))
293 (compl (try-completion string
294 minibuffer-completion-table
295 minibuffer-completion-predicate
)))
296 (when (and (stringp compl
)
297 ;; If it weren't for this piece of paranoia, I'd replace
298 ;; the whole thing with a call to complete-do-completion.
299 (= (length string
) (length compl
)))
300 (let ((beg (field-beginning))
304 (delete-region beg end
)))))
307 ((eq minibuffer-completion-confirm
'confirm-only
)
308 ;; The user is permitted to exit with an input that's rejected
309 ;; by test-completion, but at the condition to confirm her choice.
310 (if (eq last-command this-command
)
312 (minibuffer-message "Confirm")
316 ;; Call do-completion, but ignore errors.
317 (case (condition-case nil
318 (minibuffer--do-completion)
320 ((1 3) (exit-minibuffer))
321 (7 (if (not minibuffer-completion-confirm
)
323 (minibuffer-message "Confirm")
327 (defun minibuffer-try-word-completion (string table predicate
)
328 (let ((completion (try-completion string table predicate
)))
329 (if (not (stringp completion
))
332 ;; Completing a single word is actually more difficult than completing
333 ;; as much as possible, because we first have to find the "current
334 ;; position" in `completion' in order to find the end of the word
335 ;; we're completing. Normally, `string' is a prefix of `completion',
336 ;; which makes it trivial to find the position, but with fancier
337 ;; completion (plus env-var expansion, ...) `completion' might not
338 ;; look anything like `string' at all.
340 (when minibuffer-completing-file-name
341 ;; In order to minimize the problem mentioned above, let's try to
342 ;; reduce the different between `string' and `completion' by
343 ;; mirroring some of the work done in read-file-name-internal.
344 (let ((substituted (condition-case nil
345 ;; Might fail when completing an env-var.
346 (substitute-in-file-name string
)
348 (unless (eq string substituted
)
349 (setq string substituted
))))
351 ;; Make buffer (before point) contain the longest match
352 ;; of `string's tail and `completion's head.
353 (let* ((startpos (max 0 (- (length string
) (length completion
))))
354 (length (- (length string
) startpos
)))
355 (while (and (> length
0)
356 (not (eq t
(compare-strings string startpos nil
358 completion-ignore-case
))))
359 (setq startpos
(1+ startpos
))
360 (setq length
(1- length
)))
362 (setq string
(substring string startpos
)))
364 ;; Now `string' is a prefix of `completion'.
366 ;; If completion finds next char not unique,
367 ;; consider adding a space or a hyphen.
368 (when (= (length string
) (length completion
))
369 (let ((exts '(" " "-"))
371 (while (and exts
(not (stringp tem
)))
372 (setq tem
(try-completion (concat string
(pop exts
))
374 (if (stringp tem
) (setq completion tem
))))
376 ;; Otherwise cut after the first word.
377 (if (string-match "\\W" completion
(length string
))
378 ;; First find first word-break in the stuff found by completion.
379 ;; i gets index in string of where to stop completing.
380 (substring completion
0 (match-end 0))
384 (defun minibuffer-complete-word ()
385 "Complete the minibuffer contents at most a single word.
386 After one word is completed as much as possible, a space or hyphen
387 is added, provided that matches some possible completion.
388 Return nil if there is no valid completion, else t."
390 (case (minibuffer--do-completion 'minibuffer-try-word-completion
)
392 (1 (goto-char (field-end))
393 (minibuffer-message "Sole completion")
395 (3 (goto-char (field-end))
396 (minibuffer-message "Complete, but not unique")
400 (defun minibuffer--insert-strings (strings)
401 "Insert a list of STRINGS into the current buffer.
402 Uses columns to keep the listing readable but compact.
403 It also eliminates runs of equal strings."
404 (when (consp strings
)
405 (let* ((length (apply 'max
408 (+ (length (car s
)) (length (cadr s
)))
411 (window (get-buffer-window (current-buffer) 0))
412 (wwidth (if window
(1- (window-width window
)) 79))
414 ;; At least 2 columns; at least 2 spaces between columns.
415 (max 2 (/ wwidth
(+ 2 length
)))
416 ;; Don't allocate more columns than we can fill.
417 ;; Windows can't show less than 3 lines anyway.
418 (max 1 (/ (length strings
) 2))))
419 (colwidth (/ wwidth columns
))
422 ;; The insertion should be "sensible" no matter what choices were made
423 ;; for the parameters above.
424 (dolist (str strings
)
425 (unless (equal laststring str
) ; Remove (consecutive) duplicates.
426 (setq laststring str
)
429 (setq column
(+ column colwidth
))
430 ;; Leave the space unpropertized so that in the case we're
431 ;; already past the goal column, there is still
432 ;; a space displayed.
433 (set-text-properties (- (point) 1) (point)
434 ;; We can't just set tab-width, because
435 ;; completion-setup-function will kill all
436 ;; local variables :-(
437 `(display (space :align-to
,column
))))
438 (when (< wwidth
(+ (max colwidth
440 (+ (length (car str
)) (length (cadr str
)))
443 (delete-char -
2) (insert "\n") (setq column
0))
444 (if (not (consp str
))
445 (put-text-property (point) (progn (insert str
) (point))
446 'mouse-face
'highlight
)
447 (put-text-property (point) (progn (insert (car str
)) (point))
448 'mouse-face
'highlight
)
449 (put-text-property (point) (progn (insert (cadr str
)) (point))
450 'mouse-face nil
)))))))
452 (defvar completion-common-substring
)
454 (defvar completion-setup-hook nil
455 "Normal hook run at the end of setting up a completion list buffer.
456 When this hook is run, the current buffer is the one in which the
457 command to display the completion list buffer was run.
458 The completion list buffer is available as the value of `standard-output'.
459 The common prefix substring for completion may be available as the
460 value of `completion-common-substring'. See also `display-completion-list'.")
462 (defun display-completion-list (completions &optional common-substring
)
463 "Display the list of completions, COMPLETIONS, using `standard-output'.
464 Each element may be just a symbol or string
465 or may be a list of two strings to be printed as if concatenated.
466 If it is a list of two strings, the first is the actual completion
467 alternative, the second serves as annotation.
468 `standard-output' must be a buffer.
469 The actual completion alternatives, as inserted, are given `mouse-face'
470 properties of `highlight'.
471 At the end, this runs the normal hook `completion-setup-hook'.
472 It can find the completion buffer in `standard-output'.
473 The optional second arg COMMON-SUBSTRING is a string.
474 It is used to put faces, `completions-first-difference' and
475 `completions-common-part' on the completion buffer. The
476 `completions-common-part' face is put on the common substring
477 specified by COMMON-SUBSTRING. If COMMON-SUBSTRING is nil
478 and the current buffer is not the minibuffer, the faces are not put.
479 Internally, COMMON-SUBSTRING is bound to `completion-common-substring'
480 during running `completion-setup-hook'."
481 (if (not (bufferp standard-output
))
482 ;; This *never* (ever) happens, so there's no point trying to be clever.
484 (let ((standard-output (current-buffer))
485 (completion-setup-hook nil
))
486 (display-completion-list completions
))
487 (princ (buffer-string)))
489 (with-current-buffer standard-output
490 (goto-char (point-max))
491 (if (null completions
)
492 (insert "There are no possible completions of what you have typed.")
494 (insert "Possible completions are:\n")
495 (minibuffer--insert-strings completions
))))
496 (let ((completion-common-substring common-substring
))
497 (run-hooks 'completion-setup-hook
))
500 (defun minibuffer-completion-help ()
501 "Display a list of possible completions of the current minibuffer contents."
503 (message "Making completion list...")
504 (let* ((string (field-string))
505 (completions (all-completions
507 minibuffer-completion-table
508 minibuffer-completion-predicate
512 (or (cdr completions
) (not (equal (car completions
) string
))))
513 (with-output-to-temp-buffer "*Completions*"
514 (display-completion-list (sort completions
'string-lessp
)))
516 ;; If there are no completions, or if the current input is already the
517 ;; only possible completion, then hide (previous&stale) completions.
518 (let ((window (and (get-buffer "*Completions*")
519 (get-buffer-window "*Completions*" 0))))
520 (when (and (window-live-p window
) (window-dedicated-p window
))
522 (delete-window window
)
523 (error (iconify-frame (window-frame window
))))))
526 (if completions
"Sole completion" "No completions")))
529 (defun exit-minibuffer ()
530 "Terminate this minibuffer argument."
532 ;; If the command that uses this has made modifications in the minibuffer,
533 ;; we don't want them to cause deactivation of the mark in the original
535 ;; A better solution would be to make deactivate-mark buffer-local
536 ;; (or to turn it into a list of buffers, ...), but in the mean time,
537 ;; this should do the trick in most cases.
538 (setq deactivate-mark nil
)
541 (defun self-insert-and-exit ()
542 "Terminate minibuffer input."
544 (if (characterp last-command-char
)
545 (call-interactively 'self-insert-command
)
549 (defun minibuffer--double-dollars (str)
550 (replace-regexp-in-string "\\$" "$$" str
))
552 (defun completion--make-envvar-table ()
553 (mapcar (lambda (enventry)
554 (substring enventry
0 (string-match "=" enventry
)))
555 process-environment
))
557 (defun completion--embedded-envvar-table (string pred action
)
558 (when (string-match (concat "\\(?:^\\|[^$]\\(?:\\$\\$\\)*\\)"
559 "$\\([[:alnum:]_]*\\|{\\([^}]*\\)\\)\\'")
561 (let* ((beg (or (match-beginning 2) (match-beginning 1)))
562 (table (completion--make-envvar-table))
563 (prefix (substring string
0 beg
)))
564 (if (eq (aref string
(1- beg
)) ?
{)
565 (setq table
(apply-partially 'completion-table-with-terminator
567 (completion-table-with-context prefix table
568 (substring string beg
)
571 (defun completion--file-name-table (string dir action
)
572 "Internal subroutine for read-file-name. Do not call this."
573 (setq dir
(expand-file-name dir
))
574 (if (and (zerop (length string
)) (eq 'lambda action
))
576 (let* ((str (condition-case nil
577 (substitute-in-file-name string
)
579 (name (file-name-nondirectory str
))
580 (specdir (file-name-directory str
))
581 (realdir (if specdir
(expand-file-name specdir dir
)
582 (file-name-as-directory dir
))))
586 (let ((comp (file-name-completion name realdir
587 read-file-name-predicate
)))
589 ;; Requote the $s before returning the completion.
590 (minibuffer--double-dollars (concat specdir comp
))
591 ;; Requote the $s before checking for changes.
592 (setq str
(minibuffer--double-dollars str
))
593 (if (string-equal string str
)
595 ;; If there's no real completion, but substitute-in-file-name
596 ;; changed the string, then return the new string.
600 (let ((all (file-name-all-completions name realdir
)))
601 (if (memq read-file-name-predicate
'(nil file-exists-p
))
605 (if (eq read-file-name-predicate
'file-directory-p
)
606 ;; Brute-force speed up for directory checking:
607 ;; Discard strings which don't end in a slash.
609 (let ((len (length s
)))
610 (and (> len
0) (eq (aref s
(1- len
)) ?
/))))
611 ;; Must do it the hard (and slow) way.
612 read-file-name-predicate
)))
613 (let ((default-directory realdir
))
615 (if (funcall pred tem
) (push tem comp
))))
619 ;; Only other case actually used is ACTION = lambda.
620 (let ((default-directory dir
))
621 (funcall (or read-file-name-predicate
'file-exists-p
) str
)))))))
623 (defalias 'read-file-name-internal
624 (completion-table-in-turn 'completion--embedded-envvar-table
625 'completion--file-name-table
)
626 "Internal subroutine for `read-file-name'. Do not call this.")
628 (provide 'minibuffer
)
629 ;;; minibuffer.el ends here