* lisp/vc/vc.el (vc-diff-build-argument-list-internal)
[emacs.git] / lisp / minibuffer.el
blob0d26d6bdcf6f643eb0969c40853852e7dd26738a
1 ;;; minibuffer.el --- Minibuffer completion functions -*- lexical-binding: t -*-
3 ;; Copyright (C) 2008-2011 Free Software Foundation, Inc.
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6 ;; Package: emacs
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; Names with "--" are for functions and variables that are meant to be for
26 ;; internal use only.
28 ;; Functional completion tables have an extended calling conventions:
29 ;; - The `action' can be (additionally to nil, t, and lambda) of the form
30 ;; (boundaries . SUFFIX) in which case it should return
31 ;; (boundaries START . END). See `completion-boundaries'.
32 ;; Any other return value should be ignored (so we ignore values returned
33 ;; from completion tables that don't know about this new `action' form).
35 ;;; Bugs:
37 ;; - completion-all-sorted-completions list all the completions, whereas
38 ;; it should only lists the ones that `try-completion' would consider.
39 ;; E.g. it should honor completion-ignored-extensions.
40 ;; - choose-completion can't automatically figure out the boundaries
41 ;; corresponding to the displayed completions because we only
42 ;; provide the start info but not the end info in
43 ;; completion-base-position.
44 ;; - quoting is problematic. E.g. the double-dollar quoting used in
45 ;; substitute-in-file-name (and hence read-file-name-internal) bumps
46 ;; into various bugs:
47 ;; - choose-completion doesn't know how to quote the text it inserts.
48 ;; E.g. it fails to double the dollars in file-name completion, or
49 ;; to backslash-escape spaces and other chars in comint completion.
50 ;; - when completing ~/tmp/fo$$o, the highligting in *Completions*
51 ;; is off by one position.
52 ;; - all code like PCM which relies on all-completions to match
53 ;; its argument gets confused because all-completions returns unquoted
54 ;; texts (as desired for *Completions* output).
55 ;; - C-x C-f ~/*/sr ? should not list "~/./src".
56 ;; - minibuffer-force-complete completes ~/src/emacs/t<!>/lisp/minibuffer.el
57 ;; to ~/src/emacs/trunk/ and throws away lisp/minibuffer.el.
59 ;;; Todo:
61 ;; - completion-insert-complete-hook (called after inserting a complete
62 ;; completion), typically used for "complete-abbrev" where it would expand
63 ;; the abbrev. Tho we'd probably want to provide it from the
64 ;; completion-table.
65 ;; - extend `boundaries' to provide various other meta-data about the
66 ;; output of `all-completions':
67 ;; - preferred sorting order when displayed in *Completions*.
68 ;; - annotations/text-properties to add when displayed in *Completions*.
69 ;; - quoting/unquoting (so we can complete files names with envvars
70 ;; and backslashes, and all-completion can list names without
71 ;; quoting backslashes and dollars).
72 ;; - indicate how to turn all-completion's output into
73 ;; try-completion's output: e.g. completion-ignored-extensions.
74 ;; maybe that could be merged with the "quote" operation above.
75 ;; - completion hook to run when the completion is
76 ;; selected/inserted (maybe this should be provided some other
77 ;; way, e.g. as text-property, so `try-completion can also return it?)
78 ;; both for when it's inserted via TAB or via choose-completion.
79 ;; - indicate that `all-completions' doesn't do prefix-completion
80 ;; but just returns some list that relates in some other way to
81 ;; the provided string (as is the case in filecache.el), in which
82 ;; case partial-completion (for example) doesn't make any sense
83 ;; and neither does the completions-first-difference highlight.
84 ;; - indicate how to display the completions in *Completions* (turn
85 ;; \n into something else, add special boundaries between
86 ;; completions). E.g. when completing from the kill-ring.
88 ;; - make partial-completion-mode obsolete:
89 ;; - (?) <foo.h> style completion for file names.
90 ;; This can't be done identically just by tweaking completion,
91 ;; because partial-completion-mode's behavior is to expand <string.h>
92 ;; to /usr/include/string.h only when exiting the minibuffer, at which
93 ;; point the completion code is actually not involved normally.
94 ;; Partial-completion-mode does it via a find-file-not-found-function.
95 ;; - special code for C-x C-f <> to visit the file ref'd at point
96 ;; via (require 'foo) or #include "foo". ffap seems like a better
97 ;; place for this feature (supplemented with major-mode-provided
98 ;; functions to find the file ref'd at point).
100 ;; - case-sensitivity currently confuses two issues:
101 ;; - whether or not a particular completion table should be case-sensitive
102 ;; (i.e. whether strings that differ only by case are semantically
103 ;; equivalent)
104 ;; - whether the user wants completion to pay attention to case.
105 ;; e.g. we may want to make it possible for the user to say "first try
106 ;; completion case-sensitively, and if that fails, try to ignore case".
108 ;; - add support for ** to pcm.
109 ;; - Add vc-file-name-completion-table to read-file-name-internal.
110 ;; - A feature like completing-help.el.
112 ;;; Code:
114 (eval-when-compile (require 'cl))
116 ;;; Completion table manipulation
118 ;; New completion-table operation.
119 (defun completion-boundaries (string table pred suffix)
120 "Return the boundaries of the completions returned by TABLE for STRING.
121 STRING is the string on which completion will be performed.
122 SUFFIX is the string after point.
123 The result is of the form (START . END) where START is the position
124 in STRING of the beginning of the completion field and END is the position
125 in SUFFIX of the end of the completion field.
126 E.g. for simple completion tables, the result is always (0 . (length SUFFIX))
127 and for file names the result is the positions delimited by
128 the closest directory separators."
129 (let ((boundaries (if (functionp table)
130 (funcall table string pred (cons 'boundaries suffix)))))
131 (if (not (eq (car-safe boundaries) 'boundaries))
132 (setq boundaries nil))
133 (cons (or (cadr boundaries) 0)
134 (or (cddr boundaries) (length suffix)))))
136 (defun completion--some (fun xs)
137 "Apply FUN to each element of XS in turn.
138 Return the first non-nil returned value.
139 Like CL's `some'."
140 (let ((firsterror nil)
141 res)
142 (while (and (not res) xs)
143 (condition-case err
144 (setq res (funcall fun (pop xs)))
145 (error (unless firsterror (setq firsterror err)) nil)))
146 (or res
147 (if firsterror (signal (car firsterror) (cdr firsterror))))))
149 (defun complete-with-action (action table string pred)
150 "Perform completion ACTION.
151 STRING is the string to complete.
152 TABLE is the completion table, which should not be a function.
153 PRED is a completion predicate.
154 ACTION can be one of nil, t or `lambda'."
155 (cond
156 ((functionp table) (funcall table string pred action))
157 ((eq (car-safe action) 'boundaries)
158 (cons 'boundaries (completion-boundaries string table pred (cdr action))))
160 (funcall
161 (cond
162 ((null action) 'try-completion)
163 ((eq action t) 'all-completions)
164 (t 'test-completion))
165 string table pred))))
167 (defun completion-table-dynamic (fun)
168 "Use function FUN as a dynamic completion table.
169 FUN is called with one argument, the string for which completion is required,
170 and it should return an alist containing all the intended possible completions.
171 This alist may be a full list of possible completions so that FUN can ignore
172 the value of its argument. If completion is performed in the minibuffer,
173 FUN will be called in the buffer from which the minibuffer was entered.
175 The result of the `completion-table-dynamic' form is a function
176 that can be used as the COLLECTION argument to `try-completion' and
177 `all-completions'. See Info node `(elisp)Programmed Completion'."
178 (lambda (string pred action)
179 (if (eq (car-safe action) 'boundaries)
180 ;; `fun' is not supposed to return another function but a plain old
181 ;; completion table, whose boundaries are always trivial.
183 (with-current-buffer (let ((win (minibuffer-selected-window)))
184 (if (window-live-p win) (window-buffer win)
185 (current-buffer)))
186 (complete-with-action action (funcall fun string) string pred)))))
188 (defmacro lazy-completion-table (var fun)
189 "Initialize variable VAR as a lazy completion table.
190 If the completion table VAR is used for the first time (e.g., by passing VAR
191 as an argument to `try-completion'), the function FUN is called with no
192 arguments. FUN must return the completion table that will be stored in VAR.
193 If completion is requested in the minibuffer, FUN will be called in the buffer
194 from which the minibuffer was entered. The return value of
195 `lazy-completion-table' must be used to initialize the value of VAR.
197 You should give VAR a non-nil `risky-local-variable' property."
198 (declare (debug (symbolp lambda-expr)))
199 (let ((str (make-symbol "string")))
200 `(completion-table-dynamic
201 (lambda (,str)
202 (when (functionp ,var)
203 (setq ,var (,fun)))
204 ,var))))
206 (defun completion-table-case-fold (table string pred action)
207 (let ((completion-ignore-case t))
208 (complete-with-action action table string pred)))
210 (defun completion-table-with-context (prefix table string pred action)
211 ;; TODO: add `suffix' maybe?
212 ;; Notice that `pred' may not be a function in some abusive cases.
213 (when (functionp pred)
214 (setq pred
215 ;; Predicates are called differently depending on the nature of
216 ;; the completion table :-(
217 (cond
218 ((vectorp table) ;Obarray.
219 (lambda (sym) (funcall pred (concat prefix (symbol-name sym)))))
220 ((hash-table-p table)
221 (lambda (s _v) (funcall pred (concat prefix s))))
222 ((functionp table)
223 (lambda (s) (funcall pred (concat prefix s))))
224 (t ;Lists and alists.
225 (lambda (s)
226 (funcall pred (concat prefix (if (consp s) (car s) s))))))))
227 (if (eq (car-safe action) 'boundaries)
228 (let* ((len (length prefix))
229 (bound (completion-boundaries string table pred (cdr action))))
230 (list* 'boundaries (+ (car bound) len) (cdr bound)))
231 (let ((comp (complete-with-action action table string pred)))
232 (cond
233 ;; In case of try-completion, add the prefix.
234 ((stringp comp) (concat prefix comp))
235 (t comp)))))
237 (defun completion-table-with-terminator (terminator table string pred action)
238 "Construct a completion table like TABLE but with an extra TERMINATOR.
239 This is meant to be called in a curried way by first passing TERMINATOR
240 and TABLE only (via `apply-partially').
241 TABLE is a completion table, and TERMINATOR is a string appended to TABLE's
242 completion if it is complete. TERMINATOR is also used to determine the
243 completion suffix's boundary.
244 TERMINATOR can also be a cons cell (TERMINATOR . TERMINATOR-REGEXP)
245 in which case TERMINATOR-REGEXP is a regular expression whose submatch
246 number 1 should match TERMINATOR. This is used when there is a need to
247 distinguish occurrences of the TERMINATOR strings which are really terminators
248 from others (e.g. escaped)."
249 ;; FIXME: This implementation is not right since it only adds the terminator
250 ;; in try-completion, so any completion-style that builds the completion via
251 ;; all-completions won't get the terminator, and selecting an entry in
252 ;; *Completions* won't get the terminator added either.
253 (cond
254 ((eq (car-safe action) 'boundaries)
255 (let* ((suffix (cdr action))
256 (bounds (completion-boundaries string table pred suffix))
257 (terminator-regexp (if (consp terminator)
258 (cdr terminator) (regexp-quote terminator)))
259 (max (string-match terminator-regexp suffix)))
260 (list* 'boundaries (car bounds)
261 (min (cdr bounds) (or max (length suffix))))))
262 ((eq action nil)
263 (let ((comp (try-completion string table pred)))
264 (if (consp terminator) (setq terminator (car terminator)))
265 (if (eq comp t)
266 (concat string terminator)
267 (if (and (stringp comp)
268 ;; FIXME: Try to avoid this second call, especially since
269 ;; it may be very inefficient (because `comp' made us
270 ;; jump to a new boundary, so we complete in that
271 ;; boundary with an empty start string).
272 ;; completion-boundaries might help.
273 (eq (try-completion comp table pred) t))
274 (concat comp terminator)
275 comp))))
276 ((eq action t)
277 ;; FIXME: We generally want the `try' and `all' behaviors to be
278 ;; consistent so pcm can merge the `all' output to get the `try' output,
279 ;; but that sometimes clashes with the need for `all' output to look
280 ;; good in *Completions*.
281 ;; (mapcar (lambda (s) (concat s terminator))
282 ;; (all-completions string table pred))))
283 (all-completions string table pred))
284 ;; completion-table-with-terminator is always used for
285 ;; "sub-completions" so it's only called if the terminator is missing,
286 ;; in which case `test-completion' should return nil.
287 ((eq action 'lambda) nil)))
289 (defun completion-table-with-predicate (table pred1 strict string pred2 action)
290 "Make a completion table equivalent to TABLE but filtered through PRED1.
291 PRED1 is a function of one argument which returns non-nil if and only if the
292 argument is an element of TABLE which should be considered for completion.
293 STRING, PRED2, and ACTION are the usual arguments to completion tables,
294 as described in `try-completion', `all-completions', and `test-completion'.
295 If STRICT is t, the predicate always applies; if nil it only applies if
296 it does not reduce the set of possible completions to nothing.
297 Note: TABLE needs to be a proper completion table which obeys predicates."
298 (cond
299 ((and (not strict) (eq action 'lambda))
300 ;; Ignore pred1 since it doesn't really have to apply anyway.
301 (test-completion string table pred2))
303 (or (complete-with-action action table string
304 (if (null pred2) pred1
305 (lambda (x)
306 ;; Call `pred1' first, so that `pred2'
307 ;; really can't tell that `x' is in table.
308 (if (funcall pred1 x) (funcall pred2 x)))))
309 ;; If completion failed and we're not applying pred1 strictly, try
310 ;; again without pred1.
311 (and (not strict)
312 (complete-with-action action table string pred2))))))
314 (defun completion-table-in-turn (&rest tables)
315 "Create a completion table that tries each table in TABLES in turn."
316 ;; FIXME: the boundaries may come from TABLE1 even when the completion list
317 ;; is returned by TABLE2 (because TABLE1 returned an empty list).
318 (lambda (string pred action)
319 (completion--some (lambda (table)
320 (complete-with-action action table string pred))
321 tables)))
323 ;; (defmacro complete-in-turn (a b) `(completion-table-in-turn ,a ,b))
324 ;; (defmacro dynamic-completion-table (fun) `(completion-table-dynamic ,fun))
325 (define-obsolete-function-alias
326 'complete-in-turn 'completion-table-in-turn "23.1")
327 (define-obsolete-function-alias
328 'dynamic-completion-table 'completion-table-dynamic "23.1")
330 ;;; Minibuffer completion
332 (defgroup minibuffer nil
333 "Controlling the behavior of the minibuffer."
334 :link '(custom-manual "(emacs)Minibuffer")
335 :group 'environment)
337 (defun minibuffer-message (message &rest args)
338 "Temporarily display MESSAGE at the end of the minibuffer.
339 The text is displayed for `minibuffer-message-timeout' seconds,
340 or until the next input event arrives, whichever comes first.
341 Enclose MESSAGE in [...] if this is not yet the case.
342 If ARGS are provided, then pass MESSAGE through `format'."
343 (if (not (minibufferp (current-buffer)))
344 (progn
345 (if args
346 (apply 'message message args)
347 (message "%s" message))
348 (prog1 (sit-for (or minibuffer-message-timeout 1000000))
349 (message nil)))
350 ;; Clear out any old echo-area message to make way for our new thing.
351 (message nil)
352 (setq message (if (and (null args) (string-match-p "\\` *\\[.+\\]\\'" message))
353 ;; Make sure we can put-text-property.
354 (copy-sequence message)
355 (concat " [" message "]")))
356 (when args (setq message (apply 'format message args)))
357 (let ((ol (make-overlay (point-max) (point-max) nil t t))
358 ;; A quit during sit-for normally only interrupts the sit-for,
359 ;; but since minibuffer-message is used at the end of a command,
360 ;; at a time when the command has virtually finished already, a C-g
361 ;; should really cause an abort-recursive-edit instead (i.e. as if
362 ;; the C-g had been typed at top-level). Binding inhibit-quit here
363 ;; is an attempt to get that behavior.
364 (inhibit-quit t))
365 (unwind-protect
366 (progn
367 (unless (zerop (length message))
368 ;; The current C cursor code doesn't know to use the overlay's
369 ;; marker's stickiness to figure out whether to place the cursor
370 ;; before or after the string, so let's spoon-feed it the pos.
371 (put-text-property 0 1 'cursor t message))
372 (overlay-put ol 'after-string message)
373 (sit-for (or minibuffer-message-timeout 1000000)))
374 (delete-overlay ol)))))
376 (defun minibuffer-completion-contents ()
377 "Return the user input in a minibuffer before point as a string.
378 That is what completion commands operate on."
379 (buffer-substring (field-beginning) (point)))
381 (defun delete-minibuffer-contents ()
382 "Delete all user input in a minibuffer.
383 If the current buffer is not a minibuffer, erase its entire contents."
384 ;; We used to do `delete-field' here, but when file name shadowing
385 ;; is on, the field doesn't cover the entire minibuffer contents.
386 (delete-region (minibuffer-prompt-end) (point-max)))
388 (defvar completion-show-inline-help t
389 "If non-nil, print helpful inline messages during completion.")
391 (defcustom completion-auto-help t
392 "Non-nil means automatically provide help for invalid completion input.
393 If the value is t the *Completion* buffer is displayed whenever completion
394 is requested but cannot be done.
395 If the value is `lazy', the *Completions* buffer is only displayed after
396 the second failed attempt to complete."
397 :type '(choice (const nil) (const t) (const lazy))
398 :group 'minibuffer)
400 (defconst completion-styles-alist
401 '((emacs21
402 completion-emacs21-try-completion completion-emacs21-all-completions
403 "Simple prefix-based completion.
404 I.e. when completing \"foo_bar\" (where _ is the position of point),
405 it will consider all completions candidates matching the glob
406 pattern \"foobar*\".")
407 (emacs22
408 completion-emacs22-try-completion completion-emacs22-all-completions
409 "Prefix completion that only operates on the text before point.
410 I.e. when completing \"foo_bar\" (where _ is the position of point),
411 it will consider all completions candidates matching the glob
412 pattern \"foo*\" and will add back \"bar\" to the end of it.")
413 (basic
414 completion-basic-try-completion completion-basic-all-completions
415 "Completion of the prefix before point and the suffix after point.
416 I.e. when completing \"foo_bar\" (where _ is the position of point),
417 it will consider all completions candidates matching the glob
418 pattern \"foo*bar*\".")
419 (partial-completion
420 completion-pcm-try-completion completion-pcm-all-completions
421 "Completion of multiple words, each one taken as a prefix.
422 I.e. when completing \"l-co_h\" (where _ is the position of point),
423 it will consider all completions candidates matching the glob
424 pattern \"l*-co*h*\".
425 Furthermore, for completions that are done step by step in subfields,
426 the method is applied to all the preceding fields that do not yet match.
427 E.g. C-x C-f /u/mo/s TAB could complete to /usr/monnier/src.
428 Additionally the user can use the char \"*\" as a glob pattern.")
429 (substring
430 completion-substring-try-completion completion-substring-all-completions
431 "Completion of the string taken as a substring.
432 I.e. when completing \"foo_bar\" (where _ is the position of point),
433 it will consider all completions candidates matching the glob
434 pattern \"*foo*bar*\".")
435 (initials
436 completion-initials-try-completion completion-initials-all-completions
437 "Completion of acronyms and initialisms.
438 E.g. can complete M-x lch to list-command-history
439 and C-x C-f ~/sew to ~/src/emacs/work."))
440 "List of available completion styles.
441 Each element has the form (NAME TRY-COMPLETION ALL-COMPLETIONS DOC):
442 where NAME is the name that should be used in `completion-styles',
443 TRY-COMPLETION is the function that does the completion (it should
444 follow the same calling convention as `completion-try-completion'),
445 ALL-COMPLETIONS is the function that lists the completions (it should
446 follow the calling convention of `completion-all-completions'),
447 and DOC describes the way this style of completion works.")
449 (defcustom completion-styles
450 ;; First, use `basic' because prefix completion has been the standard
451 ;; for "ever" and works well in most cases, so using it first
452 ;; ensures that we obey previous behavior in most cases.
453 '(basic
454 ;; Then use `partial-completion' because it has proven to
455 ;; be a very convenient extension.
456 partial-completion
457 ;; Finally use `emacs22' so as to maintain (in many/most cases)
458 ;; the previous behavior that when completing "foobar" with point
459 ;; between "foo" and "bar" the completion try to complete "foo"
460 ;; and simply add "bar" to the end of the result.
461 emacs22)
462 "List of completion styles to use.
463 The available styles are listed in `completion-styles-alist'."
464 :type `(repeat (choice ,@(mapcar (lambda (x) (list 'const (car x)))
465 completion-styles-alist)))
466 :group 'minibuffer
467 :version "23.1")
469 (defun completion-try-completion (string table pred point)
470 "Try to complete STRING using completion table TABLE.
471 Only the elements of table that satisfy predicate PRED are considered.
472 POINT is the position of point within STRING.
473 The return value can be either nil to indicate that there is no completion,
474 t to indicate that STRING is the only possible completion,
475 or a pair (STRING . NEWPOINT) of the completed result string together with
476 a new position for point."
477 (completion--some (lambda (style)
478 (funcall (nth 1 (assq style completion-styles-alist))
479 string table pred point))
480 completion-styles))
482 (defun completion-all-completions (string table pred point)
483 "List the possible completions of STRING in completion table TABLE.
484 Only the elements of table that satisfy predicate PRED are considered.
485 POINT is the position of point within STRING.
486 The return value is a list of completions and may contain the base-size
487 in the last `cdr'."
488 ;; FIXME: We need to additionally return the info needed for the
489 ;; second part of completion-base-position.
490 (completion--some (lambda (style)
491 (funcall (nth 2 (assq style completion-styles-alist))
492 string table pred point))
493 completion-styles))
495 (defun minibuffer--bitset (modified completions exact)
496 (logior (if modified 4 0)
497 (if completions 2 0)
498 (if exact 1 0)))
500 (defun completion--replace (beg end newtext)
501 "Replace the buffer text between BEG and END with NEWTEXT.
502 Moves point to the end of the new text."
503 ;; Maybe this should be in subr.el.
504 ;; You'd think this is trivial to do, but details matter if you want
505 ;; to keep markers "at the right place" and be robust in the face of
506 ;; after-change-functions that may themselves modify the buffer.
507 (let ((prefix-len 0))
508 ;; Don't touch markers in the shared prefix (if any).
509 (while (and (< prefix-len (length newtext))
510 (< (+ beg prefix-len) end)
511 (eq (char-after (+ beg prefix-len))
512 (aref newtext prefix-len)))
513 (setq prefix-len (1+ prefix-len)))
514 (unless (zerop prefix-len)
515 (setq beg (+ beg prefix-len))
516 (setq newtext (substring newtext prefix-len))))
517 (let ((suffix-len 0))
518 ;; Don't touch markers in the shared suffix (if any).
519 (while (and (< suffix-len (length newtext))
520 (< beg (- end suffix-len))
521 (eq (char-before (- end suffix-len))
522 (aref newtext (- (length newtext) suffix-len 1))))
523 (setq suffix-len (1+ suffix-len)))
524 (unless (zerop suffix-len)
525 (setq end (- end suffix-len))
526 (setq newtext (substring newtext 0 (- suffix-len))))
527 (goto-char beg)
528 (insert newtext)
529 (delete-region (point) (+ (point) (- end beg)))
530 (forward-char suffix-len)))
532 (defcustom completion-cycle-threshold nil
533 "Number of completion candidates below which cycling is used.
534 Depending on this setting `minibuffer-complete' may use cycling,
535 like `minibuffer-force-complete'.
536 If nil, cycling is never used.
537 If t, cycling is always used.
538 If an integer, cycling is used as soon as there are fewer completion
539 candidates than this number."
540 :type '(choice (const :tag "No cycling" nil)
541 (const :tag "Always cycle" t)
542 (integer :tag "Threshold")))
544 (defvar completion-all-sorted-completions nil)
545 (make-variable-buffer-local 'completion-all-sorted-completions)
546 (defvar completion-cycling nil)
548 (defvar completion-fail-discreetly nil
549 "If non-nil, stay quiet when there is no match.")
551 (defun completion--do-completion (&optional try-completion-function)
552 "Do the completion and return a summary of what happened.
553 M = completion was performed, the text was Modified.
554 C = there were available Completions.
555 E = after completion we now have an Exact match.
558 000 0 no possible completion
559 001 1 was already an exact and unique completion
560 010 2 no completion happened
561 011 3 was already an exact completion
562 100 4 ??? impossible
563 101 5 ??? impossible
564 110 6 some completion happened
565 111 7 completed to an exact completion"
566 (let* ((beg (field-beginning))
567 (end (field-end))
568 (string (buffer-substring beg end))
569 (comp (funcall (or try-completion-function
570 'completion-try-completion)
571 string
572 minibuffer-completion-table
573 minibuffer-completion-predicate
574 (- (point) beg))))
575 (cond
576 ((null comp)
577 (minibuffer-hide-completions)
578 (when (and (not completion-fail-discreetly) completion-show-inline-help)
579 (ding)
580 (minibuffer-message "No match"))
581 (minibuffer--bitset nil nil nil))
582 ((eq t comp)
583 (minibuffer-hide-completions)
584 (goto-char (field-end))
585 (minibuffer--bitset nil nil t)) ;Exact and unique match.
587 ;; `completed' should be t if some completion was done, which doesn't
588 ;; include simply changing the case of the entered string. However,
589 ;; for appearance, the string is rewritten if the case changes.
590 (let* ((comp-pos (cdr comp))
591 (completion (car comp))
592 (completed (not (eq t (compare-strings completion nil nil
593 string nil nil t))))
594 (unchanged (eq t (compare-strings completion nil nil
595 string nil nil nil))))
596 (if unchanged
597 (goto-char end)
598 ;; Insert in minibuffer the chars we got.
599 (completion--replace beg end completion))
600 ;; Move point to its completion-mandated destination.
601 (forward-char (- comp-pos (length completion)))
603 (if (not (or unchanged completed))
604 ;; The case of the string changed, but that's all. We're not sure
605 ;; whether this is a unique completion or not, so try again using
606 ;; the real case (this shouldn't recurse again, because the next
607 ;; time try-completion will return either t or the exact string).
608 (completion--do-completion try-completion-function)
610 ;; It did find a match. Do we match some possibility exactly now?
611 (let ((exact (test-completion completion
612 minibuffer-completion-table
613 minibuffer-completion-predicate))
614 (comps
615 ;; Check to see if we want to do cycling. We do it
616 ;; here, after having performed the normal completion,
617 ;; so as to take advantage of the difference between
618 ;; try-completion and all-completions, for things
619 ;; like completion-ignored-extensions.
620 (when (and completion-cycle-threshold
621 ;; Check that the completion didn't make
622 ;; us jump to a different boundary.
623 (or (not completed)
624 (< (car (completion-boundaries
625 (substring completion 0 comp-pos)
626 minibuffer-completion-table
627 minibuffer-completion-predicate
628 ""))
629 comp-pos)))
630 (completion-all-sorted-completions))))
631 (completion--flush-all-sorted-completions)
632 (cond
633 ((and (consp (cdr comps)) ;; There's something to cycle.
634 (not (ignore-errors
635 ;; This signal an (intended) error if comps is too
636 ;; short or if completion-cycle-threshold is t.
637 (consp (nthcdr completion-cycle-threshold comps)))))
638 ;; Fewer than completion-cycle-threshold remaining
639 ;; completions: let's cycle.
640 (setq completed t exact t)
641 (setq completion-all-sorted-completions comps)
642 (minibuffer-force-complete))
643 (completed
644 ;; We could also decide to refresh the completions,
645 ;; if they're displayed (and assuming there are
646 ;; completions left).
647 (minibuffer-hide-completions))
648 ;; Show the completion table, if requested.
649 ((not exact)
650 (if (cond ((null completion-show-inline-help) t)
651 ((eq completion-auto-help 'lazy)
652 (eq this-command last-command))
653 (t completion-auto-help))
654 (minibuffer-completion-help)
655 (minibuffer-message "Next char not unique")))
656 ;; If the last exact completion and this one were the same, it
657 ;; means we've already given a "Next char not unique" message
658 ;; and the user's hit TAB again, so now we give him help.
659 ((eq this-command last-command)
660 (if completion-auto-help (minibuffer-completion-help))))
662 (minibuffer--bitset completed t exact))))))))
664 (defun minibuffer-complete ()
665 "Complete the minibuffer contents as far as possible.
666 Return nil if there is no valid completion, else t.
667 If no characters can be completed, display a list of possible completions.
668 If you repeat this command after it displayed such a list,
669 scroll the window of possible completions."
670 (interactive)
671 ;; If the previous command was not this,
672 ;; mark the completion buffer obsolete.
673 (unless (eq this-command last-command)
674 (completion--flush-all-sorted-completions)
675 (setq minibuffer-scroll-window nil))
677 (cond
678 ;; If there's a fresh completion window with a live buffer,
679 ;; and this command is repeated, scroll that window.
680 ((window-live-p minibuffer-scroll-window)
681 (let ((window minibuffer-scroll-window))
682 (with-current-buffer (window-buffer window)
683 (if (pos-visible-in-window-p (point-max) window)
684 ;; If end is in view, scroll up to the beginning.
685 (set-window-start window (point-min) nil)
686 ;; Else scroll down one screen.
687 (scroll-other-window))
688 nil)))
689 ;; If we're cycling, keep on cycling.
690 ((and completion-cycling completion-all-sorted-completions)
691 (minibuffer-force-complete)
693 (t (case (completion--do-completion)
694 (#b000 nil)
695 (#b001 (if completion-show-inline-help
696 (minibuffer-message "Sole completion"))
698 (#b011 (if completion-show-inline-help
699 (minibuffer-message "Complete, but not unique"))
701 (t t)))))
703 (defun completion--flush-all-sorted-completions (&rest _ignore)
704 (remove-hook 'after-change-functions
705 'completion--flush-all-sorted-completions t)
706 (setq completion-cycling nil)
707 (setq completion-all-sorted-completions nil))
709 (defun completion-all-sorted-completions ()
710 (or completion-all-sorted-completions
711 (let* ((start (field-beginning))
712 (end (field-end))
713 (all (completion-all-completions (buffer-substring start end)
714 minibuffer-completion-table
715 minibuffer-completion-predicate
716 (- (point) start)))
717 (last (last all))
718 (base-size (or (cdr last) 0)))
719 (when last
720 (setcdr last nil)
721 ;; Prefer shorter completions.
722 (setq all (sort all (lambda (c1 c2)
723 (let ((s1 (get-text-property
724 0 :completion-cycle-penalty c1))
725 (s2 (get-text-property
726 0 :completion-cycle-penalty c2)))
727 (if (eq s1 s2)
728 (< (length c1) (length c2))
729 (< (or s1 (length c1))
730 (or s2 (length c2))))))))
731 ;; Prefer recently used completions.
732 ;; FIXME: Additional sorting ideas:
733 ;; - for M-x, prefer commands that have no key binding.
734 (let ((hist (symbol-value minibuffer-history-variable)))
735 (setq all (sort all (lambda (c1 c2)
736 (> (length (member c1 hist))
737 (length (member c2 hist)))))))
738 ;; Cache the result. This is not just for speed, but also so that
739 ;; repeated calls to minibuffer-force-complete can cycle through
740 ;; all possibilities.
741 (add-hook 'after-change-functions
742 'completion--flush-all-sorted-completions nil t)
743 (setq completion-all-sorted-completions
744 (nconc all base-size))))))
746 (defun minibuffer-force-complete ()
747 "Complete the minibuffer to an exact match.
748 Repeated uses step through the possible completions."
749 (interactive)
750 ;; FIXME: Need to deal with the extra-size issue here as well.
751 ;; FIXME: ~/src/emacs/t<M-TAB>/lisp/minibuffer.el completes to
752 ;; ~/src/emacs/trunk/ and throws away lisp/minibuffer.el.
753 (let* ((start (field-beginning))
754 (end (field-end))
755 (all (completion-all-sorted-completions)))
756 (if (not (consp all))
757 (if completion-show-inline-help
758 (minibuffer-message
759 (if all "No more completions" "No completions")))
760 (setq completion-cycling t)
761 (goto-char end)
762 (insert (car all))
763 (delete-region (+ start (cdr (last all))) end)
764 ;; If completing file names, (car all) may be a directory, so we'd now
765 ;; have a new set of possible completions and might want to reset
766 ;; completion-all-sorted-completions to nil, but we prefer not to,
767 ;; so that repeated calls minibuffer-force-complete still cycle
768 ;; through the previous possible completions.
769 (let ((last (last all)))
770 (setcdr last (cons (car all) (cdr last)))
771 (setq completion-all-sorted-completions (cdr all))))))
773 (defvar minibuffer-confirm-exit-commands
774 '(minibuffer-complete minibuffer-complete-word PC-complete PC-complete-word)
775 "A list of commands which cause an immediately following
776 `minibuffer-complete-and-exit' to ask for extra confirmation.")
778 (defun minibuffer-complete-and-exit ()
779 "Exit if the minibuffer contains a valid completion.
780 Otherwise, try to complete the minibuffer contents. If
781 completion leads to a valid completion, a repetition of this
782 command will exit.
784 If `minibuffer-completion-confirm' is `confirm', do not try to
785 complete; instead, ask for confirmation and accept any input if
786 confirmed.
787 If `minibuffer-completion-confirm' is `confirm-after-completion',
788 do not try to complete; instead, ask for confirmation if the
789 preceding minibuffer command was a member of
790 `minibuffer-confirm-exit-commands', and accept the input
791 otherwise."
792 (interactive)
793 (let ((beg (field-beginning))
794 (end (field-end)))
795 (cond
796 ;; Allow user to specify null string
797 ((= beg end) (exit-minibuffer))
798 ((test-completion (buffer-substring beg end)
799 minibuffer-completion-table
800 minibuffer-completion-predicate)
801 ;; FIXME: completion-ignore-case has various slightly
802 ;; incompatible meanings. E.g. it can reflect whether the user
803 ;; wants completion to pay attention to case, or whether the
804 ;; string will be used in a context where case is significant.
805 ;; E.g. usually try-completion should obey the first, whereas
806 ;; test-completion should obey the second.
807 (when completion-ignore-case
808 ;; Fixup case of the field, if necessary.
809 (let* ((string (buffer-substring beg end))
810 (compl (try-completion
811 string
812 minibuffer-completion-table
813 minibuffer-completion-predicate)))
814 (when (and (stringp compl) (not (equal string compl))
815 ;; If it weren't for this piece of paranoia, I'd replace
816 ;; the whole thing with a call to do-completion.
817 ;; This is important, e.g. when the current minibuffer's
818 ;; content is a directory which only contains a single
819 ;; file, so `try-completion' actually completes to
820 ;; that file.
821 (= (length string) (length compl)))
822 (goto-char end)
823 (insert compl)
824 (delete-region beg end))))
825 (exit-minibuffer))
827 ((memq minibuffer-completion-confirm '(confirm confirm-after-completion))
828 ;; The user is permitted to exit with an input that's rejected
829 ;; by test-completion, after confirming her choice.
830 (if (or (eq last-command this-command)
831 ;; For `confirm-after-completion' we only ask for confirmation
832 ;; if trying to exit immediately after typing TAB (this
833 ;; catches most minibuffer typos).
834 (and (eq minibuffer-completion-confirm 'confirm-after-completion)
835 (not (memq last-command minibuffer-confirm-exit-commands))))
836 (exit-minibuffer)
837 (minibuffer-message "Confirm")
838 nil))
841 ;; Call do-completion, but ignore errors.
842 (case (condition-case nil
843 (completion--do-completion)
844 (error 1))
845 ((#b001 #b011) (exit-minibuffer))
846 (#b111 (if (not minibuffer-completion-confirm)
847 (exit-minibuffer)
848 (minibuffer-message "Confirm")
849 nil))
850 (t nil))))))
852 (defun completion--try-word-completion (string table predicate point)
853 (let ((comp (completion-try-completion string table predicate point)))
854 (if (not (consp comp))
855 comp
857 ;; If completion finds next char not unique,
858 ;; consider adding a space or a hyphen.
859 (when (= (length string) (length (car comp)))
860 ;; Mark the added char with the `completion-word' property, so it
861 ;; can be handled specially by completion styles such as
862 ;; partial-completion.
863 ;; We used to remove `partial-completion' from completion-styles
864 ;; instead, but it was too blunt, leading to situations where SPC
865 ;; was the only insertable char at point but minibuffer-complete-word
866 ;; refused inserting it.
867 (let ((exts (mapcar (lambda (str) (propertize str 'completion-try-word t))
868 '(" " "-")))
869 (before (substring string 0 point))
870 (after (substring string point))
871 tem)
872 (while (and exts (not (consp tem)))
873 (setq tem (completion-try-completion
874 (concat before (pop exts) after)
875 table predicate (1+ point))))
876 (if (consp tem) (setq comp tem))))
878 ;; Completing a single word is actually more difficult than completing
879 ;; as much as possible, because we first have to find the "current
880 ;; position" in `completion' in order to find the end of the word
881 ;; we're completing. Normally, `string' is a prefix of `completion',
882 ;; which makes it trivial to find the position, but with fancier
883 ;; completion (plus env-var expansion, ...) `completion' might not
884 ;; look anything like `string' at all.
885 (let* ((comppoint (cdr comp))
886 (completion (car comp))
887 (before (substring string 0 point))
888 (combined (concat before "\n" completion)))
889 ;; Find in completion the longest text that was right before point.
890 (when (string-match "\\(.+\\)\n.*?\\1" combined)
891 (let* ((prefix (match-string 1 before))
892 ;; We used non-greedy match to make `rem' as long as possible.
893 (rem (substring combined (match-end 0)))
894 ;; Find in the remainder of completion the longest text
895 ;; that was right after point.
896 (after (substring string point))
897 (suffix (if (string-match "\\`\\(.+\\).*\n.*\\1"
898 (concat after "\n" rem))
899 (match-string 1 after))))
900 ;; The general idea is to try and guess what text was inserted
901 ;; at point by the completion. Problem is: if we guess wrong,
902 ;; we may end up treating as "added by completion" text that was
903 ;; actually painfully typed by the user. So if we then cut
904 ;; after the first word, we may throw away things the
905 ;; user wrote. So let's try to be as conservative as possible:
906 ;; only cut after the first word, if we're reasonably sure that
907 ;; our guess is correct.
908 ;; Note: a quick survey on emacs-devel seemed to indicate that
909 ;; nobody actually cares about the "word-at-a-time" feature of
910 ;; minibuffer-complete-word, whose real raison-d'être is that it
911 ;; tries to add "-" or " ". One more reason to only cut after
912 ;; the first word, if we're really sure we're right.
913 (when (and (or suffix (zerop (length after)))
914 (string-match (concat
915 ;; Make submatch 1 as small as possible
916 ;; to reduce the risk of cutting
917 ;; valuable text.
918 ".*" (regexp-quote prefix) "\\(.*?\\)"
919 (if suffix (regexp-quote suffix) "\\'"))
920 completion)
921 ;; The new point in `completion' should also be just
922 ;; before the suffix, otherwise something more complex
923 ;; is going on, and we're not sure where we are.
924 (eq (match-end 1) comppoint)
925 ;; (match-beginning 1)..comppoint is now the stretch
926 ;; of text in `completion' that was completed at point.
927 (string-match "\\W" completion (match-beginning 1))
928 ;; Is there really something to cut?
929 (> comppoint (match-end 0)))
930 ;; Cut after the first word.
931 (let ((cutpos (match-end 0)))
932 (setq completion (concat (substring completion 0 cutpos)
933 (substring completion comppoint)))
934 (setq comppoint cutpos)))))
936 (cons completion comppoint)))))
939 (defun minibuffer-complete-word ()
940 "Complete the minibuffer contents at most a single word.
941 After one word is completed as much as possible, a space or hyphen
942 is added, provided that matches some possible completion.
943 Return nil if there is no valid completion, else t."
944 (interactive)
945 (case (completion--do-completion 'completion--try-word-completion)
946 (#b000 nil)
947 (#b001 (if completion-show-inline-help
948 (minibuffer-message "Sole completion"))
950 (#b011 (if completion-show-inline-help
951 (minibuffer-message "Complete, but not unique"))
953 (t t)))
955 (defface completions-annotations '((t :inherit italic))
956 "Face to use for annotations in the *Completions* buffer.")
958 (defcustom completions-format 'horizontal
959 "Define the appearance and sorting of completions.
960 If the value is `vertical', display completions sorted vertically
961 in columns in the *Completions* buffer.
962 If the value is `horizontal', display completions sorted
963 horizontally in alphabetical order, rather than down the screen."
964 :type '(choice (const horizontal) (const vertical))
965 :group 'minibuffer
966 :version "23.2")
968 (defun completion--insert-strings (strings)
969 "Insert a list of STRINGS into the current buffer.
970 Uses columns to keep the listing readable but compact.
971 It also eliminates runs of equal strings."
972 (when (consp strings)
973 (let* ((length (apply 'max
974 (mapcar (lambda (s)
975 (if (consp s)
976 (+ (string-width (car s))
977 (string-width (cadr s)))
978 (string-width s)))
979 strings)))
980 (window (get-buffer-window (current-buffer) 0))
981 (wwidth (if window (1- (window-width window)) 79))
982 (columns (min
983 ;; At least 2 columns; at least 2 spaces between columns.
984 (max 2 (/ wwidth (+ 2 length)))
985 ;; Don't allocate more columns than we can fill.
986 ;; Windows can't show less than 3 lines anyway.
987 (max 1 (/ (length strings) 2))))
988 (colwidth (/ wwidth columns))
989 (column 0)
990 (rows (/ (length strings) columns))
991 (row 0)
992 (laststring nil))
993 ;; The insertion should be "sensible" no matter what choices were made
994 ;; for the parameters above.
995 (dolist (str strings)
996 (unless (equal laststring str) ; Remove (consecutive) duplicates.
997 (setq laststring str)
998 (let ((length (if (consp str)
999 (+ (string-width (car str))
1000 (string-width (cadr str)))
1001 (string-width str))))
1002 (cond
1003 ((eq completions-format 'vertical)
1004 ;; Vertical format
1005 (when (> row rows)
1006 (forward-line (- -1 rows))
1007 (setq row 0 column (+ column colwidth)))
1008 (when (> column 0)
1009 (end-of-line)
1010 (while (> (current-column) column)
1011 (if (eobp)
1012 (insert "\n")
1013 (forward-line 1)
1014 (end-of-line)))
1015 (insert " \t")
1016 (set-text-properties (- (point) 1) (point)
1017 `(display (space :align-to ,column)))))
1019 ;; Horizontal format
1020 (unless (bolp)
1021 (if (< wwidth (+ (max colwidth length) column))
1022 ;; No space for `str' at point, move to next line.
1023 (progn (insert "\n") (setq column 0))
1024 (insert " \t")
1025 ;; Leave the space unpropertized so that in the case we're
1026 ;; already past the goal column, there is still
1027 ;; a space displayed.
1028 (set-text-properties (- (point) 1) (point)
1029 ;; We can't just set tab-width, because
1030 ;; completion-setup-function will kill
1031 ;; all local variables :-(
1032 `(display (space :align-to ,column)))
1033 nil))))
1034 (if (not (consp str))
1035 (put-text-property (point) (progn (insert str) (point))
1036 'mouse-face 'highlight)
1037 (put-text-property (point) (progn (insert (car str)) (point))
1038 'mouse-face 'highlight)
1039 (add-text-properties (point) (progn (insert (cadr str)) (point))
1040 '(mouse-face nil
1041 face completions-annotations)))
1042 (cond
1043 ((eq completions-format 'vertical)
1044 ;; Vertical format
1045 (if (> column 0)
1046 (forward-line)
1047 (insert "\n"))
1048 (setq row (1+ row)))
1050 ;; Horizontal format
1051 ;; Next column to align to.
1052 (setq column (+ column
1053 ;; Round up to a whole number of columns.
1054 (* colwidth (ceiling length colwidth))))))))))))
1056 (defvar completion-common-substring nil)
1057 (make-obsolete-variable 'completion-common-substring nil "23.1")
1059 (defvar completion-setup-hook nil
1060 "Normal hook run at the end of setting up a completion list buffer.
1061 When this hook is run, the current buffer is the one in which the
1062 command to display the completion list buffer was run.
1063 The completion list buffer is available as the value of `standard-output'.
1064 See also `display-completion-list'.")
1066 (defface completions-first-difference
1067 '((t (:inherit bold)))
1068 "Face put on the first uncommon character in completions in *Completions* buffer."
1069 :group 'completion)
1071 (defface completions-common-part
1072 '((t (:inherit default)))
1073 "Face put on the common prefix substring in completions in *Completions* buffer.
1074 The idea of `completions-common-part' is that you can use it to
1075 make the common parts less visible than normal, so that the rest
1076 of the differing parts is, by contrast, slightly highlighted."
1077 :group 'completion)
1079 (defun completion-hilit-commonality (completions prefix-len base-size)
1080 (when completions
1081 (let ((com-str-len (- prefix-len (or base-size 0))))
1082 (nconc
1083 (mapcar
1084 (lambda (elem)
1085 (let ((str
1086 ;; Don't modify the string itself, but a copy, since the
1087 ;; the string may be read-only or used for other purposes.
1088 ;; Furthermore, since `completions' may come from
1089 ;; display-completion-list, `elem' may be a list.
1090 (if (consp elem)
1091 (car (setq elem (cons (copy-sequence (car elem))
1092 (cdr elem))))
1093 (setq elem (copy-sequence elem)))))
1094 (put-text-property 0
1095 ;; If completion-boundaries returns incorrect
1096 ;; values, all-completions may return strings
1097 ;; that don't contain the prefix.
1098 (min com-str-len (length str))
1099 'font-lock-face 'completions-common-part
1100 str)
1101 (if (> (length str) com-str-len)
1102 (put-text-property com-str-len (1+ com-str-len)
1103 'font-lock-face 'completions-first-difference
1104 str)))
1105 elem)
1106 completions)
1107 base-size))))
1109 (defun display-completion-list (completions &optional common-substring)
1110 "Display the list of completions, COMPLETIONS, using `standard-output'.
1111 Each element may be just a symbol or string
1112 or may be a list of two strings to be printed as if concatenated.
1113 If it is a list of two strings, the first is the actual completion
1114 alternative, the second serves as annotation.
1115 `standard-output' must be a buffer.
1116 The actual completion alternatives, as inserted, are given `mouse-face'
1117 properties of `highlight'.
1118 At the end, this runs the normal hook `completion-setup-hook'.
1119 It can find the completion buffer in `standard-output'.
1121 The obsolete optional arg COMMON-SUBSTRING, if non-nil, should be a string
1122 specifying a common substring for adding the faces
1123 `completions-first-difference' and `completions-common-part' to
1124 the completions buffer."
1125 (if common-substring
1126 (setq completions (completion-hilit-commonality
1127 completions (length common-substring)
1128 ;; We don't know the base-size.
1129 nil)))
1130 (if (not (bufferp standard-output))
1131 ;; This *never* (ever) happens, so there's no point trying to be clever.
1132 (with-temp-buffer
1133 (let ((standard-output (current-buffer))
1134 (completion-setup-hook nil))
1135 (display-completion-list completions common-substring))
1136 (princ (buffer-string)))
1138 (with-current-buffer standard-output
1139 (goto-char (point-max))
1140 (if (null completions)
1141 (insert "There are no possible completions of what you have typed.")
1142 (insert "Possible completions are:\n")
1143 (completion--insert-strings completions))))
1145 ;; The hilit used to be applied via completion-setup-hook, so there
1146 ;; may still be some code that uses completion-common-substring.
1147 (with-no-warnings
1148 (let ((completion-common-substring common-substring))
1149 (run-hooks 'completion-setup-hook)))
1150 nil)
1152 (defvar completion-annotate-function
1154 ;; Note: there's a lot of scope as for when to add annotations and
1155 ;; what annotations to add. E.g. completing-help.el allowed adding
1156 ;; the first line of docstrings to M-x completion. But there's
1157 ;; a tension, since such annotations, while useful at times, can
1158 ;; actually drown the useful information.
1159 ;; So completion-annotate-function should be used parsimoniously, or
1160 ;; else only used upon a user's request (e.g. we could add a command
1161 ;; to completion-list-mode to add annotations to the current
1162 ;; completions).
1163 "Function to add annotations in the *Completions* buffer.
1164 The function takes a completion and should either return nil, or a string that
1165 will be displayed next to the completion. The function can access the
1166 completion table and predicates via `minibuffer-completion-table' and related
1167 variables.")
1169 (defun minibuffer-completion-help ()
1170 "Display a list of possible completions of the current minibuffer contents."
1171 (interactive)
1172 (message "Making completion list...")
1173 (let* ((start (field-beginning))
1174 (end (field-end))
1175 (string (field-string))
1176 (completions (completion-all-completions
1177 string
1178 minibuffer-completion-table
1179 minibuffer-completion-predicate
1180 (- (point) (field-beginning)))))
1181 (message nil)
1182 (if (and completions
1183 (or (consp (cdr completions))
1184 (not (equal (car completions) string))))
1185 (let* ((last (last completions))
1186 (base-size (cdr last))
1187 ;; If the *Completions* buffer is shown in a new
1188 ;; window, mark it as softly-dedicated, so bury-buffer in
1189 ;; minibuffer-hide-completions will know whether to
1190 ;; delete the window or not.
1191 (display-buffer-mark-dedicated 'soft))
1192 (with-output-to-temp-buffer "*Completions*"
1193 ;; Remove the base-size tail because `sort' requires a properly
1194 ;; nil-terminated list.
1195 (when last (setcdr last nil))
1196 (setq completions (sort completions 'string-lessp))
1197 (when completion-annotate-function
1198 (setq completions
1199 (mapcar (lambda (s)
1200 (let ((ann
1201 (funcall completion-annotate-function s)))
1202 (if ann (list s ann) s)))
1203 completions)))
1204 (with-current-buffer standard-output
1205 (set (make-local-variable 'completion-base-position)
1206 (list (+ start base-size)
1207 ;; FIXME: We should pay attention to completion
1208 ;; boundaries here, but currently
1209 ;; completion-all-completions does not give us the
1210 ;; necessary information.
1211 end)))
1212 (display-completion-list completions)))
1214 ;; If there are no completions, or if the current input is already the
1215 ;; only possible completion, then hide (previous&stale) completions.
1216 (minibuffer-hide-completions)
1217 (ding)
1218 (minibuffer-message
1219 (if completions "Sole completion" "No completions")))
1220 nil))
1222 (defun minibuffer-hide-completions ()
1223 "Get rid of an out-of-date *Completions* buffer."
1224 ;; FIXME: We could/should use minibuffer-scroll-window here, but it
1225 ;; can also point to the minibuffer-parent-window, so it's a bit tricky.
1226 (let ((win (get-buffer-window "*Completions*" 0)))
1227 (if win (with-selected-window win (bury-buffer)))))
1229 (defun exit-minibuffer ()
1230 "Terminate this minibuffer argument."
1231 (interactive)
1232 ;; If the command that uses this has made modifications in the minibuffer,
1233 ;; we don't want them to cause deactivation of the mark in the original
1234 ;; buffer.
1235 ;; A better solution would be to make deactivate-mark buffer-local
1236 ;; (or to turn it into a list of buffers, ...), but in the mean time,
1237 ;; this should do the trick in most cases.
1238 (setq deactivate-mark nil)
1239 (throw 'exit nil))
1241 (defun self-insert-and-exit ()
1242 "Terminate minibuffer input."
1243 (interactive)
1244 (if (characterp last-command-event)
1245 (call-interactively 'self-insert-command)
1246 (ding))
1247 (exit-minibuffer))
1249 (defvar completion-in-region-functions nil
1250 "Wrapper hook around `completion-in-region'.
1251 The functions on this special hook are called with 5 arguments:
1252 NEXT-FUN START END COLLECTION PREDICATE.
1253 NEXT-FUN is a function of four arguments (START END COLLECTION PREDICATE)
1254 that performs the default operation. The other four arguments are like
1255 the ones passed to `completion-in-region'. The functions on this hook
1256 are expected to perform completion on START..END using COLLECTION
1257 and PREDICATE, either by calling NEXT-FUN or by doing it themselves.")
1259 (defvar completion-in-region--data nil)
1261 (defvar completion-in-region-mode-predicate nil
1262 "Predicate to tell `completion-in-region-mode' when to exit.
1263 It is called with no argument and should return nil when
1264 `completion-in-region-mode' should exit (and hence pop down
1265 the *Completions* buffer).")
1267 (defvar completion-in-region-mode--predicate nil
1268 "Copy of the value of `completion-in-region-mode-predicate'.
1269 This holds the value `completion-in-region-mode-predicate' had when
1270 we entered `completion-in-region-mode'.")
1272 (defun completion-in-region (start end collection &optional predicate)
1273 "Complete the text between START and END using COLLECTION.
1274 Return nil if there is no valid completion, else t.
1275 Point needs to be somewhere between START and END."
1276 (assert (<= start (point)) (<= (point) end))
1277 (with-wrapper-hook
1278 ;; FIXME: Maybe we should use this hook to provide a "display
1279 ;; completions" operation as well.
1280 completion-in-region-functions (start end collection predicate)
1281 (let ((minibuffer-completion-table collection)
1282 (minibuffer-completion-predicate predicate)
1283 (ol (make-overlay start end nil nil t)))
1284 (overlay-put ol 'field 'completion)
1285 (when completion-in-region-mode-predicate
1286 (completion-in-region-mode 1)
1287 (setq completion-in-region--data
1288 (list (current-buffer) start end collection)))
1289 (unwind-protect
1290 (call-interactively 'minibuffer-complete)
1291 (delete-overlay ol)))))
1293 (defvar completion-in-region-mode-map
1294 (let ((map (make-sparse-keymap)))
1295 (define-key map "?" 'completion-help-at-point)
1296 (define-key map "\t" 'completion-at-point)
1297 map)
1298 "Keymap activated during `completion-in-region'.")
1300 ;; It is difficult to know when to exit completion-in-region-mode (i.e. hide
1301 ;; the *Completions*).
1302 ;; - lisp-mode: never.
1303 ;; - comint: only do it if you hit SPC at the right time.
1304 ;; - pcomplete: pop it down on SPC or after some time-delay.
1305 ;; - semantic: use a post-command-hook check similar to this one.
1306 (defun completion-in-region--postch ()
1307 (or unread-command-events ;Don't pop down the completions in the middle of
1308 ;mouse-drag-region/mouse-set-point.
1309 (and completion-in-region--data
1310 (and (eq (car completion-in-region--data)
1311 (current-buffer))
1312 (>= (point) (nth 1 completion-in-region--data))
1313 (<= (point)
1314 (save-excursion
1315 (goto-char (nth 2 completion-in-region--data))
1316 (line-end-position)))
1317 (when completion-in-region-mode--predicate
1318 (funcall completion-in-region-mode--predicate))))
1319 (completion-in-region-mode -1)))
1321 ;; (defalias 'completion-in-region--prech 'completion-in-region--postch)
1323 (define-minor-mode completion-in-region-mode
1324 "Transient minor mode used during `completion-in-region'."
1325 :global t
1326 (setq completion-in-region--data nil)
1327 ;; (remove-hook 'pre-command-hook #'completion-in-region--prech)
1328 (remove-hook 'post-command-hook #'completion-in-region--postch)
1329 (setq minor-mode-overriding-map-alist
1330 (delq (assq 'completion-in-region-mode minor-mode-overriding-map-alist)
1331 minor-mode-overriding-map-alist))
1332 (if (null completion-in-region-mode)
1333 (unless (or (equal "*Completions*" (buffer-name (window-buffer)))
1334 (null completion-in-region-mode--predicate))
1335 (minibuffer-hide-completions))
1336 ;; (add-hook 'pre-command-hook #'completion-in-region--prech)
1337 (set (make-local-variable 'completion-in-region-mode--predicate)
1338 completion-in-region-mode-predicate)
1339 (add-hook 'post-command-hook #'completion-in-region--postch)
1340 (push `(completion-in-region-mode . ,completion-in-region-mode-map)
1341 minor-mode-overriding-map-alist)))
1343 ;; Define-minor-mode added our keymap to minor-mode-map-alist, but we want it
1344 ;; on minor-mode-overriding-map-alist instead.
1345 (setq minor-mode-map-alist
1346 (delq (assq 'completion-in-region-mode minor-mode-map-alist)
1347 minor-mode-map-alist))
1349 (defvar completion-at-point-functions '(tags-completion-at-point-function)
1350 "Special hook to find the completion table for the thing at point.
1351 Each function on this hook is called in turns without any argument and should
1352 return either nil to mean that it is not applicable at point,
1353 or a function of no argument to perform completion (discouraged),
1354 or a list of the form (START END COLLECTION &rest PROPS) where
1355 START and END delimit the entity to complete and should include point,
1356 COLLECTION is the completion table to use to complete it, and
1357 PROPS is a property list for additional information.
1358 Currently supported properties are:
1359 `:predicate' a predicate that completion candidates need to satisfy.
1360 `:annotation-function' the value to use for `completion-annotate-function'.")
1362 (defvar completion--capf-misbehave-funs nil
1363 "List of functions found on `completion-at-point-functions' that misbehave.")
1364 (defvar completion--capf-safe-funs nil
1365 "List of well-behaved functions found on `completion-at-point-functions'.")
1367 (defun completion--capf-wrapper (fun which)
1368 (if (case which
1369 (all t)
1370 (safe (member fun completion--capf-safe-funs))
1371 (optimist (not (member fun completion--capf-misbehave-funs))))
1372 (let ((res (funcall fun)))
1373 (cond
1374 ((consp res)
1375 (unless (member fun completion--capf-safe-funs)
1376 (push fun completion--capf-safe-funs)))
1377 ((not (or (listp res) (functionp res)))
1378 (unless (member fun completion--capf-misbehave-funs)
1379 (message
1380 "Completion function %S uses a deprecated calling convention" fun)
1381 (push fun completion--capf-misbehave-funs))))
1382 (if res (cons fun res)))))
1384 (defun completion-at-point ()
1385 "Perform completion on the text around point.
1386 The completion method is determined by `completion-at-point-functions'."
1387 (interactive)
1388 (let ((res (run-hook-wrapped 'completion-at-point-functions
1389 #'completion--capf-wrapper 'all)))
1390 (pcase res
1391 (`(,_ . ,(and (pred functionp) f)) (funcall f))
1392 (`(,hookfun . (,start ,end ,collection . ,plist))
1393 (let* ((completion-annotate-function
1394 (or (plist-get plist :annotation-function)
1395 completion-annotate-function))
1396 (completion-in-region-mode-predicate
1397 (lambda ()
1398 ;; We're still in the same completion field.
1399 (eq (car (funcall hookfun)) start))))
1400 (completion-in-region start end collection
1401 (plist-get plist :predicate))))
1402 ;; Maybe completion already happened and the function returned t.
1403 (_ (cdr res)))))
1405 (defun completion-help-at-point ()
1406 "Display the completions on the text around point.
1407 The completion method is determined by `completion-at-point-functions'."
1408 (interactive)
1409 (let ((res (run-hook-wrapped 'completion-at-point-functions
1410 ;; Ignore misbehaving functions.
1411 #'completion--capf-wrapper 'optimist)))
1412 (pcase res
1413 (`(,_ . ,(and (pred functionp) f))
1414 (message "Don't know how to show completions for %S" f))
1415 (`(,hookfun . (,start ,end ,collection . ,plist))
1416 (let* ((minibuffer-completion-table collection)
1417 (minibuffer-completion-predicate (plist-get plist :predicate))
1418 (completion-annotate-function
1419 (or (plist-get plist :annotation-function)
1420 completion-annotate-function))
1421 (completion-in-region-mode-predicate
1422 (lambda ()
1423 ;; We're still in the same completion field.
1424 (eq (car (funcall hookfun)) start)))
1425 (ol (make-overlay start end nil nil t)))
1426 ;; FIXME: We should somehow (ab)use completion-in-region-function or
1427 ;; introduce a corresponding hook (plus another for word-completion,
1428 ;; and another for force-completion, maybe?).
1429 (overlay-put ol 'field 'completion)
1430 (completion-in-region-mode 1)
1431 (setq completion-in-region--data
1432 (list (current-buffer) start end collection))
1433 (unwind-protect
1434 (call-interactively 'minibuffer-completion-help)
1435 (delete-overlay ol))))
1436 (`(,hookfun . ,_)
1437 ;; The hook function already performed completion :-(
1438 ;; Not much we can do at this point.
1439 (message "%s already performed completion!" hookfun)
1440 nil)
1441 (_ (message "Nothing to complete at point")))))
1443 ;;; Key bindings.
1445 (define-obsolete-variable-alias 'minibuffer-local-must-match-filename-map
1446 'minibuffer-local-filename-must-match-map "23.1")
1448 (let ((map minibuffer-local-map))
1449 (define-key map "\C-g" 'abort-recursive-edit)
1450 (define-key map "\r" 'exit-minibuffer)
1451 (define-key map "\n" 'exit-minibuffer))
1453 (let ((map minibuffer-local-completion-map))
1454 (define-key map "\t" 'minibuffer-complete)
1455 ;; M-TAB is already abused for many other purposes, so we should find
1456 ;; another binding for it.
1457 ;; (define-key map "\e\t" 'minibuffer-force-complete)
1458 (define-key map " " 'minibuffer-complete-word)
1459 (define-key map "?" 'minibuffer-completion-help))
1461 (let ((map minibuffer-local-must-match-map))
1462 (define-key map "\r" 'minibuffer-complete-and-exit)
1463 (define-key map "\n" 'minibuffer-complete-and-exit))
1465 (let ((map minibuffer-local-filename-completion-map))
1466 (define-key map " " nil))
1467 (let ((map minibuffer-local-filename-must-match-map))
1468 (define-key map " " nil))
1470 (let ((map minibuffer-local-ns-map))
1471 (define-key map " " 'exit-minibuffer)
1472 (define-key map "\t" 'exit-minibuffer)
1473 (define-key map "?" 'self-insert-and-exit))
1475 ;;; Completion tables.
1477 (defun minibuffer--double-dollars (str)
1478 (replace-regexp-in-string "\\$" "$$" str))
1480 (defun completion--make-envvar-table ()
1481 (mapcar (lambda (enventry)
1482 (substring enventry 0 (string-match-p "=" enventry)))
1483 process-environment))
1485 (defconst completion--embedded-envvar-re
1486 (concat "\\(?:^\\|[^$]\\(?:\\$\\$\\)*\\)"
1487 "$\\([[:alnum:]_]*\\|{\\([^}]*\\)\\)\\'"))
1489 (defun completion--embedded-envvar-table (string _pred action)
1490 "Completion table for envvars embedded in a string.
1491 The envvar syntax (and escaping) rules followed by this table are the
1492 same as `substitute-in-file-name'."
1493 ;; We ignore `pred', because the predicates passed to us via
1494 ;; read-file-name-internal are not 100% correct and fail here:
1495 ;; e.g. we get predicates like file-directory-p there, whereas the filename
1496 ;; completed needs to be passed through substitute-in-file-name before it
1497 ;; can be passed to file-directory-p.
1498 (when (string-match completion--embedded-envvar-re string)
1499 (let* ((beg (or (match-beginning 2) (match-beginning 1)))
1500 (table (completion--make-envvar-table))
1501 (prefix (substring string 0 beg)))
1502 (cond
1503 ((eq action 'lambda)
1504 ;; This table is expected to be used in conjunction with some
1505 ;; other table that provides the "main" completion. Let the
1506 ;; other table handle the test-completion case.
1507 nil)
1508 ((eq (car-safe action) 'boundaries)
1509 ;; Only return boundaries if there's something to complete,
1510 ;; since otherwise when we're used in
1511 ;; completion-table-in-turn, we could return boundaries and
1512 ;; let some subsequent table return a list of completions.
1513 ;; FIXME: Maybe it should rather be fixed in
1514 ;; completion-table-in-turn instead, but it's difficult to
1515 ;; do it efficiently there.
1516 (when (try-completion (substring string beg) table nil)
1517 ;; Compute the boundaries of the subfield to which this
1518 ;; completion applies.
1519 (let ((suffix (cdr action)))
1520 (list* 'boundaries
1521 (or (match-beginning 2) (match-beginning 1))
1522 (when (string-match "[^[:alnum:]_]" suffix)
1523 (match-beginning 0))))))
1525 (if (eq (aref string (1- beg)) ?{)
1526 (setq table (apply-partially 'completion-table-with-terminator
1527 "}" table)))
1528 ;; Even if file-name completion is case-insensitive, we want
1529 ;; envvar completion to be case-sensitive.
1530 (let ((completion-ignore-case nil))
1531 (completion-table-with-context
1532 prefix table (substring string beg) nil action)))))))
1534 (defun completion-file-name-table (string pred action)
1535 "Completion table for file names."
1536 (ignore-errors
1537 (cond
1538 ((eq (car-safe action) 'boundaries)
1539 (let ((start (length (file-name-directory string)))
1540 (end (string-match-p "/" (cdr action))))
1541 (list* 'boundaries
1542 ;; if `string' is "C:" in w32, (file-name-directory string)
1543 ;; returns "C:/", so `start' is 3 rather than 2.
1544 ;; Not quite sure what is The Right Fix, but clipping it
1545 ;; back to 2 will work for this particular case. We'll
1546 ;; see if we can come up with a better fix when we bump
1547 ;; into more such problematic cases.
1548 (min start (length string)) end)))
1550 ((eq action 'lambda)
1551 (if (zerop (length string))
1552 nil ;Not sure why it's here, but it probably doesn't harm.
1553 (funcall (or pred 'file-exists-p) string)))
1556 (let* ((name (file-name-nondirectory string))
1557 (specdir (file-name-directory string))
1558 (realdir (or specdir default-directory)))
1560 (cond
1561 ((null action)
1562 (let ((comp (file-name-completion name realdir pred)))
1563 (if (stringp comp)
1564 (concat specdir comp)
1565 comp)))
1567 ((eq action t)
1568 (let ((all (file-name-all-completions name realdir)))
1570 ;; Check the predicate, if necessary.
1571 (unless (memq pred '(nil file-exists-p))
1572 (let ((comp ())
1573 (pred
1574 (if (eq pred 'file-directory-p)
1575 ;; Brute-force speed up for directory checking:
1576 ;; Discard strings which don't end in a slash.
1577 (lambda (s)
1578 (let ((len (length s)))
1579 (and (> len 0) (eq (aref s (1- len)) ?/))))
1580 ;; Must do it the hard (and slow) way.
1581 pred)))
1582 (let ((default-directory (expand-file-name realdir)))
1583 (dolist (tem all)
1584 (if (funcall pred tem) (push tem comp))))
1585 (setq all (nreverse comp))))
1587 all))))))))
1589 (defvar read-file-name-predicate nil
1590 "Current predicate used by `read-file-name-internal'.")
1591 (make-obsolete-variable 'read-file-name-predicate
1592 "use the regular PRED argument" "23.2")
1594 (defun completion--file-name-table (string pred action)
1595 "Internal subroutine for `read-file-name'. Do not call this.
1596 This is a completion table for file names, like `completion-file-name-table'
1597 except that it passes the file name through `substitute-in-file-name'."
1598 (cond
1599 ((eq (car-safe action) 'boundaries)
1600 ;; For the boundaries, we can't really delegate to
1601 ;; substitute-in-file-name+completion-file-name-table and then fix
1602 ;; them up (as we do for the other actions), because it would
1603 ;; require us to track the relationship between `str' and
1604 ;; `string', which is difficult. And in any case, if
1605 ;; substitute-in-file-name turns "fo-$TO-ba" into "fo-o/b-ba",
1606 ;; there's no way for us to return proper boundaries info, because
1607 ;; the boundary is not (yet) in `string'.
1609 ;; FIXME: Actually there is a way to return correct boundaries
1610 ;; info, at the condition of modifying the all-completions
1611 ;; return accordingly. But for now, let's not bother.
1612 (completion-file-name-table string pred action))
1615 (let* ((default-directory
1616 (if (stringp pred)
1617 ;; It used to be that `pred' was abused to pass `dir'
1618 ;; as an argument.
1619 (prog1 (file-name-as-directory (expand-file-name pred))
1620 (setq pred nil))
1621 default-directory))
1622 (str (condition-case nil
1623 (substitute-in-file-name string)
1624 (error string)))
1625 (comp (completion-file-name-table
1627 (with-no-warnings (or pred read-file-name-predicate))
1628 action)))
1630 (cond
1631 ((stringp comp)
1632 ;; Requote the $s before returning the completion.
1633 (minibuffer--double-dollars comp))
1634 ((and (null action) comp
1635 ;; Requote the $s before checking for changes.
1636 (setq str (minibuffer--double-dollars str))
1637 (not (string-equal string str)))
1638 ;; If there's no real completion, but substitute-in-file-name
1639 ;; changed the string, then return the new string.
1640 str)
1641 (t comp))))))
1643 (defalias 'read-file-name-internal
1644 (completion-table-in-turn 'completion--embedded-envvar-table
1645 'completion--file-name-table)
1646 "Internal subroutine for `read-file-name'. Do not call this.")
1648 (defvar read-file-name-function 'read-file-name-default
1649 "The function called by `read-file-name' to do its work.
1650 It should accept the same arguments as `read-file-name'.")
1652 (defcustom read-file-name-completion-ignore-case
1653 (if (memq system-type '(ms-dos windows-nt darwin cygwin))
1654 t nil)
1655 "Non-nil means when reading a file name completion ignores case."
1656 :group 'minibuffer
1657 :type 'boolean
1658 :version "22.1")
1660 (defcustom insert-default-directory t
1661 "Non-nil means when reading a filename start with default dir in minibuffer.
1663 When the initial minibuffer contents show a name of a file or a directory,
1664 typing RETURN without editing the initial contents is equivalent to typing
1665 the default file name.
1667 If this variable is non-nil, the minibuffer contents are always
1668 initially non-empty, and typing RETURN without editing will fetch the
1669 default name, if one is provided. Note however that this default name
1670 is not necessarily the same as initial contents inserted in the minibuffer,
1671 if the initial contents is just the default directory.
1673 If this variable is nil, the minibuffer often starts out empty. In
1674 that case you may have to explicitly fetch the next history element to
1675 request the default name; typing RETURN without editing will leave
1676 the minibuffer empty.
1678 For some commands, exiting with an empty minibuffer has a special meaning,
1679 such as making the current buffer visit no file in the case of
1680 `set-visited-file-name'."
1681 :group 'minibuffer
1682 :type 'boolean)
1684 ;; Not always defined, but only called if next-read-file-uses-dialog-p says so.
1685 (declare-function x-file-dialog "xfns.c"
1686 (prompt dir &optional default-filename mustmatch only-dir-p))
1688 (defun read-file-name--defaults (&optional dir initial)
1689 (let ((default
1690 (cond
1691 ;; With non-nil `initial', use `dir' as the first default.
1692 ;; Essentially, this mean reversing the normal order of the
1693 ;; current directory name and the current file name, i.e.
1694 ;; 1. with normal file reading:
1695 ;; 1.1. initial input is the current directory
1696 ;; 1.2. the first default is the current file name
1697 ;; 2. with non-nil `initial' (e.g. for `find-alternate-file'):
1698 ;; 2.2. initial input is the current file name
1699 ;; 2.1. the first default is the current directory
1700 (initial (abbreviate-file-name dir))
1701 ;; In file buffers, try to get the current file name
1702 (buffer-file-name
1703 (abbreviate-file-name buffer-file-name))))
1704 (file-name-at-point
1705 (run-hook-with-args-until-success 'file-name-at-point-functions)))
1706 (when file-name-at-point
1707 (setq default (delete-dups
1708 (delete "" (delq nil (list file-name-at-point default))))))
1709 ;; Append new defaults to the end of existing `minibuffer-default'.
1710 (append
1711 (if (listp minibuffer-default) minibuffer-default (list minibuffer-default))
1712 (if (listp default) default (list default)))))
1714 (defun read-file-name (prompt &optional dir default-filename mustmatch initial predicate)
1715 "Read file name, prompting with PROMPT and completing in directory DIR.
1716 Value is not expanded---you must call `expand-file-name' yourself.
1717 Default name to DEFAULT-FILENAME if user exits the minibuffer with
1718 the same non-empty string that was inserted by this function.
1719 (If DEFAULT-FILENAME is omitted, the visited file name is used,
1720 except that if INITIAL is specified, that combined with DIR is used.
1721 If DEFAULT-FILENAME is a list of file names, the first file name is used.)
1722 If the user exits with an empty minibuffer, this function returns
1723 an empty string. (This can only happen if the user erased the
1724 pre-inserted contents or if `insert-default-directory' is nil.)
1726 Fourth arg MUSTMATCH can take the following values:
1727 - nil means that the user can exit with any input.
1728 - t means that the user is not allowed to exit unless
1729 the input is (or completes to) an existing file.
1730 - `confirm' means that the user can exit with any input, but she needs
1731 to confirm her choice if the input is not an existing file.
1732 - `confirm-after-completion' means that the user can exit with any
1733 input, but she needs to confirm her choice if she called
1734 `minibuffer-complete' right before `minibuffer-complete-and-exit'
1735 and the input is not an existing file.
1736 - anything else behaves like t except that typing RET does not exit if it
1737 does non-null completion.
1739 Fifth arg INITIAL specifies text to start with.
1741 If optional sixth arg PREDICATE is non-nil, possible completions and
1742 the resulting file name must satisfy (funcall PREDICATE NAME).
1743 DIR should be an absolute directory name. It defaults to the value of
1744 `default-directory'.
1746 If this command was invoked with the mouse, use a graphical file
1747 dialog if `use-dialog-box' is non-nil, and the window system or X
1748 toolkit in use provides a file dialog box, and DIR is not a
1749 remote file. For graphical file dialogs, any the special values
1750 of MUSTMATCH; `confirm' and `confirm-after-completion' are
1751 treated as equivalent to nil.
1753 See also `read-file-name-completion-ignore-case'
1754 and `read-file-name-function'."
1755 (funcall (or read-file-name-function #'read-file-name-default)
1756 prompt dir default-filename mustmatch initial predicate))
1758 (defun read-file-name-default (prompt &optional dir default-filename mustmatch initial predicate)
1759 "Default method for reading file names.
1760 See `read-file-name' for the meaning of the arguments."
1761 (unless dir (setq dir default-directory))
1762 (unless (file-name-absolute-p dir) (setq dir (expand-file-name dir)))
1763 (unless default-filename
1764 (setq default-filename (if initial (expand-file-name initial dir)
1765 buffer-file-name)))
1766 ;; If dir starts with user's homedir, change that to ~.
1767 (setq dir (abbreviate-file-name dir))
1768 ;; Likewise for default-filename.
1769 (if default-filename
1770 (setq default-filename
1771 (if (consp default-filename)
1772 (mapcar 'abbreviate-file-name default-filename)
1773 (abbreviate-file-name default-filename))))
1774 (let ((insdef (cond
1775 ((and insert-default-directory (stringp dir))
1776 (if initial
1777 (cons (minibuffer--double-dollars (concat dir initial))
1778 (length (minibuffer--double-dollars dir)))
1779 (minibuffer--double-dollars dir)))
1780 (initial (cons (minibuffer--double-dollars initial) 0)))))
1782 (let ((completion-ignore-case read-file-name-completion-ignore-case)
1783 (minibuffer-completing-file-name t)
1784 (pred (or predicate 'file-exists-p))
1785 (add-to-history nil))
1787 (let* ((val
1788 (if (or (not (next-read-file-uses-dialog-p))
1789 ;; Graphical file dialogs can't handle remote
1790 ;; files (Bug#99).
1791 (file-remote-p dir))
1792 ;; We used to pass `dir' to `read-file-name-internal' by
1793 ;; abusing the `predicate' argument. It's better to
1794 ;; just use `default-directory', but in order to avoid
1795 ;; changing `default-directory' in the current buffer,
1796 ;; we don't let-bind it.
1797 (let ((dir (file-name-as-directory
1798 (expand-file-name dir))))
1799 (minibuffer-with-setup-hook
1800 (lambda ()
1801 (setq default-directory dir)
1802 ;; When the first default in `minibuffer-default'
1803 ;; duplicates initial input `insdef',
1804 ;; reset `minibuffer-default' to nil.
1805 (when (equal (or (car-safe insdef) insdef)
1806 (or (car-safe minibuffer-default)
1807 minibuffer-default))
1808 (setq minibuffer-default
1809 (cdr-safe minibuffer-default)))
1810 ;; On the first request on `M-n' fill
1811 ;; `minibuffer-default' with a list of defaults
1812 ;; relevant for file-name reading.
1813 (set (make-local-variable 'minibuffer-default-add-function)
1814 (lambda ()
1815 (with-current-buffer
1816 (window-buffer (minibuffer-selected-window))
1817 (read-file-name--defaults dir initial)))))
1818 (completing-read prompt 'read-file-name-internal
1819 pred mustmatch insdef
1820 'file-name-history default-filename)))
1821 ;; If DEFAULT-FILENAME not supplied and DIR contains
1822 ;; a file name, split it.
1823 (let ((file (file-name-nondirectory dir))
1824 ;; When using a dialog, revert to nil and non-nil
1825 ;; interpretation of mustmatch. confirm options
1826 ;; need to be interpreted as nil, otherwise
1827 ;; it is impossible to create new files using
1828 ;; dialogs with the default settings.
1829 (dialog-mustmatch
1830 (not (memq mustmatch
1831 '(nil confirm confirm-after-completion)))))
1832 (when (and (not default-filename)
1833 (not (zerop (length file))))
1834 (setq default-filename file)
1835 (setq dir (file-name-directory dir)))
1836 (when default-filename
1837 (setq default-filename
1838 (expand-file-name (if (consp default-filename)
1839 (car default-filename)
1840 default-filename)
1841 dir)))
1842 (setq add-to-history t)
1843 (x-file-dialog prompt dir default-filename
1844 dialog-mustmatch
1845 (eq predicate 'file-directory-p)))))
1847 (replace-in-history (eq (car-safe file-name-history) val)))
1848 ;; If completing-read returned the inserted default string itself
1849 ;; (rather than a new string with the same contents),
1850 ;; it has to mean that the user typed RET with the minibuffer empty.
1851 ;; In that case, we really want to return ""
1852 ;; so that commands such as set-visited-file-name can distinguish.
1853 (when (consp default-filename)
1854 (setq default-filename (car default-filename)))
1855 (when (eq val default-filename)
1856 ;; In this case, completing-read has not added an element
1857 ;; to the history. Maybe we should.
1858 (if (not replace-in-history)
1859 (setq add-to-history t))
1860 (setq val ""))
1861 (unless val (error "No file name specified"))
1863 (if (and default-filename
1864 (string-equal val (if (consp insdef) (car insdef) insdef)))
1865 (setq val default-filename))
1866 (setq val (substitute-in-file-name val))
1868 (if replace-in-history
1869 ;; Replace what Fcompleting_read added to the history
1870 ;; with what we will actually return. As an exception,
1871 ;; if that's the same as the second item in
1872 ;; file-name-history, it's really a repeat (Bug#4657).
1873 (let ((val1 (minibuffer--double-dollars val)))
1874 (if history-delete-duplicates
1875 (setcdr file-name-history
1876 (delete val1 (cdr file-name-history))))
1877 (if (string= val1 (cadr file-name-history))
1878 (pop file-name-history)
1879 (setcar file-name-history val1)))
1880 (if add-to-history
1881 ;; Add the value to the history--but not if it matches
1882 ;; the last value already there.
1883 (let ((val1 (minibuffer--double-dollars val)))
1884 (unless (and (consp file-name-history)
1885 (equal (car file-name-history) val1))
1886 (setq file-name-history
1887 (cons val1
1888 (if history-delete-duplicates
1889 (delete val1 file-name-history)
1890 file-name-history)))))))
1891 val))))
1893 (defun internal-complete-buffer-except (&optional buffer)
1894 "Perform completion on all buffers excluding BUFFER.
1895 BUFFER nil or omitted means use the current buffer.
1896 Like `internal-complete-buffer', but removes BUFFER from the completion list."
1897 (let ((except (if (stringp buffer) buffer (buffer-name buffer))))
1898 (apply-partially 'completion-table-with-predicate
1899 'internal-complete-buffer
1900 (lambda (name)
1901 (not (equal (if (consp name) (car name) name) except)))
1902 nil)))
1904 ;;; Old-style completion, used in Emacs-21 and Emacs-22.
1906 (defun completion-emacs21-try-completion (string table pred _point)
1907 (let ((completion (try-completion string table pred)))
1908 (if (stringp completion)
1909 (cons completion (length completion))
1910 completion)))
1912 (defun completion-emacs21-all-completions (string table pred _point)
1913 (completion-hilit-commonality
1914 (all-completions string table pred)
1915 (length string)
1916 (car (completion-boundaries string table pred ""))))
1918 (defun completion-emacs22-try-completion (string table pred point)
1919 (let ((suffix (substring string point))
1920 (completion (try-completion (substring string 0 point) table pred)))
1921 (if (not (stringp completion))
1922 completion
1923 ;; Merge a trailing / in completion with a / after point.
1924 ;; We used to only do it for word completion, but it seems to make
1925 ;; sense for all completions.
1926 ;; Actually, claiming this feature was part of Emacs-22 completion
1927 ;; is pushing it a bit: it was only done in minibuffer-completion-word,
1928 ;; which was (by default) not bound during file completion, where such
1929 ;; slashes are most likely to occur.
1930 (if (and (not (zerop (length completion)))
1931 (eq ?/ (aref completion (1- (length completion))))
1932 (not (zerop (length suffix)))
1933 (eq ?/ (aref suffix 0)))
1934 ;; This leaves point after the / .
1935 (setq suffix (substring suffix 1)))
1936 (cons (concat completion suffix) (length completion)))))
1938 (defun completion-emacs22-all-completions (string table pred point)
1939 (let ((beforepoint (substring string 0 point)))
1940 (completion-hilit-commonality
1941 (all-completions beforepoint table pred)
1942 point
1943 (car (completion-boundaries beforepoint table pred "")))))
1945 ;;; Basic completion.
1947 (defun completion--merge-suffix (completion point suffix)
1948 "Merge end of COMPLETION with beginning of SUFFIX.
1949 Simple generalization of the \"merge trailing /\" done in Emacs-22.
1950 Return the new suffix."
1951 (if (and (not (zerop (length suffix)))
1952 (string-match "\\(.+\\)\n\\1" (concat completion "\n" suffix)
1953 ;; Make sure we don't compress things to less
1954 ;; than we started with.
1955 point)
1956 ;; Just make sure we didn't match some other \n.
1957 (eq (match-end 1) (length completion)))
1958 (substring suffix (- (match-end 1) (match-beginning 1)))
1959 ;; Nothing to merge.
1960 suffix))
1962 (defun completion-basic--pattern (beforepoint afterpoint bounds)
1963 (delete
1964 "" (list (substring beforepoint (car bounds))
1965 'point
1966 (substring afterpoint 0 (cdr bounds)))))
1968 (defun completion-basic-try-completion (string table pred point)
1969 (let* ((beforepoint (substring string 0 point))
1970 (afterpoint (substring string point))
1971 (bounds (completion-boundaries beforepoint table pred afterpoint)))
1972 (if (zerop (cdr bounds))
1973 ;; `try-completion' may return a subtly different result
1974 ;; than `all+merge', so try to use it whenever possible.
1975 (let ((completion (try-completion beforepoint table pred)))
1976 (if (not (stringp completion))
1977 completion
1978 (cons
1979 (concat completion
1980 (completion--merge-suffix completion point afterpoint))
1981 (length completion))))
1982 (let* ((suffix (substring afterpoint (cdr bounds)))
1983 (prefix (substring beforepoint 0 (car bounds)))
1984 (pattern (delete
1985 "" (list (substring beforepoint (car bounds))
1986 'point
1987 (substring afterpoint 0 (cdr bounds)))))
1988 (all (completion-pcm--all-completions prefix pattern table pred)))
1989 (if minibuffer-completing-file-name
1990 (setq all (completion-pcm--filename-try-filter all)))
1991 (completion-pcm--merge-try pattern all prefix suffix)))))
1993 (defun completion-basic-all-completions (string table pred point)
1994 (let* ((beforepoint (substring string 0 point))
1995 (afterpoint (substring string point))
1996 (bounds (completion-boundaries beforepoint table pred afterpoint))
1997 ;; (suffix (substring afterpoint (cdr bounds)))
1998 (prefix (substring beforepoint 0 (car bounds)))
1999 (pattern (delete
2000 "" (list (substring beforepoint (car bounds))
2001 'point
2002 (substring afterpoint 0 (cdr bounds)))))
2003 (all (completion-pcm--all-completions prefix pattern table pred)))
2004 (completion-hilit-commonality all point (car bounds))))
2006 ;;; Partial-completion-mode style completion.
2008 (defvar completion-pcm--delim-wild-regex nil
2009 "Regular expression matching delimiters controlling the partial-completion.
2010 Typically, this regular expression simply matches a delimiter, meaning
2011 that completion can add something at (match-beginning 0), but if it has
2012 a submatch 1, then completion can add something at (match-end 1).
2013 This is used when the delimiter needs to be of size zero (e.g. the transition
2014 from lowercase to uppercase characters).")
2016 (defun completion-pcm--prepare-delim-re (delims)
2017 (setq completion-pcm--delim-wild-regex (concat "[" delims "*]")))
2019 (defcustom completion-pcm-word-delimiters "-_./: "
2020 "A string of characters treated as word delimiters for completion.
2021 Some arcane rules:
2022 If `]' is in this string, it must come first.
2023 If `^' is in this string, it must not come first.
2024 If `-' is in this string, it must come first or right after `]'.
2025 In other words, if S is this string, then `[S]' must be a valid Emacs regular
2026 expression (not containing character ranges like `a-z')."
2027 :set (lambda (symbol value)
2028 (set-default symbol value)
2029 ;; Refresh other vars.
2030 (completion-pcm--prepare-delim-re value))
2031 :initialize 'custom-initialize-reset
2032 :group 'minibuffer
2033 :type 'string)
2035 (defcustom completion-pcm-complete-word-inserts-delimiters nil
2036 "Treat the SPC or - inserted by `minibuffer-complete-word' as delimiters.
2037 Those chars are treated as delimiters iff this variable is non-nil.
2038 I.e. if non-nil, M-x SPC will just insert a \"-\" in the minibuffer, whereas
2039 if nil, it will list all possible commands in *Completions* because none of
2040 the commands start with a \"-\" or a SPC."
2041 :type 'boolean)
2043 (defun completion-pcm--pattern-trivial-p (pattern)
2044 (and (stringp (car pattern))
2045 ;; It can be followed by `point' and "" and still be trivial.
2046 (let ((trivial t))
2047 (dolist (elem (cdr pattern))
2048 (unless (member elem '(point ""))
2049 (setq trivial nil)))
2050 trivial)))
2052 (defun completion-pcm--string->pattern (string &optional point)
2053 "Split STRING into a pattern.
2054 A pattern is a list where each element is either a string
2055 or a symbol chosen among `any', `star', `point', `prefix'."
2056 (if (and point (< point (length string)))
2057 (let ((prefix (substring string 0 point))
2058 (suffix (substring string point)))
2059 (append (completion-pcm--string->pattern prefix)
2060 '(point)
2061 (completion-pcm--string->pattern suffix)))
2062 (let* ((pattern nil)
2063 (p 0)
2064 (p0 p))
2066 (while (and (setq p (string-match completion-pcm--delim-wild-regex
2067 string p))
2068 (or completion-pcm-complete-word-inserts-delimiters
2069 ;; If the char was added by minibuffer-complete-word,
2070 ;; then don't treat it as a delimiter, otherwise
2071 ;; "M-x SPC" ends up inserting a "-" rather than listing
2072 ;; all completions.
2073 (not (get-text-property p 'completion-try-word string))))
2074 ;; Usually, completion-pcm--delim-wild-regex matches a delimiter,
2075 ;; meaning that something can be added *before* it, but it can also
2076 ;; match a prefix and postfix, in which case something can be added
2077 ;; in-between (e.g. match [[:lower:]][[:upper:]]).
2078 ;; This is determined by the presence of a submatch-1 which delimits
2079 ;; the prefix.
2080 (if (match-end 1) (setq p (match-end 1)))
2081 (push (substring string p0 p) pattern)
2082 (if (eq (aref string p) ?*)
2083 (progn
2084 (push 'star pattern)
2085 (setq p0 (1+ p)))
2086 (push 'any pattern)
2087 (setq p0 p))
2088 (incf p))
2090 ;; An empty string might be erroneously added at the beginning.
2091 ;; It should be avoided properly, but it's so easy to remove it here.
2092 (delete "" (nreverse (cons (substring string p0) pattern))))))
2094 (defun completion-pcm--pattern->regex (pattern &optional group)
2095 (let ((re
2096 (concat "\\`"
2097 (mapconcat
2098 (lambda (x)
2099 (cond
2100 ((stringp x) (regexp-quote x))
2101 ((if (consp group) (memq x group) group) "\\(.*?\\)")
2102 (t ".*?")))
2103 pattern
2104 ""))))
2105 ;; Avoid pathological backtracking.
2106 (while (string-match "\\.\\*\\?\\(?:\\\\[()]\\)*\\(\\.\\*\\?\\)" re)
2107 (setq re (replace-match "" t t re 1)))
2108 re))
2110 (defun completion-pcm--all-completions (prefix pattern table pred)
2111 "Find all completions for PATTERN in TABLE obeying PRED.
2112 PATTERN is as returned by `completion-pcm--string->pattern'."
2113 ;; (assert (= (car (completion-boundaries prefix table pred ""))
2114 ;; (length prefix)))
2115 ;; Find an initial list of possible completions.
2116 (if (completion-pcm--pattern-trivial-p pattern)
2118 ;; Minibuffer contains no delimiters -- simple case!
2119 (all-completions (concat prefix (car pattern)) table pred)
2121 ;; Use all-completions to do an initial cull. This is a big win,
2122 ;; since all-completions is written in C!
2123 (let* (;; Convert search pattern to a standard regular expression.
2124 (regex (completion-pcm--pattern->regex pattern))
2125 (case-fold-search completion-ignore-case)
2126 (completion-regexp-list (cons regex completion-regexp-list))
2127 (compl (all-completions
2128 (concat prefix (if (stringp (car pattern)) (car pattern) ""))
2129 table pred)))
2130 (if (not (functionp table))
2131 ;; The internal functions already obeyed completion-regexp-list.
2132 compl
2133 (let ((poss ()))
2134 (dolist (c compl)
2135 (when (string-match-p regex c) (push c poss)))
2136 poss)))))
2138 (defun completion-pcm--hilit-commonality (pattern completions)
2139 (when completions
2140 (let* ((re (completion-pcm--pattern->regex pattern '(point)))
2141 (case-fold-search completion-ignore-case))
2142 (mapcar
2143 (lambda (str)
2144 ;; Don't modify the string itself.
2145 (setq str (copy-sequence str))
2146 (unless (string-match re str)
2147 (error "Internal error: %s does not match %s" re str))
2148 (let ((pos (or (match-beginning 1) (match-end 0))))
2149 (put-text-property 0 pos
2150 'font-lock-face 'completions-common-part
2151 str)
2152 (if (> (length str) pos)
2153 (put-text-property pos (1+ pos)
2154 'font-lock-face 'completions-first-difference
2155 str)))
2156 str)
2157 completions))))
2159 (defun completion-pcm--find-all-completions (string table pred point
2160 &optional filter)
2161 "Find all completions for STRING at POINT in TABLE, satisfying PRED.
2162 POINT is a position inside STRING.
2163 FILTER is a function applied to the return value, that can be used, e.g. to
2164 filter out additional entries (because TABLE migth not obey PRED)."
2165 (unless filter (setq filter 'identity))
2166 (let* ((beforepoint (substring string 0 point))
2167 (afterpoint (substring string point))
2168 (bounds (completion-boundaries beforepoint table pred afterpoint))
2169 (prefix (substring beforepoint 0 (car bounds)))
2170 (suffix (substring afterpoint (cdr bounds)))
2171 firsterror)
2172 (setq string (substring string (car bounds) (+ point (cdr bounds))))
2173 (let* ((relpoint (- point (car bounds)))
2174 (pattern (completion-pcm--string->pattern string relpoint))
2175 (all (condition-case err
2176 (funcall filter
2177 (completion-pcm--all-completions
2178 prefix pattern table pred))
2179 (error (unless firsterror (setq firsterror err)) nil))))
2180 (when (and (null all)
2181 (> (car bounds) 0)
2182 (null (ignore-errors (try-completion prefix table pred))))
2183 ;; The prefix has no completions at all, so we should try and fix
2184 ;; that first.
2185 (let ((substring (substring prefix 0 -1)))
2186 (destructuring-bind (subpat suball subprefix _subsuffix)
2187 (completion-pcm--find-all-completions
2188 substring table pred (length substring) filter)
2189 (let ((sep (aref prefix (1- (length prefix))))
2190 ;; Text that goes between the new submatches and the
2191 ;; completion substring.
2192 (between nil))
2193 ;; Eliminate submatches that don't end with the separator.
2194 (dolist (submatch (prog1 suball (setq suball ())))
2195 (when (eq sep (aref submatch (1- (length submatch))))
2196 (push submatch suball)))
2197 (when suball
2198 ;; Update the boundaries and corresponding pattern.
2199 ;; We assume that all submatches result in the same boundaries
2200 ;; since we wouldn't know how to merge them otherwise anyway.
2201 ;; FIXME: COMPLETE REWRITE!!!
2202 (let* ((newbeforepoint
2203 (concat subprefix (car suball)
2204 (substring string 0 relpoint)))
2205 (leftbound (+ (length subprefix) (length (car suball))))
2206 (newbounds (completion-boundaries
2207 newbeforepoint table pred afterpoint)))
2208 (unless (or (and (eq (cdr bounds) (cdr newbounds))
2209 (eq (car newbounds) leftbound))
2210 ;; Refuse new boundaries if they step over
2211 ;; the submatch.
2212 (< (car newbounds) leftbound))
2213 ;; The new completed prefix does change the boundaries
2214 ;; of the completed substring.
2215 (setq suffix (substring afterpoint (cdr newbounds)))
2216 (setq string
2217 (concat (substring newbeforepoint (car newbounds))
2218 (substring afterpoint 0 (cdr newbounds))))
2219 (setq between (substring newbeforepoint leftbound
2220 (car newbounds)))
2221 (setq pattern (completion-pcm--string->pattern
2222 string
2223 (- (length newbeforepoint)
2224 (car newbounds)))))
2225 (dolist (submatch suball)
2226 (setq all (nconc (mapcar
2227 (lambda (s) (concat submatch between s))
2228 (funcall filter
2229 (completion-pcm--all-completions
2230 (concat subprefix submatch between)
2231 pattern table pred)))
2232 all)))
2233 ;; FIXME: This can come in handy for try-completion,
2234 ;; but isn't right for all-completions, since it lists
2235 ;; invalid completions.
2236 ;; (unless all
2237 ;; ;; Even though we found expansions in the prefix, none
2238 ;; ;; leads to a valid completion.
2239 ;; ;; Let's keep the expansions, tho.
2240 ;; (dolist (submatch suball)
2241 ;; (push (concat submatch between newsubstring) all)))
2243 (setq pattern (append subpat (list 'any (string sep))
2244 (if between (list between)) pattern))
2245 (setq prefix subprefix)))))
2246 (if (and (null all) firsterror)
2247 (signal (car firsterror) (cdr firsterror))
2248 (list pattern all prefix suffix)))))
2250 (defun completion-pcm-all-completions (string table pred point)
2251 (destructuring-bind (pattern all &optional prefix _suffix)
2252 (completion-pcm--find-all-completions string table pred point)
2253 (when all
2254 (nconc (completion-pcm--hilit-commonality pattern all)
2255 (length prefix)))))
2257 (defun completion--sreverse (str)
2258 "Like `reverse' but for a string STR rather than a list."
2259 (apply 'string (nreverse (mapcar 'identity str))))
2261 (defun completion--common-suffix (strs)
2262 "Return the common suffix of the strings STRS."
2263 (completion--sreverse
2264 (try-completion
2266 (mapcar 'completion--sreverse strs))))
2268 (defun completion-pcm--merge-completions (strs pattern)
2269 "Extract the commonality in STRS, with the help of PATTERN."
2270 ;; When completing while ignoring case, we want to try and avoid
2271 ;; completing "fo" to "foO" when completing against "FOO" (bug#4219).
2272 ;; So we try and make sure that the string we return is all made up
2273 ;; of text from the completions rather than part from the
2274 ;; completions and part from the input.
2275 ;; FIXME: This reduces the problems of inconsistent capitalization
2276 ;; but it doesn't fully fix it: we may still end up completing
2277 ;; "fo-ba" to "foo-BAR" or "FOO-bar" when completing against
2278 ;; '("foo-barr" "FOO-BARD").
2279 (cond
2280 ((null (cdr strs)) (list (car strs)))
2282 (let ((re (completion-pcm--pattern->regex pattern 'group))
2283 (ccs ())) ;Chopped completions.
2285 ;; First chop each string into the parts corresponding to each
2286 ;; non-constant element of `pattern', using regexp-matching.
2287 (let ((case-fold-search completion-ignore-case))
2288 (dolist (str strs)
2289 (unless (string-match re str)
2290 (error "Internal error: %s doesn't match %s" str re))
2291 (let ((chopped ())
2292 (last 0)
2293 (i 1)
2294 next)
2295 (while (setq next (match-end i))
2296 (push (substring str last next) chopped)
2297 (setq last next)
2298 (setq i (1+ i)))
2299 ;; Add the text corresponding to the implicit trailing `any'.
2300 (push (substring str last) chopped)
2301 (push (nreverse chopped) ccs))))
2303 ;; Then for each of those non-constant elements, extract the
2304 ;; commonality between them.
2305 (let ((res ())
2306 (fixed ""))
2307 ;; Make the implicit trailing `any' explicit.
2308 (dolist (elem (append pattern '(any)))
2309 (if (stringp elem)
2310 (setq fixed (concat fixed elem))
2311 (let ((comps ()))
2312 (dolist (cc (prog1 ccs (setq ccs nil)))
2313 (push (car cc) comps)
2314 (push (cdr cc) ccs))
2315 ;; Might improve the likelihood to avoid choosing
2316 ;; different capitalizations in different parts.
2317 ;; In practice, it doesn't seem to make any difference.
2318 (setq ccs (nreverse ccs))
2319 (let* ((prefix (try-completion fixed comps))
2320 (unique (or (and (eq prefix t) (setq prefix fixed))
2321 (eq t (try-completion prefix comps)))))
2322 (unless (equal prefix "") (push prefix res))
2323 ;; If there's only one completion, `elem' is not useful
2324 ;; any more: it can only match the empty string.
2325 ;; FIXME: in some cases, it may be necessary to turn an
2326 ;; `any' into a `star' because the surrounding context has
2327 ;; changed such that string->pattern wouldn't add an `any'
2328 ;; here any more.
2329 (unless unique
2330 (push elem res)
2331 (when (memq elem '(star point prefix))
2332 ;; Extract common suffix additionally to common prefix.
2333 ;; Only do it for `point', `star', and `prefix' since for
2334 ;; `any' it could lead to a merged completion that
2335 ;; doesn't itself match the candidates.
2336 (let ((suffix (completion--common-suffix comps)))
2337 (assert (stringp suffix))
2338 (unless (equal suffix "")
2339 (push suffix res)))))
2340 (setq fixed "")))))
2341 ;; We return it in reverse order.
2342 res)))))
2344 (defun completion-pcm--pattern->string (pattern)
2345 (mapconcat (lambda (x) (cond
2346 ((stringp x) x)
2347 ((eq x 'star) "*")
2348 (t ""))) ;any, point, prefix.
2349 pattern
2350 ""))
2352 ;; We want to provide the functionality of `try', but we use `all'
2353 ;; and then merge it. In most cases, this works perfectly, but
2354 ;; if the completion table doesn't consider the same completions in
2355 ;; `try' as in `all', then we have a problem. The most common such
2356 ;; case is for filename completion where completion-ignored-extensions
2357 ;; is only obeyed by the `try' code. We paper over the difference
2358 ;; here. Note that it is not quite right either: if the completion
2359 ;; table uses completion-table-in-turn, this filtering may take place
2360 ;; too late to correctly fallback from the first to the
2361 ;; second alternative.
2362 (defun completion-pcm--filename-try-filter (all)
2363 "Filter to adjust `all' file completion to the behavior of `try'."
2364 (when all
2365 (let ((try ())
2366 (re (concat "\\(?:\\`\\.\\.?/\\|"
2367 (regexp-opt completion-ignored-extensions)
2368 "\\)\\'")))
2369 (dolist (f all)
2370 (unless (string-match-p re f) (push f try)))
2371 (or try all))))
2374 (defun completion-pcm--merge-try (pattern all prefix suffix)
2375 (cond
2376 ((not (consp all)) all)
2377 ((and (not (consp (cdr all))) ;Only one completion.
2378 ;; Ignore completion-ignore-case here.
2379 (equal (completion-pcm--pattern->string pattern) (car all)))
2382 (let* ((mergedpat (completion-pcm--merge-completions all pattern))
2383 ;; `mergedpat' is in reverse order. Place new point (by
2384 ;; order of preference) either at the old point, or at
2385 ;; the last place where there's something to choose, or
2386 ;; at the very end.
2387 (pointpat (or (memq 'point mergedpat)
2388 (memq 'any mergedpat)
2389 (memq 'star mergedpat)
2390 ;; Not `prefix'.
2391 mergedpat))
2392 ;; New pos from the start.
2393 (newpos (length (completion-pcm--pattern->string pointpat)))
2394 ;; Do it afterwards because it changes `pointpat' by sideeffect.
2395 (merged (completion-pcm--pattern->string (nreverse mergedpat))))
2397 (setq suffix (completion--merge-suffix merged newpos suffix))
2398 (cons (concat prefix merged suffix) (+ newpos (length prefix)))))))
2400 (defun completion-pcm-try-completion (string table pred point)
2401 (destructuring-bind (pattern all prefix suffix)
2402 (completion-pcm--find-all-completions
2403 string table pred point
2404 (if minibuffer-completing-file-name
2405 'completion-pcm--filename-try-filter))
2406 (completion-pcm--merge-try pattern all prefix suffix)))
2408 ;;; Substring completion
2409 ;; Mostly derived from the code of `basic' completion.
2411 (defun completion-substring--all-completions (string table pred point)
2412 (let* ((beforepoint (substring string 0 point))
2413 (afterpoint (substring string point))
2414 (bounds (completion-boundaries beforepoint table pred afterpoint))
2415 (suffix (substring afterpoint (cdr bounds)))
2416 (prefix (substring beforepoint 0 (car bounds)))
2417 (basic-pattern (completion-basic--pattern
2418 beforepoint afterpoint bounds))
2419 (pattern (if (not (stringp (car basic-pattern)))
2420 basic-pattern
2421 (cons 'prefix basic-pattern)))
2422 (all (completion-pcm--all-completions prefix pattern table pred)))
2423 (list all pattern prefix suffix (car bounds))))
2425 (defun completion-substring-try-completion (string table pred point)
2426 (destructuring-bind (all pattern prefix suffix _carbounds)
2427 (completion-substring--all-completions string table pred point)
2428 (if minibuffer-completing-file-name
2429 (setq all (completion-pcm--filename-try-filter all)))
2430 (completion-pcm--merge-try pattern all prefix suffix)))
2432 (defun completion-substring-all-completions (string table pred point)
2433 (destructuring-bind (all pattern prefix _suffix _carbounds)
2434 (completion-substring--all-completions string table pred point)
2435 (when all
2436 (nconc (completion-pcm--hilit-commonality pattern all)
2437 (length prefix)))))
2439 ;; Initials completion
2440 ;; Complete /ums to /usr/monnier/src or lch to list-command-history.
2442 (defun completion-initials-expand (str table pred)
2443 (let ((bounds (completion-boundaries str table pred "")))
2444 (unless (or (zerop (length str))
2445 ;; Only check within the boundaries, since the
2446 ;; boundary char (e.g. /) might be in delim-regexp.
2447 (string-match completion-pcm--delim-wild-regex str
2448 (car bounds)))
2449 (if (zerop (car bounds))
2450 (mapconcat 'string str "-")
2451 ;; If there's a boundary, it's trickier. The main use-case
2452 ;; we consider here is file-name completion. We'd like
2453 ;; to expand ~/eee to ~/e/e/e and /eee to /e/e/e.
2454 ;; But at the same time, we don't want /usr/share/ae to expand
2455 ;; to /usr/share/a/e just because we mistyped "ae" for "ar",
2456 ;; so we probably don't want initials to touch anything that
2457 ;; looks like /usr/share/foo. As a heuristic, we just check that
2458 ;; the text before the boundary char is at most 1 char.
2459 ;; This allows both ~/eee and /eee and not much more.
2460 ;; FIXME: It sadly also disallows the use of ~/eee when that's
2461 ;; embedded within something else (e.g. "(~/eee" in Info node
2462 ;; completion or "ancestor:/eee" in bzr-revision completion).
2463 (when (< (car bounds) 3)
2464 (let ((sep (substring str (1- (car bounds)) (car bounds))))
2465 ;; FIXME: the above string-match checks the whole string, whereas
2466 ;; we end up only caring about the after-boundary part.
2467 (concat (substring str 0 (car bounds))
2468 (mapconcat 'string (substring str (car bounds)) sep))))))))
2470 (defun completion-initials-all-completions (string table pred _point)
2471 (let ((newstr (completion-initials-expand string table pred)))
2472 (when newstr
2473 (completion-pcm-all-completions newstr table pred (length newstr)))))
2475 (defun completion-initials-try-completion (string table pred _point)
2476 (let ((newstr (completion-initials-expand string table pred)))
2477 (when newstr
2478 (completion-pcm-try-completion newstr table pred (length newstr)))))
2481 ;; Miscellaneous
2483 (defun minibuffer-insert-file-name-at-point ()
2484 "Get a file name at point in original buffer and insert it to minibuffer."
2485 (interactive)
2486 (let ((file-name-at-point
2487 (with-current-buffer (window-buffer (minibuffer-selected-window))
2488 (run-hook-with-args-until-success 'file-name-at-point-functions))))
2489 (when file-name-at-point
2490 (insert file-name-at-point))))
2492 (provide 'minibuffer)
2494 ;;; minibuffer.el ends here