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