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