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