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