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