Propagate buffer-local-variables changes to other threads.
[emacs.git] / lisp / minibuffer.el
blob154cc37e9a1965995f9f69f61d49cf32fa2d95e3
1 ;;; minibuffer.el --- Minibuffer completion functions
3 ;; Copyright (C) 2008, 2009, 2010 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).
34 ;;; Bugs:
36 ;; - completion-all-sorted-completions list all the completions, whereas
37 ;; it should only lists the ones that `try-completion' would consider.
38 ;; E.g. it should honor completion-ignored-extensions.
39 ;; - choose-completion can't automatically figure out the boundaries
40 ;; corresponding to the displayed completions because we only
41 ;; provide the start info but not the end info in
42 ;; completion-base-position.
43 ;; - quoting is problematic. E.g. the double-dollar quoting used in
44 ;; substitie-in-file-name (and hence read-file-name-internal) bumps
45 ;; into various bugs:
46 ;; - choose-completion doesn't know how to quote the text it inserts.
47 ;; E.g. it fails to double the dollars in file-name completion, or
48 ;; to backslash-escape spaces and other chars in comint completion.
49 ;; - when completing ~/tmp/fo$$o, the highligting in *Completions*
50 ;; is off by one position.
51 ;; - all code like PCM which relies on all-completions to match
52 ;; its argument gets confused because all-completions returns unquoted
53 ;; texts (as desired for *Completions* output).
54 ;; - C-x C-f ~/*/sr ? should not list "~/./src".
55 ;; - minibuffer-force-complete completes ~/src/emacs/t<!>/lisp/minibuffer.el
56 ;; to ~/src/emacs/trunk/ and throws away lisp/minibuffer.el.
58 ;;; Todo:
60 ;; - extend `boundaries' to provide various other meta-data about the
61 ;; output of `all-completions':
62 ;; - preferred sorting order when displayed in *Completions*.
63 ;; - annotations/text-properties to add when displayed in *Completions*.
64 ;; - quoting/unquoting (so we can complete files names with envvars
65 ;; and backslashes, and all-completion can list names without
66 ;; quoting backslashes and dollars).
67 ;; - indicate how to turn all-completion's output into
68 ;; try-completion's output: e.g. completion-ignored-extensions.
69 ;; maybe that could be merged with the "quote" operation above.
70 ;; - completion hook to run when the completion is
71 ;; selected/inserted (maybe this should be provided some other
72 ;; way, e.g. as text-property, so `try-completion can also return it?)
73 ;; both for when it's inserted via TAB or via choose-completion.
74 ;; - indicate that `all-completions' doesn't do prefix-completion
75 ;; but just returns some list that relates in some other way to
76 ;; the provided string (as is the case in filecache.el), in which
77 ;; case partial-completion (for example) doesn't make any sense
78 ;; and neither does the completions-first-difference highlight.
80 ;; - make partial-completion-mode obsolete:
81 ;; - (?) <foo.h> style completion for file names.
82 ;; This can't be done identically just by tweaking completion,
83 ;; because partial-completion-mode's behavior is to expand <string.h>
84 ;; to /usr/include/string.h only when exiting the minibuffer, at which
85 ;; point the completion code is actually not involved normally.
86 ;; Partial-completion-mode does it via a find-file-not-found-function.
87 ;; - special code for C-x C-f <> to visit the file ref'd at point
88 ;; via (require 'foo) or #include "foo". ffap seems like a better
89 ;; place for this feature (supplemented with major-mode-provided
90 ;; functions to find the file ref'd at point).
92 ;; - case-sensitivity currently confuses two issues:
93 ;; - whether or not a particular completion table should be case-sensitive
94 ;; (i.e. whether strings that differ only by case are semantically
95 ;; equivalent)
96 ;; - whether the user wants completion to pay attention to case.
97 ;; e.g. we may want to make it possible for the user to say "first try
98 ;; completion case-sensitively, and if that fails, try to ignore case".
100 ;; - add support for ** to pcm.
101 ;; - Add vc-file-name-completion-table to read-file-name-internal.
102 ;; - A feature like completing-help.el.
104 ;;; Code:
106 (eval-when-compile (require 'cl))
108 ;;; Completion table manipulation
110 ;; New completion-table operation.
111 (defun completion-boundaries (string table pred suffix)
112 "Return the boundaries of the completions returned by TABLE for STRING.
113 STRING is the string on which completion will be performed.
114 SUFFIX is the string after point.
115 The result is of the form (START . END) where START is the position
116 in STRING of the beginning of the completion field and END is the position
117 in SUFFIX of the end of the completion field.
118 E.g. for simple completion tables, the result is always (0 . (length SUFFIX))
119 and for file names the result is the positions delimited by
120 the closest directory separators."
121 (let ((boundaries (if (functionp table)
122 (funcall table string pred (cons 'boundaries suffix)))))
123 (if (not (eq (car-safe boundaries) 'boundaries))
124 (setq boundaries nil))
125 (cons (or (cadr boundaries) 0)
126 (or (cddr boundaries) (length suffix)))))
128 (defun completion--some (fun xs)
129 "Apply FUN to each element of XS in turn.
130 Return the first non-nil returned value.
131 Like CL's `some'."
132 (let ((firsterror nil)
133 res)
134 (while (and (not res) xs)
135 (condition-case err
136 (setq res (funcall fun (pop xs)))
137 (error (unless firsterror (setq firsterror err)) nil)))
138 (or res
139 (if firsterror (signal (car firsterror) (cdr firsterror))))))
141 (defun complete-with-action (action table string pred)
142 "Perform completion ACTION.
143 STRING is the string to complete.
144 TABLE is the completion table, which should not be a function.
145 PRED is a completion predicate.
146 ACTION can be one of nil, t or `lambda'."
147 (cond
148 ((functionp table) (funcall table string pred action))
149 ((eq (car-safe action) 'boundaries)
150 (cons 'boundaries (completion-boundaries string table pred (cdr action))))
152 (funcall
153 (cond
154 ((null action) 'try-completion)
155 ((eq action t) 'all-completions)
156 (t 'test-completion))
157 string table pred))))
159 (defun completion-table-dynamic (fun)
160 "Use function FUN as a dynamic completion table.
161 FUN is called with one argument, the string for which completion is required,
162 and it should return an alist containing all the intended possible completions.
163 This alist may be a full list of possible completions so that FUN can ignore
164 the value of its argument. If completion is performed in the minibuffer,
165 FUN will be called in the buffer from which the minibuffer was entered.
167 The result of the `completion-table-dynamic' form is a function
168 that can be used as the COLLECTION argument to `try-completion' and
169 `all-completions'. See Info node `(elisp)Programmed Completion'."
170 (lexical-let ((fun fun))
171 (lambda (string pred action)
172 (with-current-buffer (let ((win (minibuffer-selected-window)))
173 (if (window-live-p win) (window-buffer win)
174 (current-buffer)))
175 (complete-with-action action (funcall fun string) string pred)))))
177 (defmacro lazy-completion-table (var fun)
178 "Initialize variable VAR as a lazy completion table.
179 If the completion table VAR is used for the first time (e.g., by passing VAR
180 as an argument to `try-completion'), the function FUN is called with no
181 arguments. FUN must return the completion table that will be stored in VAR.
182 If completion is requested in the minibuffer, FUN will be called in the buffer
183 from which the minibuffer was entered. The return value of
184 `lazy-completion-table' must be used to initialize the value of VAR.
186 You should give VAR a non-nil `risky-local-variable' property."
187 (declare (debug (symbolp lambda-expr)))
188 (let ((str (make-symbol "string")))
189 `(completion-table-dynamic
190 (lambda (,str)
191 (when (functionp ,var)
192 (setq ,var (,fun)))
193 ,var))))
195 (defun completion-table-with-context (prefix table string pred action)
196 ;; TODO: add `suffix' maybe?
197 ;; Notice that `pred' may not be a function in some abusive cases.
198 (when (functionp pred)
199 (setq pred
200 (lexical-let ((pred pred))
201 ;; Predicates are called differently depending on the nature of
202 ;; the completion table :-(
203 (cond
204 ((vectorp table) ;Obarray.
205 (lambda (sym) (funcall pred (concat prefix (symbol-name sym)))))
206 ((hash-table-p table)
207 (lambda (s v) (funcall pred (concat prefix s))))
208 ((functionp table)
209 (lambda (s) (funcall pred (concat prefix s))))
210 (t ;Lists and alists.
211 (lambda (s)
212 (funcall pred (concat prefix (if (consp s) (car s) s)))))))))
213 (if (eq (car-safe action) 'boundaries)
214 (let* ((len (length prefix))
215 (bound (completion-boundaries string table pred (cdr action))))
216 (list* 'boundaries (+ (car bound) len) (cdr bound)))
217 (let ((comp (complete-with-action action table string pred)))
218 (cond
219 ;; In case of try-completion, add the prefix.
220 ((stringp comp) (concat prefix comp))
221 (t comp)))))
223 (defun completion-table-with-terminator (terminator table string pred action)
224 "Construct a completion table like TABLE but with an extra TERMINATOR.
225 This is meant to be called in a curried way by first passing TERMINATOR
226 and TABLE only (via `apply-partially').
227 TABLE is a completion table, and TERMINATOR is a string appended to TABLE's
228 completion if it is complete. TERMINATOR is also used to determine the
229 completion suffix's boundary.
230 TERMINATOR can also be a cons cell (TERMINATOR . TERMINATOR-REGEXP)
231 in which case TERMINATOR-REGEXP is a regular expression whose submatch
232 number 1 should match TERMINATOR. This is used when there is a need to
233 distinguish occurrences of the TERMINATOR strings which are really terminators
234 from others (e.g. escaped)."
235 (cond
236 ((eq (car-safe action) 'boundaries)
237 (let* ((suffix (cdr action))
238 (bounds (completion-boundaries string table pred suffix))
239 (terminator-regexp (if (consp terminator)
240 (cdr terminator) (regexp-quote terminator)))
241 (max (string-match terminator-regexp suffix)))
242 (list* 'boundaries (car bounds)
243 (min (cdr bounds) (or max (length suffix))))))
244 ((eq action nil)
245 (let ((comp (try-completion string table pred)))
246 (if (consp terminator) (setq terminator (car terminator)))
247 (if (eq comp t)
248 (concat string terminator)
249 (if (and (stringp comp)
250 ;; FIXME: Try to avoid this second call, especially since
251 ;; it may be very inefficient (because `comp' made us
252 ;; jump to a new boundary, so we complete in that
253 ;; boundary with an empty start string).
254 ;; completion-boundaries might help.
255 (eq (try-completion comp table pred) t))
256 (concat comp terminator)
257 comp))))
258 ((eq action t)
259 ;; FIXME: We generally want the `try' and `all' behaviors to be
260 ;; consistent so pcm can merge the `all' output to get the `try' output,
261 ;; but that sometimes clashes with the need for `all' output to look
262 ;; good in *Completions*.
263 ;; (mapcar (lambda (s) (concat s terminator))
264 ;; (all-completions string table pred))))
265 (all-completions string table pred))
266 ;; completion-table-with-terminator is always used for
267 ;; "sub-completions" so it's only called if the terminator is missing,
268 ;; in which case `test-completion' should return nil.
269 ((eq action 'lambda) nil)))
271 (defun completion-table-with-predicate (table pred1 strict string pred2 action)
272 "Make a completion table equivalent to TABLE but filtered through PRED1.
273 PRED1 is a function of one argument which returns non-nil if and only if the
274 argument is an element of TABLE which should be considered for completion.
275 STRING, PRED2, and ACTION are the usual arguments to completion tables,
276 as described in `try-completion', `all-completions', and `test-completion'.
277 If STRICT is t, the predicate always applies; if nil it only applies if
278 it does not reduce the set of possible completions to nothing.
279 Note: TABLE needs to be a proper completion table which obeys predicates."
280 (cond
281 ((and (not strict) (eq action 'lambda))
282 ;; Ignore pred1 since it doesn't really have to apply anyway.
283 (test-completion string table pred2))
285 (or (complete-with-action action table string
286 (if (null pred2) pred1
287 (lexical-let ((pred1 pred2) (pred2 pred2))
288 (lambda (x)
289 ;; Call `pred1' first, so that `pred2'
290 ;; really can't tell that `x' is in table.
291 (if (funcall pred1 x) (funcall pred2 x))))))
292 ;; If completion failed and we're not applying pred1 strictly, try
293 ;; again without pred1.
294 (and (not strict)
295 (complete-with-action action table string pred2))))))
297 (defun completion-table-in-turn (&rest tables)
298 "Create a completion table that tries each table in TABLES in turn."
299 ;; FIXME: the boundaries may come from TABLE1 even when the completion list
300 ;; is returned by TABLE2 (because TABLE1 returned an empty list).
301 (lexical-let ((tables tables))
302 (lambda (string pred action)
303 (completion--some (lambda (table)
304 (complete-with-action action table string pred))
305 tables))))
307 ;; (defmacro complete-in-turn (a b) `(completion-table-in-turn ,a ,b))
308 ;; (defmacro dynamic-completion-table (fun) `(completion-table-dynamic ,fun))
309 (define-obsolete-function-alias
310 'complete-in-turn 'completion-table-in-turn "23.1")
311 (define-obsolete-function-alias
312 'dynamic-completion-table 'completion-table-dynamic "23.1")
314 ;;; Minibuffer completion
316 (defgroup minibuffer nil
317 "Controlling the behavior of the minibuffer."
318 :link '(custom-manual "(emacs)Minibuffer")
319 :group 'environment)
321 (defun minibuffer-message (message &rest args)
322 "Temporarily display MESSAGE at the end of the minibuffer.
323 The text is displayed for `minibuffer-message-timeout' seconds,
324 or until the next input event arrives, whichever comes first.
325 Enclose MESSAGE in [...] if this is not yet the case.
326 If ARGS are provided, then pass MESSAGE through `format'."
327 (if (not (minibufferp (current-buffer)))
328 (progn
329 (if args
330 (apply 'message message args)
331 (message "%s" message))
332 (prog1 (sit-for (or minibuffer-message-timeout 1000000))
333 (message nil)))
334 ;; Clear out any old echo-area message to make way for our new thing.
335 (message nil)
336 (setq message (if (and (null args) (string-match-p "\\` *\\[.+\\]\\'" message))
337 ;; Make sure we can put-text-property.
338 (copy-sequence message)
339 (concat " [" message "]")))
340 (when args (setq message (apply 'format message args)))
341 (let ((ol (make-overlay (point-max) (point-max) nil t t))
342 ;; A quit during sit-for normally only interrupts the sit-for,
343 ;; but since minibuffer-message is used at the end of a command,
344 ;; at a time when the command has virtually finished already, a C-g
345 ;; should really cause an abort-recursive-edit instead (i.e. as if
346 ;; the C-g had been typed at top-level). Binding inhibit-quit here
347 ;; is an attempt to get that behavior.
348 (inhibit-quit t))
349 (unwind-protect
350 (progn
351 (unless (zerop (length message))
352 ;; The current C cursor code doesn't know to use the overlay's
353 ;; marker's stickiness to figure out whether to place the cursor
354 ;; before or after the string, so let's spoon-feed it the pos.
355 (put-text-property 0 1 'cursor t message))
356 (overlay-put ol 'after-string message)
357 (sit-for (or minibuffer-message-timeout 1000000)))
358 (delete-overlay ol)))))
360 (defun minibuffer-completion-contents ()
361 "Return the user input in a minibuffer before point as a string.
362 That is what completion commands operate on."
363 (buffer-substring (field-beginning) (point)))
365 (defun delete-minibuffer-contents ()
366 "Delete all user input in a minibuffer.
367 If the current buffer is not a minibuffer, erase its entire contents."
368 ;; We used to do `delete-field' here, but when file name shadowing
369 ;; is on, the field doesn't cover the entire minibuffer contents.
370 (delete-region (minibuffer-prompt-end) (point-max)))
372 (defcustom completion-auto-help t
373 "Non-nil means automatically provide help for invalid completion input.
374 If the value is t the *Completion* buffer is displayed whenever completion
375 is requested but cannot be done.
376 If the value is `lazy', the *Completions* buffer is only displayed after
377 the second failed attempt to complete."
378 :type '(choice (const nil) (const t) (const lazy))
379 :group 'minibuffer)
381 (defconst completion-styles-alist
382 '((emacs21
383 completion-emacs21-try-completion completion-emacs21-all-completions
384 "Simple prefix-based completion.")
385 (emacs22
386 completion-emacs22-try-completion completion-emacs22-all-completions
387 "Prefix completion that only operates on the text before point.")
388 (basic
389 completion-basic-try-completion completion-basic-all-completions
390 "Completion of the prefix before point and the suffix after point.")
391 (partial-completion
392 completion-pcm-try-completion completion-pcm-all-completions
393 "Completion of multiple words, each one taken as a prefix.
394 E.g. M-x l-c-h can complete to list-command-history
395 and C-x C-f /u/m/s to /usr/monnier/src.")
396 (substring
397 completion-substring-try-completion completion-substring-all-completions
398 "Completion of the string taken as a substring.")
399 (initials
400 completion-initials-try-completion completion-initials-all-completions
401 "Completion of acronyms and initialisms.
402 E.g. can complete M-x lch to list-command-history
403 and C-x C-f ~/sew to ~/src/emacs/work."))
404 "List of available completion styles.
405 Each element has the form (NAME TRY-COMPLETION ALL-COMPLETIONS DOC):
406 where NAME is the name that should be used in `completion-styles',
407 TRY-COMPLETION is the function that does the completion (it should
408 follow the same calling convention as `completion-try-completion'),
409 ALL-COMPLETIONS is the function that lists the completions (it should
410 follow the calling convention of `completion-all-completions'),
411 and DOC describes the way this style of completion works.")
413 (defcustom completion-styles '(basic partial-completion emacs22)
414 "List of completion styles to use.
415 The available styles are listed in `completion-styles-alist'."
416 :type `(repeat (choice ,@(mapcar (lambda (x) (list 'const (car x)))
417 completion-styles-alist)))
418 :group 'minibuffer
419 :version "23.1")
421 (defun completion-try-completion (string table pred point)
422 "Try to complete STRING using completion table TABLE.
423 Only the elements of table that satisfy predicate PRED are considered.
424 POINT is the position of point within STRING.
425 The return value can be either nil to indicate that there is no completion,
426 t to indicate that STRING is the only possible completion,
427 or a pair (STRING . NEWPOINT) of the completed result string together with
428 a new position for point."
429 (completion--some (lambda (style)
430 (funcall (nth 1 (assq style completion-styles-alist))
431 string table pred point))
432 completion-styles))
434 (defun completion-all-completions (string table pred point)
435 "List the possible completions of STRING in completion table TABLE.
436 Only the elements of table that satisfy predicate PRED are considered.
437 POINT is the position of point within STRING.
438 The return value is a list of completions and may contain the base-size
439 in the last `cdr'."
440 ;; FIXME: We need to additionally return the info needed for the
441 ;; second part of completion-base-position.
442 (completion--some (lambda (style)
443 (funcall (nth 2 (assq style completion-styles-alist))
444 string table pred point))
445 completion-styles))
447 (defun minibuffer--bitset (modified completions exact)
448 (logior (if modified 4 0)
449 (if completions 2 0)
450 (if exact 1 0)))
452 (defun completion--replace (beg end newtext)
453 "Replace the buffer text between BEG and END with NEWTEXT.
454 Moves point to the end of the new text."
455 ;; This should be in subr.el.
456 ;; You'd think this is trivial to do, but details matter if you want
457 ;; to keep markers "at the right place" and be robust in the face of
458 ;; after-change-functions that may themselves modify the buffer.
459 (goto-char beg)
460 (insert newtext)
461 (delete-region (point) (+ (point) (- end beg))))
463 (defun completion--do-completion (&optional try-completion-function)
464 "Do the completion and return a summary of what happened.
465 M = completion was performed, the text was Modified.
466 C = there were available Completions.
467 E = after completion we now have an Exact match.
470 000 0 no possible completion
471 001 1 was already an exact and unique completion
472 010 2 no completion happened
473 011 3 was already an exact completion
474 100 4 ??? impossible
475 101 5 ??? impossible
476 110 6 some completion happened
477 111 7 completed to an exact completion"
478 (let* ((beg (field-beginning))
479 (end (field-end))
480 (string (buffer-substring beg end))
481 (comp (funcall (or try-completion-function
482 'completion-try-completion)
483 string
484 minibuffer-completion-table
485 minibuffer-completion-predicate
486 (- (point) beg))))
487 (cond
488 ((null comp)
489 (minibuffer-hide-completions)
490 (ding) (minibuffer-message "No match") (minibuffer--bitset nil nil nil))
491 ((eq t comp)
492 (minibuffer-hide-completions)
493 (goto-char (field-end))
494 (minibuffer--bitset nil nil t)) ;Exact and unique match.
496 ;; `completed' should be t if some completion was done, which doesn't
497 ;; include simply changing the case of the entered string. However,
498 ;; for appearance, the string is rewritten if the case changes.
499 (let* ((comp-pos (cdr comp))
500 (completion (car comp))
501 (completed (not (eq t (compare-strings completion nil nil
502 string nil nil t))))
503 (unchanged (eq t (compare-strings completion nil nil
504 string nil nil nil))))
505 (if unchanged
506 (goto-char end)
507 ;; Insert in minibuffer the chars we got.
508 (completion--replace beg end completion))
509 ;; Move point to its completion-mandated destination.
510 (forward-char (- comp-pos (length completion)))
512 (if (not (or unchanged completed))
513 ;; The case of the string changed, but that's all. We're not sure
514 ;; whether this is a unique completion or not, so try again using
515 ;; the real case (this shouldn't recurse again, because the next
516 ;; time try-completion will return either t or the exact string).
517 (completion--do-completion try-completion-function)
519 ;; It did find a match. Do we match some possibility exactly now?
520 (let ((exact (test-completion completion
521 minibuffer-completion-table
522 minibuffer-completion-predicate)))
523 (if completed
524 ;; We could also decide to refresh the completions,
525 ;; if they're displayed (and assuming there are
526 ;; completions left).
527 (minibuffer-hide-completions)
528 ;; Show the completion table, if requested.
529 (cond
530 ((not exact)
531 (if (case completion-auto-help
532 (lazy (eq this-command last-command))
533 (t completion-auto-help))
534 (minibuffer-completion-help)
535 (minibuffer-message "Next char not unique")))
536 ;; If the last exact completion and this one were the same, it
537 ;; means we've already given a "Next char not unique" message
538 ;; and the user's hit TAB again, so now we give him help.
539 ((eq this-command last-command)
540 (if completion-auto-help (minibuffer-completion-help)))))
542 (minibuffer--bitset completed t exact))))))))
544 (defun minibuffer-complete ()
545 "Complete the minibuffer contents as far as possible.
546 Return nil if there is no valid completion, else t.
547 If no characters can be completed, display a list of possible completions.
548 If you repeat this command after it displayed such a list,
549 scroll the window of possible completions."
550 (interactive)
551 ;; If the previous command was not this,
552 ;; mark the completion buffer obsolete.
553 (unless (eq this-command last-command)
554 (setq minibuffer-scroll-window nil))
556 (let ((window minibuffer-scroll-window))
557 ;; If there's a fresh completion window with a live buffer,
558 ;; and this command is repeated, scroll that window.
559 (if (window-live-p window)
560 (with-current-buffer (window-buffer window)
561 (if (pos-visible-in-window-p (point-max) window)
562 ;; If end is in view, scroll up to the beginning.
563 (set-window-start window (point-min) nil)
564 ;; Else scroll down one screen.
565 (scroll-other-window))
566 nil)
568 (case (completion--do-completion)
569 (#b000 nil)
570 (#b001 (minibuffer-message "Sole completion")
572 (#b011 (minibuffer-message "Complete, but not unique")
574 (t t)))))
576 (defvar completion-all-sorted-completions nil)
577 (make-variable-buffer-local 'completion-all-sorted-completions)
579 (defun completion--flush-all-sorted-completions (&rest ignore)
580 (setq completion-all-sorted-completions nil))
582 (defun completion-all-sorted-completions ()
583 (or completion-all-sorted-completions
584 (let* ((start (field-beginning))
585 (end (field-end))
586 (all (completion-all-completions (buffer-substring start end)
587 minibuffer-completion-table
588 minibuffer-completion-predicate
589 (- (point) start)))
590 (last (last all))
591 (base-size (or (cdr last) 0)))
592 (when last
593 (setcdr last nil)
594 ;; Prefer shorter completions.
595 (setq all (sort all (lambda (c1 c2) (< (length c1) (length c2)))))
596 ;; Prefer recently used completions.
597 (let ((hist (symbol-value minibuffer-history-variable)))
598 (setq all (sort all (lambda (c1 c2)
599 (> (length (member c1 hist))
600 (length (member c2 hist)))))))
601 ;; Cache the result. This is not just for speed, but also so that
602 ;; repeated calls to minibuffer-force-complete can cycle through
603 ;; all possibilities.
604 (add-hook 'after-change-functions
605 'completion--flush-all-sorted-completions nil t)
606 (setq completion-all-sorted-completions
607 (nconc all base-size))))))
609 (defun minibuffer-force-complete ()
610 "Complete the minibuffer to an exact match.
611 Repeated uses step through the possible completions."
612 (interactive)
613 ;; FIXME: Need to deal with the extra-size issue here as well.
614 ;; FIXME: ~/src/emacs/t<M-TAB>/lisp/minibuffer.el completes to
615 ;; ~/src/emacs/trunk/ and throws away lisp/minibuffer.el.
616 (let* ((start (field-beginning))
617 (end (field-end))
618 (all (completion-all-sorted-completions)))
619 (if (not (consp all))
620 (minibuffer-message (if all "No more completions" "No completions"))
621 (goto-char end)
622 (insert (car all))
623 (delete-region (+ start (cdr (last all))) end)
624 ;; If completing file names, (car all) may be a directory, so we'd now
625 ;; have a new set of possible completions and might want to reset
626 ;; completion-all-sorted-completions to nil, but we prefer not to,
627 ;; so that repeated calls minibuffer-force-complete still cycle
628 ;; through the previous possible completions.
629 (let ((last (last all)))
630 (setcdr last (cons (car all) (cdr last)))
631 (setq completion-all-sorted-completions (cdr all))))))
633 (defvar minibuffer-confirm-exit-commands
634 '(minibuffer-complete minibuffer-complete-word PC-complete PC-complete-word)
635 "A list of commands which cause an immediately following
636 `minibuffer-complete-and-exit' to ask for extra confirmation.")
638 (defun minibuffer-complete-and-exit ()
639 "Exit if the minibuffer contains a valid completion.
640 Otherwise, try to complete the minibuffer contents. If
641 completion leads to a valid completion, a repetition of this
642 command will exit.
644 If `minibuffer-completion-confirm' is `confirm', do not try to
645 complete; instead, ask for confirmation and accept any input if
646 confirmed.
647 If `minibuffer-completion-confirm' is `confirm-after-completion',
648 do not try to complete; instead, ask for confirmation if the
649 preceding minibuffer command was a member of
650 `minibuffer-confirm-exit-commands', and accept the input
651 otherwise."
652 (interactive)
653 (let ((beg (field-beginning))
654 (end (field-end)))
655 (cond
656 ;; Allow user to specify null string
657 ((= beg end) (exit-minibuffer))
658 ((test-completion (buffer-substring beg end)
659 minibuffer-completion-table
660 minibuffer-completion-predicate)
661 ;; FIXME: completion-ignore-case has various slightly
662 ;; incompatible meanings. E.g. it can reflect whether the user
663 ;; wants completion to pay attention to case, or whether the
664 ;; string will be used in a context where case is significant.
665 ;; E.g. usually try-completion should obey the first, whereas
666 ;; test-completion should obey the second.
667 (when completion-ignore-case
668 ;; Fixup case of the field, if necessary.
669 (let* ((string (buffer-substring beg end))
670 (compl (try-completion
671 string
672 minibuffer-completion-table
673 minibuffer-completion-predicate)))
674 (when (and (stringp compl) (not (equal string compl))
675 ;; If it weren't for this piece of paranoia, I'd replace
676 ;; the whole thing with a call to do-completion.
677 ;; This is important, e.g. when the current minibuffer's
678 ;; content is a directory which only contains a single
679 ;; file, so `try-completion' actually completes to
680 ;; that file.
681 (= (length string) (length compl)))
682 (goto-char end)
683 (insert compl)
684 (delete-region beg end))))
685 (exit-minibuffer))
687 ((memq minibuffer-completion-confirm '(confirm confirm-after-completion))
688 ;; The user is permitted to exit with an input that's rejected
689 ;; by test-completion, after confirming her choice.
690 (if (or (eq last-command this-command)
691 ;; For `confirm-after-completion' we only ask for confirmation
692 ;; if trying to exit immediately after typing TAB (this
693 ;; catches most minibuffer typos).
694 (and (eq minibuffer-completion-confirm 'confirm-after-completion)
695 (not (memq last-command minibuffer-confirm-exit-commands))))
696 (exit-minibuffer)
697 (minibuffer-message "Confirm")
698 nil))
701 ;; Call do-completion, but ignore errors.
702 (case (condition-case nil
703 (completion--do-completion)
704 (error 1))
705 ((#b001 #b011) (exit-minibuffer))
706 (#b111 (if (not minibuffer-completion-confirm)
707 (exit-minibuffer)
708 (minibuffer-message "Confirm")
709 nil))
710 (t nil))))))
712 (defun completion--try-word-completion (string table predicate point)
713 (let ((comp (completion-try-completion string table predicate point)))
714 (if (not (consp comp))
715 comp
717 ;; If completion finds next char not unique,
718 ;; consider adding a space or a hyphen.
719 (when (= (length string) (length (car comp)))
720 ;; Mark the added char with the `completion-word' property, so it
721 ;; can be handled specially by completion styles such as
722 ;; partial-completion.
723 ;; We used to remove `partial-completion' from completion-styles
724 ;; instead, but it was too blunt, leading to situations where SPC
725 ;; was the only insertable char at point but minibuffer-complete-word
726 ;; refused inserting it.
727 (let ((exts (mapcar (lambda (str) (propertize str 'completion-try-word t))
728 '(" " "-")))
729 (before (substring string 0 point))
730 (after (substring string point))
731 tem)
732 (while (and exts (not (consp tem)))
733 (setq tem (completion-try-completion
734 (concat before (pop exts) after)
735 table predicate (1+ point))))
736 (if (consp tem) (setq comp tem))))
738 ;; Completing a single word is actually more difficult than completing
739 ;; as much as possible, because we first have to find the "current
740 ;; position" in `completion' in order to find the end of the word
741 ;; we're completing. Normally, `string' is a prefix of `completion',
742 ;; which makes it trivial to find the position, but with fancier
743 ;; completion (plus env-var expansion, ...) `completion' might not
744 ;; look anything like `string' at all.
745 (let* ((comppoint (cdr comp))
746 (completion (car comp))
747 (before (substring string 0 point))
748 (combined (concat before "\n" completion)))
749 ;; Find in completion the longest text that was right before point.
750 (when (string-match "\\(.+\\)\n.*?\\1" combined)
751 (let* ((prefix (match-string 1 before))
752 ;; We used non-greedy match to make `rem' as long as possible.
753 (rem (substring combined (match-end 0)))
754 ;; Find in the remainder of completion the longest text
755 ;; that was right after point.
756 (after (substring string point))
757 (suffix (if (string-match "\\`\\(.+\\).*\n.*\\1"
758 (concat after "\n" rem))
759 (match-string 1 after))))
760 ;; The general idea is to try and guess what text was inserted
761 ;; at point by the completion. Problem is: if we guess wrong,
762 ;; we may end up treating as "added by completion" text that was
763 ;; actually painfully typed by the user. So if we then cut
764 ;; after the first word, we may throw away things the
765 ;; user wrote. So let's try to be as conservative as possible:
766 ;; only cut after the first word, if we're reasonably sure that
767 ;; our guess is correct.
768 ;; Note: a quick survey on emacs-devel seemed to indicate that
769 ;; nobody actually cares about the "word-at-a-time" feature of
770 ;; minibuffer-complete-word, whose real raison-d'être is that it
771 ;; tries to add "-" or " ". One more reason to only cut after
772 ;; the first word, if we're really sure we're right.
773 (when (and (or suffix (zerop (length after)))
774 (string-match (concat
775 ;; Make submatch 1 as small as possible
776 ;; to reduce the risk of cutting
777 ;; valuable text.
778 ".*" (regexp-quote prefix) "\\(.*?\\)"
779 (if suffix (regexp-quote suffix) "\\'"))
780 completion)
781 ;; The new point in `completion' should also be just
782 ;; before the suffix, otherwise something more complex
783 ;; is going on, and we're not sure where we are.
784 (eq (match-end 1) comppoint)
785 ;; (match-beginning 1)..comppoint is now the stretch
786 ;; of text in `completion' that was completed at point.
787 (string-match "\\W" completion (match-beginning 1))
788 ;; Is there really something to cut?
789 (> comppoint (match-end 0)))
790 ;; Cut after the first word.
791 (let ((cutpos (match-end 0)))
792 (setq completion (concat (substring completion 0 cutpos)
793 (substring completion comppoint)))
794 (setq comppoint cutpos)))))
796 (cons completion comppoint)))))
799 (defun minibuffer-complete-word ()
800 "Complete the minibuffer contents at most a single word.
801 After one word is completed as much as possible, a space or hyphen
802 is added, provided that matches some possible completion.
803 Return nil if there is no valid completion, else t."
804 (interactive)
805 (case (completion--do-completion 'completion--try-word-completion)
806 (#b000 nil)
807 (#b001 (minibuffer-message "Sole completion")
809 (#b011 (minibuffer-message "Complete, but not unique")
811 (t t)))
813 (defface completions-annotations '((t :inherit italic))
814 "Face to use for annotations in the *Completions* buffer.")
816 (defcustom completions-format nil
817 "Define the appearance and sorting of completions.
818 If the value is `vertical', display completions sorted vertically
819 in columns in the *Completions* buffer.
820 If the value is `horizontal' or nil, display completions sorted
821 horizontally in alphabetical order, rather than down the screen."
822 :type '(choice (const nil) (const horizontal) (const vertical))
823 :group 'minibuffer
824 :version "23.2")
826 (defun completion--insert-strings (strings)
827 "Insert a list of STRINGS into the current buffer.
828 Uses columns to keep the listing readable but compact.
829 It also eliminates runs of equal strings."
830 (when (consp strings)
831 (let* ((length (apply 'max
832 (mapcar (lambda (s)
833 (if (consp s)
834 (+ (string-width (car s))
835 (string-width (cadr s)))
836 (string-width s)))
837 strings)))
838 (window (get-buffer-window (current-buffer) 0))
839 (wwidth (if window (1- (window-width window)) 79))
840 (columns (min
841 ;; At least 2 columns; at least 2 spaces between columns.
842 (max 2 (/ wwidth (+ 2 length)))
843 ;; Don't allocate more columns than we can fill.
844 ;; Windows can't show less than 3 lines anyway.
845 (max 1 (/ (length strings) 2))))
846 (colwidth (/ wwidth columns))
847 (column 0)
848 (rows (/ (length strings) columns))
849 (row 0)
850 (laststring nil))
851 ;; The insertion should be "sensible" no matter what choices were made
852 ;; for the parameters above.
853 (dolist (str strings)
854 (unless (equal laststring str) ; Remove (consecutive) duplicates.
855 (setq laststring str)
856 (let ((length (if (consp str)
857 (+ (string-width (car str))
858 (string-width (cadr str)))
859 (string-width str))))
860 (cond
861 ((eq completions-format 'vertical)
862 ;; Vertical format
863 (when (> row rows)
864 (forward-line (- -1 rows))
865 (setq row 0 column (+ column colwidth)))
866 (when (> column 0)
867 (end-of-line)
868 (while (> (current-column) column)
869 (if (eobp)
870 (insert "\n")
871 (forward-line 1)
872 (end-of-line)))
873 (insert " \t")
874 (set-text-properties (- (point) 1) (point)
875 `(display (space :align-to ,column)))))
877 ;; Horizontal format
878 (unless (bolp)
879 (if (< wwidth (+ (max colwidth length) column))
880 ;; No space for `str' at point, move to next line.
881 (progn (insert "\n") (setq column 0))
882 (insert " \t")
883 ;; Leave the space unpropertized so that in the case we're
884 ;; already past the goal column, there is still
885 ;; a space displayed.
886 (set-text-properties (- (point) 1) (point)
887 ;; We can't just set tab-width, because
888 ;; completion-setup-function will kill all
889 ;; local variables :-(
890 `(display (space :align-to ,column)))
891 nil))))
892 (if (not (consp str))
893 (put-text-property (point) (progn (insert str) (point))
894 'mouse-face 'highlight)
895 (put-text-property (point) (progn (insert (car str)) (point))
896 'mouse-face 'highlight)
897 (add-text-properties (point) (progn (insert (cadr str)) (point))
898 '(mouse-face nil
899 face completions-annotations)))
900 (cond
901 ((eq completions-format 'vertical)
902 ;; Vertical format
903 (if (> column 0)
904 (forward-line)
905 (insert "\n"))
906 (setq row (1+ row)))
908 ;; Horizontal format
909 ;; Next column to align to.
910 (setq column (+ column
911 ;; Round up to a whole number of columns.
912 (* colwidth (ceiling length colwidth))))))))))))
914 (defvar completion-common-substring nil)
915 (make-obsolete-variable 'completion-common-substring nil "23.1")
917 (defvar completion-setup-hook nil
918 "Normal hook run at the end of setting up a completion list buffer.
919 When this hook is run, the current buffer is the one in which the
920 command to display the completion list buffer was run.
921 The completion list buffer is available as the value of `standard-output'.
922 See also `display-completion-list'.")
924 (defface completions-first-difference
925 '((t (:inherit bold)))
926 "Face put on the first uncommon character in completions in *Completions* buffer."
927 :group 'completion)
929 (defface completions-common-part
930 '((t (:inherit default)))
931 "Face put on the common prefix substring in completions in *Completions* buffer.
932 The idea of `completions-common-part' is that you can use it to
933 make the common parts less visible than normal, so that the rest
934 of the differing parts is, by contrast, slightly highlighted."
935 :group 'completion)
937 (defun completion-hilit-commonality (completions prefix-len base-size)
938 (when completions
939 (let ((com-str-len (- prefix-len (or base-size 0))))
940 (nconc
941 (mapcar
942 (lambda (elem)
943 (let ((str
944 ;; Don't modify the string itself, but a copy, since the
945 ;; the string may be read-only or used for other purposes.
946 ;; Furthermore, since `completions' may come from
947 ;; display-completion-list, `elem' may be a list.
948 (if (consp elem)
949 (car (setq elem (cons (copy-sequence (car elem))
950 (cdr elem))))
951 (setq elem (copy-sequence elem)))))
952 (put-text-property 0
953 ;; If completion-boundaries returns incorrect
954 ;; values, all-completions may return strings
955 ;; that don't contain the prefix.
956 (min com-str-len (length str))
957 'font-lock-face 'completions-common-part
958 str)
959 (if (> (length str) com-str-len)
960 (put-text-property com-str-len (1+ com-str-len)
961 'font-lock-face 'completions-first-difference
962 str)))
963 elem)
964 completions)
965 base-size))))
967 (defun display-completion-list (completions &optional common-substring)
968 "Display the list of completions, COMPLETIONS, using `standard-output'.
969 Each element may be just a symbol or string
970 or may be a list of two strings to be printed as if concatenated.
971 If it is a list of two strings, the first is the actual completion
972 alternative, the second serves as annotation.
973 `standard-output' must be a buffer.
974 The actual completion alternatives, as inserted, are given `mouse-face'
975 properties of `highlight'.
976 At the end, this runs the normal hook `completion-setup-hook'.
977 It can find the completion buffer in `standard-output'.
979 The obsolete optional arg COMMON-SUBSTRING, if non-nil, should be a string
980 specifying a common substring for adding the faces
981 `completions-first-difference' and `completions-common-part' to
982 the completions buffer."
983 (if common-substring
984 (setq completions (completion-hilit-commonality
985 completions (length common-substring)
986 ;; We don't know the base-size.
987 nil)))
988 (if (not (bufferp standard-output))
989 ;; This *never* (ever) happens, so there's no point trying to be clever.
990 (with-temp-buffer
991 (let ((standard-output (current-buffer))
992 (completion-setup-hook nil))
993 (display-completion-list completions common-substring))
994 (princ (buffer-string)))
996 (with-current-buffer standard-output
997 (goto-char (point-max))
998 (if (null completions)
999 (insert "There are no possible completions of what you have typed.")
1000 (insert "Possible completions are:\n")
1001 (completion--insert-strings completions))))
1003 ;; The hilit used to be applied via completion-setup-hook, so there
1004 ;; may still be some code that uses completion-common-substring.
1005 (with-no-warnings
1006 (let ((completion-common-substring common-substring))
1007 (run-hooks 'completion-setup-hook)))
1008 nil)
1010 (defvar completion-annotate-function
1012 ;; Note: there's a lot of scope as for when to add annotations and
1013 ;; what annotations to add. E.g. completing-help.el allowed adding
1014 ;; the first line of docstrings to M-x completion. But there's
1015 ;; a tension, since such annotations, while useful at times, can
1016 ;; actually drown the useful information.
1017 ;; So completion-annotate-function should be used parsimoniously, or
1018 ;; else only used upon a user's request (e.g. we could add a command
1019 ;; to completion-list-mode to add annotations to the current
1020 ;; completions).
1021 "Function to add annotations in the *Completions* buffer.
1022 The function takes a completion and should either return nil, or a string that
1023 will be displayed next to the completion. The function can access the
1024 completion table and predicates via `minibuffer-completion-table' and related
1025 variables.")
1027 (defun minibuffer-completion-help ()
1028 "Display a list of possible completions of the current minibuffer contents."
1029 (interactive)
1030 (message "Making completion list...")
1031 (let* ((start (field-beginning))
1032 (string (field-string))
1033 (completions (completion-all-completions
1034 string
1035 minibuffer-completion-table
1036 minibuffer-completion-predicate
1037 (- (point) (field-beginning)))))
1038 (message nil)
1039 (if (and completions
1040 (or (consp (cdr completions))
1041 (not (equal (car completions) string))))
1042 (let* ((last (last completions))
1043 (base-size (cdr last))
1044 ;; If the *Completions* buffer is shown in a new
1045 ;; window, mark it as softly-dedicated, so bury-buffer in
1046 ;; minibuffer-hide-completions will know whether to
1047 ;; delete the window or not.
1048 (display-buffer-mark-dedicated 'soft))
1049 (with-output-to-temp-buffer "*Completions*"
1050 ;; Remove the base-size tail because `sort' requires a properly
1051 ;; nil-terminated list.
1052 (when last (setcdr last nil))
1053 (setq completions (sort completions 'string-lessp))
1054 (when completion-annotate-function
1055 (setq completions
1056 (mapcar (lambda (s)
1057 (let ((ann
1058 (funcall completion-annotate-function s)))
1059 (if ann (list s ann) s)))
1060 completions)))
1061 (with-current-buffer standard-output
1062 (set (make-local-variable 'completion-base-position)
1063 ;; FIXME: We should provide the END part as well, but
1064 ;; currently completion-all-completions does not give
1065 ;; us the necessary information.
1066 (list (+ start base-size) nil)))
1067 (display-completion-list completions)))
1069 ;; If there are no completions, or if the current input is already the
1070 ;; only possible completion, then hide (previous&stale) completions.
1071 (minibuffer-hide-completions)
1072 (ding)
1073 (minibuffer-message
1074 (if completions "Sole completion" "No completions")))
1075 nil))
1077 (defun minibuffer-hide-completions ()
1078 "Get rid of an out-of-date *Completions* buffer."
1079 ;; FIXME: We could/should use minibuffer-scroll-window here, but it
1080 ;; can also point to the minibuffer-parent-window, so it's a bit tricky.
1081 (let ((win (get-buffer-window "*Completions*" 0)))
1082 (if win (with-selected-window win (bury-buffer)))))
1084 (defun exit-minibuffer ()
1085 "Terminate this minibuffer argument."
1086 (interactive)
1087 ;; If the command that uses this has made modifications in the minibuffer,
1088 ;; we don't want them to cause deactivation of the mark in the original
1089 ;; buffer.
1090 ;; A better solution would be to make deactivate-mark buffer-local
1091 ;; (or to turn it into a list of buffers, ...), but in the mean time,
1092 ;; this should do the trick in most cases.
1093 (setq deactivate-mark nil)
1094 (throw 'exit nil))
1096 (defun self-insert-and-exit ()
1097 "Terminate minibuffer input."
1098 (interactive)
1099 (if (characterp last-command-event)
1100 (call-interactively 'self-insert-command)
1101 (ding))
1102 (exit-minibuffer))
1104 (defvar completion-in-region-functions nil
1105 "Wrapper hook around `completion-in-region'.
1106 The functions on this special hook are called with 5 arguments:
1107 NEXT-FUN START END COLLECTION PREDICATE.
1108 NEXT-FUN is a function of four arguments (START END COLLECTION PREDICATE)
1109 that performs the default operation. The other four arguments are like
1110 the ones passed to `completion-in-region'. The functions on this hook
1111 are expected to perform completion on START..END using COLLECTION
1112 and PREDICATE, either by calling NEXT-FUN or by doing it themselves.")
1114 (defun completion-in-region (start end collection &optional predicate)
1115 "Complete the text between START and END using COLLECTION.
1116 Return nil if there is no valid completion, else t.
1117 Point needs to be somewhere between START and END."
1118 (assert (<= start (point)) (<= (point) end))
1119 ;; FIXME: undisplay the *Completions* buffer once the completion is done.
1120 (with-wrapper-hook
1121 completion-in-region-functions (start end collection predicate)
1122 (let ((minibuffer-completion-table collection)
1123 (minibuffer-completion-predicate predicate)
1124 (ol (make-overlay start end nil nil t)))
1125 (overlay-put ol 'field 'completion)
1126 (unwind-protect
1127 (call-interactively 'minibuffer-complete)
1128 (delete-overlay ol)))))
1130 (defvar completion-at-point-functions nil
1131 "Special hook to find the completion table for the thing at point.
1132 It is called without any argument and should return either nil,
1133 or a function of no argument to perform completion (discouraged),
1134 or a list of the form (START END COLLECTION &rest PROPS) where
1135 START and END delimit the entity to complete and should include point,
1136 COLLECTION is the completion table to use to complete it, and
1137 PROPS is a property list for additional information.
1138 Currently supported properties are:
1139 `:predicate' a predicate that completion candidates need to satisfy.
1140 `:annotation-function' the value to use for `completion-annotate-function'.")
1142 (defun completion-at-point ()
1143 "Complete the thing at point according to local mode."
1144 (interactive)
1145 (let ((res (run-hook-with-args-until-success
1146 'completion-at-point-functions)))
1147 (cond
1148 ((functionp res) (funcall res))
1149 (res
1150 (let* ((plist (nthcdr 3 res))
1151 (start (nth 0 res))
1152 (end (nth 1 res))
1153 (completion-annotate-function
1154 (or (plist-get plist :annotation-function)
1155 completion-annotate-function)))
1156 (completion-in-region start end (nth 2 res)
1157 (plist-get plist :predicate)))))))
1159 ;;; Key bindings.
1161 (define-obsolete-variable-alias 'minibuffer-local-must-match-filename-map
1162 'minibuffer-local-filename-must-match-map "23.1")
1164 (let ((map minibuffer-local-map))
1165 (define-key map "\C-g" 'abort-recursive-edit)
1166 (define-key map "\r" 'exit-minibuffer)
1167 (define-key map "\n" 'exit-minibuffer))
1169 (let ((map minibuffer-local-completion-map))
1170 (define-key map "\t" 'minibuffer-complete)
1171 ;; M-TAB is already abused for many other purposes, so we should find
1172 ;; another binding for it.
1173 ;; (define-key map "\e\t" 'minibuffer-force-complete)
1174 (define-key map " " 'minibuffer-complete-word)
1175 (define-key map "?" 'minibuffer-completion-help))
1177 (let ((map minibuffer-local-must-match-map))
1178 (define-key map "\r" 'minibuffer-complete-and-exit)
1179 (define-key map "\n" 'minibuffer-complete-and-exit))
1181 (let ((map minibuffer-local-filename-completion-map))
1182 (define-key map " " nil))
1183 (let ((map minibuffer-local-filename-must-match-map))
1184 (define-key map " " nil))
1186 (let ((map minibuffer-local-ns-map))
1187 (define-key map " " 'exit-minibuffer)
1188 (define-key map "\t" 'exit-minibuffer)
1189 (define-key map "?" 'self-insert-and-exit))
1191 ;;; Completion tables.
1193 (defun minibuffer--double-dollars (str)
1194 (replace-regexp-in-string "\\$" "$$" str))
1196 (defun completion--make-envvar-table ()
1197 (mapcar (lambda (enventry)
1198 (substring enventry 0 (string-match-p "=" enventry)))
1199 process-environment))
1201 (defconst completion--embedded-envvar-re
1202 (concat "\\(?:^\\|[^$]\\(?:\\$\\$\\)*\\)"
1203 "$\\([[:alnum:]_]*\\|{\\([^}]*\\)\\)\\'"))
1205 (defun completion--embedded-envvar-table (string pred action)
1206 "Completion table for envvars embedded in a string.
1207 The envvar syntax (and escaping) rules followed by this table are the
1208 same as `substitute-in-file-name'."
1209 ;; We ignore `pred', because the predicates passed to us via
1210 ;; read-file-name-internal are not 100% correct and fail here:
1211 ;; e.g. we get predicates like file-directory-p there, whereas the filename
1212 ;; completed needs to be passed through substitute-in-file-name before it
1213 ;; can be passed to file-directory-p.
1214 (when (string-match completion--embedded-envvar-re string)
1215 (let* ((beg (or (match-beginning 2) (match-beginning 1)))
1216 (table (completion--make-envvar-table))
1217 (prefix (substring string 0 beg)))
1218 (cond
1219 ((eq action 'lambda)
1220 ;; This table is expected to be used in conjunction with some
1221 ;; other table that provides the "main" completion. Let the
1222 ;; other table handle the test-completion case.
1223 nil)
1224 ((eq (car-safe action) 'boundaries)
1225 ;; Only return boundaries if there's something to complete,
1226 ;; since otherwise when we're used in
1227 ;; completion-table-in-turn, we could return boundaries and
1228 ;; let some subsequent table return a list of completions.
1229 ;; FIXME: Maybe it should rather be fixed in
1230 ;; completion-table-in-turn instead, but it's difficult to
1231 ;; do it efficiently there.
1232 (when (try-completion (substring string beg) table nil)
1233 ;; Compute the boundaries of the subfield to which this
1234 ;; completion applies.
1235 (let ((suffix (cdr action)))
1236 (list* 'boundaries
1237 (or (match-beginning 2) (match-beginning 1))
1238 (when (string-match "[^[:alnum:]_]" suffix)
1239 (match-beginning 0))))))
1241 (if (eq (aref string (1- beg)) ?{)
1242 (setq table (apply-partially 'completion-table-with-terminator
1243 "}" table)))
1244 ;; Even if file-name completion is case-insensitive, we want
1245 ;; envvar completion to be case-sensitive.
1246 (let ((completion-ignore-case nil))
1247 (completion-table-with-context
1248 prefix table (substring string beg) nil action)))))))
1250 (defun completion-file-name-table (string pred action)
1251 "Completion table for file names."
1252 (ignore-errors
1253 (cond
1254 ((eq (car-safe action) 'boundaries)
1255 (let ((start (length (file-name-directory string)))
1256 (end (string-match-p "/" (cdr action))))
1257 (list* 'boundaries start end)))
1259 ((eq action 'lambda)
1260 (if (zerop (length string))
1261 nil ;Not sure why it's here, but it probably doesn't harm.
1262 (funcall (or pred 'file-exists-p) string)))
1265 (let* ((name (file-name-nondirectory string))
1266 (specdir (file-name-directory string))
1267 (realdir (or specdir default-directory)))
1269 (cond
1270 ((null action)
1271 (let ((comp (file-name-completion name realdir pred)))
1272 (if (stringp comp)
1273 (concat specdir comp)
1274 comp)))
1276 ((eq action t)
1277 (let ((all (file-name-all-completions name realdir)))
1279 ;; Check the predicate, if necessary.
1280 (unless (memq pred '(nil file-exists-p))
1281 (let ((comp ())
1282 (pred
1283 (if (eq pred 'file-directory-p)
1284 ;; Brute-force speed up for directory checking:
1285 ;; Discard strings which don't end in a slash.
1286 (lambda (s)
1287 (let ((len (length s)))
1288 (and (> len 0) (eq (aref s (1- len)) ?/))))
1289 ;; Must do it the hard (and slow) way.
1290 pred)))
1291 (let ((default-directory (expand-file-name realdir)))
1292 (dolist (tem all)
1293 (if (funcall pred tem) (push tem comp))))
1294 (setq all (nreverse comp))))
1296 all))))))))
1298 (defvar read-file-name-predicate nil
1299 "Current predicate used by `read-file-name-internal'.")
1300 (make-obsolete-variable 'read-file-name-predicate
1301 "use the regular PRED argument" "23.2")
1303 (defun completion--file-name-table (string pred action)
1304 "Internal subroutine for `read-file-name'. Do not call this.
1305 This is a completion table for file names, like `completion-file-name-table'
1306 except that it passes the file name through `substitute-in-file-name'."
1307 (cond
1308 ((eq (car-safe action) 'boundaries)
1309 ;; For the boundaries, we can't really delegate to
1310 ;; completion-file-name-table and then fix them up, because it
1311 ;; would require us to track the relationship between `str' and
1312 ;; `string', which is difficult. And in any case, if
1313 ;; substitute-in-file-name turns "fo-$TO-ba" into "fo-o/b-ba", there's
1314 ;; no way for us to return proper boundaries info, because the
1315 ;; boundary is not (yet) in `string'.
1316 ;; FIXME: Actually there is a way to return correct boundaries info,
1317 ;; at the condition of modifying the all-completions return accordingly.
1318 (let ((start (length (file-name-directory string)))
1319 (end (string-match-p "/" (cdr action))))
1320 (list* 'boundaries start end)))
1323 (let* ((default-directory
1324 (if (stringp pred)
1325 ;; It used to be that `pred' was abused to pass `dir'
1326 ;; as an argument.
1327 (prog1 (file-name-as-directory (expand-file-name pred))
1328 (setq pred nil))
1329 default-directory))
1330 (str (condition-case nil
1331 (substitute-in-file-name string)
1332 (error string)))
1333 (comp (completion-file-name-table
1334 str (or pred read-file-name-predicate) action)))
1336 (cond
1337 ((stringp comp)
1338 ;; Requote the $s before returning the completion.
1339 (minibuffer--double-dollars comp))
1340 ((and (null action) comp
1341 ;; Requote the $s before checking for changes.
1342 (setq str (minibuffer--double-dollars str))
1343 (not (string-equal string str)))
1344 ;; If there's no real completion, but substitute-in-file-name
1345 ;; changed the string, then return the new string.
1346 str)
1347 (t comp))))))
1349 (defalias 'read-file-name-internal
1350 (completion-table-in-turn 'completion--embedded-envvar-table
1351 'completion--file-name-table)
1352 "Internal subroutine for `read-file-name'. Do not call this.")
1354 (defvar read-file-name-function nil
1355 "If this is non-nil, `read-file-name' does its work by calling this function.")
1357 (defcustom read-file-name-completion-ignore-case
1358 (if (memq system-type '(ms-dos windows-nt darwin cygwin))
1359 t nil)
1360 "Non-nil means when reading a file name completion ignores case."
1361 :group 'minibuffer
1362 :type 'boolean
1363 :version "22.1")
1365 (defcustom insert-default-directory t
1366 "Non-nil means when reading a filename start with default dir in minibuffer.
1368 When the initial minibuffer contents show a name of a file or a directory,
1369 typing RETURN without editing the initial contents is equivalent to typing
1370 the default file name.
1372 If this variable is non-nil, the minibuffer contents are always
1373 initially non-empty, and typing RETURN without editing will fetch the
1374 default name, if one is provided. Note however that this default name
1375 is not necessarily the same as initial contents inserted in the minibuffer,
1376 if the initial contents is just the default directory.
1378 If this variable is nil, the minibuffer often starts out empty. In
1379 that case you may have to explicitly fetch the next history element to
1380 request the default name; typing RETURN without editing will leave
1381 the minibuffer empty.
1383 For some commands, exiting with an empty minibuffer has a special meaning,
1384 such as making the current buffer visit no file in the case of
1385 `set-visited-file-name'."
1386 :group 'minibuffer
1387 :type 'boolean)
1389 ;; Not always defined, but only called if next-read-file-uses-dialog-p says so.
1390 (declare-function x-file-dialog "xfns.c"
1391 (prompt dir &optional default-filename mustmatch only-dir-p))
1393 (defun read-file-name-defaults (&optional dir initial)
1394 (let ((default
1395 (cond
1396 ;; With non-nil `initial', use `dir' as the first default.
1397 ;; Essentially, this mean reversing the normal order of the
1398 ;; current directory name and the current file name, i.e.
1399 ;; 1. with normal file reading:
1400 ;; 1.1. initial input is the current directory
1401 ;; 1.2. the first default is the current file name
1402 ;; 2. with non-nil `initial' (e.g. for `find-alternate-file'):
1403 ;; 2.2. initial input is the current file name
1404 ;; 2.1. the first default is the current directory
1405 (initial (abbreviate-file-name dir))
1406 ;; In file buffers, try to get the current file name
1407 (buffer-file-name
1408 (abbreviate-file-name buffer-file-name))))
1409 (file-name-at-point
1410 (run-hook-with-args-until-success 'file-name-at-point-functions)))
1411 (when file-name-at-point
1412 (setq default (delete-dups
1413 (delete "" (delq nil (list file-name-at-point default))))))
1414 ;; Append new defaults to the end of existing `minibuffer-default'.
1415 (append
1416 (if (listp minibuffer-default) minibuffer-default (list minibuffer-default))
1417 (if (listp default) default (list default)))))
1419 (defun read-file-name (prompt &optional dir default-filename mustmatch initial predicate)
1420 "Read file name, prompting with PROMPT and completing in directory DIR.
1421 Value is not expanded---you must call `expand-file-name' yourself.
1422 Default name to DEFAULT-FILENAME if user exits the minibuffer with
1423 the same non-empty string that was inserted by this function.
1424 (If DEFAULT-FILENAME is omitted, the visited file name is used,
1425 except that if INITIAL is specified, that combined with DIR is used.
1426 If DEFAULT-FILENAME is a list of file names, the first file name is used.)
1427 If the user exits with an empty minibuffer, this function returns
1428 an empty string. (This can only happen if the user erased the
1429 pre-inserted contents or if `insert-default-directory' is nil.)
1431 Fourth arg MUSTMATCH can take the following values:
1432 - nil means that the user can exit with any input.
1433 - t means that the user is not allowed to exit unless
1434 the input is (or completes to) an existing file.
1435 - `confirm' means that the user can exit with any input, but she needs
1436 to confirm her choice if the input is not an existing file.
1437 - `confirm-after-completion' means that the user can exit with any
1438 input, but she needs to confirm her choice if she called
1439 `minibuffer-complete' right before `minibuffer-complete-and-exit'
1440 and the input is not an existing file.
1441 - anything else behaves like t except that typing RET does not exit if it
1442 does non-null completion.
1444 Fifth arg INITIAL specifies text to start with.
1446 If optional sixth arg PREDICATE is non-nil, possible completions and
1447 the resulting file name must satisfy (funcall PREDICATE NAME).
1448 DIR should be an absolute directory name. It defaults to the value of
1449 `default-directory'.
1451 If this command was invoked with the mouse, use a graphical file
1452 dialog if `use-dialog-box' is non-nil, and the window system or X
1453 toolkit in use provides a file dialog box, and DIR is not a
1454 remote file. For graphical file dialogs, any the special values
1455 of MUSTMATCH; `confirm' and `confirm-after-completion' are
1456 treated as equivalent to nil.
1458 See also `read-file-name-completion-ignore-case'
1459 and `read-file-name-function'."
1460 (unless dir (setq dir default-directory))
1461 (unless (file-name-absolute-p dir) (setq dir (expand-file-name dir)))
1462 (unless default-filename
1463 (setq default-filename (if initial (expand-file-name initial dir)
1464 buffer-file-name)))
1465 ;; If dir starts with user's homedir, change that to ~.
1466 (setq dir (abbreviate-file-name dir))
1467 ;; Likewise for default-filename.
1468 (if default-filename
1469 (setq default-filename
1470 (if (consp default-filename)
1471 (mapcar 'abbreviate-file-name default-filename)
1472 (abbreviate-file-name default-filename))))
1473 (let ((insdef (cond
1474 ((and insert-default-directory (stringp dir))
1475 (if initial
1476 (cons (minibuffer--double-dollars (concat dir initial))
1477 (length (minibuffer--double-dollars dir)))
1478 (minibuffer--double-dollars dir)))
1479 (initial (cons (minibuffer--double-dollars initial) 0)))))
1481 (if read-file-name-function
1482 (funcall read-file-name-function
1483 prompt dir default-filename mustmatch initial predicate)
1484 (let ((completion-ignore-case read-file-name-completion-ignore-case)
1485 (minibuffer-completing-file-name t)
1486 (pred (or predicate 'file-exists-p))
1487 (add-to-history nil))
1489 (let* ((val
1490 (if (or (not (next-read-file-uses-dialog-p))
1491 ;; Graphical file dialogs can't handle remote
1492 ;; files (Bug#99).
1493 (file-remote-p dir))
1494 ;; We used to pass `dir' to `read-file-name-internal' by
1495 ;; abusing the `predicate' argument. It's better to
1496 ;; just use `default-directory', but in order to avoid
1497 ;; changing `default-directory' in the current buffer,
1498 ;; we don't let-bind it.
1499 (lexical-let ((dir (file-name-as-directory
1500 (expand-file-name dir))))
1501 (minibuffer-with-setup-hook
1502 (lambda ()
1503 (setq default-directory dir)
1504 ;; When the first default in `minibuffer-default'
1505 ;; duplicates initial input `insdef',
1506 ;; reset `minibuffer-default' to nil.
1507 (when (equal (or (car-safe insdef) insdef)
1508 (or (car-safe minibuffer-default)
1509 minibuffer-default))
1510 (setq minibuffer-default
1511 (cdr-safe minibuffer-default)))
1512 ;; On the first request on `M-n' fill
1513 ;; `minibuffer-default' with a list of defaults
1514 ;; relevant for file-name reading.
1515 (set (make-local-variable 'minibuffer-default-add-function)
1516 (lambda ()
1517 (with-current-buffer
1518 (window-buffer (minibuffer-selected-window))
1519 (read-file-name-defaults dir initial)))))
1520 (completing-read prompt 'read-file-name-internal
1521 pred mustmatch insdef
1522 'file-name-history default-filename)))
1523 ;; If DEFAULT-FILENAME not supplied and DIR contains
1524 ;; a file name, split it.
1525 (let ((file (file-name-nondirectory dir))
1526 ;; When using a dialog, revert to nil and non-nil
1527 ;; interpretation of mustmatch. confirm options
1528 ;; need to be interpreted as nil, otherwise
1529 ;; it is impossible to create new files using
1530 ;; dialogs with the default settings.
1531 (dialog-mustmatch
1532 (not (memq mustmatch
1533 '(nil confirm confirm-after-completion)))))
1534 (when (and (not default-filename)
1535 (not (zerop (length file))))
1536 (setq default-filename file)
1537 (setq dir (file-name-directory dir)))
1538 (when default-filename
1539 (setq default-filename
1540 (expand-file-name (if (consp default-filename)
1541 (car default-filename)
1542 default-filename)
1543 dir)))
1544 (setq add-to-history t)
1545 (x-file-dialog prompt dir default-filename
1546 dialog-mustmatch
1547 (eq predicate 'file-directory-p)))))
1549 (replace-in-history (eq (car-safe file-name-history) val)))
1550 ;; If completing-read returned the inserted default string itself
1551 ;; (rather than a new string with the same contents),
1552 ;; it has to mean that the user typed RET with the minibuffer empty.
1553 ;; In that case, we really want to return ""
1554 ;; so that commands such as set-visited-file-name can distinguish.
1555 (when (consp default-filename)
1556 (setq default-filename (car default-filename)))
1557 (when (eq val default-filename)
1558 ;; In this case, completing-read has not added an element
1559 ;; to the history. Maybe we should.
1560 (if (not replace-in-history)
1561 (setq add-to-history t))
1562 (setq val ""))
1563 (unless val (error "No file name specified"))
1565 (if (and default-filename
1566 (string-equal val (if (consp insdef) (car insdef) insdef)))
1567 (setq val default-filename))
1568 (setq val (substitute-in-file-name val))
1570 (if replace-in-history
1571 ;; Replace what Fcompleting_read added to the history
1572 ;; with what we will actually return. As an exception,
1573 ;; if that's the same as the second item in
1574 ;; file-name-history, it's really a repeat (Bug#4657).
1575 (let ((val1 (minibuffer--double-dollars val)))
1576 (if history-delete-duplicates
1577 (setcdr file-name-history
1578 (delete val1 (cdr file-name-history))))
1579 (if (string= val1 (cadr file-name-history))
1580 (pop file-name-history)
1581 (setcar file-name-history val1)))
1582 (if add-to-history
1583 ;; Add the value to the history--but not if it matches
1584 ;; the last value already there.
1585 (let ((val1 (minibuffer--double-dollars val)))
1586 (unless (and (consp file-name-history)
1587 (equal (car file-name-history) val1))
1588 (setq file-name-history
1589 (cons val1
1590 (if history-delete-duplicates
1591 (delete val1 file-name-history)
1592 file-name-history)))))))
1593 val)))))
1595 (defun internal-complete-buffer-except (&optional buffer)
1596 "Perform completion on all buffers excluding BUFFER.
1597 BUFFER nil or omitted means use the current buffer.
1598 Like `internal-complete-buffer', but removes BUFFER from the completion list."
1599 (lexical-let ((except (if (stringp buffer) buffer (buffer-name buffer))))
1600 (apply-partially 'completion-table-with-predicate
1601 'internal-complete-buffer
1602 (lambda (name)
1603 (not (equal (if (consp name) (car name) name) except)))
1604 nil)))
1606 ;;; Old-style completion, used in Emacs-21 and Emacs-22.
1608 (defun completion-emacs21-try-completion (string table pred point)
1609 (let ((completion (try-completion string table pred)))
1610 (if (stringp completion)
1611 (cons completion (length completion))
1612 completion)))
1614 (defun completion-emacs21-all-completions (string table pred point)
1615 (completion-hilit-commonality
1616 (all-completions string table pred)
1617 (length string)
1618 (car (completion-boundaries string table pred ""))))
1620 (defun completion-emacs22-try-completion (string table pred point)
1621 (let ((suffix (substring string point))
1622 (completion (try-completion (substring string 0 point) table pred)))
1623 (if (not (stringp completion))
1624 completion
1625 ;; Merge a trailing / in completion with a / after point.
1626 ;; We used to only do it for word completion, but it seems to make
1627 ;; sense for all completions.
1628 ;; Actually, claiming this feature was part of Emacs-22 completion
1629 ;; is pushing it a bit: it was only done in minibuffer-completion-word,
1630 ;; which was (by default) not bound during file completion, where such
1631 ;; slashes are most likely to occur.
1632 (if (and (not (zerop (length completion)))
1633 (eq ?/ (aref completion (1- (length completion))))
1634 (not (zerop (length suffix)))
1635 (eq ?/ (aref suffix 0)))
1636 ;; This leaves point after the / .
1637 (setq suffix (substring suffix 1)))
1638 (cons (concat completion suffix) (length completion)))))
1640 (defun completion-emacs22-all-completions (string table pred point)
1641 (let ((beforepoint (substring string 0 point)))
1642 (completion-hilit-commonality
1643 (all-completions beforepoint table pred)
1644 point
1645 (car (completion-boundaries beforepoint table pred "")))))
1647 ;;; Basic completion.
1649 (defun completion--merge-suffix (completion point suffix)
1650 "Merge end of COMPLETION with beginning of SUFFIX.
1651 Simple generalization of the \"merge trailing /\" done in Emacs-22.
1652 Return the new suffix."
1653 (if (and (not (zerop (length suffix)))
1654 (string-match "\\(.+\\)\n\\1" (concat completion "\n" suffix)
1655 ;; Make sure we don't compress things to less
1656 ;; than we started with.
1657 point)
1658 ;; Just make sure we didn't match some other \n.
1659 (eq (match-end 1) (length completion)))
1660 (substring suffix (- (match-end 1) (match-beginning 1)))
1661 ;; Nothing to merge.
1662 suffix))
1664 (defun completion-basic--pattern (beforepoint afterpoint bounds)
1665 (delete
1666 "" (list (substring beforepoint (car bounds))
1667 'point
1668 (substring afterpoint 0 (cdr bounds)))))
1670 (defun completion-basic-try-completion (string table pred point)
1671 (let* ((beforepoint (substring string 0 point))
1672 (afterpoint (substring string point))
1673 (bounds (completion-boundaries beforepoint table pred afterpoint)))
1674 (if (zerop (cdr bounds))
1675 ;; `try-completion' may return a subtly different result
1676 ;; than `all+merge', so try to use it whenever possible.
1677 (let ((completion (try-completion beforepoint table pred)))
1678 (if (not (stringp completion))
1679 completion
1680 (cons
1681 (concat completion
1682 (completion--merge-suffix completion point afterpoint))
1683 (length completion))))
1684 (let* ((suffix (substring afterpoint (cdr bounds)))
1685 (prefix (substring beforepoint 0 (car bounds)))
1686 (pattern (completion-basic--pattern
1687 beforepoint afterpoint bounds))
1688 (all (completion-pcm--all-completions prefix pattern table pred)))
1689 (if minibuffer-completing-file-name
1690 (setq all (completion-pcm--filename-try-filter all)))
1691 (completion-pcm--merge-try pattern all prefix suffix)))))
1693 (defun completion-basic-all-completions (string table pred point)
1694 (let* ((beforepoint (substring string 0 point))
1695 (afterpoint (substring string point))
1696 (bounds (completion-boundaries beforepoint table pred afterpoint))
1697 (prefix (substring beforepoint 0 (car bounds)))
1698 (pattern (completion-basic--pattern beforepoint afterpoint bounds))
1699 (all (completion-pcm--all-completions prefix pattern table pred)))
1700 (completion-hilit-commonality all point (car bounds))))
1702 ;;; Partial-completion-mode style completion.
1704 (defvar completion-pcm--delim-wild-regex nil
1705 "Regular expression matching delimiters controlling the partial-completion.
1706 Typically, this regular expression simply matches a delimiter, meaning
1707 that completion can add something at (match-beginning 0), but if it has
1708 a submatch 1, then completion can add something at (match-end 1).
1709 This is used when the delimiter needs to be of size zero (e.g. the transition
1710 from lowercase to uppercase characters).")
1712 (defun completion-pcm--prepare-delim-re (delims)
1713 (setq completion-pcm--delim-wild-regex (concat "[" delims "*]")))
1715 (defcustom completion-pcm-word-delimiters "-_./: "
1716 "A string of characters treated as word delimiters for completion.
1717 Some arcane rules:
1718 If `]' is in this string, it must come first.
1719 If `^' is in this string, it must not come first.
1720 If `-' is in this string, it must come first or right after `]'.
1721 In other words, if S is this string, then `[S]' must be a valid Emacs regular
1722 expression (not containing character ranges like `a-z')."
1723 :set (lambda (symbol value)
1724 (set-default symbol value)
1725 ;; Refresh other vars.
1726 (completion-pcm--prepare-delim-re value))
1727 :initialize 'custom-initialize-reset
1728 :group 'minibuffer
1729 :type 'string)
1731 (defun completion-pcm--pattern-trivial-p (pattern)
1732 (and (stringp (car pattern))
1733 ;; It can be followed by `point' and "" and still be trivial.
1734 (let ((trivial t))
1735 (dolist (elem (cdr pattern))
1736 (unless (member elem '(point ""))
1737 (setq trivial nil)))
1738 trivial)))
1740 (defun completion-pcm--string->pattern (string &optional point)
1741 "Split STRING into a pattern.
1742 A pattern is a list where each element is either a string
1743 or a symbol chosen among `any', `star', `point'."
1744 (if (and point (< point (length string)))
1745 (let ((prefix (substring string 0 point))
1746 (suffix (substring string point)))
1747 (append (completion-pcm--string->pattern prefix)
1748 '(point)
1749 (completion-pcm--string->pattern suffix)))
1750 (let ((pattern nil)
1751 (p 0)
1752 (p0 0))
1754 (while (and (setq p (string-match completion-pcm--delim-wild-regex
1755 string p))
1756 ;; If the char was added by minibuffer-complete-word, then
1757 ;; don't treat it as a delimiter, otherwise "M-x SPC"
1758 ;; ends up inserting a "-" rather than listing
1759 ;; all completions.
1760 (not (get-text-property p 'completion-try-word string)))
1761 ;; Usually, completion-pcm--delim-wild-regex matches a delimiter,
1762 ;; meaning that something can be added *before* it, but it can also
1763 ;; match a prefix and postfix, in which case something can be added
1764 ;; in-between (e.g. match [[:lower:]][[:upper:]]).
1765 ;; This is determined by the presence of a submatch-1 which delimits
1766 ;; the prefix.
1767 (if (match-end 1) (setq p (match-end 1)))
1768 (push (substring string p0 p) pattern)
1769 (if (eq (aref string p) ?*)
1770 (progn
1771 (push 'star pattern)
1772 (setq p0 (1+ p)))
1773 (push 'any pattern)
1774 (setq p0 p))
1775 (incf p))
1777 ;; An empty string might be erroneously added at the beginning.
1778 ;; It should be avoided properly, but it's so easy to remove it here.
1779 (delete "" (nreverse (cons (substring string p0) pattern))))))
1781 (defun completion-pcm--pattern->regex (pattern &optional group)
1782 (let ((re
1783 (concat "\\`"
1784 (mapconcat
1785 (lambda (x)
1786 (case x
1787 ((star any point)
1788 (if (if (consp group) (memq x group) group)
1789 "\\(.*?\\)" ".*?"))
1790 (t (regexp-quote x))))
1791 pattern
1792 ""))))
1793 ;; Avoid pathological backtracking.
1794 (while (string-match "\\.\\*\\?\\(?:\\\\[()]\\)*\\(\\.\\*\\?\\)" re)
1795 (setq re (replace-match "" t t re 1)))
1796 re))
1798 (defun completion-pcm--all-completions (prefix pattern table pred)
1799 "Find all completions for PATTERN in TABLE obeying PRED.
1800 PATTERN is as returned by `completion-pcm--string->pattern'."
1801 ;; (assert (= (car (completion-boundaries prefix table pred ""))
1802 ;; (length prefix)))
1803 ;; Find an initial list of possible completions.
1804 (if (completion-pcm--pattern-trivial-p pattern)
1806 ;; Minibuffer contains no delimiters -- simple case!
1807 (all-completions (concat prefix (car pattern)) table pred)
1809 ;; Use all-completions to do an initial cull. This is a big win,
1810 ;; since all-completions is written in C!
1811 (let* (;; Convert search pattern to a standard regular expression.
1812 (regex (completion-pcm--pattern->regex pattern))
1813 (case-fold-search completion-ignore-case)
1814 (completion-regexp-list (cons regex completion-regexp-list))
1815 (compl (all-completions
1816 (concat prefix (if (stringp (car pattern)) (car pattern) ""))
1817 table pred)))
1818 (if (not (functionp table))
1819 ;; The internal functions already obeyed completion-regexp-list.
1820 compl
1821 (let ((poss ()))
1822 (dolist (c compl)
1823 (when (string-match-p regex c) (push c poss)))
1824 poss)))))
1826 (defun completion-pcm--hilit-commonality (pattern completions)
1827 (when completions
1828 (let* ((re (completion-pcm--pattern->regex pattern '(point)))
1829 (case-fold-search completion-ignore-case))
1830 (mapcar
1831 (lambda (str)
1832 ;; Don't modify the string itself.
1833 (setq str (copy-sequence str))
1834 (unless (string-match re str)
1835 (error "Internal error: %s does not match %s" re str))
1836 (let ((pos (or (match-beginning 1) (match-end 0))))
1837 (put-text-property 0 pos
1838 'font-lock-face 'completions-common-part
1839 str)
1840 (if (> (length str) pos)
1841 (put-text-property pos (1+ pos)
1842 'font-lock-face 'completions-first-difference
1843 str)))
1844 str)
1845 completions))))
1847 (defun completion-pcm--find-all-completions (string table pred point
1848 &optional filter)
1849 "Find all completions for STRING at POINT in TABLE, satisfying PRED.
1850 POINT is a position inside STRING.
1851 FILTER is a function applied to the return value, that can be used, e.g. to
1852 filter out additional entries (because TABLE migth not obey PRED)."
1853 (unless filter (setq filter 'identity))
1854 (let* ((beforepoint (substring string 0 point))
1855 (afterpoint (substring string point))
1856 (bounds (completion-boundaries beforepoint table pred afterpoint))
1857 (prefix (substring beforepoint 0 (car bounds)))
1858 (suffix (substring afterpoint (cdr bounds)))
1859 firsterror)
1860 (setq string (substring string (car bounds) (+ point (cdr bounds))))
1861 (let* ((relpoint (- point (car bounds)))
1862 (pattern (completion-pcm--string->pattern string relpoint))
1863 (all (condition-case err
1864 (funcall filter
1865 (completion-pcm--all-completions
1866 prefix pattern table pred))
1867 (error (unless firsterror (setq firsterror err)) nil))))
1868 (when (and (null all)
1869 (> (car bounds) 0)
1870 (null (ignore-errors (try-completion prefix table pred))))
1871 ;; The prefix has no completions at all, so we should try and fix
1872 ;; that first.
1873 (let ((substring (substring prefix 0 -1)))
1874 (destructuring-bind (subpat suball subprefix subsuffix)
1875 (completion-pcm--find-all-completions
1876 substring table pred (length substring) filter)
1877 (let ((sep (aref prefix (1- (length prefix))))
1878 ;; Text that goes between the new submatches and the
1879 ;; completion substring.
1880 (between nil))
1881 ;; Eliminate submatches that don't end with the separator.
1882 (dolist (submatch (prog1 suball (setq suball ())))
1883 (when (eq sep (aref submatch (1- (length submatch))))
1884 (push submatch suball)))
1885 (when suball
1886 ;; Update the boundaries and corresponding pattern.
1887 ;; We assume that all submatches result in the same boundaries
1888 ;; since we wouldn't know how to merge them otherwise anyway.
1889 ;; FIXME: COMPLETE REWRITE!!!
1890 (let* ((newbeforepoint
1891 (concat subprefix (car suball)
1892 (substring string 0 relpoint)))
1893 (leftbound (+ (length subprefix) (length (car suball))))
1894 (newbounds (completion-boundaries
1895 newbeforepoint table pred afterpoint)))
1896 (unless (or (and (eq (cdr bounds) (cdr newbounds))
1897 (eq (car newbounds) leftbound))
1898 ;; Refuse new boundaries if they step over
1899 ;; the submatch.
1900 (< (car newbounds) leftbound))
1901 ;; The new completed prefix does change the boundaries
1902 ;; of the completed substring.
1903 (setq suffix (substring afterpoint (cdr newbounds)))
1904 (setq string
1905 (concat (substring newbeforepoint (car newbounds))
1906 (substring afterpoint 0 (cdr newbounds))))
1907 (setq between (substring newbeforepoint leftbound
1908 (car newbounds)))
1909 (setq pattern (completion-pcm--string->pattern
1910 string
1911 (- (length newbeforepoint)
1912 (car newbounds)))))
1913 (dolist (submatch suball)
1914 (setq all (nconc (mapcar
1915 (lambda (s) (concat submatch between s))
1916 (funcall filter
1917 (completion-pcm--all-completions
1918 (concat subprefix submatch between)
1919 pattern table pred)))
1920 all)))
1921 ;; FIXME: This can come in handy for try-completion,
1922 ;; but isn't right for all-completions, since it lists
1923 ;; invalid completions.
1924 ;; (unless all
1925 ;; ;; Even though we found expansions in the prefix, none
1926 ;; ;; leads to a valid completion.
1927 ;; ;; Let's keep the expansions, tho.
1928 ;; (dolist (submatch suball)
1929 ;; (push (concat submatch between newsubstring) all)))
1931 (setq pattern (append subpat (list 'any (string sep))
1932 (if between (list between)) pattern))
1933 (setq prefix subprefix)))))
1934 (if (and (null all) firsterror)
1935 (signal (car firsterror) (cdr firsterror))
1936 (list pattern all prefix suffix)))))
1938 (defun completion-pcm-all-completions (string table pred point)
1939 (destructuring-bind (pattern all &optional prefix suffix)
1940 (completion-pcm--find-all-completions string table pred point)
1941 (when all
1942 (nconc (completion-pcm--hilit-commonality pattern all)
1943 (length prefix)))))
1945 (defun completion-pcm--merge-completions (strs pattern)
1946 "Extract the commonality in STRS, with the help of PATTERN."
1947 ;; When completing while ignoring case, we want to try and avoid
1948 ;; completing "fo" to "foO" when completing against "FOO" (bug#4219).
1949 ;; So we try and make sure that the string we return is all made up
1950 ;; of text from the completions rather than part from the
1951 ;; completions and part from the input.
1952 ;; FIXME: This reduces the problems of inconsistent capitalization
1953 ;; but it doesn't fully fix it: we may still end up completing
1954 ;; "fo-ba" to "foo-BAR" or "FOO-bar" when completing against
1955 ;; '("foo-barr" "FOO-BARD").
1956 (cond
1957 ((null (cdr strs)) (list (car strs)))
1959 (let ((re (completion-pcm--pattern->regex pattern 'group))
1960 (ccs ())) ;Chopped completions.
1962 ;; First chop each string into the parts corresponding to each
1963 ;; non-constant element of `pattern', using regexp-matching.
1964 (let ((case-fold-search completion-ignore-case))
1965 (dolist (str strs)
1966 (unless (string-match re str)
1967 (error "Internal error: %s doesn't match %s" str re))
1968 (let ((chopped ())
1969 (last 0)
1970 (i 1)
1971 next)
1972 (while (setq next (match-end i))
1973 (push (substring str last next) chopped)
1974 (setq last next)
1975 (setq i (1+ i)))
1976 ;; Add the text corresponding to the implicit trailing `any'.
1977 (push (substring str last) chopped)
1978 (push (nreverse chopped) ccs))))
1980 ;; Then for each of those non-constant elements, extract the
1981 ;; commonality between them.
1982 (let ((res ())
1983 (fixed ""))
1984 ;; Make the implicit trailing `any' explicit.
1985 (dolist (elem (append pattern '(any)))
1986 (if (stringp elem)
1987 (setq fixed (concat fixed elem))
1988 (let ((comps ()))
1989 (dolist (cc (prog1 ccs (setq ccs nil)))
1990 (push (car cc) comps)
1991 (push (cdr cc) ccs))
1992 ;; Might improve the likelihood to avoid choosing
1993 ;; different capitalizations in different parts.
1994 ;; In practice, it doesn't seem to make any difference.
1995 (setq ccs (nreverse ccs))
1996 (let* ((prefix (try-completion fixed comps))
1997 (unique (or (and (eq prefix t) (setq prefix fixed))
1998 (eq t (try-completion prefix comps)))))
1999 (unless (equal prefix "") (push prefix res))
2000 ;; If there's only one completion, `elem' is not useful
2001 ;; any more: it can only match the empty string.
2002 ;; FIXME: in some cases, it may be necessary to turn an
2003 ;; `any' into a `star' because the surrounding context has
2004 ;; changed such that string->pattern wouldn't add an `any'
2005 ;; here any more.
2006 (unless unique (push elem res))
2007 (setq fixed "")))))
2008 ;; We return it in reverse order.
2009 res)))))
2011 (defun completion-pcm--pattern->string (pattern)
2012 (mapconcat (lambda (x) (cond
2013 ((stringp x) x)
2014 ((eq x 'star) "*")
2015 ((eq x 'any) "")
2016 ((eq x 'point) "")))
2017 pattern
2018 ""))
2020 ;; We want to provide the functionality of `try', but we use `all'
2021 ;; and then merge it. In most cases, this works perfectly, but
2022 ;; if the completion table doesn't consider the same completions in
2023 ;; `try' as in `all', then we have a problem. The most common such
2024 ;; case is for filename completion where completion-ignored-extensions
2025 ;; is only obeyed by the `try' code. We paper over the difference
2026 ;; here. Note that it is not quite right either: if the completion
2027 ;; table uses completion-table-in-turn, this filtering may take place
2028 ;; too late to correctly fallback from the first to the
2029 ;; second alternative.
2030 (defun completion-pcm--filename-try-filter (all)
2031 "Filter to adjust `all' file completion to the behavior of `try'."
2032 (when all
2033 (let ((try ())
2034 (re (concat "\\(?:\\`\\.\\.?/\\|"
2035 (regexp-opt completion-ignored-extensions)
2036 "\\)\\'")))
2037 (dolist (f all)
2038 (unless (string-match-p re f) (push f try)))
2039 (or try all))))
2042 (defun completion-pcm--merge-try (pattern all prefix suffix)
2043 (cond
2044 ((not (consp all)) all)
2045 ((and (not (consp (cdr all))) ;Only one completion.
2046 ;; Ignore completion-ignore-case here.
2047 (equal (completion-pcm--pattern->string pattern) (car all)))
2050 (let* ((mergedpat (completion-pcm--merge-completions all pattern))
2051 ;; `mergedpat' is in reverse order. Place new point (by
2052 ;; order of preference) either at the old point, or at
2053 ;; the last place where there's something to choose, or
2054 ;; at the very end.
2055 (pointpat (or (memq 'point mergedpat)
2056 (memq 'any mergedpat)
2057 (memq 'star mergedpat)
2058 mergedpat))
2059 ;; New pos from the start.
2060 (newpos (length (completion-pcm--pattern->string pointpat)))
2061 ;; Do it afterwards because it changes `pointpat' by sideeffect.
2062 (merged (completion-pcm--pattern->string (nreverse mergedpat))))
2064 (setq suffix (completion--merge-suffix merged newpos suffix))
2065 (cons (concat prefix merged suffix) (+ newpos (length prefix)))))))
2067 (defun completion-pcm-try-completion (string table pred point)
2068 (destructuring-bind (pattern all prefix suffix)
2069 (completion-pcm--find-all-completions
2070 string table pred point
2071 (if minibuffer-completing-file-name
2072 'completion-pcm--filename-try-filter))
2073 (completion-pcm--merge-try pattern all prefix suffix)))
2075 ;;; Substring completion
2076 ;; Mostly derived from the code of `basic' completion.
2078 (defun completion-substring--all-completions (string table pred point)
2079 (let* ((beforepoint (substring string 0 point))
2080 (afterpoint (substring string point))
2081 (bounds (completion-boundaries beforepoint table pred afterpoint))
2082 (suffix (substring afterpoint (cdr bounds)))
2083 (prefix (substring beforepoint 0 (car bounds)))
2084 (basic-pattern (completion-basic--pattern
2085 beforepoint afterpoint bounds))
2086 (pattern (if (not (stringp (car basic-pattern)))
2087 basic-pattern
2088 (cons 'any basic-pattern)))
2089 (all (completion-pcm--all-completions prefix pattern table pred)))
2090 (list all pattern prefix suffix (car bounds))))
2092 (defun completion-substring-try-completion (string table pred point)
2093 (destructuring-bind (all pattern prefix suffix carbounds)
2094 (completion-substring--all-completions string table pred point)
2095 (if minibuffer-completing-file-name
2096 (setq all (completion-pcm--filename-try-filter all)))
2097 (completion-pcm--merge-try pattern all prefix suffix)))
2099 (defun completion-substring-all-completions (string table pred point)
2100 (destructuring-bind (all pattern prefix suffix carbounds)
2101 (completion-substring--all-completions string table pred point)
2102 (when all
2103 (nconc (completion-pcm--hilit-commonality pattern all)
2104 (length prefix)))))
2106 ;; Initials completion
2107 ;; Complete /ums to /usr/monnier/src or lch to list-command-history.
2109 (defun completion-initials-expand (str table pred)
2110 (let ((bounds (completion-boundaries str table pred "")))
2111 (unless (or (zerop (length str))
2112 ;; Only check within the boundaries, since the
2113 ;; boundary char (e.g. /) might be in delim-regexp.
2114 (string-match completion-pcm--delim-wild-regex str
2115 (car bounds)))
2116 (if (zerop (car bounds))
2117 (mapconcat 'string str "-")
2118 ;; If there's a boundary, it's trickier. The main use-case
2119 ;; we consider here is file-name completion. We'd like
2120 ;; to expand ~/eee to ~/e/e/e and /eee to /e/e/e.
2121 ;; But at the same time, we don't want /usr/share/ae to expand
2122 ;; to /usr/share/a/e just because we mistyped "ae" for "ar",
2123 ;; so we probably don't want initials to touch anything that
2124 ;; looks like /usr/share/foo. As a heuristic, we just check that
2125 ;; the text before the boundary char is at most 1 char.
2126 ;; This allows both ~/eee and /eee and not much more.
2127 ;; FIXME: It sadly also disallows the use of ~/eee when that's
2128 ;; embedded within something else (e.g. "(~/eee" in Info node
2129 ;; completion or "ancestor:/eee" in bzr-revision completion).
2130 (when (< (car bounds) 3)
2131 (let ((sep (substring str (1- (car bounds)) (car bounds))))
2132 ;; FIXME: the above string-match checks the whole string, whereas
2133 ;; we end up only caring about the after-boundary part.
2134 (concat (substring str 0 (car bounds))
2135 (mapconcat 'string (substring str (car bounds)) sep))))))))
2137 (defun completion-initials-all-completions (string table pred point)
2138 (let ((newstr (completion-initials-expand string table pred)))
2139 (when newstr
2140 (completion-pcm-all-completions newstr table pred (length newstr)))))
2142 (defun completion-initials-try-completion (string table pred point)
2143 (let ((newstr (completion-initials-expand string table pred)))
2144 (when newstr
2145 (completion-pcm-try-completion newstr table pred (length newstr)))))
2148 ;; Miscellaneous
2150 (defun minibuffer-insert-file-name-at-point ()
2151 "Get a file name at point in original buffer and insert it to minibuffer."
2152 (interactive)
2153 (let ((file-name-at-point
2154 (with-current-buffer (window-buffer (minibuffer-selected-window))
2155 (run-hook-with-args-until-success 'file-name-at-point-functions))))
2156 (when file-name-at-point
2157 (insert file-name-at-point))))
2159 (provide 'minibuffer)
2161 ;; arch-tag: ef8a0a15-1080-4790-a754-04017c02f08f
2162 ;;; minibuffer.el ends here