* minibuffer.el (read-file-name): Check for repeat before putting
[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. `base-size' gives the left
41 ;; boundary, but not the righthand one. So we need to add
42 ;; completion-extra-size.
43
44 ;;; Todo:
45
46 ;; - make partial-complete-mode obsolete:
47 ;; - (?) <foo.h> style completion for file names.
48
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".
56
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?
64
65 ;;; Code:
66
67 (eval-when-compile (require 'cl))
68
69 ;;; Completion table manipulation
70
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)))))
88
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))))))
101
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))))
112 (t
113 (funcall
114 (cond
115 ((null action) 'try-completion)
116 ((eq action t) 'all-completions)
117 (t 'test-completion))
118 string table pred))))
119
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.
127
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)))))
137
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.
146
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))))
155
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)))))
183
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)))
206
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))
220 (t
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))))))
232
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))))
240
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")
247
248 ;;; Minibuffer completion
249
250 (defgroup minibuffer nil
251 "Controlling the behavior of the minibuffer."
252 :link '(custom-manual "(emacs)Minibuffer")
253 :group 'environment)
254
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)))))
293
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)))
298
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)))
305
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)
314
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.")
343
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")
351
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))
364
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))
377
378 (defun minibuffer--bitset (modified completions exact)
379 (logior (if modified 4 0)
380 (if completions 2 0)
381 (if exact 1 0)))
382
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.
388
389 MCE
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.
415 (t
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
426
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))
433
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)
440
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)))))
463
464 (minibuffer--bitset completed t exact))))))))
465
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))
477
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)
489
490 (case (completion--do-completion)
491 (#b000 nil)
492 (#b001 (minibuffer-message "Sole completion")
493 t)
494 (#b011 (minibuffer-message "Complete, but not unique")
495 t)
496 (t t)))))
497
498 (defvar completion-all-sorted-completions nil)
499 (make-variable-buffer-local 'completion-all-sorted-completions)
500
501 (defun completion--flush-all-sorted-completions (&rest ignore)
502 (setq completion-all-sorted-completions nil))
503
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))))))
530
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 (let ((last (last all)))
550 (setcdr last (cons (car all) (cdr last)))
551 (setq completion-all-sorted-completions (cdr all))))))
552
553 (defvar minibuffer-confirm-exit-commands
554 '(minibuffer-complete minibuffer-complete-word PC-complete PC-complete-word)
555 "A list of commands which cause an immediately following
556 `minibuffer-complete-and-exit' to ask for extra confirmation.")
557
558 (defun minibuffer-complete-and-exit ()
559 "Exit if the minibuffer contains a valid completion.
560 Otherwise, try to complete the minibuffer contents. If
561 completion leads to a valid completion, a repetition of this
562 command will exit.
563
564 If `minibuffer-completion-confirm' is `confirm', do not try to
565 complete; instead, ask for confirmation and accept any input if
566 confirmed.
567 If `minibuffer-completion-confirm' is `confirm-after-completion',
568 do not try to complete; instead, ask for confirmation if the
569 preceding minibuffer command was a member of
570 `minibuffer-confirm-exit-commands', and accept the input
571 otherwise."
572 (interactive)
573 (let ((beg (field-beginning))
574 (end (field-end)))
575 (cond
576 ;; Allow user to specify null string
577 ((= beg end) (exit-minibuffer))
578 ((test-completion (buffer-substring beg end)
579 minibuffer-completion-table
580 minibuffer-completion-predicate)
581 (when completion-ignore-case
582 ;; Fixup case of the field, if necessary.
583 (let* ((string (buffer-substring beg end))
584 (compl (try-completion
585 string
586 minibuffer-completion-table
587 minibuffer-completion-predicate)))
588 (when (and (stringp compl)
589 ;; If it weren't for this piece of paranoia, I'd replace
590 ;; the whole thing with a call to do-completion.
591 ;; This is important, e.g. when the current minibuffer's
592 ;; content is a directory which only contains a single
593 ;; file, so `try-completion' actually completes to
594 ;; that file.
595 (= (length string) (length compl)))
596 (goto-char end)
597 (insert compl)
598 (delete-region beg end))))
599 (exit-minibuffer))
600
601 ((eq minibuffer-completion-confirm 'confirm)
602 ;; The user is permitted to exit with an input that's rejected
603 ;; by test-completion, after confirming her choice.
604 (if (eq last-command this-command)
605 (exit-minibuffer)
606 (minibuffer-message "Confirm")
607 nil))
608
609 ((eq minibuffer-completion-confirm 'confirm-after-completion)
610 ;; Similar to the above, but only if trying to exit immediately
611 ;; after typing TAB (this catches most minibuffer typos).
612 (if (memq last-command minibuffer-confirm-exit-commands)
613 (progn (minibuffer-message "Confirm")
614 nil)
615 (exit-minibuffer)))
616
617 (t
618 ;; Call do-completion, but ignore errors.
619 (case (condition-case nil
620 (completion--do-completion)
621 (error 1))
622 ((#b001 #b011) (exit-minibuffer))
623 (#b111 (if (not minibuffer-completion-confirm)
624 (exit-minibuffer)
625 (minibuffer-message "Confirm")
626 nil))
627 (t nil))))))
628
629 (defun completion--try-word-completion (string table predicate point)
630 (let ((comp (completion-try-completion string table predicate point)))
631 (if (not (consp comp))
632 comp
633
634 ;; If completion finds next char not unique,
635 ;; consider adding a space or a hyphen.
636 (when (= (length string) (length (car comp)))
637 ;; Mark the added char with the `completion-word' property, so it
638 ;; can be handled specially by completion styles such as
639 ;; partial-completion.
640 ;; We used to remove `partial-completion' from completion-styles
641 ;; instead, but it was too blunt, leading to situations where SPC
642 ;; was the only insertable char at point but minibuffer-complete-word
643 ;; refused inserting it.
644 (let ((exts (mapcar (lambda (str) (propertize str 'completion-try-word t))
645 '(" " "-")))
646 (before (substring string 0 point))
647 (after (substring string point))
648 tem)
649 (while (and exts (not (consp tem)))
650 (setq tem (completion-try-completion
651 (concat before (pop exts) after)
652 table predicate (1+ point))))
653 (if (consp tem) (setq comp tem))))
654
655 ;; Completing a single word is actually more difficult than completing
656 ;; as much as possible, because we first have to find the "current
657 ;; position" in `completion' in order to find the end of the word
658 ;; we're completing. Normally, `string' is a prefix of `completion',
659 ;; which makes it trivial to find the position, but with fancier
660 ;; completion (plus env-var expansion, ...) `completion' might not
661 ;; look anything like `string' at all.
662 (let* ((comppoint (cdr comp))
663 (completion (car comp))
664 (before (substring string 0 point))
665 (combined (concat before "\n" completion)))
666 ;; Find in completion the longest text that was right before point.
667 (when (string-match "\\(.+\\)\n.*?\\1" combined)
668 (let* ((prefix (match-string 1 before))
669 ;; We used non-greedy match to make `rem' as long as possible.
670 (rem (substring combined (match-end 0)))
671 ;; Find in the remainder of completion the longest text
672 ;; that was right after point.
673 (after (substring string point))
674 (suffix (if (string-match "\\`\\(.+\\).*\n.*\\1"
675 (concat after "\n" rem))
676 (match-string 1 after))))
677 ;; The general idea is to try and guess what text was inserted
678 ;; at point by the completion. Problem is: if we guess wrong,
679 ;; we may end up treating as "added by completion" text that was
680 ;; actually painfully typed by the user. So if we then cut
681 ;; after the first word, we may throw away things the
682 ;; user wrote. So let's try to be as conservative as possible:
683 ;; only cut after the first word, if we're reasonably sure that
684 ;; our guess is correct.
685 ;; Note: a quick survey on emacs-devel seemed to indicate that
686 ;; nobody actually cares about the "word-at-a-time" feature of
687 ;; minibuffer-complete-word, whose real raison-d'être is that it
688 ;; tries to add "-" or " ". One more reason to only cut after
689 ;; the first word, if we're really sure we're right.
690 (when (and (or suffix (zerop (length after)))
691 (string-match (concat
692 ;; Make submatch 1 as small as possible
693 ;; to reduce the risk of cutting
694 ;; valuable text.
695 ".*" (regexp-quote prefix) "\\(.*?\\)"
696 (if suffix (regexp-quote suffix) "\\'"))
697 completion)
698 ;; The new point in `completion' should also be just
699 ;; before the suffix, otherwise something more complex
700 ;; is going on, and we're not sure where we are.
701 (eq (match-end 1) comppoint)
702 ;; (match-beginning 1)..comppoint is now the stretch
703 ;; of text in `completion' that was completed at point.
704 (string-match "\\W" completion (match-beginning 1))
705 ;; Is there really something to cut?
706 (> comppoint (match-end 0)))
707 ;; Cut after the first word.
708 (let ((cutpos (match-end 0)))
709 (setq completion (concat (substring completion 0 cutpos)
710 (substring completion comppoint)))
711 (setq comppoint cutpos)))))
712
713 (cons completion comppoint)))))
714
715
716 (defun minibuffer-complete-word ()
717 "Complete the minibuffer contents at most a single word.
718 After one word is completed as much as possible, a space or hyphen
719 is added, provided that matches some possible completion.
720 Return nil if there is no valid completion, else t."
721 (interactive)
722 (case (completion--do-completion 'completion--try-word-completion)
723 (#b000 nil)
724 (#b001 (minibuffer-message "Sole completion")
725 t)
726 (#b011 (minibuffer-message "Complete, but not unique")
727 t)
728 (t t)))
729
730 (defface completions-annotations '((t :inherit italic))
731 "Face to use for annotations in the *Completions* buffer.")
732
733 (defun completion--insert-strings (strings)
734 "Insert a list of STRINGS into the current buffer.
735 Uses columns to keep the listing readable but compact.
736 It also eliminates runs of equal strings."
737 (when (consp strings)
738 (let* ((length (apply 'max
739 (mapcar (lambda (s)
740 (if (consp s)
741 (+ (string-width (car s))
742 (string-width (cadr s)))
743 (string-width s)))
744 strings)))
745 (window (get-buffer-window (current-buffer) 0))
746 (wwidth (if window (1- (window-width window)) 79))
747 (columns (min
748 ;; At least 2 columns; at least 2 spaces between columns.
749 (max 2 (/ wwidth (+ 2 length)))
750 ;; Don't allocate more columns than we can fill.
751 ;; Windows can't show less than 3 lines anyway.
752 (max 1 (/ (length strings) 2))))
753 (colwidth (/ wwidth columns))
754 (column 0)
755 (laststring nil))
756 ;; The insertion should be "sensible" no matter what choices were made
757 ;; for the parameters above.
758 (dolist (str strings)
759 (unless (equal laststring str) ; Remove (consecutive) duplicates.
760 (setq laststring str)
761 (let ((length (if (consp str)
762 (+ (string-width (car str))
763 (string-width (cadr str)))
764 (string-width str))))
765 (unless (bolp)
766 (if (< wwidth (+ (max colwidth length) column))
767 ;; No space for `str' at point, move to next line.
768 (progn (insert "\n") (setq column 0))
769 (insert " \t")
770 ;; Leave the space unpropertized so that in the case we're
771 ;; already past the goal column, there is still
772 ;; a space displayed.
773 (set-text-properties (- (point) 1) (point)
774 ;; We can't just set tab-width, because
775 ;; completion-setup-function will kill all
776 ;; local variables :-(
777 `(display (space :align-to ,column)))
778 nil))
779 (if (not (consp str))
780 (put-text-property (point) (progn (insert str) (point))
781 'mouse-face 'highlight)
782 (put-text-property (point) (progn (insert (car str)) (point))
783 'mouse-face 'highlight)
784 (add-text-properties (point) (progn (insert (cadr str)) (point))
785 '(mouse-face nil
786 face completions-annotations)))
787 ;; Next column to align to.
788 (setq column (+ column
789 ;; Round up to a whole number of columns.
790 (* colwidth (ceiling length colwidth))))))))))
791
792 (defvar completion-common-substring nil)
793 (make-obsolete-variable 'completion-common-substring nil "23.1")
794
795 (defvar completion-setup-hook nil
796 "Normal hook run at the end of setting up a completion list buffer.
797 When this hook is run, the current buffer is the one in which the
798 command to display the completion list buffer was run.
799 The completion list buffer is available as the value of `standard-output'.
800 See also `display-completion-list'.")
801
802 (defface completions-first-difference
803 '((t (:inherit bold)))
804 "Face put on the first uncommon character in completions in *Completions* buffer."
805 :group 'completion)
806
807 (defface completions-common-part
808 '((t (:inherit default)))
809 "Face put on the common prefix substring in completions in *Completions* buffer.
810 The idea of `completions-common-part' is that you can use it to
811 make the common parts less visible than normal, so that the rest
812 of the differing parts is, by contrast, slightly highlighted."
813 :group 'completion)
814
815 (defun completion-hilit-commonality (completions prefix-len base-size)
816 (when completions
817 (let ((com-str-len (- prefix-len (or base-size 0))))
818 (nconc
819 (mapcar
820 (lambda (elem)
821 (let ((str
822 ;; Don't modify the string itself, but a copy, since the
823 ;; the string may be read-only or used for other purposes.
824 ;; Furthermore, since `completions' may come from
825 ;; display-completion-list, `elem' may be a list.
826 (if (consp elem)
827 (car (setq elem (cons (copy-sequence (car elem))
828 (cdr elem))))
829 (setq elem (copy-sequence elem)))))
830 (put-text-property 0
831 ;; If completion-boundaries returns incorrect
832 ;; values, all-completions may return strings
833 ;; that don't contain the prefix.
834 (min com-str-len (length str))
835 'font-lock-face 'completions-common-part
836 str)
837 (if (> (length str) com-str-len)
838 (put-text-property com-str-len (1+ com-str-len)
839 'font-lock-face 'completions-first-difference
840 str)))
841 elem)
842 completions)
843 base-size))))
844
845 (defun display-completion-list (completions &optional common-substring)
846 "Display the list of completions, COMPLETIONS, using `standard-output'.
847 Each element may be just a symbol or string
848 or may be a list of two strings to be printed as if concatenated.
849 If it is a list of two strings, the first is the actual completion
850 alternative, the second serves as annotation.
851 `standard-output' must be a buffer.
852 The actual completion alternatives, as inserted, are given `mouse-face'
853 properties of `highlight'.
854 At the end, this runs the normal hook `completion-setup-hook'.
855 It can find the completion buffer in `standard-output'.
856
857 The obsolete optional arg COMMON-SUBSTRING, if non-nil, should be a string
858 specifying a common substring for adding the faces
859 `completions-first-difference' and `completions-common-part' to
860 the completions buffer."
861 (if common-substring
862 (setq completions (completion-hilit-commonality
863 completions (length common-substring)
864 ;; We don't know the base-size.
865 nil)))
866 (if (not (bufferp standard-output))
867 ;; This *never* (ever) happens, so there's no point trying to be clever.
868 (with-temp-buffer
869 (let ((standard-output (current-buffer))
870 (completion-setup-hook nil))
871 (display-completion-list completions common-substring))
872 (princ (buffer-string)))
873
874 (with-current-buffer standard-output
875 (goto-char (point-max))
876 (if (null completions)
877 (insert "There are no possible completions of what you have typed.")
878 (insert "Possible completions are:\n")
879 (completion--insert-strings completions))))
880
881 ;; The hilit used to be applied via completion-setup-hook, so there
882 ;; may still be some code that uses completion-common-substring.
883 (with-no-warnings
884 (let ((completion-common-substring common-substring))
885 (run-hooks 'completion-setup-hook)))
886 nil)
887
888 (defvar completion-annotate-function
889 nil
890 ;; Note: there's a lot of scope as for when to add annotations and
891 ;; what annotations to add. E.g. completing-help.el allowed adding
892 ;; the first line of docstrings to M-x completion. But there's
893 ;; a tension, since such annotations, while useful at times, can
894 ;; actually drown the useful information.
895 ;; So completion-annotate-function should be used parsimoniously, or
896 ;; else only used upon a user's request (e.g. we could add a command
897 ;; to completion-list-mode to add annotations to the current
898 ;; completions).
899 "Function to add annotations in the *Completions* buffer.
900 The function takes a completion and should either return nil, or a string that
901 will be displayed next to the completion. The function can access the
902 completion table and predicates via `minibuffer-completion-table' and related
903 variables.")
904
905 (defun minibuffer-completion-help ()
906 "Display a list of possible completions of the current minibuffer contents."
907 (interactive)
908 (message "Making completion list...")
909 (let* ((start (field-beginning))
910 (string (field-string))
911 (completions (completion-all-completions
912 string
913 minibuffer-completion-table
914 minibuffer-completion-predicate
915 (- (point) (field-beginning)))))
916 (message nil)
917 (if (and completions
918 (or (consp (cdr completions))
919 (not (equal (car completions) string))))
920 (with-output-to-temp-buffer "*Completions*"
921 (let* ((last (last completions))
922 (base-size (cdr last)))
923 ;; Remove the base-size tail because `sort' requires a properly
924 ;; nil-terminated list.
925 (when last (setcdr last nil))
926 (setq completions (sort completions 'string-lessp))
927 (when completion-annotate-function
928 (setq completions
929 (mapcar (lambda (s)
930 (let ((ann
931 (funcall completion-annotate-function s)))
932 (if ann (list s ann) s)))
933 completions)))
934 (with-current-buffer standard-output
935 (set (make-local-variable 'completion-base-position)
936 ;; FIXME: We should provide the END part as well, but
937 ;; currently completion-all-completions does not give
938 ;; us the necessary information.
939 (list (+ start base-size) nil)))
940 (display-completion-list completions)))
941
942 ;; If there are no completions, or if the current input is already the
943 ;; only possible completion, then hide (previous&stale) completions.
944 (let ((window (and (get-buffer "*Completions*")
945 (get-buffer-window "*Completions*" 0))))
946 (when (and (window-live-p window) (window-dedicated-p window))
947 (condition-case ()
948 (delete-window window)
949 (error (iconify-frame (window-frame window))))))
950 (ding)
951 (minibuffer-message
952 (if completions "Sole completion" "No completions")))
953 nil))
954
955 (defun minibuffer-hide-completions ()
956 "Get rid of an out-of-date *Completions* buffer."
957 ;; FIXME: We could/should use minibuffer-scroll-window here, but it
958 ;; can also point to the minibuffer-parent-window, so it's a bit tricky.
959 (let ((win (get-buffer-window "*Completions*" 0)))
960 (if win (with-selected-window win (bury-buffer)))))
961
962 (defun exit-minibuffer ()
963 "Terminate this minibuffer argument."
964 (interactive)
965 ;; If the command that uses this has made modifications in the minibuffer,
966 ;; we don't want them to cause deactivation of the mark in the original
967 ;; buffer.
968 ;; A better solution would be to make deactivate-mark buffer-local
969 ;; (or to turn it into a list of buffers, ...), but in the mean time,
970 ;; this should do the trick in most cases.
971 (setq deactivate-mark nil)
972 (throw 'exit nil))
973
974 (defun self-insert-and-exit ()
975 "Terminate minibuffer input."
976 (interactive)
977 (if (characterp last-command-event)
978 (call-interactively 'self-insert-command)
979 (ding))
980 (exit-minibuffer))
981
982 ;;; Key bindings.
983
984 (define-obsolete-variable-alias 'minibuffer-local-must-match-filename-map
985 'minibuffer-local-filename-must-match-map "23.1")
986
987 (let ((map minibuffer-local-map))
988 (define-key map "\C-g" 'abort-recursive-edit)
989 (define-key map "\r" 'exit-minibuffer)
990 (define-key map "\n" 'exit-minibuffer))
991
992 (let ((map minibuffer-local-completion-map))
993 (define-key map "\t" 'minibuffer-complete)
994 ;; M-TAB is already abused for many other purposes, so we should find
995 ;; another binding for it.
996 ;; (define-key map "\e\t" 'minibuffer-force-complete)
997 (define-key map " " 'minibuffer-complete-word)
998 (define-key map "?" 'minibuffer-completion-help))
999
1000 (let ((map minibuffer-local-must-match-map))
1001 (define-key map "\r" 'minibuffer-complete-and-exit)
1002 (define-key map "\n" 'minibuffer-complete-and-exit))
1003
1004 (let ((map minibuffer-local-filename-completion-map))
1005 (define-key map " " nil))
1006 (let ((map minibuffer-local-filename-must-match-map))
1007 (define-key map " " nil))
1008
1009 (let ((map minibuffer-local-ns-map))
1010 (define-key map " " 'exit-minibuffer)
1011 (define-key map "\t" 'exit-minibuffer)
1012 (define-key map "?" 'self-insert-and-exit))
1013
1014 ;;; Completion tables.
1015
1016 (defun minibuffer--double-dollars (str)
1017 (replace-regexp-in-string "\\$" "$$" str))
1018
1019 (defun completion--make-envvar-table ()
1020 (mapcar (lambda (enventry)
1021 (substring enventry 0 (string-match-p "=" enventry)))
1022 process-environment))
1023
1024 (defconst completion--embedded-envvar-re
1025 (concat "\\(?:^\\|[^$]\\(?:\\$\\$\\)*\\)"
1026 "$\\([[:alnum:]_]*\\|{\\([^}]*\\)\\)\\'"))
1027
1028 (defun completion--embedded-envvar-table (string pred action)
1029 (if (eq (car-safe action) 'boundaries)
1030 ;; Compute the boundaries of the subfield to which this
1031 ;; completion applies.
1032 (let ((suffix (cdr action)))
1033 (if (string-match completion--embedded-envvar-re string)
1034 (list* 'boundaries
1035 (or (match-beginning 2) (match-beginning 1))
1036 (when (string-match "[^[:alnum:]_]" suffix)
1037 (match-beginning 0)))))
1038 (when (string-match completion--embedded-envvar-re string)
1039 (let* ((beg (or (match-beginning 2) (match-beginning 1)))
1040 (table (completion--make-envvar-table))
1041 (prefix (substring string 0 beg)))
1042 (if (eq (aref string (1- beg)) ?{)
1043 (setq table (apply-partially 'completion-table-with-terminator
1044 "}" table)))
1045 ;; Even if file-name completion is case-insensitive, we want
1046 ;; envvar completion to be case-sensitive.
1047 (let ((completion-ignore-case nil))
1048 (completion-table-with-context
1049 prefix table (substring string beg) pred action))))))
1050
1051 (defun completion--file-name-table (string pred action)
1052 "Internal subroutine for `read-file-name'. Do not call this."
1053 (cond
1054 ((and (zerop (length string)) (eq 'lambda action))
1055 nil) ; FIXME: why?
1056 ((eq (car-safe action) 'boundaries)
1057 ;; FIXME: Actually, this is not always right in the presence of
1058 ;; envvars, but there's not much we can do, I think.
1059 (let ((start (length (file-name-directory string)))
1060 (end (string-match-p "/" (cdr action))))
1061 (list* 'boundaries start end)))
1062
1063 (t
1064 (let* ((dir (if (stringp pred)
1065 ;; It used to be that `pred' was abused to pass `dir'
1066 ;; as an argument.
1067 (prog1 (expand-file-name pred) (setq pred nil))
1068 default-directory))
1069 (str (condition-case nil
1070 (substitute-in-file-name string)
1071 (error string)))
1072 (name (file-name-nondirectory str))
1073 (specdir (file-name-directory str))
1074 (realdir (if specdir (expand-file-name specdir dir)
1075 (file-name-as-directory dir))))
1076
1077 (cond
1078 ((null action)
1079 (let ((comp (file-name-completion name realdir
1080 read-file-name-predicate)))
1081 (cond
1082 ((stringp comp)
1083 ;; Requote the $s before returning the completion.
1084 (minibuffer--double-dollars (concat specdir comp)))
1085 (comp
1086 ;; Requote the $s before checking for changes.
1087 (setq str (minibuffer--double-dollars str))
1088 (if (string-equal string str)
1089 comp
1090 ;; If there's no real completion, but substitute-in-file-name
1091 ;; changed the string, then return the new string.
1092 str)))))
1093
1094 ((eq action t)
1095 (let ((all (file-name-all-completions name realdir)))
1096
1097 ;; Check the predicate, if necessary.
1098 (unless (memq read-file-name-predicate '(nil file-exists-p))
1099 (let ((comp ())
1100 (pred
1101 (if (eq read-file-name-predicate 'file-directory-p)
1102 ;; Brute-force speed up for directory checking:
1103 ;; Discard strings which don't end in a slash.
1104 (lambda (s)
1105 (let ((len (length s)))
1106 (and (> len 0) (eq (aref s (1- len)) ?/))))
1107 ;; Must do it the hard (and slow) way.
1108 read-file-name-predicate)))
1109 (let ((default-directory realdir))
1110 (dolist (tem all)
1111 (if (funcall pred tem) (push tem comp))))
1112 (setq all (nreverse comp))))
1113
1114 all))
1115
1116 (t
1117 ;; Only other case actually used is ACTION = lambda.
1118 (let ((default-directory dir))
1119 (funcall (or read-file-name-predicate 'file-exists-p) str))))))))
1120
1121 (defalias 'read-file-name-internal
1122 (completion-table-in-turn 'completion--embedded-envvar-table
1123 'completion--file-name-table)
1124 "Internal subroutine for `read-file-name'. Do not call this.")
1125
1126 (defvar read-file-name-function nil
1127 "If this is non-nil, `read-file-name' does its work by calling this function.")
1128
1129 (defvar read-file-name-predicate nil
1130 "Current predicate used by `read-file-name-internal'.")
1131
1132 (defcustom read-file-name-completion-ignore-case
1133 (if (memq system-type '(ms-dos windows-nt darwin cygwin))
1134 t nil)
1135 "Non-nil means when reading a file name completion ignores case."
1136 :group 'minibuffer
1137 :type 'boolean
1138 :version "22.1")
1139
1140 (defcustom insert-default-directory t
1141 "Non-nil means when reading a filename start with default dir in minibuffer.
1142
1143 When the initial minibuffer contents show a name of a file or a directory,
1144 typing RETURN without editing the initial contents is equivalent to typing
1145 the default file name.
1146
1147 If this variable is non-nil, the minibuffer contents are always
1148 initially non-empty, and typing RETURN without editing will fetch the
1149 default name, if one is provided. Note however that this default name
1150 is not necessarily the same as initial contents inserted in the minibuffer,
1151 if the initial contents is just the default directory.
1152
1153 If this variable is nil, the minibuffer often starts out empty. In
1154 that case you may have to explicitly fetch the next history element to
1155 request the default name; typing RETURN without editing will leave
1156 the minibuffer empty.
1157
1158 For some commands, exiting with an empty minibuffer has a special meaning,
1159 such as making the current buffer visit no file in the case of
1160 `set-visited-file-name'."
1161 :group 'minibuffer
1162 :type 'boolean)
1163
1164 ;; Not always defined, but only called if next-read-file-uses-dialog-p says so.
1165 (declare-function x-file-dialog "xfns.c"
1166 (prompt dir &optional default-filename mustmatch only-dir-p))
1167
1168 (defun read-file-name (prompt &optional dir default-filename mustmatch initial predicate)
1169 "Read file name, prompting with PROMPT and completing in directory DIR.
1170 Value is not expanded---you must call `expand-file-name' yourself.
1171 Default name to DEFAULT-FILENAME if user exits the minibuffer with
1172 the same non-empty string that was inserted by this function.
1173 (If DEFAULT-FILENAME is omitted, the visited file name is used,
1174 except that if INITIAL is specified, that combined with DIR is used.)
1175 If the user exits with an empty minibuffer, this function returns
1176 an empty string. (This can only happen if the user erased the
1177 pre-inserted contents or if `insert-default-directory' is nil.)
1178
1179 Fourth arg MUSTMATCH can take the following values:
1180 - nil means that the user can exit with any input.
1181 - t means that the user is not allowed to exit unless
1182 the input is (or completes to) an existing file.
1183 - `confirm' means that the user can exit with any input, but she needs
1184 to confirm her choice if the input is not an existing file.
1185 - `confirm-after-completion' means that the user can exit with any
1186 input, but she needs to confirm her choice if she called
1187 `minibuffer-complete' right before `minibuffer-complete-and-exit'
1188 and the input is not an existing file.
1189 - anything else behaves like t except that typing RET does not exit if it
1190 does non-null completion.
1191
1192 Fifth arg INITIAL specifies text to start with.
1193
1194 If optional sixth arg PREDICATE is non-nil, possible completions and
1195 the resulting file name must satisfy (funcall PREDICATE NAME).
1196 DIR should be an absolute directory name. It defaults to the value of
1197 `default-directory'.
1198
1199 If this command was invoked with the mouse, use a graphical file
1200 dialog if `use-dialog-box' is non-nil, and the window system or X
1201 toolkit in use provides a file dialog box. For graphical file
1202 dialogs, any the special values of MUSTMATCH; `confirm' and
1203 `confirm-after-completion' are treated as equivalent to nil.
1204
1205 See also `read-file-name-completion-ignore-case'
1206 and `read-file-name-function'."
1207 (unless dir (setq dir default-directory))
1208 (unless (file-name-absolute-p dir) (setq dir (expand-file-name dir)))
1209 (unless default-filename
1210 (setq default-filename (if initial (expand-file-name initial dir)
1211 buffer-file-name)))
1212 ;; If dir starts with user's homedir, change that to ~.
1213 (setq dir (abbreviate-file-name dir))
1214 ;; Likewise for default-filename.
1215 (if default-filename
1216 (setq default-filename (abbreviate-file-name default-filename)))
1217 (let ((insdef (cond
1218 ((and insert-default-directory (stringp dir))
1219 (if initial
1220 (cons (minibuffer--double-dollars (concat dir initial))
1221 (length (minibuffer--double-dollars dir)))
1222 (minibuffer--double-dollars dir)))
1223 (initial (cons (minibuffer--double-dollars initial) 0)))))
1224
1225 (if read-file-name-function
1226 (funcall read-file-name-function
1227 prompt dir default-filename mustmatch initial predicate)
1228 (let ((completion-ignore-case read-file-name-completion-ignore-case)
1229 (minibuffer-completing-file-name t)
1230 (read-file-name-predicate (or predicate 'file-exists-p))
1231 (add-to-history nil))
1232
1233 (let* ((val
1234 (if (not (next-read-file-uses-dialog-p))
1235 ;; We used to pass `dir' to `read-file-name-internal' by
1236 ;; abusing the `predicate' argument. It's better to
1237 ;; just use `default-directory', but in order to avoid
1238 ;; changing `default-directory' in the current buffer,
1239 ;; we don't let-bind it.
1240 (lexical-let ((dir (file-name-as-directory
1241 (expand-file-name dir))))
1242 (minibuffer-with-setup-hook
1243 (lambda () (setq default-directory dir))
1244 (completing-read prompt 'read-file-name-internal
1245 nil mustmatch insdef 'file-name-history
1246 default-filename)))
1247 ;; If DEFAULT-FILENAME not supplied and DIR contains
1248 ;; a file name, split it.
1249 (let ((file (file-name-nondirectory dir))
1250 ;; When using a dialog, revert to nil and non-nil
1251 ;; interpretation of mustmatch. confirm options
1252 ;; need to be interpreted as nil, otherwise
1253 ;; it is impossible to create new files using
1254 ;; dialogs with the default settings.
1255 (dialog-mustmatch
1256 (and (not (eq mustmatch 'confirm))
1257 (not (eq mustmatch 'confirm-after-completion))
1258 mustmatch)))
1259 (when (and (not default-filename)
1260 (not (zerop (length file))))
1261 (setq default-filename file)
1262 (setq dir (file-name-directory dir)))
1263 (if default-filename
1264 (setq default-filename
1265 (expand-file-name default-filename dir)))
1266 (setq add-to-history t)
1267 (x-file-dialog prompt dir default-filename
1268 dialog-mustmatch
1269 (eq predicate 'file-directory-p)))))
1270
1271 (replace-in-history (eq (car-safe file-name-history) val)))
1272 ;; If completing-read returned the inserted default string itself
1273 ;; (rather than a new string with the same contents),
1274 ;; it has to mean that the user typed RET with the minibuffer empty.
1275 ;; In that case, we really want to return ""
1276 ;; so that commands such as set-visited-file-name can distinguish.
1277 (when (eq val default-filename)
1278 ;; In this case, completing-read has not added an element
1279 ;; to the history. Maybe we should.
1280 (if (not replace-in-history)
1281 (setq add-to-history t))
1282 (setq val ""))
1283 (unless val (error "No file name specified"))
1284
1285 (if (and default-filename
1286 (string-equal val (if (consp insdef) (car insdef) insdef)))
1287 (setq val default-filename))
1288 (setq val (substitute-in-file-name val))
1289
1290 (if replace-in-history
1291 ;; Replace what Fcompleting_read added to the history
1292 ;; with what we will actually return. As an exception,
1293 ;; if that's the same as the second item in
1294 ;; file-name-history, it's really a repeat (Bug#4657).
1295 (let ((val1 (minibuffer--double-dollars val)))
1296 (if history-delete-duplicates
1297 (setcdr file-name-history
1298 (delete val1 (cdr file-name-history))))
1299 (if (string= val1 (cadr file-name-history))
1300 (pop file-name-history)
1301 (setcar file-name-history val1)))
1302 (if add-to-history
1303 ;; Add the value to the history--but not if it matches
1304 ;; the last value already there.
1305 (let ((val1 (minibuffer--double-dollars val)))
1306 (unless (and (consp file-name-history)
1307 (equal (car file-name-history) val1))
1308 (setq file-name-history
1309 (cons val1
1310 (if history-delete-duplicates
1311 (delete val1 file-name-history)
1312 file-name-history)))))))
1313 val)))))
1314
1315 (defun internal-complete-buffer-except (&optional buffer)
1316 "Perform completion on all buffers excluding BUFFER.
1317 BUFFER nil or omitted means use the current buffer.
1318 Like `internal-complete-buffer', but removes BUFFER from the completion list."
1319 (lexical-let ((except (if (stringp buffer) buffer (buffer-name buffer))))
1320 (apply-partially 'completion-table-with-predicate
1321 'internal-complete-buffer
1322 (lambda (name)
1323 (not (equal (if (consp name) (car name) name) except)))
1324 nil)))
1325
1326 ;;; Old-style completion, used in Emacs-21 and Emacs-22.
1327
1328 (defun completion-emacs21-try-completion (string table pred point)
1329 (let ((completion (try-completion string table pred)))
1330 (if (stringp completion)
1331 (cons completion (length completion))
1332 completion)))
1333
1334 (defun completion-emacs21-all-completions (string table pred point)
1335 (completion-hilit-commonality
1336 (all-completions string table pred)
1337 (length string)
1338 (car (completion-boundaries string table pred ""))))
1339
1340 (defun completion-emacs22-try-completion (string table pred point)
1341 (let ((suffix (substring string point))
1342 (completion (try-completion (substring string 0 point) table pred)))
1343 (if (not (stringp completion))
1344 completion
1345 ;; Merge a trailing / in completion with a / after point.
1346 ;; We used to only do it for word completion, but it seems to make
1347 ;; sense for all completions.
1348 ;; Actually, claiming this feature was part of Emacs-22 completion
1349 ;; is pushing it a bit: it was only done in minibuffer-completion-word,
1350 ;; which was (by default) not bound during file completion, where such
1351 ;; slashes are most likely to occur.
1352 (if (and (not (zerop (length completion)))
1353 (eq ?/ (aref completion (1- (length completion))))
1354 (not (zerop (length suffix)))
1355 (eq ?/ (aref suffix 0)))
1356 ;; This leaves point after the / .
1357 (setq suffix (substring suffix 1)))
1358 (cons (concat completion suffix) (length completion)))))
1359
1360 (defun completion-emacs22-all-completions (string table pred point)
1361 (let ((beforepoint (substring string 0 point)))
1362 (completion-hilit-commonality
1363 (all-completions beforepoint table pred)
1364 point
1365 (car (completion-boundaries beforepoint table pred "")))))
1366
1367 ;;; Basic completion.
1368
1369 (defun completion--merge-suffix (completion point suffix)
1370 "Merge end of COMPLETION with beginning of SUFFIX.
1371 Simple generalization of the \"merge trailing /\" done in Emacs-22.
1372 Return the new suffix."
1373 (if (and (not (zerop (length suffix)))
1374 (string-match "\\(.+\\)\n\\1" (concat completion "\n" suffix)
1375 ;; Make sure we don't compress things to less
1376 ;; than we started with.
1377 point)
1378 ;; Just make sure we didn't match some other \n.
1379 (eq (match-end 1) (length completion)))
1380 (substring suffix (- (match-end 1) (match-beginning 1)))
1381 ;; Nothing to merge.
1382 suffix))
1383
1384 (defun completion-basic-try-completion (string table pred point)
1385 (let* ((beforepoint (substring string 0 point))
1386 (afterpoint (substring string point))
1387 (bounds (completion-boundaries beforepoint table pred afterpoint)))
1388 (if (zerop (cdr bounds))
1389 ;; `try-completion' may return a subtly different result
1390 ;; than `all+merge', so try to use it whenever possible.
1391 (let ((completion (try-completion beforepoint table pred)))
1392 (if (not (stringp completion))
1393 completion
1394 (cons
1395 (concat completion
1396 (completion--merge-suffix completion point afterpoint))
1397 (length completion))))
1398 (let* ((suffix (substring afterpoint (cdr bounds)))
1399 (prefix (substring beforepoint 0 (car bounds)))
1400 (pattern (delete
1401 "" (list (substring beforepoint (car bounds))
1402 'point
1403 (substring afterpoint 0 (cdr bounds)))))
1404 (all (completion-pcm--all-completions prefix pattern table pred)))
1405 (if minibuffer-completing-file-name
1406 (setq all (completion-pcm--filename-try-filter all)))
1407 (completion-pcm--merge-try pattern all prefix suffix)))))
1408
1409 (defun completion-basic-all-completions (string table pred point)
1410 (let* ((beforepoint (substring string 0 point))
1411 (afterpoint (substring string point))
1412 (bounds (completion-boundaries beforepoint table pred afterpoint))
1413 (suffix (substring afterpoint (cdr bounds)))
1414 (prefix (substring beforepoint 0 (car bounds)))
1415 (pattern (delete
1416 "" (list (substring beforepoint (car bounds))
1417 'point
1418 (substring afterpoint 0 (cdr bounds)))))
1419 (all (completion-pcm--all-completions prefix pattern table pred)))
1420 (completion-hilit-commonality all point (car bounds))))
1421
1422 ;;; Partial-completion-mode style completion.
1423
1424 (defvar completion-pcm--delim-wild-regex nil
1425 "Regular expression matching delimiters controlling the partial-completion.
1426 Typically, this regular expression simply matches a delimiter, meaning
1427 that completion can add something at (match-beginning 0), but if it has
1428 a submatch 1, then completion can add something at (match-end 1).
1429 This is used when the delimiter needs to be of size zero (e.g. the transition
1430 from lowercase to uppercase characters).")
1431
1432 (defun completion-pcm--prepare-delim-re (delims)
1433 (setq completion-pcm--delim-wild-regex (concat "[" delims "*]")))
1434
1435 (defcustom completion-pcm-word-delimiters "-_. "
1436 "A string of characters treated as word delimiters for completion.
1437 Some arcane rules:
1438 If `]' is in this string, it must come first.
1439 If `^' is in this string, it must not come first.
1440 If `-' is in this string, it must come first or right after `]'.
1441 In other words, if S is this string, then `[S]' must be a valid Emacs regular
1442 expression (not containing character ranges like `a-z')."
1443 :set (lambda (symbol value)
1444 (set-default symbol value)
1445 ;; Refresh other vars.
1446 (completion-pcm--prepare-delim-re value))
1447 :initialize 'custom-initialize-reset
1448 :group 'minibuffer
1449 :type 'string)
1450
1451 (defun completion-pcm--pattern-trivial-p (pattern)
1452 (and (stringp (car pattern))
1453 ;; It can be followed by `point' and "" and still be trivial.
1454 (let ((trivial t))
1455 (dolist (elem (cdr pattern))
1456 (unless (member elem '(point ""))
1457 (setq trivial nil)))
1458 trivial)))
1459
1460 (defun completion-pcm--string->pattern (string &optional point)
1461 "Split STRING into a pattern.
1462 A pattern is a list where each element is either a string
1463 or a symbol chosen among `any', `star', `point'."
1464 (if (and point (< point (length string)))
1465 (let ((prefix (substring string 0 point))
1466 (suffix (substring string point)))
1467 (append (completion-pcm--string->pattern prefix)
1468 '(point)
1469 (completion-pcm--string->pattern suffix)))
1470 (let ((pattern nil)
1471 (p 0)
1472 (p0 0))
1473
1474 (while (and (setq p (string-match completion-pcm--delim-wild-regex
1475 string p))
1476 ;; If the char was added by minibuffer-complete-word, then
1477 ;; don't treat it as a delimiter, otherwise "M-x SPC"
1478 ;; ends up inserting a "-" rather than listing
1479 ;; all completions.
1480 (not (get-text-property p 'completion-try-word string)))
1481 ;; Usually, completion-pcm--delim-wild-regex matches a delimiter,
1482 ;; meaning that something can be added *before* it, but it can also
1483 ;; match a prefix and postfix, in which case something can be added
1484 ;; in-between (e.g. match [[:lower:]][[:upper:]]).
1485 ;; This is determined by the presence of a submatch-1 which delimits
1486 ;; the prefix.
1487 (if (match-end 1) (setq p (match-end 1)))
1488 (push (substring string p0 p) pattern)
1489 (if (eq (aref string p) ?*)
1490 (progn
1491 (push 'star pattern)
1492 (setq p0 (1+ p)))
1493 (push 'any pattern)
1494 (setq p0 p))
1495 (incf p))
1496
1497 ;; An empty string might be erroneously added at the beginning.
1498 ;; It should be avoided properly, but it's so easy to remove it here.
1499 (delete "" (nreverse (cons (substring string p0) pattern))))))
1500
1501 (defun completion-pcm--pattern->regex (pattern &optional group)
1502 (let ((re
1503 (concat "\\`"
1504 (mapconcat
1505 (lambda (x)
1506 (case x
1507 ((star any point)
1508 (if (if (consp group) (memq x group) group)
1509 "\\(.*?\\)" ".*?"))
1510 (t (regexp-quote x))))
1511 pattern
1512 ""))))
1513 ;; Avoid pathological backtracking.
1514 (while (string-match "\\.\\*\\?\\(?:\\\\[()]\\)*\\(\\.\\*\\?\\)" re)
1515 (setq re (replace-match "" t t re 1)))
1516 re))
1517
1518 (defun completion-pcm--all-completions (prefix pattern table pred)
1519 "Find all completions for PATTERN in TABLE obeying PRED.
1520 PATTERN is as returned by `completion-pcm--string->pattern'."
1521 ;; (assert (= (car (completion-boundaries prefix table pred ""))
1522 ;; (length prefix)))
1523 ;; Find an initial list of possible completions.
1524 (if (completion-pcm--pattern-trivial-p pattern)
1525
1526 ;; Minibuffer contains no delimiters -- simple case!
1527 (all-completions (concat prefix (car pattern)) table pred)
1528
1529 ;; Use all-completions to do an initial cull. This is a big win,
1530 ;; since all-completions is written in C!
1531 (let* (;; Convert search pattern to a standard regular expression.
1532 (regex (completion-pcm--pattern->regex pattern))
1533 (case-fold-search completion-ignore-case)
1534 (completion-regexp-list (cons regex completion-regexp-list))
1535 (compl (all-completions
1536 (concat prefix (if (stringp (car pattern)) (car pattern) ""))
1537 table pred)))
1538 (if (not (functionp table))
1539 ;; The internal functions already obeyed completion-regexp-list.
1540 compl
1541 (let ((poss ()))
1542 (dolist (c compl)
1543 (when (string-match-p regex c) (push c poss)))
1544 poss)))))
1545
1546 (defun completion-pcm--hilit-commonality (pattern completions)
1547 (when completions
1548 (let* ((re (completion-pcm--pattern->regex pattern '(point)))
1549 (case-fold-search completion-ignore-case))
1550 ;; Remove base-size during mapcar, and add it back later.
1551 (mapcar
1552 (lambda (str)
1553 ;; Don't modify the string itself.
1554 (setq str (copy-sequence str))
1555 (unless (string-match re str)
1556 (error "Internal error: %s does not match %s" re str))
1557 (let ((pos (or (match-beginning 1) (match-end 0))))
1558 (put-text-property 0 pos
1559 'font-lock-face 'completions-common-part
1560 str)
1561 (if (> (length str) pos)
1562 (put-text-property pos (1+ pos)
1563 'font-lock-face 'completions-first-difference
1564 str)))
1565 str)
1566 completions))))
1567
1568 (defun completion-pcm--find-all-completions (string table pred point
1569 &optional filter)
1570 "Find all completions for STRING at POINT in TABLE, satisfying PRED.
1571 POINT is a position inside STRING.
1572 FILTER is a function applied to the return value, that can be used, e.g. to
1573 filter out additional entries (because TABLE migth not obey PRED)."
1574 (unless filter (setq filter 'identity))
1575 (let* ((beforepoint (substring string 0 point))
1576 (afterpoint (substring string point))
1577 (bounds (completion-boundaries beforepoint table pred afterpoint))
1578 (prefix (substring beforepoint 0 (car bounds)))
1579 (suffix (substring afterpoint (cdr bounds)))
1580 firsterror)
1581 (setq string (substring string (car bounds) (+ point (cdr bounds))))
1582 (let* ((relpoint (- point (car bounds)))
1583 (pattern (completion-pcm--string->pattern string relpoint))
1584 (all (condition-case err
1585 (funcall filter
1586 (completion-pcm--all-completions
1587 prefix pattern table pred))
1588 (error (unless firsterror (setq firsterror err)) nil))))
1589 (when (and (null all)
1590 (> (car bounds) 0)
1591 (null (ignore-errors (try-completion prefix table pred))))
1592 ;; The prefix has no completions at all, so we should try and fix
1593 ;; that first.
1594 (let ((substring (substring prefix 0 -1)))
1595 (destructuring-bind (subpat suball subprefix subsuffix)
1596 (completion-pcm--find-all-completions
1597 substring table pred (length substring) filter)
1598 (let ((sep (aref prefix (1- (length prefix))))
1599 ;; Text that goes between the new submatches and the
1600 ;; completion substring.
1601 (between nil))
1602 ;; Eliminate submatches that don't end with the separator.
1603 (dolist (submatch (prog1 suball (setq suball ())))
1604 (when (eq sep (aref submatch (1- (length submatch))))
1605 (push submatch suball)))
1606 (when suball
1607 ;; Update the boundaries and corresponding pattern.
1608 ;; We assume that all submatches result in the same boundaries
1609 ;; since we wouldn't know how to merge them otherwise anyway.
1610 ;; FIXME: COMPLETE REWRITE!!!
1611 (let* ((newbeforepoint
1612 (concat subprefix (car suball)
1613 (substring string 0 relpoint)))
1614 (leftbound (+ (length subprefix) (length (car suball))))
1615 (newbounds (completion-boundaries
1616 newbeforepoint table pred afterpoint)))
1617 (unless (or (and (eq (cdr bounds) (cdr newbounds))
1618 (eq (car newbounds) leftbound))
1619 ;; Refuse new boundaries if they step over
1620 ;; the submatch.
1621 (< (car newbounds) leftbound))
1622 ;; The new completed prefix does change the boundaries
1623 ;; of the completed substring.
1624 (setq suffix (substring afterpoint (cdr newbounds)))
1625 (setq string
1626 (concat (substring newbeforepoint (car newbounds))
1627 (substring afterpoint 0 (cdr newbounds))))
1628 (setq between (substring newbeforepoint leftbound
1629 (car newbounds)))
1630 (setq pattern (completion-pcm--string->pattern
1631 string
1632 (- (length newbeforepoint)
1633 (car newbounds)))))
1634 (dolist (submatch suball)
1635 (setq all (nconc (mapcar
1636 (lambda (s) (concat submatch between s))
1637 (funcall filter
1638 (completion-pcm--all-completions
1639 (concat subprefix submatch between)
1640 pattern table pred)))
1641 all)))
1642 ;; FIXME: This can come in handy for try-completion,
1643 ;; but isn't right for all-completions, since it lists
1644 ;; invalid completions.
1645 ;; (unless all
1646 ;; ;; Even though we found expansions in the prefix, none
1647 ;; ;; leads to a valid completion.
1648 ;; ;; Let's keep the expansions, tho.
1649 ;; (dolist (submatch suball)
1650 ;; (push (concat submatch between newsubstring) all)))
1651 ))
1652 (setq pattern (append subpat (list 'any (string sep))
1653 (if between (list between)) pattern))
1654 (setq prefix subprefix)))))
1655 (if (and (null all) firsterror)
1656 (signal (car firsterror) (cdr firsterror))
1657 (list pattern all prefix suffix)))))
1658
1659 (defun completion-pcm-all-completions (string table pred point)
1660 (destructuring-bind (pattern all &optional prefix suffix)
1661 (completion-pcm--find-all-completions string table pred point)
1662 (when all
1663 (nconc (completion-pcm--hilit-commonality pattern all)
1664 (length prefix)))))
1665
1666 (defun completion-pcm--merge-completions (strs pattern)
1667 "Extract the commonality in STRS, with the help of PATTERN."
1668 ;; When completing while ignoring case, we want to try and avoid
1669 ;; completing "fo" to "foO" when completing against "FOO" (bug#4219).
1670 ;; So we try and make sure that the string we return is all made up
1671 ;; of text from the completions rather than part from the
1672 ;; completions and part from the input.
1673 ;; FIXME: This reduces the problems of inconsistent capitalization
1674 ;; but it doesn't fully fix it: we may still end up completing
1675 ;; "fo-ba" to "foo-BAR" or "FOO-bar" when completing against
1676 ;; '("foo-barr" "FOO-BARD").
1677 (cond
1678 ((null (cdr strs)) (list (car strs)))
1679 (t
1680 (let ((re (completion-pcm--pattern->regex pattern 'group))
1681 (ccs ())) ;Chopped completions.
1682
1683 ;; First chop each string into the parts corresponding to each
1684 ;; non-constant element of `pattern', using regexp-matching.
1685 (let ((case-fold-search completion-ignore-case))
1686 (dolist (str strs)
1687 (unless (string-match re str)
1688 (error "Internal error: %s doesn't match %s" str re))
1689 (let ((chopped ())
1690 (last 0)
1691 (i 1)
1692 next)
1693 (while (setq next (match-end i))
1694 (push (substring str last next) chopped)
1695 (setq last next)
1696 (setq i (1+ i)))
1697 ;; Add the text corresponding to the implicit trailing `any'.
1698 (push (substring str last) chopped)
1699 (push (nreverse chopped) ccs))))
1700
1701 ;; Then for each of those non-constant elements, extract the
1702 ;; commonality between them.
1703 (let ((res ())
1704 (fixed ""))
1705 ;; Make the implicit trailing `any' explicit.
1706 (dolist (elem (append pattern '(any)))
1707 (if (stringp elem)
1708 (setq fixed (concat fixed elem))
1709 (let ((comps ()))
1710 (dolist (cc (prog1 ccs (setq ccs nil)))
1711 (push (car cc) comps)
1712 (push (cdr cc) ccs))
1713 ;; Might improve the likelihood to avoid choosing
1714 ;; different capitalizations in different parts.
1715 ;; In practice, it doesn't seem to make any difference.
1716 (setq ccs (nreverse ccs))
1717 (let* ((prefix (try-completion fixed comps))
1718 (unique (or (and (eq prefix t) (setq prefix fixed))
1719 (eq t (try-completion prefix comps)))))
1720 (unless (equal prefix "") (push prefix res))
1721 ;; If there's only one completion, `elem' is not useful
1722 ;; any more: it can only match the empty string.
1723 ;; FIXME: in some cases, it may be necessary to turn an
1724 ;; `any' into a `star' because the surrounding context has
1725 ;; changed such that string->pattern wouldn't add an `any'
1726 ;; here any more.
1727 (unless unique (push elem res))
1728 (setq fixed "")))))
1729 ;; We return it in reverse order.
1730 res)))))
1731
1732 (defun completion-pcm--pattern->string (pattern)
1733 (mapconcat (lambda (x) (cond
1734 ((stringp x) x)
1735 ((eq x 'star) "*")
1736 ((eq x 'any) "")
1737 ((eq x 'point) "")))
1738 pattern
1739 ""))
1740
1741 ;; We want to provide the functionality of `try', but we use `all'
1742 ;; and then merge it. In most cases, this works perfectly, but
1743 ;; if the completion table doesn't consider the same completions in
1744 ;; `try' as in `all', then we have a problem. The most common such
1745 ;; case is for filename completion where completion-ignored-extensions
1746 ;; is only obeyed by the `try' code. We paper over the difference
1747 ;; here. Note that it is not quite right either: if the completion
1748 ;; table uses completion-table-in-turn, this filtering may take place
1749 ;; too late to correctly fallback from the first to the
1750 ;; second alternative.
1751 (defun completion-pcm--filename-try-filter (all)
1752 "Filter to adjust `all' file completion to the behavior of `try'."
1753 (when all
1754 (let ((try ())
1755 (re (concat "\\(?:\\`\\.\\.?/\\|"
1756 (regexp-opt completion-ignored-extensions)
1757 "\\)\\'")))
1758 (dolist (f all)
1759 (unless (string-match-p re f) (push f try)))
1760 (or try all))))
1761
1762
1763 (defun completion-pcm--merge-try (pattern all prefix suffix)
1764 (cond
1765 ((not (consp all)) all)
1766 ((and (not (consp (cdr all))) ;Only one completion.
1767 ;; Ignore completion-ignore-case here.
1768 (equal (completion-pcm--pattern->string pattern) (car all)))
1769 t)
1770 (t
1771 (let* ((mergedpat (completion-pcm--merge-completions all pattern))
1772 ;; `mergedpat' is in reverse order. Place new point (by
1773 ;; order of preference) either at the old point, or at
1774 ;; the last place where there's something to choose, or
1775 ;; at the very end.
1776 (pointpat (or (memq 'point mergedpat) (memq 'any mergedpat)
1777 mergedpat))
1778 ;; New pos from the start.
1779 (newpos (length (completion-pcm--pattern->string pointpat)))
1780 ;; Do it afterwards because it changes `pointpat' by sideeffect.
1781 (merged (completion-pcm--pattern->string (nreverse mergedpat))))
1782
1783 (setq suffix (completion--merge-suffix merged newpos suffix))
1784 (cons (concat prefix merged suffix) (+ newpos (length prefix)))))))
1785
1786 (defun completion-pcm-try-completion (string table pred point)
1787 (destructuring-bind (pattern all prefix suffix)
1788 (completion-pcm--find-all-completions
1789 string table pred point
1790 (if minibuffer-completing-file-name
1791 'completion-pcm--filename-try-filter))
1792 (completion-pcm--merge-try pattern all prefix suffix)))
1793
1794 ;;; Initials completion
1795 ;; Complete /ums to /usr/monnier/src or lch to list-command-history.
1796
1797 (defun completion-initials-expand (str table pred)
1798 (unless (or (zerop (length str))
1799 (string-match completion-pcm--delim-wild-regex str))
1800 (let ((bounds (completion-boundaries str table pred "")))
1801 (if (zerop (car bounds))
1802 (mapconcat 'string str "-")
1803 ;; If there's a boundary, it's trickier. The main use-case
1804 ;; we consider here is file-name completion. We'd like
1805 ;; to expand ~/eee to ~/e/e/e and /eee to /e/e/e.
1806 ;; But at the same time, we don't want /usr/share/ae to expand
1807 ;; to /usr/share/a/e just because we mistyped "ae" for "ar",
1808 ;; so we probably don't want initials to touch anything that
1809 ;; looks like /usr/share/foo. As a heuristic, we just check that
1810 ;; the text before the boundary char is at most 1 char.
1811 ;; This allows both ~/eee and /eee and not much more.
1812 ;; FIXME: It sadly also disallows the use of ~/eee when that's
1813 ;; embedded within something else (e.g. "(~/eee" in Info node
1814 ;; completion or "ancestor:/eee" in bzr-revision completion).
1815 (when (< (car bounds) 3)
1816 (let ((sep (substring str (1- (car bounds)) (car bounds))))
1817 ;; FIXME: the above string-match checks the whole string, whereas
1818 ;; we end up only caring about the after-boundary part.
1819 (concat (substring str 0 (car bounds))
1820 (mapconcat 'string (substring str (car bounds)) sep))))))))
1821
1822 (defun completion-initials-all-completions (string table pred point)
1823 (let ((newstr (completion-initials-expand string table pred)))
1824 (when newstr
1825 (completion-pcm-all-completions newstr table pred (length newstr)))))
1826
1827 (defun completion-initials-try-completion (string table pred point)
1828 (let ((newstr (completion-initials-expand string table pred)))
1829 (when newstr
1830 (completion-pcm-try-completion newstr table pred (length newstr)))))
1831
1832
1833 (provide 'minibuffer)
1834
1835 ;; arch-tag: ef8a0a15-1080-4790-a754-04017c02f08f
1836 ;;; minibuffer.el ends here