Handle systems without WCONTINUED consistently.
[emacs.git] / lisp / minibuffer.el
blob9dd4ef9fe04530a47eeab688352291c9787d1964
1 ;;; minibuffer.el --- Minibuffer completion functions -*- lexical-binding: t -*-
3 ;; Copyright (C) 2008-2014 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 lists 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 ;; - C-x C-f ~/*/sr ? should not list "~/./src".
49 ;; - minibuffer-force-complete completes ~/src/emacs/t<!>/lisp/minibuffer.el
50 ;; to ~/src/emacs/trunk/ and throws away lisp/minibuffer.el.
52 ;;; Todo:
54 ;; - Make *Completions* readable even if some of the completion
55 ;; entries have LF chars or spaces in them (including at
56 ;; beginning/end) or are very long.
57 ;; - for M-x, cycle-sort commands that have no key binding first.
58 ;; - Make things like icomplete-mode or lightning-completion work with
59 ;; completion-in-region-mode.
60 ;; - extend `metadata':
61 ;; - indicate how to turn all-completion's output into
62 ;; try-completion's output: e.g. completion-ignored-extensions.
63 ;; maybe that could be merged with the "quote" operation.
64 ;; - indicate that `all-completions' doesn't do prefix-completion
65 ;; but just returns some list that relates in some other way to
66 ;; the provided string (as is the case in filecache.el), in which
67 ;; case partial-completion (for example) doesn't make any sense
68 ;; and neither does the completions-first-difference highlight.
69 ;; - indicate how to display the completions in *Completions* (turn
70 ;; \n into something else, add special boundaries between
71 ;; completions). E.g. when completing from the kill-ring.
73 ;; - case-sensitivity currently confuses two issues:
74 ;; - whether or not a particular completion table should be case-sensitive
75 ;; (i.e. whether strings that differ only by case are semantically
76 ;; equivalent)
77 ;; - whether the user wants completion to pay attention to case.
78 ;; e.g. we may want to make it possible for the user to say "first try
79 ;; completion case-sensitively, and if that fails, try to ignore case".
80 ;; Maybe the trick is that we should distinguish completion-ignore-case in
81 ;; try/all-completions (obey user's preference) from its use in
82 ;; test-completion (obey the underlying object's semantics).
84 ;; - add support for ** to pcm.
85 ;; - Add vc-file-name-completion-table to read-file-name-internal.
86 ;; - A feature like completing-help.el.
88 ;;; Code:
90 (eval-when-compile (require 'cl-lib))
92 ;;; Completion table manipulation
94 ;; New completion-table operation.
95 (defun completion-boundaries (string table pred suffix)
96 "Return the boundaries of the completions returned by TABLE for STRING.
97 STRING is the string on which completion will be performed.
98 SUFFIX is the string after point.
99 The result is of the form (START . END) where START is the position
100 in STRING of the beginning of the completion field and END is the position
101 in SUFFIX of the end of the completion field.
102 E.g. for simple completion tables, the result is always (0 . (length SUFFIX))
103 and for file names the result is the positions delimited by
104 the closest directory separators."
105 (let ((boundaries (if (functionp table)
106 (funcall table string pred
107 (cons 'boundaries suffix)))))
108 (if (not (eq (car-safe boundaries) 'boundaries))
109 (setq boundaries nil))
110 (cons (or (cadr boundaries) 0)
111 (or (cddr boundaries) (length suffix)))))
113 (defun completion-metadata (string table pred)
114 "Return the metadata of elements to complete at the end of STRING.
115 This metadata is an alist. Currently understood keys are:
116 - `category': the kind of objects returned by `all-completions'.
117 Used by `completion-category-overrides'.
118 - `annotation-function': function to add annotations in *Completions*.
119 Takes one argument (STRING), which is a possible completion and
120 returns a string to append to STRING.
121 - `display-sort-function': function to sort entries in *Completions*.
122 Takes one argument (COMPLETIONS) and should return a new list
123 of completions. Can operate destructively.
124 - `cycle-sort-function': function to sort entries when cycling.
125 Works like `display-sort-function'.
126 The metadata of a completion table should be constant between two boundaries."
127 (let ((metadata (if (functionp table)
128 (funcall table string pred 'metadata))))
129 (if (eq (car-safe metadata) 'metadata)
130 metadata
131 '(metadata))))
133 (defun completion--field-metadata (field-start)
134 (completion-metadata (buffer-substring-no-properties field-start (point))
135 minibuffer-completion-table
136 minibuffer-completion-predicate))
138 (defun completion-metadata-get (metadata prop)
139 (cdr (assq prop metadata)))
141 (defun completion--some (fun xs)
142 "Apply FUN to each element of XS in turn.
143 Return the first non-nil returned value.
144 Like CL's `some'."
145 (let ((firsterror nil)
146 res)
147 (while (and (not res) xs)
148 (condition-case-unless-debug err
149 (setq res (funcall fun (pop xs)))
150 (error (unless firsterror (setq firsterror err)) nil)))
151 (or res
152 (if firsterror (signal (car firsterror) (cdr firsterror))))))
154 (defun complete-with-action (action table string pred)
155 "Perform completion ACTION.
156 STRING is the string to complete.
157 TABLE is the completion table.
158 PRED is a completion predicate.
159 ACTION can be one of nil, t or `lambda'."
160 (cond
161 ((functionp table) (funcall table string pred action))
162 ((eq (car-safe action) 'boundaries) nil)
163 ((eq action 'metadata) nil)
165 (funcall
166 (cond
167 ((null action) 'try-completion)
168 ((eq action t) 'all-completions)
169 (t 'test-completion))
170 string table pred))))
172 (defun completion-table-dynamic (fun)
173 "Use function FUN as a dynamic completion table.
174 FUN is called with one argument, the string for which completion is required,
175 and it should return an alist containing all the intended possible completions.
176 This alist may be a full list of possible completions so that FUN can ignore
177 the value of its argument. If completion is performed in the minibuffer,
178 FUN will be called in the buffer from which the minibuffer was entered.
180 The result of the `completion-table-dynamic' form is a function
181 that can be used as the COLLECTION argument to `try-completion' and
182 `all-completions'. See Info node `(elisp)Programmed Completion'.
184 See also the related function `completion-table-with-cache'."
185 (lambda (string pred action)
186 (if (or (eq (car-safe action) 'boundaries) (eq action 'metadata))
187 ;; `fun' is not supposed to return another function but a plain old
188 ;; completion table, whose boundaries are always trivial.
190 (with-current-buffer (let ((win (minibuffer-selected-window)))
191 (if (window-live-p win) (window-buffer win)
192 (current-buffer)))
193 (complete-with-action action (funcall fun string) string pred)))))
195 (defun completion-table-with-cache (fun &optional ignore-case)
196 "Create dynamic completion table from function FUN, with cache.
197 This is a wrapper for `completion-table-dynamic' that saves the last
198 argument-result pair from FUN, so that several lookups with the
199 same argument (or with an argument that starts with the first one)
200 only need to call FUN once. This can be useful when FUN performs a
201 relatively slow operation, such as calling an external process.
203 When IGNORE-CASE is non-nil, FUN is expected to be case-insensitive."
204 ;; See eg bug#11906.
205 (let* (last-arg last-result
206 (new-fun
207 (lambda (arg)
208 (if (and last-arg (string-prefix-p last-arg arg ignore-case))
209 last-result
210 (prog1
211 (setq last-result (funcall fun arg))
212 (setq last-arg arg))))))
213 (completion-table-dynamic new-fun)))
215 (defmacro lazy-completion-table (var fun)
216 "Initialize variable VAR as a lazy completion table.
217 If the completion table VAR is used for the first time (e.g., by passing VAR
218 as an argument to `try-completion'), the function FUN is called with no
219 arguments. FUN must return the completion table that will be stored in VAR.
220 If completion is requested in the minibuffer, FUN will be called in the buffer
221 from which the minibuffer was entered. The return value of
222 `lazy-completion-table' must be used to initialize the value of VAR.
224 You should give VAR a non-nil `risky-local-variable' property."
225 (declare (debug (symbolp lambda-expr)))
226 (let ((str (make-symbol "string")))
227 `(completion-table-dynamic
228 (lambda (,str)
229 (when (functionp ,var)
230 (setq ,var (funcall #',fun)))
231 ,var))))
233 (defun completion-table-case-fold (table &optional dont-fold)
234 "Return new completion TABLE that is case insensitive.
235 If DONT-FOLD is non-nil, return a completion table that is
236 case sensitive instead."
237 (lambda (string pred action)
238 (let ((completion-ignore-case (not dont-fold)))
239 (complete-with-action action table string pred))))
241 (defun completion-table-subvert (table s1 s2)
242 "Return a completion table from TABLE with S1 replaced by S2.
243 The result is a completion table which completes strings of the
244 form (concat S1 S) in the same way as TABLE completes strings of
245 the form (concat S2 S)."
246 (lambda (string pred action)
247 (let* ((str (if (eq t (compare-strings string 0 (length s1) s1 nil nil
248 completion-ignore-case))
249 (concat s2 (substring string (length s1)))))
250 (res (if str (complete-with-action action table str pred))))
251 (when res
252 (cond
253 ((eq (car-safe action) 'boundaries)
254 (let ((beg (or (and (eq (car-safe res) 'boundaries) (cadr res)) 0)))
255 `(boundaries
256 ,(max (length s1)
257 (+ beg (- (length s1) (length s2))))
258 . ,(and (eq (car-safe res) 'boundaries) (cddr res)))))
259 ((stringp res)
260 (if (eq t (compare-strings res 0 (length s2) s2 nil nil
261 completion-ignore-case))
262 (concat s1 (substring res (length s2)))))
263 ((eq action t)
264 (let ((bounds (completion-boundaries str table pred "")))
265 (if (>= (car bounds) (length s2))
267 (let ((re (concat "\\`"
268 (regexp-quote (substring s2 (car bounds))))))
269 (delq nil
270 (mapcar (lambda (c)
271 (if (string-match re c)
272 (substring c (match-end 0))))
273 res))))))
274 ;; E.g. action=nil and it's the only completion.
275 (res))))))
277 (defun completion-table-with-context (prefix table string pred action)
278 ;; TODO: add `suffix' maybe?
279 (let ((pred
280 (if (not (functionp pred))
281 ;; Notice that `pred' may not be a function in some abusive cases.
282 pred
283 ;; Predicates are called differently depending on the nature of
284 ;; the completion table :-(
285 (cond
286 ((vectorp table) ;Obarray.
287 (lambda (sym) (funcall pred (concat prefix (symbol-name sym)))))
288 ((hash-table-p table)
289 (lambda (s _v) (funcall pred (concat prefix s))))
290 ((functionp table)
291 (lambda (s) (funcall pred (concat prefix s))))
292 (t ;Lists and alists.
293 (lambda (s)
294 (funcall pred (concat prefix (if (consp s) (car s) s)))))))))
295 (if (eq (car-safe action) 'boundaries)
296 (let* ((len (length prefix))
297 (bound (completion-boundaries string table pred (cdr action))))
298 `(boundaries ,(+ (car bound) len) . ,(cdr bound)))
299 (let ((comp (complete-with-action action table string pred)))
300 (cond
301 ;; In case of try-completion, add the prefix.
302 ((stringp comp) (concat prefix comp))
303 (t comp))))))
305 (defun completion-table-with-terminator (terminator table string pred action)
306 "Construct a completion table like TABLE but with an extra TERMINATOR.
307 This is meant to be called in a curried way by first passing TERMINATOR
308 and TABLE only (via `apply-partially').
309 TABLE is a completion table, and TERMINATOR is a string appended to TABLE's
310 completion if it is complete. TERMINATOR is also used to determine the
311 completion suffix's boundary.
312 TERMINATOR can also be a cons cell (TERMINATOR . TERMINATOR-REGEXP)
313 in which case TERMINATOR-REGEXP is a regular expression whose submatch
314 number 1 should match TERMINATOR. This is used when there is a need to
315 distinguish occurrences of the TERMINATOR strings which are really terminators
316 from others (e.g. escaped). In this form, the car of TERMINATOR can also be,
317 instead of a string, a function that takes the completion and returns the
318 \"terminated\" string."
319 ;; FIXME: This implementation is not right since it only adds the terminator
320 ;; in try-completion, so any completion-style that builds the completion via
321 ;; all-completions won't get the terminator, and selecting an entry in
322 ;; *Completions* won't get the terminator added either.
323 (cond
324 ((eq (car-safe action) 'boundaries)
325 (let* ((suffix (cdr action))
326 (bounds (completion-boundaries string table pred suffix))
327 (terminator-regexp (if (consp terminator)
328 (cdr terminator) (regexp-quote terminator)))
329 (max (and terminator-regexp
330 (string-match terminator-regexp suffix))))
331 `(boundaries ,(car bounds)
332 . ,(min (cdr bounds) (or max (length suffix))))))
333 ((eq action nil)
334 (let ((comp (try-completion string table pred)))
335 (if (consp terminator) (setq terminator (car terminator)))
336 (if (eq comp t)
337 (if (functionp terminator)
338 (funcall terminator string)
339 (concat string terminator))
340 (if (and (stringp comp) (not (zerop (length comp)))
341 ;; Try to avoid the second call to try-completion, since
342 ;; it may be very inefficient (because `comp' made us
343 ;; jump to a new boundary, so we complete in that
344 ;; boundary with an empty start string).
345 (let ((newbounds (completion-boundaries comp table pred "")))
346 (< (car newbounds) (length comp)))
347 (eq (try-completion comp table pred) t))
348 (if (functionp terminator)
349 (funcall terminator comp)
350 (concat comp terminator))
351 comp))))
352 ;; completion-table-with-terminator is always used for
353 ;; "sub-completions" so it's only called if the terminator is missing,
354 ;; in which case `test-completion' should return nil.
355 ((eq action 'lambda) nil)
357 ;; FIXME: We generally want the `try' and `all' behaviors to be
358 ;; consistent so pcm can merge the `all' output to get the `try' output,
359 ;; but that sometimes clashes with the need for `all' output to look
360 ;; good in *Completions*.
361 ;; (mapcar (lambda (s) (concat s terminator))
362 ;; (all-completions string table pred))))
363 (complete-with-action action table string pred))))
365 (defun completion-table-with-predicate (table pred1 strict string pred2 action)
366 "Make a completion table equivalent to TABLE but filtered through PRED1.
367 PRED1 is a function of one argument which returns non-nil if and only if the
368 argument is an element of TABLE which should be considered for completion.
369 STRING, PRED2, and ACTION are the usual arguments to completion tables,
370 as described in `try-completion', `all-completions', and `test-completion'.
371 If STRICT is t, the predicate always applies; if nil it only applies if
372 it does not reduce the set of possible completions to nothing.
373 Note: TABLE needs to be a proper completion table which obeys predicates."
374 (cond
375 ((and (not strict) (eq action 'lambda))
376 ;; Ignore pred1 since it doesn't really have to apply anyway.
377 (test-completion string table pred2))
379 (or (complete-with-action action table string
380 (if (not (and pred1 pred2))
381 (or pred1 pred2)
382 (lambda (x)
383 ;; Call `pred1' first, so that `pred2'
384 ;; really can't tell that `x' is in table.
385 (and (funcall pred1 x) (funcall pred2 x)))))
386 ;; If completion failed and we're not applying pred1 strictly, try
387 ;; again without pred1.
388 (and (not strict) pred1 pred2
389 (complete-with-action action table string pred2))))))
391 (defun completion-table-in-turn (&rest tables)
392 "Create a completion table that tries each table in TABLES in turn."
393 ;; FIXME: the boundaries may come from TABLE1 even when the completion list
394 ;; is returned by TABLE2 (because TABLE1 returned an empty list).
395 ;; Same potential problem if any of the tables use quoting.
396 (lambda (string pred action)
397 (completion--some (lambda (table)
398 (complete-with-action action table string pred))
399 tables)))
401 (defun completion-table-merge (&rest tables)
402 "Create a completion table that collects completions from all TABLES."
403 ;; FIXME: same caveats as in `completion-table-in-turn'.
404 (lambda (string pred action)
405 (cond
406 ((null action)
407 (let ((retvals (mapcar (lambda (table)
408 (try-completion string table pred))
409 tables)))
410 (if (member string retvals)
411 string
412 (try-completion string
413 (mapcar (lambda (value)
414 (if (eq value t) string value))
415 (delq nil retvals))
416 pred))))
417 ((eq action t)
418 (apply #'append (mapcar (lambda (table)
419 (all-completions string table pred))
420 tables)))
422 (completion--some (lambda (table)
423 (complete-with-action action table string pred))
424 tables)))))
426 (defun completion-table-with-quoting (table unquote requote)
427 ;; A difficult part of completion-with-quoting is to map positions in the
428 ;; quoted string to equivalent positions in the unquoted string and
429 ;; vice-versa. There is no efficient and reliable algorithm that works for
430 ;; arbitrary quote and unquote functions.
431 ;; So to map from quoted positions to unquoted positions, we simply assume
432 ;; that `concat' and `unquote' commute (which tends to be the case).
433 ;; And we ask `requote' to do the work of mapping from unquoted positions
434 ;; back to quoted positions.
435 ;; FIXME: For some forms of "quoting" such as the truncation behavior of
436 ;; substitute-in-file-name, it would be desirable not to requote completely.
437 "Return a new completion table operating on quoted text.
438 TABLE operates on the unquoted text.
439 UNQUOTE is a function that takes a string and returns a new unquoted string.
440 REQUOTE is a function of 2 args (UPOS QSTR) where
441 QSTR is a string entered by the user (and hence indicating
442 the user's preferred form of quoting); and
443 UPOS is a position within the unquoted form of QSTR.
444 REQUOTE should return a pair (QPOS . QFUN) such that QPOS is the
445 position corresponding to UPOS but in QSTR, and QFUN is a function
446 of one argument (a string) which returns that argument appropriately quoted
447 for use at QPOS."
448 ;; FIXME: One problem with the current setup is that `qfun' doesn't know if
449 ;; its argument is "the end of the completion", so if the quoting used double
450 ;; quotes (for example), we end up completing "fo" to "foobar and throwing
451 ;; away the closing double quote.
452 (lambda (string pred action)
453 (cond
454 ((eq action 'metadata)
455 (append (completion-metadata string table pred)
456 '((completion--unquote-requote . t))))
458 ((eq action 'lambda) ;;test-completion
459 (let ((ustring (funcall unquote string)))
460 (test-completion ustring table pred)))
462 ((eq (car-safe action) 'boundaries)
463 (let* ((ustring (funcall unquote string))
464 (qsuffix (cdr action))
465 (ufull (if (zerop (length qsuffix)) ustring
466 (funcall unquote (concat string qsuffix))))
467 (_ (cl-assert (string-prefix-p ustring ufull)))
468 (usuffix (substring ufull (length ustring)))
469 (boundaries (completion-boundaries ustring table pred usuffix))
470 (qlboundary (car (funcall requote (car boundaries) string)))
471 (qrboundary (if (zerop (cdr boundaries)) 0 ;Common case.
472 (let* ((urfullboundary
473 (+ (cdr boundaries) (length ustring))))
474 (- (car (funcall requote urfullboundary
475 (concat string qsuffix)))
476 (length string))))))
477 `(boundaries ,qlboundary . ,qrboundary)))
479 ;; In "normal" use a c-t-with-quoting completion table should never be
480 ;; called with action in (t nil) because `completion--unquote' should have
481 ;; been called before and would have returned a different completion table
482 ;; to apply to the unquoted text. But there's still a lot of code around
483 ;; that likes to use all/try-completions directly, so we do our best to
484 ;; handle those calls as well as we can.
486 ((eq action nil) ;;try-completion
487 (let* ((ustring (funcall unquote string))
488 (completion (try-completion ustring table pred)))
489 ;; Most forms of quoting allow several ways to quote the same string.
490 ;; So here we could simply requote `completion' in a kind of
491 ;; "canonical" quoted form without paying attention to the way
492 ;; `string' was quoted. But since we have to solve the more complex
493 ;; problems of "pay attention to the original quoting" for
494 ;; all-completions, we may as well use it here, since it provides
495 ;; a nicer behavior.
496 (if (not (stringp completion)) completion
497 (car (completion--twq-try
498 string ustring completion 0 unquote requote)))))
500 ((eq action t) ;;all-completions
501 ;; When all-completions is used for completion-try/all-completions
502 ;; (e.g. for `pcm' style), we can't do the job properly here because
503 ;; the caller will match our output against some pattern derived from
504 ;; the user's (quoted) input, and we don't have access to that
505 ;; pattern, so we can't know how to requote our output so that it
506 ;; matches the quoting used in the pattern. It is to fix this
507 ;; fundamental problem that we have to introduce the new
508 ;; unquote-requote method so that completion-try/all-completions can
509 ;; pass the unquoted string to the style functions.
510 (pcase-let*
511 ((ustring (funcall unquote string))
512 (completions (all-completions ustring table pred))
513 (boundary (car (completion-boundaries ustring table pred "")))
514 (completions
515 (completion--twq-all
516 string ustring completions boundary unquote requote))
517 (last (last completions)))
518 (when (consp last) (setcdr last nil))
519 completions))
521 ((eq action 'completion--unquote)
522 (let ((ustring (funcall unquote string))
523 (uprefix (funcall unquote (substring string 0 pred))))
524 ;; We presume (more or less) that `concat' and `unquote' commute.
525 (cl-assert (string-prefix-p uprefix ustring))
526 (list ustring table (length uprefix)
527 (lambda (unquoted-result op)
528 (pcase op
529 (1 ;;try
530 (if (not (stringp (car-safe unquoted-result)))
531 unquoted-result
532 (completion--twq-try
533 string ustring
534 (car unquoted-result) (cdr unquoted-result)
535 unquote requote)))
536 (2 ;;all
537 (let* ((last (last unquoted-result))
538 (base (or (cdr last) 0)))
539 (when last
540 (setcdr last nil)
541 (completion--twq-all string ustring
542 unquoted-result base
543 unquote requote))))))))))))
545 (defun completion--twq-try (string ustring completion point
546 unquote requote)
547 ;; Basically two cases: either the new result is
548 ;; - commonprefix1 <point> morecommonprefix <qpos> suffix
549 ;; - commonprefix <qpos> newprefix <point> suffix
550 (pcase-let*
551 ((prefix (fill-common-string-prefix ustring completion))
552 (suffix (substring completion (max point (length prefix))))
553 (`(,qpos . ,qfun) (funcall requote (length prefix) string))
554 (qstr1 (if (> point (length prefix))
555 (funcall qfun (substring completion (length prefix) point))))
556 (qsuffix (funcall qfun suffix))
557 (qstring (concat (substring string 0 qpos) qstr1 qsuffix))
558 (qpoint
559 (cond
560 ((zerop point) 0)
561 ((> point (length prefix)) (+ qpos (length qstr1)))
562 (t (car (funcall requote point string))))))
563 ;; Make sure `requote' worked.
564 (if (equal (funcall unquote qstring) completion)
565 (cons qstring qpoint)
566 ;; If requote failed (e.g. because sifn-requote did not handle
567 ;; Tramp's "/foo:/bar//baz -> /foo:/baz" truncation), then at least
568 ;; try requote properly.
569 (let ((qstr (funcall qfun completion)))
570 (cons qstr (length qstr))))))
572 (defun completion--string-equal-p (s1 s2)
573 (eq t (compare-strings s1 nil nil s2 nil nil 'ignore-case)))
575 (defun completion--twq-all (string ustring completions boundary
576 _unquote requote)
577 (when completions
578 (pcase-let*
579 ((prefix
580 (let ((completion-regexp-list nil))
581 (try-completion "" (cons (substring ustring boundary)
582 completions))))
583 (`(,qfullpos . ,qfun)
584 (funcall requote (+ boundary (length prefix)) string))
585 (qfullprefix (substring string 0 qfullpos))
586 ;; FIXME: This assertion can be wrong, e.g. in Cygwin, where
587 ;; (unquote "c:\bin") => "/usr/bin" but (unquote "c:\") => "/".
588 ;;(cl-assert (completion--string-equal-p
589 ;; (funcall unquote qfullprefix)
590 ;; (concat (substring ustring 0 boundary) prefix))
591 ;; t))
592 (qboundary (car (funcall requote boundary string)))
593 (_ (cl-assert (<= qboundary qfullpos)))
594 ;; FIXME: this split/quote/concat business messes up the carefully
595 ;; placed completions-common-part and completions-first-difference
596 ;; faces. We could try within the mapcar loop to search for the
597 ;; boundaries of those faces, pass them to `requote' to find their
598 ;; equivalent positions in the quoted output and re-add the faces:
599 ;; this might actually lead to correct results but would be
600 ;; pretty expensive.
601 ;; The better solution is to not quote the *Completions* display,
602 ;; which nicely circumvents the problem. The solution I used here
603 ;; instead is to hope that `qfun' preserves the text-properties and
604 ;; presume that the `first-difference' is not within the `prefix';
605 ;; this presumption is not always true, but at least in practice it is
606 ;; true in most cases.
607 (qprefix (propertize (substring qfullprefix qboundary)
608 'face 'completions-common-part)))
610 ;; Here we choose to quote all elements returned, but a better option
611 ;; would be to return unquoted elements together with a function to
612 ;; requote them, so that *Completions* can show nicer unquoted values
613 ;; which only get quoted when needed by choose-completion.
614 (nconc
615 (mapcar (lambda (completion)
616 (cl-assert (string-prefix-p prefix completion 'ignore-case) t)
617 (let* ((new (substring completion (length prefix)))
618 (qnew (funcall qfun new))
619 (qprefix
620 (if (not completion-ignore-case)
621 qprefix
622 ;; Make qprefix inherit the case from `completion'.
623 (let* ((rest (substring completion
624 0 (length prefix)))
625 (qrest (funcall qfun rest)))
626 (if (completion--string-equal-p qprefix qrest)
627 (propertize qrest 'face
628 'completions-common-part)
629 qprefix))))
630 (qcompletion (concat qprefix qnew)))
631 ;; FIXME: Similarly here, Cygwin's mapping trips this
632 ;; assertion.
633 ;;(cl-assert
634 ;; (completion--string-equal-p
635 ;; (funcall unquote
636 ;; (concat (substring string 0 qboundary)
637 ;; qcompletion))
638 ;; (concat (substring ustring 0 boundary)
639 ;; completion))
640 ;; t)
641 qcompletion))
642 completions)
643 qboundary))))
645 ;; (defmacro complete-in-turn (a b) `(completion-table-in-turn ,a ,b))
646 ;; (defmacro dynamic-completion-table (fun) `(completion-table-dynamic ,fun))
647 (define-obsolete-function-alias
648 'complete-in-turn 'completion-table-in-turn "23.1")
649 (define-obsolete-function-alias
650 'dynamic-completion-table 'completion-table-dynamic "23.1")
652 ;;; Minibuffer completion
654 (defgroup minibuffer nil
655 "Controlling the behavior of the minibuffer."
656 :link '(custom-manual "(emacs)Minibuffer")
657 :group 'environment)
659 (defun minibuffer-message (message &rest args)
660 "Temporarily display MESSAGE at the end of the minibuffer.
661 The text is displayed for `minibuffer-message-timeout' seconds,
662 or until the next input event arrives, whichever comes first.
663 Enclose MESSAGE in [...] if this is not yet the case.
664 If ARGS are provided, then pass MESSAGE through `format'."
665 (if (not (minibufferp (current-buffer)))
666 (progn
667 (if args
668 (apply 'message message args)
669 (message "%s" message))
670 (prog1 (sit-for (or minibuffer-message-timeout 1000000))
671 (message nil)))
672 ;; Clear out any old echo-area message to make way for our new thing.
673 (message nil)
674 (setq message (if (and (null args)
675 (string-match-p "\\` *\\[.+\\]\\'" message))
676 ;; Make sure we can put-text-property.
677 (copy-sequence message)
678 (concat " [" message "]")))
679 (when args (setq message (apply 'format message args)))
680 (let ((ol (make-overlay (point-max) (point-max) nil t t))
681 ;; A quit during sit-for normally only interrupts the sit-for,
682 ;; but since minibuffer-message is used at the end of a command,
683 ;; at a time when the command has virtually finished already, a C-g
684 ;; should really cause an abort-recursive-edit instead (i.e. as if
685 ;; the C-g had been typed at top-level). Binding inhibit-quit here
686 ;; is an attempt to get that behavior.
687 (inhibit-quit t))
688 (unwind-protect
689 (progn
690 (unless (zerop (length message))
691 ;; The current C cursor code doesn't know to use the overlay's
692 ;; marker's stickiness to figure out whether to place the cursor
693 ;; before or after the string, so let's spoon-feed it the pos.
694 (put-text-property 0 1 'cursor t message))
695 (overlay-put ol 'after-string message)
696 (sit-for (or minibuffer-message-timeout 1000000)))
697 (delete-overlay ol)))))
699 (defun minibuffer-completion-contents ()
700 "Return the user input in a minibuffer before point as a string.
701 In Emacs-22, that was what completion commands operated on."
702 (declare (obsolete nil "24.4"))
703 (buffer-substring (minibuffer-prompt-end) (point)))
705 (defun delete-minibuffer-contents ()
706 "Delete all user input in a minibuffer.
707 If the current buffer is not a minibuffer, erase its entire contents."
708 (interactive)
709 ;; We used to do `delete-field' here, but when file name shadowing
710 ;; is on, the field doesn't cover the entire minibuffer contents.
711 (delete-region (minibuffer-prompt-end) (point-max)))
713 (defvar completion-show-inline-help t
714 "If non-nil, print helpful inline messages during completion.")
716 (defcustom completion-auto-help t
717 "Non-nil means automatically provide help for invalid completion input.
718 If the value is t the *Completion* buffer is displayed whenever completion
719 is requested but cannot be done.
720 If the value is `lazy', the *Completions* buffer is only displayed after
721 the second failed attempt to complete."
722 :type '(choice (const nil) (const t) (const lazy)))
724 (defconst completion-styles-alist
725 '((emacs21
726 completion-emacs21-try-completion completion-emacs21-all-completions
727 "Simple prefix-based completion.
728 I.e. when completing \"foo_bar\" (where _ is the position of point),
729 it will consider all completions candidates matching the glob
730 pattern \"foobar*\".")
731 (emacs22
732 completion-emacs22-try-completion completion-emacs22-all-completions
733 "Prefix completion that only operates on the text before point.
734 I.e. when completing \"foo_bar\" (where _ is the position of point),
735 it will consider all completions candidates matching the glob
736 pattern \"foo*\" and will add back \"bar\" to the end of it.")
737 (basic
738 completion-basic-try-completion completion-basic-all-completions
739 "Completion of the prefix before point and the suffix after point.
740 I.e. when completing \"foo_bar\" (where _ is the position of point),
741 it will consider all completions candidates matching the glob
742 pattern \"foo*bar*\".")
743 (partial-completion
744 completion-pcm-try-completion completion-pcm-all-completions
745 "Completion of multiple words, each one taken as a prefix.
746 I.e. when completing \"l-co_h\" (where _ is the position of point),
747 it will consider all completions candidates matching the glob
748 pattern \"l*-co*h*\".
749 Furthermore, for completions that are done step by step in subfields,
750 the method is applied to all the preceding fields that do not yet match.
751 E.g. C-x C-f /u/mo/s TAB could complete to /usr/monnier/src.
752 Additionally the user can use the char \"*\" as a glob pattern.")
753 (substring
754 completion-substring-try-completion completion-substring-all-completions
755 "Completion of the string taken as a substring.
756 I.e. when completing \"foo_bar\" (where _ is the position of point),
757 it will consider all completions candidates matching the glob
758 pattern \"*foo*bar*\".")
759 (initials
760 completion-initials-try-completion completion-initials-all-completions
761 "Completion of acronyms and initialisms.
762 E.g. can complete M-x lch to list-command-history
763 and C-x C-f ~/sew to ~/src/emacs/work."))
764 "List of available completion styles.
765 Each element has the form (NAME TRY-COMPLETION ALL-COMPLETIONS DOC):
766 where NAME is the name that should be used in `completion-styles',
767 TRY-COMPLETION is the function that does the completion (it should
768 follow the same calling convention as `completion-try-completion'),
769 ALL-COMPLETIONS is the function that lists the completions (it should
770 follow the calling convention of `completion-all-completions'),
771 and DOC describes the way this style of completion works.")
773 (defconst completion--styles-type
774 `(repeat :tag "insert a new menu to add more styles"
775 (choice ,@(mapcar (lambda (x) (list 'const (car x)))
776 completion-styles-alist))))
777 (defconst completion--cycling-threshold-type
778 '(choice (const :tag "No cycling" nil)
779 (const :tag "Always cycle" t)
780 (integer :tag "Threshold")))
782 (defcustom completion-styles
783 ;; First, use `basic' because prefix completion has been the standard
784 ;; for "ever" and works well in most cases, so using it first
785 ;; ensures that we obey previous behavior in most cases.
786 '(basic
787 ;; Then use `partial-completion' because it has proven to
788 ;; be a very convenient extension.
789 partial-completion
790 ;; Finally use `emacs22' so as to maintain (in many/most cases)
791 ;; the previous behavior that when completing "foobar" with point
792 ;; between "foo" and "bar" the completion try to complete "foo"
793 ;; and simply add "bar" to the end of the result.
794 emacs22)
795 "List of completion styles to use.
796 The available styles are listed in `completion-styles-alist'.
798 Note that `completion-category-overrides' may override these
799 styles for specific categories, such as files, buffers, etc."
800 :type completion--styles-type
801 :version "23.1")
803 (defcustom completion-category-overrides
804 '((buffer (styles . (basic substring))))
805 "List of `completion-styles' overrides for specific categories.
806 Each override has the shape (CATEGORY . ALIST) where ALIST is
807 an association list that can specify properties such as:
808 - `styles': the list of `completion-styles' to use for that category.
809 - `cycle': the `completion-cycle-threshold' to use for that category.
810 Categories are symbols such as `buffer' and `file', used when
811 completing buffer and file names, respectively."
812 :version "24.1"
813 :type `(alist :key-type (choice :tag "Category"
814 (const buffer)
815 (const file)
816 (const unicode-name)
817 (const bookmark)
818 symbol)
819 :value-type
820 (set :tag "Properties to override"
821 (cons :tag "Completion Styles"
822 (const :tag "Select a style from the menu;" styles)
823 ,completion--styles-type)
824 (cons :tag "Completion Cycling"
825 (const :tag "Select one value from the menu." cycle)
826 ,completion--cycling-threshold-type))))
828 (defun completion--styles (metadata)
829 (let* ((cat (completion-metadata-get metadata 'category))
830 (over (assq 'styles (cdr (assq cat completion-category-overrides)))))
831 (if over
832 (delete-dups (append (cdr over) (copy-sequence completion-styles)))
833 completion-styles)))
835 (defun completion--nth-completion (n string table pred point metadata)
836 "Call the Nth method of completion styles."
837 (unless metadata
838 (setq metadata
839 (completion-metadata (substring string 0 point) table pred)))
840 ;; We provide special support for quoting/unquoting here because it cannot
841 ;; reliably be done within the normal completion-table routines: Completion
842 ;; styles such as `substring' or `partial-completion' need to match the
843 ;; output of all-completions with the user's input, and since most/all
844 ;; quoting mechanisms allow several equivalent quoted forms, the
845 ;; completion-style can't do this matching (e.g. `substring' doesn't know
846 ;; that "\a\b\e" is a valid (quoted) substring of "label").
847 ;; The quote/unquote function needs to come from the completion table (rather
848 ;; than from completion-extra-properties) because it may apply only to some
849 ;; part of the string (e.g. substitute-in-file-name).
850 (let ((requote
851 (when (completion-metadata-get metadata 'completion--unquote-requote)
852 (let ((new (funcall table string point 'completion--unquote)))
853 (setq string (pop new))
854 (setq table (pop new))
855 (setq point (pop new))
856 (pop new))))
857 (result
858 (completion--some (lambda (style)
859 (funcall (nth n (assq style
860 completion-styles-alist))
861 string table pred point))
862 (completion--styles metadata))))
863 (if requote
864 (funcall requote result n)
865 result)))
867 (defun completion-try-completion (string table pred point &optional metadata)
868 "Try to complete STRING using completion table TABLE.
869 Only the elements of table that satisfy predicate PRED are considered.
870 POINT is the position of point within STRING.
871 The return value can be either nil to indicate that there is no completion,
872 t to indicate that STRING is the only possible completion,
873 or a pair (NEWSTRING . NEWPOINT) of the completed result string together with
874 a new position for point."
875 (completion--nth-completion 1 string table pred point metadata))
877 (defun completion-all-completions (string table pred point &optional metadata)
878 "List the possible completions of STRING in completion table TABLE.
879 Only the elements of table that satisfy predicate PRED are considered.
880 POINT is the position of point within STRING.
881 The return value is a list of completions and may contain the base-size
882 in the last `cdr'."
883 ;; FIXME: We need to additionally return the info needed for the
884 ;; second part of completion-base-position.
885 (completion--nth-completion 2 string table pred point metadata))
887 (defun minibuffer--bitset (modified completions exact)
888 (logior (if modified 4 0)
889 (if completions 2 0)
890 (if exact 1 0)))
892 (defun completion--replace (beg end newtext)
893 "Replace the buffer text between BEG and END with NEWTEXT.
894 Moves point to the end of the new text."
895 ;; The properties on `newtext' include things like
896 ;; completions-first-difference, which we don't want to include
897 ;; upon insertion.
898 (set-text-properties 0 (length newtext) nil newtext)
899 ;; Maybe this should be in subr.el.
900 ;; You'd think this is trivial to do, but details matter if you want
901 ;; to keep markers "at the right place" and be robust in the face of
902 ;; after-change-functions that may themselves modify the buffer.
903 (let ((prefix-len 0))
904 ;; Don't touch markers in the shared prefix (if any).
905 (while (and (< prefix-len (length newtext))
906 (< (+ beg prefix-len) end)
907 (eq (char-after (+ beg prefix-len))
908 (aref newtext prefix-len)))
909 (setq prefix-len (1+ prefix-len)))
910 (unless (zerop prefix-len)
911 (setq beg (+ beg prefix-len))
912 (setq newtext (substring newtext prefix-len))))
913 (let ((suffix-len 0))
914 ;; Don't touch markers in the shared suffix (if any).
915 (while (and (< suffix-len (length newtext))
916 (< beg (- end suffix-len))
917 (eq (char-before (- end suffix-len))
918 (aref newtext (- (length newtext) suffix-len 1))))
919 (setq suffix-len (1+ suffix-len)))
920 (unless (zerop suffix-len)
921 (setq end (- end suffix-len))
922 (setq newtext (substring newtext 0 (- suffix-len))))
923 (goto-char beg)
924 (let ((length (- end beg))) ;Read `end' before we insert the text.
925 (insert-and-inherit newtext)
926 (delete-region (point) (+ (point) length)))
927 (forward-char suffix-len)))
929 (defcustom completion-cycle-threshold nil
930 "Number of completion candidates below which cycling is used.
931 Depending on this setting `completion-in-region' may use cycling,
932 like `minibuffer-force-complete'.
933 If nil, cycling is never used.
934 If t, cycling is always used.
935 If an integer, cycling is used so long as there are not more
936 completion candidates than this number."
937 :version "24.1"
938 :type completion--cycling-threshold-type)
940 (defun completion--cycle-threshold (metadata)
941 (let* ((cat (completion-metadata-get metadata 'category))
942 (over (assq 'cycle (cdr (assq cat completion-category-overrides)))))
943 (if over (cdr over) completion-cycle-threshold)))
945 (defvar-local completion-all-sorted-completions nil)
946 (defvar-local completion--all-sorted-completions-location nil)
947 (defvar completion-cycling nil)
949 (defvar completion-fail-discreetly nil
950 "If non-nil, stay quiet when there is no match.")
952 (defun completion--message (msg)
953 (if completion-show-inline-help
954 (minibuffer-message msg)))
956 (defun completion--do-completion (beg end &optional
957 try-completion-function expect-exact)
958 "Do the completion and return a summary of what happened.
959 M = completion was performed, the text was Modified.
960 C = there were available Completions.
961 E = after completion we now have an Exact match.
964 000 0 no possible completion
965 001 1 was already an exact and unique completion
966 010 2 no completion happened
967 011 3 was already an exact completion
968 100 4 ??? impossible
969 101 5 ??? impossible
970 110 6 some completion happened
971 111 7 completed to an exact completion
973 TRY-COMPLETION-FUNCTION is a function to use in place of `try-completion'.
974 EXPECT-EXACT, if non-nil, means that there is no need to tell the user
975 when the buffer's text is already an exact match."
976 (let* ((string (buffer-substring beg end))
977 (md (completion--field-metadata beg))
978 (comp (funcall (or try-completion-function
979 'completion-try-completion)
980 string
981 minibuffer-completion-table
982 minibuffer-completion-predicate
983 (- (point) beg)
984 md)))
985 (cond
986 ((null comp)
987 (minibuffer-hide-completions)
988 (unless completion-fail-discreetly
989 (ding)
990 (completion--message "No match"))
991 (minibuffer--bitset nil nil nil))
992 ((eq t comp)
993 (minibuffer-hide-completions)
994 (goto-char end)
995 (completion--done string 'finished
996 (unless expect-exact "Sole completion"))
997 (minibuffer--bitset nil nil t)) ;Exact and unique match.
999 ;; `completed' should be t if some completion was done, which doesn't
1000 ;; include simply changing the case of the entered string. However,
1001 ;; for appearance, the string is rewritten if the case changes.
1002 (let* ((comp-pos (cdr comp))
1003 (completion (car comp))
1004 (completed (not (eq t (compare-strings completion nil nil
1005 string nil nil t))))
1006 (unchanged (eq t (compare-strings completion nil nil
1007 string nil nil nil))))
1008 (if unchanged
1009 (goto-char end)
1010 ;; Insert in minibuffer the chars we got.
1011 (completion--replace beg end completion)
1012 (setq end (+ beg (length completion))))
1013 ;; Move point to its completion-mandated destination.
1014 (forward-char (- comp-pos (length completion)))
1016 (if (not (or unchanged completed))
1017 ;; The case of the string changed, but that's all. We're not sure
1018 ;; whether this is a unique completion or not, so try again using
1019 ;; the real case (this shouldn't recurse again, because the next
1020 ;; time try-completion will return either t or the exact string).
1021 (completion--do-completion beg end
1022 try-completion-function expect-exact)
1024 ;; It did find a match. Do we match some possibility exactly now?
1025 (let* ((exact (test-completion completion
1026 minibuffer-completion-table
1027 minibuffer-completion-predicate))
1028 (threshold (completion--cycle-threshold md))
1029 (comps
1030 ;; Check to see if we want to do cycling. We do it
1031 ;; here, after having performed the normal completion,
1032 ;; so as to take advantage of the difference between
1033 ;; try-completion and all-completions, for things
1034 ;; like completion-ignored-extensions.
1035 (when (and threshold
1036 ;; Check that the completion didn't make
1037 ;; us jump to a different boundary.
1038 (or (not completed)
1039 (< (car (completion-boundaries
1040 (substring completion 0 comp-pos)
1041 minibuffer-completion-table
1042 minibuffer-completion-predicate
1043 ""))
1044 comp-pos)))
1045 (completion-all-sorted-completions beg end))))
1046 (completion--flush-all-sorted-completions)
1047 (cond
1048 ((and (consp (cdr comps)) ;; There's something to cycle.
1049 (not (ignore-errors
1050 ;; This signal an (intended) error if comps is too
1051 ;; short or if completion-cycle-threshold is t.
1052 (consp (nthcdr threshold comps)))))
1053 ;; Not more than completion-cycle-threshold remaining
1054 ;; completions: let's cycle.
1055 (setq completed t exact t)
1056 (completion--cache-all-sorted-completions beg end comps)
1057 (minibuffer-force-complete beg end))
1058 (completed
1059 ;; We could also decide to refresh the completions,
1060 ;; if they're displayed (and assuming there are
1061 ;; completions left).
1062 (minibuffer-hide-completions)
1063 (if exact
1064 ;; If completion did not put point at end of field,
1065 ;; it's a sign that completion is not finished.
1066 (completion--done completion
1067 (if (< comp-pos (length completion))
1068 'exact 'unknown))))
1069 ;; Show the completion table, if requested.
1070 ((not exact)
1071 (if (pcase completion-auto-help
1072 (`lazy (eq this-command last-command))
1073 (_ completion-auto-help))
1074 (minibuffer-completion-help beg end)
1075 (completion--message "Next char not unique")))
1076 ;; If the last exact completion and this one were the same, it
1077 ;; means we've already given a "Complete, but not unique" message
1078 ;; and the user's hit TAB again, so now we give him help.
1080 (if (and (eq this-command last-command) completion-auto-help)
1081 (minibuffer-completion-help beg end))
1082 (completion--done completion 'exact
1083 (unless expect-exact
1084 "Complete, but not unique"))))
1086 (minibuffer--bitset completed t exact))))))))
1088 (defun minibuffer-complete ()
1089 "Complete the minibuffer contents as far as possible.
1090 Return nil if there is no valid completion, else t.
1091 If no characters can be completed, display a list of possible completions.
1092 If you repeat this command after it displayed such a list,
1093 scroll the window of possible completions."
1094 (interactive)
1095 (completion-in-region (minibuffer-prompt-end) (point-max)
1096 minibuffer-completion-table
1097 minibuffer-completion-predicate))
1099 (defun completion--in-region-1 (beg end)
1100 ;; If the previous command was not this,
1101 ;; mark the completion buffer obsolete.
1102 (setq this-command 'completion-at-point)
1103 (unless (eq 'completion-at-point last-command)
1104 (completion--flush-all-sorted-completions)
1105 (setq minibuffer-scroll-window nil))
1107 (cond
1108 ;; If there's a fresh completion window with a live buffer,
1109 ;; and this command is repeated, scroll that window.
1110 ((and (window-live-p minibuffer-scroll-window)
1111 (eq t (frame-visible-p (window-frame minibuffer-scroll-window))))
1112 (let ((window minibuffer-scroll-window))
1113 (with-current-buffer (window-buffer window)
1114 (if (pos-visible-in-window-p (point-max) window)
1115 ;; If end is in view, scroll up to the beginning.
1116 (set-window-start window (point-min) nil)
1117 ;; Else scroll down one screen.
1118 (with-selected-window window
1119 (scroll-up)))
1120 nil)))
1121 ;; If we're cycling, keep on cycling.
1122 ((and completion-cycling completion-all-sorted-completions)
1123 (minibuffer-force-complete beg end)
1125 (t (pcase (completion--do-completion beg end)
1126 (#b000 nil)
1127 (_ t)))))
1129 (defun completion--cache-all-sorted-completions (beg end comps)
1130 (add-hook 'after-change-functions
1131 'completion--flush-all-sorted-completions nil t)
1132 (setq completion--all-sorted-completions-location
1133 (cons (copy-marker beg) (copy-marker end)))
1134 (setq completion-all-sorted-completions comps))
1136 (defun completion--flush-all-sorted-completions (&optional start end _len)
1137 (unless (and start end
1138 (or (> start (cdr completion--all-sorted-completions-location))
1139 (< end (car completion--all-sorted-completions-location))))
1140 (remove-hook 'after-change-functions
1141 'completion--flush-all-sorted-completions t)
1142 (setq completion-cycling nil)
1143 (setq completion-all-sorted-completions nil)))
1145 (defun completion--metadata (string base md-at-point table pred)
1146 ;; Like completion-metadata, but for the specific case of getting the
1147 ;; metadata at `base', which tends to trigger pathological behavior for old
1148 ;; completion tables which don't understand `metadata'.
1149 (let ((bounds (completion-boundaries string table pred "")))
1150 (if (eq (car bounds) base) md-at-point
1151 (completion-metadata (substring string 0 base) table pred))))
1153 (defun completion-all-sorted-completions (&optional start end)
1154 (or completion-all-sorted-completions
1155 (let* ((start (or start (minibuffer-prompt-end)))
1156 (end (or end (point-max)))
1157 (string (buffer-substring start end))
1158 (md (completion--field-metadata start))
1159 (all (completion-all-completions
1160 string
1161 minibuffer-completion-table
1162 minibuffer-completion-predicate
1163 (- (point) start)
1164 md))
1165 (last (last all))
1166 (base-size (or (cdr last) 0))
1167 (all-md (completion--metadata (buffer-substring-no-properties
1168 start (point))
1169 base-size md
1170 minibuffer-completion-table
1171 minibuffer-completion-predicate))
1172 (sort-fun (completion-metadata-get all-md 'cycle-sort-function)))
1173 (when last
1174 (setcdr last nil)
1176 ;; Delete duplicates: do it after setting last's cdr to nil (so
1177 ;; it's a proper list), and be careful to reset `last' since it
1178 ;; may be a different cons-cell.
1179 (setq all (delete-dups all))
1180 (setq last (last all))
1182 (setq all (if sort-fun (funcall sort-fun all)
1183 ;; Prefer shorter completions, by default.
1184 (sort all (lambda (c1 c2) (< (length c1) (length c2))))))
1185 ;; Prefer recently used completions.
1186 (when (minibufferp)
1187 (let ((hist (symbol-value minibuffer-history-variable)))
1188 (setq all (sort all (lambda (c1 c2)
1189 (> (length (member c1 hist))
1190 (length (member c2 hist))))))))
1191 ;; Cache the result. This is not just for speed, but also so that
1192 ;; repeated calls to minibuffer-force-complete can cycle through
1193 ;; all possibilities.
1194 (completion--cache-all-sorted-completions
1195 start end (nconc all base-size))))))
1197 (defun minibuffer-force-complete-and-exit ()
1198 "Complete the minibuffer with first of the matches and exit."
1199 (interactive)
1200 (minibuffer-force-complete)
1201 (completion--complete-and-exit
1202 (minibuffer-prompt-end) (point-max) #'exit-minibuffer
1203 ;; If the previous completion completed to an element which fails
1204 ;; test-completion, then we shouldn't exit, but that should be rare.
1205 (lambda () (minibuffer-message "Incomplete"))))
1207 (defun minibuffer-force-complete (&optional start end)
1208 "Complete the minibuffer to an exact match.
1209 Repeated uses step through the possible completions."
1210 (interactive)
1211 (setq minibuffer-scroll-window nil)
1212 ;; FIXME: Need to deal with the extra-size issue here as well.
1213 ;; FIXME: ~/src/emacs/t<M-TAB>/lisp/minibuffer.el completes to
1214 ;; ~/src/emacs/trunk/ and throws away lisp/minibuffer.el.
1215 (let* ((start (copy-marker (or start (minibuffer-prompt-end))))
1216 (end (or end (point-max)))
1217 ;; (md (completion--field-metadata start))
1218 (all (completion-all-sorted-completions start end))
1219 (base (+ start (or (cdr (last all)) 0))))
1220 (cond
1221 ((not (consp all))
1222 (completion--message
1223 (if all "No more completions" "No completions")))
1224 ((not (consp (cdr all)))
1225 (let ((done (equal (car all) (buffer-substring-no-properties base end))))
1226 (unless done (completion--replace base end (car all)))
1227 (completion--done (buffer-substring-no-properties start (point))
1228 'finished (when done "Sole completion"))))
1230 (completion--replace base end (car all))
1231 (setq end (+ base (length (car all))))
1232 (completion--done (buffer-substring-no-properties start (point)) 'sole)
1233 ;; Set cycling after modifying the buffer since the flush hook resets it.
1234 (setq completion-cycling t)
1235 (setq this-command 'completion-at-point) ;For completion-in-region.
1236 ;; If completing file names, (car all) may be a directory, so we'd now
1237 ;; have a new set of possible completions and might want to reset
1238 ;; completion-all-sorted-completions to nil, but we prefer not to,
1239 ;; so that repeated calls minibuffer-force-complete still cycle
1240 ;; through the previous possible completions.
1241 (let ((last (last all)))
1242 (setcdr last (cons (car all) (cdr last)))
1243 (completion--cache-all-sorted-completions start end (cdr all)))
1244 ;; Make sure repeated uses cycle, even though completion--done might
1245 ;; have added a space or something that moved us outside of the field.
1246 ;; (bug#12221).
1247 (let* ((table minibuffer-completion-table)
1248 (pred minibuffer-completion-predicate)
1249 (extra-prop completion-extra-properties)
1250 (cmd
1251 (lambda () "Cycle through the possible completions."
1252 (interactive)
1253 (let ((completion-extra-properties extra-prop))
1254 (completion-in-region start (point) table pred)))))
1255 (set-transient-map
1256 (let ((map (make-sparse-keymap)))
1257 (define-key map [remap completion-at-point] cmd)
1258 (define-key map (vector last-command-event) cmd)
1259 map)))))))
1261 (defvar minibuffer-confirm-exit-commands
1262 '(completion-at-point minibuffer-complete
1263 minibuffer-complete-word PC-complete PC-complete-word)
1264 "A list of commands which cause an immediately following
1265 `minibuffer-complete-and-exit' to ask for extra confirmation.")
1267 (defun minibuffer-complete-and-exit ()
1268 "Exit if the minibuffer contains a valid completion.
1269 Otherwise, try to complete the minibuffer contents. If
1270 completion leads to a valid completion, a repetition of this
1271 command will exit.
1273 If `minibuffer-completion-confirm' is `confirm', do not try to
1274 complete; instead, ask for confirmation and accept any input if
1275 confirmed.
1276 If `minibuffer-completion-confirm' is `confirm-after-completion',
1277 do not try to complete; instead, ask for confirmation if the
1278 preceding minibuffer command was a member of
1279 `minibuffer-confirm-exit-commands', and accept the input
1280 otherwise."
1281 (interactive)
1282 (completion-complete-and-exit (minibuffer-prompt-end) (point-max)
1283 #'exit-minibuffer))
1285 (defun completion-complete-and-exit (beg end exit-function)
1286 (completion--complete-and-exit
1287 beg end exit-function
1288 (lambda ()
1289 (pcase (condition-case nil
1290 (completion--do-completion beg end
1291 nil 'expect-exact)
1292 (error 1))
1293 ((or #b001 #b011) (funcall exit-function))
1294 (#b111 (if (not minibuffer-completion-confirm)
1295 (funcall exit-function)
1296 (minibuffer-message "Confirm")
1297 nil))
1298 (_ nil)))))
1300 (defun completion--complete-and-exit (beg end
1301 exit-function completion-function)
1302 "Exit from `require-match' minibuffer.
1303 COMPLETION-FUNCTION is called if the current buffer's content does not
1304 appear to be a match."
1305 (cond
1306 ;; Allow user to specify null string
1307 ((= beg end) (funcall exit-function))
1308 ((test-completion (buffer-substring beg end)
1309 minibuffer-completion-table
1310 minibuffer-completion-predicate)
1311 ;; FIXME: completion-ignore-case has various slightly
1312 ;; incompatible meanings. E.g. it can reflect whether the user
1313 ;; wants completion to pay attention to case, or whether the
1314 ;; string will be used in a context where case is significant.
1315 ;; E.g. usually try-completion should obey the first, whereas
1316 ;; test-completion should obey the second.
1317 (when completion-ignore-case
1318 ;; Fixup case of the field, if necessary.
1319 (let* ((string (buffer-substring beg end))
1320 (compl (try-completion
1321 string
1322 minibuffer-completion-table
1323 minibuffer-completion-predicate)))
1324 (when (and (stringp compl) (not (equal string compl))
1325 ;; If it weren't for this piece of paranoia, I'd replace
1326 ;; the whole thing with a call to do-completion.
1327 ;; This is important, e.g. when the current minibuffer's
1328 ;; content is a directory which only contains a single
1329 ;; file, so `try-completion' actually completes to
1330 ;; that file.
1331 (= (length string) (length compl)))
1332 (completion--replace beg end compl))))
1333 (funcall exit-function))
1335 ((memq minibuffer-completion-confirm '(confirm confirm-after-completion))
1336 ;; The user is permitted to exit with an input that's rejected
1337 ;; by test-completion, after confirming her choice.
1338 (if (or (eq last-command this-command)
1339 ;; For `confirm-after-completion' we only ask for confirmation
1340 ;; if trying to exit immediately after typing TAB (this
1341 ;; catches most minibuffer typos).
1342 (and (eq minibuffer-completion-confirm 'confirm-after-completion)
1343 (not (memq last-command minibuffer-confirm-exit-commands))))
1344 (funcall exit-function)
1345 (minibuffer-message "Confirm")
1346 nil))
1349 ;; Call do-completion, but ignore errors.
1350 (funcall completion-function))))
1352 (defun completion--try-word-completion (string table predicate point md)
1353 (let ((comp (completion-try-completion string table predicate point md)))
1354 (if (not (consp comp))
1355 comp
1357 ;; If completion finds next char not unique,
1358 ;; consider adding a space or a hyphen.
1359 (when (= (length string) (length (car comp)))
1360 ;; Mark the added char with the `completion-word' property, so it
1361 ;; can be handled specially by completion styles such as
1362 ;; partial-completion.
1363 ;; We used to remove `partial-completion' from completion-styles
1364 ;; instead, but it was too blunt, leading to situations where SPC
1365 ;; was the only insertable char at point but minibuffer-complete-word
1366 ;; refused inserting it.
1367 (let* ((exts (mapcar (lambda (str) (propertize str 'completion-try-word t))
1368 '(" " "-")))
1369 (before (substring string 0 point))
1370 (after (substring string point))
1371 (comps
1372 (delete nil
1373 (mapcar (lambda (ext)
1374 (completion-try-completion
1375 (concat before ext after)
1376 table predicate (1+ point) md))
1377 exts))))
1378 (when (and (null (cdr comps)) (consp (car comps)))
1379 (setq comp (car comps)))))
1381 ;; Completing a single word is actually more difficult than completing
1382 ;; as much as possible, because we first have to find the "current
1383 ;; position" in `completion' in order to find the end of the word
1384 ;; we're completing. Normally, `string' is a prefix of `completion',
1385 ;; which makes it trivial to find the position, but with fancier
1386 ;; completion (plus env-var expansion, ...) `completion' might not
1387 ;; look anything like `string' at all.
1388 (let* ((comppoint (cdr comp))
1389 (completion (car comp))
1390 (before (substring string 0 point))
1391 (combined (concat before "\n" completion)))
1392 ;; Find in completion the longest text that was right before point.
1393 (when (string-match "\\(.+\\)\n.*?\\1" combined)
1394 (let* ((prefix (match-string 1 before))
1395 ;; We used non-greedy match to make `rem' as long as possible.
1396 (rem (substring combined (match-end 0)))
1397 ;; Find in the remainder of completion the longest text
1398 ;; that was right after point.
1399 (after (substring string point))
1400 (suffix (if (string-match "\\`\\(.+\\).*\n.*\\1"
1401 (concat after "\n" rem))
1402 (match-string 1 after))))
1403 ;; The general idea is to try and guess what text was inserted
1404 ;; at point by the completion. Problem is: if we guess wrong,
1405 ;; we may end up treating as "added by completion" text that was
1406 ;; actually painfully typed by the user. So if we then cut
1407 ;; after the first word, we may throw away things the
1408 ;; user wrote. So let's try to be as conservative as possible:
1409 ;; only cut after the first word, if we're reasonably sure that
1410 ;; our guess is correct.
1411 ;; Note: a quick survey on emacs-devel seemed to indicate that
1412 ;; nobody actually cares about the "word-at-a-time" feature of
1413 ;; minibuffer-complete-word, whose real raison-d'être is that it
1414 ;; tries to add "-" or " ". One more reason to only cut after
1415 ;; the first word, if we're really sure we're right.
1416 (when (and (or suffix (zerop (length after)))
1417 (string-match (concat
1418 ;; Make submatch 1 as small as possible
1419 ;; to reduce the risk of cutting
1420 ;; valuable text.
1421 ".*" (regexp-quote prefix) "\\(.*?\\)"
1422 (if suffix (regexp-quote suffix) "\\'"))
1423 completion)
1424 ;; The new point in `completion' should also be just
1425 ;; before the suffix, otherwise something more complex
1426 ;; is going on, and we're not sure where we are.
1427 (eq (match-end 1) comppoint)
1428 ;; (match-beginning 1)..comppoint is now the stretch
1429 ;; of text in `completion' that was completed at point.
1430 (string-match "\\W" completion (match-beginning 1))
1431 ;; Is there really something to cut?
1432 (> comppoint (match-end 0)))
1433 ;; Cut after the first word.
1434 (let ((cutpos (match-end 0)))
1435 (setq completion (concat (substring completion 0 cutpos)
1436 (substring completion comppoint)))
1437 (setq comppoint cutpos)))))
1439 (cons completion comppoint)))))
1442 (defun minibuffer-complete-word ()
1443 "Complete the minibuffer contents at most a single word.
1444 After one word is completed as much as possible, a space or hyphen
1445 is added, provided that matches some possible completion.
1446 Return nil if there is no valid completion, else t."
1447 (interactive)
1448 (completion-in-region--single-word
1449 (minibuffer-prompt-end) (point-max)
1450 minibuffer-completion-table minibuffer-completion-predicate))
1452 (defun completion-in-region--single-word (beg end collection
1453 &optional predicate)
1454 (let ((minibuffer-completion-table collection)
1455 (minibuffer-completion-predicate predicate))
1456 (pcase (completion--do-completion beg end
1457 #'completion--try-word-completion)
1458 (#b000 nil)
1459 (_ t))))
1461 (defface completions-annotations '((t :inherit italic))
1462 "Face to use for annotations in the *Completions* buffer.")
1464 (defcustom completions-format 'horizontal
1465 "Define the appearance and sorting of completions.
1466 If the value is `vertical', display completions sorted vertically
1467 in columns in the *Completions* buffer.
1468 If the value is `horizontal', display completions sorted
1469 horizontally in alphabetical order, rather than down the screen."
1470 :type '(choice (const horizontal) (const vertical))
1471 :version "23.2")
1473 (defun completion--insert-strings (strings)
1474 "Insert a list of STRINGS into the current buffer.
1475 Uses columns to keep the listing readable but compact.
1476 It also eliminates runs of equal strings."
1477 (when (consp strings)
1478 (let* ((length (apply 'max
1479 (mapcar (lambda (s)
1480 (if (consp s)
1481 (+ (string-width (car s))
1482 (string-width (cadr s)))
1483 (string-width s)))
1484 strings)))
1485 (window (get-buffer-window (current-buffer) 0))
1486 (wwidth (if window (1- (window-width window)) 79))
1487 (columns (min
1488 ;; At least 2 columns; at least 2 spaces between columns.
1489 (max 2 (/ wwidth (+ 2 length)))
1490 ;; Don't allocate more columns than we can fill.
1491 ;; Windows can't show less than 3 lines anyway.
1492 (max 1 (/ (length strings) 2))))
1493 (colwidth (/ wwidth columns))
1494 (column 0)
1495 (rows (/ (length strings) columns))
1496 (row 0)
1497 (first t)
1498 (laststring nil))
1499 ;; The insertion should be "sensible" no matter what choices were made
1500 ;; for the parameters above.
1501 (dolist (str strings)
1502 (unless (equal laststring str) ; Remove (consecutive) duplicates.
1503 (setq laststring str)
1504 ;; FIXME: `string-width' doesn't pay attention to
1505 ;; `display' properties.
1506 (let ((length (if (consp str)
1507 (+ (string-width (car str))
1508 (string-width (cadr str)))
1509 (string-width str))))
1510 (cond
1511 ((eq completions-format 'vertical)
1512 ;; Vertical format
1513 (when (> row rows)
1514 (forward-line (- -1 rows))
1515 (setq row 0 column (+ column colwidth)))
1516 (when (> column 0)
1517 (end-of-line)
1518 (while (> (current-column) column)
1519 (if (eobp)
1520 (insert "\n")
1521 (forward-line 1)
1522 (end-of-line)))
1523 (insert " \t")
1524 (set-text-properties (1- (point)) (point)
1525 `(display (space :align-to ,column)))))
1527 ;; Horizontal format
1528 (unless first
1529 (if (< wwidth (+ (max colwidth length) column))
1530 ;; No space for `str' at point, move to next line.
1531 (progn (insert "\n") (setq column 0))
1532 (insert " \t")
1533 ;; Leave the space unpropertized so that in the case we're
1534 ;; already past the goal column, there is still
1535 ;; a space displayed.
1536 (set-text-properties (1- (point)) (point)
1537 ;; We can't just set tab-width, because
1538 ;; completion-setup-function will kill
1539 ;; all local variables :-(
1540 `(display (space :align-to ,column)))
1541 nil))))
1542 (setq first nil)
1543 (if (not (consp str))
1544 (put-text-property (point) (progn (insert str) (point))
1545 'mouse-face 'highlight)
1546 (put-text-property (point) (progn (insert (car str)) (point))
1547 'mouse-face 'highlight)
1548 (let ((beg (point))
1549 (end (progn (insert (cadr str)) (point))))
1550 (put-text-property beg end 'mouse-face nil)
1551 (font-lock-prepend-text-property beg end 'face
1552 'completions-annotations)))
1553 (cond
1554 ((eq completions-format 'vertical)
1555 ;; Vertical format
1556 (if (> column 0)
1557 (forward-line)
1558 (insert "\n"))
1559 (setq row (1+ row)))
1561 ;; Horizontal format
1562 ;; Next column to align to.
1563 (setq column (+ column
1564 ;; Round up to a whole number of columns.
1565 (* colwidth (ceiling length colwidth))))))))))))
1567 (defvar completion-common-substring nil)
1568 (make-obsolete-variable 'completion-common-substring nil "23.1")
1570 (defvar completion-setup-hook nil
1571 "Normal hook run at the end of setting up a completion list buffer.
1572 When this hook is run, the current buffer is the one in which the
1573 command to display the completion list buffer was run.
1574 The completion list buffer is available as the value of `standard-output'.
1575 See also `display-completion-list'.")
1577 (defface completions-first-difference
1578 '((t (:inherit bold)))
1579 "Face for the first uncommon character in completions.
1580 See also the face `completions-common-part'.")
1582 (defface completions-common-part '((t nil))
1583 "Face for the common prefix substring in completions.
1584 The idea of this face is that you can use it to make the common parts
1585 less visible than normal, so that the differing parts are emphasized
1586 by contrast.
1587 See also the face `completions-first-difference'.")
1589 (defun completion-hilit-commonality (completions prefix-len &optional base-size)
1590 "Apply font-lock highlighting to a list of completions, COMPLETIONS.
1591 PREFIX-LEN is an integer. BASE-SIZE is an integer or nil (meaning zero).
1593 This adds the face `completions-common-part' to the first
1594 \(PREFIX-LEN - BASE-SIZE) characters of each completion, and the face
1595 `completions-first-difference' to the first character after that.
1597 It returns a list with font-lock properties applied to each element,
1598 and with BASE-SIZE appended as the last element."
1599 (when completions
1600 (let ((com-str-len (- prefix-len (or base-size 0))))
1601 (nconc
1602 (mapcar
1603 (lambda (elem)
1604 (let ((str
1605 ;; Don't modify the string itself, but a copy, since the
1606 ;; the string may be read-only or used for other purposes.
1607 ;; Furthermore, since `completions' may come from
1608 ;; display-completion-list, `elem' may be a list.
1609 (if (consp elem)
1610 (car (setq elem (cons (copy-sequence (car elem))
1611 (cdr elem))))
1612 (setq elem (copy-sequence elem)))))
1613 (font-lock-prepend-text-property
1615 ;; If completion-boundaries returns incorrect
1616 ;; values, all-completions may return strings
1617 ;; that don't contain the prefix.
1618 (min com-str-len (length str))
1619 'face 'completions-common-part str)
1620 (if (> (length str) com-str-len)
1621 (font-lock-prepend-text-property com-str-len (1+ com-str-len)
1622 'face
1623 'completions-first-difference
1624 str)))
1625 elem)
1626 completions)
1627 base-size))))
1629 (defun display-completion-list (completions &optional common-substring)
1630 "Display the list of completions, COMPLETIONS, using `standard-output'.
1631 Each element may be just a symbol or string
1632 or may be a list of two strings to be printed as if concatenated.
1633 If it is a list of two strings, the first is the actual completion
1634 alternative, the second serves as annotation.
1635 `standard-output' must be a buffer.
1636 The actual completion alternatives, as inserted, are given `mouse-face'
1637 properties of `highlight'.
1638 At the end, this runs the normal hook `completion-setup-hook'.
1639 It can find the completion buffer in `standard-output'."
1640 (declare (advertised-calling-convention (completions) "24.4"))
1641 (if common-substring
1642 (setq completions (completion-hilit-commonality
1643 completions (length common-substring)
1644 ;; We don't know the base-size.
1645 nil)))
1646 (if (not (bufferp standard-output))
1647 ;; This *never* (ever) happens, so there's no point trying to be clever.
1648 (with-temp-buffer
1649 (let ((standard-output (current-buffer))
1650 (completion-setup-hook nil))
1651 (display-completion-list completions common-substring))
1652 (princ (buffer-string)))
1654 (with-current-buffer standard-output
1655 (goto-char (point-max))
1656 (if (null completions)
1657 (insert "There are no possible completions of what you have typed.")
1658 (insert "Possible completions are:\n")
1659 (completion--insert-strings completions))))
1661 ;; The hilit used to be applied via completion-setup-hook, so there
1662 ;; may still be some code that uses completion-common-substring.
1663 (with-no-warnings
1664 (let ((completion-common-substring common-substring))
1665 (run-hooks 'completion-setup-hook)))
1666 nil)
1668 (defvar completion-extra-properties nil
1669 "Property list of extra properties of the current completion job.
1670 These include:
1672 `:annotation-function': Function to annotate the completions buffer.
1673 The function must accept one argument, a completion string,
1674 and return either nil or a string which is to be displayed
1675 next to the completion (but which is not part of the
1676 completion). The function can access the completion data via
1677 `minibuffer-completion-table' and related variables.
1679 `:exit-function': Function to run after completion is performed.
1681 The function must accept two arguments, STRING and STATUS.
1682 STRING is the text to which the field was completed, and
1683 STATUS indicates what kind of operation happened:
1684 `finished' - text is now complete
1685 `sole' - text cannot be further completed but
1686 completion is not finished
1687 `exact' - text is a valid completion but may be further
1688 completed.")
1690 (defvar completion-annotate-function
1692 ;; Note: there's a lot of scope as for when to add annotations and
1693 ;; what annotations to add. E.g. completing-help.el allowed adding
1694 ;; the first line of docstrings to M-x completion. But there's
1695 ;; a tension, since such annotations, while useful at times, can
1696 ;; actually drown the useful information.
1697 ;; So completion-annotate-function should be used parsimoniously, or
1698 ;; else only used upon a user's request (e.g. we could add a command
1699 ;; to completion-list-mode to add annotations to the current
1700 ;; completions).
1701 "Function to add annotations in the *Completions* buffer.
1702 The function takes a completion and should either return nil, or a string that
1703 will be displayed next to the completion. The function can access the
1704 completion table and predicates via `minibuffer-completion-table' and related
1705 variables.")
1706 (make-obsolete-variable 'completion-annotate-function
1707 'completion-extra-properties "24.1")
1709 (defun completion--done (string &optional finished message)
1710 (let* ((exit-fun (plist-get completion-extra-properties :exit-function))
1711 (pre-msg (and exit-fun (current-message))))
1712 (cl-assert (memq finished '(exact sole finished unknown)))
1713 (when exit-fun
1714 (when (eq finished 'unknown)
1715 (setq finished
1716 (if (eq (try-completion string
1717 minibuffer-completion-table
1718 minibuffer-completion-predicate)
1720 'finished 'exact)))
1721 (funcall exit-fun string finished))
1722 (when (and message
1723 ;; Don't output any message if the exit-fun already did so.
1724 (equal pre-msg (and exit-fun (current-message))))
1725 (completion--message message))))
1727 (defun minibuffer-completion-help (&optional start end)
1728 "Display a list of possible completions of the current minibuffer contents."
1729 (interactive)
1730 (message "Making completion list...")
1731 (let* ((start (or start (minibuffer-prompt-end)))
1732 (end (or end (point-max)))
1733 (string (buffer-substring start end))
1734 (md (completion--field-metadata start))
1735 (completions (completion-all-completions
1736 string
1737 minibuffer-completion-table
1738 minibuffer-completion-predicate
1739 (- (point) start)
1740 md)))
1741 (message nil)
1742 (if (or (null completions)
1743 (and (not (consp (cdr completions)))
1744 (equal (car completions) string)))
1745 (progn
1746 ;; If there are no completions, or if the current input is already
1747 ;; the sole completion, then hide (previous&stale) completions.
1748 (minibuffer-hide-completions)
1749 (ding)
1750 (minibuffer-message
1751 (if completions "Sole completion" "No completions")))
1753 (let* ((last (last completions))
1754 (base-size (cdr last))
1755 (prefix (unless (zerop base-size) (substring string 0 base-size)))
1756 (all-md (completion--metadata (buffer-substring-no-properties
1757 start (point))
1758 base-size md
1759 minibuffer-completion-table
1760 minibuffer-completion-predicate))
1761 (afun (or (completion-metadata-get all-md 'annotation-function)
1762 (plist-get completion-extra-properties
1763 :annotation-function)
1764 completion-annotate-function))
1765 ;; If the *Completions* buffer is shown in a new
1766 ;; window, mark it as softly-dedicated, so bury-buffer in
1767 ;; minibuffer-hide-completions will know whether to
1768 ;; delete the window or not.
1769 (display-buffer-mark-dedicated 'soft))
1770 (with-output-to-temp-buffer "*Completions*"
1771 ;; Remove the base-size tail because `sort' requires a properly
1772 ;; nil-terminated list.
1773 (when last (setcdr last nil))
1774 (setq completions
1775 ;; FIXME: This function is for the output of all-completions,
1776 ;; not completion-all-completions. Often it's the same, but
1777 ;; not always.
1778 (let ((sort-fun (completion-metadata-get
1779 all-md 'display-sort-function)))
1780 (if sort-fun
1781 (funcall sort-fun completions)
1782 (sort completions 'string-lessp))))
1783 (when afun
1784 (setq completions
1785 (mapcar (lambda (s)
1786 (let ((ann (funcall afun s)))
1787 (if ann (list s ann) s)))
1788 completions)))
1790 (with-current-buffer standard-output
1791 (set (make-local-variable 'completion-base-position)
1792 (list (+ start base-size)
1793 ;; FIXME: We should pay attention to completion
1794 ;; boundaries here, but currently
1795 ;; completion-all-completions does not give us the
1796 ;; necessary information.
1797 end))
1798 (set (make-local-variable 'completion-list-insert-choice-function)
1799 (let ((ctable minibuffer-completion-table)
1800 (cpred minibuffer-completion-predicate)
1801 (cprops completion-extra-properties))
1802 (lambda (start end choice)
1803 (unless (or (zerop (length prefix))
1804 (equal prefix
1805 (buffer-substring-no-properties
1806 (max (point-min)
1807 (- start (length prefix)))
1808 start)))
1809 (message "*Completions* out of date"))
1810 ;; FIXME: Use `md' to do quoting&terminator here.
1811 (completion--replace start end choice)
1812 (let* ((minibuffer-completion-table ctable)
1813 (minibuffer-completion-predicate cpred)
1814 (completion-extra-properties cprops)
1815 (result (concat prefix choice))
1816 (bounds (completion-boundaries
1817 result ctable cpred "")))
1818 ;; If the completion introduces a new field, then
1819 ;; completion is not finished.
1820 (completion--done result
1821 (if (eq (car bounds) (length result))
1822 'exact 'finished)))))))
1824 (display-completion-list completions))))
1825 nil))
1827 (defun minibuffer-hide-completions ()
1828 "Get rid of an out-of-date *Completions* buffer."
1829 ;; FIXME: We could/should use minibuffer-scroll-window here, but it
1830 ;; can also point to the minibuffer-parent-window, so it's a bit tricky.
1831 (let ((win (get-buffer-window "*Completions*" 0)))
1832 (if win (with-selected-window win (bury-buffer)))))
1834 (defun exit-minibuffer ()
1835 "Terminate this minibuffer argument."
1836 (interactive)
1837 ;; If the command that uses this has made modifications in the minibuffer,
1838 ;; we don't want them to cause deactivation of the mark in the original
1839 ;; buffer.
1840 ;; A better solution would be to make deactivate-mark buffer-local
1841 ;; (or to turn it into a list of buffers, ...), but in the mean time,
1842 ;; this should do the trick in most cases.
1843 (setq deactivate-mark nil)
1844 (throw 'exit nil))
1846 (defun self-insert-and-exit ()
1847 "Terminate minibuffer input."
1848 (interactive)
1849 (if (characterp last-command-event)
1850 (call-interactively 'self-insert-command)
1851 (ding))
1852 (exit-minibuffer))
1854 (defvar completion-in-region-functions nil
1855 "Wrapper hook around `completion-in-region'.")
1856 (make-obsolete-variable 'completion-in-region-functions
1857 'completion-in-region-function "24.4")
1859 (defvar completion-in-region-function #'completion--in-region
1860 "Function to perform the job of `completion-in-region'.
1861 The function is called with 4 arguments: START END COLLECTION PREDICATE.
1862 The arguments and expected return value are like the ones of
1863 `completion-in-region'.")
1865 (defvar completion-in-region--data nil)
1867 (defvar completion-in-region-mode-predicate nil
1868 "Predicate to tell `completion-in-region-mode' when to exit.
1869 It is called with no argument and should return nil when
1870 `completion-in-region-mode' should exit (and hence pop down
1871 the *Completions* buffer).")
1873 (defvar completion-in-region-mode--predicate nil
1874 "Copy of the value of `completion-in-region-mode-predicate'.
1875 This holds the value `completion-in-region-mode-predicate' had when
1876 we entered `completion-in-region-mode'.")
1878 (defun completion-in-region (start end collection &optional predicate)
1879 "Complete the text between START and END using COLLECTION.
1880 Return nil if there is no valid completion, else t.
1881 Point needs to be somewhere between START and END.
1882 PREDICATE (a function called with no arguments) says when to
1883 exit."
1884 (cl-assert (<= start (point)) (<= (point) end))
1885 (funcall completion-in-region-function start end collection predicate))
1887 (defcustom read-file-name-completion-ignore-case
1888 (if (memq system-type '(ms-dos windows-nt darwin cygwin))
1889 t nil)
1890 "Non-nil means when reading a file name completion ignores case."
1891 :type 'boolean
1892 :version "22.1")
1894 (defun completion--in-region (start end collection &optional predicate)
1895 (with-wrapper-hook
1896 ;; FIXME: Maybe we should use this hook to provide a "display
1897 ;; completions" operation as well.
1898 completion-in-region-functions (start end collection predicate)
1899 (let ((minibuffer-completion-table collection)
1900 (minibuffer-completion-predicate predicate))
1901 ;; HACK: if the text we are completing is already in a field, we
1902 ;; want the completion field to take priority (e.g. Bug#6830).
1903 (when completion-in-region-mode-predicate
1904 (setq completion-in-region--data
1905 `(,(if (markerp start) start (copy-marker start))
1906 ,(copy-marker end t) ,collection ,predicate))
1907 (completion-in-region-mode 1))
1908 (completion--in-region-1 start end))))
1910 (defvar completion-in-region-mode-map
1911 (let ((map (make-sparse-keymap)))
1912 ;; FIXME: Only works if completion-in-region-mode was activated via
1913 ;; completion-at-point called directly.
1914 (define-key map "\M-?" 'completion-help-at-point)
1915 (define-key map "\t" 'completion-at-point)
1916 map)
1917 "Keymap activated during `completion-in-region'.")
1919 ;; It is difficult to know when to exit completion-in-region-mode (i.e. hide
1920 ;; the *Completions*).
1921 ;; - lisp-mode: never.
1922 ;; - comint: only do it if you hit SPC at the right time.
1923 ;; - pcomplete: pop it down on SPC or after some time-delay.
1924 ;; - semantic: use a post-command-hook check similar to this one.
1925 (defun completion-in-region--postch ()
1926 (or unread-command-events ;Don't pop down the completions in the middle of
1927 ;mouse-drag-region/mouse-set-point.
1928 (and completion-in-region--data
1929 (and (eq (marker-buffer (nth 0 completion-in-region--data))
1930 (current-buffer))
1931 (>= (point) (nth 0 completion-in-region--data))
1932 (<= (point)
1933 (save-excursion
1934 (goto-char (nth 1 completion-in-region--data))
1935 (line-end-position)))
1936 (funcall completion-in-region-mode--predicate)))
1937 (completion-in-region-mode -1)))
1939 ;; (defalias 'completion-in-region--prech 'completion-in-region--postch)
1941 (defvar completion-in-region-mode nil) ;Explicit defvar, i.s.o defcustom.
1943 (define-minor-mode completion-in-region-mode
1944 "Transient minor mode used during `completion-in-region'."
1945 :global t
1946 :group 'minibuffer
1947 ;; Prevent definition of a custom-variable since it makes no sense to
1948 ;; customize this variable.
1949 :variable completion-in-region-mode
1950 ;; (remove-hook 'pre-command-hook #'completion-in-region--prech)
1951 (remove-hook 'post-command-hook #'completion-in-region--postch)
1952 (setq minor-mode-overriding-map-alist
1953 (delq (assq 'completion-in-region-mode minor-mode-overriding-map-alist)
1954 minor-mode-overriding-map-alist))
1955 (if (null completion-in-region-mode)
1956 (progn
1957 (setq completion-in-region--data nil)
1958 (unless (equal "*Completions*" (buffer-name (window-buffer)))
1959 (minibuffer-hide-completions)))
1960 ;; (add-hook 'pre-command-hook #'completion-in-region--prech)
1961 (cl-assert completion-in-region-mode-predicate)
1962 (setq completion-in-region-mode--predicate
1963 completion-in-region-mode-predicate)
1964 (add-hook 'post-command-hook #'completion-in-region--postch)
1965 (push `(completion-in-region-mode . ,completion-in-region-mode-map)
1966 minor-mode-overriding-map-alist)))
1968 ;; Define-minor-mode added our keymap to minor-mode-map-alist, but we want it
1969 ;; on minor-mode-overriding-map-alist instead.
1970 (setq minor-mode-map-alist
1971 (delq (assq 'completion-in-region-mode minor-mode-map-alist)
1972 minor-mode-map-alist))
1974 (defvar completion-at-point-functions '(tags-completion-at-point-function)
1975 "Special hook to find the completion table for the thing at point.
1976 Each function on this hook is called in turns without any argument and should
1977 return either nil to mean that it is not applicable at point,
1978 or a function of no argument to perform completion (discouraged),
1979 or a list of the form (START END COLLECTION . PROPS) where
1980 START and END delimit the entity to complete and should include point,
1981 COLLECTION is the completion table to use to complete it, and
1982 PROPS is a property list for additional information.
1983 Currently supported properties are all the properties that can appear in
1984 `completion-extra-properties' plus:
1985 `:predicate' a predicate that completion candidates need to satisfy.
1986 `:exclusive' If `no', means that if the completion table fails to
1987 match the text at point, then instead of reporting a completion
1988 failure, the completion should try the next completion function.
1989 As is the case with most hooks, the functions are responsible to preserve
1990 things like point and current buffer.")
1992 (defvar completion--capf-misbehave-funs nil
1993 "List of functions found on `completion-at-point-functions' that misbehave.
1994 These are functions that neither return completion data nor a completion
1995 function but instead perform completion right away.")
1996 (defvar completion--capf-safe-funs nil
1997 "List of well-behaved functions found on `completion-at-point-functions'.
1998 These are functions which return proper completion data rather than
1999 a completion function or god knows what else.")
2001 (defun completion--capf-wrapper (fun which)
2002 ;; FIXME: The safe/misbehave handling assumes that a given function will
2003 ;; always return the same kind of data, but this breaks down with functions
2004 ;; like comint-completion-at-point or mh-letter-completion-at-point, which
2005 ;; could be sometimes safe and sometimes misbehaving (and sometimes neither).
2006 (if (pcase which
2007 (`all t)
2008 (`safe (member fun completion--capf-safe-funs))
2009 (`optimist (not (member fun completion--capf-misbehave-funs))))
2010 (let ((res (funcall fun)))
2011 (cond
2012 ((and (consp res) (not (functionp res)))
2013 (unless (member fun completion--capf-safe-funs)
2014 (push fun completion--capf-safe-funs))
2015 (and (eq 'no (plist-get (nthcdr 3 res) :exclusive))
2016 ;; FIXME: Here we'd need to decide whether there are
2017 ;; valid completions against the current text. But this depends
2018 ;; on the actual completion UI (e.g. with the default completion
2019 ;; it depends on completion-style) ;-(
2020 ;; We approximate this result by checking whether prefix
2021 ;; completion might work, which means that non-prefix completion
2022 ;; will not work (or not right) for completion functions that
2023 ;; are non-exclusive.
2024 (null (try-completion (buffer-substring-no-properties
2025 (car res) (point))
2026 (nth 2 res)
2027 (plist-get (nthcdr 3 res) :predicate)))
2028 (setq res nil)))
2029 ((not (or (listp res) (functionp res)))
2030 (unless (member fun completion--capf-misbehave-funs)
2031 (message
2032 "Completion function %S uses a deprecated calling convention" fun)
2033 (push fun completion--capf-misbehave-funs))))
2034 (if res (cons fun res)))))
2036 (defun completion-at-point ()
2037 "Perform completion on the text around point.
2038 The completion method is determined by `completion-at-point-functions'."
2039 (interactive)
2040 (let ((res (run-hook-wrapped 'completion-at-point-functions
2041 #'completion--capf-wrapper 'all)))
2042 (pcase res
2043 (`(,_ . ,(and (pred functionp) f)) (funcall f))
2044 (`(,hookfun . (,start ,end ,collection . ,plist))
2045 (unless (markerp start) (setq start (copy-marker start)))
2046 (let* ((completion-extra-properties plist)
2047 (completion-in-region-mode-predicate
2048 (lambda ()
2049 ;; We're still in the same completion field.
2050 (let ((newstart (car-safe (funcall hookfun))))
2051 (and newstart (= newstart start))))))
2052 (completion-in-region start end collection
2053 (plist-get plist :predicate))))
2054 ;; Maybe completion already happened and the function returned t.
2055 (_ (cdr res)))))
2057 (defun completion-help-at-point ()
2058 "Display the completions on the text around point.
2059 The completion method is determined by `completion-at-point-functions'."
2060 (interactive)
2061 (let ((res (run-hook-wrapped 'completion-at-point-functions
2062 ;; Ignore misbehaving functions.
2063 #'completion--capf-wrapper 'optimist)))
2064 (pcase res
2065 (`(,_ . ,(and (pred functionp) f))
2066 (message "Don't know how to show completions for %S" f))
2067 (`(,hookfun . (,start ,end ,collection . ,plist))
2068 (unless (markerp start) (setq start (copy-marker start)))
2069 (let* ((minibuffer-completion-table collection)
2070 (minibuffer-completion-predicate (plist-get plist :predicate))
2071 (completion-extra-properties plist)
2072 (completion-in-region-mode-predicate
2073 (lambda ()
2074 ;; We're still in the same completion field.
2075 (let ((newstart (car-safe (funcall hookfun))))
2076 (and newstart (= newstart start))))))
2077 ;; FIXME: We should somehow (ab)use completion-in-region-function or
2078 ;; introduce a corresponding hook (plus another for word-completion,
2079 ;; and another for force-completion, maybe?).
2080 (setq completion-in-region--data
2081 `(,start ,(copy-marker end t) ,collection
2082 ,(plist-get plist :predicate)))
2083 (completion-in-region-mode 1)
2084 (minibuffer-completion-help start end)))
2085 (`(,hookfun . ,_)
2086 ;; The hook function already performed completion :-(
2087 ;; Not much we can do at this point.
2088 (message "%s already performed completion!" hookfun)
2089 nil)
2090 (_ (message "Nothing to complete at point")))))
2092 ;;; Key bindings.
2094 (let ((map minibuffer-local-map))
2095 (define-key map "\C-g" 'abort-recursive-edit)
2096 (define-key map "\r" 'exit-minibuffer)
2097 (define-key map "\n" 'exit-minibuffer))
2099 (defvar minibuffer-local-completion-map
2100 (let ((map (make-sparse-keymap)))
2101 (set-keymap-parent map minibuffer-local-map)
2102 (define-key map "\t" 'minibuffer-complete)
2103 ;; M-TAB is already abused for many other purposes, so we should find
2104 ;; another binding for it.
2105 ;; (define-key map "\e\t" 'minibuffer-force-complete)
2106 (define-key map " " 'minibuffer-complete-word)
2107 (define-key map "?" 'minibuffer-completion-help)
2108 map)
2109 "Local keymap for minibuffer input with completion.")
2111 (defvar minibuffer-local-must-match-map
2112 (let ((map (make-sparse-keymap)))
2113 (set-keymap-parent map minibuffer-local-completion-map)
2114 (define-key map "\r" 'minibuffer-complete-and-exit)
2115 (define-key map "\n" 'minibuffer-complete-and-exit)
2116 map)
2117 "Local keymap for minibuffer input with completion, for exact match.")
2119 (defvar minibuffer-local-filename-completion-map
2120 (let ((map (make-sparse-keymap)))
2121 (define-key map " " nil)
2122 map)
2123 "Local keymap for minibuffer input with completion for filenames.
2124 Gets combined either with `minibuffer-local-completion-map' or
2125 with `minibuffer-local-must-match-map'.")
2127 (define-obsolete-variable-alias 'minibuffer-local-must-match-filename-map
2128 'minibuffer-local-filename-must-match-map "23.1")
2129 (defvar minibuffer-local-filename-must-match-map (make-sparse-keymap))
2130 (make-obsolete-variable 'minibuffer-local-filename-must-match-map nil "24.1")
2132 (let ((map minibuffer-local-ns-map))
2133 (define-key map " " 'exit-minibuffer)
2134 (define-key map "\t" 'exit-minibuffer)
2135 (define-key map "?" 'self-insert-and-exit))
2137 (defvar minibuffer-inactive-mode-map
2138 (let ((map (make-keymap)))
2139 (suppress-keymap map)
2140 (define-key map "e" 'find-file-other-frame)
2141 (define-key map "f" 'find-file-other-frame)
2142 (define-key map "b" 'switch-to-buffer-other-frame)
2143 (define-key map "i" 'info)
2144 (define-key map "m" 'mail)
2145 (define-key map "n" 'make-frame)
2146 (define-key map [mouse-1] 'view-echo-area-messages)
2147 ;; So the global down-mouse-1 binding doesn't clutter the execution of the
2148 ;; above mouse-1 binding.
2149 (define-key map [down-mouse-1] #'ignore)
2150 map)
2151 "Keymap for use in the minibuffer when it is not active.
2152 The non-mouse bindings in this keymap can only be used in minibuffer-only
2153 frames, since the minibuffer can normally not be selected when it is
2154 not active.")
2156 (define-derived-mode minibuffer-inactive-mode nil "InactiveMinibuffer"
2157 :abbrev-table nil ;abbrev.el is not loaded yet during dump.
2158 ;; Note: this major mode is called from minibuf.c.
2159 "Major mode to use in the minibuffer when it is not active.
2160 This is only used when the minibuffer area has no active minibuffer.")
2162 ;;; Completion tables.
2164 (defun minibuffer--double-dollars (str)
2165 ;; Reuse the actual "$" from the string to preserve any text-property it
2166 ;; might have, such as `face'.
2167 (replace-regexp-in-string "\\$" (lambda (dollar) (concat dollar dollar))
2168 str))
2170 (defun completion--make-envvar-table ()
2171 (mapcar (lambda (enventry)
2172 (substring enventry 0 (string-match-p "=" enventry)))
2173 process-environment))
2175 (defconst completion--embedded-envvar-re
2176 ;; We can't reuse env--substitute-vars-regexp because we need to match only
2177 ;; potentially-unfinished envvars at end of string.
2178 (concat "\\(?:^\\|[^$]\\(?:\\$\\$\\)*\\)"
2179 "$\\([[:alnum:]_]*\\|{\\([^}]*\\)\\)\\'"))
2181 (defun completion--embedded-envvar-table (string _pred action)
2182 "Completion table for envvars embedded in a string.
2183 The envvar syntax (and escaping) rules followed by this table are the
2184 same as `substitute-in-file-name'."
2185 ;; We ignore `pred', because the predicates passed to us via
2186 ;; read-file-name-internal are not 100% correct and fail here:
2187 ;; e.g. we get predicates like file-directory-p there, whereas the filename
2188 ;; completed needs to be passed through substitute-in-file-name before it
2189 ;; can be passed to file-directory-p.
2190 (when (string-match completion--embedded-envvar-re string)
2191 (let* ((beg (or (match-beginning 2) (match-beginning 1)))
2192 (table (completion--make-envvar-table))
2193 (prefix (substring string 0 beg)))
2194 (cond
2195 ((eq action 'lambda)
2196 ;; This table is expected to be used in conjunction with some
2197 ;; other table that provides the "main" completion. Let the
2198 ;; other table handle the test-completion case.
2199 nil)
2200 ((or (eq (car-safe action) 'boundaries) (eq action 'metadata))
2201 ;; Only return boundaries/metadata if there's something to complete,
2202 ;; since otherwise when we're used in
2203 ;; completion-table-in-turn, we could return boundaries and
2204 ;; let some subsequent table return a list of completions.
2205 ;; FIXME: Maybe it should rather be fixed in
2206 ;; completion-table-in-turn instead, but it's difficult to
2207 ;; do it efficiently there.
2208 (when (try-completion (substring string beg) table nil)
2209 ;; Compute the boundaries of the subfield to which this
2210 ;; completion applies.
2211 (if (eq action 'metadata)
2212 '(metadata (category . environment-variable))
2213 (let ((suffix (cdr action)))
2214 `(boundaries
2215 ,(or (match-beginning 2) (match-beginning 1))
2216 . ,(when (string-match "[^[:alnum:]_]" suffix)
2217 (match-beginning 0)))))))
2219 (if (eq (aref string (1- beg)) ?{)
2220 (setq table (apply-partially 'completion-table-with-terminator
2221 "}" table)))
2222 ;; Even if file-name completion is case-insensitive, we want
2223 ;; envvar completion to be case-sensitive.
2224 (let ((completion-ignore-case nil))
2225 (completion-table-with-context
2226 prefix table (substring string beg) nil action)))))))
2228 (defun completion-file-name-table (string pred action)
2229 "Completion table for file names."
2230 (condition-case nil
2231 (cond
2232 ((eq action 'metadata) '(metadata (category . file)))
2233 ((string-match-p "\\`~[^/\\]*\\'" string)
2234 (completion-table-with-context "~"
2235 (mapcar (lambda (u) (concat u "/"))
2236 (system-users))
2237 (substring string 1)
2238 pred action))
2239 ((eq (car-safe action) 'boundaries)
2240 (let ((start (length (file-name-directory string)))
2241 (end (string-match-p "/" (cdr action))))
2242 `(boundaries
2243 ;; if `string' is "C:" in w32, (file-name-directory string)
2244 ;; returns "C:/", so `start' is 3 rather than 2.
2245 ;; Not quite sure what is The Right Fix, but clipping it
2246 ;; back to 2 will work for this particular case. We'll
2247 ;; see if we can come up with a better fix when we bump
2248 ;; into more such problematic cases.
2249 ,(min start (length string)) . ,end)))
2251 ((eq action 'lambda)
2252 (if (zerop (length string))
2253 nil ;Not sure why it's here, but it probably doesn't harm.
2254 (funcall (or pred 'file-exists-p) string)))
2257 (let* ((name (file-name-nondirectory string))
2258 (specdir (file-name-directory string))
2259 (realdir (or specdir default-directory)))
2261 (cond
2262 ((null action)
2263 (let ((comp (file-name-completion name realdir pred)))
2264 (if (stringp comp)
2265 (concat specdir comp)
2266 comp)))
2268 ((eq action t)
2269 (let ((all (file-name-all-completions name realdir)))
2271 ;; Check the predicate, if necessary.
2272 (unless (memq pred '(nil file-exists-p))
2273 (let ((comp ())
2274 (pred
2275 (if (eq pred 'file-directory-p)
2276 ;; Brute-force speed up for directory checking:
2277 ;; Discard strings which don't end in a slash.
2278 (lambda (s)
2279 (let ((len (length s)))
2280 (and (> len 0) (eq (aref s (1- len)) ?/))))
2281 ;; Must do it the hard (and slow) way.
2282 pred)))
2283 (let ((default-directory (expand-file-name realdir)))
2284 (dolist (tem all)
2285 (if (funcall pred tem) (push tem comp))))
2286 (setq all (nreverse comp))))
2288 all))))))
2289 (file-error nil))) ;PCM often calls with invalid directories.
2291 (defvar read-file-name-predicate nil
2292 "Current predicate used by `read-file-name-internal'.")
2293 (make-obsolete-variable 'read-file-name-predicate
2294 "use the regular PRED argument" "23.2")
2296 (defun completion--sifn-requote (upos qstr)
2297 ;; We're looking for `qpos' such that:
2298 ;; (equal (substring (substitute-in-file-name qstr) 0 upos)
2299 ;; (substitute-in-file-name (substring qstr 0 qpos)))
2300 ;; Big problem here: we have to reverse engineer substitute-in-file-name to
2301 ;; find the position corresponding to UPOS in QSTR, but
2302 ;; substitute-in-file-name can do anything, depending on file-name-handlers.
2303 ;; substitute-in-file-name does the following kind of things:
2304 ;; - expand env-var references.
2305 ;; - turn backslashes into slashes.
2306 ;; - truncate some prefix of the input.
2307 ;; - rewrite some prefix.
2308 ;; Some of these operations are written in external libraries and we'd rather
2309 ;; not hard code any assumptions here about what they actually do. IOW, we
2310 ;; want to treat substitute-in-file-name as a black box, as much as possible.
2311 ;; Kind of like in rfn-eshadow-update-overlay, only worse.
2312 ;; Example of things we need to handle:
2313 ;; - Tramp (substitute-in-file-name "/foo:~/bar//baz") => "/scpc:foo:/baz".
2314 ;; - Cygwin (substitute-in-file-name "C:\bin") => "/usr/bin"
2315 ;; (substitute-in-file-name "C:\") => "/"
2316 ;; (substitute-in-file-name "C:\bi") => "/bi"
2317 (let* ((ustr (substitute-in-file-name qstr))
2318 (uprefix (substring ustr 0 upos))
2319 qprefix)
2320 ;; Main assumption: nothing after qpos should affect the text before upos,
2321 ;; so we can work our way backward from the end of qstr, one character
2322 ;; at a time.
2323 ;; Second assumptions: If qpos is far from the end this can be a bit slow,
2324 ;; so we speed it up by doing a first loop that skips a word at a time.
2325 ;; This word-sized loop is careful not to cut in the middle of env-vars.
2326 (while (let ((boundary (string-match "\\(\\$+{?\\)?\\w+\\W*\\'" qstr)))
2327 (and boundary
2328 (progn
2329 (setq qprefix (substring qstr 0 boundary))
2330 (string-prefix-p uprefix
2331 (substitute-in-file-name qprefix)))))
2332 (setq qstr qprefix))
2333 (let ((qpos (length qstr)))
2334 (while (and (> qpos 0)
2335 (string-prefix-p uprefix
2336 (substitute-in-file-name
2337 (substring qstr 0 (1- qpos)))))
2338 (setq qpos (1- qpos)))
2339 (cons qpos #'minibuffer--double-dollars))))
2341 (defalias 'completion--file-name-table
2342 (completion-table-with-quoting #'completion-file-name-table
2343 #'substitute-in-file-name
2344 #'completion--sifn-requote)
2345 "Internal subroutine for `read-file-name'. Do not call this.
2346 This is a completion table for file names, like `completion-file-name-table'
2347 except that it passes the file name through `substitute-in-file-name'.")
2349 (defalias 'read-file-name-internal
2350 (completion-table-in-turn #'completion--embedded-envvar-table
2351 #'completion--file-name-table)
2352 "Internal subroutine for `read-file-name'. Do not call this.")
2354 (defvar read-file-name-function 'read-file-name-default
2355 "The function called by `read-file-name' to do its work.
2356 It should accept the same arguments as `read-file-name'.")
2358 (defcustom insert-default-directory t
2359 "Non-nil means when reading a filename start with default dir in minibuffer.
2361 When the initial minibuffer contents show a name of a file or a directory,
2362 typing RETURN without editing the initial contents is equivalent to typing
2363 the default file name.
2365 If this variable is non-nil, the minibuffer contents are always
2366 initially non-empty, and typing RETURN without editing will fetch the
2367 default name, if one is provided. Note however that this default name
2368 is not necessarily the same as initial contents inserted in the minibuffer,
2369 if the initial contents is just the default directory.
2371 If this variable is nil, the minibuffer often starts out empty. In
2372 that case you may have to explicitly fetch the next history element to
2373 request the default name; typing RETURN without editing will leave
2374 the minibuffer empty.
2376 For some commands, exiting with an empty minibuffer has a special meaning,
2377 such as making the current buffer visit no file in the case of
2378 `set-visited-file-name'."
2379 :type 'boolean)
2381 ;; Not always defined, but only called if next-read-file-uses-dialog-p says so.
2382 (declare-function x-file-dialog "xfns.c"
2383 (prompt dir &optional default-filename mustmatch only-dir-p))
2385 (defun read-file-name--defaults (&optional dir initial)
2386 (let ((default
2387 (cond
2388 ;; With non-nil `initial', use `dir' as the first default.
2389 ;; Essentially, this mean reversing the normal order of the
2390 ;; current directory name and the current file name, i.e.
2391 ;; 1. with normal file reading:
2392 ;; 1.1. initial input is the current directory
2393 ;; 1.2. the first default is the current file name
2394 ;; 2. with non-nil `initial' (e.g. for `find-alternate-file'):
2395 ;; 2.2. initial input is the current file name
2396 ;; 2.1. the first default is the current directory
2397 (initial (abbreviate-file-name dir))
2398 ;; In file buffers, try to get the current file name
2399 (buffer-file-name
2400 (abbreviate-file-name buffer-file-name))))
2401 (file-name-at-point
2402 (run-hook-with-args-until-success 'file-name-at-point-functions)))
2403 (when file-name-at-point
2404 (setq default (delete-dups
2405 (delete "" (delq nil (list file-name-at-point default))))))
2406 ;; Append new defaults to the end of existing `minibuffer-default'.
2407 (append
2408 (if (listp minibuffer-default) minibuffer-default (list minibuffer-default))
2409 (if (listp default) default (list default)))))
2411 (defun read-file-name (prompt &optional dir default-filename mustmatch initial predicate)
2412 "Read file name, prompting with PROMPT and completing in directory DIR.
2413 The return value is not expanded---you must call `expand-file-name' yourself.
2415 DIR is the directory to use for completing relative file names.
2416 It should be an absolute directory name, or nil (which means the
2417 current buffer's value of `default-directory').
2419 DEFAULT-FILENAME specifies the default file name to return if the
2420 user exits the minibuffer with the same non-empty string inserted
2421 by this function. If DEFAULT-FILENAME is a string, that serves
2422 as the default. If DEFAULT-FILENAME is a list of strings, the
2423 first string is the default. If DEFAULT-FILENAME is omitted or
2424 nil, then if INITIAL is non-nil, the default is DIR combined with
2425 INITIAL; otherwise, if the current buffer is visiting a file,
2426 that file serves as the default; otherwise, the default is simply
2427 the string inserted into the minibuffer.
2429 If the user exits with an empty minibuffer, return an empty
2430 string. (This happens only if the user erases the pre-inserted
2431 contents, or if `insert-default-directory' is nil.)
2433 Fourth arg MUSTMATCH can take the following values:
2434 - nil means that the user can exit with any input.
2435 - t means that the user is not allowed to exit unless
2436 the input is (or completes to) an existing file.
2437 - `confirm' means that the user can exit with any input, but she needs
2438 to confirm her choice if the input is not an existing file.
2439 - `confirm-after-completion' means that the user can exit with any
2440 input, but she needs to confirm her choice if she called
2441 `minibuffer-complete' right before `minibuffer-complete-and-exit'
2442 and the input is not an existing file.
2443 - anything else behaves like t except that typing RET does not exit if it
2444 does non-null completion.
2446 Fifth arg INITIAL specifies text to start with.
2448 Sixth arg PREDICATE, if non-nil, should be a function of one
2449 argument; then a file name is considered an acceptable completion
2450 alternative only if PREDICATE returns non-nil with the file name
2451 as its argument.
2453 If this command was invoked with the mouse, use a graphical file
2454 dialog if `use-dialog-box' is non-nil, and the window system or X
2455 toolkit in use provides a file dialog box, and DIR is not a
2456 remote file. For graphical file dialogs, any of the special values
2457 of MUSTMATCH `confirm' and `confirm-after-completion' are
2458 treated as equivalent to nil. Some graphical file dialogs respect
2459 a MUSTMATCH value of t, and some do not (or it only has a cosmetic
2460 effect, and does not actually prevent the user from entering a
2461 non-existent file).
2463 See also `read-file-name-completion-ignore-case'
2464 and `read-file-name-function'."
2465 ;; If x-gtk-use-old-file-dialog = t (xg_get_file_with_selection),
2466 ;; then MUSTMATCH is enforced. But with newer Gtk
2467 ;; (xg_get_file_with_chooser), it only has a cosmetic effect.
2468 ;; The user can still type a non-existent file name.
2469 (funcall (or read-file-name-function #'read-file-name-default)
2470 prompt dir default-filename mustmatch initial predicate))
2472 (defvar minibuffer-local-filename-syntax
2473 (let ((table (make-syntax-table))
2474 (punctuation (car (string-to-syntax "."))))
2475 ;; Convert all punctuation entries to symbol.
2476 (map-char-table (lambda (c syntax)
2477 (when (eq (car syntax) punctuation)
2478 (modify-syntax-entry c "_" table)))
2479 table)
2480 (mapc
2481 (lambda (c)
2482 (modify-syntax-entry c "." table))
2483 '(?/ ?: ?\\))
2484 table)
2485 "Syntax table used when reading a file name in the minibuffer.")
2487 ;; minibuffer-completing-file-name is a variable used internally in minibuf.c
2488 ;; to determine whether to use minibuffer-local-filename-completion-map or
2489 ;; minibuffer-local-completion-map. It shouldn't be exported to Elisp.
2490 ;; FIXME: Actually, it is also used in rfn-eshadow.el we'd otherwise have to
2491 ;; use (eq minibuffer-completion-table #'read-file-name-internal), which is
2492 ;; probably even worse. Maybe We should add some read-file-name-setup-hook
2493 ;; instead, but for now, let's keep this non-obsolete.
2494 ;;(make-obsolete-variable 'minibuffer-completing-file-name nil "future" 'get)
2496 (defun read-file-name-default (prompt &optional dir default-filename mustmatch initial predicate)
2497 "Default method for reading file names.
2498 See `read-file-name' for the meaning of the arguments."
2499 (unless dir (setq dir default-directory))
2500 (unless (file-name-absolute-p dir) (setq dir (expand-file-name dir)))
2501 (unless default-filename
2502 (setq default-filename (if initial (expand-file-name initial dir)
2503 buffer-file-name)))
2504 ;; If dir starts with user's homedir, change that to ~.
2505 (setq dir (abbreviate-file-name dir))
2506 ;; Likewise for default-filename.
2507 (if default-filename
2508 (setq default-filename
2509 (if (consp default-filename)
2510 (mapcar 'abbreviate-file-name default-filename)
2511 (abbreviate-file-name default-filename))))
2512 (let ((insdef (cond
2513 ((and insert-default-directory (stringp dir))
2514 (if initial
2515 (cons (minibuffer--double-dollars (concat dir initial))
2516 (length (minibuffer--double-dollars dir)))
2517 (minibuffer--double-dollars dir)))
2518 (initial (cons (minibuffer--double-dollars initial) 0)))))
2520 (let ((completion-ignore-case read-file-name-completion-ignore-case)
2521 (minibuffer-completing-file-name t)
2522 (pred (or predicate 'file-exists-p))
2523 (add-to-history nil))
2525 (let* ((val
2526 (if (or (not (next-read-file-uses-dialog-p))
2527 ;; Graphical file dialogs can't handle remote
2528 ;; files (Bug#99).
2529 (file-remote-p dir))
2530 ;; We used to pass `dir' to `read-file-name-internal' by
2531 ;; abusing the `predicate' argument. It's better to
2532 ;; just use `default-directory', but in order to avoid
2533 ;; changing `default-directory' in the current buffer,
2534 ;; we don't let-bind it.
2535 (let ((dir (file-name-as-directory
2536 (expand-file-name dir))))
2537 (minibuffer-with-setup-hook
2538 (lambda ()
2539 (setq default-directory dir)
2540 ;; When the first default in `minibuffer-default'
2541 ;; duplicates initial input `insdef',
2542 ;; reset `minibuffer-default' to nil.
2543 (when (equal (or (car-safe insdef) insdef)
2544 (or (car-safe minibuffer-default)
2545 minibuffer-default))
2546 (setq minibuffer-default
2547 (cdr-safe minibuffer-default)))
2548 ;; On the first request on `M-n' fill
2549 ;; `minibuffer-default' with a list of defaults
2550 ;; relevant for file-name reading.
2551 (set (make-local-variable 'minibuffer-default-add-function)
2552 (lambda ()
2553 (with-current-buffer
2554 (window-buffer (minibuffer-selected-window))
2555 (read-file-name--defaults dir initial))))
2556 (set-syntax-table minibuffer-local-filename-syntax))
2557 (completing-read prompt 'read-file-name-internal
2558 pred mustmatch insdef
2559 'file-name-history default-filename)))
2560 ;; If DEFAULT-FILENAME not supplied and DIR contains
2561 ;; a file name, split it.
2562 (let ((file (file-name-nondirectory dir))
2563 ;; When using a dialog, revert to nil and non-nil
2564 ;; interpretation of mustmatch. confirm options
2565 ;; need to be interpreted as nil, otherwise
2566 ;; it is impossible to create new files using
2567 ;; dialogs with the default settings.
2568 (dialog-mustmatch
2569 (not (memq mustmatch
2570 '(nil confirm confirm-after-completion)))))
2571 (when (and (not default-filename)
2572 (not (zerop (length file))))
2573 (setq default-filename file)
2574 (setq dir (file-name-directory dir)))
2575 (when default-filename
2576 (setq default-filename
2577 (expand-file-name (if (consp default-filename)
2578 (car default-filename)
2579 default-filename)
2580 dir)))
2581 (setq add-to-history t)
2582 (x-file-dialog prompt dir default-filename
2583 dialog-mustmatch
2584 (eq predicate 'file-directory-p)))))
2586 (replace-in-history (eq (car-safe file-name-history) val)))
2587 ;; If completing-read returned the inserted default string itself
2588 ;; (rather than a new string with the same contents),
2589 ;; it has to mean that the user typed RET with the minibuffer empty.
2590 ;; In that case, we really want to return ""
2591 ;; so that commands such as set-visited-file-name can distinguish.
2592 (when (consp default-filename)
2593 (setq default-filename (car default-filename)))
2594 (when (eq val default-filename)
2595 ;; In this case, completing-read has not added an element
2596 ;; to the history. Maybe we should.
2597 (if (not replace-in-history)
2598 (setq add-to-history t))
2599 (setq val ""))
2600 (unless val (error "No file name specified"))
2602 (if (and default-filename
2603 (string-equal val (if (consp insdef) (car insdef) insdef)))
2604 (setq val default-filename))
2605 (setq val (substitute-in-file-name val))
2607 (if replace-in-history
2608 ;; Replace what Fcompleting_read added to the history
2609 ;; with what we will actually return. As an exception,
2610 ;; if that's the same as the second item in
2611 ;; file-name-history, it's really a repeat (Bug#4657).
2612 (let ((val1 (minibuffer--double-dollars val)))
2613 (if history-delete-duplicates
2614 (setcdr file-name-history
2615 (delete val1 (cdr file-name-history))))
2616 (if (string= val1 (cadr file-name-history))
2617 (pop file-name-history)
2618 (setcar file-name-history val1)))
2619 (if add-to-history
2620 ;; Add the value to the history--but not if it matches
2621 ;; the last value already there.
2622 (let ((val1 (minibuffer--double-dollars val)))
2623 (unless (and (consp file-name-history)
2624 (equal (car file-name-history) val1))
2625 (setq file-name-history
2626 (cons val1
2627 (if history-delete-duplicates
2628 (delete val1 file-name-history)
2629 file-name-history)))))))
2630 val))))
2632 (defun internal-complete-buffer-except (&optional buffer)
2633 "Perform completion on all buffers excluding BUFFER.
2634 BUFFER nil or omitted means use the current buffer.
2635 Like `internal-complete-buffer', but removes BUFFER from the completion list."
2636 (let ((except (if (stringp buffer) buffer (buffer-name buffer))))
2637 (apply-partially 'completion-table-with-predicate
2638 'internal-complete-buffer
2639 (lambda (name)
2640 (not (equal (if (consp name) (car name) name) except)))
2641 nil)))
2643 ;;; Old-style completion, used in Emacs-21 and Emacs-22.
2645 (defun completion-emacs21-try-completion (string table pred _point)
2646 (let ((completion (try-completion string table pred)))
2647 (if (stringp completion)
2648 (cons completion (length completion))
2649 completion)))
2651 (defun completion-emacs21-all-completions (string table pred _point)
2652 (completion-hilit-commonality
2653 (all-completions string table pred)
2654 (length string)
2655 (car (completion-boundaries string table pred ""))))
2657 (defun completion-emacs22-try-completion (string table pred point)
2658 (let ((suffix (substring string point))
2659 (completion (try-completion (substring string 0 point) table pred)))
2660 (if (not (stringp completion))
2661 completion
2662 ;; Merge a trailing / in completion with a / after point.
2663 ;; We used to only do it for word completion, but it seems to make
2664 ;; sense for all completions.
2665 ;; Actually, claiming this feature was part of Emacs-22 completion
2666 ;; is pushing it a bit: it was only done in minibuffer-completion-word,
2667 ;; which was (by default) not bound during file completion, where such
2668 ;; slashes are most likely to occur.
2669 (if (and (not (zerop (length completion)))
2670 (eq ?/ (aref completion (1- (length completion))))
2671 (not (zerop (length suffix)))
2672 (eq ?/ (aref suffix 0)))
2673 ;; This leaves point after the / .
2674 (setq suffix (substring suffix 1)))
2675 (cons (concat completion suffix) (length completion)))))
2677 (defun completion-emacs22-all-completions (string table pred point)
2678 (let ((beforepoint (substring string 0 point)))
2679 (completion-hilit-commonality
2680 (all-completions beforepoint table pred)
2681 point
2682 (car (completion-boundaries beforepoint table pred "")))))
2684 ;;; Basic completion.
2686 (defun completion--merge-suffix (completion point suffix)
2687 "Merge end of COMPLETION with beginning of SUFFIX.
2688 Simple generalization of the \"merge trailing /\" done in Emacs-22.
2689 Return the new suffix."
2690 (if (and (not (zerop (length suffix)))
2691 (string-match "\\(.+\\)\n\\1" (concat completion "\n" suffix)
2692 ;; Make sure we don't compress things to less
2693 ;; than we started with.
2694 point)
2695 ;; Just make sure we didn't match some other \n.
2696 (eq (match-end 1) (length completion)))
2697 (substring suffix (- (match-end 1) (match-beginning 1)))
2698 ;; Nothing to merge.
2699 suffix))
2701 (defun completion-basic--pattern (beforepoint afterpoint bounds)
2702 (delete
2703 "" (list (substring beforepoint (car bounds))
2704 'point
2705 (substring afterpoint 0 (cdr bounds)))))
2707 (defun completion-basic-try-completion (string table pred point)
2708 (let* ((beforepoint (substring string 0 point))
2709 (afterpoint (substring string point))
2710 (bounds (completion-boundaries beforepoint table pred afterpoint)))
2711 (if (zerop (cdr bounds))
2712 ;; `try-completion' may return a subtly different result
2713 ;; than `all+merge', so try to use it whenever possible.
2714 (let ((completion (try-completion beforepoint table pred)))
2715 (if (not (stringp completion))
2716 completion
2717 (cons
2718 (concat completion
2719 (completion--merge-suffix completion point afterpoint))
2720 (length completion))))
2721 (let* ((suffix (substring afterpoint (cdr bounds)))
2722 (prefix (substring beforepoint 0 (car bounds)))
2723 (pattern (delete
2724 "" (list (substring beforepoint (car bounds))
2725 'point
2726 (substring afterpoint 0 (cdr bounds)))))
2727 (all (completion-pcm--all-completions prefix pattern table pred)))
2728 (if minibuffer-completing-file-name
2729 (setq all (completion-pcm--filename-try-filter all)))
2730 (completion-pcm--merge-try pattern all prefix suffix)))))
2732 (defun completion-basic-all-completions (string table pred point)
2733 (let* ((beforepoint (substring string 0 point))
2734 (afterpoint (substring string point))
2735 (bounds (completion-boundaries beforepoint table pred afterpoint))
2736 ;; (suffix (substring afterpoint (cdr bounds)))
2737 (prefix (substring beforepoint 0 (car bounds)))
2738 (pattern (delete
2739 "" (list (substring beforepoint (car bounds))
2740 'point
2741 (substring afterpoint 0 (cdr bounds)))))
2742 (all (completion-pcm--all-completions prefix pattern table pred)))
2743 (completion-hilit-commonality all point (car bounds))))
2745 ;;; Partial-completion-mode style completion.
2747 (defvar completion-pcm--delim-wild-regex nil
2748 "Regular expression matching delimiters controlling the partial-completion.
2749 Typically, this regular expression simply matches a delimiter, meaning
2750 that completion can add something at (match-beginning 0), but if it has
2751 a submatch 1, then completion can add something at (match-end 1).
2752 This is used when the delimiter needs to be of size zero (e.g. the transition
2753 from lowercase to uppercase characters).")
2755 (defun completion-pcm--prepare-delim-re (delims)
2756 (setq completion-pcm--delim-wild-regex (concat "[" delims "*]")))
2758 (defcustom completion-pcm-word-delimiters "-_./:| "
2759 "A string of characters treated as word delimiters for completion.
2760 Some arcane rules:
2761 If `]' is in this string, it must come first.
2762 If `^' is in this string, it must not come first.
2763 If `-' is in this string, it must come first or right after `]'.
2764 In other words, if S is this string, then `[S]' must be a valid Emacs regular
2765 expression (not containing character ranges like `a-z')."
2766 :set (lambda (symbol value)
2767 (set-default symbol value)
2768 ;; Refresh other vars.
2769 (completion-pcm--prepare-delim-re value))
2770 :initialize 'custom-initialize-reset
2771 :type 'string)
2773 (defcustom completion-pcm-complete-word-inserts-delimiters nil
2774 "Treat the SPC or - inserted by `minibuffer-complete-word' as delimiters.
2775 Those chars are treated as delimiters if this variable is non-nil.
2776 I.e. if non-nil, M-x SPC will just insert a \"-\" in the minibuffer, whereas
2777 if nil, it will list all possible commands in *Completions* because none of
2778 the commands start with a \"-\" or a SPC."
2779 :version "24.1"
2780 :type 'boolean)
2782 (defun completion-pcm--pattern-trivial-p (pattern)
2783 (and (stringp (car pattern))
2784 ;; It can be followed by `point' and "" and still be trivial.
2785 (let ((trivial t))
2786 (dolist (elem (cdr pattern))
2787 (unless (member elem '(point ""))
2788 (setq trivial nil)))
2789 trivial)))
2791 (defun completion-pcm--string->pattern (string &optional point)
2792 "Split STRING into a pattern.
2793 A pattern is a list where each element is either a string
2794 or a symbol, see `completion-pcm--merge-completions'."
2795 (if (and point (< point (length string)))
2796 (let ((prefix (substring string 0 point))
2797 (suffix (substring string point)))
2798 (append (completion-pcm--string->pattern prefix)
2799 '(point)
2800 (completion-pcm--string->pattern suffix)))
2801 (let* ((pattern nil)
2802 (p 0)
2803 (p0 p)
2804 (pending nil))
2806 (while (and (setq p (string-match completion-pcm--delim-wild-regex
2807 string p))
2808 (or completion-pcm-complete-word-inserts-delimiters
2809 ;; If the char was added by minibuffer-complete-word,
2810 ;; then don't treat it as a delimiter, otherwise
2811 ;; "M-x SPC" ends up inserting a "-" rather than listing
2812 ;; all completions.
2813 (not (get-text-property p 'completion-try-word string))))
2814 ;; Usually, completion-pcm--delim-wild-regex matches a delimiter,
2815 ;; meaning that something can be added *before* it, but it can also
2816 ;; match a prefix and postfix, in which case something can be added
2817 ;; in-between (e.g. match [[:lower:]][[:upper:]]).
2818 ;; This is determined by the presence of a submatch-1 which delimits
2819 ;; the prefix.
2820 (if (match-end 1) (setq p (match-end 1)))
2821 (unless (= p0 p)
2822 (if pending (push pending pattern))
2823 (push (substring string p0 p) pattern))
2824 (setq pending nil)
2825 (if (eq (aref string p) ?*)
2826 (progn
2827 (push 'star pattern)
2828 (setq p0 (1+ p)))
2829 (push 'any pattern)
2830 (if (match-end 1)
2831 (setq p0 p)
2832 (push (substring string p (match-end 0)) pattern)
2833 ;; `any-delim' is used so that "a-b" also finds "array->beginning".
2834 (setq pending 'any-delim)
2835 (setq p0 (match-end 0))))
2836 (setq p p0))
2838 (when (> (length string) p0)
2839 (if pending (push pending pattern))
2840 (push (substring string p0) pattern))
2841 ;; An empty string might be erroneously added at the beginning.
2842 ;; It should be avoided properly, but it's so easy to remove it here.
2843 (delete "" (nreverse pattern)))))
2845 (defun completion-pcm--optimize-pattern (p)
2846 ;; Remove empty strings in a separate phase since otherwise a ""
2847 ;; might prevent some other optimization, as in '(any "" any).
2848 (setq p (delete "" p))
2849 (let ((n '()))
2850 (while p
2851 (pcase p
2852 (`(,(and s1 (pred stringp)) ,(and s2 (pred stringp)) . ,rest)
2853 (setq p (cons (concat s1 s2) rest)))
2854 (`(,(and p1 (pred symbolp)) ,(and p2 (guard (eq p1 p2))) . ,_)
2855 (setq p (cdr p)))
2856 (`(star ,(pred symbolp) . ,rest) (setq p `(star . ,rest)))
2857 (`(,(pred symbolp) star . ,rest) (setq p `(star . ,rest)))
2858 (`(point ,(or `any `any-delim) . ,rest) (setq p `(point . ,rest)))
2859 (`(,(or `any `any-delim) point . ,rest) (setq p `(point . ,rest)))
2860 (`(any ,(or `any `any-delim) . ,rest) (setq p `(any . ,rest)))
2861 (`(,(pred symbolp)) (setq p nil)) ;Implicit terminating `any'.
2862 (_ (push (pop p) n))))
2863 (nreverse n)))
2865 (defun completion-pcm--pattern->regex (pattern &optional group)
2866 (let ((re
2867 (concat "\\`"
2868 (mapconcat
2869 (lambda (x)
2870 (cond
2871 ((stringp x) (regexp-quote x))
2873 (let ((re (if (eq x 'any-delim)
2874 (concat completion-pcm--delim-wild-regex "*?")
2875 ".*?")))
2876 (if (if (consp group) (memq x group) group)
2877 (concat "\\(" re "\\)")
2878 re)))))
2879 pattern
2880 ""))))
2881 ;; Avoid pathological backtracking.
2882 (while (string-match "\\.\\*\\?\\(?:\\\\[()]\\)*\\(\\.\\*\\?\\)" re)
2883 (setq re (replace-match "" t t re 1)))
2884 re))
2886 (defun completion-pcm--all-completions (prefix pattern table pred)
2887 "Find all completions for PATTERN in TABLE obeying PRED.
2888 PATTERN is as returned by `completion-pcm--string->pattern'."
2889 ;; (cl-assert (= (car (completion-boundaries prefix table pred ""))
2890 ;; (length prefix)))
2891 ;; Find an initial list of possible completions.
2892 (if (completion-pcm--pattern-trivial-p pattern)
2894 ;; Minibuffer contains no delimiters -- simple case!
2895 (all-completions (concat prefix (car pattern)) table pred)
2897 ;; Use all-completions to do an initial cull. This is a big win,
2898 ;; since all-completions is written in C!
2899 (let* (;; Convert search pattern to a standard regular expression.
2900 (regex (completion-pcm--pattern->regex pattern))
2901 (case-fold-search completion-ignore-case)
2902 (completion-regexp-list (cons regex completion-regexp-list))
2903 (compl (all-completions
2904 (concat prefix
2905 (if (stringp (car pattern)) (car pattern) ""))
2906 table pred)))
2907 (if (not (functionp table))
2908 ;; The internal functions already obeyed completion-regexp-list.
2909 compl
2910 (let ((poss ()))
2911 (dolist (c compl)
2912 (when (string-match-p regex c) (push c poss)))
2913 poss)))))
2915 (defun completion-pcm--hilit-commonality (pattern completions)
2916 (when completions
2917 (let* ((re (completion-pcm--pattern->regex pattern '(point)))
2918 (case-fold-search completion-ignore-case))
2919 (mapcar
2920 (lambda (str)
2921 ;; Don't modify the string itself.
2922 (setq str (copy-sequence str))
2923 (unless (string-match re str)
2924 (error "Internal error: %s does not match %s" re str))
2925 (let ((pos (or (match-beginning 1) (match-end 0))))
2926 (put-text-property 0 pos
2927 'font-lock-face 'completions-common-part
2928 str)
2929 (if (> (length str) pos)
2930 (put-text-property pos (1+ pos)
2931 'font-lock-face 'completions-first-difference
2932 str)))
2933 str)
2934 completions))))
2936 (defun completion-pcm--find-all-completions (string table pred point
2937 &optional filter)
2938 "Find all completions for STRING at POINT in TABLE, satisfying PRED.
2939 POINT is a position inside STRING.
2940 FILTER is a function applied to the return value, that can be used, e.g. to
2941 filter out additional entries (because TABLE might not obey PRED)."
2942 (unless filter (setq filter 'identity))
2943 (let* ((beforepoint (substring string 0 point))
2944 (afterpoint (substring string point))
2945 (bounds (completion-boundaries beforepoint table pred afterpoint))
2946 (prefix (substring beforepoint 0 (car bounds)))
2947 (suffix (substring afterpoint (cdr bounds)))
2948 firsterror)
2949 (setq string (substring string (car bounds) (+ point (cdr bounds))))
2950 (let* ((relpoint (- point (car bounds)))
2951 (pattern (completion-pcm--string->pattern string relpoint))
2952 (all (condition-case-unless-debug err
2953 (funcall filter
2954 (completion-pcm--all-completions
2955 prefix pattern table pred))
2956 (error (setq firsterror err) nil))))
2957 (when (and (null all)
2958 (> (car bounds) 0)
2959 (null (ignore-errors (try-completion prefix table pred))))
2960 ;; The prefix has no completions at all, so we should try and fix
2961 ;; that first.
2962 (let ((substring (substring prefix 0 -1)))
2963 (pcase-let ((`(,subpat ,suball ,subprefix ,_subsuffix)
2964 (completion-pcm--find-all-completions
2965 substring table pred (length substring) filter)))
2966 (let ((sep (aref prefix (1- (length prefix))))
2967 ;; Text that goes between the new submatches and the
2968 ;; completion substring.
2969 (between nil))
2970 ;; Eliminate submatches that don't end with the separator.
2971 (dolist (submatch (prog1 suball (setq suball ())))
2972 (when (eq sep (aref submatch (1- (length submatch))))
2973 (push submatch suball)))
2974 (when suball
2975 ;; Update the boundaries and corresponding pattern.
2976 ;; We assume that all submatches result in the same boundaries
2977 ;; since we wouldn't know how to merge them otherwise anyway.
2978 ;; FIXME: COMPLETE REWRITE!!!
2979 (let* ((newbeforepoint
2980 (concat subprefix (car suball)
2981 (substring string 0 relpoint)))
2982 (leftbound (+ (length subprefix) (length (car suball))))
2983 (newbounds (completion-boundaries
2984 newbeforepoint table pred afterpoint)))
2985 (unless (or (and (eq (cdr bounds) (cdr newbounds))
2986 (eq (car newbounds) leftbound))
2987 ;; Refuse new boundaries if they step over
2988 ;; the submatch.
2989 (< (car newbounds) leftbound))
2990 ;; The new completed prefix does change the boundaries
2991 ;; of the completed substring.
2992 (setq suffix (substring afterpoint (cdr newbounds)))
2993 (setq string
2994 (concat (substring newbeforepoint (car newbounds))
2995 (substring afterpoint 0 (cdr newbounds))))
2996 (setq between (substring newbeforepoint leftbound
2997 (car newbounds)))
2998 (setq pattern (completion-pcm--string->pattern
2999 string
3000 (- (length newbeforepoint)
3001 (car newbounds)))))
3002 (dolist (submatch suball)
3003 (setq all (nconc
3004 (mapcar
3005 (lambda (s) (concat submatch between s))
3006 (funcall filter
3007 (completion-pcm--all-completions
3008 (concat subprefix submatch between)
3009 pattern table pred)))
3010 all)))
3011 ;; FIXME: This can come in handy for try-completion,
3012 ;; but isn't right for all-completions, since it lists
3013 ;; invalid completions.
3014 ;; (unless all
3015 ;; ;; Even though we found expansions in the prefix, none
3016 ;; ;; leads to a valid completion.
3017 ;; ;; Let's keep the expansions, tho.
3018 ;; (dolist (submatch suball)
3019 ;; (push (concat submatch between newsubstring) all)))
3021 (setq pattern (append subpat (list 'any (string sep))
3022 (if between (list between)) pattern))
3023 (setq prefix subprefix)))))
3024 (if (and (null all) firsterror)
3025 (signal (car firsterror) (cdr firsterror))
3026 (list pattern all prefix suffix)))))
3028 (defun completion-pcm-all-completions (string table pred point)
3029 (pcase-let ((`(,pattern ,all ,prefix ,_suffix)
3030 (completion-pcm--find-all-completions string table pred point)))
3031 (when all
3032 (nconc (completion-pcm--hilit-commonality pattern all)
3033 (length prefix)))))
3035 (defun completion--sreverse (str)
3036 "Like `reverse' but for a string STR rather than a list."
3037 (apply #'string (nreverse (mapcar 'identity str))))
3039 (defun completion--common-suffix (strs)
3040 "Return the common suffix of the strings STRS."
3041 (completion--sreverse
3042 (try-completion
3044 (mapcar #'completion--sreverse strs))))
3046 (defun completion-pcm--merge-completions (strs pattern)
3047 "Extract the commonality in STRS, with the help of PATTERN.
3048 PATTERN can contain strings and symbols chosen among `star', `any', `point',
3049 and `prefix'. They all match anything (aka \".*\") but are merged differently:
3050 `any' only grows from the left (when matching \"a1b\" and \"a2b\" it gets
3051 completed to just \"a\").
3052 `prefix' only grows from the right (when matching \"a1b\" and \"a2b\" it gets
3053 completed to just \"b\").
3054 `star' grows from both ends and is reified into a \"*\" (when matching \"a1b\"
3055 and \"a2b\" it gets completed to \"a*b\").
3056 `point' is like `star' except that it gets reified as the position of point
3057 instead of being reified as a \"*\" character.
3058 The underlying idea is that we should return a string which still matches
3059 the same set of elements."
3060 ;; When completing while ignoring case, we want to try and avoid
3061 ;; completing "fo" to "foO" when completing against "FOO" (bug#4219).
3062 ;; So we try and make sure that the string we return is all made up
3063 ;; of text from the completions rather than part from the
3064 ;; completions and part from the input.
3065 ;; FIXME: This reduces the problems of inconsistent capitalization
3066 ;; but it doesn't fully fix it: we may still end up completing
3067 ;; "fo-ba" to "foo-BAR" or "FOO-bar" when completing against
3068 ;; '("foo-barr" "FOO-BARD").
3069 (cond
3070 ((null (cdr strs)) (list (car strs)))
3072 (let ((re (completion-pcm--pattern->regex pattern 'group))
3073 (ccs ())) ;Chopped completions.
3075 ;; First chop each string into the parts corresponding to each
3076 ;; non-constant element of `pattern', using regexp-matching.
3077 (let ((case-fold-search completion-ignore-case))
3078 (dolist (str strs)
3079 (unless (string-match re str)
3080 (error "Internal error: %s doesn't match %s" str re))
3081 (let ((chopped ())
3082 (last 0)
3083 (i 1)
3084 next)
3085 (while (setq next (match-end i))
3086 (push (substring str last next) chopped)
3087 (setq last next)
3088 (setq i (1+ i)))
3089 ;; Add the text corresponding to the implicit trailing `any'.
3090 (push (substring str last) chopped)
3091 (push (nreverse chopped) ccs))))
3093 ;; Then for each of those non-constant elements, extract the
3094 ;; commonality between them.
3095 (let ((res ())
3096 (fixed ""))
3097 ;; Make the implicit trailing `any' explicit.
3098 (dolist (elem (append pattern '(any)))
3099 (if (stringp elem)
3100 (setq fixed (concat fixed elem))
3101 (let ((comps ()))
3102 (dolist (cc (prog1 ccs (setq ccs nil)))
3103 (push (car cc) comps)
3104 (push (cdr cc) ccs))
3105 ;; Might improve the likelihood to avoid choosing
3106 ;; different capitalizations in different parts.
3107 ;; In practice, it doesn't seem to make any difference.
3108 (setq ccs (nreverse ccs))
3109 (let* ((prefix (try-completion fixed comps))
3110 (unique (or (and (eq prefix t) (setq prefix fixed))
3111 (eq t (try-completion prefix comps)))))
3112 (unless (or (eq elem 'prefix)
3113 (equal prefix ""))
3114 (push prefix res))
3115 ;; If there's only one completion, `elem' is not useful
3116 ;; any more: it can only match the empty string.
3117 ;; FIXME: in some cases, it may be necessary to turn an
3118 ;; `any' into a `star' because the surrounding context has
3119 ;; changed such that string->pattern wouldn't add an `any'
3120 ;; here any more.
3121 (unless unique
3122 (push elem res)
3123 ;; Extract common suffix additionally to common prefix.
3124 ;; Don't do it for `any' since it could lead to a merged
3125 ;; completion that doesn't itself match the candidates.
3126 (when (and (memq elem '(star point prefix))
3127 ;; If prefix is one of the completions, there's no
3128 ;; suffix left to find.
3129 (not (assoc-string prefix comps t)))
3130 (let ((suffix
3131 (completion--common-suffix
3132 (if (zerop (length prefix)) comps
3133 ;; Ignore the chars in the common prefix, so we
3134 ;; don't merge '("abc" "abbc") as "ab*bc".
3135 (let ((skip (length prefix)))
3136 (mapcar (lambda (str) (substring str skip))
3137 comps))))))
3138 (cl-assert (stringp suffix))
3139 (unless (equal suffix "")
3140 (push suffix res)))))
3141 (setq fixed "")))))
3142 ;; We return it in reverse order.
3143 res)))))
3145 (defun completion-pcm--pattern->string (pattern)
3146 (mapconcat (lambda (x) (cond
3147 ((stringp x) x)
3148 ((eq x 'star) "*")
3149 (t ""))) ;any, point, prefix.
3150 pattern
3151 ""))
3153 ;; We want to provide the functionality of `try', but we use `all'
3154 ;; and then merge it. In most cases, this works perfectly, but
3155 ;; if the completion table doesn't consider the same completions in
3156 ;; `try' as in `all', then we have a problem. The most common such
3157 ;; case is for filename completion where completion-ignored-extensions
3158 ;; is only obeyed by the `try' code. We paper over the difference
3159 ;; here. Note that it is not quite right either: if the completion
3160 ;; table uses completion-table-in-turn, this filtering may take place
3161 ;; too late to correctly fallback from the first to the
3162 ;; second alternative.
3163 (defun completion-pcm--filename-try-filter (all)
3164 "Filter to adjust `all' file completion to the behavior of `try'."
3165 (when all
3166 (let ((try ())
3167 (re (concat "\\(?:\\`\\.\\.?/\\|"
3168 (regexp-opt completion-ignored-extensions)
3169 "\\)\\'")))
3170 (dolist (f all)
3171 (unless (string-match-p re f) (push f try)))
3172 (or try all))))
3175 (defun completion-pcm--merge-try (pattern all prefix suffix)
3176 (cond
3177 ((not (consp all)) all)
3178 ((and (not (consp (cdr all))) ;Only one completion.
3179 ;; Ignore completion-ignore-case here.
3180 (equal (completion-pcm--pattern->string pattern) (car all)))
3183 (let* ((mergedpat (completion-pcm--merge-completions all pattern))
3184 ;; `mergedpat' is in reverse order. Place new point (by
3185 ;; order of preference) either at the old point, or at
3186 ;; the last place where there's something to choose, or
3187 ;; at the very end.
3188 (pointpat (or (memq 'point mergedpat)
3189 (memq 'any mergedpat)
3190 (memq 'star mergedpat)
3191 ;; Not `prefix'.
3192 mergedpat))
3193 ;; New pos from the start.
3194 (newpos (length (completion-pcm--pattern->string pointpat)))
3195 ;; Do it afterwards because it changes `pointpat' by side effect.
3196 (merged (completion-pcm--pattern->string (nreverse mergedpat))))
3198 (setq suffix (completion--merge-suffix merged newpos suffix))
3199 (cons (concat prefix merged suffix) (+ newpos (length prefix)))))))
3201 (defun completion-pcm-try-completion (string table pred point)
3202 (pcase-let ((`(,pattern ,all ,prefix ,suffix)
3203 (completion-pcm--find-all-completions
3204 string table pred point
3205 (if minibuffer-completing-file-name
3206 'completion-pcm--filename-try-filter))))
3207 (completion-pcm--merge-try pattern all prefix suffix)))
3209 ;;; Substring completion
3210 ;; Mostly derived from the code of `basic' completion.
3212 (defun completion-substring--all-completions (string table pred point)
3213 (let* ((beforepoint (substring string 0 point))
3214 (afterpoint (substring string point))
3215 (bounds (completion-boundaries beforepoint table pred afterpoint))
3216 (suffix (substring afterpoint (cdr bounds)))
3217 (prefix (substring beforepoint 0 (car bounds)))
3218 (basic-pattern (completion-basic--pattern
3219 beforepoint afterpoint bounds))
3220 (pattern (if (not (stringp (car basic-pattern)))
3221 basic-pattern
3222 (cons 'prefix basic-pattern)))
3223 (all (completion-pcm--all-completions prefix pattern table pred)))
3224 (list all pattern prefix suffix (car bounds))))
3226 (defun completion-substring-try-completion (string table pred point)
3227 (pcase-let ((`(,all ,pattern ,prefix ,suffix ,_carbounds)
3228 (completion-substring--all-completions
3229 string table pred point)))
3230 (if minibuffer-completing-file-name
3231 (setq all (completion-pcm--filename-try-filter all)))
3232 (completion-pcm--merge-try pattern all prefix suffix)))
3234 (defun completion-substring-all-completions (string table pred point)
3235 (pcase-let ((`(,all ,pattern ,prefix ,_suffix ,_carbounds)
3236 (completion-substring--all-completions
3237 string table pred point)))
3238 (when all
3239 (nconc (completion-pcm--hilit-commonality pattern all)
3240 (length prefix)))))
3242 ;; Initials completion
3243 ;; Complete /ums to /usr/monnier/src or lch to list-command-history.
3245 (defun completion-initials-expand (str table pred)
3246 (let ((bounds (completion-boundaries str table pred "")))
3247 (unless (or (zerop (length str))
3248 ;; Only check within the boundaries, since the
3249 ;; boundary char (e.g. /) might be in delim-regexp.
3250 (string-match completion-pcm--delim-wild-regex str
3251 (car bounds)))
3252 (if (zerop (car bounds))
3253 (mapconcat 'string str "-")
3254 ;; If there's a boundary, it's trickier. The main use-case
3255 ;; we consider here is file-name completion. We'd like
3256 ;; to expand ~/eee to ~/e/e/e and /eee to /e/e/e.
3257 ;; But at the same time, we don't want /usr/share/ae to expand
3258 ;; to /usr/share/a/e just because we mistyped "ae" for "ar",
3259 ;; so we probably don't want initials to touch anything that
3260 ;; looks like /usr/share/foo. As a heuristic, we just check that
3261 ;; the text before the boundary char is at most 1 char.
3262 ;; This allows both ~/eee and /eee and not much more.
3263 ;; FIXME: It sadly also disallows the use of ~/eee when that's
3264 ;; embedded within something else (e.g. "(~/eee" in Info node
3265 ;; completion or "ancestor:/eee" in bzr-revision completion).
3266 (when (< (car bounds) 3)
3267 (let ((sep (substring str (1- (car bounds)) (car bounds))))
3268 ;; FIXME: the above string-match checks the whole string, whereas
3269 ;; we end up only caring about the after-boundary part.
3270 (concat (substring str 0 (car bounds))
3271 (mapconcat 'string (substring str (car bounds)) sep))))))))
3273 (defun completion-initials-all-completions (string table pred _point)
3274 (let ((newstr (completion-initials-expand string table pred)))
3275 (when newstr
3276 (completion-pcm-all-completions newstr table pred (length newstr)))))
3278 (defun completion-initials-try-completion (string table pred _point)
3279 (let ((newstr (completion-initials-expand string table pred)))
3280 (when newstr
3281 (completion-pcm-try-completion newstr table pred (length newstr)))))
3283 (defvar completing-read-function 'completing-read-default
3284 "The function called by `completing-read' to do its work.
3285 It should accept the same arguments as `completing-read'.")
3287 (defun completing-read-default (prompt collection &optional predicate
3288 require-match initial-input
3289 hist def inherit-input-method)
3290 "Default method for reading from the minibuffer with completion.
3291 See `completing-read' for the meaning of the arguments."
3293 (when (consp initial-input)
3294 (setq initial-input
3295 (cons (car initial-input)
3296 ;; `completing-read' uses 0-based index while
3297 ;; `read-from-minibuffer' uses 1-based index.
3298 (1+ (cdr initial-input)))))
3300 (let* ((minibuffer-completion-table collection)
3301 (minibuffer-completion-predicate predicate)
3302 (minibuffer-completion-confirm (unless (eq require-match t)
3303 require-match))
3304 (base-keymap (if require-match
3305 minibuffer-local-must-match-map
3306 minibuffer-local-completion-map))
3307 (keymap (if (memq minibuffer-completing-file-name '(nil lambda))
3308 base-keymap
3309 ;; Layer minibuffer-local-filename-completion-map
3310 ;; on top of the base map.
3311 (make-composed-keymap
3312 minibuffer-local-filename-completion-map
3313 ;; Set base-keymap as the parent, so that nil bindings
3314 ;; in minibuffer-local-filename-completion-map can
3315 ;; override bindings in base-keymap.
3316 base-keymap)))
3317 (result (read-from-minibuffer prompt initial-input keymap
3318 nil hist def inherit-input-method)))
3319 (when (and (equal result "") def)
3320 (setq result (if (consp def) (car def) def)))
3321 result))
3323 ;; Miscellaneous
3325 (defun minibuffer-insert-file-name-at-point ()
3326 "Get a file name at point in original buffer and insert it to minibuffer."
3327 (interactive)
3328 (let ((file-name-at-point
3329 (with-current-buffer (window-buffer (minibuffer-selected-window))
3330 (run-hook-with-args-until-success 'file-name-at-point-functions))))
3331 (when file-name-at-point
3332 (insert file-name-at-point))))
3334 (provide 'minibuffer)
3336 ;;; minibuffer.el ends here