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