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