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