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