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