]> code.delx.au - gnu-emacs/blob - lisp/minibuffer.el
Merge from emacs-23; up to 2010-06-12T11:17:12Z!eliz@gnu.org.
[gnu-emacs] / lisp / minibuffer.el
1 ;;; minibuffer.el --- Minibuffer completion functions -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2008-2011 Free Software Foundation, Inc.
4
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6 ;; Package: emacs
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;; Names with "--" are for functions and variables that are meant to be for
26 ;; internal use only.
27
28 ;; Functional completion tables have an extended calling conventions:
29 ;; - The `action' can be (additionally to nil, t, and lambda) of the form
30 ;; (boundaries . SUFFIX) in which case it should return
31 ;; (boundaries START . END). See `completion-boundaries'.
32 ;; Any other return value should be ignored (so we ignore values returned
33 ;; from completion tables that don't know about this new `action' form).
34
35 ;;; Bugs:
36
37 ;; - completion-all-sorted-completions list all the completions, whereas
38 ;; it should only lists the ones that `try-completion' would consider.
39 ;; E.g. it should honor completion-ignored-extensions.
40 ;; - choose-completion can't automatically figure out the boundaries
41 ;; corresponding to the displayed completions because we only
42 ;; provide the start info but not the end info in
43 ;; completion-base-position.
44 ;; - quoting is problematic. E.g. the double-dollar quoting used in
45 ;; substitute-in-file-name (and hence read-file-name-internal) bumps
46 ;; into various bugs:
47 ;; - choose-completion doesn't know how to quote the text it inserts.
48 ;; E.g. it fails to double the dollars in file-name completion, or
49 ;; to backslash-escape spaces and other chars in comint completion.
50 ;; - when completing ~/tmp/fo$$o, the highligting in *Completions*
51 ;; is off by one position.
52 ;; - all code like PCM which relies on all-completions to match
53 ;; its argument gets confused because all-completions returns unquoted
54 ;; texts (as desired for *Completions* output).
55 ;; - C-x C-f ~/*/sr ? should not list "~/./src".
56 ;; - minibuffer-force-complete completes ~/src/emacs/t<!>/lisp/minibuffer.el
57 ;; to ~/src/emacs/trunk/ and throws away lisp/minibuffer.el.
58
59 ;;; Todo:
60
61 ;; - for M-x, cycle-sort commands that have no key binding first.
62 ;; - Make things like icomplete-mode or lightning-completion work with
63 ;; completion-in-region-mode.
64 ;; - extend `boundaries' to provide various other meta-data about the
65 ;; output of `all-completions':
66 ;; - preferred sorting order when displayed in *Completions*.
67 ;; - annotations/text-properties to add when displayed in *Completions*.
68 ;; - quoting/unquoting (so we can complete files names with envvars
69 ;; and backslashes, and all-completion can list names without
70 ;; quoting backslashes and dollars).
71 ;; - indicate how to turn all-completion's output into
72 ;; try-completion's output: e.g. completion-ignored-extensions.
73 ;; maybe that could be merged with the "quote" operation above.
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.
79 ;; - indicate how to display the completions in *Completions* (turn
80 ;; \n into something else, add special boundaries between
81 ;; completions). E.g. when completing from the kill-ring.
82
83 ;; - case-sensitivity currently confuses two issues:
84 ;; - whether or not a particular completion table should be case-sensitive
85 ;; (i.e. whether strings that differ only by case are semantically
86 ;; equivalent)
87 ;; - whether the user wants completion to pay attention to case.
88 ;; e.g. we may want to make it possible for the user to say "first try
89 ;; completion case-sensitively, and if that fails, try to ignore case".
90
91 ;; - add support for ** to pcm.
92 ;; - Add vc-file-name-completion-table to read-file-name-internal.
93 ;; - A feature like completing-help.el.
94
95 ;;; Code:
96
97 (eval-when-compile (require 'cl))
98
99 ;;; Completion table manipulation
100
101 ;; New completion-table operation.
102 (defun completion-boundaries (string table pred suffix)
103 "Return the boundaries of the completions returned by TABLE for STRING.
104 STRING is the string on which completion will be performed.
105 SUFFIX is the string after point.
106 The result is of the form (START . END) where START is the position
107 in STRING of the beginning of the completion field and END is the position
108 in SUFFIX of the end of the completion field.
109 E.g. for simple completion tables, the result is always (0 . (length SUFFIX))
110 and for file names the result is the positions delimited by
111 the closest directory separators."
112 (let ((boundaries (if (functionp table)
113 (funcall table string pred (cons 'boundaries suffix)))))
114 (if (not (eq (car-safe boundaries) 'boundaries))
115 (setq boundaries nil))
116 (cons (or (cadr boundaries) 0)
117 (or (cddr boundaries) (length suffix)))))
118
119 (defun completion--some (fun xs)
120 "Apply FUN to each element of XS in turn.
121 Return the first non-nil returned value.
122 Like CL's `some'."
123 (let ((firsterror nil)
124 res)
125 (while (and (not res) xs)
126 (condition-case err
127 (setq res (funcall fun (pop xs)))
128 (error (unless firsterror (setq firsterror err)) nil)))
129 (or res
130 (if firsterror (signal (car firsterror) (cdr firsterror))))))
131
132 (defun complete-with-action (action table string pred)
133 "Perform completion ACTION.
134 STRING is the string to complete.
135 TABLE is the completion table, which should not be a function.
136 PRED is a completion predicate.
137 ACTION can be one of nil, t or `lambda'."
138 (cond
139 ((functionp table) (funcall table string pred action))
140 ((eq (car-safe action) 'boundaries)
141 (cons 'boundaries (completion-boundaries string table pred (cdr action))))
142 (t
143 (funcall
144 (cond
145 ((null action) 'try-completion)
146 ((eq action t) 'all-completions)
147 (t 'test-completion))
148 string table pred))))
149
150 (defun completion-table-dynamic (fun)
151 "Use function FUN as a dynamic completion table.
152 FUN is called with one argument, the string for which completion is required,
153 and it should return an alist containing all the intended possible completions.
154 This alist may be a full list of possible completions so that FUN can ignore
155 the value of its argument. If completion is performed in the minibuffer,
156 FUN will be called in the buffer from which the minibuffer was entered.
157
158 The result of the `completion-table-dynamic' form is a function
159 that can be used as the COLLECTION argument to `try-completion' and
160 `all-completions'. See Info node `(elisp)Programmed Completion'."
161 (lambda (string pred action)
162 (if (eq (car-safe action) 'boundaries)
163 ;; `fun' is not supposed to return another function but a plain old
164 ;; completion table, whose boundaries are always trivial.
165 nil
166 (with-current-buffer (let ((win (minibuffer-selected-window)))
167 (if (window-live-p win) (window-buffer win)
168 (current-buffer)))
169 (complete-with-action action (funcall fun string) string pred)))))
170
171 (defmacro lazy-completion-table (var fun)
172 "Initialize variable VAR as a lazy completion table.
173 If the completion table VAR is used for the first time (e.g., by passing VAR
174 as an argument to `try-completion'), the function FUN is called with no
175 arguments. FUN must return the completion table that will be stored in VAR.
176 If completion is requested in the minibuffer, FUN will be called in the buffer
177 from which the minibuffer was entered. The return value of
178 `lazy-completion-table' must be used to initialize the value of VAR.
179
180 You should give VAR a non-nil `risky-local-variable' property."
181 (declare (debug (symbolp lambda-expr)))
182 (let ((str (make-symbol "string")))
183 `(completion-table-dynamic
184 (lambda (,str)
185 (when (functionp ,var)
186 (setq ,var (,fun)))
187 ,var))))
188
189 (defun completion-table-case-fold (table string pred action)
190 (let ((completion-ignore-case t))
191 (complete-with-action action table string pred)))
192
193 (defun completion-table-with-context (prefix table string pred action)
194 ;; TODO: add `suffix' maybe?
195 ;; Notice that `pred' may not be a function in some abusive cases.
196 (when (functionp pred)
197 (setq pred
198 ;; Predicates are called differently depending on the nature of
199 ;; the completion table :-(
200 (cond
201 ((vectorp table) ;Obarray.
202 (lambda (sym) (funcall pred (concat prefix (symbol-name sym)))))
203 ((hash-table-p table)
204 (lambda (s _v) (funcall pred (concat prefix s))))
205 ((functionp table)
206 (lambda (s) (funcall pred (concat prefix s))))
207 (t ;Lists and alists.
208 (lambda (s)
209 (funcall pred (concat prefix (if (consp s) (car s) s))))))))
210 (if (eq (car-safe action) 'boundaries)
211 (let* ((len (length prefix))
212 (bound (completion-boundaries string table pred (cdr action))))
213 (list* 'boundaries (+ (car bound) len) (cdr bound)))
214 (let ((comp (complete-with-action action table string pred)))
215 (cond
216 ;; In case of try-completion, add the prefix.
217 ((stringp comp) (concat prefix comp))
218 (t comp)))))
219
220 (defun completion-table-with-terminator (terminator table string pred action)
221 "Construct a completion table like TABLE but with an extra TERMINATOR.
222 This is meant to be called in a curried way by first passing TERMINATOR
223 and TABLE only (via `apply-partially').
224 TABLE is a completion table, and TERMINATOR is a string appended to TABLE's
225 completion if it is complete. TERMINATOR is also used to determine the
226 completion suffix's boundary.
227 TERMINATOR can also be a cons cell (TERMINATOR . TERMINATOR-REGEXP)
228 in which case TERMINATOR-REGEXP is a regular expression whose submatch
229 number 1 should match TERMINATOR. This is used when there is a need to
230 distinguish occurrences of the TERMINATOR strings which are really terminators
231 from others (e.g. escaped). In this form, the car of TERMINATOR can also be,
232 instead of a string, a function that takes the completion and returns the
233 \"terminated\" string."
234 ;; FIXME: This implementation is not right since it only adds the terminator
235 ;; in try-completion, so any completion-style that builds the completion via
236 ;; all-completions won't get the terminator, and selecting an entry in
237 ;; *Completions* won't get the terminator added either.
238 (cond
239 ((eq (car-safe action) 'boundaries)
240 (let* ((suffix (cdr action))
241 (bounds (completion-boundaries string table pred suffix))
242 (terminator-regexp (if (consp terminator)
243 (cdr terminator) (regexp-quote terminator)))
244 (max (and terminator-regexp
245 (string-match terminator-regexp suffix))))
246 (list* 'boundaries (car bounds)
247 (min (cdr bounds) (or max (length suffix))))))
248 ((eq action nil)
249 (let ((comp (try-completion string table pred)))
250 (if (consp terminator) (setq terminator (car terminator)))
251 (if (eq comp t)
252 (if (functionp terminator)
253 (funcall terminator string)
254 (concat string terminator))
255 (if (and (stringp comp) (not (zerop (length comp)))
256 ;; Try to avoid the second call to try-completion, since
257 ;; it may be very inefficient (because `comp' made us
258 ;; jump to a new boundary, so we complete in that
259 ;; boundary with an empty start string).
260 (let ((newbounds (completion-boundaries comp table pred "")))
261 (< (car newbounds) (length comp)))
262 (eq (try-completion comp table pred) t))
263 (if (functionp terminator)
264 (funcall terminator comp)
265 (concat comp terminator))
266 comp))))
267 ((eq action t)
268 ;; FIXME: We generally want the `try' and `all' behaviors to be
269 ;; consistent so pcm can merge the `all' output to get the `try' output,
270 ;; but that sometimes clashes with the need for `all' output to look
271 ;; good in *Completions*.
272 ;; (mapcar (lambda (s) (concat s terminator))
273 ;; (all-completions string table pred))))
274 (all-completions string table pred))
275 ;; completion-table-with-terminator is always used for
276 ;; "sub-completions" so it's only called if the terminator is missing,
277 ;; in which case `test-completion' should return nil.
278 ((eq action 'lambda) nil)))
279
280 (defun completion-table-with-predicate (table pred1 strict string pred2 action)
281 "Make a completion table equivalent to TABLE but filtered through PRED1.
282 PRED1 is a function of one argument which returns non-nil if and only if the
283 argument is an element of TABLE which should be considered for completion.
284 STRING, PRED2, and ACTION are the usual arguments to completion tables,
285 as described in `try-completion', `all-completions', and `test-completion'.
286 If STRICT is t, the predicate always applies; if nil it only applies if
287 it does not reduce the set of possible completions to nothing.
288 Note: TABLE needs to be a proper completion table which obeys predicates."
289 (cond
290 ((and (not strict) (eq action 'lambda))
291 ;; Ignore pred1 since it doesn't really have to apply anyway.
292 (test-completion string table pred2))
293 (t
294 (or (complete-with-action action table string
295 (if (null pred2) pred1
296 (lambda (x)
297 ;; Call `pred1' first, so that `pred2'
298 ;; really can't tell that `x' is in table.
299 (if (funcall pred1 x) (funcall pred2 x)))))
300 ;; If completion failed and we're not applying pred1 strictly, try
301 ;; again without pred1.
302 (and (not strict)
303 (complete-with-action action table string pred2))))))
304
305 (defun completion-table-in-turn (&rest tables)
306 "Create a completion table that tries each table in TABLES in turn."
307 ;; FIXME: the boundaries may come from TABLE1 even when the completion list
308 ;; is returned by TABLE2 (because TABLE1 returned an empty list).
309 (lambda (string pred action)
310 (completion--some (lambda (table)
311 (complete-with-action action table string pred))
312 tables)))
313
314 ;; (defmacro complete-in-turn (a b) `(completion-table-in-turn ,a ,b))
315 ;; (defmacro dynamic-completion-table (fun) `(completion-table-dynamic ,fun))
316 (define-obsolete-function-alias
317 'complete-in-turn 'completion-table-in-turn "23.1")
318 (define-obsolete-function-alias
319 'dynamic-completion-table 'completion-table-dynamic "23.1")
320
321 ;;; Minibuffer completion
322
323 (defgroup minibuffer nil
324 "Controlling the behavior of the minibuffer."
325 :link '(custom-manual "(emacs)Minibuffer")
326 :group 'environment)
327
328 (defun minibuffer-message (message &rest args)
329 "Temporarily display MESSAGE at the end of the minibuffer.
330 The text is displayed for `minibuffer-message-timeout' seconds,
331 or until the next input event arrives, whichever comes first.
332 Enclose MESSAGE in [...] if this is not yet the case.
333 If ARGS are provided, then pass MESSAGE through `format'."
334 (if (not (minibufferp (current-buffer)))
335 (progn
336 (if args
337 (apply 'message message args)
338 (message "%s" message))
339 (prog1 (sit-for (or minibuffer-message-timeout 1000000))
340 (message nil)))
341 ;; Clear out any old echo-area message to make way for our new thing.
342 (message nil)
343 (setq message (if (and (null args) (string-match-p "\\` *\\[.+\\]\\'" message))
344 ;; Make sure we can put-text-property.
345 (copy-sequence message)
346 (concat " [" message "]")))
347 (when args (setq message (apply 'format message args)))
348 (let ((ol (make-overlay (point-max) (point-max) nil t t))
349 ;; A quit during sit-for normally only interrupts the sit-for,
350 ;; but since minibuffer-message is used at the end of a command,
351 ;; at a time when the command has virtually finished already, a C-g
352 ;; should really cause an abort-recursive-edit instead (i.e. as if
353 ;; the C-g had been typed at top-level). Binding inhibit-quit here
354 ;; is an attempt to get that behavior.
355 (inhibit-quit t))
356 (unwind-protect
357 (progn
358 (unless (zerop (length message))
359 ;; The current C cursor code doesn't know to use the overlay's
360 ;; marker's stickiness to figure out whether to place the cursor
361 ;; before or after the string, so let's spoon-feed it the pos.
362 (put-text-property 0 1 'cursor t message))
363 (overlay-put ol 'after-string message)
364 (sit-for (or minibuffer-message-timeout 1000000)))
365 (delete-overlay ol)))))
366
367 (defun minibuffer-completion-contents ()
368 "Return the user input in a minibuffer before point as a string.
369 That is what completion commands operate on."
370 (buffer-substring (field-beginning) (point)))
371
372 (defun delete-minibuffer-contents ()
373 "Delete all user input in a minibuffer.
374 If the current buffer is not a minibuffer, erase its entire contents."
375 ;; We used to do `delete-field' here, but when file name shadowing
376 ;; is on, the field doesn't cover the entire minibuffer contents.
377 (delete-region (minibuffer-prompt-end) (point-max)))
378
379 (defvar completion-show-inline-help t
380 "If non-nil, print helpful inline messages during completion.")
381
382 (defcustom completion-auto-help t
383 "Non-nil means automatically provide help for invalid completion input.
384 If the value is t the *Completion* buffer is displayed whenever completion
385 is requested but cannot be done.
386 If the value is `lazy', the *Completions* buffer is only displayed after
387 the second failed attempt to complete."
388 :type '(choice (const nil) (const t) (const lazy))
389 :group 'minibuffer)
390
391 (defconst completion-styles-alist
392 '((emacs21
393 completion-emacs21-try-completion completion-emacs21-all-completions
394 "Simple prefix-based completion.
395 I.e. when completing \"foo_bar\" (where _ is the position of point),
396 it will consider all completions candidates matching the glob
397 pattern \"foobar*\".")
398 (emacs22
399 completion-emacs22-try-completion completion-emacs22-all-completions
400 "Prefix completion that only operates on the text before point.
401 I.e. when completing \"foo_bar\" (where _ is the position of point),
402 it will consider all completions candidates matching the glob
403 pattern \"foo*\" and will add back \"bar\" to the end of it.")
404 (basic
405 completion-basic-try-completion completion-basic-all-completions
406 "Completion of the prefix before point and the suffix after point.
407 I.e. when completing \"foo_bar\" (where _ is the position of point),
408 it will consider all completions candidates matching the glob
409 pattern \"foo*bar*\".")
410 (partial-completion
411 completion-pcm-try-completion completion-pcm-all-completions
412 "Completion of multiple words, each one taken as a prefix.
413 I.e. when completing \"l-co_h\" (where _ is the position of point),
414 it will consider all completions candidates matching the glob
415 pattern \"l*-co*h*\".
416 Furthermore, for completions that are done step by step in subfields,
417 the method is applied to all the preceding fields that do not yet match.
418 E.g. C-x C-f /u/mo/s TAB could complete to /usr/monnier/src.
419 Additionally the user can use the char \"*\" as a glob pattern.")
420 (substring
421 completion-substring-try-completion completion-substring-all-completions
422 "Completion of the string taken as a substring.
423 I.e. when completing \"foo_bar\" (where _ is the position of point),
424 it will consider all completions candidates matching the glob
425 pattern \"*foo*bar*\".")
426 (initials
427 completion-initials-try-completion completion-initials-all-completions
428 "Completion of acronyms and initialisms.
429 E.g. can complete M-x lch to list-command-history
430 and C-x C-f ~/sew to ~/src/emacs/work."))
431 "List of available completion styles.
432 Each element has the form (NAME TRY-COMPLETION ALL-COMPLETIONS DOC):
433 where NAME is the name that should be used in `completion-styles',
434 TRY-COMPLETION is the function that does the completion (it should
435 follow the same calling convention as `completion-try-completion'),
436 ALL-COMPLETIONS is the function that lists the completions (it should
437 follow the calling convention of `completion-all-completions'),
438 and DOC describes the way this style of completion works.")
439
440 (defcustom completion-styles
441 ;; First, use `basic' because prefix completion has been the standard
442 ;; for "ever" and works well in most cases, so using it first
443 ;; ensures that we obey previous behavior in most cases.
444 '(basic
445 ;; Then use `partial-completion' because it has proven to
446 ;; be a very convenient extension.
447 partial-completion
448 ;; Finally use `emacs22' so as to maintain (in many/most cases)
449 ;; the previous behavior that when completing "foobar" with point
450 ;; between "foo" and "bar" the completion try to complete "foo"
451 ;; and simply add "bar" to the end of the result.
452 emacs22)
453 "List of completion styles to use.
454 The available styles are listed in `completion-styles-alist'."
455 :type `(repeat (choice ,@(mapcar (lambda (x) (list 'const (car x)))
456 completion-styles-alist)))
457 :group 'minibuffer
458 :version "23.1")
459
460 (defun completion-try-completion (string table pred point)
461 "Try to complete STRING using completion table TABLE.
462 Only the elements of table that satisfy predicate PRED are considered.
463 POINT is the position of point within STRING.
464 The return value can be either nil to indicate that there is no completion,
465 t to indicate that STRING is the only possible completion,
466 or a pair (STRING . NEWPOINT) of the completed result string together with
467 a new position for point."
468 (completion--some (lambda (style)
469 (funcall (nth 1 (assq style completion-styles-alist))
470 string table pred point))
471 completion-styles))
472
473 (defun completion-all-completions (string table pred point)
474 "List the possible completions of STRING in completion table TABLE.
475 Only the elements of table that satisfy predicate PRED are considered.
476 POINT is the position of point within STRING.
477 The return value is a list of completions and may contain the base-size
478 in the last `cdr'."
479 ;; FIXME: We need to additionally return the info needed for the
480 ;; second part of completion-base-position.
481 (completion--some (lambda (style)
482 (funcall (nth 2 (assq style completion-styles-alist))
483 string table pred point))
484 completion-styles))
485
486 (defun minibuffer--bitset (modified completions exact)
487 (logior (if modified 4 0)
488 (if completions 2 0)
489 (if exact 1 0)))
490
491 (defun completion--replace (beg end newtext)
492 "Replace the buffer text between BEG and END with NEWTEXT.
493 Moves point to the end of the new text."
494 ;; Maybe this should be in subr.el.
495 ;; You'd think this is trivial to do, but details matter if you want
496 ;; to keep markers "at the right place" and be robust in the face of
497 ;; after-change-functions that may themselves modify the buffer.
498 (let ((prefix-len 0))
499 ;; Don't touch markers in the shared prefix (if any).
500 (while (and (< prefix-len (length newtext))
501 (< (+ beg prefix-len) end)
502 (eq (char-after (+ beg prefix-len))
503 (aref newtext prefix-len)))
504 (setq prefix-len (1+ prefix-len)))
505 (unless (zerop prefix-len)
506 (setq beg (+ beg prefix-len))
507 (setq newtext (substring newtext prefix-len))))
508 (let ((suffix-len 0))
509 ;; Don't touch markers in the shared suffix (if any).
510 (while (and (< suffix-len (length newtext))
511 (< beg (- end suffix-len))
512 (eq (char-before (- end suffix-len))
513 (aref newtext (- (length newtext) suffix-len 1))))
514 (setq suffix-len (1+ suffix-len)))
515 (unless (zerop suffix-len)
516 (setq end (- end suffix-len))
517 (setq newtext (substring newtext 0 (- suffix-len))))
518 (goto-char beg)
519 (insert newtext)
520 (delete-region (point) (+ (point) (- end beg)))
521 (forward-char suffix-len)))
522
523 (defcustom completion-cycle-threshold nil
524 "Number of completion candidates below which cycling is used.
525 Depending on this setting `minibuffer-complete' may use cycling,
526 like `minibuffer-force-complete'.
527 If nil, cycling is never used.
528 If t, cycling is always used.
529 If an integer, cycling is used as soon as there are fewer completion
530 candidates than this number."
531 :type '(choice (const :tag "No cycling" nil)
532 (const :tag "Always cycle" t)
533 (integer :tag "Threshold")))
534
535 (defvar completion-all-sorted-completions nil)
536 (make-variable-buffer-local 'completion-all-sorted-completions)
537 (defvar completion-cycling nil)
538
539 (defvar completion-fail-discreetly nil
540 "If non-nil, stay quiet when there is no match.")
541
542 (defun completion--message (msg)
543 (if completion-show-inline-help
544 (minibuffer-message msg)))
545
546 (defun completion--do-completion (&optional try-completion-function
547 expect-exact)
548 "Do the completion and return a summary of what happened.
549 M = completion was performed, the text was Modified.
550 C = there were available Completions.
551 E = after completion we now have an Exact match.
552
553 MCE
554 000 0 no possible completion
555 001 1 was already an exact and unique completion
556 010 2 no completion happened
557 011 3 was already an exact completion
558 100 4 ??? impossible
559 101 5 ??? impossible
560 110 6 some completion happened
561 111 7 completed to an exact completion
562
563 TRY-COMPLETION-FUNCTION is a function to use in place of `try-completion'.
564 EXPECT-EXACT, if non-nil, means that there is no need to tell the user
565 when the buffer's text is already an exact match."
566 (let* ((beg (field-beginning))
567 (end (field-end))
568 (string (buffer-substring beg end))
569 (comp (funcall (or try-completion-function
570 'completion-try-completion)
571 string
572 minibuffer-completion-table
573 minibuffer-completion-predicate
574 (- (point) beg))))
575 (cond
576 ((null comp)
577 (minibuffer-hide-completions)
578 (unless completion-fail-discreetly
579 (ding)
580 (completion--message "No match"))
581 (minibuffer--bitset nil nil nil))
582 ((eq t comp)
583 (minibuffer-hide-completions)
584 (goto-char end)
585 (completion--done string 'finished
586 (unless expect-exact "Sole completion"))
587 (minibuffer--bitset nil nil t)) ;Exact and unique match.
588 (t
589 ;; `completed' should be t if some completion was done, which doesn't
590 ;; include simply changing the case of the entered string. However,
591 ;; for appearance, the string is rewritten if the case changes.
592 (let* ((comp-pos (cdr comp))
593 (completion (car comp))
594 (completed (not (eq t (compare-strings completion nil nil
595 string nil nil t))))
596 (unchanged (eq t (compare-strings completion nil nil
597 string nil nil nil))))
598 (if unchanged
599 (goto-char end)
600 ;; Insert in minibuffer the chars we got.
601 (completion--replace beg end completion))
602 ;; Move point to its completion-mandated destination.
603 (forward-char (- comp-pos (length completion)))
604
605 (if (not (or unchanged completed))
606 ;; The case of the string changed, but that's all. We're not sure
607 ;; whether this is a unique completion or not, so try again using
608 ;; the real case (this shouldn't recurse again, because the next
609 ;; time try-completion will return either t or the exact string).
610 (completion--do-completion try-completion-function expect-exact)
611
612 ;; It did find a match. Do we match some possibility exactly now?
613 (let ((exact (test-completion completion
614 minibuffer-completion-table
615 minibuffer-completion-predicate))
616 (comps
617 ;; Check to see if we want to do cycling. We do it
618 ;; here, after having performed the normal completion,
619 ;; so as to take advantage of the difference between
620 ;; try-completion and all-completions, for things
621 ;; like completion-ignored-extensions.
622 (when (and completion-cycle-threshold
623 ;; Check that the completion didn't make
624 ;; us jump to a different boundary.
625 (or (not completed)
626 (< (car (completion-boundaries
627 (substring completion 0 comp-pos)
628 minibuffer-completion-table
629 minibuffer-completion-predicate
630 ""))
631 comp-pos)))
632 (completion-all-sorted-completions))))
633 (completion--flush-all-sorted-completions)
634 (cond
635 ((and (consp (cdr comps)) ;; There's something to cycle.
636 (not (ignore-errors
637 ;; This signal an (intended) error if comps is too
638 ;; short or if completion-cycle-threshold is t.
639 (consp (nthcdr completion-cycle-threshold comps)))))
640 ;; Fewer than completion-cycle-threshold remaining
641 ;; completions: let's cycle.
642 (setq completed t exact t)
643 (setq completion-all-sorted-completions comps)
644 (minibuffer-force-complete))
645 (completed
646 ;; We could also decide to refresh the completions,
647 ;; if they're displayed (and assuming there are
648 ;; completions left).
649 (minibuffer-hide-completions)
650 (if exact
651 ;; If completion did not put point at end of field,
652 ;; it's a sign that completion is not finished.
653 (completion--done completion
654 (if (< comp-pos (length completion))
655 'exact 'unknown))))
656 ;; Show the completion table, if requested.
657 ((not exact)
658 (if (case completion-auto-help
659 (lazy (eq this-command last-command))
660 (t completion-auto-help))
661 (minibuffer-completion-help)
662 (completion--message "Next char not unique")))
663 ;; If the last exact completion and this one were the same, it
664 ;; means we've already given a "Complete, but not unique" message
665 ;; and the user's hit TAB again, so now we give him help.
666 (t
667 (if (and (eq this-command last-command) completion-auto-help)
668 (minibuffer-completion-help))
669 (completion--done completion 'exact
670 (unless expect-exact
671 "Complete, but not unique"))))
672
673 (minibuffer--bitset completed t exact))))))))
674
675 (defun minibuffer-complete ()
676 "Complete the minibuffer contents as far as possible.
677 Return nil if there is no valid completion, else t.
678 If no characters can be completed, display a list of possible completions.
679 If you repeat this command after it displayed such a list,
680 scroll the window of possible completions."
681 (interactive)
682 ;; If the previous command was not this,
683 ;; mark the completion buffer obsolete.
684 (unless (eq this-command last-command)
685 (completion--flush-all-sorted-completions)
686 (setq minibuffer-scroll-window nil))
687
688 (cond
689 ;; If there's a fresh completion window with a live buffer,
690 ;; and this command is repeated, scroll that window.
691 ((window-live-p minibuffer-scroll-window)
692 (let ((window minibuffer-scroll-window))
693 (with-current-buffer (window-buffer window)
694 (if (pos-visible-in-window-p (point-max) window)
695 ;; If end is in view, scroll up to the beginning.
696 (set-window-start window (point-min) nil)
697 ;; Else scroll down one screen.
698 (scroll-other-window))
699 nil)))
700 ;; If we're cycling, keep on cycling.
701 ((and completion-cycling completion-all-sorted-completions)
702 (minibuffer-force-complete)
703 t)
704 (t (case (completion--do-completion)
705 (#b000 nil)
706 (t t)))))
707
708 (defun completion--flush-all-sorted-completions (&rest _ignore)
709 (remove-hook 'after-change-functions
710 'completion--flush-all-sorted-completions t)
711 (setq completion-cycling nil)
712 (setq completion-all-sorted-completions nil))
713
714 (defun completion-all-sorted-completions ()
715 (or completion-all-sorted-completions
716 (let* ((start (field-beginning))
717 (end (field-end))
718 (all (completion-all-completions (buffer-substring start end)
719 minibuffer-completion-table
720 minibuffer-completion-predicate
721 (- (point) start)))
722 (last (last all))
723 (base-size (or (cdr last) 0)))
724 (when last
725 (setcdr last nil)
726 ;; Prefer shorter completions.
727 (setq all (sort all (lambda (c1 c2)
728 (let ((s1 (get-text-property
729 0 :completion-cycle-penalty c1))
730 (s2 (get-text-property
731 0 :completion-cycle-penalty c2)))
732 (if (eq s1 s2)
733 (< (length c1) (length c2))
734 (< (or s1 (length c1))
735 (or s2 (length c2))))))))
736 ;; Prefer recently used completions.
737 ;; FIXME: Additional sorting ideas:
738 ;; - for M-x, prefer commands that have no key binding.
739 (when (minibufferp)
740 (let ((hist (symbol-value minibuffer-history-variable)))
741 (setq all (sort all (lambda (c1 c2)
742 (> (length (member c1 hist))
743 (length (member c2 hist))))))))
744 ;; Cache the result. This is not just for speed, but also so that
745 ;; repeated calls to minibuffer-force-complete can cycle through
746 ;; all possibilities.
747 (add-hook 'after-change-functions
748 'completion--flush-all-sorted-completions nil t)
749 (setq completion-all-sorted-completions
750 (nconc all base-size))))))
751
752 (defun minibuffer-force-complete ()
753 "Complete the minibuffer to an exact match.
754 Repeated uses step through the possible completions."
755 (interactive)
756 ;; FIXME: Need to deal with the extra-size issue here as well.
757 ;; FIXME: ~/src/emacs/t<M-TAB>/lisp/minibuffer.el completes to
758 ;; ~/src/emacs/trunk/ and throws away lisp/minibuffer.el.
759 (let* ((start (field-beginning))
760 (end (field-end))
761 (all (completion-all-sorted-completions))
762 (base (+ start (or (cdr (last all)) 0))))
763 (cond
764 ((not (consp all))
765 (completion--message
766 (if all "No more completions" "No completions")))
767 ((not (consp (cdr all)))
768 (let ((mod (equal (car all) (buffer-substring-no-properties base end))))
769 (if mod (completion--replace base end (car all)))
770 (completion--done (buffer-substring-no-properties start (point))
771 'finished (unless mod "Sole completion"))))
772 (t
773 (setq completion-cycling t)
774 (completion--replace base end (car all))
775 (completion--done (buffer-substring-no-properties start (point)) 'sole)
776 ;; If completing file names, (car all) may be a directory, so we'd now
777 ;; have a new set of possible completions and might want to reset
778 ;; completion-all-sorted-completions to nil, but we prefer not to,
779 ;; so that repeated calls minibuffer-force-complete still cycle
780 ;; through the previous possible completions.
781 (let ((last (last all)))
782 (setcdr last (cons (car all) (cdr last)))
783 (setq completion-all-sorted-completions (cdr all)))))))
784
785 (defvar minibuffer-confirm-exit-commands
786 '(minibuffer-complete minibuffer-complete-word PC-complete PC-complete-word)
787 "A list of commands which cause an immediately following
788 `minibuffer-complete-and-exit' to ask for extra confirmation.")
789
790 (defun minibuffer-complete-and-exit ()
791 "Exit if the minibuffer contains a valid completion.
792 Otherwise, try to complete the minibuffer contents. If
793 completion leads to a valid completion, a repetition of this
794 command will exit.
795
796 If `minibuffer-completion-confirm' is `confirm', do not try to
797 complete; instead, ask for confirmation and accept any input if
798 confirmed.
799 If `minibuffer-completion-confirm' is `confirm-after-completion',
800 do not try to complete; instead, ask for confirmation if the
801 preceding minibuffer command was a member of
802 `minibuffer-confirm-exit-commands', and accept the input
803 otherwise."
804 (interactive)
805 (let ((beg (field-beginning))
806 (end (field-end)))
807 (cond
808 ;; Allow user to specify null string
809 ((= beg end) (exit-minibuffer))
810 ((test-completion (buffer-substring beg end)
811 minibuffer-completion-table
812 minibuffer-completion-predicate)
813 ;; FIXME: completion-ignore-case has various slightly
814 ;; incompatible meanings. E.g. it can reflect whether the user
815 ;; wants completion to pay attention to case, or whether the
816 ;; string will be used in a context where case is significant.
817 ;; E.g. usually try-completion should obey the first, whereas
818 ;; test-completion should obey the second.
819 (when completion-ignore-case
820 ;; Fixup case of the field, if necessary.
821 (let* ((string (buffer-substring beg end))
822 (compl (try-completion
823 string
824 minibuffer-completion-table
825 minibuffer-completion-predicate)))
826 (when (and (stringp compl) (not (equal string compl))
827 ;; If it weren't for this piece of paranoia, I'd replace
828 ;; the whole thing with a call to do-completion.
829 ;; This is important, e.g. when the current minibuffer's
830 ;; content is a directory which only contains a single
831 ;; file, so `try-completion' actually completes to
832 ;; that file.
833 (= (length string) (length compl)))
834 (goto-char end)
835 (insert compl)
836 (delete-region beg end))))
837 (exit-minibuffer))
838
839 ((memq minibuffer-completion-confirm '(confirm confirm-after-completion))
840 ;; The user is permitted to exit with an input that's rejected
841 ;; by test-completion, after confirming her choice.
842 (if (or (eq last-command this-command)
843 ;; For `confirm-after-completion' we only ask for confirmation
844 ;; if trying to exit immediately after typing TAB (this
845 ;; catches most minibuffer typos).
846 (and (eq minibuffer-completion-confirm 'confirm-after-completion)
847 (not (memq last-command minibuffer-confirm-exit-commands))))
848 (exit-minibuffer)
849 (minibuffer-message "Confirm")
850 nil))
851
852 (t
853 ;; Call do-completion, but ignore errors.
854 (case (condition-case nil
855 (completion--do-completion nil 'expect-exact)
856 (error 1))
857 ((#b001 #b011) (exit-minibuffer))
858 (#b111 (if (not minibuffer-completion-confirm)
859 (exit-minibuffer)
860 (minibuffer-message "Confirm")
861 nil))
862 (t nil))))))
863
864 (defun completion--try-word-completion (string table predicate point)
865 (let ((comp (completion-try-completion string table predicate point)))
866 (if (not (consp comp))
867 comp
868
869 ;; If completion finds next char not unique,
870 ;; consider adding a space or a hyphen.
871 (when (= (length string) (length (car comp)))
872 ;; Mark the added char with the `completion-word' property, so it
873 ;; can be handled specially by completion styles such as
874 ;; partial-completion.
875 ;; We used to remove `partial-completion' from completion-styles
876 ;; instead, but it was too blunt, leading to situations where SPC
877 ;; was the only insertable char at point but minibuffer-complete-word
878 ;; refused inserting it.
879 (let ((exts (mapcar (lambda (str) (propertize str 'completion-try-word t))
880 '(" " "-")))
881 (before (substring string 0 point))
882 (after (substring string point))
883 tem)
884 (while (and exts (not (consp tem)))
885 (setq tem (completion-try-completion
886 (concat before (pop exts) after)
887 table predicate (1+ point))))
888 (if (consp tem) (setq comp tem))))
889
890 ;; Completing a single word is actually more difficult than completing
891 ;; as much as possible, because we first have to find the "current
892 ;; position" in `completion' in order to find the end of the word
893 ;; we're completing. Normally, `string' is a prefix of `completion',
894 ;; which makes it trivial to find the position, but with fancier
895 ;; completion (plus env-var expansion, ...) `completion' might not
896 ;; look anything like `string' at all.
897 (let* ((comppoint (cdr comp))
898 (completion (car comp))
899 (before (substring string 0 point))
900 (combined (concat before "\n" completion)))
901 ;; Find in completion the longest text that was right before point.
902 (when (string-match "\\(.+\\)\n.*?\\1" combined)
903 (let* ((prefix (match-string 1 before))
904 ;; We used non-greedy match to make `rem' as long as possible.
905 (rem (substring combined (match-end 0)))
906 ;; Find in the remainder of completion the longest text
907 ;; that was right after point.
908 (after (substring string point))
909 (suffix (if (string-match "\\`\\(.+\\).*\n.*\\1"
910 (concat after "\n" rem))
911 (match-string 1 after))))
912 ;; The general idea is to try and guess what text was inserted
913 ;; at point by the completion. Problem is: if we guess wrong,
914 ;; we may end up treating as "added by completion" text that was
915 ;; actually painfully typed by the user. So if we then cut
916 ;; after the first word, we may throw away things the
917 ;; user wrote. So let's try to be as conservative as possible:
918 ;; only cut after the first word, if we're reasonably sure that
919 ;; our guess is correct.
920 ;; Note: a quick survey on emacs-devel seemed to indicate that
921 ;; nobody actually cares about the "word-at-a-time" feature of
922 ;; minibuffer-complete-word, whose real raison-d'être is that it
923 ;; tries to add "-" or " ". One more reason to only cut after
924 ;; the first word, if we're really sure we're right.
925 (when (and (or suffix (zerop (length after)))
926 (string-match (concat
927 ;; Make submatch 1 as small as possible
928 ;; to reduce the risk of cutting
929 ;; valuable text.
930 ".*" (regexp-quote prefix) "\\(.*?\\)"
931 (if suffix (regexp-quote suffix) "\\'"))
932 completion)
933 ;; The new point in `completion' should also be just
934 ;; before the suffix, otherwise something more complex
935 ;; is going on, and we're not sure where we are.
936 (eq (match-end 1) comppoint)
937 ;; (match-beginning 1)..comppoint is now the stretch
938 ;; of text in `completion' that was completed at point.
939 (string-match "\\W" completion (match-beginning 1))
940 ;; Is there really something to cut?
941 (> comppoint (match-end 0)))
942 ;; Cut after the first word.
943 (let ((cutpos (match-end 0)))
944 (setq completion (concat (substring completion 0 cutpos)
945 (substring completion comppoint)))
946 (setq comppoint cutpos)))))
947
948 (cons completion comppoint)))))
949
950
951 (defun minibuffer-complete-word ()
952 "Complete the minibuffer contents at most a single word.
953 After one word is completed as much as possible, a space or hyphen
954 is added, provided that matches some possible completion.
955 Return nil if there is no valid completion, else t."
956 (interactive)
957 (case (completion--do-completion 'completion--try-word-completion)
958 (#b000 nil)
959 (t t)))
960
961 (defface completions-annotations '((t :inherit italic))
962 "Face to use for annotations in the *Completions* buffer.")
963
964 (defcustom completions-format 'horizontal
965 "Define the appearance and sorting of completions.
966 If the value is `vertical', display completions sorted vertically
967 in columns in the *Completions* buffer.
968 If the value is `horizontal', display completions sorted
969 horizontally in alphabetical order, rather than down the screen."
970 :type '(choice (const horizontal) (const vertical))
971 :group 'minibuffer
972 :version "23.2")
973
974 (defun completion--insert-strings (strings)
975 "Insert a list of STRINGS into the current buffer.
976 Uses columns to keep the listing readable but compact.
977 It also eliminates runs of equal strings."
978 (when (consp strings)
979 (let* ((length (apply 'max
980 (mapcar (lambda (s)
981 (if (consp s)
982 (+ (string-width (car s))
983 (string-width (cadr s)))
984 (string-width s)))
985 strings)))
986 (window (get-buffer-window (current-buffer) 0))
987 (wwidth (if window (1- (window-width window)) 79))
988 (columns (min
989 ;; At least 2 columns; at least 2 spaces between columns.
990 (max 2 (/ wwidth (+ 2 length)))
991 ;; Don't allocate more columns than we can fill.
992 ;; Windows can't show less than 3 lines anyway.
993 (max 1 (/ (length strings) 2))))
994 (colwidth (/ wwidth columns))
995 (column 0)
996 (rows (/ (length strings) columns))
997 (row 0)
998 (laststring nil))
999 ;; The insertion should be "sensible" no matter what choices were made
1000 ;; for the parameters above.
1001 (dolist (str strings)
1002 (unless (equal laststring str) ; Remove (consecutive) duplicates.
1003 (setq laststring str)
1004 (let ((length (if (consp str)
1005 (+ (string-width (car str))
1006 (string-width (cadr str)))
1007 (string-width str))))
1008 (cond
1009 ((eq completions-format 'vertical)
1010 ;; Vertical format
1011 (when (> row rows)
1012 (forward-line (- -1 rows))
1013 (setq row 0 column (+ column colwidth)))
1014 (when (> column 0)
1015 (end-of-line)
1016 (while (> (current-column) column)
1017 (if (eobp)
1018 (insert "\n")
1019 (forward-line 1)
1020 (end-of-line)))
1021 (insert " \t")
1022 (set-text-properties (- (point) 1) (point)
1023 `(display (space :align-to ,column)))))
1024 (t
1025 ;; Horizontal format
1026 (unless (bolp)
1027 (if (< wwidth (+ (max colwidth length) column))
1028 ;; No space for `str' at point, move to next line.
1029 (progn (insert "\n") (setq column 0))
1030 (insert " \t")
1031 ;; Leave the space unpropertized so that in the case we're
1032 ;; already past the goal column, there is still
1033 ;; a space displayed.
1034 (set-text-properties (- (point) 1) (point)
1035 ;; We can't just set tab-width, because
1036 ;; completion-setup-function will kill
1037 ;; all local variables :-(
1038 `(display (space :align-to ,column)))
1039 nil))))
1040 (if (not (consp str))
1041 (put-text-property (point) (progn (insert str) (point))
1042 'mouse-face 'highlight)
1043 (put-text-property (point) (progn (insert (car str)) (point))
1044 'mouse-face 'highlight)
1045 (add-text-properties (point) (progn (insert (cadr str)) (point))
1046 '(mouse-face nil
1047 face completions-annotations)))
1048 (cond
1049 ((eq completions-format 'vertical)
1050 ;; Vertical format
1051 (if (> column 0)
1052 (forward-line)
1053 (insert "\n"))
1054 (setq row (1+ row)))
1055 (t
1056 ;; Horizontal format
1057 ;; Next column to align to.
1058 (setq column (+ column
1059 ;; Round up to a whole number of columns.
1060 (* colwidth (ceiling length colwidth))))))))))))
1061
1062 (defvar completion-common-substring nil)
1063 (make-obsolete-variable 'completion-common-substring nil "23.1")
1064
1065 (defvar completion-setup-hook nil
1066 "Normal hook run at the end of setting up a completion list buffer.
1067 When this hook is run, the current buffer is the one in which the
1068 command to display the completion list buffer was run.
1069 The completion list buffer is available as the value of `standard-output'.
1070 See also `display-completion-list'.")
1071
1072 (defface completions-first-difference
1073 '((t (:inherit bold)))
1074 "Face put on the first uncommon character in completions in *Completions* buffer."
1075 :group 'completion)
1076
1077 (defface completions-common-part
1078 '((t (:inherit default)))
1079 "Face put on the common prefix substring in completions in *Completions* buffer.
1080 The idea of `completions-common-part' is that you can use it to
1081 make the common parts less visible than normal, so that the rest
1082 of the differing parts is, by contrast, slightly highlighted."
1083 :group 'completion)
1084
1085 (defun completion-hilit-commonality (completions prefix-len base-size)
1086 (when completions
1087 (let ((com-str-len (- prefix-len (or base-size 0))))
1088 (nconc
1089 (mapcar
1090 (lambda (elem)
1091 (let ((str
1092 ;; Don't modify the string itself, but a copy, since the
1093 ;; the string may be read-only or used for other purposes.
1094 ;; Furthermore, since `completions' may come from
1095 ;; display-completion-list, `elem' may be a list.
1096 (if (consp elem)
1097 (car (setq elem (cons (copy-sequence (car elem))
1098 (cdr elem))))
1099 (setq elem (copy-sequence elem)))))
1100 (put-text-property 0
1101 ;; If completion-boundaries returns incorrect
1102 ;; values, all-completions may return strings
1103 ;; that don't contain the prefix.
1104 (min com-str-len (length str))
1105 'font-lock-face 'completions-common-part
1106 str)
1107 (if (> (length str) com-str-len)
1108 (put-text-property com-str-len (1+ com-str-len)
1109 'font-lock-face 'completions-first-difference
1110 str)))
1111 elem)
1112 completions)
1113 base-size))))
1114
1115 (defun display-completion-list (completions &optional common-substring)
1116 "Display the list of completions, COMPLETIONS, using `standard-output'.
1117 Each element may be just a symbol or string
1118 or may be a list of two strings to be printed as if concatenated.
1119 If it is a list of two strings, the first is the actual completion
1120 alternative, the second serves as annotation.
1121 `standard-output' must be a buffer.
1122 The actual completion alternatives, as inserted, are given `mouse-face'
1123 properties of `highlight'.
1124 At the end, this runs the normal hook `completion-setup-hook'.
1125 It can find the completion buffer in `standard-output'.
1126
1127 The obsolete optional arg COMMON-SUBSTRING, if non-nil, should be a string
1128 specifying a common substring for adding the faces
1129 `completions-first-difference' and `completions-common-part' to
1130 the completions buffer."
1131 (if common-substring
1132 (setq completions (completion-hilit-commonality
1133 completions (length common-substring)
1134 ;; We don't know the base-size.
1135 nil)))
1136 (if (not (bufferp standard-output))
1137 ;; This *never* (ever) happens, so there's no point trying to be clever.
1138 (with-temp-buffer
1139 (let ((standard-output (current-buffer))
1140 (completion-setup-hook nil))
1141 (display-completion-list completions common-substring))
1142 (princ (buffer-string)))
1143
1144 (with-current-buffer standard-output
1145 (goto-char (point-max))
1146 (if (null completions)
1147 (insert "There are no possible completions of what you have typed.")
1148 (insert "Possible completions are:\n")
1149 (completion--insert-strings completions))))
1150
1151 ;; The hilit used to be applied via completion-setup-hook, so there
1152 ;; may still be some code that uses completion-common-substring.
1153 (with-no-warnings
1154 (let ((completion-common-substring common-substring))
1155 (run-hooks 'completion-setup-hook)))
1156 nil)
1157
1158 (defvar completion-extra-properties nil
1159 "Property list of extra properties of the current completion job.
1160 These include:
1161 `:annotation-function': Function to add annotations in the completions buffer.
1162 The function takes a completion and should either return nil, or a string
1163 that will be displayed next to the completion. The function can access the
1164 completion data via `minibuffer-completion-table' and related variables.
1165 `:exit-function': Function to run after completion is performed.
1166 The function takes at least 2 parameters (STRING and STATUS) where STRING
1167 is the text to which the field was completed and STATUS indicates what
1168 kind of operation happened: if text is now complete it's `finished', if text
1169 cannot be further completed but completion is not finished, it's `sole', if
1170 text is a valid completion but may be further completed, it's `exact', and
1171 other STATUSes may be added in the future.")
1172
1173 (defvar completion-annotate-function
1174 nil
1175 ;; Note: there's a lot of scope as for when to add annotations and
1176 ;; what annotations to add. E.g. completing-help.el allowed adding
1177 ;; the first line of docstrings to M-x completion. But there's
1178 ;; a tension, since such annotations, while useful at times, can
1179 ;; actually drown the useful information.
1180 ;; So completion-annotate-function should be used parsimoniously, or
1181 ;; else only used upon a user's request (e.g. we could add a command
1182 ;; to completion-list-mode to add annotations to the current
1183 ;; completions).
1184 "Function to add annotations in the *Completions* buffer.
1185 The function takes a completion and should either return nil, or a string that
1186 will be displayed next to the completion. The function can access the
1187 completion table and predicates via `minibuffer-completion-table' and related
1188 variables.")
1189 (make-obsolete-variable 'completion-annotate-function
1190 'completion-extra-properties "24.1")
1191
1192 (defun completion--done (string &optional finished message)
1193 (let* ((exit-fun (plist-get completion-extra-properties :exit-function))
1194 (pre-msg (and exit-fun (current-message))))
1195 (assert (memq finished '(exact sole finished unknown)))
1196 ;; FIXME: exit-fun should receive `finished' as a parameter.
1197 (when exit-fun
1198 (when (eq finished 'unknown)
1199 (setq finished
1200 (if (eq (try-completion string
1201 minibuffer-completion-table
1202 minibuffer-completion-predicate)
1203 t)
1204 'finished 'exact)))
1205 (funcall exit-fun string finished))
1206 (when (and message
1207 ;; Don't output any message if the exit-fun already did so.
1208 (equal pre-msg (and exit-fun (current-message))))
1209 (completion--message message))))
1210
1211 (defun minibuffer-completion-help ()
1212 "Display a list of possible completions of the current minibuffer contents."
1213 (interactive)
1214 (message "Making completion list...")
1215 (let* ((start (field-beginning))
1216 (end (field-end))
1217 (string (field-string))
1218 (completions (completion-all-completions
1219 string
1220 minibuffer-completion-table
1221 minibuffer-completion-predicate
1222 (- (point) (field-beginning)))))
1223 (message nil)
1224 (if (or (null completions)
1225 (and (not (consp (cdr completions)))
1226 (equal (car completions) string)))
1227 (progn
1228 ;; If there are no completions, or if the current input is already
1229 ;; the sole completion, then hide (previous&stale) completions.
1230 (minibuffer-hide-completions)
1231 (ding)
1232 (minibuffer-message
1233 (if completions "Sole completion" "No completions")))
1234
1235 (let* ((last (last completions))
1236 (base-size (cdr last))
1237 (prefix (unless (zerop base-size) (substring string 0 base-size)))
1238 (global-af (or (plist-get completion-extra-properties
1239 :annotation-function)
1240 completion-annotate-function))
1241 ;; If the *Completions* buffer is shown in a new
1242 ;; window, mark it as softly-dedicated, so bury-buffer in
1243 ;; minibuffer-hide-completions will know whether to
1244 ;; delete the window or not.
1245 (display-buffer-mark-dedicated 'soft))
1246 (with-output-to-temp-buffer "*Completions*"
1247 ;; Remove the base-size tail because `sort' requires a properly
1248 ;; nil-terminated list.
1249 (when last (setcdr last nil))
1250 (setq completions (sort completions 'string-lessp))
1251 (setq completions
1252 (cond
1253 (global-af
1254 (mapcar (lambda (s)
1255 (let ((ann (funcall global-af s)))
1256 (if ann (list s ann) s)))
1257 completions))
1258 (t completions)))
1259
1260 (with-current-buffer standard-output
1261 (set (make-local-variable 'completion-base-position)
1262 (list (+ start base-size)
1263 ;; FIXME: We should pay attention to completion
1264 ;; boundaries here, but currently
1265 ;; completion-all-completions does not give us the
1266 ;; necessary information.
1267 end))
1268 (set (make-local-variable 'completion-list-insert-choice-function)
1269 (let ((ctable minibuffer-completion-table)
1270 (cpred minibuffer-completion-predicate)
1271 (cprops completion-extra-properties))
1272 (lambda (start end choice)
1273 (unless
1274 (or (zerop (length prefix))
1275 (equal prefix
1276 (buffer-substring-no-properties
1277 (max (point-min) (- start (length prefix)))
1278 start)))
1279 (message "*Completions* out of date"))
1280 ;; FIXME: Use `md' to do quoting&terminator here.
1281 (completion--replace start end choice)
1282 (let* ((minibuffer-completion-table ctable)
1283 (minibuffer-completion-predicate cpred)
1284 (completion-extra-properties cprops)
1285 (result (concat prefix choice))
1286 (bounds (completion-boundaries
1287 result ctable cpred "")))
1288 ;; If the completion introduces a new field, then
1289 ;; completion is not finished.
1290 (completion--done result
1291 (if (eq (car bounds) (length result))
1292 'exact 'finished)))))))
1293
1294 (display-completion-list completions))))
1295 nil))
1296
1297 (defun minibuffer-hide-completions ()
1298 "Get rid of an out-of-date *Completions* buffer."
1299 ;; FIXME: We could/should use minibuffer-scroll-window here, but it
1300 ;; can also point to the minibuffer-parent-window, so it's a bit tricky.
1301 (let ((win (get-buffer-window "*Completions*" 0)))
1302 (if win (with-selected-window win (bury-buffer)))))
1303
1304 (defun exit-minibuffer ()
1305 "Terminate this minibuffer argument."
1306 (interactive)
1307 ;; If the command that uses this has made modifications in the minibuffer,
1308 ;; we don't want them to cause deactivation of the mark in the original
1309 ;; buffer.
1310 ;; A better solution would be to make deactivate-mark buffer-local
1311 ;; (or to turn it into a list of buffers, ...), but in the mean time,
1312 ;; this should do the trick in most cases.
1313 (setq deactivate-mark nil)
1314 (throw 'exit nil))
1315
1316 (defun self-insert-and-exit ()
1317 "Terminate minibuffer input."
1318 (interactive)
1319 (if (characterp last-command-event)
1320 (call-interactively 'self-insert-command)
1321 (ding))
1322 (exit-minibuffer))
1323
1324 (defvar completion-in-region-functions nil
1325 "Wrapper hook around `completion-in-region'.
1326 The functions on this special hook are called with 5 arguments:
1327 NEXT-FUN START END COLLECTION PREDICATE.
1328 NEXT-FUN is a function of four arguments (START END COLLECTION PREDICATE)
1329 that performs the default operation. The other four arguments are like
1330 the ones passed to `completion-in-region'. The functions on this hook
1331 are expected to perform completion on START..END using COLLECTION
1332 and PREDICATE, either by calling NEXT-FUN or by doing it themselves.")
1333
1334 (defvar completion-in-region--data nil)
1335
1336 (defvar completion-in-region-mode-predicate nil
1337 "Predicate to tell `completion-in-region-mode' when to exit.
1338 It is called with no argument and should return nil when
1339 `completion-in-region-mode' should exit (and hence pop down
1340 the *Completions* buffer).")
1341
1342 (defvar completion-in-region-mode--predicate nil
1343 "Copy of the value of `completion-in-region-mode-predicate'.
1344 This holds the value `completion-in-region-mode-predicate' had when
1345 we entered `completion-in-region-mode'.")
1346
1347 (defun completion-in-region (start end collection &optional predicate)
1348 "Complete the text between START and END using COLLECTION.
1349 Return nil if there is no valid completion, else t.
1350 Point needs to be somewhere between START and END."
1351 (assert (<= start (point)) (<= (point) end))
1352 (with-wrapper-hook
1353 ;; FIXME: Maybe we should use this hook to provide a "display
1354 ;; completions" operation as well.
1355 completion-in-region-functions (start end collection predicate)
1356 (let ((minibuffer-completion-table collection)
1357 (minibuffer-completion-predicate predicate)
1358 (ol (make-overlay start end nil nil t)))
1359 (overlay-put ol 'field 'completion)
1360 (when completion-in-region-mode-predicate
1361 (completion-in-region-mode 1)
1362 (setq completion-in-region--data
1363 (list (current-buffer) start end collection)))
1364 (unwind-protect
1365 (call-interactively 'minibuffer-complete)
1366 (delete-overlay ol)))))
1367
1368 (defvar completion-in-region-mode-map
1369 (let ((map (make-sparse-keymap)))
1370 ;; FIXME: Only works if completion-in-region-mode was activated via
1371 ;; completion-at-point called directly.
1372 (define-key map "?" 'completion-help-at-point)
1373 (define-key map "\t" 'completion-at-point)
1374 map)
1375 "Keymap activated during `completion-in-region'.")
1376
1377 ;; It is difficult to know when to exit completion-in-region-mode (i.e. hide
1378 ;; the *Completions*).
1379 ;; - lisp-mode: never.
1380 ;; - comint: only do it if you hit SPC at the right time.
1381 ;; - pcomplete: pop it down on SPC or after some time-delay.
1382 ;; - semantic: use a post-command-hook check similar to this one.
1383 (defun completion-in-region--postch ()
1384 (or unread-command-events ;Don't pop down the completions in the middle of
1385 ;mouse-drag-region/mouse-set-point.
1386 (and completion-in-region--data
1387 (and (eq (car completion-in-region--data)
1388 (current-buffer))
1389 (>= (point) (nth 1 completion-in-region--data))
1390 (<= (point)
1391 (save-excursion
1392 (goto-char (nth 2 completion-in-region--data))
1393 (line-end-position)))
1394 (funcall completion-in-region-mode--predicate)))
1395 (completion-in-region-mode -1)))
1396
1397 ;; (defalias 'completion-in-region--prech 'completion-in-region--postch)
1398
1399 (define-minor-mode completion-in-region-mode
1400 "Transient minor mode used during `completion-in-region'."
1401 :global t
1402 (setq completion-in-region--data nil)
1403 ;; (remove-hook 'pre-command-hook #'completion-in-region--prech)
1404 (remove-hook 'post-command-hook #'completion-in-region--postch)
1405 (setq minor-mode-overriding-map-alist
1406 (delq (assq 'completion-in-region-mode minor-mode-overriding-map-alist)
1407 minor-mode-overriding-map-alist))
1408 (if (null completion-in-region-mode)
1409 (unless (equal "*Completions*" (buffer-name (window-buffer)))
1410 (minibuffer-hide-completions))
1411 ;; (add-hook 'pre-command-hook #'completion-in-region--prech)
1412 (assert completion-in-region-mode-predicate)
1413 (setq completion-in-region-mode--predicate
1414 completion-in-region-mode-predicate)
1415 (add-hook 'post-command-hook #'completion-in-region--postch)
1416 (push `(completion-in-region-mode . ,completion-in-region-mode-map)
1417 minor-mode-overriding-map-alist)))
1418
1419 ;; Define-minor-mode added our keymap to minor-mode-map-alist, but we want it
1420 ;; on minor-mode-overriding-map-alist instead.
1421 (setq minor-mode-map-alist
1422 (delq (assq 'completion-in-region-mode minor-mode-map-alist)
1423 minor-mode-map-alist))
1424
1425 (defvar completion-at-point-functions '(tags-completion-at-point-function)
1426 "Special hook to find the completion table for the thing at point.
1427 Each function on this hook is called in turns without any argument and should
1428 return either nil to mean that it is not applicable at point,
1429 or a function of no argument to perform completion (discouraged),
1430 or a list of the form (START END COLLECTION &rest PROPS) where
1431 START and END delimit the entity to complete and should include point,
1432 COLLECTION is the completion table to use to complete it, and
1433 PROPS is a property list for additional information.
1434 Currently supported properties are all the properties that can appear in
1435 `completion-extra-properties' plus:
1436 `:predicate' a predicate that completion candidates need to satisfy.
1437 `:exclusive' If `no', means that if the completion data does not match the
1438 text at point failure, then instead of reporting a completion failure,
1439 the completion should try the next completion function.")
1440
1441 (defvar completion--capf-misbehave-funs nil
1442 "List of functions found on `completion-at-point-functions' that misbehave.
1443 These are functions that neither return completion data nor a completion
1444 function but instead perform completion right away.")
1445 (defvar completion--capf-safe-funs nil
1446 "List of well-behaved functions found on `completion-at-point-functions'.
1447 These are functions which return proper completion data rather than
1448 a completion function or god knows what else.")
1449
1450 (defun completion--capf-wrapper (fun which)
1451 ;; FIXME: The safe/misbehave handling assumes that a given function will
1452 ;; always return the same kind of data, but this breaks down with functions
1453 ;; like comint-completion-at-point or mh-letter-completion-at-point, which
1454 ;; could be sometimes safe and sometimes misbehaving (and sometimes neither).
1455 (if (case which
1456 (all t)
1457 (safe (member fun completion--capf-safe-funs))
1458 (optimist (not (member fun completion--capf-misbehave-funs))))
1459 (let ((res (funcall fun)))
1460 (cond
1461 ((and (consp res) (not (functionp res)))
1462 (unless (member fun completion--capf-safe-funs)
1463 (push fun completion--capf-safe-funs))
1464 (and (eq 'no (plist-get (nthcdr 3 res) :exclusive))
1465 ;; FIXME: Here we'd need to decide whether there are
1466 ;; valid completions against the current text. But this depends
1467 ;; on the actual completion UI (e.g. with the default completion
1468 ;; it depends on completion-style) ;-(
1469 ;; We approximate this result by checking whether prefix
1470 ;; completion might work, which means that non-prefix completion
1471 ;; will not work (or not right) for completion functions that
1472 ;; are non-exclusive.
1473 (null (try-completion (buffer-substring-no-properties
1474 (car res) (point))
1475 (nth 2 res)
1476 (plist-get (nthcdr 3 res) :predicate)))
1477 (setq res nil)))
1478 ((not (or (listp res) (functionp res)))
1479 (unless (member fun completion--capf-misbehave-funs)
1480 (message
1481 "Completion function %S uses a deprecated calling convention" fun)
1482 (push fun completion--capf-misbehave-funs))))
1483 (if res (cons fun res)))))
1484
1485 (defun completion-at-point ()
1486 "Perform completion on the text around point.
1487 The completion method is determined by `completion-at-point-functions'."
1488 (interactive)
1489 (let ((res (run-hook-wrapped 'completion-at-point-functions
1490 #'completion--capf-wrapper 'all)))
1491 (pcase res
1492 (`(,_ . ,(and (pred functionp) f)) (funcall f))
1493 (`(,hookfun . (,start ,end ,collection . ,plist))
1494 (let* ((completion-extra-properties plist)
1495 (completion-in-region-mode-predicate
1496 (lambda ()
1497 ;; We're still in the same completion field.
1498 (eq (car-safe (funcall hookfun)) start))))
1499 (completion-in-region start end collection
1500 (plist-get plist :predicate))))
1501 ;; Maybe completion already happened and the function returned t.
1502 (_ (cdr res)))))
1503
1504 (defun completion-help-at-point ()
1505 "Display the completions on the text around point.
1506 The completion method is determined by `completion-at-point-functions'."
1507 (interactive)
1508 (let ((res (run-hook-wrapped 'completion-at-point-functions
1509 ;; Ignore misbehaving functions.
1510 #'completion--capf-wrapper 'optimist)))
1511 (pcase res
1512 (`(,_ . ,(and (pred functionp) f))
1513 (message "Don't know how to show completions for %S" f))
1514 (`(,hookfun . (,start ,end ,collection . ,plist))
1515 (let* ((minibuffer-completion-table collection)
1516 (minibuffer-completion-predicate (plist-get plist :predicate))
1517 (completion-extra-properties plist)
1518 (completion-in-region-mode-predicate
1519 (lambda ()
1520 ;; We're still in the same completion field.
1521 (eq (car-safe (funcall hookfun)) start)))
1522 (ol (make-overlay start end nil nil t)))
1523 ;; FIXME: We should somehow (ab)use completion-in-region-function or
1524 ;; introduce a corresponding hook (plus another for word-completion,
1525 ;; and another for force-completion, maybe?).
1526 (overlay-put ol 'field 'completion)
1527 (completion-in-region-mode 1)
1528 (setq completion-in-region--data
1529 (list (current-buffer) start end collection))
1530 (unwind-protect
1531 (call-interactively 'minibuffer-completion-help)
1532 (delete-overlay ol))))
1533 (`(,hookfun . ,_)
1534 ;; The hook function already performed completion :-(
1535 ;; Not much we can do at this point.
1536 (message "%s already performed completion!" hookfun)
1537 nil)
1538 (_ (message "Nothing to complete at point")))))
1539
1540 ;;; Key bindings.
1541
1542 (define-obsolete-variable-alias 'minibuffer-local-must-match-filename-map
1543 'minibuffer-local-filename-must-match-map "23.1")
1544
1545 (let ((map minibuffer-local-map))
1546 (define-key map "\C-g" 'abort-recursive-edit)
1547 (define-key map "\r" 'exit-minibuffer)
1548 (define-key map "\n" 'exit-minibuffer))
1549
1550 (let ((map minibuffer-local-completion-map))
1551 (define-key map "\t" 'minibuffer-complete)
1552 ;; M-TAB is already abused for many other purposes, so we should find
1553 ;; another binding for it.
1554 ;; (define-key map "\e\t" 'minibuffer-force-complete)
1555 (define-key map " " 'minibuffer-complete-word)
1556 (define-key map "?" 'minibuffer-completion-help))
1557
1558 (let ((map minibuffer-local-must-match-map))
1559 (define-key map "\r" 'minibuffer-complete-and-exit)
1560 (define-key map "\n" 'minibuffer-complete-and-exit))
1561
1562 (let ((map minibuffer-local-filename-completion-map))
1563 (define-key map " " nil))
1564 (let ((map minibuffer-local-filename-must-match-map))
1565 (define-key map " " nil))
1566
1567 (let ((map minibuffer-local-ns-map))
1568 (define-key map " " 'exit-minibuffer)
1569 (define-key map "\t" 'exit-minibuffer)
1570 (define-key map "?" 'self-insert-and-exit))
1571
1572 ;;; Completion tables.
1573
1574 (defun minibuffer--double-dollars (str)
1575 (replace-regexp-in-string "\\$" "$$" str))
1576
1577 (defun completion--make-envvar-table ()
1578 (mapcar (lambda (enventry)
1579 (substring enventry 0 (string-match-p "=" enventry)))
1580 process-environment))
1581
1582 (defconst completion--embedded-envvar-re
1583 (concat "\\(?:^\\|[^$]\\(?:\\$\\$\\)*\\)"
1584 "$\\([[:alnum:]_]*\\|{\\([^}]*\\)\\)\\'"))
1585
1586 (defun completion--embedded-envvar-table (string _pred action)
1587 "Completion table for envvars embedded in a string.
1588 The envvar syntax (and escaping) rules followed by this table are the
1589 same as `substitute-in-file-name'."
1590 ;; We ignore `pred', because the predicates passed to us via
1591 ;; read-file-name-internal are not 100% correct and fail here:
1592 ;; e.g. we get predicates like file-directory-p there, whereas the filename
1593 ;; completed needs to be passed through substitute-in-file-name before it
1594 ;; can be passed to file-directory-p.
1595 (when (string-match completion--embedded-envvar-re string)
1596 (let* ((beg (or (match-beginning 2) (match-beginning 1)))
1597 (table (completion--make-envvar-table))
1598 (prefix (substring string 0 beg)))
1599 (cond
1600 ((eq action 'lambda)
1601 ;; This table is expected to be used in conjunction with some
1602 ;; other table that provides the "main" completion. Let the
1603 ;; other table handle the test-completion case.
1604 nil)
1605 ((eq (car-safe action) 'boundaries)
1606 ;; Only return boundaries if there's something to complete,
1607 ;; since otherwise when we're used in
1608 ;; completion-table-in-turn, we could return boundaries and
1609 ;; let some subsequent table return a list of completions.
1610 ;; FIXME: Maybe it should rather be fixed in
1611 ;; completion-table-in-turn instead, but it's difficult to
1612 ;; do it efficiently there.
1613 (when (try-completion (substring string beg) table nil)
1614 ;; Compute the boundaries of the subfield to which this
1615 ;; completion applies.
1616 (let ((suffix (cdr action)))
1617 (list* 'boundaries
1618 (or (match-beginning 2) (match-beginning 1))
1619 (when (string-match "[^[:alnum:]_]" suffix)
1620 (match-beginning 0))))))
1621 (t
1622 (if (eq (aref string (1- beg)) ?{)
1623 (setq table (apply-partially 'completion-table-with-terminator
1624 "}" table)))
1625 ;; Even if file-name completion is case-insensitive, we want
1626 ;; envvar completion to be case-sensitive.
1627 (let ((completion-ignore-case nil))
1628 (completion-table-with-context
1629 prefix table (substring string beg) nil action)))))))
1630
1631 (defun completion-file-name-table (string pred action)
1632 "Completion table for file names."
1633 (ignore-errors
1634 (cond
1635 ((eq (car-safe action) 'boundaries)
1636 (let ((start (length (file-name-directory string)))
1637 (end (string-match-p "/" (cdr action))))
1638 (list* 'boundaries
1639 ;; if `string' is "C:" in w32, (file-name-directory string)
1640 ;; returns "C:/", so `start' is 3 rather than 2.
1641 ;; Not quite sure what is The Right Fix, but clipping it
1642 ;; back to 2 will work for this particular case. We'll
1643 ;; see if we can come up with a better fix when we bump
1644 ;; into more such problematic cases.
1645 (min start (length string)) end)))
1646
1647 ((eq action 'lambda)
1648 (if (zerop (length string))
1649 nil ;Not sure why it's here, but it probably doesn't harm.
1650 (funcall (or pred 'file-exists-p) string)))
1651
1652 (t
1653 (let* ((name (file-name-nondirectory string))
1654 (specdir (file-name-directory string))
1655 (realdir (or specdir default-directory)))
1656
1657 (cond
1658 ((null action)
1659 (let ((comp (file-name-completion name realdir pred)))
1660 (if (stringp comp)
1661 (concat specdir comp)
1662 comp)))
1663
1664 ((eq action t)
1665 (let ((all (file-name-all-completions name realdir)))
1666
1667 ;; Check the predicate, if necessary.
1668 (unless (memq pred '(nil file-exists-p))
1669 (let ((comp ())
1670 (pred
1671 (if (eq pred 'file-directory-p)
1672 ;; Brute-force speed up for directory checking:
1673 ;; Discard strings which don't end in a slash.
1674 (lambda (s)
1675 (let ((len (length s)))
1676 (and (> len 0) (eq (aref s (1- len)) ?/))))
1677 ;; Must do it the hard (and slow) way.
1678 pred)))
1679 (let ((default-directory (expand-file-name realdir)))
1680 (dolist (tem all)
1681 (if (funcall pred tem) (push tem comp))))
1682 (setq all (nreverse comp))))
1683
1684 all))))))))
1685
1686 (defvar read-file-name-predicate nil
1687 "Current predicate used by `read-file-name-internal'.")
1688 (make-obsolete-variable 'read-file-name-predicate
1689 "use the regular PRED argument" "23.2")
1690
1691 (defun completion--file-name-table (string pred action)
1692 "Internal subroutine for `read-file-name'. Do not call this.
1693 This is a completion table for file names, like `completion-file-name-table'
1694 except that it passes the file name through `substitute-in-file-name'."
1695 (cond
1696 ((eq (car-safe action) 'boundaries)
1697 ;; For the boundaries, we can't really delegate to
1698 ;; substitute-in-file-name+completion-file-name-table and then fix
1699 ;; them up (as we do for the other actions), because it would
1700 ;; require us to track the relationship between `str' and
1701 ;; `string', which is difficult. And in any case, if
1702 ;; substitute-in-file-name turns "fo-$TO-ba" into "fo-o/b-ba",
1703 ;; there's no way for us to return proper boundaries info, because
1704 ;; the boundary is not (yet) in `string'.
1705 ;;
1706 ;; FIXME: Actually there is a way to return correct boundaries
1707 ;; info, at the condition of modifying the all-completions
1708 ;; return accordingly. But for now, let's not bother.
1709 (completion-file-name-table string pred action))
1710
1711 (t
1712 (let* ((default-directory
1713 (if (stringp pred)
1714 ;; It used to be that `pred' was abused to pass `dir'
1715 ;; as an argument.
1716 (prog1 (file-name-as-directory (expand-file-name pred))
1717 (setq pred nil))
1718 default-directory))
1719 (str (condition-case nil
1720 (substitute-in-file-name string)
1721 (error string)))
1722 (comp (completion-file-name-table
1723 str
1724 (with-no-warnings (or pred read-file-name-predicate))
1725 action)))
1726
1727 (cond
1728 ((stringp comp)
1729 ;; Requote the $s before returning the completion.
1730 (minibuffer--double-dollars comp))
1731 ((and (null action) comp
1732 ;; Requote the $s before checking for changes.
1733 (setq str (minibuffer--double-dollars str))
1734 (not (string-equal string str)))
1735 ;; If there's no real completion, but substitute-in-file-name
1736 ;; changed the string, then return the new string.
1737 str)
1738 (t comp))))))
1739
1740 (defalias 'read-file-name-internal
1741 (completion-table-in-turn 'completion--embedded-envvar-table
1742 'completion--file-name-table)
1743 "Internal subroutine for `read-file-name'. Do not call this.")
1744
1745 (defvar read-file-name-function 'read-file-name-default
1746 "The function called by `read-file-name' to do its work.
1747 It should accept the same arguments as `read-file-name'.")
1748
1749 (defcustom read-file-name-completion-ignore-case
1750 (if (memq system-type '(ms-dos windows-nt darwin cygwin))
1751 t nil)
1752 "Non-nil means when reading a file name completion ignores case."
1753 :group 'minibuffer
1754 :type 'boolean
1755 :version "22.1")
1756
1757 (defcustom insert-default-directory t
1758 "Non-nil means when reading a filename start with default dir in minibuffer.
1759
1760 When the initial minibuffer contents show a name of a file or a directory,
1761 typing RETURN without editing the initial contents is equivalent to typing
1762 the default file name.
1763
1764 If this variable is non-nil, the minibuffer contents are always
1765 initially non-empty, and typing RETURN without editing will fetch the
1766 default name, if one is provided. Note however that this default name
1767 is not necessarily the same as initial contents inserted in the minibuffer,
1768 if the initial contents is just the default directory.
1769
1770 If this variable is nil, the minibuffer often starts out empty. In
1771 that case you may have to explicitly fetch the next history element to
1772 request the default name; typing RETURN without editing will leave
1773 the minibuffer empty.
1774
1775 For some commands, exiting with an empty minibuffer has a special meaning,
1776 such as making the current buffer visit no file in the case of
1777 `set-visited-file-name'."
1778 :group 'minibuffer
1779 :type 'boolean)
1780
1781 ;; Not always defined, but only called if next-read-file-uses-dialog-p says so.
1782 (declare-function x-file-dialog "xfns.c"
1783 (prompt dir &optional default-filename mustmatch only-dir-p))
1784
1785 (defun read-file-name--defaults (&optional dir initial)
1786 (let ((default
1787 (cond
1788 ;; With non-nil `initial', use `dir' as the first default.
1789 ;; Essentially, this mean reversing the normal order of the
1790 ;; current directory name and the current file name, i.e.
1791 ;; 1. with normal file reading:
1792 ;; 1.1. initial input is the current directory
1793 ;; 1.2. the first default is the current file name
1794 ;; 2. with non-nil `initial' (e.g. for `find-alternate-file'):
1795 ;; 2.2. initial input is the current file name
1796 ;; 2.1. the first default is the current directory
1797 (initial (abbreviate-file-name dir))
1798 ;; In file buffers, try to get the current file name
1799 (buffer-file-name
1800 (abbreviate-file-name buffer-file-name))))
1801 (file-name-at-point
1802 (run-hook-with-args-until-success 'file-name-at-point-functions)))
1803 (when file-name-at-point
1804 (setq default (delete-dups
1805 (delete "" (delq nil (list file-name-at-point default))))))
1806 ;; Append new defaults to the end of existing `minibuffer-default'.
1807 (append
1808 (if (listp minibuffer-default) minibuffer-default (list minibuffer-default))
1809 (if (listp default) default (list default)))))
1810
1811 (defun read-file-name (prompt &optional dir default-filename mustmatch initial predicate)
1812 "Read file name, prompting with PROMPT and completing in directory DIR.
1813 Value is not expanded---you must call `expand-file-name' yourself.
1814 Default name to DEFAULT-FILENAME if user exits the minibuffer with
1815 the same non-empty string that was inserted by this function.
1816 (If DEFAULT-FILENAME is omitted, the visited file name is used,
1817 except that if INITIAL is specified, that combined with DIR is used.
1818 If DEFAULT-FILENAME is a list of file names, the first file name is used.)
1819 If the user exits with an empty minibuffer, this function returns
1820 an empty string. (This can only happen if the user erased the
1821 pre-inserted contents or if `insert-default-directory' is nil.)
1822
1823 Fourth arg MUSTMATCH can take the following values:
1824 - nil means that the user can exit with any input.
1825 - t means that the user is not allowed to exit unless
1826 the input is (or completes to) an existing file.
1827 - `confirm' means that the user can exit with any input, but she needs
1828 to confirm her choice if the input is not an existing file.
1829 - `confirm-after-completion' means that the user can exit with any
1830 input, but she needs to confirm her choice if she called
1831 `minibuffer-complete' right before `minibuffer-complete-and-exit'
1832 and the input is not an existing file.
1833 - anything else behaves like t except that typing RET does not exit if it
1834 does non-null completion.
1835
1836 Fifth arg INITIAL specifies text to start with.
1837
1838 If optional sixth arg PREDICATE is non-nil, possible completions and
1839 the resulting file name must satisfy (funcall PREDICATE NAME).
1840 DIR should be an absolute directory name. It defaults to the value of
1841 `default-directory'.
1842
1843 If this command was invoked with the mouse, use a graphical file
1844 dialog if `use-dialog-box' is non-nil, and the window system or X
1845 toolkit in use provides a file dialog box, and DIR is not a
1846 remote file. For graphical file dialogs, any the special values
1847 of MUSTMATCH; `confirm' and `confirm-after-completion' are
1848 treated as equivalent to nil.
1849
1850 See also `read-file-name-completion-ignore-case'
1851 and `read-file-name-function'."
1852 (funcall (or read-file-name-function #'read-file-name-default)
1853 prompt dir default-filename mustmatch initial predicate))
1854
1855 (defun read-file-name-default (prompt &optional dir default-filename mustmatch initial predicate)
1856 "Default method for reading file names.
1857 See `read-file-name' for the meaning of the arguments."
1858 (unless dir (setq dir default-directory))
1859 (unless (file-name-absolute-p dir) (setq dir (expand-file-name dir)))
1860 (unless default-filename
1861 (setq default-filename (if initial (expand-file-name initial dir)
1862 buffer-file-name)))
1863 ;; If dir starts with user's homedir, change that to ~.
1864 (setq dir (abbreviate-file-name dir))
1865 ;; Likewise for default-filename.
1866 (if default-filename
1867 (setq default-filename
1868 (if (consp default-filename)
1869 (mapcar 'abbreviate-file-name default-filename)
1870 (abbreviate-file-name default-filename))))
1871 (let ((insdef (cond
1872 ((and insert-default-directory (stringp dir))
1873 (if initial
1874 (cons (minibuffer--double-dollars (concat dir initial))
1875 (length (minibuffer--double-dollars dir)))
1876 (minibuffer--double-dollars dir)))
1877 (initial (cons (minibuffer--double-dollars initial) 0)))))
1878
1879 (let ((completion-ignore-case read-file-name-completion-ignore-case)
1880 (minibuffer-completing-file-name t)
1881 (pred (or predicate 'file-exists-p))
1882 (add-to-history nil))
1883
1884 (let* ((val
1885 (if (or (not (next-read-file-uses-dialog-p))
1886 ;; Graphical file dialogs can't handle remote
1887 ;; files (Bug#99).
1888 (file-remote-p dir))
1889 ;; We used to pass `dir' to `read-file-name-internal' by
1890 ;; abusing the `predicate' argument. It's better to
1891 ;; just use `default-directory', but in order to avoid
1892 ;; changing `default-directory' in the current buffer,
1893 ;; we don't let-bind it.
1894 (let ((dir (file-name-as-directory
1895 (expand-file-name dir))))
1896 (minibuffer-with-setup-hook
1897 (lambda ()
1898 (setq default-directory dir)
1899 ;; When the first default in `minibuffer-default'
1900 ;; duplicates initial input `insdef',
1901 ;; reset `minibuffer-default' to nil.
1902 (when (equal (or (car-safe insdef) insdef)
1903 (or (car-safe minibuffer-default)
1904 minibuffer-default))
1905 (setq minibuffer-default
1906 (cdr-safe minibuffer-default)))
1907 ;; On the first request on `M-n' fill
1908 ;; `minibuffer-default' with a list of defaults
1909 ;; relevant for file-name reading.
1910 (set (make-local-variable 'minibuffer-default-add-function)
1911 (lambda ()
1912 (with-current-buffer
1913 (window-buffer (minibuffer-selected-window))
1914 (read-file-name--defaults dir initial)))))
1915 (completing-read prompt 'read-file-name-internal
1916 pred mustmatch insdef
1917 'file-name-history default-filename)))
1918 ;; If DEFAULT-FILENAME not supplied and DIR contains
1919 ;; a file name, split it.
1920 (let ((file (file-name-nondirectory dir))
1921 ;; When using a dialog, revert to nil and non-nil
1922 ;; interpretation of mustmatch. confirm options
1923 ;; need to be interpreted as nil, otherwise
1924 ;; it is impossible to create new files using
1925 ;; dialogs with the default settings.
1926 (dialog-mustmatch
1927 (not (memq mustmatch
1928 '(nil confirm confirm-after-completion)))))
1929 (when (and (not default-filename)
1930 (not (zerop (length file))))
1931 (setq default-filename file)
1932 (setq dir (file-name-directory dir)))
1933 (when default-filename
1934 (setq default-filename
1935 (expand-file-name (if (consp default-filename)
1936 (car default-filename)
1937 default-filename)
1938 dir)))
1939 (setq add-to-history t)
1940 (x-file-dialog prompt dir default-filename
1941 dialog-mustmatch
1942 (eq predicate 'file-directory-p)))))
1943
1944 (replace-in-history (eq (car-safe file-name-history) val)))
1945 ;; If completing-read returned the inserted default string itself
1946 ;; (rather than a new string with the same contents),
1947 ;; it has to mean that the user typed RET with the minibuffer empty.
1948 ;; In that case, we really want to return ""
1949 ;; so that commands such as set-visited-file-name can distinguish.
1950 (when (consp default-filename)
1951 (setq default-filename (car default-filename)))
1952 (when (eq val default-filename)
1953 ;; In this case, completing-read has not added an element
1954 ;; to the history. Maybe we should.
1955 (if (not replace-in-history)
1956 (setq add-to-history t))
1957 (setq val ""))
1958 (unless val (error "No file name specified"))
1959
1960 (if (and default-filename
1961 (string-equal val (if (consp insdef) (car insdef) insdef)))
1962 (setq val default-filename))
1963 (setq val (substitute-in-file-name val))
1964
1965 (if replace-in-history
1966 ;; Replace what Fcompleting_read added to the history
1967 ;; with what we will actually return. As an exception,
1968 ;; if that's the same as the second item in
1969 ;; file-name-history, it's really a repeat (Bug#4657).
1970 (let ((val1 (minibuffer--double-dollars val)))
1971 (if history-delete-duplicates
1972 (setcdr file-name-history
1973 (delete val1 (cdr file-name-history))))
1974 (if (string= val1 (cadr file-name-history))
1975 (pop file-name-history)
1976 (setcar file-name-history val1)))
1977 (if add-to-history
1978 ;; Add the value to the history--but not if it matches
1979 ;; the last value already there.
1980 (let ((val1 (minibuffer--double-dollars val)))
1981 (unless (and (consp file-name-history)
1982 (equal (car file-name-history) val1))
1983 (setq file-name-history
1984 (cons val1
1985 (if history-delete-duplicates
1986 (delete val1 file-name-history)
1987 file-name-history)))))))
1988 val))))
1989
1990 (defun internal-complete-buffer-except (&optional buffer)
1991 "Perform completion on all buffers excluding BUFFER.
1992 BUFFER nil or omitted means use the current buffer.
1993 Like `internal-complete-buffer', but removes BUFFER from the completion list."
1994 (let ((except (if (stringp buffer) buffer (buffer-name buffer))))
1995 (apply-partially 'completion-table-with-predicate
1996 'internal-complete-buffer
1997 (lambda (name)
1998 (not (equal (if (consp name) (car name) name) except)))
1999 nil)))
2000
2001 ;;; Old-style completion, used in Emacs-21 and Emacs-22.
2002
2003 (defun completion-emacs21-try-completion (string table pred _point)
2004 (let ((completion (try-completion string table pred)))
2005 (if (stringp completion)
2006 (cons completion (length completion))
2007 completion)))
2008
2009 (defun completion-emacs21-all-completions (string table pred _point)
2010 (completion-hilit-commonality
2011 (all-completions string table pred)
2012 (length string)
2013 (car (completion-boundaries string table pred ""))))
2014
2015 (defun completion-emacs22-try-completion (string table pred point)
2016 (let ((suffix (substring string point))
2017 (completion (try-completion (substring string 0 point) table pred)))
2018 (if (not (stringp completion))
2019 completion
2020 ;; Merge a trailing / in completion with a / after point.
2021 ;; We used to only do it for word completion, but it seems to make
2022 ;; sense for all completions.
2023 ;; Actually, claiming this feature was part of Emacs-22 completion
2024 ;; is pushing it a bit: it was only done in minibuffer-completion-word,
2025 ;; which was (by default) not bound during file completion, where such
2026 ;; slashes are most likely to occur.
2027 (if (and (not (zerop (length completion)))
2028 (eq ?/ (aref completion (1- (length completion))))
2029 (not (zerop (length suffix)))
2030 (eq ?/ (aref suffix 0)))
2031 ;; This leaves point after the / .
2032 (setq suffix (substring suffix 1)))
2033 (cons (concat completion suffix) (length completion)))))
2034
2035 (defun completion-emacs22-all-completions (string table pred point)
2036 (let ((beforepoint (substring string 0 point)))
2037 (completion-hilit-commonality
2038 (all-completions beforepoint table pred)
2039 point
2040 (car (completion-boundaries beforepoint table pred "")))))
2041
2042 ;;; Basic completion.
2043
2044 (defun completion--merge-suffix (completion point suffix)
2045 "Merge end of COMPLETION with beginning of SUFFIX.
2046 Simple generalization of the \"merge trailing /\" done in Emacs-22.
2047 Return the new suffix."
2048 (if (and (not (zerop (length suffix)))
2049 (string-match "\\(.+\\)\n\\1" (concat completion "\n" suffix)
2050 ;; Make sure we don't compress things to less
2051 ;; than we started with.
2052 point)
2053 ;; Just make sure we didn't match some other \n.
2054 (eq (match-end 1) (length completion)))
2055 (substring suffix (- (match-end 1) (match-beginning 1)))
2056 ;; Nothing to merge.
2057 suffix))
2058
2059 (defun completion-basic--pattern (beforepoint afterpoint bounds)
2060 (delete
2061 "" (list (substring beforepoint (car bounds))
2062 'point
2063 (substring afterpoint 0 (cdr bounds)))))
2064
2065 (defun completion-basic-try-completion (string table pred point)
2066 (let* ((beforepoint (substring string 0 point))
2067 (afterpoint (substring string point))
2068 (bounds (completion-boundaries beforepoint table pred afterpoint)))
2069 (if (zerop (cdr bounds))
2070 ;; `try-completion' may return a subtly different result
2071 ;; than `all+merge', so try to use it whenever possible.
2072 (let ((completion (try-completion beforepoint table pred)))
2073 (if (not (stringp completion))
2074 completion
2075 (cons
2076 (concat completion
2077 (completion--merge-suffix completion point afterpoint))
2078 (length completion))))
2079 (let* ((suffix (substring afterpoint (cdr bounds)))
2080 (prefix (substring beforepoint 0 (car bounds)))
2081 (pattern (delete
2082 "" (list (substring beforepoint (car bounds))
2083 'point
2084 (substring afterpoint 0 (cdr bounds)))))
2085 (all (completion-pcm--all-completions prefix pattern table pred)))
2086 (if minibuffer-completing-file-name
2087 (setq all (completion-pcm--filename-try-filter all)))
2088 (completion-pcm--merge-try pattern all prefix suffix)))))
2089
2090 (defun completion-basic-all-completions (string table pred point)
2091 (let* ((beforepoint (substring string 0 point))
2092 (afterpoint (substring string point))
2093 (bounds (completion-boundaries beforepoint table pred afterpoint))
2094 ;; (suffix (substring afterpoint (cdr bounds)))
2095 (prefix (substring beforepoint 0 (car bounds)))
2096 (pattern (delete
2097 "" (list (substring beforepoint (car bounds))
2098 'point
2099 (substring afterpoint 0 (cdr bounds)))))
2100 (all (completion-pcm--all-completions prefix pattern table pred)))
2101 (completion-hilit-commonality all point (car bounds))))
2102
2103 ;;; Partial-completion-mode style completion.
2104
2105 (defvar completion-pcm--delim-wild-regex nil
2106 "Regular expression matching delimiters controlling the partial-completion.
2107 Typically, this regular expression simply matches a delimiter, meaning
2108 that completion can add something at (match-beginning 0), but if it has
2109 a submatch 1, then completion can add something at (match-end 1).
2110 This is used when the delimiter needs to be of size zero (e.g. the transition
2111 from lowercase to uppercase characters).")
2112
2113 (defun completion-pcm--prepare-delim-re (delims)
2114 (setq completion-pcm--delim-wild-regex (concat "[" delims "*]")))
2115
2116 (defcustom completion-pcm-word-delimiters "-_./:| "
2117 "A string of characters treated as word delimiters for completion.
2118 Some arcane rules:
2119 If `]' is in this string, it must come first.
2120 If `^' is in this string, it must not come first.
2121 If `-' is in this string, it must come first or right after `]'.
2122 In other words, if S is this string, then `[S]' must be a valid Emacs regular
2123 expression (not containing character ranges like `a-z')."
2124 :set (lambda (symbol value)
2125 (set-default symbol value)
2126 ;; Refresh other vars.
2127 (completion-pcm--prepare-delim-re value))
2128 :initialize 'custom-initialize-reset
2129 :group 'minibuffer
2130 :type 'string)
2131
2132 (defcustom completion-pcm-complete-word-inserts-delimiters nil
2133 "Treat the SPC or - inserted by `minibuffer-complete-word' as delimiters.
2134 Those chars are treated as delimiters iff this variable is non-nil.
2135 I.e. if non-nil, M-x SPC will just insert a \"-\" in the minibuffer, whereas
2136 if nil, it will list all possible commands in *Completions* because none of
2137 the commands start with a \"-\" or a SPC."
2138 :type 'boolean)
2139
2140 (defun completion-pcm--pattern-trivial-p (pattern)
2141 (and (stringp (car pattern))
2142 ;; It can be followed by `point' and "" and still be trivial.
2143 (let ((trivial t))
2144 (dolist (elem (cdr pattern))
2145 (unless (member elem '(point ""))
2146 (setq trivial nil)))
2147 trivial)))
2148
2149 (defun completion-pcm--string->pattern (string &optional point)
2150 "Split STRING into a pattern.
2151 A pattern is a list where each element is either a string
2152 or a symbol chosen among `any', `star', `point', `prefix'."
2153 (if (and point (< point (length string)))
2154 (let ((prefix (substring string 0 point))
2155 (suffix (substring string point)))
2156 (append (completion-pcm--string->pattern prefix)
2157 '(point)
2158 (completion-pcm--string->pattern suffix)))
2159 (let* ((pattern nil)
2160 (p 0)
2161 (p0 p))
2162
2163 (while (and (setq p (string-match completion-pcm--delim-wild-regex
2164 string p))
2165 (or completion-pcm-complete-word-inserts-delimiters
2166 ;; If the char was added by minibuffer-complete-word,
2167 ;; then don't treat it as a delimiter, otherwise
2168 ;; "M-x SPC" ends up inserting a "-" rather than listing
2169 ;; all completions.
2170 (not (get-text-property p 'completion-try-word string))))
2171 ;; Usually, completion-pcm--delim-wild-regex matches a delimiter,
2172 ;; meaning that something can be added *before* it, but it can also
2173 ;; match a prefix and postfix, in which case something can be added
2174 ;; in-between (e.g. match [[:lower:]][[:upper:]]).
2175 ;; This is determined by the presence of a submatch-1 which delimits
2176 ;; the prefix.
2177 (if (match-end 1) (setq p (match-end 1)))
2178 (push (substring string p0 p) pattern)
2179 (if (eq (aref string p) ?*)
2180 (progn
2181 (push 'star pattern)
2182 (setq p0 (1+ p)))
2183 (push 'any pattern)
2184 (setq p0 p))
2185 (incf p))
2186
2187 ;; An empty string might be erroneously added at the beginning.
2188 ;; It should be avoided properly, but it's so easy to remove it here.
2189 (delete "" (nreverse (cons (substring string p0) pattern))))))
2190
2191 (defun completion-pcm--pattern->regex (pattern &optional group)
2192 (let ((re
2193 (concat "\\`"
2194 (mapconcat
2195 (lambda (x)
2196 (cond
2197 ((stringp x) (regexp-quote x))
2198 ((if (consp group) (memq x group) group) "\\(.*?\\)")
2199 (t ".*?")))
2200 pattern
2201 ""))))
2202 ;; Avoid pathological backtracking.
2203 (while (string-match "\\.\\*\\?\\(?:\\\\[()]\\)*\\(\\.\\*\\?\\)" re)
2204 (setq re (replace-match "" t t re 1)))
2205 re))
2206
2207 (defun completion-pcm--all-completions (prefix pattern table pred)
2208 "Find all completions for PATTERN in TABLE obeying PRED.
2209 PATTERN is as returned by `completion-pcm--string->pattern'."
2210 ;; (assert (= (car (completion-boundaries prefix table pred ""))
2211 ;; (length prefix)))
2212 ;; Find an initial list of possible completions.
2213 (if (completion-pcm--pattern-trivial-p pattern)
2214
2215 ;; Minibuffer contains no delimiters -- simple case!
2216 (all-completions (concat prefix (car pattern)) table pred)
2217
2218 ;; Use all-completions to do an initial cull. This is a big win,
2219 ;; since all-completions is written in C!
2220 (let* (;; Convert search pattern to a standard regular expression.
2221 (regex (completion-pcm--pattern->regex pattern))
2222 (case-fold-search completion-ignore-case)
2223 (completion-regexp-list (cons regex completion-regexp-list))
2224 (compl (all-completions
2225 (concat prefix (if (stringp (car pattern)) (car pattern) ""))
2226 table pred)))
2227 (if (not (functionp table))
2228 ;; The internal functions already obeyed completion-regexp-list.
2229 compl
2230 (let ((poss ()))
2231 (dolist (c compl)
2232 (when (string-match-p regex c) (push c poss)))
2233 poss)))))
2234
2235 (defun completion-pcm--hilit-commonality (pattern completions)
2236 (when completions
2237 (let* ((re (completion-pcm--pattern->regex pattern '(point)))
2238 (case-fold-search completion-ignore-case))
2239 (mapcar
2240 (lambda (str)
2241 ;; Don't modify the string itself.
2242 (setq str (copy-sequence str))
2243 (unless (string-match re str)
2244 (error "Internal error: %s does not match %s" re str))
2245 (let ((pos (or (match-beginning 1) (match-end 0))))
2246 (put-text-property 0 pos
2247 'font-lock-face 'completions-common-part
2248 str)
2249 (if (> (length str) pos)
2250 (put-text-property pos (1+ pos)
2251 'font-lock-face 'completions-first-difference
2252 str)))
2253 str)
2254 completions))))
2255
2256 (defun completion-pcm--find-all-completions (string table pred point
2257 &optional filter)
2258 "Find all completions for STRING at POINT in TABLE, satisfying PRED.
2259 POINT is a position inside STRING.
2260 FILTER is a function applied to the return value, that can be used, e.g. to
2261 filter out additional entries (because TABLE migth not obey PRED)."
2262 (unless filter (setq filter 'identity))
2263 (let* ((beforepoint (substring string 0 point))
2264 (afterpoint (substring string point))
2265 (bounds (completion-boundaries beforepoint table pred afterpoint))
2266 (prefix (substring beforepoint 0 (car bounds)))
2267 (suffix (substring afterpoint (cdr bounds)))
2268 firsterror)
2269 (setq string (substring string (car bounds) (+ point (cdr bounds))))
2270 (let* ((relpoint (- point (car bounds)))
2271 (pattern (completion-pcm--string->pattern string relpoint))
2272 (all (condition-case err
2273 (funcall filter
2274 (completion-pcm--all-completions
2275 prefix pattern table pred))
2276 (error (unless firsterror (setq firsterror err)) nil))))
2277 (when (and (null all)
2278 (> (car bounds) 0)
2279 (null (ignore-errors (try-completion prefix table pred))))
2280 ;; The prefix has no completions at all, so we should try and fix
2281 ;; that first.
2282 (let ((substring (substring prefix 0 -1)))
2283 (destructuring-bind (subpat suball subprefix _subsuffix)
2284 (completion-pcm--find-all-completions
2285 substring table pred (length substring) filter)
2286 (let ((sep (aref prefix (1- (length prefix))))
2287 ;; Text that goes between the new submatches and the
2288 ;; completion substring.
2289 (between nil))
2290 ;; Eliminate submatches that don't end with the separator.
2291 (dolist (submatch (prog1 suball (setq suball ())))
2292 (when (eq sep (aref submatch (1- (length submatch))))
2293 (push submatch suball)))
2294 (when suball
2295 ;; Update the boundaries and corresponding pattern.
2296 ;; We assume that all submatches result in the same boundaries
2297 ;; since we wouldn't know how to merge them otherwise anyway.
2298 ;; FIXME: COMPLETE REWRITE!!!
2299 (let* ((newbeforepoint
2300 (concat subprefix (car suball)
2301 (substring string 0 relpoint)))
2302 (leftbound (+ (length subprefix) (length (car suball))))
2303 (newbounds (completion-boundaries
2304 newbeforepoint table pred afterpoint)))
2305 (unless (or (and (eq (cdr bounds) (cdr newbounds))
2306 (eq (car newbounds) leftbound))
2307 ;; Refuse new boundaries if they step over
2308 ;; the submatch.
2309 (< (car newbounds) leftbound))
2310 ;; The new completed prefix does change the boundaries
2311 ;; of the completed substring.
2312 (setq suffix (substring afterpoint (cdr newbounds)))
2313 (setq string
2314 (concat (substring newbeforepoint (car newbounds))
2315 (substring afterpoint 0 (cdr newbounds))))
2316 (setq between (substring newbeforepoint leftbound
2317 (car newbounds)))
2318 (setq pattern (completion-pcm--string->pattern
2319 string
2320 (- (length newbeforepoint)
2321 (car newbounds)))))
2322 (dolist (submatch suball)
2323 (setq all (nconc (mapcar
2324 (lambda (s) (concat submatch between s))
2325 (funcall filter
2326 (completion-pcm--all-completions
2327 (concat subprefix submatch between)
2328 pattern table pred)))
2329 all)))
2330 ;; FIXME: This can come in handy for try-completion,
2331 ;; but isn't right for all-completions, since it lists
2332 ;; invalid completions.
2333 ;; (unless all
2334 ;; ;; Even though we found expansions in the prefix, none
2335 ;; ;; leads to a valid completion.
2336 ;; ;; Let's keep the expansions, tho.
2337 ;; (dolist (submatch suball)
2338 ;; (push (concat submatch between newsubstring) all)))
2339 ))
2340 (setq pattern (append subpat (list 'any (string sep))
2341 (if between (list between)) pattern))
2342 (setq prefix subprefix)))))
2343 (if (and (null all) firsterror)
2344 (signal (car firsterror) (cdr firsterror))
2345 (list pattern all prefix suffix)))))
2346
2347 (defun completion-pcm-all-completions (string table pred point)
2348 (destructuring-bind (pattern all &optional prefix _suffix)
2349 (completion-pcm--find-all-completions string table pred point)
2350 (when all
2351 (nconc (completion-pcm--hilit-commonality pattern all)
2352 (length prefix)))))
2353
2354 (defun completion--sreverse (str)
2355 "Like `reverse' but for a string STR rather than a list."
2356 (apply 'string (nreverse (mapcar 'identity str))))
2357
2358 (defun completion--common-suffix (strs)
2359 "Return the common suffix of the strings STRS."
2360 (completion--sreverse
2361 (try-completion
2362 ""
2363 (mapcar 'completion--sreverse strs))))
2364
2365 (defun completion-pcm--merge-completions (strs pattern)
2366 "Extract the commonality in STRS, with the help of PATTERN."
2367 ;; When completing while ignoring case, we want to try and avoid
2368 ;; completing "fo" to "foO" when completing against "FOO" (bug#4219).
2369 ;; So we try and make sure that the string we return is all made up
2370 ;; of text from the completions rather than part from the
2371 ;; completions and part from the input.
2372 ;; FIXME: This reduces the problems of inconsistent capitalization
2373 ;; but it doesn't fully fix it: we may still end up completing
2374 ;; "fo-ba" to "foo-BAR" or "FOO-bar" when completing against
2375 ;; '("foo-barr" "FOO-BARD").
2376 (cond
2377 ((null (cdr strs)) (list (car strs)))
2378 (t
2379 (let ((re (completion-pcm--pattern->regex pattern 'group))
2380 (ccs ())) ;Chopped completions.
2381
2382 ;; First chop each string into the parts corresponding to each
2383 ;; non-constant element of `pattern', using regexp-matching.
2384 (let ((case-fold-search completion-ignore-case))
2385 (dolist (str strs)
2386 (unless (string-match re str)
2387 (error "Internal error: %s doesn't match %s" str re))
2388 (let ((chopped ())
2389 (last 0)
2390 (i 1)
2391 next)
2392 (while (setq next (match-end i))
2393 (push (substring str last next) chopped)
2394 (setq last next)
2395 (setq i (1+ i)))
2396 ;; Add the text corresponding to the implicit trailing `any'.
2397 (push (substring str last) chopped)
2398 (push (nreverse chopped) ccs))))
2399
2400 ;; Then for each of those non-constant elements, extract the
2401 ;; commonality between them.
2402 (let ((res ())
2403 (fixed ""))
2404 ;; Make the implicit trailing `any' explicit.
2405 (dolist (elem (append pattern '(any)))
2406 (if (stringp elem)
2407 (setq fixed (concat fixed elem))
2408 (let ((comps ()))
2409 (dolist (cc (prog1 ccs (setq ccs nil)))
2410 (push (car cc) comps)
2411 (push (cdr cc) ccs))
2412 ;; Might improve the likelihood to avoid choosing
2413 ;; different capitalizations in different parts.
2414 ;; In practice, it doesn't seem to make any difference.
2415 (setq ccs (nreverse ccs))
2416 (let* ((prefix (try-completion fixed comps))
2417 (unique (or (and (eq prefix t) (setq prefix fixed))
2418 (eq t (try-completion prefix comps)))))
2419 (unless (equal prefix "") (push prefix res))
2420 ;; If there's only one completion, `elem' is not useful
2421 ;; any more: it can only match the empty string.
2422 ;; FIXME: in some cases, it may be necessary to turn an
2423 ;; `any' into a `star' because the surrounding context has
2424 ;; changed such that string->pattern wouldn't add an `any'
2425 ;; here any more.
2426 (unless unique
2427 (push elem res)
2428 (when (memq elem '(star point prefix))
2429 ;; Extract common suffix additionally to common prefix.
2430 ;; Only do it for `point', `star', and `prefix' since for
2431 ;; `any' it could lead to a merged completion that
2432 ;; doesn't itself match the candidates.
2433 (let ((suffix (completion--common-suffix comps)))
2434 (assert (stringp suffix))
2435 (unless (equal suffix "")
2436 (push suffix res)))))
2437 (setq fixed "")))))
2438 ;; We return it in reverse order.
2439 res)))))
2440
2441 (defun completion-pcm--pattern->string (pattern)
2442 (mapconcat (lambda (x) (cond
2443 ((stringp x) x)
2444 ((eq x 'star) "*")
2445 (t ""))) ;any, point, prefix.
2446 pattern
2447 ""))
2448
2449 ;; We want to provide the functionality of `try', but we use `all'
2450 ;; and then merge it. In most cases, this works perfectly, but
2451 ;; if the completion table doesn't consider the same completions in
2452 ;; `try' as in `all', then we have a problem. The most common such
2453 ;; case is for filename completion where completion-ignored-extensions
2454 ;; is only obeyed by the `try' code. We paper over the difference
2455 ;; here. Note that it is not quite right either: if the completion
2456 ;; table uses completion-table-in-turn, this filtering may take place
2457 ;; too late to correctly fallback from the first to the
2458 ;; second alternative.
2459 (defun completion-pcm--filename-try-filter (all)
2460 "Filter to adjust `all' file completion to the behavior of `try'."
2461 (when all
2462 (let ((try ())
2463 (re (concat "\\(?:\\`\\.\\.?/\\|"
2464 (regexp-opt completion-ignored-extensions)
2465 "\\)\\'")))
2466 (dolist (f all)
2467 (unless (string-match-p re f) (push f try)))
2468 (or try all))))
2469
2470
2471 (defun completion-pcm--merge-try (pattern all prefix suffix)
2472 (cond
2473 ((not (consp all)) all)
2474 ((and (not (consp (cdr all))) ;Only one completion.
2475 ;; Ignore completion-ignore-case here.
2476 (equal (completion-pcm--pattern->string pattern) (car all)))
2477 t)
2478 (t
2479 (let* ((mergedpat (completion-pcm--merge-completions all pattern))
2480 ;; `mergedpat' is in reverse order. Place new point (by
2481 ;; order of preference) either at the old point, or at
2482 ;; the last place where there's something to choose, or
2483 ;; at the very end.
2484 (pointpat (or (memq 'point mergedpat)
2485 (memq 'any mergedpat)
2486 (memq 'star mergedpat)
2487 ;; Not `prefix'.
2488 mergedpat))
2489 ;; New pos from the start.
2490 (newpos (length (completion-pcm--pattern->string pointpat)))
2491 ;; Do it afterwards because it changes `pointpat' by sideeffect.
2492 (merged (completion-pcm--pattern->string (nreverse mergedpat))))
2493
2494 (setq suffix (completion--merge-suffix merged newpos suffix))
2495 (cons (concat prefix merged suffix) (+ newpos (length prefix)))))))
2496
2497 (defun completion-pcm-try-completion (string table pred point)
2498 (destructuring-bind (pattern all prefix suffix)
2499 (completion-pcm--find-all-completions
2500 string table pred point
2501 (if minibuffer-completing-file-name
2502 'completion-pcm--filename-try-filter))
2503 (completion-pcm--merge-try pattern all prefix suffix)))
2504
2505 ;;; Substring completion
2506 ;; Mostly derived from the code of `basic' completion.
2507
2508 (defun completion-substring--all-completions (string table pred point)
2509 (let* ((beforepoint (substring string 0 point))
2510 (afterpoint (substring string point))
2511 (bounds (completion-boundaries beforepoint table pred afterpoint))
2512 (suffix (substring afterpoint (cdr bounds)))
2513 (prefix (substring beforepoint 0 (car bounds)))
2514 (basic-pattern (completion-basic--pattern
2515 beforepoint afterpoint bounds))
2516 (pattern (if (not (stringp (car basic-pattern)))
2517 basic-pattern
2518 (cons 'prefix basic-pattern)))
2519 (all (completion-pcm--all-completions prefix pattern table pred)))
2520 (list all pattern prefix suffix (car bounds))))
2521
2522 (defun completion-substring-try-completion (string table pred point)
2523 (destructuring-bind (all pattern prefix suffix _carbounds)
2524 (completion-substring--all-completions string table pred point)
2525 (if minibuffer-completing-file-name
2526 (setq all (completion-pcm--filename-try-filter all)))
2527 (completion-pcm--merge-try pattern all prefix suffix)))
2528
2529 (defun completion-substring-all-completions (string table pred point)
2530 (destructuring-bind (all pattern prefix _suffix _carbounds)
2531 (completion-substring--all-completions string table pred point)
2532 (when all
2533 (nconc (completion-pcm--hilit-commonality pattern all)
2534 (length prefix)))))
2535
2536 ;; Initials completion
2537 ;; Complete /ums to /usr/monnier/src or lch to list-command-history.
2538
2539 (defun completion-initials-expand (str table pred)
2540 (let ((bounds (completion-boundaries str table pred "")))
2541 (unless (or (zerop (length str))
2542 ;; Only check within the boundaries, since the
2543 ;; boundary char (e.g. /) might be in delim-regexp.
2544 (string-match completion-pcm--delim-wild-regex str
2545 (car bounds)))
2546 (if (zerop (car bounds))
2547 (mapconcat 'string str "-")
2548 ;; If there's a boundary, it's trickier. The main use-case
2549 ;; we consider here is file-name completion. We'd like
2550 ;; to expand ~/eee to ~/e/e/e and /eee to /e/e/e.
2551 ;; But at the same time, we don't want /usr/share/ae to expand
2552 ;; to /usr/share/a/e just because we mistyped "ae" for "ar",
2553 ;; so we probably don't want initials to touch anything that
2554 ;; looks like /usr/share/foo. As a heuristic, we just check that
2555 ;; the text before the boundary char is at most 1 char.
2556 ;; This allows both ~/eee and /eee and not much more.
2557 ;; FIXME: It sadly also disallows the use of ~/eee when that's
2558 ;; embedded within something else (e.g. "(~/eee" in Info node
2559 ;; completion or "ancestor:/eee" in bzr-revision completion).
2560 (when (< (car bounds) 3)
2561 (let ((sep (substring str (1- (car bounds)) (car bounds))))
2562 ;; FIXME: the above string-match checks the whole string, whereas
2563 ;; we end up only caring about the after-boundary part.
2564 (concat (substring str 0 (car bounds))
2565 (mapconcat 'string (substring str (car bounds)) sep))))))))
2566
2567 (defun completion-initials-all-completions (string table pred _point)
2568 (let ((newstr (completion-initials-expand string table pred)))
2569 (when newstr
2570 (completion-pcm-all-completions newstr table pred (length newstr)))))
2571
2572 (defun completion-initials-try-completion (string table pred _point)
2573 (let ((newstr (completion-initials-expand string table pred)))
2574 (when newstr
2575 (completion-pcm-try-completion newstr table pred (length newstr)))))
2576
2577 \f
2578 ;; Miscellaneous
2579
2580 (defun minibuffer-insert-file-name-at-point ()
2581 "Get a file name at point in original buffer and insert it to minibuffer."
2582 (interactive)
2583 (let ((file-name-at-point
2584 (with-current-buffer (window-buffer (minibuffer-selected-window))
2585 (run-hook-with-args-until-success 'file-name-at-point-functions))))
2586 (when file-name-at-point
2587 (insert file-name-at-point))))
2588
2589 (provide 'minibuffer)
2590
2591 ;;; minibuffer.el ends here