Merge from emacs-24; up to 2014-04-16T15:28:06Z!eggert@cs.ucla.edu
[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 (when (<= (minibuffer-prompt-end) (point))
1096 (completion-in-region (minibuffer-prompt-end) (point-max)
1097 minibuffer-completion-table
1098 minibuffer-completion-predicate)))
1099
1100 (defun completion--in-region-1 (beg end)
1101 ;; If the previous command was not this,
1102 ;; mark the completion buffer obsolete.
1103 (setq this-command 'completion-at-point)
1104 (unless (eq 'completion-at-point last-command)
1105 (completion--flush-all-sorted-completions)
1106 (setq minibuffer-scroll-window nil))
1107
1108 (cond
1109 ;; If there's a fresh completion window with a live buffer,
1110 ;; and this command is repeated, scroll that window.
1111 ((and (window-live-p minibuffer-scroll-window)
1112 (eq t (frame-visible-p (window-frame minibuffer-scroll-window))))
1113 (let ((window minibuffer-scroll-window))
1114 (with-current-buffer (window-buffer window)
1115 (if (pos-visible-in-window-p (point-max) window)
1116 ;; If end is in view, scroll up to the beginning.
1117 (set-window-start window (point-min) nil)
1118 ;; Else scroll down one screen.
1119 (with-selected-window window
1120 (scroll-up)))
1121 nil)))
1122 ;; If we're cycling, keep on cycling.
1123 ((and completion-cycling completion-all-sorted-completions)
1124 (minibuffer-force-complete beg end)
1125 t)
1126 (t (pcase (completion--do-completion beg end)
1127 (#b000 nil)
1128 (_ t)))))
1129
1130 (defun completion--cache-all-sorted-completions (beg end comps)
1131 (add-hook 'after-change-functions
1132 'completion--flush-all-sorted-completions nil t)
1133 (setq completion--all-sorted-completions-location
1134 (cons (copy-marker beg) (copy-marker end)))
1135 (setq completion-all-sorted-completions comps))
1136
1137 (defun completion--flush-all-sorted-completions (&optional start end _len)
1138 (unless (and start end
1139 (or (> start (cdr completion--all-sorted-completions-location))
1140 (< end (car completion--all-sorted-completions-location))))
1141 (remove-hook 'after-change-functions
1142 'completion--flush-all-sorted-completions t)
1143 (setq completion-cycling nil)
1144 (setq completion-all-sorted-completions nil)))
1145
1146 (defun completion--metadata (string base md-at-point table pred)
1147 ;; Like completion-metadata, but for the specific case of getting the
1148 ;; metadata at `base', which tends to trigger pathological behavior for old
1149 ;; completion tables which don't understand `metadata'.
1150 (let ((bounds (completion-boundaries string table pred "")))
1151 (if (eq (car bounds) base) md-at-point
1152 (completion-metadata (substring string 0 base) table pred))))
1153
1154 (defun completion-all-sorted-completions (&optional start end)
1155 (or completion-all-sorted-completions
1156 (let* ((start (or start (minibuffer-prompt-end)))
1157 (end (or end (point-max)))
1158 (string (buffer-substring start end))
1159 (md (completion--field-metadata start))
1160 (all (completion-all-completions
1161 string
1162 minibuffer-completion-table
1163 minibuffer-completion-predicate
1164 (- (point) start)
1165 md))
1166 (last (last all))
1167 (base-size (or (cdr last) 0))
1168 (all-md (completion--metadata (buffer-substring-no-properties
1169 start (point))
1170 base-size md
1171 minibuffer-completion-table
1172 minibuffer-completion-predicate))
1173 (sort-fun (completion-metadata-get all-md 'cycle-sort-function)))
1174 (when last
1175 (setcdr last nil)
1176
1177 ;; Delete duplicates: do it after setting last's cdr to nil (so
1178 ;; it's a proper list), and be careful to reset `last' since it
1179 ;; may be a different cons-cell.
1180 (setq all (delete-dups all))
1181 (setq last (last all))
1182
1183 (setq all (if sort-fun (funcall sort-fun all)
1184 ;; Prefer shorter completions, by default.
1185 (sort all (lambda (c1 c2) (< (length c1) (length c2))))))
1186 ;; Prefer recently used completions.
1187 (when (minibufferp)
1188 (let ((hist (symbol-value minibuffer-history-variable)))
1189 (setq all (sort all (lambda (c1 c2)
1190 (> (length (member c1 hist))
1191 (length (member c2 hist))))))))
1192 ;; Cache the result. This is not just for speed, but also so that
1193 ;; repeated calls to minibuffer-force-complete can cycle through
1194 ;; all possibilities.
1195 (completion--cache-all-sorted-completions
1196 start end (nconc all base-size))))))
1197
1198 (defun minibuffer-force-complete-and-exit ()
1199 "Complete the minibuffer with first of the matches and exit."
1200 (interactive)
1201 (minibuffer-force-complete)
1202 (completion--complete-and-exit
1203 (minibuffer-prompt-end) (point-max) #'exit-minibuffer
1204 ;; If the previous completion completed to an element which fails
1205 ;; test-completion, then we shouldn't exit, but that should be rare.
1206 (lambda () (minibuffer-message "Incomplete"))))
1207
1208 (defun minibuffer-force-complete (&optional start end)
1209 "Complete the minibuffer to an exact match.
1210 Repeated uses step through the possible completions."
1211 (interactive)
1212 (setq minibuffer-scroll-window nil)
1213 ;; FIXME: Need to deal with the extra-size issue here as well.
1214 ;; FIXME: ~/src/emacs/t<M-TAB>/lisp/minibuffer.el completes to
1215 ;; ~/src/emacs/trunk/ and throws away lisp/minibuffer.el.
1216 (let* ((start (copy-marker (or start (minibuffer-prompt-end))))
1217 (end (or end (point-max)))
1218 ;; (md (completion--field-metadata start))
1219 (all (completion-all-sorted-completions start end))
1220 (base (+ start (or (cdr (last all)) 0))))
1221 (cond
1222 ((not (consp all))
1223 (completion--message
1224 (if all "No more completions" "No completions")))
1225 ((not (consp (cdr all)))
1226 (let ((done (equal (car all) (buffer-substring-no-properties base end))))
1227 (unless done (completion--replace base end (car all)))
1228 (completion--done (buffer-substring-no-properties start (point))
1229 'finished (when done "Sole completion"))))
1230 (t
1231 (completion--replace base end (car all))
1232 (setq end (+ base (length (car all))))
1233 (completion--done (buffer-substring-no-properties start (point)) 'sole)
1234 ;; Set cycling after modifying the buffer since the flush hook resets it.
1235 (setq completion-cycling t)
1236 (setq this-command 'completion-at-point) ;For completion-in-region.
1237 ;; If completing file names, (car all) may be a directory, so we'd now
1238 ;; have a new set of possible completions and might want to reset
1239 ;; completion-all-sorted-completions to nil, but we prefer not to,
1240 ;; so that repeated calls minibuffer-force-complete still cycle
1241 ;; through the previous possible completions.
1242 (let ((last (last all)))
1243 (setcdr last (cons (car all) (cdr last)))
1244 (completion--cache-all-sorted-completions start end (cdr all)))
1245 ;; Make sure repeated uses cycle, even though completion--done might
1246 ;; have added a space or something that moved us outside of the field.
1247 ;; (bug#12221).
1248 (let* ((table minibuffer-completion-table)
1249 (pred minibuffer-completion-predicate)
1250 (extra-prop completion-extra-properties)
1251 (cmd
1252 (lambda () "Cycle through the possible completions."
1253 (interactive)
1254 (let ((completion-extra-properties extra-prop))
1255 (completion-in-region start (point) table pred)))))
1256 (set-transient-map
1257 (let ((map (make-sparse-keymap)))
1258 (define-key map [remap completion-at-point] cmd)
1259 (define-key map (vector last-command-event) cmd)
1260 map)))))))
1261
1262 (defvar minibuffer-confirm-exit-commands
1263 '(completion-at-point minibuffer-complete
1264 minibuffer-complete-word PC-complete PC-complete-word)
1265 "A list of commands which cause an immediately following
1266 `minibuffer-complete-and-exit' to ask for extra confirmation.")
1267
1268 (defun minibuffer-complete-and-exit ()
1269 "Exit if the minibuffer contains a valid completion.
1270 Otherwise, try to complete the minibuffer contents. If
1271 completion leads to a valid completion, a repetition of this
1272 command will exit.
1273
1274 If `minibuffer-completion-confirm' is `confirm', do not try to
1275 complete; instead, ask for confirmation and accept any input if
1276 confirmed.
1277 If `minibuffer-completion-confirm' is `confirm-after-completion',
1278 do not try to complete; instead, ask for confirmation if the
1279 preceding minibuffer command was a member of
1280 `minibuffer-confirm-exit-commands', and accept the input
1281 otherwise."
1282 (interactive)
1283 (completion-complete-and-exit (minibuffer-prompt-end) (point-max)
1284 #'exit-minibuffer))
1285
1286 (defun completion-complete-and-exit (beg end exit-function)
1287 (completion--complete-and-exit
1288 beg end exit-function
1289 (lambda ()
1290 (pcase (condition-case nil
1291 (completion--do-completion beg end
1292 nil 'expect-exact)
1293 (error 1))
1294 ((or #b001 #b011) (funcall exit-function))
1295 (#b111 (if (not minibuffer-completion-confirm)
1296 (funcall exit-function)
1297 (minibuffer-message "Confirm")
1298 nil))
1299 (_ nil)))))
1300
1301 (defun completion--complete-and-exit (beg end
1302 exit-function completion-function)
1303 "Exit from `require-match' minibuffer.
1304 COMPLETION-FUNCTION is called if the current buffer's content does not
1305 appear to be a match."
1306 (cond
1307 ;; Allow user to specify null string
1308 ((= beg end) (funcall exit-function))
1309 ((test-completion (buffer-substring beg end)
1310 minibuffer-completion-table
1311 minibuffer-completion-predicate)
1312 ;; FIXME: completion-ignore-case has various slightly
1313 ;; incompatible meanings. E.g. it can reflect whether the user
1314 ;; wants completion to pay attention to case, or whether the
1315 ;; string will be used in a context where case is significant.
1316 ;; E.g. usually try-completion should obey the first, whereas
1317 ;; test-completion should obey the second.
1318 (when completion-ignore-case
1319 ;; Fixup case of the field, if necessary.
1320 (let* ((string (buffer-substring beg end))
1321 (compl (try-completion
1322 string
1323 minibuffer-completion-table
1324 minibuffer-completion-predicate)))
1325 (when (and (stringp compl) (not (equal string compl))
1326 ;; If it weren't for this piece of paranoia, I'd replace
1327 ;; the whole thing with a call to do-completion.
1328 ;; This is important, e.g. when the current minibuffer's
1329 ;; content is a directory which only contains a single
1330 ;; file, so `try-completion' actually completes to
1331 ;; that file.
1332 (= (length string) (length compl)))
1333 (completion--replace beg end compl))))
1334 (funcall exit-function))
1335
1336 ((memq minibuffer-completion-confirm '(confirm confirm-after-completion))
1337 ;; The user is permitted to exit with an input that's rejected
1338 ;; by test-completion, after confirming her choice.
1339 (if (or (eq last-command this-command)
1340 ;; For `confirm-after-completion' we only ask for confirmation
1341 ;; if trying to exit immediately after typing TAB (this
1342 ;; catches most minibuffer typos).
1343 (and (eq minibuffer-completion-confirm 'confirm-after-completion)
1344 (not (memq last-command minibuffer-confirm-exit-commands))))
1345 (funcall exit-function)
1346 (minibuffer-message "Confirm")
1347 nil))
1348
1349 (t
1350 ;; Call do-completion, but ignore errors.
1351 (funcall completion-function))))
1352
1353 (defun completion--try-word-completion (string table predicate point md)
1354 (let ((comp (completion-try-completion string table predicate point md)))
1355 (if (not (consp comp))
1356 comp
1357
1358 ;; If completion finds next char not unique,
1359 ;; consider adding a space or a hyphen.
1360 (when (= (length string) (length (car comp)))
1361 ;; Mark the added char with the `completion-word' property, so it
1362 ;; can be handled specially by completion styles such as
1363 ;; partial-completion.
1364 ;; We used to remove `partial-completion' from completion-styles
1365 ;; instead, but it was too blunt, leading to situations where SPC
1366 ;; was the only insertable char at point but minibuffer-complete-word
1367 ;; refused inserting it.
1368 (let* ((exts (mapcar (lambda (str) (propertize str 'completion-try-word t))
1369 '(" " "-")))
1370 (before (substring string 0 point))
1371 (after (substring string point))
1372 (comps
1373 (delete nil
1374 (mapcar (lambda (ext)
1375 (completion-try-completion
1376 (concat before ext after)
1377 table predicate (1+ point) md))
1378 exts))))
1379 (when (and (null (cdr comps)) (consp (car comps)))
1380 (setq comp (car comps)))))
1381
1382 ;; Completing a single word is actually more difficult than completing
1383 ;; as much as possible, because we first have to find the "current
1384 ;; position" in `completion' in order to find the end of the word
1385 ;; we're completing. Normally, `string' is a prefix of `completion',
1386 ;; which makes it trivial to find the position, but with fancier
1387 ;; completion (plus env-var expansion, ...) `completion' might not
1388 ;; look anything like `string' at all.
1389 (let* ((comppoint (cdr comp))
1390 (completion (car comp))
1391 (before (substring string 0 point))
1392 (combined (concat before "\n" completion)))
1393 ;; Find in completion the longest text that was right before point.
1394 (when (string-match "\\(.+\\)\n.*?\\1" combined)
1395 (let* ((prefix (match-string 1 before))
1396 ;; We used non-greedy match to make `rem' as long as possible.
1397 (rem (substring combined (match-end 0)))
1398 ;; Find in the remainder of completion the longest text
1399 ;; that was right after point.
1400 (after (substring string point))
1401 (suffix (if (string-match "\\`\\(.+\\).*\n.*\\1"
1402 (concat after "\n" rem))
1403 (match-string 1 after))))
1404 ;; The general idea is to try and guess what text was inserted
1405 ;; at point by the completion. Problem is: if we guess wrong,
1406 ;; we may end up treating as "added by completion" text that was
1407 ;; actually painfully typed by the user. So if we then cut
1408 ;; after the first word, we may throw away things the
1409 ;; user wrote. So let's try to be as conservative as possible:
1410 ;; only cut after the first word, if we're reasonably sure that
1411 ;; our guess is correct.
1412 ;; Note: a quick survey on emacs-devel seemed to indicate that
1413 ;; nobody actually cares about the "word-at-a-time" feature of
1414 ;; minibuffer-complete-word, whose real raison-d'être is that it
1415 ;; tries to add "-" or " ". One more reason to only cut after
1416 ;; the first word, if we're really sure we're right.
1417 (when (and (or suffix (zerop (length after)))
1418 (string-match (concat
1419 ;; Make submatch 1 as small as possible
1420 ;; to reduce the risk of cutting
1421 ;; valuable text.
1422 ".*" (regexp-quote prefix) "\\(.*?\\)"
1423 (if suffix (regexp-quote suffix) "\\'"))
1424 completion)
1425 ;; The new point in `completion' should also be just
1426 ;; before the suffix, otherwise something more complex
1427 ;; is going on, and we're not sure where we are.
1428 (eq (match-end 1) comppoint)
1429 ;; (match-beginning 1)..comppoint is now the stretch
1430 ;; of text in `completion' that was completed at point.
1431 (string-match "\\W" completion (match-beginning 1))
1432 ;; Is there really something to cut?
1433 (> comppoint (match-end 0)))
1434 ;; Cut after the first word.
1435 (let ((cutpos (match-end 0)))
1436 (setq completion (concat (substring completion 0 cutpos)
1437 (substring completion comppoint)))
1438 (setq comppoint cutpos)))))
1439
1440 (cons completion comppoint)))))
1441
1442
1443 (defun minibuffer-complete-word ()
1444 "Complete the minibuffer contents at most a single word.
1445 After one word is completed as much as possible, a space or hyphen
1446 is added, provided that matches some possible completion.
1447 Return nil if there is no valid completion, else t."
1448 (interactive)
1449 (completion-in-region--single-word
1450 (minibuffer-prompt-end) (point-max)
1451 minibuffer-completion-table minibuffer-completion-predicate))
1452
1453 (defun completion-in-region--single-word (beg end collection
1454 &optional predicate)
1455 (let ((minibuffer-completion-table collection)
1456 (minibuffer-completion-predicate predicate))
1457 (pcase (completion--do-completion beg end
1458 #'completion--try-word-completion)
1459 (#b000 nil)
1460 (_ t))))
1461
1462 (defface completions-annotations '((t :inherit italic))
1463 "Face to use for annotations in the *Completions* buffer.")
1464
1465 (defcustom completions-format 'horizontal
1466 "Define the appearance and sorting of completions.
1467 If the value is `vertical', display completions sorted vertically
1468 in columns in the *Completions* buffer.
1469 If the value is `horizontal', display completions sorted
1470 horizontally in alphabetical order, rather than down the screen."
1471 :type '(choice (const horizontal) (const vertical))
1472 :version "23.2")
1473
1474 (defun completion--insert-strings (strings)
1475 "Insert a list of STRINGS into the current buffer.
1476 Uses columns to keep the listing readable but compact.
1477 It also eliminates runs of equal strings."
1478 (when (consp strings)
1479 (let* ((length (apply 'max
1480 (mapcar (lambda (s)
1481 (if (consp s)
1482 (+ (string-width (car s))
1483 (string-width (cadr s)))
1484 (string-width s)))
1485 strings)))
1486 (window (get-buffer-window (current-buffer) 0))
1487 (wwidth (if window (1- (window-width window)) 79))
1488 (columns (min
1489 ;; At least 2 columns; at least 2 spaces between columns.
1490 (max 2 (/ wwidth (+ 2 length)))
1491 ;; Don't allocate more columns than we can fill.
1492 ;; Windows can't show less than 3 lines anyway.
1493 (max 1 (/ (length strings) 2))))
1494 (colwidth (/ wwidth columns))
1495 (column 0)
1496 (rows (/ (length strings) columns))
1497 (row 0)
1498 (first t)
1499 (laststring nil))
1500 ;; The insertion should be "sensible" no matter what choices were made
1501 ;; for the parameters above.
1502 (dolist (str strings)
1503 (unless (equal laststring str) ; Remove (consecutive) duplicates.
1504 (setq laststring str)
1505 ;; FIXME: `string-width' doesn't pay attention to
1506 ;; `display' properties.
1507 (let ((length (if (consp str)
1508 (+ (string-width (car str))
1509 (string-width (cadr str)))
1510 (string-width str))))
1511 (cond
1512 ((eq completions-format 'vertical)
1513 ;; Vertical format
1514 (when (> row rows)
1515 (forward-line (- -1 rows))
1516 (setq row 0 column (+ column colwidth)))
1517 (when (> column 0)
1518 (end-of-line)
1519 (while (> (current-column) column)
1520 (if (eobp)
1521 (insert "\n")
1522 (forward-line 1)
1523 (end-of-line)))
1524 (insert " \t")
1525 (set-text-properties (1- (point)) (point)
1526 `(display (space :align-to ,column)))))
1527 (t
1528 ;; Horizontal format
1529 (unless first
1530 (if (< wwidth (+ (max colwidth length) column))
1531 ;; No space for `str' at point, move to next line.
1532 (progn (insert "\n") (setq column 0))
1533 (insert " \t")
1534 ;; Leave the space unpropertized so that in the case we're
1535 ;; already past the goal column, there is still
1536 ;; a space displayed.
1537 (set-text-properties (1- (point)) (point)
1538 ;; We can't just set tab-width, because
1539 ;; completion-setup-function will kill
1540 ;; all local variables :-(
1541 `(display (space :align-to ,column)))
1542 nil))))
1543 (setq first nil)
1544 (if (not (consp str))
1545 (put-text-property (point) (progn (insert str) (point))
1546 'mouse-face 'highlight)
1547 (put-text-property (point) (progn (insert (car str)) (point))
1548 'mouse-face 'highlight)
1549 (let ((beg (point))
1550 (end (progn (insert (cadr str)) (point))))
1551 (put-text-property beg end 'mouse-face nil)
1552 (font-lock-prepend-text-property beg end 'face
1553 'completions-annotations)))
1554 (cond
1555 ((eq completions-format 'vertical)
1556 ;; Vertical format
1557 (if (> column 0)
1558 (forward-line)
1559 (insert "\n"))
1560 (setq row (1+ row)))
1561 (t
1562 ;; Horizontal format
1563 ;; Next column to align to.
1564 (setq column (+ column
1565 ;; Round up to a whole number of columns.
1566 (* colwidth (ceiling length colwidth))))))))))))
1567
1568 (defvar completion-common-substring nil)
1569 (make-obsolete-variable 'completion-common-substring nil "23.1")
1570
1571 (defvar completion-setup-hook nil
1572 "Normal hook run at the end of setting up a completion list buffer.
1573 When this hook is run, the current buffer is the one in which the
1574 command to display the completion list buffer was run.
1575 The completion list buffer is available as the value of `standard-output'.
1576 See also `display-completion-list'.")
1577
1578 (defface completions-first-difference
1579 '((t (:inherit bold)))
1580 "Face for the first uncommon character in completions.
1581 See also the face `completions-common-part'.")
1582
1583 (defface completions-common-part '((t nil))
1584 "Face for the common prefix substring in completions.
1585 The idea of this face is that you can use it to make the common parts
1586 less visible than normal, so that the differing parts are emphasized
1587 by contrast.
1588 See also the face `completions-first-difference'.")
1589
1590 (defun completion-hilit-commonality (completions prefix-len &optional base-size)
1591 "Apply font-lock highlighting to a list of completions, COMPLETIONS.
1592 PREFIX-LEN is an integer. BASE-SIZE is an integer or nil (meaning zero).
1593
1594 This adds the face `completions-common-part' to the first
1595 \(PREFIX-LEN - BASE-SIZE) characters of each completion, and the face
1596 `completions-first-difference' to the first character after that.
1597
1598 It returns a list with font-lock properties applied to each element,
1599 and with BASE-SIZE appended as the last element."
1600 (when completions
1601 (let ((com-str-len (- prefix-len (or base-size 0))))
1602 (nconc
1603 (mapcar
1604 (lambda (elem)
1605 (let ((str
1606 ;; Don't modify the string itself, but a copy, since the
1607 ;; the string may be read-only or used for other purposes.
1608 ;; Furthermore, since `completions' may come from
1609 ;; display-completion-list, `elem' may be a list.
1610 (if (consp elem)
1611 (car (setq elem (cons (copy-sequence (car elem))
1612 (cdr elem))))
1613 (setq elem (copy-sequence elem)))))
1614 (font-lock-prepend-text-property
1615 0
1616 ;; If completion-boundaries returns incorrect
1617 ;; values, all-completions may return strings
1618 ;; that don't contain the prefix.
1619 (min com-str-len (length str))
1620 'face 'completions-common-part str)
1621 (if (> (length str) com-str-len)
1622 (font-lock-prepend-text-property com-str-len (1+ com-str-len)
1623 'face
1624 'completions-first-difference
1625 str)))
1626 elem)
1627 completions)
1628 base-size))))
1629
1630 (defun display-completion-list (completions &optional common-substring)
1631 "Display the list of completions, COMPLETIONS, using `standard-output'.
1632 Each element may be just a symbol or string
1633 or may be a list of two strings to be printed as if concatenated.
1634 If it is a list of two strings, the first is the actual completion
1635 alternative, the second serves as annotation.
1636 `standard-output' must be a buffer.
1637 The actual completion alternatives, as inserted, are given `mouse-face'
1638 properties of `highlight'.
1639 At the end, this runs the normal hook `completion-setup-hook'.
1640 It can find the completion buffer in `standard-output'."
1641 (declare (advertised-calling-convention (completions) "24.4"))
1642 (if common-substring
1643 (setq completions (completion-hilit-commonality
1644 completions (length common-substring)
1645 ;; We don't know the base-size.
1646 nil)))
1647 (if (not (bufferp standard-output))
1648 ;; This *never* (ever) happens, so there's no point trying to be clever.
1649 (with-temp-buffer
1650 (let ((standard-output (current-buffer))
1651 (completion-setup-hook nil))
1652 (display-completion-list completions common-substring))
1653 (princ (buffer-string)))
1654
1655 (with-current-buffer standard-output
1656 (goto-char (point-max))
1657 (if (null completions)
1658 (insert "There are no possible completions of what you have typed.")
1659 (insert "Possible completions are:\n")
1660 (completion--insert-strings completions))))
1661
1662 ;; The hilit used to be applied via completion-setup-hook, so there
1663 ;; may still be some code that uses completion-common-substring.
1664 (with-no-warnings
1665 (let ((completion-common-substring common-substring))
1666 (run-hooks 'completion-setup-hook)))
1667 nil)
1668
1669 (defvar completion-extra-properties nil
1670 "Property list of extra properties of the current completion job.
1671 These include:
1672
1673 `:annotation-function': Function to annotate the completions buffer.
1674 The function must accept one argument, a completion string,
1675 and return either nil or a string which is to be displayed
1676 next to the completion (but which is not part of the
1677 completion). The function can access the completion data via
1678 `minibuffer-completion-table' and related variables.
1679
1680 `:exit-function': Function to run after completion is performed.
1681
1682 The function must accept two arguments, STRING and STATUS.
1683 STRING is the text to which the field was completed, and
1684 STATUS indicates what kind of operation happened:
1685 `finished' - text is now complete
1686 `sole' - text cannot be further completed but
1687 completion is not finished
1688 `exact' - text is a valid completion but may be further
1689 completed.")
1690
1691 (defvar completion-annotate-function
1692 nil
1693 ;; Note: there's a lot of scope as for when to add annotations and
1694 ;; what annotations to add. E.g. completing-help.el allowed adding
1695 ;; the first line of docstrings to M-x completion. But there's
1696 ;; a tension, since such annotations, while useful at times, can
1697 ;; actually drown the useful information.
1698 ;; So completion-annotate-function should be used parsimoniously, or
1699 ;; else only used upon a user's request (e.g. we could add a command
1700 ;; to completion-list-mode to add annotations to the current
1701 ;; completions).
1702 "Function to add annotations in the *Completions* buffer.
1703 The function takes a completion and should either return nil, or a string that
1704 will be displayed next to the completion. The function can access the
1705 completion table and predicates via `minibuffer-completion-table' and related
1706 variables.")
1707 (make-obsolete-variable 'completion-annotate-function
1708 'completion-extra-properties "24.1")
1709
1710 (defun completion--done (string &optional finished message)
1711 (let* ((exit-fun (plist-get completion-extra-properties :exit-function))
1712 (pre-msg (and exit-fun (current-message))))
1713 (cl-assert (memq finished '(exact sole finished unknown)))
1714 (when exit-fun
1715 (when (eq finished 'unknown)
1716 (setq finished
1717 (if (eq (try-completion string
1718 minibuffer-completion-table
1719 minibuffer-completion-predicate)
1720 t)
1721 'finished 'exact)))
1722 (funcall exit-fun string finished))
1723 (when (and message
1724 ;; Don't output any message if the exit-fun already did so.
1725 (equal pre-msg (and exit-fun (current-message))))
1726 (completion--message message))))
1727
1728 (defun minibuffer-completion-help (&optional start end)
1729 "Display a list of possible completions of the current minibuffer contents."
1730 (interactive)
1731 (message "Making completion list...")
1732 (let* ((start (or start (minibuffer-prompt-end)))
1733 (end (or end (point-max)))
1734 (string (buffer-substring start end))
1735 (md (completion--field-metadata start))
1736 (completions (completion-all-completions
1737 string
1738 minibuffer-completion-table
1739 minibuffer-completion-predicate
1740 (- (point) start)
1741 md)))
1742 (message nil)
1743 (if (or (null completions)
1744 (and (not (consp (cdr completions)))
1745 (equal (car completions) string)))
1746 (progn
1747 ;; If there are no completions, or if the current input is already
1748 ;; the sole completion, then hide (previous&stale) completions.
1749 (minibuffer-hide-completions)
1750 (ding)
1751 (minibuffer-message
1752 (if completions "Sole completion" "No completions")))
1753
1754 (let* ((last (last completions))
1755 (base-size (cdr last))
1756 (prefix (unless (zerop base-size) (substring string 0 base-size)))
1757 (all-md (completion--metadata (buffer-substring-no-properties
1758 start (point))
1759 base-size md
1760 minibuffer-completion-table
1761 minibuffer-completion-predicate))
1762 (afun (or (completion-metadata-get all-md 'annotation-function)
1763 (plist-get completion-extra-properties
1764 :annotation-function)
1765 completion-annotate-function))
1766 ;; If the *Completions* buffer is shown in a new
1767 ;; window, mark it as softly-dedicated, so bury-buffer in
1768 ;; minibuffer-hide-completions will know whether to
1769 ;; delete the window or not.
1770 (display-buffer-mark-dedicated 'soft))
1771 (with-output-to-temp-buffer "*Completions*"
1772 ;; Remove the base-size tail because `sort' requires a properly
1773 ;; nil-terminated list.
1774 (when last (setcdr last nil))
1775 (setq completions
1776 ;; FIXME: This function is for the output of all-completions,
1777 ;; not completion-all-completions. Often it's the same, but
1778 ;; not always.
1779 (let ((sort-fun (completion-metadata-get
1780 all-md 'display-sort-function)))
1781 (if sort-fun
1782 (funcall sort-fun completions)
1783 (sort completions 'string-lessp))))
1784 (when afun
1785 (setq completions
1786 (mapcar (lambda (s)
1787 (let ((ann (funcall afun s)))
1788 (if ann (list s ann) s)))
1789 completions)))
1790
1791 (with-current-buffer standard-output
1792 (set (make-local-variable 'completion-base-position)
1793 (list (+ start base-size)
1794 ;; FIXME: We should pay attention to completion
1795 ;; boundaries here, but currently
1796 ;; completion-all-completions does not give us the
1797 ;; necessary information.
1798 end))
1799 (set (make-local-variable 'completion-list-insert-choice-function)
1800 (let ((ctable minibuffer-completion-table)
1801 (cpred minibuffer-completion-predicate)
1802 (cprops completion-extra-properties))
1803 (lambda (start end choice)
1804 (unless (or (zerop (length prefix))
1805 (equal prefix
1806 (buffer-substring-no-properties
1807 (max (point-min)
1808 (- start (length prefix)))
1809 start)))
1810 (message "*Completions* out of date"))
1811 ;; FIXME: Use `md' to do quoting&terminator here.
1812 (completion--replace start end choice)
1813 (let* ((minibuffer-completion-table ctable)
1814 (minibuffer-completion-predicate cpred)
1815 (completion-extra-properties cprops)
1816 (result (concat prefix choice))
1817 (bounds (completion-boundaries
1818 result ctable cpred "")))
1819 ;; If the completion introduces a new field, then
1820 ;; completion is not finished.
1821 (completion--done result
1822 (if (eq (car bounds) (length result))
1823 'exact 'finished)))))))
1824
1825 (display-completion-list completions))))
1826 nil))
1827
1828 (defun minibuffer-hide-completions ()
1829 "Get rid of an out-of-date *Completions* buffer."
1830 ;; FIXME: We could/should use minibuffer-scroll-window here, but it
1831 ;; can also point to the minibuffer-parent-window, so it's a bit tricky.
1832 (let ((win (get-buffer-window "*Completions*" 0)))
1833 (if win (with-selected-window win (bury-buffer)))))
1834
1835 (defun exit-minibuffer ()
1836 "Terminate this minibuffer argument."
1837 (interactive)
1838 ;; If the command that uses this has made modifications in the minibuffer,
1839 ;; we don't want them to cause deactivation of the mark in the original
1840 ;; buffer.
1841 ;; A better solution would be to make deactivate-mark buffer-local
1842 ;; (or to turn it into a list of buffers, ...), but in the mean time,
1843 ;; this should do the trick in most cases.
1844 (setq deactivate-mark nil)
1845 (throw 'exit nil))
1846
1847 (defun self-insert-and-exit ()
1848 "Terminate minibuffer input."
1849 (interactive)
1850 (if (characterp last-command-event)
1851 (call-interactively 'self-insert-command)
1852 (ding))
1853 (exit-minibuffer))
1854
1855 (defvar completion-in-region-functions nil
1856 "Wrapper hook around `completion-in-region'.")
1857 (make-obsolete-variable 'completion-in-region-functions
1858 'completion-in-region-function "24.4")
1859
1860 (defvar completion-in-region-function #'completion--in-region
1861 "Function to perform the job of `completion-in-region'.
1862 The function is called with 4 arguments: START END COLLECTION PREDICATE.
1863 The arguments and expected return value are like the ones of
1864 `completion-in-region'.")
1865
1866 (defvar completion-in-region--data nil)
1867
1868 (defvar completion-in-region-mode-predicate nil
1869 "Predicate to tell `completion-in-region-mode' when to exit.
1870 It is called with no argument and should return nil when
1871 `completion-in-region-mode' should exit (and hence pop down
1872 the *Completions* buffer).")
1873
1874 (defvar completion-in-region-mode--predicate nil
1875 "Copy of the value of `completion-in-region-mode-predicate'.
1876 This holds the value `completion-in-region-mode-predicate' had when
1877 we entered `completion-in-region-mode'.")
1878
1879 (defun completion-in-region (start end collection &optional predicate)
1880 "Complete the text between START and END using COLLECTION.
1881 Return nil if there is no valid completion, else t.
1882 Point needs to be somewhere between START and END.
1883 PREDICATE (a function called with no arguments) says when to
1884 exit."
1885 (cl-assert (<= start (point)) (<= (point) end))
1886 (funcall completion-in-region-function start end collection predicate))
1887
1888 (defcustom read-file-name-completion-ignore-case
1889 (if (memq system-type '(ms-dos windows-nt darwin cygwin))
1890 t nil)
1891 "Non-nil means when reading a file name completion ignores case."
1892 :type 'boolean
1893 :version "22.1")
1894
1895 (defun completion--in-region (start end collection &optional predicate)
1896 (with-wrapper-hook
1897 ;; FIXME: Maybe we should use this hook to provide a "display
1898 ;; completions" operation as well.
1899 completion-in-region-functions (start end collection predicate)
1900 (let ((minibuffer-completion-table collection)
1901 (minibuffer-completion-predicate predicate))
1902 ;; HACK: if the text we are completing is already in a field, we
1903 ;; want the completion field to take priority (e.g. Bug#6830).
1904 (when completion-in-region-mode-predicate
1905 (setq completion-in-region--data
1906 `(,(if (markerp start) start (copy-marker start))
1907 ,(copy-marker end t) ,collection ,predicate))
1908 (completion-in-region-mode 1))
1909 (completion--in-region-1 start end))))
1910
1911 (defvar completion-in-region-mode-map
1912 (let ((map (make-sparse-keymap)))
1913 ;; FIXME: Only works if completion-in-region-mode was activated via
1914 ;; completion-at-point called directly.
1915 (define-key map "\M-?" 'completion-help-at-point)
1916 (define-key map "\t" 'completion-at-point)
1917 map)
1918 "Keymap activated during `completion-in-region'.")
1919
1920 ;; It is difficult to know when to exit completion-in-region-mode (i.e. hide
1921 ;; the *Completions*).
1922 ;; - lisp-mode: never.
1923 ;; - comint: only do it if you hit SPC at the right time.
1924 ;; - pcomplete: pop it down on SPC or after some time-delay.
1925 ;; - semantic: use a post-command-hook check similar to this one.
1926 (defun completion-in-region--postch ()
1927 (or unread-command-events ;Don't pop down the completions in the middle of
1928 ;mouse-drag-region/mouse-set-point.
1929 (and completion-in-region--data
1930 (and (eq (marker-buffer (nth 0 completion-in-region--data))
1931 (current-buffer))
1932 (>= (point) (nth 0 completion-in-region--data))
1933 (<= (point)
1934 (save-excursion
1935 (goto-char (nth 1 completion-in-region--data))
1936 (line-end-position)))
1937 (funcall completion-in-region-mode--predicate)))
1938 (completion-in-region-mode -1)))
1939
1940 ;; (defalias 'completion-in-region--prech 'completion-in-region--postch)
1941
1942 (defvar completion-in-region-mode nil) ;Explicit defvar, i.s.o defcustom.
1943
1944 (define-minor-mode completion-in-region-mode
1945 "Transient minor mode used during `completion-in-region'."
1946 :global t
1947 :group 'minibuffer
1948 ;; Prevent definition of a custom-variable since it makes no sense to
1949 ;; customize this variable.
1950 :variable completion-in-region-mode
1951 ;; (remove-hook 'pre-command-hook #'completion-in-region--prech)
1952 (remove-hook 'post-command-hook #'completion-in-region--postch)
1953 (setq minor-mode-overriding-map-alist
1954 (delq (assq 'completion-in-region-mode minor-mode-overriding-map-alist)
1955 minor-mode-overriding-map-alist))
1956 (if (null completion-in-region-mode)
1957 (progn
1958 (setq completion-in-region--data nil)
1959 (unless (equal "*Completions*" (buffer-name (window-buffer)))
1960 (minibuffer-hide-completions)))
1961 ;; (add-hook 'pre-command-hook #'completion-in-region--prech)
1962 (cl-assert completion-in-region-mode-predicate)
1963 (setq completion-in-region-mode--predicate
1964 completion-in-region-mode-predicate)
1965 (add-hook 'post-command-hook #'completion-in-region--postch)
1966 (push `(completion-in-region-mode . ,completion-in-region-mode-map)
1967 minor-mode-overriding-map-alist)))
1968
1969 ;; Define-minor-mode added our keymap to minor-mode-map-alist, but we want it
1970 ;; on minor-mode-overriding-map-alist instead.
1971 (setq minor-mode-map-alist
1972 (delq (assq 'completion-in-region-mode minor-mode-map-alist)
1973 minor-mode-map-alist))
1974
1975 (defvar completion-at-point-functions '(tags-completion-at-point-function)
1976 "Special hook to find the completion table for the thing at point.
1977 Each function on this hook is called in turns without any argument and should
1978 return either nil to mean that it is not applicable at point,
1979 or a function of no argument to perform completion (discouraged),
1980 or a list of the form (START END COLLECTION . PROPS) where
1981 START and END delimit the entity to complete and should include point,
1982 COLLECTION is the completion table to use to complete it, and
1983 PROPS is a property list for additional information.
1984 Currently supported properties are all the properties that can appear in
1985 `completion-extra-properties' plus:
1986 `:predicate' a predicate that completion candidates need to satisfy.
1987 `:exclusive' If `no', means that if the completion table fails to
1988 match the text at point, then instead of reporting a completion
1989 failure, the completion should try the next completion function.
1990 As is the case with most hooks, the functions are responsible to preserve
1991 things like point and current buffer.")
1992
1993 (defvar completion--capf-misbehave-funs nil
1994 "List of functions found on `completion-at-point-functions' that misbehave.
1995 These are functions that neither return completion data nor a completion
1996 function but instead perform completion right away.")
1997 (defvar completion--capf-safe-funs nil
1998 "List of well-behaved functions found on `completion-at-point-functions'.
1999 These are functions which return proper completion data rather than
2000 a completion function or god knows what else.")
2001
2002 (defun completion--capf-wrapper (fun which)
2003 ;; FIXME: The safe/misbehave handling assumes that a given function will
2004 ;; always return the same kind of data, but this breaks down with functions
2005 ;; like comint-completion-at-point or mh-letter-completion-at-point, which
2006 ;; could be sometimes safe and sometimes misbehaving (and sometimes neither).
2007 (if (pcase which
2008 (`all t)
2009 (`safe (member fun completion--capf-safe-funs))
2010 (`optimist (not (member fun completion--capf-misbehave-funs))))
2011 (let ((res (funcall fun)))
2012 (cond
2013 ((and (consp res) (not (functionp res)))
2014 (unless (member fun completion--capf-safe-funs)
2015 (push fun completion--capf-safe-funs))
2016 (and (eq 'no (plist-get (nthcdr 3 res) :exclusive))
2017 ;; FIXME: Here we'd need to decide whether there are
2018 ;; valid completions against the current text. But this depends
2019 ;; on the actual completion UI (e.g. with the default completion
2020 ;; it depends on completion-style) ;-(
2021 ;; We approximate this result by checking whether prefix
2022 ;; completion might work, which means that non-prefix completion
2023 ;; will not work (or not right) for completion functions that
2024 ;; are non-exclusive.
2025 (null (try-completion (buffer-substring-no-properties
2026 (car res) (point))
2027 (nth 2 res)
2028 (plist-get (nthcdr 3 res) :predicate)))
2029 (setq res nil)))
2030 ((not (or (listp res) (functionp res)))
2031 (unless (member fun completion--capf-misbehave-funs)
2032 (message
2033 "Completion function %S uses a deprecated calling convention" fun)
2034 (push fun completion--capf-misbehave-funs))))
2035 (if res (cons fun res)))))
2036
2037 (defun completion-at-point ()
2038 "Perform completion on the text around point.
2039 The completion method is determined by `completion-at-point-functions'."
2040 (interactive)
2041 (let ((res (run-hook-wrapped 'completion-at-point-functions
2042 #'completion--capf-wrapper 'all)))
2043 (pcase res
2044 (`(,_ . ,(and (pred functionp) f)) (funcall f))
2045 (`(,hookfun . (,start ,end ,collection . ,plist))
2046 (unless (markerp start) (setq start (copy-marker start)))
2047 (let* ((completion-extra-properties plist)
2048 (completion-in-region-mode-predicate
2049 (lambda ()
2050 ;; We're still in the same completion field.
2051 (let ((newstart (car-safe (funcall hookfun))))
2052 (and newstart (= newstart start))))))
2053 (completion-in-region start end collection
2054 (plist-get plist :predicate))))
2055 ;; Maybe completion already happened and the function returned t.
2056 (_ (cdr res)))))
2057
2058 (defun completion-help-at-point ()
2059 "Display the completions on the text around point.
2060 The completion method is determined by `completion-at-point-functions'."
2061 (interactive)
2062 (let ((res (run-hook-wrapped 'completion-at-point-functions
2063 ;; Ignore misbehaving functions.
2064 #'completion--capf-wrapper 'optimist)))
2065 (pcase res
2066 (`(,_ . ,(and (pred functionp) f))
2067 (message "Don't know how to show completions for %S" f))
2068 (`(,hookfun . (,start ,end ,collection . ,plist))
2069 (unless (markerp start) (setq start (copy-marker start)))
2070 (let* ((minibuffer-completion-table collection)
2071 (minibuffer-completion-predicate (plist-get plist :predicate))
2072 (completion-extra-properties plist)
2073 (completion-in-region-mode-predicate
2074 (lambda ()
2075 ;; We're still in the same completion field.
2076 (let ((newstart (car-safe (funcall hookfun))))
2077 (and newstart (= newstart start))))))
2078 ;; FIXME: We should somehow (ab)use completion-in-region-function or
2079 ;; introduce a corresponding hook (plus another for word-completion,
2080 ;; and another for force-completion, maybe?).
2081 (setq completion-in-region--data
2082 `(,start ,(copy-marker end t) ,collection
2083 ,(plist-get plist :predicate)))
2084 (completion-in-region-mode 1)
2085 (minibuffer-completion-help start end)))
2086 (`(,hookfun . ,_)
2087 ;; The hook function already performed completion :-(
2088 ;; Not much we can do at this point.
2089 (message "%s already performed completion!" hookfun)
2090 nil)
2091 (_ (message "Nothing to complete at point")))))
2092
2093 ;;; Key bindings.
2094
2095 (let ((map minibuffer-local-map))
2096 (define-key map "\C-g" 'abort-recursive-edit)
2097 (define-key map "\r" 'exit-minibuffer)
2098 (define-key map "\n" 'exit-minibuffer))
2099
2100 (defvar minibuffer-local-completion-map
2101 (let ((map (make-sparse-keymap)))
2102 (set-keymap-parent map minibuffer-local-map)
2103 (define-key map "\t" 'minibuffer-complete)
2104 ;; M-TAB is already abused for many other purposes, so we should find
2105 ;; another binding for it.
2106 ;; (define-key map "\e\t" 'minibuffer-force-complete)
2107 (define-key map " " 'minibuffer-complete-word)
2108 (define-key map "?" 'minibuffer-completion-help)
2109 map)
2110 "Local keymap for minibuffer input with completion.")
2111
2112 (defvar minibuffer-local-must-match-map
2113 (let ((map (make-sparse-keymap)))
2114 (set-keymap-parent map minibuffer-local-completion-map)
2115 (define-key map "\r" 'minibuffer-complete-and-exit)
2116 (define-key map "\n" 'minibuffer-complete-and-exit)
2117 map)
2118 "Local keymap for minibuffer input with completion, for exact match.")
2119
2120 (defvar minibuffer-local-filename-completion-map
2121 (let ((map (make-sparse-keymap)))
2122 (define-key map " " nil)
2123 map)
2124 "Local keymap for minibuffer input with completion for filenames.
2125 Gets combined either with `minibuffer-local-completion-map' or
2126 with `minibuffer-local-must-match-map'.")
2127
2128 (define-obsolete-variable-alias 'minibuffer-local-must-match-filename-map
2129 'minibuffer-local-filename-must-match-map "23.1")
2130 (defvar minibuffer-local-filename-must-match-map (make-sparse-keymap))
2131 (make-obsolete-variable 'minibuffer-local-filename-must-match-map nil "24.1")
2132
2133 (let ((map minibuffer-local-ns-map))
2134 (define-key map " " 'exit-minibuffer)
2135 (define-key map "\t" 'exit-minibuffer)
2136 (define-key map "?" 'self-insert-and-exit))
2137
2138 (defvar minibuffer-inactive-mode-map
2139 (let ((map (make-keymap)))
2140 (suppress-keymap map)
2141 (define-key map "e" 'find-file-other-frame)
2142 (define-key map "f" 'find-file-other-frame)
2143 (define-key map "b" 'switch-to-buffer-other-frame)
2144 (define-key map "i" 'info)
2145 (define-key map "m" 'mail)
2146 (define-key map "n" 'make-frame)
2147 (define-key map [mouse-1] 'view-echo-area-messages)
2148 ;; So the global down-mouse-1 binding doesn't clutter the execution of the
2149 ;; above mouse-1 binding.
2150 (define-key map [down-mouse-1] #'ignore)
2151 map)
2152 "Keymap for use in the minibuffer when it is not active.
2153 The non-mouse bindings in this keymap can only be used in minibuffer-only
2154 frames, since the minibuffer can normally not be selected when it is
2155 not active.")
2156
2157 (define-derived-mode minibuffer-inactive-mode nil "InactiveMinibuffer"
2158 :abbrev-table nil ;abbrev.el is not loaded yet during dump.
2159 ;; Note: this major mode is called from minibuf.c.
2160 "Major mode to use in the minibuffer when it is not active.
2161 This is only used when the minibuffer area has no active minibuffer.")
2162
2163 ;;; Completion tables.
2164
2165 (defun minibuffer--double-dollars (str)
2166 ;; Reuse the actual "$" from the string to preserve any text-property it
2167 ;; might have, such as `face'.
2168 (replace-regexp-in-string "\\$" (lambda (dollar) (concat dollar dollar))
2169 str))
2170
2171 (defun completion--make-envvar-table ()
2172 (mapcar (lambda (enventry)
2173 (substring enventry 0 (string-match-p "=" enventry)))
2174 process-environment))
2175
2176 (defconst completion--embedded-envvar-re
2177 ;; We can't reuse env--substitute-vars-regexp because we need to match only
2178 ;; potentially-unfinished envvars at end of string.
2179 (concat "\\(?:^\\|[^$]\\(?:\\$\\$\\)*\\)"
2180 "$\\([[:alnum:]_]*\\|{\\([^}]*\\)\\)\\'"))
2181
2182 (defun completion--embedded-envvar-table (string _pred action)
2183 "Completion table for envvars embedded in a string.
2184 The envvar syntax (and escaping) rules followed by this table are the
2185 same as `substitute-in-file-name'."
2186 ;; We ignore `pred', because the predicates passed to us via
2187 ;; read-file-name-internal are not 100% correct and fail here:
2188 ;; e.g. we get predicates like file-directory-p there, whereas the filename
2189 ;; completed needs to be passed through substitute-in-file-name before it
2190 ;; can be passed to file-directory-p.
2191 (when (string-match completion--embedded-envvar-re string)
2192 (let* ((beg (or (match-beginning 2) (match-beginning 1)))
2193 (table (completion--make-envvar-table))
2194 (prefix (substring string 0 beg)))
2195 (cond
2196 ((eq action 'lambda)
2197 ;; This table is expected to be used in conjunction with some
2198 ;; other table that provides the "main" completion. Let the
2199 ;; other table handle the test-completion case.
2200 nil)
2201 ((or (eq (car-safe action) 'boundaries) (eq action 'metadata))
2202 ;; Only return boundaries/metadata if there's something to complete,
2203 ;; since otherwise when we're used in
2204 ;; completion-table-in-turn, we could return boundaries and
2205 ;; let some subsequent table return a list of completions.
2206 ;; FIXME: Maybe it should rather be fixed in
2207 ;; completion-table-in-turn instead, but it's difficult to
2208 ;; do it efficiently there.
2209 (when (try-completion (substring string beg) table nil)
2210 ;; Compute the boundaries of the subfield to which this
2211 ;; completion applies.
2212 (if (eq action 'metadata)
2213 '(metadata (category . environment-variable))
2214 (let ((suffix (cdr action)))
2215 `(boundaries
2216 ,(or (match-beginning 2) (match-beginning 1))
2217 . ,(when (string-match "[^[:alnum:]_]" suffix)
2218 (match-beginning 0)))))))
2219 (t
2220 (if (eq (aref string (1- beg)) ?{)
2221 (setq table (apply-partially 'completion-table-with-terminator
2222 "}" table)))
2223 ;; Even if file-name completion is case-insensitive, we want
2224 ;; envvar completion to be case-sensitive.
2225 (let ((completion-ignore-case nil))
2226 (completion-table-with-context
2227 prefix table (substring string beg) nil action)))))))
2228
2229 (defun completion-file-name-table (string pred action)
2230 "Completion table for file names."
2231 (condition-case nil
2232 (cond
2233 ((eq action 'metadata) '(metadata (category . file)))
2234 ((string-match-p "\\`~[^/\\]*\\'" string)
2235 (completion-table-with-context "~"
2236 (mapcar (lambda (u) (concat u "/"))
2237 (system-users))
2238 (substring string 1)
2239 pred action))
2240 ((eq (car-safe action) 'boundaries)
2241 (let ((start (length (file-name-directory string)))
2242 (end (string-match-p "/" (cdr action))))
2243 `(boundaries
2244 ;; if `string' is "C:" in w32, (file-name-directory string)
2245 ;; returns "C:/", so `start' is 3 rather than 2.
2246 ;; Not quite sure what is The Right Fix, but clipping it
2247 ;; back to 2 will work for this particular case. We'll
2248 ;; see if we can come up with a better fix when we bump
2249 ;; into more such problematic cases.
2250 ,(min start (length string)) . ,end)))
2251
2252 ((eq action 'lambda)
2253 (if (zerop (length string))
2254 nil ;Not sure why it's here, but it probably doesn't harm.
2255 (funcall (or pred 'file-exists-p) string)))
2256
2257 (t
2258 (let* ((name (file-name-nondirectory string))
2259 (specdir (file-name-directory string))
2260 (realdir (or specdir default-directory)))
2261
2262 (cond
2263 ((null action)
2264 (let ((comp (file-name-completion name realdir pred)))
2265 (if (stringp comp)
2266 (concat specdir comp)
2267 comp)))
2268
2269 ((eq action t)
2270 (let ((all (file-name-all-completions name realdir)))
2271
2272 ;; Check the predicate, if necessary.
2273 (unless (memq pred '(nil file-exists-p))
2274 (let ((comp ())
2275 (pred
2276 (if (eq pred 'file-directory-p)
2277 ;; Brute-force speed up for directory checking:
2278 ;; Discard strings which don't end in a slash.
2279 (lambda (s)
2280 (let ((len (length s)))
2281 (and (> len 0) (eq (aref s (1- len)) ?/))))
2282 ;; Must do it the hard (and slow) way.
2283 pred)))
2284 (let ((default-directory (expand-file-name realdir)))
2285 (dolist (tem all)
2286 (if (funcall pred tem) (push tem comp))))
2287 (setq all (nreverse comp))))
2288
2289 all))))))
2290 (file-error nil))) ;PCM often calls with invalid directories.
2291
2292 (defvar read-file-name-predicate nil
2293 "Current predicate used by `read-file-name-internal'.")
2294 (make-obsolete-variable 'read-file-name-predicate
2295 "use the regular PRED argument" "23.2")
2296
2297 (defun completion--sifn-requote (upos qstr)
2298 ;; We're looking for `qpos' such that:
2299 ;; (equal (substring (substitute-in-file-name qstr) 0 upos)
2300 ;; (substitute-in-file-name (substring qstr 0 qpos)))
2301 ;; Big problem here: we have to reverse engineer substitute-in-file-name to
2302 ;; find the position corresponding to UPOS in QSTR, but
2303 ;; substitute-in-file-name can do anything, depending on file-name-handlers.
2304 ;; substitute-in-file-name does the following kind of things:
2305 ;; - expand env-var references.
2306 ;; - turn backslashes into slashes.
2307 ;; - truncate some prefix of the input.
2308 ;; - rewrite some prefix.
2309 ;; Some of these operations are written in external libraries and we'd rather
2310 ;; not hard code any assumptions here about what they actually do. IOW, we
2311 ;; want to treat substitute-in-file-name as a black box, as much as possible.
2312 ;; Kind of like in rfn-eshadow-update-overlay, only worse.
2313 ;; Example of things we need to handle:
2314 ;; - Tramp (substitute-in-file-name "/foo:~/bar//baz") => "/scpc:foo:/baz".
2315 ;; - Cygwin (substitute-in-file-name "C:\bin") => "/usr/bin"
2316 ;; (substitute-in-file-name "C:\") => "/"
2317 ;; (substitute-in-file-name "C:\bi") => "/bi"
2318 (let* ((ustr (substitute-in-file-name qstr))
2319 (uprefix (substring ustr 0 upos))
2320 qprefix)
2321 ;; Main assumption: nothing after qpos should affect the text before upos,
2322 ;; so we can work our way backward from the end of qstr, one character
2323 ;; at a time.
2324 ;; Second assumptions: If qpos is far from the end this can be a bit slow,
2325 ;; so we speed it up by doing a first loop that skips a word at a time.
2326 ;; This word-sized loop is careful not to cut in the middle of env-vars.
2327 (while (let ((boundary (string-match "\\(\\$+{?\\)?\\w+\\W*\\'" qstr)))
2328 (and boundary
2329 (progn
2330 (setq qprefix (substring qstr 0 boundary))
2331 (string-prefix-p uprefix
2332 (substitute-in-file-name qprefix)))))
2333 (setq qstr qprefix))
2334 (let ((qpos (length qstr)))
2335 (while (and (> qpos 0)
2336 (string-prefix-p uprefix
2337 (substitute-in-file-name
2338 (substring qstr 0 (1- qpos)))))
2339 (setq qpos (1- qpos)))
2340 (cons qpos #'minibuffer--double-dollars))))
2341
2342 (defalias 'completion--file-name-table
2343 (completion-table-with-quoting #'completion-file-name-table
2344 #'substitute-in-file-name
2345 #'completion--sifn-requote)
2346 "Internal subroutine for `read-file-name'. Do not call this.
2347 This is a completion table for file names, like `completion-file-name-table'
2348 except that it passes the file name through `substitute-in-file-name'.")
2349
2350 (defalias 'read-file-name-internal
2351 (completion-table-in-turn #'completion--embedded-envvar-table
2352 #'completion--file-name-table)
2353 "Internal subroutine for `read-file-name'. Do not call this.")
2354
2355 (defvar read-file-name-function 'read-file-name-default
2356 "The function called by `read-file-name' to do its work.
2357 It should accept the same arguments as `read-file-name'.")
2358
2359 (defcustom insert-default-directory t
2360 "Non-nil means when reading a filename start with default dir in minibuffer.
2361
2362 When the initial minibuffer contents show a name of a file or a directory,
2363 typing RETURN without editing the initial contents is equivalent to typing
2364 the default file name.
2365
2366 If this variable is non-nil, the minibuffer contents are always
2367 initially non-empty, and typing RETURN without editing will fetch the
2368 default name, if one is provided. Note however that this default name
2369 is not necessarily the same as initial contents inserted in the minibuffer,
2370 if the initial contents is just the default directory.
2371
2372 If this variable is nil, the minibuffer often starts out empty. In
2373 that case you may have to explicitly fetch the next history element to
2374 request the default name; typing RETURN without editing will leave
2375 the minibuffer empty.
2376
2377 For some commands, exiting with an empty minibuffer has a special meaning,
2378 such as making the current buffer visit no file in the case of
2379 `set-visited-file-name'."
2380 :type 'boolean)
2381
2382 ;; Not always defined, but only called if next-read-file-uses-dialog-p says so.
2383 (declare-function x-file-dialog "xfns.c"
2384 (prompt dir &optional default-filename mustmatch only-dir-p))
2385
2386 (defun read-file-name--defaults (&optional dir initial)
2387 (let ((default
2388 (cond
2389 ;; With non-nil `initial', use `dir' as the first default.
2390 ;; Essentially, this mean reversing the normal order of the
2391 ;; current directory name and the current file name, i.e.
2392 ;; 1. with normal file reading:
2393 ;; 1.1. initial input is the current directory
2394 ;; 1.2. the first default is the current file name
2395 ;; 2. with non-nil `initial' (e.g. for `find-alternate-file'):
2396 ;; 2.2. initial input is the current file name
2397 ;; 2.1. the first default is the current directory
2398 (initial (abbreviate-file-name dir))
2399 ;; In file buffers, try to get the current file name
2400 (buffer-file-name
2401 (abbreviate-file-name buffer-file-name))))
2402 (file-name-at-point
2403 (run-hook-with-args-until-success 'file-name-at-point-functions)))
2404 (when file-name-at-point
2405 (setq default (delete-dups
2406 (delete "" (delq nil (list file-name-at-point default))))))
2407 ;; Append new defaults to the end of existing `minibuffer-default'.
2408 (append
2409 (if (listp minibuffer-default) minibuffer-default (list minibuffer-default))
2410 (if (listp default) default (list default)))))
2411
2412 (defun read-file-name (prompt &optional dir default-filename mustmatch initial predicate)
2413 "Read file name, prompting with PROMPT and completing in directory DIR.
2414 The return value is not expanded---you must call `expand-file-name' yourself.
2415
2416 DIR is the directory to use for completing relative file names.
2417 It should be an absolute directory name, or nil (which means the
2418 current buffer's value of `default-directory').
2419
2420 DEFAULT-FILENAME specifies the default file name to return if the
2421 user exits the minibuffer with the same non-empty string inserted
2422 by this function. If DEFAULT-FILENAME is a string, that serves
2423 as the default. If DEFAULT-FILENAME is a list of strings, the
2424 first string is the default. If DEFAULT-FILENAME is omitted or
2425 nil, then if INITIAL is non-nil, the default is DIR combined with
2426 INITIAL; otherwise, if the current buffer is visiting a file,
2427 that file serves as the default; otherwise, the default is simply
2428 the string inserted into the minibuffer.
2429
2430 If the user exits with an empty minibuffer, return an empty
2431 string. (This happens only if the user erases the pre-inserted
2432 contents, or if `insert-default-directory' is nil.)
2433
2434 Fourth arg MUSTMATCH can take the following values:
2435 - nil means that the user can exit with any input.
2436 - t means that the user is not allowed to exit unless
2437 the input is (or completes to) an existing file.
2438 - `confirm' means that the user can exit with any input, but she needs
2439 to confirm her choice if the input is not an existing file.
2440 - `confirm-after-completion' means that the user can exit with any
2441 input, but she needs to confirm her choice if she called
2442 `minibuffer-complete' right before `minibuffer-complete-and-exit'
2443 and the input is not an existing file.
2444 - anything else behaves like t except that typing RET does not exit if it
2445 does non-null completion.
2446
2447 Fifth arg INITIAL specifies text to start with.
2448
2449 Sixth arg PREDICATE, if non-nil, should be a function of one
2450 argument; then a file name is considered an acceptable completion
2451 alternative only if PREDICATE returns non-nil with the file name
2452 as its argument.
2453
2454 If this command was invoked with the mouse, use a graphical file
2455 dialog if `use-dialog-box' is non-nil, and the window system or X
2456 toolkit in use provides a file dialog box, and DIR is not a
2457 remote file. For graphical file dialogs, any of the special values
2458 of MUSTMATCH `confirm' and `confirm-after-completion' are
2459 treated as equivalent to nil. Some graphical file dialogs respect
2460 a MUSTMATCH value of t, and some do not (or it only has a cosmetic
2461 effect, and does not actually prevent the user from entering a
2462 non-existent file).
2463
2464 See also `read-file-name-completion-ignore-case'
2465 and `read-file-name-function'."
2466 ;; If x-gtk-use-old-file-dialog = t (xg_get_file_with_selection),
2467 ;; then MUSTMATCH is enforced. But with newer Gtk
2468 ;; (xg_get_file_with_chooser), it only has a cosmetic effect.
2469 ;; The user can still type a non-existent file name.
2470 (funcall (or read-file-name-function #'read-file-name-default)
2471 prompt dir default-filename mustmatch initial predicate))
2472
2473 (defvar minibuffer-local-filename-syntax
2474 (let ((table (make-syntax-table))
2475 (punctuation (car (string-to-syntax "."))))
2476 ;; Convert all punctuation entries to symbol.
2477 (map-char-table (lambda (c syntax)
2478 (when (eq (car syntax) punctuation)
2479 (modify-syntax-entry c "_" table)))
2480 table)
2481 (mapc
2482 (lambda (c)
2483 (modify-syntax-entry c "." table))
2484 '(?/ ?: ?\\))
2485 table)
2486 "Syntax table used when reading a file name in the minibuffer.")
2487
2488 ;; minibuffer-completing-file-name is a variable used internally in minibuf.c
2489 ;; to determine whether to use minibuffer-local-filename-completion-map or
2490 ;; minibuffer-local-completion-map. It shouldn't be exported to Elisp.
2491 ;; FIXME: Actually, it is also used in rfn-eshadow.el we'd otherwise have to
2492 ;; use (eq minibuffer-completion-table #'read-file-name-internal), which is
2493 ;; probably even worse. Maybe We should add some read-file-name-setup-hook
2494 ;; instead, but for now, let's keep this non-obsolete.
2495 ;;(make-obsolete-variable 'minibuffer-completing-file-name nil "future" 'get)
2496
2497 (defun read-file-name-default (prompt &optional dir default-filename mustmatch initial predicate)
2498 "Default method for reading file names.
2499 See `read-file-name' for the meaning of the arguments."
2500 (unless dir (setq dir default-directory))
2501 (unless (file-name-absolute-p dir) (setq dir (expand-file-name dir)))
2502 (unless default-filename
2503 (setq default-filename (if initial (expand-file-name initial dir)
2504 buffer-file-name)))
2505 ;; If dir starts with user's homedir, change that to ~.
2506 (setq dir (abbreviate-file-name dir))
2507 ;; Likewise for default-filename.
2508 (if default-filename
2509 (setq default-filename
2510 (if (consp default-filename)
2511 (mapcar 'abbreviate-file-name default-filename)
2512 (abbreviate-file-name default-filename))))
2513 (let ((insdef (cond
2514 ((and insert-default-directory (stringp dir))
2515 (if initial
2516 (cons (minibuffer--double-dollars (concat dir initial))
2517 (length (minibuffer--double-dollars dir)))
2518 (minibuffer--double-dollars dir)))
2519 (initial (cons (minibuffer--double-dollars initial) 0)))))
2520
2521 (let ((completion-ignore-case read-file-name-completion-ignore-case)
2522 (minibuffer-completing-file-name t)
2523 (pred (or predicate 'file-exists-p))
2524 (add-to-history nil))
2525
2526 (let* ((val
2527 (if (or (not (next-read-file-uses-dialog-p))
2528 ;; Graphical file dialogs can't handle remote
2529 ;; files (Bug#99).
2530 (file-remote-p dir))
2531 ;; We used to pass `dir' to `read-file-name-internal' by
2532 ;; abusing the `predicate' argument. It's better to
2533 ;; just use `default-directory', but in order to avoid
2534 ;; changing `default-directory' in the current buffer,
2535 ;; we don't let-bind it.
2536 (let ((dir (file-name-as-directory
2537 (expand-file-name dir))))
2538 (minibuffer-with-setup-hook
2539 (lambda ()
2540 (setq default-directory dir)
2541 ;; When the first default in `minibuffer-default'
2542 ;; duplicates initial input `insdef',
2543 ;; reset `minibuffer-default' to nil.
2544 (when (equal (or (car-safe insdef) insdef)
2545 (or (car-safe minibuffer-default)
2546 minibuffer-default))
2547 (setq minibuffer-default
2548 (cdr-safe minibuffer-default)))
2549 ;; On the first request on `M-n' fill
2550 ;; `minibuffer-default' with a list of defaults
2551 ;; relevant for file-name reading.
2552 (set (make-local-variable 'minibuffer-default-add-function)
2553 (lambda ()
2554 (with-current-buffer
2555 (window-buffer (minibuffer-selected-window))
2556 (read-file-name--defaults dir initial))))
2557 (set-syntax-table minibuffer-local-filename-syntax))
2558 (completing-read prompt 'read-file-name-internal
2559 pred mustmatch insdef
2560 'file-name-history default-filename)))
2561 ;; If DEFAULT-FILENAME not supplied and DIR contains
2562 ;; a file name, split it.
2563 (let ((file (file-name-nondirectory dir))
2564 ;; When using a dialog, revert to nil and non-nil
2565 ;; interpretation of mustmatch. confirm options
2566 ;; need to be interpreted as nil, otherwise
2567 ;; it is impossible to create new files using
2568 ;; dialogs with the default settings.
2569 (dialog-mustmatch
2570 (not (memq mustmatch
2571 '(nil confirm confirm-after-completion)))))
2572 (when (and (not default-filename)
2573 (not (zerop (length file))))
2574 (setq default-filename file)
2575 (setq dir (file-name-directory dir)))
2576 (when default-filename
2577 (setq default-filename
2578 (expand-file-name (if (consp default-filename)
2579 (car default-filename)
2580 default-filename)
2581 dir)))
2582 (setq add-to-history t)
2583 (x-file-dialog prompt dir default-filename
2584 dialog-mustmatch
2585 (eq predicate 'file-directory-p)))))
2586
2587 (replace-in-history (eq (car-safe file-name-history) val)))
2588 ;; If completing-read returned the inserted default string itself
2589 ;; (rather than a new string with the same contents),
2590 ;; it has to mean that the user typed RET with the minibuffer empty.
2591 ;; In that case, we really want to return ""
2592 ;; so that commands such as set-visited-file-name can distinguish.
2593 (when (consp default-filename)
2594 (setq default-filename (car default-filename)))
2595 (when (eq val default-filename)
2596 ;; In this case, completing-read has not added an element
2597 ;; to the history. Maybe we should.
2598 (if (not replace-in-history)
2599 (setq add-to-history t))
2600 (setq val ""))
2601 (unless val (error "No file name specified"))
2602
2603 (if (and default-filename
2604 (string-equal val (if (consp insdef) (car insdef) insdef)))
2605 (setq val default-filename))
2606 (setq val (substitute-in-file-name val))
2607
2608 (if replace-in-history
2609 ;; Replace what Fcompleting_read added to the history
2610 ;; with what we will actually return. As an exception,
2611 ;; if that's the same as the second item in
2612 ;; file-name-history, it's really a repeat (Bug#4657).
2613 (let ((val1 (minibuffer--double-dollars val)))
2614 (if history-delete-duplicates
2615 (setcdr file-name-history
2616 (delete val1 (cdr file-name-history))))
2617 (if (string= val1 (cadr file-name-history))
2618 (pop file-name-history)
2619 (setcar file-name-history val1)))
2620 (if add-to-history
2621 ;; Add the value to the history--but not if it matches
2622 ;; the last value already there.
2623 (let ((val1 (minibuffer--double-dollars val)))
2624 (unless (and (consp file-name-history)
2625 (equal (car file-name-history) val1))
2626 (setq file-name-history
2627 (cons val1
2628 (if history-delete-duplicates
2629 (delete val1 file-name-history)
2630 file-name-history)))))))
2631 val))))
2632
2633 (defun internal-complete-buffer-except (&optional buffer)
2634 "Perform completion on all buffers excluding BUFFER.
2635 BUFFER nil or omitted means use the current buffer.
2636 Like `internal-complete-buffer', but removes BUFFER from the completion list."
2637 (let ((except (if (stringp buffer) buffer (buffer-name buffer))))
2638 (apply-partially 'completion-table-with-predicate
2639 'internal-complete-buffer
2640 (lambda (name)
2641 (not (equal (if (consp name) (car name) name) except)))
2642 nil)))
2643
2644 ;;; Old-style completion, used in Emacs-21 and Emacs-22.
2645
2646 (defun completion-emacs21-try-completion (string table pred _point)
2647 (let ((completion (try-completion string table pred)))
2648 (if (stringp completion)
2649 (cons completion (length completion))
2650 completion)))
2651
2652 (defun completion-emacs21-all-completions (string table pred _point)
2653 (completion-hilit-commonality
2654 (all-completions string table pred)
2655 (length string)
2656 (car (completion-boundaries string table pred ""))))
2657
2658 (defun completion-emacs22-try-completion (string table pred point)
2659 (let ((suffix (substring string point))
2660 (completion (try-completion (substring string 0 point) table pred)))
2661 (if (not (stringp completion))
2662 completion
2663 ;; Merge a trailing / in completion with a / after point.
2664 ;; We used to only do it for word completion, but it seems to make
2665 ;; sense for all completions.
2666 ;; Actually, claiming this feature was part of Emacs-22 completion
2667 ;; is pushing it a bit: it was only done in minibuffer-completion-word,
2668 ;; which was (by default) not bound during file completion, where such
2669 ;; slashes are most likely to occur.
2670 (if (and (not (zerop (length completion)))
2671 (eq ?/ (aref completion (1- (length completion))))
2672 (not (zerop (length suffix)))
2673 (eq ?/ (aref suffix 0)))
2674 ;; This leaves point after the / .
2675 (setq suffix (substring suffix 1)))
2676 (cons (concat completion suffix) (length completion)))))
2677
2678 (defun completion-emacs22-all-completions (string table pred point)
2679 (let ((beforepoint (substring string 0 point)))
2680 (completion-hilit-commonality
2681 (all-completions beforepoint table pred)
2682 point
2683 (car (completion-boundaries beforepoint table pred "")))))
2684
2685 ;;; Basic completion.
2686
2687 (defun completion--merge-suffix (completion point suffix)
2688 "Merge end of COMPLETION with beginning of SUFFIX.
2689 Simple generalization of the \"merge trailing /\" done in Emacs-22.
2690 Return the new suffix."
2691 (if (and (not (zerop (length suffix)))
2692 (string-match "\\(.+\\)\n\\1" (concat completion "\n" suffix)
2693 ;; Make sure we don't compress things to less
2694 ;; than we started with.
2695 point)
2696 ;; Just make sure we didn't match some other \n.
2697 (eq (match-end 1) (length completion)))
2698 (substring suffix (- (match-end 1) (match-beginning 1)))
2699 ;; Nothing to merge.
2700 suffix))
2701
2702 (defun completion-basic--pattern (beforepoint afterpoint bounds)
2703 (delete
2704 "" (list (substring beforepoint (car bounds))
2705 'point
2706 (substring afterpoint 0 (cdr bounds)))))
2707
2708 (defun completion-basic-try-completion (string table pred point)
2709 (let* ((beforepoint (substring string 0 point))
2710 (afterpoint (substring string point))
2711 (bounds (completion-boundaries beforepoint table pred afterpoint)))
2712 (if (zerop (cdr bounds))
2713 ;; `try-completion' may return a subtly different result
2714 ;; than `all+merge', so try to use it whenever possible.
2715 (let ((completion (try-completion beforepoint table pred)))
2716 (if (not (stringp completion))
2717 completion
2718 (cons
2719 (concat completion
2720 (completion--merge-suffix completion point afterpoint))
2721 (length completion))))
2722 (let* ((suffix (substring afterpoint (cdr bounds)))
2723 (prefix (substring beforepoint 0 (car bounds)))
2724 (pattern (delete
2725 "" (list (substring beforepoint (car bounds))
2726 'point
2727 (substring afterpoint 0 (cdr bounds)))))
2728 (all (completion-pcm--all-completions prefix pattern table pred)))
2729 (if minibuffer-completing-file-name
2730 (setq all (completion-pcm--filename-try-filter all)))
2731 (completion-pcm--merge-try pattern all prefix suffix)))))
2732
2733 (defun completion-basic-all-completions (string table pred point)
2734 (let* ((beforepoint (substring string 0 point))
2735 (afterpoint (substring string point))
2736 (bounds (completion-boundaries beforepoint table pred afterpoint))
2737 ;; (suffix (substring afterpoint (cdr bounds)))
2738 (prefix (substring beforepoint 0 (car bounds)))
2739 (pattern (delete
2740 "" (list (substring beforepoint (car bounds))
2741 'point
2742 (substring afterpoint 0 (cdr bounds)))))
2743 (all (completion-pcm--all-completions prefix pattern table pred)))
2744 (completion-hilit-commonality all point (car bounds))))
2745
2746 ;;; Partial-completion-mode style completion.
2747
2748 (defvar completion-pcm--delim-wild-regex nil
2749 "Regular expression matching delimiters controlling the partial-completion.
2750 Typically, this regular expression simply matches a delimiter, meaning
2751 that completion can add something at (match-beginning 0), but if it has
2752 a submatch 1, then completion can add something at (match-end 1).
2753 This is used when the delimiter needs to be of size zero (e.g. the transition
2754 from lowercase to uppercase characters).")
2755
2756 (defun completion-pcm--prepare-delim-re (delims)
2757 (setq completion-pcm--delim-wild-regex (concat "[" delims "*]")))
2758
2759 (defcustom completion-pcm-word-delimiters "-_./:| "
2760 "A string of characters treated as word delimiters for completion.
2761 Some arcane rules:
2762 If `]' is in this string, it must come first.
2763 If `^' is in this string, it must not come first.
2764 If `-' is in this string, it must come first or right after `]'.
2765 In other words, if S is this string, then `[S]' must be a valid Emacs regular
2766 expression (not containing character ranges like `a-z')."
2767 :set (lambda (symbol value)
2768 (set-default symbol value)
2769 ;; Refresh other vars.
2770 (completion-pcm--prepare-delim-re value))
2771 :initialize 'custom-initialize-reset
2772 :type 'string)
2773
2774 (defcustom completion-pcm-complete-word-inserts-delimiters nil
2775 "Treat the SPC or - inserted by `minibuffer-complete-word' as delimiters.
2776 Those chars are treated as delimiters iff this variable is non-nil.
2777 I.e. if non-nil, M-x SPC will just insert a \"-\" in the minibuffer, whereas
2778 if nil, it will list all possible commands in *Completions* because none of
2779 the commands start with a \"-\" or a SPC."
2780 :version "24.1"
2781 :type 'boolean)
2782
2783 (defun completion-pcm--pattern-trivial-p (pattern)
2784 (and (stringp (car pattern))
2785 ;; It can be followed by `point' and "" and still be trivial.
2786 (let ((trivial t))
2787 (dolist (elem (cdr pattern))
2788 (unless (member elem '(point ""))
2789 (setq trivial nil)))
2790 trivial)))
2791
2792 (defun completion-pcm--string->pattern (string &optional point)
2793 "Split STRING into a pattern.
2794 A pattern is a list where each element is either a string
2795 or a symbol, see `completion-pcm--merge-completions'."
2796 (if (and point (< point (length string)))
2797 (let ((prefix (substring string 0 point))
2798 (suffix (substring string point)))
2799 (append (completion-pcm--string->pattern prefix)
2800 '(point)
2801 (completion-pcm--string->pattern suffix)))
2802 (let* ((pattern nil)
2803 (p 0)
2804 (p0 p)
2805 (pending nil))
2806
2807 (while (and (setq p (string-match completion-pcm--delim-wild-regex
2808 string p))
2809 (or completion-pcm-complete-word-inserts-delimiters
2810 ;; If the char was added by minibuffer-complete-word,
2811 ;; then don't treat it as a delimiter, otherwise
2812 ;; "M-x SPC" ends up inserting a "-" rather than listing
2813 ;; all completions.
2814 (not (get-text-property p 'completion-try-word string))))
2815 ;; Usually, completion-pcm--delim-wild-regex matches a delimiter,
2816 ;; meaning that something can be added *before* it, but it can also
2817 ;; match a prefix and postfix, in which case something can be added
2818 ;; in-between (e.g. match [[:lower:]][[:upper:]]).
2819 ;; This is determined by the presence of a submatch-1 which delimits
2820 ;; the prefix.
2821 (if (match-end 1) (setq p (match-end 1)))
2822 (unless (= p0 p)
2823 (if pending (push pending pattern))
2824 (push (substring string p0 p) pattern))
2825 (setq pending nil)
2826 (if (eq (aref string p) ?*)
2827 (progn
2828 (push 'star pattern)
2829 (setq p0 (1+ p)))
2830 (push 'any pattern)
2831 (if (match-end 1)
2832 (setq p0 p)
2833 (push (substring string p (match-end 0)) pattern)
2834 ;; `any-delim' is used so that "a-b" also finds "array->beginning".
2835 (setq pending 'any-delim)
2836 (setq p0 (match-end 0))))
2837 (setq p p0))
2838
2839 (when (> (length string) p0)
2840 (if pending (push pending pattern))
2841 (push (substring string p0) pattern))
2842 ;; An empty string might be erroneously added at the beginning.
2843 ;; It should be avoided properly, but it's so easy to remove it here.
2844 (delete "" (nreverse pattern)))))
2845
2846 (defun completion-pcm--optimize-pattern (p)
2847 ;; Remove empty strings in a separate phase since otherwise a ""
2848 ;; might prevent some other optimization, as in '(any "" any).
2849 (setq p (delete "" p))
2850 (let ((n '()))
2851 (while p
2852 (pcase p
2853 (`(,(and s1 (pred stringp)) ,(and s2 (pred stringp)) . ,rest)
2854 (setq p (cons (concat s1 s2) rest)))
2855 (`(,(and p1 (pred symbolp)) ,(and p2 (guard (eq p1 p2))) . ,_)
2856 (setq p (cdr p)))
2857 (`(star ,(pred symbolp) . ,rest) (setq p `(star . ,rest)))
2858 (`(,(pred symbolp) star . ,rest) (setq p `(star . ,rest)))
2859 (`(point ,(or `any `any-delim) . ,rest) (setq p `(point . ,rest)))
2860 (`(,(or `any `any-delim) point . ,rest) (setq p `(point . ,rest)))
2861 (`(any ,(or `any `any-delim) . ,rest) (setq p `(any . ,rest)))
2862 (`(,(pred symbolp)) (setq p nil)) ;Implicit terminating `any'.
2863 (_ (push (pop p) n))))
2864 (nreverse n)))
2865
2866 (defun completion-pcm--pattern->regex (pattern &optional group)
2867 (let ((re
2868 (concat "\\`"
2869 (mapconcat
2870 (lambda (x)
2871 (cond
2872 ((stringp x) (regexp-quote x))
2873 (t
2874 (let ((re (if (eq x 'any-delim)
2875 (concat completion-pcm--delim-wild-regex "*?")
2876 ".*?")))
2877 (if (if (consp group) (memq x group) group)
2878 (concat "\\(" re "\\)")
2879 re)))))
2880 pattern
2881 ""))))
2882 ;; Avoid pathological backtracking.
2883 (while (string-match "\\.\\*\\?\\(?:\\\\[()]\\)*\\(\\.\\*\\?\\)" re)
2884 (setq re (replace-match "" t t re 1)))
2885 re))
2886
2887 (defun completion-pcm--all-completions (prefix pattern table pred)
2888 "Find all completions for PATTERN in TABLE obeying PRED.
2889 PATTERN is as returned by `completion-pcm--string->pattern'."
2890 ;; (cl-assert (= (car (completion-boundaries prefix table pred ""))
2891 ;; (length prefix)))
2892 ;; Find an initial list of possible completions.
2893 (if (completion-pcm--pattern-trivial-p pattern)
2894
2895 ;; Minibuffer contains no delimiters -- simple case!
2896 (all-completions (concat prefix (car pattern)) table pred)
2897
2898 ;; Use all-completions to do an initial cull. This is a big win,
2899 ;; since all-completions is written in C!
2900 (let* (;; Convert search pattern to a standard regular expression.
2901 (regex (completion-pcm--pattern->regex pattern))
2902 (case-fold-search completion-ignore-case)
2903 (completion-regexp-list (cons regex completion-regexp-list))
2904 (compl (all-completions
2905 (concat prefix
2906 (if (stringp (car pattern)) (car pattern) ""))
2907 table pred)))
2908 (if (not (functionp table))
2909 ;; The internal functions already obeyed completion-regexp-list.
2910 compl
2911 (let ((poss ()))
2912 (dolist (c compl)
2913 (when (string-match-p regex c) (push c poss)))
2914 poss)))))
2915
2916 (defun completion-pcm--hilit-commonality (pattern completions)
2917 (when completions
2918 (let* ((re (completion-pcm--pattern->regex pattern '(point)))
2919 (case-fold-search completion-ignore-case))
2920 (mapcar
2921 (lambda (str)
2922 ;; Don't modify the string itself.
2923 (setq str (copy-sequence str))
2924 (unless (string-match re str)
2925 (error "Internal error: %s does not match %s" re str))
2926 (let ((pos (or (match-beginning 1) (match-end 0))))
2927 (put-text-property 0 pos
2928 'font-lock-face 'completions-common-part
2929 str)
2930 (if (> (length str) pos)
2931 (put-text-property pos (1+ pos)
2932 'font-lock-face 'completions-first-difference
2933 str)))
2934 str)
2935 completions))))
2936
2937 (defun completion-pcm--find-all-completions (string table pred point
2938 &optional filter)
2939 "Find all completions for STRING at POINT in TABLE, satisfying PRED.
2940 POINT is a position inside STRING.
2941 FILTER is a function applied to the return value, that can be used, e.g. to
2942 filter out additional entries (because TABLE might not obey PRED)."
2943 (unless filter (setq filter 'identity))
2944 (let* ((beforepoint (substring string 0 point))
2945 (afterpoint (substring string point))
2946 (bounds (completion-boundaries beforepoint table pred afterpoint))
2947 (prefix (substring beforepoint 0 (car bounds)))
2948 (suffix (substring afterpoint (cdr bounds)))
2949 firsterror)
2950 (setq string (substring string (car bounds) (+ point (cdr bounds))))
2951 (let* ((relpoint (- point (car bounds)))
2952 (pattern (completion-pcm--string->pattern string relpoint))
2953 (all (condition-case-unless-debug err
2954 (funcall filter
2955 (completion-pcm--all-completions
2956 prefix pattern table pred))
2957 (error (setq firsterror err) nil))))
2958 (when (and (null all)
2959 (> (car bounds) 0)
2960 (null (ignore-errors (try-completion prefix table pred))))
2961 ;; The prefix has no completions at all, so we should try and fix
2962 ;; that first.
2963 (let ((substring (substring prefix 0 -1)))
2964 (pcase-let ((`(,subpat ,suball ,subprefix ,_subsuffix)
2965 (completion-pcm--find-all-completions
2966 substring table pred (length substring) filter)))
2967 (let ((sep (aref prefix (1- (length prefix))))
2968 ;; Text that goes between the new submatches and the
2969 ;; completion substring.
2970 (between nil))
2971 ;; Eliminate submatches that don't end with the separator.
2972 (dolist (submatch (prog1 suball (setq suball ())))
2973 (when (eq sep (aref submatch (1- (length submatch))))
2974 (push submatch suball)))
2975 (when suball
2976 ;; Update the boundaries and corresponding pattern.
2977 ;; We assume that all submatches result in the same boundaries
2978 ;; since we wouldn't know how to merge them otherwise anyway.
2979 ;; FIXME: COMPLETE REWRITE!!!
2980 (let* ((newbeforepoint
2981 (concat subprefix (car suball)
2982 (substring string 0 relpoint)))
2983 (leftbound (+ (length subprefix) (length (car suball))))
2984 (newbounds (completion-boundaries
2985 newbeforepoint table pred afterpoint)))
2986 (unless (or (and (eq (cdr bounds) (cdr newbounds))
2987 (eq (car newbounds) leftbound))
2988 ;; Refuse new boundaries if they step over
2989 ;; the submatch.
2990 (< (car newbounds) leftbound))
2991 ;; The new completed prefix does change the boundaries
2992 ;; of the completed substring.
2993 (setq suffix (substring afterpoint (cdr newbounds)))
2994 (setq string
2995 (concat (substring newbeforepoint (car newbounds))
2996 (substring afterpoint 0 (cdr newbounds))))
2997 (setq between (substring newbeforepoint leftbound
2998 (car newbounds)))
2999 (setq pattern (completion-pcm--string->pattern
3000 string
3001 (- (length newbeforepoint)
3002 (car newbounds)))))
3003 (dolist (submatch suball)
3004 (setq all (nconc
3005 (mapcar
3006 (lambda (s) (concat submatch between s))
3007 (funcall filter
3008 (completion-pcm--all-completions
3009 (concat subprefix submatch between)
3010 pattern table pred)))
3011 all)))
3012 ;; FIXME: This can come in handy for try-completion,
3013 ;; but isn't right for all-completions, since it lists
3014 ;; invalid completions.
3015 ;; (unless all
3016 ;; ;; Even though we found expansions in the prefix, none
3017 ;; ;; leads to a valid completion.
3018 ;; ;; Let's keep the expansions, tho.
3019 ;; (dolist (submatch suball)
3020 ;; (push (concat submatch between newsubstring) all)))
3021 ))
3022 (setq pattern (append subpat (list 'any (string sep))
3023 (if between (list between)) pattern))
3024 (setq prefix subprefix)))))
3025 (if (and (null all) firsterror)
3026 (signal (car firsterror) (cdr firsterror))
3027 (list pattern all prefix suffix)))))
3028
3029 (defun completion-pcm-all-completions (string table pred point)
3030 (pcase-let ((`(,pattern ,all ,prefix ,_suffix)
3031 (completion-pcm--find-all-completions string table pred point)))
3032 (when all
3033 (nconc (completion-pcm--hilit-commonality pattern all)
3034 (length prefix)))))
3035
3036 (defun completion--sreverse (str)
3037 "Like `reverse' but for a string STR rather than a list."
3038 (apply #'string (nreverse (mapcar 'identity str))))
3039
3040 (defun completion--common-suffix (strs)
3041 "Return the common suffix of the strings STRS."
3042 (completion--sreverse
3043 (try-completion
3044 ""
3045 (mapcar #'completion--sreverse strs))))
3046
3047 (defun completion-pcm--merge-completions (strs pattern)
3048 "Extract the commonality in STRS, with the help of PATTERN.
3049 PATTERN can contain strings and symbols chosen among `star', `any', `point',
3050 and `prefix'. They all match anything (aka \".*\") but are merged differently:
3051 `any' only grows from the left (when matching \"a1b\" and \"a2b\" it gets
3052 completed to just \"a\").
3053 `prefix' only grows from the right (when matching \"a1b\" and \"a2b\" it gets
3054 completed to just \"b\").
3055 `star' grows from both ends and is reified into a \"*\" (when matching \"a1b\"
3056 and \"a2b\" it gets completed to \"a*b\").
3057 `point' is like `star' except that it gets reified as the position of point
3058 instead of being reified as a \"*\" character.
3059 The underlying idea is that we should return a string which still matches
3060 the same set of elements."
3061 ;; When completing while ignoring case, we want to try and avoid
3062 ;; completing "fo" to "foO" when completing against "FOO" (bug#4219).
3063 ;; So we try and make sure that the string we return is all made up
3064 ;; of text from the completions rather than part from the
3065 ;; completions and part from the input.
3066 ;; FIXME: This reduces the problems of inconsistent capitalization
3067 ;; but it doesn't fully fix it: we may still end up completing
3068 ;; "fo-ba" to "foo-BAR" or "FOO-bar" when completing against
3069 ;; '("foo-barr" "FOO-BARD").
3070 (cond
3071 ((null (cdr strs)) (list (car strs)))
3072 (t
3073 (let ((re (completion-pcm--pattern->regex pattern 'group))
3074 (ccs ())) ;Chopped completions.
3075
3076 ;; First chop each string into the parts corresponding to each
3077 ;; non-constant element of `pattern', using regexp-matching.
3078 (let ((case-fold-search completion-ignore-case))
3079 (dolist (str strs)
3080 (unless (string-match re str)
3081 (error "Internal error: %s doesn't match %s" str re))
3082 (let ((chopped ())
3083 (last 0)
3084 (i 1)
3085 next)
3086 (while (setq next (match-end i))
3087 (push (substring str last next) chopped)
3088 (setq last next)
3089 (setq i (1+ i)))
3090 ;; Add the text corresponding to the implicit trailing `any'.
3091 (push (substring str last) chopped)
3092 (push (nreverse chopped) ccs))))
3093
3094 ;; Then for each of those non-constant elements, extract the
3095 ;; commonality between them.
3096 (let ((res ())
3097 (fixed ""))
3098 ;; Make the implicit trailing `any' explicit.
3099 (dolist (elem (append pattern '(any)))
3100 (if (stringp elem)
3101 (setq fixed (concat fixed elem))
3102 (let ((comps ()))
3103 (dolist (cc (prog1 ccs (setq ccs nil)))
3104 (push (car cc) comps)
3105 (push (cdr cc) ccs))
3106 ;; Might improve the likelihood to avoid choosing
3107 ;; different capitalizations in different parts.
3108 ;; In practice, it doesn't seem to make any difference.
3109 (setq ccs (nreverse ccs))
3110 (let* ((prefix (try-completion fixed comps))
3111 (unique (or (and (eq prefix t) (setq prefix fixed))
3112 (eq t (try-completion prefix comps)))))
3113 (unless (or (eq elem 'prefix)
3114 (equal prefix ""))
3115 (push prefix res))
3116 ;; If there's only one completion, `elem' is not useful
3117 ;; any more: it can only match the empty string.
3118 ;; FIXME: in some cases, it may be necessary to turn an
3119 ;; `any' into a `star' because the surrounding context has
3120 ;; changed such that string->pattern wouldn't add an `any'
3121 ;; here any more.
3122 (unless unique
3123 (push elem res)
3124 ;; Extract common suffix additionally to common prefix.
3125 ;; Don't do it for `any' since it could lead to a merged
3126 ;; completion that doesn't itself match the candidates.
3127 (when (and (memq elem '(star point prefix))
3128 ;; If prefix is one of the completions, there's no
3129 ;; suffix left to find.
3130 (not (assoc-string prefix comps t)))
3131 (let ((suffix
3132 (completion--common-suffix
3133 (if (zerop (length prefix)) comps
3134 ;; Ignore the chars in the common prefix, so we
3135 ;; don't merge '("abc" "abbc") as "ab*bc".
3136 (let ((skip (length prefix)))
3137 (mapcar (lambda (str) (substring str skip))
3138 comps))))))
3139 (cl-assert (stringp suffix))
3140 (unless (equal suffix "")
3141 (push suffix res)))))
3142 (setq fixed "")))))
3143 ;; We return it in reverse order.
3144 res)))))
3145
3146 (defun completion-pcm--pattern->string (pattern)
3147 (mapconcat (lambda (x) (cond
3148 ((stringp x) x)
3149 ((eq x 'star) "*")
3150 (t ""))) ;any, point, prefix.
3151 pattern
3152 ""))
3153
3154 ;; We want to provide the functionality of `try', but we use `all'
3155 ;; and then merge it. In most cases, this works perfectly, but
3156 ;; if the completion table doesn't consider the same completions in
3157 ;; `try' as in `all', then we have a problem. The most common such
3158 ;; case is for filename completion where completion-ignored-extensions
3159 ;; is only obeyed by the `try' code. We paper over the difference
3160 ;; here. Note that it is not quite right either: if the completion
3161 ;; table uses completion-table-in-turn, this filtering may take place
3162 ;; too late to correctly fallback from the first to the
3163 ;; second alternative.
3164 (defun completion-pcm--filename-try-filter (all)
3165 "Filter to adjust `all' file completion to the behavior of `try'."
3166 (when all
3167 (let ((try ())
3168 (re (concat "\\(?:\\`\\.\\.?/\\|"
3169 (regexp-opt completion-ignored-extensions)
3170 "\\)\\'")))
3171 (dolist (f all)
3172 (unless (string-match-p re f) (push f try)))
3173 (or try all))))
3174
3175
3176 (defun completion-pcm--merge-try (pattern all prefix suffix)
3177 (cond
3178 ((not (consp all)) all)
3179 ((and (not (consp (cdr all))) ;Only one completion.
3180 ;; Ignore completion-ignore-case here.
3181 (equal (completion-pcm--pattern->string pattern) (car all)))
3182 t)
3183 (t
3184 (let* ((mergedpat (completion-pcm--merge-completions all pattern))
3185 ;; `mergedpat' is in reverse order. Place new point (by
3186 ;; order of preference) either at the old point, or at
3187 ;; the last place where there's something to choose, or
3188 ;; at the very end.
3189 (pointpat (or (memq 'point mergedpat)
3190 (memq 'any mergedpat)
3191 (memq 'star mergedpat)
3192 ;; Not `prefix'.
3193 mergedpat))
3194 ;; New pos from the start.
3195 (newpos (length (completion-pcm--pattern->string pointpat)))
3196 ;; Do it afterwards because it changes `pointpat' by side effect.
3197 (merged (completion-pcm--pattern->string (nreverse mergedpat))))
3198
3199 (setq suffix (completion--merge-suffix merged newpos suffix))
3200 (cons (concat prefix merged suffix) (+ newpos (length prefix)))))))
3201
3202 (defun completion-pcm-try-completion (string table pred point)
3203 (pcase-let ((`(,pattern ,all ,prefix ,suffix)
3204 (completion-pcm--find-all-completions
3205 string table pred point
3206 (if minibuffer-completing-file-name
3207 'completion-pcm--filename-try-filter))))
3208 (completion-pcm--merge-try pattern all prefix suffix)))
3209
3210 ;;; Substring completion
3211 ;; Mostly derived from the code of `basic' completion.
3212
3213 (defun completion-substring--all-completions (string table pred point)
3214 (let* ((beforepoint (substring string 0 point))
3215 (afterpoint (substring string point))
3216 (bounds (completion-boundaries beforepoint table pred afterpoint))
3217 (suffix (substring afterpoint (cdr bounds)))
3218 (prefix (substring beforepoint 0 (car bounds)))
3219 (basic-pattern (completion-basic--pattern
3220 beforepoint afterpoint bounds))
3221 (pattern (if (not (stringp (car basic-pattern)))
3222 basic-pattern
3223 (cons 'prefix basic-pattern)))
3224 (all (completion-pcm--all-completions prefix pattern table pred)))
3225 (list all pattern prefix suffix (car bounds))))
3226
3227 (defun completion-substring-try-completion (string table pred point)
3228 (pcase-let ((`(,all ,pattern ,prefix ,suffix ,_carbounds)
3229 (completion-substring--all-completions
3230 string table pred point)))
3231 (if minibuffer-completing-file-name
3232 (setq all (completion-pcm--filename-try-filter all)))
3233 (completion-pcm--merge-try pattern all prefix suffix)))
3234
3235 (defun completion-substring-all-completions (string table pred point)
3236 (pcase-let ((`(,all ,pattern ,prefix ,_suffix ,_carbounds)
3237 (completion-substring--all-completions
3238 string table pred point)))
3239 (when all
3240 (nconc (completion-pcm--hilit-commonality pattern all)
3241 (length prefix)))))
3242
3243 ;; Initials completion
3244 ;; Complete /ums to /usr/monnier/src or lch to list-command-history.
3245
3246 (defun completion-initials-expand (str table pred)
3247 (let ((bounds (completion-boundaries str table pred "")))
3248 (unless (or (zerop (length str))
3249 ;; Only check within the boundaries, since the
3250 ;; boundary char (e.g. /) might be in delim-regexp.
3251 (string-match completion-pcm--delim-wild-regex str
3252 (car bounds)))
3253 (if (zerop (car bounds))
3254 (mapconcat 'string str "-")
3255 ;; If there's a boundary, it's trickier. The main use-case
3256 ;; we consider here is file-name completion. We'd like
3257 ;; to expand ~/eee to ~/e/e/e and /eee to /e/e/e.
3258 ;; But at the same time, we don't want /usr/share/ae to expand
3259 ;; to /usr/share/a/e just because we mistyped "ae" for "ar",
3260 ;; so we probably don't want initials to touch anything that
3261 ;; looks like /usr/share/foo. As a heuristic, we just check that
3262 ;; the text before the boundary char is at most 1 char.
3263 ;; This allows both ~/eee and /eee and not much more.
3264 ;; FIXME: It sadly also disallows the use of ~/eee when that's
3265 ;; embedded within something else (e.g. "(~/eee" in Info node
3266 ;; completion or "ancestor:/eee" in bzr-revision completion).
3267 (when (< (car bounds) 3)
3268 (let ((sep (substring str (1- (car bounds)) (car bounds))))
3269 ;; FIXME: the above string-match checks the whole string, whereas
3270 ;; we end up only caring about the after-boundary part.
3271 (concat (substring str 0 (car bounds))
3272 (mapconcat 'string (substring str (car bounds)) sep))))))))
3273
3274 (defun completion-initials-all-completions (string table pred _point)
3275 (let ((newstr (completion-initials-expand string table pred)))
3276 (when newstr
3277 (completion-pcm-all-completions newstr table pred (length newstr)))))
3278
3279 (defun completion-initials-try-completion (string table pred _point)
3280 (let ((newstr (completion-initials-expand string table pred)))
3281 (when newstr
3282 (completion-pcm-try-completion newstr table pred (length newstr)))))
3283 \f
3284 (defvar completing-read-function 'completing-read-default
3285 "The function called by `completing-read' to do its work.
3286 It should accept the same arguments as `completing-read'.")
3287
3288 (defun completing-read-default (prompt collection &optional predicate
3289 require-match initial-input
3290 hist def inherit-input-method)
3291 "Default method for reading from the minibuffer with completion.
3292 See `completing-read' for the meaning of the arguments."
3293
3294 (when (consp initial-input)
3295 (setq initial-input
3296 (cons (car initial-input)
3297 ;; `completing-read' uses 0-based index while
3298 ;; `read-from-minibuffer' uses 1-based index.
3299 (1+ (cdr initial-input)))))
3300
3301 (let* ((minibuffer-completion-table collection)
3302 (minibuffer-completion-predicate predicate)
3303 (minibuffer-completion-confirm (unless (eq require-match t)
3304 require-match))
3305 (base-keymap (if require-match
3306 minibuffer-local-must-match-map
3307 minibuffer-local-completion-map))
3308 (keymap (if (memq minibuffer-completing-file-name '(nil lambda))
3309 base-keymap
3310 ;; Layer minibuffer-local-filename-completion-map
3311 ;; on top of the base map.
3312 (make-composed-keymap
3313 minibuffer-local-filename-completion-map
3314 ;; Set base-keymap as the parent, so that nil bindings
3315 ;; in minibuffer-local-filename-completion-map can
3316 ;; override bindings in base-keymap.
3317 base-keymap)))
3318 (result (read-from-minibuffer prompt initial-input keymap
3319 nil hist def inherit-input-method)))
3320 (when (and (equal result "") def)
3321 (setq result (if (consp def) (car def) def)))
3322 result))
3323 \f
3324 ;; Miscellaneous
3325
3326 (defun minibuffer-insert-file-name-at-point ()
3327 "Get a file name at point in original buffer and insert it to minibuffer."
3328 (interactive)
3329 (let ((file-name-at-point
3330 (with-current-buffer (window-buffer (minibuffer-selected-window))
3331 (run-hook-with-args-until-success 'file-name-at-point-functions))))
3332 (when file-name-at-point
3333 (insert file-name-at-point))))
3334
3335 (provide 'minibuffer)
3336
3337 ;;; minibuffer.el ends here