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