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