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