]> code.delx.au - gnu-emacs/blob - lisp/minibuffer.el
* lisp/shell.el: Use lexical-binding and std completion UI.
[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 ((null completion-show-inline-help) t)
661 ((eq completion-auto-help 'lazy)
662 (eq this-command last-command))
663 (t completion-auto-help))
664 (minibuffer-completion-help)
665 (minibuffer-message "Next char not unique")))
666 ;; If the last exact completion and this one were the same, it
667 ;; means we've already given a "Next char not unique" message
668 ;; and the user's hit TAB again, so now we give him help.
669 ((eq this-command last-command)
670 (if completion-auto-help (minibuffer-completion-help))))
671
672 (minibuffer--bitset completed t exact))))))))
673
674 (defun minibuffer-complete ()
675 "Complete the minibuffer contents as far as possible.
676 Return nil if there is no valid completion, else t.
677 If no characters can be completed, display a list of possible completions.
678 If you repeat this command after it displayed such a list,
679 scroll the window of possible completions."
680 (interactive)
681 ;; If the previous command was not this,
682 ;; mark the completion buffer obsolete.
683 (unless (eq this-command last-command)
684 (completion--flush-all-sorted-completions)
685 (setq minibuffer-scroll-window nil))
686
687 (cond
688 ;; If there's a fresh completion window with a live buffer,
689 ;; and this command is repeated, scroll that window.
690 ((window-live-p minibuffer-scroll-window)
691 (let ((window minibuffer-scroll-window))
692 (with-current-buffer (window-buffer window)
693 (if (pos-visible-in-window-p (point-max) window)
694 ;; If end is in view, scroll up to the beginning.
695 (set-window-start window (point-min) nil)
696 ;; Else scroll down one screen.
697 (scroll-other-window))
698 nil)))
699 ;; If we're cycling, keep on cycling.
700 ((and completion-cycling completion-all-sorted-completions)
701 (minibuffer-force-complete)
702 t)
703 (t (case (completion--do-completion)
704 (#b000 nil)
705 (#b001 (if completion-show-inline-help
706 (minibuffer-message "Sole completion"))
707 t)
708 (#b011 (if completion-show-inline-help
709 (minibuffer-message "Complete, but not unique"))
710 t)
711 (t t)))))
712
713 (defun completion--flush-all-sorted-completions (&rest _ignore)
714 (remove-hook 'after-change-functions
715 'completion--flush-all-sorted-completions t)
716 (setq completion-cycling nil)
717 (setq completion-all-sorted-completions nil))
718
719 (defun completion-all-sorted-completions ()
720 (or completion-all-sorted-completions
721 (let* ((start (field-beginning))
722 (end (field-end))
723 (all (completion-all-completions (buffer-substring start end)
724 minibuffer-completion-table
725 minibuffer-completion-predicate
726 (- (point) start)))
727 (last (last all))
728 (base-size (or (cdr last) 0)))
729 (when last
730 (setcdr last nil)
731 ;; Prefer shorter completions.
732 (setq all (sort all (lambda (c1 c2)
733 (let ((s1 (get-text-property
734 0 :completion-cycle-penalty c1))
735 (s2 (get-text-property
736 0 :completion-cycle-penalty c2)))
737 (if (eq s1 s2)
738 (< (length c1) (length c2))
739 (< (or s1 (length c1))
740 (or s2 (length c2))))))))
741 ;; Prefer recently used completions.
742 ;; FIXME: Additional sorting ideas:
743 ;; - for M-x, prefer commands that have no key binding.
744 (let ((hist (symbol-value minibuffer-history-variable)))
745 (setq all (sort all (lambda (c1 c2)
746 (> (length (member c1 hist))
747 (length (member c2 hist)))))))
748 ;; Cache the result. This is not just for speed, but also so that
749 ;; repeated calls to minibuffer-force-complete can cycle through
750 ;; all possibilities.
751 (add-hook 'after-change-functions
752 'completion--flush-all-sorted-completions nil t)
753 (setq completion-all-sorted-completions
754 (nconc all base-size))))))
755
756 (defun minibuffer-force-complete ()
757 "Complete the minibuffer to an exact match.
758 Repeated uses step through the possible completions."
759 (interactive)
760 ;; FIXME: Need to deal with the extra-size issue here as well.
761 ;; FIXME: ~/src/emacs/t<M-TAB>/lisp/minibuffer.el completes to
762 ;; ~/src/emacs/trunk/ and throws away lisp/minibuffer.el.
763 (let* ((start (field-beginning))
764 (end (field-end))
765 (all (completion-all-sorted-completions)))
766 (if (not (consp all))
767 (if completion-show-inline-help
768 (minibuffer-message
769 (if all "No more completions" "No completions")))
770 (setq completion-cycling t)
771 (goto-char end)
772 (insert (car all))
773 (delete-region (+ start (cdr (last all))) end)
774 ;; If completing file names, (car all) may be a directory, so we'd now
775 ;; have a new set of possible completions and might want to reset
776 ;; completion-all-sorted-completions to nil, but we prefer not to,
777 ;; so that repeated calls minibuffer-force-complete still cycle
778 ;; through the previous possible completions.
779 (let ((last (last all)))
780 (setcdr last (cons (car all) (cdr last)))
781 (setq completion-all-sorted-completions (cdr all))))))
782
783 (defvar minibuffer-confirm-exit-commands
784 '(minibuffer-complete minibuffer-complete-word PC-complete PC-complete-word)
785 "A list of commands which cause an immediately following
786 `minibuffer-complete-and-exit' to ask for extra confirmation.")
787
788 (defun minibuffer-complete-and-exit ()
789 "Exit if the minibuffer contains a valid completion.
790 Otherwise, try to complete the minibuffer contents. If
791 completion leads to a valid completion, a repetition of this
792 command will exit.
793
794 If `minibuffer-completion-confirm' is `confirm', do not try to
795 complete; instead, ask for confirmation and accept any input if
796 confirmed.
797 If `minibuffer-completion-confirm' is `confirm-after-completion',
798 do not try to complete; instead, ask for confirmation if the
799 preceding minibuffer command was a member of
800 `minibuffer-confirm-exit-commands', and accept the input
801 otherwise."
802 (interactive)
803 (let ((beg (field-beginning))
804 (end (field-end)))
805 (cond
806 ;; Allow user to specify null string
807 ((= beg end) (exit-minibuffer))
808 ((test-completion (buffer-substring beg end)
809 minibuffer-completion-table
810 minibuffer-completion-predicate)
811 ;; FIXME: completion-ignore-case has various slightly
812 ;; incompatible meanings. E.g. it can reflect whether the user
813 ;; wants completion to pay attention to case, or whether the
814 ;; string will be used in a context where case is significant.
815 ;; E.g. usually try-completion should obey the first, whereas
816 ;; test-completion should obey the second.
817 (when completion-ignore-case
818 ;; Fixup case of the field, if necessary.
819 (let* ((string (buffer-substring beg end))
820 (compl (try-completion
821 string
822 minibuffer-completion-table
823 minibuffer-completion-predicate)))
824 (when (and (stringp compl) (not (equal string compl))
825 ;; If it weren't for this piece of paranoia, I'd replace
826 ;; the whole thing with a call to do-completion.
827 ;; This is important, e.g. when the current minibuffer's
828 ;; content is a directory which only contains a single
829 ;; file, so `try-completion' actually completes to
830 ;; that file.
831 (= (length string) (length compl)))
832 (goto-char end)
833 (insert compl)
834 (delete-region beg end))))
835 (exit-minibuffer))
836
837 ((memq minibuffer-completion-confirm '(confirm confirm-after-completion))
838 ;; The user is permitted to exit with an input that's rejected
839 ;; by test-completion, after confirming her choice.
840 (if (or (eq last-command this-command)
841 ;; For `confirm-after-completion' we only ask for confirmation
842 ;; if trying to exit immediately after typing TAB (this
843 ;; catches most minibuffer typos).
844 (and (eq minibuffer-completion-confirm 'confirm-after-completion)
845 (not (memq last-command minibuffer-confirm-exit-commands))))
846 (exit-minibuffer)
847 (minibuffer-message "Confirm")
848 nil))
849
850 (t
851 ;; Call do-completion, but ignore errors.
852 (case (condition-case nil
853 (completion--do-completion)
854 (error 1))
855 ((#b001 #b011) (exit-minibuffer))
856 (#b111 (if (not minibuffer-completion-confirm)
857 (exit-minibuffer)
858 (minibuffer-message "Confirm")
859 nil))
860 (t nil))))))
861
862 (defun completion--try-word-completion (string table predicate point)
863 (let ((comp (completion-try-completion string table predicate point)))
864 (if (not (consp comp))
865 comp
866
867 ;; If completion finds next char not unique,
868 ;; consider adding a space or a hyphen.
869 (when (= (length string) (length (car comp)))
870 ;; Mark the added char with the `completion-word' property, so it
871 ;; can be handled specially by completion styles such as
872 ;; partial-completion.
873 ;; We used to remove `partial-completion' from completion-styles
874 ;; instead, but it was too blunt, leading to situations where SPC
875 ;; was the only insertable char at point but minibuffer-complete-word
876 ;; refused inserting it.
877 (let ((exts (mapcar (lambda (str) (propertize str 'completion-try-word t))
878 '(" " "-")))
879 (before (substring string 0 point))
880 (after (substring string point))
881 tem)
882 (while (and exts (not (consp tem)))
883 (setq tem (completion-try-completion
884 (concat before (pop exts) after)
885 table predicate (1+ point))))
886 (if (consp tem) (setq comp tem))))
887
888 ;; Completing a single word is actually more difficult than completing
889 ;; as much as possible, because we first have to find the "current
890 ;; position" in `completion' in order to find the end of the word
891 ;; we're completing. Normally, `string' is a prefix of `completion',
892 ;; which makes it trivial to find the position, but with fancier
893 ;; completion (plus env-var expansion, ...) `completion' might not
894 ;; look anything like `string' at all.
895 (let* ((comppoint (cdr comp))
896 (completion (car comp))
897 (before (substring string 0 point))
898 (combined (concat before "\n" completion)))
899 ;; Find in completion the longest text that was right before point.
900 (when (string-match "\\(.+\\)\n.*?\\1" combined)
901 (let* ((prefix (match-string 1 before))
902 ;; We used non-greedy match to make `rem' as long as possible.
903 (rem (substring combined (match-end 0)))
904 ;; Find in the remainder of completion the longest text
905 ;; that was right after point.
906 (after (substring string point))
907 (suffix (if (string-match "\\`\\(.+\\).*\n.*\\1"
908 (concat after "\n" rem))
909 (match-string 1 after))))
910 ;; The general idea is to try and guess what text was inserted
911 ;; at point by the completion. Problem is: if we guess wrong,
912 ;; we may end up treating as "added by completion" text that was
913 ;; actually painfully typed by the user. So if we then cut
914 ;; after the first word, we may throw away things the
915 ;; user wrote. So let's try to be as conservative as possible:
916 ;; only cut after the first word, if we're reasonably sure that
917 ;; our guess is correct.
918 ;; Note: a quick survey on emacs-devel seemed to indicate that
919 ;; nobody actually cares about the "word-at-a-time" feature of
920 ;; minibuffer-complete-word, whose real raison-d'être is that it
921 ;; tries to add "-" or " ". One more reason to only cut after
922 ;; the first word, if we're really sure we're right.
923 (when (and (or suffix (zerop (length after)))
924 (string-match (concat
925 ;; Make submatch 1 as small as possible
926 ;; to reduce the risk of cutting
927 ;; valuable text.
928 ".*" (regexp-quote prefix) "\\(.*?\\)"
929 (if suffix (regexp-quote suffix) "\\'"))
930 completion)
931 ;; The new point in `completion' should also be just
932 ;; before the suffix, otherwise something more complex
933 ;; is going on, and we're not sure where we are.
934 (eq (match-end 1) comppoint)
935 ;; (match-beginning 1)..comppoint is now the stretch
936 ;; of text in `completion' that was completed at point.
937 (string-match "\\W" completion (match-beginning 1))
938 ;; Is there really something to cut?
939 (> comppoint (match-end 0)))
940 ;; Cut after the first word.
941 (let ((cutpos (match-end 0)))
942 (setq completion (concat (substring completion 0 cutpos)
943 (substring completion comppoint)))
944 (setq comppoint cutpos)))))
945
946 (cons completion comppoint)))))
947
948
949 (defun minibuffer-complete-word ()
950 "Complete the minibuffer contents at most a single word.
951 After one word is completed as much as possible, a space or hyphen
952 is added, provided that matches some possible completion.
953 Return nil if there is no valid completion, else t."
954 (interactive)
955 (case (completion--do-completion 'completion--try-word-completion)
956 (#b000 nil)
957 (#b001 (if completion-show-inline-help
958 (minibuffer-message "Sole completion"))
959 t)
960 (#b011 (if completion-show-inline-help
961 (minibuffer-message "Complete, but not unique"))
962 t)
963 (t t)))
964
965 (defface completions-annotations '((t :inherit italic))
966 "Face to use for annotations in the *Completions* buffer.")
967
968 (defcustom completions-format 'horizontal
969 "Define the appearance and sorting of completions.
970 If the value is `vertical', display completions sorted vertically
971 in columns in the *Completions* buffer.
972 If the value is `horizontal', display completions sorted
973 horizontally in alphabetical order, rather than down the screen."
974 :type '(choice (const horizontal) (const vertical))
975 :group 'minibuffer
976 :version "23.2")
977
978 (defun completion--insert-strings (strings)
979 "Insert a list of STRINGS into the current buffer.
980 Uses columns to keep the listing readable but compact.
981 It also eliminates runs of equal strings."
982 (when (consp strings)
983 (let* ((length (apply 'max
984 (mapcar (lambda (s)
985 (if (consp s)
986 (+ (string-width (car s))
987 (string-width (cadr s)))
988 (string-width s)))
989 strings)))
990 (window (get-buffer-window (current-buffer) 0))
991 (wwidth (if window (1- (window-width window)) 79))
992 (columns (min
993 ;; At least 2 columns; at least 2 spaces between columns.
994 (max 2 (/ wwidth (+ 2 length)))
995 ;; Don't allocate more columns than we can fill.
996 ;; Windows can't show less than 3 lines anyway.
997 (max 1 (/ (length strings) 2))))
998 (colwidth (/ wwidth columns))
999 (column 0)
1000 (rows (/ (length strings) columns))
1001 (row 0)
1002 (laststring nil))
1003 ;; The insertion should be "sensible" no matter what choices were made
1004 ;; for the parameters above.
1005 (dolist (str strings)
1006 (unless (equal laststring str) ; Remove (consecutive) duplicates.
1007 (setq laststring str)
1008 (let ((length (if (consp str)
1009 (+ (string-width (car str))
1010 (string-width (cadr str)))
1011 (string-width str))))
1012 (cond
1013 ((eq completions-format 'vertical)
1014 ;; Vertical format
1015 (when (> row rows)
1016 (forward-line (- -1 rows))
1017 (setq row 0 column (+ column colwidth)))
1018 (when (> column 0)
1019 (end-of-line)
1020 (while (> (current-column) column)
1021 (if (eobp)
1022 (insert "\n")
1023 (forward-line 1)
1024 (end-of-line)))
1025 (insert " \t")
1026 (set-text-properties (- (point) 1) (point)
1027 `(display (space :align-to ,column)))))
1028 (t
1029 ;; Horizontal format
1030 (unless (bolp)
1031 (if (< wwidth (+ (max colwidth length) column))
1032 ;; No space for `str' at point, move to next line.
1033 (progn (insert "\n") (setq column 0))
1034 (insert " \t")
1035 ;; Leave the space unpropertized so that in the case we're
1036 ;; already past the goal column, there is still
1037 ;; a space displayed.
1038 (set-text-properties (- (point) 1) (point)
1039 ;; We can't just set tab-width, because
1040 ;; completion-setup-function will kill
1041 ;; all local variables :-(
1042 `(display (space :align-to ,column)))
1043 nil))))
1044 (if (not (consp str))
1045 (put-text-property (point) (progn (insert str) (point))
1046 'mouse-face 'highlight)
1047 (put-text-property (point) (progn (insert (car str)) (point))
1048 'mouse-face 'highlight)
1049 (add-text-properties (point) (progn (insert (cadr str)) (point))
1050 '(mouse-face nil
1051 face completions-annotations)))
1052 (cond
1053 ((eq completions-format 'vertical)
1054 ;; Vertical format
1055 (if (> column 0)
1056 (forward-line)
1057 (insert "\n"))
1058 (setq row (1+ row)))
1059 (t
1060 ;; Horizontal format
1061 ;; Next column to align to.
1062 (setq column (+ column
1063 ;; Round up to a whole number of columns.
1064 (* colwidth (ceiling length colwidth))))))))))))
1065
1066 (defvar completion-common-substring nil)
1067 (make-obsolete-variable 'completion-common-substring nil "23.1")
1068
1069 (defvar completion-setup-hook nil
1070 "Normal hook run at the end of setting up a completion list buffer.
1071 When this hook is run, the current buffer is the one in which the
1072 command to display the completion list buffer was run.
1073 The completion list buffer is available as the value of `standard-output'.
1074 See also `display-completion-list'.")
1075
1076 (defface completions-first-difference
1077 '((t (:inherit bold)))
1078 "Face put on the first uncommon character in completions in *Completions* buffer."
1079 :group 'completion)
1080
1081 (defface completions-common-part
1082 '((t (:inherit default)))
1083 "Face put on the common prefix substring in completions in *Completions* buffer.
1084 The idea of `completions-common-part' is that you can use it to
1085 make the common parts less visible than normal, so that the rest
1086 of the differing parts is, by contrast, slightly highlighted."
1087 :group 'completion)
1088
1089 (defun completion-hilit-commonality (completions prefix-len base-size)
1090 (when completions
1091 (let ((com-str-len (- prefix-len (or base-size 0))))
1092 (nconc
1093 (mapcar
1094 (lambda (elem)
1095 (let ((str
1096 ;; Don't modify the string itself, but a copy, since the
1097 ;; the string may be read-only or used for other purposes.
1098 ;; Furthermore, since `completions' may come from
1099 ;; display-completion-list, `elem' may be a list.
1100 (if (consp elem)
1101 (car (setq elem (cons (copy-sequence (car elem))
1102 (cdr elem))))
1103 (setq elem (copy-sequence elem)))))
1104 (put-text-property 0
1105 ;; If completion-boundaries returns incorrect
1106 ;; values, all-completions may return strings
1107 ;; that don't contain the prefix.
1108 (min com-str-len (length str))
1109 'font-lock-face 'completions-common-part
1110 str)
1111 (if (> (length str) com-str-len)
1112 (put-text-property com-str-len (1+ com-str-len)
1113 'font-lock-face 'completions-first-difference
1114 str)))
1115 elem)
1116 completions)
1117 base-size))))
1118
1119 (defun display-completion-list (completions &optional common-substring)
1120 "Display the list of completions, COMPLETIONS, using `standard-output'.
1121 Each element may be just a symbol or string
1122 or may be a list of two strings to be printed as if concatenated.
1123 If it is a list of two strings, the first is the actual completion
1124 alternative, the second serves as annotation.
1125 `standard-output' must be a buffer.
1126 The actual completion alternatives, as inserted, are given `mouse-face'
1127 properties of `highlight'.
1128 At the end, this runs the normal hook `completion-setup-hook'.
1129 It can find the completion buffer in `standard-output'.
1130
1131 The obsolete optional arg COMMON-SUBSTRING, if non-nil, should be a string
1132 specifying a common substring for adding the faces
1133 `completions-first-difference' and `completions-common-part' to
1134 the completions buffer."
1135 (if common-substring
1136 (setq completions (completion-hilit-commonality
1137 completions (length common-substring)
1138 ;; We don't know the base-size.
1139 nil)))
1140 (if (not (bufferp standard-output))
1141 ;; This *never* (ever) happens, so there's no point trying to be clever.
1142 (with-temp-buffer
1143 (let ((standard-output (current-buffer))
1144 (completion-setup-hook nil))
1145 (display-completion-list completions common-substring))
1146 (princ (buffer-string)))
1147
1148 (with-current-buffer standard-output
1149 (goto-char (point-max))
1150 (if (null completions)
1151 (insert "There are no possible completions of what you have typed.")
1152 (insert "Possible completions are:\n")
1153 (completion--insert-strings completions))))
1154
1155 ;; The hilit used to be applied via completion-setup-hook, so there
1156 ;; may still be some code that uses completion-common-substring.
1157 (with-no-warnings
1158 (let ((completion-common-substring common-substring))
1159 (run-hooks 'completion-setup-hook)))
1160 nil)
1161
1162 (defvar completion-annotate-function
1163 nil
1164 ;; Note: there's a lot of scope as for when to add annotations and
1165 ;; what annotations to add. E.g. completing-help.el allowed adding
1166 ;; the first line of docstrings to M-x completion. But there's
1167 ;; a tension, since such annotations, while useful at times, can
1168 ;; actually drown the useful information.
1169 ;; So completion-annotate-function should be used parsimoniously, or
1170 ;; else only used upon a user's request (e.g. we could add a command
1171 ;; to completion-list-mode to add annotations to the current
1172 ;; completions).
1173 "Function to add annotations in the *Completions* buffer.
1174 The function takes a completion and should either return nil, or a string that
1175 will be displayed next to the completion. The function can access the
1176 completion table and predicates via `minibuffer-completion-table' and related
1177 variables.")
1178
1179 (defun minibuffer-completion-help ()
1180 "Display a list of possible completions of the current minibuffer contents."
1181 (interactive)
1182 (message "Making completion list...")
1183 (let* ((start (field-beginning))
1184 (end (field-end))
1185 (string (field-string))
1186 (completions (completion-all-completions
1187 string
1188 minibuffer-completion-table
1189 minibuffer-completion-predicate
1190 (- (point) (field-beginning)))))
1191 (message nil)
1192 (if (and completions
1193 (or (consp (cdr completions))
1194 (not (equal (car completions) string))))
1195 (let* ((last (last completions))
1196 (base-size (cdr last))
1197 ;; If the *Completions* buffer is shown in a new
1198 ;; window, mark it as softly-dedicated, so bury-buffer in
1199 ;; minibuffer-hide-completions will know whether to
1200 ;; delete the window or not.
1201 (display-buffer-mark-dedicated 'soft))
1202 (with-output-to-temp-buffer "*Completions*"
1203 ;; Remove the base-size tail because `sort' requires a properly
1204 ;; nil-terminated list.
1205 (when last (setcdr last nil))
1206 (setq completions (sort completions 'string-lessp))
1207 (when completion-annotate-function
1208 (setq completions
1209 (mapcar (lambda (s)
1210 (let ((ann
1211 (funcall completion-annotate-function s)))
1212 (if ann (list s ann) s)))
1213 completions)))
1214 (with-current-buffer standard-output
1215 (set (make-local-variable 'completion-base-position)
1216 (list (+ start base-size)
1217 ;; FIXME: We should pay attention to completion
1218 ;; boundaries here, but currently
1219 ;; completion-all-completions does not give us the
1220 ;; necessary information.
1221 end)))
1222 (display-completion-list completions)))
1223
1224 ;; If there are no completions, or if the current input is already the
1225 ;; only possible completion, then hide (previous&stale) completions.
1226 (minibuffer-hide-completions)
1227 (ding)
1228 (minibuffer-message
1229 (if completions "Sole completion" "No completions")))
1230 nil))
1231
1232 (defun minibuffer-hide-completions ()
1233 "Get rid of an out-of-date *Completions* buffer."
1234 ;; FIXME: We could/should use minibuffer-scroll-window here, but it
1235 ;; can also point to the minibuffer-parent-window, so it's a bit tricky.
1236 (let ((win (get-buffer-window "*Completions*" 0)))
1237 (if win (with-selected-window win (bury-buffer)))))
1238
1239 (defun exit-minibuffer ()
1240 "Terminate this minibuffer argument."
1241 (interactive)
1242 ;; If the command that uses this has made modifications in the minibuffer,
1243 ;; we don't want them to cause deactivation of the mark in the original
1244 ;; buffer.
1245 ;; A better solution would be to make deactivate-mark buffer-local
1246 ;; (or to turn it into a list of buffers, ...), but in the mean time,
1247 ;; this should do the trick in most cases.
1248 (setq deactivate-mark nil)
1249 (throw 'exit nil))
1250
1251 (defun self-insert-and-exit ()
1252 "Terminate minibuffer input."
1253 (interactive)
1254 (if (characterp last-command-event)
1255 (call-interactively 'self-insert-command)
1256 (ding))
1257 (exit-minibuffer))
1258
1259 (defvar completion-in-region-functions nil
1260 "Wrapper hook around `completion-in-region'.
1261 The functions on this special hook are called with 5 arguments:
1262 NEXT-FUN START END COLLECTION PREDICATE.
1263 NEXT-FUN is a function of four arguments (START END COLLECTION PREDICATE)
1264 that performs the default operation. The other four arguments are like
1265 the ones passed to `completion-in-region'. The functions on this hook
1266 are expected to perform completion on START..END using COLLECTION
1267 and PREDICATE, either by calling NEXT-FUN or by doing it themselves.")
1268
1269 (defvar completion-in-region--data nil)
1270
1271 (defvar completion-in-region-mode-predicate nil
1272 "Predicate to tell `completion-in-region-mode' when to exit.
1273 It is called with no argument and should return nil when
1274 `completion-in-region-mode' should exit (and hence pop down
1275 the *Completions* buffer).")
1276
1277 (defvar completion-in-region-mode--predicate nil
1278 "Copy of the value of `completion-in-region-mode-predicate'.
1279 This holds the value `completion-in-region-mode-predicate' had when
1280 we entered `completion-in-region-mode'.")
1281
1282 (defun completion-in-region (start end collection &optional predicate)
1283 "Complete the text between START and END using COLLECTION.
1284 Return nil if there is no valid completion, else t.
1285 Point needs to be somewhere between START and END."
1286 (assert (<= start (point)) (<= (point) end))
1287 (with-wrapper-hook
1288 ;; FIXME: Maybe we should use this hook to provide a "display
1289 ;; completions" operation as well.
1290 completion-in-region-functions (start end collection predicate)
1291 (let ((minibuffer-completion-table collection)
1292 (minibuffer-completion-predicate predicate)
1293 (ol (make-overlay start end nil nil t)))
1294 (overlay-put ol 'field 'completion)
1295 (when completion-in-region-mode-predicate
1296 (completion-in-region-mode 1)
1297 (setq completion-in-region--data
1298 (list (current-buffer) start end collection)))
1299 (unwind-protect
1300 (call-interactively 'minibuffer-complete)
1301 (delete-overlay ol)))))
1302
1303 (defvar completion-in-region-mode-map
1304 (let ((map (make-sparse-keymap)))
1305 ;; FIXME: Only works if completion-in-region-mode was activated via
1306 ;; completion-at-point called directly.
1307 (define-key map "?" 'completion-help-at-point)
1308 (define-key map "\t" 'completion-at-point)
1309 map)
1310 "Keymap activated during `completion-in-region'.")
1311
1312 ;; It is difficult to know when to exit completion-in-region-mode (i.e. hide
1313 ;; the *Completions*).
1314 ;; - lisp-mode: never.
1315 ;; - comint: only do it if you hit SPC at the right time.
1316 ;; - pcomplete: pop it down on SPC or after some time-delay.
1317 ;; - semantic: use a post-command-hook check similar to this one.
1318 (defun completion-in-region--postch ()
1319 (or unread-command-events ;Don't pop down the completions in the middle of
1320 ;mouse-drag-region/mouse-set-point.
1321 (and completion-in-region--data
1322 (and (eq (car completion-in-region--data)
1323 (current-buffer))
1324 (>= (point) (nth 1 completion-in-region--data))
1325 (<= (point)
1326 (save-excursion
1327 (goto-char (nth 2 completion-in-region--data))
1328 (line-end-position)))
1329 (funcall completion-in-region-mode--predicate)))
1330 (completion-in-region-mode -1)))
1331
1332 ;; (defalias 'completion-in-region--prech 'completion-in-region--postch)
1333
1334 (define-minor-mode completion-in-region-mode
1335 "Transient minor mode used during `completion-in-region'."
1336 :global t
1337 (setq completion-in-region--data nil)
1338 ;; (remove-hook 'pre-command-hook #'completion-in-region--prech)
1339 (remove-hook 'post-command-hook #'completion-in-region--postch)
1340 (setq minor-mode-overriding-map-alist
1341 (delq (assq 'completion-in-region-mode minor-mode-overriding-map-alist)
1342 minor-mode-overriding-map-alist))
1343 (if (null completion-in-region-mode)
1344 (unless (equal "*Completions*" (buffer-name (window-buffer)))
1345 (minibuffer-hide-completions))
1346 ;; (add-hook 'pre-command-hook #'completion-in-region--prech)
1347 (assert completion-in-region-mode-predicate)
1348 (setq completion-in-region-mode--predicate
1349 completion-in-region-mode-predicate)
1350 (add-hook 'post-command-hook #'completion-in-region--postch)
1351 (push `(completion-in-region-mode . ,completion-in-region-mode-map)
1352 minor-mode-overriding-map-alist)))
1353
1354 ;; Define-minor-mode added our keymap to minor-mode-map-alist, but we want it
1355 ;; on minor-mode-overriding-map-alist instead.
1356 (setq minor-mode-map-alist
1357 (delq (assq 'completion-in-region-mode minor-mode-map-alist)
1358 minor-mode-map-alist))
1359
1360 (defvar completion-at-point-functions '(tags-completion-at-point-function)
1361 "Special hook to find the completion table for the thing at point.
1362 Each function on this hook is called in turns without any argument and should
1363 return either nil to mean that it is not applicable at point,
1364 or a function of no argument to perform completion (discouraged),
1365 or a list of the form (START END COLLECTION &rest PROPS) where
1366 START and END delimit the entity to complete and should include point,
1367 COLLECTION is the completion table to use to complete it, and
1368 PROPS is a property list for additional information.
1369 Currently supported properties are:
1370 `:predicate' a predicate that completion candidates need to satisfy.
1371 `:annotation-function' the value to use for `completion-annotate-function'.")
1372
1373 (defvar completion--capf-misbehave-funs nil
1374 "List of functions found on `completion-at-point-functions' that misbehave.")
1375 (defvar completion--capf-safe-funs nil
1376 "List of well-behaved functions found on `completion-at-point-functions'.")
1377
1378 (defun completion--capf-wrapper (fun which)
1379 (if (case which
1380 (all t)
1381 (safe (member fun completion--capf-safe-funs))
1382 (optimist (not (member fun completion--capf-misbehave-funs))))
1383 (let ((res (funcall fun)))
1384 (cond
1385 ((consp res)
1386 (unless (member fun completion--capf-safe-funs)
1387 (push fun completion--capf-safe-funs)))
1388 ((not (or (listp res) (functionp res)))
1389 (unless (member fun completion--capf-misbehave-funs)
1390 (message
1391 "Completion function %S uses a deprecated calling convention" fun)
1392 (push fun completion--capf-misbehave-funs))))
1393 (if res (cons fun res)))))
1394
1395 (defun completion-at-point ()
1396 "Perform completion on the text around point.
1397 The completion method is determined by `completion-at-point-functions'."
1398 (interactive)
1399 (let ((res (run-hook-wrapped 'completion-at-point-functions
1400 #'completion--capf-wrapper 'all)))
1401 (pcase res
1402 (`(,_ . ,(and (pred functionp) f)) (funcall f))
1403 (`(,hookfun . (,start ,end ,collection . ,plist))
1404 (let* ((completion-annotate-function
1405 (or (plist-get plist :annotation-function)
1406 completion-annotate-function))
1407 (completion-in-region-mode-predicate
1408 (lambda ()
1409 ;; We're still in the same completion field.
1410 (eq (car (funcall hookfun)) start))))
1411 (completion-in-region start end collection
1412 (plist-get plist :predicate))))
1413 ;; Maybe completion already happened and the function returned t.
1414 (_ (cdr res)))))
1415
1416 (defun completion-help-at-point ()
1417 "Display the completions on the text around point.
1418 The completion method is determined by `completion-at-point-functions'."
1419 (interactive)
1420 (let ((res (run-hook-wrapped 'completion-at-point-functions
1421 ;; Ignore misbehaving functions.
1422 #'completion--capf-wrapper 'optimist)))
1423 (pcase res
1424 (`(,_ . ,(and (pred functionp) f))
1425 (message "Don't know how to show completions for %S" f))
1426 (`(,hookfun . (,start ,end ,collection . ,plist))
1427 (let* ((minibuffer-completion-table collection)
1428 (minibuffer-completion-predicate (plist-get plist :predicate))
1429 (completion-annotate-function
1430 (or (plist-get plist :annotation-function)
1431 completion-annotate-function))
1432 (completion-in-region-mode-predicate
1433 (lambda ()
1434 ;; We're still in the same completion field.
1435 (eq (car (funcall hookfun)) start)))
1436 (ol (make-overlay start end nil nil t)))
1437 ;; FIXME: We should somehow (ab)use completion-in-region-function or
1438 ;; introduce a corresponding hook (plus another for word-completion,
1439 ;; and another for force-completion, maybe?).
1440 (overlay-put ol 'field 'completion)
1441 (completion-in-region-mode 1)
1442 (setq completion-in-region--data
1443 (list (current-buffer) start end collection))
1444 (unwind-protect
1445 (call-interactively 'minibuffer-completion-help)
1446 (delete-overlay ol))))
1447 (`(,hookfun . ,_)
1448 ;; The hook function already performed completion :-(
1449 ;; Not much we can do at this point.
1450 (message "%s already performed completion!" hookfun)
1451 nil)
1452 (_ (message "Nothing to complete at point")))))
1453
1454 ;;; Key bindings.
1455
1456 (define-obsolete-variable-alias 'minibuffer-local-must-match-filename-map
1457 'minibuffer-local-filename-must-match-map "23.1")
1458
1459 (let ((map minibuffer-local-map))
1460 (define-key map "\C-g" 'abort-recursive-edit)
1461 (define-key map "\r" 'exit-minibuffer)
1462 (define-key map "\n" 'exit-minibuffer))
1463
1464 (let ((map minibuffer-local-completion-map))
1465 (define-key map "\t" 'minibuffer-complete)
1466 ;; M-TAB is already abused for many other purposes, so we should find
1467 ;; another binding for it.
1468 ;; (define-key map "\e\t" 'minibuffer-force-complete)
1469 (define-key map " " 'minibuffer-complete-word)
1470 (define-key map "?" 'minibuffer-completion-help))
1471
1472 (let ((map minibuffer-local-must-match-map))
1473 (define-key map "\r" 'minibuffer-complete-and-exit)
1474 (define-key map "\n" 'minibuffer-complete-and-exit))
1475
1476 (let ((map minibuffer-local-filename-completion-map))
1477 (define-key map " " nil))
1478 (let ((map minibuffer-local-filename-must-match-map))
1479 (define-key map " " nil))
1480
1481 (let ((map minibuffer-local-ns-map))
1482 (define-key map " " 'exit-minibuffer)
1483 (define-key map "\t" 'exit-minibuffer)
1484 (define-key map "?" 'self-insert-and-exit))
1485
1486 ;;; Completion tables.
1487
1488 (defun minibuffer--double-dollars (str)
1489 (replace-regexp-in-string "\\$" "$$" str))
1490
1491 (defun completion--make-envvar-table ()
1492 (mapcar (lambda (enventry)
1493 (substring enventry 0 (string-match-p "=" enventry)))
1494 process-environment))
1495
1496 (defconst completion--embedded-envvar-re
1497 (concat "\\(?:^\\|[^$]\\(?:\\$\\$\\)*\\)"
1498 "$\\([[:alnum:]_]*\\|{\\([^}]*\\)\\)\\'"))
1499
1500 (defun completion--embedded-envvar-table (string _pred action)
1501 "Completion table for envvars embedded in a string.
1502 The envvar syntax (and escaping) rules followed by this table are the
1503 same as `substitute-in-file-name'."
1504 ;; We ignore `pred', because the predicates passed to us via
1505 ;; read-file-name-internal are not 100% correct and fail here:
1506 ;; e.g. we get predicates like file-directory-p there, whereas the filename
1507 ;; completed needs to be passed through substitute-in-file-name before it
1508 ;; can be passed to file-directory-p.
1509 (when (string-match completion--embedded-envvar-re string)
1510 (let* ((beg (or (match-beginning 2) (match-beginning 1)))
1511 (table (completion--make-envvar-table))
1512 (prefix (substring string 0 beg)))
1513 (cond
1514 ((eq action 'lambda)
1515 ;; This table is expected to be used in conjunction with some
1516 ;; other table that provides the "main" completion. Let the
1517 ;; other table handle the test-completion case.
1518 nil)
1519 ((eq (car-safe action) 'boundaries)
1520 ;; Only return boundaries if there's something to complete,
1521 ;; since otherwise when we're used in
1522 ;; completion-table-in-turn, we could return boundaries and
1523 ;; let some subsequent table return a list of completions.
1524 ;; FIXME: Maybe it should rather be fixed in
1525 ;; completion-table-in-turn instead, but it's difficult to
1526 ;; do it efficiently there.
1527 (when (try-completion (substring string beg) table nil)
1528 ;; Compute the boundaries of the subfield to which this
1529 ;; completion applies.
1530 (let ((suffix (cdr action)))
1531 (list* 'boundaries
1532 (or (match-beginning 2) (match-beginning 1))
1533 (when (string-match "[^[:alnum:]_]" suffix)
1534 (match-beginning 0))))))
1535 (t
1536 (if (eq (aref string (1- beg)) ?{)
1537 (setq table (apply-partially 'completion-table-with-terminator
1538 "}" table)))
1539 ;; Even if file-name completion is case-insensitive, we want
1540 ;; envvar completion to be case-sensitive.
1541 (let ((completion-ignore-case nil))
1542 (completion-table-with-context
1543 prefix table (substring string beg) nil action)))))))
1544
1545 (defun completion-file-name-table (string pred action)
1546 "Completion table for file names."
1547 (ignore-errors
1548 (cond
1549 ((eq (car-safe action) 'boundaries)
1550 (let ((start (length (file-name-directory string)))
1551 (end (string-match-p "/" (cdr action))))
1552 (list* 'boundaries
1553 ;; if `string' is "C:" in w32, (file-name-directory string)
1554 ;; returns "C:/", so `start' is 3 rather than 2.
1555 ;; Not quite sure what is The Right Fix, but clipping it
1556 ;; back to 2 will work for this particular case. We'll
1557 ;; see if we can come up with a better fix when we bump
1558 ;; into more such problematic cases.
1559 (min start (length string)) end)))
1560
1561 ((eq action 'lambda)
1562 (if (zerop (length string))
1563 nil ;Not sure why it's here, but it probably doesn't harm.
1564 (funcall (or pred 'file-exists-p) string)))
1565
1566 (t
1567 (let* ((name (file-name-nondirectory string))
1568 (specdir (file-name-directory string))
1569 (realdir (or specdir default-directory)))
1570
1571 (cond
1572 ((null action)
1573 (let ((comp (file-name-completion name realdir pred)))
1574 (if (stringp comp)
1575 (concat specdir comp)
1576 comp)))
1577
1578 ((eq action t)
1579 (let ((all (file-name-all-completions name realdir)))
1580
1581 ;; Check the predicate, if necessary.
1582 (unless (memq pred '(nil file-exists-p))
1583 (let ((comp ())
1584 (pred
1585 (if (eq pred 'file-directory-p)
1586 ;; Brute-force speed up for directory checking:
1587 ;; Discard strings which don't end in a slash.
1588 (lambda (s)
1589 (let ((len (length s)))
1590 (and (> len 0) (eq (aref s (1- len)) ?/))))
1591 ;; Must do it the hard (and slow) way.
1592 pred)))
1593 (let ((default-directory (expand-file-name realdir)))
1594 (dolist (tem all)
1595 (if (funcall pred tem) (push tem comp))))
1596 (setq all (nreverse comp))))
1597
1598 all))))))))
1599
1600 (defvar read-file-name-predicate nil
1601 "Current predicate used by `read-file-name-internal'.")
1602 (make-obsolete-variable 'read-file-name-predicate
1603 "use the regular PRED argument" "23.2")
1604
1605 (defun completion--file-name-table (string pred action)
1606 "Internal subroutine for `read-file-name'. Do not call this.
1607 This is a completion table for file names, like `completion-file-name-table'
1608 except that it passes the file name through `substitute-in-file-name'."
1609 (cond
1610 ((eq (car-safe action) 'boundaries)
1611 ;; For the boundaries, we can't really delegate to
1612 ;; substitute-in-file-name+completion-file-name-table and then fix
1613 ;; them up (as we do for the other actions), because it would
1614 ;; require us to track the relationship between `str' and
1615 ;; `string', which is difficult. And in any case, if
1616 ;; substitute-in-file-name turns "fo-$TO-ba" into "fo-o/b-ba",
1617 ;; there's no way for us to return proper boundaries info, because
1618 ;; the boundary is not (yet) in `string'.
1619 ;;
1620 ;; FIXME: Actually there is a way to return correct boundaries
1621 ;; info, at the condition of modifying the all-completions
1622 ;; return accordingly. But for now, let's not bother.
1623 (completion-file-name-table string pred action))
1624
1625 (t
1626 (let* ((default-directory
1627 (if (stringp pred)
1628 ;; It used to be that `pred' was abused to pass `dir'
1629 ;; as an argument.
1630 (prog1 (file-name-as-directory (expand-file-name pred))
1631 (setq pred nil))
1632 default-directory))
1633 (str (condition-case nil
1634 (substitute-in-file-name string)
1635 (error string)))
1636 (comp (completion-file-name-table
1637 str
1638 (with-no-warnings (or pred read-file-name-predicate))
1639 action)))
1640
1641 (cond
1642 ((stringp comp)
1643 ;; Requote the $s before returning the completion.
1644 (minibuffer--double-dollars comp))
1645 ((and (null action) comp
1646 ;; Requote the $s before checking for changes.
1647 (setq str (minibuffer--double-dollars str))
1648 (not (string-equal string str)))
1649 ;; If there's no real completion, but substitute-in-file-name
1650 ;; changed the string, then return the new string.
1651 str)
1652 (t comp))))))
1653
1654 (defalias 'read-file-name-internal
1655 (completion-table-in-turn 'completion--embedded-envvar-table
1656 'completion--file-name-table)
1657 "Internal subroutine for `read-file-name'. Do not call this.")
1658
1659 (defvar read-file-name-function 'read-file-name-default
1660 "The function called by `read-file-name' to do its work.
1661 It should accept the same arguments as `read-file-name'.")
1662
1663 (defcustom read-file-name-completion-ignore-case
1664 (if (memq system-type '(ms-dos windows-nt darwin cygwin))
1665 t nil)
1666 "Non-nil means when reading a file name completion ignores case."
1667 :group 'minibuffer
1668 :type 'boolean
1669 :version "22.1")
1670
1671 (defcustom insert-default-directory t
1672 "Non-nil means when reading a filename start with default dir in minibuffer.
1673
1674 When the initial minibuffer contents show a name of a file or a directory,
1675 typing RETURN without editing the initial contents is equivalent to typing
1676 the default file name.
1677
1678 If this variable is non-nil, the minibuffer contents are always
1679 initially non-empty, and typing RETURN without editing will fetch the
1680 default name, if one is provided. Note however that this default name
1681 is not necessarily the same as initial contents inserted in the minibuffer,
1682 if the initial contents is just the default directory.
1683
1684 If this variable is nil, the minibuffer often starts out empty. In
1685 that case you may have to explicitly fetch the next history element to
1686 request the default name; typing RETURN without editing will leave
1687 the minibuffer empty.
1688
1689 For some commands, exiting with an empty minibuffer has a special meaning,
1690 such as making the current buffer visit no file in the case of
1691 `set-visited-file-name'."
1692 :group 'minibuffer
1693 :type 'boolean)
1694
1695 ;; Not always defined, but only called if next-read-file-uses-dialog-p says so.
1696 (declare-function x-file-dialog "xfns.c"
1697 (prompt dir &optional default-filename mustmatch only-dir-p))
1698
1699 (defun read-file-name--defaults (&optional dir initial)
1700 (let ((default
1701 (cond
1702 ;; With non-nil `initial', use `dir' as the first default.
1703 ;; Essentially, this mean reversing the normal order of the
1704 ;; current directory name and the current file name, i.e.
1705 ;; 1. with normal file reading:
1706 ;; 1.1. initial input is the current directory
1707 ;; 1.2. the first default is the current file name
1708 ;; 2. with non-nil `initial' (e.g. for `find-alternate-file'):
1709 ;; 2.2. initial input is the current file name
1710 ;; 2.1. the first default is the current directory
1711 (initial (abbreviate-file-name dir))
1712 ;; In file buffers, try to get the current file name
1713 (buffer-file-name
1714 (abbreviate-file-name buffer-file-name))))
1715 (file-name-at-point
1716 (run-hook-with-args-until-success 'file-name-at-point-functions)))
1717 (when file-name-at-point
1718 (setq default (delete-dups
1719 (delete "" (delq nil (list file-name-at-point default))))))
1720 ;; Append new defaults to the end of existing `minibuffer-default'.
1721 (append
1722 (if (listp minibuffer-default) minibuffer-default (list minibuffer-default))
1723 (if (listp default) default (list default)))))
1724
1725 (defun read-file-name (prompt &optional dir default-filename mustmatch initial predicate)
1726 "Read file name, prompting with PROMPT and completing in directory DIR.
1727 Value is not expanded---you must call `expand-file-name' yourself.
1728 Default name to DEFAULT-FILENAME if user exits the minibuffer with
1729 the same non-empty string that was inserted by this function.
1730 (If DEFAULT-FILENAME is omitted, the visited file name is used,
1731 except that if INITIAL is specified, that combined with DIR is used.
1732 If DEFAULT-FILENAME is a list of file names, the first file name is used.)
1733 If the user exits with an empty minibuffer, this function returns
1734 an empty string. (This can only happen if the user erased the
1735 pre-inserted contents or if `insert-default-directory' is nil.)
1736
1737 Fourth arg MUSTMATCH can take the following values:
1738 - nil means that the user can exit with any input.
1739 - t means that the user is not allowed to exit unless
1740 the input is (or completes to) an existing file.
1741 - `confirm' means that the user can exit with any input, but she needs
1742 to confirm her choice if the input is not an existing file.
1743 - `confirm-after-completion' means that the user can exit with any
1744 input, but she needs to confirm her choice if she called
1745 `minibuffer-complete' right before `minibuffer-complete-and-exit'
1746 and the input is not an existing file.
1747 - anything else behaves like t except that typing RET does not exit if it
1748 does non-null completion.
1749
1750 Fifth arg INITIAL specifies text to start with.
1751
1752 If optional sixth arg PREDICATE is non-nil, possible completions and
1753 the resulting file name must satisfy (funcall PREDICATE NAME).
1754 DIR should be an absolute directory name. It defaults to the value of
1755 `default-directory'.
1756
1757 If this command was invoked with the mouse, use a graphical file
1758 dialog if `use-dialog-box' is non-nil, and the window system or X
1759 toolkit in use provides a file dialog box, and DIR is not a
1760 remote file. For graphical file dialogs, any the special values
1761 of MUSTMATCH; `confirm' and `confirm-after-completion' are
1762 treated as equivalent to nil.
1763
1764 See also `read-file-name-completion-ignore-case'
1765 and `read-file-name-function'."
1766 (funcall (or read-file-name-function #'read-file-name-default)
1767 prompt dir default-filename mustmatch initial predicate))
1768
1769 (defun read-file-name-default (prompt &optional dir default-filename mustmatch initial predicate)
1770 "Default method for reading file names.
1771 See `read-file-name' for the meaning of the arguments."
1772 (unless dir (setq dir default-directory))
1773 (unless (file-name-absolute-p dir) (setq dir (expand-file-name dir)))
1774 (unless default-filename
1775 (setq default-filename (if initial (expand-file-name initial dir)
1776 buffer-file-name)))
1777 ;; If dir starts with user's homedir, change that to ~.
1778 (setq dir (abbreviate-file-name dir))
1779 ;; Likewise for default-filename.
1780 (if default-filename
1781 (setq default-filename
1782 (if (consp default-filename)
1783 (mapcar 'abbreviate-file-name default-filename)
1784 (abbreviate-file-name default-filename))))
1785 (let ((insdef (cond
1786 ((and insert-default-directory (stringp dir))
1787 (if initial
1788 (cons (minibuffer--double-dollars (concat dir initial))
1789 (length (minibuffer--double-dollars dir)))
1790 (minibuffer--double-dollars dir)))
1791 (initial (cons (minibuffer--double-dollars initial) 0)))))
1792
1793 (let ((completion-ignore-case read-file-name-completion-ignore-case)
1794 (minibuffer-completing-file-name t)
1795 (pred (or predicate 'file-exists-p))
1796 (add-to-history nil))
1797
1798 (let* ((val
1799 (if (or (not (next-read-file-uses-dialog-p))
1800 ;; Graphical file dialogs can't handle remote
1801 ;; files (Bug#99).
1802 (file-remote-p dir))
1803 ;; We used to pass `dir' to `read-file-name-internal' by
1804 ;; abusing the `predicate' argument. It's better to
1805 ;; just use `default-directory', but in order to avoid
1806 ;; changing `default-directory' in the current buffer,
1807 ;; we don't let-bind it.
1808 (let ((dir (file-name-as-directory
1809 (expand-file-name dir))))
1810 (minibuffer-with-setup-hook
1811 (lambda ()
1812 (setq default-directory dir)
1813 ;; When the first default in `minibuffer-default'
1814 ;; duplicates initial input `insdef',
1815 ;; reset `minibuffer-default' to nil.
1816 (when (equal (or (car-safe insdef) insdef)
1817 (or (car-safe minibuffer-default)
1818 minibuffer-default))
1819 (setq minibuffer-default
1820 (cdr-safe minibuffer-default)))
1821 ;; On the first request on `M-n' fill
1822 ;; `minibuffer-default' with a list of defaults
1823 ;; relevant for file-name reading.
1824 (set (make-local-variable 'minibuffer-default-add-function)
1825 (lambda ()
1826 (with-current-buffer
1827 (window-buffer (minibuffer-selected-window))
1828 (read-file-name--defaults dir initial)))))
1829 (completing-read prompt 'read-file-name-internal
1830 pred mustmatch insdef
1831 'file-name-history default-filename)))
1832 ;; If DEFAULT-FILENAME not supplied and DIR contains
1833 ;; a file name, split it.
1834 (let ((file (file-name-nondirectory dir))
1835 ;; When using a dialog, revert to nil and non-nil
1836 ;; interpretation of mustmatch. confirm options
1837 ;; need to be interpreted as nil, otherwise
1838 ;; it is impossible to create new files using
1839 ;; dialogs with the default settings.
1840 (dialog-mustmatch
1841 (not (memq mustmatch
1842 '(nil confirm confirm-after-completion)))))
1843 (when (and (not default-filename)
1844 (not (zerop (length file))))
1845 (setq default-filename file)
1846 (setq dir (file-name-directory dir)))
1847 (when default-filename
1848 (setq default-filename
1849 (expand-file-name (if (consp default-filename)
1850 (car default-filename)
1851 default-filename)
1852 dir)))
1853 (setq add-to-history t)
1854 (x-file-dialog prompt dir default-filename
1855 dialog-mustmatch
1856 (eq predicate 'file-directory-p)))))
1857
1858 (replace-in-history (eq (car-safe file-name-history) val)))
1859 ;; If completing-read returned the inserted default string itself
1860 ;; (rather than a new string with the same contents),
1861 ;; it has to mean that the user typed RET with the minibuffer empty.
1862 ;; In that case, we really want to return ""
1863 ;; so that commands such as set-visited-file-name can distinguish.
1864 (when (consp default-filename)
1865 (setq default-filename (car default-filename)))
1866 (when (eq val default-filename)
1867 ;; In this case, completing-read has not added an element
1868 ;; to the history. Maybe we should.
1869 (if (not replace-in-history)
1870 (setq add-to-history t))
1871 (setq val ""))
1872 (unless val (error "No file name specified"))
1873
1874 (if (and default-filename
1875 (string-equal val (if (consp insdef) (car insdef) insdef)))
1876 (setq val default-filename))
1877 (setq val (substitute-in-file-name val))
1878
1879 (if replace-in-history
1880 ;; Replace what Fcompleting_read added to the history
1881 ;; with what we will actually return. As an exception,
1882 ;; if that's the same as the second item in
1883 ;; file-name-history, it's really a repeat (Bug#4657).
1884 (let ((val1 (minibuffer--double-dollars val)))
1885 (if history-delete-duplicates
1886 (setcdr file-name-history
1887 (delete val1 (cdr file-name-history))))
1888 (if (string= val1 (cadr file-name-history))
1889 (pop file-name-history)
1890 (setcar file-name-history val1)))
1891 (if add-to-history
1892 ;; Add the value to the history--but not if it matches
1893 ;; the last value already there.
1894 (let ((val1 (minibuffer--double-dollars val)))
1895 (unless (and (consp file-name-history)
1896 (equal (car file-name-history) val1))
1897 (setq file-name-history
1898 (cons val1
1899 (if history-delete-duplicates
1900 (delete val1 file-name-history)
1901 file-name-history)))))))
1902 val))))
1903
1904 (defun internal-complete-buffer-except (&optional buffer)
1905 "Perform completion on all buffers excluding BUFFER.
1906 BUFFER nil or omitted means use the current buffer.
1907 Like `internal-complete-buffer', but removes BUFFER from the completion list."
1908 (let ((except (if (stringp buffer) buffer (buffer-name buffer))))
1909 (apply-partially 'completion-table-with-predicate
1910 'internal-complete-buffer
1911 (lambda (name)
1912 (not (equal (if (consp name) (car name) name) except)))
1913 nil)))
1914
1915 ;;; Old-style completion, used in Emacs-21 and Emacs-22.
1916
1917 (defun completion-emacs21-try-completion (string table pred _point)
1918 (let ((completion (try-completion string table pred)))
1919 (if (stringp completion)
1920 (cons completion (length completion))
1921 completion)))
1922
1923 (defun completion-emacs21-all-completions (string table pred _point)
1924 (completion-hilit-commonality
1925 (all-completions string table pred)
1926 (length string)
1927 (car (completion-boundaries string table pred ""))))
1928
1929 (defun completion-emacs22-try-completion (string table pred point)
1930 (let ((suffix (substring string point))
1931 (completion (try-completion (substring string 0 point) table pred)))
1932 (if (not (stringp completion))
1933 completion
1934 ;; Merge a trailing / in completion with a / after point.
1935 ;; We used to only do it for word completion, but it seems to make
1936 ;; sense for all completions.
1937 ;; Actually, claiming this feature was part of Emacs-22 completion
1938 ;; is pushing it a bit: it was only done in minibuffer-completion-word,
1939 ;; which was (by default) not bound during file completion, where such
1940 ;; slashes are most likely to occur.
1941 (if (and (not (zerop (length completion)))
1942 (eq ?/ (aref completion (1- (length completion))))
1943 (not (zerop (length suffix)))
1944 (eq ?/ (aref suffix 0)))
1945 ;; This leaves point after the / .
1946 (setq suffix (substring suffix 1)))
1947 (cons (concat completion suffix) (length completion)))))
1948
1949 (defun completion-emacs22-all-completions (string table pred point)
1950 (let ((beforepoint (substring string 0 point)))
1951 (completion-hilit-commonality
1952 (all-completions beforepoint table pred)
1953 point
1954 (car (completion-boundaries beforepoint table pred "")))))
1955
1956 ;;; Basic completion.
1957
1958 (defun completion--merge-suffix (completion point suffix)
1959 "Merge end of COMPLETION with beginning of SUFFIX.
1960 Simple generalization of the \"merge trailing /\" done in Emacs-22.
1961 Return the new suffix."
1962 (if (and (not (zerop (length suffix)))
1963 (string-match "\\(.+\\)\n\\1" (concat completion "\n" suffix)
1964 ;; Make sure we don't compress things to less
1965 ;; than we started with.
1966 point)
1967 ;; Just make sure we didn't match some other \n.
1968 (eq (match-end 1) (length completion)))
1969 (substring suffix (- (match-end 1) (match-beginning 1)))
1970 ;; Nothing to merge.
1971 suffix))
1972
1973 (defun completion-basic--pattern (beforepoint afterpoint bounds)
1974 (delete
1975 "" (list (substring beforepoint (car bounds))
1976 'point
1977 (substring afterpoint 0 (cdr bounds)))))
1978
1979 (defun completion-basic-try-completion (string table pred point)
1980 (let* ((beforepoint (substring string 0 point))
1981 (afterpoint (substring string point))
1982 (bounds (completion-boundaries beforepoint table pred afterpoint)))
1983 (if (zerop (cdr bounds))
1984 ;; `try-completion' may return a subtly different result
1985 ;; than `all+merge', so try to use it whenever possible.
1986 (let ((completion (try-completion beforepoint table pred)))
1987 (if (not (stringp completion))
1988 completion
1989 (cons
1990 (concat completion
1991 (completion--merge-suffix completion point afterpoint))
1992 (length completion))))
1993 (let* ((suffix (substring afterpoint (cdr bounds)))
1994 (prefix (substring beforepoint 0 (car bounds)))
1995 (pattern (delete
1996 "" (list (substring beforepoint (car bounds))
1997 'point
1998 (substring afterpoint 0 (cdr bounds)))))
1999 (all (completion-pcm--all-completions prefix pattern table pred)))
2000 (if minibuffer-completing-file-name
2001 (setq all (completion-pcm--filename-try-filter all)))
2002 (completion-pcm--merge-try pattern all prefix suffix)))))
2003
2004 (defun completion-basic-all-completions (string table pred point)
2005 (let* ((beforepoint (substring string 0 point))
2006 (afterpoint (substring string point))
2007 (bounds (completion-boundaries beforepoint table pred afterpoint))
2008 ;; (suffix (substring afterpoint (cdr bounds)))
2009 (prefix (substring beforepoint 0 (car bounds)))
2010 (pattern (delete
2011 "" (list (substring beforepoint (car bounds))
2012 'point
2013 (substring afterpoint 0 (cdr bounds)))))
2014 (all (completion-pcm--all-completions prefix pattern table pred)))
2015 (completion-hilit-commonality all point (car bounds))))
2016
2017 ;;; Partial-completion-mode style completion.
2018
2019 (defvar completion-pcm--delim-wild-regex nil
2020 "Regular expression matching delimiters controlling the partial-completion.
2021 Typically, this regular expression simply matches a delimiter, meaning
2022 that completion can add something at (match-beginning 0), but if it has
2023 a submatch 1, then completion can add something at (match-end 1).
2024 This is used when the delimiter needs to be of size zero (e.g. the transition
2025 from lowercase to uppercase characters).")
2026
2027 (defun completion-pcm--prepare-delim-re (delims)
2028 (setq completion-pcm--delim-wild-regex (concat "[" delims "*]")))
2029
2030 (defcustom completion-pcm-word-delimiters "-_./: "
2031 "A string of characters treated as word delimiters for completion.
2032 Some arcane rules:
2033 If `]' is in this string, it must come first.
2034 If `^' is in this string, it must not come first.
2035 If `-' is in this string, it must come first or right after `]'.
2036 In other words, if S is this string, then `[S]' must be a valid Emacs regular
2037 expression (not containing character ranges like `a-z')."
2038 :set (lambda (symbol value)
2039 (set-default symbol value)
2040 ;; Refresh other vars.
2041 (completion-pcm--prepare-delim-re value))
2042 :initialize 'custom-initialize-reset
2043 :group 'minibuffer
2044 :type 'string)
2045
2046 (defcustom completion-pcm-complete-word-inserts-delimiters nil
2047 "Treat the SPC or - inserted by `minibuffer-complete-word' as delimiters.
2048 Those chars are treated as delimiters iff this variable is non-nil.
2049 I.e. if non-nil, M-x SPC will just insert a \"-\" in the minibuffer, whereas
2050 if nil, it will list all possible commands in *Completions* because none of
2051 the commands start with a \"-\" or a SPC."
2052 :type 'boolean)
2053
2054 (defun completion-pcm--pattern-trivial-p (pattern)
2055 (and (stringp (car pattern))
2056 ;; It can be followed by `point' and "" and still be trivial.
2057 (let ((trivial t))
2058 (dolist (elem (cdr pattern))
2059 (unless (member elem '(point ""))
2060 (setq trivial nil)))
2061 trivial)))
2062
2063 (defun completion-pcm--string->pattern (string &optional point)
2064 "Split STRING into a pattern.
2065 A pattern is a list where each element is either a string
2066 or a symbol chosen among `any', `star', `point', `prefix'."
2067 (if (and point (< point (length string)))
2068 (let ((prefix (substring string 0 point))
2069 (suffix (substring string point)))
2070 (append (completion-pcm--string->pattern prefix)
2071 '(point)
2072 (completion-pcm--string->pattern suffix)))
2073 (let* ((pattern nil)
2074 (p 0)
2075 (p0 p))
2076
2077 (while (and (setq p (string-match completion-pcm--delim-wild-regex
2078 string p))
2079 (or completion-pcm-complete-word-inserts-delimiters
2080 ;; If the char was added by minibuffer-complete-word,
2081 ;; then don't treat it as a delimiter, otherwise
2082 ;; "M-x SPC" ends up inserting a "-" rather than listing
2083 ;; all completions.
2084 (not (get-text-property p 'completion-try-word string))))
2085 ;; Usually, completion-pcm--delim-wild-regex matches a delimiter,
2086 ;; meaning that something can be added *before* it, but it can also
2087 ;; match a prefix and postfix, in which case something can be added
2088 ;; in-between (e.g. match [[:lower:]][[:upper:]]).
2089 ;; This is determined by the presence of a submatch-1 which delimits
2090 ;; the prefix.
2091 (if (match-end 1) (setq p (match-end 1)))
2092 (push (substring string p0 p) pattern)
2093 (if (eq (aref string p) ?*)
2094 (progn
2095 (push 'star pattern)
2096 (setq p0 (1+ p)))
2097 (push 'any pattern)
2098 (setq p0 p))
2099 (incf p))
2100
2101 ;; An empty string might be erroneously added at the beginning.
2102 ;; It should be avoided properly, but it's so easy to remove it here.
2103 (delete "" (nreverse (cons (substring string p0) pattern))))))
2104
2105 (defun completion-pcm--pattern->regex (pattern &optional group)
2106 (let ((re
2107 (concat "\\`"
2108 (mapconcat
2109 (lambda (x)
2110 (cond
2111 ((stringp x) (regexp-quote x))
2112 ((if (consp group) (memq x group) group) "\\(.*?\\)")
2113 (t ".*?")))
2114 pattern
2115 ""))))
2116 ;; Avoid pathological backtracking.
2117 (while (string-match "\\.\\*\\?\\(?:\\\\[()]\\)*\\(\\.\\*\\?\\)" re)
2118 (setq re (replace-match "" t t re 1)))
2119 re))
2120
2121 (defun completion-pcm--all-completions (prefix pattern table pred)
2122 "Find all completions for PATTERN in TABLE obeying PRED.
2123 PATTERN is as returned by `completion-pcm--string->pattern'."
2124 ;; (assert (= (car (completion-boundaries prefix table pred ""))
2125 ;; (length prefix)))
2126 ;; Find an initial list of possible completions.
2127 (if (completion-pcm--pattern-trivial-p pattern)
2128
2129 ;; Minibuffer contains no delimiters -- simple case!
2130 (all-completions (concat prefix (car pattern)) table pred)
2131
2132 ;; Use all-completions to do an initial cull. This is a big win,
2133 ;; since all-completions is written in C!
2134 (let* (;; Convert search pattern to a standard regular expression.
2135 (regex (completion-pcm--pattern->regex pattern))
2136 (case-fold-search completion-ignore-case)
2137 (completion-regexp-list (cons regex completion-regexp-list))
2138 (compl (all-completions
2139 (concat prefix (if (stringp (car pattern)) (car pattern) ""))
2140 table pred)))
2141 (if (not (functionp table))
2142 ;; The internal functions already obeyed completion-regexp-list.
2143 compl
2144 (let ((poss ()))
2145 (dolist (c compl)
2146 (when (string-match-p regex c) (push c poss)))
2147 poss)))))
2148
2149 (defun completion-pcm--hilit-commonality (pattern completions)
2150 (when completions
2151 (let* ((re (completion-pcm--pattern->regex pattern '(point)))
2152 (case-fold-search completion-ignore-case))
2153 (mapcar
2154 (lambda (str)
2155 ;; Don't modify the string itself.
2156 (setq str (copy-sequence str))
2157 (unless (string-match re str)
2158 (error "Internal error: %s does not match %s" re str))
2159 (let ((pos (or (match-beginning 1) (match-end 0))))
2160 (put-text-property 0 pos
2161 'font-lock-face 'completions-common-part
2162 str)
2163 (if (> (length str) pos)
2164 (put-text-property pos (1+ pos)
2165 'font-lock-face 'completions-first-difference
2166 str)))
2167 str)
2168 completions))))
2169
2170 (defun completion-pcm--find-all-completions (string table pred point
2171 &optional filter)
2172 "Find all completions for STRING at POINT in TABLE, satisfying PRED.
2173 POINT is a position inside STRING.
2174 FILTER is a function applied to the return value, that can be used, e.g. to
2175 filter out additional entries (because TABLE migth not obey PRED)."
2176 (unless filter (setq filter 'identity))
2177 (let* ((beforepoint (substring string 0 point))
2178 (afterpoint (substring string point))
2179 (bounds (completion-boundaries beforepoint table pred afterpoint))
2180 (prefix (substring beforepoint 0 (car bounds)))
2181 (suffix (substring afterpoint (cdr bounds)))
2182 firsterror)
2183 (setq string (substring string (car bounds) (+ point (cdr bounds))))
2184 (let* ((relpoint (- point (car bounds)))
2185 (pattern (completion-pcm--string->pattern string relpoint))
2186 (all (condition-case err
2187 (funcall filter
2188 (completion-pcm--all-completions
2189 prefix pattern table pred))
2190 (error (unless firsterror (setq firsterror err)) nil))))
2191 (when (and (null all)
2192 (> (car bounds) 0)
2193 (null (ignore-errors (try-completion prefix table pred))))
2194 ;; The prefix has no completions at all, so we should try and fix
2195 ;; that first.
2196 (let ((substring (substring prefix 0 -1)))
2197 (destructuring-bind (subpat suball subprefix _subsuffix)
2198 (completion-pcm--find-all-completions
2199 substring table pred (length substring) filter)
2200 (let ((sep (aref prefix (1- (length prefix))))
2201 ;; Text that goes between the new submatches and the
2202 ;; completion substring.
2203 (between nil))
2204 ;; Eliminate submatches that don't end with the separator.
2205 (dolist (submatch (prog1 suball (setq suball ())))
2206 (when (eq sep (aref submatch (1- (length submatch))))
2207 (push submatch suball)))
2208 (when suball
2209 ;; Update the boundaries and corresponding pattern.
2210 ;; We assume that all submatches result in the same boundaries
2211 ;; since we wouldn't know how to merge them otherwise anyway.
2212 ;; FIXME: COMPLETE REWRITE!!!
2213 (let* ((newbeforepoint
2214 (concat subprefix (car suball)
2215 (substring string 0 relpoint)))
2216 (leftbound (+ (length subprefix) (length (car suball))))
2217 (newbounds (completion-boundaries
2218 newbeforepoint table pred afterpoint)))
2219 (unless (or (and (eq (cdr bounds) (cdr newbounds))
2220 (eq (car newbounds) leftbound))
2221 ;; Refuse new boundaries if they step over
2222 ;; the submatch.
2223 (< (car newbounds) leftbound))
2224 ;; The new completed prefix does change the boundaries
2225 ;; of the completed substring.
2226 (setq suffix (substring afterpoint (cdr newbounds)))
2227 (setq string
2228 (concat (substring newbeforepoint (car newbounds))
2229 (substring afterpoint 0 (cdr newbounds))))
2230 (setq between (substring newbeforepoint leftbound
2231 (car newbounds)))
2232 (setq pattern (completion-pcm--string->pattern
2233 string
2234 (- (length newbeforepoint)
2235 (car newbounds)))))
2236 (dolist (submatch suball)
2237 (setq all (nconc (mapcar
2238 (lambda (s) (concat submatch between s))
2239 (funcall filter
2240 (completion-pcm--all-completions
2241 (concat subprefix submatch between)
2242 pattern table pred)))
2243 all)))
2244 ;; FIXME: This can come in handy for try-completion,
2245 ;; but isn't right for all-completions, since it lists
2246 ;; invalid completions.
2247 ;; (unless all
2248 ;; ;; Even though we found expansions in the prefix, none
2249 ;; ;; leads to a valid completion.
2250 ;; ;; Let's keep the expansions, tho.
2251 ;; (dolist (submatch suball)
2252 ;; (push (concat submatch between newsubstring) all)))
2253 ))
2254 (setq pattern (append subpat (list 'any (string sep))
2255 (if between (list between)) pattern))
2256 (setq prefix subprefix)))))
2257 (if (and (null all) firsterror)
2258 (signal (car firsterror) (cdr firsterror))
2259 (list pattern all prefix suffix)))))
2260
2261 (defun completion-pcm-all-completions (string table pred point)
2262 (destructuring-bind (pattern all &optional prefix _suffix)
2263 (completion-pcm--find-all-completions string table pred point)
2264 (when all
2265 (nconc (completion-pcm--hilit-commonality pattern all)
2266 (length prefix)))))
2267
2268 (defun completion--sreverse (str)
2269 "Like `reverse' but for a string STR rather than a list."
2270 (apply 'string (nreverse (mapcar 'identity str))))
2271
2272 (defun completion--common-suffix (strs)
2273 "Return the common suffix of the strings STRS."
2274 (completion--sreverse
2275 (try-completion
2276 ""
2277 (mapcar 'completion--sreverse strs))))
2278
2279 (defun completion-pcm--merge-completions (strs pattern)
2280 "Extract the commonality in STRS, with the help of PATTERN."
2281 ;; When completing while ignoring case, we want to try and avoid
2282 ;; completing "fo" to "foO" when completing against "FOO" (bug#4219).
2283 ;; So we try and make sure that the string we return is all made up
2284 ;; of text from the completions rather than part from the
2285 ;; completions and part from the input.
2286 ;; FIXME: This reduces the problems of inconsistent capitalization
2287 ;; but it doesn't fully fix it: we may still end up completing
2288 ;; "fo-ba" to "foo-BAR" or "FOO-bar" when completing against
2289 ;; '("foo-barr" "FOO-BARD").
2290 (cond
2291 ((null (cdr strs)) (list (car strs)))
2292 (t
2293 (let ((re (completion-pcm--pattern->regex pattern 'group))
2294 (ccs ())) ;Chopped completions.
2295
2296 ;; First chop each string into the parts corresponding to each
2297 ;; non-constant element of `pattern', using regexp-matching.
2298 (let ((case-fold-search completion-ignore-case))
2299 (dolist (str strs)
2300 (unless (string-match re str)
2301 (error "Internal error: %s doesn't match %s" str re))
2302 (let ((chopped ())
2303 (last 0)
2304 (i 1)
2305 next)
2306 (while (setq next (match-end i))
2307 (push (substring str last next) chopped)
2308 (setq last next)
2309 (setq i (1+ i)))
2310 ;; Add the text corresponding to the implicit trailing `any'.
2311 (push (substring str last) chopped)
2312 (push (nreverse chopped) ccs))))
2313
2314 ;; Then for each of those non-constant elements, extract the
2315 ;; commonality between them.
2316 (let ((res ())
2317 (fixed ""))
2318 ;; Make the implicit trailing `any' explicit.
2319 (dolist (elem (append pattern '(any)))
2320 (if (stringp elem)
2321 (setq fixed (concat fixed elem))
2322 (let ((comps ()))
2323 (dolist (cc (prog1 ccs (setq ccs nil)))
2324 (push (car cc) comps)
2325 (push (cdr cc) ccs))
2326 ;; Might improve the likelihood to avoid choosing
2327 ;; different capitalizations in different parts.
2328 ;; In practice, it doesn't seem to make any difference.
2329 (setq ccs (nreverse ccs))
2330 (let* ((prefix (try-completion fixed comps))
2331 (unique (or (and (eq prefix t) (setq prefix fixed))
2332 (eq t (try-completion prefix comps)))))
2333 (unless (equal prefix "") (push prefix res))
2334 ;; If there's only one completion, `elem' is not useful
2335 ;; any more: it can only match the empty string.
2336 ;; FIXME: in some cases, it may be necessary to turn an
2337 ;; `any' into a `star' because the surrounding context has
2338 ;; changed such that string->pattern wouldn't add an `any'
2339 ;; here any more.
2340 (unless unique
2341 (push elem res)
2342 (when (memq elem '(star point prefix))
2343 ;; Extract common suffix additionally to common prefix.
2344 ;; Only do it for `point', `star', and `prefix' since for
2345 ;; `any' it could lead to a merged completion that
2346 ;; doesn't itself match the candidates.
2347 (let ((suffix (completion--common-suffix comps)))
2348 (assert (stringp suffix))
2349 (unless (equal suffix "")
2350 (push suffix res)))))
2351 (setq fixed "")))))
2352 ;; We return it in reverse order.
2353 res)))))
2354
2355 (defun completion-pcm--pattern->string (pattern)
2356 (mapconcat (lambda (x) (cond
2357 ((stringp x) x)
2358 ((eq x 'star) "*")
2359 (t ""))) ;any, point, prefix.
2360 pattern
2361 ""))
2362
2363 ;; We want to provide the functionality of `try', but we use `all'
2364 ;; and then merge it. In most cases, this works perfectly, but
2365 ;; if the completion table doesn't consider the same completions in
2366 ;; `try' as in `all', then we have a problem. The most common such
2367 ;; case is for filename completion where completion-ignored-extensions
2368 ;; is only obeyed by the `try' code. We paper over the difference
2369 ;; here. Note that it is not quite right either: if the completion
2370 ;; table uses completion-table-in-turn, this filtering may take place
2371 ;; too late to correctly fallback from the first to the
2372 ;; second alternative.
2373 (defun completion-pcm--filename-try-filter (all)
2374 "Filter to adjust `all' file completion to the behavior of `try'."
2375 (when all
2376 (let ((try ())
2377 (re (concat "\\(?:\\`\\.\\.?/\\|"
2378 (regexp-opt completion-ignored-extensions)
2379 "\\)\\'")))
2380 (dolist (f all)
2381 (unless (string-match-p re f) (push f try)))
2382 (or try all))))
2383
2384
2385 (defun completion-pcm--merge-try (pattern all prefix suffix)
2386 (cond
2387 ((not (consp all)) all)
2388 ((and (not (consp (cdr all))) ;Only one completion.
2389 ;; Ignore completion-ignore-case here.
2390 (equal (completion-pcm--pattern->string pattern) (car all)))
2391 t)
2392 (t
2393 (let* ((mergedpat (completion-pcm--merge-completions all pattern))
2394 ;; `mergedpat' is in reverse order. Place new point (by
2395 ;; order of preference) either at the old point, or at
2396 ;; the last place where there's something to choose, or
2397 ;; at the very end.
2398 (pointpat (or (memq 'point mergedpat)
2399 (memq 'any mergedpat)
2400 (memq 'star mergedpat)
2401 ;; Not `prefix'.
2402 mergedpat))
2403 ;; New pos from the start.
2404 (newpos (length (completion-pcm--pattern->string pointpat)))
2405 ;; Do it afterwards because it changes `pointpat' by sideeffect.
2406 (merged (completion-pcm--pattern->string (nreverse mergedpat))))
2407
2408 (setq suffix (completion--merge-suffix merged newpos suffix))
2409 (cons (concat prefix merged suffix) (+ newpos (length prefix)))))))
2410
2411 (defun completion-pcm-try-completion (string table pred point)
2412 (destructuring-bind (pattern all prefix suffix)
2413 (completion-pcm--find-all-completions
2414 string table pred point
2415 (if minibuffer-completing-file-name
2416 'completion-pcm--filename-try-filter))
2417 (completion-pcm--merge-try pattern all prefix suffix)))
2418
2419 ;;; Substring completion
2420 ;; Mostly derived from the code of `basic' completion.
2421
2422 (defun completion-substring--all-completions (string table pred point)
2423 (let* ((beforepoint (substring string 0 point))
2424 (afterpoint (substring string point))
2425 (bounds (completion-boundaries beforepoint table pred afterpoint))
2426 (suffix (substring afterpoint (cdr bounds)))
2427 (prefix (substring beforepoint 0 (car bounds)))
2428 (basic-pattern (completion-basic--pattern
2429 beforepoint afterpoint bounds))
2430 (pattern (if (not (stringp (car basic-pattern)))
2431 basic-pattern
2432 (cons 'prefix basic-pattern)))
2433 (all (completion-pcm--all-completions prefix pattern table pred)))
2434 (list all pattern prefix suffix (car bounds))))
2435
2436 (defun completion-substring-try-completion (string table pred point)
2437 (destructuring-bind (all pattern prefix suffix _carbounds)
2438 (completion-substring--all-completions string table pred point)
2439 (if minibuffer-completing-file-name
2440 (setq all (completion-pcm--filename-try-filter all)))
2441 (completion-pcm--merge-try pattern all prefix suffix)))
2442
2443 (defun completion-substring-all-completions (string table pred point)
2444 (destructuring-bind (all pattern prefix _suffix _carbounds)
2445 (completion-substring--all-completions string table pred point)
2446 (when all
2447 (nconc (completion-pcm--hilit-commonality pattern all)
2448 (length prefix)))))
2449
2450 ;; Initials completion
2451 ;; Complete /ums to /usr/monnier/src or lch to list-command-history.
2452
2453 (defun completion-initials-expand (str table pred)
2454 (let ((bounds (completion-boundaries str table pred "")))
2455 (unless (or (zerop (length str))
2456 ;; Only check within the boundaries, since the
2457 ;; boundary char (e.g. /) might be in delim-regexp.
2458 (string-match completion-pcm--delim-wild-regex str
2459 (car bounds)))
2460 (if (zerop (car bounds))
2461 (mapconcat 'string str "-")
2462 ;; If there's a boundary, it's trickier. The main use-case
2463 ;; we consider here is file-name completion. We'd like
2464 ;; to expand ~/eee to ~/e/e/e and /eee to /e/e/e.
2465 ;; But at the same time, we don't want /usr/share/ae to expand
2466 ;; to /usr/share/a/e just because we mistyped "ae" for "ar",
2467 ;; so we probably don't want initials to touch anything that
2468 ;; looks like /usr/share/foo. As a heuristic, we just check that
2469 ;; the text before the boundary char is at most 1 char.
2470 ;; This allows both ~/eee and /eee and not much more.
2471 ;; FIXME: It sadly also disallows the use of ~/eee when that's
2472 ;; embedded within something else (e.g. "(~/eee" in Info node
2473 ;; completion or "ancestor:/eee" in bzr-revision completion).
2474 (when (< (car bounds) 3)
2475 (let ((sep (substring str (1- (car bounds)) (car bounds))))
2476 ;; FIXME: the above string-match checks the whole string, whereas
2477 ;; we end up only caring about the after-boundary part.
2478 (concat (substring str 0 (car bounds))
2479 (mapconcat 'string (substring str (car bounds)) sep))))))))
2480
2481 (defun completion-initials-all-completions (string table pred _point)
2482 (let ((newstr (completion-initials-expand string table pred)))
2483 (when newstr
2484 (completion-pcm-all-completions newstr table pred (length newstr)))))
2485
2486 (defun completion-initials-try-completion (string table pred _point)
2487 (let ((newstr (completion-initials-expand string table pred)))
2488 (when newstr
2489 (completion-pcm-try-completion newstr table pred (length newstr)))))
2490
2491 \f
2492 ;; Miscellaneous
2493
2494 (defun minibuffer-insert-file-name-at-point ()
2495 "Get a file name at point in original buffer and insert it to minibuffer."
2496 (interactive)
2497 (let ((file-name-at-point
2498 (with-current-buffer (window-buffer (minibuffer-selected-window))
2499 (run-hook-with-args-until-success 'file-name-at-point-functions))))
2500 (when file-name-at-point
2501 (insert file-name-at-point))))
2502
2503 (provide 'minibuffer)
2504
2505 ;;; minibuffer.el ends here