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