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