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