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