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