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