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