1 ;;; minibuffer.el --- Minibuffer completion functions
3 ;; Copyright (C) 2008, 2009, 2010 Free Software Foundation, Inc.
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
7 ;; This file is part of GNU Emacs.
9 ;; GNU Emacs is free software: you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;; Names with "--" are for functions and variables that are meant to be for
27 ;; Functional completion tables have an extended calling conventions:
28 ;; - The `action' can be (additionally to nil, t, and lambda) of the form
29 ;; (boundaries . SUFFIX) in which case it should return
30 ;; (boundaries START . END). See `completion-boundaries'.
31 ;; Any other return value should be ignored (so we ignore values returned
32 ;; from completion tables that don't know about this new `action' form).
36 ;; - completion-all-sorted-completions list all the completions, whereas
37 ;; it should only lists the ones that `try-completion' would consider.
38 ;; E.g. it should honor completion-ignored-extensions.
39 ;; - choose-completion can't automatically figure out the boundaries
40 ;; corresponding to the displayed completions because we only
41 ;; provide the start info but not the end info in
42 ;; completion-base-position.
43 ;; - quoting is problematic. E.g. the double-dollar quoting used in
44 ;; substitie-in-file-name (and hence read-file-name-internal) bumps
46 ;; - choose-completion doesn't know how to quote the text it inserts.
47 ;; E.g. it fails to double the dollars in file-name completion, or
48 ;; to backslash-escape spaces and other chars in comint completion.
49 ;; - when completing ~/tmp/fo$$o, the highligting in *Completions*
50 ;; is off by one position.
51 ;; - all code like PCM which relies on all-completions to match
52 ;; its argument gets confused because all-completions returns unquoted
53 ;; texts (as desired for *Completions* output).
54 ;; - C-x C-f ~/*/sr ? should not list "~/./src".
55 ;; - minibuffer-force-complete completes ~/src/emacs/t<!>/lisp/minibuffer.el
56 ;; to ~/src/emacs/trunk/ and throws away lisp/minibuffer.el.
60 ;; - extend `boundaries' to provide various other meta-data about the
61 ;; output of `all-completions':
62 ;; - preferred sorting order when displayed in *Completions*.
63 ;; - annotations/text-properties to add when displayed in *Completions*.
64 ;; - quoting/unquoting (so we can complete files names with envvars
65 ;; and backslashes, and all-completion can list names without
66 ;; quoting backslashes and dollars).
67 ;; - indicate how to turn all-completion's output into
68 ;; try-completion's output: e.g. completion-ignored-extensions.
69 ;; maybe that could be merged with the "quote" operation above.
70 ;; - completion hook to run when the completion is
71 ;; selected/inserted (maybe this should be provided some other
72 ;; way, e.g. as text-property, so `try-completion can also return it?)
73 ;; both for when it's inserted via TAB or via choose-completion.
74 ;; - indicate that `all-completions' doesn't do prefix-completion
75 ;; but just returns some list that relates in some other way to
76 ;; the provided string (as is the case in filecache.el), in which
77 ;; case partial-completion (for example) doesn't make any sense
78 ;; and neither does the completions-first-difference highlight.
79 ;; - indicate how to display the completions in *Completions* (turn
80 ;; \n into something else, add special boundaries between
81 ;; completions). E.g. when completing from the kill-ring.
83 ;; - make partial-completion-mode obsolete:
84 ;; - (?) <foo.h> style completion for file names.
85 ;; This can't be done identically just by tweaking completion,
86 ;; because partial-completion-mode's behavior is to expand <string.h>
87 ;; to /usr/include/string.h only when exiting the minibuffer, at which
88 ;; point the completion code is actually not involved normally.
89 ;; Partial-completion-mode does it via a find-file-not-found-function.
90 ;; - special code for C-x C-f <> to visit the file ref'd at point
91 ;; via (require 'foo) or #include "foo". ffap seems like a better
92 ;; place for this feature (supplemented with major-mode-provided
93 ;; functions to find the file ref'd at point).
95 ;; - case-sensitivity currently confuses two issues:
96 ;; - whether or not a particular completion table should be case-sensitive
97 ;; (i.e. whether strings that differ only by case are semantically
99 ;; - whether the user wants completion to pay attention to case.
100 ;; e.g. we may want to make it possible for the user to say "first try
101 ;; completion case-sensitively, and if that fails, try to ignore case".
103 ;; - add support for ** to pcm.
104 ;; - Add vc-file-name-completion-table to read-file-name-internal.
105 ;; - A feature like completing-help.el.
109 (eval-when-compile (require 'cl
))
111 ;;; Completion table manipulation
113 ;; New completion-table operation.
114 (defun completion-boundaries (string table pred suffix
)
115 "Return the boundaries of the completions returned by TABLE for STRING.
116 STRING is the string on which completion will be performed.
117 SUFFIX is the string after point.
118 The result is of the form (START . END) where START is the position
119 in STRING of the beginning of the completion field and END is the position
120 in SUFFIX of the end of the completion field.
121 E.g. for simple completion tables, the result is always (0 . (length SUFFIX))
122 and for file names the result is the positions delimited by
123 the closest directory separators."
124 (let ((boundaries (if (functionp table
)
125 (funcall table string pred
(cons 'boundaries suffix
)))))
126 (if (not (eq (car-safe boundaries
) 'boundaries
))
127 (setq boundaries nil
))
128 (cons (or (cadr boundaries
) 0)
129 (or (cddr boundaries
) (length suffix
)))))
131 (defun completion--some (fun xs
)
132 "Apply FUN to each element of XS in turn.
133 Return the first non-nil returned value.
135 (let ((firsterror nil
)
137 (while (and (not res
) xs
)
139 (setq res
(funcall fun
(pop xs
)))
140 (error (unless firsterror
(setq firsterror err
)) nil
)))
142 (if firsterror
(signal (car firsterror
) (cdr firsterror
))))))
144 (defun complete-with-action (action table string pred
)
145 "Perform completion ACTION.
146 STRING is the string to complete.
147 TABLE is the completion table, which should not be a function.
148 PRED is a completion predicate.
149 ACTION can be one of nil, t or `lambda'."
151 ((functionp table
) (funcall table string pred action
))
152 ((eq (car-safe action
) 'boundaries
)
153 (cons 'boundaries
(completion-boundaries string table pred
(cdr action
))))
157 ((null action
) 'try-completion
)
158 ((eq action t
) 'all-completions
)
159 (t 'test-completion
))
160 string table pred
))))
162 (defun completion-table-dynamic (fun)
163 "Use function FUN as a dynamic completion table.
164 FUN is called with one argument, the string for which completion is required,
165 and it should return an alist containing all the intended possible completions.
166 This alist may be a full list of possible completions so that FUN can ignore
167 the value of its argument. If completion is performed in the minibuffer,
168 FUN will be called in the buffer from which the minibuffer was entered.
170 The result of the `completion-table-dynamic' form is a function
171 that can be used as the COLLECTION argument to `try-completion' and
172 `all-completions'. See Info node `(elisp)Programmed Completion'."
173 (lexical-let ((fun fun
))
174 (lambda (string pred action
)
175 (with-current-buffer (let ((win (minibuffer-selected-window)))
176 (if (window-live-p win
) (window-buffer win
)
178 (complete-with-action action
(funcall fun string
) string pred
)))))
180 (defmacro lazy-completion-table
(var fun
)
181 "Initialize variable VAR as a lazy completion table.
182 If the completion table VAR is used for the first time (e.g., by passing VAR
183 as an argument to `try-completion'), the function FUN is called with no
184 arguments. FUN must return the completion table that will be stored in VAR.
185 If completion is requested in the minibuffer, FUN will be called in the buffer
186 from which the minibuffer was entered. The return value of
187 `lazy-completion-table' must be used to initialize the value of VAR.
189 You should give VAR a non-nil `risky-local-variable' property."
190 (declare (debug (symbolp lambda-expr
)))
191 (let ((str (make-symbol "string")))
192 `(completion-table-dynamic
194 (when (functionp ,var
)
198 (defun completion-table-with-context (prefix table string pred action
)
199 ;; TODO: add `suffix' maybe?
200 ;; Notice that `pred' may not be a function in some abusive cases.
201 (when (functionp pred
)
203 (lexical-let ((pred pred
))
204 ;; Predicates are called differently depending on the nature of
205 ;; the completion table :-(
207 ((vectorp table
) ;Obarray.
208 (lambda (sym) (funcall pred
(concat prefix
(symbol-name sym
)))))
209 ((hash-table-p table
)
210 (lambda (s v
) (funcall pred
(concat prefix s
))))
212 (lambda (s) (funcall pred
(concat prefix s
))))
213 (t ;Lists and alists.
215 (funcall pred
(concat prefix
(if (consp s
) (car s
) s
)))))))))
216 (if (eq (car-safe action
) 'boundaries
)
217 (let* ((len (length prefix
))
218 (bound (completion-boundaries string table pred
(cdr action
))))
219 (list* 'boundaries
(+ (car bound
) len
) (cdr bound
)))
220 (let ((comp (complete-with-action action table string pred
)))
222 ;; In case of try-completion, add the prefix.
223 ((stringp comp
) (concat prefix comp
))
226 (defun completion-table-with-terminator (terminator table string pred action
)
227 "Construct a completion table like TABLE but with an extra TERMINATOR.
228 This is meant to be called in a curried way by first passing TERMINATOR
229 and TABLE only (via `apply-partially').
230 TABLE is a completion table, and TERMINATOR is a string appended to TABLE's
231 completion if it is complete. TERMINATOR is also used to determine the
232 completion suffix's boundary.
233 TERMINATOR can also be a cons cell (TERMINATOR . TERMINATOR-REGEXP)
234 in which case TERMINATOR-REGEXP is a regular expression whose submatch
235 number 1 should match TERMINATOR. This is used when there is a need to
236 distinguish occurrences of the TERMINATOR strings which are really terminators
237 from others (e.g. escaped)."
239 ((eq (car-safe action
) 'boundaries
)
240 (let* ((suffix (cdr action
))
241 (bounds (completion-boundaries string table pred suffix
))
242 (terminator-regexp (if (consp terminator
)
243 (cdr terminator
) (regexp-quote terminator
)))
244 (max (string-match terminator-regexp suffix
)))
245 (list* 'boundaries
(car bounds
)
246 (min (cdr bounds
) (or max
(length suffix
))))))
248 (let ((comp (try-completion string table pred
)))
249 (if (consp terminator
) (setq terminator
(car terminator
)))
251 (concat string terminator
)
252 (if (and (stringp comp
)
253 ;; FIXME: Try to avoid this second call, especially since
254 ;; it may be very inefficient (because `comp' made us
255 ;; jump to a new boundary, so we complete in that
256 ;; boundary with an empty start string).
257 ;; completion-boundaries might help.
258 (eq (try-completion comp table pred
) t
))
259 (concat comp terminator
)
262 ;; FIXME: We generally want the `try' and `all' behaviors to be
263 ;; consistent so pcm can merge the `all' output to get the `try' output,
264 ;; but that sometimes clashes with the need for `all' output to look
265 ;; good in *Completions*.
266 ;; (mapcar (lambda (s) (concat s terminator))
267 ;; (all-completions string table pred))))
268 (all-completions string table pred
))
269 ;; completion-table-with-terminator is always used for
270 ;; "sub-completions" so it's only called if the terminator is missing,
271 ;; in which case `test-completion' should return nil.
272 ((eq action
'lambda
) nil
)))
274 (defun completion-table-with-predicate (table pred1 strict string pred2 action
)
275 "Make a completion table equivalent to TABLE but filtered through PRED1.
276 PRED1 is a function of one argument which returns non-nil if and only if the
277 argument is an element of TABLE which should be considered for completion.
278 STRING, PRED2, and ACTION are the usual arguments to completion tables,
279 as described in `try-completion', `all-completions', and `test-completion'.
280 If STRICT is t, the predicate always applies; if nil it only applies if
281 it does not reduce the set of possible completions to nothing.
282 Note: TABLE needs to be a proper completion table which obeys predicates."
284 ((and (not strict
) (eq action
'lambda
))
285 ;; Ignore pred1 since it doesn't really have to apply anyway.
286 (test-completion string table pred2
))
288 (or (complete-with-action action table string
289 (if (null pred2
) pred1
290 (lexical-let ((pred1 pred2
) (pred2 pred2
))
292 ;; Call `pred1' first, so that `pred2'
293 ;; really can't tell that `x' is in table.
294 (if (funcall pred1 x
) (funcall pred2 x
))))))
295 ;; If completion failed and we're not applying pred1 strictly, try
296 ;; again without pred1.
298 (complete-with-action action table string pred2
))))))
300 (defun completion-table-in-turn (&rest tables
)
301 "Create a completion table that tries each table in TABLES in turn."
302 ;; FIXME: the boundaries may come from TABLE1 even when the completion list
303 ;; is returned by TABLE2 (because TABLE1 returned an empty list).
304 (lexical-let ((tables tables
))
305 (lambda (string pred action
)
306 (completion--some (lambda (table)
307 (complete-with-action action table string pred
))
310 ;; (defmacro complete-in-turn (a b) `(completion-table-in-turn ,a ,b))
311 ;; (defmacro dynamic-completion-table (fun) `(completion-table-dynamic ,fun))
312 (define-obsolete-function-alias
313 'complete-in-turn
'completion-table-in-turn
"23.1")
314 (define-obsolete-function-alias
315 'dynamic-completion-table
'completion-table-dynamic
"23.1")
317 ;;; Minibuffer completion
319 (defgroup minibuffer nil
320 "Controlling the behavior of the minibuffer."
321 :link
'(custom-manual "(emacs)Minibuffer")
324 (defun minibuffer-message (message &rest args
)
325 "Temporarily display MESSAGE at the end of the minibuffer.
326 The text is displayed for `minibuffer-message-timeout' seconds,
327 or until the next input event arrives, whichever comes first.
328 Enclose MESSAGE in [...] if this is not yet the case.
329 If ARGS are provided, then pass MESSAGE through `format'."
330 (if (not (minibufferp (current-buffer)))
333 (apply 'message message args
)
334 (message "%s" message
))
335 (prog1 (sit-for (or minibuffer-message-timeout
1000000))
337 ;; Clear out any old echo-area message to make way for our new thing.
339 (setq message
(if (and (null args
) (string-match-p "\\` *\\[.+\\]\\'" message
))
340 ;; Make sure we can put-text-property.
341 (copy-sequence message
)
342 (concat " [" message
"]")))
343 (when args
(setq message
(apply 'format message args
)))
344 (let ((ol (make-overlay (point-max) (point-max) nil t t
))
345 ;; A quit during sit-for normally only interrupts the sit-for,
346 ;; but since minibuffer-message is used at the end of a command,
347 ;; at a time when the command has virtually finished already, a C-g
348 ;; should really cause an abort-recursive-edit instead (i.e. as if
349 ;; the C-g had been typed at top-level). Binding inhibit-quit here
350 ;; is an attempt to get that behavior.
354 (unless (zerop (length message
))
355 ;; The current C cursor code doesn't know to use the overlay's
356 ;; marker's stickiness to figure out whether to place the cursor
357 ;; before or after the string, so let's spoon-feed it the pos.
358 (put-text-property 0 1 'cursor t message
))
359 (overlay-put ol
'after-string message
)
360 (sit-for (or minibuffer-message-timeout
1000000)))
361 (delete-overlay ol
)))))
363 (defun minibuffer-completion-contents ()
364 "Return the user input in a minibuffer before point as a string.
365 That is what completion commands operate on."
366 (buffer-substring (field-beginning) (point)))
368 (defun delete-minibuffer-contents ()
369 "Delete all user input in a minibuffer.
370 If the current buffer is not a minibuffer, erase its entire contents."
371 ;; We used to do `delete-field' here, but when file name shadowing
372 ;; is on, the field doesn't cover the entire minibuffer contents.
373 (delete-region (minibuffer-prompt-end) (point-max)))
375 (defcustom completion-auto-help t
376 "Non-nil means automatically provide help for invalid completion input.
377 If the value is t the *Completion* buffer is displayed whenever completion
378 is requested but cannot be done.
379 If the value is `lazy', the *Completions* buffer is only displayed after
380 the second failed attempt to complete."
381 :type
'(choice (const nil
) (const t
) (const lazy
))
384 (defconst completion-styles-alist
386 completion-emacs21-try-completion completion-emacs21-all-completions
387 "Simple prefix-based completion.
388 I.e. when completing \"foo_bar\" (where _ is the position of point),
389 it will consider all completions candidates matching the glob
390 pattern \"foobar*\".")
392 completion-emacs22-try-completion completion-emacs22-all-completions
393 "Prefix completion that only operates on the text before point.
394 I.e. when completing \"foo_bar\" (where _ is the position of point),
395 it will consider all completions candidates matching the glob
396 pattern \"foo*\" and will add back \"bar\" to the end of it.")
398 completion-basic-try-completion completion-basic-all-completions
399 "Completion of the prefix before point and the suffix after point.
400 I.e. when completing \"foo_bar\" (where _ is the position of point),
401 it will consider all completions candidates matching the glob
402 pattern \"foo*bar*\".")
404 completion-pcm-try-completion completion-pcm-all-completions
405 "Completion of multiple words, each one taken as a prefix.
406 I.e. when completing \"l-co_h\" (where _ is the position of point),
407 it will consider all completions candidates matching the glob
408 pattern \"l*-co*h*\".
409 Furthermore, for completions that are done step by step in subfields,
410 the method is applied to all the preceding fields that do not yet match.
411 E.g. C-x C-f /u/mo/s TAB could complete to /usr/monnier/src.
412 Additionally the user can use the char \"*\" as a glob pattern.")
414 completion-substring-try-completion completion-substring-all-completions
415 "Completion of the string taken as a substring.
416 I.e. when completing \"foo_bar\" (where _ is the position of point),
417 it will consider all completions candidates matching the glob
418 pattern \"*foo*bar*\".")
420 completion-initials-try-completion completion-initials-all-completions
421 "Completion of acronyms and initialisms.
422 E.g. can complete M-x lch to list-command-history
423 and C-x C-f ~/sew to ~/src/emacs/work."))
424 "List of available completion styles.
425 Each element has the form (NAME TRY-COMPLETION ALL-COMPLETIONS DOC):
426 where NAME is the name that should be used in `completion-styles',
427 TRY-COMPLETION is the function that does the completion (it should
428 follow the same calling convention as `completion-try-completion'),
429 ALL-COMPLETIONS is the function that lists the completions (it should
430 follow the calling convention of `completion-all-completions'),
431 and DOC describes the way this style of completion works.")
433 (defcustom completion-styles
434 ;; First, use `basic' because prefix completion has been the standard
435 ;; for "ever" and works well in most cases, so using it first
436 ;; ensures that we obey previous behavior in most cases.
438 ;; Then use `partial-completion' because it has proven to
439 ;; be a very convenient extension.
441 ;; Finally use `emacs22' so as to maintain (in many/most cases)
442 ;; the previous behavior that when completing "foobar" with point
443 ;; between "foo" and "bar" the completion try to complete "foo"
444 ;; and simply add "bar" to the end of the result.
446 "List of completion styles to use.
447 The available styles are listed in `completion-styles-alist'."
448 :type
`(repeat (choice ,@(mapcar (lambda (x) (list 'const
(car x
)))
449 completion-styles-alist
)))
453 (defun completion-try-completion (string table pred point
)
454 "Try to complete STRING using completion table TABLE.
455 Only the elements of table that satisfy predicate PRED are considered.
456 POINT is the position of point within STRING.
457 The return value can be either nil to indicate that there is no completion,
458 t to indicate that STRING is the only possible completion,
459 or a pair (STRING . NEWPOINT) of the completed result string together with
460 a new position for point."
461 (completion--some (lambda (style)
462 (funcall (nth 1 (assq style completion-styles-alist
))
463 string table pred point
))
466 (defun completion-all-completions (string table pred point
)
467 "List the possible completions of STRING in completion table TABLE.
468 Only the elements of table that satisfy predicate PRED are considered.
469 POINT is the position of point within STRING.
470 The return value is a list of completions and may contain the base-size
472 ;; FIXME: We need to additionally return the info needed for the
473 ;; second part of completion-base-position.
474 (completion--some (lambda (style)
475 (funcall (nth 2 (assq style completion-styles-alist
))
476 string table pred point
))
479 (defun minibuffer--bitset (modified completions exact
)
480 (logior (if modified
4 0)
484 (defun completion--replace (beg end newtext
)
485 "Replace the buffer text between BEG and END with NEWTEXT.
486 Moves point to the end of the new text."
487 ;; This should be in subr.el.
488 ;; You'd think this is trivial to do, but details matter if you want
489 ;; to keep markers "at the right place" and be robust in the face of
490 ;; after-change-functions that may themselves modify the buffer.
493 (delete-region (point) (+ (point) (- end beg
))))
495 (defcustom completion-cycle-threshold nil
496 "Number of completion candidates below which cycling is used.
497 Depending on this setting `minibuffer-complete' may use cycling,
498 like `minibuffer-force-complete'.
499 If nil, cycling is never used.
500 If t, cycling is always used.
501 If an integer, cycling is used as soon as there are fewer completion
502 candidates than this number."
503 :type
'(choice (const :tag
"No cycling" nil
)
504 (const :tag
"Always cycle" t
)
505 (integer :tag
"Threshold")))
507 (defun completion--do-completion (&optional try-completion-function
)
508 "Do the completion and return a summary of what happened.
509 M = completion was performed, the text was Modified.
510 C = there were available Completions.
511 E = after completion we now have an Exact match.
514 000 0 no possible completion
515 001 1 was already an exact and unique completion
516 010 2 no completion happened
517 011 3 was already an exact completion
520 110 6 some completion happened
521 111 7 completed to an exact completion"
522 (let* ((beg (field-beginning))
524 (string (buffer-substring beg end
))
525 (comp (funcall (or try-completion-function
526 'completion-try-completion
)
528 minibuffer-completion-table
529 minibuffer-completion-predicate
533 (minibuffer-hide-completions)
534 (ding) (minibuffer-message "No match") (minibuffer--bitset nil nil nil
))
536 (minibuffer-hide-completions)
537 (goto-char (field-end))
538 (minibuffer--bitset nil nil t
)) ;Exact and unique match.
540 ;; `completed' should be t if some completion was done, which doesn't
541 ;; include simply changing the case of the entered string. However,
542 ;; for appearance, the string is rewritten if the case changes.
543 (let* ((comp-pos (cdr comp
))
544 (completion (car comp
))
545 (completed (not (eq t
(compare-strings completion nil nil
547 (unchanged (eq t
(compare-strings completion nil nil
548 string nil nil nil
))))
551 ;; Insert in minibuffer the chars we got.
552 (completion--replace beg end completion
))
553 ;; Move point to its completion-mandated destination.
554 (forward-char (- comp-pos
(length completion
)))
556 (if (not (or unchanged completed
))
557 ;; The case of the string changed, but that's all. We're not sure
558 ;; whether this is a unique completion or not, so try again using
559 ;; the real case (this shouldn't recurse again, because the next
560 ;; time try-completion will return either t or the exact string).
561 (completion--do-completion try-completion-function
)
563 ;; It did find a match. Do we match some possibility exactly now?
564 (let ((exact (test-completion completion
565 minibuffer-completion-table
566 minibuffer-completion-predicate
))
568 ;; Check to see if we want to do cycling. We do it
569 ;; here, after having performed the normal completion,
570 ;; so as to take advantage of the difference between
571 ;; try-completion and all-completions, for things
572 ;; like completion-ignored-extensions.
573 (when (and completion-cycle-threshold
574 ;; Check that the completion didn't make
575 ;; us jump to a different boundary.
577 (< (car (completion-boundaries
578 (substring completion
0 comp-pos
)
579 minibuffer-completion-table
580 minibuffer-completion-predicate
583 (completion-all-sorted-completions))))
584 (setq completion-all-sorted-completions nil
)
586 ((and (not (ignore-errors
587 ;; This signal an (intended) error if comps is too
588 ;; short or if completion-cycle-threshold is t.
589 (consp (nthcdr completion-cycle-threshold comps
))))
590 ;; More than 1, so there's something to cycle.
592 ;; Fewer than completion-cycle-threshold remaining
593 ;; completions: let's cycle.
594 (setq completed t exact t
)
595 (setq completion-all-sorted-completions comps
)
596 (minibuffer-force-complete))
598 ;; We could also decide to refresh the completions,
599 ;; if they're displayed (and assuming there are
600 ;; completions left).
601 (minibuffer-hide-completions))
602 ;; Show the completion table, if requested.
604 (if (case completion-auto-help
605 (lazy (eq this-command last-command
))
606 (t completion-auto-help
))
607 (minibuffer-completion-help)
608 (minibuffer-message "Next char not unique")))
609 ;; If the last exact completion and this one were the same, it
610 ;; means we've already given a "Next char not unique" message
611 ;; and the user's hit TAB again, so now we give him help.
612 ((eq this-command last-command
)
613 (if completion-auto-help
(minibuffer-completion-help))))
615 (minibuffer--bitset completed t exact
))))))))
617 (defun minibuffer-complete ()
618 "Complete the minibuffer contents as far as possible.
619 Return nil if there is no valid completion, else t.
620 If no characters can be completed, display a list of possible completions.
621 If you repeat this command after it displayed such a list,
622 scroll the window of possible completions."
624 ;; If the previous command was not this,
625 ;; mark the completion buffer obsolete.
626 (unless (eq this-command last-command
)
627 (setq completion-all-sorted-completions nil
)
628 (setq minibuffer-scroll-window nil
))
631 ;; If there's a fresh completion window with a live buffer,
632 ;; and this command is repeated, scroll that window.
633 ((window-live-p minibuffer-scroll-window
)
634 (let ((window minibuffer-scroll-window
))
635 (with-current-buffer (window-buffer window
)
636 (if (pos-visible-in-window-p (point-max) window
)
637 ;; If end is in view, scroll up to the beginning.
638 (set-window-start window
(point-min) nil
)
639 ;; Else scroll down one screen.
640 (scroll-other-window))
642 ;; If we're cycling, keep on cycling.
643 (completion-all-sorted-completions
644 (minibuffer-force-complete)
646 (t (case (completion--do-completion)
648 (#b001
(minibuffer-message "Sole completion")
650 (#b011
(minibuffer-message "Complete, but not unique")
654 (defvar completion-all-sorted-completions nil
)
655 (make-variable-buffer-local 'completion-all-sorted-completions
)
657 (defun completion--flush-all-sorted-completions (&rest ignore
)
658 (setq completion-all-sorted-completions nil
))
660 (defun completion-all-sorted-completions ()
661 (or completion-all-sorted-completions
662 (let* ((start (field-beginning))
664 (all (completion-all-completions (buffer-substring start end
)
665 minibuffer-completion-table
666 minibuffer-completion-predicate
669 (base-size (or (cdr last
) 0)))
672 ;; Prefer shorter completions.
673 (setq all
(sort all
(lambda (c1 c2
) (< (length c1
) (length c2
)))))
674 ;; Prefer recently used completions.
675 (let ((hist (symbol-value minibuffer-history-variable
)))
676 (setq all
(sort all
(lambda (c1 c2
)
677 (> (length (member c1 hist
))
678 (length (member c2 hist
)))))))
679 ;; Cache the result. This is not just for speed, but also so that
680 ;; repeated calls to minibuffer-force-complete can cycle through
681 ;; all possibilities.
682 (add-hook 'after-change-functions
683 'completion--flush-all-sorted-completions nil t
)
684 (setq completion-all-sorted-completions
685 (nconc all base-size
))))))
687 (defun minibuffer-force-complete ()
688 "Complete the minibuffer to an exact match.
689 Repeated uses step through the possible completions."
691 ;; FIXME: Need to deal with the extra-size issue here as well.
692 ;; FIXME: ~/src/emacs/t<M-TAB>/lisp/minibuffer.el completes to
693 ;; ~/src/emacs/trunk/ and throws away lisp/minibuffer.el.
694 (let* ((start (field-beginning))
696 (all (completion-all-sorted-completions)))
697 (if (not (consp all
))
698 (minibuffer-message (if all
"No more completions" "No completions"))
701 (delete-region (+ start
(cdr (last all
))) end
)
702 ;; If completing file names, (car all) may be a directory, so we'd now
703 ;; have a new set of possible completions and might want to reset
704 ;; completion-all-sorted-completions to nil, but we prefer not to,
705 ;; so that repeated calls minibuffer-force-complete still cycle
706 ;; through the previous possible completions.
707 (let ((last (last all
)))
708 (setcdr last
(cons (car all
) (cdr last
)))
709 (setq completion-all-sorted-completions
(cdr all
))))))
711 (defvar minibuffer-confirm-exit-commands
712 '(minibuffer-complete minibuffer-complete-word PC-complete PC-complete-word
)
713 "A list of commands which cause an immediately following
714 `minibuffer-complete-and-exit' to ask for extra confirmation.")
716 (defun minibuffer-complete-and-exit ()
717 "Exit if the minibuffer contains a valid completion.
718 Otherwise, try to complete the minibuffer contents. If
719 completion leads to a valid completion, a repetition of this
722 If `minibuffer-completion-confirm' is `confirm', do not try to
723 complete; instead, ask for confirmation and accept any input if
725 If `minibuffer-completion-confirm' is `confirm-after-completion',
726 do not try to complete; instead, ask for confirmation if the
727 preceding minibuffer command was a member of
728 `minibuffer-confirm-exit-commands', and accept the input
731 (let ((beg (field-beginning))
734 ;; Allow user to specify null string
735 ((= beg end
) (exit-minibuffer))
736 ((test-completion (buffer-substring beg end
)
737 minibuffer-completion-table
738 minibuffer-completion-predicate
)
739 ;; FIXME: completion-ignore-case has various slightly
740 ;; incompatible meanings. E.g. it can reflect whether the user
741 ;; wants completion to pay attention to case, or whether the
742 ;; string will be used in a context where case is significant.
743 ;; E.g. usually try-completion should obey the first, whereas
744 ;; test-completion should obey the second.
745 (when completion-ignore-case
746 ;; Fixup case of the field, if necessary.
747 (let* ((string (buffer-substring beg end
))
748 (compl (try-completion
750 minibuffer-completion-table
751 minibuffer-completion-predicate
)))
752 (when (and (stringp compl
) (not (equal string compl
))
753 ;; If it weren't for this piece of paranoia, I'd replace
754 ;; the whole thing with a call to do-completion.
755 ;; This is important, e.g. when the current minibuffer's
756 ;; content is a directory which only contains a single
757 ;; file, so `try-completion' actually completes to
759 (= (length string
) (length compl
)))
762 (delete-region beg end
))))
765 ((memq minibuffer-completion-confirm
'(confirm confirm-after-completion
))
766 ;; The user is permitted to exit with an input that's rejected
767 ;; by test-completion, after confirming her choice.
768 (if (or (eq last-command this-command
)
769 ;; For `confirm-after-completion' we only ask for confirmation
770 ;; if trying to exit immediately after typing TAB (this
771 ;; catches most minibuffer typos).
772 (and (eq minibuffer-completion-confirm
'confirm-after-completion
)
773 (not (memq last-command minibuffer-confirm-exit-commands
))))
775 (minibuffer-message "Confirm")
779 ;; Call do-completion, but ignore errors.
780 (case (condition-case nil
781 (completion--do-completion)
783 ((#b001
#b011
) (exit-minibuffer))
784 (#b111
(if (not minibuffer-completion-confirm
)
786 (minibuffer-message "Confirm")
790 (defun completion--try-word-completion (string table predicate point
)
791 (let ((comp (completion-try-completion string table predicate point
)))
792 (if (not (consp comp
))
795 ;; If completion finds next char not unique,
796 ;; consider adding a space or a hyphen.
797 (when (= (length string
) (length (car comp
)))
798 ;; Mark the added char with the `completion-word' property, so it
799 ;; can be handled specially by completion styles such as
800 ;; partial-completion.
801 ;; We used to remove `partial-completion' from completion-styles
802 ;; instead, but it was too blunt, leading to situations where SPC
803 ;; was the only insertable char at point but minibuffer-complete-word
804 ;; refused inserting it.
805 (let ((exts (mapcar (lambda (str) (propertize str
'completion-try-word t
))
807 (before (substring string
0 point
))
808 (after (substring string point
))
810 (while (and exts
(not (consp tem
)))
811 (setq tem
(completion-try-completion
812 (concat before
(pop exts
) after
)
813 table predicate
(1+ point
))))
814 (if (consp tem
) (setq comp tem
))))
816 ;; Completing a single word is actually more difficult than completing
817 ;; as much as possible, because we first have to find the "current
818 ;; position" in `completion' in order to find the end of the word
819 ;; we're completing. Normally, `string' is a prefix of `completion',
820 ;; which makes it trivial to find the position, but with fancier
821 ;; completion (plus env-var expansion, ...) `completion' might not
822 ;; look anything like `string' at all.
823 (let* ((comppoint (cdr comp
))
824 (completion (car comp
))
825 (before (substring string
0 point
))
826 (combined (concat before
"\n" completion
)))
827 ;; Find in completion the longest text that was right before point.
828 (when (string-match "\\(.+\\)\n.*?\\1" combined
)
829 (let* ((prefix (match-string 1 before
))
830 ;; We used non-greedy match to make `rem' as long as possible.
831 (rem (substring combined
(match-end 0)))
832 ;; Find in the remainder of completion the longest text
833 ;; that was right after point.
834 (after (substring string point
))
835 (suffix (if (string-match "\\`\\(.+\\).*\n.*\\1"
836 (concat after
"\n" rem
))
837 (match-string 1 after
))))
838 ;; The general idea is to try and guess what text was inserted
839 ;; at point by the completion. Problem is: if we guess wrong,
840 ;; we may end up treating as "added by completion" text that was
841 ;; actually painfully typed by the user. So if we then cut
842 ;; after the first word, we may throw away things the
843 ;; user wrote. So let's try to be as conservative as possible:
844 ;; only cut after the first word, if we're reasonably sure that
845 ;; our guess is correct.
846 ;; Note: a quick survey on emacs-devel seemed to indicate that
847 ;; nobody actually cares about the "word-at-a-time" feature of
848 ;; minibuffer-complete-word, whose real raison-d'être is that it
849 ;; tries to add "-" or " ". One more reason to only cut after
850 ;; the first word, if we're really sure we're right.
851 (when (and (or suffix
(zerop (length after
)))
852 (string-match (concat
853 ;; Make submatch 1 as small as possible
854 ;; to reduce the risk of cutting
856 ".*" (regexp-quote prefix
) "\\(.*?\\)"
857 (if suffix
(regexp-quote suffix
) "\\'"))
859 ;; The new point in `completion' should also be just
860 ;; before the suffix, otherwise something more complex
861 ;; is going on, and we're not sure where we are.
862 (eq (match-end 1) comppoint
)
863 ;; (match-beginning 1)..comppoint is now the stretch
864 ;; of text in `completion' that was completed at point.
865 (string-match "\\W" completion
(match-beginning 1))
866 ;; Is there really something to cut?
867 (> comppoint
(match-end 0)))
868 ;; Cut after the first word.
869 (let ((cutpos (match-end 0)))
870 (setq completion
(concat (substring completion
0 cutpos
)
871 (substring completion comppoint
)))
872 (setq comppoint cutpos
)))))
874 (cons completion comppoint
)))))
877 (defun minibuffer-complete-word ()
878 "Complete the minibuffer contents at most a single word.
879 After one word is completed as much as possible, a space or hyphen
880 is added, provided that matches some possible completion.
881 Return nil if there is no valid completion, else t."
883 (case (completion--do-completion 'completion--try-word-completion
)
885 (#b001
(minibuffer-message "Sole completion")
887 (#b011
(minibuffer-message "Complete, but not unique")
891 (defface completions-annotations
'((t :inherit italic
))
892 "Face to use for annotations in the *Completions* buffer.")
894 (defcustom completions-format nil
895 "Define the appearance and sorting of completions.
896 If the value is `vertical', display completions sorted vertically
897 in columns in the *Completions* buffer.
898 If the value is `horizontal' or nil, display completions sorted
899 horizontally in alphabetical order, rather than down the screen."
900 :type
'(choice (const nil
) (const horizontal
) (const vertical
))
904 (defun completion--insert-strings (strings)
905 "Insert a list of STRINGS into the current buffer.
906 Uses columns to keep the listing readable but compact.
907 It also eliminates runs of equal strings."
908 (when (consp strings
)
909 (let* ((length (apply 'max
912 (+ (string-width (car s
))
913 (string-width (cadr s
)))
916 (window (get-buffer-window (current-buffer) 0))
917 (wwidth (if window
(1- (window-width window
)) 79))
919 ;; At least 2 columns; at least 2 spaces between columns.
920 (max 2 (/ wwidth
(+ 2 length
)))
921 ;; Don't allocate more columns than we can fill.
922 ;; Windows can't show less than 3 lines anyway.
923 (max 1 (/ (length strings
) 2))))
924 (colwidth (/ wwidth columns
))
926 (rows (/ (length strings
) columns
))
929 ;; The insertion should be "sensible" no matter what choices were made
930 ;; for the parameters above.
931 (dolist (str strings
)
932 (unless (equal laststring str
) ; Remove (consecutive) duplicates.
933 (setq laststring str
)
934 (let ((length (if (consp str
)
935 (+ (string-width (car str
))
936 (string-width (cadr str
)))
937 (string-width str
))))
939 ((eq completions-format
'vertical
)
942 (forward-line (- -
1 rows
))
943 (setq row
0 column
(+ column colwidth
)))
946 (while (> (current-column) column
)
952 (set-text-properties (- (point) 1) (point)
953 `(display (space :align-to
,column
)))))
957 (if (< wwidth
(+ (max colwidth length
) column
))
958 ;; No space for `str' at point, move to next line.
959 (progn (insert "\n") (setq column
0))
961 ;; Leave the space unpropertized so that in the case we're
962 ;; already past the goal column, there is still
963 ;; a space displayed.
964 (set-text-properties (- (point) 1) (point)
965 ;; We can't just set tab-width, because
966 ;; completion-setup-function will kill all
967 ;; local variables :-(
968 `(display (space :align-to
,column
)))
970 (if (not (consp str
))
971 (put-text-property (point) (progn (insert str
) (point))
972 'mouse-face
'highlight
)
973 (put-text-property (point) (progn (insert (car str
)) (point))
974 'mouse-face
'highlight
)
975 (add-text-properties (point) (progn (insert (cadr str
)) (point))
977 face completions-annotations
)))
979 ((eq completions-format
'vertical
)
987 ;; Next column to align to.
988 (setq column
(+ column
989 ;; Round up to a whole number of columns.
990 (* colwidth
(ceiling length colwidth
))))))))))))
992 (defvar completion-common-substring nil
)
993 (make-obsolete-variable 'completion-common-substring nil
"23.1")
995 (defvar completion-setup-hook nil
996 "Normal hook run at the end of setting up a completion list buffer.
997 When this hook is run, the current buffer is the one in which the
998 command to display the completion list buffer was run.
999 The completion list buffer is available as the value of `standard-output'.
1000 See also `display-completion-list'.")
1002 (defface completions-first-difference
1003 '((t (:inherit bold
)))
1004 "Face put on the first uncommon character in completions in *Completions* buffer."
1007 (defface completions-common-part
1008 '((t (:inherit default
)))
1009 "Face put on the common prefix substring in completions in *Completions* buffer.
1010 The idea of `completions-common-part' is that you can use it to
1011 make the common parts less visible than normal, so that the rest
1012 of the differing parts is, by contrast, slightly highlighted."
1015 (defun completion-hilit-commonality (completions prefix-len base-size
)
1017 (let ((com-str-len (- prefix-len
(or base-size
0))))
1022 ;; Don't modify the string itself, but a copy, since the
1023 ;; the string may be read-only or used for other purposes.
1024 ;; Furthermore, since `completions' may come from
1025 ;; display-completion-list, `elem' may be a list.
1027 (car (setq elem
(cons (copy-sequence (car elem
))
1029 (setq elem
(copy-sequence elem
)))))
1030 (put-text-property 0
1031 ;; If completion-boundaries returns incorrect
1032 ;; values, all-completions may return strings
1033 ;; that don't contain the prefix.
1034 (min com-str-len
(length str
))
1035 'font-lock-face
'completions-common-part
1037 (if (> (length str
) com-str-len
)
1038 (put-text-property com-str-len
(1+ com-str-len
)
1039 'font-lock-face
'completions-first-difference
1045 (defun display-completion-list (completions &optional common-substring
)
1046 "Display the list of completions, COMPLETIONS, using `standard-output'.
1047 Each element may be just a symbol or string
1048 or may be a list of two strings to be printed as if concatenated.
1049 If it is a list of two strings, the first is the actual completion
1050 alternative, the second serves as annotation.
1051 `standard-output' must be a buffer.
1052 The actual completion alternatives, as inserted, are given `mouse-face'
1053 properties of `highlight'.
1054 At the end, this runs the normal hook `completion-setup-hook'.
1055 It can find the completion buffer in `standard-output'.
1057 The obsolete optional arg COMMON-SUBSTRING, if non-nil, should be a string
1058 specifying a common substring for adding the faces
1059 `completions-first-difference' and `completions-common-part' to
1060 the completions buffer."
1061 (if common-substring
1062 (setq completions
(completion-hilit-commonality
1063 completions
(length common-substring
)
1064 ;; We don't know the base-size.
1066 (if (not (bufferp standard-output
))
1067 ;; This *never* (ever) happens, so there's no point trying to be clever.
1069 (let ((standard-output (current-buffer))
1070 (completion-setup-hook nil
))
1071 (display-completion-list completions common-substring
))
1072 (princ (buffer-string)))
1074 (with-current-buffer standard-output
1075 (goto-char (point-max))
1076 (if (null completions
)
1077 (insert "There are no possible completions of what you have typed.")
1078 (insert "Possible completions are:\n")
1079 (completion--insert-strings completions
))))
1081 ;; The hilit used to be applied via completion-setup-hook, so there
1082 ;; may still be some code that uses completion-common-substring.
1084 (let ((completion-common-substring common-substring
))
1085 (run-hooks 'completion-setup-hook
)))
1088 (defvar completion-annotate-function
1090 ;; Note: there's a lot of scope as for when to add annotations and
1091 ;; what annotations to add. E.g. completing-help.el allowed adding
1092 ;; the first line of docstrings to M-x completion. But there's
1093 ;; a tension, since such annotations, while useful at times, can
1094 ;; actually drown the useful information.
1095 ;; So completion-annotate-function should be used parsimoniously, or
1096 ;; else only used upon a user's request (e.g. we could add a command
1097 ;; to completion-list-mode to add annotations to the current
1099 "Function to add annotations in the *Completions* buffer.
1100 The function takes a completion and should either return nil, or a string that
1101 will be displayed next to the completion. The function can access the
1102 completion table and predicates via `minibuffer-completion-table' and related
1105 (defun minibuffer-completion-help ()
1106 "Display a list of possible completions of the current minibuffer contents."
1108 (message "Making completion list...")
1109 (let* ((non-essential t
)
1110 (start (field-beginning))
1111 (string (field-string))
1112 (completions (completion-all-completions
1114 minibuffer-completion-table
1115 minibuffer-completion-predicate
1116 (- (point) (field-beginning)))))
1118 (if (and completions
1119 (or (consp (cdr completions
))
1120 (not (equal (car completions
) string
))))
1121 (let* ((last (last completions
))
1122 (base-size (cdr last
))
1123 ;; If the *Completions* buffer is shown in a new
1124 ;; window, mark it as softly-dedicated, so bury-buffer in
1125 ;; minibuffer-hide-completions will know whether to
1126 ;; delete the window or not.
1127 (display-buffer-mark-dedicated 'soft
))
1128 (with-output-to-temp-buffer "*Completions*"
1129 ;; Remove the base-size tail because `sort' requires a properly
1130 ;; nil-terminated list.
1131 (when last
(setcdr last nil
))
1132 (setq completions
(sort completions
'string-lessp
))
1133 (when completion-annotate-function
1137 (funcall completion-annotate-function s
)))
1138 (if ann
(list s ann
) s
)))
1140 (with-current-buffer standard-output
1141 (set (make-local-variable 'completion-base-position
)
1142 ;; FIXME: We should provide the END part as well, but
1143 ;; currently completion-all-completions does not give
1144 ;; us the necessary information.
1145 (list (+ start base-size
) nil
)))
1146 (display-completion-list completions
)))
1148 ;; If there are no completions, or if the current input is already the
1149 ;; only possible completion, then hide (previous&stale) completions.
1150 (minibuffer-hide-completions)
1153 (if completions
"Sole completion" "No completions")))
1156 (defun minibuffer-hide-completions ()
1157 "Get rid of an out-of-date *Completions* buffer."
1158 ;; FIXME: We could/should use minibuffer-scroll-window here, but it
1159 ;; can also point to the minibuffer-parent-window, so it's a bit tricky.
1160 (let ((win (get-buffer-window "*Completions*" 0)))
1161 (if win
(with-selected-window win
(bury-buffer)))))
1163 (defun exit-minibuffer ()
1164 "Terminate this minibuffer argument."
1166 ;; If the command that uses this has made modifications in the minibuffer,
1167 ;; we don't want them to cause deactivation of the mark in the original
1169 ;; A better solution would be to make deactivate-mark buffer-local
1170 ;; (or to turn it into a list of buffers, ...), but in the mean time,
1171 ;; this should do the trick in most cases.
1172 (setq deactivate-mark nil
)
1175 (defun self-insert-and-exit ()
1176 "Terminate minibuffer input."
1178 (if (characterp last-command-event
)
1179 (call-interactively 'self-insert-command
)
1183 (defvar completion-in-region-functions nil
1184 "Wrapper hook around `completion-in-region'.
1185 The functions on this special hook are called with 5 arguments:
1186 NEXT-FUN START END COLLECTION PREDICATE.
1187 NEXT-FUN is a function of four arguments (START END COLLECTION PREDICATE)
1188 that performs the default operation. The other four arguments are like
1189 the ones passed to `completion-in-region'. The functions on this hook
1190 are expected to perform completion on START..END using COLLECTION
1191 and PREDICATE, either by calling NEXT-FUN or by doing it themselves.")
1193 (defun completion-in-region (start end collection
&optional predicate
)
1194 "Complete the text between START and END using COLLECTION.
1195 Return nil if there is no valid completion, else t.
1196 Point needs to be somewhere between START and END."
1197 (assert (<= start
(point)) (<= (point) end
))
1198 ;; FIXME: undisplay the *Completions* buffer once the completion is done.
1200 completion-in-region-functions
(start end collection predicate
)
1201 (let ((minibuffer-completion-table collection
)
1202 (minibuffer-completion-predicate predicate
)
1203 (ol (make-overlay start end nil nil t
)))
1204 (overlay-put ol
'field
'completion
)
1206 (call-interactively 'minibuffer-complete
)
1207 (delete-overlay ol
)))))
1209 (defvar completion-at-point-functions
'(tags-completion-at-point-function)
1210 "Special hook to find the completion table for the thing at point.
1211 It is called without any argument and should return either nil,
1212 or a function of no argument to perform completion (discouraged),
1213 or a list of the form (START END COLLECTION &rest PROPS) where
1214 START and END delimit the entity to complete and should include point,
1215 COLLECTION is the completion table to use to complete it, and
1216 PROPS is a property list for additional information.
1217 Currently supported properties are:
1218 `:predicate' a predicate that completion candidates need to satisfy.
1219 `:annotation-function' the value to use for `completion-annotate-function'.")
1221 (defun completion-at-point (&optional arg
)
1222 "Perform completion on the text around point.
1223 The completion method is determined by `completion-at-point-functions'.
1225 With a prefix argument, this command does completion within
1226 the collection of symbols listed in the index of the manual for the
1227 language you are using."
1230 (info-complete-symbol)
1231 (let ((res (run-hook-with-args-until-success
1232 'completion-at-point-functions
)))
1234 ((functionp res
) (funcall res
))
1236 (let* ((plist (nthcdr 3 res
))
1239 (completion-annotate-function
1240 (or (plist-get plist
:annotation-function
)
1241 completion-annotate-function
)))
1242 (completion-in-region start end
(nth 2 res
)
1243 (plist-get plist
:predicate
))))))))
1245 (define-obsolete-function-alias 'complete-symbol
'completion-at-point
"24.1")
1249 (define-obsolete-variable-alias 'minibuffer-local-must-match-filename-map
1250 'minibuffer-local-filename-must-match-map
"23.1")
1252 (let ((map minibuffer-local-map
))
1253 (define-key map
"\C-g" 'abort-recursive-edit
)
1254 (define-key map
"\r" 'exit-minibuffer
)
1255 (define-key map
"\n" 'exit-minibuffer
))
1257 (let ((map minibuffer-local-completion-map
))
1258 (define-key map
"\t" 'minibuffer-complete
)
1259 ;; M-TAB is already abused for many other purposes, so we should find
1260 ;; another binding for it.
1261 ;; (define-key map "\e\t" 'minibuffer-force-complete)
1262 (define-key map
" " 'minibuffer-complete-word
)
1263 (define-key map
"?" 'minibuffer-completion-help
))
1265 (let ((map minibuffer-local-must-match-map
))
1266 (define-key map
"\r" 'minibuffer-complete-and-exit
)
1267 (define-key map
"\n" 'minibuffer-complete-and-exit
))
1269 (let ((map minibuffer-local-filename-completion-map
))
1270 (define-key map
" " nil
))
1271 (let ((map minibuffer-local-filename-must-match-map
))
1272 (define-key map
" " nil
))
1274 (let ((map minibuffer-local-ns-map
))
1275 (define-key map
" " 'exit-minibuffer
)
1276 (define-key map
"\t" 'exit-minibuffer
)
1277 (define-key map
"?" 'self-insert-and-exit
))
1279 ;;; Completion tables.
1281 (defun minibuffer--double-dollars (str)
1282 (replace-regexp-in-string "\\$" "$$" str
))
1284 (defun completion--make-envvar-table ()
1285 (mapcar (lambda (enventry)
1286 (substring enventry
0 (string-match-p "=" enventry
)))
1287 process-environment
))
1289 (defconst completion--embedded-envvar-re
1290 (concat "\\(?:^\\|[^$]\\(?:\\$\\$\\)*\\)"
1291 "$\\([[:alnum:]_]*\\|{\\([^}]*\\)\\)\\'"))
1293 (defun completion--embedded-envvar-table (string pred action
)
1294 "Completion table for envvars embedded in a string.
1295 The envvar syntax (and escaping) rules followed by this table are the
1296 same as `substitute-in-file-name'."
1297 ;; We ignore `pred', because the predicates passed to us via
1298 ;; read-file-name-internal are not 100% correct and fail here:
1299 ;; e.g. we get predicates like file-directory-p there, whereas the filename
1300 ;; completed needs to be passed through substitute-in-file-name before it
1301 ;; can be passed to file-directory-p.
1302 (when (string-match completion--embedded-envvar-re string
)
1303 (let* ((beg (or (match-beginning 2) (match-beginning 1)))
1304 (table (completion--make-envvar-table))
1305 (prefix (substring string
0 beg
)))
1307 ((eq action
'lambda
)
1308 ;; This table is expected to be used in conjunction with some
1309 ;; other table that provides the "main" completion. Let the
1310 ;; other table handle the test-completion case.
1312 ((eq (car-safe action
) 'boundaries
)
1313 ;; Only return boundaries if there's something to complete,
1314 ;; since otherwise when we're used in
1315 ;; completion-table-in-turn, we could return boundaries and
1316 ;; let some subsequent table return a list of completions.
1317 ;; FIXME: Maybe it should rather be fixed in
1318 ;; completion-table-in-turn instead, but it's difficult to
1319 ;; do it efficiently there.
1320 (when (try-completion (substring string beg
) table nil
)
1321 ;; Compute the boundaries of the subfield to which this
1322 ;; completion applies.
1323 (let ((suffix (cdr action
)))
1325 (or (match-beginning 2) (match-beginning 1))
1326 (when (string-match "[^[:alnum:]_]" suffix
)
1327 (match-beginning 0))))))
1329 (if (eq (aref string
(1- beg
)) ?
{)
1330 (setq table
(apply-partially 'completion-table-with-terminator
1332 ;; Even if file-name completion is case-insensitive, we want
1333 ;; envvar completion to be case-sensitive.
1334 (let ((completion-ignore-case nil
))
1335 (completion-table-with-context
1336 prefix table
(substring string beg
) nil action
)))))))
1338 (defun completion-file-name-table (string pred action
)
1339 "Completion table for file names."
1342 ((eq (car-safe action
) 'boundaries
)
1343 (let ((start (length (file-name-directory string
)))
1344 (end (string-match-p "/" (cdr action
))))
1346 ;; if `string' is "C:" in w32, (file-name-directory string)
1347 ;; returns "C:/", so `start' is 3 rather than 2.
1348 ;; Not quite sure what is The Right Fix, but clipping it
1349 ;; back to 2 will work for this particular case. We'll
1350 ;; see if we can come up with a better fix when we bump
1351 ;; into more such problematic cases.
1352 (min start
(length string
)) end
)))
1354 ((eq action
'lambda
)
1355 (if (zerop (length string
))
1356 nil
;Not sure why it's here, but it probably doesn't harm.
1357 (funcall (or pred
'file-exists-p
) string
)))
1360 (let* ((name (file-name-nondirectory string
))
1361 (specdir (file-name-directory string
))
1362 (realdir (or specdir default-directory
)))
1366 (let ((comp (file-name-completion name realdir pred
)))
1368 (concat specdir comp
)
1372 (let ((all (file-name-all-completions name realdir
)))
1374 ;; Check the predicate, if necessary.
1375 (unless (memq pred
'(nil file-exists-p
))
1378 (if (eq pred
'file-directory-p
)
1379 ;; Brute-force speed up for directory checking:
1380 ;; Discard strings which don't end in a slash.
1382 (let ((len (length s
)))
1383 (and (> len
0) (eq (aref s
(1- len
)) ?
/))))
1384 ;; Must do it the hard (and slow) way.
1386 (let ((default-directory (expand-file-name realdir
)))
1388 (if (funcall pred tem
) (push tem comp
))))
1389 (setq all
(nreverse comp
))))
1393 (defvar read-file-name-predicate nil
1394 "Current predicate used by `read-file-name-internal'.")
1395 (make-obsolete-variable 'read-file-name-predicate
1396 "use the regular PRED argument" "23.2")
1398 (defun completion--file-name-table (string pred action
)
1399 "Internal subroutine for `read-file-name'. Do not call this.
1400 This is a completion table for file names, like `completion-file-name-table'
1401 except that it passes the file name through `substitute-in-file-name'."
1403 ((eq (car-safe action
) 'boundaries
)
1404 ;; For the boundaries, we can't really delegate to
1405 ;; substitute-in-file-name+completion-file-name-table and then fix
1406 ;; them up (as we do for the other actions), because it would
1407 ;; require us to track the relationship between `str' and
1408 ;; `string', which is difficult. And in any case, if
1409 ;; substitute-in-file-name turns "fo-$TO-ba" into "fo-o/b-ba",
1410 ;; there's no way for us to return proper boundaries info, because
1411 ;; the boundary is not (yet) in `string'.
1413 ;; FIXME: Actually there is a way to return correct boundaries
1414 ;; info, at the condition of modifying the all-completions
1415 ;; return accordingly. But for now, let's not bother.
1416 (completion-file-name-table string pred action
))
1419 (let* ((default-directory
1421 ;; It used to be that `pred' was abused to pass `dir'
1423 (prog1 (file-name-as-directory (expand-file-name pred
))
1426 (str (condition-case nil
1427 (substitute-in-file-name string
)
1429 (comp (completion-file-name-table
1431 (with-no-warnings (or pred read-file-name-predicate
))
1436 ;; Requote the $s before returning the completion.
1437 (minibuffer--double-dollars comp
))
1438 ((and (null action
) comp
1439 ;; Requote the $s before checking for changes.
1440 (setq str
(minibuffer--double-dollars str
))
1441 (not (string-equal string str
)))
1442 ;; If there's no real completion, but substitute-in-file-name
1443 ;; changed the string, then return the new string.
1447 (defalias 'read-file-name-internal
1448 (completion-table-in-turn 'completion--embedded-envvar-table
1449 'completion--file-name-table
)
1450 "Internal subroutine for `read-file-name'. Do not call this.")
1452 (defvar read-file-name-function nil
1453 "If this is non-nil, `read-file-name' does its work by calling this function.")
1455 (defcustom read-file-name-completion-ignore-case
1456 (if (memq system-type
'(ms-dos windows-nt darwin cygwin
))
1458 "Non-nil means when reading a file name completion ignores case."
1463 (defcustom insert-default-directory t
1464 "Non-nil means when reading a filename start with default dir in minibuffer.
1466 When the initial minibuffer contents show a name of a file or a directory,
1467 typing RETURN without editing the initial contents is equivalent to typing
1468 the default file name.
1470 If this variable is non-nil, the minibuffer contents are always
1471 initially non-empty, and typing RETURN without editing will fetch the
1472 default name, if one is provided. Note however that this default name
1473 is not necessarily the same as initial contents inserted in the minibuffer,
1474 if the initial contents is just the default directory.
1476 If this variable is nil, the minibuffer often starts out empty. In
1477 that case you may have to explicitly fetch the next history element to
1478 request the default name; typing RETURN without editing will leave
1479 the minibuffer empty.
1481 For some commands, exiting with an empty minibuffer has a special meaning,
1482 such as making the current buffer visit no file in the case of
1483 `set-visited-file-name'."
1487 ;; Not always defined, but only called if next-read-file-uses-dialog-p says so.
1488 (declare-function x-file-dialog
"xfns.c"
1489 (prompt dir
&optional default-filename mustmatch only-dir-p
))
1491 (defun read-file-name-defaults (&optional dir initial
)
1494 ;; With non-nil `initial', use `dir' as the first default.
1495 ;; Essentially, this mean reversing the normal order of the
1496 ;; current directory name and the current file name, i.e.
1497 ;; 1. with normal file reading:
1498 ;; 1.1. initial input is the current directory
1499 ;; 1.2. the first default is the current file name
1500 ;; 2. with non-nil `initial' (e.g. for `find-alternate-file'):
1501 ;; 2.2. initial input is the current file name
1502 ;; 2.1. the first default is the current directory
1503 (initial (abbreviate-file-name dir
))
1504 ;; In file buffers, try to get the current file name
1506 (abbreviate-file-name buffer-file-name
))))
1508 (run-hook-with-args-until-success 'file-name-at-point-functions
)))
1509 (when file-name-at-point
1510 (setq default
(delete-dups
1511 (delete "" (delq nil
(list file-name-at-point default
))))))
1512 ;; Append new defaults to the end of existing `minibuffer-default'.
1514 (if (listp minibuffer-default
) minibuffer-default
(list minibuffer-default
))
1515 (if (listp default
) default
(list default
)))))
1517 (defun read-file-name (prompt &optional dir default-filename mustmatch initial predicate
)
1518 "Read file name, prompting with PROMPT and completing in directory DIR.
1519 Value is not expanded---you must call `expand-file-name' yourself.
1520 Default name to DEFAULT-FILENAME if user exits the minibuffer with
1521 the same non-empty string that was inserted by this function.
1522 (If DEFAULT-FILENAME is omitted, the visited file name is used,
1523 except that if INITIAL is specified, that combined with DIR is used.
1524 If DEFAULT-FILENAME is a list of file names, the first file name is used.)
1525 If the user exits with an empty minibuffer, this function returns
1526 an empty string. (This can only happen if the user erased the
1527 pre-inserted contents or if `insert-default-directory' is nil.)
1529 Fourth arg MUSTMATCH can take the following values:
1530 - nil means that the user can exit with any input.
1531 - t means that the user is not allowed to exit unless
1532 the input is (or completes to) an existing file.
1533 - `confirm' means that the user can exit with any input, but she needs
1534 to confirm her choice if the input is not an existing file.
1535 - `confirm-after-completion' means that the user can exit with any
1536 input, but she needs to confirm her choice if she called
1537 `minibuffer-complete' right before `minibuffer-complete-and-exit'
1538 and the input is not an existing file.
1539 - anything else behaves like t except that typing RET does not exit if it
1540 does non-null completion.
1542 Fifth arg INITIAL specifies text to start with.
1544 If optional sixth arg PREDICATE is non-nil, possible completions and
1545 the resulting file name must satisfy (funcall PREDICATE NAME).
1546 DIR should be an absolute directory name. It defaults to the value of
1547 `default-directory'.
1549 If this command was invoked with the mouse, use a graphical file
1550 dialog if `use-dialog-box' is non-nil, and the window system or X
1551 toolkit in use provides a file dialog box, and DIR is not a
1552 remote file. For graphical file dialogs, any the special values
1553 of MUSTMATCH; `confirm' and `confirm-after-completion' are
1554 treated as equivalent to nil.
1556 See also `read-file-name-completion-ignore-case'
1557 and `read-file-name-function'."
1558 (unless dir
(setq dir default-directory
))
1559 (unless (file-name-absolute-p dir
) (setq dir
(expand-file-name dir
)))
1560 (unless default-filename
1561 (setq default-filename
(if initial
(expand-file-name initial dir
)
1563 ;; If dir starts with user's homedir, change that to ~.
1564 (setq dir
(abbreviate-file-name dir
))
1565 ;; Likewise for default-filename.
1566 (if default-filename
1567 (setq default-filename
1568 (if (consp default-filename
)
1569 (mapcar 'abbreviate-file-name default-filename
)
1570 (abbreviate-file-name default-filename
))))
1572 ((and insert-default-directory
(stringp dir
))
1574 (cons (minibuffer--double-dollars (concat dir initial
))
1575 (length (minibuffer--double-dollars dir
)))
1576 (minibuffer--double-dollars dir
)))
1577 (initial (cons (minibuffer--double-dollars initial
) 0)))))
1579 (if read-file-name-function
1580 (funcall read-file-name-function
1581 prompt dir default-filename mustmatch initial predicate
)
1582 (let ((completion-ignore-case read-file-name-completion-ignore-case
)
1583 (minibuffer-completing-file-name t
)
1584 (pred (or predicate
'file-exists-p
))
1585 (add-to-history nil
))
1588 (if (or (not (next-read-file-uses-dialog-p))
1589 ;; Graphical file dialogs can't handle remote
1591 (file-remote-p dir
))
1592 ;; We used to pass `dir' to `read-file-name-internal' by
1593 ;; abusing the `predicate' argument. It's better to
1594 ;; just use `default-directory', but in order to avoid
1595 ;; changing `default-directory' in the current buffer,
1596 ;; we don't let-bind it.
1597 (lexical-let ((dir (file-name-as-directory
1598 (expand-file-name dir
))))
1599 (minibuffer-with-setup-hook
1601 (setq default-directory dir
)
1602 ;; When the first default in `minibuffer-default'
1603 ;; duplicates initial input `insdef',
1604 ;; reset `minibuffer-default' to nil.
1605 (when (equal (or (car-safe insdef
) insdef
)
1606 (or (car-safe minibuffer-default
)
1607 minibuffer-default
))
1608 (setq minibuffer-default
1609 (cdr-safe minibuffer-default
)))
1610 ;; On the first request on `M-n' fill
1611 ;; `minibuffer-default' with a list of defaults
1612 ;; relevant for file-name reading.
1613 (set (make-local-variable 'minibuffer-default-add-function
)
1615 (with-current-buffer
1616 (window-buffer (minibuffer-selected-window))
1617 (read-file-name-defaults dir initial
)))))
1618 (completing-read prompt
'read-file-name-internal
1619 pred mustmatch insdef
1620 'file-name-history default-filename
)))
1621 ;; If DEFAULT-FILENAME not supplied and DIR contains
1622 ;; a file name, split it.
1623 (let ((file (file-name-nondirectory dir
))
1624 ;; When using a dialog, revert to nil and non-nil
1625 ;; interpretation of mustmatch. confirm options
1626 ;; need to be interpreted as nil, otherwise
1627 ;; it is impossible to create new files using
1628 ;; dialogs with the default settings.
1630 (not (memq mustmatch
1631 '(nil confirm confirm-after-completion
)))))
1632 (when (and (not default-filename
)
1633 (not (zerop (length file
))))
1634 (setq default-filename file
)
1635 (setq dir
(file-name-directory dir
)))
1636 (when default-filename
1637 (setq default-filename
1638 (expand-file-name (if (consp default-filename
)
1639 (car default-filename
)
1642 (setq add-to-history t
)
1643 (x-file-dialog prompt dir default-filename
1645 (eq predicate
'file-directory-p
)))))
1647 (replace-in-history (eq (car-safe file-name-history
) val
)))
1648 ;; If completing-read returned the inserted default string itself
1649 ;; (rather than a new string with the same contents),
1650 ;; it has to mean that the user typed RET with the minibuffer empty.
1651 ;; In that case, we really want to return ""
1652 ;; so that commands such as set-visited-file-name can distinguish.
1653 (when (consp default-filename
)
1654 (setq default-filename
(car default-filename
)))
1655 (when (eq val default-filename
)
1656 ;; In this case, completing-read has not added an element
1657 ;; to the history. Maybe we should.
1658 (if (not replace-in-history
)
1659 (setq add-to-history t
))
1661 (unless val
(error "No file name specified"))
1663 (if (and default-filename
1664 (string-equal val
(if (consp insdef
) (car insdef
) insdef
)))
1665 (setq val default-filename
))
1666 (setq val
(substitute-in-file-name val
))
1668 (if replace-in-history
1669 ;; Replace what Fcompleting_read added to the history
1670 ;; with what we will actually return. As an exception,
1671 ;; if that's the same as the second item in
1672 ;; file-name-history, it's really a repeat (Bug#4657).
1673 (let ((val1 (minibuffer--double-dollars val
)))
1674 (if history-delete-duplicates
1675 (setcdr file-name-history
1676 (delete val1
(cdr file-name-history
))))
1677 (if (string= val1
(cadr file-name-history
))
1678 (pop file-name-history
)
1679 (setcar file-name-history val1
)))
1681 ;; Add the value to the history--but not if it matches
1682 ;; the last value already there.
1683 (let ((val1 (minibuffer--double-dollars val
)))
1684 (unless (and (consp file-name-history
)
1685 (equal (car file-name-history
) val1
))
1686 (setq file-name-history
1688 (if history-delete-duplicates
1689 (delete val1 file-name-history
)
1690 file-name-history
)))))))
1693 (defun internal-complete-buffer-except (&optional buffer
)
1694 "Perform completion on all buffers excluding BUFFER.
1695 BUFFER nil or omitted means use the current buffer.
1696 Like `internal-complete-buffer', but removes BUFFER from the completion list."
1697 (lexical-let ((except (if (stringp buffer
) buffer
(buffer-name buffer
))))
1698 (apply-partially 'completion-table-with-predicate
1699 'internal-complete-buffer
1701 (not (equal (if (consp name
) (car name
) name
) except
)))
1704 ;;; Old-style completion, used in Emacs-21 and Emacs-22.
1706 (defun completion-emacs21-try-completion (string table pred point
)
1707 (let ((completion (try-completion string table pred
)))
1708 (if (stringp completion
)
1709 (cons completion
(length completion
))
1712 (defun completion-emacs21-all-completions (string table pred point
)
1713 (completion-hilit-commonality
1714 (all-completions string table pred
)
1716 (car (completion-boundaries string table pred
""))))
1718 (defun completion-emacs22-try-completion (string table pred point
)
1719 (let ((suffix (substring string point
))
1720 (completion (try-completion (substring string
0 point
) table pred
)))
1721 (if (not (stringp completion
))
1723 ;; Merge a trailing / in completion with a / after point.
1724 ;; We used to only do it for word completion, but it seems to make
1725 ;; sense for all completions.
1726 ;; Actually, claiming this feature was part of Emacs-22 completion
1727 ;; is pushing it a bit: it was only done in minibuffer-completion-word,
1728 ;; which was (by default) not bound during file completion, where such
1729 ;; slashes are most likely to occur.
1730 (if (and (not (zerop (length completion
)))
1731 (eq ?
/ (aref completion
(1- (length completion
))))
1732 (not (zerop (length suffix
)))
1733 (eq ?
/ (aref suffix
0)))
1734 ;; This leaves point after the / .
1735 (setq suffix
(substring suffix
1)))
1736 (cons (concat completion suffix
) (length completion
)))))
1738 (defun completion-emacs22-all-completions (string table pred point
)
1739 (let ((beforepoint (substring string
0 point
)))
1740 (completion-hilit-commonality
1741 (all-completions beforepoint table pred
)
1743 (car (completion-boundaries beforepoint table pred
"")))))
1745 ;;; Basic completion.
1747 (defun completion--merge-suffix (completion point suffix
)
1748 "Merge end of COMPLETION with beginning of SUFFIX.
1749 Simple generalization of the \"merge trailing /\" done in Emacs-22.
1750 Return the new suffix."
1751 (if (and (not (zerop (length suffix
)))
1752 (string-match "\\(.+\\)\n\\1" (concat completion
"\n" suffix
)
1753 ;; Make sure we don't compress things to less
1754 ;; than we started with.
1756 ;; Just make sure we didn't match some other \n.
1757 (eq (match-end 1) (length completion
)))
1758 (substring suffix
(- (match-end 1) (match-beginning 1)))
1759 ;; Nothing to merge.
1762 (defun completion-basic--pattern (beforepoint afterpoint bounds
)
1764 "" (list (substring beforepoint
(car bounds
))
1766 (substring afterpoint
0 (cdr bounds
)))))
1768 (defun completion-basic-try-completion (string table pred point
)
1769 (let* ((beforepoint (substring string
0 point
))
1770 (afterpoint (substring string point
))
1771 (bounds (completion-boundaries beforepoint table pred afterpoint
)))
1772 (if (zerop (cdr bounds
))
1773 ;; `try-completion' may return a subtly different result
1774 ;; than `all+merge', so try to use it whenever possible.
1775 (let ((completion (try-completion beforepoint table pred
)))
1776 (if (not (stringp completion
))
1780 (completion--merge-suffix completion point afterpoint
))
1781 (length completion
))))
1782 (let* ((suffix (substring afterpoint
(cdr bounds
)))
1783 (prefix (substring beforepoint
0 (car bounds
)))
1784 (pattern (completion-basic--pattern
1785 beforepoint afterpoint bounds
))
1786 (all (completion-pcm--all-completions prefix pattern table pred
)))
1787 (if minibuffer-completing-file-name
1788 (setq all
(completion-pcm--filename-try-filter all
)))
1789 (completion-pcm--merge-try pattern all prefix suffix
)))))
1791 (defun completion-basic-all-completions (string table pred point
)
1792 (let* ((beforepoint (substring string
0 point
))
1793 (afterpoint (substring string point
))
1794 (bounds (completion-boundaries beforepoint table pred afterpoint
))
1795 (prefix (substring beforepoint
0 (car bounds
)))
1796 (pattern (completion-basic--pattern beforepoint afterpoint bounds
))
1797 (all (completion-pcm--all-completions prefix pattern table pred
)))
1798 (completion-hilit-commonality all point
(car bounds
))))
1800 ;;; Partial-completion-mode style completion.
1802 (defvar completion-pcm--delim-wild-regex nil
1803 "Regular expression matching delimiters controlling the partial-completion.
1804 Typically, this regular expression simply matches a delimiter, meaning
1805 that completion can add something at (match-beginning 0), but if it has
1806 a submatch 1, then completion can add something at (match-end 1).
1807 This is used when the delimiter needs to be of size zero (e.g. the transition
1808 from lowercase to uppercase characters).")
1810 (defun completion-pcm--prepare-delim-re (delims)
1811 (setq completion-pcm--delim-wild-regex
(concat "[" delims
"*]")))
1813 (defcustom completion-pcm-word-delimiters
"-_./: "
1814 "A string of characters treated as word delimiters for completion.
1816 If `]' is in this string, it must come first.
1817 If `^' is in this string, it must not come first.
1818 If `-' is in this string, it must come first or right after `]'.
1819 In other words, if S is this string, then `[S]' must be a valid Emacs regular
1820 expression (not containing character ranges like `a-z')."
1821 :set
(lambda (symbol value
)
1822 (set-default symbol value
)
1823 ;; Refresh other vars.
1824 (completion-pcm--prepare-delim-re value
))
1825 :initialize
'custom-initialize-reset
1829 (defcustom completion-pcm-complete-word-inserts-delimiters nil
1830 "Treat the SPC or - inserted by `minibuffer-complete-word' as delimiters.
1831 Those chars are treated as delimiters iff this variable is non-nil.
1832 I.e. if non-nil, M-x SPC will just insert a \"-\" in the minibuffer, whereas
1833 if nil, it will list all possible commands in *Completions* because none of
1834 the commands start with a \"-\" or a SPC."
1837 (defun completion-pcm--pattern-trivial-p (pattern)
1838 (and (stringp (car pattern
))
1839 ;; It can be followed by `point' and "" and still be trivial.
1841 (dolist (elem (cdr pattern
))
1842 (unless (member elem
'(point ""))
1843 (setq trivial nil
)))
1846 (defun completion-pcm--string->pattern
(string &optional point
)
1847 "Split STRING into a pattern.
1848 A pattern is a list where each element is either a string
1849 or a symbol chosen among `any', `star', `point', `prefix'."
1850 (if (and point
(< point
(length string
)))
1851 (let ((prefix (substring string
0 point
))
1852 (suffix (substring string point
)))
1853 (append (completion-pcm--string->pattern prefix
)
1855 (completion-pcm--string->pattern suffix
)))
1860 (while (and (setq p
(string-match completion-pcm--delim-wild-regex
1862 (or completion-pcm-complete-word-inserts-delimiters
1863 ;; If the char was added by minibuffer-complete-word,
1864 ;; then don't treat it as a delimiter, otherwise
1865 ;; "M-x SPC" ends up inserting a "-" rather than listing
1867 (not (get-text-property p
'completion-try-word string
))))
1868 ;; Usually, completion-pcm--delim-wild-regex matches a delimiter,
1869 ;; meaning that something can be added *before* it, but it can also
1870 ;; match a prefix and postfix, in which case something can be added
1871 ;; in-between (e.g. match [[:lower:]][[:upper:]]).
1872 ;; This is determined by the presence of a submatch-1 which delimits
1874 (if (match-end 1) (setq p
(match-end 1)))
1875 (push (substring string p0 p
) pattern
)
1876 (if (eq (aref string p
) ?
*)
1878 (push 'star pattern
)
1884 ;; An empty string might be erroneously added at the beginning.
1885 ;; It should be avoided properly, but it's so easy to remove it here.
1886 (delete "" (nreverse (cons (substring string p0
) pattern
))))))
1888 (defun completion-pcm--pattern->regex
(pattern &optional group
)
1894 ((stringp x
) (regexp-quote x
))
1895 ((if (consp group
) (memq x group
) group
) "\\(.*?\\)")
1899 ;; Avoid pathological backtracking.
1900 (while (string-match "\\.\\*\\?\\(?:\\\\[()]\\)*\\(\\.\\*\\?\\)" re
)
1901 (setq re
(replace-match "" t t re
1)))
1904 (defun completion-pcm--all-completions (prefix pattern table pred
)
1905 "Find all completions for PATTERN in TABLE obeying PRED.
1906 PATTERN is as returned by `completion-pcm--string->pattern'."
1907 ;; (assert (= (car (completion-boundaries prefix table pred ""))
1908 ;; (length prefix)))
1909 ;; Find an initial list of possible completions.
1910 (if (completion-pcm--pattern-trivial-p pattern
)
1912 ;; Minibuffer contains no delimiters -- simple case!
1913 (all-completions (concat prefix
(car pattern
)) table pred
)
1915 ;; Use all-completions to do an initial cull. This is a big win,
1916 ;; since all-completions is written in C!
1917 (let* (;; Convert search pattern to a standard regular expression.
1918 (regex (completion-pcm--pattern->regex pattern
))
1919 (case-fold-search completion-ignore-case
)
1920 (completion-regexp-list (cons regex completion-regexp-list
))
1921 (compl (all-completions
1922 (concat prefix
(if (stringp (car pattern
)) (car pattern
) ""))
1924 (if (not (functionp table
))
1925 ;; The internal functions already obeyed completion-regexp-list.
1929 (when (string-match-p regex c
) (push c poss
)))
1932 (defun completion-pcm--hilit-commonality (pattern completions
)
1934 (let* ((re (completion-pcm--pattern->regex pattern
'(point)))
1935 (case-fold-search completion-ignore-case
))
1938 ;; Don't modify the string itself.
1939 (setq str
(copy-sequence str
))
1940 (unless (string-match re str
)
1941 (error "Internal error: %s does not match %s" re str
))
1942 (let ((pos (or (match-beginning 1) (match-end 0))))
1943 (put-text-property 0 pos
1944 'font-lock-face
'completions-common-part
1946 (if (> (length str
) pos
)
1947 (put-text-property pos
(1+ pos
)
1948 'font-lock-face
'completions-first-difference
1953 (defun completion-pcm--find-all-completions (string table pred point
1955 "Find all completions for STRING at POINT in TABLE, satisfying PRED.
1956 POINT is a position inside STRING.
1957 FILTER is a function applied to the return value, that can be used, e.g. to
1958 filter out additional entries (because TABLE migth not obey PRED)."
1959 (unless filter
(setq filter
'identity
))
1960 (let* ((beforepoint (substring string
0 point
))
1961 (afterpoint (substring string point
))
1962 (bounds (completion-boundaries beforepoint table pred afterpoint
))
1963 (prefix (substring beforepoint
0 (car bounds
)))
1964 (suffix (substring afterpoint
(cdr bounds
)))
1966 (setq string
(substring string
(car bounds
) (+ point
(cdr bounds
))))
1967 (let* ((relpoint (- point
(car bounds
)))
1968 (pattern (completion-pcm--string->pattern string relpoint
))
1969 (all (condition-case err
1971 (completion-pcm--all-completions
1972 prefix pattern table pred
))
1973 (error (unless firsterror
(setq firsterror err
)) nil
))))
1974 (when (and (null all
)
1976 (null (ignore-errors (try-completion prefix table pred
))))
1977 ;; The prefix has no completions at all, so we should try and fix
1979 (let ((substring (substring prefix
0 -
1)))
1980 (destructuring-bind (subpat suball subprefix subsuffix
)
1981 (completion-pcm--find-all-completions
1982 substring table pred
(length substring
) filter
)
1983 (let ((sep (aref prefix
(1- (length prefix
))))
1984 ;; Text that goes between the new submatches and the
1985 ;; completion substring.
1987 ;; Eliminate submatches that don't end with the separator.
1988 (dolist (submatch (prog1 suball
(setq suball
())))
1989 (when (eq sep
(aref submatch
(1- (length submatch
))))
1990 (push submatch suball
)))
1992 ;; Update the boundaries and corresponding pattern.
1993 ;; We assume that all submatches result in the same boundaries
1994 ;; since we wouldn't know how to merge them otherwise anyway.
1995 ;; FIXME: COMPLETE REWRITE!!!
1996 (let* ((newbeforepoint
1997 (concat subprefix
(car suball
)
1998 (substring string
0 relpoint
)))
1999 (leftbound (+ (length subprefix
) (length (car suball
))))
2000 (newbounds (completion-boundaries
2001 newbeforepoint table pred afterpoint
)))
2002 (unless (or (and (eq (cdr bounds
) (cdr newbounds
))
2003 (eq (car newbounds
) leftbound
))
2004 ;; Refuse new boundaries if they step over
2006 (< (car newbounds
) leftbound
))
2007 ;; The new completed prefix does change the boundaries
2008 ;; of the completed substring.
2009 (setq suffix
(substring afterpoint
(cdr newbounds
)))
2011 (concat (substring newbeforepoint
(car newbounds
))
2012 (substring afterpoint
0 (cdr newbounds
))))
2013 (setq between
(substring newbeforepoint leftbound
2015 (setq pattern
(completion-pcm--string->pattern
2017 (- (length newbeforepoint
)
2019 (dolist (submatch suball
)
2020 (setq all
(nconc (mapcar
2021 (lambda (s) (concat submatch between s
))
2023 (completion-pcm--all-completions
2024 (concat subprefix submatch between
)
2025 pattern table pred
)))
2027 ;; FIXME: This can come in handy for try-completion,
2028 ;; but isn't right for all-completions, since it lists
2029 ;; invalid completions.
2031 ;; ;; Even though we found expansions in the prefix, none
2032 ;; ;; leads to a valid completion.
2033 ;; ;; Let's keep the expansions, tho.
2034 ;; (dolist (submatch suball)
2035 ;; (push (concat submatch between newsubstring) all)))
2037 (setq pattern
(append subpat
(list 'any
(string sep
))
2038 (if between
(list between
)) pattern
))
2039 (setq prefix subprefix
)))))
2040 (if (and (null all
) firsterror
)
2041 (signal (car firsterror
) (cdr firsterror
))
2042 (list pattern all prefix suffix
)))))
2044 (defun completion-pcm-all-completions (string table pred point
)
2045 (destructuring-bind (pattern all
&optional prefix suffix
)
2046 (completion-pcm--find-all-completions string table pred point
)
2048 (nconc (completion-pcm--hilit-commonality pattern all
)
2051 (defun completion--sreverse (str)
2052 "Like `reverse' but for a string STR rather than a list."
2053 (apply 'string
(nreverse (mapcar 'identity str
))))
2055 (defun completion--common-suffix (strs)
2056 "Return the common suffix of the strings STRS."
2057 (completion--sreverse
2060 (mapcar 'completion--sreverse strs
))))
2062 (defun completion-pcm--merge-completions (strs pattern
)
2063 "Extract the commonality in STRS, with the help of PATTERN."
2064 ;; When completing while ignoring case, we want to try and avoid
2065 ;; completing "fo" to "foO" when completing against "FOO" (bug#4219).
2066 ;; So we try and make sure that the string we return is all made up
2067 ;; of text from the completions rather than part from the
2068 ;; completions and part from the input.
2069 ;; FIXME: This reduces the problems of inconsistent capitalization
2070 ;; but it doesn't fully fix it: we may still end up completing
2071 ;; "fo-ba" to "foo-BAR" or "FOO-bar" when completing against
2072 ;; '("foo-barr" "FOO-BARD").
2074 ((null (cdr strs
)) (list (car strs
)))
2076 (let ((re (completion-pcm--pattern->regex pattern
'group
))
2077 (ccs ())) ;Chopped completions.
2079 ;; First chop each string into the parts corresponding to each
2080 ;; non-constant element of `pattern', using regexp-matching.
2081 (let ((case-fold-search completion-ignore-case
))
2083 (unless (string-match re str
)
2084 (error "Internal error: %s doesn't match %s" str re
))
2089 (while (setq next
(match-end i
))
2090 (push (substring str last next
) chopped
)
2093 ;; Add the text corresponding to the implicit trailing `any'.
2094 (push (substring str last
) chopped
)
2095 (push (nreverse chopped
) ccs
))))
2097 ;; Then for each of those non-constant elements, extract the
2098 ;; commonality between them.
2101 ;; Make the implicit trailing `any' explicit.
2102 (dolist (elem (append pattern
'(any)))
2104 (setq fixed
(concat fixed elem
))
2106 (dolist (cc (prog1 ccs
(setq ccs nil
)))
2107 (push (car cc
) comps
)
2108 (push (cdr cc
) ccs
))
2109 ;; Might improve the likelihood to avoid choosing
2110 ;; different capitalizations in different parts.
2111 ;; In practice, it doesn't seem to make any difference.
2112 (setq ccs
(nreverse ccs
))
2113 (let* ((prefix (try-completion fixed comps
))
2114 (unique (or (and (eq prefix t
) (setq prefix fixed
))
2115 (eq t
(try-completion prefix comps
)))))
2116 (unless (equal prefix
"") (push prefix res
))
2117 ;; If there's only one completion, `elem' is not useful
2118 ;; any more: it can only match the empty string.
2119 ;; FIXME: in some cases, it may be necessary to turn an
2120 ;; `any' into a `star' because the surrounding context has
2121 ;; changed such that string->pattern wouldn't add an `any'
2125 (when (memq elem
'(star point prefix
))
2126 ;; Extract common suffix additionally to common prefix.
2127 ;; Only do it for `point', `star', and `prefix' since for
2128 ;; `any' it could lead to a merged completion that
2129 ;; doesn't itself match the candidates.
2130 (let ((suffix (completion--common-suffix comps
)))
2131 (assert (stringp suffix
))
2132 (unless (equal suffix
"")
2133 (push suffix res
)))))
2135 ;; We return it in reverse order.
2138 (defun completion-pcm--pattern->string
(pattern)
2139 (mapconcat (lambda (x) (cond
2142 (t ""))) ;any, point, prefix.
2146 ;; We want to provide the functionality of `try', but we use `all'
2147 ;; and then merge it. In most cases, this works perfectly, but
2148 ;; if the completion table doesn't consider the same completions in
2149 ;; `try' as in `all', then we have a problem. The most common such
2150 ;; case is for filename completion where completion-ignored-extensions
2151 ;; is only obeyed by the `try' code. We paper over the difference
2152 ;; here. Note that it is not quite right either: if the completion
2153 ;; table uses completion-table-in-turn, this filtering may take place
2154 ;; too late to correctly fallback from the first to the
2155 ;; second alternative.
2156 (defun completion-pcm--filename-try-filter (all)
2157 "Filter to adjust `all' file completion to the behavior of `try'."
2160 (re (concat "\\(?:\\`\\.\\.?/\\|"
2161 (regexp-opt completion-ignored-extensions
)
2164 (unless (string-match-p re f
) (push f try
)))
2168 (defun completion-pcm--merge-try (pattern all prefix suffix
)
2170 ((not (consp all
)) all
)
2171 ((and (not (consp (cdr all
))) ;Only one completion.
2172 ;; Ignore completion-ignore-case here.
2173 (equal (completion-pcm--pattern->string pattern
) (car all
)))
2176 (let* ((mergedpat (completion-pcm--merge-completions all pattern
))
2177 ;; `mergedpat' is in reverse order. Place new point (by
2178 ;; order of preference) either at the old point, or at
2179 ;; the last place where there's something to choose, or
2181 (pointpat (or (memq 'point mergedpat
)
2182 (memq 'any mergedpat
)
2183 (memq 'star mergedpat
)
2186 ;; New pos from the start.
2187 (newpos (length (completion-pcm--pattern->string pointpat
)))
2188 ;; Do it afterwards because it changes `pointpat' by sideeffect.
2189 (merged (completion-pcm--pattern->string
(nreverse mergedpat
))))
2191 (setq suffix
(completion--merge-suffix merged newpos suffix
))
2192 (cons (concat prefix merged suffix
) (+ newpos
(length prefix
)))))))
2194 (defun completion-pcm-try-completion (string table pred point
)
2195 (destructuring-bind (pattern all prefix suffix
)
2196 (completion-pcm--find-all-completions
2197 string table pred point
2198 (if minibuffer-completing-file-name
2199 'completion-pcm--filename-try-filter
))
2200 (completion-pcm--merge-try pattern all prefix suffix
)))
2202 ;;; Substring completion
2203 ;; Mostly derived from the code of `basic' completion.
2205 (defun completion-substring--all-completions (string table pred point
)
2206 (let* ((beforepoint (substring string
0 point
))
2207 (afterpoint (substring string point
))
2208 (bounds (completion-boundaries beforepoint table pred afterpoint
))
2209 (suffix (substring afterpoint
(cdr bounds
)))
2210 (prefix (substring beforepoint
0 (car bounds
)))
2211 (basic-pattern (completion-basic--pattern
2212 beforepoint afterpoint bounds
))
2213 (pattern (if (not (stringp (car basic-pattern
)))
2215 (cons 'prefix basic-pattern
)))
2216 (all (completion-pcm--all-completions prefix pattern table pred
)))
2217 (list all pattern prefix suffix
(car bounds
))))
2219 (defun completion-substring-try-completion (string table pred point
)
2220 (destructuring-bind (all pattern prefix suffix carbounds
)
2221 (completion-substring--all-completions string table pred point
)
2222 (if minibuffer-completing-file-name
2223 (setq all
(completion-pcm--filename-try-filter all
)))
2224 (completion-pcm--merge-try pattern all prefix suffix
)))
2226 (defun completion-substring-all-completions (string table pred point
)
2227 (destructuring-bind (all pattern prefix suffix carbounds
)
2228 (completion-substring--all-completions string table pred point
)
2230 (nconc (completion-pcm--hilit-commonality pattern all
)
2233 ;; Initials completion
2234 ;; Complete /ums to /usr/monnier/src or lch to list-command-history.
2236 (defun completion-initials-expand (str table pred
)
2237 (let ((bounds (completion-boundaries str table pred
"")))
2238 (unless (or (zerop (length str
))
2239 ;; Only check within the boundaries, since the
2240 ;; boundary char (e.g. /) might be in delim-regexp.
2241 (string-match completion-pcm--delim-wild-regex str
2243 (if (zerop (car bounds
))
2244 (mapconcat 'string str
"-")
2245 ;; If there's a boundary, it's trickier. The main use-case
2246 ;; we consider here is file-name completion. We'd like
2247 ;; to expand ~/eee to ~/e/e/e and /eee to /e/e/e.
2248 ;; But at the same time, we don't want /usr/share/ae to expand
2249 ;; to /usr/share/a/e just because we mistyped "ae" for "ar",
2250 ;; so we probably don't want initials to touch anything that
2251 ;; looks like /usr/share/foo. As a heuristic, we just check that
2252 ;; the text before the boundary char is at most 1 char.
2253 ;; This allows both ~/eee and /eee and not much more.
2254 ;; FIXME: It sadly also disallows the use of ~/eee when that's
2255 ;; embedded within something else (e.g. "(~/eee" in Info node
2256 ;; completion or "ancestor:/eee" in bzr-revision completion).
2257 (when (< (car bounds
) 3)
2258 (let ((sep (substring str
(1- (car bounds
)) (car bounds
))))
2259 ;; FIXME: the above string-match checks the whole string, whereas
2260 ;; we end up only caring about the after-boundary part.
2261 (concat (substring str
0 (car bounds
))
2262 (mapconcat 'string
(substring str
(car bounds
)) sep
))))))))
2264 (defun completion-initials-all-completions (string table pred point
)
2265 (let ((newstr (completion-initials-expand string table pred
)))
2267 (completion-pcm-all-completions newstr table pred
(length newstr
)))))
2269 (defun completion-initials-try-completion (string table pred point
)
2270 (let ((newstr (completion-initials-expand string table pred
)))
2272 (completion-pcm-try-completion newstr table pred
(length newstr
)))))
2277 (defun minibuffer-insert-file-name-at-point ()
2278 "Get a file name at point in original buffer and insert it to minibuffer."
2280 (let ((file-name-at-point
2281 (with-current-buffer (window-buffer (minibuffer-selected-window))
2282 (run-hook-with-args-until-success 'file-name-at-point-functions
))))
2283 (when file-name-at-point
2284 (insert file-name-at-point
))))
2286 (provide 'minibuffer
)
2288 ;; arch-tag: ef8a0a15-1080-4790-a754-04017c02f08f
2289 ;;; minibuffer.el ends here