* lisp/minibuffer.el (completion--replace): Better preserve markers.
[emacs.git] / lisp / minibuffer.el
blob9a47702042124624444a756a8bc192b505980ae3
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 I.e. when completing \"foo_bar\" (where _ is the position of point),
386 it will consider all completions candidates matching the glob
387 pattern \"foobar*\".")
388 (emacs22
389 completion-emacs22-try-completion completion-emacs22-all-completions
390 "Prefix completion that only operates on the text before point.
391 I.e. when completing \"foo_bar\" (where _ is the position of point),
392 it will consider all completions candidates matching the glob
393 pattern \"foo*\" and will add back \"bar\" to the end of it.")
394 (basic
395 completion-basic-try-completion completion-basic-all-completions
396 "Completion of the prefix before point and the suffix after point.
397 I.e. when completing \"foo_bar\" (where _ is the position of point),
398 it will consider all completions candidates matching the glob
399 pattern \"foo*bar*\".")
400 (partial-completion
401 completion-pcm-try-completion completion-pcm-all-completions
402 "Completion of multiple words, each one taken as a prefix.
403 I.e. when completing \"l-co_h\" (where _ is the position of point),
404 it will consider all completions candidates matching the glob
405 pattern \"l*-co*h*\".
406 Furthermore, for completions that are done step by step in subfields,
407 the method is applied to all the preceding fields that do not yet match.
408 E.g. C-x C-f /u/mo/s TAB could complete to /usr/monnier/src.
409 Additionally the user can use the char \"*\" as a glob pattern.")
410 (initials
411 completion-initials-try-completion completion-initials-all-completions
412 "Completion of acronyms and initialisms.
413 E.g. can complete M-x lch to list-command-history
414 and C-x C-f ~/sew to ~/src/emacs/work."))
415 "List of available completion styles.
416 Each element has the form (NAME TRY-COMPLETION ALL-COMPLETIONS DOC):
417 where NAME is the name that should be used in `completion-styles',
418 TRY-COMPLETION is the function that does the completion (it should
419 follow the same calling convention as `completion-try-completion'),
420 ALL-COMPLETIONS is the function that lists the completions (it should
421 follow the calling convention of `completion-all-completions'),
422 and DOC describes the way this style of completion works.")
424 (defcustom completion-styles
425 ;; First, use `basic' because prefix completion has been the standard
426 ;; for "ever" and works well in most cases, so using it first
427 ;; ensures that we obey previous behavior in most cases.
428 '(basic
429 ;; Then use `partial-completion' because it has proven to
430 ;; be a very convenient extension.
431 partial-completion
432 ;; Finally use `emacs22' so as to maintain (in many/most cases)
433 ;; the previous behavior that when completing "foobar" with point
434 ;; between "foo" and "bar" the completion try to complete "foo"
435 ;; and simply add "bar" to the end of the result.
436 emacs22)
437 "List of completion styles to use.
438 The available styles are listed in `completion-styles-alist'."
439 :type `(repeat (choice ,@(mapcar (lambda (x) (list 'const (car x)))
440 completion-styles-alist)))
441 :group 'minibuffer
442 :version "23.1")
444 (defun completion-try-completion (string table pred point)
445 "Try to complete STRING using completion table TABLE.
446 Only the elements of table that satisfy predicate PRED are considered.
447 POINT is the position of point within STRING.
448 The return value can be either nil to indicate that there is no completion,
449 t to indicate that STRING is the only possible completion,
450 or a pair (STRING . NEWPOINT) of the completed result string together with
451 a new position for point."
452 (completion--some (lambda (style)
453 (funcall (nth 1 (assq style completion-styles-alist))
454 string table pred point))
455 completion-styles))
457 (defun completion-all-completions (string table pred point)
458 "List the possible completions of STRING in completion table TABLE.
459 Only the elements of table that satisfy predicate PRED are considered.
460 POINT is the position of point within STRING.
461 The return value is a list of completions and may contain the base-size
462 in the last `cdr'."
463 ;; FIXME: We need to additionally return the info needed for the
464 ;; second part of completion-base-position.
465 (completion--some (lambda (style)
466 (funcall (nth 2 (assq style completion-styles-alist))
467 string table pred point))
468 completion-styles))
470 (defun minibuffer--bitset (modified completions exact)
471 (logior (if modified 4 0)
472 (if completions 2 0)
473 (if exact 1 0)))
475 (defun completion--replace (beg end newtext)
476 "Replace the buffer text between BEG and END with NEWTEXT.
477 Moves point to the end of the new text."
478 ;; Maybe this should be in subr.el.
479 ;; You'd think this is trivial to do, but details matter if you want
480 ;; to keep markers "at the right place" and be robust in the face of
481 ;; after-change-functions that may themselves modify the buffer.
482 (let ((prefix-len 0))
483 ;; Don't touch markers in the shared prefix (if any).
484 (while (and (< prefix-len (length newtext))
485 (< (+ beg prefix-len) end)
486 (eq (char-after (+ beg prefix-len))
487 (aref newtext prefix-len)))
488 (setq prefix-len (1+ prefix-len)))
489 (unless (zerop prefix-len)
490 (setq beg (+ beg prefix-len))
491 (setq newtext (substring newtext prefix-len))))
492 (let ((suffix-len 0))
493 ;; Don't touch markers in the shared suffix (if any).
494 (while (and (< suffix-len (length newtext))
495 (< beg (- end suffix-len))
496 (eq (char-before (- end suffix-len))
497 (aref newtext (- (length newtext) suffix-len 1))))
498 (setq suffix-len (1+ suffix-len)))
499 (unless (zerop suffix-len)
500 (setq end (- end suffix-len))
501 (setq newtext (substring newtext 0 (- suffix-len)))))
502 (goto-char beg)
503 (insert newtext)
504 (delete-region (point) (+ (point) (- end beg))))
506 (defun completion--do-completion (&optional try-completion-function)
507 "Do the completion and return a summary of what happened.
508 M = completion was performed, the text was Modified.
509 C = there were available Completions.
510 E = after completion we now have an Exact match.
513 000 0 no possible completion
514 001 1 was already an exact and unique completion
515 010 2 no completion happened
516 011 3 was already an exact completion
517 100 4 ??? impossible
518 101 5 ??? impossible
519 110 6 some completion happened
520 111 7 completed to an exact completion"
521 (let* ((beg (field-beginning))
522 (end (field-end))
523 (string (buffer-substring beg end))
524 (comp (funcall (or try-completion-function
525 'completion-try-completion)
526 string
527 minibuffer-completion-table
528 minibuffer-completion-predicate
529 (- (point) beg))))
530 (cond
531 ((null comp)
532 (minibuffer-hide-completions)
533 (ding) (minibuffer-message "No match") (minibuffer--bitset nil nil nil))
534 ((eq t comp)
535 (minibuffer-hide-completions)
536 (goto-char (field-end))
537 (minibuffer--bitset nil nil t)) ;Exact and unique match.
539 ;; `completed' should be t if some completion was done, which doesn't
540 ;; include simply changing the case of the entered string. However,
541 ;; for appearance, the string is rewritten if the case changes.
542 (let* ((comp-pos (cdr comp))
543 (completion (car comp))
544 (completed (not (eq t (compare-strings completion nil nil
545 string nil nil t))))
546 (unchanged (eq t (compare-strings completion nil nil
547 string nil nil nil))))
548 (if unchanged
549 (goto-char end)
550 ;; Insert in minibuffer the chars we got.
551 (completion--replace beg end completion))
552 ;; Move point to its completion-mandated destination.
553 (forward-char (- comp-pos (length completion)))
555 (if (not (or unchanged completed))
556 ;; The case of the string changed, but that's all. We're not sure
557 ;; whether this is a unique completion or not, so try again using
558 ;; the real case (this shouldn't recurse again, because the next
559 ;; time try-completion will return either t or the exact string).
560 (completion--do-completion try-completion-function)
562 ;; It did find a match. Do we match some possibility exactly now?
563 (let ((exact (test-completion completion
564 minibuffer-completion-table
565 minibuffer-completion-predicate)))
566 (if completed
567 ;; We could also decide to refresh the completions,
568 ;; if they're displayed (and assuming there are
569 ;; completions left).
570 (minibuffer-hide-completions)
571 ;; Show the completion table, if requested.
572 (cond
573 ((not exact)
574 (if (case completion-auto-help
575 (lazy (eq this-command last-command))
576 (t completion-auto-help))
577 (minibuffer-completion-help)
578 (minibuffer-message "Next char not unique")))
579 ;; If the last exact completion and this one were the same, it
580 ;; means we've already given a "Next char not unique" message
581 ;; and the user's hit TAB again, so now we give him help.
582 ((eq this-command last-command)
583 (if completion-auto-help (minibuffer-completion-help)))))
585 (minibuffer--bitset completed t exact))))))))
587 (defun minibuffer-complete ()
588 "Complete the minibuffer contents as far as possible.
589 Return nil if there is no valid completion, else t.
590 If no characters can be completed, display a list of possible completions.
591 If you repeat this command after it displayed such a list,
592 scroll the window of possible completions."
593 (interactive)
594 ;; If the previous command was not this,
595 ;; mark the completion buffer obsolete.
596 (unless (eq this-command last-command)
597 (setq minibuffer-scroll-window nil))
599 (let ((window minibuffer-scroll-window))
600 ;; If there's a fresh completion window with a live buffer,
601 ;; and this command is repeated, scroll that window.
602 (if (window-live-p window)
603 (with-current-buffer (window-buffer window)
604 (if (pos-visible-in-window-p (point-max) window)
605 ;; If end is in view, scroll up to the beginning.
606 (set-window-start window (point-min) nil)
607 ;; Else scroll down one screen.
608 (scroll-other-window))
609 nil)
611 (case (completion--do-completion)
612 (#b000 nil)
613 (#b001 (minibuffer-message "Sole completion")
615 (#b011 (minibuffer-message "Complete, but not unique")
617 (t t)))))
619 (defvar completion-all-sorted-completions nil)
620 (make-variable-buffer-local 'completion-all-sorted-completions)
622 (defun completion--flush-all-sorted-completions (&rest ignore)
623 (setq completion-all-sorted-completions nil))
625 (defun completion-all-sorted-completions ()
626 (or completion-all-sorted-completions
627 (let* ((start (field-beginning))
628 (end (field-end))
629 (all (completion-all-completions (buffer-substring start end)
630 minibuffer-completion-table
631 minibuffer-completion-predicate
632 (- (point) start)))
633 (last (last all))
634 (base-size (or (cdr last) 0)))
635 (when last
636 (setcdr last nil)
637 ;; Prefer shorter completions.
638 (setq all (sort all (lambda (c1 c2) (< (length c1) (length c2)))))
639 ;; Prefer recently used completions.
640 (let ((hist (symbol-value minibuffer-history-variable)))
641 (setq all (sort all (lambda (c1 c2)
642 (> (length (member c1 hist))
643 (length (member c2 hist)))))))
644 ;; Cache the result. This is not just for speed, but also so that
645 ;; repeated calls to minibuffer-force-complete can cycle through
646 ;; all possibilities.
647 (add-hook 'after-change-functions
648 'completion--flush-all-sorted-completions nil t)
649 (setq completion-all-sorted-completions
650 (nconc all base-size))))))
652 (defun minibuffer-force-complete ()
653 "Complete the minibuffer to an exact match.
654 Repeated uses step through the possible completions."
655 (interactive)
656 ;; FIXME: Need to deal with the extra-size issue here as well.
657 ;; FIXME: ~/src/emacs/t<M-TAB>/lisp/minibuffer.el completes to
658 ;; ~/src/emacs/trunk/ and throws away lisp/minibuffer.el.
659 (let* ((start (field-beginning))
660 (end (field-end))
661 (all (completion-all-sorted-completions)))
662 (if (not (consp all))
663 (minibuffer-message (if all "No more completions" "No completions"))
664 (goto-char end)
665 (insert (car all))
666 (delete-region (+ start (cdr (last all))) end)
667 ;; If completing file names, (car all) may be a directory, so we'd now
668 ;; have a new set of possible completions and might want to reset
669 ;; completion-all-sorted-completions to nil, but we prefer not to,
670 ;; so that repeated calls minibuffer-force-complete still cycle
671 ;; through the previous possible completions.
672 (let ((last (last all)))
673 (setcdr last (cons (car all) (cdr last)))
674 (setq completion-all-sorted-completions (cdr all))))))
676 (defvar minibuffer-confirm-exit-commands
677 '(minibuffer-complete minibuffer-complete-word PC-complete PC-complete-word)
678 "A list of commands which cause an immediately following
679 `minibuffer-complete-and-exit' to ask for extra confirmation.")
681 (defun minibuffer-complete-and-exit ()
682 "Exit if the minibuffer contains a valid completion.
683 Otherwise, try to complete the minibuffer contents. If
684 completion leads to a valid completion, a repetition of this
685 command will exit.
687 If `minibuffer-completion-confirm' is `confirm', do not try to
688 complete; instead, ask for confirmation and accept any input if
689 confirmed.
690 If `minibuffer-completion-confirm' is `confirm-after-completion',
691 do not try to complete; instead, ask for confirmation if the
692 preceding minibuffer command was a member of
693 `minibuffer-confirm-exit-commands', and accept the input
694 otherwise."
695 (interactive)
696 (let ((beg (field-beginning))
697 (end (field-end)))
698 (cond
699 ;; Allow user to specify null string
700 ((= beg end) (exit-minibuffer))
701 ((test-completion (buffer-substring beg end)
702 minibuffer-completion-table
703 minibuffer-completion-predicate)
704 ;; FIXME: completion-ignore-case has various slightly
705 ;; incompatible meanings. E.g. it can reflect whether the user
706 ;; wants completion to pay attention to case, or whether the
707 ;; string will be used in a context where case is significant.
708 ;; E.g. usually try-completion should obey the first, whereas
709 ;; test-completion should obey the second.
710 (when completion-ignore-case
711 ;; Fixup case of the field, if necessary.
712 (let* ((string (buffer-substring beg end))
713 (compl (try-completion
714 string
715 minibuffer-completion-table
716 minibuffer-completion-predicate)))
717 (when (and (stringp compl) (not (equal string compl))
718 ;; If it weren't for this piece of paranoia, I'd replace
719 ;; the whole thing with a call to do-completion.
720 ;; This is important, e.g. when the current minibuffer's
721 ;; content is a directory which only contains a single
722 ;; file, so `try-completion' actually completes to
723 ;; that file.
724 (= (length string) (length compl)))
725 (goto-char end)
726 (insert compl)
727 (delete-region beg end))))
728 (exit-minibuffer))
730 ((memq minibuffer-completion-confirm '(confirm confirm-after-completion))
731 ;; The user is permitted to exit with an input that's rejected
732 ;; by test-completion, after confirming her choice.
733 (if (or (eq last-command this-command)
734 ;; For `confirm-after-completion' we only ask for confirmation
735 ;; if trying to exit immediately after typing TAB (this
736 ;; catches most minibuffer typos).
737 (and (eq minibuffer-completion-confirm 'confirm-after-completion)
738 (not (memq last-command minibuffer-confirm-exit-commands))))
739 (exit-minibuffer)
740 (minibuffer-message "Confirm")
741 nil))
744 ;; Call do-completion, but ignore errors.
745 (case (condition-case nil
746 (completion--do-completion)
747 (error 1))
748 ((#b001 #b011) (exit-minibuffer))
749 (#b111 (if (not minibuffer-completion-confirm)
750 (exit-minibuffer)
751 (minibuffer-message "Confirm")
752 nil))
753 (t nil))))))
755 (defun completion--try-word-completion (string table predicate point)
756 (let ((comp (completion-try-completion string table predicate point)))
757 (if (not (consp comp))
758 comp
760 ;; If completion finds next char not unique,
761 ;; consider adding a space or a hyphen.
762 (when (= (length string) (length (car comp)))
763 ;; Mark the added char with the `completion-word' property, so it
764 ;; can be handled specially by completion styles such as
765 ;; partial-completion.
766 ;; We used to remove `partial-completion' from completion-styles
767 ;; instead, but it was too blunt, leading to situations where SPC
768 ;; was the only insertable char at point but minibuffer-complete-word
769 ;; refused inserting it.
770 (let ((exts (mapcar (lambda (str) (propertize str 'completion-try-word t))
771 '(" " "-")))
772 (before (substring string 0 point))
773 (after (substring string point))
774 tem)
775 (while (and exts (not (consp tem)))
776 (setq tem (completion-try-completion
777 (concat before (pop exts) after)
778 table predicate (1+ point))))
779 (if (consp tem) (setq comp tem))))
781 ;; Completing a single word is actually more difficult than completing
782 ;; as much as possible, because we first have to find the "current
783 ;; position" in `completion' in order to find the end of the word
784 ;; we're completing. Normally, `string' is a prefix of `completion',
785 ;; which makes it trivial to find the position, but with fancier
786 ;; completion (plus env-var expansion, ...) `completion' might not
787 ;; look anything like `string' at all.
788 (let* ((comppoint (cdr comp))
789 (completion (car comp))
790 (before (substring string 0 point))
791 (combined (concat before "\n" completion)))
792 ;; Find in completion the longest text that was right before point.
793 (when (string-match "\\(.+\\)\n.*?\\1" combined)
794 (let* ((prefix (match-string 1 before))
795 ;; We used non-greedy match to make `rem' as long as possible.
796 (rem (substring combined (match-end 0)))
797 ;; Find in the remainder of completion the longest text
798 ;; that was right after point.
799 (after (substring string point))
800 (suffix (if (string-match "\\`\\(.+\\).*\n.*\\1"
801 (concat after "\n" rem))
802 (match-string 1 after))))
803 ;; The general idea is to try and guess what text was inserted
804 ;; at point by the completion. Problem is: if we guess wrong,
805 ;; we may end up treating as "added by completion" text that was
806 ;; actually painfully typed by the user. So if we then cut
807 ;; after the first word, we may throw away things the
808 ;; user wrote. So let's try to be as conservative as possible:
809 ;; only cut after the first word, if we're reasonably sure that
810 ;; our guess is correct.
811 ;; Note: a quick survey on emacs-devel seemed to indicate that
812 ;; nobody actually cares about the "word-at-a-time" feature of
813 ;; minibuffer-complete-word, whose real raison-d'être is that it
814 ;; tries to add "-" or " ". One more reason to only cut after
815 ;; the first word, if we're really sure we're right.
816 (when (and (or suffix (zerop (length after)))
817 (string-match (concat
818 ;; Make submatch 1 as small as possible
819 ;; to reduce the risk of cutting
820 ;; valuable text.
821 ".*" (regexp-quote prefix) "\\(.*?\\)"
822 (if suffix (regexp-quote suffix) "\\'"))
823 completion)
824 ;; The new point in `completion' should also be just
825 ;; before the suffix, otherwise something more complex
826 ;; is going on, and we're not sure where we are.
827 (eq (match-end 1) comppoint)
828 ;; (match-beginning 1)..comppoint is now the stretch
829 ;; of text in `completion' that was completed at point.
830 (string-match "\\W" completion (match-beginning 1))
831 ;; Is there really something to cut?
832 (> comppoint (match-end 0)))
833 ;; Cut after the first word.
834 (let ((cutpos (match-end 0)))
835 (setq completion (concat (substring completion 0 cutpos)
836 (substring completion comppoint)))
837 (setq comppoint cutpos)))))
839 (cons completion comppoint)))))
842 (defun minibuffer-complete-word ()
843 "Complete the minibuffer contents at most a single word.
844 After one word is completed as much as possible, a space or hyphen
845 is added, provided that matches some possible completion.
846 Return nil if there is no valid completion, else t."
847 (interactive)
848 (case (completion--do-completion 'completion--try-word-completion)
849 (#b000 nil)
850 (#b001 (minibuffer-message "Sole completion")
852 (#b011 (minibuffer-message "Complete, but not unique")
854 (t t)))
856 (defface completions-annotations '((t :inherit italic))
857 "Face to use for annotations in the *Completions* buffer.")
859 (defcustom completions-format nil
860 "Define the appearance and sorting of completions.
861 If the value is `vertical', display completions sorted vertically
862 in columns in the *Completions* buffer.
863 If the value is `horizontal' or nil, display completions sorted
864 horizontally in alphabetical order, rather than down the screen."
865 :type '(choice (const nil) (const horizontal) (const vertical))
866 :group 'minibuffer
867 :version "23.2")
869 (defun completion--insert-strings (strings)
870 "Insert a list of STRINGS into the current buffer.
871 Uses columns to keep the listing readable but compact.
872 It also eliminates runs of equal strings."
873 (when (consp strings)
874 (let* ((length (apply 'max
875 (mapcar (lambda (s)
876 (if (consp s)
877 (+ (string-width (car s))
878 (string-width (cadr s)))
879 (string-width s)))
880 strings)))
881 (window (get-buffer-window (current-buffer) 0))
882 (wwidth (if window (1- (window-width window)) 79))
883 (columns (min
884 ;; At least 2 columns; at least 2 spaces between columns.
885 (max 2 (/ wwidth (+ 2 length)))
886 ;; Don't allocate more columns than we can fill.
887 ;; Windows can't show less than 3 lines anyway.
888 (max 1 (/ (length strings) 2))))
889 (colwidth (/ wwidth columns))
890 (column 0)
891 (rows (/ (length strings) columns))
892 (row 0)
893 (laststring nil))
894 ;; The insertion should be "sensible" no matter what choices were made
895 ;; for the parameters above.
896 (dolist (str strings)
897 (unless (equal laststring str) ; Remove (consecutive) duplicates.
898 (setq laststring str)
899 (let ((length (if (consp str)
900 (+ (string-width (car str))
901 (string-width (cadr str)))
902 (string-width str))))
903 (cond
904 ((eq completions-format 'vertical)
905 ;; Vertical format
906 (when (> row rows)
907 (forward-line (- -1 rows))
908 (setq row 0 column (+ column colwidth)))
909 (when (> column 0)
910 (end-of-line)
911 (while (> (current-column) column)
912 (if (eobp)
913 (insert "\n")
914 (forward-line 1)
915 (end-of-line)))
916 (insert " \t")
917 (set-text-properties (- (point) 1) (point)
918 `(display (space :align-to ,column)))))
920 ;; Horizontal format
921 (unless (bolp)
922 (if (< wwidth (+ (max colwidth length) column))
923 ;; No space for `str' at point, move to next line.
924 (progn (insert "\n") (setq column 0))
925 (insert " \t")
926 ;; Leave the space unpropertized so that in the case we're
927 ;; already past the goal column, there is still
928 ;; a space displayed.
929 (set-text-properties (- (point) 1) (point)
930 ;; We can't just set tab-width, because
931 ;; completion-setup-function will kill all
932 ;; local variables :-(
933 `(display (space :align-to ,column)))
934 nil))))
935 (if (not (consp str))
936 (put-text-property (point) (progn (insert str) (point))
937 'mouse-face 'highlight)
938 (put-text-property (point) (progn (insert (car str)) (point))
939 'mouse-face 'highlight)
940 (add-text-properties (point) (progn (insert (cadr str)) (point))
941 '(mouse-face nil
942 face completions-annotations)))
943 (cond
944 ((eq completions-format 'vertical)
945 ;; Vertical format
946 (if (> column 0)
947 (forward-line)
948 (insert "\n"))
949 (setq row (1+ row)))
951 ;; Horizontal format
952 ;; Next column to align to.
953 (setq column (+ column
954 ;; Round up to a whole number of columns.
955 (* colwidth (ceiling length colwidth))))))))))))
957 (defvar completion-common-substring nil)
958 (make-obsolete-variable 'completion-common-substring nil "23.1")
960 (defvar completion-setup-hook nil
961 "Normal hook run at the end of setting up a completion list buffer.
962 When this hook is run, the current buffer is the one in which the
963 command to display the completion list buffer was run.
964 The completion list buffer is available as the value of `standard-output'.
965 See also `display-completion-list'.")
967 (defface completions-first-difference
968 '((t (:inherit bold)))
969 "Face put on the first uncommon character in completions in *Completions* buffer."
970 :group 'completion)
972 (defface completions-common-part
973 '((t (:inherit default)))
974 "Face put on the common prefix substring in completions in *Completions* buffer.
975 The idea of `completions-common-part' is that you can use it to
976 make the common parts less visible than normal, so that the rest
977 of the differing parts is, by contrast, slightly highlighted."
978 :group 'completion)
980 (defun completion-hilit-commonality (completions prefix-len base-size)
981 (when completions
982 (let ((com-str-len (- prefix-len (or base-size 0))))
983 (nconc
984 (mapcar
985 (lambda (elem)
986 (let ((str
987 ;; Don't modify the string itself, but a copy, since the
988 ;; the string may be read-only or used for other purposes.
989 ;; Furthermore, since `completions' may come from
990 ;; display-completion-list, `elem' may be a list.
991 (if (consp elem)
992 (car (setq elem (cons (copy-sequence (car elem))
993 (cdr elem))))
994 (setq elem (copy-sequence elem)))))
995 (put-text-property 0
996 ;; If completion-boundaries returns incorrect
997 ;; values, all-completions may return strings
998 ;; that don't contain the prefix.
999 (min com-str-len (length str))
1000 'font-lock-face 'completions-common-part
1001 str)
1002 (if (> (length str) com-str-len)
1003 (put-text-property com-str-len (1+ com-str-len)
1004 'font-lock-face 'completions-first-difference
1005 str)))
1006 elem)
1007 completions)
1008 base-size))))
1010 (defun display-completion-list (completions &optional common-substring)
1011 "Display the list of completions, COMPLETIONS, using `standard-output'.
1012 Each element may be just a symbol or string
1013 or may be a list of two strings to be printed as if concatenated.
1014 If it is a list of two strings, the first is the actual completion
1015 alternative, the second serves as annotation.
1016 `standard-output' must be a buffer.
1017 The actual completion alternatives, as inserted, are given `mouse-face'
1018 properties of `highlight'.
1019 At the end, this runs the normal hook `completion-setup-hook'.
1020 It can find the completion buffer in `standard-output'.
1022 The obsolete optional arg COMMON-SUBSTRING, if non-nil, should be a string
1023 specifying a common substring for adding the faces
1024 `completions-first-difference' and `completions-common-part' to
1025 the completions buffer."
1026 (if common-substring
1027 (setq completions (completion-hilit-commonality
1028 completions (length common-substring)
1029 ;; We don't know the base-size.
1030 nil)))
1031 (if (not (bufferp standard-output))
1032 ;; This *never* (ever) happens, so there's no point trying to be clever.
1033 (with-temp-buffer
1034 (let ((standard-output (current-buffer))
1035 (completion-setup-hook nil))
1036 (display-completion-list completions common-substring))
1037 (princ (buffer-string)))
1039 (with-current-buffer standard-output
1040 (goto-char (point-max))
1041 (if (null completions)
1042 (insert "There are no possible completions of what you have typed.")
1043 (insert "Possible completions are:\n")
1044 (completion--insert-strings completions))))
1046 ;; The hilit used to be applied via completion-setup-hook, so there
1047 ;; may still be some code that uses completion-common-substring.
1048 (with-no-warnings
1049 (let ((completion-common-substring common-substring))
1050 (run-hooks 'completion-setup-hook)))
1051 nil)
1053 (defvar completion-annotate-function
1055 ;; Note: there's a lot of scope as for when to add annotations and
1056 ;; what annotations to add. E.g. completing-help.el allowed adding
1057 ;; the first line of docstrings to M-x completion. But there's
1058 ;; a tension, since such annotations, while useful at times, can
1059 ;; actually drown the useful information.
1060 ;; So completion-annotate-function should be used parsimoniously, or
1061 ;; else only used upon a user's request (e.g. we could add a command
1062 ;; to completion-list-mode to add annotations to the current
1063 ;; completions).
1064 "Function to add annotations in the *Completions* buffer.
1065 The function takes a completion and should either return nil, or a string that
1066 will be displayed next to the completion. The function can access the
1067 completion table and predicates via `minibuffer-completion-table' and related
1068 variables.")
1070 (defun minibuffer-completion-help ()
1071 "Display a list of possible completions of the current minibuffer contents."
1072 (interactive)
1073 (message "Making completion list...")
1074 (let* ((start (field-beginning))
1075 (string (field-string))
1076 (completions (completion-all-completions
1077 string
1078 minibuffer-completion-table
1079 minibuffer-completion-predicate
1080 (- (point) (field-beginning)))))
1081 (message nil)
1082 (if (and completions
1083 (or (consp (cdr completions))
1084 (not (equal (car completions) string))))
1085 (let* ((last (last completions))
1086 (base-size (cdr last))
1087 ;; If the *Completions* buffer is shown in a new
1088 ;; window, mark it as softly-dedicated, so bury-buffer in
1089 ;; minibuffer-hide-completions will know whether to
1090 ;; delete the window or not.
1091 (display-buffer-mark-dedicated 'soft))
1092 (with-output-to-temp-buffer "*Completions*"
1093 ;; Remove the base-size tail because `sort' requires a properly
1094 ;; nil-terminated list.
1095 (when last (setcdr last nil))
1096 (setq completions (sort completions 'string-lessp))
1097 (when completion-annotate-function
1098 (setq completions
1099 (mapcar (lambda (s)
1100 (let ((ann
1101 (funcall completion-annotate-function s)))
1102 (if ann (list s ann) s)))
1103 completions)))
1104 (with-current-buffer standard-output
1105 (set (make-local-variable 'completion-base-position)
1106 ;; FIXME: We should provide the END part as well, but
1107 ;; currently completion-all-completions does not give
1108 ;; us the necessary information.
1109 (list (+ start base-size) nil)))
1110 (display-completion-list completions)))
1112 ;; If there are no completions, or if the current input is already the
1113 ;; only possible completion, then hide (previous&stale) completions.
1114 (minibuffer-hide-completions)
1115 (ding)
1116 (minibuffer-message
1117 (if completions "Sole completion" "No completions")))
1118 nil))
1120 (defun minibuffer-hide-completions ()
1121 "Get rid of an out-of-date *Completions* buffer."
1122 ;; FIXME: We could/should use minibuffer-scroll-window here, but it
1123 ;; can also point to the minibuffer-parent-window, so it's a bit tricky.
1124 (let ((win (get-buffer-window "*Completions*" 0)))
1125 (if win (with-selected-window win (bury-buffer)))))
1127 (defun exit-minibuffer ()
1128 "Terminate this minibuffer argument."
1129 (interactive)
1130 ;; If the command that uses this has made modifications in the minibuffer,
1131 ;; we don't want them to cause deactivation of the mark in the original
1132 ;; buffer.
1133 ;; A better solution would be to make deactivate-mark buffer-local
1134 ;; (or to turn it into a list of buffers, ...), but in the mean time,
1135 ;; this should do the trick in most cases.
1136 (setq deactivate-mark nil)
1137 (throw 'exit nil))
1139 (defun self-insert-and-exit ()
1140 "Terminate minibuffer input."
1141 (interactive)
1142 (if (characterp last-command-event)
1143 (call-interactively 'self-insert-command)
1144 (ding))
1145 (exit-minibuffer))
1147 (defvar completion-in-region-functions nil
1148 "Wrapper hook around `completion-in-region'.
1149 The functions on this special hook are called with 5 arguments:
1150 NEXT-FUN START END COLLECTION PREDICATE.
1151 NEXT-FUN is a function of four arguments (START END COLLECTION PREDICATE)
1152 that performs the default operation. The other four arguments are like
1153 the ones passed to `completion-in-region'. The functions on this hook
1154 are expected to perform completion on START..END using COLLECTION
1155 and PREDICATE, either by calling NEXT-FUN or by doing it themselves.")
1157 (defun completion-in-region (start end collection &optional predicate)
1158 "Complete the text between START and END using COLLECTION.
1159 Return nil if there is no valid completion, else t.
1160 Point needs to be somewhere between START and END."
1161 (assert (<= start (point)) (<= (point) end))
1162 ;; FIXME: undisplay the *Completions* buffer once the completion is done.
1163 (with-wrapper-hook
1164 completion-in-region-functions (start end collection predicate)
1165 (let ((minibuffer-completion-table collection)
1166 (minibuffer-completion-predicate predicate)
1167 (ol (make-overlay start end nil nil t)))
1168 (overlay-put ol 'field 'completion)
1169 (unwind-protect
1170 (call-interactively 'minibuffer-complete)
1171 (delete-overlay ol)))))
1173 (defvar completion-at-point-functions nil
1174 "Special hook to find the completion table for the thing at point.
1175 It is called without any argument and should return either nil,
1176 or a function of no argument to perform completion (discouraged),
1177 or a list of the form (START END COLLECTION &rest PROPS) where
1178 START and END delimit the entity to complete and should include point,
1179 COLLECTION is the completion table to use to complete it, and
1180 PROPS is a property list for additional information.
1181 Currently supported properties are:
1182 `:predicate' a predicate that completion candidates need to satisfy.
1183 `:annotation-function' the value to use for `completion-annotate-function'.")
1185 (defun completion-at-point ()
1186 "Complete the thing at point according to local mode.
1187 This runs the hook `completion-at-point-functions' until a member returns
1188 non-nil."
1189 (interactive)
1190 (let ((res (run-hook-with-args-until-success
1191 'completion-at-point-functions)))
1192 (cond
1193 ((functionp res) (funcall res))
1194 (res
1195 (let* ((plist (nthcdr 3 res))
1196 (start (nth 0 res))
1197 (end (nth 1 res))
1198 (completion-annotate-function
1199 (or (plist-get plist :annotation-function)
1200 completion-annotate-function)))
1201 (completion-in-region start end (nth 2 res)
1202 (plist-get plist :predicate)))))))
1204 ;;; Key bindings.
1206 (define-obsolete-variable-alias 'minibuffer-local-must-match-filename-map
1207 'minibuffer-local-filename-must-match-map "23.1")
1209 (let ((map minibuffer-local-map))
1210 (define-key map "\C-g" 'abort-recursive-edit)
1211 (define-key map "\r" 'exit-minibuffer)
1212 (define-key map "\n" 'exit-minibuffer))
1214 (let ((map minibuffer-local-completion-map))
1215 (define-key map "\t" 'minibuffer-complete)
1216 ;; M-TAB is already abused for many other purposes, so we should find
1217 ;; another binding for it.
1218 ;; (define-key map "\e\t" 'minibuffer-force-complete)
1219 (define-key map " " 'minibuffer-complete-word)
1220 (define-key map "?" 'minibuffer-completion-help))
1222 (let ((map minibuffer-local-must-match-map))
1223 (define-key map "\r" 'minibuffer-complete-and-exit)
1224 (define-key map "\n" 'minibuffer-complete-and-exit))
1226 (let ((map minibuffer-local-filename-completion-map))
1227 (define-key map " " nil))
1228 (let ((map minibuffer-local-filename-must-match-map))
1229 (define-key map " " nil))
1231 (let ((map minibuffer-local-ns-map))
1232 (define-key map " " 'exit-minibuffer)
1233 (define-key map "\t" 'exit-minibuffer)
1234 (define-key map "?" 'self-insert-and-exit))
1236 ;;; Completion tables.
1238 (defun minibuffer--double-dollars (str)
1239 (replace-regexp-in-string "\\$" "$$" str))
1241 (defun completion--make-envvar-table ()
1242 (mapcar (lambda (enventry)
1243 (substring enventry 0 (string-match-p "=" enventry)))
1244 process-environment))
1246 (defconst completion--embedded-envvar-re
1247 (concat "\\(?:^\\|[^$]\\(?:\\$\\$\\)*\\)"
1248 "$\\([[:alnum:]_]*\\|{\\([^}]*\\)\\)\\'"))
1250 (defun completion--embedded-envvar-table (string pred action)
1251 "Completion table for envvars embedded in a string.
1252 The envvar syntax (and escaping) rules followed by this table are the
1253 same as `substitute-in-file-name'."
1254 ;; We ignore `pred', because the predicates passed to us via
1255 ;; read-file-name-internal are not 100% correct and fail here:
1256 ;; e.g. we get predicates like file-directory-p there, whereas the filename
1257 ;; completed needs to be passed through substitute-in-file-name before it
1258 ;; can be passed to file-directory-p.
1259 (when (string-match completion--embedded-envvar-re string)
1260 (let* ((beg (or (match-beginning 2) (match-beginning 1)))
1261 (table (completion--make-envvar-table))
1262 (prefix (substring string 0 beg)))
1263 (cond
1264 ((eq action 'lambda)
1265 ;; This table is expected to be used in conjunction with some
1266 ;; other table that provides the "main" completion. Let the
1267 ;; other table handle the test-completion case.
1268 nil)
1269 ((eq (car-safe action) 'boundaries)
1270 ;; Only return boundaries if there's something to complete,
1271 ;; since otherwise when we're used in
1272 ;; completion-table-in-turn, we could return boundaries and
1273 ;; let some subsequent table return a list of completions.
1274 ;; FIXME: Maybe it should rather be fixed in
1275 ;; completion-table-in-turn instead, but it's difficult to
1276 ;; do it efficiently there.
1277 (when (try-completion (substring string beg) table nil)
1278 ;; Compute the boundaries of the subfield to which this
1279 ;; completion applies.
1280 (let ((suffix (cdr action)))
1281 (list* 'boundaries
1282 (or (match-beginning 2) (match-beginning 1))
1283 (when (string-match "[^[:alnum:]_]" suffix)
1284 (match-beginning 0))))))
1286 (if (eq (aref string (1- beg)) ?{)
1287 (setq table (apply-partially 'completion-table-with-terminator
1288 "}" table)))
1289 ;; Even if file-name completion is case-insensitive, we want
1290 ;; envvar completion to be case-sensitive.
1291 (let ((completion-ignore-case nil))
1292 (completion-table-with-context
1293 prefix table (substring string beg) nil action)))))))
1295 (defun completion-file-name-table (string pred action)
1296 "Completion table for file names."
1297 (ignore-errors
1298 (cond
1299 ((eq (car-safe action) 'boundaries)
1300 (let ((start (length (file-name-directory string)))
1301 (end (string-match-p "/" (cdr action))))
1302 (list* 'boundaries start end)))
1304 ((eq action 'lambda)
1305 (if (zerop (length string))
1306 nil ;Not sure why it's here, but it probably doesn't harm.
1307 (funcall (or pred 'file-exists-p) string)))
1310 (let* ((name (file-name-nondirectory string))
1311 (specdir (file-name-directory string))
1312 (realdir (or specdir default-directory)))
1314 (cond
1315 ((null action)
1316 (let ((comp (file-name-completion name realdir pred)))
1317 (if (stringp comp)
1318 (concat specdir comp)
1319 comp)))
1321 ((eq action t)
1322 (let ((all (file-name-all-completions name realdir)))
1324 ;; Check the predicate, if necessary.
1325 (unless (memq pred '(nil file-exists-p))
1326 (let ((comp ())
1327 (pred
1328 (if (eq pred 'file-directory-p)
1329 ;; Brute-force speed up for directory checking:
1330 ;; Discard strings which don't end in a slash.
1331 (lambda (s)
1332 (let ((len (length s)))
1333 (and (> len 0) (eq (aref s (1- len)) ?/))))
1334 ;; Must do it the hard (and slow) way.
1335 pred)))
1336 (let ((default-directory (expand-file-name realdir)))
1337 (dolist (tem all)
1338 (if (funcall pred tem) (push tem comp))))
1339 (setq all (nreverse comp))))
1341 all))))))))
1343 (defvar read-file-name-predicate nil
1344 "Current predicate used by `read-file-name-internal'.")
1345 (make-obsolete-variable 'read-file-name-predicate
1346 "use the regular PRED argument" "23.2")
1348 (defun completion--file-name-table (string pred action)
1349 "Internal subroutine for `read-file-name'. Do not call this.
1350 This is a completion table for file names, like `completion-file-name-table'
1351 except that it passes the file name through `substitute-in-file-name'."
1352 (cond
1353 ((eq (car-safe action) 'boundaries)
1354 ;; For the boundaries, we can't really delegate to
1355 ;; completion-file-name-table and then fix them up, because it
1356 ;; would require us to track the relationship between `str' and
1357 ;; `string', which is difficult. And in any case, if
1358 ;; substitute-in-file-name turns "fo-$TO-ba" into "fo-o/b-ba", there's
1359 ;; no way for us to return proper boundaries info, because the
1360 ;; boundary is not (yet) in `string'.
1361 ;; FIXME: Actually there is a way to return correct boundaries info,
1362 ;; at the condition of modifying the all-completions return accordingly.
1363 (let ((start (length (file-name-directory string)))
1364 (end (string-match-p "/" (cdr action))))
1365 (list* 'boundaries start end)))
1368 (let* ((default-directory
1369 (if (stringp pred)
1370 ;; It used to be that `pred' was abused to pass `dir'
1371 ;; as an argument.
1372 (prog1 (file-name-as-directory (expand-file-name pred))
1373 (setq pred nil))
1374 default-directory))
1375 (str (condition-case nil
1376 (substitute-in-file-name string)
1377 (error string)))
1378 (comp (completion-file-name-table
1379 str (or pred read-file-name-predicate) action)))
1381 (cond
1382 ((stringp comp)
1383 ;; Requote the $s before returning the completion.
1384 (minibuffer--double-dollars comp))
1385 ((and (null action) comp
1386 ;; Requote the $s before checking for changes.
1387 (setq str (minibuffer--double-dollars str))
1388 (not (string-equal string str)))
1389 ;; If there's no real completion, but substitute-in-file-name
1390 ;; changed the string, then return the new string.
1391 str)
1392 (t comp))))))
1394 (defalias 'read-file-name-internal
1395 (completion-table-in-turn 'completion--embedded-envvar-table
1396 'completion--file-name-table)
1397 "Internal subroutine for `read-file-name'. Do not call this.")
1399 (defvar read-file-name-function nil
1400 "If this is non-nil, `read-file-name' does its work by calling this function.")
1402 (defcustom read-file-name-completion-ignore-case
1403 (if (memq system-type '(ms-dos windows-nt darwin cygwin))
1404 t nil)
1405 "Non-nil means when reading a file name completion ignores case."
1406 :group 'minibuffer
1407 :type 'boolean
1408 :version "22.1")
1410 (defcustom insert-default-directory t
1411 "Non-nil means when reading a filename start with default dir in minibuffer.
1413 When the initial minibuffer contents show a name of a file or a directory,
1414 typing RETURN without editing the initial contents is equivalent to typing
1415 the default file name.
1417 If this variable is non-nil, the minibuffer contents are always
1418 initially non-empty, and typing RETURN without editing will fetch the
1419 default name, if one is provided. Note however that this default name
1420 is not necessarily the same as initial contents inserted in the minibuffer,
1421 if the initial contents is just the default directory.
1423 If this variable is nil, the minibuffer often starts out empty. In
1424 that case you may have to explicitly fetch the next history element to
1425 request the default name; typing RETURN without editing will leave
1426 the minibuffer empty.
1428 For some commands, exiting with an empty minibuffer has a special meaning,
1429 such as making the current buffer visit no file in the case of
1430 `set-visited-file-name'."
1431 :group 'minibuffer
1432 :type 'boolean)
1434 ;; Not always defined, but only called if next-read-file-uses-dialog-p says so.
1435 (declare-function x-file-dialog "xfns.c"
1436 (prompt dir &optional default-filename mustmatch only-dir-p))
1438 (defun read-file-name-defaults (&optional dir initial)
1439 (let ((default
1440 (cond
1441 ;; With non-nil `initial', use `dir' as the first default.
1442 ;; Essentially, this mean reversing the normal order of the
1443 ;; current directory name and the current file name, i.e.
1444 ;; 1. with normal file reading:
1445 ;; 1.1. initial input is the current directory
1446 ;; 1.2. the first default is the current file name
1447 ;; 2. with non-nil `initial' (e.g. for `find-alternate-file'):
1448 ;; 2.2. initial input is the current file name
1449 ;; 2.1. the first default is the current directory
1450 (initial (abbreviate-file-name dir))
1451 ;; In file buffers, try to get the current file name
1452 (buffer-file-name
1453 (abbreviate-file-name buffer-file-name))))
1454 (file-name-at-point
1455 (run-hook-with-args-until-success 'file-name-at-point-functions)))
1456 (when file-name-at-point
1457 (setq default (delete-dups
1458 (delete "" (delq nil (list file-name-at-point default))))))
1459 ;; Append new defaults to the end of existing `minibuffer-default'.
1460 (append
1461 (if (listp minibuffer-default) minibuffer-default (list minibuffer-default))
1462 (if (listp default) default (list default)))))
1464 (defun read-file-name (prompt &optional dir default-filename mustmatch initial predicate)
1465 "Read file name, prompting with PROMPT and completing in directory DIR.
1466 Value is not expanded---you must call `expand-file-name' yourself.
1467 Default name to DEFAULT-FILENAME if user exits the minibuffer with
1468 the same non-empty string that was inserted by this function.
1469 (If DEFAULT-FILENAME is omitted, the visited file name is used,
1470 except that if INITIAL is specified, that combined with DIR is used.
1471 If DEFAULT-FILENAME is a list of file names, the first file name is used.)
1472 If the user exits with an empty minibuffer, this function returns
1473 an empty string. (This can only happen if the user erased the
1474 pre-inserted contents or if `insert-default-directory' is nil.)
1476 Fourth arg MUSTMATCH can take the following values:
1477 - nil means that the user can exit with any input.
1478 - t means that the user is not allowed to exit unless
1479 the input is (or completes to) an existing file.
1480 - `confirm' means that the user can exit with any input, but she needs
1481 to confirm her choice if the input is not an existing file.
1482 - `confirm-after-completion' means that the user can exit with any
1483 input, but she needs to confirm her choice if she called
1484 `minibuffer-complete' right before `minibuffer-complete-and-exit'
1485 and the input is not an existing file.
1486 - anything else behaves like t except that typing RET does not exit if it
1487 does non-null completion.
1489 Fifth arg INITIAL specifies text to start with.
1491 If optional sixth arg PREDICATE is non-nil, possible completions and
1492 the resulting file name must satisfy (funcall PREDICATE NAME).
1493 DIR should be an absolute directory name. It defaults to the value of
1494 `default-directory'.
1496 If this command was invoked with the mouse, use a graphical file
1497 dialog if `use-dialog-box' is non-nil, and the window system or X
1498 toolkit in use provides a file dialog box, and DIR is not a
1499 remote file. For graphical file dialogs, any the special values
1500 of MUSTMATCH; `confirm' and `confirm-after-completion' are
1501 treated as equivalent to nil.
1503 See also `read-file-name-completion-ignore-case'
1504 and `read-file-name-function'."
1505 (unless dir (setq dir default-directory))
1506 (unless (file-name-absolute-p dir) (setq dir (expand-file-name dir)))
1507 (unless default-filename
1508 (setq default-filename (if initial (expand-file-name initial dir)
1509 buffer-file-name)))
1510 ;; If dir starts with user's homedir, change that to ~.
1511 (setq dir (abbreviate-file-name dir))
1512 ;; Likewise for default-filename.
1513 (if default-filename
1514 (setq default-filename
1515 (if (consp default-filename)
1516 (mapcar 'abbreviate-file-name default-filename)
1517 (abbreviate-file-name default-filename))))
1518 (let ((insdef (cond
1519 ((and insert-default-directory (stringp dir))
1520 (if initial
1521 (cons (minibuffer--double-dollars (concat dir initial))
1522 (length (minibuffer--double-dollars dir)))
1523 (minibuffer--double-dollars dir)))
1524 (initial (cons (minibuffer--double-dollars initial) 0)))))
1526 (if read-file-name-function
1527 (funcall read-file-name-function
1528 prompt dir default-filename mustmatch initial predicate)
1529 (let ((completion-ignore-case read-file-name-completion-ignore-case)
1530 (minibuffer-completing-file-name t)
1531 (pred (or predicate 'file-exists-p))
1532 (add-to-history nil))
1534 (let* ((val
1535 (if (or (not (next-read-file-uses-dialog-p))
1536 ;; Graphical file dialogs can't handle remote
1537 ;; files (Bug#99).
1538 (file-remote-p dir))
1539 ;; We used to pass `dir' to `read-file-name-internal' by
1540 ;; abusing the `predicate' argument. It's better to
1541 ;; just use `default-directory', but in order to avoid
1542 ;; changing `default-directory' in the current buffer,
1543 ;; we don't let-bind it.
1544 (lexical-let ((dir (file-name-as-directory
1545 (expand-file-name dir))))
1546 (minibuffer-with-setup-hook
1547 (lambda ()
1548 (setq default-directory dir)
1549 ;; When the first default in `minibuffer-default'
1550 ;; duplicates initial input `insdef',
1551 ;; reset `minibuffer-default' to nil.
1552 (when (equal (or (car-safe insdef) insdef)
1553 (or (car-safe minibuffer-default)
1554 minibuffer-default))
1555 (setq minibuffer-default
1556 (cdr-safe minibuffer-default)))
1557 ;; On the first request on `M-n' fill
1558 ;; `minibuffer-default' with a list of defaults
1559 ;; relevant for file-name reading.
1560 (set (make-local-variable 'minibuffer-default-add-function)
1561 (lambda ()
1562 (with-current-buffer
1563 (window-buffer (minibuffer-selected-window))
1564 (read-file-name-defaults dir initial)))))
1565 (completing-read prompt 'read-file-name-internal
1566 pred mustmatch insdef
1567 'file-name-history default-filename)))
1568 ;; If DEFAULT-FILENAME not supplied and DIR contains
1569 ;; a file name, split it.
1570 (let ((file (file-name-nondirectory dir))
1571 ;; When using a dialog, revert to nil and non-nil
1572 ;; interpretation of mustmatch. confirm options
1573 ;; need to be interpreted as nil, otherwise
1574 ;; it is impossible to create new files using
1575 ;; dialogs with the default settings.
1576 (dialog-mustmatch
1577 (not (memq mustmatch
1578 '(nil confirm confirm-after-completion)))))
1579 (when (and (not default-filename)
1580 (not (zerop (length file))))
1581 (setq default-filename file)
1582 (setq dir (file-name-directory dir)))
1583 (when default-filename
1584 (setq default-filename
1585 (expand-file-name (if (consp default-filename)
1586 (car default-filename)
1587 default-filename)
1588 dir)))
1589 (setq add-to-history t)
1590 (x-file-dialog prompt dir default-filename
1591 dialog-mustmatch
1592 (eq predicate 'file-directory-p)))))
1594 (replace-in-history (eq (car-safe file-name-history) val)))
1595 ;; If completing-read returned the inserted default string itself
1596 ;; (rather than a new string with the same contents),
1597 ;; it has to mean that the user typed RET with the minibuffer empty.
1598 ;; In that case, we really want to return ""
1599 ;; so that commands such as set-visited-file-name can distinguish.
1600 (when (consp default-filename)
1601 (setq default-filename (car default-filename)))
1602 (when (eq val default-filename)
1603 ;; In this case, completing-read has not added an element
1604 ;; to the history. Maybe we should.
1605 (if (not replace-in-history)
1606 (setq add-to-history t))
1607 (setq val ""))
1608 (unless val (error "No file name specified"))
1610 (if (and default-filename
1611 (string-equal val (if (consp insdef) (car insdef) insdef)))
1612 (setq val default-filename))
1613 (setq val (substitute-in-file-name val))
1615 (if replace-in-history
1616 ;; Replace what Fcompleting_read added to the history
1617 ;; with what we will actually return. As an exception,
1618 ;; if that's the same as the second item in
1619 ;; file-name-history, it's really a repeat (Bug#4657).
1620 (let ((val1 (minibuffer--double-dollars val)))
1621 (if history-delete-duplicates
1622 (setcdr file-name-history
1623 (delete val1 (cdr file-name-history))))
1624 (if (string= val1 (cadr file-name-history))
1625 (pop file-name-history)
1626 (setcar file-name-history val1)))
1627 (if add-to-history
1628 ;; Add the value to the history--but not if it matches
1629 ;; the last value already there.
1630 (let ((val1 (minibuffer--double-dollars val)))
1631 (unless (and (consp file-name-history)
1632 (equal (car file-name-history) val1))
1633 (setq file-name-history
1634 (cons val1
1635 (if history-delete-duplicates
1636 (delete val1 file-name-history)
1637 file-name-history)))))))
1638 val)))))
1640 (defun internal-complete-buffer-except (&optional buffer)
1641 "Perform completion on all buffers excluding BUFFER.
1642 BUFFER nil or omitted means use the current buffer.
1643 Like `internal-complete-buffer', but removes BUFFER from the completion list."
1644 (lexical-let ((except (if (stringp buffer) buffer (buffer-name buffer))))
1645 (apply-partially 'completion-table-with-predicate
1646 'internal-complete-buffer
1647 (lambda (name)
1648 (not (equal (if (consp name) (car name) name) except)))
1649 nil)))
1651 ;;; Old-style completion, used in Emacs-21 and Emacs-22.
1653 (defun completion-emacs21-try-completion (string table pred point)
1654 (let ((completion (try-completion string table pred)))
1655 (if (stringp completion)
1656 (cons completion (length completion))
1657 completion)))
1659 (defun completion-emacs21-all-completions (string table pred point)
1660 (completion-hilit-commonality
1661 (all-completions string table pred)
1662 (length string)
1663 (car (completion-boundaries string table pred ""))))
1665 (defun completion-emacs22-try-completion (string table pred point)
1666 (let ((suffix (substring string point))
1667 (completion (try-completion (substring string 0 point) table pred)))
1668 (if (not (stringp completion))
1669 completion
1670 ;; Merge a trailing / in completion with a / after point.
1671 ;; We used to only do it for word completion, but it seems to make
1672 ;; sense for all completions.
1673 ;; Actually, claiming this feature was part of Emacs-22 completion
1674 ;; is pushing it a bit: it was only done in minibuffer-completion-word,
1675 ;; which was (by default) not bound during file completion, where such
1676 ;; slashes are most likely to occur.
1677 (if (and (not (zerop (length completion)))
1678 (eq ?/ (aref completion (1- (length completion))))
1679 (not (zerop (length suffix)))
1680 (eq ?/ (aref suffix 0)))
1681 ;; This leaves point after the / .
1682 (setq suffix (substring suffix 1)))
1683 (cons (concat completion suffix) (length completion)))))
1685 (defun completion-emacs22-all-completions (string table pred point)
1686 (let ((beforepoint (substring string 0 point)))
1687 (completion-hilit-commonality
1688 (all-completions beforepoint table pred)
1689 point
1690 (car (completion-boundaries beforepoint table pred "")))))
1692 ;;; Basic completion.
1694 (defun completion--merge-suffix (completion point suffix)
1695 "Merge end of COMPLETION with beginning of SUFFIX.
1696 Simple generalization of the \"merge trailing /\" done in Emacs-22.
1697 Return the new suffix."
1698 (if (and (not (zerop (length suffix)))
1699 (string-match "\\(.+\\)\n\\1" (concat completion "\n" suffix)
1700 ;; Make sure we don't compress things to less
1701 ;; than we started with.
1702 point)
1703 ;; Just make sure we didn't match some other \n.
1704 (eq (match-end 1) (length completion)))
1705 (substring suffix (- (match-end 1) (match-beginning 1)))
1706 ;; Nothing to merge.
1707 suffix))
1709 (defun completion-basic-try-completion (string table pred point)
1710 (let* ((beforepoint (substring string 0 point))
1711 (afterpoint (substring string point))
1712 (bounds (completion-boundaries beforepoint table pred afterpoint)))
1713 (if (zerop (cdr bounds))
1714 ;; `try-completion' may return a subtly different result
1715 ;; than `all+merge', so try to use it whenever possible.
1716 (let ((completion (try-completion beforepoint table pred)))
1717 (if (not (stringp completion))
1718 completion
1719 (cons
1720 (concat completion
1721 (completion--merge-suffix completion point afterpoint))
1722 (length completion))))
1723 (let* ((suffix (substring afterpoint (cdr bounds)))
1724 (prefix (substring beforepoint 0 (car bounds)))
1725 (pattern (delete
1726 "" (list (substring beforepoint (car bounds))
1727 'point
1728 (substring afterpoint 0 (cdr bounds)))))
1729 (all (completion-pcm--all-completions prefix pattern table pred)))
1730 (if minibuffer-completing-file-name
1731 (setq all (completion-pcm--filename-try-filter all)))
1732 (completion-pcm--merge-try pattern all prefix suffix)))))
1734 (defun completion-basic-all-completions (string table pred point)
1735 (let* ((beforepoint (substring string 0 point))
1736 (afterpoint (substring string point))
1737 (bounds (completion-boundaries beforepoint table pred afterpoint))
1738 (suffix (substring afterpoint (cdr bounds)))
1739 (prefix (substring beforepoint 0 (car bounds)))
1740 (pattern (delete
1741 "" (list (substring beforepoint (car bounds))
1742 'point
1743 (substring afterpoint 0 (cdr bounds)))))
1744 (all (completion-pcm--all-completions prefix pattern table pred)))
1745 (completion-hilit-commonality all point (car bounds))))
1747 ;;; Partial-completion-mode style completion.
1749 (defvar completion-pcm--delim-wild-regex nil
1750 "Regular expression matching delimiters controlling the partial-completion.
1751 Typically, this regular expression simply matches a delimiter, meaning
1752 that completion can add something at (match-beginning 0), but if it has
1753 a submatch 1, then completion can add something at (match-end 1).
1754 This is used when the delimiter needs to be of size zero (e.g. the transition
1755 from lowercase to uppercase characters).")
1757 (defun completion-pcm--prepare-delim-re (delims)
1758 (setq completion-pcm--delim-wild-regex (concat "[" delims "*]")))
1760 (defcustom completion-pcm-word-delimiters "-_./: "
1761 "A string of characters treated as word delimiters for completion.
1762 Some arcane rules:
1763 If `]' is in this string, it must come first.
1764 If `^' is in this string, it must not come first.
1765 If `-' is in this string, it must come first or right after `]'.
1766 In other words, if S is this string, then `[S]' must be a valid Emacs regular
1767 expression (not containing character ranges like `a-z')."
1768 :set (lambda (symbol value)
1769 (set-default symbol value)
1770 ;; Refresh other vars.
1771 (completion-pcm--prepare-delim-re value))
1772 :initialize 'custom-initialize-reset
1773 :group 'minibuffer
1774 :type 'string)
1776 (defun completion-pcm--pattern-trivial-p (pattern)
1777 (and (stringp (car pattern))
1778 ;; It can be followed by `point' and "" and still be trivial.
1779 (let ((trivial t))
1780 (dolist (elem (cdr pattern))
1781 (unless (member elem '(point ""))
1782 (setq trivial nil)))
1783 trivial)))
1785 (defun completion-pcm--string->pattern (string &optional point)
1786 "Split STRING into a pattern.
1787 A pattern is a list where each element is either a string
1788 or a symbol chosen among `any', `star', `point'."
1789 (if (and point (< point (length string)))
1790 (let ((prefix (substring string 0 point))
1791 (suffix (substring string point)))
1792 (append (completion-pcm--string->pattern prefix)
1793 '(point)
1794 (completion-pcm--string->pattern suffix)))
1795 (let ((pattern nil)
1796 (p 0)
1797 (p0 0))
1799 (while (and (setq p (string-match completion-pcm--delim-wild-regex
1800 string p))
1801 ;; If the char was added by minibuffer-complete-word, then
1802 ;; don't treat it as a delimiter, otherwise "M-x SPC"
1803 ;; ends up inserting a "-" rather than listing
1804 ;; all completions.
1805 (not (get-text-property p 'completion-try-word string)))
1806 ;; Usually, completion-pcm--delim-wild-regex matches a delimiter,
1807 ;; meaning that something can be added *before* it, but it can also
1808 ;; match a prefix and postfix, in which case something can be added
1809 ;; in-between (e.g. match [[:lower:]][[:upper:]]).
1810 ;; This is determined by the presence of a submatch-1 which delimits
1811 ;; the prefix.
1812 (if (match-end 1) (setq p (match-end 1)))
1813 (push (substring string p0 p) pattern)
1814 (if (eq (aref string p) ?*)
1815 (progn
1816 (push 'star pattern)
1817 (setq p0 (1+ p)))
1818 (push 'any pattern)
1819 (setq p0 p))
1820 (incf p))
1822 ;; An empty string might be erroneously added at the beginning.
1823 ;; It should be avoided properly, but it's so easy to remove it here.
1824 (delete "" (nreverse (cons (substring string p0) pattern))))))
1826 (defun completion-pcm--pattern->regex (pattern &optional group)
1827 (let ((re
1828 (concat "\\`"
1829 (mapconcat
1830 (lambda (x)
1831 (case x
1832 ((star any point)
1833 (if (if (consp group) (memq x group) group)
1834 "\\(.*?\\)" ".*?"))
1835 (t (regexp-quote x))))
1836 pattern
1837 ""))))
1838 ;; Avoid pathological backtracking.
1839 (while (string-match "\\.\\*\\?\\(?:\\\\[()]\\)*\\(\\.\\*\\?\\)" re)
1840 (setq re (replace-match "" t t re 1)))
1841 re))
1843 (defun completion-pcm--all-completions (prefix pattern table pred)
1844 "Find all completions for PATTERN in TABLE obeying PRED.
1845 PATTERN is as returned by `completion-pcm--string->pattern'."
1846 ;; (assert (= (car (completion-boundaries prefix table pred ""))
1847 ;; (length prefix)))
1848 ;; Find an initial list of possible completions.
1849 (if (completion-pcm--pattern-trivial-p pattern)
1851 ;; Minibuffer contains no delimiters -- simple case!
1852 (all-completions (concat prefix (car pattern)) table pred)
1854 ;; Use all-completions to do an initial cull. This is a big win,
1855 ;; since all-completions is written in C!
1856 (let* (;; Convert search pattern to a standard regular expression.
1857 (regex (completion-pcm--pattern->regex pattern))
1858 (case-fold-search completion-ignore-case)
1859 (completion-regexp-list (cons regex completion-regexp-list))
1860 (compl (all-completions
1861 (concat prefix (if (stringp (car pattern)) (car pattern) ""))
1862 table pred)))
1863 (if (not (functionp table))
1864 ;; The internal functions already obeyed completion-regexp-list.
1865 compl
1866 (let ((poss ()))
1867 (dolist (c compl)
1868 (when (string-match-p regex c) (push c poss)))
1869 poss)))))
1871 (defun completion-pcm--hilit-commonality (pattern completions)
1872 (when completions
1873 (let* ((re (completion-pcm--pattern->regex pattern '(point)))
1874 (case-fold-search completion-ignore-case))
1875 (mapcar
1876 (lambda (str)
1877 ;; Don't modify the string itself.
1878 (setq str (copy-sequence str))
1879 (unless (string-match re str)
1880 (error "Internal error: %s does not match %s" re str))
1881 (let ((pos (or (match-beginning 1) (match-end 0))))
1882 (put-text-property 0 pos
1883 'font-lock-face 'completions-common-part
1884 str)
1885 (if (> (length str) pos)
1886 (put-text-property pos (1+ pos)
1887 'font-lock-face 'completions-first-difference
1888 str)))
1889 str)
1890 completions))))
1892 (defun completion-pcm--find-all-completions (string table pred point
1893 &optional filter)
1894 "Find all completions for STRING at POINT in TABLE, satisfying PRED.
1895 POINT is a position inside STRING.
1896 FILTER is a function applied to the return value, that can be used, e.g. to
1897 filter out additional entries (because TABLE migth not obey PRED)."
1898 (unless filter (setq filter 'identity))
1899 (let* ((beforepoint (substring string 0 point))
1900 (afterpoint (substring string point))
1901 (bounds (completion-boundaries beforepoint table pred afterpoint))
1902 (prefix (substring beforepoint 0 (car bounds)))
1903 (suffix (substring afterpoint (cdr bounds)))
1904 firsterror)
1905 (setq string (substring string (car bounds) (+ point (cdr bounds))))
1906 (let* ((relpoint (- point (car bounds)))
1907 (pattern (completion-pcm--string->pattern string relpoint))
1908 (all (condition-case err
1909 (funcall filter
1910 (completion-pcm--all-completions
1911 prefix pattern table pred))
1912 (error (unless firsterror (setq firsterror err)) nil))))
1913 (when (and (null all)
1914 (> (car bounds) 0)
1915 (null (ignore-errors (try-completion prefix table pred))))
1916 ;; The prefix has no completions at all, so we should try and fix
1917 ;; that first.
1918 (let ((substring (substring prefix 0 -1)))
1919 (destructuring-bind (subpat suball subprefix subsuffix)
1920 (completion-pcm--find-all-completions
1921 substring table pred (length substring) filter)
1922 (let ((sep (aref prefix (1- (length prefix))))
1923 ;; Text that goes between the new submatches and the
1924 ;; completion substring.
1925 (between nil))
1926 ;; Eliminate submatches that don't end with the separator.
1927 (dolist (submatch (prog1 suball (setq suball ())))
1928 (when (eq sep (aref submatch (1- (length submatch))))
1929 (push submatch suball)))
1930 (when suball
1931 ;; Update the boundaries and corresponding pattern.
1932 ;; We assume that all submatches result in the same boundaries
1933 ;; since we wouldn't know how to merge them otherwise anyway.
1934 ;; FIXME: COMPLETE REWRITE!!!
1935 (let* ((newbeforepoint
1936 (concat subprefix (car suball)
1937 (substring string 0 relpoint)))
1938 (leftbound (+ (length subprefix) (length (car suball))))
1939 (newbounds (completion-boundaries
1940 newbeforepoint table pred afterpoint)))
1941 (unless (or (and (eq (cdr bounds) (cdr newbounds))
1942 (eq (car newbounds) leftbound))
1943 ;; Refuse new boundaries if they step over
1944 ;; the submatch.
1945 (< (car newbounds) leftbound))
1946 ;; The new completed prefix does change the boundaries
1947 ;; of the completed substring.
1948 (setq suffix (substring afterpoint (cdr newbounds)))
1949 (setq string
1950 (concat (substring newbeforepoint (car newbounds))
1951 (substring afterpoint 0 (cdr newbounds))))
1952 (setq between (substring newbeforepoint leftbound
1953 (car newbounds)))
1954 (setq pattern (completion-pcm--string->pattern
1955 string
1956 (- (length newbeforepoint)
1957 (car newbounds)))))
1958 (dolist (submatch suball)
1959 (setq all (nconc (mapcar
1960 (lambda (s) (concat submatch between s))
1961 (funcall filter
1962 (completion-pcm--all-completions
1963 (concat subprefix submatch between)
1964 pattern table pred)))
1965 all)))
1966 ;; FIXME: This can come in handy for try-completion,
1967 ;; but isn't right for all-completions, since it lists
1968 ;; invalid completions.
1969 ;; (unless all
1970 ;; ;; Even though we found expansions in the prefix, none
1971 ;; ;; leads to a valid completion.
1972 ;; ;; Let's keep the expansions, tho.
1973 ;; (dolist (submatch suball)
1974 ;; (push (concat submatch between newsubstring) all)))
1976 (setq pattern (append subpat (list 'any (string sep))
1977 (if between (list between)) pattern))
1978 (setq prefix subprefix)))))
1979 (if (and (null all) firsterror)
1980 (signal (car firsterror) (cdr firsterror))
1981 (list pattern all prefix suffix)))))
1983 (defun completion-pcm-all-completions (string table pred point)
1984 (destructuring-bind (pattern all &optional prefix suffix)
1985 (completion-pcm--find-all-completions string table pred point)
1986 (when all
1987 (nconc (completion-pcm--hilit-commonality pattern all)
1988 (length prefix)))))
1990 (defun completion-pcm--merge-completions (strs pattern)
1991 "Extract the commonality in STRS, with the help of PATTERN."
1992 ;; When completing while ignoring case, we want to try and avoid
1993 ;; completing "fo" to "foO" when completing against "FOO" (bug#4219).
1994 ;; So we try and make sure that the string we return is all made up
1995 ;; of text from the completions rather than part from the
1996 ;; completions and part from the input.
1997 ;; FIXME: This reduces the problems of inconsistent capitalization
1998 ;; but it doesn't fully fix it: we may still end up completing
1999 ;; "fo-ba" to "foo-BAR" or "FOO-bar" when completing against
2000 ;; '("foo-barr" "FOO-BARD").
2001 (cond
2002 ((null (cdr strs)) (list (car strs)))
2004 (let ((re (completion-pcm--pattern->regex pattern 'group))
2005 (ccs ())) ;Chopped completions.
2007 ;; First chop each string into the parts corresponding to each
2008 ;; non-constant element of `pattern', using regexp-matching.
2009 (let ((case-fold-search completion-ignore-case))
2010 (dolist (str strs)
2011 (unless (string-match re str)
2012 (error "Internal error: %s doesn't match %s" str re))
2013 (let ((chopped ())
2014 (last 0)
2015 (i 1)
2016 next)
2017 (while (setq next (match-end i))
2018 (push (substring str last next) chopped)
2019 (setq last next)
2020 (setq i (1+ i)))
2021 ;; Add the text corresponding to the implicit trailing `any'.
2022 (push (substring str last) chopped)
2023 (push (nreverse chopped) ccs))))
2025 ;; Then for each of those non-constant elements, extract the
2026 ;; commonality between them.
2027 (let ((res ())
2028 (fixed ""))
2029 ;; Make the implicit trailing `any' explicit.
2030 (dolist (elem (append pattern '(any)))
2031 (if (stringp elem)
2032 (setq fixed (concat fixed elem))
2033 (let ((comps ()))
2034 (dolist (cc (prog1 ccs (setq ccs nil)))
2035 (push (car cc) comps)
2036 (push (cdr cc) ccs))
2037 ;; Might improve the likelihood to avoid choosing
2038 ;; different capitalizations in different parts.
2039 ;; In practice, it doesn't seem to make any difference.
2040 (setq ccs (nreverse ccs))
2041 (let* ((prefix (try-completion fixed comps))
2042 (unique (or (and (eq prefix t) (setq prefix fixed))
2043 (eq t (try-completion prefix comps)))))
2044 (unless (equal prefix "") (push prefix res))
2045 ;; If there's only one completion, `elem' is not useful
2046 ;; any more: it can only match the empty string.
2047 ;; FIXME: in some cases, it may be necessary to turn an
2048 ;; `any' into a `star' because the surrounding context has
2049 ;; changed such that string->pattern wouldn't add an `any'
2050 ;; here any more.
2051 (unless unique (push elem res))
2052 (setq fixed "")))))
2053 ;; We return it in reverse order.
2054 res)))))
2056 (defun completion-pcm--pattern->string (pattern)
2057 (mapconcat (lambda (x) (cond
2058 ((stringp x) x)
2059 ((eq x 'star) "*")
2060 ((eq x 'any) "")
2061 ((eq x 'point) "")))
2062 pattern
2063 ""))
2065 ;; We want to provide the functionality of `try', but we use `all'
2066 ;; and then merge it. In most cases, this works perfectly, but
2067 ;; if the completion table doesn't consider the same completions in
2068 ;; `try' as in `all', then we have a problem. The most common such
2069 ;; case is for filename completion where completion-ignored-extensions
2070 ;; is only obeyed by the `try' code. We paper over the difference
2071 ;; here. Note that it is not quite right either: if the completion
2072 ;; table uses completion-table-in-turn, this filtering may take place
2073 ;; too late to correctly fallback from the first to the
2074 ;; second alternative.
2075 (defun completion-pcm--filename-try-filter (all)
2076 "Filter to adjust `all' file completion to the behavior of `try'."
2077 (when all
2078 (let ((try ())
2079 (re (concat "\\(?:\\`\\.\\.?/\\|"
2080 (regexp-opt completion-ignored-extensions)
2081 "\\)\\'")))
2082 (dolist (f all)
2083 (unless (string-match-p re f) (push f try)))
2084 (or try all))))
2087 (defun completion-pcm--merge-try (pattern all prefix suffix)
2088 (cond
2089 ((not (consp all)) all)
2090 ((and (not (consp (cdr all))) ;Only one completion.
2091 ;; Ignore completion-ignore-case here.
2092 (equal (completion-pcm--pattern->string pattern) (car all)))
2095 (let* ((mergedpat (completion-pcm--merge-completions all pattern))
2096 ;; `mergedpat' is in reverse order. Place new point (by
2097 ;; order of preference) either at the old point, or at
2098 ;; the last place where there's something to choose, or
2099 ;; at the very end.
2100 (pointpat (or (memq 'point mergedpat)
2101 (memq 'any mergedpat)
2102 (memq 'star mergedpat)
2103 mergedpat))
2104 ;; New pos from the start.
2105 (newpos (length (completion-pcm--pattern->string pointpat)))
2106 ;; Do it afterwards because it changes `pointpat' by sideeffect.
2107 (merged (completion-pcm--pattern->string (nreverse mergedpat))))
2109 (setq suffix (completion--merge-suffix merged newpos suffix))
2110 (cons (concat prefix merged suffix) (+ newpos (length prefix)))))))
2112 (defun completion-pcm-try-completion (string table pred point)
2113 (destructuring-bind (pattern all prefix suffix)
2114 (completion-pcm--find-all-completions
2115 string table pred point
2116 (if minibuffer-completing-file-name
2117 'completion-pcm--filename-try-filter))
2118 (completion-pcm--merge-try pattern all prefix suffix)))
2120 ;;; Initials completion
2121 ;; Complete /ums to /usr/monnier/src or lch to list-command-history.
2123 (defun completion-initials-expand (str table pred)
2124 (let ((bounds (completion-boundaries str table pred "")))
2125 (unless (or (zerop (length str))
2126 ;; Only check within the boundaries, since the
2127 ;; boundary char (e.g. /) might be in delim-regexp.
2128 (string-match completion-pcm--delim-wild-regex str
2129 (car bounds)))
2130 (if (zerop (car bounds))
2131 (mapconcat 'string str "-")
2132 ;; If there's a boundary, it's trickier. The main use-case
2133 ;; we consider here is file-name completion. We'd like
2134 ;; to expand ~/eee to ~/e/e/e and /eee to /e/e/e.
2135 ;; But at the same time, we don't want /usr/share/ae to expand
2136 ;; to /usr/share/a/e just because we mistyped "ae" for "ar",
2137 ;; so we probably don't want initials to touch anything that
2138 ;; looks like /usr/share/foo. As a heuristic, we just check that
2139 ;; the text before the boundary char is at most 1 char.
2140 ;; This allows both ~/eee and /eee and not much more.
2141 ;; FIXME: It sadly also disallows the use of ~/eee when that's
2142 ;; embedded within something else (e.g. "(~/eee" in Info node
2143 ;; completion or "ancestor:/eee" in bzr-revision completion).
2144 (when (< (car bounds) 3)
2145 (let ((sep (substring str (1- (car bounds)) (car bounds))))
2146 ;; FIXME: the above string-match checks the whole string, whereas
2147 ;; we end up only caring about the after-boundary part.
2148 (concat (substring str 0 (car bounds))
2149 (mapconcat 'string (substring str (car bounds)) sep))))))))
2151 (defun completion-initials-all-completions (string table pred point)
2152 (let ((newstr (completion-initials-expand string table pred)))
2153 (when newstr
2154 (completion-pcm-all-completions newstr table pred (length newstr)))))
2156 (defun completion-initials-try-completion (string table pred point)
2157 (let ((newstr (completion-initials-expand string table pred)))
2158 (when newstr
2159 (completion-pcm-try-completion newstr table pred (length newstr)))))
2162 ;; Miscellaneous
2164 (defun minibuffer-insert-file-name-at-point ()
2165 "Get a file name at point in original buffer and insert it to minibuffer."
2166 (interactive)
2167 (let ((file-name-at-point
2168 (with-current-buffer (window-buffer (minibuffer-selected-window))
2169 (run-hook-with-args-until-success 'file-name-at-point-functions))))
2170 (when file-name-at-point
2171 (insert file-name-at-point))))
2173 (provide 'minibuffer)
2175 ;; arch-tag: ef8a0a15-1080-4790-a754-04017c02f08f
2176 ;;; minibuffer.el ends here