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