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