* abbrev.el (abbrev-with-wrapper-hook): (re)move...
[bpt/emacs.git] / 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 (defconst 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 (minibuffer-hide-completions)
993 (ding)
994 (minibuffer-message
995 (if completions "Sole completion" "No completions")))
996 nil))
997
998 (defun minibuffer-hide-completions ()
999 "Get rid of an out-of-date *Completions* buffer."
1000 ;; FIXME: We could/should use minibuffer-scroll-window here, but it
1001 ;; can also point to the minibuffer-parent-window, so it's a bit tricky.
1002 (let ((win (get-buffer-window "*Completions*" 0)))
1003 (if win (with-selected-window win (bury-buffer)))))
1004
1005 (defun exit-minibuffer ()
1006 "Terminate this minibuffer argument."
1007 (interactive)
1008 ;; If the command that uses this has made modifications in the minibuffer,
1009 ;; we don't want them to cause deactivation of the mark in the original
1010 ;; buffer.
1011 ;; A better solution would be to make deactivate-mark buffer-local
1012 ;; (or to turn it into a list of buffers, ...), but in the mean time,
1013 ;; this should do the trick in most cases.
1014 (setq deactivate-mark nil)
1015 (throw 'exit nil))
1016
1017 (defun self-insert-and-exit ()
1018 "Terminate minibuffer input."
1019 (interactive)
1020 (if (characterp last-command-event)
1021 (call-interactively 'self-insert-command)
1022 (ding))
1023 (exit-minibuffer))
1024
1025 (defvar completion-in-region-functions nil
1026 "Wrapper hook around `complete-in-region'.
1027 The functions on this special hook are called with 5 arguments:
1028 NEXT-FUN START END COLLECTION PREDICATE.
1029 NEXT-FUN is a function of four arguments (START END COLLECTION PREDICATE)
1030 that performs the default operation. The other four argument are like
1031 the ones passed to `complete-in-region'. The functions on this hook
1032 are expected to perform completion on START..END using COLLECTION
1033 and PREDICATE, either by calling NEXT-FUN or by doing it themselves.")
1034
1035 (defun completion-in-region (start end collection &optional predicate)
1036 "Complete the text between START and END using COLLECTION.
1037 Point needs to be somewhere between START and END."
1038 ;; FIXME: some callers need to setup completion-ignore-case,
1039 ;; completion-ignored-extensions. The latter can be embedded in the
1040 ;; completion tables, but the first cannot (actually, maybe it should).
1041 (assert (<= start (point)) (<= (point) end))
1042 ;; FIXME: undisplay the *Completions* buffer once the completion is done.
1043 (with-wrapper-hook
1044 completion-in-region-functions (start end collection predicate)
1045 (let ((minibuffer-completion-table collection)
1046 (minibuffer-completion-predicate predicate)
1047 (ol (make-overlay start end nil nil t)))
1048 (overlay-put ol 'field 'completion)
1049 (unwind-protect
1050 (call-interactively 'minibuffer-complete)
1051 (delete-overlay ol)))))
1052
1053 (let ((map minibuffer-local-map))
1054 (define-key map "\C-g" 'abort-recursive-edit)
1055 (define-key map "\r" 'exit-minibuffer)
1056 (define-key map "\n" 'exit-minibuffer))
1057
1058 (let ((map minibuffer-local-completion-map))
1059 (define-key map "\t" 'minibuffer-complete)
1060 ;; M-TAB is already abused for many other purposes, so we should find
1061 ;; another binding for it.
1062 ;; (define-key map "\e\t" 'minibuffer-force-complete)
1063 (define-key map " " 'minibuffer-complete-word)
1064 (define-key map "?" 'minibuffer-completion-help))
1065
1066 (let ((map minibuffer-local-must-match-map))
1067 (define-key map "\r" 'minibuffer-complete-and-exit)
1068 (define-key map "\n" 'minibuffer-complete-and-exit))
1069
1070 (let ((map minibuffer-local-filename-completion-map))
1071 (define-key map " " nil))
1072 (let ((map minibuffer-local-filename-must-match-map))
1073 (define-key map " " nil))
1074
1075 (let ((map minibuffer-local-ns-map))
1076 (define-key map " " 'exit-minibuffer)
1077 (define-key map "\t" 'exit-minibuffer)
1078 (define-key map "?" 'self-insert-and-exit))
1079
1080 ;;; Completion tables.
1081
1082 (defun minibuffer--double-dollars (str)
1083 (replace-regexp-in-string "\\$" "$$" str))
1084
1085 (defun completion--make-envvar-table ()
1086 (mapcar (lambda (enventry)
1087 (substring enventry 0 (string-match-p "=" enventry)))
1088 process-environment))
1089
1090 (defconst completion--embedded-envvar-re
1091 (concat "\\(?:^\\|[^$]\\(?:\\$\\$\\)*\\)"
1092 "$\\([[:alnum:]_]*\\|{\\([^}]*\\)\\)\\'"))
1093
1094 (defun completion--embedded-envvar-table (string pred action)
1095 "Completion table for envvars embedded in a string.
1096 The envvar syntax (and escaping) rules followed by this table are the
1097 same as `substitute-in-file-name'."
1098 ;; We ignore `pred', because the predicates passed to us via
1099 ;; read-file-name-internal are not 100% correct and fail here:
1100 ;; e.g. we get predicates like file-directory-p there, whereas the filename
1101 ;; completed needs to be passed through substitute-in-file-name before it
1102 ;; can be passed to file-directory-p.
1103 (when (string-match completion--embedded-envvar-re string)
1104 (let* ((beg (or (match-beginning 2) (match-beginning 1)))
1105 (table (completion--make-envvar-table))
1106 (prefix (substring string 0 beg)))
1107 (cond
1108 ((eq action 'lambda)
1109 ;; This table is expected to be used in conjunction with some
1110 ;; other table that provides the "main" completion. Let the
1111 ;; other table handle the test-completion case.
1112 nil)
1113 ((eq (car-safe action) 'boundaries)
1114 ;; Only return boundaries if there's something to complete,
1115 ;; since otherwise when we're used in
1116 ;; completion-table-in-turn, we could return boundaries and
1117 ;; let some subsequent table return a list of completions.
1118 ;; FIXME: Maybe it should rather be fixed in
1119 ;; completion-table-in-turn instead, but it's difficult to
1120 ;; do it efficiently there.
1121 (when (try-completion (substring string beg) table nil)
1122 ;; Compute the boundaries of the subfield to which this
1123 ;; completion applies.
1124 (let ((suffix (cdr action)))
1125 (list* 'boundaries
1126 (or (match-beginning 2) (match-beginning 1))
1127 (when (string-match "[^[:alnum:]_]" suffix)
1128 (match-beginning 0))))))
1129 (t
1130 (if (eq (aref string (1- beg)) ?{)
1131 (setq table (apply-partially 'completion-table-with-terminator
1132 "}" table)))
1133 ;; Even if file-name completion is case-insensitive, we want
1134 ;; envvar completion to be case-sensitive.
1135 (let ((completion-ignore-case nil))
1136 (completion-table-with-context
1137 prefix table (substring string beg) nil action)))))))
1138
1139 (defun completion-file-name-table (string pred action)
1140 "Completion table for file names."
1141 (ignore-errors
1142 (cond
1143 ((eq (car-safe action) 'boundaries)
1144 (let ((start (length (file-name-directory string)))
1145 (end (string-match-p "/" (cdr action))))
1146 (list* 'boundaries start end)))
1147
1148 ((eq action 'lambda)
1149 (if (zerop (length string))
1150 nil ;Not sure why it's here, but it probably doesn't harm.
1151 (funcall (or pred 'file-exists-p) string)))
1152
1153 (t
1154 (let* ((name (file-name-nondirectory string))
1155 (specdir (file-name-directory string))
1156 (realdir (or specdir default-directory)))
1157
1158 (cond
1159 ((null action)
1160 (let ((comp (file-name-completion name realdir pred)))
1161 (if (stringp comp)
1162 (concat specdir comp)
1163 comp)))
1164
1165 ((eq action t)
1166 (let ((all (file-name-all-completions name realdir)))
1167
1168 ;; Check the predicate, if necessary.
1169 (unless (memq pred '(nil file-exists-p))
1170 (let ((comp ())
1171 (pred
1172 (if (eq pred 'file-directory-p)
1173 ;; Brute-force speed up for directory checking:
1174 ;; Discard strings which don't end in a slash.
1175 (lambda (s)
1176 (let ((len (length s)))
1177 (and (> len 0) (eq (aref s (1- len)) ?/))))
1178 ;; Must do it the hard (and slow) way.
1179 pred)))
1180 (let ((default-directory (expand-file-name realdir)))
1181 (dolist (tem all)
1182 (if (funcall pred tem) (push tem comp))))
1183 (setq all (nreverse comp))))
1184
1185 all))))))))
1186
1187 (defvar read-file-name-predicate nil
1188 "Current predicate used by `read-file-name-internal'.")
1189 (make-obsolete-variable 'read-file-name-predicate
1190 "use the regular PRED argument" "23.2")
1191
1192 (defun completion--file-name-table (string pred action)
1193 "Internal subroutine for `read-file-name'. Do not call this.
1194 This is a completion table for file names, like `completion-file-name-table'
1195 except that it passes the file name through `substitute-in-file-name'."
1196 (cond
1197 ((eq (car-safe action) 'boundaries)
1198 ;; For the boundaries, we can't really delegate to
1199 ;; completion-file-name-table and then fix them up, because it
1200 ;; would require us to track the relationship between `str' and
1201 ;; `string', which is difficult. And in any case, if
1202 ;; substitute-in-file-name turns "fo-$TO-ba" into "fo-o/b-ba", there's
1203 ;; no way for us to return proper boundaries info, because the
1204 ;; boundary is not (yet) in `string'.
1205 (let ((start (length (file-name-directory string)))
1206 (end (string-match-p "/" (cdr action))))
1207 (list* 'boundaries start end)))
1208
1209 (t
1210 (let* ((default-directory
1211 (if (stringp pred)
1212 ;; It used to be that `pred' was abused to pass `dir'
1213 ;; as an argument.
1214 (prog1 (file-name-as-directory (expand-file-name pred))
1215 (setq pred nil))
1216 default-directory))
1217 (str (condition-case nil
1218 (substitute-in-file-name string)
1219 (error string)))
1220 (comp (completion-file-name-table
1221 str (or pred read-file-name-predicate) action)))
1222
1223 (cond
1224 ((stringp comp)
1225 ;; Requote the $s before returning the completion.
1226 (minibuffer--double-dollars comp))
1227 ((and (null action) comp
1228 ;; Requote the $s before checking for changes.
1229 (setq str (minibuffer--double-dollars str))
1230 (not (string-equal string str)))
1231 ;; If there's no real completion, but substitute-in-file-name
1232 ;; changed the string, then return the new string.
1233 str)
1234 (t comp))))))
1235
1236 (defalias 'read-file-name-internal
1237 (completion-table-in-turn 'completion--embedded-envvar-table
1238 'completion--file-name-table)
1239 "Internal subroutine for `read-file-name'. Do not call this.")
1240
1241 (defvar read-file-name-function nil
1242 "If this is non-nil, `read-file-name' does its work by calling this function.")
1243
1244 (defcustom read-file-name-completion-ignore-case
1245 (if (memq system-type '(ms-dos windows-nt darwin cygwin))
1246 t nil)
1247 "Non-nil means when reading a file name completion ignores case."
1248 :group 'minibuffer
1249 :type 'boolean
1250 :version "22.1")
1251
1252 (defcustom insert-default-directory t
1253 "Non-nil means when reading a filename start with default dir in minibuffer.
1254
1255 When the initial minibuffer contents show a name of a file or a directory,
1256 typing RETURN without editing the initial contents is equivalent to typing
1257 the default file name.
1258
1259 If this variable is non-nil, the minibuffer contents are always
1260 initially non-empty, and typing RETURN without editing will fetch the
1261 default name, if one is provided. Note however that this default name
1262 is not necessarily the same as initial contents inserted in the minibuffer,
1263 if the initial contents is just the default directory.
1264
1265 If this variable is nil, the minibuffer often starts out empty. In
1266 that case you may have to explicitly fetch the next history element to
1267 request the default name; typing RETURN without editing will leave
1268 the minibuffer empty.
1269
1270 For some commands, exiting with an empty minibuffer has a special meaning,
1271 such as making the current buffer visit no file in the case of
1272 `set-visited-file-name'."
1273 :group 'minibuffer
1274 :type 'boolean)
1275
1276 ;; Not always defined, but only called if next-read-file-uses-dialog-p says so.
1277 (declare-function x-file-dialog "xfns.c"
1278 (prompt dir &optional default-filename mustmatch only-dir-p))
1279
1280 (defun read-file-name (prompt &optional dir default-filename mustmatch initial predicate)
1281 "Read file name, prompting with PROMPT and completing in directory DIR.
1282 Value is not expanded---you must call `expand-file-name' yourself.
1283 Default name to DEFAULT-FILENAME if user exits the minibuffer with
1284 the same non-empty string that was inserted by this function.
1285 (If DEFAULT-FILENAME is omitted, the visited file name is used,
1286 except that if INITIAL is specified, that combined with DIR is used.
1287 If DEFAULT-FILENAME is a list of file names, the first file name is used.)
1288 If the user exits with an empty minibuffer, this function returns
1289 an empty string. (This can only happen if the user erased the
1290 pre-inserted contents or if `insert-default-directory' is nil.)
1291
1292 Fourth arg MUSTMATCH can take the following values:
1293 - nil means that the user can exit with any input.
1294 - t means that the user is not allowed to exit unless
1295 the input is (or completes to) an existing file.
1296 - `confirm' means that the user can exit with any input, but she needs
1297 to confirm her choice if the input is not an existing file.
1298 - `confirm-after-completion' means that the user can exit with any
1299 input, but she needs to confirm her choice if she called
1300 `minibuffer-complete' right before `minibuffer-complete-and-exit'
1301 and the input is not an existing file.
1302 - anything else behaves like t except that typing RET does not exit if it
1303 does non-null completion.
1304
1305 Fifth arg INITIAL specifies text to start with.
1306
1307 If optional sixth arg PREDICATE is non-nil, possible completions and
1308 the resulting file name must satisfy (funcall PREDICATE NAME).
1309 DIR should be an absolute directory name. It defaults to the value of
1310 `default-directory'.
1311
1312 If this command was invoked with the mouse, use a graphical file
1313 dialog if `use-dialog-box' is non-nil, and the window system or X
1314 toolkit in use provides a file dialog box, and DIR is not a
1315 remote file. For graphical file dialogs, any the special values
1316 of MUSTMATCH; `confirm' and `confirm-after-completion' are
1317 treated as equivalent to nil.
1318
1319 See also `read-file-name-completion-ignore-case'
1320 and `read-file-name-function'."
1321 (unless dir (setq dir default-directory))
1322 (unless (file-name-absolute-p dir) (setq dir (expand-file-name dir)))
1323 (unless default-filename
1324 (setq default-filename (if initial (expand-file-name initial dir)
1325 buffer-file-name)))
1326 ;; If dir starts with user's homedir, change that to ~.
1327 (setq dir (abbreviate-file-name dir))
1328 ;; Likewise for default-filename.
1329 (if default-filename
1330 (setq default-filename
1331 (if (consp default-filename)
1332 (mapcar 'abbreviate-file-name default-filename)
1333 (abbreviate-file-name default-filename))))
1334 (let ((insdef (cond
1335 ((and insert-default-directory (stringp dir))
1336 (if initial
1337 (cons (minibuffer--double-dollars (concat dir initial))
1338 (length (minibuffer--double-dollars dir)))
1339 (minibuffer--double-dollars dir)))
1340 (initial (cons (minibuffer--double-dollars initial) 0)))))
1341
1342 (if read-file-name-function
1343 (funcall read-file-name-function
1344 prompt dir default-filename mustmatch initial predicate)
1345 (let ((completion-ignore-case read-file-name-completion-ignore-case)
1346 (minibuffer-completing-file-name t)
1347 (pred (or predicate 'file-exists-p))
1348 (add-to-history nil))
1349
1350 (let* ((val
1351 (if (or (not (next-read-file-uses-dialog-p))
1352 ;; Graphical file dialogs can't handle remote
1353 ;; files (Bug#99).
1354 (file-remote-p dir))
1355 ;; We used to pass `dir' to `read-file-name-internal' by
1356 ;; abusing the `predicate' argument. It's better to
1357 ;; just use `default-directory', but in order to avoid
1358 ;; changing `default-directory' in the current buffer,
1359 ;; we don't let-bind it.
1360 (lexical-let ((dir (file-name-as-directory
1361 (expand-file-name dir))))
1362 (minibuffer-with-setup-hook
1363 (lambda () (setq default-directory dir))
1364 (completing-read prompt 'read-file-name-internal
1365 pred mustmatch insdef
1366 'file-name-history default-filename)))
1367 ;; If DEFAULT-FILENAME not supplied and DIR contains
1368 ;; a file name, split it.
1369 (let ((file (file-name-nondirectory dir))
1370 ;; When using a dialog, revert to nil and non-nil
1371 ;; interpretation of mustmatch. confirm options
1372 ;; need to be interpreted as nil, otherwise
1373 ;; it is impossible to create new files using
1374 ;; dialogs with the default settings.
1375 (dialog-mustmatch
1376 (not (memq mustmatch
1377 '(nil confirm confirm-after-completion)))))
1378 (when (and (not default-filename)
1379 (not (zerop (length file))))
1380 (setq default-filename file)
1381 (setq dir (file-name-directory dir)))
1382 (when default-filename
1383 (setq default-filename
1384 (expand-file-name (if (consp default-filename)
1385 (car default-filename)
1386 default-filename)
1387 dir)))
1388 (setq add-to-history t)
1389 (x-file-dialog prompt dir default-filename
1390 dialog-mustmatch
1391 (eq predicate 'file-directory-p)))))
1392
1393 (replace-in-history (eq (car-safe file-name-history) val)))
1394 ;; If completing-read returned the inserted default string itself
1395 ;; (rather than a new string with the same contents),
1396 ;; it has to mean that the user typed RET with the minibuffer empty.
1397 ;; In that case, we really want to return ""
1398 ;; so that commands such as set-visited-file-name can distinguish.
1399 (when (consp default-filename)
1400 (setq default-filename (car default-filename)))
1401 (when (eq val default-filename)
1402 ;; In this case, completing-read has not added an element
1403 ;; to the history. Maybe we should.
1404 (if (not replace-in-history)
1405 (setq add-to-history t))
1406 (setq val ""))
1407 (unless val (error "No file name specified"))
1408
1409 (if (and default-filename
1410 (string-equal val (if (consp insdef) (car insdef) insdef)))
1411 (setq val default-filename))
1412 (setq val (substitute-in-file-name val))
1413
1414 (if replace-in-history
1415 ;; Replace what Fcompleting_read added to the history
1416 ;; with what we will actually return. As an exception,
1417 ;; if that's the same as the second item in
1418 ;; file-name-history, it's really a repeat (Bug#4657).
1419 (let ((val1 (minibuffer--double-dollars val)))
1420 (if history-delete-duplicates
1421 (setcdr file-name-history
1422 (delete val1 (cdr file-name-history))))
1423 (if (string= val1 (cadr file-name-history))
1424 (pop file-name-history)
1425 (setcar file-name-history val1)))
1426 (if add-to-history
1427 ;; Add the value to the history--but not if it matches
1428 ;; the last value already there.
1429 (let ((val1 (minibuffer--double-dollars val)))
1430 (unless (and (consp file-name-history)
1431 (equal (car file-name-history) val1))
1432 (setq file-name-history
1433 (cons val1
1434 (if history-delete-duplicates
1435 (delete val1 file-name-history)
1436 file-name-history)))))))
1437 val)))))
1438
1439 (defun internal-complete-buffer-except (&optional buffer)
1440 "Perform completion on all buffers excluding BUFFER.
1441 BUFFER nil or omitted means use the current buffer.
1442 Like `internal-complete-buffer', but removes BUFFER from the completion list."
1443 (lexical-let ((except (if (stringp buffer) buffer (buffer-name buffer))))
1444 (apply-partially 'completion-table-with-predicate
1445 'internal-complete-buffer
1446 (lambda (name)
1447 (not (equal (if (consp name) (car name) name) except)))
1448 nil)))
1449
1450 ;;; Old-style completion, used in Emacs-21 and Emacs-22.
1451
1452 (defun completion-emacs21-try-completion (string table pred point)
1453 (let ((completion (try-completion string table pred)))
1454 (if (stringp completion)
1455 (cons completion (length completion))
1456 completion)))
1457
1458 (defun completion-emacs21-all-completions (string table pred point)
1459 (completion-hilit-commonality
1460 (all-completions string table pred)
1461 (length string)
1462 (car (completion-boundaries string table pred ""))))
1463
1464 (defun completion-emacs22-try-completion (string table pred point)
1465 (let ((suffix (substring string point))
1466 (completion (try-completion (substring string 0 point) table pred)))
1467 (if (not (stringp completion))
1468 completion
1469 ;; Merge a trailing / in completion with a / after point.
1470 ;; We used to only do it for word completion, but it seems to make
1471 ;; sense for all completions.
1472 ;; Actually, claiming this feature was part of Emacs-22 completion
1473 ;; is pushing it a bit: it was only done in minibuffer-completion-word,
1474 ;; which was (by default) not bound during file completion, where such
1475 ;; slashes are most likely to occur.
1476 (if (and (not (zerop (length completion)))
1477 (eq ?/ (aref completion (1- (length completion))))
1478 (not (zerop (length suffix)))
1479 (eq ?/ (aref suffix 0)))
1480 ;; This leaves point after the / .
1481 (setq suffix (substring suffix 1)))
1482 (cons (concat completion suffix) (length completion)))))
1483
1484 (defun completion-emacs22-all-completions (string table pred point)
1485 (let ((beforepoint (substring string 0 point)))
1486 (completion-hilit-commonality
1487 (all-completions beforepoint table pred)
1488 point
1489 (car (completion-boundaries beforepoint table pred "")))))
1490
1491 ;;; Basic completion.
1492
1493 (defun completion--merge-suffix (completion point suffix)
1494 "Merge end of COMPLETION with beginning of SUFFIX.
1495 Simple generalization of the \"merge trailing /\" done in Emacs-22.
1496 Return the new suffix."
1497 (if (and (not (zerop (length suffix)))
1498 (string-match "\\(.+\\)\n\\1" (concat completion "\n" suffix)
1499 ;; Make sure we don't compress things to less
1500 ;; than we started with.
1501 point)
1502 ;; Just make sure we didn't match some other \n.
1503 (eq (match-end 1) (length completion)))
1504 (substring suffix (- (match-end 1) (match-beginning 1)))
1505 ;; Nothing to merge.
1506 suffix))
1507
1508 (defun completion-basic-try-completion (string table pred point)
1509 (let* ((beforepoint (substring string 0 point))
1510 (afterpoint (substring string point))
1511 (bounds (completion-boundaries beforepoint table pred afterpoint)))
1512 (if (zerop (cdr bounds))
1513 ;; `try-completion' may return a subtly different result
1514 ;; than `all+merge', so try to use it whenever possible.
1515 (let ((completion (try-completion beforepoint table pred)))
1516 (if (not (stringp completion))
1517 completion
1518 (cons
1519 (concat completion
1520 (completion--merge-suffix completion point afterpoint))
1521 (length completion))))
1522 (let* ((suffix (substring afterpoint (cdr bounds)))
1523 (prefix (substring beforepoint 0 (car bounds)))
1524 (pattern (delete
1525 "" (list (substring beforepoint (car bounds))
1526 'point
1527 (substring afterpoint 0 (cdr bounds)))))
1528 (all (completion-pcm--all-completions prefix pattern table pred)))
1529 (if minibuffer-completing-file-name
1530 (setq all (completion-pcm--filename-try-filter all)))
1531 (completion-pcm--merge-try pattern all prefix suffix)))))
1532
1533 (defun completion-basic-all-completions (string table pred point)
1534 (let* ((beforepoint (substring string 0 point))
1535 (afterpoint (substring string point))
1536 (bounds (completion-boundaries beforepoint table pred afterpoint))
1537 (suffix (substring afterpoint (cdr bounds)))
1538 (prefix (substring beforepoint 0 (car bounds)))
1539 (pattern (delete
1540 "" (list (substring beforepoint (car bounds))
1541 'point
1542 (substring afterpoint 0 (cdr bounds)))))
1543 (all (completion-pcm--all-completions prefix pattern table pred)))
1544 (completion-hilit-commonality all point (car bounds))))
1545
1546 ;;; Partial-completion-mode style completion.
1547
1548 (defvar completion-pcm--delim-wild-regex nil
1549 "Regular expression matching delimiters controlling the partial-completion.
1550 Typically, this regular expression simply matches a delimiter, meaning
1551 that completion can add something at (match-beginning 0), but if it has
1552 a submatch 1, then completion can add something at (match-end 1).
1553 This is used when the delimiter needs to be of size zero (e.g. the transition
1554 from lowercase to uppercase characters).")
1555
1556 (defun completion-pcm--prepare-delim-re (delims)
1557 (setq completion-pcm--delim-wild-regex (concat "[" delims "*]")))
1558
1559 (defcustom completion-pcm-word-delimiters "-_. "
1560 "A string of characters treated as word delimiters for completion.
1561 Some arcane rules:
1562 If `]' is in this string, it must come first.
1563 If `^' is in this string, it must not come first.
1564 If `-' is in this string, it must come first or right after `]'.
1565 In other words, if S is this string, then `[S]' must be a valid Emacs regular
1566 expression (not containing character ranges like `a-z')."
1567 :set (lambda (symbol value)
1568 (set-default symbol value)
1569 ;; Refresh other vars.
1570 (completion-pcm--prepare-delim-re value))
1571 :initialize 'custom-initialize-reset
1572 :group 'minibuffer
1573 :type 'string)
1574
1575 (defun completion-pcm--pattern-trivial-p (pattern)
1576 (and (stringp (car pattern))
1577 ;; It can be followed by `point' and "" and still be trivial.
1578 (let ((trivial t))
1579 (dolist (elem (cdr pattern))
1580 (unless (member elem '(point ""))
1581 (setq trivial nil)))
1582 trivial)))
1583
1584 (defun completion-pcm--string->pattern (string &optional point)
1585 "Split STRING into a pattern.
1586 A pattern is a list where each element is either a string
1587 or a symbol chosen among `any', `star', `point'."
1588 (if (and point (< point (length string)))
1589 (let ((prefix (substring string 0 point))
1590 (suffix (substring string point)))
1591 (append (completion-pcm--string->pattern prefix)
1592 '(point)
1593 (completion-pcm--string->pattern suffix)))
1594 (let ((pattern nil)
1595 (p 0)
1596 (p0 0))
1597
1598 (while (and (setq p (string-match completion-pcm--delim-wild-regex
1599 string p))
1600 ;; If the char was added by minibuffer-complete-word, then
1601 ;; don't treat it as a delimiter, otherwise "M-x SPC"
1602 ;; ends up inserting a "-" rather than listing
1603 ;; all completions.
1604 (not (get-text-property p 'completion-try-word string)))
1605 ;; Usually, completion-pcm--delim-wild-regex matches a delimiter,
1606 ;; meaning that something can be added *before* it, but it can also
1607 ;; match a prefix and postfix, in which case something can be added
1608 ;; in-between (e.g. match [[:lower:]][[:upper:]]).
1609 ;; This is determined by the presence of a submatch-1 which delimits
1610 ;; the prefix.
1611 (if (match-end 1) (setq p (match-end 1)))
1612 (push (substring string p0 p) pattern)
1613 (if (eq (aref string p) ?*)
1614 (progn
1615 (push 'star pattern)
1616 (setq p0 (1+ p)))
1617 (push 'any pattern)
1618 (setq p0 p))
1619 (incf p))
1620
1621 ;; An empty string might be erroneously added at the beginning.
1622 ;; It should be avoided properly, but it's so easy to remove it here.
1623 (delete "" (nreverse (cons (substring string p0) pattern))))))
1624
1625 (defun completion-pcm--pattern->regex (pattern &optional group)
1626 (let ((re
1627 (concat "\\`"
1628 (mapconcat
1629 (lambda (x)
1630 (case x
1631 ((star any point)
1632 (if (if (consp group) (memq x group) group)
1633 "\\(.*?\\)" ".*?"))
1634 (t (regexp-quote x))))
1635 pattern
1636 ""))))
1637 ;; Avoid pathological backtracking.
1638 (while (string-match "\\.\\*\\?\\(?:\\\\[()]\\)*\\(\\.\\*\\?\\)" re)
1639 (setq re (replace-match "" t t re 1)))
1640 re))
1641
1642 (defun completion-pcm--all-completions (prefix pattern table pred)
1643 "Find all completions for PATTERN in TABLE obeying PRED.
1644 PATTERN is as returned by `completion-pcm--string->pattern'."
1645 ;; (assert (= (car (completion-boundaries prefix table pred ""))
1646 ;; (length prefix)))
1647 ;; Find an initial list of possible completions.
1648 (if (completion-pcm--pattern-trivial-p pattern)
1649
1650 ;; Minibuffer contains no delimiters -- simple case!
1651 (all-completions (concat prefix (car pattern)) table pred)
1652
1653 ;; Use all-completions to do an initial cull. This is a big win,
1654 ;; since all-completions is written in C!
1655 (let* (;; Convert search pattern to a standard regular expression.
1656 (regex (completion-pcm--pattern->regex pattern))
1657 (case-fold-search completion-ignore-case)
1658 (completion-regexp-list (cons regex completion-regexp-list))
1659 (compl (all-completions
1660 (concat prefix (if (stringp (car pattern)) (car pattern) ""))
1661 table pred)))
1662 (if (not (functionp table))
1663 ;; The internal functions already obeyed completion-regexp-list.
1664 compl
1665 (let ((poss ()))
1666 (dolist (c compl)
1667 (when (string-match-p regex c) (push c poss)))
1668 poss)))))
1669
1670 (defun completion-pcm--hilit-commonality (pattern completions)
1671 (when completions
1672 (let* ((re (completion-pcm--pattern->regex pattern '(point)))
1673 (case-fold-search completion-ignore-case))
1674 ;; Remove base-size during mapcar, and add it back later.
1675 (mapcar
1676 (lambda (str)
1677 ;; Don't modify the string itself.
1678 (setq str (copy-sequence str))
1679 (unless (string-match re str)
1680 (error "Internal error: %s does not match %s" re str))
1681 (let ((pos (or (match-beginning 1) (match-end 0))))
1682 (put-text-property 0 pos
1683 'font-lock-face 'completions-common-part
1684 str)
1685 (if (> (length str) pos)
1686 (put-text-property pos (1+ pos)
1687 'font-lock-face 'completions-first-difference
1688 str)))
1689 str)
1690 completions))))
1691
1692 (defun completion-pcm--find-all-completions (string table pred point
1693 &optional filter)
1694 "Find all completions for STRING at POINT in TABLE, satisfying PRED.
1695 POINT is a position inside STRING.
1696 FILTER is a function applied to the return value, that can be used, e.g. to
1697 filter out additional entries (because TABLE migth not obey PRED)."
1698 (unless filter (setq filter 'identity))
1699 (let* ((beforepoint (substring string 0 point))
1700 (afterpoint (substring string point))
1701 (bounds (completion-boundaries beforepoint table pred afterpoint))
1702 (prefix (substring beforepoint 0 (car bounds)))
1703 (suffix (substring afterpoint (cdr bounds)))
1704 firsterror)
1705 (setq string (substring string (car bounds) (+ point (cdr bounds))))
1706 (let* ((relpoint (- point (car bounds)))
1707 (pattern (completion-pcm--string->pattern string relpoint))
1708 (all (condition-case err
1709 (funcall filter
1710 (completion-pcm--all-completions
1711 prefix pattern table pred))
1712 (error (unless firsterror (setq firsterror err)) nil))))
1713 (when (and (null all)
1714 (> (car bounds) 0)
1715 (null (ignore-errors (try-completion prefix table pred))))
1716 ;; The prefix has no completions at all, so we should try and fix
1717 ;; that first.
1718 (let ((substring (substring prefix 0 -1)))
1719 (destructuring-bind (subpat suball subprefix subsuffix)
1720 (completion-pcm--find-all-completions
1721 substring table pred (length substring) filter)
1722 (let ((sep (aref prefix (1- (length prefix))))
1723 ;; Text that goes between the new submatches and the
1724 ;; completion substring.
1725 (between nil))
1726 ;; Eliminate submatches that don't end with the separator.
1727 (dolist (submatch (prog1 suball (setq suball ())))
1728 (when (eq sep (aref submatch (1- (length submatch))))
1729 (push submatch suball)))
1730 (when suball
1731 ;; Update the boundaries and corresponding pattern.
1732 ;; We assume that all submatches result in the same boundaries
1733 ;; since we wouldn't know how to merge them otherwise anyway.
1734 ;; FIXME: COMPLETE REWRITE!!!
1735 (let* ((newbeforepoint
1736 (concat subprefix (car suball)
1737 (substring string 0 relpoint)))
1738 (leftbound (+ (length subprefix) (length (car suball))))
1739 (newbounds (completion-boundaries
1740 newbeforepoint table pred afterpoint)))
1741 (unless (or (and (eq (cdr bounds) (cdr newbounds))
1742 (eq (car newbounds) leftbound))
1743 ;; Refuse new boundaries if they step over
1744 ;; the submatch.
1745 (< (car newbounds) leftbound))
1746 ;; The new completed prefix does change the boundaries
1747 ;; of the completed substring.
1748 (setq suffix (substring afterpoint (cdr newbounds)))
1749 (setq string
1750 (concat (substring newbeforepoint (car newbounds))
1751 (substring afterpoint 0 (cdr newbounds))))
1752 (setq between (substring newbeforepoint leftbound
1753 (car newbounds)))
1754 (setq pattern (completion-pcm--string->pattern
1755 string
1756 (- (length newbeforepoint)
1757 (car newbounds)))))
1758 (dolist (submatch suball)
1759 (setq all (nconc (mapcar
1760 (lambda (s) (concat submatch between s))
1761 (funcall filter
1762 (completion-pcm--all-completions
1763 (concat subprefix submatch between)
1764 pattern table pred)))
1765 all)))
1766 ;; FIXME: This can come in handy for try-completion,
1767 ;; but isn't right for all-completions, since it lists
1768 ;; invalid completions.
1769 ;; (unless all
1770 ;; ;; Even though we found expansions in the prefix, none
1771 ;; ;; leads to a valid completion.
1772 ;; ;; Let's keep the expansions, tho.
1773 ;; (dolist (submatch suball)
1774 ;; (push (concat submatch between newsubstring) all)))
1775 ))
1776 (setq pattern (append subpat (list 'any (string sep))
1777 (if between (list between)) pattern))
1778 (setq prefix subprefix)))))
1779 (if (and (null all) firsterror)
1780 (signal (car firsterror) (cdr firsterror))
1781 (list pattern all prefix suffix)))))
1782
1783 (defun completion-pcm-all-completions (string table pred point)
1784 (destructuring-bind (pattern all &optional prefix suffix)
1785 (completion-pcm--find-all-completions string table pred point)
1786 (when all
1787 (nconc (completion-pcm--hilit-commonality pattern all)
1788 (length prefix)))))
1789
1790 (defun completion-pcm--merge-completions (strs pattern)
1791 "Extract the commonality in STRS, with the help of PATTERN."
1792 ;; When completing while ignoring case, we want to try and avoid
1793 ;; completing "fo" to "foO" when completing against "FOO" (bug#4219).
1794 ;; So we try and make sure that the string we return is all made up
1795 ;; of text from the completions rather than part from the
1796 ;; completions and part from the input.
1797 ;; FIXME: This reduces the problems of inconsistent capitalization
1798 ;; but it doesn't fully fix it: we may still end up completing
1799 ;; "fo-ba" to "foo-BAR" or "FOO-bar" when completing against
1800 ;; '("foo-barr" "FOO-BARD").
1801 (cond
1802 ((null (cdr strs)) (list (car strs)))
1803 (t
1804 (let ((re (completion-pcm--pattern->regex pattern 'group))
1805 (ccs ())) ;Chopped completions.
1806
1807 ;; First chop each string into the parts corresponding to each
1808 ;; non-constant element of `pattern', using regexp-matching.
1809 (let ((case-fold-search completion-ignore-case))
1810 (dolist (str strs)
1811 (unless (string-match re str)
1812 (error "Internal error: %s doesn't match %s" str re))
1813 (let ((chopped ())
1814 (last 0)
1815 (i 1)
1816 next)
1817 (while (setq next (match-end i))
1818 (push (substring str last next) chopped)
1819 (setq last next)
1820 (setq i (1+ i)))
1821 ;; Add the text corresponding to the implicit trailing `any'.
1822 (push (substring str last) chopped)
1823 (push (nreverse chopped) ccs))))
1824
1825 ;; Then for each of those non-constant elements, extract the
1826 ;; commonality between them.
1827 (let ((res ())
1828 (fixed ""))
1829 ;; Make the implicit trailing `any' explicit.
1830 (dolist (elem (append pattern '(any)))
1831 (if (stringp elem)
1832 (setq fixed (concat fixed elem))
1833 (let ((comps ()))
1834 (dolist (cc (prog1 ccs (setq ccs nil)))
1835 (push (car cc) comps)
1836 (push (cdr cc) ccs))
1837 ;; Might improve the likelihood to avoid choosing
1838 ;; different capitalizations in different parts.
1839 ;; In practice, it doesn't seem to make any difference.
1840 (setq ccs (nreverse ccs))
1841 (let* ((prefix (try-completion fixed comps))
1842 (unique (or (and (eq prefix t) (setq prefix fixed))
1843 (eq t (try-completion prefix comps)))))
1844 (unless (equal prefix "") (push prefix res))
1845 ;; If there's only one completion, `elem' is not useful
1846 ;; any more: it can only match the empty string.
1847 ;; FIXME: in some cases, it may be necessary to turn an
1848 ;; `any' into a `star' because the surrounding context has
1849 ;; changed such that string->pattern wouldn't add an `any'
1850 ;; here any more.
1851 (unless unique (push elem res))
1852 (setq fixed "")))))
1853 ;; We return it in reverse order.
1854 res)))))
1855
1856 (defun completion-pcm--pattern->string (pattern)
1857 (mapconcat (lambda (x) (cond
1858 ((stringp x) x)
1859 ((eq x 'star) "*")
1860 ((eq x 'any) "")
1861 ((eq x 'point) "")))
1862 pattern
1863 ""))
1864
1865 ;; We want to provide the functionality of `try', but we use `all'
1866 ;; and then merge it. In most cases, this works perfectly, but
1867 ;; if the completion table doesn't consider the same completions in
1868 ;; `try' as in `all', then we have a problem. The most common such
1869 ;; case is for filename completion where completion-ignored-extensions
1870 ;; is only obeyed by the `try' code. We paper over the difference
1871 ;; here. Note that it is not quite right either: if the completion
1872 ;; table uses completion-table-in-turn, this filtering may take place
1873 ;; too late to correctly fallback from the first to the
1874 ;; second alternative.
1875 (defun completion-pcm--filename-try-filter (all)
1876 "Filter to adjust `all' file completion to the behavior of `try'."
1877 (when all
1878 (let ((try ())
1879 (re (concat "\\(?:\\`\\.\\.?/\\|"
1880 (regexp-opt completion-ignored-extensions)
1881 "\\)\\'")))
1882 (dolist (f all)
1883 (unless (string-match-p re f) (push f try)))
1884 (or try all))))
1885
1886
1887 (defun completion-pcm--merge-try (pattern all prefix suffix)
1888 (cond
1889 ((not (consp all)) all)
1890 ((and (not (consp (cdr all))) ;Only one completion.
1891 ;; Ignore completion-ignore-case here.
1892 (equal (completion-pcm--pattern->string pattern) (car all)))
1893 t)
1894 (t
1895 (let* ((mergedpat (completion-pcm--merge-completions all pattern))
1896 ;; `mergedpat' is in reverse order. Place new point (by
1897 ;; order of preference) either at the old point, or at
1898 ;; the last place where there's something to choose, or
1899 ;; at the very end.
1900 (pointpat (or (memq 'point mergedpat) (memq 'any mergedpat)
1901 mergedpat))
1902 ;; New pos from the start.
1903 (newpos (length (completion-pcm--pattern->string pointpat)))
1904 ;; Do it afterwards because it changes `pointpat' by sideeffect.
1905 (merged (completion-pcm--pattern->string (nreverse mergedpat))))
1906
1907 (setq suffix (completion--merge-suffix merged newpos suffix))
1908 (cons (concat prefix merged suffix) (+ newpos (length prefix)))))))
1909
1910 (defun completion-pcm-try-completion (string table pred point)
1911 (destructuring-bind (pattern all prefix suffix)
1912 (completion-pcm--find-all-completions
1913 string table pred point
1914 (if minibuffer-completing-file-name
1915 'completion-pcm--filename-try-filter))
1916 (completion-pcm--merge-try pattern all prefix suffix)))
1917
1918 ;;; Initials completion
1919 ;; Complete /ums to /usr/monnier/src or lch to list-command-history.
1920
1921 (defun completion-initials-expand (str table pred)
1922 (unless (or (zerop (length str))
1923 (string-match completion-pcm--delim-wild-regex str))
1924 (let ((bounds (completion-boundaries str table pred "")))
1925 (if (zerop (car bounds))
1926 (mapconcat 'string str "-")
1927 ;; If there's a boundary, it's trickier. The main use-case
1928 ;; we consider here is file-name completion. We'd like
1929 ;; to expand ~/eee to ~/e/e/e and /eee to /e/e/e.
1930 ;; But at the same time, we don't want /usr/share/ae to expand
1931 ;; to /usr/share/a/e just because we mistyped "ae" for "ar",
1932 ;; so we probably don't want initials to touch anything that
1933 ;; looks like /usr/share/foo. As a heuristic, we just check that
1934 ;; the text before the boundary char is at most 1 char.
1935 ;; This allows both ~/eee and /eee and not much more.
1936 ;; FIXME: It sadly also disallows the use of ~/eee when that's
1937 ;; embedded within something else (e.g. "(~/eee" in Info node
1938 ;; completion or "ancestor:/eee" in bzr-revision completion).
1939 (when (< (car bounds) 3)
1940 (let ((sep (substring str (1- (car bounds)) (car bounds))))
1941 ;; FIXME: the above string-match checks the whole string, whereas
1942 ;; we end up only caring about the after-boundary part.
1943 (concat (substring str 0 (car bounds))
1944 (mapconcat 'string (substring str (car bounds)) sep))))))))
1945
1946 (defun completion-initials-all-completions (string table pred point)
1947 (let ((newstr (completion-initials-expand string table pred)))
1948 (when newstr
1949 (completion-pcm-all-completions newstr table pred (length newstr)))))
1950
1951 (defun completion-initials-try-completion (string table pred point)
1952 (let ((newstr (completion-initials-expand string table pred)))
1953 (when newstr
1954 (completion-pcm-try-completion newstr table pred (length newstr)))))
1955
1956
1957 (provide 'minibuffer)
1958
1959 ;; arch-tag: ef8a0a15-1080-4790-a754-04017c02f08f
1960 ;;; minibuffer.el ends here