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