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