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