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