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