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