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