Checklist for adding new files to Emacs.
[bpt/emacs.git] / lisp / minibuffer.el
CommitLineData
32bae13c
SM
1;;; minibuffer.el --- Minibuffer completion functions
2
ae940284 3;; Copyright (C) 2008, 2009 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).
33;; See `completion-boundaries'.
34
35;;; Bugs:
36
eee6de73
SM
37;; - completion-all-sorted-completions list all the completions, whereas
38;; it should only lists the ones that `try-completion' would consider.
39;; E.g. it should honor completion-ignored-extensions.
a38313e1
SM
40;; - choose-completion can't automatically figure out the boundaries
41;; corresponding to the displayed completions. `base-size' gives the left
42;; boundary, but not the righthand one. So we need to add
43;; completion-extra-size (and also completion-no-auto-exit).
ba5ff07b 44
3911966b
SM
45;;; Todo:
46
eee6de73 47;; - make lisp-complete-symbol and sym-comp use it.
a38313e1 48;; - add support for ** to pcm.
19c04f39 49;; - Make read-file-name-predicate obsolete.
3911966b
SM
50;; - Add vc-file-name-completion-table to read-file-name-internal.
51;; - A feature like completing-help.el.
eee6de73 52;; - make lisp/complete.el obsolete.
3911966b 53;; - Make the `hide-spaces' arg of all-completions obsolete?
32bae13c
SM
54
55;;; Code:
56
57(eval-when-compile (require 'cl))
58
21622c6d
SM
59;;; Completion table manipulation
60
a38313e1 61;; New completion-table operation.
f8381803
SM
62(defun completion-boundaries (string table pred suffix)
63 "Return the boundaries of the completions returned by TABLE for STRING.
a38313e1 64STRING is the string on which completion will be performed.
f8381803
SM
65SUFFIX is the string after point.
66The result is of the form (START . END) where START is the position
67in STRING of the beginning of the completion field and END is the position
68in SUFFIX of the end of the completion field.
f8381803
SM
69E.g. for simple completion tables, the result is always (0 . (length SUFFIX))
70and for file names the result is the positions delimited by
a38313e1
SM
71the closest directory separators."
72 (let ((boundaries (if (functionp table)
f8381803 73 (funcall table string pred (cons 'boundaries suffix)))))
a38313e1
SM
74 (if (not (eq (car-safe boundaries) 'boundaries))
75 (setq boundaries nil))
76 (cons (or (cadr boundaries) 0)
f8381803 77 (or (cddr boundaries) (length suffix)))))
a38313e1 78
e2947429
SM
79(defun completion--some (fun xs)
80 "Apply FUN to each element of XS in turn.
81Return the first non-nil returned value.
82Like CL's `some'."
a38313e1
SM
83 (let ((firsterror nil)
84 res)
e2947429 85 (while (and (not res) xs)
a38313e1
SM
86 (condition-case err
87 (setq res (funcall fun (pop xs)))
88 (error (unless firsterror (setq firsterror err)) nil)))
89 (or res
90 (if firsterror (signal (car firsterror) (cdr firsterror))))))
e2947429 91
21622c6d
SM
92(defun complete-with-action (action table string pred)
93 "Perform completion ACTION.
94STRING is the string to complete.
95TABLE is the completion table, which should not be a function.
96PRED is a completion predicate.
97ACTION can be one of nil, t or `lambda'."
a38313e1
SM
98 (cond
99 ((functionp table) (funcall table string pred action))
100 ((eq (car-safe action) 'boundaries)
101 (cons 'boundaries (completion-boundaries string table pred (cdr action))))
102 (t
103 (funcall
104 (cond
105 ((null action) 'try-completion)
106 ((eq action t) 'all-completions)
107 (t 'test-completion))
108 string table pred))))
21622c6d
SM
109
110(defun completion-table-dynamic (fun)
111 "Use function FUN as a dynamic completion table.
112FUN is called with one argument, the string for which completion is required,
b95c7600
JB
113and it should return an alist containing all the intended possible completions.
114This alist may be a full list of possible completions so that FUN can ignore
115the value of its argument. If completion is performed in the minibuffer,
116FUN will be called in the buffer from which the minibuffer was entered.
21622c6d 117
e8061cd9 118The result of the `completion-table-dynamic' form is a function
d9aa6b33 119that can be used as the COLLECTION argument to `try-completion' and
b95c7600 120`all-completions'. See Info node `(elisp)Programmed Completion'."
21622c6d
SM
121 (lexical-let ((fun fun))
122 (lambda (string pred action)
123 (with-current-buffer (let ((win (minibuffer-selected-window)))
124 (if (window-live-p win) (window-buffer win)
125 (current-buffer)))
126 (complete-with-action action (funcall fun string) string pred)))))
127
128(defmacro lazy-completion-table (var fun)
129 "Initialize variable VAR as a lazy completion table.
130If the completion table VAR is used for the first time (e.g., by passing VAR
131as an argument to `try-completion'), the function FUN is called with no
132arguments. FUN must return the completion table that will be stored in VAR.
133If completion is requested in the minibuffer, FUN will be called in the buffer
134from which the minibuffer was entered. The return value of
135`lazy-completion-table' must be used to initialize the value of VAR.
136
137You should give VAR a non-nil `risky-local-variable' property."
69e018a7 138 (declare (debug (symbolp lambda-expr)))
21622c6d
SM
139 (let ((str (make-symbol "string")))
140 `(completion-table-dynamic
141 (lambda (,str)
142 (when (functionp ,var)
143 (setq ,var (,fun)))
144 ,var))))
145
146(defun completion-table-with-context (prefix table string pred action)
25c0d999 147 ;; TODO: add `suffix' maybe?
a38313e1 148 ;; Notice that `pred' may not be a function in some abusive cases.
34200787
SM
149 (when (functionp pred)
150 (setq pred
151 (lexical-let ((pred pred))
152 ;; Predicates are called differently depending on the nature of
153 ;; the completion table :-(
154 (cond
155 ((vectorp table) ;Obarray.
156 (lambda (sym) (funcall pred (concat prefix (symbol-name sym)))))
157 ((hash-table-p table)
158 (lambda (s v) (funcall pred (concat prefix s))))
159 ((functionp table)
160 (lambda (s) (funcall pred (concat prefix s))))
161 (t ;Lists and alists.
162 (lambda (s)
163 (funcall pred (concat prefix (if (consp s) (car s) s)))))))))
a38313e1
SM
164 (if (eq (car-safe action) 'boundaries)
165 (let* ((len (length prefix))
f8381803
SM
166 (bound (completion-boundaries string table pred (cdr action))))
167 (list* 'boundaries (+ (car bound) len) (cdr bound)))
a38313e1
SM
168 (let ((comp (complete-with-action action table string pred)))
169 (cond
170 ;; In case of try-completion, add the prefix.
171 ((stringp comp) (concat prefix comp))
a38313e1 172 (t comp)))))
21622c6d
SM
173
174(defun completion-table-with-terminator (terminator table string pred action)
25c0d999
SM
175 (cond
176 ((eq action nil)
177 (let ((comp (try-completion string table pred)))
88893215
SM
178 (if (eq comp t)
179 (concat string terminator)
180 (if (and (stringp comp)
25c0d999 181 (eq (try-completion comp table pred) t))
88893215 182 (concat comp terminator)
25c0d999 183 comp))))
a38313e1
SM
184 ((eq action t)
185 ;; FIXME: We generally want the `try' and `all' behaviors to be
186 ;; consistent so pcm can merge the `all' output to get the `try' output,
187 ;; but that sometimes clashes with the need for `all' output to look
188 ;; good in *Completions*.
125f7951
SM
189 ;; (mapcar (lambda (s) (concat s terminator))
190 ;; (all-completions string table pred))))
a38313e1 191 (all-completions string table pred))
25c0d999
SM
192 ;; completion-table-with-terminator is always used for
193 ;; "sub-completions" so it's only called if the terminator is missing,
194 ;; in which case `test-completion' should return nil.
195 ((eq action 'lambda) nil)))
196
197(defun completion-table-with-predicate (table pred1 strict string pred2 action)
198 "Make a completion table equivalent to TABLE but filtered through PRED1.
cf43708e 199PRED1 is a function of one argument which returns non-nil if and only if the
25c0d999
SM
200argument is an element of TABLE which should be considered for completion.
201STRING, PRED2, and ACTION are the usual arguments to completion tables,
202as described in `try-completion', `all-completions', and `test-completion'.
3911966b
SM
203If STRICT is t, the predicate always applies; if nil it only applies if
204it does not reduce the set of possible completions to nothing.
25c0d999
SM
205Note: TABLE needs to be a proper completion table which obeys predicates."
206 (cond
207 ((and (not strict) (eq action 'lambda))
208 ;; Ignore pred1 since it doesn't really have to apply anyway.
af48580e 209 (test-completion string table pred2))
25c0d999
SM
210 (t
211 (or (complete-with-action action table string
212 (if (null pred2) pred1
213 (lexical-let ((pred1 pred2) (pred2 pred2))
214 (lambda (x)
215 ;; Call `pred1' first, so that `pred2'
216 ;; really can't tell that `x' is in table.
217 (if (funcall pred1 x) (funcall pred2 x))))))
218 ;; If completion failed and we're not applying pred1 strictly, try
219 ;; again without pred1.
220 (and (not strict)
221 (complete-with-action action table string pred2))))))
21622c6d 222
e2947429
SM
223(defun completion-table-in-turn (&rest tables)
224 "Create a completion table that tries each table in TABLES in turn."
225 (lexical-let ((tables tables))
21622c6d 226 (lambda (string pred action)
e2947429
SM
227 (completion--some (lambda (table)
228 (complete-with-action action table string pred))
229 tables))))
230
25c0d999
SM
231;; (defmacro complete-in-turn (a b) `(completion-table-in-turn ,a ,b))
232;; (defmacro dynamic-completion-table (fun) `(completion-table-dynamic ,fun))
e2947429
SM
233(define-obsolete-function-alias
234 'complete-in-turn 'completion-table-in-turn "23.1")
25c0d999
SM
235(define-obsolete-function-alias
236 'dynamic-completion-table 'completion-table-dynamic "23.1")
21622c6d
SM
237
238;;; Minibuffer completion
239
ba5ff07b
SM
240(defgroup minibuffer nil
241 "Controlling the behavior of the minibuffer."
242 :link '(custom-manual "(emacs)Minibuffer")
243 :group 'environment)
244
32bae13c
SM
245(defun minibuffer-message (message &rest args)
246 "Temporarily display MESSAGE at the end of the minibuffer.
247The text is displayed for `minibuffer-message-timeout' seconds,
248or until the next input event arrives, whichever comes first.
249Enclose MESSAGE in [...] if this is not yet the case.
250If ARGS are provided, then pass MESSAGE through `format'."
251 ;; Clear out any old echo-area message to make way for our new thing.
252 (message nil)
9f3618b5 253 (setq message (if (and (null args) (string-match-p "\\` *\\[.+\\]\\'" message))
bd5c2732
SM
254 ;; Make sure we can put-text-property.
255 (copy-sequence message)
256 (concat " [" message "]")))
32bae13c 257 (when args (setq message (apply 'format message args)))
24f7ee4c 258 (let ((ol (make-overlay (point-max) (point-max) nil t t))
eee6de73
SM
259 ;; A quit during sit-for normally only interrupts the sit-for,
260 ;; but since minibuffer-message is used at the end of a command,
261 ;; at a time when the command has virtually finished already, a C-g
262 ;; should really cause an abort-recursive-edit instead (i.e. as if
263 ;; the C-g had been typed at top-level). Binding inhibit-quit here
264 ;; is an attempt to get that behavior.
24f7ee4c 265 (inhibit-quit t))
32bae13c
SM
266 (unwind-protect
267 (progn
bf87d5fc
SM
268 (unless (zerop (length message))
269 ;; The current C cursor code doesn't know to use the overlay's
270 ;; marker's stickiness to figure out whether to place the cursor
271 ;; before or after the string, so let's spoon-feed it the pos.
272 (put-text-property 0 1 'cursor t message))
32bae13c
SM
273 (overlay-put ol 'after-string message)
274 (sit-for (or minibuffer-message-timeout 1000000)))
275 (delete-overlay ol))))
276
277(defun minibuffer-completion-contents ()
278 "Return the user input in a minibuffer before point as a string.
279That is what completion commands operate on."
280 (buffer-substring (field-beginning) (point)))
281
282(defun delete-minibuffer-contents ()
283 "Delete all user input in a minibuffer.
284If the current buffer is not a minibuffer, erase its entire contents."
8c9f211f
CY
285 ;; We used to do `delete-field' here, but when file name shadowing
286 ;; is on, the field doesn't cover the entire minibuffer contents.
287 (delete-region (minibuffer-prompt-end) (point-max)))
32bae13c 288
ba5ff07b
SM
289(defcustom completion-auto-help t
290 "Non-nil means automatically provide help for invalid completion input.
291If the value is t the *Completion* buffer is displayed whenever completion
292is requested but cannot be done.
293If the value is `lazy', the *Completions* buffer is only displayed after
294the second failed attempt to complete."
e1bb0fe5 295 :type '(choice (const nil) (const t) (const lazy))
ba5ff07b
SM
296 :group 'minibuffer)
297
e2947429 298(defvar completion-styles-alist
19c04f39
SM
299 '((basic completion-basic-try-completion completion-basic-all-completions)
300 (emacs22 completion-emacs22-try-completion completion-emacs22-all-completions)
301 (emacs21 completion-emacs21-try-completion completion-emacs21-all-completions)
34200787
SM
302 (partial-completion
303 completion-pcm-try-completion completion-pcm-all-completions))
e2947429
SM
304 "List of available completion styles.
305Each element has the form (NAME TRY-COMPLETION ALL-COMPLETIONS)
26c548b0 306where NAME is the name that should be used in `completion-styles',
e2947429
SM
307TRY-COMPLETION is the function that does the completion, and
308ALL-COMPLETIONS is the function that lists the completions.")
309
68b113f6 310(defcustom completion-styles '(basic partial-completion emacs22)
e2947429
SM
311 "List of completion styles to use."
312 :type `(repeat (choice ,@(mapcar (lambda (x) (list 'const (car x)))
313 completion-styles-alist)))
314 :group 'minibuffer
315 :version "23.1")
316
19c04f39
SM
317(defun completion-try-completion (string table pred point)
318 "Try to complete STRING using completion table TABLE.
319Only the elements of table that satisfy predicate PRED are considered.
320POINT is the position of point within STRING.
321The return value can be either nil to indicate that there is no completion,
322t to indicate that STRING is the only possible completion,
323or a pair (STRING . NEWPOINT) of the completed result string together with
324a new position for point."
3911966b
SM
325 ;; The property `completion-styles' indicates that this functional
326 ;; completion-table claims to take care of completion styles itself.
327 ;; [I.e. It will most likely call us back at some point. ]
328 (if (and (symbolp table) (get table 'completion-styles))
19c04f39
SM
329 ;; Extended semantics for functional completion-tables:
330 ;; They accept a 4th argument `point' and when called with action=nil
331 ;; and this 4th argument (a position inside `string'), they should
332 ;; return instead of a string a pair (STRING . NEWPOINT).
333 (funcall table string pred nil point)
e2947429 334 (completion--some (lambda (style)
2ed430f4 335 (funcall (nth 1 (assq style completion-styles-alist))
19c04f39 336 string table pred point))
e2947429
SM
337 completion-styles)))
338
19c04f39
SM
339(defun completion-all-completions (string table pred point)
340 "List the possible completions of STRING in completion table TABLE.
341Only the elements of table that satisfy predicate PRED are considered.
342POINT is the position of point within STRING.
26c548b0 343The return value is a list of completions and may contain the base-size
19c04f39 344in the last `cdr'."
125f7951
SM
345 ;; The property `completion-styles' indicates that this functional
346 ;; completion-table claims to take care of completion styles itself.
347 ;; [I.e. It will most likely call us back at some point. ]
348 (if (and (symbolp table) (get table 'completion-styles))
349 ;; Extended semantics for functional completion-tables:
350 ;; They accept a 4th argument `point' and when called with action=t
351 ;; and this 4th argument (a position inside `string'), they may
352 ;; return BASE-SIZE in the last `cdr'.
353 (funcall table string pred t point)
354 (completion--some (lambda (style)
355 (funcall (nth 2 (assq style completion-styles-alist))
356 string table pred point))
357 completion-styles)))
e2947429 358
ba5ff07b
SM
359(defun minibuffer--bitset (modified completions exact)
360 (logior (if modified 4 0)
361 (if completions 2 0)
362 (if exact 1 0)))
363
3911966b 364(defun completion--do-completion (&optional try-completion-function)
32bae13c 365 "Do the completion and return a summary of what happened.
ba5ff07b
SM
366M = completion was performed, the text was Modified.
367C = there were available Completions.
368E = after completion we now have an Exact match.
369
370 MCE
371 000 0 no possible completion
372 001 1 was already an exact and unique completion
373 010 2 no completion happened
374 011 3 was already an exact completion
375 100 4 ??? impossible
376 101 5 ??? impossible
377 110 6 some completion happened
378 111 7 completed to an exact completion"
379 (let* ((beg (field-beginning))
19c04f39 380 (end (field-end))
3911966b 381 (string (buffer-substring beg end))
19c04f39
SM
382 (comp (funcall (or try-completion-function
383 'completion-try-completion)
384 string
385 minibuffer-completion-table
386 minibuffer-completion-predicate
387 (- (point) beg))))
32bae13c 388 (cond
19c04f39 389 ((null comp)
ba5ff07b 390 (ding) (minibuffer-message "No match") (minibuffer--bitset nil nil nil))
19c04f39 391 ((eq t comp) (minibuffer--bitset nil nil t)) ;Exact and unique match.
32bae13c
SM
392 (t
393 ;; `completed' should be t if some completion was done, which doesn't
394 ;; include simply changing the case of the entered string. However,
395 ;; for appearance, the string is rewritten if the case changes.
19c04f39
SM
396 (let* ((comp-pos (cdr comp))
397 (completion (car comp))
398 (completed (not (eq t (compare-strings completion nil nil
399 string nil nil t))))
3911966b
SM
400 (unchanged (eq t (compare-strings completion nil nil
401 string nil nil nil))))
32bae13c 402 (unless unchanged
ba5ff07b
SM
403
404 ;; Insert in minibuffer the chars we got.
3911966b
SM
405 (goto-char end)
406 (insert completion)
81ff9458
SM
407 (delete-region beg end))
408 ;; Move point.
409 (goto-char (+ beg comp-pos))
ba5ff07b 410
32bae13c
SM
411 (if (not (or unchanged completed))
412 ;; The case of the string changed, but that's all. We're not sure
413 ;; whether this is a unique completion or not, so try again using
414 ;; the real case (this shouldn't recurse again, because the next
415 ;; time try-completion will return either t or the exact string).
3911966b 416 (completion--do-completion try-completion-function)
32bae13c
SM
417
418 ;; It did find a match. Do we match some possibility exactly now?
19c04f39 419 (let ((exact (test-completion completion
32bae13c
SM
420 minibuffer-completion-table
421 minibuffer-completion-predicate)))
ba5ff07b
SM
422 (unless completed
423 ;; Show the completion table, if requested.
424 (cond
425 ((not exact)
426 (if (case completion-auto-help
427 (lazy (eq this-command last-command))
428 (t completion-auto-help))
429 (minibuffer-completion-help)
430 (minibuffer-message "Next char not unique")))
431 ;; If the last exact completion and this one were the same,
432 ;; it means we've already given a "Complete but not unique"
433 ;; message and the user's hit TAB again, so now we give him help.
434 ((eq this-command last-command)
435 (if completion-auto-help (minibuffer-completion-help)))))
436
437 (minibuffer--bitset completed t exact))))))))
32bae13c
SM
438
439(defun minibuffer-complete ()
440 "Complete the minibuffer contents as far as possible.
441Return nil if there is no valid completion, else t.
442If no characters can be completed, display a list of possible completions.
443If you repeat this command after it displayed such a list,
444scroll the window of possible completions."
445 (interactive)
446 ;; If the previous command was not this,
447 ;; mark the completion buffer obsolete.
448 (unless (eq this-command last-command)
449 (setq minibuffer-scroll-window nil))
450
451 (let ((window minibuffer-scroll-window))
452 ;; If there's a fresh completion window with a live buffer,
453 ;; and this command is repeated, scroll that window.
454 (if (window-live-p window)
455 (with-current-buffer (window-buffer window)
456 (if (pos-visible-in-window-p (point-max) window)
457 ;; If end is in view, scroll up to the beginning.
458 (set-window-start window (point-min) nil)
459 ;; Else scroll down one screen.
460 (scroll-other-window))
461 nil)
462
3911966b 463 (case (completion--do-completion)
a38313e1
SM
464 (#b000 nil)
465 (#b001 (goto-char (field-end))
466 (minibuffer-message "Sole completion")
467 t)
468 (#b011 (goto-char (field-end))
469 (minibuffer-message "Complete, but not unique")
470 t)
471 (t t)))))
32bae13c 472
14c24780
SM
473(defvar completion-all-sorted-completions nil)
474(make-variable-buffer-local 'completion-all-sorted-completions)
475
476(defun completion--flush-all-sorted-completions (&rest ignore)
477 (setq completion-all-sorted-completions nil))
478
479(defun completion-all-sorted-completions ()
480 (or completion-all-sorted-completions
481 (let* ((start (field-beginning))
482 (end (field-end))
483 (all (completion-all-completions (buffer-substring start end)
484 minibuffer-completion-table
485 minibuffer-completion-predicate
486 (- (point) start)))
487 (last (last all))
488 (base-size (or (cdr last) 0)))
489 (when last
490 (setcdr last nil)
491 ;; Prefer shorter completions.
492 (setq all (sort all (lambda (c1 c2) (< (length c1) (length c2)))))
493 ;; Prefer recently used completions.
494 (let ((hist (symbol-value minibuffer-history-variable)))
495 (setq all (sort all (lambda (c1 c2)
496 (> (length (member c1 hist))
497 (length (member c2 hist)))))))
498 ;; Cache the result. This is not just for speed, but also so that
499 ;; repeated calls to minibuffer-force-complete can cycle through
500 ;; all possibilities.
501 (add-hook 'after-change-functions
502 'completion--flush-all-sorted-completions nil t)
503 (setq completion-all-sorted-completions
504 (nconc all base-size))))))
505
506(defun minibuffer-force-complete ()
507 "Complete the minibuffer to an exact match.
508Repeated uses step through the possible completions."
509 (interactive)
510 ;; FIXME: Need to deal with the extra-size issue here as well.
511 (let* ((start (field-beginning))
512 (end (field-end))
513 (all (completion-all-sorted-completions)))
514 (if (not (consp all))
515 (minibuffer-message (if all "No more completions" "No completions"))
516 (goto-char end)
517 (insert (car all))
518 (delete-region (+ start (cdr (last all))) end)
519 ;; If completing file names, (car all) may be a directory, so we'd now
520 ;; have a new set of possible completions and might want to reset
521 ;; completion-all-sorted-completions to nil, but we prefer not to,
522 ;; so that repeated calls minibuffer-force-complete still cycle
523 ;; through the previous possible completions.
524 (setq completion-all-sorted-completions (cdr all)))))
525
d1826585 526(defvar minibuffer-confirm-exit-commands
a25c543a 527 '(minibuffer-complete minibuffer-complete-word PC-complete PC-complete-word)
d1826585
MB
528 "A list of commands which cause an immediately following
529`minibuffer-complete-and-exit' to ask for extra confirmation.")
530
32bae13c 531(defun minibuffer-complete-and-exit ()
bec1e8a5
CY
532 "Exit if the minibuffer contains a valid completion.
533Otherwise, try to complete the minibuffer contents. If
534completion leads to a valid completion, a repetition of this
535command will exit.
536
537If `minibuffer-completion-confirm' is `confirm', do not try to
538 complete; instead, ask for confirmation and accept any input if
539 confirmed.
540If `minibuffer-completion-confirm' is `confirm-after-completion',
541 do not try to complete; instead, ask for confirmation if the
90810a8e
CY
542 preceding minibuffer command was a member of
543 `minibuffer-confirm-exit-commands', and accept the input
544 otherwise."
32bae13c 545 (interactive)
3911966b
SM
546 (let ((beg (field-beginning))
547 (end (field-end)))
548 (cond
549 ;; Allow user to specify null string
550 ((= beg end) (exit-minibuffer))
551 ((test-completion (buffer-substring beg end)
552 minibuffer-completion-table
553 minibuffer-completion-predicate)
554 (when completion-ignore-case
555 ;; Fixup case of the field, if necessary.
b0a5a021 556 (let* ((string (buffer-substring beg end))
3911966b
SM
557 (compl (try-completion
558 string
559 minibuffer-completion-table
560 minibuffer-completion-predicate)))
561 (when (and (stringp compl)
562 ;; If it weren't for this piece of paranoia, I'd replace
563 ;; the whole thing with a call to do-completion.
eee6de73
SM
564 ;; This is important, e.g. when the current minibuffer's
565 ;; content is a directory which only contains a single
566 ;; file, so `try-completion' actually completes to
567 ;; that file.
3911966b 568 (= (length string) (length compl)))
32bae13c
SM
569 (goto-char end)
570 (insert compl)
3911966b
SM
571 (delete-region beg end))))
572 (exit-minibuffer))
32bae13c 573
bec1e8a5 574 ((eq minibuffer-completion-confirm 'confirm)
3911966b 575 ;; The user is permitted to exit with an input that's rejected
bec1e8a5 576 ;; by test-completion, after confirming her choice.
3911966b
SM
577 (if (eq last-command this-command)
578 (exit-minibuffer)
579 (minibuffer-message "Confirm")
580 nil))
32bae13c 581
bec1e8a5
CY
582 ((eq minibuffer-completion-confirm 'confirm-after-completion)
583 ;; Similar to the above, but only if trying to exit immediately
584 ;; after typing TAB (this catches most minibuffer typos).
d1826585 585 (if (memq last-command minibuffer-confirm-exit-commands)
bec1e8a5
CY
586 (progn (minibuffer-message "Confirm")
587 nil)
588 (exit-minibuffer)))
589
3911966b
SM
590 (t
591 ;; Call do-completion, but ignore errors.
592 (case (condition-case nil
593 (completion--do-completion)
594 (error 1))
a38313e1
SM
595 ((#b001 #b011) (exit-minibuffer))
596 (#b111 (if (not minibuffer-completion-confirm)
597 (exit-minibuffer)
598 (minibuffer-message "Confirm")
599 nil))
3911966b
SM
600 (t nil))))))
601
19c04f39
SM
602(defun completion--try-word-completion (string table predicate point)
603 (let ((comp (completion-try-completion string table predicate point)))
604 (if (not (consp comp))
605 comp
32bae13c 606
3911966b
SM
607 ;; If completion finds next char not unique,
608 ;; consider adding a space or a hyphen.
19c04f39 609 (when (= (length string) (length (car comp)))
1afbbf85
SM
610 ;; Mark the added char with the `completion-word' property, so it
611 ;; can be handled specially by completion styles such as
612 ;; partial-completion.
613 ;; We used to remove `partial-completion' from completion-styles
614 ;; instead, but it was too blunt, leading to situations where SPC
615 ;; was the only insertable char at point but minibuffer-complete-word
616 ;; refused inserting it.
617 (let ((exts (mapcar (lambda (str) (propertize str 'completion-try-word t))
618 '(" " "-")))
19c04f39
SM
619 (before (substring string 0 point))
620 (after (substring string point))
621 tem)
622 (while (and exts (not (consp tem)))
3911966b 623 (setq tem (completion-try-completion
19c04f39
SM
624 (concat before (pop exts) after)
625 table predicate (1+ point))))
626 (if (consp tem) (setq comp tem))))
3911966b 627
32bae13c
SM
628 ;; Completing a single word is actually more difficult than completing
629 ;; as much as possible, because we first have to find the "current
630 ;; position" in `completion' in order to find the end of the word
631 ;; we're completing. Normally, `string' is a prefix of `completion',
632 ;; which makes it trivial to find the position, but with fancier
633 ;; completion (plus env-var expansion, ...) `completion' might not
634 ;; look anything like `string' at all.
19c04f39
SM
635 (let* ((comppoint (cdr comp))
636 (completion (car comp))
637 (before (substring string 0 point))
638 (combined (concat before "\n" completion)))
639 ;; Find in completion the longest text that was right before point.
640 (when (string-match "\\(.+\\)\n.*?\\1" combined)
641 (let* ((prefix (match-string 1 before))
642 ;; We used non-greedy match to make `rem' as long as possible.
643 (rem (substring combined (match-end 0)))
644 ;; Find in the remainder of completion the longest text
645 ;; that was right after point.
646 (after (substring string point))
647 (suffix (if (string-match "\\`\\(.+\\).*\n.*\\1"
648 (concat after "\n" rem))
649 (match-string 1 after))))
650 ;; The general idea is to try and guess what text was inserted
651 ;; at point by the completion. Problem is: if we guess wrong,
652 ;; we may end up treating as "added by completion" text that was
653 ;; actually painfully typed by the user. So if we then cut
654 ;; after the first word, we may throw away things the
655 ;; user wrote. So let's try to be as conservative as possible:
656 ;; only cut after the first word, if we're reasonably sure that
657 ;; our guess is correct.
658 ;; Note: a quick survey on emacs-devel seemed to indicate that
659 ;; nobody actually cares about the "word-at-a-time" feature of
660 ;; minibuffer-complete-word, whose real raison-d'être is that it
661 ;; tries to add "-" or " ". One more reason to only cut after
662 ;; the first word, if we're really sure we're right.
663 (when (and (or suffix (zerop (length after)))
664 (string-match (concat
665 ;; Make submatch 1 as small as possible
666 ;; to reduce the risk of cutting
667 ;; valuable text.
668 ".*" (regexp-quote prefix) "\\(.*?\\)"
669 (if suffix (regexp-quote suffix) "\\'"))
670 completion)
671 ;; The new point in `completion' should also be just
672 ;; before the suffix, otherwise something more complex
673 ;; is going on, and we're not sure where we are.
674 (eq (match-end 1) comppoint)
675 ;; (match-beginning 1)..comppoint is now the stretch
676 ;; of text in `completion' that was completed at point.
677 (string-match "\\W" completion (match-beginning 1))
678 ;; Is there really something to cut?
679 (> comppoint (match-end 0)))
680 ;; Cut after the first word.
681 (let ((cutpos (match-end 0)))
682 (setq completion (concat (substring completion 0 cutpos)
683 (substring completion comppoint)))
684 (setq comppoint cutpos)))))
685
686 (cons completion comppoint)))))
ba5ff07b
SM
687
688
689(defun minibuffer-complete-word ()
690 "Complete the minibuffer contents at most a single word.
691After one word is completed as much as possible, a space or hyphen
692is added, provided that matches some possible completion.
693Return nil if there is no valid completion, else t."
694 (interactive)
3911966b 695 (case (completion--do-completion 'completion--try-word-completion)
a38313e1
SM
696 (#b000 nil)
697 (#b001 (goto-char (field-end))
698 (minibuffer-message "Sole completion")
699 t)
700 (#b011 (goto-char (field-end))
701 (minibuffer-message "Complete, but not unique")
702 t)
703 (t t)))
ba5ff07b 704
3911966b 705(defun completion--insert-strings (strings)
32bae13c
SM
706 "Insert a list of STRINGS into the current buffer.
707Uses columns to keep the listing readable but compact.
708It also eliminates runs of equal strings."
709 (when (consp strings)
710 (let* ((length (apply 'max
711 (mapcar (lambda (s)
712 (if (consp s)
e5b5b82d
SM
713 (+ (string-width (car s))
714 (string-width (cadr s)))
715 (string-width s)))
32bae13c
SM
716 strings)))
717 (window (get-buffer-window (current-buffer) 0))
718 (wwidth (if window (1- (window-width window)) 79))
719 (columns (min
720 ;; At least 2 columns; at least 2 spaces between columns.
721 (max 2 (/ wwidth (+ 2 length)))
722 ;; Don't allocate more columns than we can fill.
723 ;; Windows can't show less than 3 lines anyway.
724 (max 1 (/ (length strings) 2))))
725 (colwidth (/ wwidth columns))
726 (column 0)
727 (laststring nil))
728 ;; The insertion should be "sensible" no matter what choices were made
729 ;; for the parameters above.
730 (dolist (str strings)
f87ff539 731 (unless (equal laststring str) ; Remove (consecutive) duplicates.
32bae13c 732 (setq laststring str)
f87ff539
SM
733 (let ((length (if (consp str)
734 (+ (string-width (car str))
735 (string-width (cadr str)))
736 (string-width str))))
737 (unless (bolp)
738 (if (< wwidth (+ (max colwidth length) column))
739 ;; No space for `str' at point, move to next line.
740 (progn (insert "\n") (setq column 0))
741 (insert " \t")
742 ;; Leave the space unpropertized so that in the case we're
743 ;; already past the goal column, there is still
744 ;; a space displayed.
745 (set-text-properties (- (point) 1) (point)
746 ;; We can't just set tab-width, because
747 ;; completion-setup-function will kill all
748 ;; local variables :-(
749 `(display (space :align-to ,column)))
750 nil))
751 (if (not (consp str))
752 (put-text-property (point) (progn (insert str) (point))
753 'mouse-face 'highlight)
754 (put-text-property (point) (progn (insert (car str)) (point))
755 'mouse-face 'highlight)
756 (put-text-property (point) (progn (insert (cadr str)) (point))
757 'mouse-face nil))
758 ;; Next column to align to.
759 (setq column (+ column
760 ;; Round up to a whole number of columns.
761 (* colwidth (ceiling length colwidth))))))))))
32bae13c 762
6138158d
SM
763(defvar completion-common-substring nil)
764(make-obsolete-variable 'completion-common-substring nil "23.1")
32bae13c 765
21622c6d
SM
766(defvar completion-setup-hook nil
767 "Normal hook run at the end of setting up a completion list buffer.
768When this hook is run, the current buffer is the one in which the
769command to display the completion list buffer was run.
770The completion list buffer is available as the value of `standard-output'.
6138158d
SM
771See also `display-completion-list'.")
772
773(defface completions-first-difference
774 '((t (:inherit bold)))
775 "Face put on the first uncommon character in completions in *Completions* buffer."
776 :group 'completion)
777
778(defface completions-common-part
779 '((t (:inherit default)))
780 "Face put on the common prefix substring in completions in *Completions* buffer.
781The idea of `completions-common-part' is that you can use it to
782make the common parts less visible than normal, so that the rest
783of the differing parts is, by contrast, slightly highlighted."
784 :group 'completion)
785
125f7951 786(defun completion-hilit-commonality (completions prefix-len base-size)
6138158d 787 (when completions
125f7951 788 (let ((com-str-len (- prefix-len (or base-size 0))))
6138158d
SM
789 (nconc
790 (mapcar
457d37ba
SM
791 (lambda (elem)
792 (let ((str
793 ;; Don't modify the string itself, but a copy, since the
794 ;; the string may be read-only or used for other purposes.
795 ;; Furthermore, since `completions' may come from
796 ;; display-completion-list, `elem' may be a list.
797 (if (consp elem)
798 (car (setq elem (cons (copy-sequence (car elem))
799 (cdr elem))))
800 (setq elem (copy-sequence elem)))))
1bba1cfc
SM
801 (put-text-property 0
802 ;; If completion-boundaries returns incorrect
803 ;; values, all-completions may return strings
804 ;; that don't contain the prefix.
805 (min com-str-len (length str))
457d37ba
SM
806 'font-lock-face 'completions-common-part
807 str)
808 (if (> (length str) com-str-len)
809 (put-text-property com-str-len (1+ com-str-len)
810 'font-lock-face 'completions-first-difference
811 str)))
812 elem)
6138158d
SM
813 completions)
814 base-size))))
21622c6d 815
7bc7f64d 816(defun display-completion-list (completions &optional common-substring)
32bae13c
SM
817 "Display the list of completions, COMPLETIONS, using `standard-output'.
818Each element may be just a symbol or string
819or may be a list of two strings to be printed as if concatenated.
820If it is a list of two strings, the first is the actual completion
821alternative, the second serves as annotation.
822`standard-output' must be a buffer.
823The actual completion alternatives, as inserted, are given `mouse-face'
824properties of `highlight'.
825At the end, this runs the normal hook `completion-setup-hook'.
826It can find the completion buffer in `standard-output'.
7ce8dff2 827
72444d02 828The obsolete optional arg COMMON-SUBSTRING, if non-nil, should be a string
7ce8dff2
CY
829specifying a common substring for adding the faces
830`completions-first-difference' and `completions-common-part' to
7bc7f64d 831the completions buffer."
6138158d
SM
832 (if common-substring
833 (setq completions (completion-hilit-commonality
125f7951
SM
834 completions (length common-substring)
835 ;; We don't know the base-size.
836 nil)))
32bae13c
SM
837 (if (not (bufferp standard-output))
838 ;; This *never* (ever) happens, so there's no point trying to be clever.
839 (with-temp-buffer
840 (let ((standard-output (current-buffer))
841 (completion-setup-hook nil))
7bc7f64d 842 (display-completion-list completions common-substring))
32bae13c
SM
843 (princ (buffer-string)))
844
7bc7f64d
CY
845 (let ((mainbuf (current-buffer)))
846 (with-current-buffer standard-output
847 (goto-char (point-max))
848 (if (null completions)
849 (insert "There are no possible completions of what you have typed.")
850 (insert "Possible completions are:\n")
851 (let ((last (last completions)))
852 ;; Set base-size from the tail of the list.
853 (set (make-local-variable 'completion-base-size)
854 (or (cdr last)
855 (and (minibufferp mainbuf) 0)))
856 (setcdr last nil)) ; Make completions a properly nil-terminated list.
857 (completion--insert-strings completions)))))
e2947429 858
6138158d
SM
859 ;; The hilit used to be applied via completion-setup-hook, so there
860 ;; may still be some code that uses completion-common-substring.
7ce8dff2
CY
861 (with-no-warnings
862 (let ((completion-common-substring common-substring))
863 (run-hooks 'completion-setup-hook)))
32bae13c
SM
864 nil)
865
866(defun minibuffer-completion-help ()
867 "Display a list of possible completions of the current minibuffer contents."
868 (interactive)
869 (message "Making completion list...")
870 (let* ((string (field-string))
3911966b 871 (completions (completion-all-completions
32bae13c
SM
872 string
873 minibuffer-completion-table
19c04f39
SM
874 minibuffer-completion-predicate
875 (- (point) (field-beginning)))))
32bae13c
SM
876 (message nil)
877 (if (and completions
e2947429
SM
878 (or (consp (cdr completions))
879 (not (equal (car completions) string))))
32bae13c 880 (with-output-to-temp-buffer "*Completions*"
e2947429
SM
881 (let* ((last (last completions))
882 (base-size (cdr last)))
883 ;; Remove the base-size tail because `sort' requires a properly
884 ;; nil-terminated list.
885 (when last (setcdr last nil))
886 (display-completion-list (nconc (sort completions 'string-lessp)
887 base-size))))
32bae13c
SM
888
889 ;; If there are no completions, or if the current input is already the
890 ;; only possible completion, then hide (previous&stale) completions.
891 (let ((window (and (get-buffer "*Completions*")
892 (get-buffer-window "*Completions*" 0))))
893 (when (and (window-live-p window) (window-dedicated-p window))
894 (condition-case ()
895 (delete-window window)
896 (error (iconify-frame (window-frame window))))))
897 (ding)
898 (minibuffer-message
899 (if completions "Sole completion" "No completions")))
900 nil))
901
902(defun exit-minibuffer ()
903 "Terminate this minibuffer argument."
904 (interactive)
905 ;; If the command that uses this has made modifications in the minibuffer,
906 ;; we don't want them to cause deactivation of the mark in the original
907 ;; buffer.
908 ;; A better solution would be to make deactivate-mark buffer-local
909 ;; (or to turn it into a list of buffers, ...), but in the mean time,
910 ;; this should do the trick in most cases.
ba5ff07b 911 (setq deactivate-mark nil)
32bae13c
SM
912 (throw 'exit nil))
913
914(defun self-insert-and-exit ()
915 "Terminate minibuffer input."
916 (interactive)
8989a920 917 (if (characterp last-command-event)
32bae13c
SM
918 (call-interactively 'self-insert-command)
919 (ding))
920 (exit-minibuffer))
921
a38313e1
SM
922;;; Key bindings.
923
8ba31f36
SM
924(define-obsolete-variable-alias 'minibuffer-local-must-match-filename-map
925 'minibuffer-local-filename-must-match-map "23.1")
926
a38313e1
SM
927(let ((map minibuffer-local-map))
928 (define-key map "\C-g" 'abort-recursive-edit)
929 (define-key map "\r" 'exit-minibuffer)
930 (define-key map "\n" 'exit-minibuffer))
931
932(let ((map minibuffer-local-completion-map))
933 (define-key map "\t" 'minibuffer-complete)
14c24780
SM
934 ;; M-TAB is already abused for many other purposes, so we should find
935 ;; another binding for it.
936 ;; (define-key map "\e\t" 'minibuffer-force-complete)
a38313e1
SM
937 (define-key map " " 'minibuffer-complete-word)
938 (define-key map "?" 'minibuffer-completion-help))
939
940(let ((map minibuffer-local-must-match-map))
941 (define-key map "\r" 'minibuffer-complete-and-exit)
942 (define-key map "\n" 'minibuffer-complete-and-exit))
943
944(let ((map minibuffer-local-filename-completion-map))
945 (define-key map " " nil))
8ba31f36 946(let ((map minibuffer-local-filename-must-match-map))
a38313e1
SM
947 (define-key map " " nil))
948
949(let ((map minibuffer-local-ns-map))
950 (define-key map " " 'exit-minibuffer)
951 (define-key map "\t" 'exit-minibuffer)
952 (define-key map "?" 'self-insert-and-exit))
953
954;;; Completion tables.
955
34b67b0f
SM
956(defun minibuffer--double-dollars (str)
957 (replace-regexp-in-string "\\$" "$$" str))
958
21622c6d
SM
959(defun completion--make-envvar-table ()
960 (mapcar (lambda (enventry)
9f3618b5 961 (substring enventry 0 (string-match-p "=" enventry)))
21622c6d
SM
962 process-environment))
963
a38313e1
SM
964(defconst completion--embedded-envvar-re
965 (concat "\\(?:^\\|[^$]\\(?:\\$\\$\\)*\\)"
966 "$\\([[:alnum:]_]*\\|{\\([^}]*\\)\\)\\'"))
967
21622c6d 968(defun completion--embedded-envvar-table (string pred action)
a38313e1
SM
969 (if (eq (car-safe action) 'boundaries)
970 ;; Compute the boundaries of the subfield to which this
971 ;; completion applies.
f8381803
SM
972 (let ((suffix (cdr action)))
973 (if (string-match completion--embedded-envvar-re string)
974 (list* 'boundaries
975 (or (match-beginning 2) (match-beginning 1))
a38313e1 976 (when (string-match "[^[:alnum:]_]" suffix)
f8381803 977 (match-beginning 0)))))
a38313e1
SM
978 (when (string-match completion--embedded-envvar-re string)
979 (let* ((beg (or (match-beginning 2) (match-beginning 1)))
980 (table (completion--make-envvar-table))
981 (prefix (substring string 0 beg)))
982 (if (eq (aref string (1- beg)) ?{)
983 (setq table (apply-partially 'completion-table-with-terminator
984 "}" table)))
985 (completion-table-with-context
986 prefix table (substring string beg) pred action)))))
017c22fe 987
f50e56f0 988(defun completion--file-name-table (string pred action)
b95c7600 989 "Internal subroutine for `read-file-name'. Do not call this."
a38313e1
SM
990 (cond
991 ((and (zerop (length string)) (eq 'lambda action))
992 nil) ; FIXME: why?
993 ((eq (car-safe action) 'boundaries)
994 ;; FIXME: Actually, this is not always right in the presence of
995 ;; envvars, but there's not much we can do, I think.
f8381803 996 (let ((start (length (file-name-directory string)))
9f3618b5 997 (end (string-match-p "/" (cdr action))))
a38313e1 998 (list* 'boundaries start end)))
d9aa6b33 999
a38313e1 1000 (t
f50e56f0
SM
1001 (let* ((dir (if (stringp pred)
1002 ;; It used to be that `pred' was abused to pass `dir'
1003 ;; as an argument.
1004 (prog1 (expand-file-name pred) (setq pred nil))
1005 default-directory))
1006 (str (condition-case nil
21622c6d
SM
1007 (substitute-in-file-name string)
1008 (error string)))
34b67b0f
SM
1009 (name (file-name-nondirectory str))
1010 (specdir (file-name-directory str))
1011 (realdir (if specdir (expand-file-name specdir dir)
1012 (file-name-as-directory dir))))
017c22fe 1013
34b67b0f
SM
1014 (cond
1015 ((null action)
1016 (let ((comp (file-name-completion name realdir
1017 read-file-name-predicate)))
1018 (if (stringp comp)
1019 ;; Requote the $s before returning the completion.
1020 (minibuffer--double-dollars (concat specdir comp))
1021 ;; Requote the $s before checking for changes.
1022 (setq str (minibuffer--double-dollars str))
1023 (if (string-equal string str)
1024 comp
1025 ;; If there's no real completion, but substitute-in-file-name
1026 ;; changed the string, then return the new string.
1027 str))))
017c22fe 1028
34b67b0f 1029 ((eq action t)
125f7951 1030 (let ((all (file-name-all-completions name realdir)))
e2947429
SM
1031
1032 ;; Check the predicate, if necessary.
1033 (unless (memq read-file-name-predicate '(nil file-exists-p))
34b67b0f
SM
1034 (let ((comp ())
1035 (pred
1036 (if (eq read-file-name-predicate 'file-directory-p)
1037 ;; Brute-force speed up for directory checking:
1038 ;; Discard strings which don't end in a slash.
1039 (lambda (s)
1040 (let ((len (length s)))
1041 (and (> len 0) (eq (aref s (1- len)) ?/))))
1042 ;; Must do it the hard (and slow) way.
1043 read-file-name-predicate)))
1044 (let ((default-directory realdir))
1045 (dolist (tem all)
1046 (if (funcall pred tem) (push tem comp))))
e2947429
SM
1047 (setq all (nreverse comp))))
1048
125f7951 1049 all))
34b67b0f
SM
1050
1051 (t
1052 ;; Only other case actually used is ACTION = lambda.
1053 (let ((default-directory dir))
a38313e1 1054 (funcall (or read-file-name-predicate 'file-exists-p) str))))))))
34b67b0f 1055
21622c6d 1056(defalias 'read-file-name-internal
017c22fe 1057 (completion-table-in-turn 'completion--embedded-envvar-table
88893215 1058 'completion--file-name-table)
21622c6d 1059 "Internal subroutine for `read-file-name'. Do not call this.")
34b67b0f 1060
dbd50d4b
SM
1061(defvar read-file-name-function nil
1062 "If this is non-nil, `read-file-name' does its work by calling this function.")
1063
1064(defvar read-file-name-predicate nil
1065 "Current predicate used by `read-file-name-internal'.")
1066
1067(defcustom read-file-name-completion-ignore-case
9f6336e8 1068 (if (memq system-type '(ms-dos windows-nt darwin cygwin))
dbd50d4b
SM
1069 t nil)
1070 "Non-nil means when reading a file name completion ignores case."
1071 :group 'minibuffer
1072 :type 'boolean
1073 :version "22.1")
1074
1075(defcustom insert-default-directory t
1076 "Non-nil means when reading a filename start with default dir in minibuffer.
1077
1078When the initial minibuffer contents show a name of a file or a directory,
1079typing RETURN without editing the initial contents is equivalent to typing
1080the default file name.
1081
1082If this variable is non-nil, the minibuffer contents are always
1083initially non-empty, and typing RETURN without editing will fetch the
1084default name, if one is provided. Note however that this default name
1085is not necessarily the same as initial contents inserted in the minibuffer,
1086if the initial contents is just the default directory.
1087
1088If this variable is nil, the minibuffer often starts out empty. In
1089that case you may have to explicitly fetch the next history element to
1090request the default name; typing RETURN without editing will leave
1091the minibuffer empty.
1092
1093For some commands, exiting with an empty minibuffer has a special meaning,
1094such as making the current buffer visit no file in the case of
1095`set-visited-file-name'."
1096 :group 'minibuffer
1097 :type 'boolean)
1098
4e3870f5
GM
1099;; Not always defined, but only called if next-read-file-uses-dialog-p says so.
1100(declare-function x-file-dialog "xfns.c"
1101 (prompt dir &optional default-filename mustmatch only-dir-p))
1102
dbd50d4b
SM
1103(defun read-file-name (prompt &optional dir default-filename mustmatch initial predicate)
1104 "Read file name, prompting with PROMPT and completing in directory DIR.
1105Value is not expanded---you must call `expand-file-name' yourself.
1106Default name to DEFAULT-FILENAME if user exits the minibuffer with
1107the same non-empty string that was inserted by this function.
1108 (If DEFAULT-FILENAME is omitted, the visited file name is used,
1109 except that if INITIAL is specified, that combined with DIR is used.)
1110If the user exits with an empty minibuffer, this function returns
1111an empty string. (This can only happen if the user erased the
1112pre-inserted contents or if `insert-default-directory' is nil.)
846b6eba
CY
1113
1114Fourth arg MUSTMATCH can take the following values:
1115- nil means that the user can exit with any input.
1116- t means that the user is not allowed to exit unless
1117 the input is (or completes to) an existing file.
1118- `confirm' means that the user can exit with any input, but she needs
1119 to confirm her choice if the input is not an existing file.
1120- `confirm-after-completion' means that the user can exit with any
1121 input, but she needs to confirm her choice if she called
1122 `minibuffer-complete' right before `minibuffer-complete-and-exit'
1123 and the input is not an existing file.
1124- anything else behaves like t except that typing RET does not exit if it
1125 does non-null completion.
1126
dbd50d4b 1127Fifth arg INITIAL specifies text to start with.
846b6eba 1128
dbd50d4b
SM
1129If optional sixth arg PREDICATE is non-nil, possible completions and
1130the resulting file name must satisfy (funcall PREDICATE NAME).
1131DIR should be an absolute directory name. It defaults to the value of
1132`default-directory'.
1133
846b6eba
CY
1134If this command was invoked with the mouse, use a graphical file
1135dialog if `use-dialog-box' is non-nil, and the window system or X
1136toolkit in use provides a file dialog box. For graphical file
2aafe808
JR
1137dialogs, any the special values of MUSTMATCH; `confirm' and
1138`confirm-after-completion' are treated as equivalent to nil.
dbd50d4b
SM
1139
1140See also `read-file-name-completion-ignore-case'
1141and `read-file-name-function'."
1142 (unless dir (setq dir default-directory))
1143 (unless (file-name-absolute-p dir) (setq dir (expand-file-name dir)))
1144 (unless default-filename
1145 (setq default-filename (if initial (expand-file-name initial dir)
1146 buffer-file-name)))
1147 ;; If dir starts with user's homedir, change that to ~.
1148 (setq dir (abbreviate-file-name dir))
1149 ;; Likewise for default-filename.
e8a5fe3e
SM
1150 (if default-filename
1151 (setq default-filename (abbreviate-file-name default-filename)))
dbd50d4b
SM
1152 (let ((insdef (cond
1153 ((and insert-default-directory (stringp dir))
1154 (if initial
1155 (cons (minibuffer--double-dollars (concat dir initial))
1156 (length (minibuffer--double-dollars dir)))
1157 (minibuffer--double-dollars dir)))
1158 (initial (cons (minibuffer--double-dollars initial) 0)))))
1159
1160 (if read-file-name-function
1161 (funcall read-file-name-function
1162 prompt dir default-filename mustmatch initial predicate)
e8a5fe3e 1163 (let ((completion-ignore-case read-file-name-completion-ignore-case)
dbd50d4b
SM
1164 (minibuffer-completing-file-name t)
1165 (read-file-name-predicate (or predicate 'file-exists-p))
1166 (add-to-history nil))
1167
1168 (let* ((val
1169 (if (not (next-read-file-uses-dialog-p))
e8a5fe3e
SM
1170 ;; We used to pass `dir' to `read-file-name-internal' by
1171 ;; abusing the `predicate' argument. It's better to
1172 ;; just use `default-directory', but in order to avoid
1173 ;; changing `default-directory' in the current buffer,
1174 ;; we don't let-bind it.
1175 (lexical-let ((dir (file-name-as-directory
1176 (expand-file-name dir))))
1177 (minibuffer-with-setup-hook
1178 (lambda () (setq default-directory dir))
1179 (completing-read prompt 'read-file-name-internal
1180 nil mustmatch insdef 'file-name-history
1181 default-filename)))
6462af0d
JR
1182 ;; If DEFAULT-FILENAME not supplied and DIR contains
1183 ;; a file name, split it.
2aafe808
JR
1184 (let ((file (file-name-nondirectory dir))
1185 ;; When using a dialog, revert to nil and non-nil
1186 ;; interpretation of mustmatch. confirm options
1187 ;; need to be interpreted as nil, otherwise
1188 ;; it is impossible to create new files using
1189 ;; dialogs with the default settings.
1190 (dialog-mustmatch
1191 (and (not (eq mustmatch 'confirm))
1192 (not (eq mustmatch 'confirm-after-completion))
1193 mustmatch)))
6462af0d
JR
1194 (when (and (not default-filename)
1195 (not (zerop (length file))))
dbd50d4b
SM
1196 (setq default-filename file)
1197 (setq dir (file-name-directory dir)))
1198 (if default-filename
1199 (setq default-filename
1200 (expand-file-name default-filename dir)))
1201 (setq add-to-history t)
2aafe808
JR
1202 (x-file-dialog prompt dir default-filename
1203 dialog-mustmatch
dbd50d4b
SM
1204 (eq predicate 'file-directory-p)))))
1205
1206 (replace-in-history (eq (car-safe file-name-history) val)))
1207 ;; If completing-read returned the inserted default string itself
1208 ;; (rather than a new string with the same contents),
1209 ;; it has to mean that the user typed RET with the minibuffer empty.
1210 ;; In that case, we really want to return ""
1211 ;; so that commands such as set-visited-file-name can distinguish.
1212 (when (eq val default-filename)
1213 ;; In this case, completing-read has not added an element
1214 ;; to the history. Maybe we should.
1215 (if (not replace-in-history)
1216 (setq add-to-history t))
1217 (setq val ""))
1218 (unless val (error "No file name specified"))
1219
1220 (if (and default-filename
1221 (string-equal val (if (consp insdef) (car insdef) insdef)))
1222 (setq val default-filename))
1223 (setq val (substitute-in-file-name val))
1224
1225 (if replace-in-history
1226 ;; Replace what Fcompleting_read added to the history
1227 ;; with what we will actually return.
1228 (let ((val1 (minibuffer--double-dollars val)))
1229 (if history-delete-duplicates
1230 (setcdr file-name-history
1231 (delete val1 (cdr file-name-history))))
1232 (setcar file-name-history val1))
1233 (if add-to-history
1234 ;; Add the value to the history--but not if it matches
1235 ;; the last value already there.
1236 (let ((val1 (minibuffer--double-dollars val)))
1237 (unless (and (consp file-name-history)
1238 (equal (car file-name-history) val1))
1239 (setq file-name-history
1240 (cons val1
1241 (if history-delete-duplicates
1242 (delete val1 file-name-history)
1243 file-name-history)))))))
1244 val)))))
1245
8b04c0ae
JL
1246(defun internal-complete-buffer-except (&optional buffer)
1247 "Perform completion on all buffers excluding BUFFER.
e35b3063 1248BUFFER nil or omitted means use the current buffer.
8b04c0ae
JL
1249Like `internal-complete-buffer', but removes BUFFER from the completion list."
1250 (lexical-let ((except (if (stringp buffer) buffer (buffer-name buffer))))
1251 (apply-partially 'completion-table-with-predicate
1252 'internal-complete-buffer
1253 (lambda (name)
1254 (not (equal (if (consp name) (car name) name) except)))
1255 nil)))
1256
eee6de73 1257;;; Old-style completion, used in Emacs-21 and Emacs-22.
19c04f39
SM
1258
1259(defun completion-emacs21-try-completion (string table pred point)
1260 (let ((completion (try-completion string table pred)))
1261 (if (stringp completion)
1262 (cons completion (length completion))
1263 completion)))
1264
1265(defun completion-emacs21-all-completions (string table pred point)
6138158d 1266 (completion-hilit-commonality
eee6de73 1267 (all-completions string table pred)
125f7951
SM
1268 (length string)
1269 (car (completion-boundaries string table pred ""))))
19c04f39 1270
19c04f39
SM
1271(defun completion-emacs22-try-completion (string table pred point)
1272 (let ((suffix (substring string point))
1273 (completion (try-completion (substring string 0 point) table pred)))
1274 (if (not (stringp completion))
1275 completion
1276 ;; Merge a trailing / in completion with a / after point.
1277 ;; We used to only do it for word completion, but it seems to make
1278 ;; sense for all completions.
34200787
SM
1279 ;; Actually, claiming this feature was part of Emacs-22 completion
1280 ;; is pushing it a bit: it was only done in minibuffer-completion-word,
1281 ;; which was (by default) not bound during file completion, where such
1282 ;; slashes are most likely to occur.
1283 (if (and (not (zerop (length completion)))
1284 (eq ?/ (aref completion (1- (length completion))))
19c04f39
SM
1285 (not (zerop (length suffix)))
1286 (eq ?/ (aref suffix 0)))
34200787
SM
1287 ;; This leaves point after the / .
1288 (setq suffix (substring suffix 1)))
19c04f39
SM
1289 (cons (concat completion suffix) (length completion)))))
1290
1291(defun completion-emacs22-all-completions (string table pred point)
125f7951
SM
1292 (let ((beforepoint (substring string 0 point)))
1293 (completion-hilit-commonality
1294 (all-completions beforepoint table pred)
1295 point
1296 (car (completion-boundaries beforepoint table pred "")))))
19c04f39 1297
eee6de73
SM
1298;;; Basic completion.
1299
1300(defun completion--merge-suffix (completion point suffix)
1301 "Merge end of COMPLETION with beginning of SUFFIX.
1302Simple generalization of the \"merge trailing /\" done in Emacs-22.
1303Return the new suffix."
1304 (if (and (not (zerop (length suffix)))
1305 (string-match "\\(.+\\)\n\\1" (concat completion "\n" suffix)
1306 ;; Make sure we don't compress things to less
1307 ;; than we started with.
1308 point)
1309 ;; Just make sure we didn't match some other \n.
1310 (eq (match-end 1) (length completion)))
1311 (substring suffix (- (match-end 1) (match-beginning 1)))
1312 ;; Nothing to merge.
1313 suffix))
1314
34200787 1315(defun completion-basic-try-completion (string table pred point)
eee6de73
SM
1316 (let* ((beforepoint (substring string 0 point))
1317 (afterpoint (substring string point))
86011bf2
SM
1318 (bounds (completion-boundaries beforepoint table pred afterpoint)))
1319 (if (zerop (cdr bounds))
1320 ;; `try-completion' may return a subtly different result
1321 ;; than `all+merge', so try to use it whenever possible.
1322 (let ((completion (try-completion beforepoint table pred)))
1323 (if (not (stringp completion))
1324 completion
1325 (cons
1326 (concat completion
1327 (completion--merge-suffix completion point afterpoint))
1328 (length completion))))
1329 (let* ((suffix (substring afterpoint (cdr bounds)))
1330 (prefix (substring beforepoint 0 (car bounds)))
1331 (pattern (delete
1332 "" (list (substring beforepoint (car bounds))
1333 'point
1334 (substring afterpoint 0 (cdr bounds)))))
1335 (all (completion-pcm--all-completions prefix pattern table pred)))
1336 (if minibuffer-completing-file-name
1337 (setq all (completion-pcm--filename-try-filter all)))
1338 (completion-pcm--merge-try pattern all prefix suffix)))))
1339
1340(defun completion-basic-all-completions (string table pred point)
1341 (let* ((beforepoint (substring string 0 point))
1342 (afterpoint (substring string point))
1343 (bounds (completion-boundaries beforepoint table pred afterpoint))
1344 (suffix (substring afterpoint (cdr bounds)))
1345 (prefix (substring beforepoint 0 (car bounds)))
1346 (pattern (delete
1347 "" (list (substring beforepoint (car bounds))
1348 'point
1349 (substring afterpoint 0 (cdr bounds)))))
1350 (all (completion-pcm--all-completions prefix pattern table pred)))
125f7951 1351 (completion-hilit-commonality all point (car bounds))))
19c04f39 1352
34200787
SM
1353;;; Partial-completion-mode style completion.
1354
34200787
SM
1355(defvar completion-pcm--delim-wild-regex nil)
1356
1357(defun completion-pcm--prepare-delim-re (delims)
1358 (setq completion-pcm--delim-wild-regex (concat "[" delims "*]")))
1359
1360(defcustom completion-pcm-word-delimiters "-_. "
1361 "A string of characters treated as word delimiters for completion.
1362Some arcane rules:
1363If `]' is in this string, it must come first.
1364If `^' is in this string, it must not come first.
1365If `-' is in this string, it must come first or right after `]'.
1366In other words, if S is this string, then `[S]' must be a valid Emacs regular
1367expression (not containing character ranges like `a-z')."
1368 :set (lambda (symbol value)
1369 (set-default symbol value)
1370 ;; Refresh other vars.
1371 (completion-pcm--prepare-delim-re value))
1372 :initialize 'custom-initialize-reset
26c548b0 1373 :group 'minibuffer
34200787
SM
1374 :type 'string)
1375
1376(defun completion-pcm--pattern-trivial-p (pattern)
1bba1cfc
SM
1377 (and (stringp (car pattern))
1378 ;; It can be followed by `point' and "" and still be trivial.
1379 (let ((trivial t))
1380 (dolist (elem (cdr pattern))
1381 (unless (member elem '(point ""))
1382 (setq trivial nil)))
1383 trivial)))
34200787 1384
a38313e1
SM
1385(defun completion-pcm--string->pattern (string &optional point)
1386 "Split STRING into a pattern.
34200787
SM
1387A pattern is a list where each element is either a string
1388or a symbol chosen among `any', `star', `point'."
a38313e1
SM
1389 (if (and point (< point (length string)))
1390 (let ((prefix (substring string 0 point))
1391 (suffix (substring string point)))
34200787
SM
1392 (append (completion-pcm--string->pattern prefix)
1393 '(point)
1394 (completion-pcm--string->pattern suffix)))
1395 (let ((pattern nil)
1396 (p 0)
1397 (p0 0))
26c548b0 1398
1afbbf85
SM
1399 (while (and (setq p (string-match-p completion-pcm--delim-wild-regex
1400 string p))
1401 ;; If the char was added by minibuffer-complete-word, then
1402 ;; don't treat it as a delimiter, otherwise "M-x SPC"
1403 ;; ends up inserting a "-" rather than listing
1404 ;; all completions.
1405 (not (get-text-property p 'completion-try-word string)))
a38313e1
SM
1406 (push (substring string p0 p) pattern)
1407 (if (eq (aref string p) ?*)
34200787
SM
1408 (progn
1409 (push 'star pattern)
1410 (setq p0 (1+ p)))
1411 (push 'any pattern)
1412 (setq p0 p))
1413 (incf p))
1414
1415 ;; An empty string might be erroneously added at the beginning.
1416 ;; It should be avoided properly, but it's so easy to remove it here.
a38313e1 1417 (delete "" (nreverse (cons (substring string p0) pattern))))))
34200787
SM
1418
1419(defun completion-pcm--pattern->regex (pattern &optional group)
a38313e1 1420 (let ((re
34200787
SM
1421 (concat "\\`"
1422 (mapconcat
1423 (lambda (x)
1424 (case x
15c72e1d
SM
1425 ((star any point)
1426 (if (if (consp group) (memq x group) group)
1427 "\\(.*?\\)" ".*?"))
1428 (t (regexp-quote x))))
1429 pattern
1430 ""))))
a38313e1
SM
1431 ;; Avoid pathological backtracking.
1432 (while (string-match "\\.\\*\\?\\(?:\\\\[()]\\)*\\(\\.\\*\\?\\)" re)
1433 (setq re (replace-match "" t t re 1)))
1434 re))
34200787 1435
a38313e1 1436(defun completion-pcm--all-completions (prefix pattern table pred)
34200787 1437 "Find all completions for PATTERN in TABLE obeying PRED.
26c548b0 1438PATTERN is as returned by `completion-pcm--string->pattern'."
125f7951
SM
1439 ;; (assert (= (car (completion-boundaries prefix table pred ""))
1440 ;; (length prefix)))
34200787
SM
1441 ;; Find an initial list of possible completions.
1442 (if (completion-pcm--pattern-trivial-p pattern)
1443
1444 ;; Minibuffer contains no delimiters -- simple case!
125f7951 1445 (all-completions (concat prefix (car pattern)) table pred)
26c548b0 1446
34200787
SM
1447 ;; Use all-completions to do an initial cull. This is a big win,
1448 ;; since all-completions is written in C!
1449 (let* (;; Convert search pattern to a standard regular expression.
1450 (regex (completion-pcm--pattern->regex pattern))
15c72e1d
SM
1451 (case-fold-search completion-ignore-case)
1452 (completion-regexp-list (cons regex completion-regexp-list))
34200787 1453 (compl (all-completions
a38313e1 1454 (concat prefix (if (stringp (car pattern)) (car pattern) ""))
125f7951 1455 table pred)))
34200787
SM
1456 (if (not (functionp table))
1457 ;; The internal functions already obeyed completion-regexp-list.
1458 compl
15c72e1d 1459 (let ((poss ()))
34200787 1460 (dolist (c compl)
9f3618b5 1461 (when (string-match-p regex c) (push c poss)))
34200787
SM
1462 poss)))))
1463
7372b09c
SM
1464(defun completion-pcm--hilit-commonality (pattern completions)
1465 (when completions
1466 (let* ((re (completion-pcm--pattern->regex pattern '(point)))
1bba1cfc 1467 (case-fold-search completion-ignore-case))
7372b09c 1468 ;; Remove base-size during mapcar, and add it back later.
1bba1cfc
SM
1469 (mapcar
1470 (lambda (str)
1471 ;; Don't modify the string itself.
1472 (setq str (copy-sequence str))
1473 (unless (string-match re str)
1474 (error "Internal error: %s does not match %s" re str))
1475 (let ((pos (or (match-beginning 1) (match-end 0))))
1476 (put-text-property 0 pos
1477 'font-lock-face 'completions-common-part
1478 str)
1479 (if (> (length str) pos)
1480 (put-text-property pos (1+ pos)
1481 'font-lock-face 'completions-first-difference
1482 str)))
1483 str)
1484 completions))))
7372b09c 1485
eee6de73
SM
1486(defun completion-pcm--find-all-completions (string table pred point
1487 &optional filter)
1488 "Find all completions for STRING at POINT in TABLE, satisfying PRED.
1489POINT is a position inside STRING.
1490FILTER is a function applied to the return value, that can be used, e.g. to
1491filter out additional entries (because TABLE migth not obey PRED)."
1492 (unless filter (setq filter 'identity))
f8381803
SM
1493 (let* ((beforepoint (substring string 0 point))
1494 (afterpoint (substring string point))
1495 (bounds (completion-boundaries beforepoint table pred afterpoint))
1496 (prefix (substring beforepoint 0 (car bounds)))
1497 (suffix (substring afterpoint (cdr bounds)))
a38313e1 1498 firsterror)
f8381803
SM
1499 (setq string (substring string (car bounds) (+ point (cdr bounds))))
1500 (let* ((relpoint (- point (car bounds)))
1501 (pattern (completion-pcm--string->pattern string relpoint))
a38313e1 1502 (all (condition-case err
eee6de73
SM
1503 (funcall filter
1504 (completion-pcm--all-completions
1505 prefix pattern table pred))
a38313e1
SM
1506 (error (unless firsterror (setq firsterror err)) nil))))
1507 (when (and (null all)
1508 (> (car bounds) 0)
1509 (null (ignore-errors (try-completion prefix table pred))))
1510 ;; The prefix has no completions at all, so we should try and fix
1511 ;; that first.
1512 (let ((substring (substring prefix 0 -1)))
1513 (destructuring-bind (subpat suball subprefix subsuffix)
1514 (completion-pcm--find-all-completions
eee6de73 1515 substring table pred (length substring) filter)
a38313e1
SM
1516 (let ((sep (aref prefix (1- (length prefix))))
1517 ;; Text that goes between the new submatches and the
1518 ;; completion substring.
1519 (between nil))
1520 ;; Eliminate submatches that don't end with the separator.
1521 (dolist (submatch (prog1 suball (setq suball ())))
1522 (when (eq sep (aref submatch (1- (length submatch))))
1523 (push submatch suball)))
1524 (when suball
1525 ;; Update the boundaries and corresponding pattern.
1526 ;; We assume that all submatches result in the same boundaries
1527 ;; since we wouldn't know how to merge them otherwise anyway.
f8381803
SM
1528 ;; FIXME: COMPLETE REWRITE!!!
1529 (let* ((newbeforepoint
1530 (concat subprefix (car suball)
1531 (substring string 0 relpoint)))
1532 (leftbound (+ (length subprefix) (length (car suball))))
a38313e1 1533 (newbounds (completion-boundaries
f8381803
SM
1534 newbeforepoint table pred afterpoint)))
1535 (unless (or (and (eq (cdr bounds) (cdr newbounds))
1536 (eq (car newbounds) leftbound))
a38313e1
SM
1537 ;; Refuse new boundaries if they step over
1538 ;; the submatch.
f8381803 1539 (< (car newbounds) leftbound))
a38313e1
SM
1540 ;; The new completed prefix does change the boundaries
1541 ;; of the completed substring.
f8381803
SM
1542 (setq suffix (substring afterpoint (cdr newbounds)))
1543 (setq string
1544 (concat (substring newbeforepoint (car newbounds))
1545 (substring afterpoint 0 (cdr newbounds))))
1546 (setq between (substring newbeforepoint leftbound
a38313e1
SM
1547 (car newbounds)))
1548 (setq pattern (completion-pcm--string->pattern
f8381803
SM
1549 string
1550 (- (length newbeforepoint)
1551 (car newbounds)))))
a38313e1
SM
1552 (dolist (submatch suball)
1553 (setq all (nconc (mapcar
1554 (lambda (s) (concat submatch between s))
eee6de73
SM
1555 (funcall filter
1556 (completion-pcm--all-completions
1557 (concat subprefix submatch between)
1558 pattern table pred)))
a38313e1 1559 all)))
c63028e1
SM
1560 ;; FIXME: This can come in handy for try-completion,
1561 ;; but isn't right for all-completions, since it lists
1562 ;; invalid completions.
1563 ;; (unless all
1564 ;; ;; Even though we found expansions in the prefix, none
1565 ;; ;; leads to a valid completion.
1566 ;; ;; Let's keep the expansions, tho.
1567 ;; (dolist (submatch suball)
1568 ;; (push (concat submatch between newsubstring) all)))
1569 ))
a38313e1
SM
1570 (setq pattern (append subpat (list 'any (string sep))
1571 (if between (list between)) pattern))
1572 (setq prefix subprefix)))))
1573 (if (and (null all) firsterror)
1574 (signal (car firsterror) (cdr firsterror))
1575 (list pattern all prefix suffix)))))
1576
34200787 1577(defun completion-pcm-all-completions (string table pred point)
a38313e1
SM
1578 (destructuring-bind (pattern all &optional prefix suffix)
1579 (completion-pcm--find-all-completions string table pred point)
d4e88786
SM
1580 (when all
1581 (nconc (completion-pcm--hilit-commonality pattern all)
1582 (length prefix)))))
34200787
SM
1583
1584(defun completion-pcm--merge-completions (strs pattern)
1585 "Extract the commonality in STRS, with the help of PATTERN."
1586 (cond
1587 ((null (cdr strs)) (list (car strs)))
1588 (t
1589 (let ((re (completion-pcm--pattern->regex pattern 'group))
1590 (ccs ())) ;Chopped completions.
1591
1592 ;; First chop each string into the parts corresponding to each
1593 ;; non-constant element of `pattern', using regexp-matching.
1594 (let ((case-fold-search completion-ignore-case))
1595 (dolist (str strs)
1596 (unless (string-match re str)
1597 (error "Internal error: %s doesn't match %s" str re))
1598 (let ((chopped ())
1599 (i 1))
1600 (while (match-beginning i)
1601 (push (match-string i str) chopped)
1602 (setq i (1+ i)))
1603 ;; Add the text corresponding to the implicit trailing `any'.
1604 (push (substring str (match-end 0)) chopped)
1605 (push (nreverse chopped) ccs))))
1606
1607 ;; Then for each of those non-constant elements, extract the
1608 ;; commonality between them.
1609 (let ((res ()))
1610 ;; Make the implicit `any' explicit. We could make it explicit
1611 ;; everywhere, but it would slow down regexp-matching a little bit.
1612 (dolist (elem (append pattern '(any)))
1613 (if (stringp elem)
1614 (push elem res)
1615 (let ((comps ()))
1616 (dolist (cc (prog1 ccs (setq ccs nil)))
1617 (push (car cc) comps)
1618 (push (cdr cc) ccs))
1619 (let* ((prefix (try-completion "" comps))
1620 (unique (or (and (eq prefix t) (setq prefix ""))
1621 (eq t (try-completion prefix comps)))))
1622 (unless (equal prefix "") (push prefix res))
1623 ;; If there's only one completion, `elem' is not useful
1624 ;; any more: it can only match the empty string.
1625 ;; FIXME: in some cases, it may be necessary to turn an
1626 ;; `any' into a `star' because the surrounding context has
1627 ;; changed such that string->pattern wouldn't add an `any'
1628 ;; here any more.
1629 (unless unique (push elem res))))))
1630 ;; We return it in reverse order.
1631 res)))))
1632
1633(defun completion-pcm--pattern->string (pattern)
1634 (mapconcat (lambda (x) (cond
1635 ((stringp x) x)
1636 ((eq x 'star) "*")
1637 ((eq x 'any) "")
1638 ((eq x 'point) "")))
1639 pattern
1640 ""))
1641
eee6de73
SM
1642;; We want to provide the functionality of `try', but we use `all'
1643;; and then merge it. In most cases, this works perfectly, but
1644;; if the completion table doesn't consider the same completions in
1645;; `try' as in `all', then we have a problem. The most common such
1646;; case is for filename completion where completion-ignored-extensions
1647;; is only obeyed by the `try' code. We paper over the difference
1648;; here. Note that it is not quite right either: if the completion
1649;; table uses completion-table-in-turn, this filtering may take place
1650;; too late to correctly fallback from the first to the
1651;; second alternative.
1652(defun completion-pcm--filename-try-filter (all)
1653 "Filter to adjust `all' file completion to the behavior of `try'."
34200787 1654 (when all
eee6de73
SM
1655 (let ((try ())
1656 (re (concat "\\(?:\\`\\.\\.?/\\|"
1657 (regexp-opt completion-ignored-extensions)
1658 "\\)\\'")))
1659 (dolist (f all)
9f3618b5 1660 (unless (string-match-p re f) (push f try)))
eee6de73 1661 (or try all))))
9f3618b5 1662
eee6de73
SM
1663
1664(defun completion-pcm--merge-try (pattern all prefix suffix)
1665 (cond
1666 ((not (consp all)) all)
1667 ((and (not (consp (cdr all))) ;Only one completion.
1668 ;; Ignore completion-ignore-case here.
1669 (equal (completion-pcm--pattern->string pattern) (car all)))
1670 t)
1671 (t
34200787 1672 (let* ((mergedpat (completion-pcm--merge-completions all pattern))
81ff9458
SM
1673 ;; `mergedpat' is in reverse order. Place new point (by
1674 ;; order of preference) either at the old point, or at
1675 ;; the last place where there's something to choose, or
1676 ;; at the very end.
1677 (pointpat (or (memq 'point mergedpat) (memq 'any mergedpat)
b00942d0 1678 mergedpat))
81ff9458 1679 ;; New pos from the start.
34200787 1680 (newpos (length (completion-pcm--pattern->string pointpat)))
81ff9458 1681 ;; Do it afterwards because it changes `pointpat' by sideeffect.
34200787 1682 (merged (completion-pcm--pattern->string (nreverse mergedpat))))
eee6de73
SM
1683
1684 (setq suffix (completion--merge-suffix merged newpos suffix))
a38313e1 1685 (cons (concat prefix merged suffix) (+ newpos (length prefix)))))))
34200787 1686
eee6de73
SM
1687(defun completion-pcm-try-completion (string table pred point)
1688 (destructuring-bind (pattern all prefix suffix)
1689 (completion-pcm--find-all-completions
1690 string table pred point
1691 (if minibuffer-completing-file-name
1692 'completion-pcm--filename-try-filter))
1693 (completion-pcm--merge-try pattern all prefix suffix)))
1694
34200787 1695
32bae13c 1696(provide 'minibuffer)
dc6ee347
MB
1697
1698;; arch-tag: ef8a0a15-1080-4790-a754-04017c02f08f
32bae13c 1699;;; minibuffer.el ends here