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