1 ;;; minibuffer.el --- Minibuffer completion functions
3 ;; Copyright (C) 2008, 2009, 2010 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 ;; - extend `boundaries' to provide various other meta-data about the
61 ;; output of `all-completions':
62 ;; - quoting/unquoting (so we can complete files names with envvars
63 ;; and backslashes, and all-completion can list names without
64 ;; quoting backslashes and dollars).
65 ;; - indicate how to turn all-completion's output into
66 ;; try-completion's output: e.g. completion-ignored-extensions.
67 ;; maybe that could be merged with the "quote" operation above.
68 ;; - completion hook to run when the completion is
69 ;; selected/inserted (maybe this should be provided some other
70 ;; way, e.g. as text-property, so `try-completion can also return it?)
71 ;; both for when it's inserted via TAB or via choose-completion.
72 ;; - indicate that `all-completions' doesn't do prefix-completion
73 ;; but just returns some list that relates in some other way to
74 ;; the provided string (as is the case in filecache.el), in which
75 ;; case partial-completion (for example) doesn't make any sense
76 ;; and neither does the completions-first-difference highlight.
78 ;; - make partial-completion-mode obsolete:
79 ;; - (?) <foo.h> style completion for file names.
80 ;; This can't be done identically just by tweaking completion,
81 ;; because partial-completion-mode's behavior is to expand <string.h>
82 ;; to /usr/include/string.h only when exiting the minibuffer, at which
83 ;; point the completion code is actually not involved normally.
84 ;; Partial-completion-mode does it via a find-file-not-found-function.
85 ;; - special code for C-x C-f <> to visit the file ref'd at point
86 ;; via (require 'foo) or #include "foo". ffap seems like a better
87 ;; place for this feature (supplemented with major-mode-provided
88 ;; functions to find the file ref'd at point).
90 ;; - case-sensitivity currently confuses two issues:
91 ;; - whether or not a particular completion table should be case-sensitive
92 ;; (i.e. whether strings that differ only by case are semantically
94 ;; - whether the user wants completion to pay attention to case.
95 ;; e.g. we may want to make it possible for the user to say "first try
96 ;; completion case-sensitively, and if that fails, try to ignore case".
98 ;; - add support for ** to pcm.
99 ;; - Add vc-file-name-completion-table to read-file-name-internal.
100 ;; - A feature like completing-help.el.
104 (eval-when-compile (require 'cl
))
106 ;;; Completion table manipulation
108 ;; New completion-table operation.
109 (defun completion-boundaries (string table pred suffix
)
110 "Return the boundaries of the completions returned by TABLE for STRING.
111 STRING is the string on which completion will be performed.
112 SUFFIX is the string after point.
113 The result is of the form (START . END) where START is the position
114 in STRING of the beginning of the completion field and END is the position
115 in SUFFIX of the end of the completion field.
116 E.g. for simple completion tables, the result is always (0 . (length SUFFIX))
117 and for file names the result is the positions delimited by
118 the closest directory separators."
119 (let ((boundaries (if (functionp table
)
120 (funcall table string pred
(cons 'boundaries suffix
)))))
121 (if (not (eq (car-safe boundaries
) 'boundaries
))
122 (setq boundaries nil
))
123 (cons (or (cadr boundaries
) 0)
124 (or (cddr boundaries
) (length suffix
)))))
126 (defun completion--some (fun xs
)
127 "Apply FUN to each element of XS in turn.
128 Return the first non-nil returned value.
130 (let ((firsterror nil
)
132 (while (and (not res
) xs
)
134 (setq res
(funcall fun
(pop xs
)))
135 (error (unless firsterror
(setq firsterror err
)) nil
)))
137 (if firsterror
(signal (car firsterror
) (cdr firsterror
))))))
139 (defun complete-with-action (action table string pred
)
140 "Perform completion ACTION.
141 STRING is the string to complete.
142 TABLE is the completion table, which should not be a function.
143 PRED is a completion predicate.
144 ACTION can be one of nil, t or `lambda'."
146 ((functionp table
) (funcall table string pred action
))
147 ((eq (car-safe action
) 'boundaries
)
148 (cons 'boundaries
(completion-boundaries string table pred
(cdr action
))))
152 ((null action
) 'try-completion
)
153 ((eq action t
) 'all-completions
)
154 (t 'test-completion
))
155 string table pred
))))
157 (defun completion-table-dynamic (fun)
158 "Use function FUN as a dynamic completion table.
159 FUN is called with one argument, the string for which completion is required,
160 and it should return an alist containing all the intended possible completions.
161 This alist may be a full list of possible completions so that FUN can ignore
162 the value of its argument. If completion is performed in the minibuffer,
163 FUN will be called in the buffer from which the minibuffer was entered.
165 The result of the `completion-table-dynamic' form is a function
166 that can be used as the COLLECTION argument to `try-completion' and
167 `all-completions'. See Info node `(elisp)Programmed Completion'."
168 (lexical-let ((fun fun
))
169 (lambda (string pred action
)
170 (with-current-buffer (let ((win (minibuffer-selected-window)))
171 (if (window-live-p win
) (window-buffer win
)
173 (complete-with-action action
(funcall fun string
) string pred
)))))
175 (defmacro lazy-completion-table
(var fun
)
176 "Initialize variable VAR as a lazy completion table.
177 If the completion table VAR is used for the first time (e.g., by passing VAR
178 as an argument to `try-completion'), the function FUN is called with no
179 arguments. FUN must return the completion table that will be stored in VAR.
180 If completion is requested in the minibuffer, FUN will be called in the buffer
181 from which the minibuffer was entered. The return value of
182 `lazy-completion-table' must be used to initialize the value of VAR.
184 You should give VAR a non-nil `risky-local-variable' property."
185 (declare (debug (symbolp lambda-expr
)))
186 (let ((str (make-symbol "string")))
187 `(completion-table-dynamic
189 (when (functionp ,var
)
193 (defun completion-table-with-context (prefix table string pred action
)
194 ;; TODO: add `suffix' maybe?
195 ;; Notice that `pred' may not be a function in some abusive cases.
196 (when (functionp pred
)
198 (lexical-let ((pred pred
))
199 ;; Predicates are called differently depending on the nature of
200 ;; the completion table :-(
202 ((vectorp table
) ;Obarray.
203 (lambda (sym) (funcall pred
(concat prefix
(symbol-name sym
)))))
204 ((hash-table-p table
)
205 (lambda (s v
) (funcall pred
(concat prefix s
))))
207 (lambda (s) (funcall pred
(concat prefix s
))))
208 (t ;Lists and alists.
210 (funcall pred
(concat prefix
(if (consp s
) (car s
) s
)))))))))
211 (if (eq (car-safe action
) 'boundaries
)
212 (let* ((len (length prefix
))
213 (bound (completion-boundaries string table pred
(cdr action
))))
214 (list* 'boundaries
(+ (car bound
) len
) (cdr bound
)))
215 (let ((comp (complete-with-action action table string pred
)))
217 ;; In case of try-completion, add the prefix.
218 ((stringp comp
) (concat prefix comp
))
221 (defun completion-table-with-terminator (terminator table string pred action
)
222 "Construct a completion table like TABLE but with an extra TERMINATOR.
223 This is meant to be called in a curried way by first passing TERMINATOR
224 and TABLE only (via `apply-partially').
225 TABLE is a completion table, and TERMINATOR is a string appended to TABLE's
226 completion if it is complete. TERMINATOR is also used to determine the
227 completion suffix's boundary.
228 TERMINATOR can also be a cons cell (TERMINATOR . TERMINATOR-REGEXP)
229 in which case TERMINATOR-REGEXP is a regular expression whose submatch
230 number 1 should match TERMINATOR. This is used when there is a need to
231 distinguish occurrences of the TERMINATOR strings which are really terminators
232 from others (e.g. escaped)."
234 ((eq (car-safe action
) 'boundaries
)
235 (let* ((suffix (cdr action
))
236 (bounds (completion-boundaries string table pred suffix
))
237 (terminator-regexp (if (consp terminator
)
238 (cdr terminator
) (regexp-quote terminator
)))
239 (max (string-match terminator-regexp suffix
)))
240 (list* 'boundaries
(car bounds
)
241 (min (cdr bounds
) (or max
(length suffix
))))))
243 (let ((comp (try-completion string table pred
)))
244 (if (consp terminator
) (setq terminator
(car terminator
)))
246 (concat string terminator
)
247 (if (and (stringp comp
)
248 ;; FIXME: Try to avoid this second call, especially since
249 ;; it may be very inefficient (because `comp' made us
250 ;; jump to a new boundary, so we complete in that
251 ;; boundary with an empty start string).
252 ;; completion-boundaries might help.
253 (eq (try-completion comp table pred
) t
))
254 (concat comp terminator
)
257 ;; FIXME: We generally want the `try' and `all' behaviors to be
258 ;; consistent so pcm can merge the `all' output to get the `try' output,
259 ;; but that sometimes clashes with the need for `all' output to look
260 ;; good in *Completions*.
261 ;; (mapcar (lambda (s) (concat s terminator))
262 ;; (all-completions string table pred))))
263 (all-completions string table pred
))
264 ;; completion-table-with-terminator is always used for
265 ;; "sub-completions" so it's only called if the terminator is missing,
266 ;; in which case `test-completion' should return nil.
267 ((eq action
'lambda
) nil
)))
269 (defun completion-table-with-predicate (table pred1 strict string pred2 action
)
270 "Make a completion table equivalent to TABLE but filtered through PRED1.
271 PRED1 is a function of one argument which returns non-nil if and only if the
272 argument is an element of TABLE which should be considered for completion.
273 STRING, PRED2, and ACTION are the usual arguments to completion tables,
274 as described in `try-completion', `all-completions', and `test-completion'.
275 If STRICT is t, the predicate always applies; if nil it only applies if
276 it does not reduce the set of possible completions to nothing.
277 Note: TABLE needs to be a proper completion table which obeys predicates."
279 ((and (not strict
) (eq action
'lambda
))
280 ;; Ignore pred1 since it doesn't really have to apply anyway.
281 (test-completion string table pred2
))
283 (or (complete-with-action action table string
284 (if (null pred2
) pred1
285 (lexical-let ((pred1 pred2
) (pred2 pred2
))
287 ;; Call `pred1' first, so that `pred2'
288 ;; really can't tell that `x' is in table.
289 (if (funcall pred1 x
) (funcall pred2 x
))))))
290 ;; If completion failed and we're not applying pred1 strictly, try
291 ;; again without pred1.
293 (complete-with-action action table string pred2
))))))
295 (defun completion-table-in-turn (&rest tables
)
296 "Create a completion table that tries each table in TABLES in turn."
297 ;; FIXME: the boundaries may come from TABLE1 even when the completion list
298 ;; is returned by TABLE2 (because TABLE1 returned an empty list).
299 (lexical-let ((tables tables
))
300 (lambda (string pred action
)
301 (completion--some (lambda (table)
302 (complete-with-action action table string pred
))
305 ;; (defmacro complete-in-turn (a b) `(completion-table-in-turn ,a ,b))
306 ;; (defmacro dynamic-completion-table (fun) `(completion-table-dynamic ,fun))
307 (define-obsolete-function-alias
308 'complete-in-turn
'completion-table-in-turn
"23.1")
309 (define-obsolete-function-alias
310 'dynamic-completion-table
'completion-table-dynamic
"23.1")
312 ;;; Minibuffer completion
314 (defgroup minibuffer nil
315 "Controlling the behavior of the minibuffer."
316 :link
'(custom-manual "(emacs)Minibuffer")
319 (defun minibuffer-message (message &rest args
)
320 "Temporarily display MESSAGE at the end of the minibuffer.
321 The text is displayed for `minibuffer-message-timeout' seconds,
322 or until the next input event arrives, whichever comes first.
323 Enclose MESSAGE in [...] if this is not yet the case.
324 If ARGS are provided, then pass MESSAGE through `format'."
325 (if (not (minibufferp (current-buffer)))
328 (apply 'message message args
)
329 (message "%s" message
))
330 (prog1 (sit-for (or minibuffer-message-timeout
1000000))
332 ;; Clear out any old echo-area message to make way for our new thing.
334 (setq message
(if (and (null args
) (string-match-p "\\` *\\[.+\\]\\'" message
))
335 ;; Make sure we can put-text-property.
336 (copy-sequence message
)
337 (concat " [" message
"]")))
338 (when args
(setq message
(apply 'format message args
)))
339 (let ((ol (make-overlay (point-max) (point-max) nil t t
))
340 ;; A quit during sit-for normally only interrupts the sit-for,
341 ;; but since minibuffer-message is used at the end of a command,
342 ;; at a time when the command has virtually finished already, a C-g
343 ;; should really cause an abort-recursive-edit instead (i.e. as if
344 ;; the C-g had been typed at top-level). Binding inhibit-quit here
345 ;; is an attempt to get that behavior.
349 (unless (zerop (length message
))
350 ;; The current C cursor code doesn't know to use the overlay's
351 ;; marker's stickiness to figure out whether to place the cursor
352 ;; before or after the string, so let's spoon-feed it the pos.
353 (put-text-property 0 1 'cursor t message
))
354 (overlay-put ol
'after-string message
)
355 (sit-for (or minibuffer-message-timeout
1000000)))
356 (delete-overlay ol
)))))
358 (defun minibuffer-completion-contents ()
359 "Return the user input in a minibuffer before point as a string.
360 That is what completion commands operate on."
361 (buffer-substring (field-beginning) (point)))
363 (defun delete-minibuffer-contents ()
364 "Delete all user input in a minibuffer.
365 If the current buffer is not a minibuffer, erase its entire contents."
366 ;; We used to do `delete-field' here, but when file name shadowing
367 ;; is on, the field doesn't cover the entire minibuffer contents.
368 (delete-region (minibuffer-prompt-end) (point-max)))
370 (defcustom completion-auto-help t
371 "Non-nil means automatically provide help for invalid completion input.
372 If the value is t the *Completion* buffer is displayed whenever completion
373 is requested but cannot be done.
374 If the value is `lazy', the *Completions* buffer is only displayed after
375 the second failed attempt to complete."
376 :type
'(choice (const nil
) (const t
) (const lazy
))
379 (defconst completion-styles-alist
381 completion-emacs21-try-completion completion-emacs21-all-completions
382 "Simple prefix-based completion.")
384 completion-emacs22-try-completion completion-emacs22-all-completions
385 "Prefix completion that only operates on the text before point.")
387 completion-basic-try-completion completion-basic-all-completions
388 "Completion of the prefix before point and the suffix after point.")
390 completion-pcm-try-completion completion-pcm-all-completions
391 "Completion of multiple words, each one taken as a prefix.
392 E.g. M-x l-c-h can complete to list-command-history
393 and C-x C-f /u/m/s to /usr/monnier/src.")
395 completion-initials-try-completion completion-initials-all-completions
396 "Completion of acronyms and initialisms.
397 E.g. can complete M-x lch to list-command-history
398 and C-x C-f ~/sew to ~/src/emacs/work."))
399 "List of available completion styles.
400 Each element has the form (NAME TRY-COMPLETION ALL-COMPLETIONS DOC):
401 where NAME is the name that should be used in `completion-styles',
402 TRY-COMPLETION is the function that does the completion (it should
403 follow the same calling convention as `completion-try-completion'),
404 ALL-COMPLETIONS is the function that lists the completions (it should
405 follow the calling convention of `completion-all-completions'),
406 and DOC describes the way this style of completion works.")
408 (defcustom completion-styles
'(basic partial-completion emacs22
)
409 "List of completion styles to use.
410 The available styles are listed in `completion-styles-alist'."
411 :type
`(repeat (choice ,@(mapcar (lambda (x) (list 'const
(car x
)))
412 completion-styles-alist
)))
416 (defun completion-try-completion (string table pred point
)
417 "Try to complete STRING using completion table TABLE.
418 Only the elements of table that satisfy predicate PRED are considered.
419 POINT is the position of point within STRING.
420 The return value can be either nil to indicate that there is no completion,
421 t to indicate that STRING is the only possible completion,
422 or a pair (STRING . NEWPOINT) of the completed result string together with
423 a new position for point."
424 (completion--some (lambda (style)
425 (funcall (nth 1 (assq style completion-styles-alist
))
426 string table pred point
))
429 (defun completion-all-completions (string table pred point
)
430 "List the possible completions of STRING in completion table TABLE.
431 Only the elements of table that satisfy predicate PRED are considered.
432 POINT is the position of point within STRING.
433 The return value is a list of completions and may contain the base-size
435 ;; FIXME: We need to additionally return the info needed for the
436 ;; second part of completion-base-position.
437 (completion--some (lambda (style)
438 (funcall (nth 2 (assq style completion-styles-alist
))
439 string table pred point
))
442 (defun minibuffer--bitset (modified completions exact
)
443 (logior (if modified
4 0)
447 (defun completion--do-completion (&optional try-completion-function
)
448 "Do the completion and return a summary of what happened.
449 M = completion was performed, the text was Modified.
450 C = there were available Completions.
451 E = after completion we now have an Exact match.
454 000 0 no possible completion
455 001 1 was already an exact and unique completion
456 010 2 no completion happened
457 011 3 was already an exact completion
460 110 6 some completion happened
461 111 7 completed to an exact completion"
462 (let* ((beg (field-beginning))
464 (string (buffer-substring beg end
))
465 (comp (funcall (or try-completion-function
466 'completion-try-completion
)
468 minibuffer-completion-table
469 minibuffer-completion-predicate
473 (minibuffer-hide-completions)
474 (ding) (minibuffer-message "No match") (minibuffer--bitset nil nil nil
))
476 (minibuffer-hide-completions)
477 (goto-char (field-end))
478 (minibuffer--bitset nil nil t
)) ;Exact and unique match.
480 ;; `completed' should be t if some completion was done, which doesn't
481 ;; include simply changing the case of the entered string. However,
482 ;; for appearance, the string is rewritten if the case changes.
483 (let* ((comp-pos (cdr comp
))
484 (completion (car comp
))
485 (completed (not (eq t
(compare-strings completion nil nil
487 (unchanged (eq t
(compare-strings completion nil nil
488 string nil nil nil
))))
491 ;; Insert in minibuffer the chars we got.
494 (delete-region beg end
))
496 (goto-char (+ beg comp-pos
))
498 (if (not (or unchanged completed
))
499 ;; The case of the string changed, but that's all. We're not sure
500 ;; whether this is a unique completion or not, so try again using
501 ;; the real case (this shouldn't recurse again, because the next
502 ;; time try-completion will return either t or the exact string).
503 (completion--do-completion try-completion-function
)
505 ;; It did find a match. Do we match some possibility exactly now?
506 (let ((exact (test-completion completion
507 minibuffer-completion-table
508 minibuffer-completion-predicate
)))
510 ;; We could also decide to refresh the completions,
511 ;; if they're displayed (and assuming there are
512 ;; completions left).
513 (minibuffer-hide-completions)
514 ;; Show the completion table, if requested.
517 (if (case completion-auto-help
518 (lazy (eq this-command last-command
))
519 (t completion-auto-help
))
520 (minibuffer-completion-help)
521 (minibuffer-message "Next char not unique")))
522 ;; If the last exact completion and this one were the same, it
523 ;; means we've already given a "Next char not unique" message
524 ;; and the user's hit TAB again, so now we give him help.
525 ((eq this-command last-command
)
526 (if completion-auto-help
(minibuffer-completion-help)))))
528 (minibuffer--bitset completed t exact
))))))))
530 (defun minibuffer-complete ()
531 "Complete the minibuffer contents as far as possible.
532 Return nil if there is no valid completion, else t.
533 If no characters can be completed, display a list of possible completions.
534 If you repeat this command after it displayed such a list,
535 scroll the window of possible completions."
537 ;; If the previous command was not this,
538 ;; mark the completion buffer obsolete.
539 (unless (eq this-command last-command
)
540 (setq minibuffer-scroll-window nil
))
542 (let ((window minibuffer-scroll-window
))
543 ;; If there's a fresh completion window with a live buffer,
544 ;; and this command is repeated, scroll that window.
545 (if (window-live-p window
)
546 (with-current-buffer (window-buffer window
)
547 (if (pos-visible-in-window-p (point-max) window
)
548 ;; If end is in view, scroll up to the beginning.
549 (set-window-start window
(point-min) nil
)
550 ;; Else scroll down one screen.
551 (scroll-other-window))
554 (case (completion--do-completion)
556 (#b001
(minibuffer-message "Sole completion")
558 (#b011
(minibuffer-message "Complete, but not unique")
562 (defvar completion-all-sorted-completions nil
)
563 (make-variable-buffer-local 'completion-all-sorted-completions
)
565 (defun completion--flush-all-sorted-completions (&rest ignore
)
566 (setq completion-all-sorted-completions nil
))
568 (defun completion-all-sorted-completions ()
569 (or completion-all-sorted-completions
570 (let* ((start (field-beginning))
572 (all (completion-all-completions (buffer-substring start end
)
573 minibuffer-completion-table
574 minibuffer-completion-predicate
577 (base-size (or (cdr last
) 0)))
580 ;; Prefer shorter completions.
581 (setq all
(sort all
(lambda (c1 c2
) (< (length c1
) (length c2
)))))
582 ;; Prefer recently used completions.
583 (let ((hist (symbol-value minibuffer-history-variable
)))
584 (setq all
(sort all
(lambda (c1 c2
)
585 (> (length (member c1 hist
))
586 (length (member c2 hist
)))))))
587 ;; Cache the result. This is not just for speed, but also so that
588 ;; repeated calls to minibuffer-force-complete can cycle through
589 ;; all possibilities.
590 (add-hook 'after-change-functions
591 'completion--flush-all-sorted-completions nil t
)
592 (setq completion-all-sorted-completions
593 (nconc all base-size
))))))
595 (defun minibuffer-force-complete ()
596 "Complete the minibuffer to an exact match.
597 Repeated uses step through the possible completions."
599 ;; FIXME: Need to deal with the extra-size issue here as well.
600 ;; FIXME: ~/src/emacs/t<M-TAB>/lisp/minibuffer.el completes to
601 ;; ~/src/emacs/trunk/ and throws away lisp/minibuffer.el.
602 (let* ((start (field-beginning))
604 (all (completion-all-sorted-completions)))
605 (if (not (consp all
))
606 (minibuffer-message (if all
"No more completions" "No completions"))
609 (delete-region (+ start
(cdr (last all
))) end
)
610 ;; If completing file names, (car all) may be a directory, so we'd now
611 ;; have a new set of possible completions and might want to reset
612 ;; completion-all-sorted-completions to nil, but we prefer not to,
613 ;; so that repeated calls minibuffer-force-complete still cycle
614 ;; through the previous possible completions.
615 (let ((last (last all
)))
616 (setcdr last
(cons (car all
) (cdr last
)))
617 (setq completion-all-sorted-completions
(cdr all
))))))
619 (defvar minibuffer-confirm-exit-commands
620 '(minibuffer-complete minibuffer-complete-word PC-complete PC-complete-word
)
621 "A list of commands which cause an immediately following
622 `minibuffer-complete-and-exit' to ask for extra confirmation.")
624 (defun minibuffer-complete-and-exit ()
625 "Exit if the minibuffer contains a valid completion.
626 Otherwise, try to complete the minibuffer contents. If
627 completion leads to a valid completion, a repetition of this
630 If `minibuffer-completion-confirm' is `confirm', do not try to
631 complete; instead, ask for confirmation and accept any input if
633 If `minibuffer-completion-confirm' is `confirm-after-completion',
634 do not try to complete; instead, ask for confirmation if the
635 preceding minibuffer command was a member of
636 `minibuffer-confirm-exit-commands', and accept the input
639 (let ((beg (field-beginning))
642 ;; Allow user to specify null string
643 ((= beg end
) (exit-minibuffer))
644 ((test-completion (buffer-substring beg end
)
645 minibuffer-completion-table
646 minibuffer-completion-predicate
)
647 ;; FIXME: completion-ignore-case has various slightly
648 ;; incompatible meanings. E.g. it can reflect whether the user
649 ;; wants completion to pay attention to case, or whether the
650 ;; string will be used in a context where case is significant.
651 ;; E.g. usually try-completion should obey the first, whereas
652 ;; test-completion should obey the second.
653 (when completion-ignore-case
654 ;; Fixup case of the field, if necessary.
655 (let* ((string (buffer-substring beg end
))
656 (compl (try-completion
658 minibuffer-completion-table
659 minibuffer-completion-predicate
)))
660 (when (and (stringp compl
) (not (equal string compl
))
661 ;; If it weren't for this piece of paranoia, I'd replace
662 ;; the whole thing with a call to do-completion.
663 ;; This is important, e.g. when the current minibuffer's
664 ;; content is a directory which only contains a single
665 ;; file, so `try-completion' actually completes to
667 (= (length string
) (length compl
)))
670 (delete-region beg end
))))
673 ((memq minibuffer-completion-confirm
'(confirm confirm-after-completion
))
674 ;; The user is permitted to exit with an input that's rejected
675 ;; by test-completion, after confirming her choice.
676 (if (or (eq last-command this-command
)
677 ;; For `confirm-after-completion' we only ask for confirmation
678 ;; if trying to exit immediately after typing TAB (this
679 ;; catches most minibuffer typos).
680 (and (eq minibuffer-completion-confirm
'confirm-after-completion
)
681 (not (memq last-command minibuffer-confirm-exit-commands
))))
683 (minibuffer-message "Confirm")
687 ;; Call do-completion, but ignore errors.
688 (case (condition-case nil
689 (completion--do-completion)
691 ((#b001
#b011
) (exit-minibuffer))
692 (#b111
(if (not minibuffer-completion-confirm
)
694 (minibuffer-message "Confirm")
698 (defun completion--try-word-completion (string table predicate point
)
699 (let ((comp (completion-try-completion string table predicate point
)))
700 (if (not (consp comp
))
703 ;; If completion finds next char not unique,
704 ;; consider adding a space or a hyphen.
705 (when (= (length string
) (length (car comp
)))
706 ;; Mark the added char with the `completion-word' property, so it
707 ;; can be handled specially by completion styles such as
708 ;; partial-completion.
709 ;; We used to remove `partial-completion' from completion-styles
710 ;; instead, but it was too blunt, leading to situations where SPC
711 ;; was the only insertable char at point but minibuffer-complete-word
712 ;; refused inserting it.
713 (let ((exts (mapcar (lambda (str) (propertize str
'completion-try-word t
))
715 (before (substring string
0 point
))
716 (after (substring string point
))
718 (while (and exts
(not (consp tem
)))
719 (setq tem
(completion-try-completion
720 (concat before
(pop exts
) after
)
721 table predicate
(1+ point
))))
722 (if (consp tem
) (setq comp tem
))))
724 ;; Completing a single word is actually more difficult than completing
725 ;; as much as possible, because we first have to find the "current
726 ;; position" in `completion' in order to find the end of the word
727 ;; we're completing. Normally, `string' is a prefix of `completion',
728 ;; which makes it trivial to find the position, but with fancier
729 ;; completion (plus env-var expansion, ...) `completion' might not
730 ;; look anything like `string' at all.
731 (let* ((comppoint (cdr comp
))
732 (completion (car comp
))
733 (before (substring string
0 point
))
734 (combined (concat before
"\n" completion
)))
735 ;; Find in completion the longest text that was right before point.
736 (when (string-match "\\(.+\\)\n.*?\\1" combined
)
737 (let* ((prefix (match-string 1 before
))
738 ;; We used non-greedy match to make `rem' as long as possible.
739 (rem (substring combined
(match-end 0)))
740 ;; Find in the remainder of completion the longest text
741 ;; that was right after point.
742 (after (substring string point
))
743 (suffix (if (string-match "\\`\\(.+\\).*\n.*\\1"
744 (concat after
"\n" rem
))
745 (match-string 1 after
))))
746 ;; The general idea is to try and guess what text was inserted
747 ;; at point by the completion. Problem is: if we guess wrong,
748 ;; we may end up treating as "added by completion" text that was
749 ;; actually painfully typed by the user. So if we then cut
750 ;; after the first word, we may throw away things the
751 ;; user wrote. So let's try to be as conservative as possible:
752 ;; only cut after the first word, if we're reasonably sure that
753 ;; our guess is correct.
754 ;; Note: a quick survey on emacs-devel seemed to indicate that
755 ;; nobody actually cares about the "word-at-a-time" feature of
756 ;; minibuffer-complete-word, whose real raison-d'être is that it
757 ;; tries to add "-" or " ". One more reason to only cut after
758 ;; the first word, if we're really sure we're right.
759 (when (and (or suffix
(zerop (length after
)))
760 (string-match (concat
761 ;; Make submatch 1 as small as possible
762 ;; to reduce the risk of cutting
764 ".*" (regexp-quote prefix
) "\\(.*?\\)"
765 (if suffix
(regexp-quote suffix
) "\\'"))
767 ;; The new point in `completion' should also be just
768 ;; before the suffix, otherwise something more complex
769 ;; is going on, and we're not sure where we are.
770 (eq (match-end 1) comppoint
)
771 ;; (match-beginning 1)..comppoint is now the stretch
772 ;; of text in `completion' that was completed at point.
773 (string-match "\\W" completion
(match-beginning 1))
774 ;; Is there really something to cut?
775 (> comppoint
(match-end 0)))
776 ;; Cut after the first word.
777 (let ((cutpos (match-end 0)))
778 (setq completion
(concat (substring completion
0 cutpos
)
779 (substring completion comppoint
)))
780 (setq comppoint cutpos
)))))
782 (cons completion comppoint
)))))
785 (defun minibuffer-complete-word ()
786 "Complete the minibuffer contents at most a single word.
787 After one word is completed as much as possible, a space or hyphen
788 is added, provided that matches some possible completion.
789 Return nil if there is no valid completion, else t."
791 (case (completion--do-completion 'completion--try-word-completion
)
793 (#b001
(minibuffer-message "Sole completion")
795 (#b011
(minibuffer-message "Complete, but not unique")
799 (defface completions-annotations
'((t :inherit italic
))
800 "Face to use for annotations in the *Completions* buffer.")
802 (defcustom completions-format nil
803 "Define the appearance and sorting of completions.
804 If the value is `vertical', display completions sorted vertically
805 in columns in the *Completions* buffer.
806 If the value is `horizontal' or nil, display completions sorted
807 horizontally in alphabetical order, rather than down the screen."
808 :type
'(choice (const nil
) (const horizontal
) (const vertical
))
812 (defun completion--insert-strings (strings)
813 "Insert a list of STRINGS into the current buffer.
814 Uses columns to keep the listing readable but compact.
815 It also eliminates runs of equal strings."
816 (when (consp strings
)
817 (let* ((length (apply 'max
820 (+ (string-width (car s
))
821 (string-width (cadr s
)))
824 (window (get-buffer-window (current-buffer) 0))
825 (wwidth (if window
(1- (window-width window
)) 79))
827 ;; At least 2 columns; at least 2 spaces between columns.
828 (max 2 (/ wwidth
(+ 2 length
)))
829 ;; Don't allocate more columns than we can fill.
830 ;; Windows can't show less than 3 lines anyway.
831 (max 1 (/ (length strings
) 2))))
832 (colwidth (/ wwidth columns
))
834 (rows (/ (length strings
) columns
))
837 ;; The insertion should be "sensible" no matter what choices were made
838 ;; for the parameters above.
839 (dolist (str strings
)
840 (unless (equal laststring str
) ; Remove (consecutive) duplicates.
841 (setq laststring str
)
842 (let ((length (if (consp str
)
843 (+ (string-width (car str
))
844 (string-width (cadr str
)))
845 (string-width str
))))
847 ((eq completions-format
'vertical
)
850 (forward-line (- -
1 rows
))
851 (setq row
0 column
(+ column colwidth
)))
854 (while (> (current-column) column
)
860 (set-text-properties (- (point) 1) (point)
861 `(display (space :align-to
,column
)))))
865 (if (< wwidth
(+ (max colwidth length
) column
))
866 ;; No space for `str' at point, move to next line.
867 (progn (insert "\n") (setq column
0))
869 ;; Leave the space unpropertized so that in the case we're
870 ;; already past the goal column, there is still
871 ;; a space displayed.
872 (set-text-properties (- (point) 1) (point)
873 ;; We can't just set tab-width, because
874 ;; completion-setup-function will kill all
875 ;; local variables :-(
876 `(display (space :align-to
,column
)))
878 (if (not (consp str
))
879 (put-text-property (point) (progn (insert str
) (point))
880 'mouse-face
'highlight
)
881 (put-text-property (point) (progn (insert (car str
)) (point))
882 'mouse-face
'highlight
)
883 (add-text-properties (point) (progn (insert (cadr str
)) (point))
885 face completions-annotations
)))
887 ((eq completions-format
'vertical
)
895 ;; Next column to align to.
896 (setq column
(+ column
897 ;; Round up to a whole number of columns.
898 (* colwidth
(ceiling length colwidth
))))))))))))
900 (defvar completion-common-substring nil
)
901 (make-obsolete-variable 'completion-common-substring nil
"23.1")
903 (defvar completion-setup-hook nil
904 "Normal hook run at the end of setting up a completion list buffer.
905 When this hook is run, the current buffer is the one in which the
906 command to display the completion list buffer was run.
907 The completion list buffer is available as the value of `standard-output'.
908 See also `display-completion-list'.")
910 (defface completions-first-difference
911 '((t (:inherit bold
)))
912 "Face put on the first uncommon character in completions in *Completions* buffer."
915 (defface completions-common-part
916 '((t (:inherit default
)))
917 "Face put on the common prefix substring in completions in *Completions* buffer.
918 The idea of `completions-common-part' is that you can use it to
919 make the common parts less visible than normal, so that the rest
920 of the differing parts is, by contrast, slightly highlighted."
923 (defun completion-hilit-commonality (completions prefix-len base-size
)
925 (let ((com-str-len (- prefix-len
(or base-size
0))))
930 ;; Don't modify the string itself, but a copy, since the
931 ;; the string may be read-only or used for other purposes.
932 ;; Furthermore, since `completions' may come from
933 ;; display-completion-list, `elem' may be a list.
935 (car (setq elem
(cons (copy-sequence (car elem
))
937 (setq elem
(copy-sequence elem
)))))
939 ;; If completion-boundaries returns incorrect
940 ;; values, all-completions may return strings
941 ;; that don't contain the prefix.
942 (min com-str-len
(length str
))
943 'font-lock-face
'completions-common-part
945 (if (> (length str
) com-str-len
)
946 (put-text-property com-str-len
(1+ com-str-len
)
947 'font-lock-face
'completions-first-difference
953 (defun display-completion-list (completions &optional common-substring
)
954 "Display the list of completions, COMPLETIONS, using `standard-output'.
955 Each element may be just a symbol or string
956 or may be a list of two strings to be printed as if concatenated.
957 If it is a list of two strings, the first is the actual completion
958 alternative, the second serves as annotation.
959 `standard-output' must be a buffer.
960 The actual completion alternatives, as inserted, are given `mouse-face'
961 properties of `highlight'.
962 At the end, this runs the normal hook `completion-setup-hook'.
963 It can find the completion buffer in `standard-output'.
965 The obsolete optional arg COMMON-SUBSTRING, if non-nil, should be a string
966 specifying a common substring for adding the faces
967 `completions-first-difference' and `completions-common-part' to
968 the completions buffer."
970 (setq completions
(completion-hilit-commonality
971 completions
(length common-substring
)
972 ;; We don't know the base-size.
974 (if (not (bufferp standard-output
))
975 ;; This *never* (ever) happens, so there's no point trying to be clever.
977 (let ((standard-output (current-buffer))
978 (completion-setup-hook nil
))
979 (display-completion-list completions common-substring
))
980 (princ (buffer-string)))
982 (with-current-buffer standard-output
983 (goto-char (point-max))
984 (if (null completions
)
985 (insert "There are no possible completions of what you have typed.")
986 (insert "Possible completions are:\n")
987 (completion--insert-strings completions
))))
989 ;; The hilit used to be applied via completion-setup-hook, so there
990 ;; may still be some code that uses completion-common-substring.
992 (let ((completion-common-substring common-substring
))
993 (run-hooks 'completion-setup-hook
)))
996 (defvar completion-annotate-function
998 ;; Note: there's a lot of scope as for when to add annotations and
999 ;; what annotations to add. E.g. completing-help.el allowed adding
1000 ;; the first line of docstrings to M-x completion. But there's
1001 ;; a tension, since such annotations, while useful at times, can
1002 ;; actually drown the useful information.
1003 ;; So completion-annotate-function should be used parsimoniously, or
1004 ;; else only used upon a user's request (e.g. we could add a command
1005 ;; to completion-list-mode to add annotations to the current
1007 "Function to add annotations in the *Completions* buffer.
1008 The function takes a completion and should either return nil, or a string that
1009 will be displayed next to the completion. The function can access the
1010 completion table and predicates via `minibuffer-completion-table' and related
1013 (defun minibuffer-completion-help ()
1014 "Display a list of possible completions of the current minibuffer contents."
1016 (message "Making completion list...")
1017 (let* ((start (field-beginning))
1018 (string (field-string))
1019 (completions (completion-all-completions
1021 minibuffer-completion-table
1022 minibuffer-completion-predicate
1023 (- (point) (field-beginning)))))
1025 (if (and completions
1026 (or (consp (cdr completions
))
1027 (not (equal (car completions
) string
))))
1028 (let* ((last (last completions
))
1029 (base-size (cdr last
))
1030 ;; If the *Completions* buffer is shown in a new
1031 ;; window, mark it as softly-dedicated, so bury-buffer in
1032 ;; minibuffer-hide-completions will know whether to
1033 ;; delete the window or not.
1034 (display-buffer-mark-dedicated 'soft
))
1035 (with-output-to-temp-buffer "*Completions*"
1036 ;; Remove the base-size tail because `sort' requires a properly
1037 ;; nil-terminated list.
1038 (when last
(setcdr last nil
))
1039 (setq completions
(sort completions
'string-lessp
))
1040 (when completion-annotate-function
1044 (funcall completion-annotate-function s
)))
1045 (if ann
(list s ann
) s
)))
1047 (with-current-buffer standard-output
1048 (set (make-local-variable 'completion-base-position
)
1049 ;; FIXME: We should provide the END part as well, but
1050 ;; currently completion-all-completions does not give
1051 ;; us the necessary information.
1052 (list (+ start base-size
) nil
)))
1053 (display-completion-list completions
)))
1055 ;; If there are no completions, or if the current input is already the
1056 ;; only possible completion, then hide (previous&stale) completions.
1057 (minibuffer-hide-completions)
1060 (if completions
"Sole completion" "No completions")))
1063 (defun minibuffer-hide-completions ()
1064 "Get rid of an out-of-date *Completions* buffer."
1065 ;; FIXME: We could/should use minibuffer-scroll-window here, but it
1066 ;; can also point to the minibuffer-parent-window, so it's a bit tricky.
1067 (let ((win (get-buffer-window "*Completions*" 0)))
1068 (if win
(with-selected-window win
(bury-buffer)))))
1070 (defun exit-minibuffer ()
1071 "Terminate this minibuffer argument."
1073 ;; If the command that uses this has made modifications in the minibuffer,
1074 ;; we don't want them to cause deactivation of the mark in the original
1076 ;; A better solution would be to make deactivate-mark buffer-local
1077 ;; (or to turn it into a list of buffers, ...), but in the mean time,
1078 ;; this should do the trick in most cases.
1079 (setq deactivate-mark nil
)
1082 (defun self-insert-and-exit ()
1083 "Terminate minibuffer input."
1085 (if (characterp last-command-event
)
1086 (call-interactively 'self-insert-command
)
1090 (defvar completion-in-region-functions nil
1091 "Wrapper hook around `complete-in-region'.
1092 The functions on this special hook are called with 5 arguments:
1093 NEXT-FUN START END COLLECTION PREDICATE.
1094 NEXT-FUN is a function of four arguments (START END COLLECTION PREDICATE)
1095 that performs the default operation. The other four argument are like
1096 the ones passed to `complete-in-region'. The functions on this hook
1097 are expected to perform completion on START..END using COLLECTION
1098 and PREDICATE, either by calling NEXT-FUN or by doing it themselves.")
1100 (defun completion-in-region (start end collection
&optional predicate
)
1101 "Complete the text between START and END using COLLECTION.
1102 Return nil if there is no valid completion, else t.
1103 Point needs to be somewhere between START and END."
1104 (assert (<= start
(point)) (<= (point) end
))
1105 ;; FIXME: undisplay the *Completions* buffer once the completion is done.
1107 completion-in-region-functions
(start end collection predicate
)
1108 (let ((minibuffer-completion-table collection
)
1109 (minibuffer-completion-predicate predicate
)
1110 (ol (make-overlay start end nil nil t
)))
1111 (overlay-put ol
'field
'completion
)
1113 (call-interactively 'minibuffer-complete
)
1114 (delete-overlay ol
)))))
1116 (defvar completion-at-point-functions nil
1117 "Special hook to find the completion table for the thing at point.
1118 It is called without any argument and should return either nil,
1119 or a function of no argument to perform completion (discouraged),
1120 or a list of the form (START END COLLECTION &rest PROPS) where
1121 START and END delimit the entity to complete and should include point,
1122 COLLECTION is the completion table to use to complete it, and
1123 PROPS is a property list for additional information.
1124 Currently supported properties are:
1125 `:predicate' a predicate that completion candidates need to satisfy.
1126 `:annotation-function' the value to use for `completion-annotate-function'.")
1128 (defun completion-at-point ()
1129 "Complete the thing at point according to local mode."
1131 (let ((res (run-hook-with-args-until-success
1132 'completion-at-point-functions
)))
1134 ((functionp res
) (funcall res
))
1136 (let* ((plist (nthcdr 3 res
))
1139 (completion-annotate-function
1140 (or (plist-get plist
:annotation-function
)
1141 completion-annotate-function
)))
1142 (completion-in-region start end
(nth 2 res
)
1143 (plist-get plist
:predicate
)))))))
1147 (define-obsolete-variable-alias 'minibuffer-local-must-match-filename-map
1148 'minibuffer-local-filename-must-match-map
"23.1")
1150 (let ((map minibuffer-local-map
))
1151 (define-key map
"\C-g" 'abort-recursive-edit
)
1152 (define-key map
"\r" 'exit-minibuffer
)
1153 (define-key map
"\n" 'exit-minibuffer
))
1155 (let ((map minibuffer-local-completion-map
))
1156 (define-key map
"\t" 'minibuffer-complete
)
1157 ;; M-TAB is already abused for many other purposes, so we should find
1158 ;; another binding for it.
1159 ;; (define-key map "\e\t" 'minibuffer-force-complete)
1160 (define-key map
" " 'minibuffer-complete-word
)
1161 (define-key map
"?" 'minibuffer-completion-help
))
1163 (let ((map minibuffer-local-must-match-map
))
1164 (define-key map
"\r" 'minibuffer-complete-and-exit
)
1165 (define-key map
"\n" 'minibuffer-complete-and-exit
))
1167 (let ((map minibuffer-local-filename-completion-map
))
1168 (define-key map
" " nil
))
1169 (let ((map minibuffer-local-filename-must-match-map
))
1170 (define-key map
" " nil
))
1172 (let ((map minibuffer-local-ns-map
))
1173 (define-key map
" " 'exit-minibuffer
)
1174 (define-key map
"\t" 'exit-minibuffer
)
1175 (define-key map
"?" 'self-insert-and-exit
))
1177 ;;; Completion tables.
1179 (defun minibuffer--double-dollars (str)
1180 (replace-regexp-in-string "\\$" "$$" str
))
1182 (defun completion--make-envvar-table ()
1183 (mapcar (lambda (enventry)
1184 (substring enventry
0 (string-match-p "=" enventry
)))
1185 process-environment
))
1187 (defconst completion--embedded-envvar-re
1188 (concat "\\(?:^\\|[^$]\\(?:\\$\\$\\)*\\)"
1189 "$\\([[:alnum:]_]*\\|{\\([^}]*\\)\\)\\'"))
1191 (defun completion--embedded-envvar-table (string pred action
)
1192 "Completion table for envvars embedded in a string.
1193 The envvar syntax (and escaping) rules followed by this table are the
1194 same as `substitute-in-file-name'."
1195 ;; We ignore `pred', because the predicates passed to us via
1196 ;; read-file-name-internal are not 100% correct and fail here:
1197 ;; e.g. we get predicates like file-directory-p there, whereas the filename
1198 ;; completed needs to be passed through substitute-in-file-name before it
1199 ;; can be passed to file-directory-p.
1200 (when (string-match completion--embedded-envvar-re string
)
1201 (let* ((beg (or (match-beginning 2) (match-beginning 1)))
1202 (table (completion--make-envvar-table))
1203 (prefix (substring string
0 beg
)))
1205 ((eq action
'lambda
)
1206 ;; This table is expected to be used in conjunction with some
1207 ;; other table that provides the "main" completion. Let the
1208 ;; other table handle the test-completion case.
1210 ((eq (car-safe action
) 'boundaries
)
1211 ;; Only return boundaries if there's something to complete,
1212 ;; since otherwise when we're used in
1213 ;; completion-table-in-turn, we could return boundaries and
1214 ;; let some subsequent table return a list of completions.
1215 ;; FIXME: Maybe it should rather be fixed in
1216 ;; completion-table-in-turn instead, but it's difficult to
1217 ;; do it efficiently there.
1218 (when (try-completion (substring string beg
) table nil
)
1219 ;; Compute the boundaries of the subfield to which this
1220 ;; completion applies.
1221 (let ((suffix (cdr action
)))
1223 (or (match-beginning 2) (match-beginning 1))
1224 (when (string-match "[^[:alnum:]_]" suffix
)
1225 (match-beginning 0))))))
1227 (if (eq (aref string
(1- beg
)) ?
{)
1228 (setq table
(apply-partially 'completion-table-with-terminator
1230 ;; Even if file-name completion is case-insensitive, we want
1231 ;; envvar completion to be case-sensitive.
1232 (let ((completion-ignore-case nil
))
1233 (completion-table-with-context
1234 prefix table
(substring string beg
) nil action
)))))))
1236 (defun completion-file-name-table (string pred action
)
1237 "Completion table for file names."
1240 ((eq (car-safe action
) 'boundaries
)
1241 (let ((start (length (file-name-directory string
)))
1242 (end (string-match-p "/" (cdr action
))))
1243 (list* 'boundaries start end
)))
1245 ((eq action
'lambda
)
1246 (if (zerop (length string
))
1247 nil
;Not sure why it's here, but it probably doesn't harm.
1248 (funcall (or pred
'file-exists-p
) string
)))
1251 (let* ((name (file-name-nondirectory string
))
1252 (specdir (file-name-directory string
))
1253 (realdir (or specdir default-directory
)))
1257 (let ((comp (file-name-completion name realdir pred
)))
1259 (concat specdir comp
)
1263 (let ((all (file-name-all-completions name realdir
)))
1265 ;; Check the predicate, if necessary.
1266 (unless (memq pred
'(nil file-exists-p
))
1269 (if (eq pred
'file-directory-p
)
1270 ;; Brute-force speed up for directory checking:
1271 ;; Discard strings which don't end in a slash.
1273 (let ((len (length s
)))
1274 (and (> len
0) (eq (aref s
(1- len
)) ?
/))))
1275 ;; Must do it the hard (and slow) way.
1277 (let ((default-directory (expand-file-name realdir
)))
1279 (if (funcall pred tem
) (push tem comp
))))
1280 (setq all
(nreverse comp
))))
1284 (defvar read-file-name-predicate nil
1285 "Current predicate used by `read-file-name-internal'.")
1286 (make-obsolete-variable 'read-file-name-predicate
1287 "use the regular PRED argument" "23.2")
1289 (defun completion--file-name-table (string pred action
)
1290 "Internal subroutine for `read-file-name'. Do not call this.
1291 This is a completion table for file names, like `completion-file-name-table'
1292 except that it passes the file name through `substitute-in-file-name'."
1294 ((eq (car-safe action
) 'boundaries
)
1295 ;; For the boundaries, we can't really delegate to
1296 ;; completion-file-name-table and then fix them up, because it
1297 ;; would require us to track the relationship between `str' and
1298 ;; `string', which is difficult. And in any case, if
1299 ;; substitute-in-file-name turns "fo-$TO-ba" into "fo-o/b-ba", there's
1300 ;; no way for us to return proper boundaries info, because the
1301 ;; boundary is not (yet) in `string'.
1302 ;; FIXME: Actually there is a way to return correct boundaries info,
1303 ;; at the condition of modifying the all-completions return accordingly.
1304 (let ((start (length (file-name-directory string
)))
1305 (end (string-match-p "/" (cdr action
))))
1306 (list* 'boundaries start end
)))
1309 (let* ((default-directory
1311 ;; It used to be that `pred' was abused to pass `dir'
1313 (prog1 (file-name-as-directory (expand-file-name pred
))
1316 (str (condition-case nil
1317 (substitute-in-file-name string
)
1319 (comp (completion-file-name-table
1320 str
(or pred read-file-name-predicate
) action
)))
1324 ;; Requote the $s before returning the completion.
1325 (minibuffer--double-dollars comp
))
1326 ((and (null action
) comp
1327 ;; Requote the $s before checking for changes.
1328 (setq str
(minibuffer--double-dollars str
))
1329 (not (string-equal string str
)))
1330 ;; If there's no real completion, but substitute-in-file-name
1331 ;; changed the string, then return the new string.
1335 (defalias 'read-file-name-internal
1336 (completion-table-in-turn 'completion--embedded-envvar-table
1337 'completion--file-name-table
)
1338 "Internal subroutine for `read-file-name'. Do not call this.")
1340 (defvar read-file-name-function nil
1341 "If this is non-nil, `read-file-name' does its work by calling this function.")
1343 (defcustom read-file-name-completion-ignore-case
1344 (if (memq system-type
'(ms-dos windows-nt darwin cygwin
))
1346 "Non-nil means when reading a file name completion ignores case."
1351 (defcustom insert-default-directory t
1352 "Non-nil means when reading a filename start with default dir in minibuffer.
1354 When the initial minibuffer contents show a name of a file or a directory,
1355 typing RETURN without editing the initial contents is equivalent to typing
1356 the default file name.
1358 If this variable is non-nil, the minibuffer contents are always
1359 initially non-empty, and typing RETURN without editing will fetch the
1360 default name, if one is provided. Note however that this default name
1361 is not necessarily the same as initial contents inserted in the minibuffer,
1362 if the initial contents is just the default directory.
1364 If this variable is nil, the minibuffer often starts out empty. In
1365 that case you may have to explicitly fetch the next history element to
1366 request the default name; typing RETURN without editing will leave
1367 the minibuffer empty.
1369 For some commands, exiting with an empty minibuffer has a special meaning,
1370 such as making the current buffer visit no file in the case of
1371 `set-visited-file-name'."
1375 ;; Not always defined, but only called if next-read-file-uses-dialog-p says so.
1376 (declare-function x-file-dialog
"xfns.c"
1377 (prompt dir
&optional default-filename mustmatch only-dir-p
))
1379 (defun read-file-name-defaults (&optional dir initial
)
1382 ;; With non-nil `initial', use `dir' as the first default.
1383 ;; Essentially, this mean reversing the normal order of the
1384 ;; current directory name and the current file name, i.e.
1385 ;; 1. with normal file reading:
1386 ;; 1.1. initial input is the current directory
1387 ;; 1.2. the first default is the current file name
1388 ;; 2. with non-nil `initial' (e.g. for `find-alternate-file'):
1389 ;; 2.2. initial input is the current file name
1390 ;; 2.1. the first default is the current directory
1391 (initial (abbreviate-file-name dir
))
1392 ;; In file buffers, try to get the current file name
1394 (abbreviate-file-name buffer-file-name
))))
1396 (run-hook-with-args-until-success 'file-name-at-point-functions
)))
1397 (when file-name-at-point
1398 (setq default
(delete-dups
1399 (delete "" (delq nil
(list file-name-at-point default
))))))
1400 ;; Append new defaults to the end of existing `minibuffer-default'.
1402 (if (listp minibuffer-default
) minibuffer-default
(list minibuffer-default
))
1403 (if (listp default
) default
(list default
)))))
1405 (defun read-file-name (prompt &optional dir default-filename mustmatch initial predicate
)
1406 "Read file name, prompting with PROMPT and completing in directory DIR.
1407 Value is not expanded---you must call `expand-file-name' yourself.
1408 Default name to DEFAULT-FILENAME if user exits the minibuffer with
1409 the same non-empty string that was inserted by this function.
1410 (If DEFAULT-FILENAME is omitted, the visited file name is used,
1411 except that if INITIAL is specified, that combined with DIR is used.
1412 If DEFAULT-FILENAME is a list of file names, the first file name is used.)
1413 If the user exits with an empty minibuffer, this function returns
1414 an empty string. (This can only happen if the user erased the
1415 pre-inserted contents or if `insert-default-directory' is nil.)
1417 Fourth arg MUSTMATCH can take the following values:
1418 - nil means that the user can exit with any input.
1419 - t means that the user is not allowed to exit unless
1420 the input is (or completes to) an existing file.
1421 - `confirm' means that the user can exit with any input, but she needs
1422 to confirm her choice if the input is not an existing file.
1423 - `confirm-after-completion' means that the user can exit with any
1424 input, but she needs to confirm her choice if she called
1425 `minibuffer-complete' right before `minibuffer-complete-and-exit'
1426 and the input is not an existing file.
1427 - anything else behaves like t except that typing RET does not exit if it
1428 does non-null completion.
1430 Fifth arg INITIAL specifies text to start with.
1432 If optional sixth arg PREDICATE is non-nil, possible completions and
1433 the resulting file name must satisfy (funcall PREDICATE NAME).
1434 DIR should be an absolute directory name. It defaults to the value of
1435 `default-directory'.
1437 If this command was invoked with the mouse, use a graphical file
1438 dialog if `use-dialog-box' is non-nil, and the window system or X
1439 toolkit in use provides a file dialog box, and DIR is not a
1440 remote file. For graphical file dialogs, any the special values
1441 of MUSTMATCH; `confirm' and `confirm-after-completion' are
1442 treated as equivalent to nil.
1444 See also `read-file-name-completion-ignore-case'
1445 and `read-file-name-function'."
1446 (unless dir
(setq dir default-directory
))
1447 (unless (file-name-absolute-p dir
) (setq dir
(expand-file-name dir
)))
1448 (unless default-filename
1449 (setq default-filename
(if initial
(expand-file-name initial dir
)
1451 ;; If dir starts with user's homedir, change that to ~.
1452 (setq dir
(abbreviate-file-name dir
))
1453 ;; Likewise for default-filename.
1454 (if default-filename
1455 (setq default-filename
1456 (if (consp default-filename
)
1457 (mapcar 'abbreviate-file-name default-filename
)
1458 (abbreviate-file-name default-filename
))))
1460 ((and insert-default-directory
(stringp dir
))
1462 (cons (minibuffer--double-dollars (concat dir initial
))
1463 (length (minibuffer--double-dollars dir
)))
1464 (minibuffer--double-dollars dir
)))
1465 (initial (cons (minibuffer--double-dollars initial
) 0)))))
1467 (if read-file-name-function
1468 (funcall read-file-name-function
1469 prompt dir default-filename mustmatch initial predicate
)
1470 (let ((completion-ignore-case read-file-name-completion-ignore-case
)
1471 (minibuffer-completing-file-name t
)
1472 (pred (or predicate
'file-exists-p
))
1473 (add-to-history nil
))
1476 (if (or (not (next-read-file-uses-dialog-p))
1477 ;; Graphical file dialogs can't handle remote
1479 (file-remote-p dir
))
1480 ;; We used to pass `dir' to `read-file-name-internal' by
1481 ;; abusing the `predicate' argument. It's better to
1482 ;; just use `default-directory', but in order to avoid
1483 ;; changing `default-directory' in the current buffer,
1484 ;; we don't let-bind it.
1485 (lexical-let ((dir (file-name-as-directory
1486 (expand-file-name dir
))))
1487 (minibuffer-with-setup-hook
1489 (setq default-directory dir
)
1490 ;; When the first default in `minibuffer-default'
1491 ;; duplicates initial input `insdef',
1492 ;; reset `minibuffer-default' to nil.
1493 (when (equal (or (car-safe insdef
) insdef
)
1494 (or (car-safe minibuffer-default
)
1495 minibuffer-default
))
1496 (setq minibuffer-default
1497 (cdr-safe minibuffer-default
)))
1498 ;; On the first request on `M-n' fill
1499 ;; `minibuffer-default' with a list of defaults
1500 ;; relevant for file-name reading.
1501 (set (make-local-variable 'minibuffer-default-add-function
)
1503 (with-current-buffer
1504 (window-buffer (minibuffer-selected-window))
1505 (read-file-name-defaults dir initial
)))))
1506 (completing-read prompt
'read-file-name-internal
1507 pred mustmatch insdef
1508 'file-name-history default-filename
)))
1509 ;; If DEFAULT-FILENAME not supplied and DIR contains
1510 ;; a file name, split it.
1511 (let ((file (file-name-nondirectory dir
))
1512 ;; When using a dialog, revert to nil and non-nil
1513 ;; interpretation of mustmatch. confirm options
1514 ;; need to be interpreted as nil, otherwise
1515 ;; it is impossible to create new files using
1516 ;; dialogs with the default settings.
1518 (not (memq mustmatch
1519 '(nil confirm confirm-after-completion
)))))
1520 (when (and (not default-filename
)
1521 (not (zerop (length file
))))
1522 (setq default-filename file
)
1523 (setq dir
(file-name-directory dir
)))
1524 (when default-filename
1525 (setq default-filename
1526 (expand-file-name (if (consp default-filename
)
1527 (car default-filename
)
1530 (setq add-to-history t
)
1531 (x-file-dialog prompt dir default-filename
1533 (eq predicate
'file-directory-p
)))))
1535 (replace-in-history (eq (car-safe file-name-history
) val
)))
1536 ;; If completing-read returned the inserted default string itself
1537 ;; (rather than a new string with the same contents),
1538 ;; it has to mean that the user typed RET with the minibuffer empty.
1539 ;; In that case, we really want to return ""
1540 ;; so that commands such as set-visited-file-name can distinguish.
1541 (when (consp default-filename
)
1542 (setq default-filename
(car default-filename
)))
1543 (when (eq val default-filename
)
1544 ;; In this case, completing-read has not added an element
1545 ;; to the history. Maybe we should.
1546 (if (not replace-in-history
)
1547 (setq add-to-history t
))
1549 (unless val
(error "No file name specified"))
1551 (if (and default-filename
1552 (string-equal val
(if (consp insdef
) (car insdef
) insdef
)))
1553 (setq val default-filename
))
1554 (setq val
(substitute-in-file-name val
))
1556 (if replace-in-history
1557 ;; Replace what Fcompleting_read added to the history
1558 ;; with what we will actually return. As an exception,
1559 ;; if that's the same as the second item in
1560 ;; file-name-history, it's really a repeat (Bug#4657).
1561 (let ((val1 (minibuffer--double-dollars val
)))
1562 (if history-delete-duplicates
1563 (setcdr file-name-history
1564 (delete val1
(cdr file-name-history
))))
1565 (if (string= val1
(cadr file-name-history
))
1566 (pop file-name-history
)
1567 (setcar file-name-history val1
)))
1569 ;; Add the value to the history--but not if it matches
1570 ;; the last value already there.
1571 (let ((val1 (minibuffer--double-dollars val
)))
1572 (unless (and (consp file-name-history
)
1573 (equal (car file-name-history
) val1
))
1574 (setq file-name-history
1576 (if history-delete-duplicates
1577 (delete val1 file-name-history
)
1578 file-name-history
)))))))
1581 (defun internal-complete-buffer-except (&optional buffer
)
1582 "Perform completion on all buffers excluding BUFFER.
1583 BUFFER nil or omitted means use the current buffer.
1584 Like `internal-complete-buffer', but removes BUFFER from the completion list."
1585 (lexical-let ((except (if (stringp buffer
) buffer
(buffer-name buffer
))))
1586 (apply-partially 'completion-table-with-predicate
1587 'internal-complete-buffer
1589 (not (equal (if (consp name
) (car name
) name
) except
)))
1592 ;;; Old-style completion, used in Emacs-21 and Emacs-22.
1594 (defun completion-emacs21-try-completion (string table pred point
)
1595 (let ((completion (try-completion string table pred
)))
1596 (if (stringp completion
)
1597 (cons completion
(length completion
))
1600 (defun completion-emacs21-all-completions (string table pred point
)
1601 (completion-hilit-commonality
1602 (all-completions string table pred
)
1604 (car (completion-boundaries string table pred
""))))
1606 (defun completion-emacs22-try-completion (string table pred point
)
1607 (let ((suffix (substring string point
))
1608 (completion (try-completion (substring string
0 point
) table pred
)))
1609 (if (not (stringp completion
))
1611 ;; Merge a trailing / in completion with a / after point.
1612 ;; We used to only do it for word completion, but it seems to make
1613 ;; sense for all completions.
1614 ;; Actually, claiming this feature was part of Emacs-22 completion
1615 ;; is pushing it a bit: it was only done in minibuffer-completion-word,
1616 ;; which was (by default) not bound during file completion, where such
1617 ;; slashes are most likely to occur.
1618 (if (and (not (zerop (length completion
)))
1619 (eq ?
/ (aref completion
(1- (length completion
))))
1620 (not (zerop (length suffix
)))
1621 (eq ?
/ (aref suffix
0)))
1622 ;; This leaves point after the / .
1623 (setq suffix
(substring suffix
1)))
1624 (cons (concat completion suffix
) (length completion
)))))
1626 (defun completion-emacs22-all-completions (string table pred point
)
1627 (let ((beforepoint (substring string
0 point
)))
1628 (completion-hilit-commonality
1629 (all-completions beforepoint table pred
)
1631 (car (completion-boundaries beforepoint table pred
"")))))
1633 ;;; Basic completion.
1635 (defun completion--merge-suffix (completion point suffix
)
1636 "Merge end of COMPLETION with beginning of SUFFIX.
1637 Simple generalization of the \"merge trailing /\" done in Emacs-22.
1638 Return the new suffix."
1639 (if (and (not (zerop (length suffix
)))
1640 (string-match "\\(.+\\)\n\\1" (concat completion
"\n" suffix
)
1641 ;; Make sure we don't compress things to less
1642 ;; than we started with.
1644 ;; Just make sure we didn't match some other \n.
1645 (eq (match-end 1) (length completion
)))
1646 (substring suffix
(- (match-end 1) (match-beginning 1)))
1647 ;; Nothing to merge.
1650 (defun completion-basic-try-completion (string table pred point
)
1651 (let* ((beforepoint (substring string
0 point
))
1652 (afterpoint (substring string point
))
1653 (bounds (completion-boundaries beforepoint table pred afterpoint
)))
1654 (if (zerop (cdr bounds
))
1655 ;; `try-completion' may return a subtly different result
1656 ;; than `all+merge', so try to use it whenever possible.
1657 (let ((completion (try-completion beforepoint table pred
)))
1658 (if (not (stringp completion
))
1662 (completion--merge-suffix completion point afterpoint
))
1663 (length completion
))))
1664 (let* ((suffix (substring afterpoint
(cdr bounds
)))
1665 (prefix (substring beforepoint
0 (car bounds
)))
1667 "" (list (substring beforepoint
(car bounds
))
1669 (substring afterpoint
0 (cdr bounds
)))))
1670 (all (completion-pcm--all-completions prefix pattern table pred
)))
1671 (if minibuffer-completing-file-name
1672 (setq all
(completion-pcm--filename-try-filter all
)))
1673 (completion-pcm--merge-try pattern all prefix suffix
)))))
1675 (defun completion-basic-all-completions (string table pred point
)
1676 (let* ((beforepoint (substring string
0 point
))
1677 (afterpoint (substring string point
))
1678 (bounds (completion-boundaries beforepoint table pred afterpoint
))
1679 (suffix (substring afterpoint
(cdr bounds
)))
1680 (prefix (substring beforepoint
0 (car bounds
)))
1682 "" (list (substring beforepoint
(car bounds
))
1684 (substring afterpoint
0 (cdr bounds
)))))
1685 (all (completion-pcm--all-completions prefix pattern table pred
)))
1686 (completion-hilit-commonality all point
(car bounds
))))
1688 ;;; Partial-completion-mode style completion.
1690 (defvar completion-pcm--delim-wild-regex nil
1691 "Regular expression matching delimiters controlling the partial-completion.
1692 Typically, this regular expression simply matches a delimiter, meaning
1693 that completion can add something at (match-beginning 0), but if it has
1694 a submatch 1, then completion can add something at (match-end 1).
1695 This is used when the delimiter needs to be of size zero (e.g. the transition
1696 from lowercase to uppercase characters).")
1698 (defun completion-pcm--prepare-delim-re (delims)
1699 (setq completion-pcm--delim-wild-regex
(concat "[" delims
"*]")))
1701 (defcustom completion-pcm-word-delimiters
"-_./: "
1702 "A string of characters treated as word delimiters for completion.
1704 If `]' is in this string, it must come first.
1705 If `^' is in this string, it must not come first.
1706 If `-' is in this string, it must come first or right after `]'.
1707 In other words, if S is this string, then `[S]' must be a valid Emacs regular
1708 expression (not containing character ranges like `a-z')."
1709 :set
(lambda (symbol value
)
1710 (set-default symbol value
)
1711 ;; Refresh other vars.
1712 (completion-pcm--prepare-delim-re value
))
1713 :initialize
'custom-initialize-reset
1717 (defun completion-pcm--pattern-trivial-p (pattern)
1718 (and (stringp (car pattern
))
1719 ;; It can be followed by `point' and "" and still be trivial.
1721 (dolist (elem (cdr pattern
))
1722 (unless (member elem
'(point ""))
1723 (setq trivial nil
)))
1726 (defun completion-pcm--string->pattern
(string &optional point
)
1727 "Split STRING into a pattern.
1728 A pattern is a list where each element is either a string
1729 or a symbol chosen among `any', `star', `point'."
1730 (if (and point
(< point
(length string
)))
1731 (let ((prefix (substring string
0 point
))
1732 (suffix (substring string point
)))
1733 (append (completion-pcm--string->pattern prefix
)
1735 (completion-pcm--string->pattern suffix
)))
1740 (while (and (setq p
(string-match completion-pcm--delim-wild-regex
1742 ;; If the char was added by minibuffer-complete-word, then
1743 ;; don't treat it as a delimiter, otherwise "M-x SPC"
1744 ;; ends up inserting a "-" rather than listing
1746 (not (get-text-property p
'completion-try-word string
)))
1747 ;; Usually, completion-pcm--delim-wild-regex matches a delimiter,
1748 ;; meaning that something can be added *before* it, but it can also
1749 ;; match a prefix and postfix, in which case something can be added
1750 ;; in-between (e.g. match [[:lower:]][[:upper:]]).
1751 ;; This is determined by the presence of a submatch-1 which delimits
1753 (if (match-end 1) (setq p
(match-end 1)))
1754 (push (substring string p0 p
) pattern
)
1755 (if (eq (aref string p
) ?
*)
1757 (push 'star pattern
)
1763 ;; An empty string might be erroneously added at the beginning.
1764 ;; It should be avoided properly, but it's so easy to remove it here.
1765 (delete "" (nreverse (cons (substring string p0
) pattern
))))))
1767 (defun completion-pcm--pattern->regex
(pattern &optional group
)
1774 (if (if (consp group
) (memq x group
) group
)
1776 (t (regexp-quote x
))))
1779 ;; Avoid pathological backtracking.
1780 (while (string-match "\\.\\*\\?\\(?:\\\\[()]\\)*\\(\\.\\*\\?\\)" re
)
1781 (setq re
(replace-match "" t t re
1)))
1784 (defun completion-pcm--all-completions (prefix pattern table pred
)
1785 "Find all completions for PATTERN in TABLE obeying PRED.
1786 PATTERN is as returned by `completion-pcm--string->pattern'."
1787 ;; (assert (= (car (completion-boundaries prefix table pred ""))
1788 ;; (length prefix)))
1789 ;; Find an initial list of possible completions.
1790 (if (completion-pcm--pattern-trivial-p pattern
)
1792 ;; Minibuffer contains no delimiters -- simple case!
1793 (all-completions (concat prefix
(car pattern
)) table pred
)
1795 ;; Use all-completions to do an initial cull. This is a big win,
1796 ;; since all-completions is written in C!
1797 (let* (;; Convert search pattern to a standard regular expression.
1798 (regex (completion-pcm--pattern->regex pattern
))
1799 (case-fold-search completion-ignore-case
)
1800 (completion-regexp-list (cons regex completion-regexp-list
))
1801 (compl (all-completions
1802 (concat prefix
(if (stringp (car pattern
)) (car pattern
) ""))
1804 (if (not (functionp table
))
1805 ;; The internal functions already obeyed completion-regexp-list.
1809 (when (string-match-p regex c
) (push c poss
)))
1812 (defun completion-pcm--hilit-commonality (pattern completions
)
1814 (let* ((re (completion-pcm--pattern->regex pattern
'(point)))
1815 (case-fold-search completion-ignore-case
))
1816 ;; Remove base-size during mapcar, and add it back later.
1819 ;; Don't modify the string itself.
1820 (setq str
(copy-sequence str
))
1821 (unless (string-match re str
)
1822 (error "Internal error: %s does not match %s" re str
))
1823 (let ((pos (or (match-beginning 1) (match-end 0))))
1824 (put-text-property 0 pos
1825 'font-lock-face
'completions-common-part
1827 (if (> (length str
) pos
)
1828 (put-text-property pos
(1+ pos
)
1829 'font-lock-face
'completions-first-difference
1834 (defun completion-pcm--find-all-completions (string table pred point
1836 "Find all completions for STRING at POINT in TABLE, satisfying PRED.
1837 POINT is a position inside STRING.
1838 FILTER is a function applied to the return value, that can be used, e.g. to
1839 filter out additional entries (because TABLE migth not obey PRED)."
1840 (unless filter
(setq filter
'identity
))
1841 (let* ((beforepoint (substring string
0 point
))
1842 (afterpoint (substring string point
))
1843 (bounds (completion-boundaries beforepoint table pred afterpoint
))
1844 (prefix (substring beforepoint
0 (car bounds
)))
1845 (suffix (substring afterpoint
(cdr bounds
)))
1847 (setq string
(substring string
(car bounds
) (+ point
(cdr bounds
))))
1848 (let* ((relpoint (- point
(car bounds
)))
1849 (pattern (completion-pcm--string->pattern string relpoint
))
1850 (all (condition-case err
1852 (completion-pcm--all-completions
1853 prefix pattern table pred
))
1854 (error (unless firsterror
(setq firsterror err
)) nil
))))
1855 (when (and (null all
)
1857 (null (ignore-errors (try-completion prefix table pred
))))
1858 ;; The prefix has no completions at all, so we should try and fix
1860 (let ((substring (substring prefix
0 -
1)))
1861 (destructuring-bind (subpat suball subprefix subsuffix
)
1862 (completion-pcm--find-all-completions
1863 substring table pred
(length substring
) filter
)
1864 (let ((sep (aref prefix
(1- (length prefix
))))
1865 ;; Text that goes between the new submatches and the
1866 ;; completion substring.
1868 ;; Eliminate submatches that don't end with the separator.
1869 (dolist (submatch (prog1 suball
(setq suball
())))
1870 (when (eq sep
(aref submatch
(1- (length submatch
))))
1871 (push submatch suball
)))
1873 ;; Update the boundaries and corresponding pattern.
1874 ;; We assume that all submatches result in the same boundaries
1875 ;; since we wouldn't know how to merge them otherwise anyway.
1876 ;; FIXME: COMPLETE REWRITE!!!
1877 (let* ((newbeforepoint
1878 (concat subprefix
(car suball
)
1879 (substring string
0 relpoint
)))
1880 (leftbound (+ (length subprefix
) (length (car suball
))))
1881 (newbounds (completion-boundaries
1882 newbeforepoint table pred afterpoint
)))
1883 (unless (or (and (eq (cdr bounds
) (cdr newbounds
))
1884 (eq (car newbounds
) leftbound
))
1885 ;; Refuse new boundaries if they step over
1887 (< (car newbounds
) leftbound
))
1888 ;; The new completed prefix does change the boundaries
1889 ;; of the completed substring.
1890 (setq suffix
(substring afterpoint
(cdr newbounds
)))
1892 (concat (substring newbeforepoint
(car newbounds
))
1893 (substring afterpoint
0 (cdr newbounds
))))
1894 (setq between
(substring newbeforepoint leftbound
1896 (setq pattern
(completion-pcm--string->pattern
1898 (- (length newbeforepoint
)
1900 (dolist (submatch suball
)
1901 (setq all
(nconc (mapcar
1902 (lambda (s) (concat submatch between s
))
1904 (completion-pcm--all-completions
1905 (concat subprefix submatch between
)
1906 pattern table pred
)))
1908 ;; FIXME: This can come in handy for try-completion,
1909 ;; but isn't right for all-completions, since it lists
1910 ;; invalid completions.
1912 ;; ;; Even though we found expansions in the prefix, none
1913 ;; ;; leads to a valid completion.
1914 ;; ;; Let's keep the expansions, tho.
1915 ;; (dolist (submatch suball)
1916 ;; (push (concat submatch between newsubstring) all)))
1918 (setq pattern
(append subpat
(list 'any
(string sep
))
1919 (if between
(list between
)) pattern
))
1920 (setq prefix subprefix
)))))
1921 (if (and (null all
) firsterror
)
1922 (signal (car firsterror
) (cdr firsterror
))
1923 (list pattern all prefix suffix
)))))
1925 (defun completion-pcm-all-completions (string table pred point
)
1926 (destructuring-bind (pattern all
&optional prefix suffix
)
1927 (completion-pcm--find-all-completions string table pred point
)
1929 (nconc (completion-pcm--hilit-commonality pattern all
)
1932 (defun completion-pcm--merge-completions (strs pattern
)
1933 "Extract the commonality in STRS, with the help of PATTERN."
1934 ;; When completing while ignoring case, we want to try and avoid
1935 ;; completing "fo" to "foO" when completing against "FOO" (bug#4219).
1936 ;; So we try and make sure that the string we return is all made up
1937 ;; of text from the completions rather than part from the
1938 ;; completions and part from the input.
1939 ;; FIXME: This reduces the problems of inconsistent capitalization
1940 ;; but it doesn't fully fix it: we may still end up completing
1941 ;; "fo-ba" to "foo-BAR" or "FOO-bar" when completing against
1942 ;; '("foo-barr" "FOO-BARD").
1944 ((null (cdr strs
)) (list (car strs
)))
1946 (let ((re (completion-pcm--pattern->regex pattern
'group
))
1947 (ccs ())) ;Chopped completions.
1949 ;; First chop each string into the parts corresponding to each
1950 ;; non-constant element of `pattern', using regexp-matching.
1951 (let ((case-fold-search completion-ignore-case
))
1953 (unless (string-match re str
)
1954 (error "Internal error: %s doesn't match %s" str re
))
1959 (while (setq next
(match-end i
))
1960 (push (substring str last next
) chopped
)
1963 ;; Add the text corresponding to the implicit trailing `any'.
1964 (push (substring str last
) chopped
)
1965 (push (nreverse chopped
) ccs
))))
1967 ;; Then for each of those non-constant elements, extract the
1968 ;; commonality between them.
1971 ;; Make the implicit trailing `any' explicit.
1972 (dolist (elem (append pattern
'(any)))
1974 (setq fixed
(concat fixed elem
))
1976 (dolist (cc (prog1 ccs
(setq ccs nil
)))
1977 (push (car cc
) comps
)
1978 (push (cdr cc
) ccs
))
1979 ;; Might improve the likelihood to avoid choosing
1980 ;; different capitalizations in different parts.
1981 ;; In practice, it doesn't seem to make any difference.
1982 (setq ccs
(nreverse ccs
))
1983 (let* ((prefix (try-completion fixed comps
))
1984 (unique (or (and (eq prefix t
) (setq prefix fixed
))
1985 (eq t
(try-completion prefix comps
)))))
1986 (unless (equal prefix
"") (push prefix res
))
1987 ;; If there's only one completion, `elem' is not useful
1988 ;; any more: it can only match the empty string.
1989 ;; FIXME: in some cases, it may be necessary to turn an
1990 ;; `any' into a `star' because the surrounding context has
1991 ;; changed such that string->pattern wouldn't add an `any'
1993 (unless unique
(push elem res
))
1995 ;; We return it in reverse order.
1998 (defun completion-pcm--pattern->string
(pattern)
1999 (mapconcat (lambda (x) (cond
2003 ((eq x
'point
) "")))
2007 ;; We want to provide the functionality of `try', but we use `all'
2008 ;; and then merge it. In most cases, this works perfectly, but
2009 ;; if the completion table doesn't consider the same completions in
2010 ;; `try' as in `all', then we have a problem. The most common such
2011 ;; case is for filename completion where completion-ignored-extensions
2012 ;; is only obeyed by the `try' code. We paper over the difference
2013 ;; here. Note that it is not quite right either: if the completion
2014 ;; table uses completion-table-in-turn, this filtering may take place
2015 ;; too late to correctly fallback from the first to the
2016 ;; second alternative.
2017 (defun completion-pcm--filename-try-filter (all)
2018 "Filter to adjust `all' file completion to the behavior of `try'."
2021 (re (concat "\\(?:\\`\\.\\.?/\\|"
2022 (regexp-opt completion-ignored-extensions
)
2025 (unless (string-match-p re f
) (push f try
)))
2029 (defun completion-pcm--merge-try (pattern all prefix suffix
)
2031 ((not (consp all
)) all
)
2032 ((and (not (consp (cdr all
))) ;Only one completion.
2033 ;; Ignore completion-ignore-case here.
2034 (equal (completion-pcm--pattern->string pattern
) (car all
)))
2037 (let* ((mergedpat (completion-pcm--merge-completions all pattern
))
2038 ;; `mergedpat' is in reverse order. Place new point (by
2039 ;; order of preference) either at the old point, or at
2040 ;; the last place where there's something to choose, or
2042 (pointpat (or (memq 'point mergedpat
)
2043 (memq 'any mergedpat
)
2044 (memq 'star mergedpat
)
2046 ;; New pos from the start.
2047 (newpos (length (completion-pcm--pattern->string pointpat
)))
2048 ;; Do it afterwards because it changes `pointpat' by sideeffect.
2049 (merged (completion-pcm--pattern->string
(nreverse mergedpat
))))
2051 (setq suffix
(completion--merge-suffix merged newpos suffix
))
2052 (cons (concat prefix merged suffix
) (+ newpos
(length prefix
)))))))
2054 (defun completion-pcm-try-completion (string table pred point
)
2055 (destructuring-bind (pattern all prefix suffix
)
2056 (completion-pcm--find-all-completions
2057 string table pred point
2058 (if minibuffer-completing-file-name
2059 'completion-pcm--filename-try-filter
))
2060 (completion-pcm--merge-try pattern all prefix suffix
)))
2062 ;;; Initials completion
2063 ;; Complete /ums to /usr/monnier/src or lch to list-command-history.
2065 (defun completion-initials-expand (str table pred
)
2066 (let ((bounds (completion-boundaries str table pred
"")))
2067 (unless (or (zerop (length str
))
2068 ;; Only check within the boundaries, since the
2069 ;; boundary char (e.g. /) might be in delim-regexp.
2070 (string-match completion-pcm--delim-wild-regex str
2072 (if (zerop (car bounds
))
2073 (mapconcat 'string str
"-")
2074 ;; If there's a boundary, it's trickier. The main use-case
2075 ;; we consider here is file-name completion. We'd like
2076 ;; to expand ~/eee to ~/e/e/e and /eee to /e/e/e.
2077 ;; But at the same time, we don't want /usr/share/ae to expand
2078 ;; to /usr/share/a/e just because we mistyped "ae" for "ar",
2079 ;; so we probably don't want initials to touch anything that
2080 ;; looks like /usr/share/foo. As a heuristic, we just check that
2081 ;; the text before the boundary char is at most 1 char.
2082 ;; This allows both ~/eee and /eee and not much more.
2083 ;; FIXME: It sadly also disallows the use of ~/eee when that's
2084 ;; embedded within something else (e.g. "(~/eee" in Info node
2085 ;; completion or "ancestor:/eee" in bzr-revision completion).
2086 (when (< (car bounds
) 3)
2087 (let ((sep (substring str
(1- (car bounds
)) (car bounds
))))
2088 ;; FIXME: the above string-match checks the whole string, whereas
2089 ;; we end up only caring about the after-boundary part.
2090 (concat (substring str
0 (car bounds
))
2091 (mapconcat 'string
(substring str
(car bounds
)) sep
))))))))
2093 (defun completion-initials-all-completions (string table pred point
)
2094 (let ((newstr (completion-initials-expand string table pred
)))
2096 (completion-pcm-all-completions newstr table pred
(length newstr
)))))
2098 (defun completion-initials-try-completion (string table pred point
)
2099 (let ((newstr (completion-initials-expand string table pred
)))
2101 (completion-pcm-try-completion newstr table pred
(length newstr
)))))
2106 (defun minibuffer-insert-file-name-at-point ()
2107 "Get a file name at point in original buffer and insert it to minibuffer."
2109 (let ((file-name-at-point
2110 (with-current-buffer (window-buffer (minibuffer-selected-window))
2111 (run-hook-with-args-until-success 'file-name-at-point-functions
))))
2112 (when file-name-at-point
2113 (insert file-name-at-point
))))
2115 (provide 'minibuffer
)
2117 ;; arch-tag: ef8a0a15-1080-4790-a754-04017c02f08f
2118 ;;; minibuffer.el ends here