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