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