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