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