New functions window-point-1 and set-window-point-1.
[emacs.git] / lisp / minibuffer.el
blobe2ed07f1ef115cc22a54e9d147f0286dea9c78d7
1 ;;; minibuffer.el --- Minibuffer completion functions -*- lexical-binding: t -*-
3 ;; Copyright (C) 2008-2011 Free Software Foundation, Inc.
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6 ;; Package: emacs
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; Names with "--" are for functions and variables that are meant to be for
26 ;; internal use only.
28 ;; Functional completion tables have an extended calling conventions:
29 ;; The `action' can be (additionally to nil, t, and lambda) of the form
30 ;; - (boundaries . SUFFIX) in which case it should return
31 ;; (boundaries START . END). See `completion-boundaries'.
32 ;; Any other return value should be ignored (so we ignore values returned
33 ;; from completion tables that don't know about this new `action' form).
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 highligting 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 :type `(alist :key-type (choice :tag "Category"
514 (const buffer)
515 (const file)
516 (const unicode-name)
517 symbol)
518 :value-type
519 (set :tag "Properties to override"
520 (cons :tag "Completion Styles"
521 (const :tag "Select a style from the menu;" styles)
522 ,completion--styles-type)
523 (cons :tag "Completion Cycling"
524 (const :tag "Select one value from the menu." cycle)
525 ,completion--cycling-threshold-type))))
527 (defun completion--styles (metadata)
528 (let* ((cat (completion-metadata-get metadata 'category))
529 (over (assq 'styles (cdr (assq cat completion-category-overrides)))))
530 (if over
531 (delete-dups (append (cdr over) (copy-sequence completion-styles)))
532 completion-styles)))
534 (defun completion-try-completion (string table pred point &optional metadata)
535 "Try to complete STRING using completion table TABLE.
536 Only the elements of table that satisfy predicate PRED are considered.
537 POINT is the position of point within STRING.
538 The return value can be either nil to indicate that there is no completion,
539 t to indicate that STRING is the only possible completion,
540 or a pair (STRING . NEWPOINT) of the completed result string together with
541 a new position for point."
542 (completion--some (lambda (style)
543 (funcall (nth 1 (assq style completion-styles-alist))
544 string table pred point))
545 (completion--styles (or metadata
546 (completion-metadata
547 (substring string 0 point)
548 table pred)))))
550 (defun completion-all-completions (string table pred point &optional metadata)
551 "List the possible completions of STRING in completion table TABLE.
552 Only the elements of table that satisfy predicate PRED are considered.
553 POINT is the position of point within STRING.
554 The return value is a list of completions and may contain the base-size
555 in the last `cdr'."
556 ;; FIXME: We need to additionally return the info needed for the
557 ;; second part of completion-base-position.
558 (completion--some (lambda (style)
559 (funcall (nth 2 (assq style completion-styles-alist))
560 string table pred point))
561 (completion--styles (or metadata
562 (completion-metadata
563 (substring string 0 point)
564 table pred)))))
566 (defun minibuffer--bitset (modified completions exact)
567 (logior (if modified 4 0)
568 (if completions 2 0)
569 (if exact 1 0)))
571 (defun completion--replace (beg end newtext)
572 "Replace the buffer text between BEG and END with NEWTEXT.
573 Moves point to the end of the new text."
574 ;; Maybe this should be in subr.el.
575 ;; You'd think this is trivial to do, but details matter if you want
576 ;; to keep markers "at the right place" and be robust in the face of
577 ;; after-change-functions that may themselves modify the buffer.
578 (let ((prefix-len 0))
579 ;; Don't touch markers in the shared prefix (if any).
580 (while (and (< prefix-len (length newtext))
581 (< (+ beg prefix-len) end)
582 (eq (char-after (+ beg prefix-len))
583 (aref newtext prefix-len)))
584 (setq prefix-len (1+ prefix-len)))
585 (unless (zerop prefix-len)
586 (setq beg (+ beg prefix-len))
587 (setq newtext (substring newtext prefix-len))))
588 (let ((suffix-len 0))
589 ;; Don't touch markers in the shared suffix (if any).
590 (while (and (< suffix-len (length newtext))
591 (< beg (- end suffix-len))
592 (eq (char-before (- end suffix-len))
593 (aref newtext (- (length newtext) suffix-len 1))))
594 (setq suffix-len (1+ suffix-len)))
595 (unless (zerop suffix-len)
596 (setq end (- end suffix-len))
597 (setq newtext (substring newtext 0 (- suffix-len))))
598 (goto-char beg)
599 (insert newtext)
600 (delete-region (point) (+ (point) (- end beg)))
601 (forward-char suffix-len)))
603 (defcustom completion-cycle-threshold nil
604 "Number of completion candidates below which cycling is used.
605 Depending on this setting `minibuffer-complete' may use cycling,
606 like `minibuffer-force-complete'.
607 If nil, cycling is never used.
608 If t, cycling is always used.
609 If an integer, cycling is used as soon as there are fewer completion
610 candidates than this number."
611 :type completion--cycling-threshold-type)
613 (defun completion--cycle-threshold (metadata)
614 (let* ((cat (completion-metadata-get metadata 'category))
615 (over (assq 'cycle (cdr (assq cat completion-category-overrides)))))
616 (if over (cdr over) completion-cycle-threshold)))
618 (defvar completion-all-sorted-completions nil)
619 (make-variable-buffer-local 'completion-all-sorted-completions)
620 (defvar completion-cycling nil)
622 (defvar completion-fail-discreetly nil
623 "If non-nil, stay quiet when there is no match.")
625 (defun completion--message (msg)
626 (if completion-show-inline-help
627 (minibuffer-message msg)))
629 (defun completion--do-completion (&optional try-completion-function
630 expect-exact)
631 "Do the completion and return a summary of what happened.
632 M = completion was performed, the text was Modified.
633 C = there were available Completions.
634 E = after completion we now have an Exact match.
637 000 0 no possible completion
638 001 1 was already an exact and unique completion
639 010 2 no completion happened
640 011 3 was already an exact completion
641 100 4 ??? impossible
642 101 5 ??? impossible
643 110 6 some completion happened
644 111 7 completed to an exact completion
646 TRY-COMPLETION-FUNCTION is a function to use in place of `try-completion'.
647 EXPECT-EXACT, if non-nil, means that there is no need to tell the user
648 when the buffer's text is already an exact match."
649 (let* ((beg (field-beginning))
650 (end (field-end))
651 (string (buffer-substring beg end))
652 (md (completion--field-metadata beg))
653 (comp (funcall (or try-completion-function
654 'completion-try-completion)
655 string
656 minibuffer-completion-table
657 minibuffer-completion-predicate
658 (- (point) beg)
659 md)))
660 (cond
661 ((null comp)
662 (minibuffer-hide-completions)
663 (unless completion-fail-discreetly
664 (ding)
665 (completion--message "No match"))
666 (minibuffer--bitset nil nil nil))
667 ((eq t comp)
668 (minibuffer-hide-completions)
669 (goto-char end)
670 (completion--done string 'finished
671 (unless expect-exact "Sole completion"))
672 (minibuffer--bitset nil nil t)) ;Exact and unique match.
674 ;; `completed' should be t if some completion was done, which doesn't
675 ;; include simply changing the case of the entered string. However,
676 ;; for appearance, the string is rewritten if the case changes.
677 (let* ((comp-pos (cdr comp))
678 (completion (car comp))
679 (completed (not (eq t (compare-strings completion nil nil
680 string nil nil t))))
681 (unchanged (eq t (compare-strings completion nil nil
682 string nil nil nil))))
683 (if unchanged
684 (goto-char end)
685 ;; Insert in minibuffer the chars we got.
686 (completion--replace beg end completion))
687 ;; Move point to its completion-mandated destination.
688 (forward-char (- comp-pos (length completion)))
690 (if (not (or unchanged completed))
691 ;; The case of the string changed, but that's all. We're not sure
692 ;; whether this is a unique completion or not, so try again using
693 ;; the real case (this shouldn't recurse again, because the next
694 ;; time try-completion will return either t or the exact string).
695 (completion--do-completion try-completion-function expect-exact)
697 ;; It did find a match. Do we match some possibility exactly now?
698 (let* ((exact (test-completion completion
699 minibuffer-completion-table
700 minibuffer-completion-predicate))
701 (threshold (completion--cycle-threshold md))
702 (comps
703 ;; Check to see if we want to do cycling. We do it
704 ;; here, after having performed the normal completion,
705 ;; so as to take advantage of the difference between
706 ;; try-completion and all-completions, for things
707 ;; like completion-ignored-extensions.
708 (when (and threshold
709 ;; Check that the completion didn't make
710 ;; us jump to a different boundary.
711 (or (not completed)
712 (< (car (completion-boundaries
713 (substring completion 0 comp-pos)
714 minibuffer-completion-table
715 minibuffer-completion-predicate
716 ""))
717 comp-pos)))
718 (completion-all-sorted-completions))))
719 (completion--flush-all-sorted-completions)
720 (cond
721 ((and (consp (cdr comps)) ;; There's something to cycle.
722 (not (ignore-errors
723 ;; This signal an (intended) error if comps is too
724 ;; short or if completion-cycle-threshold is t.
725 (consp (nthcdr threshold comps)))))
726 ;; Fewer than completion-cycle-threshold remaining
727 ;; completions: let's cycle.
728 (setq completed t exact t)
729 (setq completion-all-sorted-completions comps)
730 (minibuffer-force-complete))
731 (completed
732 ;; We could also decide to refresh the completions,
733 ;; if they're displayed (and assuming there are
734 ;; completions left).
735 (minibuffer-hide-completions)
736 (if exact
737 ;; If completion did not put point at end of field,
738 ;; it's a sign that completion is not finished.
739 (completion--done completion
740 (if (< comp-pos (length completion))
741 'exact 'unknown))))
742 ;; Show the completion table, if requested.
743 ((not exact)
744 (if (case completion-auto-help
745 (lazy (eq this-command last-command))
746 (t completion-auto-help))
747 (minibuffer-completion-help)
748 (completion--message "Next char not unique")))
749 ;; If the last exact completion and this one were the same, it
750 ;; means we've already given a "Complete, but not unique" message
751 ;; and the user's hit TAB again, so now we give him help.
753 (if (and (eq this-command last-command) completion-auto-help)
754 (minibuffer-completion-help))
755 (completion--done completion 'exact
756 (unless expect-exact
757 "Complete, but not unique"))))
759 (minibuffer--bitset completed t exact))))))))
761 (defun minibuffer-complete ()
762 "Complete the minibuffer contents as far as possible.
763 Return nil if there is no valid completion, else t.
764 If no characters can be completed, display a list of possible completions.
765 If you repeat this command after it displayed such a list,
766 scroll the window of possible completions."
767 (interactive)
768 ;; If the previous command was not this,
769 ;; mark the completion buffer obsolete.
770 (unless (eq this-command last-command)
771 (completion--flush-all-sorted-completions)
772 (setq minibuffer-scroll-window nil))
774 (cond
775 ;; If there's a fresh completion window with a live buffer,
776 ;; and this command is repeated, scroll that window.
777 ((window-live-p minibuffer-scroll-window)
778 (let ((window minibuffer-scroll-window))
779 (with-current-buffer (window-buffer window)
780 (if (pos-visible-in-window-p (point-max) window)
781 ;; If end is in view, scroll up to the beginning.
782 (set-window-start window (point-min) nil)
783 ;; Else scroll down one screen.
784 (scroll-other-window))
785 nil)))
786 ;; If we're cycling, keep on cycling.
787 ((and completion-cycling completion-all-sorted-completions)
788 (minibuffer-force-complete)
790 (t (case (completion--do-completion)
791 (#b000 nil)
792 (t t)))))
794 (defun completion--flush-all-sorted-completions (&rest _ignore)
795 (remove-hook 'after-change-functions
796 'completion--flush-all-sorted-completions t)
797 (setq completion-cycling nil)
798 (setq completion-all-sorted-completions nil))
800 (defun completion--metadata (string base md-at-point table pred)
801 ;; Like completion-metadata, but for the specific case of getting the
802 ;; metadata at `base', which tends to trigger pathological behavior for old
803 ;; completion tables which don't understand `metadata'.
804 (let ((bounds (completion-boundaries string table pred "")))
805 (if (eq (car bounds) base) md-at-point
806 (completion-metadata (substring string 0 base) table pred))))
808 (defun completion-all-sorted-completions ()
809 (or completion-all-sorted-completions
810 (let* ((start (field-beginning))
811 (end (field-end))
812 (string (buffer-substring start end))
813 (md (completion--field-metadata start))
814 (all (completion-all-completions
815 string
816 minibuffer-completion-table
817 minibuffer-completion-predicate
818 (- (point) start)
819 md))
820 (last (last all))
821 (base-size (or (cdr last) 0))
822 (all-md (completion--metadata (buffer-substring-no-properties
823 start (point))
824 base-size md
825 minibuffer-completion-table
826 minibuffer-completion-predicate))
827 (sort-fun (completion-metadata-get all-md 'cycle-sort-function)))
828 (when last
829 (setcdr last nil)
830 (setq all (if sort-fun (funcall sort-fun all)
831 ;; Prefer shorter completions, by default.
832 (sort all (lambda (c1 c2) (< (length c1) (length c2))))))
833 ;; Prefer recently used completions.
834 (when (minibufferp)
835 (let ((hist (symbol-value minibuffer-history-variable)))
836 (setq all (sort all (lambda (c1 c2)
837 (> (length (member c1 hist))
838 (length (member c2 hist))))))))
839 ;; Cache the result. This is not just for speed, but also so that
840 ;; repeated calls to minibuffer-force-complete can cycle through
841 ;; all possibilities.
842 (add-hook 'after-change-functions
843 'completion--flush-all-sorted-completions nil t)
844 (setq completion-all-sorted-completions
845 (nconc all base-size))))))
847 (defun minibuffer-force-complete ()
848 "Complete the minibuffer to an exact match.
849 Repeated uses step through the possible completions."
850 (interactive)
851 ;; FIXME: Need to deal with the extra-size issue here as well.
852 ;; FIXME: ~/src/emacs/t<M-TAB>/lisp/minibuffer.el completes to
853 ;; ~/src/emacs/trunk/ and throws away lisp/minibuffer.el.
854 (let* ((start (field-beginning))
855 (end (field-end))
856 ;; (md (completion--field-metadata start))
857 (all (completion-all-sorted-completions))
858 (base (+ start (or (cdr (last all)) 0))))
859 (cond
860 ((not (consp all))
861 (completion--message
862 (if all "No more completions" "No completions")))
863 ((not (consp (cdr all)))
864 (let ((mod (equal (car all) (buffer-substring-no-properties base end))))
865 (if mod (completion--replace base end (car all)))
866 (completion--done (buffer-substring-no-properties start (point))
867 'finished (unless mod "Sole completion"))))
869 (setq completion-cycling t)
870 (completion--replace base end (car all))
871 (completion--done (buffer-substring-no-properties start (point)) 'sole)
872 ;; If completing file names, (car all) may be a directory, so we'd now
873 ;; have a new set of possible completions and might want to reset
874 ;; completion-all-sorted-completions to nil, but we prefer not to,
875 ;; so that repeated calls minibuffer-force-complete still cycle
876 ;; through the previous possible completions.
877 (let ((last (last all)))
878 (setcdr last (cons (car all) (cdr last)))
879 (setq completion-all-sorted-completions (cdr all)))))))
881 (defvar minibuffer-confirm-exit-commands
882 '(minibuffer-complete minibuffer-complete-word PC-complete PC-complete-word)
883 "A list of commands which cause an immediately following
884 `minibuffer-complete-and-exit' to ask for extra confirmation.")
886 (defun minibuffer-complete-and-exit ()
887 "Exit if the minibuffer contains a valid completion.
888 Otherwise, try to complete the minibuffer contents. If
889 completion leads to a valid completion, a repetition of this
890 command will exit.
892 If `minibuffer-completion-confirm' is `confirm', do not try to
893 complete; instead, ask for confirmation and accept any input if
894 confirmed.
895 If `minibuffer-completion-confirm' is `confirm-after-completion',
896 do not try to complete; instead, ask for confirmation if the
897 preceding minibuffer command was a member of
898 `minibuffer-confirm-exit-commands', and accept the input
899 otherwise."
900 (interactive)
901 (let ((beg (field-beginning))
902 (end (field-end)))
903 (cond
904 ;; Allow user to specify null string
905 ((= beg end) (exit-minibuffer))
906 ((test-completion (buffer-substring beg end)
907 minibuffer-completion-table
908 minibuffer-completion-predicate)
909 ;; FIXME: completion-ignore-case has various slightly
910 ;; incompatible meanings. E.g. it can reflect whether the user
911 ;; wants completion to pay attention to case, or whether the
912 ;; string will be used in a context where case is significant.
913 ;; E.g. usually try-completion should obey the first, whereas
914 ;; test-completion should obey the second.
915 (when completion-ignore-case
916 ;; Fixup case of the field, if necessary.
917 (let* ((string (buffer-substring beg end))
918 (compl (try-completion
919 string
920 minibuffer-completion-table
921 minibuffer-completion-predicate)))
922 (when (and (stringp compl) (not (equal string compl))
923 ;; If it weren't for this piece of paranoia, I'd replace
924 ;; the whole thing with a call to do-completion.
925 ;; This is important, e.g. when the current minibuffer's
926 ;; content is a directory which only contains a single
927 ;; file, so `try-completion' actually completes to
928 ;; that file.
929 (= (length string) (length compl)))
930 (goto-char end)
931 (insert compl)
932 (delete-region beg end))))
933 (exit-minibuffer))
935 ((memq minibuffer-completion-confirm '(confirm confirm-after-completion))
936 ;; The user is permitted to exit with an input that's rejected
937 ;; by test-completion, after confirming her choice.
938 (if (or (eq last-command this-command)
939 ;; For `confirm-after-completion' we only ask for confirmation
940 ;; if trying to exit immediately after typing TAB (this
941 ;; catches most minibuffer typos).
942 (and (eq minibuffer-completion-confirm 'confirm-after-completion)
943 (not (memq last-command minibuffer-confirm-exit-commands))))
944 (exit-minibuffer)
945 (minibuffer-message "Confirm")
946 nil))
949 ;; Call do-completion, but ignore errors.
950 (case (condition-case nil
951 (completion--do-completion nil 'expect-exact)
952 (error 1))
953 ((#b001 #b011) (exit-minibuffer))
954 (#b111 (if (not minibuffer-completion-confirm)
955 (exit-minibuffer)
956 (minibuffer-message "Confirm")
957 nil))
958 (t nil))))))
960 (defun completion--try-word-completion (string table predicate point md)
961 (let ((comp (completion-try-completion string table predicate point md)))
962 (if (not (consp comp))
963 comp
965 ;; If completion finds next char not unique,
966 ;; consider adding a space or a hyphen.
967 (when (= (length string) (length (car comp)))
968 ;; Mark the added char with the `completion-word' property, so it
969 ;; can be handled specially by completion styles such as
970 ;; partial-completion.
971 ;; We used to remove `partial-completion' from completion-styles
972 ;; instead, but it was too blunt, leading to situations where SPC
973 ;; was the only insertable char at point but minibuffer-complete-word
974 ;; refused inserting it.
975 (let ((exts (mapcar (lambda (str) (propertize str 'completion-try-word t))
976 '(" " "-")))
977 (before (substring string 0 point))
978 (after (substring string point))
979 tem)
980 (while (and exts (not (consp tem)))
981 (setq tem (completion-try-completion
982 (concat before (pop exts) after)
983 table predicate (1+ point) md)))
984 (if (consp tem) (setq comp tem))))
986 ;; Completing a single word is actually more difficult than completing
987 ;; as much as possible, because we first have to find the "current
988 ;; position" in `completion' in order to find the end of the word
989 ;; we're completing. Normally, `string' is a prefix of `completion',
990 ;; which makes it trivial to find the position, but with fancier
991 ;; completion (plus env-var expansion, ...) `completion' might not
992 ;; look anything like `string' at all.
993 (let* ((comppoint (cdr comp))
994 (completion (car comp))
995 (before (substring string 0 point))
996 (combined (concat before "\n" completion)))
997 ;; Find in completion the longest text that was right before point.
998 (when (string-match "\\(.+\\)\n.*?\\1" combined)
999 (let* ((prefix (match-string 1 before))
1000 ;; We used non-greedy match to make `rem' as long as possible.
1001 (rem (substring combined (match-end 0)))
1002 ;; Find in the remainder of completion the longest text
1003 ;; that was right after point.
1004 (after (substring string point))
1005 (suffix (if (string-match "\\`\\(.+\\).*\n.*\\1"
1006 (concat after "\n" rem))
1007 (match-string 1 after))))
1008 ;; The general idea is to try and guess what text was inserted
1009 ;; at point by the completion. Problem is: if we guess wrong,
1010 ;; we may end up treating as "added by completion" text that was
1011 ;; actually painfully typed by the user. So if we then cut
1012 ;; after the first word, we may throw away things the
1013 ;; user wrote. So let's try to be as conservative as possible:
1014 ;; only cut after the first word, if we're reasonably sure that
1015 ;; our guess is correct.
1016 ;; Note: a quick survey on emacs-devel seemed to indicate that
1017 ;; nobody actually cares about the "word-at-a-time" feature of
1018 ;; minibuffer-complete-word, whose real raison-d'être is that it
1019 ;; tries to add "-" or " ". One more reason to only cut after
1020 ;; the first word, if we're really sure we're right.
1021 (when (and (or suffix (zerop (length after)))
1022 (string-match (concat
1023 ;; Make submatch 1 as small as possible
1024 ;; to reduce the risk of cutting
1025 ;; valuable text.
1026 ".*" (regexp-quote prefix) "\\(.*?\\)"
1027 (if suffix (regexp-quote suffix) "\\'"))
1028 completion)
1029 ;; The new point in `completion' should also be just
1030 ;; before the suffix, otherwise something more complex
1031 ;; is going on, and we're not sure where we are.
1032 (eq (match-end 1) comppoint)
1033 ;; (match-beginning 1)..comppoint is now the stretch
1034 ;; of text in `completion' that was completed at point.
1035 (string-match "\\W" completion (match-beginning 1))
1036 ;; Is there really something to cut?
1037 (> comppoint (match-end 0)))
1038 ;; Cut after the first word.
1039 (let ((cutpos (match-end 0)))
1040 (setq completion (concat (substring completion 0 cutpos)
1041 (substring completion comppoint)))
1042 (setq comppoint cutpos)))))
1044 (cons completion comppoint)))))
1047 (defun minibuffer-complete-word ()
1048 "Complete the minibuffer contents at most a single word.
1049 After one word is completed as much as possible, a space or hyphen
1050 is added, provided that matches some possible completion.
1051 Return nil if there is no valid completion, else t."
1052 (interactive)
1053 (case (completion--do-completion 'completion--try-word-completion)
1054 (#b000 nil)
1055 (t t)))
1057 (defface completions-annotations '((t :inherit italic))
1058 "Face to use for annotations in the *Completions* buffer.")
1060 (defcustom completions-format 'horizontal
1061 "Define the appearance and sorting of completions.
1062 If the value is `vertical', display completions sorted vertically
1063 in columns in the *Completions* buffer.
1064 If the value is `horizontal', display completions sorted
1065 horizontally in alphabetical order, rather than down the screen."
1066 :type '(choice (const horizontal) (const vertical))
1067 :group 'minibuffer
1068 :version "23.2")
1070 (defun completion--insert-strings (strings)
1071 "Insert a list of STRINGS into the current buffer.
1072 Uses columns to keep the listing readable but compact.
1073 It also eliminates runs of equal strings."
1074 (when (consp strings)
1075 (let* ((length (apply 'max
1076 (mapcar (lambda (s)
1077 (if (consp s)
1078 (+ (string-width (car s))
1079 (string-width (cadr s)))
1080 (string-width s)))
1081 strings)))
1082 (window (get-buffer-window (current-buffer) 0))
1083 (wwidth (if window (1- (window-width window)) 79))
1084 (columns (min
1085 ;; At least 2 columns; at least 2 spaces between columns.
1086 (max 2 (/ wwidth (+ 2 length)))
1087 ;; Don't allocate more columns than we can fill.
1088 ;; Windows can't show less than 3 lines anyway.
1089 (max 1 (/ (length strings) 2))))
1090 (colwidth (/ wwidth columns))
1091 (column 0)
1092 (rows (/ (length strings) columns))
1093 (row 0)
1094 (first t)
1095 (laststring nil))
1096 ;; The insertion should be "sensible" no matter what choices were made
1097 ;; for the parameters above.
1098 (dolist (str strings)
1099 (unless (equal laststring str) ; Remove (consecutive) duplicates.
1100 (setq laststring str)
1101 ;; FIXME: `string-width' doesn't pay attention to
1102 ;; `display' properties.
1103 (let ((length (if (consp str)
1104 (+ (string-width (car str))
1105 (string-width (cadr str)))
1106 (string-width str))))
1107 (cond
1108 ((eq completions-format 'vertical)
1109 ;; Vertical format
1110 (when (> row rows)
1111 (forward-line (- -1 rows))
1112 (setq row 0 column (+ column colwidth)))
1113 (when (> column 0)
1114 (end-of-line)
1115 (while (> (current-column) column)
1116 (if (eobp)
1117 (insert "\n")
1118 (forward-line 1)
1119 (end-of-line)))
1120 (insert " \t")
1121 (set-text-properties (1- (point)) (point)
1122 `(display (space :align-to ,column)))))
1124 ;; Horizontal format
1125 (unless first
1126 (if (< wwidth (+ (max colwidth length) column))
1127 ;; No space for `str' at point, move to next line.
1128 (progn (insert "\n") (setq column 0))
1129 (insert " \t")
1130 ;; Leave the space unpropertized so that in the case we're
1131 ;; already past the goal column, there is still
1132 ;; a space displayed.
1133 (set-text-properties (1- (point)) (point)
1134 ;; We can't just set tab-width, because
1135 ;; completion-setup-function will kill
1136 ;; all local variables :-(
1137 `(display (space :align-to ,column)))
1138 nil))))
1139 (setq first nil)
1140 (if (not (consp str))
1141 (put-text-property (point) (progn (insert str) (point))
1142 'mouse-face 'highlight)
1143 (put-text-property (point) (progn (insert (car str)) (point))
1144 'mouse-face 'highlight)
1145 (add-text-properties (point) (progn (insert (cadr str)) (point))
1146 '(mouse-face nil
1147 face completions-annotations)))
1148 (cond
1149 ((eq completions-format 'vertical)
1150 ;; Vertical format
1151 (if (> column 0)
1152 (forward-line)
1153 (insert "\n"))
1154 (setq row (1+ row)))
1156 ;; Horizontal format
1157 ;; Next column to align to.
1158 (setq column (+ column
1159 ;; Round up to a whole number of columns.
1160 (* colwidth (ceiling length colwidth))))))))))))
1162 (defvar completion-common-substring nil)
1163 (make-obsolete-variable 'completion-common-substring nil "23.1")
1165 (defvar completion-setup-hook nil
1166 "Normal hook run at the end of setting up a completion list buffer.
1167 When this hook is run, the current buffer is the one in which the
1168 command to display the completion list buffer was run.
1169 The completion list buffer is available as the value of `standard-output'.
1170 See also `display-completion-list'.")
1172 (defface completions-first-difference
1173 '((t (:inherit bold)))
1174 "Face put on the first uncommon character in completions in *Completions* buffer."
1175 :group 'completion)
1177 (defface completions-common-part
1178 '((t (:inherit default)))
1179 "Face put on the common prefix substring in completions in *Completions* buffer.
1180 The idea of `completions-common-part' is that you can use it to
1181 make the common parts less visible than normal, so that the rest
1182 of the differing parts is, by contrast, slightly highlighted."
1183 :group 'completion)
1185 (defun completion-hilit-commonality (completions prefix-len base-size)
1186 (when completions
1187 (let ((com-str-len (- prefix-len (or base-size 0))))
1188 (nconc
1189 (mapcar
1190 (lambda (elem)
1191 (let ((str
1192 ;; Don't modify the string itself, but a copy, since the
1193 ;; the string may be read-only or used for other purposes.
1194 ;; Furthermore, since `completions' may come from
1195 ;; display-completion-list, `elem' may be a list.
1196 (if (consp elem)
1197 (car (setq elem (cons (copy-sequence (car elem))
1198 (cdr elem))))
1199 (setq elem (copy-sequence elem)))))
1200 (put-text-property 0
1201 ;; If completion-boundaries returns incorrect
1202 ;; values, all-completions may return strings
1203 ;; that don't contain the prefix.
1204 (min com-str-len (length str))
1205 'font-lock-face 'completions-common-part
1206 str)
1207 (if (> (length str) com-str-len)
1208 (put-text-property com-str-len (1+ com-str-len)
1209 'font-lock-face 'completions-first-difference
1210 str)))
1211 elem)
1212 completions)
1213 base-size))))
1215 (defun display-completion-list (completions &optional common-substring)
1216 "Display the list of completions, COMPLETIONS, using `standard-output'.
1217 Each element may be just a symbol or string
1218 or may be a list of two strings to be printed as if concatenated.
1219 If it is a list of two strings, the first is the actual completion
1220 alternative, the second serves as annotation.
1221 `standard-output' must be a buffer.
1222 The actual completion alternatives, as inserted, are given `mouse-face'
1223 properties of `highlight'.
1224 At the end, this runs the normal hook `completion-setup-hook'.
1225 It can find the completion buffer in `standard-output'.
1227 The obsolete optional arg COMMON-SUBSTRING, if non-nil, should be a string
1228 specifying a common substring for adding the faces
1229 `completions-first-difference' and `completions-common-part' to
1230 the completions buffer."
1231 (if common-substring
1232 (setq completions (completion-hilit-commonality
1233 completions (length common-substring)
1234 ;; We don't know the base-size.
1235 nil)))
1236 (if (not (bufferp standard-output))
1237 ;; This *never* (ever) happens, so there's no point trying to be clever.
1238 (with-temp-buffer
1239 (let ((standard-output (current-buffer))
1240 (completion-setup-hook nil))
1241 (display-completion-list completions common-substring))
1242 (princ (buffer-string)))
1244 (with-current-buffer standard-output
1245 (goto-char (point-max))
1246 (if (null completions)
1247 (insert "There are no possible completions of what you have typed.")
1248 (insert "Possible completions are:\n")
1249 (completion--insert-strings completions))))
1251 ;; The hilit used to be applied via completion-setup-hook, so there
1252 ;; may still be some code that uses completion-common-substring.
1253 (with-no-warnings
1254 (let ((completion-common-substring common-substring))
1255 (run-hooks 'completion-setup-hook)))
1256 nil)
1258 (defvar completion-extra-properties nil
1259 "Property list of extra properties of the current completion job.
1260 These include:
1261 `:annotation-function': Function to add annotations in the completions buffer.
1262 The function takes a completion and should either return nil, or a string
1263 that will be displayed next to the completion. The function can access the
1264 completion data via `minibuffer-completion-table' and related variables.
1265 `:exit-function': Function to run after completion is performed.
1266 The function takes at least 2 parameters (STRING and STATUS) where STRING
1267 is the text to which the field was completed and STATUS indicates what
1268 kind of operation happened: if text is now complete it's `finished', if text
1269 cannot be further completed but completion is not finished, it's `sole', if
1270 text is a valid completion but may be further completed, it's `exact', and
1271 other STATUSes may be added in the future.")
1273 (defvar completion-annotate-function
1275 ;; Note: there's a lot of scope as for when to add annotations and
1276 ;; what annotations to add. E.g. completing-help.el allowed adding
1277 ;; the first line of docstrings to M-x completion. But there's
1278 ;; a tension, since such annotations, while useful at times, can
1279 ;; actually drown the useful information.
1280 ;; So completion-annotate-function should be used parsimoniously, or
1281 ;; else only used upon a user's request (e.g. we could add a command
1282 ;; to completion-list-mode to add annotations to the current
1283 ;; completions).
1284 "Function to add annotations in the *Completions* buffer.
1285 The function takes a completion and should either return nil, or a string that
1286 will be displayed next to the completion. The function can access the
1287 completion table and predicates via `minibuffer-completion-table' and related
1288 variables.")
1289 (make-obsolete-variable 'completion-annotate-function
1290 'completion-extra-properties "24.1")
1292 (defun completion--done (string &optional finished message)
1293 (let* ((exit-fun (plist-get completion-extra-properties :exit-function))
1294 (pre-msg (and exit-fun (current-message))))
1295 (assert (memq finished '(exact sole finished unknown)))
1296 ;; FIXME: exit-fun should receive `finished' as a parameter.
1297 (when exit-fun
1298 (when (eq finished 'unknown)
1299 (setq finished
1300 (if (eq (try-completion string
1301 minibuffer-completion-table
1302 minibuffer-completion-predicate)
1304 'finished 'exact)))
1305 (funcall exit-fun string finished))
1306 (when (and message
1307 ;; Don't output any message if the exit-fun already did so.
1308 (equal pre-msg (and exit-fun (current-message))))
1309 (completion--message message))))
1311 (defun minibuffer-completion-help ()
1312 "Display a list of possible completions of the current minibuffer contents."
1313 (interactive)
1314 (message "Making completion list...")
1315 (let* ((start (field-beginning))
1316 (end (field-end))
1317 (string (field-string))
1318 (md (completion--field-metadata start))
1319 (completions (completion-all-completions
1320 string
1321 minibuffer-completion-table
1322 minibuffer-completion-predicate
1323 (- (point) (field-beginning))
1324 md)))
1325 (message nil)
1326 (if (or (null completions)
1327 (and (not (consp (cdr completions)))
1328 (equal (car completions) string)))
1329 (progn
1330 ;; If there are no completions, or if the current input is already
1331 ;; the sole completion, then hide (previous&stale) completions.
1332 (minibuffer-hide-completions)
1333 (ding)
1334 (minibuffer-message
1335 (if completions "Sole completion" "No completions")))
1337 (let* ((last (last completions))
1338 (base-size (cdr last))
1339 (prefix (unless (zerop base-size) (substring string 0 base-size)))
1340 (all-md (completion--metadata (buffer-substring-no-properties
1341 start (point))
1342 base-size md
1343 minibuffer-completion-table
1344 minibuffer-completion-predicate))
1345 (afun (or (completion-metadata-get all-md 'annotation-function)
1346 (plist-get completion-extra-properties
1347 :annotation-function)
1348 completion-annotate-function))
1349 ;; If the *Completions* buffer is shown in a new
1350 ;; window, mark it as softly-dedicated, so bury-buffer in
1351 ;; minibuffer-hide-completions will know whether to
1352 ;; delete the window or not.
1353 (display-buffer-mark-dedicated 'soft))
1354 (with-output-to-temp-buffer "*Completions*"
1355 ;; Remove the base-size tail because `sort' requires a properly
1356 ;; nil-terminated list.
1357 (when last (setcdr last nil))
1358 (setq completions
1359 ;; FIXME: This function is for the output of all-completions,
1360 ;; not completion-all-completions. Often it's the same, but
1361 ;; not always.
1362 (let ((sort-fun (completion-metadata-get
1363 all-md 'display-sort-function)))
1364 (if sort-fun
1365 (funcall sort-fun completions)
1366 (sort completions 'string-lessp))))
1367 (when afun
1368 (setq completions
1369 (mapcar (lambda (s)
1370 (let ((ann (funcall afun s)))
1371 (if ann (list s ann) s)))
1372 completions)))
1374 (with-current-buffer standard-output
1375 (set (make-local-variable 'completion-base-position)
1376 (list (+ start base-size)
1377 ;; FIXME: We should pay attention to completion
1378 ;; boundaries here, but currently
1379 ;; completion-all-completions does not give us the
1380 ;; necessary information.
1381 end))
1382 (set (make-local-variable 'completion-list-insert-choice-function)
1383 (let ((ctable minibuffer-completion-table)
1384 (cpred minibuffer-completion-predicate)
1385 (cprops completion-extra-properties))
1386 (lambda (start end choice)
1387 (unless (or (zerop (length prefix))
1388 (equal prefix
1389 (buffer-substring-no-properties
1390 (max (point-min)
1391 (- start (length prefix)))
1392 start)))
1393 (message "*Completions* out of date"))
1394 ;; FIXME: Use `md' to do quoting&terminator here.
1395 (completion--replace start end choice)
1396 (let* ((minibuffer-completion-table ctable)
1397 (minibuffer-completion-predicate cpred)
1398 (completion-extra-properties cprops)
1399 (result (concat prefix choice))
1400 (bounds (completion-boundaries
1401 result ctable cpred "")))
1402 ;; If the completion introduces a new field, then
1403 ;; completion is not finished.
1404 (completion--done result
1405 (if (eq (car bounds) (length result))
1406 'exact 'finished)))))))
1408 (display-completion-list completions))))
1409 nil))
1411 (defun minibuffer-hide-completions ()
1412 "Get rid of an out-of-date *Completions* buffer."
1413 ;; FIXME: We could/should use minibuffer-scroll-window here, but it
1414 ;; can also point to the minibuffer-parent-window, so it's a bit tricky.
1415 (let ((win (get-buffer-window "*Completions*" 0)))
1416 (if win (with-selected-window win (bury-buffer)))))
1418 (defun exit-minibuffer ()
1419 "Terminate this minibuffer argument."
1420 (interactive)
1421 ;; If the command that uses this has made modifications in the minibuffer,
1422 ;; we don't want them to cause deactivation of the mark in the original
1423 ;; buffer.
1424 ;; A better solution would be to make deactivate-mark buffer-local
1425 ;; (or to turn it into a list of buffers, ...), but in the mean time,
1426 ;; this should do the trick in most cases.
1427 (setq deactivate-mark nil)
1428 (throw 'exit nil))
1430 (defun self-insert-and-exit ()
1431 "Terminate minibuffer input."
1432 (interactive)
1433 (if (characterp last-command-event)
1434 (call-interactively 'self-insert-command)
1435 (ding))
1436 (exit-minibuffer))
1438 (defvar completion-in-region-functions nil
1439 "Wrapper hook around `completion-in-region'.
1440 The functions on this special hook are called with 5 arguments:
1441 NEXT-FUN START END COLLECTION PREDICATE.
1442 NEXT-FUN is a function of four arguments (START END COLLECTION PREDICATE)
1443 that performs the default operation. The other four arguments are like
1444 the ones passed to `completion-in-region'. The functions on this hook
1445 are expected to perform completion on START..END using COLLECTION
1446 and PREDICATE, either by calling NEXT-FUN or by doing it themselves.")
1448 (defvar completion-in-region--data nil)
1450 (defvar completion-in-region-mode-predicate nil
1451 "Predicate to tell `completion-in-region-mode' when to exit.
1452 It is called with no argument and should return nil when
1453 `completion-in-region-mode' should exit (and hence pop down
1454 the *Completions* buffer).")
1456 (defvar completion-in-region-mode--predicate nil
1457 "Copy of the value of `completion-in-region-mode-predicate'.
1458 This holds the value `completion-in-region-mode-predicate' had when
1459 we entered `completion-in-region-mode'.")
1461 (defun completion-in-region (start end collection &optional predicate)
1462 "Complete the text between START and END using COLLECTION.
1463 Return nil if there is no valid completion, else t.
1464 Point needs to be somewhere between START and END.
1465 PREDICATE (a function called with no arguments) says when to
1466 exit."
1467 (assert (<= start (point)) (<= (point) end))
1468 (with-wrapper-hook
1469 ;; FIXME: Maybe we should use this hook to provide a "display
1470 ;; completions" operation as well.
1471 completion-in-region-functions (start end collection predicate)
1472 (let ((minibuffer-completion-table collection)
1473 (minibuffer-completion-predicate predicate)
1474 (ol (make-overlay start end nil nil t)))
1475 (overlay-put ol 'field 'completion)
1476 (when completion-in-region-mode-predicate
1477 (completion-in-region-mode 1)
1478 (setq completion-in-region--data
1479 (list (current-buffer) start end collection)))
1480 (unwind-protect
1481 (call-interactively 'minibuffer-complete)
1482 (delete-overlay ol)))))
1484 (defvar completion-in-region-mode-map
1485 (let ((map (make-sparse-keymap)))
1486 ;; FIXME: Only works if completion-in-region-mode was activated via
1487 ;; completion-at-point called directly.
1488 (define-key map "?" 'completion-help-at-point)
1489 (define-key map "\t" 'completion-at-point)
1490 map)
1491 "Keymap activated during `completion-in-region'.")
1493 ;; It is difficult to know when to exit completion-in-region-mode (i.e. hide
1494 ;; the *Completions*).
1495 ;; - lisp-mode: never.
1496 ;; - comint: only do it if you hit SPC at the right time.
1497 ;; - pcomplete: pop it down on SPC or after some time-delay.
1498 ;; - semantic: use a post-command-hook check similar to this one.
1499 (defun completion-in-region--postch ()
1500 (or unread-command-events ;Don't pop down the completions in the middle of
1501 ;mouse-drag-region/mouse-set-point.
1502 (and completion-in-region--data
1503 (and (eq (car completion-in-region--data)
1504 (current-buffer))
1505 (>= (point) (nth 1 completion-in-region--data))
1506 (<= (point)
1507 (save-excursion
1508 (goto-char (nth 2 completion-in-region--data))
1509 (line-end-position)))
1510 (funcall completion-in-region-mode--predicate)))
1511 (completion-in-region-mode -1)))
1513 ;; (defalias 'completion-in-region--prech 'completion-in-region--postch)
1515 (define-minor-mode completion-in-region-mode
1516 "Transient minor mode used during `completion-in-region'."
1517 :global t
1518 (setq completion-in-region--data nil)
1519 ;; (remove-hook 'pre-command-hook #'completion-in-region--prech)
1520 (remove-hook 'post-command-hook #'completion-in-region--postch)
1521 (setq minor-mode-overriding-map-alist
1522 (delq (assq 'completion-in-region-mode minor-mode-overriding-map-alist)
1523 minor-mode-overriding-map-alist))
1524 (if (null completion-in-region-mode)
1525 (unless (equal "*Completions*" (buffer-name (window-buffer)))
1526 (minibuffer-hide-completions))
1527 ;; (add-hook 'pre-command-hook #'completion-in-region--prech)
1528 (assert completion-in-region-mode-predicate)
1529 (setq completion-in-region-mode--predicate
1530 completion-in-region-mode-predicate)
1531 (add-hook 'post-command-hook #'completion-in-region--postch)
1532 (push `(completion-in-region-mode . ,completion-in-region-mode-map)
1533 minor-mode-overriding-map-alist)))
1535 ;; Define-minor-mode added our keymap to minor-mode-map-alist, but we want it
1536 ;; on minor-mode-overriding-map-alist instead.
1537 (setq minor-mode-map-alist
1538 (delq (assq 'completion-in-region-mode minor-mode-map-alist)
1539 minor-mode-map-alist))
1541 (defvar completion-at-point-functions '(tags-completion-at-point-function)
1542 "Special hook to find the completion table for the thing at point.
1543 Each function on this hook is called in turns without any argument and should
1544 return either nil to mean that it is not applicable at point,
1545 or a function of no argument to perform completion (discouraged),
1546 or a list of the form (START END COLLECTION &rest PROPS) where
1547 START and END delimit the entity to complete and should include point,
1548 COLLECTION is the completion table to use to complete it, and
1549 PROPS is a property list for additional information.
1550 Currently supported properties are all the properties that can appear in
1551 `completion-extra-properties' plus:
1552 `:predicate' a predicate that completion candidates need to satisfy.
1553 `:exclusive' If `no', means that if the completion data does not match the
1554 text at point failure, then instead of reporting a completion failure,
1555 the completion should try the next completion function.")
1557 (defvar completion--capf-misbehave-funs nil
1558 "List of functions found on `completion-at-point-functions' that misbehave.
1559 These are functions that neither return completion data nor a completion
1560 function but instead perform completion right away.")
1561 (defvar completion--capf-safe-funs nil
1562 "List of well-behaved functions found on `completion-at-point-functions'.
1563 These are functions which return proper completion data rather than
1564 a completion function or god knows what else.")
1566 (defun completion--capf-wrapper (fun which)
1567 ;; FIXME: The safe/misbehave handling assumes that a given function will
1568 ;; always return the same kind of data, but this breaks down with functions
1569 ;; like comint-completion-at-point or mh-letter-completion-at-point, which
1570 ;; could be sometimes safe and sometimes misbehaving (and sometimes neither).
1571 (if (case which
1572 (all t)
1573 (safe (member fun completion--capf-safe-funs))
1574 (optimist (not (member fun completion--capf-misbehave-funs))))
1575 (let ((res (funcall fun)))
1576 (cond
1577 ((and (consp res) (not (functionp res)))
1578 (unless (member fun completion--capf-safe-funs)
1579 (push fun completion--capf-safe-funs))
1580 (and (eq 'no (plist-get (nthcdr 3 res) :exclusive))
1581 ;; FIXME: Here we'd need to decide whether there are
1582 ;; valid completions against the current text. But this depends
1583 ;; on the actual completion UI (e.g. with the default completion
1584 ;; it depends on completion-style) ;-(
1585 ;; We approximate this result by checking whether prefix
1586 ;; completion might work, which means that non-prefix completion
1587 ;; will not work (or not right) for completion functions that
1588 ;; are non-exclusive.
1589 (null (try-completion (buffer-substring-no-properties
1590 (car res) (point))
1591 (nth 2 res)
1592 (plist-get (nthcdr 3 res) :predicate)))
1593 (setq res nil)))
1594 ((not (or (listp res) (functionp res)))
1595 (unless (member fun completion--capf-misbehave-funs)
1596 (message
1597 "Completion function %S uses a deprecated calling convention" fun)
1598 (push fun completion--capf-misbehave-funs))))
1599 (if res (cons fun res)))))
1601 (defun completion-at-point ()
1602 "Perform completion on the text around point.
1603 The completion method is determined by `completion-at-point-functions'."
1604 (interactive)
1605 (let ((res (run-hook-wrapped 'completion-at-point-functions
1606 #'completion--capf-wrapper 'all)))
1607 (pcase res
1608 (`(,_ . ,(and (pred functionp) f)) (funcall f))
1609 (`(,hookfun . (,start ,end ,collection . ,plist))
1610 (let* ((completion-extra-properties plist)
1611 (completion-in-region-mode-predicate
1612 (lambda ()
1613 ;; We're still in the same completion field.
1614 (eq (car-safe (funcall hookfun)) start))))
1615 (completion-in-region start end collection
1616 (plist-get plist :predicate))))
1617 ;; Maybe completion already happened and the function returned t.
1618 (_ (cdr res)))))
1620 (defun completion-help-at-point ()
1621 "Display the completions on the text around point.
1622 The completion method is determined by `completion-at-point-functions'."
1623 (interactive)
1624 (let ((res (run-hook-wrapped 'completion-at-point-functions
1625 ;; Ignore misbehaving functions.
1626 #'completion--capf-wrapper 'optimist)))
1627 (pcase res
1628 (`(,_ . ,(and (pred functionp) f))
1629 (message "Don't know how to show completions for %S" f))
1630 (`(,hookfun . (,start ,end ,collection . ,plist))
1631 (let* ((minibuffer-completion-table collection)
1632 (minibuffer-completion-predicate (plist-get plist :predicate))
1633 (completion-extra-properties plist)
1634 (completion-in-region-mode-predicate
1635 (lambda ()
1636 ;; We're still in the same completion field.
1637 (eq (car-safe (funcall hookfun)) start)))
1638 (ol (make-overlay start end nil nil t)))
1639 ;; FIXME: We should somehow (ab)use completion-in-region-function or
1640 ;; introduce a corresponding hook (plus another for word-completion,
1641 ;; and another for force-completion, maybe?).
1642 (overlay-put ol 'field 'completion)
1643 (completion-in-region-mode 1)
1644 (setq completion-in-region--data
1645 (list (current-buffer) start end collection))
1646 (unwind-protect
1647 (call-interactively 'minibuffer-completion-help)
1648 (delete-overlay ol))))
1649 (`(,hookfun . ,_)
1650 ;; The hook function already performed completion :-(
1651 ;; Not much we can do at this point.
1652 (message "%s already performed completion!" hookfun)
1653 nil)
1654 (_ (message "Nothing to complete at point")))))
1656 ;;; Key bindings.
1658 (let ((map minibuffer-local-map))
1659 (define-key map "\C-g" 'abort-recursive-edit)
1660 (define-key map "\r" 'exit-minibuffer)
1661 (define-key map "\n" 'exit-minibuffer))
1663 (defvar minibuffer-local-completion-map
1664 (let ((map (make-sparse-keymap)))
1665 (set-keymap-parent map minibuffer-local-map)
1666 (define-key map "\t" 'minibuffer-complete)
1667 ;; M-TAB is already abused for many other purposes, so we should find
1668 ;; another binding for it.
1669 ;; (define-key map "\e\t" 'minibuffer-force-complete)
1670 (define-key map " " 'minibuffer-complete-word)
1671 (define-key map "?" 'minibuffer-completion-help)
1672 map)
1673 "Local keymap for minibuffer input with completion.")
1675 (defvar minibuffer-local-must-match-map
1676 (let ((map (make-sparse-keymap)))
1677 (set-keymap-parent map minibuffer-local-completion-map)
1678 (define-key map "\r" 'minibuffer-complete-and-exit)
1679 (define-key map "\n" 'minibuffer-complete-and-exit)
1680 map)
1681 "Local keymap for minibuffer input with completion, for exact match.")
1683 (defvar minibuffer-local-filename-completion-map
1684 (let ((map (make-sparse-keymap)))
1685 (define-key map " " nil)
1686 map)
1687 "Local keymap for minibuffer input with completion for filenames.
1688 Gets combined either with `minibuffer-local-completion-map' or
1689 with `minibuffer-local-must-match-map'.")
1691 (defvar minibuffer-local-filename-must-match-map (make-sparse-keymap))
1692 (make-obsolete-variable 'minibuffer-local-filename-must-match-map nil "24.1")
1693 (define-obsolete-variable-alias 'minibuffer-local-must-match-filename-map
1694 'minibuffer-local-filename-must-match-map "23.1")
1696 (let ((map minibuffer-local-ns-map))
1697 (define-key map " " 'exit-minibuffer)
1698 (define-key map "\t" 'exit-minibuffer)
1699 (define-key map "?" 'self-insert-and-exit))
1701 (defvar minibuffer-inactive-mode-map
1702 (let ((map (make-keymap)))
1703 (suppress-keymap map)
1704 (define-key map "e" 'find-file-other-frame)
1705 (define-key map "f" 'find-file-other-frame)
1706 (define-key map "b" 'switch-to-buffer-other-frame)
1707 (define-key map "i" 'info)
1708 (define-key map "m" 'mail)
1709 (define-key map "n" 'make-frame)
1710 (define-key map [mouse-1] (lambda () (interactive)
1711 (with-current-buffer "*Messages*"
1712 (goto-char (point-max))
1713 (display-buffer (current-buffer)))))
1714 ;; So the global down-mouse-1 binding doesn't clutter the execution of the
1715 ;; above mouse-1 binding.
1716 (define-key map [down-mouse-1] #'ignore)
1717 map)
1718 "Keymap for use in the minibuffer when it is not active.
1719 The non-mouse bindings in this keymap can only be used in minibuffer-only
1720 frames, since the minibuffer can normally not be selected when it is
1721 not active.")
1723 (define-derived-mode minibuffer-inactive-mode nil "InactiveMinibuffer"
1724 :abbrev-table nil ;abbrev.el is not loaded yet during dump.
1725 ;; Note: this major mode is called from minibuf.c.
1726 "Major mode to use in the minibuffer when it is not active.
1727 This is only used when the minibuffer area has no active minibuffer.")
1729 ;;; Completion tables.
1731 (defun minibuffer--double-dollars (str)
1732 (replace-regexp-in-string "\\$" "$$" str))
1734 (defun completion--make-envvar-table ()
1735 (mapcar (lambda (enventry)
1736 (substring enventry 0 (string-match-p "=" enventry)))
1737 process-environment))
1739 (defconst completion--embedded-envvar-re
1740 (concat "\\(?:^\\|[^$]\\(?:\\$\\$\\)*\\)"
1741 "$\\([[:alnum:]_]*\\|{\\([^}]*\\)\\)\\'"))
1743 (defun completion--embedded-envvar-table (string _pred action)
1744 "Completion table for envvars embedded in a string.
1745 The envvar syntax (and escaping) rules followed by this table are the
1746 same as `substitute-in-file-name'."
1747 ;; We ignore `pred', because the predicates passed to us via
1748 ;; read-file-name-internal are not 100% correct and fail here:
1749 ;; e.g. we get predicates like file-directory-p there, whereas the filename
1750 ;; completed needs to be passed through substitute-in-file-name before it
1751 ;; can be passed to file-directory-p.
1752 (when (string-match completion--embedded-envvar-re string)
1753 (let* ((beg (or (match-beginning 2) (match-beginning 1)))
1754 (table (completion--make-envvar-table))
1755 (prefix (substring string 0 beg)))
1756 (cond
1757 ((eq action 'lambda)
1758 ;; This table is expected to be used in conjunction with some
1759 ;; other table that provides the "main" completion. Let the
1760 ;; other table handle the test-completion case.
1761 nil)
1762 ((or (eq (car-safe action) 'boundaries) (eq action 'metadata))
1763 ;; Only return boundaries/metadata if there's something to complete,
1764 ;; since otherwise when we're used in
1765 ;; completion-table-in-turn, we could return boundaries and
1766 ;; let some subsequent table return a list of completions.
1767 ;; FIXME: Maybe it should rather be fixed in
1768 ;; completion-table-in-turn instead, but it's difficult to
1769 ;; do it efficiently there.
1770 (when (try-completion (substring string beg) table nil)
1771 ;; Compute the boundaries of the subfield to which this
1772 ;; completion applies.
1773 (if (eq action 'metadata)
1774 '(metadata (category . environment-variable))
1775 (let ((suffix (cdr action)))
1776 (list* 'boundaries
1777 (or (match-beginning 2) (match-beginning 1))
1778 (when (string-match "[^[:alnum:]_]" suffix)
1779 (match-beginning 0)))))))
1781 (if (eq (aref string (1- beg)) ?{)
1782 (setq table (apply-partially 'completion-table-with-terminator
1783 "}" table)))
1784 ;; Even if file-name completion is case-insensitive, we want
1785 ;; envvar completion to be case-sensitive.
1786 (let ((completion-ignore-case nil))
1787 (completion-table-with-context
1788 prefix table (substring string beg) nil action)))))))
1790 (defun completion-file-name-table (string pred action)
1791 "Completion table for file names."
1792 (with-demoted-errors
1793 (cond
1794 ((eq action 'metadata) '(metadata (category . file)))
1795 ((eq (car-safe action) 'boundaries)
1796 (let ((start (length (file-name-directory string)))
1797 (end (string-match-p "/" (cdr action))))
1798 (list* 'boundaries
1799 ;; if `string' is "C:" in w32, (file-name-directory string)
1800 ;; returns "C:/", so `start' is 3 rather than 2.
1801 ;; Not quite sure what is The Right Fix, but clipping it
1802 ;; back to 2 will work for this particular case. We'll
1803 ;; see if we can come up with a better fix when we bump
1804 ;; into more such problematic cases.
1805 (min start (length string)) end)))
1807 ((eq action 'lambda)
1808 (if (zerop (length string))
1809 nil ;Not sure why it's here, but it probably doesn't harm.
1810 (funcall (or pred 'file-exists-p) string)))
1813 (let* ((name (file-name-nondirectory string))
1814 (specdir (file-name-directory string))
1815 (realdir (or specdir default-directory)))
1817 (cond
1818 ((null action)
1819 (let ((comp (file-name-completion name realdir pred)))
1820 (if (stringp comp)
1821 (concat specdir comp)
1822 comp)))
1824 ((eq action t)
1825 (let ((all (file-name-all-completions name realdir)))
1827 ;; Check the predicate, if necessary.
1828 (unless (memq pred '(nil file-exists-p))
1829 (let ((comp ())
1830 (pred
1831 (if (eq pred 'file-directory-p)
1832 ;; Brute-force speed up for directory checking:
1833 ;; Discard strings which don't end in a slash.
1834 (lambda (s)
1835 (let ((len (length s)))
1836 (and (> len 0) (eq (aref s (1- len)) ?/))))
1837 ;; Must do it the hard (and slow) way.
1838 pred)))
1839 (let ((default-directory (expand-file-name realdir)))
1840 (dolist (tem all)
1841 (if (funcall pred tem) (push tem comp))))
1842 (setq all (nreverse comp))))
1844 all))))))))
1846 (defvar read-file-name-predicate nil
1847 "Current predicate used by `read-file-name-internal'.")
1848 (make-obsolete-variable 'read-file-name-predicate
1849 "use the regular PRED argument" "23.2")
1851 (defun completion--file-name-table (string pred action)
1852 "Internal subroutine for `read-file-name'. Do not call this.
1853 This is a completion table for file names, like `completion-file-name-table'
1854 except that it passes the file name through `substitute-in-file-name'."
1855 (cond
1856 ((eq (car-safe action) 'boundaries)
1857 ;; For the boundaries, we can't really delegate to
1858 ;; substitute-in-file-name+completion-file-name-table and then fix
1859 ;; them up (as we do for the other actions), because it would
1860 ;; require us to track the relationship between `str' and
1861 ;; `string', which is difficult. And in any case, if
1862 ;; substitute-in-file-name turns "fo-$TO-ba" into "fo-o/b-ba",
1863 ;; there's no way for us to return proper boundaries info, because
1864 ;; the boundary is not (yet) in `string'.
1866 ;; FIXME: Actually there is a way to return correct boundaries
1867 ;; info, at the condition of modifying the all-completions
1868 ;; return accordingly. But for now, let's not bother.
1869 (completion-file-name-table string pred action))
1872 (let* ((default-directory
1873 (if (stringp pred)
1874 ;; It used to be that `pred' was abused to pass `dir'
1875 ;; as an argument.
1876 (prog1 (file-name-as-directory (expand-file-name pred))
1877 (setq pred nil))
1878 default-directory))
1879 (str (condition-case nil
1880 (substitute-in-file-name string)
1881 (error string)))
1882 (comp (completion-file-name-table
1884 (with-no-warnings (or pred read-file-name-predicate))
1885 action)))
1887 (cond
1888 ((stringp comp)
1889 ;; Requote the $s before returning the completion.
1890 (minibuffer--double-dollars comp))
1891 ((and (null action) comp
1892 ;; Requote the $s before checking for changes.
1893 (setq str (minibuffer--double-dollars str))
1894 (not (string-equal string str)))
1895 ;; If there's no real completion, but substitute-in-file-name
1896 ;; changed the string, then return the new string.
1897 str)
1898 (t comp))))))
1900 (defalias 'read-file-name-internal
1901 (completion-table-in-turn 'completion--embedded-envvar-table
1902 'completion--file-name-table)
1903 "Internal subroutine for `read-file-name'. Do not call this.")
1905 (defvar read-file-name-function 'read-file-name-default
1906 "The function called by `read-file-name' to do its work.
1907 It should accept the same arguments as `read-file-name'.")
1909 (defcustom read-file-name-completion-ignore-case
1910 (if (memq system-type '(ms-dos windows-nt darwin cygwin))
1911 t nil)
1912 "Non-nil means when reading a file name completion ignores case."
1913 :group 'minibuffer
1914 :type 'boolean
1915 :version "22.1")
1917 (defcustom insert-default-directory t
1918 "Non-nil means when reading a filename start with default dir in minibuffer.
1920 When the initial minibuffer contents show a name of a file or a directory,
1921 typing RETURN without editing the initial contents is equivalent to typing
1922 the default file name.
1924 If this variable is non-nil, the minibuffer contents are always
1925 initially non-empty, and typing RETURN without editing will fetch the
1926 default name, if one is provided. Note however that this default name
1927 is not necessarily the same as initial contents inserted in the minibuffer,
1928 if the initial contents is just the default directory.
1930 If this variable is nil, the minibuffer often starts out empty. In
1931 that case you may have to explicitly fetch the next history element to
1932 request the default name; typing RETURN without editing will leave
1933 the minibuffer empty.
1935 For some commands, exiting with an empty minibuffer has a special meaning,
1936 such as making the current buffer visit no file in the case of
1937 `set-visited-file-name'."
1938 :group 'minibuffer
1939 :type 'boolean)
1941 ;; Not always defined, but only called if next-read-file-uses-dialog-p says so.
1942 (declare-function x-file-dialog "xfns.c"
1943 (prompt dir &optional default-filename mustmatch only-dir-p))
1945 (defun read-file-name--defaults (&optional dir initial)
1946 (let ((default
1947 (cond
1948 ;; With non-nil `initial', use `dir' as the first default.
1949 ;; Essentially, this mean reversing the normal order of the
1950 ;; current directory name and the current file name, i.e.
1951 ;; 1. with normal file reading:
1952 ;; 1.1. initial input is the current directory
1953 ;; 1.2. the first default is the current file name
1954 ;; 2. with non-nil `initial' (e.g. for `find-alternate-file'):
1955 ;; 2.2. initial input is the current file name
1956 ;; 2.1. the first default is the current directory
1957 (initial (abbreviate-file-name dir))
1958 ;; In file buffers, try to get the current file name
1959 (buffer-file-name
1960 (abbreviate-file-name buffer-file-name))))
1961 (file-name-at-point
1962 (run-hook-with-args-until-success 'file-name-at-point-functions)))
1963 (when file-name-at-point
1964 (setq default (delete-dups
1965 (delete "" (delq nil (list file-name-at-point default))))))
1966 ;; Append new defaults to the end of existing `minibuffer-default'.
1967 (append
1968 (if (listp minibuffer-default) minibuffer-default (list minibuffer-default))
1969 (if (listp default) default (list default)))))
1971 (defun read-file-name (prompt &optional dir default-filename mustmatch initial predicate)
1972 "Read file name, prompting with PROMPT and completing in directory DIR.
1973 Value is not expanded---you must call `expand-file-name' yourself.
1974 Default name to DEFAULT-FILENAME if user exits the minibuffer with
1975 the same non-empty string that was inserted by this function.
1976 (If DEFAULT-FILENAME is omitted, the visited file name is used,
1977 except that if INITIAL is specified, that combined with DIR is used.
1978 If DEFAULT-FILENAME is a list of file names, the first file name is used.)
1979 If the user exits with an empty minibuffer, this function returns
1980 an empty string. (This can only happen if the user erased the
1981 pre-inserted contents or if `insert-default-directory' is nil.)
1983 Fourth arg MUSTMATCH can take the following values:
1984 - nil means that the user can exit with any input.
1985 - t means that the user is not allowed to exit unless
1986 the input is (or completes to) an existing file.
1987 - `confirm' means that the user can exit with any input, but she needs
1988 to confirm her choice if the input is not an existing file.
1989 - `confirm-after-completion' means that the user can exit with any
1990 input, but she needs to confirm her choice if she called
1991 `minibuffer-complete' right before `minibuffer-complete-and-exit'
1992 and the input is not an existing file.
1993 - anything else behaves like t except that typing RET does not exit if it
1994 does non-null completion.
1996 Fifth arg INITIAL specifies text to start with.
1998 If optional sixth arg PREDICATE is non-nil, possible completions and
1999 the resulting file name must satisfy (funcall PREDICATE NAME).
2000 DIR should be an absolute directory name. It defaults to the value of
2001 `default-directory'.
2003 If this command was invoked with the mouse, use a graphical file
2004 dialog if `use-dialog-box' is non-nil, and the window system or X
2005 toolkit in use provides a file dialog box, and DIR is not a
2006 remote file. For graphical file dialogs, any the special values
2007 of MUSTMATCH; `confirm' and `confirm-after-completion' are
2008 treated as equivalent to nil.
2010 See also `read-file-name-completion-ignore-case'
2011 and `read-file-name-function'."
2012 (funcall (or read-file-name-function #'read-file-name-default)
2013 prompt dir default-filename mustmatch initial predicate))
2015 ;; minibuffer-completing-file-name is a variable used internally in minibuf.c
2016 ;; to determine whether to use minibuffer-local-filename-completion-map or
2017 ;; minibuffer-local-completion-map. It shouldn't be exported to Elisp.
2018 ;; FIXME: Actually, it is also used in rfn-eshadow.el we'd otherwise have to
2019 ;; use (eq minibuffer-completion-table #'read-file-name-internal), which is
2020 ;; probably even worse. Maybe We should add some read-file-name-setup-hook
2021 ;; instead, but for now, let's keep this non-obsolete.
2022 ;;(make-obsolete-variable 'minibuffer-completing-file-name nil "24.1" 'get)
2024 (defun read-file-name-default (prompt &optional dir default-filename mustmatch initial predicate)
2025 "Default method for reading file names.
2026 See `read-file-name' for the meaning of the arguments."
2027 (unless dir (setq dir default-directory))
2028 (unless (file-name-absolute-p dir) (setq dir (expand-file-name dir)))
2029 (unless default-filename
2030 (setq default-filename (if initial (expand-file-name initial dir)
2031 buffer-file-name)))
2032 ;; If dir starts with user's homedir, change that to ~.
2033 (setq dir (abbreviate-file-name dir))
2034 ;; Likewise for default-filename.
2035 (if default-filename
2036 (setq default-filename
2037 (if (consp default-filename)
2038 (mapcar 'abbreviate-file-name default-filename)
2039 (abbreviate-file-name default-filename))))
2040 (let ((insdef (cond
2041 ((and insert-default-directory (stringp dir))
2042 (if initial
2043 (cons (minibuffer--double-dollars (concat dir initial))
2044 (length (minibuffer--double-dollars dir)))
2045 (minibuffer--double-dollars dir)))
2046 (initial (cons (minibuffer--double-dollars initial) 0)))))
2048 (let ((completion-ignore-case read-file-name-completion-ignore-case)
2049 (minibuffer-completing-file-name t)
2050 (pred (or predicate 'file-exists-p))
2051 (add-to-history nil))
2053 (let* ((val
2054 (if (or (not (next-read-file-uses-dialog-p))
2055 ;; Graphical file dialogs can't handle remote
2056 ;; files (Bug#99).
2057 (file-remote-p dir))
2058 ;; We used to pass `dir' to `read-file-name-internal' by
2059 ;; abusing the `predicate' argument. It's better to
2060 ;; just use `default-directory', but in order to avoid
2061 ;; changing `default-directory' in the current buffer,
2062 ;; we don't let-bind it.
2063 (let ((dir (file-name-as-directory
2064 (expand-file-name dir))))
2065 (minibuffer-with-setup-hook
2066 (lambda ()
2067 (setq default-directory dir)
2068 ;; When the first default in `minibuffer-default'
2069 ;; duplicates initial input `insdef',
2070 ;; reset `minibuffer-default' to nil.
2071 (when (equal (or (car-safe insdef) insdef)
2072 (or (car-safe minibuffer-default)
2073 minibuffer-default))
2074 (setq minibuffer-default
2075 (cdr-safe minibuffer-default)))
2076 ;; On the first request on `M-n' fill
2077 ;; `minibuffer-default' with a list of defaults
2078 ;; relevant for file-name reading.
2079 (set (make-local-variable 'minibuffer-default-add-function)
2080 (lambda ()
2081 (with-current-buffer
2082 (window-buffer (minibuffer-selected-window))
2083 (read-file-name--defaults dir initial)))))
2084 (completing-read prompt 'read-file-name-internal
2085 pred mustmatch insdef
2086 'file-name-history default-filename)))
2087 ;; If DEFAULT-FILENAME not supplied and DIR contains
2088 ;; a file name, split it.
2089 (let ((file (file-name-nondirectory dir))
2090 ;; When using a dialog, revert to nil and non-nil
2091 ;; interpretation of mustmatch. confirm options
2092 ;; need to be interpreted as nil, otherwise
2093 ;; it is impossible to create new files using
2094 ;; dialogs with the default settings.
2095 (dialog-mustmatch
2096 (not (memq mustmatch
2097 '(nil confirm confirm-after-completion)))))
2098 (when (and (not default-filename)
2099 (not (zerop (length file))))
2100 (setq default-filename file)
2101 (setq dir (file-name-directory dir)))
2102 (when default-filename
2103 (setq default-filename
2104 (expand-file-name (if (consp default-filename)
2105 (car default-filename)
2106 default-filename)
2107 dir)))
2108 (setq add-to-history t)
2109 (x-file-dialog prompt dir default-filename
2110 dialog-mustmatch
2111 (eq predicate 'file-directory-p)))))
2113 (replace-in-history (eq (car-safe file-name-history) val)))
2114 ;; If completing-read returned the inserted default string itself
2115 ;; (rather than a new string with the same contents),
2116 ;; it has to mean that the user typed RET with the minibuffer empty.
2117 ;; In that case, we really want to return ""
2118 ;; so that commands such as set-visited-file-name can distinguish.
2119 (when (consp default-filename)
2120 (setq default-filename (car default-filename)))
2121 (when (eq val default-filename)
2122 ;; In this case, completing-read has not added an element
2123 ;; to the history. Maybe we should.
2124 (if (not replace-in-history)
2125 (setq add-to-history t))
2126 (setq val ""))
2127 (unless val (error "No file name specified"))
2129 (if (and default-filename
2130 (string-equal val (if (consp insdef) (car insdef) insdef)))
2131 (setq val default-filename))
2132 (setq val (substitute-in-file-name val))
2134 (if replace-in-history
2135 ;; Replace what Fcompleting_read added to the history
2136 ;; with what we will actually return. As an exception,
2137 ;; if that's the same as the second item in
2138 ;; file-name-history, it's really a repeat (Bug#4657).
2139 (let ((val1 (minibuffer--double-dollars val)))
2140 (if history-delete-duplicates
2141 (setcdr file-name-history
2142 (delete val1 (cdr file-name-history))))
2143 (if (string= val1 (cadr file-name-history))
2144 (pop file-name-history)
2145 (setcar file-name-history val1)))
2146 (if add-to-history
2147 ;; Add the value to the history--but not if it matches
2148 ;; the last value already there.
2149 (let ((val1 (minibuffer--double-dollars val)))
2150 (unless (and (consp file-name-history)
2151 (equal (car file-name-history) val1))
2152 (setq file-name-history
2153 (cons val1
2154 (if history-delete-duplicates
2155 (delete val1 file-name-history)
2156 file-name-history)))))))
2157 val))))
2159 (defun internal-complete-buffer-except (&optional buffer)
2160 "Perform completion on all buffers excluding BUFFER.
2161 BUFFER nil or omitted means use the current buffer.
2162 Like `internal-complete-buffer', but removes BUFFER from the completion list."
2163 (let ((except (if (stringp buffer) buffer (buffer-name buffer))))
2164 (apply-partially 'completion-table-with-predicate
2165 'internal-complete-buffer
2166 (lambda (name)
2167 (not (equal (if (consp name) (car name) name) except)))
2168 nil)))
2170 ;;; Old-style completion, used in Emacs-21 and Emacs-22.
2172 (defun completion-emacs21-try-completion (string table pred _point)
2173 (let ((completion (try-completion string table pred)))
2174 (if (stringp completion)
2175 (cons completion (length completion))
2176 completion)))
2178 (defun completion-emacs21-all-completions (string table pred _point)
2179 (completion-hilit-commonality
2180 (all-completions string table pred)
2181 (length string)
2182 (car (completion-boundaries string table pred ""))))
2184 (defun completion-emacs22-try-completion (string table pred point)
2185 (let ((suffix (substring string point))
2186 (completion (try-completion (substring string 0 point) table pred)))
2187 (if (not (stringp completion))
2188 completion
2189 ;; Merge a trailing / in completion with a / after point.
2190 ;; We used to only do it for word completion, but it seems to make
2191 ;; sense for all completions.
2192 ;; Actually, claiming this feature was part of Emacs-22 completion
2193 ;; is pushing it a bit: it was only done in minibuffer-completion-word,
2194 ;; which was (by default) not bound during file completion, where such
2195 ;; slashes are most likely to occur.
2196 (if (and (not (zerop (length completion)))
2197 (eq ?/ (aref completion (1- (length completion))))
2198 (not (zerop (length suffix)))
2199 (eq ?/ (aref suffix 0)))
2200 ;; This leaves point after the / .
2201 (setq suffix (substring suffix 1)))
2202 (cons (concat completion suffix) (length completion)))))
2204 (defun completion-emacs22-all-completions (string table pred point)
2205 (let ((beforepoint (substring string 0 point)))
2206 (completion-hilit-commonality
2207 (all-completions beforepoint table pred)
2208 point
2209 (car (completion-boundaries beforepoint table pred "")))))
2211 ;;; Basic completion.
2213 (defun completion--merge-suffix (completion point suffix)
2214 "Merge end of COMPLETION with beginning of SUFFIX.
2215 Simple generalization of the \"merge trailing /\" done in Emacs-22.
2216 Return the new suffix."
2217 (if (and (not (zerop (length suffix)))
2218 (string-match "\\(.+\\)\n\\1" (concat completion "\n" suffix)
2219 ;; Make sure we don't compress things to less
2220 ;; than we started with.
2221 point)
2222 ;; Just make sure we didn't match some other \n.
2223 (eq (match-end 1) (length completion)))
2224 (substring suffix (- (match-end 1) (match-beginning 1)))
2225 ;; Nothing to merge.
2226 suffix))
2228 (defun completion-basic--pattern (beforepoint afterpoint bounds)
2229 (delete
2230 "" (list (substring beforepoint (car bounds))
2231 'point
2232 (substring afterpoint 0 (cdr bounds)))))
2234 (defun completion-basic-try-completion (string table pred point)
2235 (let* ((beforepoint (substring string 0 point))
2236 (afterpoint (substring string point))
2237 (bounds (completion-boundaries beforepoint table pred afterpoint)))
2238 (if (zerop (cdr bounds))
2239 ;; `try-completion' may return a subtly different result
2240 ;; than `all+merge', so try to use it whenever possible.
2241 (let ((completion (try-completion beforepoint table pred)))
2242 (if (not (stringp completion))
2243 completion
2244 (cons
2245 (concat completion
2246 (completion--merge-suffix completion point afterpoint))
2247 (length completion))))
2248 (let* ((suffix (substring afterpoint (cdr bounds)))
2249 (prefix (substring beforepoint 0 (car bounds)))
2250 (pattern (delete
2251 "" (list (substring beforepoint (car bounds))
2252 'point
2253 (substring afterpoint 0 (cdr bounds)))))
2254 (all (completion-pcm--all-completions prefix pattern table pred)))
2255 (if minibuffer-completing-file-name
2256 (setq all (completion-pcm--filename-try-filter all)))
2257 (completion-pcm--merge-try pattern all prefix suffix)))))
2259 (defun completion-basic-all-completions (string table pred point)
2260 (let* ((beforepoint (substring string 0 point))
2261 (afterpoint (substring string point))
2262 (bounds (completion-boundaries beforepoint table pred afterpoint))
2263 ;; (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 (completion-hilit-commonality all point (car bounds))))
2272 ;;; Partial-completion-mode style completion.
2274 (defvar completion-pcm--delim-wild-regex nil
2275 "Regular expression matching delimiters controlling the partial-completion.
2276 Typically, this regular expression simply matches a delimiter, meaning
2277 that completion can add something at (match-beginning 0), but if it has
2278 a submatch 1, then completion can add something at (match-end 1).
2279 This is used when the delimiter needs to be of size zero (e.g. the transition
2280 from lowercase to uppercase characters).")
2282 (defun completion-pcm--prepare-delim-re (delims)
2283 (setq completion-pcm--delim-wild-regex (concat "[" delims "*]")))
2285 (defcustom completion-pcm-word-delimiters "-_./:| "
2286 "A string of characters treated as word delimiters for completion.
2287 Some arcane rules:
2288 If `]' is in this string, it must come first.
2289 If `^' is in this string, it must not come first.
2290 If `-' is in this string, it must come first or right after `]'.
2291 In other words, if S is this string, then `[S]' must be a valid Emacs regular
2292 expression (not containing character ranges like `a-z')."
2293 :set (lambda (symbol value)
2294 (set-default symbol value)
2295 ;; Refresh other vars.
2296 (completion-pcm--prepare-delim-re value))
2297 :initialize 'custom-initialize-reset
2298 :group 'minibuffer
2299 :type 'string)
2301 (defcustom completion-pcm-complete-word-inserts-delimiters nil
2302 "Treat the SPC or - inserted by `minibuffer-complete-word' as delimiters.
2303 Those chars are treated as delimiters iff this variable is non-nil.
2304 I.e. if non-nil, M-x SPC will just insert a \"-\" in the minibuffer, whereas
2305 if nil, it will list all possible commands in *Completions* because none of
2306 the commands start with a \"-\" or a SPC."
2307 :type 'boolean)
2309 (defun completion-pcm--pattern-trivial-p (pattern)
2310 (and (stringp (car pattern))
2311 ;; It can be followed by `point' and "" and still be trivial.
2312 (let ((trivial t))
2313 (dolist (elem (cdr pattern))
2314 (unless (member elem '(point ""))
2315 (setq trivial nil)))
2316 trivial)))
2318 (defun completion-pcm--string->pattern (string &optional point)
2319 "Split STRING into a pattern.
2320 A pattern is a list where each element is either a string
2321 or a symbol, see `completion-pcm--merge-completions'."
2322 (if (and point (< point (length string)))
2323 (let ((prefix (substring string 0 point))
2324 (suffix (substring string point)))
2325 (append (completion-pcm--string->pattern prefix)
2326 '(point)
2327 (completion-pcm--string->pattern suffix)))
2328 (let* ((pattern nil)
2329 (p 0)
2330 (p0 p))
2332 (while (and (setq p (string-match completion-pcm--delim-wild-regex
2333 string p))
2334 (or completion-pcm-complete-word-inserts-delimiters
2335 ;; If the char was added by minibuffer-complete-word,
2336 ;; then don't treat it as a delimiter, otherwise
2337 ;; "M-x SPC" ends up inserting a "-" rather than listing
2338 ;; all completions.
2339 (not (get-text-property p 'completion-try-word string))))
2340 ;; Usually, completion-pcm--delim-wild-regex matches a delimiter,
2341 ;; meaning that something can be added *before* it, but it can also
2342 ;; match a prefix and postfix, in which case something can be added
2343 ;; in-between (e.g. match [[:lower:]][[:upper:]]).
2344 ;; This is determined by the presence of a submatch-1 which delimits
2345 ;; the prefix.
2346 (if (match-end 1) (setq p (match-end 1)))
2347 (push (substring string p0 p) pattern)
2348 (if (eq (aref string p) ?*)
2349 (progn
2350 (push 'star pattern)
2351 (setq p0 (1+ p)))
2352 (push 'any pattern)
2353 (setq p0 p))
2354 (incf p))
2356 ;; An empty string might be erroneously added at the beginning.
2357 ;; It should be avoided properly, but it's so easy to remove it here.
2358 (delete "" (nreverse (cons (substring string p0) pattern))))))
2360 (defun completion-pcm--pattern->regex (pattern &optional group)
2361 (let ((re
2362 (concat "\\`"
2363 (mapconcat
2364 (lambda (x)
2365 (cond
2366 ((stringp x) (regexp-quote x))
2367 ((if (consp group) (memq x group) group) "\\(.*?\\)")
2368 (t ".*?")))
2369 pattern
2370 ""))))
2371 ;; Avoid pathological backtracking.
2372 (while (string-match "\\.\\*\\?\\(?:\\\\[()]\\)*\\(\\.\\*\\?\\)" re)
2373 (setq re (replace-match "" t t re 1)))
2374 re))
2376 (defun completion-pcm--all-completions (prefix pattern table pred)
2377 "Find all completions for PATTERN in TABLE obeying PRED.
2378 PATTERN is as returned by `completion-pcm--string->pattern'."
2379 ;; (assert (= (car (completion-boundaries prefix table pred ""))
2380 ;; (length prefix)))
2381 ;; Find an initial list of possible completions.
2382 (if (completion-pcm--pattern-trivial-p pattern)
2384 ;; Minibuffer contains no delimiters -- simple case!
2385 (all-completions (concat prefix (car pattern)) table pred)
2387 ;; Use all-completions to do an initial cull. This is a big win,
2388 ;; since all-completions is written in C!
2389 (let* (;; Convert search pattern to a standard regular expression.
2390 (regex (completion-pcm--pattern->regex pattern))
2391 (case-fold-search completion-ignore-case)
2392 (completion-regexp-list (cons regex completion-regexp-list))
2393 (compl (all-completions
2394 (concat prefix
2395 (if (stringp (car pattern)) (car pattern) ""))
2396 table pred)))
2397 (if (not (functionp table))
2398 ;; The internal functions already obeyed completion-regexp-list.
2399 compl
2400 (let ((poss ()))
2401 (dolist (c compl)
2402 (when (string-match-p regex c) (push c poss)))
2403 poss)))))
2405 (defun completion-pcm--hilit-commonality (pattern completions)
2406 (when completions
2407 (let* ((re (completion-pcm--pattern->regex pattern '(point)))
2408 (case-fold-search completion-ignore-case))
2409 (mapcar
2410 (lambda (str)
2411 ;; Don't modify the string itself.
2412 (setq str (copy-sequence str))
2413 (unless (string-match re str)
2414 (error "Internal error: %s does not match %s" re str))
2415 (let ((pos (or (match-beginning 1) (match-end 0))))
2416 (put-text-property 0 pos
2417 'font-lock-face 'completions-common-part
2418 str)
2419 (if (> (length str) pos)
2420 (put-text-property pos (1+ pos)
2421 'font-lock-face 'completions-first-difference
2422 str)))
2423 str)
2424 completions))))
2426 (defun completion-pcm--find-all-completions (string table pred point
2427 &optional filter)
2428 "Find all completions for STRING at POINT in TABLE, satisfying PRED.
2429 POINT is a position inside STRING.
2430 FILTER is a function applied to the return value, that can be used, e.g. to
2431 filter out additional entries (because TABLE migth not obey PRED)."
2432 (unless filter (setq filter 'identity))
2433 (let* ((beforepoint (substring string 0 point))
2434 (afterpoint (substring string point))
2435 (bounds (completion-boundaries beforepoint table pred afterpoint))
2436 (prefix (substring beforepoint 0 (car bounds)))
2437 (suffix (substring afterpoint (cdr bounds)))
2438 firsterror)
2439 (setq string (substring string (car bounds) (+ point (cdr bounds))))
2440 (let* ((relpoint (- point (car bounds)))
2441 (pattern (completion-pcm--string->pattern string relpoint))
2442 (all (condition-case err
2443 (funcall filter
2444 (completion-pcm--all-completions
2445 prefix pattern table pred))
2446 (error (unless firsterror (setq firsterror err)) nil))))
2447 (when (and (null all)
2448 (> (car bounds) 0)
2449 (null (ignore-errors (try-completion prefix table pred))))
2450 ;; The prefix has no completions at all, so we should try and fix
2451 ;; that first.
2452 (let ((substring (substring prefix 0 -1)))
2453 (destructuring-bind (subpat suball subprefix _subsuffix)
2454 (completion-pcm--find-all-completions
2455 substring table pred (length substring) filter)
2456 (let ((sep (aref prefix (1- (length prefix))))
2457 ;; Text that goes between the new submatches and the
2458 ;; completion substring.
2459 (between nil))
2460 ;; Eliminate submatches that don't end with the separator.
2461 (dolist (submatch (prog1 suball (setq suball ())))
2462 (when (eq sep (aref submatch (1- (length submatch))))
2463 (push submatch suball)))
2464 (when suball
2465 ;; Update the boundaries and corresponding pattern.
2466 ;; We assume that all submatches result in the same boundaries
2467 ;; since we wouldn't know how to merge them otherwise anyway.
2468 ;; FIXME: COMPLETE REWRITE!!!
2469 (let* ((newbeforepoint
2470 (concat subprefix (car suball)
2471 (substring string 0 relpoint)))
2472 (leftbound (+ (length subprefix) (length (car suball))))
2473 (newbounds (completion-boundaries
2474 newbeforepoint table pred afterpoint)))
2475 (unless (or (and (eq (cdr bounds) (cdr newbounds))
2476 (eq (car newbounds) leftbound))
2477 ;; Refuse new boundaries if they step over
2478 ;; the submatch.
2479 (< (car newbounds) leftbound))
2480 ;; The new completed prefix does change the boundaries
2481 ;; of the completed substring.
2482 (setq suffix (substring afterpoint (cdr newbounds)))
2483 (setq string
2484 (concat (substring newbeforepoint (car newbounds))
2485 (substring afterpoint 0 (cdr newbounds))))
2486 (setq between (substring newbeforepoint leftbound
2487 (car newbounds)))
2488 (setq pattern (completion-pcm--string->pattern
2489 string
2490 (- (length newbeforepoint)
2491 (car newbounds)))))
2492 (dolist (submatch suball)
2493 (setq all (nconc
2494 (mapcar
2495 (lambda (s) (concat submatch between s))
2496 (funcall filter
2497 (completion-pcm--all-completions
2498 (concat subprefix submatch between)
2499 pattern table pred)))
2500 all)))
2501 ;; FIXME: This can come in handy for try-completion,
2502 ;; but isn't right for all-completions, since it lists
2503 ;; invalid completions.
2504 ;; (unless all
2505 ;; ;; Even though we found expansions in the prefix, none
2506 ;; ;; leads to a valid completion.
2507 ;; ;; Let's keep the expansions, tho.
2508 ;; (dolist (submatch suball)
2509 ;; (push (concat submatch between newsubstring) all)))
2511 (setq pattern (append subpat (list 'any (string sep))
2512 (if between (list between)) pattern))
2513 (setq prefix subprefix)))))
2514 (if (and (null all) firsterror)
2515 (signal (car firsterror) (cdr firsterror))
2516 (list pattern all prefix suffix)))))
2518 (defun completion-pcm-all-completions (string table pred point)
2519 (destructuring-bind (pattern all &optional prefix _suffix)
2520 (completion-pcm--find-all-completions string table pred point)
2521 (when all
2522 (nconc (completion-pcm--hilit-commonality pattern all)
2523 (length prefix)))))
2525 (defun completion--sreverse (str)
2526 "Like `reverse' but for a string STR rather than a list."
2527 (apply 'string (nreverse (mapcar 'identity str))))
2529 (defun completion--common-suffix (strs)
2530 "Return the common suffix of the strings STRS."
2531 (completion--sreverse
2532 (try-completion
2534 (mapcar 'completion--sreverse strs))))
2536 (defun completion-pcm--merge-completions (strs pattern)
2537 "Extract the commonality in STRS, with the help of PATTERN.
2538 PATTERN can contain strings and symbols chosen among `star', `any', `point',
2539 and `prefix'. They all match anything (aka \".*\") but are merged differently:
2540 `any' only grows from the left (when matching \"a1b\" and \"a2b\" it gets
2541 completed to just \"a\").
2542 `prefix' only grows from the right (when matching \"a1b\" and \"a2b\" it gets
2543 completed to just \"b\").
2544 `star' grows from both ends and is reified into a \"*\" (when matching \"a1b\"
2545 and \"a2b\" it gets completed to \"a*b\").
2546 `point' is like `star' except that it gets reified as the position of point
2547 instead of being reified as a \"*\" character.
2548 The underlying idea is that we should return a string which still matches
2549 the same set of elements."
2550 ;; When completing while ignoring case, we want to try and avoid
2551 ;; completing "fo" to "foO" when completing against "FOO" (bug#4219).
2552 ;; So we try and make sure that the string we return is all made up
2553 ;; of text from the completions rather than part from the
2554 ;; completions and part from the input.
2555 ;; FIXME: This reduces the problems of inconsistent capitalization
2556 ;; but it doesn't fully fix it: we may still end up completing
2557 ;; "fo-ba" to "foo-BAR" or "FOO-bar" when completing against
2558 ;; '("foo-barr" "FOO-BARD").
2559 (cond
2560 ((null (cdr strs)) (list (car strs)))
2562 (let ((re (completion-pcm--pattern->regex pattern 'group))
2563 (ccs ())) ;Chopped completions.
2565 ;; First chop each string into the parts corresponding to each
2566 ;; non-constant element of `pattern', using regexp-matching.
2567 (let ((case-fold-search completion-ignore-case))
2568 (dolist (str strs)
2569 (unless (string-match re str)
2570 (error "Internal error: %s doesn't match %s" str re))
2571 (let ((chopped ())
2572 (last 0)
2573 (i 1)
2574 next)
2575 (while (setq next (match-end i))
2576 (push (substring str last next) chopped)
2577 (setq last next)
2578 (setq i (1+ i)))
2579 ;; Add the text corresponding to the implicit trailing `any'.
2580 (push (substring str last) chopped)
2581 (push (nreverse chopped) ccs))))
2583 ;; Then for each of those non-constant elements, extract the
2584 ;; commonality between them.
2585 (let ((res ())
2586 (fixed ""))
2587 ;; Make the implicit trailing `any' explicit.
2588 (dolist (elem (append pattern '(any)))
2589 (if (stringp elem)
2590 (setq fixed (concat fixed elem))
2591 (let ((comps ()))
2592 (dolist (cc (prog1 ccs (setq ccs nil)))
2593 (push (car cc) comps)
2594 (push (cdr cc) ccs))
2595 ;; Might improve the likelihood to avoid choosing
2596 ;; different capitalizations in different parts.
2597 ;; In practice, it doesn't seem to make any difference.
2598 (setq ccs (nreverse ccs))
2599 (let* ((prefix (try-completion fixed comps))
2600 (unique (or (and (eq prefix t) (setq prefix fixed))
2601 (eq t (try-completion prefix comps)))))
2602 (unless (or (eq elem 'prefix)
2603 (equal prefix ""))
2604 (push prefix res))
2605 ;; If there's only one completion, `elem' is not useful
2606 ;; any more: it can only match the empty string.
2607 ;; FIXME: in some cases, it may be necessary to turn an
2608 ;; `any' into a `star' because the surrounding context has
2609 ;; changed such that string->pattern wouldn't add an `any'
2610 ;; here any more.
2611 (unless unique
2612 (push elem res)
2613 (when (memq elem '(star point prefix))
2614 ;; Extract common suffix additionally to common prefix.
2615 ;; Only do it for `point', `star', and `prefix' since for
2616 ;; `any' it could lead to a merged completion that
2617 ;; doesn't itself match the candidates.
2618 (let ((suffix (completion--common-suffix comps)))
2619 (assert (stringp suffix))
2620 (unless (equal suffix "")
2621 (push suffix res)))))
2622 (setq fixed "")))))
2623 ;; We return it in reverse order.
2624 res)))))
2626 (defun completion-pcm--pattern->string (pattern)
2627 (mapconcat (lambda (x) (cond
2628 ((stringp x) x)
2629 ((eq x 'star) "*")
2630 (t ""))) ;any, point, prefix.
2631 pattern
2632 ""))
2634 ;; We want to provide the functionality of `try', but we use `all'
2635 ;; and then merge it. In most cases, this works perfectly, but
2636 ;; if the completion table doesn't consider the same completions in
2637 ;; `try' as in `all', then we have a problem. The most common such
2638 ;; case is for filename completion where completion-ignored-extensions
2639 ;; is only obeyed by the `try' code. We paper over the difference
2640 ;; here. Note that it is not quite right either: if the completion
2641 ;; table uses completion-table-in-turn, this filtering may take place
2642 ;; too late to correctly fallback from the first to the
2643 ;; second alternative.
2644 (defun completion-pcm--filename-try-filter (all)
2645 "Filter to adjust `all' file completion to the behavior of `try'."
2646 (when all
2647 (let ((try ())
2648 (re (concat "\\(?:\\`\\.\\.?/\\|"
2649 (regexp-opt completion-ignored-extensions)
2650 "\\)\\'")))
2651 (dolist (f all)
2652 (unless (string-match-p re f) (push f try)))
2653 (or try all))))
2656 (defun completion-pcm--merge-try (pattern all prefix suffix)
2657 (cond
2658 ((not (consp all)) all)
2659 ((and (not (consp (cdr all))) ;Only one completion.
2660 ;; Ignore completion-ignore-case here.
2661 (equal (completion-pcm--pattern->string pattern) (car all)))
2664 (let* ((mergedpat (completion-pcm--merge-completions all pattern))
2665 ;; `mergedpat' is in reverse order. Place new point (by
2666 ;; order of preference) either at the old point, or at
2667 ;; the last place where there's something to choose, or
2668 ;; at the very end.
2669 (pointpat (or (memq 'point mergedpat)
2670 (memq 'any mergedpat)
2671 (memq 'star mergedpat)
2672 ;; Not `prefix'.
2673 mergedpat))
2674 ;; New pos from the start.
2675 (newpos (length (completion-pcm--pattern->string pointpat)))
2676 ;; Do it afterwards because it changes `pointpat' by sideeffect.
2677 (merged (completion-pcm--pattern->string (nreverse mergedpat))))
2679 (setq suffix (completion--merge-suffix merged newpos suffix))
2680 (cons (concat prefix merged suffix) (+ newpos (length prefix)))))))
2682 (defun completion-pcm-try-completion (string table pred point)
2683 (destructuring-bind (pattern all prefix suffix)
2684 (completion-pcm--find-all-completions
2685 string table pred point
2686 (if minibuffer-completing-file-name
2687 'completion-pcm--filename-try-filter))
2688 (completion-pcm--merge-try pattern all prefix suffix)))
2690 ;;; Substring completion
2691 ;; Mostly derived from the code of `basic' completion.
2693 (defun completion-substring--all-completions (string table pred point)
2694 (let* ((beforepoint (substring string 0 point))
2695 (afterpoint (substring string point))
2696 (bounds (completion-boundaries beforepoint table pred afterpoint))
2697 (suffix (substring afterpoint (cdr bounds)))
2698 (prefix (substring beforepoint 0 (car bounds)))
2699 (basic-pattern (completion-basic--pattern
2700 beforepoint afterpoint bounds))
2701 (pattern (if (not (stringp (car basic-pattern)))
2702 basic-pattern
2703 (cons 'prefix basic-pattern)))
2704 (all (completion-pcm--all-completions prefix pattern table pred)))
2705 (list all pattern prefix suffix (car bounds))))
2707 (defun completion-substring-try-completion (string table pred point)
2708 (destructuring-bind (all pattern prefix suffix _carbounds)
2709 (completion-substring--all-completions string table pred point)
2710 (if minibuffer-completing-file-name
2711 (setq all (completion-pcm--filename-try-filter all)))
2712 (completion-pcm--merge-try pattern all prefix suffix)))
2714 (defun completion-substring-all-completions (string table pred point)
2715 (destructuring-bind (all pattern prefix _suffix _carbounds)
2716 (completion-substring--all-completions string table pred point)
2717 (when all
2718 (nconc (completion-pcm--hilit-commonality pattern all)
2719 (length prefix)))))
2721 ;; Initials completion
2722 ;; Complete /ums to /usr/monnier/src or lch to list-command-history.
2724 (defun completion-initials-expand (str table pred)
2725 (let ((bounds (completion-boundaries str table pred "")))
2726 (unless (or (zerop (length str))
2727 ;; Only check within the boundaries, since the
2728 ;; boundary char (e.g. /) might be in delim-regexp.
2729 (string-match completion-pcm--delim-wild-regex str
2730 (car bounds)))
2731 (if (zerop (car bounds))
2732 (mapconcat 'string str "-")
2733 ;; If there's a boundary, it's trickier. The main use-case
2734 ;; we consider here is file-name completion. We'd like
2735 ;; to expand ~/eee to ~/e/e/e and /eee to /e/e/e.
2736 ;; But at the same time, we don't want /usr/share/ae to expand
2737 ;; to /usr/share/a/e just because we mistyped "ae" for "ar",
2738 ;; so we probably don't want initials to touch anything that
2739 ;; looks like /usr/share/foo. As a heuristic, we just check that
2740 ;; the text before the boundary char is at most 1 char.
2741 ;; This allows both ~/eee and /eee and not much more.
2742 ;; FIXME: It sadly also disallows the use of ~/eee when that's
2743 ;; embedded within something else (e.g. "(~/eee" in Info node
2744 ;; completion or "ancestor:/eee" in bzr-revision completion).
2745 (when (< (car bounds) 3)
2746 (let ((sep (substring str (1- (car bounds)) (car bounds))))
2747 ;; FIXME: the above string-match checks the whole string, whereas
2748 ;; we end up only caring about the after-boundary part.
2749 (concat (substring str 0 (car bounds))
2750 (mapconcat 'string (substring str (car bounds)) sep))))))))
2752 (defun completion-initials-all-completions (string table pred _point)
2753 (let ((newstr (completion-initials-expand string table pred)))
2754 (when newstr
2755 (completion-pcm-all-completions newstr table pred (length newstr)))))
2757 (defun completion-initials-try-completion (string table pred _point)
2758 (let ((newstr (completion-initials-expand string table pred)))
2759 (when newstr
2760 (completion-pcm-try-completion newstr table pred (length newstr)))))
2762 (defvar completing-read-function 'completing-read-default
2763 "The function called by `completing-read' to do its work.
2764 It should accept the same arguments as `completing-read'.")
2766 (defun completing-read-default (prompt collection &optional predicate
2767 require-match initial-input
2768 hist def inherit-input-method)
2769 "Default method for reading from the minibuffer with completion.
2770 See `completing-read' for the meaning of the arguments."
2772 (when (consp initial-input)
2773 (setq initial-input
2774 (cons (car initial-input)
2775 ;; `completing-read' uses 0-based index while
2776 ;; `read-from-minibuffer' uses 1-based index.
2777 (1+ (cdr initial-input)))))
2779 (let* ((minibuffer-completion-table collection)
2780 (minibuffer-completion-predicate predicate)
2781 (minibuffer-completion-confirm (unless (eq require-match t)
2782 require-match))
2783 (base-keymap (if require-match
2784 minibuffer-local-must-match-map
2785 minibuffer-local-completion-map))
2786 (keymap (if (memq minibuffer-completing-file-name '(nil lambda))
2787 base-keymap
2788 ;; Layer minibuffer-local-filename-completion-map
2789 ;; on top of the base map.
2790 (make-composed-keymap
2791 minibuffer-local-filename-completion-map
2792 ;; Set base-keymap as the parent, so that nil bindings
2793 ;; in minibuffer-local-filename-completion-map can
2794 ;; override bindings in base-keymap.
2795 base-keymap)))
2796 (result (read-from-minibuffer prompt initial-input keymap
2797 nil hist def inherit-input-method)))
2798 (when (and (equal result "") def)
2799 (setq result (if (consp def) (car def) def)))
2800 result))
2802 ;; Miscellaneous
2804 (defun minibuffer-insert-file-name-at-point ()
2805 "Get a file name at point in original buffer and insert it to minibuffer."
2806 (interactive)
2807 (let ((file-name-at-point
2808 (with-current-buffer (window-buffer (minibuffer-selected-window))
2809 (run-hook-with-args-until-success 'file-name-at-point-functions))))
2810 (when file-name-at-point
2811 (insert file-name-at-point))))
2813 (provide 'minibuffer)
2815 ;;; minibuffer.el ends here