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