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