1 ;;; minibuffer.el --- Minibuffer completion functions
3 ;; Copyright (C) 2008, 2009 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 with "--" are for functions and variables that are meant to be for
27 ;; Functional completion tables have an extended calling conventions:
28 ;; - The `action' can be (additionally to nil, t, and lambda) of the form
29 ;; (boundaries . SUFFIX) in which case it should return
30 ;; (boundaries START . END). See `completion-boundaries'.
31 ;; Any other return value should be ignored (so we ignore values returned
32 ;; from completion tables that don't know about this new `action' form).
36 ;; - completion-all-sorted-completions list all the completions, whereas
37 ;; it should only lists the ones that `try-completion' would consider.
38 ;; E.g. it should honor completion-ignored-extensions.
39 ;; - choose-completion can't automatically figure out the boundaries
40 ;; corresponding to the displayed completions. `base-size' gives the left
41 ;; boundary, but not the righthand one. So we need to add
42 ;; completion-extra-size.
46 ;; - make partial-complete-mode obsolete:
47 ;; - (?) <foo.h> style completion for file names.
49 ;; - case-sensitivity is currently confuses two issues:
50 ;; - whether or not a particular completion table should be case-sensitive
51 ;; (i.e. whether strings that different only by case are semantically
53 ;; - whether the user wants completion to pay attention to case.
54 ;; e.g. we may want to make it possible for the user to say "first try
55 ;; completion case-sensitively, and if that fails, try to ignore case".
57 ;; - make lisp-complete-symbol and sym-comp use it.
58 ;; - add support for ** to pcm.
59 ;; - Make read-file-name-predicate obsolete.
60 ;; - Add vc-file-name-completion-table to read-file-name-internal.
61 ;; - A feature like completing-help.el.
62 ;; - make lisp/complete.el obsolete.
63 ;; - Make the `hide-spaces' arg of all-completions obsolete?
67 (eval-when-compile (require 'cl
))
69 ;;; Completion table manipulation
71 ;; New completion-table operation.
72 (defun completion-boundaries (string table pred suffix
)
73 "Return the boundaries of the completions returned by TABLE for STRING.
74 STRING is the string on which completion will be performed.
75 SUFFIX is the string after point.
76 The result is of the form (START . END) where START is the position
77 in STRING of the beginning of the completion field and END is the position
78 in SUFFIX of the end of the completion field.
79 E.g. for simple completion tables, the result is always (0 . (length SUFFIX))
80 and for file names the result is the positions delimited by
81 the closest directory separators."
82 (let ((boundaries (if (functionp table
)
83 (funcall table string pred
(cons 'boundaries suffix
)))))
84 (if (not (eq (car-safe boundaries
) 'boundaries
))
85 (setq boundaries nil
))
86 (cons (or (cadr boundaries
) 0)
87 (or (cddr boundaries
) (length suffix
)))))
89 (defun completion--some (fun xs
)
90 "Apply FUN to each element of XS in turn.
91 Return the first non-nil returned value.
93 (let ((firsterror nil
)
95 (while (and (not res
) xs
)
97 (setq res
(funcall fun
(pop xs
)))
98 (error (unless firsterror
(setq firsterror err
)) nil
)))
100 (if firsterror
(signal (car firsterror
) (cdr firsterror
))))))
102 (defun complete-with-action (action table string pred
)
103 "Perform completion ACTION.
104 STRING is the string to complete.
105 TABLE is the completion table, which should not be a function.
106 PRED is a completion predicate.
107 ACTION can be one of nil, t or `lambda'."
109 ((functionp table
) (funcall table string pred action
))
110 ((eq (car-safe action
) 'boundaries
)
111 (cons 'boundaries
(completion-boundaries string table pred
(cdr action
))))
115 ((null action
) 'try-completion
)
116 ((eq action t
) 'all-completions
)
117 (t 'test-completion
))
118 string table pred
))))
120 (defun completion-table-dynamic (fun)
121 "Use function FUN as a dynamic completion table.
122 FUN is called with one argument, the string for which completion is required,
123 and it should return an alist containing all the intended possible completions.
124 This alist may be a full list of possible completions so that FUN can ignore
125 the value of its argument. If completion is performed in the minibuffer,
126 FUN will be called in the buffer from which the minibuffer was entered.
128 The result of the `completion-table-dynamic' form is a function
129 that can be used as the COLLECTION argument to `try-completion' and
130 `all-completions'. See Info node `(elisp)Programmed Completion'."
131 (lexical-let ((fun fun
))
132 (lambda (string pred action
)
133 (with-current-buffer (let ((win (minibuffer-selected-window)))
134 (if (window-live-p win
) (window-buffer win
)
136 (complete-with-action action
(funcall fun string
) string pred
)))))
138 (defmacro lazy-completion-table
(var fun
)
139 "Initialize variable VAR as a lazy completion table.
140 If the completion table VAR is used for the first time (e.g., by passing VAR
141 as an argument to `try-completion'), the function FUN is called with no
142 arguments. FUN must return the completion table that will be stored in VAR.
143 If completion is requested in the minibuffer, FUN will be called in the buffer
144 from which the minibuffer was entered. The return value of
145 `lazy-completion-table' must be used to initialize the value of VAR.
147 You should give VAR a non-nil `risky-local-variable' property."
148 (declare (debug (symbolp lambda-expr
)))
149 (let ((str (make-symbol "string")))
150 `(completion-table-dynamic
152 (when (functionp ,var
)
156 (defun completion-table-with-context (prefix table string pred action
)
157 ;; TODO: add `suffix' maybe?
158 ;; Notice that `pred' may not be a function in some abusive cases.
159 (when (functionp pred
)
161 (lexical-let ((pred pred
))
162 ;; Predicates are called differently depending on the nature of
163 ;; the completion table :-(
165 ((vectorp table
) ;Obarray.
166 (lambda (sym) (funcall pred
(concat prefix
(symbol-name sym
)))))
167 ((hash-table-p table
)
168 (lambda (s v
) (funcall pred
(concat prefix s
))))
170 (lambda (s) (funcall pred
(concat prefix s
))))
171 (t ;Lists and alists.
173 (funcall pred
(concat prefix
(if (consp s
) (car s
) s
)))))))))
174 (if (eq (car-safe action
) 'boundaries
)
175 (let* ((len (length prefix
))
176 (bound (completion-boundaries string table pred
(cdr action
))))
177 (list* 'boundaries
(+ (car bound
) len
) (cdr bound
)))
178 (let ((comp (complete-with-action action table string pred
)))
180 ;; In case of try-completion, add the prefix.
181 ((stringp comp
) (concat prefix comp
))
184 (defun completion-table-with-terminator (terminator table string pred action
)
187 (let ((comp (try-completion string table pred
)))
189 (concat string terminator
)
190 (if (and (stringp comp
)
191 (eq (try-completion comp table pred
) t
))
192 (concat comp terminator
)
195 ;; FIXME: We generally want the `try' and `all' behaviors to be
196 ;; consistent so pcm can merge the `all' output to get the `try' output,
197 ;; but that sometimes clashes with the need for `all' output to look
198 ;; good in *Completions*.
199 ;; (mapcar (lambda (s) (concat s terminator))
200 ;; (all-completions string table pred))))
201 (all-completions string table pred
))
202 ;; completion-table-with-terminator is always used for
203 ;; "sub-completions" so it's only called if the terminator is missing,
204 ;; in which case `test-completion' should return nil.
205 ((eq action
'lambda
) nil
)))
207 (defun completion-table-with-predicate (table pred1 strict string pred2 action
)
208 "Make a completion table equivalent to TABLE but filtered through PRED1.
209 PRED1 is a function of one argument which returns non-nil if and only if the
210 argument is an element of TABLE which should be considered for completion.
211 STRING, PRED2, and ACTION are the usual arguments to completion tables,
212 as described in `try-completion', `all-completions', and `test-completion'.
213 If STRICT is t, the predicate always applies; if nil it only applies if
214 it does not reduce the set of possible completions to nothing.
215 Note: TABLE needs to be a proper completion table which obeys predicates."
217 ((and (not strict
) (eq action
'lambda
))
218 ;; Ignore pred1 since it doesn't really have to apply anyway.
219 (test-completion string table pred2
))
221 (or (complete-with-action action table string
222 (if (null pred2
) pred1
223 (lexical-let ((pred1 pred2
) (pred2 pred2
))
225 ;; Call `pred1' first, so that `pred2'
226 ;; really can't tell that `x' is in table.
227 (if (funcall pred1 x
) (funcall pred2 x
))))))
228 ;; If completion failed and we're not applying pred1 strictly, try
229 ;; again without pred1.
231 (complete-with-action action table string pred2
))))))
233 (defun completion-table-in-turn (&rest tables
)
234 "Create a completion table that tries each table in TABLES in turn."
235 (lexical-let ((tables tables
))
236 (lambda (string pred action
)
237 (completion--some (lambda (table)
238 (complete-with-action action table string pred
))
241 ;; (defmacro complete-in-turn (a b) `(completion-table-in-turn ,a ,b))
242 ;; (defmacro dynamic-completion-table (fun) `(completion-table-dynamic ,fun))
243 (define-obsolete-function-alias
244 'complete-in-turn
'completion-table-in-turn
"23.1")
245 (define-obsolete-function-alias
246 'dynamic-completion-table
'completion-table-dynamic
"23.1")
248 ;;; Minibuffer completion
250 (defgroup minibuffer nil
251 "Controlling the behavior of the minibuffer."
252 :link
'(custom-manual "(emacs)Minibuffer")
255 (defun minibuffer-message (message &rest args
)
256 "Temporarily display MESSAGE at the end of the minibuffer.
257 The text is displayed for `minibuffer-message-timeout' seconds,
258 or until the next input event arrives, whichever comes first.
259 Enclose MESSAGE in [...] if this is not yet the case.
260 If ARGS are provided, then pass MESSAGE through `format'."
261 (if (not (minibufferp (current-buffer)))
264 (apply 'message message args
)
265 (message "%s" message
))
266 (prog1 (sit-for (or minibuffer-message-timeout
1000000))
268 ;; Clear out any old echo-area message to make way for our new thing.
270 (setq message
(if (and (null args
) (string-match-p "\\` *\\[.+\\]\\'" message
))
271 ;; Make sure we can put-text-property.
272 (copy-sequence message
)
273 (concat " [" message
"]")))
274 (when args
(setq message
(apply 'format message args
)))
275 (let ((ol (make-overlay (point-max) (point-max) nil t t
))
276 ;; A quit during sit-for normally only interrupts the sit-for,
277 ;; but since minibuffer-message is used at the end of a command,
278 ;; at a time when the command has virtually finished already, a C-g
279 ;; should really cause an abort-recursive-edit instead (i.e. as if
280 ;; the C-g had been typed at top-level). Binding inhibit-quit here
281 ;; is an attempt to get that behavior.
285 (unless (zerop (length message
))
286 ;; The current C cursor code doesn't know to use the overlay's
287 ;; marker's stickiness to figure out whether to place the cursor
288 ;; before or after the string, so let's spoon-feed it the pos.
289 (put-text-property 0 1 'cursor t message
))
290 (overlay-put ol
'after-string message
)
291 (sit-for (or minibuffer-message-timeout
1000000)))
292 (delete-overlay ol
)))))
294 (defun minibuffer-completion-contents ()
295 "Return the user input in a minibuffer before point as a string.
296 That is what completion commands operate on."
297 (buffer-substring (field-beginning) (point)))
299 (defun delete-minibuffer-contents ()
300 "Delete all user input in a minibuffer.
301 If the current buffer is not a minibuffer, erase its entire contents."
302 ;; We used to do `delete-field' here, but when file name shadowing
303 ;; is on, the field doesn't cover the entire minibuffer contents.
304 (delete-region (minibuffer-prompt-end) (point-max)))
306 (defcustom completion-auto-help t
307 "Non-nil means automatically provide help for invalid completion input.
308 If the value is t the *Completion* buffer is displayed whenever completion
309 is requested but cannot be done.
310 If the value is `lazy', the *Completions* buffer is only displayed after
311 the second failed attempt to complete."
312 :type
'(choice (const nil
) (const t
) (const lazy
))
315 (defvar completion-styles-alist
317 completion-emacs21-try-completion completion-emacs21-all-completions
318 "Simple prefix-based completion.")
320 completion-emacs22-try-completion completion-emacs22-all-completions
321 "Prefix completion that only operates on the text before point.")
323 completion-basic-try-completion completion-basic-all-completions
324 "Completion of the prefix before point and the suffix after point.")
326 completion-pcm-try-completion completion-pcm-all-completions
327 "Completion of multiple words, each one taken as a prefix.
328 E.g. M-x l-c-h can complete to list-command-history
329 and C-x C-f /u/m/s to /usr/monnier/src.")
331 completion-initials-try-completion completion-initials-all-completions
332 "Completion of acronyms and initialisms.
333 E.g. can complete M-x lch to list-command-history
334 and C-x C-f ~/sew to ~/src/emacs/work."))
335 "List of available completion styles.
336 Each element has the form (NAME TRY-COMPLETION ALL-COMPLETIONS DOC):
337 where NAME is the name that should be used in `completion-styles',
338 TRY-COMPLETION is the function that does the completion (it should
339 follow the same calling convention as `completion-try-completion'),
340 ALL-COMPLETIONS is the function that lists the completions (it should
341 follow the calling convention of `completion-all-completions'),
342 and DOC describes the way this style of completion works.")
344 (defcustom completion-styles
'(basic partial-completion emacs22
)
345 "List of completion styles to use.
346 The available styles are listed in `completion-styles-alist'."
347 :type
`(repeat (choice ,@(mapcar (lambda (x) (list 'const
(car x
)))
348 completion-styles-alist
)))
352 (defun completion-try-completion (string table pred point
)
353 "Try to complete STRING using completion table TABLE.
354 Only the elements of table that satisfy predicate PRED are considered.
355 POINT is the position of point within STRING.
356 The return value can be either nil to indicate that there is no completion,
357 t to indicate that STRING is the only possible completion,
358 or a pair (STRING . NEWPOINT) of the completed result string together with
359 a new position for point."
360 (completion--some (lambda (style)
361 (funcall (nth 1 (assq style completion-styles-alist
))
362 string table pred point
))
365 (defun completion-all-completions (string table pred point
)
366 "List the possible completions of STRING in completion table TABLE.
367 Only the elements of table that satisfy predicate PRED are considered.
368 POINT is the position of point within STRING.
369 The return value is a list of completions and may contain the base-size
371 ;; FIXME: We need to additionally return completion-extra-size (similar
372 ;; to completion-base-size but for the text after point).
373 (completion--some (lambda (style)
374 (funcall (nth 2 (assq style completion-styles-alist
))
375 string table pred point
))
378 (defun minibuffer--bitset (modified completions exact
)
379 (logior (if modified
4 0)
383 (defun completion--do-completion (&optional try-completion-function
)
384 "Do the completion and return a summary of what happened.
385 M = completion was performed, the text was Modified.
386 C = there were available Completions.
387 E = after completion we now have an Exact match.
390 000 0 no possible completion
391 001 1 was already an exact and unique completion
392 010 2 no completion happened
393 011 3 was already an exact completion
396 110 6 some completion happened
397 111 7 completed to an exact completion"
398 (let* ((beg (field-beginning))
400 (string (buffer-substring beg end
))
401 (comp (funcall (or try-completion-function
402 'completion-try-completion
)
404 minibuffer-completion-table
405 minibuffer-completion-predicate
409 (minibuffer-hide-completions)
410 (ding) (minibuffer-message "No match") (minibuffer--bitset nil nil nil
))
412 (minibuffer-hide-completions)
413 (goto-char (field-end))
414 (minibuffer--bitset nil nil t
)) ;Exact and unique match.
416 ;; `completed' should be t if some completion was done, which doesn't
417 ;; include simply changing the case of the entered string. However,
418 ;; for appearance, the string is rewritten if the case changes.
419 (let* ((comp-pos (cdr comp
))
420 (completion (car comp
))
421 (completed (not (eq t
(compare-strings completion nil nil
423 (unchanged (eq t
(compare-strings completion nil nil
424 string nil nil nil
))))
427 ;; Insert in minibuffer the chars we got.
430 (delete-region beg end
))
432 (goto-char (+ beg comp-pos
))
434 (if (not (or unchanged completed
))
435 ;; The case of the string changed, but that's all. We're not sure
436 ;; whether this is a unique completion or not, so try again using
437 ;; the real case (this shouldn't recurse again, because the next
438 ;; time try-completion will return either t or the exact string).
439 (completion--do-completion try-completion-function
)
441 ;; It did find a match. Do we match some possibility exactly now?
442 (let ((exact (test-completion completion
443 minibuffer-completion-table
444 minibuffer-completion-predicate
)))
446 ;; We could also decide to refresh the completions,
447 ;; if they're displayed (and assuming there are
448 ;; completions left).
449 (minibuffer-hide-completions)
450 ;; Show the completion table, if requested.
453 (if (case completion-auto-help
454 (lazy (eq this-command last-command
))
455 (t completion-auto-help
))
456 (minibuffer-completion-help)
457 (minibuffer-message "Next char not unique")))
458 ;; If the last exact completion and this one were the same, it
459 ;; means we've already given a "Next char not unique" message
460 ;; and the user's hit TAB again, so now we give him help.
461 ((eq this-command last-command
)
462 (if completion-auto-help
(minibuffer-completion-help)))))
464 (minibuffer--bitset completed t exact
))))))))
466 (defun minibuffer-complete ()
467 "Complete the minibuffer contents as far as possible.
468 Return nil if there is no valid completion, else t.
469 If no characters can be completed, display a list of possible completions.
470 If you repeat this command after it displayed such a list,
471 scroll the window of possible completions."
473 ;; If the previous command was not this,
474 ;; mark the completion buffer obsolete.
475 (unless (eq this-command last-command
)
476 (setq minibuffer-scroll-window nil
))
478 (let ((window minibuffer-scroll-window
))
479 ;; If there's a fresh completion window with a live buffer,
480 ;; and this command is repeated, scroll that window.
481 (if (window-live-p window
)
482 (with-current-buffer (window-buffer window
)
483 (if (pos-visible-in-window-p (point-max) window
)
484 ;; If end is in view, scroll up to the beginning.
485 (set-window-start window
(point-min) nil
)
486 ;; Else scroll down one screen.
487 (scroll-other-window))
490 (case (completion--do-completion)
492 (#b001
(minibuffer-message "Sole completion")
494 (#b011
(minibuffer-message "Complete, but not unique")
498 (defvar completion-all-sorted-completions nil
)
499 (make-variable-buffer-local 'completion-all-sorted-completions
)
501 (defun completion--flush-all-sorted-completions (&rest ignore
)
502 (setq completion-all-sorted-completions nil
))
504 (defun completion-all-sorted-completions ()
505 (or completion-all-sorted-completions
506 (let* ((start (field-beginning))
508 (all (completion-all-completions (buffer-substring start end
)
509 minibuffer-completion-table
510 minibuffer-completion-predicate
513 (base-size (or (cdr last
) 0)))
516 ;; Prefer shorter completions.
517 (setq all
(sort all
(lambda (c1 c2
) (< (length c1
) (length c2
)))))
518 ;; Prefer recently used completions.
519 (let ((hist (symbol-value minibuffer-history-variable
)))
520 (setq all
(sort all
(lambda (c1 c2
)
521 (> (length (member c1 hist
))
522 (length (member c2 hist
)))))))
523 ;; Cache the result. This is not just for speed, but also so that
524 ;; repeated calls to minibuffer-force-complete can cycle through
525 ;; all possibilities.
526 (add-hook 'after-change-functions
527 'completion--flush-all-sorted-completions nil t
)
528 (setq completion-all-sorted-completions
529 (nconc all base-size
))))))
531 (defun minibuffer-force-complete ()
532 "Complete the minibuffer to an exact match.
533 Repeated uses step through the possible completions."
535 ;; FIXME: Need to deal with the extra-size issue here as well.
536 (let* ((start (field-beginning))
538 (all (completion-all-sorted-completions)))
539 (if (not (consp all
))
540 (minibuffer-message (if all
"No more completions" "No completions"))
543 (delete-region (+ start
(cdr (last all
))) end
)
544 ;; If completing file names, (car all) may be a directory, so we'd now
545 ;; have a new set of possible completions and might want to reset
546 ;; completion-all-sorted-completions to nil, but we prefer not to,
547 ;; so that repeated calls minibuffer-force-complete still cycle
548 ;; through the previous possible completions.
549 (let ((last (last all
)))
550 (setcdr last
(cons (car all
) (cdr last
)))
551 (setq completion-all-sorted-completions
(cdr all
))))))
553 (defvar minibuffer-confirm-exit-commands
554 '(minibuffer-complete minibuffer-complete-word PC-complete PC-complete-word
)
555 "A list of commands which cause an immediately following
556 `minibuffer-complete-and-exit' to ask for extra confirmation.")
558 (defun minibuffer-complete-and-exit ()
559 "Exit if the minibuffer contains a valid completion.
560 Otherwise, try to complete the minibuffer contents. If
561 completion leads to a valid completion, a repetition of this
564 If `minibuffer-completion-confirm' is `confirm', do not try to
565 complete; instead, ask for confirmation and accept any input if
567 If `minibuffer-completion-confirm' is `confirm-after-completion',
568 do not try to complete; instead, ask for confirmation if the
569 preceding minibuffer command was a member of
570 `minibuffer-confirm-exit-commands', and accept the input
573 (let ((beg (field-beginning))
576 ;; Allow user to specify null string
577 ((= beg end
) (exit-minibuffer))
578 ((test-completion (buffer-substring beg end
)
579 minibuffer-completion-table
580 minibuffer-completion-predicate
)
581 (when completion-ignore-case
582 ;; Fixup case of the field, if necessary.
583 (let* ((string (buffer-substring beg end
))
584 (compl (try-completion
586 minibuffer-completion-table
587 minibuffer-completion-predicate
)))
588 (when (and (stringp compl
)
589 ;; If it weren't for this piece of paranoia, I'd replace
590 ;; the whole thing with a call to do-completion.
591 ;; This is important, e.g. when the current minibuffer's
592 ;; content is a directory which only contains a single
593 ;; file, so `try-completion' actually completes to
595 (= (length string
) (length compl
)))
598 (delete-region beg end
))))
601 ((eq minibuffer-completion-confirm
'confirm
)
602 ;; The user is permitted to exit with an input that's rejected
603 ;; by test-completion, after confirming her choice.
604 (if (eq last-command this-command
)
606 (minibuffer-message "Confirm")
609 ((eq minibuffer-completion-confirm
'confirm-after-completion
)
610 ;; Similar to the above, but only if trying to exit immediately
611 ;; after typing TAB (this catches most minibuffer typos).
612 (if (memq last-command minibuffer-confirm-exit-commands
)
613 (progn (minibuffer-message "Confirm")
618 ;; Call do-completion, but ignore errors.
619 (case (condition-case nil
620 (completion--do-completion)
622 ((#b001
#b011
) (exit-minibuffer))
623 (#b111
(if (not minibuffer-completion-confirm
)
625 (minibuffer-message "Confirm")
629 (defun completion--try-word-completion (string table predicate point
)
630 (let ((comp (completion-try-completion string table predicate point
)))
631 (if (not (consp comp
))
634 ;; If completion finds next char not unique,
635 ;; consider adding a space or a hyphen.
636 (when (= (length string
) (length (car comp
)))
637 ;; Mark the added char with the `completion-word' property, so it
638 ;; can be handled specially by completion styles such as
639 ;; partial-completion.
640 ;; We used to remove `partial-completion' from completion-styles
641 ;; instead, but it was too blunt, leading to situations where SPC
642 ;; was the only insertable char at point but minibuffer-complete-word
643 ;; refused inserting it.
644 (let ((exts (mapcar (lambda (str) (propertize str
'completion-try-word t
))
646 (before (substring string
0 point
))
647 (after (substring string point
))
649 (while (and exts
(not (consp tem
)))
650 (setq tem
(completion-try-completion
651 (concat before
(pop exts
) after
)
652 table predicate
(1+ point
))))
653 (if (consp tem
) (setq comp tem
))))
655 ;; Completing a single word is actually more difficult than completing
656 ;; as much as possible, because we first have to find the "current
657 ;; position" in `completion' in order to find the end of the word
658 ;; we're completing. Normally, `string' is a prefix of `completion',
659 ;; which makes it trivial to find the position, but with fancier
660 ;; completion (plus env-var expansion, ...) `completion' might not
661 ;; look anything like `string' at all.
662 (let* ((comppoint (cdr comp
))
663 (completion (car comp
))
664 (before (substring string
0 point
))
665 (combined (concat before
"\n" completion
)))
666 ;; Find in completion the longest text that was right before point.
667 (when (string-match "\\(.+\\)\n.*?\\1" combined
)
668 (let* ((prefix (match-string 1 before
))
669 ;; We used non-greedy match to make `rem' as long as possible.
670 (rem (substring combined
(match-end 0)))
671 ;; Find in the remainder of completion the longest text
672 ;; that was right after point.
673 (after (substring string point
))
674 (suffix (if (string-match "\\`\\(.+\\).*\n.*\\1"
675 (concat after
"\n" rem
))
676 (match-string 1 after
))))
677 ;; The general idea is to try and guess what text was inserted
678 ;; at point by the completion. Problem is: if we guess wrong,
679 ;; we may end up treating as "added by completion" text that was
680 ;; actually painfully typed by the user. So if we then cut
681 ;; after the first word, we may throw away things the
682 ;; user wrote. So let's try to be as conservative as possible:
683 ;; only cut after the first word, if we're reasonably sure that
684 ;; our guess is correct.
685 ;; Note: a quick survey on emacs-devel seemed to indicate that
686 ;; nobody actually cares about the "word-at-a-time" feature of
687 ;; minibuffer-complete-word, whose real raison-d'être is that it
688 ;; tries to add "-" or " ". One more reason to only cut after
689 ;; the first word, if we're really sure we're right.
690 (when (and (or suffix
(zerop (length after
)))
691 (string-match (concat
692 ;; Make submatch 1 as small as possible
693 ;; to reduce the risk of cutting
695 ".*" (regexp-quote prefix
) "\\(.*?\\)"
696 (if suffix
(regexp-quote suffix
) "\\'"))
698 ;; The new point in `completion' should also be just
699 ;; before the suffix, otherwise something more complex
700 ;; is going on, and we're not sure where we are.
701 (eq (match-end 1) comppoint
)
702 ;; (match-beginning 1)..comppoint is now the stretch
703 ;; of text in `completion' that was completed at point.
704 (string-match "\\W" completion
(match-beginning 1))
705 ;; Is there really something to cut?
706 (> comppoint
(match-end 0)))
707 ;; Cut after the first word.
708 (let ((cutpos (match-end 0)))
709 (setq completion
(concat (substring completion
0 cutpos
)
710 (substring completion comppoint
)))
711 (setq comppoint cutpos
)))))
713 (cons completion comppoint
)))))
716 (defun minibuffer-complete-word ()
717 "Complete the minibuffer contents at most a single word.
718 After one word is completed as much as possible, a space or hyphen
719 is added, provided that matches some possible completion.
720 Return nil if there is no valid completion, else t."
722 (case (completion--do-completion 'completion--try-word-completion
)
724 (#b001
(minibuffer-message "Sole completion")
726 (#b011
(minibuffer-message "Complete, but not unique")
730 (defface completions-annotations
'((t :inherit italic
))
731 "Face to use for annotations in the *Completions* buffer.")
733 (defun completion--insert-strings (strings)
734 "Insert a list of STRINGS into the current buffer.
735 Uses columns to keep the listing readable but compact.
736 It also eliminates runs of equal strings."
737 (when (consp strings
)
738 (let* ((length (apply 'max
741 (+ (string-width (car s
))
742 (string-width (cadr s
)))
745 (window (get-buffer-window (current-buffer) 0))
746 (wwidth (if window
(1- (window-width window
)) 79))
748 ;; At least 2 columns; at least 2 spaces between columns.
749 (max 2 (/ wwidth
(+ 2 length
)))
750 ;; Don't allocate more columns than we can fill.
751 ;; Windows can't show less than 3 lines anyway.
752 (max 1 (/ (length strings
) 2))))
753 (colwidth (/ wwidth columns
))
756 ;; The insertion should be "sensible" no matter what choices were made
757 ;; for the parameters above.
758 (dolist (str strings
)
759 (unless (equal laststring str
) ; Remove (consecutive) duplicates.
760 (setq laststring str
)
761 (let ((length (if (consp str
)
762 (+ (string-width (car str
))
763 (string-width (cadr str
)))
764 (string-width str
))))
766 (if (< wwidth
(+ (max colwidth length
) column
))
767 ;; No space for `str' at point, move to next line.
768 (progn (insert "\n") (setq column
0))
770 ;; Leave the space unpropertized so that in the case we're
771 ;; already past the goal column, there is still
772 ;; a space displayed.
773 (set-text-properties (- (point) 1) (point)
774 ;; We can't just set tab-width, because
775 ;; completion-setup-function will kill all
776 ;; local variables :-(
777 `(display (space :align-to
,column
)))
779 (if (not (consp str
))
780 (put-text-property (point) (progn (insert str
) (point))
781 'mouse-face
'highlight
)
782 (put-text-property (point) (progn (insert (car str
)) (point))
783 'mouse-face
'highlight
)
784 (add-text-properties (point) (progn (insert (cadr str
)) (point))
786 face completions-annotations
)))
787 ;; Next column to align to.
788 (setq column
(+ column
789 ;; Round up to a whole number of columns.
790 (* colwidth
(ceiling length colwidth
))))))))))
792 (defvar completion-common-substring nil
)
793 (make-obsolete-variable 'completion-common-substring nil
"23.1")
795 (defvar completion-setup-hook nil
796 "Normal hook run at the end of setting up a completion list buffer.
797 When this hook is run, the current buffer is the one in which the
798 command to display the completion list buffer was run.
799 The completion list buffer is available as the value of `standard-output'.
800 See also `display-completion-list'.")
802 (defface completions-first-difference
803 '((t (:inherit bold
)))
804 "Face put on the first uncommon character in completions in *Completions* buffer."
807 (defface completions-common-part
808 '((t (:inherit default
)))
809 "Face put on the common prefix substring in completions in *Completions* buffer.
810 The idea of `completions-common-part' is that you can use it to
811 make the common parts less visible than normal, so that the rest
812 of the differing parts is, by contrast, slightly highlighted."
815 (defun completion-hilit-commonality (completions prefix-len base-size
)
817 (let ((com-str-len (- prefix-len
(or base-size
0))))
822 ;; Don't modify the string itself, but a copy, since the
823 ;; the string may be read-only or used for other purposes.
824 ;; Furthermore, since `completions' may come from
825 ;; display-completion-list, `elem' may be a list.
827 (car (setq elem
(cons (copy-sequence (car elem
))
829 (setq elem
(copy-sequence elem
)))))
831 ;; If completion-boundaries returns incorrect
832 ;; values, all-completions may return strings
833 ;; that don't contain the prefix.
834 (min com-str-len
(length str
))
835 'font-lock-face
'completions-common-part
837 (if (> (length str
) com-str-len
)
838 (put-text-property com-str-len
(1+ com-str-len
)
839 'font-lock-face
'completions-first-difference
845 (defun display-completion-list (completions &optional common-substring
)
846 "Display the list of completions, COMPLETIONS, using `standard-output'.
847 Each element may be just a symbol or string
848 or may be a list of two strings to be printed as if concatenated.
849 If it is a list of two strings, the first is the actual completion
850 alternative, the second serves as annotation.
851 `standard-output' must be a buffer.
852 The actual completion alternatives, as inserted, are given `mouse-face'
853 properties of `highlight'.
854 At the end, this runs the normal hook `completion-setup-hook'.
855 It can find the completion buffer in `standard-output'.
857 The obsolete optional arg COMMON-SUBSTRING, if non-nil, should be a string
858 specifying a common substring for adding the faces
859 `completions-first-difference' and `completions-common-part' to
860 the completions buffer."
862 (setq completions
(completion-hilit-commonality
863 completions
(length common-substring
)
864 ;; We don't know the base-size.
866 (if (not (bufferp standard-output
))
867 ;; This *never* (ever) happens, so there's no point trying to be clever.
869 (let ((standard-output (current-buffer))
870 (completion-setup-hook nil
))
871 (display-completion-list completions common-substring
))
872 (princ (buffer-string)))
874 (let ((mainbuf (current-buffer)))
875 (with-current-buffer standard-output
876 (goto-char (point-max))
877 (if (null completions
)
878 (insert "There are no possible completions of what you have typed.")
879 (insert "Possible completions are:\n")
880 (let ((last (last completions
)))
881 ;; Set base-size from the tail of the list.
882 (set (make-local-variable 'completion-base-size
)
884 (and (minibufferp mainbuf
) 0)))
885 (setcdr last nil
)) ; Make completions a properly nil-terminated list.
886 (completion--insert-strings completions
)))))
888 ;; The hilit used to be applied via completion-setup-hook, so there
889 ;; may still be some code that uses completion-common-substring.
891 (let ((completion-common-substring common-substring
))
892 (run-hooks 'completion-setup-hook
)))
895 (defvar completion-annotate-function
897 ;; Note: there's a lot of scope as for when to add annotations and
898 ;; what annotations to add. E.g. completing-help.el allowed adding
899 ;; the first line of docstrings to M-x completion. But there's
900 ;; a tension, since such annotations, while useful at times, can
901 ;; actually drown the useful information.
902 ;; So completion-annotate-function should be used parsimoniously, or
903 ;; else only used upon a user's request (e.g. we could add a command
904 ;; to completion-list-mode to add annotations to the current
906 "Function to add annotations in the *Completions* buffer.
907 The function takes a completion and should either return nil, or a string that
908 will be displayed next to the completion. The function can access the
909 completion table and predicates via `minibuffer-completion-table' and related
912 (defun minibuffer-completion-help ()
913 "Display a list of possible completions of the current minibuffer contents."
915 (message "Making completion list...")
916 (let* ((string (field-string))
917 (completions (completion-all-completions
919 minibuffer-completion-table
920 minibuffer-completion-predicate
921 (- (point) (field-beginning)))))
924 (or (consp (cdr completions
))
925 (not (equal (car completions
) string
))))
926 (with-output-to-temp-buffer "*Completions*"
927 (let* ((last (last completions
))
928 (base-size (cdr last
)))
929 ;; Remove the base-size tail because `sort' requires a properly
930 ;; nil-terminated list.
931 (when last
(setcdr last nil
))
932 (setq completions
(sort completions
'string-lessp
))
933 (when completion-annotate-function
937 (funcall completion-annotate-function s
)))
938 (if ann
(list s ann
) s
)))
940 (display-completion-list (nconc completions base-size
))))
942 ;; If there are no completions, or if the current input is already the
943 ;; only possible completion, then hide (previous&stale) completions.
944 (let ((window (and (get-buffer "*Completions*")
945 (get-buffer-window "*Completions*" 0))))
946 (when (and (window-live-p window
) (window-dedicated-p window
))
948 (delete-window window
)
949 (error (iconify-frame (window-frame window
))))))
952 (if completions
"Sole completion" "No completions")))
955 (defun minibuffer-hide-completions ()
956 "Get rid of an out-of-date *Completions* buffer."
957 ;; FIXME: We could/should use minibuffer-scroll-window here, but it
958 ;; can also point to the minibuffer-parent-window, so it's a bit tricky.
959 (let ((win (get-buffer-window "*Completions*" 0)))
960 (if win
(with-selected-window win
(bury-buffer)))))
962 (defun exit-minibuffer ()
963 "Terminate this minibuffer argument."
965 ;; If the command that uses this has made modifications in the minibuffer,
966 ;; we don't want them to cause deactivation of the mark in the original
968 ;; A better solution would be to make deactivate-mark buffer-local
969 ;; (or to turn it into a list of buffers, ...), but in the mean time,
970 ;; this should do the trick in most cases.
971 (setq deactivate-mark nil
)
974 (defun self-insert-and-exit ()
975 "Terminate minibuffer input."
977 (if (characterp last-command-event
)
978 (call-interactively 'self-insert-command
)
984 (define-obsolete-variable-alias 'minibuffer-local-must-match-filename-map
985 'minibuffer-local-filename-must-match-map
"23.1")
987 (let ((map minibuffer-local-map
))
988 (define-key map
"\C-g" 'abort-recursive-edit
)
989 (define-key map
"\r" 'exit-minibuffer
)
990 (define-key map
"\n" 'exit-minibuffer
))
992 (let ((map minibuffer-local-completion-map
))
993 (define-key map
"\t" 'minibuffer-complete
)
994 ;; M-TAB is already abused for many other purposes, so we should find
995 ;; another binding for it.
996 ;; (define-key map "\e\t" 'minibuffer-force-complete)
997 (define-key map
" " 'minibuffer-complete-word
)
998 (define-key map
"?" 'minibuffer-completion-help
))
1000 (let ((map minibuffer-local-must-match-map
))
1001 (define-key map
"\r" 'minibuffer-complete-and-exit
)
1002 (define-key map
"\n" 'minibuffer-complete-and-exit
))
1004 (let ((map minibuffer-local-filename-completion-map
))
1005 (define-key map
" " nil
))
1006 (let ((map minibuffer-local-filename-must-match-map
))
1007 (define-key map
" " nil
))
1009 (let ((map minibuffer-local-ns-map
))
1010 (define-key map
" " 'exit-minibuffer
)
1011 (define-key map
"\t" 'exit-minibuffer
)
1012 (define-key map
"?" 'self-insert-and-exit
))
1014 ;;; Completion tables.
1016 (defun minibuffer--double-dollars (str)
1017 (replace-regexp-in-string "\\$" "$$" str
))
1019 (defun completion--make-envvar-table ()
1020 (mapcar (lambda (enventry)
1021 (substring enventry
0 (string-match-p "=" enventry
)))
1022 process-environment
))
1024 (defconst completion--embedded-envvar-re
1025 (concat "\\(?:^\\|[^$]\\(?:\\$\\$\\)*\\)"
1026 "$\\([[:alnum:]_]*\\|{\\([^}]*\\)\\)\\'"))
1028 (defun completion--embedded-envvar-table (string pred action
)
1029 (if (eq (car-safe action
) 'boundaries
)
1030 ;; Compute the boundaries of the subfield to which this
1031 ;; completion applies.
1032 (let ((suffix (cdr action
)))
1033 (if (string-match completion--embedded-envvar-re string
)
1035 (or (match-beginning 2) (match-beginning 1))
1036 (when (string-match "[^[:alnum:]_]" suffix
)
1037 (match-beginning 0)))))
1038 (when (string-match completion--embedded-envvar-re string
)
1039 (let* ((beg (or (match-beginning 2) (match-beginning 1)))
1040 (table (completion--make-envvar-table))
1041 (prefix (substring string
0 beg
)))
1042 (if (eq (aref string
(1- beg
)) ?
{)
1043 (setq table
(apply-partially 'completion-table-with-terminator
1045 ;; Even if file-name completion is case-insensitive, we want
1046 ;; envvar completion to be case-sensitive.
1047 (let ((completion-ignore-case nil
))
1048 (completion-table-with-context
1049 prefix table
(substring string beg
) pred action
))))))
1051 (defun completion--file-name-table (string pred action
)
1052 "Internal subroutine for `read-file-name'. Do not call this."
1054 ((and (zerop (length string
)) (eq 'lambda action
))
1056 ((eq (car-safe action
) 'boundaries
)
1057 ;; FIXME: Actually, this is not always right in the presence of
1058 ;; envvars, but there's not much we can do, I think.
1059 (let ((start (length (file-name-directory string
)))
1060 (end (string-match-p "/" (cdr action
))))
1061 (list* 'boundaries start end
)))
1064 (let* ((dir (if (stringp pred
)
1065 ;; It used to be that `pred' was abused to pass `dir'
1067 (prog1 (expand-file-name pred
) (setq pred nil
))
1069 (str (condition-case nil
1070 (substitute-in-file-name string
)
1072 (name (file-name-nondirectory str
))
1073 (specdir (file-name-directory str
))
1074 (realdir (if specdir
(expand-file-name specdir dir
)
1075 (file-name-as-directory dir
))))
1079 (let ((comp (file-name-completion name realdir
1080 read-file-name-predicate
)))
1082 ;; Requote the $s before returning the completion.
1083 (minibuffer--double-dollars (concat specdir comp
))
1084 ;; Requote the $s before checking for changes.
1085 (setq str
(minibuffer--double-dollars str
))
1086 (if (string-equal string str
)
1088 ;; If there's no real completion, but substitute-in-file-name
1089 ;; changed the string, then return the new string.
1093 (let ((all (file-name-all-completions name realdir
)))
1095 ;; Check the predicate, if necessary.
1096 (unless (memq read-file-name-predicate
'(nil file-exists-p
))
1099 (if (eq read-file-name-predicate
'file-directory-p
)
1100 ;; Brute-force speed up for directory checking:
1101 ;; Discard strings which don't end in a slash.
1103 (let ((len (length s
)))
1104 (and (> len
0) (eq (aref s
(1- len
)) ?
/))))
1105 ;; Must do it the hard (and slow) way.
1106 read-file-name-predicate
)))
1107 (let ((default-directory realdir
))
1109 (if (funcall pred tem
) (push tem comp
))))
1110 (setq all
(nreverse comp
))))
1115 ;; Only other case actually used is ACTION = lambda.
1116 (let ((default-directory dir
))
1117 (funcall (or read-file-name-predicate
'file-exists-p
) str
))))))))
1119 (defalias 'read-file-name-internal
1120 (completion-table-in-turn 'completion--embedded-envvar-table
1121 'completion--file-name-table
)
1122 "Internal subroutine for `read-file-name'. Do not call this.")
1124 (defvar read-file-name-function nil
1125 "If this is non-nil, `read-file-name' does its work by calling this function.")
1127 (defvar read-file-name-predicate nil
1128 "Current predicate used by `read-file-name-internal'.")
1130 (defcustom read-file-name-completion-ignore-case
1131 (if (memq system-type
'(ms-dos windows-nt darwin cygwin
))
1133 "Non-nil means when reading a file name completion ignores case."
1138 (defcustom insert-default-directory t
1139 "Non-nil means when reading a filename start with default dir in minibuffer.
1141 When the initial minibuffer contents show a name of a file or a directory,
1142 typing RETURN without editing the initial contents is equivalent to typing
1143 the default file name.
1145 If this variable is non-nil, the minibuffer contents are always
1146 initially non-empty, and typing RETURN without editing will fetch the
1147 default name, if one is provided. Note however that this default name
1148 is not necessarily the same as initial contents inserted in the minibuffer,
1149 if the initial contents is just the default directory.
1151 If this variable is nil, the minibuffer often starts out empty. In
1152 that case you may have to explicitly fetch the next history element to
1153 request the default name; typing RETURN without editing will leave
1154 the minibuffer empty.
1156 For some commands, exiting with an empty minibuffer has a special meaning,
1157 such as making the current buffer visit no file in the case of
1158 `set-visited-file-name'."
1162 ;; Not always defined, but only called if next-read-file-uses-dialog-p says so.
1163 (declare-function x-file-dialog
"xfns.c"
1164 (prompt dir
&optional default-filename mustmatch only-dir-p
))
1166 (defun read-file-name (prompt &optional dir default-filename mustmatch initial predicate
)
1167 "Read file name, prompting with PROMPT and completing in directory DIR.
1168 Value is not expanded---you must call `expand-file-name' yourself.
1169 Default name to DEFAULT-FILENAME if user exits the minibuffer with
1170 the same non-empty string that was inserted by this function.
1171 (If DEFAULT-FILENAME is omitted, the visited file name is used,
1172 except that if INITIAL is specified, that combined with DIR is used.)
1173 If the user exits with an empty minibuffer, this function returns
1174 an empty string. (This can only happen if the user erased the
1175 pre-inserted contents or if `insert-default-directory' is nil.)
1177 Fourth arg MUSTMATCH can take the following values:
1178 - nil means that the user can exit with any input.
1179 - t means that the user is not allowed to exit unless
1180 the input is (or completes to) an existing file.
1181 - `confirm' means that the user can exit with any input, but she needs
1182 to confirm her choice if the input is not an existing file.
1183 - `confirm-after-completion' means that the user can exit with any
1184 input, but she needs to confirm her choice if she called
1185 `minibuffer-complete' right before `minibuffer-complete-and-exit'
1186 and the input is not an existing file.
1187 - anything else behaves like t except that typing RET does not exit if it
1188 does non-null completion.
1190 Fifth arg INITIAL specifies text to start with.
1192 If optional sixth arg PREDICATE is non-nil, possible completions and
1193 the resulting file name must satisfy (funcall PREDICATE NAME).
1194 DIR should be an absolute directory name. It defaults to the value of
1195 `default-directory'.
1197 If this command was invoked with the mouse, use a graphical file
1198 dialog if `use-dialog-box' is non-nil, and the window system or X
1199 toolkit in use provides a file dialog box. For graphical file
1200 dialogs, any the special values of MUSTMATCH; `confirm' and
1201 `confirm-after-completion' are treated as equivalent to nil.
1203 See also `read-file-name-completion-ignore-case'
1204 and `read-file-name-function'."
1205 (unless dir
(setq dir default-directory
))
1206 (unless (file-name-absolute-p dir
) (setq dir
(expand-file-name dir
)))
1207 (unless default-filename
1208 (setq default-filename
(if initial
(expand-file-name initial dir
)
1210 ;; If dir starts with user's homedir, change that to ~.
1211 (setq dir
(abbreviate-file-name dir
))
1212 ;; Likewise for default-filename.
1213 (if default-filename
1214 (setq default-filename
(abbreviate-file-name default-filename
)))
1216 ((and insert-default-directory
(stringp dir
))
1218 (cons (minibuffer--double-dollars (concat dir initial
))
1219 (length (minibuffer--double-dollars dir
)))
1220 (minibuffer--double-dollars dir
)))
1221 (initial (cons (minibuffer--double-dollars initial
) 0)))))
1223 (if read-file-name-function
1224 (funcall read-file-name-function
1225 prompt dir default-filename mustmatch initial predicate
)
1226 (let ((completion-ignore-case read-file-name-completion-ignore-case
)
1227 (minibuffer-completing-file-name t
)
1228 (read-file-name-predicate (or predicate
'file-exists-p
))
1229 (add-to-history nil
))
1232 (if (not (next-read-file-uses-dialog-p))
1233 ;; We used to pass `dir' to `read-file-name-internal' by
1234 ;; abusing the `predicate' argument. It's better to
1235 ;; just use `default-directory', but in order to avoid
1236 ;; changing `default-directory' in the current buffer,
1237 ;; we don't let-bind it.
1238 (lexical-let ((dir (file-name-as-directory
1239 (expand-file-name dir
))))
1240 (minibuffer-with-setup-hook
1241 (lambda () (setq default-directory dir
))
1242 (completing-read prompt
'read-file-name-internal
1243 nil mustmatch insdef
'file-name-history
1245 ;; If DEFAULT-FILENAME not supplied and DIR contains
1246 ;; a file name, split it.
1247 (let ((file (file-name-nondirectory dir
))
1248 ;; When using a dialog, revert to nil and non-nil
1249 ;; interpretation of mustmatch. confirm options
1250 ;; need to be interpreted as nil, otherwise
1251 ;; it is impossible to create new files using
1252 ;; dialogs with the default settings.
1254 (and (not (eq mustmatch
'confirm
))
1255 (not (eq mustmatch
'confirm-after-completion
))
1257 (when (and (not default-filename
)
1258 (not (zerop (length file
))))
1259 (setq default-filename file
)
1260 (setq dir
(file-name-directory dir
)))
1261 (if default-filename
1262 (setq default-filename
1263 (expand-file-name default-filename dir
)))
1264 (setq add-to-history t
)
1265 (x-file-dialog prompt dir default-filename
1267 (eq predicate
'file-directory-p
)))))
1269 (replace-in-history (eq (car-safe file-name-history
) val
)))
1270 ;; If completing-read returned the inserted default string itself
1271 ;; (rather than a new string with the same contents),
1272 ;; it has to mean that the user typed RET with the minibuffer empty.
1273 ;; In that case, we really want to return ""
1274 ;; so that commands such as set-visited-file-name can distinguish.
1275 (when (eq val default-filename
)
1276 ;; In this case, completing-read has not added an element
1277 ;; to the history. Maybe we should.
1278 (if (not replace-in-history
)
1279 (setq add-to-history t
))
1281 (unless val
(error "No file name specified"))
1283 (if (and default-filename
1284 (string-equal val
(if (consp insdef
) (car insdef
) insdef
)))
1285 (setq val default-filename
))
1286 (setq val
(substitute-in-file-name val
))
1288 (if replace-in-history
1289 ;; Replace what Fcompleting_read added to the history
1290 ;; with what we will actually return.
1291 (let ((val1 (minibuffer--double-dollars val
)))
1292 (if history-delete-duplicates
1293 (setcdr file-name-history
1294 (delete val1
(cdr file-name-history
))))
1295 (setcar file-name-history val1
))
1297 ;; Add the value to the history--but not if it matches
1298 ;; the last value already there.
1299 (let ((val1 (minibuffer--double-dollars val
)))
1300 (unless (and (consp file-name-history
)
1301 (equal (car file-name-history
) val1
))
1302 (setq file-name-history
1304 (if history-delete-duplicates
1305 (delete val1 file-name-history
)
1306 file-name-history
)))))))
1309 (defun internal-complete-buffer-except (&optional buffer
)
1310 "Perform completion on all buffers excluding BUFFER.
1311 BUFFER nil or omitted means use the current buffer.
1312 Like `internal-complete-buffer', but removes BUFFER from the completion list."
1313 (lexical-let ((except (if (stringp buffer
) buffer
(buffer-name buffer
))))
1314 (apply-partially 'completion-table-with-predicate
1315 'internal-complete-buffer
1317 (not (equal (if (consp name
) (car name
) name
) except
)))
1320 ;;; Old-style completion, used in Emacs-21 and Emacs-22.
1322 (defun completion-emacs21-try-completion (string table pred point
)
1323 (let ((completion (try-completion string table pred
)))
1324 (if (stringp completion
)
1325 (cons completion
(length completion
))
1328 (defun completion-emacs21-all-completions (string table pred point
)
1329 (completion-hilit-commonality
1330 (all-completions string table pred
)
1332 (car (completion-boundaries string table pred
""))))
1334 (defun completion-emacs22-try-completion (string table pred point
)
1335 (let ((suffix (substring string point
))
1336 (completion (try-completion (substring string
0 point
) table pred
)))
1337 (if (not (stringp completion
))
1339 ;; Merge a trailing / in completion with a / after point.
1340 ;; We used to only do it for word completion, but it seems to make
1341 ;; sense for all completions.
1342 ;; Actually, claiming this feature was part of Emacs-22 completion
1343 ;; is pushing it a bit: it was only done in minibuffer-completion-word,
1344 ;; which was (by default) not bound during file completion, where such
1345 ;; slashes are most likely to occur.
1346 (if (and (not (zerop (length completion
)))
1347 (eq ?
/ (aref completion
(1- (length completion
))))
1348 (not (zerop (length suffix
)))
1349 (eq ?
/ (aref suffix
0)))
1350 ;; This leaves point after the / .
1351 (setq suffix
(substring suffix
1)))
1352 (cons (concat completion suffix
) (length completion
)))))
1354 (defun completion-emacs22-all-completions (string table pred point
)
1355 (let ((beforepoint (substring string
0 point
)))
1356 (completion-hilit-commonality
1357 (all-completions beforepoint table pred
)
1359 (car (completion-boundaries beforepoint table pred
"")))))
1361 ;;; Basic completion.
1363 (defun completion--merge-suffix (completion point suffix
)
1364 "Merge end of COMPLETION with beginning of SUFFIX.
1365 Simple generalization of the \"merge trailing /\" done in Emacs-22.
1366 Return the new suffix."
1367 (if (and (not (zerop (length suffix
)))
1368 (string-match "\\(.+\\)\n\\1" (concat completion
"\n" suffix
)
1369 ;; Make sure we don't compress things to less
1370 ;; than we started with.
1372 ;; Just make sure we didn't match some other \n.
1373 (eq (match-end 1) (length completion
)))
1374 (substring suffix
(- (match-end 1) (match-beginning 1)))
1375 ;; Nothing to merge.
1378 (defun completion-basic-try-completion (string table pred point
)
1379 (let* ((beforepoint (substring string
0 point
))
1380 (afterpoint (substring string point
))
1381 (bounds (completion-boundaries beforepoint table pred afterpoint
)))
1382 (if (zerop (cdr bounds
))
1383 ;; `try-completion' may return a subtly different result
1384 ;; than `all+merge', so try to use it whenever possible.
1385 (let ((completion (try-completion beforepoint table pred
)))
1386 (if (not (stringp completion
))
1390 (completion--merge-suffix completion point afterpoint
))
1391 (length completion
))))
1392 (let* ((suffix (substring afterpoint
(cdr bounds
)))
1393 (prefix (substring beforepoint
0 (car bounds
)))
1395 "" (list (substring beforepoint
(car bounds
))
1397 (substring afterpoint
0 (cdr bounds
)))))
1398 (all (completion-pcm--all-completions prefix pattern table pred
)))
1399 (if minibuffer-completing-file-name
1400 (setq all
(completion-pcm--filename-try-filter all
)))
1401 (completion-pcm--merge-try pattern all prefix suffix
)))))
1403 (defun completion-basic-all-completions (string table pred point
)
1404 (let* ((beforepoint (substring string
0 point
))
1405 (afterpoint (substring string point
))
1406 (bounds (completion-boundaries beforepoint table pred afterpoint
))
1407 (suffix (substring afterpoint
(cdr bounds
)))
1408 (prefix (substring beforepoint
0 (car bounds
)))
1410 "" (list (substring beforepoint
(car bounds
))
1412 (substring afterpoint
0 (cdr bounds
)))))
1413 (all (completion-pcm--all-completions prefix pattern table pred
)))
1414 (completion-hilit-commonality all point
(car bounds
))))
1416 ;;; Partial-completion-mode style completion.
1418 (defvar completion-pcm--delim-wild-regex nil
1419 "Regular expression matching delimiters controlling the partial-completion.
1420 Typically, this regular expression simply matches a delimiter, meaning
1421 that completion can add something at (match-beginning 0), but if it has
1422 a submatch 1, then completion can add something at (match-end 1).
1423 This is used when the delimiter needs to be of size zero (e.g. the transition
1424 from lowercase to uppercase characters).")
1426 (defun completion-pcm--prepare-delim-re (delims)
1427 (setq completion-pcm--delim-wild-regex
(concat "[" delims
"*]")))
1429 (defcustom completion-pcm-word-delimiters
"-_. "
1430 "A string of characters treated as word delimiters for completion.
1432 If `]' is in this string, it must come first.
1433 If `^' is in this string, it must not come first.
1434 If `-' is in this string, it must come first or right after `]'.
1435 In other words, if S is this string, then `[S]' must be a valid Emacs regular
1436 expression (not containing character ranges like `a-z')."
1437 :set
(lambda (symbol value
)
1438 (set-default symbol value
)
1439 ;; Refresh other vars.
1440 (completion-pcm--prepare-delim-re value
))
1441 :initialize
'custom-initialize-reset
1445 (defun completion-pcm--pattern-trivial-p (pattern)
1446 (and (stringp (car pattern
))
1447 ;; It can be followed by `point' and "" and still be trivial.
1449 (dolist (elem (cdr pattern
))
1450 (unless (member elem
'(point ""))
1451 (setq trivial nil
)))
1454 (defun completion-pcm--string->pattern
(string &optional point
)
1455 "Split STRING into a pattern.
1456 A pattern is a list where each element is either a string
1457 or a symbol chosen among `any', `star', `point'."
1458 (if (and point
(< point
(length string
)))
1459 (let ((prefix (substring string
0 point
))
1460 (suffix (substring string point
)))
1461 (append (completion-pcm--string->pattern prefix
)
1463 (completion-pcm--string->pattern suffix
)))
1468 (while (and (setq p
(string-match completion-pcm--delim-wild-regex
1470 ;; If the char was added by minibuffer-complete-word, then
1471 ;; don't treat it as a delimiter, otherwise "M-x SPC"
1472 ;; ends up inserting a "-" rather than listing
1474 (not (get-text-property p
'completion-try-word string
)))
1475 ;; Usually, completion-pcm--delim-wild-regex matches a delimiter,
1476 ;; meaning that something can be added *before* it, but it can also
1477 ;; match a prefix and postfix, in which case something can be added
1478 ;; in-between (e.g. match [[:lower:]][[:upper:]]).
1479 ;; This is determined by the presence of a submatch-1 which delimits
1481 (if (match-end 1) (setq p
(match-end 1)))
1482 (push (substring string p0 p
) pattern
)
1483 (if (eq (aref string p
) ?
*)
1485 (push 'star pattern
)
1491 ;; An empty string might be erroneously added at the beginning.
1492 ;; It should be avoided properly, but it's so easy to remove it here.
1493 (delete "" (nreverse (cons (substring string p0
) pattern
))))))
1495 (defun completion-pcm--pattern->regex
(pattern &optional group
)
1502 (if (if (consp group
) (memq x group
) group
)
1504 (t (regexp-quote x
))))
1507 ;; Avoid pathological backtracking.
1508 (while (string-match "\\.\\*\\?\\(?:\\\\[()]\\)*\\(\\.\\*\\?\\)" re
)
1509 (setq re
(replace-match "" t t re
1)))
1512 (defun completion-pcm--all-completions (prefix pattern table pred
)
1513 "Find all completions for PATTERN in TABLE obeying PRED.
1514 PATTERN is as returned by `completion-pcm--string->pattern'."
1515 ;; (assert (= (car (completion-boundaries prefix table pred ""))
1516 ;; (length prefix)))
1517 ;; Find an initial list of possible completions.
1518 (if (completion-pcm--pattern-trivial-p pattern
)
1520 ;; Minibuffer contains no delimiters -- simple case!
1521 (all-completions (concat prefix
(car pattern
)) table pred
)
1523 ;; Use all-completions to do an initial cull. This is a big win,
1524 ;; since all-completions is written in C!
1525 (let* (;; Convert search pattern to a standard regular expression.
1526 (regex (completion-pcm--pattern->regex pattern
))
1527 (case-fold-search completion-ignore-case
)
1528 (completion-regexp-list (cons regex completion-regexp-list
))
1529 (compl (all-completions
1530 (concat prefix
(if (stringp (car pattern
)) (car pattern
) ""))
1532 (if (not (functionp table
))
1533 ;; The internal functions already obeyed completion-regexp-list.
1537 (when (string-match-p regex c
) (push c poss
)))
1540 (defun completion-pcm--hilit-commonality (pattern completions
)
1542 (let* ((re (completion-pcm--pattern->regex pattern
'(point)))
1543 (case-fold-search completion-ignore-case
))
1544 ;; Remove base-size during mapcar, and add it back later.
1547 ;; Don't modify the string itself.
1548 (setq str
(copy-sequence str
))
1549 (unless (string-match re str
)
1550 (error "Internal error: %s does not match %s" re str
))
1551 (let ((pos (or (match-beginning 1) (match-end 0))))
1552 (put-text-property 0 pos
1553 'font-lock-face
'completions-common-part
1555 (if (> (length str
) pos
)
1556 (put-text-property pos
(1+ pos
)
1557 'font-lock-face
'completions-first-difference
1562 (defun completion-pcm--find-all-completions (string table pred point
1564 "Find all completions for STRING at POINT in TABLE, satisfying PRED.
1565 POINT is a position inside STRING.
1566 FILTER is a function applied to the return value, that can be used, e.g. to
1567 filter out additional entries (because TABLE migth not obey PRED)."
1568 (unless filter
(setq filter
'identity
))
1569 (let* ((beforepoint (substring string
0 point
))
1570 (afterpoint (substring string point
))
1571 (bounds (completion-boundaries beforepoint table pred afterpoint
))
1572 (prefix (substring beforepoint
0 (car bounds
)))
1573 (suffix (substring afterpoint
(cdr bounds
)))
1575 (setq string
(substring string
(car bounds
) (+ point
(cdr bounds
))))
1576 (let* ((relpoint (- point
(car bounds
)))
1577 (pattern (completion-pcm--string->pattern string relpoint
))
1578 (all (condition-case err
1580 (completion-pcm--all-completions
1581 prefix pattern table pred
))
1582 (error (unless firsterror
(setq firsterror err
)) nil
))))
1583 (when (and (null all
)
1585 (null (ignore-errors (try-completion prefix table pred
))))
1586 ;; The prefix has no completions at all, so we should try and fix
1588 (let ((substring (substring prefix
0 -
1)))
1589 (destructuring-bind (subpat suball subprefix subsuffix
)
1590 (completion-pcm--find-all-completions
1591 substring table pred
(length substring
) filter
)
1592 (let ((sep (aref prefix
(1- (length prefix
))))
1593 ;; Text that goes between the new submatches and the
1594 ;; completion substring.
1596 ;; Eliminate submatches that don't end with the separator.
1597 (dolist (submatch (prog1 suball
(setq suball
())))
1598 (when (eq sep
(aref submatch
(1- (length submatch
))))
1599 (push submatch suball
)))
1601 ;; Update the boundaries and corresponding pattern.
1602 ;; We assume that all submatches result in the same boundaries
1603 ;; since we wouldn't know how to merge them otherwise anyway.
1604 ;; FIXME: COMPLETE REWRITE!!!
1605 (let* ((newbeforepoint
1606 (concat subprefix
(car suball
)
1607 (substring string
0 relpoint
)))
1608 (leftbound (+ (length subprefix
) (length (car suball
))))
1609 (newbounds (completion-boundaries
1610 newbeforepoint table pred afterpoint
)))
1611 (unless (or (and (eq (cdr bounds
) (cdr newbounds
))
1612 (eq (car newbounds
) leftbound
))
1613 ;; Refuse new boundaries if they step over
1615 (< (car newbounds
) leftbound
))
1616 ;; The new completed prefix does change the boundaries
1617 ;; of the completed substring.
1618 (setq suffix
(substring afterpoint
(cdr newbounds
)))
1620 (concat (substring newbeforepoint
(car newbounds
))
1621 (substring afterpoint
0 (cdr newbounds
))))
1622 (setq between
(substring newbeforepoint leftbound
1624 (setq pattern
(completion-pcm--string->pattern
1626 (- (length newbeforepoint
)
1628 (dolist (submatch suball
)
1629 (setq all
(nconc (mapcar
1630 (lambda (s) (concat submatch between s
))
1632 (completion-pcm--all-completions
1633 (concat subprefix submatch between
)
1634 pattern table pred
)))
1636 ;; FIXME: This can come in handy for try-completion,
1637 ;; but isn't right for all-completions, since it lists
1638 ;; invalid completions.
1640 ;; ;; Even though we found expansions in the prefix, none
1641 ;; ;; leads to a valid completion.
1642 ;; ;; Let's keep the expansions, tho.
1643 ;; (dolist (submatch suball)
1644 ;; (push (concat submatch between newsubstring) all)))
1646 (setq pattern
(append subpat
(list 'any
(string sep
))
1647 (if between
(list between
)) pattern
))
1648 (setq prefix subprefix
)))))
1649 (if (and (null all
) firsterror
)
1650 (signal (car firsterror
) (cdr firsterror
))
1651 (list pattern all prefix suffix
)))))
1653 (defun completion-pcm-all-completions (string table pred point
)
1654 (destructuring-bind (pattern all
&optional prefix suffix
)
1655 (completion-pcm--find-all-completions string table pred point
)
1657 (nconc (completion-pcm--hilit-commonality pattern all
)
1660 (defun completion-pcm--merge-completions (strs pattern
)
1661 "Extract the commonality in STRS, with the help of PATTERN."
1663 ((null (cdr strs
)) (list (car strs
)))
1665 (let ((re (completion-pcm--pattern->regex pattern
'group
))
1666 (ccs ())) ;Chopped completions.
1668 ;; First chop each string into the parts corresponding to each
1669 ;; non-constant element of `pattern', using regexp-matching.
1670 (let ((case-fold-search completion-ignore-case
))
1672 (unless (string-match re str
)
1673 (error "Internal error: %s doesn't match %s" str re
))
1676 (while (match-beginning i
)
1677 (push (match-string i str
) chopped
)
1679 ;; Add the text corresponding to the implicit trailing `any'.
1680 (push (substring str
(match-end 0)) chopped
)
1681 (push (nreverse chopped
) ccs
))))
1683 ;; Then for each of those non-constant elements, extract the
1684 ;; commonality between them.
1686 ;; Make the implicit `any' explicit. We could make it explicit
1687 ;; everywhere, but it would slow down regexp-matching a little bit.
1688 (dolist (elem (append pattern
'(any)))
1692 (dolist (cc (prog1 ccs
(setq ccs nil
)))
1693 (push (car cc
) comps
)
1694 (push (cdr cc
) ccs
))
1695 (let* ((prefix (try-completion "" comps
))
1696 (unique (or (and (eq prefix t
) (setq prefix
""))
1697 (eq t
(try-completion prefix comps
)))))
1698 (unless (equal prefix
"") (push prefix res
))
1699 ;; If there's only one completion, `elem' is not useful
1700 ;; any more: it can only match the empty string.
1701 ;; FIXME: in some cases, it may be necessary to turn an
1702 ;; `any' into a `star' because the surrounding context has
1703 ;; changed such that string->pattern wouldn't add an `any'
1705 (unless unique
(push elem res
))))))
1706 ;; We return it in reverse order.
1709 (defun completion-pcm--pattern->string
(pattern)
1710 (mapconcat (lambda (x) (cond
1714 ((eq x
'point
) "")))
1718 ;; We want to provide the functionality of `try', but we use `all'
1719 ;; and then merge it. In most cases, this works perfectly, but
1720 ;; if the completion table doesn't consider the same completions in
1721 ;; `try' as in `all', then we have a problem. The most common such
1722 ;; case is for filename completion where completion-ignored-extensions
1723 ;; is only obeyed by the `try' code. We paper over the difference
1724 ;; here. Note that it is not quite right either: if the completion
1725 ;; table uses completion-table-in-turn, this filtering may take place
1726 ;; too late to correctly fallback from the first to the
1727 ;; second alternative.
1728 (defun completion-pcm--filename-try-filter (all)
1729 "Filter to adjust `all' file completion to the behavior of `try'."
1732 (re (concat "\\(?:\\`\\.\\.?/\\|"
1733 (regexp-opt completion-ignored-extensions
)
1736 (unless (string-match-p re f
) (push f try
)))
1740 (defun completion-pcm--merge-try (pattern all prefix suffix
)
1742 ((not (consp all
)) all
)
1743 ((and (not (consp (cdr all
))) ;Only one completion.
1744 ;; Ignore completion-ignore-case here.
1745 (equal (completion-pcm--pattern->string pattern
) (car all
)))
1748 (let* ((mergedpat (completion-pcm--merge-completions all pattern
))
1749 ;; `mergedpat' is in reverse order. Place new point (by
1750 ;; order of preference) either at the old point, or at
1751 ;; the last place where there's something to choose, or
1753 (pointpat (or (memq 'point mergedpat
) (memq 'any mergedpat
)
1755 ;; New pos from the start.
1756 (newpos (length (completion-pcm--pattern->string pointpat
)))
1757 ;; Do it afterwards because it changes `pointpat' by sideeffect.
1758 (merged (completion-pcm--pattern->string
(nreverse mergedpat
))))
1760 (setq suffix
(completion--merge-suffix merged newpos suffix
))
1761 (cons (concat prefix merged suffix
) (+ newpos
(length prefix
)))))))
1763 (defun completion-pcm-try-completion (string table pred point
)
1764 (destructuring-bind (pattern all prefix suffix
)
1765 (completion-pcm--find-all-completions
1766 string table pred point
1767 (if minibuffer-completing-file-name
1768 'completion-pcm--filename-try-filter
))
1769 (completion-pcm--merge-try pattern all prefix suffix
)))
1771 ;;; Initials completion
1772 ;; Complete /ums to /usr/monnier/src or lch to list-command-history.
1774 (defun completion-initials-expand (str table pred
)
1775 (unless (or (zerop (length str
))
1776 (string-match completion-pcm--delim-wild-regex str
))
1777 (let ((bounds (completion-boundaries str table pred
"")))
1778 (if (zerop (car bounds
))
1779 (mapconcat 'string str
"-")
1780 ;; If there's a boundary, it's trickier. The main use-case
1781 ;; we consider here is file-name completion. We'd like
1782 ;; to expand ~/eee to ~/e/e/e and /eee to /e/e/e.
1783 ;; But at the same time, we don't want /usr/share/ae to expand
1784 ;; to /usr/share/a/e just because we mistyped "ae" for "ar",
1785 ;; so we probably don't want initials to touch anything that
1786 ;; looks like /usr/share/foo. As a heuristic, we just check that
1787 ;; the text before the boundary char is at most 1 char.
1788 ;; This allows both ~/eee and /eee and not much more.
1789 ;; FIXME: It sadly also disallows the use of ~/eee when that's
1790 ;; embedded within something else (e.g. "(~/eee" in Info node
1791 ;; completion or "ancestor:/eee" in bzr-revision completion).
1792 (when (< (car bounds
) 3)
1793 (let ((sep (substring str
(1- (car bounds
)) (car bounds
))))
1794 ;; FIXME: the above string-match checks the whole string, whereas
1795 ;; we end up only caring about the after-boundary part.
1796 (concat (substring str
0 (car bounds
))
1797 (mapconcat 'string
(substring str
(car bounds
)) sep
))))))))
1799 (defun completion-initials-all-completions (string table pred point
)
1800 (let ((newstr (completion-initials-expand string table pred
)))
1802 (completion-pcm-all-completions newstr table pred
(length newstr
)))))
1804 (defun completion-initials-try-completion (string table pred point
)
1805 (let ((newstr (completion-initials-expand string table pred
)))
1807 (completion-pcm-try-completion newstr table pred
(length newstr
)))))
1810 (provide 'minibuffer
)
1812 ;; arch-tag: ef8a0a15-1080-4790-a754-04017c02f08f
1813 ;;; minibuffer.el ends here