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