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