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 ;; GNU Emacs 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 GNU Emacs. 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.
29 ;; - Make read-file-name-predicate obsolete.
30 ;; - New command minibuffer-force-complete that chooses one of all-completions.
31 ;; - Add vc-file-name-completion-table to read-file-name-internal.
32 ;; - A feature like completing-help.el.
33 ;; - Make the `hide-spaces' arg of all-completions obsolete?
37 (eval-when-compile (require 'cl
))
39 (defvar completion-all-completions-with-base-size nil
40 "If non-nil, `all-completions' may return the base-size in the last cdr.
41 The base-size is the length of the prefix that is elided from each
42 element in the returned list of completions. See `completion-base-size'.")
44 ;;; Completion table manipulation
46 (defun completion--some (fun xs
)
47 "Apply FUN to each element of XS in turn.
48 Return the first non-nil returned value.
51 (while (and (not res
) xs
)
52 (setq res
(funcall fun
(pop xs
))))
55 (defun apply-partially (fun &rest args
)
56 "Do a \"curried\" partial application of FUN to ARGS.
57 ARGS is a list of the first N arguments to pass to FUN.
58 The result is a new function that takes the remaining arguments,
60 (lexical-let ((fun fun
) (args1 args
))
61 (lambda (&rest args2
) (apply fun
(append args1 args2
)))))
63 (defun complete-with-action (action table string pred
)
64 "Perform completion ACTION.
65 STRING is the string to complete.
66 TABLE is the completion table, which should not be a function.
67 PRED is a completion predicate.
68 ACTION can be one of nil, t or `lambda'."
69 ;; (assert (not (functionp table)))
72 ((null action
) 'try-completion
)
73 ((eq action t
) 'all-completions
)
77 (defun completion-table-dynamic (fun)
78 "Use function FUN as a dynamic completion table.
79 FUN is called with one argument, the string for which completion is required,
80 and it should return an alist containing all the intended possible completions.
81 This alist may be a full list of possible completions so that FUN can ignore
82 the value of its argument. If completion is performed in the minibuffer,
83 FUN will be called in the buffer from which the minibuffer was entered.
85 The result of the `dynamic-completion-table' form is a function
86 that can be used as the ALIST argument to `try-completion' and
87 `all-completions'. See Info node `(elisp)Programmed Completion'."
88 (lexical-let ((fun fun
))
89 (lambda (string pred action
)
90 (with-current-buffer (let ((win (minibuffer-selected-window)))
91 (if (window-live-p win
) (window-buffer win
)
93 (complete-with-action action
(funcall fun string
) string pred
)))))
95 (defmacro lazy-completion-table
(var fun
)
96 "Initialize variable VAR as a lazy completion table.
97 If the completion table VAR is used for the first time (e.g., by passing VAR
98 as an argument to `try-completion'), the function FUN is called with no
99 arguments. FUN must return the completion table that will be stored in VAR.
100 If completion is requested in the minibuffer, FUN will be called in the buffer
101 from which the minibuffer was entered. The return value of
102 `lazy-completion-table' must be used to initialize the value of VAR.
104 You should give VAR a non-nil `risky-local-variable' property."
105 (declare (debug (symbolp lambda-expr
)))
106 (let ((str (make-symbol "string")))
107 `(completion-table-dynamic
109 (when (functionp ,var
)
113 (defun completion-table-with-context (prefix table string pred action
)
114 ;; TODO: add `suffix' maybe?
115 ;; Notice that `pred' is not a predicate when called from read-file-name
116 ;; or Info-read-node-name-2.
117 (when (functionp pred
)
119 (lexical-let ((pred pred
))
120 ;; Predicates are called differently depending on the nature of
121 ;; the completion table :-(
123 ((vectorp table
) ;Obarray.
124 (lambda (sym) (funcall pred
(concat prefix
(symbol-name sym
)))))
125 ((hash-table-p table
)
126 (lambda (s v
) (funcall pred
(concat prefix s
))))
128 (lambda (s) (funcall pred
(concat prefix s
))))
129 (t ;Lists and alists.
131 (funcall pred
(concat prefix
(if (consp s
) (car s
) s
)))))))))
132 (let ((comp (complete-with-action action table string pred
)))
134 ;; In case of try-completion, add the prefix.
135 ((stringp comp
) (concat prefix comp
))
136 ;; In case of non-empty all-completions,
137 ;; add the prefix size to the base-size.
139 (let ((last (last comp
)))
140 (when completion-all-completions-with-base-size
141 (setcdr last
(+ (or (cdr last
) 0) (length prefix
))))
145 (defun completion-table-with-terminator (terminator table string pred action
)
148 (let ((comp (try-completion string table pred
)))
150 (concat string terminator
)
151 (if (and (stringp comp
)
152 (eq (try-completion comp table pred
) t
))
153 (concat comp terminator
)
155 ((eq action t
) (all-completions string table pred
))
156 ;; completion-table-with-terminator is always used for
157 ;; "sub-completions" so it's only called if the terminator is missing,
158 ;; in which case `test-completion' should return nil.
159 ((eq action
'lambda
) nil
)))
161 (defun completion-table-with-predicate (table pred1 strict string pred2 action
)
162 "Make a completion table equivalent to TABLE but filtered through PRED1.
163 PRED1 is a function of one argument which returns non-nil if and only if the
164 argument is an element of TABLE which should be considered for completion.
165 STRING, PRED2, and ACTION are the usual arguments to completion tables,
166 as described in `try-completion', `all-completions', and `test-completion'.
167 If STRICT is t, the predicate always applies; if nil it only applies if
168 it does not reduce the set of possible completions to nothing.
169 Note: TABLE needs to be a proper completion table which obeys predicates."
171 ((and (not strict
) (eq action
'lambda
))
172 ;; Ignore pred1 since it doesn't really have to apply anyway.
173 (test-completion string table pred2
))
175 (or (complete-with-action action table string
176 (if (null pred2
) pred1
177 (lexical-let ((pred1 pred2
) (pred2 pred2
))
179 ;; Call `pred1' first, so that `pred2'
180 ;; really can't tell that `x' is in table.
181 (if (funcall pred1 x
) (funcall pred2 x
))))))
182 ;; If completion failed and we're not applying pred1 strictly, try
183 ;; again without pred1.
185 (complete-with-action action table string pred2
))))))
187 (defun completion-table-in-turn (&rest tables
)
188 "Create a completion table that tries each table in TABLES in turn."
189 (lexical-let ((tables tables
))
190 (lambda (string pred action
)
191 (completion--some (lambda (table)
192 (complete-with-action action table string pred
))
195 ;; (defmacro complete-in-turn (a b) `(completion-table-in-turn ,a ,b))
196 ;; (defmacro dynamic-completion-table (fun) `(completion-table-dynamic ,fun))
197 (define-obsolete-function-alias
198 'complete-in-turn
'completion-table-in-turn
"23.1")
199 (define-obsolete-function-alias
200 'dynamic-completion-table
'completion-table-dynamic
"23.1")
202 ;;; Minibuffer completion
204 (defgroup minibuffer nil
205 "Controlling the behavior of the minibuffer."
206 :link
'(custom-manual "(emacs)Minibuffer")
209 (defun minibuffer-message (message &rest args
)
210 "Temporarily display MESSAGE at the end of the minibuffer.
211 The text is displayed for `minibuffer-message-timeout' seconds,
212 or until the next input event arrives, whichever comes first.
213 Enclose MESSAGE in [...] if this is not yet the case.
214 If ARGS are provided, then pass MESSAGE through `format'."
215 ;; Clear out any old echo-area message to make way for our new thing.
217 (setq message
(if (and (null args
) (string-match "\\[.+\\]" message
))
218 ;; Make sure we can put-text-property.
219 (copy-sequence message
)
220 (concat " [" message
"]")))
221 (when args
(setq message
(apply 'format message args
)))
222 (let ((ol (make-overlay (point-max) (point-max) nil t t
)))
225 (unless (zerop (length message
))
226 ;; The current C cursor code doesn't know to use the overlay's
227 ;; marker's stickiness to figure out whether to place the cursor
228 ;; before or after the string, so let's spoon-feed it the pos.
229 (put-text-property 0 1 'cursor t message
))
230 (overlay-put ol
'after-string message
)
231 (sit-for (or minibuffer-message-timeout
1000000)))
232 (delete-overlay ol
))))
234 (defun minibuffer-completion-contents ()
235 "Return the user input in a minibuffer before point as a string.
236 That is what completion commands operate on."
237 (buffer-substring (field-beginning) (point)))
239 (defun delete-minibuffer-contents ()
240 "Delete all user input in a minibuffer.
241 If the current buffer is not a minibuffer, erase its entire contents."
244 (defcustom completion-auto-help t
245 "Non-nil means automatically provide help for invalid completion input.
246 If the value is t the *Completion* buffer is displayed whenever completion
247 is requested but cannot be done.
248 If the value is `lazy', the *Completions* buffer is only displayed after
249 the second failed attempt to complete."
250 :type
'(choice (const nil
) (const t
) (const lazy
))
253 (defvar completion-styles-alist
254 '((basic completion-basic-try-completion completion-basic-all-completions
)
255 (emacs22 completion-emacs22-try-completion completion-emacs22-all-completions
)
256 (emacs21 completion-emacs21-try-completion completion-emacs21-all-completions
)
258 completion-pcm-try-completion completion-pcm-all-completions
))
259 "List of available completion styles.
260 Each element has the form (NAME TRY-COMPLETION ALL-COMPLETIONS)
261 where NAME is the name that should be used in `completion-styles',
262 TRY-COMPLETION is the function that does the completion, and
263 ALL-COMPLETIONS is the function that lists the completions.")
265 (defcustom completion-styles
'(basic partial-completion
)
266 "List of completion styles to use."
267 :type
`(repeat (choice ,@(mapcar (lambda (x) (list 'const
(car x
)))
268 completion-styles-alist
)))
272 (defun completion-try-completion (string table pred point
)
273 "Try to complete STRING using completion table TABLE.
274 Only the elements of table that satisfy predicate PRED are considered.
275 POINT is the position of point within STRING.
276 The return value can be either nil to indicate that there is no completion,
277 t to indicate that STRING is the only possible completion,
278 or a pair (STRING . NEWPOINT) of the completed result string together with
279 a new position for point."
280 ;; The property `completion-styles' indicates that this functional
281 ;; completion-table claims to take care of completion styles itself.
282 ;; [I.e. It will most likely call us back at some point. ]
283 (if (and (symbolp table
) (get table
'completion-styles
))
284 ;; Extended semantics for functional completion-tables:
285 ;; They accept a 4th argument `point' and when called with action=nil
286 ;; and this 4th argument (a position inside `string'), they should
287 ;; return instead of a string a pair (STRING . NEWPOINT).
288 (funcall table string pred nil point
)
289 (completion--some (lambda (style)
290 (funcall (nth 1 (assq style completion-styles-alist
))
291 string table pred point
))
294 (defun completion-all-completions (string table pred point
)
295 "List the possible completions of STRING in completion table TABLE.
296 Only the elements of table that satisfy predicate PRED are considered.
297 POINT is the position of point within STRING.
298 The return value is a list of completions and may contain the base-size
300 ;; The property `completion-styles' indicates that this functional
301 ;; completion-table claims to take care of completion styles itself.
302 ;; [I.e. It will most likely call us back at some point. ]
303 (let ((completion-all-completions-with-base-size t
))
304 (if (and (symbolp table
) (get table
'completion-styles
))
305 ;; Extended semantics for functional completion-tables:
306 ;; They accept a 4th argument `point' and when called with action=t
307 ;; and this 4th argument (a position inside `string'), they may
308 ;; return BASE-SIZE in the last `cdr'.
309 (funcall table string pred t point
)
310 (completion--some (lambda (style)
311 (funcall (nth 2 (assq style completion-styles-alist
))
312 string table pred point
))
313 completion-styles
))))
315 (defun minibuffer--bitset (modified completions exact
)
316 (logior (if modified
4 0)
320 (defun completion--do-completion (&optional try-completion-function
)
321 "Do the completion and return a summary of what happened.
322 M = completion was performed, the text was Modified.
323 C = there were available Completions.
324 E = after completion we now have an Exact match.
327 000 0 no possible completion
328 001 1 was already an exact and unique completion
329 010 2 no completion happened
330 011 3 was already an exact completion
333 110 6 some completion happened
334 111 7 completed to an exact completion"
335 (let* ((beg (field-beginning))
337 (string (buffer-substring beg end
))
338 (comp (funcall (or try-completion-function
339 'completion-try-completion
)
341 minibuffer-completion-table
342 minibuffer-completion-predicate
346 (ding) (minibuffer-message "No match") (minibuffer--bitset nil nil nil
))
347 ((eq t comp
) (minibuffer--bitset nil nil t
)) ;Exact and unique match.
349 ;; `completed' should be t if some completion was done, which doesn't
350 ;; include simply changing the case of the entered string. However,
351 ;; for appearance, the string is rewritten if the case changes.
352 (let* ((comp-pos (cdr comp
))
353 (completion (car comp
))
354 (completed (not (eq t
(compare-strings completion nil nil
356 (unchanged (eq t
(compare-strings completion nil nil
357 string nil nil nil
))))
360 ;; Insert in minibuffer the chars we got.
363 (delete-region beg end
))
365 (goto-char (+ beg comp-pos
))
367 (if (not (or unchanged completed
))
368 ;; The case of the string changed, but that's all. We're not sure
369 ;; whether this is a unique completion or not, so try again using
370 ;; the real case (this shouldn't recurse again, because the next
371 ;; time try-completion will return either t or the exact string).
372 (completion--do-completion try-completion-function
)
374 ;; It did find a match. Do we match some possibility exactly now?
375 (let ((exact (test-completion completion
376 minibuffer-completion-table
377 minibuffer-completion-predicate
)))
379 ;; Show the completion table, if requested.
382 (if (case completion-auto-help
383 (lazy (eq this-command last-command
))
384 (t completion-auto-help
))
385 (minibuffer-completion-help)
386 (minibuffer-message "Next char not unique")))
387 ;; If the last exact completion and this one were the same,
388 ;; it means we've already given a "Complete but not unique"
389 ;; message and the user's hit TAB again, so now we give him help.
390 ((eq this-command last-command
)
391 (if completion-auto-help
(minibuffer-completion-help)))))
393 (minibuffer--bitset completed t exact
))))))))
395 (defun minibuffer-complete ()
396 "Complete the minibuffer contents as far as possible.
397 Return nil if there is no valid completion, else t.
398 If no characters can be completed, display a list of possible completions.
399 If you repeat this command after it displayed such a list,
400 scroll the window of possible completions."
402 ;; If the previous command was not this,
403 ;; mark the completion buffer obsolete.
404 (unless (eq this-command last-command
)
405 (setq minibuffer-scroll-window nil
))
407 (let ((window minibuffer-scroll-window
))
408 ;; If there's a fresh completion window with a live buffer,
409 ;; and this command is repeated, scroll that window.
410 (if (window-live-p window
)
411 (with-current-buffer (window-buffer window
)
412 (if (pos-visible-in-window-p (point-max) window
)
413 ;; If end is in view, scroll up to the beginning.
414 (set-window-start window
(point-min) nil
)
415 ;; Else scroll down one screen.
416 (scroll-other-window))
419 (case (completion--do-completion)
421 (1 (goto-char (field-end))
422 (minibuffer-message "Sole completion")
424 (3 (goto-char (field-end))
425 (minibuffer-message "Complete, but not unique")
429 (defun minibuffer-complete-and-exit ()
430 "If the minibuffer contents is a valid completion then exit.
431 Otherwise try to complete it. If completion leads to a valid completion,
432 a repetition of this command will exit."
434 (let ((beg (field-beginning))
437 ;; Allow user to specify null string
438 ((= beg end
) (exit-minibuffer))
439 ((test-completion (buffer-substring beg end
)
440 minibuffer-completion-table
441 minibuffer-completion-predicate
)
442 (when completion-ignore-case
443 ;; Fixup case of the field, if necessary.
444 (let* ((string (buffer-substring beg end
))
445 (compl (try-completion
447 minibuffer-completion-table
448 minibuffer-completion-predicate
)))
449 (when (and (stringp compl
)
450 ;; If it weren't for this piece of paranoia, I'd replace
451 ;; the whole thing with a call to do-completion.
452 (= (length string
) (length compl
)))
455 (delete-region beg end
))))
458 ((eq minibuffer-completion-confirm
'confirm-only
)
459 ;; The user is permitted to exit with an input that's rejected
460 ;; by test-completion, but at the condition to confirm her choice.
461 (if (eq last-command this-command
)
463 (minibuffer-message "Confirm")
467 ;; Call do-completion, but ignore errors.
468 (case (condition-case nil
469 (completion--do-completion)
471 ((1 3) (exit-minibuffer))
472 (7 (if (not minibuffer-completion-confirm
)
474 (minibuffer-message "Confirm")
478 (defun completion--try-word-completion (string table predicate point
)
479 (let ((comp (completion-try-completion string table predicate point
)))
480 (if (not (consp comp
))
483 ;; If completion finds next char not unique,
484 ;; consider adding a space or a hyphen.
485 (when (= (length string
) (length (car comp
)))
486 (let ((exts '(" " "-"))
487 (before (substring string
0 point
))
488 (after (substring string point
))
490 (while (and exts
(not (consp tem
)))
491 (setq tem
(completion-try-completion
492 (concat before
(pop exts
) after
)
493 table predicate
(1+ point
))))
494 (if (consp tem
) (setq comp tem
))))
496 ;; Completing a single word is actually more difficult than completing
497 ;; as much as possible, because we first have to find the "current
498 ;; position" in `completion' in order to find the end of the word
499 ;; we're completing. Normally, `string' is a prefix of `completion',
500 ;; which makes it trivial to find the position, but with fancier
501 ;; completion (plus env-var expansion, ...) `completion' might not
502 ;; look anything like `string' at all.
503 (let* ((comppoint (cdr comp
))
504 (completion (car comp
))
505 (before (substring string
0 point
))
506 (combined (concat before
"\n" completion
)))
507 ;; Find in completion the longest text that was right before point.
508 (when (string-match "\\(.+\\)\n.*?\\1" combined
)
509 (let* ((prefix (match-string 1 before
))
510 ;; We used non-greedy match to make `rem' as long as possible.
511 (rem (substring combined
(match-end 0)))
512 ;; Find in the remainder of completion the longest text
513 ;; that was right after point.
514 (after (substring string point
))
515 (suffix (if (string-match "\\`\\(.+\\).*\n.*\\1"
516 (concat after
"\n" rem
))
517 (match-string 1 after
))))
518 ;; The general idea is to try and guess what text was inserted
519 ;; at point by the completion. Problem is: if we guess wrong,
520 ;; we may end up treating as "added by completion" text that was
521 ;; actually painfully typed by the user. So if we then cut
522 ;; after the first word, we may throw away things the
523 ;; user wrote. So let's try to be as conservative as possible:
524 ;; only cut after the first word, if we're reasonably sure that
525 ;; our guess is correct.
526 ;; Note: a quick survey on emacs-devel seemed to indicate that
527 ;; nobody actually cares about the "word-at-a-time" feature of
528 ;; minibuffer-complete-word, whose real raison-d'être is that it
529 ;; tries to add "-" or " ". One more reason to only cut after
530 ;; the first word, if we're really sure we're right.
531 (when (and (or suffix
(zerop (length after
)))
532 (string-match (concat
533 ;; Make submatch 1 as small as possible
534 ;; to reduce the risk of cutting
536 ".*" (regexp-quote prefix
) "\\(.*?\\)"
537 (if suffix
(regexp-quote suffix
) "\\'"))
539 ;; The new point in `completion' should also be just
540 ;; before the suffix, otherwise something more complex
541 ;; is going on, and we're not sure where we are.
542 (eq (match-end 1) comppoint
)
543 ;; (match-beginning 1)..comppoint is now the stretch
544 ;; of text in `completion' that was completed at point.
545 (string-match "\\W" completion
(match-beginning 1))
546 ;; Is there really something to cut?
547 (> comppoint
(match-end 0)))
548 ;; Cut after the first word.
549 (let ((cutpos (match-end 0)))
550 (setq completion
(concat (substring completion
0 cutpos
)
551 (substring completion comppoint
)))
552 (setq comppoint cutpos
)))))
554 (cons completion comppoint
)))))
557 (defun minibuffer-complete-word ()
558 "Complete the minibuffer contents at most a single word.
559 After one word is completed as much as possible, a space or hyphen
560 is added, provided that matches some possible completion.
561 Return nil if there is no valid completion, else t."
563 (case (completion--do-completion 'completion--try-word-completion
)
565 (1 (goto-char (field-end))
566 (minibuffer-message "Sole completion")
568 (3 (goto-char (field-end))
569 (minibuffer-message "Complete, but not unique")
573 (defun completion--insert-strings (strings)
574 "Insert a list of STRINGS into the current buffer.
575 Uses columns to keep the listing readable but compact.
576 It also eliminates runs of equal strings."
577 (when (consp strings
)
578 (let* ((length (apply 'max
581 (+ (string-width (car s
))
582 (string-width (cadr s
)))
585 (window (get-buffer-window (current-buffer) 0))
586 (wwidth (if window
(1- (window-width window
)) 79))
588 ;; At least 2 columns; at least 2 spaces between columns.
589 (max 2 (/ wwidth
(+ 2 length
)))
590 ;; Don't allocate more columns than we can fill.
591 ;; Windows can't show less than 3 lines anyway.
592 (max 1 (/ (length strings
) 2))))
593 (colwidth (/ wwidth columns
))
596 ;; The insertion should be "sensible" no matter what choices were made
597 ;; for the parameters above.
598 (dolist (str strings
)
599 (unless (equal laststring str
) ; Remove (consecutive) duplicates.
600 (setq laststring str
)
603 (setq column
(+ column colwidth
))
604 ;; Leave the space unpropertized so that in the case we're
605 ;; already past the goal column, there is still
606 ;; a space displayed.
607 (set-text-properties (- (point) 1) (point)
608 ;; We can't just set tab-width, because
609 ;; completion-setup-function will kill all
610 ;; local variables :-(
611 `(display (space :align-to
,column
)))
612 (when (< wwidth
(+ (max colwidth
614 (+ (string-width (car str
))
615 (string-width (cadr str
)))
618 (delete-char -
2) (insert "\n") (setq column
0)))
619 (if (not (consp str
))
620 (put-text-property (point) (progn (insert str
) (point))
621 'mouse-face
'highlight
)
622 (put-text-property (point) (progn (insert (car str
)) (point))
623 'mouse-face
'highlight
)
624 (put-text-property (point) (progn (insert (cadr str
)) (point))
625 'mouse-face nil
)))))))
627 (defvar completion-common-substring nil
)
628 (make-obsolete-variable 'completion-common-substring nil
"23.1")
630 (defvar completion-setup-hook nil
631 "Normal hook run at the end of setting up a completion list buffer.
632 When this hook is run, the current buffer is the one in which the
633 command to display the completion list buffer was run.
634 The completion list buffer is available as the value of `standard-output'.
635 See also `display-completion-list'.")
637 (defface completions-first-difference
638 '((t (:inherit bold
)))
639 "Face put on the first uncommon character in completions in *Completions* buffer."
642 (defface completions-common-part
643 '((t (:inherit default
)))
644 "Face put on the common prefix substring in completions in *Completions* buffer.
645 The idea of `completions-common-part' is that you can use it to
646 make the common parts less visible than normal, so that the rest
647 of the differing parts is, by contrast, slightly highlighted."
650 (defun completion-hilit-commonality (completions prefix-len
)
652 (let* ((last (last completions
))
653 (base-size (cdr last
))
654 (com-str-len (- prefix-len
(or base-size
0))))
655 ;; Remove base-size during mapcar, and add it back later.
661 ;; Don't modify the string itself, but a copy, since the
662 ;; the string may be read-only or used for other purposes.
663 ;; Furthermore, since `completions' may come from
664 ;; display-completion-list, `elem' may be a list.
666 (car (setq elem
(cons (copy-sequence (car elem
))
668 (setq elem
(copy-sequence elem
)))))
669 (put-text-property 0 com-str-len
670 'font-lock-face
'completions-common-part
672 (if (> (length str
) com-str-len
)
673 (put-text-property com-str-len
(1+ com-str-len
)
674 'font-lock-face
'completions-first-difference
680 (defun display-completion-list (completions &optional common-substring
)
681 "Display the list of completions, COMPLETIONS, using `standard-output'.
682 Each element may be just a symbol or string
683 or may be a list of two strings to be printed as if concatenated.
684 If it is a list of two strings, the first is the actual completion
685 alternative, the second serves as annotation.
686 `standard-output' must be a buffer.
687 The actual completion alternatives, as inserted, are given `mouse-face'
688 properties of `highlight'.
689 At the end, this runs the normal hook `completion-setup-hook'.
690 It can find the completion buffer in `standard-output'.
691 The obsolete optional second arg COMMON-SUBSTRING is a string.
692 It is used to put faces, `completions-first-difference' and
693 `completions-common-part' on the completion buffer. The
694 `completions-common-part' face is put on the common substring
695 specified by COMMON-SUBSTRING."
697 (setq completions
(completion-hilit-commonality
698 completions
(length common-substring
))))
699 (if (not (bufferp standard-output
))
700 ;; This *never* (ever) happens, so there's no point trying to be clever.
702 (let ((standard-output (current-buffer))
703 (completion-setup-hook nil
))
704 (display-completion-list completions
))
705 (princ (buffer-string)))
707 (with-current-buffer standard-output
708 (goto-char (point-max))
709 (if (null completions
)
710 (insert "There are no possible completions of what you have typed.")
712 (insert "Possible completions are:\n")
713 (let ((last (last completions
)))
714 ;; Get the base-size from the tail of the list.
715 (set (make-local-variable 'completion-base-size
) (or (cdr last
) 0))
716 (setcdr last nil
)) ;Make completions a properly nil-terminated list.
717 (completion--insert-strings completions
))))
719 ;; The hilit used to be applied via completion-setup-hook, so there
720 ;; may still be some code that uses completion-common-substring.
721 (let ((completion-common-substring common-substring
))
722 (run-hooks 'completion-setup-hook
))
725 (defun minibuffer-completion-help ()
726 "Display a list of possible completions of the current minibuffer contents."
728 (message "Making completion list...")
729 (let* ((string (field-string))
730 (completions (completion-all-completions
732 minibuffer-completion-table
733 minibuffer-completion-predicate
734 (- (point) (field-beginning)))))
737 (or (consp (cdr completions
))
738 (not (equal (car completions
) string
))))
739 (with-output-to-temp-buffer "*Completions*"
740 (let* ((last (last completions
))
741 (base-size (cdr last
)))
742 ;; Remove the base-size tail because `sort' requires a properly
743 ;; nil-terminated list.
744 (when last
(setcdr last nil
))
745 (display-completion-list (nconc (sort completions
'string-lessp
)
748 ;; If there are no completions, or if the current input is already the
749 ;; only possible completion, then hide (previous&stale) completions.
750 (let ((window (and (get-buffer "*Completions*")
751 (get-buffer-window "*Completions*" 0))))
752 (when (and (window-live-p window
) (window-dedicated-p window
))
754 (delete-window window
)
755 (error (iconify-frame (window-frame window
))))))
758 (if completions
"Sole completion" "No completions")))
761 (defun exit-minibuffer ()
762 "Terminate this minibuffer argument."
764 ;; If the command that uses this has made modifications in the minibuffer,
765 ;; we don't want them to cause deactivation of the mark in the original
767 ;; A better solution would be to make deactivate-mark buffer-local
768 ;; (or to turn it into a list of buffers, ...), but in the mean time,
769 ;; this should do the trick in most cases.
770 (setq deactivate-mark nil
)
773 (defun self-insert-and-exit ()
774 "Terminate minibuffer input."
776 (if (characterp last-command-char
)
777 (call-interactively 'self-insert-command
)
781 (defun minibuffer--double-dollars (str)
782 (replace-regexp-in-string "\\$" "$$" str
))
784 (defun completion--make-envvar-table ()
785 (mapcar (lambda (enventry)
786 (substring enventry
0 (string-match "=" enventry
)))
787 process-environment
))
789 (defun completion--embedded-envvar-table (string pred action
)
790 (when (string-match (concat "\\(?:^\\|[^$]\\(?:\\$\\$\\)*\\)"
791 "$\\([[:alnum:]_]*\\|{\\([^}]*\\)\\)\\'")
793 (let* ((beg (or (match-beginning 2) (match-beginning 1)))
794 (table (completion--make-envvar-table))
795 (prefix (substring string
0 beg
)))
796 (if (eq (aref string
(1- beg
)) ?
{)
797 (setq table
(apply-partially 'completion-table-with-terminator
799 (completion-table-with-context prefix table
800 (substring string beg
)
803 (defun completion--file-name-table (string pred action
)
804 "Internal subroutine for `read-file-name'. Do not call this."
805 (if (and (zerop (length string
)) (eq 'lambda action
))
807 (let* ((dir (if (stringp pred
)
808 ;; It used to be that `pred' was abused to pass `dir'
810 (prog1 (expand-file-name pred
) (setq pred nil
))
812 (str (condition-case nil
813 (substitute-in-file-name string
)
815 (name (file-name-nondirectory str
))
816 (specdir (file-name-directory str
))
817 (realdir (if specdir
(expand-file-name specdir dir
)
818 (file-name-as-directory dir
))))
822 (let ((comp (file-name-completion name realdir
823 read-file-name-predicate
)))
825 ;; Requote the $s before returning the completion.
826 (minibuffer--double-dollars (concat specdir comp
))
827 ;; Requote the $s before checking for changes.
828 (setq str
(minibuffer--double-dollars str
))
829 (if (string-equal string str
)
831 ;; If there's no real completion, but substitute-in-file-name
832 ;; changed the string, then return the new string.
836 (let ((all (file-name-all-completions name realdir
))
837 ;; Actually, this is not always right in the presence of
838 ;; envvars, but there's not much we can do, I think.
839 (base-size (length (file-name-directory string
))))
841 ;; Check the predicate, if necessary.
842 (unless (memq read-file-name-predicate
'(nil file-exists-p
))
845 (if (eq read-file-name-predicate
'file-directory-p
)
846 ;; Brute-force speed up for directory checking:
847 ;; Discard strings which don't end in a slash.
849 (let ((len (length s
)))
850 (and (> len
0) (eq (aref s
(1- len
)) ?
/))))
851 ;; Must do it the hard (and slow) way.
852 read-file-name-predicate
)))
853 (let ((default-directory realdir
))
855 (if (funcall pred tem
) (push tem comp
))))
856 (setq all
(nreverse comp
))))
858 (if (and completion-all-completions-with-base-size
(consp all
))
859 ;; Add base-size, but only if the list is non-empty.
860 (nconc all base-size
))
865 ;; Only other case actually used is ACTION = lambda.
866 (let ((default-directory dir
))
867 (funcall (or read-file-name-predicate
'file-exists-p
) str
)))))))
869 (defalias 'read-file-name-internal
870 (completion-table-in-turn 'completion--embedded-envvar-table
871 'completion--file-name-table
)
872 "Internal subroutine for `read-file-name'. Do not call this.")
874 (defvar read-file-name-function nil
875 "If this is non-nil, `read-file-name' does its work by calling this function.")
877 (defvar read-file-name-predicate nil
878 "Current predicate used by `read-file-name-internal'.")
880 (defcustom read-file-name-completion-ignore-case
881 (if (memq system-type
'(ms-dos windows-nt darwin macos vax-vms axp-vms
))
883 "Non-nil means when reading a file name completion ignores case."
888 (defcustom insert-default-directory t
889 "Non-nil means when reading a filename start with default dir in minibuffer.
891 When the initial minibuffer contents show a name of a file or a directory,
892 typing RETURN without editing the initial contents is equivalent to typing
893 the default file name.
895 If this variable is non-nil, the minibuffer contents are always
896 initially non-empty, and typing RETURN without editing will fetch the
897 default name, if one is provided. Note however that this default name
898 is not necessarily the same as initial contents inserted in the minibuffer,
899 if the initial contents is just the default directory.
901 If this variable is nil, the minibuffer often starts out empty. In
902 that case you may have to explicitly fetch the next history element to
903 request the default name; typing RETURN without editing will leave
904 the minibuffer empty.
906 For some commands, exiting with an empty minibuffer has a special meaning,
907 such as making the current buffer visit no file in the case of
908 `set-visited-file-name'."
912 ;; Not always defined, but only called if next-read-file-uses-dialog-p says so.
913 (declare-function x-file-dialog
"xfns.c"
914 (prompt dir
&optional default-filename mustmatch only-dir-p
))
916 (defun read-file-name (prompt &optional dir default-filename mustmatch initial predicate
)
917 "Read file name, prompting with PROMPT and completing in directory DIR.
918 Value is not expanded---you must call `expand-file-name' yourself.
919 Default name to DEFAULT-FILENAME if user exits the minibuffer with
920 the same non-empty string that was inserted by this function.
921 (If DEFAULT-FILENAME is omitted, the visited file name is used,
922 except that if INITIAL is specified, that combined with DIR is used.)
923 If the user exits with an empty minibuffer, this function returns
924 an empty string. (This can only happen if the user erased the
925 pre-inserted contents or if `insert-default-directory' is nil.)
926 Fourth arg MUSTMATCH non-nil means require existing file's name.
927 Non-nil and non-t means also require confirmation after completion.
928 Fifth arg INITIAL specifies text to start with.
929 If optional sixth arg PREDICATE is non-nil, possible completions and
930 the resulting file name must satisfy (funcall PREDICATE NAME).
931 DIR should be an absolute directory name. It defaults to the value of
934 If this command was invoked with the mouse, use a file dialog box if
935 `use-dialog-box' is non-nil, and the window system or X toolkit in use
936 provides a file dialog box.
938 See also `read-file-name-completion-ignore-case'
939 and `read-file-name-function'."
940 (unless dir
(setq dir default-directory
))
941 (unless (file-name-absolute-p dir
) (setq dir
(expand-file-name dir
)))
942 (unless default-filename
943 (setq default-filename
(if initial
(expand-file-name initial dir
)
945 ;; If dir starts with user's homedir, change that to ~.
946 (setq dir
(abbreviate-file-name dir
))
947 ;; Likewise for default-filename.
949 (setq default-filename
(abbreviate-file-name default-filename
)))
951 ((and insert-default-directory
(stringp dir
))
953 (cons (minibuffer--double-dollars (concat dir initial
))
954 (length (minibuffer--double-dollars dir
)))
955 (minibuffer--double-dollars dir
)))
956 (initial (cons (minibuffer--double-dollars initial
) 0)))))
958 (if read-file-name-function
959 (funcall read-file-name-function
960 prompt dir default-filename mustmatch initial predicate
)
961 (let ((completion-ignore-case read-file-name-completion-ignore-case
)
962 (minibuffer-completing-file-name t
)
963 (read-file-name-predicate (or predicate
'file-exists-p
))
964 (add-to-history nil
))
967 (if (not (next-read-file-uses-dialog-p))
968 ;; We used to pass `dir' to `read-file-name-internal' by
969 ;; abusing the `predicate' argument. It's better to
970 ;; just use `default-directory', but in order to avoid
971 ;; changing `default-directory' in the current buffer,
972 ;; we don't let-bind it.
973 (lexical-let ((dir (file-name-as-directory
974 (expand-file-name dir
))))
975 (minibuffer-with-setup-hook
976 (lambda () (setq default-directory dir
))
977 (completing-read prompt
'read-file-name-internal
978 nil mustmatch insdef
'file-name-history
980 ;; If DIR contains a file name, split it.
981 (let ((file (file-name-nondirectory dir
)))
982 (when (and default-filename
(not (zerop (length file
))))
983 (setq default-filename file
)
984 (setq dir
(file-name-directory dir
)))
986 (setq default-filename
987 (expand-file-name default-filename dir
)))
988 (setq add-to-history t
)
989 (x-file-dialog prompt dir default-filename mustmatch
990 (eq predicate
'file-directory-p
)))))
992 (replace-in-history (eq (car-safe file-name-history
) val
)))
993 ;; If completing-read returned the inserted default string itself
994 ;; (rather than a new string with the same contents),
995 ;; it has to mean that the user typed RET with the minibuffer empty.
996 ;; In that case, we really want to return ""
997 ;; so that commands such as set-visited-file-name can distinguish.
998 (when (eq val default-filename
)
999 ;; In this case, completing-read has not added an element
1000 ;; to the history. Maybe we should.
1001 (if (not replace-in-history
)
1002 (setq add-to-history t
))
1004 (unless val
(error "No file name specified"))
1006 (if (and default-filename
1007 (string-equal val
(if (consp insdef
) (car insdef
) insdef
)))
1008 (setq val default-filename
))
1009 (setq val
(substitute-in-file-name val
))
1011 (if replace-in-history
1012 ;; Replace what Fcompleting_read added to the history
1013 ;; with what we will actually return.
1014 (let ((val1 (minibuffer--double-dollars val
)))
1015 (if history-delete-duplicates
1016 (setcdr file-name-history
1017 (delete val1
(cdr file-name-history
))))
1018 (setcar file-name-history val1
))
1020 ;; Add the value to the history--but not if it matches
1021 ;; the last value already there.
1022 (let ((val1 (minibuffer--double-dollars val
)))
1023 (unless (and (consp file-name-history
)
1024 (equal (car file-name-history
) val1
))
1025 (setq file-name-history
1027 (if history-delete-duplicates
1028 (delete val1 file-name-history
)
1029 file-name-history
)))))))
1032 (defun internal-complete-buffer-except (&optional buffer
)
1033 "Perform completion on all buffers excluding BUFFER.
1034 Like `internal-complete-buffer', but removes BUFFER from the completion list."
1035 (lexical-let ((except (if (stringp buffer
) buffer
(buffer-name buffer
))))
1036 (apply-partially 'completion-table-with-predicate
1037 'internal-complete-buffer
1039 (not (equal (if (consp name
) (car name
) name
) except
)))
1042 ;;; Old-style completion, used in Emacs-21.
1044 (defun completion-emacs21-try-completion (string table pred point
)
1045 (let ((completion (try-completion string table pred
)))
1046 (if (stringp completion
)
1047 (cons completion
(length completion
))
1050 (defun completion-emacs21-all-completions (string table pred point
)
1051 (completion-hilit-commonality
1052 (all-completions string table pred t
)
1055 ;;; Basic completion, used in Emacs-22.
1057 (defun completion-emacs22-try-completion (string table pred point
)
1058 (let ((suffix (substring string point
))
1059 (completion (try-completion (substring string
0 point
) table pred
)))
1060 (if (not (stringp completion
))
1062 ;; Merge a trailing / in completion with a / after point.
1063 ;; We used to only do it for word completion, but it seems to make
1064 ;; sense for all completions.
1065 ;; Actually, claiming this feature was part of Emacs-22 completion
1066 ;; is pushing it a bit: it was only done in minibuffer-completion-word,
1067 ;; which was (by default) not bound during file completion, where such
1068 ;; slashes are most likely to occur.
1069 (if (and (not (zerop (length completion
)))
1070 (eq ?
/ (aref completion
(1- (length completion
))))
1071 (not (zerop (length suffix
)))
1072 (eq ?
/ (aref suffix
0)))
1073 ;; This leaves point after the / .
1074 (setq suffix
(substring suffix
1)))
1075 (cons (concat completion suffix
) (length completion
)))))
1077 (defun completion-emacs22-all-completions (string table pred point
)
1078 (completion-hilit-commonality
1079 (all-completions (substring string
0 point
) table pred t
)
1082 (defun completion-basic-try-completion (string table pred point
)
1083 (let ((suffix (substring string point
))
1084 (completion (try-completion (substring string
0 point
) table pred
)))
1085 (if (not (stringp completion
))
1087 ;; Merge end of completion with beginning of suffix.
1088 ;; Simple generalization of the "merge trailing /" done in Emacs-22.
1089 (when (and (not (zerop (length suffix
)))
1090 (string-match "\\(.+\\)\n\\1" (concat completion
"\n" suffix
)
1091 ;; Make sure we don't compress things to less
1092 ;; than we started with.
1094 ;; Just make sure we didn't match some other \n.
1095 (eq (match-end 1) (length completion
)))
1096 (setq suffix
(substring suffix
(- (match-end 1) (match-beginning 1)))))
1098 (cons (concat completion suffix
) (length completion
)))))
1100 (defalias 'completion-basic-all-completions
'completion-emacs22-all-completions
)
1102 ;;; Partial-completion-mode style completion.
1106 ;; - "minibuffer-s- TAB" with minibuffer-selected-window ends up with
1107 ;; "minibuffer--s-" which matches other options.
1109 (defvar completion-pcm--delim-wild-regex nil
)
1111 (defun completion-pcm--prepare-delim-re (delims)
1112 (setq completion-pcm--delim-wild-regex
(concat "[" delims
"*]")))
1114 (defcustom completion-pcm-word-delimiters
"-_. "
1115 "A string of characters treated as word delimiters for completion.
1117 If `]' is in this string, it must come first.
1118 If `^' is in this string, it must not come first.
1119 If `-' is in this string, it must come first or right after `]'.
1120 In other words, if S is this string, then `[S]' must be a valid Emacs regular
1121 expression (not containing character ranges like `a-z')."
1122 :set
(lambda (symbol value
)
1123 (set-default symbol value
)
1124 ;; Refresh other vars.
1125 (completion-pcm--prepare-delim-re value
))
1126 :initialize
'custom-initialize-reset
1130 (defun completion-pcm--pattern-trivial-p (pattern)
1131 (and (stringp (car pattern
)) (null (cdr pattern
))))
1133 (defun completion-pcm--string->pattern
(basestr &optional point
)
1134 "Split BASESTR into a pattern.
1135 A pattern is a list where each element is either a string
1136 or a symbol chosen among `any', `star', `point'."
1137 (if (and point
(< point
(length basestr
)))
1138 (let ((prefix (substring basestr
0 point
))
1139 (suffix (substring basestr point
)))
1140 (append (completion-pcm--string->pattern prefix
)
1142 (completion-pcm--string->pattern suffix
)))
1147 (while (setq p
(string-match completion-pcm--delim-wild-regex basestr p
))
1148 (push (substring basestr p0 p
) pattern
)
1149 (if (eq (aref basestr p
) ?
*)
1151 (push 'star pattern
)
1157 ;; An empty string might be erroneously added at the beginning.
1158 ;; It should be avoided properly, but it's so easy to remove it here.
1159 (delete "" (nreverse (cons (substring basestr p0
) pattern
))))))
1161 (defun completion-pcm--pattern->regex
(pattern &optional group
)
1166 ((star any point
) (if (if (consp group
) (memq x group
) group
)
1168 (t (regexp-quote x
))))
1172 (defun completion-pcm--all-completions (pattern table pred
)
1173 "Find all completions for PATTERN in TABLE obeying PRED.
1174 PATTERN is as returned by `completion-pcm--string->pattern'."
1175 ;; Find an initial list of possible completions.
1176 (if (completion-pcm--pattern-trivial-p pattern
)
1178 ;; Minibuffer contains no delimiters -- simple case!
1179 (all-completions (car pattern
) table pred
)
1181 ;; Use all-completions to do an initial cull. This is a big win,
1182 ;; since all-completions is written in C!
1183 (let* (;; Convert search pattern to a standard regular expression.
1184 (regex (completion-pcm--pattern->regex pattern
))
1185 (completion-regexp-list (cons regex completion-regexp-list
))
1186 (compl (all-completions
1187 (if (stringp (car pattern
)) (car pattern
) "")
1189 (last (last compl
)))
1190 ;; FIXME: If `base-size' is not 0, we have a problem :-(
1191 (if last
(setcdr last nil
))
1192 (if (not (functionp table
))
1193 ;; The internal functions already obeyed completion-regexp-list.
1195 (let ((case-fold-search completion-ignore-case
)
1198 (when (string-match regex c
) (push c poss
)))
1201 (defun completion-pcm--hilit-commonality (pattern completions
)
1203 (let* ((re (completion-pcm--pattern->regex pattern
'(point)))
1204 (last (last completions
))
1205 (base-size (cdr last
)))
1206 ;; Remove base-size during mapcar, and add it back later.
1211 ;; Don't modify the string itself.
1212 (setq str
(copy-sequence str
))
1213 (unless (string-match re str
)
1214 (error "Internal error: %s does not match %s" re str
))
1215 (let ((pos (or (match-beginning 1) (match-end 0))))
1216 (put-text-property 0 pos
1217 'font-lock-face
'completions-common-part
1219 (if (> (length str
) pos
)
1220 (put-text-property pos
(1+ pos
)
1221 'font-lock-face
'completions-first-difference
1227 (defun completion-pcm-all-completions (string table pred point
)
1228 (let ((pattern (completion-pcm--string->pattern string point
)))
1229 (completion-pcm--hilit-commonality
1231 (completion-pcm--all-completions pattern table pred
))))
1233 (defun completion-pcm--merge-completions (strs pattern
)
1234 "Extract the commonality in STRS, with the help of PATTERN."
1236 ((null (cdr strs
)) (list (car strs
)))
1238 (let ((re (completion-pcm--pattern->regex pattern
'group
))
1239 (ccs ())) ;Chopped completions.
1241 ;; First chop each string into the parts corresponding to each
1242 ;; non-constant element of `pattern', using regexp-matching.
1243 (let ((case-fold-search completion-ignore-case
))
1245 (unless (string-match re str
)
1246 (error "Internal error: %s doesn't match %s" str re
))
1249 (while (match-beginning i
)
1250 (push (match-string i str
) chopped
)
1252 ;; Add the text corresponding to the implicit trailing `any'.
1253 (push (substring str
(match-end 0)) chopped
)
1254 (push (nreverse chopped
) ccs
))))
1256 ;; Then for each of those non-constant elements, extract the
1257 ;; commonality between them.
1259 ;; Make the implicit `any' explicit. We could make it explicit
1260 ;; everywhere, but it would slow down regexp-matching a little bit.
1261 (dolist (elem (append pattern
'(any)))
1265 (dolist (cc (prog1 ccs
(setq ccs nil
)))
1266 (push (car cc
) comps
)
1267 (push (cdr cc
) ccs
))
1268 (let* ((prefix (try-completion "" comps
))
1269 (unique (or (and (eq prefix t
) (setq prefix
""))
1270 (eq t
(try-completion prefix comps
)))))
1271 (unless (equal prefix
"") (push prefix res
))
1272 ;; If there's only one completion, `elem' is not useful
1273 ;; any more: it can only match the empty string.
1274 ;; FIXME: in some cases, it may be necessary to turn an
1275 ;; `any' into a `star' because the surrounding context has
1276 ;; changed such that string->pattern wouldn't add an `any'
1278 (unless unique
(push elem res
))))))
1279 ;; We return it in reverse order.
1282 (defun completion-pcm--pattern->string
(pattern)
1283 (mapconcat (lambda (x) (cond
1287 ((eq x
'point
) "")))
1291 (defun completion-pcm-try-completion (string table pred point
)
1292 (let* ((pattern (completion-pcm--string->pattern string point
))
1293 (all (completion-pcm--all-completions pattern table pred
)))
1295 (let* ((mergedpat (completion-pcm--merge-completions all pattern
))
1296 ;; `mergedpat' is in reverse order. Place new point (by
1297 ;; order of preference) either at the old point, or at
1298 ;; the last place where there's something to choose, or
1300 (pointpat (or (memq 'point mergedpat
) (memq 'any mergedpat
)
1302 ;; New pos from the start.
1303 (newpos (length (completion-pcm--pattern->string pointpat
)))
1304 ;; Do it afterwards because it changes `pointpat' by sideeffect.
1305 (merged (completion-pcm--pattern->string
(nreverse mergedpat
))))
1306 (cons merged newpos
)))))
1309 (provide 'minibuffer
)
1311 ;; arch-tag: ef8a0a15-1080-4790-a754-04017c02f08f
1312 ;;; minibuffer.el ends here