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