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