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