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 because we only
41 ;; provide the start info but not the end info in
42 ;; completion-base-position.
43 ;; - quoting is problematic. E.g. the double-dollar quoting used in
44 ;; substitie-in-file-name (and hence read-file-name-internal) bumps
46 ;; - choose-completion doesn't know how to quote the text it inserts.
47 ;; E.g. it fails to double the dollars in file-name completion, or
48 ;; to backslash-escape spaces and other chars in comint completion.
49 ;; - when completing ~/tmp/fo$$o, the highligting in *Completions*
50 ;; is off by one position.
51 ;; - all code like PCM which relies on all-completions to match
52 ;; its argument gets confused because all-completions returns unquoted
53 ;; texts (as desired for *Completions* output).
54 ;; - C-x C-f ~/*/sr ? should not list "~/./src".
55 ;; - minibuffer-force-complete completes ~/src/emacs/t<!>/lisp/minibuffer.el
56 ;; to ~/src/emacs/trunk/ and throws away lisp/minibuffer.el.
60 ;; - make partial-complete-mode obsolete:
61 ;; - (?) <foo.h> style completion for file names.
62 ;; This can't be done identically just by tweaking completion,
63 ;; because partial-completion-mode's behavior is to expand <string.h>
64 ;; to /usr/include/string.h only when exiting the minibuffer, at which
65 ;; point the completion code is actually not involved normally.
66 ;; Partial-completion-mode does it via a find-file-not-found-function.
67 ;; - special code for C-x C-f <> to visit the file ref'd at point
68 ;; via (require 'foo) or #include "foo". ffap seems like a better
69 ;; place for this feature (supplemented with major-mode-provided
70 ;; functions to find the file ref'd at point).
72 ;; - case-sensitivity currently confuses two issues:
73 ;; - whether or not a particular completion table should be case-sensitive
74 ;; (i.e. whether strings that differ only by case are semantically
76 ;; - whether the user wants completion to pay attention to case.
77 ;; e.g. we may want to make it possible for the user to say "first try
78 ;; completion case-sensitively, and if that fails, try to ignore case".
80 ;; - add support for ** to pcm.
81 ;; - Add vc-file-name-completion-table to read-file-name-internal.
82 ;; - A feature like completing-help.el.
86 (eval-when-compile (require 'cl
))
88 ;;; Completion table manipulation
90 ;; New completion-table operation.
91 (defun completion-boundaries (string table pred suffix
)
92 "Return the boundaries of the completions returned by TABLE for STRING.
93 STRING is the string on which completion will be performed.
94 SUFFIX is the string after point.
95 The result is of the form (START . END) where START is the position
96 in STRING of the beginning of the completion field and END is the position
97 in SUFFIX of the end of the completion field.
98 E.g. for simple completion tables, the result is always (0 . (length SUFFIX))
99 and for file names the result is the positions delimited by
100 the closest directory separators."
101 (let ((boundaries (if (functionp table
)
102 (funcall table string pred
(cons 'boundaries suffix
)))))
103 (if (not (eq (car-safe boundaries
) 'boundaries
))
104 (setq boundaries nil
))
105 (cons (or (cadr boundaries
) 0)
106 (or (cddr boundaries
) (length suffix
)))))
108 (defun completion--some (fun xs
)
109 "Apply FUN to each element of XS in turn.
110 Return the first non-nil returned value.
112 (let ((firsterror nil
)
114 (while (and (not res
) xs
)
116 (setq res
(funcall fun
(pop xs
)))
117 (error (unless firsterror
(setq firsterror err
)) nil
)))
119 (if firsterror
(signal (car firsterror
) (cdr firsterror
))))))
121 (defun complete-with-action (action table string pred
)
122 "Perform completion ACTION.
123 STRING is the string to complete.
124 TABLE is the completion table, which should not be a function.
125 PRED is a completion predicate.
126 ACTION can be one of nil, t or `lambda'."
128 ((functionp table
) (funcall table string pred action
))
129 ((eq (car-safe action
) 'boundaries
)
130 (cons 'boundaries
(completion-boundaries string table pred
(cdr action
))))
134 ((null action
) 'try-completion
)
135 ((eq action t
) 'all-completions
)
136 (t 'test-completion
))
137 string table pred
))))
139 (defun completion-table-dynamic (fun)
140 "Use function FUN as a dynamic completion table.
141 FUN is called with one argument, the string for which completion is required,
142 and it should return an alist containing all the intended possible completions.
143 This alist may be a full list of possible completions so that FUN can ignore
144 the value of its argument. If completion is performed in the minibuffer,
145 FUN will be called in the buffer from which the minibuffer was entered.
147 The result of the `completion-table-dynamic' form is a function
148 that can be used as the COLLECTION argument to `try-completion' and
149 `all-completions'. See Info node `(elisp)Programmed Completion'."
150 (lexical-let ((fun fun
))
151 (lambda (string pred action
)
152 (with-current-buffer (let ((win (minibuffer-selected-window)))
153 (if (window-live-p win
) (window-buffer win
)
155 (complete-with-action action
(funcall fun string
) string pred
)))))
157 (defmacro lazy-completion-table
(var fun
)
158 "Initialize variable VAR as a lazy completion table.
159 If the completion table VAR is used for the first time (e.g., by passing VAR
160 as an argument to `try-completion'), the function FUN is called with no
161 arguments. FUN must return the completion table that will be stored in VAR.
162 If completion is requested in the minibuffer, FUN will be called in the buffer
163 from which the minibuffer was entered. The return value of
164 `lazy-completion-table' must be used to initialize the value of VAR.
166 You should give VAR a non-nil `risky-local-variable' property."
167 (declare (debug (symbolp lambda-expr
)))
168 (let ((str (make-symbol "string")))
169 `(completion-table-dynamic
171 (when (functionp ,var
)
175 (defun completion-table-with-context (prefix table string pred action
)
176 ;; TODO: add `suffix' maybe?
177 ;; Notice that `pred' may not be a function in some abusive cases.
178 (when (functionp pred
)
180 (lexical-let ((pred pred
))
181 ;; Predicates are called differently depending on the nature of
182 ;; the completion table :-(
184 ((vectorp table
) ;Obarray.
185 (lambda (sym) (funcall pred
(concat prefix
(symbol-name sym
)))))
186 ((hash-table-p table
)
187 (lambda (s v
) (funcall pred
(concat prefix s
))))
189 (lambda (s) (funcall pred
(concat prefix s
))))
190 (t ;Lists and alists.
192 (funcall pred
(concat prefix
(if (consp s
) (car s
) s
)))))))))
193 (if (eq (car-safe action
) 'boundaries
)
194 (let* ((len (length prefix
))
195 (bound (completion-boundaries string table pred
(cdr action
))))
196 (list* 'boundaries
(+ (car bound
) len
) (cdr bound
)))
197 (let ((comp (complete-with-action action table string pred
)))
199 ;; In case of try-completion, add the prefix.
200 ((stringp comp
) (concat prefix comp
))
203 (defun completion-table-with-terminator (terminator table string pred action
)
204 "Construct a completion table like TABLE but with an extra TERMINATOR.
205 This is meant to be called in a curried way by first passing TERMINATOR
206 and TABLE only (via `apply-partially').
207 TABLE is a completion table, and TERMINATOR is a string appended to TABLE's
208 completion if it is complete. TERMINATOR is also used to determine the
209 completion suffix's boundary.
210 TERMINATOR can also be a cons cell (TERMINATOR . TERMINATOR-REGEXP)
211 in which case TERMINATOR-REGEXP is a regular expression whose submatch
212 number 1 should match TERMINATOR. This is used when there is a need to
213 distinguish occurrences of the TERMINATOR strings which are really terminators
214 from others (e.g. escaped)."
216 ((eq (car-safe action
) 'boundaries
)
217 (let* ((suffix (cdr action
))
218 (bounds (completion-boundaries string table pred suffix
))
219 (terminator-regexp (if (consp terminator
)
220 (cdr terminator
) (regexp-quote terminator
)))
221 (max (string-match terminator-regexp suffix
)))
222 (list* 'boundaries
(car bounds
)
223 (min (cdr bounds
) (or max
(length suffix
))))))
225 (let ((comp (try-completion string table pred
)))
226 (if (consp terminator
) (setq terminator
(car terminator
)))
228 (concat string terminator
)
229 (if (and (stringp comp
)
230 ;; FIXME: Try to avoid this second call, especially since
231 ;; it may be very inefficient (because `comp' made us
232 ;; jump to a new boundary, so we complete in that
233 ;; boundary with an empty start string).
234 ;; completion-boundaries might help.
235 (eq (try-completion comp table pred
) t
))
236 (concat comp terminator
)
239 ;; FIXME: We generally want the `try' and `all' behaviors to be
240 ;; consistent so pcm can merge the `all' output to get the `try' output,
241 ;; but that sometimes clashes with the need for `all' output to look
242 ;; good in *Completions*.
243 ;; (mapcar (lambda (s) (concat s terminator))
244 ;; (all-completions string table pred))))
245 (all-completions string table pred
))
246 ;; completion-table-with-terminator is always used for
247 ;; "sub-completions" so it's only called if the terminator is missing,
248 ;; in which case `test-completion' should return nil.
249 ((eq action
'lambda
) nil
)))
251 (defun completion-table-with-predicate (table pred1 strict string pred2 action
)
252 "Make a completion table equivalent to TABLE but filtered through PRED1.
253 PRED1 is a function of one argument which returns non-nil if and only if the
254 argument is an element of TABLE which should be considered for completion.
255 STRING, PRED2, and ACTION are the usual arguments to completion tables,
256 as described in `try-completion', `all-completions', and `test-completion'.
257 If STRICT is t, the predicate always applies; if nil it only applies if
258 it does not reduce the set of possible completions to nothing.
259 Note: TABLE needs to be a proper completion table which obeys predicates."
261 ((and (not strict
) (eq action
'lambda
))
262 ;; Ignore pred1 since it doesn't really have to apply anyway.
263 (test-completion string table pred2
))
265 (or (complete-with-action action table string
266 (if (null pred2
) pred1
267 (lexical-let ((pred1 pred2
) (pred2 pred2
))
269 ;; Call `pred1' first, so that `pred2'
270 ;; really can't tell that `x' is in table.
271 (if (funcall pred1 x
) (funcall pred2 x
))))))
272 ;; If completion failed and we're not applying pred1 strictly, try
273 ;; again without pred1.
275 (complete-with-action action table string pred2
))))))
277 (defun completion-table-in-turn (&rest tables
)
278 "Create a completion table that tries each table in TABLES in turn."
279 ;; FIXME: the boundaries may come from TABLE1 even when the completion list
280 ;; is returned by TABLE2 (because TABLE1 returned an empty list).
281 (lexical-let ((tables tables
))
282 (lambda (string pred action
)
283 (completion--some (lambda (table)
284 (complete-with-action action table string pred
))
287 ;; (defmacro complete-in-turn (a b) `(completion-table-in-turn ,a ,b))
288 ;; (defmacro dynamic-completion-table (fun) `(completion-table-dynamic ,fun))
289 (define-obsolete-function-alias
290 'complete-in-turn
'completion-table-in-turn
"23.1")
291 (define-obsolete-function-alias
292 'dynamic-completion-table
'completion-table-dynamic
"23.1")
294 ;;; Minibuffer completion
296 (defgroup minibuffer nil
297 "Controlling the behavior of the minibuffer."
298 :link
'(custom-manual "(emacs)Minibuffer")
301 (defun minibuffer-message (message &rest args
)
302 "Temporarily display MESSAGE at the end of the minibuffer.
303 The text is displayed for `minibuffer-message-timeout' seconds,
304 or until the next input event arrives, whichever comes first.
305 Enclose MESSAGE in [...] if this is not yet the case.
306 If ARGS are provided, then pass MESSAGE through `format'."
307 (if (not (minibufferp (current-buffer)))
310 (apply 'message message args
)
311 (message "%s" message
))
312 (prog1 (sit-for (or minibuffer-message-timeout
1000000))
314 ;; Clear out any old echo-area message to make way for our new thing.
316 (setq message
(if (and (null args
) (string-match-p "\\` *\\[.+\\]\\'" message
))
317 ;; Make sure we can put-text-property.
318 (copy-sequence message
)
319 (concat " [" message
"]")))
320 (when args
(setq message
(apply 'format message args
)))
321 (let ((ol (make-overlay (point-max) (point-max) nil t t
))
322 ;; A quit during sit-for normally only interrupts the sit-for,
323 ;; but since minibuffer-message is used at the end of a command,
324 ;; at a time when the command has virtually finished already, a C-g
325 ;; should really cause an abort-recursive-edit instead (i.e. as if
326 ;; the C-g had been typed at top-level). Binding inhibit-quit here
327 ;; is an attempt to get that behavior.
331 (unless (zerop (length message
))
332 ;; The current C cursor code doesn't know to use the overlay's
333 ;; marker's stickiness to figure out whether to place the cursor
334 ;; before or after the string, so let's spoon-feed it the pos.
335 (put-text-property 0 1 'cursor t message
))
336 (overlay-put ol
'after-string message
)
337 (sit-for (or minibuffer-message-timeout
1000000)))
338 (delete-overlay ol
)))))
340 (defun minibuffer-completion-contents ()
341 "Return the user input in a minibuffer before point as a string.
342 That is what completion commands operate on."
343 (buffer-substring (field-beginning) (point)))
345 (defun delete-minibuffer-contents ()
346 "Delete all user input in a minibuffer.
347 If the current buffer is not a minibuffer, erase its entire contents."
348 ;; We used to do `delete-field' here, but when file name shadowing
349 ;; is on, the field doesn't cover the entire minibuffer contents.
350 (delete-region (minibuffer-prompt-end) (point-max)))
352 (defcustom completion-auto-help t
353 "Non-nil means automatically provide help for invalid completion input.
354 If the value is t the *Completion* buffer is displayed whenever completion
355 is requested but cannot be done.
356 If the value is `lazy', the *Completions* buffer is only displayed after
357 the second failed attempt to complete."
358 :type
'(choice (const nil
) (const t
) (const lazy
))
361 (defconst completion-styles-alist
363 completion-emacs21-try-completion completion-emacs21-all-completions
364 "Simple prefix-based completion.")
366 completion-emacs22-try-completion completion-emacs22-all-completions
367 "Prefix completion that only operates on the text before point.")
369 completion-basic-try-completion completion-basic-all-completions
370 "Completion of the prefix before point and the suffix after point.")
372 completion-pcm-try-completion completion-pcm-all-completions
373 "Completion of multiple words, each one taken as a prefix.
374 E.g. M-x l-c-h can complete to list-command-history
375 and C-x C-f /u/m/s to /usr/monnier/src.")
377 completion-initials-try-completion completion-initials-all-completions
378 "Completion of acronyms and initialisms.
379 E.g. can complete M-x lch to list-command-history
380 and C-x C-f ~/sew to ~/src/emacs/work."))
381 "List of available completion styles.
382 Each element has the form (NAME TRY-COMPLETION ALL-COMPLETIONS DOC):
383 where NAME is the name that should be used in `completion-styles',
384 TRY-COMPLETION is the function that does the completion (it should
385 follow the same calling convention as `completion-try-completion'),
386 ALL-COMPLETIONS is the function that lists the completions (it should
387 follow the calling convention of `completion-all-completions'),
388 and DOC describes the way this style of completion works.")
390 (defcustom completion-styles
'(basic partial-completion emacs22
)
391 "List of completion styles to use.
392 The available styles are listed in `completion-styles-alist'."
393 :type
`(repeat (choice ,@(mapcar (lambda (x) (list 'const
(car x
)))
394 completion-styles-alist
)))
398 (defun completion-try-completion (string table pred point
)
399 "Try to complete STRING using completion table TABLE.
400 Only the elements of table that satisfy predicate PRED are considered.
401 POINT is the position of point within STRING.
402 The return value can be either nil to indicate that there is no completion,
403 t to indicate that STRING is the only possible completion,
404 or a pair (STRING . NEWPOINT) of the completed result string together with
405 a new position for point."
406 (completion--some (lambda (style)
407 (funcall (nth 1 (assq style completion-styles-alist
))
408 string table pred point
))
411 (defun completion-all-completions (string table pred point
)
412 "List the possible completions of STRING in completion table TABLE.
413 Only the elements of table that satisfy predicate PRED are considered.
414 POINT is the position of point within STRING.
415 The return value is a list of completions and may contain the base-size
417 ;; FIXME: We need to additionally return completion-extra-size (similar
418 ;; to completion-base-size but for the text after point).
419 (completion--some (lambda (style)
420 (funcall (nth 2 (assq style completion-styles-alist
))
421 string table pred point
))
424 (defun minibuffer--bitset (modified completions exact
)
425 (logior (if modified
4 0)
429 (defun completion--do-completion (&optional try-completion-function
)
430 "Do the completion and return a summary of what happened.
431 M = completion was performed, the text was Modified.
432 C = there were available Completions.
433 E = after completion we now have an Exact match.
436 000 0 no possible completion
437 001 1 was already an exact and unique completion
438 010 2 no completion happened
439 011 3 was already an exact completion
442 110 6 some completion happened
443 111 7 completed to an exact completion"
444 (let* ((beg (field-beginning))
446 (string (buffer-substring beg end
))
447 (comp (funcall (or try-completion-function
448 'completion-try-completion
)
450 minibuffer-completion-table
451 minibuffer-completion-predicate
455 (minibuffer-hide-completions)
456 (ding) (minibuffer-message "No match") (minibuffer--bitset nil nil nil
))
458 (minibuffer-hide-completions)
459 (goto-char (field-end))
460 (minibuffer--bitset nil nil t
)) ;Exact and unique match.
462 ;; `completed' should be t if some completion was done, which doesn't
463 ;; include simply changing the case of the entered string. However,
464 ;; for appearance, the string is rewritten if the case changes.
465 (let* ((comp-pos (cdr comp
))
466 (completion (car comp
))
467 (completed (not (eq t
(compare-strings completion nil nil
469 (unchanged (eq t
(compare-strings completion nil nil
470 string nil nil nil
))))
473 ;; Insert in minibuffer the chars we got.
476 (delete-region beg end
))
478 (goto-char (+ beg comp-pos
))
480 (if (not (or unchanged completed
))
481 ;; The case of the string changed, but that's all. We're not sure
482 ;; whether this is a unique completion or not, so try again using
483 ;; the real case (this shouldn't recurse again, because the next
484 ;; time try-completion will return either t or the exact string).
485 (completion--do-completion try-completion-function
)
487 ;; It did find a match. Do we match some possibility exactly now?
488 (let ((exact (test-completion completion
489 minibuffer-completion-table
490 minibuffer-completion-predicate
)))
492 ;; We could also decide to refresh the completions,
493 ;; if they're displayed (and assuming there are
494 ;; completions left).
495 (minibuffer-hide-completions)
496 ;; Show the completion table, if requested.
499 (if (case completion-auto-help
500 (lazy (eq this-command last-command
))
501 (t completion-auto-help
))
502 (minibuffer-completion-help)
503 (minibuffer-message "Next char not unique")))
504 ;; If the last exact completion and this one were the same, it
505 ;; means we've already given a "Next char not unique" message
506 ;; and the user's hit TAB again, so now we give him help.
507 ((eq this-command last-command
)
508 (if completion-auto-help
(minibuffer-completion-help)))))
510 (minibuffer--bitset completed t exact
))))))))
512 (defun minibuffer-complete ()
513 "Complete the minibuffer contents as far as possible.
514 Return nil if there is no valid completion, else t.
515 If no characters can be completed, display a list of possible completions.
516 If you repeat this command after it displayed such a list,
517 scroll the window of possible completions."
519 ;; If the previous command was not this,
520 ;; mark the completion buffer obsolete.
521 (unless (eq this-command last-command
)
522 (setq minibuffer-scroll-window nil
))
524 (let ((window minibuffer-scroll-window
))
525 ;; If there's a fresh completion window with a live buffer,
526 ;; and this command is repeated, scroll that window.
527 (if (window-live-p window
)
528 (with-current-buffer (window-buffer window
)
529 (if (pos-visible-in-window-p (point-max) window
)
530 ;; If end is in view, scroll up to the beginning.
531 (set-window-start window
(point-min) nil
)
532 ;; Else scroll down one screen.
533 (scroll-other-window))
536 (case (completion--do-completion)
538 (#b001
(minibuffer-message "Sole completion")
540 (#b011
(minibuffer-message "Complete, but not unique")
544 (defvar completion-all-sorted-completions nil
)
545 (make-variable-buffer-local 'completion-all-sorted-completions
)
547 (defun completion--flush-all-sorted-completions (&rest ignore
)
548 (setq completion-all-sorted-completions nil
))
550 (defun completion-all-sorted-completions ()
551 (or completion-all-sorted-completions
552 (let* ((start (field-beginning))
554 (all (completion-all-completions (buffer-substring start end
)
555 minibuffer-completion-table
556 minibuffer-completion-predicate
559 (base-size (or (cdr last
) 0)))
562 ;; Prefer shorter completions.
563 (setq all
(sort all
(lambda (c1 c2
) (< (length c1
) (length c2
)))))
564 ;; Prefer recently used completions.
565 (let ((hist (symbol-value minibuffer-history-variable
)))
566 (setq all
(sort all
(lambda (c1 c2
)
567 (> (length (member c1 hist
))
568 (length (member c2 hist
)))))))
569 ;; Cache the result. This is not just for speed, but also so that
570 ;; repeated calls to minibuffer-force-complete can cycle through
571 ;; all possibilities.
572 (add-hook 'after-change-functions
573 'completion--flush-all-sorted-completions nil t
)
574 (setq completion-all-sorted-completions
575 (nconc all base-size
))))))
577 (defun minibuffer-force-complete ()
578 "Complete the minibuffer to an exact match.
579 Repeated uses step through the possible completions."
581 ;; FIXME: Need to deal with the extra-size issue here as well.
582 ;; FIXME: ~/src/emacs/t<M-TAB>/lisp/minibuffer.el completes to
583 ;; ~/src/emacs/trunk/ and throws away lisp/minibuffer.el.
584 (let* ((start (field-beginning))
586 (all (completion-all-sorted-completions)))
587 (if (not (consp all
))
588 (minibuffer-message (if all
"No more completions" "No completions"))
591 (delete-region (+ start
(cdr (last all
))) end
)
592 ;; If completing file names, (car all) may be a directory, so we'd now
593 ;; have a new set of possible completions and might want to reset
594 ;; completion-all-sorted-completions to nil, but we prefer not to,
595 ;; so that repeated calls minibuffer-force-complete still cycle
596 ;; through the previous possible completions.
597 (let ((last (last all
)))
598 (setcdr last
(cons (car all
) (cdr last
)))
599 (setq completion-all-sorted-completions
(cdr all
))))))
601 (defvar minibuffer-confirm-exit-commands
602 '(minibuffer-complete minibuffer-complete-word PC-complete PC-complete-word
)
603 "A list of commands which cause an immediately following
604 `minibuffer-complete-and-exit' to ask for extra confirmation.")
606 (defun minibuffer-complete-and-exit ()
607 "Exit if the minibuffer contains a valid completion.
608 Otherwise, try to complete the minibuffer contents. If
609 completion leads to a valid completion, a repetition of this
612 If `minibuffer-completion-confirm' is `confirm', do not try to
613 complete; instead, ask for confirmation and accept any input if
615 If `minibuffer-completion-confirm' is `confirm-after-completion',
616 do not try to complete; instead, ask for confirmation if the
617 preceding minibuffer command was a member of
618 `minibuffer-confirm-exit-commands', and accept the input
621 (let ((beg (field-beginning))
624 ;; Allow user to specify null string
625 ((= beg end
) (exit-minibuffer))
626 ((test-completion (buffer-substring beg end
)
627 minibuffer-completion-table
628 minibuffer-completion-predicate
)
629 (when completion-ignore-case
630 ;; Fixup case of the field, if necessary.
631 (let* ((string (buffer-substring beg end
))
632 (compl (try-completion
634 minibuffer-completion-table
635 minibuffer-completion-predicate
)))
636 (when (and (stringp compl
)
637 ;; If it weren't for this piece of paranoia, I'd replace
638 ;; the whole thing with a call to do-completion.
639 ;; This is important, e.g. when the current minibuffer's
640 ;; content is a directory which only contains a single
641 ;; file, so `try-completion' actually completes to
643 (= (length string
) (length compl
)))
646 (delete-region beg end
))))
649 ((eq minibuffer-completion-confirm
'confirm
)
650 ;; The user is permitted to exit with an input that's rejected
651 ;; by test-completion, after confirming her choice.
652 (if (eq last-command this-command
)
654 (minibuffer-message "Confirm")
657 ((eq minibuffer-completion-confirm
'confirm-after-completion
)
658 ;; Similar to the above, but only if trying to exit immediately
659 ;; after typing TAB (this catches most minibuffer typos).
660 (if (memq last-command minibuffer-confirm-exit-commands
)
661 (progn (minibuffer-message "Confirm")
666 ;; Call do-completion, but ignore errors.
667 (case (condition-case nil
668 (completion--do-completion)
670 ((#b001
#b011
) (exit-minibuffer))
671 (#b111
(if (not minibuffer-completion-confirm
)
673 (minibuffer-message "Confirm")
677 (defun completion--try-word-completion (string table predicate point
)
678 (let ((comp (completion-try-completion string table predicate point
)))
679 (if (not (consp comp
))
682 ;; If completion finds next char not unique,
683 ;; consider adding a space or a hyphen.
684 (when (= (length string
) (length (car comp
)))
685 ;; Mark the added char with the `completion-word' property, so it
686 ;; can be handled specially by completion styles such as
687 ;; partial-completion.
688 ;; We used to remove `partial-completion' from completion-styles
689 ;; instead, but it was too blunt, leading to situations where SPC
690 ;; was the only insertable char at point but minibuffer-complete-word
691 ;; refused inserting it.
692 (let ((exts (mapcar (lambda (str) (propertize str
'completion-try-word t
))
694 (before (substring string
0 point
))
695 (after (substring string point
))
697 (while (and exts
(not (consp tem
)))
698 (setq tem
(completion-try-completion
699 (concat before
(pop exts
) after
)
700 table predicate
(1+ point
))))
701 (if (consp tem
) (setq comp tem
))))
703 ;; Completing a single word is actually more difficult than completing
704 ;; as much as possible, because we first have to find the "current
705 ;; position" in `completion' in order to find the end of the word
706 ;; we're completing. Normally, `string' is a prefix of `completion',
707 ;; which makes it trivial to find the position, but with fancier
708 ;; completion (plus env-var expansion, ...) `completion' might not
709 ;; look anything like `string' at all.
710 (let* ((comppoint (cdr comp
))
711 (completion (car comp
))
712 (before (substring string
0 point
))
713 (combined (concat before
"\n" completion
)))
714 ;; Find in completion the longest text that was right before point.
715 (when (string-match "\\(.+\\)\n.*?\\1" combined
)
716 (let* ((prefix (match-string 1 before
))
717 ;; We used non-greedy match to make `rem' as long as possible.
718 (rem (substring combined
(match-end 0)))
719 ;; Find in the remainder of completion the longest text
720 ;; that was right after point.
721 (after (substring string point
))
722 (suffix (if (string-match "\\`\\(.+\\).*\n.*\\1"
723 (concat after
"\n" rem
))
724 (match-string 1 after
))))
725 ;; The general idea is to try and guess what text was inserted
726 ;; at point by the completion. Problem is: if we guess wrong,
727 ;; we may end up treating as "added by completion" text that was
728 ;; actually painfully typed by the user. So if we then cut
729 ;; after the first word, we may throw away things the
730 ;; user wrote. So let's try to be as conservative as possible:
731 ;; only cut after the first word, if we're reasonably sure that
732 ;; our guess is correct.
733 ;; Note: a quick survey on emacs-devel seemed to indicate that
734 ;; nobody actually cares about the "word-at-a-time" feature of
735 ;; minibuffer-complete-word, whose real raison-d'être is that it
736 ;; tries to add "-" or " ". One more reason to only cut after
737 ;; the first word, if we're really sure we're right.
738 (when (and (or suffix
(zerop (length after
)))
739 (string-match (concat
740 ;; Make submatch 1 as small as possible
741 ;; to reduce the risk of cutting
743 ".*" (regexp-quote prefix
) "\\(.*?\\)"
744 (if suffix
(regexp-quote suffix
) "\\'"))
746 ;; The new point in `completion' should also be just
747 ;; before the suffix, otherwise something more complex
748 ;; is going on, and we're not sure where we are.
749 (eq (match-end 1) comppoint
)
750 ;; (match-beginning 1)..comppoint is now the stretch
751 ;; of text in `completion' that was completed at point.
752 (string-match "\\W" completion
(match-beginning 1))
753 ;; Is there really something to cut?
754 (> comppoint
(match-end 0)))
755 ;; Cut after the first word.
756 (let ((cutpos (match-end 0)))
757 (setq completion
(concat (substring completion
0 cutpos
)
758 (substring completion comppoint
)))
759 (setq comppoint cutpos
)))))
761 (cons completion comppoint
)))))
764 (defun minibuffer-complete-word ()
765 "Complete the minibuffer contents at most a single word.
766 After one word is completed as much as possible, a space or hyphen
767 is added, provided that matches some possible completion.
768 Return nil if there is no valid completion, else t."
770 (case (completion--do-completion 'completion--try-word-completion
)
772 (#b001
(minibuffer-message "Sole completion")
774 (#b011
(minibuffer-message "Complete, but not unique")
778 (defface completions-annotations
'((t :inherit italic
))
779 "Face to use for annotations in the *Completions* buffer.")
781 (defcustom completions-format nil
782 "Define the appearance and sorting of completions.
783 If the value is `vertical', display completions sorted vertically
784 in columns in the *Completions* buffer.
785 If the value is `horizontal' or nil, display completions sorted
786 horizontally in alphabetical order, rather than down the screen."
787 :type
'(choice (const nil
) (const horizontal
) (const vertical
))
791 (defun completion--insert-strings (strings)
792 "Insert a list of STRINGS into the current buffer.
793 Uses columns to keep the listing readable but compact.
794 It also eliminates runs of equal strings."
795 (when (consp strings
)
796 (let* ((length (apply 'max
799 (+ (string-width (car s
))
800 (string-width (cadr s
)))
803 (window (get-buffer-window (current-buffer) 0))
804 (wwidth (if window
(1- (window-width window
)) 79))
806 ;; At least 2 columns; at least 2 spaces between columns.
807 (max 2 (/ wwidth
(+ 2 length
)))
808 ;; Don't allocate more columns than we can fill.
809 ;; Windows can't show less than 3 lines anyway.
810 (max 1 (/ (length strings
) 2))))
811 (colwidth (/ wwidth columns
))
813 (rows (/ (length strings
) columns
))
816 ;; The insertion should be "sensible" no matter what choices were made
817 ;; for the parameters above.
818 (dolist (str strings
)
819 (unless (equal laststring str
) ; Remove (consecutive) duplicates.
820 (setq laststring str
)
821 (let ((length (if (consp str
)
822 (+ (string-width (car str
))
823 (string-width (cadr str
)))
824 (string-width str
))))
826 ((eq completions-format
'vertical
)
829 (forward-line (- -
1 rows
))
830 (setq row
0 column
(+ column colwidth
)))
833 (while (> (current-column) column
)
839 (set-text-properties (- (point) 1) (point)
840 `(display (space :align-to
,column
)))))
844 (if (< wwidth
(+ (max colwidth length
) column
))
845 ;; No space for `str' at point, move to next line.
846 (progn (insert "\n") (setq column
0))
848 ;; Leave the space unpropertized so that in the case we're
849 ;; already past the goal column, there is still
850 ;; a space displayed.
851 (set-text-properties (- (point) 1) (point)
852 ;; We can't just set tab-width, because
853 ;; completion-setup-function will kill all
854 ;; local variables :-(
855 `(display (space :align-to
,column
)))
857 (if (not (consp str
))
858 (put-text-property (point) (progn (insert str
) (point))
859 'mouse-face
'highlight
)
860 (put-text-property (point) (progn (insert (car str
)) (point))
861 'mouse-face
'highlight
)
862 (add-text-properties (point) (progn (insert (cadr str
)) (point))
864 face completions-annotations
)))
866 ((eq completions-format
'vertical
)
874 ;; Next column to align to.
875 (setq column
(+ column
876 ;; Round up to a whole number of columns.
877 (* colwidth
(ceiling length colwidth
))))))))))))
879 (defvar completion-common-substring nil
)
880 (make-obsolete-variable 'completion-common-substring nil
"23.1")
882 (defvar completion-setup-hook nil
883 "Normal hook run at the end of setting up a completion list buffer.
884 When this hook is run, the current buffer is the one in which the
885 command to display the completion list buffer was run.
886 The completion list buffer is available as the value of `standard-output'.
887 See also `display-completion-list'.")
889 (defface completions-first-difference
890 '((t (:inherit bold
)))
891 "Face put on the first uncommon character in completions in *Completions* buffer."
894 (defface completions-common-part
895 '((t (:inherit default
)))
896 "Face put on the common prefix substring in completions in *Completions* buffer.
897 The idea of `completions-common-part' is that you can use it to
898 make the common parts less visible than normal, so that the rest
899 of the differing parts is, by contrast, slightly highlighted."
902 (defun completion-hilit-commonality (completions prefix-len base-size
)
904 (let ((com-str-len (- prefix-len
(or base-size
0))))
909 ;; Don't modify the string itself, but a copy, since the
910 ;; the string may be read-only or used for other purposes.
911 ;; Furthermore, since `completions' may come from
912 ;; display-completion-list, `elem' may be a list.
914 (car (setq elem
(cons (copy-sequence (car elem
))
916 (setq elem
(copy-sequence elem
)))))
918 ;; If completion-boundaries returns incorrect
919 ;; values, all-completions may return strings
920 ;; that don't contain the prefix.
921 (min com-str-len
(length str
))
922 'font-lock-face
'completions-common-part
924 (if (> (length str
) com-str-len
)
925 (put-text-property com-str-len
(1+ com-str-len
)
926 'font-lock-face
'completions-first-difference
932 (defun display-completion-list (completions &optional common-substring
)
933 "Display the list of completions, COMPLETIONS, using `standard-output'.
934 Each element may be just a symbol or string
935 or may be a list of two strings to be printed as if concatenated.
936 If it is a list of two strings, the first is the actual completion
937 alternative, the second serves as annotation.
938 `standard-output' must be a buffer.
939 The actual completion alternatives, as inserted, are given `mouse-face'
940 properties of `highlight'.
941 At the end, this runs the normal hook `completion-setup-hook'.
942 It can find the completion buffer in `standard-output'.
944 The obsolete optional arg COMMON-SUBSTRING, if non-nil, should be a string
945 specifying a common substring for adding the faces
946 `completions-first-difference' and `completions-common-part' to
947 the completions buffer."
949 (setq completions
(completion-hilit-commonality
950 completions
(length common-substring
)
951 ;; We don't know the base-size.
953 (if (not (bufferp standard-output
))
954 ;; This *never* (ever) happens, so there's no point trying to be clever.
956 (let ((standard-output (current-buffer))
957 (completion-setup-hook nil
))
958 (display-completion-list completions common-substring
))
959 (princ (buffer-string)))
961 (with-current-buffer standard-output
962 (goto-char (point-max))
963 (if (null completions
)
964 (insert "There are no possible completions of what you have typed.")
965 (insert "Possible completions are:\n")
966 (completion--insert-strings completions
))))
968 ;; The hilit used to be applied via completion-setup-hook, so there
969 ;; may still be some code that uses completion-common-substring.
971 (let ((completion-common-substring common-substring
))
972 (run-hooks 'completion-setup-hook
)))
975 (defvar completion-annotate-function
977 ;; Note: there's a lot of scope as for when to add annotations and
978 ;; what annotations to add. E.g. completing-help.el allowed adding
979 ;; the first line of docstrings to M-x completion. But there's
980 ;; a tension, since such annotations, while useful at times, can
981 ;; actually drown the useful information.
982 ;; So completion-annotate-function should be used parsimoniously, or
983 ;; else only used upon a user's request (e.g. we could add a command
984 ;; to completion-list-mode to add annotations to the current
986 "Function to add annotations in the *Completions* buffer.
987 The function takes a completion and should either return nil, or a string that
988 will be displayed next to the completion. The function can access the
989 completion table and predicates via `minibuffer-completion-table' and related
992 (defun minibuffer-completion-help ()
993 "Display a list of possible completions of the current minibuffer contents."
995 (message "Making completion list...")
996 (let* ((start (field-beginning))
997 (string (field-string))
998 (completions (completion-all-completions
1000 minibuffer-completion-table
1001 minibuffer-completion-predicate
1002 (- (point) (field-beginning)))))
1004 (if (and completions
1005 (or (consp (cdr completions
))
1006 (not (equal (car completions
) string
))))
1007 (let* ((last (last completions
))
1008 (base-size (cdr last
))
1009 ;; If the *Completions* buffer is shown in a new
1010 ;; window, mark it as softly-dedicated, so bury-buffer in
1011 ;; minibuffer-hide-completions will know whether to
1012 ;; delete the window or not.
1013 (display-buffer-mark-dedicated 'soft
))
1014 (with-output-to-temp-buffer "*Completions*"
1015 ;; Remove the base-size tail because `sort' requires a properly
1016 ;; nil-terminated list.
1017 (when last
(setcdr last nil
))
1018 (setq completions
(sort completions
'string-lessp
))
1019 (when completion-annotate-function
1023 (funcall completion-annotate-function s
)))
1024 (if ann
(list s ann
) s
)))
1026 (with-current-buffer standard-output
1027 (set (make-local-variable 'completion-base-position
)
1028 ;; FIXME: We should provide the END part as well, but
1029 ;; currently completion-all-completions does not give
1030 ;; us the necessary information.
1031 (list (+ start base-size
) nil
)))
1032 (display-completion-list completions
)))
1034 ;; If there are no completions, or if the current input is already the
1035 ;; only possible completion, then hide (previous&stale) completions.
1036 (minibuffer-hide-completions)
1039 (if completions
"Sole completion" "No completions")))
1042 (defun minibuffer-hide-completions ()
1043 "Get rid of an out-of-date *Completions* buffer."
1044 ;; FIXME: We could/should use minibuffer-scroll-window here, but it
1045 ;; can also point to the minibuffer-parent-window, so it's a bit tricky.
1046 (let ((win (get-buffer-window "*Completions*" 0)))
1047 (if win
(with-selected-window win
(bury-buffer)))))
1049 (defun exit-minibuffer ()
1050 "Terminate this minibuffer argument."
1052 ;; If the command that uses this has made modifications in the minibuffer,
1053 ;; we don't want them to cause deactivation of the mark in the original
1055 ;; A better solution would be to make deactivate-mark buffer-local
1056 ;; (or to turn it into a list of buffers, ...), but in the mean time,
1057 ;; this should do the trick in most cases.
1058 (setq deactivate-mark nil
)
1061 (defun self-insert-and-exit ()
1062 "Terminate minibuffer input."
1064 (if (characterp last-command-event
)
1065 (call-interactively 'self-insert-command
)
1069 (defvar completion-in-region-functions nil
1070 "Wrapper hook around `complete-in-region'.
1071 The functions on this special hook are called with 5 arguments:
1072 NEXT-FUN START END COLLECTION PREDICATE.
1073 NEXT-FUN is a function of four arguments (START END COLLECTION PREDICATE)
1074 that performs the default operation. The other four argument are like
1075 the ones passed to `complete-in-region'. The functions on this hook
1076 are expected to perform completion on START..END using COLLECTION
1077 and PREDICATE, either by calling NEXT-FUN or by doing it themselves.")
1079 (defun completion-in-region (start end collection
&optional predicate
)
1080 "Complete the text between START and END using COLLECTION.
1081 Point needs to be somewhere between START and END."
1082 ;; FIXME: some callers need to setup completion-ignore-case,
1083 ;; completion-ignored-extensions. The latter can be embedded in the
1084 ;; completion tables, but the first cannot (actually, maybe it should).
1085 (assert (<= start
(point)) (<= (point) end
))
1086 ;; FIXME: undisplay the *Completions* buffer once the completion is done.
1088 completion-in-region-functions
(start end collection predicate
)
1089 (let ((minibuffer-completion-table collection
)
1090 (minibuffer-completion-predicate predicate
)
1091 (ol (make-overlay start end nil nil t
)))
1092 (overlay-put ol
'field
'completion
)
1094 (call-interactively 'minibuffer-complete
)
1095 (delete-overlay ol
)))))
1097 (let ((map minibuffer-local-map
))
1098 (define-key map
"\C-g" 'abort-recursive-edit
)
1099 (define-key map
"\r" 'exit-minibuffer
)
1100 (define-key map
"\n" 'exit-minibuffer
))
1102 (let ((map minibuffer-local-completion-map
))
1103 (define-key map
"\t" 'minibuffer-complete
)
1104 ;; M-TAB is already abused for many other purposes, so we should find
1105 ;; another binding for it.
1106 ;; (define-key map "\e\t" 'minibuffer-force-complete)
1107 (define-key map
" " 'minibuffer-complete-word
)
1108 (define-key map
"?" 'minibuffer-completion-help
))
1110 (let ((map minibuffer-local-must-match-map
))
1111 (define-key map
"\r" 'minibuffer-complete-and-exit
)
1112 (define-key map
"\n" 'minibuffer-complete-and-exit
))
1114 (let ((map minibuffer-local-filename-completion-map
))
1115 (define-key map
" " nil
))
1116 (let ((map minibuffer-local-filename-must-match-map
))
1117 (define-key map
" " nil
))
1119 (let ((map minibuffer-local-ns-map
))
1120 (define-key map
" " 'exit-minibuffer
)
1121 (define-key map
"\t" 'exit-minibuffer
)
1122 (define-key map
"?" 'self-insert-and-exit
))
1124 ;;; Completion tables.
1126 (defun minibuffer--double-dollars (str)
1127 (replace-regexp-in-string "\\$" "$$" str
))
1129 (defun completion--make-envvar-table ()
1130 (mapcar (lambda (enventry)
1131 (substring enventry
0 (string-match-p "=" enventry
)))
1132 process-environment
))
1134 (defconst completion--embedded-envvar-re
1135 (concat "\\(?:^\\|[^$]\\(?:\\$\\$\\)*\\)"
1136 "$\\([[:alnum:]_]*\\|{\\([^}]*\\)\\)\\'"))
1138 (defun completion--embedded-envvar-table (string pred action
)
1139 "Completion table for envvars embedded in a string.
1140 The envvar syntax (and escaping) rules followed by this table are the
1141 same as `substitute-in-file-name'."
1142 ;; We ignore `pred', because the predicates passed to us via
1143 ;; read-file-name-internal are not 100% correct and fail here:
1144 ;; e.g. we get predicates like file-directory-p there, whereas the filename
1145 ;; completed needs to be passed through substitute-in-file-name before it
1146 ;; can be passed to file-directory-p.
1147 (when (string-match completion--embedded-envvar-re string
)
1148 (let* ((beg (or (match-beginning 2) (match-beginning 1)))
1149 (table (completion--make-envvar-table))
1150 (prefix (substring string
0 beg
)))
1152 ((eq action
'lambda
)
1153 ;; This table is expected to be used in conjunction with some
1154 ;; other table that provides the "main" completion. Let the
1155 ;; other table handle the test-completion case.
1157 ((eq (car-safe action
) 'boundaries
)
1158 ;; Only return boundaries if there's something to complete,
1159 ;; since otherwise when we're used in
1160 ;; completion-table-in-turn, we could return boundaries and
1161 ;; let some subsequent table return a list of completions.
1162 ;; FIXME: Maybe it should rather be fixed in
1163 ;; completion-table-in-turn instead, but it's difficult to
1164 ;; do it efficiently there.
1165 (when (try-completion (substring string beg
) table nil
)
1166 ;; Compute the boundaries of the subfield to which this
1167 ;; completion applies.
1168 (let ((suffix (cdr action
)))
1170 (or (match-beginning 2) (match-beginning 1))
1171 (when (string-match "[^[:alnum:]_]" suffix
)
1172 (match-beginning 0))))))
1174 (if (eq (aref string
(1- beg
)) ?
{)
1175 (setq table
(apply-partially 'completion-table-with-terminator
1177 ;; Even if file-name completion is case-insensitive, we want
1178 ;; envvar completion to be case-sensitive.
1179 (let ((completion-ignore-case nil
))
1180 (completion-table-with-context
1181 prefix table
(substring string beg
) nil action
)))))))
1183 (defun completion-file-name-table (string pred action
)
1184 "Completion table for file names."
1187 ((eq (car-safe action
) 'boundaries
)
1188 (let ((start (length (file-name-directory string
)))
1189 (end (string-match-p "/" (cdr action
))))
1190 (list* 'boundaries start end
)))
1192 ((eq action
'lambda
)
1193 (if (zerop (length string
))
1194 nil
;Not sure why it's here, but it probably doesn't harm.
1195 (funcall (or pred
'file-exists-p
) string
)))
1198 (let* ((name (file-name-nondirectory string
))
1199 (specdir (file-name-directory string
))
1200 (realdir (or specdir default-directory
)))
1204 (let ((comp (file-name-completion name realdir pred
)))
1206 (concat specdir comp
)
1210 (let ((all (file-name-all-completions name realdir
)))
1212 ;; Check the predicate, if necessary.
1213 (unless (memq pred
'(nil file-exists-p
))
1216 (if (eq pred
'file-directory-p
)
1217 ;; Brute-force speed up for directory checking:
1218 ;; Discard strings which don't end in a slash.
1220 (let ((len (length s
)))
1221 (and (> len
0) (eq (aref s
(1- len
)) ?
/))))
1222 ;; Must do it the hard (and slow) way.
1224 (let ((default-directory (expand-file-name realdir
)))
1226 (if (funcall pred tem
) (push tem comp
))))
1227 (setq all
(nreverse comp
))))
1231 (defvar read-file-name-predicate nil
1232 "Current predicate used by `read-file-name-internal'.")
1233 (make-obsolete-variable 'read-file-name-predicate
1234 "use the regular PRED argument" "23.2")
1236 (defun completion--file-name-table (string pred action
)
1237 "Internal subroutine for `read-file-name'. Do not call this.
1238 This is a completion table for file names, like `completion-file-name-table'
1239 except that it passes the file name through `substitute-in-file-name'."
1241 ((eq (car-safe action
) 'boundaries
)
1242 ;; For the boundaries, we can't really delegate to
1243 ;; completion-file-name-table and then fix them up, because it
1244 ;; would require us to track the relationship between `str' and
1245 ;; `string', which is difficult. And in any case, if
1246 ;; substitute-in-file-name turns "fo-$TO-ba" into "fo-o/b-ba", there's
1247 ;; no way for us to return proper boundaries info, because the
1248 ;; boundary is not (yet) in `string'.
1249 (let ((start (length (file-name-directory string
)))
1250 (end (string-match-p "/" (cdr action
))))
1251 (list* 'boundaries start end
)))
1254 (let* ((default-directory
1256 ;; It used to be that `pred' was abused to pass `dir'
1258 (prog1 (file-name-as-directory (expand-file-name pred
))
1261 (str (condition-case nil
1262 (substitute-in-file-name string
)
1264 (comp (completion-file-name-table
1265 str
(or pred read-file-name-predicate
) action
)))
1269 ;; Requote the $s before returning the completion.
1270 (minibuffer--double-dollars comp
))
1271 ((and (null action
) comp
1272 ;; Requote the $s before checking for changes.
1273 (setq str
(minibuffer--double-dollars str
))
1274 (not (string-equal string str
)))
1275 ;; If there's no real completion, but substitute-in-file-name
1276 ;; changed the string, then return the new string.
1280 (defalias 'read-file-name-internal
1281 (completion-table-in-turn 'completion--embedded-envvar-table
1282 'completion--file-name-table
)
1283 "Internal subroutine for `read-file-name'. Do not call this.")
1285 (defvar read-file-name-function nil
1286 "If this is non-nil, `read-file-name' does its work by calling this function.")
1288 (defcustom read-file-name-completion-ignore-case
1289 (if (memq system-type
'(ms-dos windows-nt darwin cygwin
))
1291 "Non-nil means when reading a file name completion ignores case."
1296 (defcustom insert-default-directory t
1297 "Non-nil means when reading a filename start with default dir in minibuffer.
1299 When the initial minibuffer contents show a name of a file or a directory,
1300 typing RETURN without editing the initial contents is equivalent to typing
1301 the default file name.
1303 If this variable is non-nil, the minibuffer contents are always
1304 initially non-empty, and typing RETURN without editing will fetch the
1305 default name, if one is provided. Note however that this default name
1306 is not necessarily the same as initial contents inserted in the minibuffer,
1307 if the initial contents is just the default directory.
1309 If this variable is nil, the minibuffer often starts out empty. In
1310 that case you may have to explicitly fetch the next history element to
1311 request the default name; typing RETURN without editing will leave
1312 the minibuffer empty.
1314 For some commands, exiting with an empty minibuffer has a special meaning,
1315 such as making the current buffer visit no file in the case of
1316 `set-visited-file-name'."
1320 ;; Not always defined, but only called if next-read-file-uses-dialog-p says so.
1321 (declare-function x-file-dialog
"xfns.c"
1322 (prompt dir
&optional default-filename mustmatch only-dir-p
))
1324 (defun read-file-name-defaults (&optional dir initial
)
1327 ;; With non-nil `initial', use `dir' as the first default.
1328 ;; Essentially, this mean reversing the normal order of the
1329 ;; current directory name and the current file name, i.e.
1330 ;; 1. with normal file reading:
1331 ;; 1.1. initial input is the current directory
1332 ;; 1.2. the first default is the current file name
1333 ;; 2. with non-nil `initial' (e.g. for `find-alternate-file'):
1334 ;; 2.2. initial input is the current file name
1335 ;; 2.1. the first default is the current directory
1336 (initial (abbreviate-file-name dir
))
1337 ;; In file buffers, try to get the current file name
1339 (abbreviate-file-name buffer-file-name
))))
1341 (run-hook-with-args-until-success 'file-name-at-point-functions
)))
1342 (when file-name-at-point
1343 (setq default
(delete-dups
1344 (delete "" (delq nil
(list file-name-at-point default
))))))
1345 ;; Append new defaults to the end of existing `minibuffer-default'.
1347 (if (listp minibuffer-default
) minibuffer-default
(list minibuffer-default
))
1348 (if (listp default
) default
(list default
)))))
1350 (defun read-file-name (prompt &optional dir default-filename mustmatch initial predicate
)
1351 "Read file name, prompting with PROMPT and completing in directory DIR.
1352 Value is not expanded---you must call `expand-file-name' yourself.
1353 Default name to DEFAULT-FILENAME if user exits the minibuffer with
1354 the same non-empty string that was inserted by this function.
1355 (If DEFAULT-FILENAME is omitted, the visited file name is used,
1356 except that if INITIAL is specified, that combined with DIR is used.
1357 If DEFAULT-FILENAME is a list of file names, the first file name is used.)
1358 If the user exits with an empty minibuffer, this function returns
1359 an empty string. (This can only happen if the user erased the
1360 pre-inserted contents or if `insert-default-directory' is nil.)
1362 Fourth arg MUSTMATCH can take the following values:
1363 - nil means that the user can exit with any input.
1364 - t means that the user is not allowed to exit unless
1365 the input is (or completes to) an existing file.
1366 - `confirm' means that the user can exit with any input, but she needs
1367 to confirm her choice if the input is not an existing file.
1368 - `confirm-after-completion' means that the user can exit with any
1369 input, but she needs to confirm her choice if she called
1370 `minibuffer-complete' right before `minibuffer-complete-and-exit'
1371 and the input is not an existing file.
1372 - anything else behaves like t except that typing RET does not exit if it
1373 does non-null completion.
1375 Fifth arg INITIAL specifies text to start with.
1377 If optional sixth arg PREDICATE is non-nil, possible completions and
1378 the resulting file name must satisfy (funcall PREDICATE NAME).
1379 DIR should be an absolute directory name. It defaults to the value of
1380 `default-directory'.
1382 If this command was invoked with the mouse, use a graphical file
1383 dialog if `use-dialog-box' is non-nil, and the window system or X
1384 toolkit in use provides a file dialog box, and DIR is not a
1385 remote file. For graphical file dialogs, any the special values
1386 of MUSTMATCH; `confirm' and `confirm-after-completion' are
1387 treated as equivalent to nil.
1389 See also `read-file-name-completion-ignore-case'
1390 and `read-file-name-function'."
1391 (unless dir
(setq dir default-directory
))
1392 (unless (file-name-absolute-p dir
) (setq dir
(expand-file-name dir
)))
1393 (unless default-filename
1394 (setq default-filename
(if initial
(expand-file-name initial dir
)
1396 ;; If dir starts with user's homedir, change that to ~.
1397 (setq dir
(abbreviate-file-name dir
))
1398 ;; Likewise for default-filename.
1399 (if default-filename
1400 (setq default-filename
1401 (if (consp default-filename
)
1402 (mapcar 'abbreviate-file-name default-filename
)
1403 (abbreviate-file-name default-filename
))))
1405 ((and insert-default-directory
(stringp dir
))
1407 (cons (minibuffer--double-dollars (concat dir initial
))
1408 (length (minibuffer--double-dollars dir
)))
1409 (minibuffer--double-dollars dir
)))
1410 (initial (cons (minibuffer--double-dollars initial
) 0)))))
1412 (if read-file-name-function
1413 (funcall read-file-name-function
1414 prompt dir default-filename mustmatch initial predicate
)
1415 (let ((completion-ignore-case read-file-name-completion-ignore-case
)
1416 (minibuffer-completing-file-name t
)
1417 (pred (or predicate
'file-exists-p
))
1418 (add-to-history nil
))
1421 (if (or (not (next-read-file-uses-dialog-p))
1422 ;; Graphical file dialogs can't handle remote
1424 (file-remote-p dir
))
1425 ;; We used to pass `dir' to `read-file-name-internal' by
1426 ;; abusing the `predicate' argument. It's better to
1427 ;; just use `default-directory', but in order to avoid
1428 ;; changing `default-directory' in the current buffer,
1429 ;; we don't let-bind it.
1430 (lexical-let ((dir (file-name-as-directory
1431 (expand-file-name dir
))))
1432 (minibuffer-with-setup-hook
1434 (setq default-directory dir
)
1435 ;; When the first default in `minibuffer-default'
1436 ;; duplicates initial input `insdef',
1437 ;; reset `minibuffer-default' to nil.
1438 (when (equal (or (car-safe insdef
) insdef
)
1439 (or (car-safe minibuffer-default
)
1440 minibuffer-default
))
1441 (setq minibuffer-default
1442 (cdr-safe minibuffer-default
)))
1443 ;; On the first request on `M-n' fill
1444 ;; `minibuffer-default' with a list of defaults
1445 ;; relevant for file-name reading.
1446 (set (make-local-variable 'minibuffer-default-add-function
)
1448 (with-current-buffer
1449 (window-buffer (minibuffer-selected-window))
1450 (read-file-name-defaults dir initial
)))))
1451 (completing-read prompt
'read-file-name-internal
1452 pred mustmatch insdef
1453 'file-name-history default-filename
)))
1454 ;; If DEFAULT-FILENAME not supplied and DIR contains
1455 ;; a file name, split it.
1456 (let ((file (file-name-nondirectory dir
))
1457 ;; When using a dialog, revert to nil and non-nil
1458 ;; interpretation of mustmatch. confirm options
1459 ;; need to be interpreted as nil, otherwise
1460 ;; it is impossible to create new files using
1461 ;; dialogs with the default settings.
1463 (not (memq mustmatch
1464 '(nil confirm confirm-after-completion
)))))
1465 (when (and (not default-filename
)
1466 (not (zerop (length file
))))
1467 (setq default-filename file
)
1468 (setq dir
(file-name-directory dir
)))
1469 (when default-filename
1470 (setq default-filename
1471 (expand-file-name (if (consp default-filename
)
1472 (car default-filename
)
1475 (setq add-to-history t
)
1476 (x-file-dialog prompt dir default-filename
1478 (eq predicate
'file-directory-p
)))))
1480 (replace-in-history (eq (car-safe file-name-history
) val
)))
1481 ;; If completing-read returned the inserted default string itself
1482 ;; (rather than a new string with the same contents),
1483 ;; it has to mean that the user typed RET with the minibuffer empty.
1484 ;; In that case, we really want to return ""
1485 ;; so that commands such as set-visited-file-name can distinguish.
1486 (when (consp default-filename
)
1487 (setq default-filename
(car default-filename
)))
1488 (when (eq val default-filename
)
1489 ;; In this case, completing-read has not added an element
1490 ;; to the history. Maybe we should.
1491 (if (not replace-in-history
)
1492 (setq add-to-history t
))
1494 (unless val
(error "No file name specified"))
1496 (if (and default-filename
1497 (string-equal val
(if (consp insdef
) (car insdef
) insdef
)))
1498 (setq val default-filename
))
1499 (setq val
(substitute-in-file-name val
))
1501 (if replace-in-history
1502 ;; Replace what Fcompleting_read added to the history
1503 ;; with what we will actually return. As an exception,
1504 ;; if that's the same as the second item in
1505 ;; file-name-history, it's really a repeat (Bug#4657).
1506 (let ((val1 (minibuffer--double-dollars val
)))
1507 (if history-delete-duplicates
1508 (setcdr file-name-history
1509 (delete val1
(cdr file-name-history
))))
1510 (if (string= val1
(cadr file-name-history
))
1511 (pop file-name-history
)
1512 (setcar file-name-history val1
)))
1514 ;; Add the value to the history--but not if it matches
1515 ;; the last value already there.
1516 (let ((val1 (minibuffer--double-dollars val
)))
1517 (unless (and (consp file-name-history
)
1518 (equal (car file-name-history
) val1
))
1519 (setq file-name-history
1521 (if history-delete-duplicates
1522 (delete val1 file-name-history
)
1523 file-name-history
)))))))
1526 (defun internal-complete-buffer-except (&optional buffer
)
1527 "Perform completion on all buffers excluding BUFFER.
1528 BUFFER nil or omitted means use the current buffer.
1529 Like `internal-complete-buffer', but removes BUFFER from the completion list."
1530 (lexical-let ((except (if (stringp buffer
) buffer
(buffer-name buffer
))))
1531 (apply-partially 'completion-table-with-predicate
1532 'internal-complete-buffer
1534 (not (equal (if (consp name
) (car name
) name
) except
)))
1537 ;;; Old-style completion, used in Emacs-21 and Emacs-22.
1539 (defun completion-emacs21-try-completion (string table pred point
)
1540 (let ((completion (try-completion string table pred
)))
1541 (if (stringp completion
)
1542 (cons completion
(length completion
))
1545 (defun completion-emacs21-all-completions (string table pred point
)
1546 (completion-hilit-commonality
1547 (all-completions string table pred
)
1549 (car (completion-boundaries string table pred
""))))
1551 (defun completion-emacs22-try-completion (string table pred point
)
1552 (let ((suffix (substring string point
))
1553 (completion (try-completion (substring string
0 point
) table pred
)))
1554 (if (not (stringp completion
))
1556 ;; Merge a trailing / in completion with a / after point.
1557 ;; We used to only do it for word completion, but it seems to make
1558 ;; sense for all completions.
1559 ;; Actually, claiming this feature was part of Emacs-22 completion
1560 ;; is pushing it a bit: it was only done in minibuffer-completion-word,
1561 ;; which was (by default) not bound during file completion, where such
1562 ;; slashes are most likely to occur.
1563 (if (and (not (zerop (length completion
)))
1564 (eq ?
/ (aref completion
(1- (length completion
))))
1565 (not (zerop (length suffix
)))
1566 (eq ?
/ (aref suffix
0)))
1567 ;; This leaves point after the / .
1568 (setq suffix
(substring suffix
1)))
1569 (cons (concat completion suffix
) (length completion
)))))
1571 (defun completion-emacs22-all-completions (string table pred point
)
1572 (let ((beforepoint (substring string
0 point
)))
1573 (completion-hilit-commonality
1574 (all-completions beforepoint table pred
)
1576 (car (completion-boundaries beforepoint table pred
"")))))
1578 ;;; Basic completion.
1580 (defun completion--merge-suffix (completion point suffix
)
1581 "Merge end of COMPLETION with beginning of SUFFIX.
1582 Simple generalization of the \"merge trailing /\" done in Emacs-22.
1583 Return the new suffix."
1584 (if (and (not (zerop (length suffix
)))
1585 (string-match "\\(.+\\)\n\\1" (concat completion
"\n" suffix
)
1586 ;; Make sure we don't compress things to less
1587 ;; than we started with.
1589 ;; Just make sure we didn't match some other \n.
1590 (eq (match-end 1) (length completion
)))
1591 (substring suffix
(- (match-end 1) (match-beginning 1)))
1592 ;; Nothing to merge.
1595 (defun completion-basic-try-completion (string table pred point
)
1596 (let* ((beforepoint (substring string
0 point
))
1597 (afterpoint (substring string point
))
1598 (bounds (completion-boundaries beforepoint table pred afterpoint
)))
1599 (if (zerop (cdr bounds
))
1600 ;; `try-completion' may return a subtly different result
1601 ;; than `all+merge', so try to use it whenever possible.
1602 (let ((completion (try-completion beforepoint table pred
)))
1603 (if (not (stringp completion
))
1607 (completion--merge-suffix completion point afterpoint
))
1608 (length completion
))))
1609 (let* ((suffix (substring afterpoint
(cdr bounds
)))
1610 (prefix (substring beforepoint
0 (car bounds
)))
1612 "" (list (substring beforepoint
(car bounds
))
1614 (substring afterpoint
0 (cdr bounds
)))))
1615 (all (completion-pcm--all-completions prefix pattern table pred
)))
1616 (if minibuffer-completing-file-name
1617 (setq all
(completion-pcm--filename-try-filter all
)))
1618 (completion-pcm--merge-try pattern all prefix suffix
)))))
1620 (defun completion-basic-all-completions (string table pred point
)
1621 (let* ((beforepoint (substring string
0 point
))
1622 (afterpoint (substring string point
))
1623 (bounds (completion-boundaries beforepoint table pred afterpoint
))
1624 (suffix (substring afterpoint
(cdr bounds
)))
1625 (prefix (substring beforepoint
0 (car bounds
)))
1627 "" (list (substring beforepoint
(car bounds
))
1629 (substring afterpoint
0 (cdr bounds
)))))
1630 (all (completion-pcm--all-completions prefix pattern table pred
)))
1631 (completion-hilit-commonality all point
(car bounds
))))
1633 ;;; Partial-completion-mode style completion.
1635 (defvar completion-pcm--delim-wild-regex nil
1636 "Regular expression matching delimiters controlling the partial-completion.
1637 Typically, this regular expression simply matches a delimiter, meaning
1638 that completion can add something at (match-beginning 0), but if it has
1639 a submatch 1, then completion can add something at (match-end 1).
1640 This is used when the delimiter needs to be of size zero (e.g. the transition
1641 from lowercase to uppercase characters).")
1643 (defun completion-pcm--prepare-delim-re (delims)
1644 (setq completion-pcm--delim-wild-regex
(concat "[" delims
"*]")))
1646 (defcustom completion-pcm-word-delimiters
"-_. "
1647 "A string of characters treated as word delimiters for completion.
1649 If `]' is in this string, it must come first.
1650 If `^' is in this string, it must not come first.
1651 If `-' is in this string, it must come first or right after `]'.
1652 In other words, if S is this string, then `[S]' must be a valid Emacs regular
1653 expression (not containing character ranges like `a-z')."
1654 :set
(lambda (symbol value
)
1655 (set-default symbol value
)
1656 ;; Refresh other vars.
1657 (completion-pcm--prepare-delim-re value
))
1658 :initialize
'custom-initialize-reset
1662 (defun completion-pcm--pattern-trivial-p (pattern)
1663 (and (stringp (car pattern
))
1664 ;; It can be followed by `point' and "" and still be trivial.
1666 (dolist (elem (cdr pattern
))
1667 (unless (member elem
'(point ""))
1668 (setq trivial nil
)))
1671 (defun completion-pcm--string->pattern
(string &optional point
)
1672 "Split STRING into a pattern.
1673 A pattern is a list where each element is either a string
1674 or a symbol chosen among `any', `star', `point'."
1675 (if (and point
(< point
(length string
)))
1676 (let ((prefix (substring string
0 point
))
1677 (suffix (substring string point
)))
1678 (append (completion-pcm--string->pattern prefix
)
1680 (completion-pcm--string->pattern suffix
)))
1685 (while (and (setq p
(string-match completion-pcm--delim-wild-regex
1687 ;; If the char was added by minibuffer-complete-word, then
1688 ;; don't treat it as a delimiter, otherwise "M-x SPC"
1689 ;; ends up inserting a "-" rather than listing
1691 (not (get-text-property p
'completion-try-word string
)))
1692 ;; Usually, completion-pcm--delim-wild-regex matches a delimiter,
1693 ;; meaning that something can be added *before* it, but it can also
1694 ;; match a prefix and postfix, in which case something can be added
1695 ;; in-between (e.g. match [[:lower:]][[:upper:]]).
1696 ;; This is determined by the presence of a submatch-1 which delimits
1698 (if (match-end 1) (setq p
(match-end 1)))
1699 (push (substring string p0 p
) pattern
)
1700 (if (eq (aref string p
) ?
*)
1702 (push 'star pattern
)
1708 ;; An empty string might be erroneously added at the beginning.
1709 ;; It should be avoided properly, but it's so easy to remove it here.
1710 (delete "" (nreverse (cons (substring string p0
) pattern
))))))
1712 (defun completion-pcm--pattern->regex
(pattern &optional group
)
1719 (if (if (consp group
) (memq x group
) group
)
1721 (t (regexp-quote x
))))
1724 ;; Avoid pathological backtracking.
1725 (while (string-match "\\.\\*\\?\\(?:\\\\[()]\\)*\\(\\.\\*\\?\\)" re
)
1726 (setq re
(replace-match "" t t re
1)))
1729 (defun completion-pcm--all-completions (prefix pattern table pred
)
1730 "Find all completions for PATTERN in TABLE obeying PRED.
1731 PATTERN is as returned by `completion-pcm--string->pattern'."
1732 ;; (assert (= (car (completion-boundaries prefix table pred ""))
1733 ;; (length prefix)))
1734 ;; Find an initial list of possible completions.
1735 (if (completion-pcm--pattern-trivial-p pattern
)
1737 ;; Minibuffer contains no delimiters -- simple case!
1738 (all-completions (concat prefix
(car pattern
)) table pred
)
1740 ;; Use all-completions to do an initial cull. This is a big win,
1741 ;; since all-completions is written in C!
1742 (let* (;; Convert search pattern to a standard regular expression.
1743 (regex (completion-pcm--pattern->regex pattern
))
1744 (case-fold-search completion-ignore-case
)
1745 (completion-regexp-list (cons regex completion-regexp-list
))
1746 (compl (all-completions
1747 (concat prefix
(if (stringp (car pattern
)) (car pattern
) ""))
1749 (if (not (functionp table
))
1750 ;; The internal functions already obeyed completion-regexp-list.
1754 (when (string-match-p regex c
) (push c poss
)))
1757 (defun completion-pcm--hilit-commonality (pattern completions
)
1759 (let* ((re (completion-pcm--pattern->regex pattern
'(point)))
1760 (case-fold-search completion-ignore-case
))
1761 ;; Remove base-size during mapcar, and add it back later.
1764 ;; Don't modify the string itself.
1765 (setq str
(copy-sequence str
))
1766 (unless (string-match re str
)
1767 (error "Internal error: %s does not match %s" re str
))
1768 (let ((pos (or (match-beginning 1) (match-end 0))))
1769 (put-text-property 0 pos
1770 'font-lock-face
'completions-common-part
1772 (if (> (length str
) pos
)
1773 (put-text-property pos
(1+ pos
)
1774 'font-lock-face
'completions-first-difference
1779 (defun completion-pcm--find-all-completions (string table pred point
1781 "Find all completions for STRING at POINT in TABLE, satisfying PRED.
1782 POINT is a position inside STRING.
1783 FILTER is a function applied to the return value, that can be used, e.g. to
1784 filter out additional entries (because TABLE migth not obey PRED)."
1785 (unless filter
(setq filter
'identity
))
1786 (let* ((beforepoint (substring string
0 point
))
1787 (afterpoint (substring string point
))
1788 (bounds (completion-boundaries beforepoint table pred afterpoint
))
1789 (prefix (substring beforepoint
0 (car bounds
)))
1790 (suffix (substring afterpoint
(cdr bounds
)))
1792 (setq string
(substring string
(car bounds
) (+ point
(cdr bounds
))))
1793 (let* ((relpoint (- point
(car bounds
)))
1794 (pattern (completion-pcm--string->pattern string relpoint
))
1795 (all (condition-case err
1797 (completion-pcm--all-completions
1798 prefix pattern table pred
))
1799 (error (unless firsterror
(setq firsterror err
)) nil
))))
1800 (when (and (null all
)
1802 (null (ignore-errors (try-completion prefix table pred
))))
1803 ;; The prefix has no completions at all, so we should try and fix
1805 (let ((substring (substring prefix
0 -
1)))
1806 (destructuring-bind (subpat suball subprefix subsuffix
)
1807 (completion-pcm--find-all-completions
1808 substring table pred
(length substring
) filter
)
1809 (let ((sep (aref prefix
(1- (length prefix
))))
1810 ;; Text that goes between the new submatches and the
1811 ;; completion substring.
1813 ;; Eliminate submatches that don't end with the separator.
1814 (dolist (submatch (prog1 suball
(setq suball
())))
1815 (when (eq sep
(aref submatch
(1- (length submatch
))))
1816 (push submatch suball
)))
1818 ;; Update the boundaries and corresponding pattern.
1819 ;; We assume that all submatches result in the same boundaries
1820 ;; since we wouldn't know how to merge them otherwise anyway.
1821 ;; FIXME: COMPLETE REWRITE!!!
1822 (let* ((newbeforepoint
1823 (concat subprefix
(car suball
)
1824 (substring string
0 relpoint
)))
1825 (leftbound (+ (length subprefix
) (length (car suball
))))
1826 (newbounds (completion-boundaries
1827 newbeforepoint table pred afterpoint
)))
1828 (unless (or (and (eq (cdr bounds
) (cdr newbounds
))
1829 (eq (car newbounds
) leftbound
))
1830 ;; Refuse new boundaries if they step over
1832 (< (car newbounds
) leftbound
))
1833 ;; The new completed prefix does change the boundaries
1834 ;; of the completed substring.
1835 (setq suffix
(substring afterpoint
(cdr newbounds
)))
1837 (concat (substring newbeforepoint
(car newbounds
))
1838 (substring afterpoint
0 (cdr newbounds
))))
1839 (setq between
(substring newbeforepoint leftbound
1841 (setq pattern
(completion-pcm--string->pattern
1843 (- (length newbeforepoint
)
1845 (dolist (submatch suball
)
1846 (setq all
(nconc (mapcar
1847 (lambda (s) (concat submatch between s
))
1849 (completion-pcm--all-completions
1850 (concat subprefix submatch between
)
1851 pattern table pred
)))
1853 ;; FIXME: This can come in handy for try-completion,
1854 ;; but isn't right for all-completions, since it lists
1855 ;; invalid completions.
1857 ;; ;; Even though we found expansions in the prefix, none
1858 ;; ;; leads to a valid completion.
1859 ;; ;; Let's keep the expansions, tho.
1860 ;; (dolist (submatch suball)
1861 ;; (push (concat submatch between newsubstring) all)))
1863 (setq pattern
(append subpat
(list 'any
(string sep
))
1864 (if between
(list between
)) pattern
))
1865 (setq prefix subprefix
)))))
1866 (if (and (null all
) firsterror
)
1867 (signal (car firsterror
) (cdr firsterror
))
1868 (list pattern all prefix suffix
)))))
1870 (defun completion-pcm-all-completions (string table pred point
)
1871 (destructuring-bind (pattern all
&optional prefix suffix
)
1872 (completion-pcm--find-all-completions string table pred point
)
1874 (nconc (completion-pcm--hilit-commonality pattern all
)
1877 (defun completion-pcm--merge-completions (strs pattern
)
1878 "Extract the commonality in STRS, with the help of PATTERN."
1879 ;; When completing while ignoring case, we want to try and avoid
1880 ;; completing "fo" to "foO" when completing against "FOO" (bug#4219).
1881 ;; So we try and make sure that the string we return is all made up
1882 ;; of text from the completions rather than part from the
1883 ;; completions and part from the input.
1884 ;; FIXME: This reduces the problems of inconsistent capitalization
1885 ;; but it doesn't fully fix it: we may still end up completing
1886 ;; "fo-ba" to "foo-BAR" or "FOO-bar" when completing against
1887 ;; '("foo-barr" "FOO-BARD").
1889 ((null (cdr strs
)) (list (car strs
)))
1891 (let ((re (completion-pcm--pattern->regex pattern
'group
))
1892 (ccs ())) ;Chopped completions.
1894 ;; First chop each string into the parts corresponding to each
1895 ;; non-constant element of `pattern', using regexp-matching.
1896 (let ((case-fold-search completion-ignore-case
))
1898 (unless (string-match re str
)
1899 (error "Internal error: %s doesn't match %s" str re
))
1904 (while (setq next
(match-end i
))
1905 (push (substring str last next
) chopped
)
1908 ;; Add the text corresponding to the implicit trailing `any'.
1909 (push (substring str last
) chopped
)
1910 (push (nreverse chopped
) ccs
))))
1912 ;; Then for each of those non-constant elements, extract the
1913 ;; commonality between them.
1916 ;; Make the implicit trailing `any' explicit.
1917 (dolist (elem (append pattern
'(any)))
1919 (setq fixed
(concat fixed elem
))
1921 (dolist (cc (prog1 ccs
(setq ccs nil
)))
1922 (push (car cc
) comps
)
1923 (push (cdr cc
) ccs
))
1924 ;; Might improve the likelihood to avoid choosing
1925 ;; different capitalizations in different parts.
1926 ;; In practice, it doesn't seem to make any difference.
1927 (setq ccs
(nreverse ccs
))
1928 (let* ((prefix (try-completion fixed comps
))
1929 (unique (or (and (eq prefix t
) (setq prefix fixed
))
1930 (eq t
(try-completion prefix comps
)))))
1931 (unless (equal prefix
"") (push prefix res
))
1932 ;; If there's only one completion, `elem' is not useful
1933 ;; any more: it can only match the empty string.
1934 ;; FIXME: in some cases, it may be necessary to turn an
1935 ;; `any' into a `star' because the surrounding context has
1936 ;; changed such that string->pattern wouldn't add an `any'
1938 (unless unique
(push elem res
))
1940 ;; We return it in reverse order.
1943 (defun completion-pcm--pattern->string
(pattern)
1944 (mapconcat (lambda (x) (cond
1948 ((eq x
'point
) "")))
1952 ;; We want to provide the functionality of `try', but we use `all'
1953 ;; and then merge it. In most cases, this works perfectly, but
1954 ;; if the completion table doesn't consider the same completions in
1955 ;; `try' as in `all', then we have a problem. The most common such
1956 ;; case is for filename completion where completion-ignored-extensions
1957 ;; is only obeyed by the `try' code. We paper over the difference
1958 ;; here. Note that it is not quite right either: if the completion
1959 ;; table uses completion-table-in-turn, this filtering may take place
1960 ;; too late to correctly fallback from the first to the
1961 ;; second alternative.
1962 (defun completion-pcm--filename-try-filter (all)
1963 "Filter to adjust `all' file completion to the behavior of `try'."
1966 (re (concat "\\(?:\\`\\.\\.?/\\|"
1967 (regexp-opt completion-ignored-extensions
)
1970 (unless (string-match-p re f
) (push f try
)))
1974 (defun completion-pcm--merge-try (pattern all prefix suffix
)
1976 ((not (consp all
)) all
)
1977 ((and (not (consp (cdr all
))) ;Only one completion.
1978 ;; Ignore completion-ignore-case here.
1979 (equal (completion-pcm--pattern->string pattern
) (car all
)))
1982 (let* ((mergedpat (completion-pcm--merge-completions all pattern
))
1983 ;; `mergedpat' is in reverse order. Place new point (by
1984 ;; order of preference) either at the old point, or at
1985 ;; the last place where there's something to choose, or
1987 (pointpat (or (memq 'point mergedpat
) (memq 'any mergedpat
)
1989 ;; New pos from the start.
1990 (newpos (length (completion-pcm--pattern->string pointpat
)))
1991 ;; Do it afterwards because it changes `pointpat' by sideeffect.
1992 (merged (completion-pcm--pattern->string
(nreverse mergedpat
))))
1994 (setq suffix
(completion--merge-suffix merged newpos suffix
))
1995 (cons (concat prefix merged suffix
) (+ newpos
(length prefix
)))))))
1997 (defun completion-pcm-try-completion (string table pred point
)
1998 (destructuring-bind (pattern all prefix suffix
)
1999 (completion-pcm--find-all-completions
2000 string table pred point
2001 (if minibuffer-completing-file-name
2002 'completion-pcm--filename-try-filter
))
2003 (completion-pcm--merge-try pattern all prefix suffix
)))
2005 ;;; Initials completion
2006 ;; Complete /ums to /usr/monnier/src or lch to list-command-history.
2008 (defun completion-initials-expand (str table pred
)
2009 (unless (or (zerop (length str
))
2010 (string-match completion-pcm--delim-wild-regex str
))
2011 (let ((bounds (completion-boundaries str table pred
"")))
2012 (if (zerop (car bounds
))
2013 (mapconcat 'string str
"-")
2014 ;; If there's a boundary, it's trickier. The main use-case
2015 ;; we consider here is file-name completion. We'd like
2016 ;; to expand ~/eee to ~/e/e/e and /eee to /e/e/e.
2017 ;; But at the same time, we don't want /usr/share/ae to expand
2018 ;; to /usr/share/a/e just because we mistyped "ae" for "ar",
2019 ;; so we probably don't want initials to touch anything that
2020 ;; looks like /usr/share/foo. As a heuristic, we just check that
2021 ;; the text before the boundary char is at most 1 char.
2022 ;; This allows both ~/eee and /eee and not much more.
2023 ;; FIXME: It sadly also disallows the use of ~/eee when that's
2024 ;; embedded within something else (e.g. "(~/eee" in Info node
2025 ;; completion or "ancestor:/eee" in bzr-revision completion).
2026 (when (< (car bounds
) 3)
2027 (let ((sep (substring str
(1- (car bounds
)) (car bounds
))))
2028 ;; FIXME: the above string-match checks the whole string, whereas
2029 ;; we end up only caring about the after-boundary part.
2030 (concat (substring str
0 (car bounds
))
2031 (mapconcat 'string
(substring str
(car bounds
)) sep
))))))))
2033 (defun completion-initials-all-completions (string table pred point
)
2034 (let ((newstr (completion-initials-expand string table pred
)))
2036 (completion-pcm-all-completions newstr table pred
(length newstr
)))))
2038 (defun completion-initials-try-completion (string table pred point
)
2039 (let ((newstr (completion-initials-expand string table pred
)))
2041 (completion-pcm-try-completion newstr table pred
(length newstr
)))))
2046 (defun minibuffer-insert-file-name-at-point ()
2047 "Get a file name at point in original buffer and insert it to minibuffer."
2049 (let ((file-name-at-point
2050 (with-current-buffer (window-buffer (minibuffer-selected-window))
2051 (run-hook-with-args-until-success 'file-name-at-point-functions
))))
2052 (when file-name-at-point
2053 (insert file-name-at-point
))))
2055 (provide 'minibuffer
)
2057 ;; arch-tag: ef8a0a15-1080-4790-a754-04017c02f08f
2058 ;;; minibuffer.el ends here