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