1 ;;; minibuffer.el --- Minibuffer completion functions -*- lexical-binding: t -*-
3 ;; Copyright (C) 2008-2012 Free Software Foundation, Inc.
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
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/>.
25 ;; Names with "--" are for functions and variables that are meant to be for
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).
34 ;; - `metadata' in which case it should return (metadata . ALIST) where
35 ;; ALIST is the metadata of this table. See `completion-metadata'.
36 ;; Any other return value should be ignored (so we ignore values returned
37 ;; from completion tables that don't know about this new `action' form).
41 ;; - completion-all-sorted-completions list all the completions, whereas
42 ;; it should only lists the ones that `try-completion' would consider.
43 ;; E.g. it should honor completion-ignored-extensions.
44 ;; - choose-completion can't automatically figure out the boundaries
45 ;; corresponding to the displayed completions because we only
46 ;; provide the start info but not the end info in
47 ;; completion-base-position.
48 ;; - quoting is problematic. E.g. the double-dollar quoting used in
49 ;; substitute-in-file-name (and hence read-file-name-internal) bumps
51 ;; - choose-completion doesn't know how to quote the text it inserts.
52 ;; E.g. it fails to double the dollars in file-name completion, or
53 ;; to backslash-escape spaces and other chars in comint completion.
54 ;; - when completing ~/tmp/fo$$o, the highlighting in *Completions*
55 ;; is off by one position.
56 ;; - all code like PCM which relies on all-completions to match
57 ;; its argument gets confused because all-completions returns unquoted
58 ;; texts (as desired for *Completions* output).
59 ;; - C-x C-f ~/*/sr ? should not list "~/./src".
60 ;; - minibuffer-force-complete completes ~/src/emacs/t<!>/lisp/minibuffer.el
61 ;; to ~/src/emacs/trunk/ and throws away lisp/minibuffer.el.
65 ;; - for M-x, cycle-sort commands that have no key binding first.
66 ;; - Make things like icomplete-mode or lightning-completion work with
67 ;; completion-in-region-mode.
68 ;; - extend `metadata':
69 ;; - quoting/unquoting (so we can complete files names with envvars
70 ;; and backslashes, and all-completion can list names without
71 ;; quoting backslashes and dollars).
72 ;; - indicate how to turn all-completion's output into
73 ;; try-completion's output: e.g. completion-ignored-extensions.
74 ;; maybe that could be merged with the "quote" operation above.
75 ;; - indicate that `all-completions' doesn't do prefix-completion
76 ;; but just returns some list that relates in some other way to
77 ;; the provided string (as is the case in filecache.el), in which
78 ;; case partial-completion (for example) doesn't make any sense
79 ;; and neither does the completions-first-difference highlight.
80 ;; - indicate how to display the completions in *Completions* (turn
81 ;; \n into something else, add special boundaries between
82 ;; completions). E.g. when completing from the kill-ring.
84 ;; - case-sensitivity currently confuses two issues:
85 ;; - whether or not a particular completion table should be case-sensitive
86 ;; (i.e. whether strings that differ only by case are semantically
88 ;; - whether the user wants completion to pay attention to case.
89 ;; e.g. we may want to make it possible for the user to say "first try
90 ;; completion case-sensitively, and if that fails, try to ignore case".
92 ;; - add support for ** to pcm.
93 ;; - Add vc-file-name-completion-table to read-file-name-internal.
94 ;; - A feature like completing-help.el.
98 (eval-when-compile (require 'cl
))
100 ;;; Completion table manipulation
102 ;; New completion-table operation.
103 (defun completion-boundaries (string table pred suffix
)
104 "Return the boundaries of the completions returned by TABLE for STRING.
105 STRING is the string on which completion will be performed.
106 SUFFIX is the string after point.
107 The result is of the form (START . END) where START is the position
108 in STRING of the beginning of the completion field and END is the position
109 in SUFFIX of the end of the completion field.
110 E.g. for simple completion tables, the result is always (0 . (length SUFFIX))
111 and for file names the result is the positions delimited by
112 the closest directory separators."
113 (let ((boundaries (if (functionp table
)
114 (funcall table string pred
115 (cons 'boundaries suffix
)))))
116 (if (not (eq (car-safe boundaries
) 'boundaries
))
117 (setq boundaries nil
))
118 (cons (or (cadr boundaries
) 0)
119 (or (cddr boundaries
) (length suffix
)))))
121 (defun completion-metadata (string table pred
)
122 "Return the metadata of elements to complete at the end of STRING.
123 This metadata is an alist. Currently understood keys are:
124 - `category': the kind of objects returned by `all-completions'.
125 Used by `completion-category-overrides'.
126 - `annotation-function': function to add annotations in *Completions*.
127 Takes one argument (STRING), which is a possible completion and
128 returns a string to append to STRING.
129 - `display-sort-function': function to sort entries in *Completions*.
130 Takes one argument (COMPLETIONS) and should return a new list
131 of completions. Can operate destructively.
132 - `cycle-sort-function': function to sort entries when cycling.
133 Works like `display-sort-function'.
134 The metadata of a completion table should be constant between two boundaries."
135 (let ((metadata (if (functionp table
)
136 (funcall table string pred
'metadata
))))
137 (if (eq (car-safe metadata
) 'metadata
)
141 (defun completion--field-metadata (field-start)
142 (completion-metadata (buffer-substring-no-properties field-start
(point))
143 minibuffer-completion-table
144 minibuffer-completion-predicate
))
146 (defun completion-metadata-get (metadata prop
)
147 (cdr (assq prop metadata
)))
149 (defun completion--some (fun xs
)
150 "Apply FUN to each element of XS in turn.
151 Return the first non-nil returned value.
153 (let ((firsterror nil
)
155 (while (and (not res
) xs
)
157 (setq res
(funcall fun
(pop xs
)))
158 (error (unless firsterror
(setq firsterror err
)) nil
)))
160 (if firsterror
(signal (car firsterror
) (cdr firsterror
))))))
162 (defun complete-with-action (action table string pred
)
163 "Perform completion ACTION.
164 STRING is the string to complete.
165 TABLE is the completion table.
166 PRED is a completion predicate.
167 ACTION can be one of nil, t or `lambda'."
169 ((functionp table
) (funcall table string pred action
))
170 ((eq (car-safe action
) 'boundaries
) nil
)
171 ((eq action
'metadata
) nil
)
175 ((null action
) 'try-completion
)
176 ((eq action t
) 'all-completions
)
177 (t 'test-completion
))
178 string table pred
))))
180 (defun completion-table-dynamic (fun)
181 "Use function FUN as a dynamic completion table.
182 FUN is called with one argument, the string for which completion is required,
183 and it should return an alist containing all the intended possible completions.
184 This alist may be a full list of possible completions so that FUN can ignore
185 the value of its argument. If completion is performed in the minibuffer,
186 FUN will be called in the buffer from which the minibuffer was entered.
188 The result of the `completion-table-dynamic' form is a function
189 that can be used as the COLLECTION argument to `try-completion' and
190 `all-completions'. See Info node `(elisp)Programmed Completion'."
191 (lambda (string pred action
)
192 (if (or (eq (car-safe action
) 'boundaries
) (eq action
'metadata
))
193 ;; `fun' is not supposed to return another function but a plain old
194 ;; completion table, whose boundaries are always trivial.
196 (with-current-buffer (let ((win (minibuffer-selected-window)))
197 (if (window-live-p win
) (window-buffer win
)
199 (complete-with-action action
(funcall fun string
) string pred
)))))
201 (defmacro lazy-completion-table
(var fun
)
202 "Initialize variable VAR as a lazy completion table.
203 If the completion table VAR is used for the first time (e.g., by passing VAR
204 as an argument to `try-completion'), the function FUN is called with no
205 arguments. FUN must return the completion table that will be stored in VAR.
206 If completion is requested in the minibuffer, FUN will be called in the buffer
207 from which the minibuffer was entered. The return value of
208 `lazy-completion-table' must be used to initialize the value of VAR.
210 You should give VAR a non-nil `risky-local-variable' property."
211 (declare (debug (symbolp lambda-expr
)))
212 (let ((str (make-symbol "string")))
213 `(completion-table-dynamic
215 (when (functionp ,var
)
219 (defun completion-table-case-fold (table &optional dont-fold
)
220 "Return new completion TABLE that is case insensitive.
221 If DONT-FOLD is non-nil, return a completion table that is
222 case sensitive instead."
223 (lambda (string pred action
)
224 (let ((completion-ignore-case (not dont-fold
)))
225 (complete-with-action action table string pred
))))
227 (defun completion-table-with-context (prefix table string pred action
)
228 ;; TODO: add `suffix' maybe?
230 (if (not (functionp pred
))
231 ;; Notice that `pred' may not be a function in some abusive cases.
233 ;; Predicates are called differently depending on the nature of
234 ;; the completion table :-(
236 ((vectorp table
) ;Obarray.
237 (lambda (sym) (funcall pred
(concat prefix
(symbol-name sym
)))))
238 ((hash-table-p table
)
239 (lambda (s _v
) (funcall pred
(concat prefix s
))))
241 (lambda (s) (funcall pred
(concat prefix s
))))
242 (t ;Lists and alists.
244 (funcall pred
(concat prefix
(if (consp s
) (car s
) s
)))))))))
245 (if (eq (car-safe action
) 'boundaries
)
246 (let* ((len (length prefix
))
247 (bound (completion-boundaries string table pred
(cdr action
))))
248 (list* 'boundaries
(+ (car bound
) len
) (cdr bound
)))
249 (let ((comp (complete-with-action action table string pred
)))
251 ;; In case of try-completion, add the prefix.
252 ((stringp comp
) (concat prefix comp
))
255 (defun completion-table-with-terminator (terminator table string pred action
)
256 "Construct a completion table like TABLE but with an extra TERMINATOR.
257 This is meant to be called in a curried way by first passing TERMINATOR
258 and TABLE only (via `apply-partially').
259 TABLE is a completion table, and TERMINATOR is a string appended to TABLE's
260 completion if it is complete. TERMINATOR is also used to determine the
261 completion suffix's boundary.
262 TERMINATOR can also be a cons cell (TERMINATOR . TERMINATOR-REGEXP)
263 in which case TERMINATOR-REGEXP is a regular expression whose submatch
264 number 1 should match TERMINATOR. This is used when there is a need to
265 distinguish occurrences of the TERMINATOR strings which are really terminators
266 from others (e.g. escaped). In this form, the car of TERMINATOR can also be,
267 instead of a string, a function that takes the completion and returns the
268 \"terminated\" string."
269 ;; FIXME: This implementation is not right since it only adds the terminator
270 ;; in try-completion, so any completion-style that builds the completion via
271 ;; all-completions won't get the terminator, and selecting an entry in
272 ;; *Completions* won't get the terminator added either.
274 ((eq (car-safe action
) 'boundaries
)
275 (let* ((suffix (cdr action
))
276 (bounds (completion-boundaries string table pred suffix
))
277 (terminator-regexp (if (consp terminator
)
278 (cdr terminator
) (regexp-quote terminator
)))
279 (max (and terminator-regexp
280 (string-match terminator-regexp suffix
))))
281 (list* 'boundaries
(car bounds
)
282 (min (cdr bounds
) (or max
(length suffix
))))))
284 (let ((comp (try-completion string table pred
)))
285 (if (consp terminator
) (setq terminator
(car terminator
)))
287 (if (functionp terminator
)
288 (funcall terminator string
)
289 (concat string terminator
))
290 (if (and (stringp comp
) (not (zerop (length comp
)))
291 ;; Try to avoid the second call to try-completion, since
292 ;; it may be very inefficient (because `comp' made us
293 ;; jump to a new boundary, so we complete in that
294 ;; boundary with an empty start string).
295 (let ((newbounds (completion-boundaries comp table pred
"")))
296 (< (car newbounds
) (length comp
)))
297 (eq (try-completion comp table pred
) t
))
298 (if (functionp terminator
)
299 (funcall terminator comp
)
300 (concat comp terminator
))
302 ;; completion-table-with-terminator is always used for
303 ;; "sub-completions" so it's only called if the terminator is missing,
304 ;; in which case `test-completion' should return nil.
305 ((eq action
'lambda
) nil
)
307 ;; FIXME: We generally want the `try' and `all' behaviors to be
308 ;; consistent so pcm can merge the `all' output to get the `try' output,
309 ;; but that sometimes clashes with the need for `all' output to look
310 ;; good in *Completions*.
311 ;; (mapcar (lambda (s) (concat s terminator))
312 ;; (all-completions string table pred))))
313 (complete-with-action action table string pred
))))
315 (defun completion-table-with-predicate (table pred1 strict string pred2 action
)
316 "Make a completion table equivalent to TABLE but filtered through PRED1.
317 PRED1 is a function of one argument which returns non-nil if and only if the
318 argument is an element of TABLE which should be considered for completion.
319 STRING, PRED2, and ACTION are the usual arguments to completion tables,
320 as described in `try-completion', `all-completions', and `test-completion'.
321 If STRICT is t, the predicate always applies; if nil it only applies if
322 it does not reduce the set of possible completions to nothing.
323 Note: TABLE needs to be a proper completion table which obeys predicates."
325 ((and (not strict
) (eq action
'lambda
))
326 ;; Ignore pred1 since it doesn't really have to apply anyway.
327 (test-completion string table pred2
))
329 (or (complete-with-action action table string
330 (if (not (and pred1 pred2
))
333 ;; Call `pred1' first, so that `pred2'
334 ;; really can't tell that `x' is in table.
335 (and (funcall pred1 x
) (funcall pred2 x
)))))
336 ;; If completion failed and we're not applying pred1 strictly, try
337 ;; again without pred1.
338 (and (not strict
) pred1 pred2
339 (complete-with-action action table string pred2
))))))
341 (defun completion-table-in-turn (&rest tables
)
342 "Create a completion table that tries each table in TABLES in turn."
343 ;; FIXME: the boundaries may come from TABLE1 even when the completion list
344 ;; is returned by TABLE2 (because TABLE1 returned an empty list).
345 (lambda (string pred action
)
346 (completion--some (lambda (table)
347 (complete-with-action action table string pred
))
350 ;; (defmacro complete-in-turn (a b) `(completion-table-in-turn ,a ,b))
351 ;; (defmacro dynamic-completion-table (fun) `(completion-table-dynamic ,fun))
352 (define-obsolete-function-alias
353 'complete-in-turn
'completion-table-in-turn
"23.1")
354 (define-obsolete-function-alias
355 'dynamic-completion-table
'completion-table-dynamic
"23.1")
357 ;;; Minibuffer completion
359 (defgroup minibuffer nil
360 "Controlling the behavior of the minibuffer."
361 :link
'(custom-manual "(emacs)Minibuffer")
364 (defun minibuffer-message (message &rest args
)
365 "Temporarily display MESSAGE at the end of the minibuffer.
366 The text is displayed for `minibuffer-message-timeout' seconds,
367 or until the next input event arrives, whichever comes first.
368 Enclose MESSAGE in [...] if this is not yet the case.
369 If ARGS are provided, then pass MESSAGE through `format'."
370 (if (not (minibufferp (current-buffer)))
373 (apply 'message message args
)
374 (message "%s" message
))
375 (prog1 (sit-for (or minibuffer-message-timeout
1000000))
377 ;; Clear out any old echo-area message to make way for our new thing.
379 (setq message
(if (and (null args
) (string-match-p "\\` *\\[.+\\]\\'" message
))
380 ;; Make sure we can put-text-property.
381 (copy-sequence message
)
382 (concat " [" message
"]")))
383 (when args
(setq message
(apply 'format message args
)))
384 (let ((ol (make-overlay (point-max) (point-max) nil t t
))
385 ;; A quit during sit-for normally only interrupts the sit-for,
386 ;; but since minibuffer-message is used at the end of a command,
387 ;; at a time when the command has virtually finished already, a C-g
388 ;; should really cause an abort-recursive-edit instead (i.e. as if
389 ;; the C-g had been typed at top-level). Binding inhibit-quit here
390 ;; is an attempt to get that behavior.
394 (unless (zerop (length message
))
395 ;; The current C cursor code doesn't know to use the overlay's
396 ;; marker's stickiness to figure out whether to place the cursor
397 ;; before or after the string, so let's spoon-feed it the pos.
398 (put-text-property 0 1 'cursor t message
))
399 (overlay-put ol
'after-string message
)
400 (sit-for (or minibuffer-message-timeout
1000000)))
401 (delete-overlay ol
)))))
403 (defun minibuffer-completion-contents ()
404 "Return the user input in a minibuffer before point as a string.
405 That is what completion commands operate on."
406 (buffer-substring (field-beginning) (point)))
408 (defun delete-minibuffer-contents ()
409 "Delete all user input in a minibuffer.
410 If the current buffer is not a minibuffer, erase its entire contents."
411 ;; We used to do `delete-field' here, but when file name shadowing
412 ;; is on, the field doesn't cover the entire minibuffer contents.
413 (delete-region (minibuffer-prompt-end) (point-max)))
415 (defvar completion-show-inline-help t
416 "If non-nil, print helpful inline messages during completion.")
418 (defcustom completion-auto-help t
419 "Non-nil means automatically provide help for invalid completion input.
420 If the value is t the *Completion* buffer is displayed whenever completion
421 is requested but cannot be done.
422 If the value is `lazy', the *Completions* buffer is only displayed after
423 the second failed attempt to complete."
424 :type
'(choice (const nil
) (const t
) (const lazy
))
427 (defconst completion-styles-alist
429 completion-emacs21-try-completion completion-emacs21-all-completions
430 "Simple prefix-based completion.
431 I.e. when completing \"foo_bar\" (where _ is the position of point),
432 it will consider all completions candidates matching the glob
433 pattern \"foobar*\".")
435 completion-emacs22-try-completion completion-emacs22-all-completions
436 "Prefix completion that only operates on the text before point.
437 I.e. when completing \"foo_bar\" (where _ is the position of point),
438 it will consider all completions candidates matching the glob
439 pattern \"foo*\" and will add back \"bar\" to the end of it.")
441 completion-basic-try-completion completion-basic-all-completions
442 "Completion of the prefix before point and the suffix after point.
443 I.e. when completing \"foo_bar\" (where _ is the position of point),
444 it will consider all completions candidates matching the glob
445 pattern \"foo*bar*\".")
447 completion-pcm-try-completion completion-pcm-all-completions
448 "Completion of multiple words, each one taken as a prefix.
449 I.e. when completing \"l-co_h\" (where _ is the position of point),
450 it will consider all completions candidates matching the glob
451 pattern \"l*-co*h*\".
452 Furthermore, for completions that are done step by step in subfields,
453 the method is applied to all the preceding fields that do not yet match.
454 E.g. C-x C-f /u/mo/s TAB could complete to /usr/monnier/src.
455 Additionally the user can use the char \"*\" as a glob pattern.")
457 completion-substring-try-completion completion-substring-all-completions
458 "Completion of the string taken as a substring.
459 I.e. when completing \"foo_bar\" (where _ is the position of point),
460 it will consider all completions candidates matching the glob
461 pattern \"*foo*bar*\".")
463 completion-initials-try-completion completion-initials-all-completions
464 "Completion of acronyms and initialisms.
465 E.g. can complete M-x lch to list-command-history
466 and C-x C-f ~/sew to ~/src/emacs/work."))
467 "List of available completion styles.
468 Each element has the form (NAME TRY-COMPLETION ALL-COMPLETIONS DOC):
469 where NAME is the name that should be used in `completion-styles',
470 TRY-COMPLETION is the function that does the completion (it should
471 follow the same calling convention as `completion-try-completion'),
472 ALL-COMPLETIONS is the function that lists the completions (it should
473 follow the calling convention of `completion-all-completions'),
474 and DOC describes the way this style of completion works.")
476 (defconst completion--styles-type
477 `(repeat :tag
"insert a new menu to add more styles"
478 (choice ,@(mapcar (lambda (x) (list 'const
(car x
)))
479 completion-styles-alist
))))
480 (defconst completion--cycling-threshold-type
481 '(choice (const :tag
"No cycling" nil
)
482 (const :tag
"Always cycle" t
)
483 (integer :tag
"Threshold")))
485 (defcustom completion-styles
486 ;; First, use `basic' because prefix completion has been the standard
487 ;; for "ever" and works well in most cases, so using it first
488 ;; ensures that we obey previous behavior in most cases.
490 ;; Then use `partial-completion' because it has proven to
491 ;; be a very convenient extension.
493 ;; Finally use `emacs22' so as to maintain (in many/most cases)
494 ;; the previous behavior that when completing "foobar" with point
495 ;; between "foo" and "bar" the completion try to complete "foo"
496 ;; and simply add "bar" to the end of the result.
498 "List of completion styles to use.
499 The available styles are listed in `completion-styles-alist'.
501 Note that `completion-category-overrides' may override these
502 styles for specific categories, such as files, buffers, etc."
503 :type completion--styles-type
507 (defcustom completion-category-overrides
508 '((buffer (styles .
(basic substring
))))
509 "List of `completion-styles' overrides for specific categories.
510 Each override has the shape (CATEGORY . ALIST) where ALIST is
511 an association list that can specify properties such as:
512 - `styles': the list of `completion-styles' to use for that category.
513 - `cycle': the `completion-cycle-threshold' to use for that category.
514 Categories are symbols such as `buffer' and `file', used when
515 completing buffer and file names, respectively."
517 :type
`(alist :key-type
(choice :tag
"Category"
523 (set :tag
"Properties to override"
524 (cons :tag
"Completion Styles"
525 (const :tag
"Select a style from the menu;" styles
)
526 ,completion--styles-type
)
527 (cons :tag
"Completion Cycling"
528 (const :tag
"Select one value from the menu." cycle
)
529 ,completion--cycling-threshold-type
))))
531 (defun completion--styles (metadata)
532 (let* ((cat (completion-metadata-get metadata
'category
))
533 (over (assq 'styles
(cdr (assq cat completion-category-overrides
)))))
535 (delete-dups (append (cdr over
) (copy-sequence completion-styles
)))
538 (defun completion-try-completion (string table pred point
&optional metadata
)
539 "Try to complete STRING using completion table TABLE.
540 Only the elements of table that satisfy predicate PRED are considered.
541 POINT is the position of point within STRING.
542 The return value can be either nil to indicate that there is no completion,
543 t to indicate that STRING is the only possible completion,
544 or a pair (STRING . NEWPOINT) of the completed result string together with
545 a new position for point."
546 (completion--some (lambda (style)
547 (funcall (nth 1 (assq style completion-styles-alist
))
548 string table pred point
))
549 (completion--styles (or metadata
551 (substring string
0 point
)
554 (defun completion-all-completions (string table pred point
&optional metadata
)
555 "List the possible completions of STRING in completion table TABLE.
556 Only the elements of table that satisfy predicate PRED are considered.
557 POINT is the position of point within STRING.
558 The return value is a list of completions and may contain the base-size
560 ;; FIXME: We need to additionally return the info needed for the
561 ;; second part of completion-base-position.
562 (completion--some (lambda (style)
563 (funcall (nth 2 (assq style completion-styles-alist
))
564 string table pred point
))
565 (completion--styles (or metadata
567 (substring string
0 point
)
570 (defun minibuffer--bitset (modified completions exact
)
571 (logior (if modified
4 0)
575 (defun completion--replace (beg end newtext
)
576 "Replace the buffer text between BEG and END with NEWTEXT.
577 Moves point to the end of the new text."
578 ;; The properties on `newtext' include things like
579 ;; completions-first-difference, which we don't want to include
581 (set-text-properties 0 (length newtext
) nil newtext
)
582 ;; Maybe this should be in subr.el.
583 ;; You'd think this is trivial to do, but details matter if you want
584 ;; to keep markers "at the right place" and be robust in the face of
585 ;; after-change-functions that may themselves modify the buffer.
586 (let ((prefix-len 0))
587 ;; Don't touch markers in the shared prefix (if any).
588 (while (and (< prefix-len
(length newtext
))
589 (< (+ beg prefix-len
) end
)
590 (eq (char-after (+ beg prefix-len
))
591 (aref newtext prefix-len
)))
592 (setq prefix-len
(1+ prefix-len
)))
593 (unless (zerop prefix-len
)
594 (setq beg
(+ beg prefix-len
))
595 (setq newtext
(substring newtext prefix-len
))))
596 (let ((suffix-len 0))
597 ;; Don't touch markers in the shared suffix (if any).
598 (while (and (< suffix-len
(length newtext
))
599 (< beg
(- end suffix-len
))
600 (eq (char-before (- end suffix-len
))
601 (aref newtext
(- (length newtext
) suffix-len
1))))
602 (setq suffix-len
(1+ suffix-len
)))
603 (unless (zerop suffix-len
)
604 (setq end
(- end suffix-len
))
605 (setq newtext
(substring newtext
0 (- suffix-len
))))
607 (insert-and-inherit newtext
)
608 (delete-region (point) (+ (point) (- end beg
)))
609 (forward-char suffix-len
)))
611 (defcustom completion-cycle-threshold nil
612 "Number of completion candidates below which cycling is used.
613 Depending on this setting `minibuffer-complete' may use cycling,
614 like `minibuffer-force-complete'.
615 If nil, cycling is never used.
616 If t, cycling is always used.
617 If an integer, cycling is used as soon as there are fewer completion
618 candidates than this number."
620 :type completion--cycling-threshold-type
)
622 (defun completion--cycle-threshold (metadata)
623 (let* ((cat (completion-metadata-get metadata
'category
))
624 (over (assq 'cycle
(cdr (assq cat completion-category-overrides
)))))
625 (if over
(cdr over
) completion-cycle-threshold
)))
627 (defvar completion-all-sorted-completions nil
)
628 (make-variable-buffer-local 'completion-all-sorted-completions
)
629 (defvar completion-cycling nil
)
631 (defvar completion-fail-discreetly nil
632 "If non-nil, stay quiet when there is no match.")
634 (defun completion--message (msg)
635 (if completion-show-inline-help
636 (minibuffer-message msg
)))
638 (defun completion--do-completion (&optional try-completion-function
640 "Do the completion and return a summary of what happened.
641 M = completion was performed, the text was Modified.
642 C = there were available Completions.
643 E = after completion we now have an Exact match.
646 000 0 no possible completion
647 001 1 was already an exact and unique completion
648 010 2 no completion happened
649 011 3 was already an exact completion
652 110 6 some completion happened
653 111 7 completed to an exact completion
655 TRY-COMPLETION-FUNCTION is a function to use in place of `try-completion'.
656 EXPECT-EXACT, if non-nil, means that there is no need to tell the user
657 when the buffer's text is already an exact match."
658 (let* ((beg (field-beginning))
660 (string (buffer-substring beg end
))
661 (md (completion--field-metadata beg
))
662 (comp (funcall (or try-completion-function
663 'completion-try-completion
)
665 minibuffer-completion-table
666 minibuffer-completion-predicate
671 (minibuffer-hide-completions)
672 (unless completion-fail-discreetly
674 (completion--message "No match"))
675 (minibuffer--bitset nil nil nil
))
677 (minibuffer-hide-completions)
679 (completion--done string
'finished
680 (unless expect-exact
"Sole completion"))
681 (minibuffer--bitset nil nil t
)) ;Exact and unique match.
683 ;; `completed' should be t if some completion was done, which doesn't
684 ;; include simply changing the case of the entered string. However,
685 ;; for appearance, the string is rewritten if the case changes.
686 (let* ((comp-pos (cdr comp
))
687 (completion (car comp
))
688 (completed (not (eq t
(compare-strings completion nil nil
690 (unchanged (eq t
(compare-strings completion nil nil
691 string nil nil nil
))))
694 ;; Insert in minibuffer the chars we got.
695 (completion--replace beg end completion
))
696 ;; Move point to its completion-mandated destination.
697 (forward-char (- comp-pos
(length completion
)))
699 (if (not (or unchanged completed
))
700 ;; The case of the string changed, but that's all. We're not sure
701 ;; whether this is a unique completion or not, so try again using
702 ;; the real case (this shouldn't recurse again, because the next
703 ;; time try-completion will return either t or the exact string).
704 (completion--do-completion try-completion-function expect-exact
)
706 ;; It did find a match. Do we match some possibility exactly now?
707 (let* ((exact (test-completion completion
708 minibuffer-completion-table
709 minibuffer-completion-predicate
))
710 (threshold (completion--cycle-threshold md
))
712 ;; Check to see if we want to do cycling. We do it
713 ;; here, after having performed the normal completion,
714 ;; so as to take advantage of the difference between
715 ;; try-completion and all-completions, for things
716 ;; like completion-ignored-extensions.
718 ;; Check that the completion didn't make
719 ;; us jump to a different boundary.
721 (< (car (completion-boundaries
722 (substring completion
0 comp-pos
)
723 minibuffer-completion-table
724 minibuffer-completion-predicate
727 (completion-all-sorted-completions))))
728 (completion--flush-all-sorted-completions)
730 ((and (consp (cdr comps
)) ;; There's something to cycle.
732 ;; This signal an (intended) error if comps is too
733 ;; short or if completion-cycle-threshold is t.
734 (consp (nthcdr threshold comps
)))))
735 ;; Fewer than completion-cycle-threshold remaining
736 ;; completions: let's cycle.
737 (setq completed t exact t
)
738 (completion--cache-all-sorted-completions comps
)
739 (minibuffer-force-complete))
741 ;; We could also decide to refresh the completions,
742 ;; if they're displayed (and assuming there are
743 ;; completions left).
744 (minibuffer-hide-completions)
746 ;; If completion did not put point at end of field,
747 ;; it's a sign that completion is not finished.
748 (completion--done completion
749 (if (< comp-pos
(length completion
))
751 ;; Show the completion table, if requested.
753 (if (case completion-auto-help
754 (lazy (eq this-command last-command
))
755 (t completion-auto-help
))
756 (minibuffer-completion-help)
757 (completion--message "Next char not unique")))
758 ;; If the last exact completion and this one were the same, it
759 ;; means we've already given a "Complete, but not unique" message
760 ;; and the user's hit TAB again, so now we give him help.
762 (if (and (eq this-command last-command
) completion-auto-help
)
763 (minibuffer-completion-help))
764 (completion--done completion
'exact
766 "Complete, but not unique"))))
768 (minibuffer--bitset completed t exact
))))))))
770 (defun minibuffer-complete ()
771 "Complete the minibuffer contents as far as possible.
772 Return nil if there is no valid completion, else t.
773 If no characters can be completed, display a list of possible completions.
774 If you repeat this command after it displayed such a list,
775 scroll the window of possible completions."
777 ;; If the previous command was not this,
778 ;; mark the completion buffer obsolete.
779 (setq this-command
'completion-at-point
)
780 (unless (eq 'completion-at-point last-command
)
781 (completion--flush-all-sorted-completions)
782 (setq minibuffer-scroll-window nil
))
785 ;; If there's a fresh completion window with a live buffer,
786 ;; and this command is repeated, scroll that window.
787 ((window-live-p minibuffer-scroll-window
)
788 (let ((window minibuffer-scroll-window
))
789 (with-current-buffer (window-buffer window
)
790 (if (pos-visible-in-window-p (point-max) window
)
791 ;; If end is in view, scroll up to the beginning.
792 (set-window-start window
(point-min) nil
)
793 ;; Else scroll down one screen.
794 (scroll-other-window))
796 ;; If we're cycling, keep on cycling.
797 ((and completion-cycling completion-all-sorted-completions
)
798 (minibuffer-force-complete)
800 (t (case (completion--do-completion)
804 (defun completion--cache-all-sorted-completions (comps)
805 (add-hook 'after-change-functions
806 'completion--flush-all-sorted-completions nil t
)
807 (setq completion-all-sorted-completions comps
))
809 (defun completion--flush-all-sorted-completions (&rest _ignore
)
810 (remove-hook 'after-change-functions
811 'completion--flush-all-sorted-completions t
)
812 (setq completion-cycling nil
)
813 (setq completion-all-sorted-completions nil
))
815 (defun completion--metadata (string base md-at-point table pred
)
816 ;; Like completion-metadata, but for the specific case of getting the
817 ;; metadata at `base', which tends to trigger pathological behavior for old
818 ;; completion tables which don't understand `metadata'.
819 (let ((bounds (completion-boundaries string table pred
"")))
820 (if (eq (car bounds
) base
) md-at-point
821 (completion-metadata (substring string
0 base
) table pred
))))
823 (defun completion-all-sorted-completions ()
824 (or completion-all-sorted-completions
825 (let* ((start (field-beginning))
827 (string (buffer-substring start end
))
828 (md (completion--field-metadata start
))
829 (all (completion-all-completions
831 minibuffer-completion-table
832 minibuffer-completion-predicate
836 (base-size (or (cdr last
) 0))
837 (all-md (completion--metadata (buffer-substring-no-properties
840 minibuffer-completion-table
841 minibuffer-completion-predicate
))
842 (sort-fun (completion-metadata-get all-md
'cycle-sort-function
)))
845 (setq all
(if sort-fun
(funcall sort-fun all
)
846 ;; Prefer shorter completions, by default.
847 (sort all
(lambda (c1 c2
) (< (length c1
) (length c2
))))))
848 ;; Prefer recently used completions.
850 (let ((hist (symbol-value minibuffer-history-variable
)))
851 (setq all
(sort all
(lambda (c1 c2
)
852 (> (length (member c1 hist
))
853 (length (member c2 hist
))))))))
854 ;; Cache the result. This is not just for speed, but also so that
855 ;; repeated calls to minibuffer-force-complete can cycle through
856 ;; all possibilities.
857 (completion--cache-all-sorted-completions (nconc all base-size
))))))
859 (defun minibuffer-force-complete ()
860 "Complete the minibuffer to an exact match.
861 Repeated uses step through the possible completions."
863 ;; FIXME: Need to deal with the extra-size issue here as well.
864 ;; FIXME: ~/src/emacs/t<M-TAB>/lisp/minibuffer.el completes to
865 ;; ~/src/emacs/trunk/ and throws away lisp/minibuffer.el.
866 (let* ((start (field-beginning))
868 ;; (md (completion--field-metadata start))
869 (all (completion-all-sorted-completions))
870 (base (+ start
(or (cdr (last all
)) 0))))
874 (if all
"No more completions" "No completions")))
875 ((not (consp (cdr all
)))
876 (let ((mod (equal (car all
) (buffer-substring-no-properties base end
))))
877 (if mod
(completion--replace base end
(car all
)))
878 (completion--done (buffer-substring-no-properties start
(point))
879 'finished
(unless mod
"Sole completion"))))
881 (completion--replace base end
(car all
))
882 (completion--done (buffer-substring-no-properties start
(point)) 'sole
)
883 ;; Set cycling after modifying the buffer since the flush hook resets it.
884 (setq completion-cycling t
)
885 ;; If completing file names, (car all) may be a directory, so we'd now
886 ;; have a new set of possible completions and might want to reset
887 ;; completion-all-sorted-completions to nil, but we prefer not to,
888 ;; so that repeated calls minibuffer-force-complete still cycle
889 ;; through the previous possible completions.
890 (let ((last (last all
)))
891 (setcdr last
(cons (car all
) (cdr last
)))
892 (completion--cache-all-sorted-completions (cdr all
)))))))
894 (defvar minibuffer-confirm-exit-commands
895 '(minibuffer-complete minibuffer-complete-word PC-complete PC-complete-word
)
896 "A list of commands which cause an immediately following
897 `minibuffer-complete-and-exit' to ask for extra confirmation.")
899 (defun minibuffer-complete-and-exit ()
900 "Exit if the minibuffer contains a valid completion.
901 Otherwise, try to complete the minibuffer contents. If
902 completion leads to a valid completion, a repetition of this
905 If `minibuffer-completion-confirm' is `confirm', do not try to
906 complete; instead, ask for confirmation and accept any input if
908 If `minibuffer-completion-confirm' is `confirm-after-completion',
909 do not try to complete; instead, ask for confirmation if the
910 preceding minibuffer command was a member of
911 `minibuffer-confirm-exit-commands', and accept the input
914 (let ((beg (field-beginning))
917 ;; Allow user to specify null string
918 ((= beg end
) (exit-minibuffer))
919 ((test-completion (buffer-substring beg end
)
920 minibuffer-completion-table
921 minibuffer-completion-predicate
)
922 ;; FIXME: completion-ignore-case has various slightly
923 ;; incompatible meanings. E.g. it can reflect whether the user
924 ;; wants completion to pay attention to case, or whether the
925 ;; string will be used in a context where case is significant.
926 ;; E.g. usually try-completion should obey the first, whereas
927 ;; test-completion should obey the second.
928 (when completion-ignore-case
929 ;; Fixup case of the field, if necessary.
930 (let* ((string (buffer-substring beg end
))
931 (compl (try-completion
933 minibuffer-completion-table
934 minibuffer-completion-predicate
)))
935 (when (and (stringp compl
) (not (equal string compl
))
936 ;; If it weren't for this piece of paranoia, I'd replace
937 ;; the whole thing with a call to do-completion.
938 ;; This is important, e.g. when the current minibuffer's
939 ;; content is a directory which only contains a single
940 ;; file, so `try-completion' actually completes to
942 (= (length string
) (length compl
)))
943 (completion--replace beg end compl
))))
946 ((memq minibuffer-completion-confirm
'(confirm confirm-after-completion
))
947 ;; The user is permitted to exit with an input that's rejected
948 ;; by test-completion, after confirming her choice.
949 (if (or (eq last-command this-command
)
950 ;; For `confirm-after-completion' we only ask for confirmation
951 ;; if trying to exit immediately after typing TAB (this
952 ;; catches most minibuffer typos).
953 (and (eq minibuffer-completion-confirm
'confirm-after-completion
)
954 (not (memq last-command minibuffer-confirm-exit-commands
))))
956 (minibuffer-message "Confirm")
960 ;; Call do-completion, but ignore errors.
961 (case (condition-case nil
962 (completion--do-completion nil
'expect-exact
)
964 ((#b001
#b011
) (exit-minibuffer))
965 (#b111
(if (not minibuffer-completion-confirm
)
967 (minibuffer-message "Confirm")
971 (defun completion--try-word-completion (string table predicate point md
)
972 (let ((comp (completion-try-completion string table predicate point md
)))
973 (if (not (consp comp
))
976 ;; If completion finds next char not unique,
977 ;; consider adding a space or a hyphen.
978 (when (= (length string
) (length (car comp
)))
979 ;; Mark the added char with the `completion-word' property, so it
980 ;; can be handled specially by completion styles such as
981 ;; partial-completion.
982 ;; We used to remove `partial-completion' from completion-styles
983 ;; instead, but it was too blunt, leading to situations where SPC
984 ;; was the only insertable char at point but minibuffer-complete-word
985 ;; refused inserting it.
986 (let ((exts (mapcar (lambda (str) (propertize str
'completion-try-word t
))
988 (before (substring string
0 point
))
989 (after (substring string point
))
991 (while (and exts
(not (consp tem
)))
992 (setq tem
(completion-try-completion
993 (concat before
(pop exts
) after
)
994 table predicate
(1+ point
) md
)))
995 (if (consp tem
) (setq comp tem
))))
997 ;; Completing a single word is actually more difficult than completing
998 ;; as much as possible, because we first have to find the "current
999 ;; position" in `completion' in order to find the end of the word
1000 ;; we're completing. Normally, `string' is a prefix of `completion',
1001 ;; which makes it trivial to find the position, but with fancier
1002 ;; completion (plus env-var expansion, ...) `completion' might not
1003 ;; look anything like `string' at all.
1004 (let* ((comppoint (cdr comp
))
1005 (completion (car comp
))
1006 (before (substring string
0 point
))
1007 (combined (concat before
"\n" completion
)))
1008 ;; Find in completion the longest text that was right before point.
1009 (when (string-match "\\(.+\\)\n.*?\\1" combined
)
1010 (let* ((prefix (match-string 1 before
))
1011 ;; We used non-greedy match to make `rem' as long as possible.
1012 (rem (substring combined
(match-end 0)))
1013 ;; Find in the remainder of completion the longest text
1014 ;; that was right after point.
1015 (after (substring string point
))
1016 (suffix (if (string-match "\\`\\(.+\\).*\n.*\\1"
1017 (concat after
"\n" rem
))
1018 (match-string 1 after
))))
1019 ;; The general idea is to try and guess what text was inserted
1020 ;; at point by the completion. Problem is: if we guess wrong,
1021 ;; we may end up treating as "added by completion" text that was
1022 ;; actually painfully typed by the user. So if we then cut
1023 ;; after the first word, we may throw away things the
1024 ;; user wrote. So let's try to be as conservative as possible:
1025 ;; only cut after the first word, if we're reasonably sure that
1026 ;; our guess is correct.
1027 ;; Note: a quick survey on emacs-devel seemed to indicate that
1028 ;; nobody actually cares about the "word-at-a-time" feature of
1029 ;; minibuffer-complete-word, whose real raison-d'être is that it
1030 ;; tries to add "-" or " ". One more reason to only cut after
1031 ;; the first word, if we're really sure we're right.
1032 (when (and (or suffix
(zerop (length after
)))
1033 (string-match (concat
1034 ;; Make submatch 1 as small as possible
1035 ;; to reduce the risk of cutting
1037 ".*" (regexp-quote prefix
) "\\(.*?\\)"
1038 (if suffix
(regexp-quote suffix
) "\\'"))
1040 ;; The new point in `completion' should also be just
1041 ;; before the suffix, otherwise something more complex
1042 ;; is going on, and we're not sure where we are.
1043 (eq (match-end 1) comppoint
)
1044 ;; (match-beginning 1)..comppoint is now the stretch
1045 ;; of text in `completion' that was completed at point.
1046 (string-match "\\W" completion
(match-beginning 1))
1047 ;; Is there really something to cut?
1048 (> comppoint
(match-end 0)))
1049 ;; Cut after the first word.
1050 (let ((cutpos (match-end 0)))
1051 (setq completion
(concat (substring completion
0 cutpos
)
1052 (substring completion comppoint
)))
1053 (setq comppoint cutpos
)))))
1055 (cons completion comppoint
)))))
1058 (defun minibuffer-complete-word ()
1059 "Complete the minibuffer contents at most a single word.
1060 After one word is completed as much as possible, a space or hyphen
1061 is added, provided that matches some possible completion.
1062 Return nil if there is no valid completion, else t."
1064 (case (completion--do-completion 'completion--try-word-completion
)
1068 (defface completions-annotations
'((t :inherit italic
))
1069 "Face to use for annotations in the *Completions* buffer.")
1071 (defcustom completions-format
'horizontal
1072 "Define the appearance and sorting of completions.
1073 If the value is `vertical', display completions sorted vertically
1074 in columns in the *Completions* buffer.
1075 If the value is `horizontal', display completions sorted
1076 horizontally in alphabetical order, rather than down the screen."
1077 :type
'(choice (const horizontal
) (const vertical
))
1081 (defun completion--insert-strings (strings)
1082 "Insert a list of STRINGS into the current buffer.
1083 Uses columns to keep the listing readable but compact.
1084 It also eliminates runs of equal strings."
1085 (when (consp strings
)
1086 (let* ((length (apply 'max
1089 (+ (string-width (car s
))
1090 (string-width (cadr s
)))
1093 (window (get-buffer-window (current-buffer) 0))
1094 (wwidth (if window
(1- (window-width window
)) 79))
1096 ;; At least 2 columns; at least 2 spaces between columns.
1097 (max 2 (/ wwidth
(+ 2 length
)))
1098 ;; Don't allocate more columns than we can fill.
1099 ;; Windows can't show less than 3 lines anyway.
1100 (max 1 (/ (length strings
) 2))))
1101 (colwidth (/ wwidth columns
))
1103 (rows (/ (length strings
) columns
))
1107 ;; The insertion should be "sensible" no matter what choices were made
1108 ;; for the parameters above.
1109 (dolist (str strings
)
1110 (unless (equal laststring str
) ; Remove (consecutive) duplicates.
1111 (setq laststring str
)
1112 ;; FIXME: `string-width' doesn't pay attention to
1113 ;; `display' properties.
1114 (let ((length (if (consp str
)
1115 (+ (string-width (car str
))
1116 (string-width (cadr str
)))
1117 (string-width str
))))
1119 ((eq completions-format
'vertical
)
1122 (forward-line (- -
1 rows
))
1123 (setq row
0 column
(+ column colwidth
)))
1126 (while (> (current-column) column
)
1132 (set-text-properties (1- (point)) (point)
1133 `(display (space :align-to
,column
)))))
1135 ;; Horizontal format
1137 (if (< wwidth
(+ (max colwidth length
) column
))
1138 ;; No space for `str' at point, move to next line.
1139 (progn (insert "\n") (setq column
0))
1141 ;; Leave the space unpropertized so that in the case we're
1142 ;; already past the goal column, there is still
1143 ;; a space displayed.
1144 (set-text-properties (1- (point)) (point)
1145 ;; We can't just set tab-width, because
1146 ;; completion-setup-function will kill
1147 ;; all local variables :-(
1148 `(display (space :align-to
,column
)))
1151 (if (not (consp str
))
1152 (put-text-property (point) (progn (insert str
) (point))
1153 'mouse-face
'highlight
)
1154 (put-text-property (point) (progn (insert (car str
)) (point))
1155 'mouse-face
'highlight
)
1156 (add-text-properties (point) (progn (insert (cadr str
)) (point))
1158 face completions-annotations
)))
1160 ((eq completions-format
'vertical
)
1165 (setq row
(1+ row
)))
1167 ;; Horizontal format
1168 ;; Next column to align to.
1169 (setq column
(+ column
1170 ;; Round up to a whole number of columns.
1171 (* colwidth
(ceiling length colwidth
))))))))))))
1173 (defvar completion-common-substring nil
)
1174 (make-obsolete-variable 'completion-common-substring nil
"23.1")
1176 (defvar completion-setup-hook nil
1177 "Normal hook run at the end of setting up a completion list buffer.
1178 When this hook is run, the current buffer is the one in which the
1179 command to display the completion list buffer was run.
1180 The completion list buffer is available as the value of `standard-output'.
1181 See also `display-completion-list'.")
1183 (defface completions-first-difference
1184 '((t (:inherit bold
)))
1185 "Face put on the first uncommon character in completions in *Completions* buffer."
1188 (defface completions-common-part
1189 '((t (:inherit default
)))
1190 "Face put on the common prefix substring in completions in *Completions* buffer.
1191 The idea of `completions-common-part' is that you can use it to
1192 make the common parts less visible than normal, so that the rest
1193 of the differing parts is, by contrast, slightly highlighted."
1196 (defun completion-hilit-commonality (completions prefix-len base-size
)
1198 (let ((com-str-len (- prefix-len
(or base-size
0))))
1203 ;; Don't modify the string itself, but a copy, since the
1204 ;; the string may be read-only or used for other purposes.
1205 ;; Furthermore, since `completions' may come from
1206 ;; display-completion-list, `elem' may be a list.
1208 (car (setq elem
(cons (copy-sequence (car elem
))
1210 (setq elem
(copy-sequence elem
)))))
1211 (put-text-property 0
1212 ;; If completion-boundaries returns incorrect
1213 ;; values, all-completions may return strings
1214 ;; that don't contain the prefix.
1215 (min com-str-len
(length str
))
1216 'font-lock-face
'completions-common-part
1218 (if (> (length str
) com-str-len
)
1219 (put-text-property com-str-len
(1+ com-str-len
)
1220 'font-lock-face
'completions-first-difference
1226 (defun display-completion-list (completions &optional common-substring
)
1227 "Display the list of completions, COMPLETIONS, using `standard-output'.
1228 Each element may be just a symbol or string
1229 or may be a list of two strings to be printed as if concatenated.
1230 If it is a list of two strings, the first is the actual completion
1231 alternative, the second serves as annotation.
1232 `standard-output' must be a buffer.
1233 The actual completion alternatives, as inserted, are given `mouse-face'
1234 properties of `highlight'.
1235 At the end, this runs the normal hook `completion-setup-hook'.
1236 It can find the completion buffer in `standard-output'.
1238 The obsolete optional arg COMMON-SUBSTRING, if non-nil, should be a string
1239 specifying a common substring for adding the faces
1240 `completions-first-difference' and `completions-common-part' to
1241 the completions buffer."
1242 (if common-substring
1243 (setq completions
(completion-hilit-commonality
1244 completions
(length common-substring
)
1245 ;; We don't know the base-size.
1247 (if (not (bufferp standard-output
))
1248 ;; This *never* (ever) happens, so there's no point trying to be clever.
1250 (let ((standard-output (current-buffer))
1251 (completion-setup-hook nil
))
1252 (display-completion-list completions common-substring
))
1253 (princ (buffer-string)))
1255 (with-current-buffer standard-output
1256 (goto-char (point-max))
1257 (if (null completions
)
1258 (insert "There are no possible completions of what you have typed.")
1259 (insert "Possible completions are:\n")
1260 (completion--insert-strings completions
))))
1262 ;; The hilit used to be applied via completion-setup-hook, so there
1263 ;; may still be some code that uses completion-common-substring.
1265 (let ((completion-common-substring common-substring
))
1266 (run-hooks 'completion-setup-hook
)))
1269 (defvar completion-extra-properties nil
1270 "Property list of extra properties of the current completion job.
1272 `:annotation-function': Function to add annotations in the completions buffer.
1273 The function takes a completion and should either return nil, or a string
1274 that will be displayed next to the completion. The function can access the
1275 completion data via `minibuffer-completion-table' and related variables.
1276 `:exit-function': Function to run after completion is performed.
1277 The function takes at least 2 parameters (STRING and STATUS) where STRING
1278 is the text to which the field was completed and STATUS indicates what
1279 kind of operation happened: if text is now complete it's `finished', if text
1280 cannot be further completed but completion is not finished, it's `sole', if
1281 text is a valid completion but may be further completed, it's `exact', and
1282 other STATUSes may be added in the future.")
1284 (defvar completion-annotate-function
1286 ;; Note: there's a lot of scope as for when to add annotations and
1287 ;; what annotations to add. E.g. completing-help.el allowed adding
1288 ;; the first line of docstrings to M-x completion. But there's
1289 ;; a tension, since such annotations, while useful at times, can
1290 ;; actually drown the useful information.
1291 ;; So completion-annotate-function should be used parsimoniously, or
1292 ;; else only used upon a user's request (e.g. we could add a command
1293 ;; to completion-list-mode to add annotations to the current
1295 "Function to add annotations in the *Completions* buffer.
1296 The function takes a completion and should either return nil, or a string that
1297 will be displayed next to the completion. The function can access the
1298 completion table and predicates via `minibuffer-completion-table' and related
1300 (make-obsolete-variable 'completion-annotate-function
1301 'completion-extra-properties
"24.1")
1303 (defun completion--done (string &optional finished message
)
1304 (let* ((exit-fun (plist-get completion-extra-properties
:exit-function
))
1305 (pre-msg (and exit-fun
(current-message))))
1306 (assert (memq finished
'(exact sole finished unknown
)))
1307 ;; FIXME: exit-fun should receive `finished' as a parameter.
1309 (when (eq finished
'unknown
)
1311 (if (eq (try-completion string
1312 minibuffer-completion-table
1313 minibuffer-completion-predicate
)
1316 (funcall exit-fun string finished
))
1318 ;; Don't output any message if the exit-fun already did so.
1319 (equal pre-msg
(and exit-fun
(current-message))))
1320 (completion--message message
))))
1322 (defun minibuffer-completion-help ()
1323 "Display a list of possible completions of the current minibuffer contents."
1325 (message "Making completion list...")
1326 (let* ((start (field-beginning))
1328 (string (field-string))
1329 (md (completion--field-metadata start
))
1330 (completions (completion-all-completions
1332 minibuffer-completion-table
1333 minibuffer-completion-predicate
1334 (- (point) (field-beginning))
1337 (if (or (null completions
)
1338 (and (not (consp (cdr completions
)))
1339 (equal (car completions
) string
)))
1341 ;; If there are no completions, or if the current input is already
1342 ;; the sole completion, then hide (previous&stale) completions.
1343 (minibuffer-hide-completions)
1346 (if completions
"Sole completion" "No completions")))
1348 (let* ((last (last completions
))
1349 (base-size (cdr last
))
1350 (prefix (unless (zerop base-size
) (substring string
0 base-size
)))
1351 (all-md (completion--metadata (buffer-substring-no-properties
1354 minibuffer-completion-table
1355 minibuffer-completion-predicate
))
1356 (afun (or (completion-metadata-get all-md
'annotation-function
)
1357 (plist-get completion-extra-properties
1358 :annotation-function
)
1359 completion-annotate-function
))
1360 ;; If the *Completions* buffer is shown in a new
1361 ;; window, mark it as softly-dedicated, so bury-buffer in
1362 ;; minibuffer-hide-completions will know whether to
1363 ;; delete the window or not.
1364 (display-buffer-mark-dedicated 'soft
))
1365 (with-output-to-temp-buffer "*Completions*"
1366 ;; Remove the base-size tail because `sort' requires a properly
1367 ;; nil-terminated list.
1368 (when last
(setcdr last nil
))
1370 ;; FIXME: This function is for the output of all-completions,
1371 ;; not completion-all-completions. Often it's the same, but
1373 (let ((sort-fun (completion-metadata-get
1374 all-md
'display-sort-function
)))
1376 (funcall sort-fun completions
)
1377 (sort completions
'string-lessp
))))
1381 (let ((ann (funcall afun s
)))
1382 (if ann
(list s ann
) s
)))
1385 (with-current-buffer standard-output
1386 (set (make-local-variable 'completion-base-position
)
1387 (list (+ start base-size
)
1388 ;; FIXME: We should pay attention to completion
1389 ;; boundaries here, but currently
1390 ;; completion-all-completions does not give us the
1391 ;; necessary information.
1393 (set (make-local-variable 'completion-list-insert-choice-function
)
1394 (let ((ctable minibuffer-completion-table
)
1395 (cpred minibuffer-completion-predicate
)
1396 (cprops completion-extra-properties
))
1397 (lambda (start end choice
)
1398 (unless (or (zerop (length prefix
))
1400 (buffer-substring-no-properties
1402 (- start
(length prefix
)))
1404 (message "*Completions* out of date"))
1405 ;; FIXME: Use `md' to do quoting&terminator here.
1406 (completion--replace start end choice
)
1407 (let* ((minibuffer-completion-table ctable
)
1408 (minibuffer-completion-predicate cpred
)
1409 (completion-extra-properties cprops
)
1410 (result (concat prefix choice
))
1411 (bounds (completion-boundaries
1412 result ctable cpred
"")))
1413 ;; If the completion introduces a new field, then
1414 ;; completion is not finished.
1415 (completion--done result
1416 (if (eq (car bounds
) (length result
))
1417 'exact
'finished
)))))))
1419 (display-completion-list completions
))))
1422 (defun minibuffer-hide-completions ()
1423 "Get rid of an out-of-date *Completions* buffer."
1424 ;; FIXME: We could/should use minibuffer-scroll-window here, but it
1425 ;; can also point to the minibuffer-parent-window, so it's a bit tricky.
1426 (let ((win (get-buffer-window "*Completions*" 0)))
1427 (if win
(with-selected-window win
(bury-buffer)))))
1429 (defun exit-minibuffer ()
1430 "Terminate this minibuffer argument."
1432 ;; If the command that uses this has made modifications in the minibuffer,
1433 ;; we don't want them to cause deactivation of the mark in the original
1435 ;; A better solution would be to make deactivate-mark buffer-local
1436 ;; (or to turn it into a list of buffers, ...), but in the mean time,
1437 ;; this should do the trick in most cases.
1438 (setq deactivate-mark nil
)
1441 (defun self-insert-and-exit ()
1442 "Terminate minibuffer input."
1444 (if (characterp last-command-event
)
1445 (call-interactively 'self-insert-command
)
1449 (defvar completion-in-region-functions nil
1450 "Wrapper hook around `completion-in-region'.
1451 The functions on this special hook are called with 5 arguments:
1452 NEXT-FUN START END COLLECTION PREDICATE.
1453 NEXT-FUN is a function of four arguments (START END COLLECTION PREDICATE)
1454 that performs the default operation. The other four arguments are like
1455 the ones passed to `completion-in-region'. The functions on this hook
1456 are expected to perform completion on START..END using COLLECTION
1457 and PREDICATE, either by calling NEXT-FUN or by doing it themselves.")
1459 (defvar completion-in-region--data nil
)
1461 (defvar completion-in-region-mode-predicate nil
1462 "Predicate to tell `completion-in-region-mode' when to exit.
1463 It is called with no argument and should return nil when
1464 `completion-in-region-mode' should exit (and hence pop down
1465 the *Completions* buffer).")
1467 (defvar completion-in-region-mode--predicate nil
1468 "Copy of the value of `completion-in-region-mode-predicate'.
1469 This holds the value `completion-in-region-mode-predicate' had when
1470 we entered `completion-in-region-mode'.")
1472 (defun completion-in-region (start end collection
&optional predicate
)
1473 "Complete the text between START and END using COLLECTION.
1474 Return nil if there is no valid completion, else t.
1475 Point needs to be somewhere between START and END.
1476 PREDICATE (a function called with no arguments) says when to
1478 (assert (<= start
(point)) (<= (point) end
))
1480 ;; FIXME: Maybe we should use this hook to provide a "display
1481 ;; completions" operation as well.
1482 completion-in-region-functions
(start end collection predicate
)
1483 (let ((minibuffer-completion-table collection
)
1484 (minibuffer-completion-predicate predicate
)
1485 (ol (make-overlay start end nil nil t
)))
1486 (overlay-put ol
'field
'completion
)
1487 ;; HACK: if the text we are completing is already in a field, we
1488 ;; want the completion field to take priority (e.g. Bug#6830).
1489 (overlay-put ol
'priority
100)
1490 (when completion-in-region-mode-predicate
1491 (completion-in-region-mode 1)
1492 (setq completion-in-region--data
1493 (list (current-buffer) start end collection
)))
1495 (call-interactively 'minibuffer-complete
)
1496 (delete-overlay ol
)))))
1498 (defvar completion-in-region-mode-map
1499 (let ((map (make-sparse-keymap)))
1500 ;; FIXME: Only works if completion-in-region-mode was activated via
1501 ;; completion-at-point called directly.
1502 (define-key map
"?" 'completion-help-at-point
)
1503 (define-key map
"\t" 'completion-at-point
)
1505 "Keymap activated during `completion-in-region'.")
1507 ;; It is difficult to know when to exit completion-in-region-mode (i.e. hide
1508 ;; the *Completions*).
1509 ;; - lisp-mode: never.
1510 ;; - comint: only do it if you hit SPC at the right time.
1511 ;; - pcomplete: pop it down on SPC or after some time-delay.
1512 ;; - semantic: use a post-command-hook check similar to this one.
1513 (defun completion-in-region--postch ()
1514 (or unread-command-events
;Don't pop down the completions in the middle of
1515 ;mouse-drag-region/mouse-set-point.
1516 (and completion-in-region--data
1517 (and (eq (car completion-in-region--data
)
1519 (>= (point) (nth 1 completion-in-region--data
))
1522 (goto-char (nth 2 completion-in-region--data
))
1523 (line-end-position)))
1524 (funcall completion-in-region-mode--predicate
)))
1525 (completion-in-region-mode -
1)))
1527 ;; (defalias 'completion-in-region--prech 'completion-in-region--postch)
1529 (define-minor-mode completion-in-region-mode
1530 "Transient minor mode used during `completion-in-region'.
1531 With a prefix argument ARG, enable the modemode if ARG is
1532 positive, and disable it otherwise. If called from Lisp, enable
1533 the mode if ARG is omitted or nil."
1535 (setq completion-in-region--data nil
)
1536 ;; (remove-hook 'pre-command-hook #'completion-in-region--prech)
1537 (remove-hook 'post-command-hook
#'completion-in-region--postch
)
1538 (setq minor-mode-overriding-map-alist
1539 (delq (assq 'completion-in-region-mode minor-mode-overriding-map-alist
)
1540 minor-mode-overriding-map-alist
))
1541 (if (null completion-in-region-mode
)
1542 (unless (equal "*Completions*" (buffer-name (window-buffer)))
1543 (minibuffer-hide-completions))
1544 ;; (add-hook 'pre-command-hook #'completion-in-region--prech)
1545 (assert completion-in-region-mode-predicate
)
1546 (setq completion-in-region-mode--predicate
1547 completion-in-region-mode-predicate
)
1548 (add-hook 'post-command-hook
#'completion-in-region--postch
)
1549 (push `(completion-in-region-mode .
,completion-in-region-mode-map
)
1550 minor-mode-overriding-map-alist
)))
1552 ;; Define-minor-mode added our keymap to minor-mode-map-alist, but we want it
1553 ;; on minor-mode-overriding-map-alist instead.
1554 (setq minor-mode-map-alist
1555 (delq (assq 'completion-in-region-mode minor-mode-map-alist
)
1556 minor-mode-map-alist
))
1558 (defvar completion-at-point-functions
'(tags-completion-at-point-function)
1559 "Special hook to find the completion table for the thing at point.
1560 Each function on this hook is called in turns without any argument and should
1561 return either nil to mean that it is not applicable at point,
1562 or a function of no argument to perform completion (discouraged),
1563 or a list of the form (START END COLLECTION . PROPS) where
1564 START and END delimit the entity to complete and should include point,
1565 COLLECTION is the completion table to use to complete it, and
1566 PROPS is a property list for additional information.
1567 Currently supported properties are all the properties that can appear in
1568 `completion-extra-properties' plus:
1569 `:predicate' a predicate that completion candidates need to satisfy.
1570 `:exclusive' If `no', means that if the completion table fails to
1571 match the text at point, then instead of reporting a completion
1572 failure, the completion should try the next completion function.")
1574 (defvar completion--capf-misbehave-funs nil
1575 "List of functions found on `completion-at-point-functions' that misbehave.
1576 These are functions that neither return completion data nor a completion
1577 function but instead perform completion right away.")
1578 (defvar completion--capf-safe-funs nil
1579 "List of well-behaved functions found on `completion-at-point-functions'.
1580 These are functions which return proper completion data rather than
1581 a completion function or god knows what else.")
1583 (defun completion--capf-wrapper (fun which
)
1584 ;; FIXME: The safe/misbehave handling assumes that a given function will
1585 ;; always return the same kind of data, but this breaks down with functions
1586 ;; like comint-completion-at-point or mh-letter-completion-at-point, which
1587 ;; could be sometimes safe and sometimes misbehaving (and sometimes neither).
1590 (safe (member fun completion--capf-safe-funs
))
1591 (optimist (not (member fun completion--capf-misbehave-funs
))))
1592 (let ((res (funcall fun
)))
1594 ((and (consp res
) (not (functionp res
)))
1595 (unless (member fun completion--capf-safe-funs
)
1596 (push fun completion--capf-safe-funs
))
1597 (and (eq 'no
(plist-get (nthcdr 3 res
) :exclusive
))
1598 ;; FIXME: Here we'd need to decide whether there are
1599 ;; valid completions against the current text. But this depends
1600 ;; on the actual completion UI (e.g. with the default completion
1601 ;; it depends on completion-style) ;-(
1602 ;; We approximate this result by checking whether prefix
1603 ;; completion might work, which means that non-prefix completion
1604 ;; will not work (or not right) for completion functions that
1605 ;; are non-exclusive.
1606 (null (try-completion (buffer-substring-no-properties
1609 (plist-get (nthcdr 3 res
) :predicate
)))
1611 ((not (or (listp res
) (functionp res
)))
1612 (unless (member fun completion--capf-misbehave-funs
)
1614 "Completion function %S uses a deprecated calling convention" fun
)
1615 (push fun completion--capf-misbehave-funs
))))
1616 (if res
(cons fun res
)))))
1618 (defun completion-at-point ()
1619 "Perform completion on the text around point.
1620 The completion method is determined by `completion-at-point-functions'."
1622 (let ((res (run-hook-wrapped 'completion-at-point-functions
1623 #'completion--capf-wrapper
'all
)))
1625 (`(,_ .
,(and (pred functionp
) f
)) (funcall f
))
1626 (`(,hookfun .
(,start
,end
,collection .
,plist
))
1627 (let* ((completion-extra-properties plist
)
1628 (completion-in-region-mode-predicate
1630 ;; We're still in the same completion field.
1631 (eq (car-safe (funcall hookfun
)) start
))))
1632 (completion-in-region start end collection
1633 (plist-get plist
:predicate
))))
1634 ;; Maybe completion already happened and the function returned t.
1637 (defun completion-help-at-point ()
1638 "Display the completions on the text around point.
1639 The completion method is determined by `completion-at-point-functions'."
1641 (let ((res (run-hook-wrapped 'completion-at-point-functions
1642 ;; Ignore misbehaving functions.
1643 #'completion--capf-wrapper
'optimist
)))
1645 (`(,_ .
,(and (pred functionp
) f
))
1646 (message "Don't know how to show completions for %S" f
))
1647 (`(,hookfun .
(,start
,end
,collection .
,plist
))
1648 (let* ((minibuffer-completion-table collection
)
1649 (minibuffer-completion-predicate (plist-get plist
:predicate
))
1650 (completion-extra-properties plist
)
1651 (completion-in-region-mode-predicate
1653 ;; We're still in the same completion field.
1654 (eq (car-safe (funcall hookfun
)) start
)))
1655 (ol (make-overlay start end nil nil t
)))
1656 ;; FIXME: We should somehow (ab)use completion-in-region-function or
1657 ;; introduce a corresponding hook (plus another for word-completion,
1658 ;; and another for force-completion, maybe?).
1659 (overlay-put ol
'field
'completion
)
1660 (overlay-put ol
'priority
100)
1661 (completion-in-region-mode 1)
1662 (setq completion-in-region--data
1663 (list (current-buffer) start end collection
))
1665 (call-interactively 'minibuffer-completion-help
)
1666 (delete-overlay ol
))))
1668 ;; The hook function already performed completion :-(
1669 ;; Not much we can do at this point.
1670 (message "%s already performed completion!" hookfun
)
1672 (_ (message "Nothing to complete at point")))))
1676 (let ((map minibuffer-local-map
))
1677 (define-key map
"\C-g" 'abort-recursive-edit
)
1678 (define-key map
"\r" 'exit-minibuffer
)
1679 (define-key map
"\n" 'exit-minibuffer
))
1681 (defvar minibuffer-local-completion-map
1682 (let ((map (make-sparse-keymap)))
1683 (set-keymap-parent map minibuffer-local-map
)
1684 (define-key map
"\t" 'minibuffer-complete
)
1685 ;; M-TAB is already abused for many other purposes, so we should find
1686 ;; another binding for it.
1687 ;; (define-key map "\e\t" 'minibuffer-force-complete)
1688 (define-key map
" " 'minibuffer-complete-word
)
1689 (define-key map
"?" 'minibuffer-completion-help
)
1691 "Local keymap for minibuffer input with completion.")
1693 (defvar minibuffer-local-must-match-map
1694 (let ((map (make-sparse-keymap)))
1695 (set-keymap-parent map minibuffer-local-completion-map
)
1696 (define-key map
"\r" 'minibuffer-complete-and-exit
)
1697 (define-key map
"\n" 'minibuffer-complete-and-exit
)
1699 "Local keymap for minibuffer input with completion, for exact match.")
1701 (defvar minibuffer-local-filename-completion-map
1702 (let ((map (make-sparse-keymap)))
1703 (define-key map
" " nil
)
1705 "Local keymap for minibuffer input with completion for filenames.
1706 Gets combined either with `minibuffer-local-completion-map' or
1707 with `minibuffer-local-must-match-map'.")
1709 (defvar minibuffer-local-filename-must-match-map
(make-sparse-keymap))
1710 (make-obsolete-variable 'minibuffer-local-filename-must-match-map nil
"24.1")
1711 (define-obsolete-variable-alias 'minibuffer-local-must-match-filename-map
1712 'minibuffer-local-filename-must-match-map
"23.1")
1714 (let ((map minibuffer-local-ns-map
))
1715 (define-key map
" " 'exit-minibuffer
)
1716 (define-key map
"\t" 'exit-minibuffer
)
1717 (define-key map
"?" 'self-insert-and-exit
))
1719 (defvar minibuffer-inactive-mode-map
1720 (let ((map (make-keymap)))
1721 (suppress-keymap map
)
1722 (define-key map
"e" 'find-file-other-frame
)
1723 (define-key map
"f" 'find-file-other-frame
)
1724 (define-key map
"b" 'switch-to-buffer-other-frame
)
1725 (define-key map
"i" 'info
)
1726 (define-key map
"m" 'mail
)
1727 (define-key map
"n" 'make-frame
)
1728 (define-key map
[mouse-1
] (lambda () (interactive)
1729 (with-current-buffer "*Messages*"
1730 (goto-char (point-max))
1731 (display-buffer (current-buffer)))))
1732 ;; So the global down-mouse-1 binding doesn't clutter the execution of the
1733 ;; above mouse-1 binding.
1734 (define-key map
[down-mouse-1
] #'ignore
)
1736 "Keymap for use in the minibuffer when it is not active.
1737 The non-mouse bindings in this keymap can only be used in minibuffer-only
1738 frames, since the minibuffer can normally not be selected when it is
1741 (define-derived-mode minibuffer-inactive-mode nil
"InactiveMinibuffer"
1742 :abbrev-table nil
;abbrev.el is not loaded yet during dump.
1743 ;; Note: this major mode is called from minibuf.c.
1744 "Major mode to use in the minibuffer when it is not active.
1745 This is only used when the minibuffer area has no active minibuffer.")
1747 ;;; Completion tables.
1749 (defun minibuffer--double-dollars (str)
1750 (replace-regexp-in-string "\\$" "$$" str
))
1752 (defun completion--make-envvar-table ()
1753 (mapcar (lambda (enventry)
1754 (substring enventry
0 (string-match-p "=" enventry
)))
1755 process-environment
))
1757 (defconst completion--embedded-envvar-re
1758 (concat "\\(?:^\\|[^$]\\(?:\\$\\$\\)*\\)"
1759 "$\\([[:alnum:]_]*\\|{\\([^}]*\\)\\)\\'"))
1761 (defun completion--embedded-envvar-table (string _pred action
)
1762 "Completion table for envvars embedded in a string.
1763 The envvar syntax (and escaping) rules followed by this table are the
1764 same as `substitute-in-file-name'."
1765 ;; We ignore `pred', because the predicates passed to us via
1766 ;; read-file-name-internal are not 100% correct and fail here:
1767 ;; e.g. we get predicates like file-directory-p there, whereas the filename
1768 ;; completed needs to be passed through substitute-in-file-name before it
1769 ;; can be passed to file-directory-p.
1770 (when (string-match completion--embedded-envvar-re string
)
1771 (let* ((beg (or (match-beginning 2) (match-beginning 1)))
1772 (table (completion--make-envvar-table))
1773 (prefix (substring string
0 beg
)))
1775 ((eq action
'lambda
)
1776 ;; This table is expected to be used in conjunction with some
1777 ;; other table that provides the "main" completion. Let the
1778 ;; other table handle the test-completion case.
1780 ((or (eq (car-safe action
) 'boundaries
) (eq action
'metadata
))
1781 ;; Only return boundaries/metadata if there's something to complete,
1782 ;; since otherwise when we're used in
1783 ;; completion-table-in-turn, we could return boundaries and
1784 ;; let some subsequent table return a list of completions.
1785 ;; FIXME: Maybe it should rather be fixed in
1786 ;; completion-table-in-turn instead, but it's difficult to
1787 ;; do it efficiently there.
1788 (when (try-completion (substring string beg
) table nil
)
1789 ;; Compute the boundaries of the subfield to which this
1790 ;; completion applies.
1791 (if (eq action
'metadata
)
1792 '(metadata (category . environment-variable
))
1793 (let ((suffix (cdr action
)))
1795 (or (match-beginning 2) (match-beginning 1))
1796 (when (string-match "[^[:alnum:]_]" suffix
)
1797 (match-beginning 0)))))))
1799 (if (eq (aref string
(1- beg
)) ?
{)
1800 (setq table
(apply-partially 'completion-table-with-terminator
1802 ;; Even if file-name completion is case-insensitive, we want
1803 ;; envvar completion to be case-sensitive.
1804 (let ((completion-ignore-case nil
))
1805 (completion-table-with-context
1806 prefix table
(substring string beg
) nil action
)))))))
1808 (defun completion-file-name-table (string pred action
)
1809 "Completion table for file names."
1812 ((eq action
'metadata
) '(metadata (category . file
)))
1813 ((eq (car-safe action
) 'boundaries
)
1814 (let ((start (length (file-name-directory string
)))
1815 (end (string-match-p "/" (cdr action
))))
1817 ;; if `string' is "C:" in w32, (file-name-directory string)
1818 ;; returns "C:/", so `start' is 3 rather than 2.
1819 ;; Not quite sure what is The Right Fix, but clipping it
1820 ;; back to 2 will work for this particular case. We'll
1821 ;; see if we can come up with a better fix when we bump
1822 ;; into more such problematic cases.
1823 (min start
(length string
)) end
)))
1825 ((eq action
'lambda
)
1826 (if (zerop (length string
))
1827 nil
;Not sure why it's here, but it probably doesn't harm.
1828 (funcall (or pred
'file-exists-p
) string
)))
1831 (let* ((name (file-name-nondirectory string
))
1832 (specdir (file-name-directory string
))
1833 (realdir (or specdir default-directory
)))
1837 (let ((comp (file-name-completion name realdir pred
)))
1839 (concat specdir comp
)
1843 (let ((all (file-name-all-completions name realdir
)))
1845 ;; Check the predicate, if necessary.
1846 (unless (memq pred
'(nil file-exists-p
))
1849 (if (eq pred
'file-directory-p
)
1850 ;; Brute-force speed up for directory checking:
1851 ;; Discard strings which don't end in a slash.
1853 (let ((len (length s
)))
1854 (and (> len
0) (eq (aref s
(1- len
)) ?
/))))
1855 ;; Must do it the hard (and slow) way.
1857 (let ((default-directory (expand-file-name realdir
)))
1859 (if (funcall pred tem
) (push tem comp
))))
1860 (setq all
(nreverse comp
))))
1863 (file-error nil
))) ;PCM often calls with invalid directories.
1865 (defvar read-file-name-predicate nil
1866 "Current predicate used by `read-file-name-internal'.")
1867 (make-obsolete-variable 'read-file-name-predicate
1868 "use the regular PRED argument" "23.2")
1870 (defun completion--file-name-table (string pred action
)
1871 "Internal subroutine for `read-file-name'. Do not call this.
1872 This is a completion table for file names, like `completion-file-name-table'
1873 except that it passes the file name through `substitute-in-file-name'."
1875 ((eq (car-safe action
) 'boundaries
)
1876 ;; For the boundaries, we can't really delegate to
1877 ;; substitute-in-file-name+completion-file-name-table and then fix
1878 ;; them up (as we do for the other actions), because it would
1879 ;; require us to track the relationship between `str' and
1880 ;; `string', which is difficult. And in any case, if
1881 ;; substitute-in-file-name turns "fo-$TO-ba" into "fo-o/b-ba",
1882 ;; there's no way for us to return proper boundaries info, because
1883 ;; the boundary is not (yet) in `string'.
1885 ;; FIXME: Actually there is a way to return correct boundaries
1886 ;; info, at the condition of modifying the all-completions
1887 ;; return accordingly. But for now, let's not bother.
1888 (completion-file-name-table string pred action
))
1891 (let* ((default-directory
1893 ;; It used to be that `pred' was abused to pass `dir'
1895 (prog1 (file-name-as-directory (expand-file-name pred
))
1898 (str (condition-case nil
1899 (substitute-in-file-name string
)
1901 (comp (completion-file-name-table
1903 (with-no-warnings (or pred read-file-name-predicate
))
1908 ;; Requote the $s before returning the completion.
1909 (minibuffer--double-dollars comp
))
1910 ((and (null action
) comp
1911 ;; Requote the $s before checking for changes.
1912 (setq str
(minibuffer--double-dollars str
))
1913 (not (string-equal string str
)))
1914 ;; If there's no real completion, but substitute-in-file-name
1915 ;; changed the string, then return the new string.
1919 (defalias 'read-file-name-internal
1920 (completion-table-in-turn 'completion--embedded-envvar-table
1921 'completion--file-name-table
)
1922 "Internal subroutine for `read-file-name'. Do not call this.")
1924 (defvar read-file-name-function
'read-file-name-default
1925 "The function called by `read-file-name' to do its work.
1926 It should accept the same arguments as `read-file-name'.")
1928 (defcustom read-file-name-completion-ignore-case
1929 (if (memq system-type
'(ms-dos windows-nt darwin cygwin
))
1931 "Non-nil means when reading a file name completion ignores case."
1936 (defcustom insert-default-directory t
1937 "Non-nil means when reading a filename start with default dir in minibuffer.
1939 When the initial minibuffer contents show a name of a file or a directory,
1940 typing RETURN without editing the initial contents is equivalent to typing
1941 the default file name.
1943 If this variable is non-nil, the minibuffer contents are always
1944 initially non-empty, and typing RETURN without editing will fetch the
1945 default name, if one is provided. Note however that this default name
1946 is not necessarily the same as initial contents inserted in the minibuffer,
1947 if the initial contents is just the default directory.
1949 If this variable is nil, the minibuffer often starts out empty. In
1950 that case you may have to explicitly fetch the next history element to
1951 request the default name; typing RETURN without editing will leave
1952 the minibuffer empty.
1954 For some commands, exiting with an empty minibuffer has a special meaning,
1955 such as making the current buffer visit no file in the case of
1956 `set-visited-file-name'."
1960 ;; Not always defined, but only called if next-read-file-uses-dialog-p says so.
1961 (declare-function x-file-dialog
"xfns.c"
1962 (prompt dir
&optional default-filename mustmatch only-dir-p
))
1964 (defun read-file-name--defaults (&optional dir initial
)
1967 ;; With non-nil `initial', use `dir' as the first default.
1968 ;; Essentially, this mean reversing the normal order of the
1969 ;; current directory name and the current file name, i.e.
1970 ;; 1. with normal file reading:
1971 ;; 1.1. initial input is the current directory
1972 ;; 1.2. the first default is the current file name
1973 ;; 2. with non-nil `initial' (e.g. for `find-alternate-file'):
1974 ;; 2.2. initial input is the current file name
1975 ;; 2.1. the first default is the current directory
1976 (initial (abbreviate-file-name dir
))
1977 ;; In file buffers, try to get the current file name
1979 (abbreviate-file-name buffer-file-name
))))
1981 (run-hook-with-args-until-success 'file-name-at-point-functions
)))
1982 (when file-name-at-point
1983 (setq default
(delete-dups
1984 (delete "" (delq nil
(list file-name-at-point default
))))))
1985 ;; Append new defaults to the end of existing `minibuffer-default'.
1987 (if (listp minibuffer-default
) minibuffer-default
(list minibuffer-default
))
1988 (if (listp default
) default
(list default
)))))
1990 (defun read-file-name (prompt &optional dir default-filename mustmatch initial predicate
)
1991 "Read file name, prompting with PROMPT and completing in directory DIR.
1992 Value is not expanded---you must call `expand-file-name' yourself.
1993 Default name to DEFAULT-FILENAME if user exits the minibuffer with
1994 the same non-empty string that was inserted by this function.
1995 (If DEFAULT-FILENAME is omitted, the visited file name is used,
1996 except that if INITIAL is specified, that combined with DIR is used.
1997 If DEFAULT-FILENAME is a list of file names, the first file name is used.)
1998 If the user exits with an empty minibuffer, this function returns
1999 an empty string. (This can only happen if the user erased the
2000 pre-inserted contents or if `insert-default-directory' is nil.)
2002 Fourth arg MUSTMATCH can take the following values:
2003 - nil means that the user can exit with any input.
2004 - t means that the user is not allowed to exit unless
2005 the input is (or completes to) an existing file.
2006 - `confirm' means that the user can exit with any input, but she needs
2007 to confirm her choice if the input is not an existing file.
2008 - `confirm-after-completion' means that the user can exit with any
2009 input, but she needs to confirm her choice if she called
2010 `minibuffer-complete' right before `minibuffer-complete-and-exit'
2011 and the input is not an existing file.
2012 - anything else behaves like t except that typing RET does not exit if it
2013 does non-null completion.
2015 Fifth arg INITIAL specifies text to start with.
2017 If optional sixth arg PREDICATE is non-nil, possible completions and
2018 the resulting file name must satisfy (funcall PREDICATE NAME).
2019 DIR should be an absolute directory name. It defaults to the value of
2020 `default-directory'.
2022 If this command was invoked with the mouse, use a graphical file
2023 dialog if `use-dialog-box' is non-nil, and the window system or X
2024 toolkit in use provides a file dialog box, and DIR is not a
2025 remote file. For graphical file dialogs, any of the special values
2026 of MUSTMATCH `confirm' and `confirm-after-completion' are
2027 treated as equivalent to nil. Some graphical file dialogs respect
2028 a MUSTMATCH value of t, and some do not (or it only has a cosmetic
2029 effect, and does not actually prevent the user from entering a
2032 See also `read-file-name-completion-ignore-case'
2033 and `read-file-name-function'."
2034 ;; If x-gtk-use-old-file-dialog = t (xg_get_file_with_selection),
2035 ;; then MUSTMATCH is enforced. But with newer Gtk
2036 ;; (xg_get_file_with_chooser), it only has a cosmetic effect.
2037 ;; The user can still type a non-existent file name.
2038 (funcall (or read-file-name-function
#'read-file-name-default
)
2039 prompt dir default-filename mustmatch initial predicate
))
2041 ;; minibuffer-completing-file-name is a variable used internally in minibuf.c
2042 ;; to determine whether to use minibuffer-local-filename-completion-map or
2043 ;; minibuffer-local-completion-map. It shouldn't be exported to Elisp.
2044 ;; FIXME: Actually, it is also used in rfn-eshadow.el we'd otherwise have to
2045 ;; use (eq minibuffer-completion-table #'read-file-name-internal), which is
2046 ;; probably even worse. Maybe We should add some read-file-name-setup-hook
2047 ;; instead, but for now, let's keep this non-obsolete.
2048 ;;(make-obsolete-variable 'minibuffer-completing-file-name nil "24.1" 'get)
2050 (defun read-file-name-default (prompt &optional dir default-filename mustmatch initial predicate
)
2051 "Default method for reading file names.
2052 See `read-file-name' for the meaning of the arguments."
2053 (unless dir
(setq dir default-directory
))
2054 (unless (file-name-absolute-p dir
) (setq dir
(expand-file-name dir
)))
2055 (unless default-filename
2056 (setq default-filename
(if initial
(expand-file-name initial dir
)
2058 ;; If dir starts with user's homedir, change that to ~.
2059 (setq dir
(abbreviate-file-name dir
))
2060 ;; Likewise for default-filename.
2061 (if default-filename
2062 (setq default-filename
2063 (if (consp default-filename
)
2064 (mapcar 'abbreviate-file-name default-filename
)
2065 (abbreviate-file-name default-filename
))))
2067 ((and insert-default-directory
(stringp dir
))
2069 (cons (minibuffer--double-dollars (concat dir initial
))
2070 (length (minibuffer--double-dollars dir
)))
2071 (minibuffer--double-dollars dir
)))
2072 (initial (cons (minibuffer--double-dollars initial
) 0)))))
2074 (let ((completion-ignore-case read-file-name-completion-ignore-case
)
2075 (minibuffer-completing-file-name t
)
2076 (pred (or predicate
'file-exists-p
))
2077 (add-to-history nil
))
2080 (if (or (not (next-read-file-uses-dialog-p))
2081 ;; Graphical file dialogs can't handle remote
2083 (file-remote-p dir
))
2084 ;; We used to pass `dir' to `read-file-name-internal' by
2085 ;; abusing the `predicate' argument. It's better to
2086 ;; just use `default-directory', but in order to avoid
2087 ;; changing `default-directory' in the current buffer,
2088 ;; we don't let-bind it.
2089 (let ((dir (file-name-as-directory
2090 (expand-file-name dir
))))
2091 (minibuffer-with-setup-hook
2093 (setq default-directory dir
)
2094 ;; When the first default in `minibuffer-default'
2095 ;; duplicates initial input `insdef',
2096 ;; reset `minibuffer-default' to nil.
2097 (when (equal (or (car-safe insdef
) insdef
)
2098 (or (car-safe minibuffer-default
)
2099 minibuffer-default
))
2100 (setq minibuffer-default
2101 (cdr-safe minibuffer-default
)))
2102 ;; On the first request on `M-n' fill
2103 ;; `minibuffer-default' with a list of defaults
2104 ;; relevant for file-name reading.
2105 (set (make-local-variable 'minibuffer-default-add-function
)
2107 (with-current-buffer
2108 (window-buffer (minibuffer-selected-window))
2109 (read-file-name--defaults dir initial
)))))
2110 (completing-read prompt
'read-file-name-internal
2111 pred mustmatch insdef
2112 'file-name-history default-filename
)))
2113 ;; If DEFAULT-FILENAME not supplied and DIR contains
2114 ;; a file name, split it.
2115 (let ((file (file-name-nondirectory dir
))
2116 ;; When using a dialog, revert to nil and non-nil
2117 ;; interpretation of mustmatch. confirm options
2118 ;; need to be interpreted as nil, otherwise
2119 ;; it is impossible to create new files using
2120 ;; dialogs with the default settings.
2122 (not (memq mustmatch
2123 '(nil confirm confirm-after-completion
)))))
2124 (when (and (not default-filename
)
2125 (not (zerop (length file
))))
2126 (setq default-filename file
)
2127 (setq dir
(file-name-directory dir
)))
2128 (when default-filename
2129 (setq default-filename
2130 (expand-file-name (if (consp default-filename
)
2131 (car default-filename
)
2134 (setq add-to-history t
)
2135 (x-file-dialog prompt dir default-filename
2137 (eq predicate
'file-directory-p
)))))
2139 (replace-in-history (eq (car-safe file-name-history
) val
)))
2140 ;; If completing-read returned the inserted default string itself
2141 ;; (rather than a new string with the same contents),
2142 ;; it has to mean that the user typed RET with the minibuffer empty.
2143 ;; In that case, we really want to return ""
2144 ;; so that commands such as set-visited-file-name can distinguish.
2145 (when (consp default-filename
)
2146 (setq default-filename
(car default-filename
)))
2147 (when (eq val default-filename
)
2148 ;; In this case, completing-read has not added an element
2149 ;; to the history. Maybe we should.
2150 (if (not replace-in-history
)
2151 (setq add-to-history t
))
2153 (unless val
(error "No file name specified"))
2155 (if (and default-filename
2156 (string-equal val
(if (consp insdef
) (car insdef
) insdef
)))
2157 (setq val default-filename
))
2158 (setq val
(substitute-in-file-name val
))
2160 (if replace-in-history
2161 ;; Replace what Fcompleting_read added to the history
2162 ;; with what we will actually return. As an exception,
2163 ;; if that's the same as the second item in
2164 ;; file-name-history, it's really a repeat (Bug#4657).
2165 (let ((val1 (minibuffer--double-dollars val
)))
2166 (if history-delete-duplicates
2167 (setcdr file-name-history
2168 (delete val1
(cdr file-name-history
))))
2169 (if (string= val1
(cadr file-name-history
))
2170 (pop file-name-history
)
2171 (setcar file-name-history val1
)))
2173 ;; Add the value to the history--but not if it matches
2174 ;; the last value already there.
2175 (let ((val1 (minibuffer--double-dollars val
)))
2176 (unless (and (consp file-name-history
)
2177 (equal (car file-name-history
) val1
))
2178 (setq file-name-history
2180 (if history-delete-duplicates
2181 (delete val1 file-name-history
)
2182 file-name-history
)))))))
2185 (defun internal-complete-buffer-except (&optional buffer
)
2186 "Perform completion on all buffers excluding BUFFER.
2187 BUFFER nil or omitted means use the current buffer.
2188 Like `internal-complete-buffer', but removes BUFFER from the completion list."
2189 (let ((except (if (stringp buffer
) buffer
(buffer-name buffer
))))
2190 (apply-partially 'completion-table-with-predicate
2191 'internal-complete-buffer
2193 (not (equal (if (consp name
) (car name
) name
) except
)))
2196 ;;; Old-style completion, used in Emacs-21 and Emacs-22.
2198 (defun completion-emacs21-try-completion (string table pred _point
)
2199 (let ((completion (try-completion string table pred
)))
2200 (if (stringp completion
)
2201 (cons completion
(length completion
))
2204 (defun completion-emacs21-all-completions (string table pred _point
)
2205 (completion-hilit-commonality
2206 (all-completions string table pred
)
2208 (car (completion-boundaries string table pred
""))))
2210 (defun completion-emacs22-try-completion (string table pred point
)
2211 (let ((suffix (substring string point
))
2212 (completion (try-completion (substring string
0 point
) table pred
)))
2213 (if (not (stringp completion
))
2215 ;; Merge a trailing / in completion with a / after point.
2216 ;; We used to only do it for word completion, but it seems to make
2217 ;; sense for all completions.
2218 ;; Actually, claiming this feature was part of Emacs-22 completion
2219 ;; is pushing it a bit: it was only done in minibuffer-completion-word,
2220 ;; which was (by default) not bound during file completion, where such
2221 ;; slashes are most likely to occur.
2222 (if (and (not (zerop (length completion
)))
2223 (eq ?
/ (aref completion
(1- (length completion
))))
2224 (not (zerop (length suffix
)))
2225 (eq ?
/ (aref suffix
0)))
2226 ;; This leaves point after the / .
2227 (setq suffix
(substring suffix
1)))
2228 (cons (concat completion suffix
) (length completion
)))))
2230 (defun completion-emacs22-all-completions (string table pred point
)
2231 (let ((beforepoint (substring string
0 point
)))
2232 (completion-hilit-commonality
2233 (all-completions beforepoint table pred
)
2235 (car (completion-boundaries beforepoint table pred
"")))))
2237 ;;; Basic completion.
2239 (defun completion--merge-suffix (completion point suffix
)
2240 "Merge end of COMPLETION with beginning of SUFFIX.
2241 Simple generalization of the \"merge trailing /\" done in Emacs-22.
2242 Return the new suffix."
2243 (if (and (not (zerop (length suffix
)))
2244 (string-match "\\(.+\\)\n\\1" (concat completion
"\n" suffix
)
2245 ;; Make sure we don't compress things to less
2246 ;; than we started with.
2248 ;; Just make sure we didn't match some other \n.
2249 (eq (match-end 1) (length completion
)))
2250 (substring suffix
(- (match-end 1) (match-beginning 1)))
2251 ;; Nothing to merge.
2254 (defun completion-basic--pattern (beforepoint afterpoint bounds
)
2256 "" (list (substring beforepoint
(car bounds
))
2258 (substring afterpoint
0 (cdr bounds
)))))
2260 (defun completion-basic-try-completion (string table pred point
)
2261 (let* ((beforepoint (substring string
0 point
))
2262 (afterpoint (substring string point
))
2263 (bounds (completion-boundaries beforepoint table pred afterpoint
)))
2264 (if (zerop (cdr bounds
))
2265 ;; `try-completion' may return a subtly different result
2266 ;; than `all+merge', so try to use it whenever possible.
2267 (let ((completion (try-completion beforepoint table pred
)))
2268 (if (not (stringp completion
))
2272 (completion--merge-suffix completion point afterpoint
))
2273 (length completion
))))
2274 (let* ((suffix (substring afterpoint
(cdr bounds
)))
2275 (prefix (substring beforepoint
0 (car bounds
)))
2277 "" (list (substring beforepoint
(car bounds
))
2279 (substring afterpoint
0 (cdr bounds
)))))
2280 (all (completion-pcm--all-completions prefix pattern table pred
)))
2281 (if minibuffer-completing-file-name
2282 (setq all
(completion-pcm--filename-try-filter all
)))
2283 (completion-pcm--merge-try pattern all prefix suffix
)))))
2285 (defun completion-basic-all-completions (string table pred point
)
2286 (let* ((beforepoint (substring string
0 point
))
2287 (afterpoint (substring string point
))
2288 (bounds (completion-boundaries beforepoint table pred afterpoint
))
2289 ;; (suffix (substring afterpoint (cdr bounds)))
2290 (prefix (substring beforepoint
0 (car bounds
)))
2292 "" (list (substring beforepoint
(car bounds
))
2294 (substring afterpoint
0 (cdr bounds
)))))
2295 (all (completion-pcm--all-completions prefix pattern table pred
)))
2296 (completion-hilit-commonality all point
(car bounds
))))
2298 ;;; Partial-completion-mode style completion.
2300 (defvar completion-pcm--delim-wild-regex nil
2301 "Regular expression matching delimiters controlling the partial-completion.
2302 Typically, this regular expression simply matches a delimiter, meaning
2303 that completion can add something at (match-beginning 0), but if it has
2304 a submatch 1, then completion can add something at (match-end 1).
2305 This is used when the delimiter needs to be of size zero (e.g. the transition
2306 from lowercase to uppercase characters).")
2308 (defun completion-pcm--prepare-delim-re (delims)
2309 (setq completion-pcm--delim-wild-regex
(concat "[" delims
"*]")))
2311 (defcustom completion-pcm-word-delimiters
"-_./:| "
2312 "A string of characters treated as word delimiters for completion.
2314 If `]' is in this string, it must come first.
2315 If `^' is in this string, it must not come first.
2316 If `-' is in this string, it must come first or right after `]'.
2317 In other words, if S is this string, then `[S]' must be a valid Emacs regular
2318 expression (not containing character ranges like `a-z')."
2319 :set
(lambda (symbol value
)
2320 (set-default symbol value
)
2321 ;; Refresh other vars.
2322 (completion-pcm--prepare-delim-re value
))
2323 :initialize
'custom-initialize-reset
2327 (defcustom completion-pcm-complete-word-inserts-delimiters nil
2328 "Treat the SPC or - inserted by `minibuffer-complete-word' as delimiters.
2329 Those chars are treated as delimiters iff this variable is non-nil.
2330 I.e. if non-nil, M-x SPC will just insert a \"-\" in the minibuffer, whereas
2331 if nil, it will list all possible commands in *Completions* because none of
2332 the commands start with a \"-\" or a SPC."
2336 (defun completion-pcm--pattern-trivial-p (pattern)
2337 (and (stringp (car pattern
))
2338 ;; It can be followed by `point' and "" and still be trivial.
2340 (dolist (elem (cdr pattern
))
2341 (unless (member elem
'(point ""))
2342 (setq trivial nil
)))
2345 (defun completion-pcm--string->pattern
(string &optional point
)
2346 "Split STRING into a pattern.
2347 A pattern is a list where each element is either a string
2348 or a symbol, see `completion-pcm--merge-completions'."
2349 (if (and point
(< point
(length string
)))
2350 (let ((prefix (substring string
0 point
))
2351 (suffix (substring string point
)))
2352 (append (completion-pcm--string->pattern prefix
)
2354 (completion-pcm--string->pattern suffix
)))
2355 (let* ((pattern nil
)
2359 (while (and (setq p
(string-match completion-pcm--delim-wild-regex
2361 (or completion-pcm-complete-word-inserts-delimiters
2362 ;; If the char was added by minibuffer-complete-word,
2363 ;; then don't treat it as a delimiter, otherwise
2364 ;; "M-x SPC" ends up inserting a "-" rather than listing
2366 (not (get-text-property p
'completion-try-word string
))))
2367 ;; Usually, completion-pcm--delim-wild-regex matches a delimiter,
2368 ;; meaning that something can be added *before* it, but it can also
2369 ;; match a prefix and postfix, in which case something can be added
2370 ;; in-between (e.g. match [[:lower:]][[:upper:]]).
2371 ;; This is determined by the presence of a submatch-1 which delimits
2373 (if (match-end 1) (setq p
(match-end 1)))
2374 (push (substring string p0 p
) pattern
)
2375 (if (eq (aref string p
) ?
*)
2377 (push 'star pattern
)
2383 ;; An empty string might be erroneously added at the beginning.
2384 ;; It should be avoided properly, but it's so easy to remove it here.
2385 (delete "" (nreverse (cons (substring string p0
) pattern
))))))
2387 (defun completion-pcm--pattern->regex
(pattern &optional group
)
2393 ((stringp x
) (regexp-quote x
))
2394 ((if (consp group
) (memq x group
) group
) "\\(.*?\\)")
2398 ;; Avoid pathological backtracking.
2399 (while (string-match "\\.\\*\\?\\(?:\\\\[()]\\)*\\(\\.\\*\\?\\)" re
)
2400 (setq re
(replace-match "" t t re
1)))
2403 (defun completion-pcm--all-completions (prefix pattern table pred
)
2404 "Find all completions for PATTERN in TABLE obeying PRED.
2405 PATTERN is as returned by `completion-pcm--string->pattern'."
2406 ;; (assert (= (car (completion-boundaries prefix table pred ""))
2407 ;; (length prefix)))
2408 ;; Find an initial list of possible completions.
2409 (if (completion-pcm--pattern-trivial-p pattern
)
2411 ;; Minibuffer contains no delimiters -- simple case!
2412 (all-completions (concat prefix
(car pattern
)) table pred
)
2414 ;; Use all-completions to do an initial cull. This is a big win,
2415 ;; since all-completions is written in C!
2416 (let* (;; Convert search pattern to a standard regular expression.
2417 (regex (completion-pcm--pattern->regex pattern
))
2418 (case-fold-search completion-ignore-case
)
2419 (completion-regexp-list (cons regex completion-regexp-list
))
2420 (compl (all-completions
2422 (if (stringp (car pattern
)) (car pattern
) ""))
2424 (if (not (functionp table
))
2425 ;; The internal functions already obeyed completion-regexp-list.
2429 (when (string-match-p regex c
) (push c poss
)))
2432 (defun completion-pcm--hilit-commonality (pattern completions
)
2434 (let* ((re (completion-pcm--pattern->regex pattern
'(point)))
2435 (case-fold-search completion-ignore-case
))
2438 ;; Don't modify the string itself.
2439 (setq str
(copy-sequence str
))
2440 (unless (string-match re str
)
2441 (error "Internal error: %s does not match %s" re str
))
2442 (let ((pos (or (match-beginning 1) (match-end 0))))
2443 (put-text-property 0 pos
2444 'font-lock-face
'completions-common-part
2446 (if (> (length str
) pos
)
2447 (put-text-property pos
(1+ pos
)
2448 'font-lock-face
'completions-first-difference
2453 (defun completion-pcm--find-all-completions (string table pred point
2455 "Find all completions for STRING at POINT in TABLE, satisfying PRED.
2456 POINT is a position inside STRING.
2457 FILTER is a function applied to the return value, that can be used, e.g. to
2458 filter out additional entries (because TABLE might not obey PRED)."
2459 (unless filter
(setq filter
'identity
))
2460 (let* ((beforepoint (substring string
0 point
))
2461 (afterpoint (substring string point
))
2462 (bounds (completion-boundaries beforepoint table pred afterpoint
))
2463 (prefix (substring beforepoint
0 (car bounds
)))
2464 (suffix (substring afterpoint
(cdr bounds
)))
2466 (setq string
(substring string
(car bounds
) (+ point
(cdr bounds
))))
2467 (let* ((relpoint (- point
(car bounds
)))
2468 (pattern (completion-pcm--string->pattern string relpoint
))
2469 (all (condition-case err
2471 (completion-pcm--all-completions
2472 prefix pattern table pred
))
2473 (error (unless firsterror
(setq firsterror err
)) nil
))))
2474 (when (and (null all
)
2476 (null (ignore-errors (try-completion prefix table pred
))))
2477 ;; The prefix has no completions at all, so we should try and fix
2479 (let ((substring (substring prefix
0 -
1)))
2480 (destructuring-bind (subpat suball subprefix _subsuffix
)
2481 (completion-pcm--find-all-completions
2482 substring table pred
(length substring
) filter
)
2483 (let ((sep (aref prefix
(1- (length prefix
))))
2484 ;; Text that goes between the new submatches and the
2485 ;; completion substring.
2487 ;; Eliminate submatches that don't end with the separator.
2488 (dolist (submatch (prog1 suball
(setq suball
())))
2489 (when (eq sep
(aref submatch
(1- (length submatch
))))
2490 (push submatch suball
)))
2492 ;; Update the boundaries and corresponding pattern.
2493 ;; We assume that all submatches result in the same boundaries
2494 ;; since we wouldn't know how to merge them otherwise anyway.
2495 ;; FIXME: COMPLETE REWRITE!!!
2496 (let* ((newbeforepoint
2497 (concat subprefix
(car suball
)
2498 (substring string
0 relpoint
)))
2499 (leftbound (+ (length subprefix
) (length (car suball
))))
2500 (newbounds (completion-boundaries
2501 newbeforepoint table pred afterpoint
)))
2502 (unless (or (and (eq (cdr bounds
) (cdr newbounds
))
2503 (eq (car newbounds
) leftbound
))
2504 ;; Refuse new boundaries if they step over
2506 (< (car newbounds
) leftbound
))
2507 ;; The new completed prefix does change the boundaries
2508 ;; of the completed substring.
2509 (setq suffix
(substring afterpoint
(cdr newbounds
)))
2511 (concat (substring newbeforepoint
(car newbounds
))
2512 (substring afterpoint
0 (cdr newbounds
))))
2513 (setq between
(substring newbeforepoint leftbound
2515 (setq pattern
(completion-pcm--string->pattern
2517 (- (length newbeforepoint
)
2519 (dolist (submatch suball
)
2522 (lambda (s) (concat submatch between s
))
2524 (completion-pcm--all-completions
2525 (concat subprefix submatch between
)
2526 pattern table pred
)))
2528 ;; FIXME: This can come in handy for try-completion,
2529 ;; but isn't right for all-completions, since it lists
2530 ;; invalid completions.
2532 ;; ;; Even though we found expansions in the prefix, none
2533 ;; ;; leads to a valid completion.
2534 ;; ;; Let's keep the expansions, tho.
2535 ;; (dolist (submatch suball)
2536 ;; (push (concat submatch between newsubstring) all)))
2538 (setq pattern
(append subpat
(list 'any
(string sep
))
2539 (if between
(list between
)) pattern
))
2540 (setq prefix subprefix
)))))
2541 (if (and (null all
) firsterror
)
2542 (signal (car firsterror
) (cdr firsterror
))
2543 (list pattern all prefix suffix
)))))
2545 (defun completion-pcm-all-completions (string table pred point
)
2546 (destructuring-bind (pattern all
&optional prefix _suffix
)
2547 (completion-pcm--find-all-completions string table pred point
)
2549 (nconc (completion-pcm--hilit-commonality pattern all
)
2552 (defun completion--sreverse (str)
2553 "Like `reverse' but for a string STR rather than a list."
2554 (apply 'string
(nreverse (mapcar 'identity str
))))
2556 (defun completion--common-suffix (strs)
2557 "Return the common suffix of the strings STRS."
2558 (completion--sreverse
2561 (mapcar 'completion--sreverse strs
))))
2563 (defun completion-pcm--merge-completions (strs pattern
)
2564 "Extract the commonality in STRS, with the help of PATTERN.
2565 PATTERN can contain strings and symbols chosen among `star', `any', `point',
2566 and `prefix'. They all match anything (aka \".*\") but are merged differently:
2567 `any' only grows from the left (when matching \"a1b\" and \"a2b\" it gets
2568 completed to just \"a\").
2569 `prefix' only grows from the right (when matching \"a1b\" and \"a2b\" it gets
2570 completed to just \"b\").
2571 `star' grows from both ends and is reified into a \"*\" (when matching \"a1b\"
2572 and \"a2b\" it gets completed to \"a*b\").
2573 `point' is like `star' except that it gets reified as the position of point
2574 instead of being reified as a \"*\" character.
2575 The underlying idea is that we should return a string which still matches
2576 the same set of elements."
2577 ;; When completing while ignoring case, we want to try and avoid
2578 ;; completing "fo" to "foO" when completing against "FOO" (bug#4219).
2579 ;; So we try and make sure that the string we return is all made up
2580 ;; of text from the completions rather than part from the
2581 ;; completions and part from the input.
2582 ;; FIXME: This reduces the problems of inconsistent capitalization
2583 ;; but it doesn't fully fix it: we may still end up completing
2584 ;; "fo-ba" to "foo-BAR" or "FOO-bar" when completing against
2585 ;; '("foo-barr" "FOO-BARD").
2587 ((null (cdr strs
)) (list (car strs
)))
2589 (let ((re (completion-pcm--pattern->regex pattern
'group
))
2590 (ccs ())) ;Chopped completions.
2592 ;; First chop each string into the parts corresponding to each
2593 ;; non-constant element of `pattern', using regexp-matching.
2594 (let ((case-fold-search completion-ignore-case
))
2596 (unless (string-match re str
)
2597 (error "Internal error: %s doesn't match %s" str re
))
2602 (while (setq next
(match-end i
))
2603 (push (substring str last next
) chopped
)
2606 ;; Add the text corresponding to the implicit trailing `any'.
2607 (push (substring str last
) chopped
)
2608 (push (nreverse chopped
) ccs
))))
2610 ;; Then for each of those non-constant elements, extract the
2611 ;; commonality between them.
2614 ;; Make the implicit trailing `any' explicit.
2615 (dolist (elem (append pattern
'(any)))
2617 (setq fixed
(concat fixed elem
))
2619 (dolist (cc (prog1 ccs
(setq ccs nil
)))
2620 (push (car cc
) comps
)
2621 (push (cdr cc
) ccs
))
2622 ;; Might improve the likelihood to avoid choosing
2623 ;; different capitalizations in different parts.
2624 ;; In practice, it doesn't seem to make any difference.
2625 (setq ccs
(nreverse ccs
))
2626 (let* ((prefix (try-completion fixed comps
))
2627 (unique (or (and (eq prefix t
) (setq prefix fixed
))
2628 (eq t
(try-completion prefix comps
)))))
2629 (unless (or (eq elem
'prefix
)
2632 ;; If there's only one completion, `elem' is not useful
2633 ;; any more: it can only match the empty string.
2634 ;; FIXME: in some cases, it may be necessary to turn an
2635 ;; `any' into a `star' because the surrounding context has
2636 ;; changed such that string->pattern wouldn't add an `any'
2640 (when (memq elem
'(star point prefix
))
2641 ;; Extract common suffix additionally to common prefix.
2642 ;; Only do it for `point', `star', and `prefix' since for
2643 ;; `any' it could lead to a merged completion that
2644 ;; doesn't itself match the candidates.
2645 (let ((suffix (completion--common-suffix comps
)))
2646 (assert (stringp suffix
))
2647 (unless (equal suffix
"")
2648 (push suffix res
)))))
2650 ;; We return it in reverse order.
2653 (defun completion-pcm--pattern->string
(pattern)
2654 (mapconcat (lambda (x) (cond
2657 (t ""))) ;any, point, prefix.
2661 ;; We want to provide the functionality of `try', but we use `all'
2662 ;; and then merge it. In most cases, this works perfectly, but
2663 ;; if the completion table doesn't consider the same completions in
2664 ;; `try' as in `all', then we have a problem. The most common such
2665 ;; case is for filename completion where completion-ignored-extensions
2666 ;; is only obeyed by the `try' code. We paper over the difference
2667 ;; here. Note that it is not quite right either: if the completion
2668 ;; table uses completion-table-in-turn, this filtering may take place
2669 ;; too late to correctly fallback from the first to the
2670 ;; second alternative.
2671 (defun completion-pcm--filename-try-filter (all)
2672 "Filter to adjust `all' file completion to the behavior of `try'."
2675 (re (concat "\\(?:\\`\\.\\.?/\\|"
2676 (regexp-opt completion-ignored-extensions
)
2679 (unless (string-match-p re f
) (push f try
)))
2683 (defun completion-pcm--merge-try (pattern all prefix suffix
)
2685 ((not (consp all
)) all
)
2686 ((and (not (consp (cdr all
))) ;Only one completion.
2687 ;; Ignore completion-ignore-case here.
2688 (equal (completion-pcm--pattern->string pattern
) (car all
)))
2691 (let* ((mergedpat (completion-pcm--merge-completions all pattern
))
2692 ;; `mergedpat' is in reverse order. Place new point (by
2693 ;; order of preference) either at the old point, or at
2694 ;; the last place where there's something to choose, or
2696 (pointpat (or (memq 'point mergedpat
)
2697 (memq 'any mergedpat
)
2698 (memq 'star mergedpat
)
2701 ;; New pos from the start.
2702 (newpos (length (completion-pcm--pattern->string pointpat
)))
2703 ;; Do it afterwards because it changes `pointpat' by side effect.
2704 (merged (completion-pcm--pattern->string
(nreverse mergedpat
))))
2706 (setq suffix
(completion--merge-suffix merged newpos suffix
))
2707 (cons (concat prefix merged suffix
) (+ newpos
(length prefix
)))))))
2709 (defun completion-pcm-try-completion (string table pred point
)
2710 (destructuring-bind (pattern all prefix suffix
)
2711 (completion-pcm--find-all-completions
2712 string table pred point
2713 (if minibuffer-completing-file-name
2714 'completion-pcm--filename-try-filter
))
2715 (completion-pcm--merge-try pattern all prefix suffix
)))
2717 ;;; Substring completion
2718 ;; Mostly derived from the code of `basic' completion.
2720 (defun completion-substring--all-completions (string table pred point
)
2721 (let* ((beforepoint (substring string
0 point
))
2722 (afterpoint (substring string point
))
2723 (bounds (completion-boundaries beforepoint table pred afterpoint
))
2724 (suffix (substring afterpoint
(cdr bounds
)))
2725 (prefix (substring beforepoint
0 (car bounds
)))
2726 (basic-pattern (completion-basic--pattern
2727 beforepoint afterpoint bounds
))
2728 (pattern (if (not (stringp (car basic-pattern
)))
2730 (cons 'prefix basic-pattern
)))
2731 (all (completion-pcm--all-completions prefix pattern table pred
)))
2732 (list all pattern prefix suffix
(car bounds
))))
2734 (defun completion-substring-try-completion (string table pred point
)
2735 (destructuring-bind (all pattern prefix suffix _carbounds
)
2736 (completion-substring--all-completions string table pred point
)
2737 (if minibuffer-completing-file-name
2738 (setq all
(completion-pcm--filename-try-filter all
)))
2739 (completion-pcm--merge-try pattern all prefix suffix
)))
2741 (defun completion-substring-all-completions (string table pred point
)
2742 (destructuring-bind (all pattern prefix _suffix _carbounds
)
2743 (completion-substring--all-completions string table pred point
)
2745 (nconc (completion-pcm--hilit-commonality pattern all
)
2748 ;; Initials completion
2749 ;; Complete /ums to /usr/monnier/src or lch to list-command-history.
2751 (defun completion-initials-expand (str table pred
)
2752 (let ((bounds (completion-boundaries str table pred
"")))
2753 (unless (or (zerop (length str
))
2754 ;; Only check within the boundaries, since the
2755 ;; boundary char (e.g. /) might be in delim-regexp.
2756 (string-match completion-pcm--delim-wild-regex str
2758 (if (zerop (car bounds
))
2759 (mapconcat 'string str
"-")
2760 ;; If there's a boundary, it's trickier. The main use-case
2761 ;; we consider here is file-name completion. We'd like
2762 ;; to expand ~/eee to ~/e/e/e and /eee to /e/e/e.
2763 ;; But at the same time, we don't want /usr/share/ae to expand
2764 ;; to /usr/share/a/e just because we mistyped "ae" for "ar",
2765 ;; so we probably don't want initials to touch anything that
2766 ;; looks like /usr/share/foo. As a heuristic, we just check that
2767 ;; the text before the boundary char is at most 1 char.
2768 ;; This allows both ~/eee and /eee and not much more.
2769 ;; FIXME: It sadly also disallows the use of ~/eee when that's
2770 ;; embedded within something else (e.g. "(~/eee" in Info node
2771 ;; completion or "ancestor:/eee" in bzr-revision completion).
2772 (when (< (car bounds
) 3)
2773 (let ((sep (substring str
(1- (car bounds
)) (car bounds
))))
2774 ;; FIXME: the above string-match checks the whole string, whereas
2775 ;; we end up only caring about the after-boundary part.
2776 (concat (substring str
0 (car bounds
))
2777 (mapconcat 'string
(substring str
(car bounds
)) sep
))))))))
2779 (defun completion-initials-all-completions (string table pred _point
)
2780 (let ((newstr (completion-initials-expand string table pred
)))
2782 (completion-pcm-all-completions newstr table pred
(length newstr
)))))
2784 (defun completion-initials-try-completion (string table pred _point
)
2785 (let ((newstr (completion-initials-expand string table pred
)))
2787 (completion-pcm-try-completion newstr table pred
(length newstr
)))))
2789 (defvar completing-read-function
'completing-read-default
2790 "The function called by `completing-read' to do its work.
2791 It should accept the same arguments as `completing-read'.")
2793 (defun completing-read-default (prompt collection
&optional predicate
2794 require-match initial-input
2795 hist def inherit-input-method
)
2796 "Default method for reading from the minibuffer with completion.
2797 See `completing-read' for the meaning of the arguments."
2799 (when (consp initial-input
)
2801 (cons (car initial-input
)
2802 ;; `completing-read' uses 0-based index while
2803 ;; `read-from-minibuffer' uses 1-based index.
2804 (1+ (cdr initial-input
)))))
2806 (let* ((minibuffer-completion-table collection
)
2807 (minibuffer-completion-predicate predicate
)
2808 (minibuffer-completion-confirm (unless (eq require-match t
)
2810 (base-keymap (if require-match
2811 minibuffer-local-must-match-map
2812 minibuffer-local-completion-map
))
2813 (keymap (if (memq minibuffer-completing-file-name
'(nil lambda
))
2815 ;; Layer minibuffer-local-filename-completion-map
2816 ;; on top of the base map.
2817 (make-composed-keymap
2818 minibuffer-local-filename-completion-map
2819 ;; Set base-keymap as the parent, so that nil bindings
2820 ;; in minibuffer-local-filename-completion-map can
2821 ;; override bindings in base-keymap.
2823 (result (read-from-minibuffer prompt initial-input keymap
2824 nil hist def inherit-input-method
)))
2825 (when (and (equal result
"") def
)
2826 (setq result
(if (consp def
) (car def
) def
)))
2831 (defun minibuffer-insert-file-name-at-point ()
2832 "Get a file name at point in original buffer and insert it to minibuffer."
2834 (let ((file-name-at-point
2835 (with-current-buffer (window-buffer (minibuffer-selected-window))
2836 (run-hook-with-args-until-success 'file-name-at-point-functions
))))
2837 (when file-name-at-point
2838 (insert file-name-at-point
))))
2840 (provide 'minibuffer
)
2842 ;;; minibuffer.el ends here