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