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