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