Fix typos in docstrings.
[bpt/emacs.git] / lisp / minibuffer.el
1 ;;; minibuffer.el --- Minibuffer completion functions
2
3 ;; Copyright (C) 2008, 2009, 2010 Free Software Foundation, Inc.
4
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software: you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
21
22 ;;; Commentary:
23
24 ;; Names with "--" are for functions and variables that are meant to be for
25 ;; internal use only.
26
27 ;; Functional completion tables have an extended calling conventions:
28 ;; - The `action' can be (additionally to nil, t, and lambda) of the form
29 ;; (boundaries . SUFFIX) in which case it should return
30 ;; (boundaries START . END). See `completion-boundaries'.
31 ;; Any other return value should be ignored (so we ignore values returned
32 ;; from completion tables that don't know about this new `action' form).
33
34 ;;; Bugs:
35
36 ;; - completion-all-sorted-completions list all the completions, whereas
37 ;; it should only lists the ones that `try-completion' would consider.
38 ;; E.g. it should honor completion-ignored-extensions.
39 ;; - choose-completion can't automatically figure out the boundaries
40 ;; corresponding to the displayed completions because we only
41 ;; provide the start info but not the end info in
42 ;; completion-base-position.
43 ;; - quoting is problematic. E.g. the double-dollar quoting used in
44 ;; substitie-in-file-name (and hence read-file-name-internal) bumps
45 ;; into various bugs:
46 ;; - choose-completion doesn't know how to quote the text it inserts.
47 ;; E.g. it fails to double the dollars in file-name completion, or
48 ;; to backslash-escape spaces and other chars in comint completion.
49 ;; - when completing ~/tmp/fo$$o, the highligting in *Completions*
50 ;; is off by one position.
51 ;; - all code like PCM which relies on all-completions to match
52 ;; its argument gets confused because all-completions returns unquoted
53 ;; texts (as desired for *Completions* output).
54 ;; - C-x C-f ~/*/sr ? should not list "~/./src".
55 ;; - minibuffer-force-complete completes ~/src/emacs/t<!>/lisp/minibuffer.el
56 ;; to ~/src/emacs/trunk/ and throws away lisp/minibuffer.el.
57
58 ;;; Todo:
59
60 ;; - extend `boundaries' to provide various other meta-data about the
61 ;; output of `all-completions':
62 ;; - preferred sorting order when displayed in *Completions*.
63 ;; - annotations/text-properties to add when displayed in *Completions*.
64 ;; - quoting/unquoting (so we can complete files names with envvars
65 ;; and backslashes, and all-completion can list names without
66 ;; quoting backslashes and dollars).
67 ;; - indicate how to turn all-completion's output into
68 ;; try-completion's output: e.g. completion-ignored-extensions.
69 ;; maybe that could be merged with the "quote" operation above.
70 ;; - completion hook to run when the completion is
71 ;; selected/inserted (maybe this should be provided some other
72 ;; way, e.g. as text-property, so `try-completion can also return it?)
73 ;; both for when it's inserted via TAB or via choose-completion.
74 ;; - indicate that `all-completions' doesn't do prefix-completion
75 ;; but just returns some list that relates in some other way to
76 ;; the provided string (as is the case in filecache.el), in which
77 ;; case partial-completion (for example) doesn't make any sense
78 ;; and neither does the completions-first-difference highlight.
79
80 ;; - make partial-completion-mode obsolete:
81 ;; - (?) <foo.h> style completion for file names.
82 ;; This can't be done identically just by tweaking completion,
83 ;; because partial-completion-mode's behavior is to expand <string.h>
84 ;; to /usr/include/string.h only when exiting the minibuffer, at which
85 ;; point the completion code is actually not involved normally.
86 ;; Partial-completion-mode does it via a find-file-not-found-function.
87 ;; - special code for C-x C-f <> to visit the file ref'd at point
88 ;; via (require 'foo) or #include "foo". ffap seems like a better
89 ;; place for this feature (supplemented with major-mode-provided
90 ;; functions to find the file ref'd at point).
91
92 ;; - case-sensitivity currently confuses two issues:
93 ;; - whether or not a particular completion table should be case-sensitive
94 ;; (i.e. whether strings that differ only by case are semantically
95 ;; equivalent)
96 ;; - whether the user wants completion to pay attention to case.
97 ;; e.g. we may want to make it possible for the user to say "first try
98 ;; completion case-sensitively, and if that fails, try to ignore case".
99
100 ;; - add support for ** to pcm.
101 ;; - Add vc-file-name-completion-table to read-file-name-internal.
102 ;; - A feature like completing-help.el.
103
104 ;;; Code:
105
106 (eval-when-compile (require 'cl))
107
108 ;;; Completion table manipulation
109
110 ;; New completion-table operation.
111 (defun completion-boundaries (string table pred suffix)
112 "Return the boundaries of the completions returned by TABLE for STRING.
113 STRING is the string on which completion will be performed.
114 SUFFIX is the string after point.
115 The result is of the form (START . END) where START is the position
116 in STRING of the beginning of the completion field and END is the position
117 in SUFFIX of the end of the completion field.
118 E.g. for simple completion tables, the result is always (0 . (length SUFFIX))
119 and for file names the result is the positions delimited by
120 the closest directory separators."
121 (let ((boundaries (if (functionp table)
122 (funcall table string pred (cons 'boundaries suffix)))))
123 (if (not (eq (car-safe boundaries) 'boundaries))
124 (setq boundaries nil))
125 (cons (or (cadr boundaries) 0)
126 (or (cddr boundaries) (length suffix)))))
127
128 (defun completion--some (fun xs)
129 "Apply FUN to each element of XS in turn.
130 Return the first non-nil returned value.
131 Like CL's `some'."
132 (let ((firsterror nil)
133 res)
134 (while (and (not res) xs)
135 (condition-case err
136 (setq res (funcall fun (pop xs)))
137 (error (unless firsterror (setq firsterror err)) nil)))
138 (or res
139 (if firsterror (signal (car firsterror) (cdr firsterror))))))
140
141 (defun complete-with-action (action table string pred)
142 "Perform completion ACTION.
143 STRING is the string to complete.
144 TABLE is the completion table, which should not be a function.
145 PRED is a completion predicate.
146 ACTION can be one of nil, t or `lambda'."
147 (cond
148 ((functionp table) (funcall table string pred action))
149 ((eq (car-safe action) 'boundaries)
150 (cons 'boundaries (completion-boundaries string table pred (cdr action))))
151 (t
152 (funcall
153 (cond
154 ((null action) 'try-completion)
155 ((eq action t) 'all-completions)
156 (t 'test-completion))
157 string table pred))))
158
159 (defun completion-table-dynamic (fun)
160 "Use function FUN as a dynamic completion table.
161 FUN is called with one argument, the string for which completion is required,
162 and it should return an alist containing all the intended possible completions.
163 This alist may be a full list of possible completions so that FUN can ignore
164 the value of its argument. If completion is performed in the minibuffer,
165 FUN will be called in the buffer from which the minibuffer was entered.
166
167 The result of the `completion-table-dynamic' form is a function
168 that can be used as the COLLECTION argument to `try-completion' and
169 `all-completions'. See Info node `(elisp)Programmed Completion'."
170 (lexical-let ((fun fun))
171 (lambda (string pred action)
172 (with-current-buffer (let ((win (minibuffer-selected-window)))
173 (if (window-live-p win) (window-buffer win)
174 (current-buffer)))
175 (complete-with-action action (funcall fun string) string pred)))))
176
177 (defmacro lazy-completion-table (var fun)
178 "Initialize variable VAR as a lazy completion table.
179 If the completion table VAR is used for the first time (e.g., by passing VAR
180 as an argument to `try-completion'), the function FUN is called with no
181 arguments. FUN must return the completion table that will be stored in VAR.
182 If completion is requested in the minibuffer, FUN will be called in the buffer
183 from which the minibuffer was entered. The return value of
184 `lazy-completion-table' must be used to initialize the value of VAR.
185
186 You should give VAR a non-nil `risky-local-variable' property."
187 (declare (debug (symbolp lambda-expr)))
188 (let ((str (make-symbol "string")))
189 `(completion-table-dynamic
190 (lambda (,str)
191 (when (functionp ,var)
192 (setq ,var (,fun)))
193 ,var))))
194
195 (defun completion-table-with-context (prefix table string pred action)
196 ;; TODO: add `suffix' maybe?
197 ;; Notice that `pred' may not be a function in some abusive cases.
198 (when (functionp pred)
199 (setq pred
200 (lexical-let ((pred pred))
201 ;; Predicates are called differently depending on the nature of
202 ;; the completion table :-(
203 (cond
204 ((vectorp table) ;Obarray.
205 (lambda (sym) (funcall pred (concat prefix (symbol-name sym)))))
206 ((hash-table-p table)
207 (lambda (s v) (funcall pred (concat prefix s))))
208 ((functionp table)
209 (lambda (s) (funcall pred (concat prefix s))))
210 (t ;Lists and alists.
211 (lambda (s)
212 (funcall pred (concat prefix (if (consp s) (car s) s)))))))))
213 (if (eq (car-safe action) 'boundaries)
214 (let* ((len (length prefix))
215 (bound (completion-boundaries string table pred (cdr action))))
216 (list* 'boundaries (+ (car bound) len) (cdr bound)))
217 (let ((comp (complete-with-action action table string pred)))
218 (cond
219 ;; In case of try-completion, add the prefix.
220 ((stringp comp) (concat prefix comp))
221 (t comp)))))
222
223 (defun completion-table-with-terminator (terminator table string pred action)
224 "Construct a completion table like TABLE but with an extra TERMINATOR.
225 This is meant to be called in a curried way by first passing TERMINATOR
226 and TABLE only (via `apply-partially').
227 TABLE is a completion table, and TERMINATOR is a string appended to TABLE's
228 completion if it is complete. TERMINATOR is also used to determine the
229 completion suffix's boundary.
230 TERMINATOR can also be a cons cell (TERMINATOR . TERMINATOR-REGEXP)
231 in which case TERMINATOR-REGEXP is a regular expression whose submatch
232 number 1 should match TERMINATOR. This is used when there is a need to
233 distinguish occurrences of the TERMINATOR strings which are really terminators
234 from others (e.g. escaped)."
235 (cond
236 ((eq (car-safe action) 'boundaries)
237 (let* ((suffix (cdr action))
238 (bounds (completion-boundaries string table pred suffix))
239 (terminator-regexp (if (consp terminator)
240 (cdr terminator) (regexp-quote terminator)))
241 (max (string-match terminator-regexp suffix)))
242 (list* 'boundaries (car bounds)
243 (min (cdr bounds) (or max (length suffix))))))
244 ((eq action nil)
245 (let ((comp (try-completion string table pred)))
246 (if (consp terminator) (setq terminator (car terminator)))
247 (if (eq comp t)
248 (concat string terminator)
249 (if (and (stringp comp)
250 ;; FIXME: Try to avoid this second call, especially since
251 ;; it may be very inefficient (because `comp' made us
252 ;; jump to a new boundary, so we complete in that
253 ;; boundary with an empty start string).
254 ;; completion-boundaries might help.
255 (eq (try-completion comp table pred) t))
256 (concat comp terminator)
257 comp))))
258 ((eq action t)
259 ;; FIXME: We generally want the `try' and `all' behaviors to be
260 ;; consistent so pcm can merge the `all' output to get the `try' output,
261 ;; but that sometimes clashes with the need for `all' output to look
262 ;; good in *Completions*.
263 ;; (mapcar (lambda (s) (concat s terminator))
264 ;; (all-completions string table pred))))
265 (all-completions string table pred))
266 ;; completion-table-with-terminator is always used for
267 ;; "sub-completions" so it's only called if the terminator is missing,
268 ;; in which case `test-completion' should return nil.
269 ((eq action 'lambda) nil)))
270
271 (defun completion-table-with-predicate (table pred1 strict string pred2 action)
272 "Make a completion table equivalent to TABLE but filtered through PRED1.
273 PRED1 is a function of one argument which returns non-nil if and only if the
274 argument is an element of TABLE which should be considered for completion.
275 STRING, PRED2, and ACTION are the usual arguments to completion tables,
276 as described in `try-completion', `all-completions', and `test-completion'.
277 If STRICT is t, the predicate always applies; if nil it only applies if
278 it does not reduce the set of possible completions to nothing.
279 Note: TABLE needs to be a proper completion table which obeys predicates."
280 (cond
281 ((and (not strict) (eq action 'lambda))
282 ;; Ignore pred1 since it doesn't really have to apply anyway.
283 (test-completion string table pred2))
284 (t
285 (or (complete-with-action action table string
286 (if (null pred2) pred1
287 (lexical-let ((pred1 pred2) (pred2 pred2))
288 (lambda (x)
289 ;; Call `pred1' first, so that `pred2'
290 ;; really can't tell that `x' is in table.
291 (if (funcall pred1 x) (funcall pred2 x))))))
292 ;; If completion failed and we're not applying pred1 strictly, try
293 ;; again without pred1.
294 (and (not strict)
295 (complete-with-action action table string pred2))))))
296
297 (defun completion-table-in-turn (&rest tables)
298 "Create a completion table that tries each table in TABLES in turn."
299 ;; FIXME: the boundaries may come from TABLE1 even when the completion list
300 ;; is returned by TABLE2 (because TABLE1 returned an empty list).
301 (lexical-let ((tables tables))
302 (lambda (string pred action)
303 (completion--some (lambda (table)
304 (complete-with-action action table string pred))
305 tables))))
306
307 ;; (defmacro complete-in-turn (a b) `(completion-table-in-turn ,a ,b))
308 ;; (defmacro dynamic-completion-table (fun) `(completion-table-dynamic ,fun))
309 (define-obsolete-function-alias
310 'complete-in-turn 'completion-table-in-turn "23.1")
311 (define-obsolete-function-alias
312 'dynamic-completion-table 'completion-table-dynamic "23.1")
313
314 ;;; Minibuffer completion
315
316 (defgroup minibuffer nil
317 "Controlling the behavior of the minibuffer."
318 :link '(custom-manual "(emacs)Minibuffer")
319 :group 'environment)
320
321 (defun minibuffer-message (message &rest args)
322 "Temporarily display MESSAGE at the end of the minibuffer.
323 The text is displayed for `minibuffer-message-timeout' seconds,
324 or until the next input event arrives, whichever comes first.
325 Enclose MESSAGE in [...] if this is not yet the case.
326 If ARGS are provided, then pass MESSAGE through `format'."
327 (if (not (minibufferp (current-buffer)))
328 (progn
329 (if args
330 (apply 'message message args)
331 (message "%s" message))
332 (prog1 (sit-for (or minibuffer-message-timeout 1000000))
333 (message nil)))
334 ;; Clear out any old echo-area message to make way for our new thing.
335 (message nil)
336 (setq message (if (and (null args) (string-match-p "\\` *\\[.+\\]\\'" message))
337 ;; Make sure we can put-text-property.
338 (copy-sequence message)
339 (concat " [" message "]")))
340 (when args (setq message (apply 'format message args)))
341 (let ((ol (make-overlay (point-max) (point-max) nil t t))
342 ;; A quit during sit-for normally only interrupts the sit-for,
343 ;; but since minibuffer-message is used at the end of a command,
344 ;; at a time when the command has virtually finished already, a C-g
345 ;; should really cause an abort-recursive-edit instead (i.e. as if
346 ;; the C-g had been typed at top-level). Binding inhibit-quit here
347 ;; is an attempt to get that behavior.
348 (inhibit-quit t))
349 (unwind-protect
350 (progn
351 (unless (zerop (length message))
352 ;; The current C cursor code doesn't know to use the overlay's
353 ;; marker's stickiness to figure out whether to place the cursor
354 ;; before or after the string, so let's spoon-feed it the pos.
355 (put-text-property 0 1 'cursor t message))
356 (overlay-put ol 'after-string message)
357 (sit-for (or minibuffer-message-timeout 1000000)))
358 (delete-overlay ol)))))
359
360 (defun minibuffer-completion-contents ()
361 "Return the user input in a minibuffer before point as a string.
362 That is what completion commands operate on."
363 (buffer-substring (field-beginning) (point)))
364
365 (defun delete-minibuffer-contents ()
366 "Delete all user input in a minibuffer.
367 If the current buffer is not a minibuffer, erase its entire contents."
368 ;; We used to do `delete-field' here, but when file name shadowing
369 ;; is on, the field doesn't cover the entire minibuffer contents.
370 (delete-region (minibuffer-prompt-end) (point-max)))
371
372 (defcustom completion-auto-help t
373 "Non-nil means automatically provide help for invalid completion input.
374 If the value is t the *Completion* buffer is displayed whenever completion
375 is requested but cannot be done.
376 If the value is `lazy', the *Completions* buffer is only displayed after
377 the second failed attempt to complete."
378 :type '(choice (const nil) (const t) (const lazy))
379 :group 'minibuffer)
380
381 (defconst completion-styles-alist
382 '((emacs21
383 completion-emacs21-try-completion completion-emacs21-all-completions
384 "Simple prefix-based completion.")
385 (emacs22
386 completion-emacs22-try-completion completion-emacs22-all-completions
387 "Prefix completion that only operates on the text before point.")
388 (basic
389 completion-basic-try-completion completion-basic-all-completions
390 "Completion of the prefix before point and the suffix after point.")
391 (partial-completion
392 completion-pcm-try-completion completion-pcm-all-completions
393 "Completion of multiple words, each one taken as a prefix.
394 E.g. M-x l-c-h can complete to list-command-history
395 and C-x C-f /u/m/s to /usr/monnier/src.")
396 (initials
397 completion-initials-try-completion completion-initials-all-completions
398 "Completion of acronyms and initialisms.
399 E.g. can complete M-x lch to list-command-history
400 and C-x C-f ~/sew to ~/src/emacs/work."))
401 "List of available completion styles.
402 Each element has the form (NAME TRY-COMPLETION ALL-COMPLETIONS DOC):
403 where NAME is the name that should be used in `completion-styles',
404 TRY-COMPLETION is the function that does the completion (it should
405 follow the same calling convention as `completion-try-completion'),
406 ALL-COMPLETIONS is the function that lists the completions (it should
407 follow the calling convention of `completion-all-completions'),
408 and DOC describes the way this style of completion works.")
409
410 (defcustom completion-styles '(basic partial-completion emacs22)
411 "List of completion styles to use.
412 The available styles are listed in `completion-styles-alist'."
413 :type `(repeat (choice ,@(mapcar (lambda (x) (list 'const (car x)))
414 completion-styles-alist)))
415 :group 'minibuffer
416 :version "23.1")
417
418 (defun completion-try-completion (string table pred point)
419 "Try to complete STRING using completion table TABLE.
420 Only the elements of table that satisfy predicate PRED are considered.
421 POINT is the position of point within STRING.
422 The return value can be either nil to indicate that there is no completion,
423 t to indicate that STRING is the only possible completion,
424 or a pair (STRING . NEWPOINT) of the completed result string together with
425 a new position for point."
426 (completion--some (lambda (style)
427 (funcall (nth 1 (assq style completion-styles-alist))
428 string table pred point))
429 completion-styles))
430
431 (defun completion-all-completions (string table pred point)
432 "List the possible completions of STRING in completion table TABLE.
433 Only the elements of table that satisfy predicate PRED are considered.
434 POINT is the position of point within STRING.
435 The return value is a list of completions and may contain the base-size
436 in the last `cdr'."
437 ;; FIXME: We need to additionally return the info needed for the
438 ;; second part of completion-base-position.
439 (completion--some (lambda (style)
440 (funcall (nth 2 (assq style completion-styles-alist))
441 string table pred point))
442 completion-styles))
443
444 (defun minibuffer--bitset (modified completions exact)
445 (logior (if modified 4 0)
446 (if completions 2 0)
447 (if exact 1 0)))
448
449 (defun completion--replace (beg end newtext)
450 "Replace the buffer text between BEG and END with NEWTEXT.
451 Moves point to the end of the new text."
452 ;; This should be in subr.el.
453 ;; You'd think this is trivial to do, but details matter if you want
454 ;; to keep markers "at the right place" and be robust in the face of
455 ;; after-change-functions that may themselves modify the buffer.
456 (goto-char beg)
457 (insert newtext)
458 (delete-region (point) (+ (point) (- end beg))))
459
460 (defun completion--do-completion (&optional try-completion-function)
461 "Do the completion and return a summary of what happened.
462 M = completion was performed, the text was Modified.
463 C = there were available Completions.
464 E = after completion we now have an Exact match.
465
466 MCE
467 000 0 no possible completion
468 001 1 was already an exact and unique completion
469 010 2 no completion happened
470 011 3 was already an exact completion
471 100 4 ??? impossible
472 101 5 ??? impossible
473 110 6 some completion happened
474 111 7 completed to an exact completion"
475 (let* ((beg (field-beginning))
476 (end (field-end))
477 (string (buffer-substring beg end))
478 (comp (funcall (or try-completion-function
479 'completion-try-completion)
480 string
481 minibuffer-completion-table
482 minibuffer-completion-predicate
483 (- (point) beg))))
484 (cond
485 ((null comp)
486 (minibuffer-hide-completions)
487 (ding) (minibuffer-message "No match") (minibuffer--bitset nil nil nil))
488 ((eq t comp)
489 (minibuffer-hide-completions)
490 (goto-char (field-end))
491 (minibuffer--bitset nil nil t)) ;Exact and unique match.
492 (t
493 ;; `completed' should be t if some completion was done, which doesn't
494 ;; include simply changing the case of the entered string. However,
495 ;; for appearance, the string is rewritten if the case changes.
496 (let* ((comp-pos (cdr comp))
497 (completion (car comp))
498 (completed (not (eq t (compare-strings completion nil nil
499 string nil nil t))))
500 (unchanged (eq t (compare-strings completion nil nil
501 string nil nil nil))))
502 (if unchanged
503 (goto-char end)
504 ;; Insert in minibuffer the chars we got.
505 (completion--replace beg end completion))
506 ;; Move point to its completion-mandated destination.
507 (forward-char (- comp-pos (length completion)))
508
509 (if (not (or unchanged completed))
510 ;; The case of the string changed, but that's all. We're not sure
511 ;; whether this is a unique completion or not, so try again using
512 ;; the real case (this shouldn't recurse again, because the next
513 ;; time try-completion will return either t or the exact string).
514 (completion--do-completion try-completion-function)
515
516 ;; It did find a match. Do we match some possibility exactly now?
517 (let ((exact (test-completion completion
518 minibuffer-completion-table
519 minibuffer-completion-predicate)))
520 (if completed
521 ;; We could also decide to refresh the completions,
522 ;; if they're displayed (and assuming there are
523 ;; completions left).
524 (minibuffer-hide-completions)
525 ;; Show the completion table, if requested.
526 (cond
527 ((not exact)
528 (if (case completion-auto-help
529 (lazy (eq this-command last-command))
530 (t completion-auto-help))
531 (minibuffer-completion-help)
532 (minibuffer-message "Next char not unique")))
533 ;; If the last exact completion and this one were the same, it
534 ;; means we've already given a "Next char not unique" message
535 ;; and the user's hit TAB again, so now we give him help.
536 ((eq this-command last-command)
537 (if completion-auto-help (minibuffer-completion-help)))))
538
539 (minibuffer--bitset completed t exact))))))))
540
541 (defun minibuffer-complete ()
542 "Complete the minibuffer contents as far as possible.
543 Return nil if there is no valid completion, else t.
544 If no characters can be completed, display a list of possible completions.
545 If you repeat this command after it displayed such a list,
546 scroll the window of possible completions."
547 (interactive)
548 ;; If the previous command was not this,
549 ;; mark the completion buffer obsolete.
550 (unless (eq this-command last-command)
551 (setq minibuffer-scroll-window nil))
552
553 (let ((window minibuffer-scroll-window))
554 ;; If there's a fresh completion window with a live buffer,
555 ;; and this command is repeated, scroll that window.
556 (if (window-live-p window)
557 (with-current-buffer (window-buffer window)
558 (if (pos-visible-in-window-p (point-max) window)
559 ;; If end is in view, scroll up to the beginning.
560 (set-window-start window (point-min) nil)
561 ;; Else scroll down one screen.
562 (scroll-other-window))
563 nil)
564
565 (case (completion--do-completion)
566 (#b000 nil)
567 (#b001 (minibuffer-message "Sole completion")
568 t)
569 (#b011 (minibuffer-message "Complete, but not unique")
570 t)
571 (t t)))))
572
573 (defvar completion-all-sorted-completions nil)
574 (make-variable-buffer-local 'completion-all-sorted-completions)
575
576 (defun completion--flush-all-sorted-completions (&rest ignore)
577 (setq completion-all-sorted-completions nil))
578
579 (defun completion-all-sorted-completions ()
580 (or completion-all-sorted-completions
581 (let* ((start (field-beginning))
582 (end (field-end))
583 (all (completion-all-completions (buffer-substring start end)
584 minibuffer-completion-table
585 minibuffer-completion-predicate
586 (- (point) start)))
587 (last (last all))
588 (base-size (or (cdr last) 0)))
589 (when last
590 (setcdr last nil)
591 ;; Prefer shorter completions.
592 (setq all (sort all (lambda (c1 c2) (< (length c1) (length c2)))))
593 ;; Prefer recently used completions.
594 (let ((hist (symbol-value minibuffer-history-variable)))
595 (setq all (sort all (lambda (c1 c2)
596 (> (length (member c1 hist))
597 (length (member c2 hist)))))))
598 ;; Cache the result. This is not just for speed, but also so that
599 ;; repeated calls to minibuffer-force-complete can cycle through
600 ;; all possibilities.
601 (add-hook 'after-change-functions
602 'completion--flush-all-sorted-completions nil t)
603 (setq completion-all-sorted-completions
604 (nconc all base-size))))))
605
606 (defun minibuffer-force-complete ()
607 "Complete the minibuffer to an exact match.
608 Repeated uses step through the possible completions."
609 (interactive)
610 ;; FIXME: Need to deal with the extra-size issue here as well.
611 ;; FIXME: ~/src/emacs/t<M-TAB>/lisp/minibuffer.el completes to
612 ;; ~/src/emacs/trunk/ and throws away lisp/minibuffer.el.
613 (let* ((start (field-beginning))
614 (end (field-end))
615 (all (completion-all-sorted-completions)))
616 (if (not (consp all))
617 (minibuffer-message (if all "No more completions" "No completions"))
618 (goto-char end)
619 (insert (car all))
620 (delete-region (+ start (cdr (last all))) end)
621 ;; If completing file names, (car all) may be a directory, so we'd now
622 ;; have a new set of possible completions and might want to reset
623 ;; completion-all-sorted-completions to nil, but we prefer not to,
624 ;; so that repeated calls minibuffer-force-complete still cycle
625 ;; through the previous possible completions.
626 (let ((last (last all)))
627 (setcdr last (cons (car all) (cdr last)))
628 (setq completion-all-sorted-completions (cdr all))))))
629
630 (defvar minibuffer-confirm-exit-commands
631 '(minibuffer-complete minibuffer-complete-word PC-complete PC-complete-word)
632 "A list of commands which cause an immediately following
633 `minibuffer-complete-and-exit' to ask for extra confirmation.")
634
635 (defun minibuffer-complete-and-exit ()
636 "Exit if the minibuffer contains a valid completion.
637 Otherwise, try to complete the minibuffer contents. If
638 completion leads to a valid completion, a repetition of this
639 command will exit.
640
641 If `minibuffer-completion-confirm' is `confirm', do not try to
642 complete; instead, ask for confirmation and accept any input if
643 confirmed.
644 If `minibuffer-completion-confirm' is `confirm-after-completion',
645 do not try to complete; instead, ask for confirmation if the
646 preceding minibuffer command was a member of
647 `minibuffer-confirm-exit-commands', and accept the input
648 otherwise."
649 (interactive)
650 (let ((beg (field-beginning))
651 (end (field-end)))
652 (cond
653 ;; Allow user to specify null string
654 ((= beg end) (exit-minibuffer))
655 ((test-completion (buffer-substring beg end)
656 minibuffer-completion-table
657 minibuffer-completion-predicate)
658 ;; FIXME: completion-ignore-case has various slightly
659 ;; incompatible meanings. E.g. it can reflect whether the user
660 ;; wants completion to pay attention to case, or whether the
661 ;; string will be used in a context where case is significant.
662 ;; E.g. usually try-completion should obey the first, whereas
663 ;; test-completion should obey the second.
664 (when completion-ignore-case
665 ;; Fixup case of the field, if necessary.
666 (let* ((string (buffer-substring beg end))
667 (compl (try-completion
668 string
669 minibuffer-completion-table
670 minibuffer-completion-predicate)))
671 (when (and (stringp compl) (not (equal string compl))
672 ;; If it weren't for this piece of paranoia, I'd replace
673 ;; the whole thing with a call to do-completion.
674 ;; This is important, e.g. when the current minibuffer's
675 ;; content is a directory which only contains a single
676 ;; file, so `try-completion' actually completes to
677 ;; that file.
678 (= (length string) (length compl)))
679 (goto-char end)
680 (insert compl)
681 (delete-region beg end))))
682 (exit-minibuffer))
683
684 ((memq minibuffer-completion-confirm '(confirm confirm-after-completion))
685 ;; The user is permitted to exit with an input that's rejected
686 ;; by test-completion, after confirming her choice.
687 (if (or (eq last-command this-command)
688 ;; For `confirm-after-completion' we only ask for confirmation
689 ;; if trying to exit immediately after typing TAB (this
690 ;; catches most minibuffer typos).
691 (and (eq minibuffer-completion-confirm 'confirm-after-completion)
692 (not (memq last-command minibuffer-confirm-exit-commands))))
693 (exit-minibuffer)
694 (minibuffer-message "Confirm")
695 nil))
696
697 (t
698 ;; Call do-completion, but ignore errors.
699 (case (condition-case nil
700 (completion--do-completion)
701 (error 1))
702 ((#b001 #b011) (exit-minibuffer))
703 (#b111 (if (not minibuffer-completion-confirm)
704 (exit-minibuffer)
705 (minibuffer-message "Confirm")
706 nil))
707 (t nil))))))
708
709 (defun completion--try-word-completion (string table predicate point)
710 (let ((comp (completion-try-completion string table predicate point)))
711 (if (not (consp comp))
712 comp
713
714 ;; If completion finds next char not unique,
715 ;; consider adding a space or a hyphen.
716 (when (= (length string) (length (car comp)))
717 ;; Mark the added char with the `completion-word' property, so it
718 ;; can be handled specially by completion styles such as
719 ;; partial-completion.
720 ;; We used to remove `partial-completion' from completion-styles
721 ;; instead, but it was too blunt, leading to situations where SPC
722 ;; was the only insertable char at point but minibuffer-complete-word
723 ;; refused inserting it.
724 (let ((exts (mapcar (lambda (str) (propertize str 'completion-try-word t))
725 '(" " "-")))
726 (before (substring string 0 point))
727 (after (substring string point))
728 tem)
729 (while (and exts (not (consp tem)))
730 (setq tem (completion-try-completion
731 (concat before (pop exts) after)
732 table predicate (1+ point))))
733 (if (consp tem) (setq comp tem))))
734
735 ;; Completing a single word is actually more difficult than completing
736 ;; as much as possible, because we first have to find the "current
737 ;; position" in `completion' in order to find the end of the word
738 ;; we're completing. Normally, `string' is a prefix of `completion',
739 ;; which makes it trivial to find the position, but with fancier
740 ;; completion (plus env-var expansion, ...) `completion' might not
741 ;; look anything like `string' at all.
742 (let* ((comppoint (cdr comp))
743 (completion (car comp))
744 (before (substring string 0 point))
745 (combined (concat before "\n" completion)))
746 ;; Find in completion the longest text that was right before point.
747 (when (string-match "\\(.+\\)\n.*?\\1" combined)
748 (let* ((prefix (match-string 1 before))
749 ;; We used non-greedy match to make `rem' as long as possible.
750 (rem (substring combined (match-end 0)))
751 ;; Find in the remainder of completion the longest text
752 ;; that was right after point.
753 (after (substring string point))
754 (suffix (if (string-match "\\`\\(.+\\).*\n.*\\1"
755 (concat after "\n" rem))
756 (match-string 1 after))))
757 ;; The general idea is to try and guess what text was inserted
758 ;; at point by the completion. Problem is: if we guess wrong,
759 ;; we may end up treating as "added by completion" text that was
760 ;; actually painfully typed by the user. So if we then cut
761 ;; after the first word, we may throw away things the
762 ;; user wrote. So let's try to be as conservative as possible:
763 ;; only cut after the first word, if we're reasonably sure that
764 ;; our guess is correct.
765 ;; Note: a quick survey on emacs-devel seemed to indicate that
766 ;; nobody actually cares about the "word-at-a-time" feature of
767 ;; minibuffer-complete-word, whose real raison-d'être is that it
768 ;; tries to add "-" or " ". One more reason to only cut after
769 ;; the first word, if we're really sure we're right.
770 (when (and (or suffix (zerop (length after)))
771 (string-match (concat
772 ;; Make submatch 1 as small as possible
773 ;; to reduce the risk of cutting
774 ;; valuable text.
775 ".*" (regexp-quote prefix) "\\(.*?\\)"
776 (if suffix (regexp-quote suffix) "\\'"))
777 completion)
778 ;; The new point in `completion' should also be just
779 ;; before the suffix, otherwise something more complex
780 ;; is going on, and we're not sure where we are.
781 (eq (match-end 1) comppoint)
782 ;; (match-beginning 1)..comppoint is now the stretch
783 ;; of text in `completion' that was completed at point.
784 (string-match "\\W" completion (match-beginning 1))
785 ;; Is there really something to cut?
786 (> comppoint (match-end 0)))
787 ;; Cut after the first word.
788 (let ((cutpos (match-end 0)))
789 (setq completion (concat (substring completion 0 cutpos)
790 (substring completion comppoint)))
791 (setq comppoint cutpos)))))
792
793 (cons completion comppoint)))))
794
795
796 (defun minibuffer-complete-word ()
797 "Complete the minibuffer contents at most a single word.
798 After one word is completed as much as possible, a space or hyphen
799 is added, provided that matches some possible completion.
800 Return nil if there is no valid completion, else t."
801 (interactive)
802 (case (completion--do-completion 'completion--try-word-completion)
803 (#b000 nil)
804 (#b001 (minibuffer-message "Sole completion")
805 t)
806 (#b011 (minibuffer-message "Complete, but not unique")
807 t)
808 (t t)))
809
810 (defface completions-annotations '((t :inherit italic))
811 "Face to use for annotations in the *Completions* buffer.")
812
813 (defcustom completions-format nil
814 "Define the appearance and sorting of completions.
815 If the value is `vertical', display completions sorted vertically
816 in columns in the *Completions* buffer.
817 If the value is `horizontal' or nil, display completions sorted
818 horizontally in alphabetical order, rather than down the screen."
819 :type '(choice (const nil) (const horizontal) (const vertical))
820 :group 'minibuffer
821 :version "23.2")
822
823 (defun completion--insert-strings (strings)
824 "Insert a list of STRINGS into the current buffer.
825 Uses columns to keep the listing readable but compact.
826 It also eliminates runs of equal strings."
827 (when (consp strings)
828 (let* ((length (apply 'max
829 (mapcar (lambda (s)
830 (if (consp s)
831 (+ (string-width (car s))
832 (string-width (cadr s)))
833 (string-width s)))
834 strings)))
835 (window (get-buffer-window (current-buffer) 0))
836 (wwidth (if window (1- (window-width window)) 79))
837 (columns (min
838 ;; At least 2 columns; at least 2 spaces between columns.
839 (max 2 (/ wwidth (+ 2 length)))
840 ;; Don't allocate more columns than we can fill.
841 ;; Windows can't show less than 3 lines anyway.
842 (max 1 (/ (length strings) 2))))
843 (colwidth (/ wwidth columns))
844 (column 0)
845 (rows (/ (length strings) columns))
846 (row 0)
847 (laststring nil))
848 ;; The insertion should be "sensible" no matter what choices were made
849 ;; for the parameters above.
850 (dolist (str strings)
851 (unless (equal laststring str) ; Remove (consecutive) duplicates.
852 (setq laststring str)
853 (let ((length (if (consp str)
854 (+ (string-width (car str))
855 (string-width (cadr str)))
856 (string-width str))))
857 (cond
858 ((eq completions-format 'vertical)
859 ;; Vertical format
860 (when (> row rows)
861 (forward-line (- -1 rows))
862 (setq row 0 column (+ column colwidth)))
863 (when (> column 0)
864 (end-of-line)
865 (while (> (current-column) column)
866 (if (eobp)
867 (insert "\n")
868 (forward-line 1)
869 (end-of-line)))
870 (insert " \t")
871 (set-text-properties (- (point) 1) (point)
872 `(display (space :align-to ,column)))))
873 (t
874 ;; Horizontal format
875 (unless (bolp)
876 (if (< wwidth (+ (max colwidth length) column))
877 ;; No space for `str' at point, move to next line.
878 (progn (insert "\n") (setq column 0))
879 (insert " \t")
880 ;; Leave the space unpropertized so that in the case we're
881 ;; already past the goal column, there is still
882 ;; a space displayed.
883 (set-text-properties (- (point) 1) (point)
884 ;; We can't just set tab-width, because
885 ;; completion-setup-function will kill all
886 ;; local variables :-(
887 `(display (space :align-to ,column)))
888 nil))))
889 (if (not (consp str))
890 (put-text-property (point) (progn (insert str) (point))
891 'mouse-face 'highlight)
892 (put-text-property (point) (progn (insert (car str)) (point))
893 'mouse-face 'highlight)
894 (add-text-properties (point) (progn (insert (cadr str)) (point))
895 '(mouse-face nil
896 face completions-annotations)))
897 (cond
898 ((eq completions-format 'vertical)
899 ;; Vertical format
900 (if (> column 0)
901 (forward-line)
902 (insert "\n"))
903 (setq row (1+ row)))
904 (t
905 ;; Horizontal format
906 ;; Next column to align to.
907 (setq column (+ column
908 ;; Round up to a whole number of columns.
909 (* colwidth (ceiling length colwidth))))))))))))
910
911 (defvar completion-common-substring nil)
912 (make-obsolete-variable 'completion-common-substring nil "23.1")
913
914 (defvar completion-setup-hook nil
915 "Normal hook run at the end of setting up a completion list buffer.
916 When this hook is run, the current buffer is the one in which the
917 command to display the completion list buffer was run.
918 The completion list buffer is available as the value of `standard-output'.
919 See also `display-completion-list'.")
920
921 (defface completions-first-difference
922 '((t (:inherit bold)))
923 "Face put on the first uncommon character in completions in *Completions* buffer."
924 :group 'completion)
925
926 (defface completions-common-part
927 '((t (:inherit default)))
928 "Face put on the common prefix substring in completions in *Completions* buffer.
929 The idea of `completions-common-part' is that you can use it to
930 make the common parts less visible than normal, so that the rest
931 of the differing parts is, by contrast, slightly highlighted."
932 :group 'completion)
933
934 (defun completion-hilit-commonality (completions prefix-len base-size)
935 (when completions
936 (let ((com-str-len (- prefix-len (or base-size 0))))
937 (nconc
938 (mapcar
939 (lambda (elem)
940 (let ((str
941 ;; Don't modify the string itself, but a copy, since the
942 ;; the string may be read-only or used for other purposes.
943 ;; Furthermore, since `completions' may come from
944 ;; display-completion-list, `elem' may be a list.
945 (if (consp elem)
946 (car (setq elem (cons (copy-sequence (car elem))
947 (cdr elem))))
948 (setq elem (copy-sequence elem)))))
949 (put-text-property 0
950 ;; If completion-boundaries returns incorrect
951 ;; values, all-completions may return strings
952 ;; that don't contain the prefix.
953 (min com-str-len (length str))
954 'font-lock-face 'completions-common-part
955 str)
956 (if (> (length str) com-str-len)
957 (put-text-property com-str-len (1+ com-str-len)
958 'font-lock-face 'completions-first-difference
959 str)))
960 elem)
961 completions)
962 base-size))))
963
964 (defun display-completion-list (completions &optional common-substring)
965 "Display the list of completions, COMPLETIONS, using `standard-output'.
966 Each element may be just a symbol or string
967 or may be a list of two strings to be printed as if concatenated.
968 If it is a list of two strings, the first is the actual completion
969 alternative, the second serves as annotation.
970 `standard-output' must be a buffer.
971 The actual completion alternatives, as inserted, are given `mouse-face'
972 properties of `highlight'.
973 At the end, this runs the normal hook `completion-setup-hook'.
974 It can find the completion buffer in `standard-output'.
975
976 The obsolete optional arg COMMON-SUBSTRING, if non-nil, should be a string
977 specifying a common substring for adding the faces
978 `completions-first-difference' and `completions-common-part' to
979 the completions buffer."
980 (if common-substring
981 (setq completions (completion-hilit-commonality
982 completions (length common-substring)
983 ;; We don't know the base-size.
984 nil)))
985 (if (not (bufferp standard-output))
986 ;; This *never* (ever) happens, so there's no point trying to be clever.
987 (with-temp-buffer
988 (let ((standard-output (current-buffer))
989 (completion-setup-hook nil))
990 (display-completion-list completions common-substring))
991 (princ (buffer-string)))
992
993 (with-current-buffer standard-output
994 (goto-char (point-max))
995 (if (null completions)
996 (insert "There are no possible completions of what you have typed.")
997 (insert "Possible completions are:\n")
998 (completion--insert-strings completions))))
999
1000 ;; The hilit used to be applied via completion-setup-hook, so there
1001 ;; may still be some code that uses completion-common-substring.
1002 (with-no-warnings
1003 (let ((completion-common-substring common-substring))
1004 (run-hooks 'completion-setup-hook)))
1005 nil)
1006
1007 (defvar completion-annotate-function
1008 nil
1009 ;; Note: there's a lot of scope as for when to add annotations and
1010 ;; what annotations to add. E.g. completing-help.el allowed adding
1011 ;; the first line of docstrings to M-x completion. But there's
1012 ;; a tension, since such annotations, while useful at times, can
1013 ;; actually drown the useful information.
1014 ;; So completion-annotate-function should be used parsimoniously, or
1015 ;; else only used upon a user's request (e.g. we could add a command
1016 ;; to completion-list-mode to add annotations to the current
1017 ;; completions).
1018 "Function to add annotations in the *Completions* buffer.
1019 The function takes a completion and should either return nil, or a string that
1020 will be displayed next to the completion. The function can access the
1021 completion table and predicates via `minibuffer-completion-table' and related
1022 variables.")
1023
1024 (defun minibuffer-completion-help ()
1025 "Display a list of possible completions of the current minibuffer contents."
1026 (interactive)
1027 (message "Making completion list...")
1028 (let* ((start (field-beginning))
1029 (string (field-string))
1030 (completions (completion-all-completions
1031 string
1032 minibuffer-completion-table
1033 minibuffer-completion-predicate
1034 (- (point) (field-beginning)))))
1035 (message nil)
1036 (if (and completions
1037 (or (consp (cdr completions))
1038 (not (equal (car completions) string))))
1039 (let* ((last (last completions))
1040 (base-size (cdr last))
1041 ;; If the *Completions* buffer is shown in a new
1042 ;; window, mark it as softly-dedicated, so bury-buffer in
1043 ;; minibuffer-hide-completions will know whether to
1044 ;; delete the window or not.
1045 (display-buffer-mark-dedicated 'soft))
1046 (with-output-to-temp-buffer "*Completions*"
1047 ;; Remove the base-size tail because `sort' requires a properly
1048 ;; nil-terminated list.
1049 (when last (setcdr last nil))
1050 (setq completions (sort completions 'string-lessp))
1051 (when completion-annotate-function
1052 (setq completions
1053 (mapcar (lambda (s)
1054 (let ((ann
1055 (funcall completion-annotate-function s)))
1056 (if ann (list s ann) s)))
1057 completions)))
1058 (with-current-buffer standard-output
1059 (set (make-local-variable 'completion-base-position)
1060 ;; FIXME: We should provide the END part as well, but
1061 ;; currently completion-all-completions does not give
1062 ;; us the necessary information.
1063 (list (+ start base-size) nil)))
1064 (display-completion-list completions)))
1065
1066 ;; If there are no completions, or if the current input is already the
1067 ;; only possible completion, then hide (previous&stale) completions.
1068 (minibuffer-hide-completions)
1069 (ding)
1070 (minibuffer-message
1071 (if completions "Sole completion" "No completions")))
1072 nil))
1073
1074 (defun minibuffer-hide-completions ()
1075 "Get rid of an out-of-date *Completions* buffer."
1076 ;; FIXME: We could/should use minibuffer-scroll-window here, but it
1077 ;; can also point to the minibuffer-parent-window, so it's a bit tricky.
1078 (let ((win (get-buffer-window "*Completions*" 0)))
1079 (if win (with-selected-window win (bury-buffer)))))
1080
1081 (defun exit-minibuffer ()
1082 "Terminate this minibuffer argument."
1083 (interactive)
1084 ;; If the command that uses this has made modifications in the minibuffer,
1085 ;; we don't want them to cause deactivation of the mark in the original
1086 ;; buffer.
1087 ;; A better solution would be to make deactivate-mark buffer-local
1088 ;; (or to turn it into a list of buffers, ...), but in the mean time,
1089 ;; this should do the trick in most cases.
1090 (setq deactivate-mark nil)
1091 (throw 'exit nil))
1092
1093 (defun self-insert-and-exit ()
1094 "Terminate minibuffer input."
1095 (interactive)
1096 (if (characterp last-command-event)
1097 (call-interactively 'self-insert-command)
1098 (ding))
1099 (exit-minibuffer))
1100
1101 (defvar completion-in-region-functions nil
1102 "Wrapper hook around `completion-in-region'.
1103 The functions on this special hook are called with 5 arguments:
1104 NEXT-FUN START END COLLECTION PREDICATE.
1105 NEXT-FUN is a function of four arguments (START END COLLECTION PREDICATE)
1106 that performs the default operation. The other four arguments are like
1107 the ones passed to `completion-in-region'. The functions on this hook
1108 are expected to perform completion on START..END using COLLECTION
1109 and PREDICATE, either by calling NEXT-FUN or by doing it themselves.")
1110
1111 (defun completion-in-region (start end collection &optional predicate)
1112 "Complete the text between START and END using COLLECTION.
1113 Return nil if there is no valid completion, else t.
1114 Point needs to be somewhere between START and END."
1115 (assert (<= start (point)) (<= (point) end))
1116 ;; FIXME: undisplay the *Completions* buffer once the completion is done.
1117 (with-wrapper-hook
1118 completion-in-region-functions (start end collection predicate)
1119 (let ((minibuffer-completion-table collection)
1120 (minibuffer-completion-predicate predicate)
1121 (ol (make-overlay start end nil nil t)))
1122 (overlay-put ol 'field 'completion)
1123 (unwind-protect
1124 (call-interactively 'minibuffer-complete)
1125 (delete-overlay ol)))))
1126
1127 (defvar completion-at-point-functions nil
1128 "Special hook to find the completion table for the thing at point.
1129 It is called without any argument and should return either nil,
1130 or a function of no argument to perform completion (discouraged),
1131 or a list of the form (START END COLLECTION &rest PROPS) where
1132 START and END delimit the entity to complete and should include point,
1133 COLLECTION is the completion table to use to complete it, and
1134 PROPS is a property list for additional information.
1135 Currently supported properties are:
1136 `:predicate' a predicate that completion candidates need to satisfy.
1137 `:annotation-function' the value to use for `completion-annotate-function'.")
1138
1139 (defun completion-at-point ()
1140 "Complete the thing at point according to local mode."
1141 (interactive)
1142 (let ((res (run-hook-with-args-until-success
1143 'completion-at-point-functions)))
1144 (cond
1145 ((functionp res) (funcall res))
1146 (res
1147 (let* ((plist (nthcdr 3 res))
1148 (start (nth 0 res))
1149 (end (nth 1 res))
1150 (completion-annotate-function
1151 (or (plist-get plist :annotation-function)
1152 completion-annotate-function)))
1153 (completion-in-region start end (nth 2 res)
1154 (plist-get plist :predicate)))))))
1155
1156 ;;; Key bindings.
1157
1158 (define-obsolete-variable-alias 'minibuffer-local-must-match-filename-map
1159 'minibuffer-local-filename-must-match-map "23.1")
1160
1161 (let ((map minibuffer-local-map))
1162 (define-key map "\C-g" 'abort-recursive-edit)
1163 (define-key map "\r" 'exit-minibuffer)
1164 (define-key map "\n" 'exit-minibuffer))
1165
1166 (let ((map minibuffer-local-completion-map))
1167 (define-key map "\t" 'minibuffer-complete)
1168 ;; M-TAB is already abused for many other purposes, so we should find
1169 ;; another binding for it.
1170 ;; (define-key map "\e\t" 'minibuffer-force-complete)
1171 (define-key map " " 'minibuffer-complete-word)
1172 (define-key map "?" 'minibuffer-completion-help))
1173
1174 (let ((map minibuffer-local-must-match-map))
1175 (define-key map "\r" 'minibuffer-complete-and-exit)
1176 (define-key map "\n" 'minibuffer-complete-and-exit))
1177
1178 (let ((map minibuffer-local-filename-completion-map))
1179 (define-key map " " nil))
1180 (let ((map minibuffer-local-filename-must-match-map))
1181 (define-key map " " nil))
1182
1183 (let ((map minibuffer-local-ns-map))
1184 (define-key map " " 'exit-minibuffer)
1185 (define-key map "\t" 'exit-minibuffer)
1186 (define-key map "?" 'self-insert-and-exit))
1187
1188 ;;; Completion tables.
1189
1190 (defun minibuffer--double-dollars (str)
1191 (replace-regexp-in-string "\\$" "$$" str))
1192
1193 (defun completion--make-envvar-table ()
1194 (mapcar (lambda (enventry)
1195 (substring enventry 0 (string-match-p "=" enventry)))
1196 process-environment))
1197
1198 (defconst completion--embedded-envvar-re
1199 (concat "\\(?:^\\|[^$]\\(?:\\$\\$\\)*\\)"
1200 "$\\([[:alnum:]_]*\\|{\\([^}]*\\)\\)\\'"))
1201
1202 (defun completion--embedded-envvar-table (string pred action)
1203 "Completion table for envvars embedded in a string.
1204 The envvar syntax (and escaping) rules followed by this table are the
1205 same as `substitute-in-file-name'."
1206 ;; We ignore `pred', because the predicates passed to us via
1207 ;; read-file-name-internal are not 100% correct and fail here:
1208 ;; e.g. we get predicates like file-directory-p there, whereas the filename
1209 ;; completed needs to be passed through substitute-in-file-name before it
1210 ;; can be passed to file-directory-p.
1211 (when (string-match completion--embedded-envvar-re string)
1212 (let* ((beg (or (match-beginning 2) (match-beginning 1)))
1213 (table (completion--make-envvar-table))
1214 (prefix (substring string 0 beg)))
1215 (cond
1216 ((eq action 'lambda)
1217 ;; This table is expected to be used in conjunction with some
1218 ;; other table that provides the "main" completion. Let the
1219 ;; other table handle the test-completion case.
1220 nil)
1221 ((eq (car-safe action) 'boundaries)
1222 ;; Only return boundaries if there's something to complete,
1223 ;; since otherwise when we're used in
1224 ;; completion-table-in-turn, we could return boundaries and
1225 ;; let some subsequent table return a list of completions.
1226 ;; FIXME: Maybe it should rather be fixed in
1227 ;; completion-table-in-turn instead, but it's difficult to
1228 ;; do it efficiently there.
1229 (when (try-completion (substring string beg) table nil)
1230 ;; Compute the boundaries of the subfield to which this
1231 ;; completion applies.
1232 (let ((suffix (cdr action)))
1233 (list* 'boundaries
1234 (or (match-beginning 2) (match-beginning 1))
1235 (when (string-match "[^[:alnum:]_]" suffix)
1236 (match-beginning 0))))))
1237 (t
1238 (if (eq (aref string (1- beg)) ?{)
1239 (setq table (apply-partially 'completion-table-with-terminator
1240 "}" table)))
1241 ;; Even if file-name completion is case-insensitive, we want
1242 ;; envvar completion to be case-sensitive.
1243 (let ((completion-ignore-case nil))
1244 (completion-table-with-context
1245 prefix table (substring string beg) nil action)))))))
1246
1247 (defun completion-file-name-table (string pred action)
1248 "Completion table for file names."
1249 (ignore-errors
1250 (cond
1251 ((eq (car-safe action) 'boundaries)
1252 (let ((start (length (file-name-directory string)))
1253 (end (string-match-p "/" (cdr action))))
1254 (list* 'boundaries start end)))
1255
1256 ((eq action 'lambda)
1257 (if (zerop (length string))
1258 nil ;Not sure why it's here, but it probably doesn't harm.
1259 (funcall (or pred 'file-exists-p) string)))
1260
1261 (t
1262 (let* ((name (file-name-nondirectory string))
1263 (specdir (file-name-directory string))
1264 (realdir (or specdir default-directory)))
1265
1266 (cond
1267 ((null action)
1268 (let ((comp (file-name-completion name realdir pred)))
1269 (if (stringp comp)
1270 (concat specdir comp)
1271 comp)))
1272
1273 ((eq action t)
1274 (let ((all (file-name-all-completions name realdir)))
1275
1276 ;; Check the predicate, if necessary.
1277 (unless (memq pred '(nil file-exists-p))
1278 (let ((comp ())
1279 (pred
1280 (if (eq pred 'file-directory-p)
1281 ;; Brute-force speed up for directory checking:
1282 ;; Discard strings which don't end in a slash.
1283 (lambda (s)
1284 (let ((len (length s)))
1285 (and (> len 0) (eq (aref s (1- len)) ?/))))
1286 ;; Must do it the hard (and slow) way.
1287 pred)))
1288 (let ((default-directory (expand-file-name realdir)))
1289 (dolist (tem all)
1290 (if (funcall pred tem) (push tem comp))))
1291 (setq all (nreverse comp))))
1292
1293 all))))))))
1294
1295 (defvar read-file-name-predicate nil
1296 "Current predicate used by `read-file-name-internal'.")
1297 (make-obsolete-variable 'read-file-name-predicate
1298 "use the regular PRED argument" "23.2")
1299
1300 (defun completion--file-name-table (string pred action)
1301 "Internal subroutine for `read-file-name'. Do not call this.
1302 This is a completion table for file names, like `completion-file-name-table'
1303 except that it passes the file name through `substitute-in-file-name'."
1304 (cond
1305 ((eq (car-safe action) 'boundaries)
1306 ;; For the boundaries, we can't really delegate to
1307 ;; completion-file-name-table and then fix them up, because it
1308 ;; would require us to track the relationship between `str' and
1309 ;; `string', which is difficult. And in any case, if
1310 ;; substitute-in-file-name turns "fo-$TO-ba" into "fo-o/b-ba", there's
1311 ;; no way for us to return proper boundaries info, because the
1312 ;; boundary is not (yet) in `string'.
1313 ;; FIXME: Actually there is a way to return correct boundaries info,
1314 ;; at the condition of modifying the all-completions return accordingly.
1315 (let ((start (length (file-name-directory string)))
1316 (end (string-match-p "/" (cdr action))))
1317 (list* 'boundaries start end)))
1318
1319 (t
1320 (let* ((default-directory
1321 (if (stringp pred)
1322 ;; It used to be that `pred' was abused to pass `dir'
1323 ;; as an argument.
1324 (prog1 (file-name-as-directory (expand-file-name pred))
1325 (setq pred nil))
1326 default-directory))
1327 (str (condition-case nil
1328 (substitute-in-file-name string)
1329 (error string)))
1330 (comp (completion-file-name-table
1331 str (or pred read-file-name-predicate) action)))
1332
1333 (cond
1334 ((stringp comp)
1335 ;; Requote the $s before returning the completion.
1336 (minibuffer--double-dollars comp))
1337 ((and (null action) comp
1338 ;; Requote the $s before checking for changes.
1339 (setq str (minibuffer--double-dollars str))
1340 (not (string-equal string str)))
1341 ;; If there's no real completion, but substitute-in-file-name
1342 ;; changed the string, then return the new string.
1343 str)
1344 (t comp))))))
1345
1346 (defalias 'read-file-name-internal
1347 (completion-table-in-turn 'completion--embedded-envvar-table
1348 'completion--file-name-table)
1349 "Internal subroutine for `read-file-name'. Do not call this.")
1350
1351 (defvar read-file-name-function nil
1352 "If this is non-nil, `read-file-name' does its work by calling this function.")
1353
1354 (defcustom read-file-name-completion-ignore-case
1355 (if (memq system-type '(ms-dos windows-nt darwin cygwin))
1356 t nil)
1357 "Non-nil means when reading a file name completion ignores case."
1358 :group 'minibuffer
1359 :type 'boolean
1360 :version "22.1")
1361
1362 (defcustom insert-default-directory t
1363 "Non-nil means when reading a filename start with default dir in minibuffer.
1364
1365 When the initial minibuffer contents show a name of a file or a directory,
1366 typing RETURN without editing the initial contents is equivalent to typing
1367 the default file name.
1368
1369 If this variable is non-nil, the minibuffer contents are always
1370 initially non-empty, and typing RETURN without editing will fetch the
1371 default name, if one is provided. Note however that this default name
1372 is not necessarily the same as initial contents inserted in the minibuffer,
1373 if the initial contents is just the default directory.
1374
1375 If this variable is nil, the minibuffer often starts out empty. In
1376 that case you may have to explicitly fetch the next history element to
1377 request the default name; typing RETURN without editing will leave
1378 the minibuffer empty.
1379
1380 For some commands, exiting with an empty minibuffer has a special meaning,
1381 such as making the current buffer visit no file in the case of
1382 `set-visited-file-name'."
1383 :group 'minibuffer
1384 :type 'boolean)
1385
1386 ;; Not always defined, but only called if next-read-file-uses-dialog-p says so.
1387 (declare-function x-file-dialog "xfns.c"
1388 (prompt dir &optional default-filename mustmatch only-dir-p))
1389
1390 (defun read-file-name-defaults (&optional dir initial)
1391 (let ((default
1392 (cond
1393 ;; With non-nil `initial', use `dir' as the first default.
1394 ;; Essentially, this mean reversing the normal order of the
1395 ;; current directory name and the current file name, i.e.
1396 ;; 1. with normal file reading:
1397 ;; 1.1. initial input is the current directory
1398 ;; 1.2. the first default is the current file name
1399 ;; 2. with non-nil `initial' (e.g. for `find-alternate-file'):
1400 ;; 2.2. initial input is the current file name
1401 ;; 2.1. the first default is the current directory
1402 (initial (abbreviate-file-name dir))
1403 ;; In file buffers, try to get the current file name
1404 (buffer-file-name
1405 (abbreviate-file-name buffer-file-name))))
1406 (file-name-at-point
1407 (run-hook-with-args-until-success 'file-name-at-point-functions)))
1408 (when file-name-at-point
1409 (setq default (delete-dups
1410 (delete "" (delq nil (list file-name-at-point default))))))
1411 ;; Append new defaults to the end of existing `minibuffer-default'.
1412 (append
1413 (if (listp minibuffer-default) minibuffer-default (list minibuffer-default))
1414 (if (listp default) default (list default)))))
1415
1416 (defun read-file-name (prompt &optional dir default-filename mustmatch initial predicate)
1417 "Read file name, prompting with PROMPT and completing in directory DIR.
1418 Value is not expanded---you must call `expand-file-name' yourself.
1419 Default name to DEFAULT-FILENAME if user exits the minibuffer with
1420 the same non-empty string that was inserted by this function.
1421 (If DEFAULT-FILENAME is omitted, the visited file name is used,
1422 except that if INITIAL is specified, that combined with DIR is used.
1423 If DEFAULT-FILENAME is a list of file names, the first file name is used.)
1424 If the user exits with an empty minibuffer, this function returns
1425 an empty string. (This can only happen if the user erased the
1426 pre-inserted contents or if `insert-default-directory' is nil.)
1427
1428 Fourth arg MUSTMATCH can take the following values:
1429 - nil means that the user can exit with any input.
1430 - t means that the user is not allowed to exit unless
1431 the input is (or completes to) an existing file.
1432 - `confirm' means that the user can exit with any input, but she needs
1433 to confirm her choice if the input is not an existing file.
1434 - `confirm-after-completion' means that the user can exit with any
1435 input, but she needs to confirm her choice if she called
1436 `minibuffer-complete' right before `minibuffer-complete-and-exit'
1437 and the input is not an existing file.
1438 - anything else behaves like t except that typing RET does not exit if it
1439 does non-null completion.
1440
1441 Fifth arg INITIAL specifies text to start with.
1442
1443 If optional sixth arg PREDICATE is non-nil, possible completions and
1444 the resulting file name must satisfy (funcall PREDICATE NAME).
1445 DIR should be an absolute directory name. It defaults to the value of
1446 `default-directory'.
1447
1448 If this command was invoked with the mouse, use a graphical file
1449 dialog if `use-dialog-box' is non-nil, and the window system or X
1450 toolkit in use provides a file dialog box, and DIR is not a
1451 remote file. For graphical file dialogs, any the special values
1452 of MUSTMATCH; `confirm' and `confirm-after-completion' are
1453 treated as equivalent to nil.
1454
1455 See also `read-file-name-completion-ignore-case'
1456 and `read-file-name-function'."
1457 (unless dir (setq dir default-directory))
1458 (unless (file-name-absolute-p dir) (setq dir (expand-file-name dir)))
1459 (unless default-filename
1460 (setq default-filename (if initial (expand-file-name initial dir)
1461 buffer-file-name)))
1462 ;; If dir starts with user's homedir, change that to ~.
1463 (setq dir (abbreviate-file-name dir))
1464 ;; Likewise for default-filename.
1465 (if default-filename
1466 (setq default-filename
1467 (if (consp default-filename)
1468 (mapcar 'abbreviate-file-name default-filename)
1469 (abbreviate-file-name default-filename))))
1470 (let ((insdef (cond
1471 ((and insert-default-directory (stringp dir))
1472 (if initial
1473 (cons (minibuffer--double-dollars (concat dir initial))
1474 (length (minibuffer--double-dollars dir)))
1475 (minibuffer--double-dollars dir)))
1476 (initial (cons (minibuffer--double-dollars initial) 0)))))
1477
1478 (if read-file-name-function
1479 (funcall read-file-name-function
1480 prompt dir default-filename mustmatch initial predicate)
1481 (let ((completion-ignore-case read-file-name-completion-ignore-case)
1482 (minibuffer-completing-file-name t)
1483 (pred (or predicate 'file-exists-p))
1484 (add-to-history nil))
1485
1486 (let* ((val
1487 (if (or (not (next-read-file-uses-dialog-p))
1488 ;; Graphical file dialogs can't handle remote
1489 ;; files (Bug#99).
1490 (file-remote-p dir))
1491 ;; We used to pass `dir' to `read-file-name-internal' by
1492 ;; abusing the `predicate' argument. It's better to
1493 ;; just use `default-directory', but in order to avoid
1494 ;; changing `default-directory' in the current buffer,
1495 ;; we don't let-bind it.
1496 (lexical-let ((dir (file-name-as-directory
1497 (expand-file-name dir))))
1498 (minibuffer-with-setup-hook
1499 (lambda ()
1500 (setq default-directory dir)
1501 ;; When the first default in `minibuffer-default'
1502 ;; duplicates initial input `insdef',
1503 ;; reset `minibuffer-default' to nil.
1504 (when (equal (or (car-safe insdef) insdef)
1505 (or (car-safe minibuffer-default)
1506 minibuffer-default))
1507 (setq minibuffer-default
1508 (cdr-safe minibuffer-default)))
1509 ;; On the first request on `M-n' fill
1510 ;; `minibuffer-default' with a list of defaults
1511 ;; relevant for file-name reading.
1512 (set (make-local-variable 'minibuffer-default-add-function)
1513 (lambda ()
1514 (with-current-buffer
1515 (window-buffer (minibuffer-selected-window))
1516 (read-file-name-defaults dir initial)))))
1517 (completing-read prompt 'read-file-name-internal
1518 pred mustmatch insdef
1519 'file-name-history default-filename)))
1520 ;; If DEFAULT-FILENAME not supplied and DIR contains
1521 ;; a file name, split it.
1522 (let ((file (file-name-nondirectory dir))
1523 ;; When using a dialog, revert to nil and non-nil
1524 ;; interpretation of mustmatch. confirm options
1525 ;; need to be interpreted as nil, otherwise
1526 ;; it is impossible to create new files using
1527 ;; dialogs with the default settings.
1528 (dialog-mustmatch
1529 (not (memq mustmatch
1530 '(nil confirm confirm-after-completion)))))
1531 (when (and (not default-filename)
1532 (not (zerop (length file))))
1533 (setq default-filename file)
1534 (setq dir (file-name-directory dir)))
1535 (when default-filename
1536 (setq default-filename
1537 (expand-file-name (if (consp default-filename)
1538 (car default-filename)
1539 default-filename)
1540 dir)))
1541 (setq add-to-history t)
1542 (x-file-dialog prompt dir default-filename
1543 dialog-mustmatch
1544 (eq predicate 'file-directory-p)))))
1545
1546 (replace-in-history (eq (car-safe file-name-history) val)))
1547 ;; If completing-read returned the inserted default string itself
1548 ;; (rather than a new string with the same contents),
1549 ;; it has to mean that the user typed RET with the minibuffer empty.
1550 ;; In that case, we really want to return ""
1551 ;; so that commands such as set-visited-file-name can distinguish.
1552 (when (consp default-filename)
1553 (setq default-filename (car default-filename)))
1554 (when (eq val default-filename)
1555 ;; In this case, completing-read has not added an element
1556 ;; to the history. Maybe we should.
1557 (if (not replace-in-history)
1558 (setq add-to-history t))
1559 (setq val ""))
1560 (unless val (error "No file name specified"))
1561
1562 (if (and default-filename
1563 (string-equal val (if (consp insdef) (car insdef) insdef)))
1564 (setq val default-filename))
1565 (setq val (substitute-in-file-name val))
1566
1567 (if replace-in-history
1568 ;; Replace what Fcompleting_read added to the history
1569 ;; with what we will actually return. As an exception,
1570 ;; if that's the same as the second item in
1571 ;; file-name-history, it's really a repeat (Bug#4657).
1572 (let ((val1 (minibuffer--double-dollars val)))
1573 (if history-delete-duplicates
1574 (setcdr file-name-history
1575 (delete val1 (cdr file-name-history))))
1576 (if (string= val1 (cadr file-name-history))
1577 (pop file-name-history)
1578 (setcar file-name-history val1)))
1579 (if add-to-history
1580 ;; Add the value to the history--but not if it matches
1581 ;; the last value already there.
1582 (let ((val1 (minibuffer--double-dollars val)))
1583 (unless (and (consp file-name-history)
1584 (equal (car file-name-history) val1))
1585 (setq file-name-history
1586 (cons val1
1587 (if history-delete-duplicates
1588 (delete val1 file-name-history)
1589 file-name-history)))))))
1590 val)))))
1591
1592 (defun internal-complete-buffer-except (&optional buffer)
1593 "Perform completion on all buffers excluding BUFFER.
1594 BUFFER nil or omitted means use the current buffer.
1595 Like `internal-complete-buffer', but removes BUFFER from the completion list."
1596 (lexical-let ((except (if (stringp buffer) buffer (buffer-name buffer))))
1597 (apply-partially 'completion-table-with-predicate
1598 'internal-complete-buffer
1599 (lambda (name)
1600 (not (equal (if (consp name) (car name) name) except)))
1601 nil)))
1602
1603 ;;; Old-style completion, used in Emacs-21 and Emacs-22.
1604
1605 (defun completion-emacs21-try-completion (string table pred point)
1606 (let ((completion (try-completion string table pred)))
1607 (if (stringp completion)
1608 (cons completion (length completion))
1609 completion)))
1610
1611 (defun completion-emacs21-all-completions (string table pred point)
1612 (completion-hilit-commonality
1613 (all-completions string table pred)
1614 (length string)
1615 (car (completion-boundaries string table pred ""))))
1616
1617 (defun completion-emacs22-try-completion (string table pred point)
1618 (let ((suffix (substring string point))
1619 (completion (try-completion (substring string 0 point) table pred)))
1620 (if (not (stringp completion))
1621 completion
1622 ;; Merge a trailing / in completion with a / after point.
1623 ;; We used to only do it for word completion, but it seems to make
1624 ;; sense for all completions.
1625 ;; Actually, claiming this feature was part of Emacs-22 completion
1626 ;; is pushing it a bit: it was only done in minibuffer-completion-word,
1627 ;; which was (by default) not bound during file completion, where such
1628 ;; slashes are most likely to occur.
1629 (if (and (not (zerop (length completion)))
1630 (eq ?/ (aref completion (1- (length completion))))
1631 (not (zerop (length suffix)))
1632 (eq ?/ (aref suffix 0)))
1633 ;; This leaves point after the / .
1634 (setq suffix (substring suffix 1)))
1635 (cons (concat completion suffix) (length completion)))))
1636
1637 (defun completion-emacs22-all-completions (string table pred point)
1638 (let ((beforepoint (substring string 0 point)))
1639 (completion-hilit-commonality
1640 (all-completions beforepoint table pred)
1641 point
1642 (car (completion-boundaries beforepoint table pred "")))))
1643
1644 ;;; Basic completion.
1645
1646 (defun completion--merge-suffix (completion point suffix)
1647 "Merge end of COMPLETION with beginning of SUFFIX.
1648 Simple generalization of the \"merge trailing /\" done in Emacs-22.
1649 Return the new suffix."
1650 (if (and (not (zerop (length suffix)))
1651 (string-match "\\(.+\\)\n\\1" (concat completion "\n" suffix)
1652 ;; Make sure we don't compress things to less
1653 ;; than we started with.
1654 point)
1655 ;; Just make sure we didn't match some other \n.
1656 (eq (match-end 1) (length completion)))
1657 (substring suffix (- (match-end 1) (match-beginning 1)))
1658 ;; Nothing to merge.
1659 suffix))
1660
1661 (defun completion-basic-try-completion (string table pred point)
1662 (let* ((beforepoint (substring string 0 point))
1663 (afterpoint (substring string point))
1664 (bounds (completion-boundaries beforepoint table pred afterpoint)))
1665 (if (zerop (cdr bounds))
1666 ;; `try-completion' may return a subtly different result
1667 ;; than `all+merge', so try to use it whenever possible.
1668 (let ((completion (try-completion beforepoint table pred)))
1669 (if (not (stringp completion))
1670 completion
1671 (cons
1672 (concat completion
1673 (completion--merge-suffix completion point afterpoint))
1674 (length completion))))
1675 (let* ((suffix (substring afterpoint (cdr bounds)))
1676 (prefix (substring beforepoint 0 (car bounds)))
1677 (pattern (delete
1678 "" (list (substring beforepoint (car bounds))
1679 'point
1680 (substring afterpoint 0 (cdr bounds)))))
1681 (all (completion-pcm--all-completions prefix pattern table pred)))
1682 (if minibuffer-completing-file-name
1683 (setq all (completion-pcm--filename-try-filter all)))
1684 (completion-pcm--merge-try pattern all prefix suffix)))))
1685
1686 (defun completion-basic-all-completions (string table pred point)
1687 (let* ((beforepoint (substring string 0 point))
1688 (afterpoint (substring string point))
1689 (bounds (completion-boundaries beforepoint table pred afterpoint))
1690 (suffix (substring afterpoint (cdr bounds)))
1691 (prefix (substring beforepoint 0 (car bounds)))
1692 (pattern (delete
1693 "" (list (substring beforepoint (car bounds))
1694 'point
1695 (substring afterpoint 0 (cdr bounds)))))
1696 (all (completion-pcm--all-completions prefix pattern table pred)))
1697 (completion-hilit-commonality all point (car bounds))))
1698
1699 ;;; Partial-completion-mode style completion.
1700
1701 (defvar completion-pcm--delim-wild-regex nil
1702 "Regular expression matching delimiters controlling the partial-completion.
1703 Typically, this regular expression simply matches a delimiter, meaning
1704 that completion can add something at (match-beginning 0), but if it has
1705 a submatch 1, then completion can add something at (match-end 1).
1706 This is used when the delimiter needs to be of size zero (e.g. the transition
1707 from lowercase to uppercase characters).")
1708
1709 (defun completion-pcm--prepare-delim-re (delims)
1710 (setq completion-pcm--delim-wild-regex (concat "[" delims "*]")))
1711
1712 (defcustom completion-pcm-word-delimiters "-_./: "
1713 "A string of characters treated as word delimiters for completion.
1714 Some arcane rules:
1715 If `]' is in this string, it must come first.
1716 If `^' is in this string, it must not come first.
1717 If `-' is in this string, it must come first or right after `]'.
1718 In other words, if S is this string, then `[S]' must be a valid Emacs regular
1719 expression (not containing character ranges like `a-z')."
1720 :set (lambda (symbol value)
1721 (set-default symbol value)
1722 ;; Refresh other vars.
1723 (completion-pcm--prepare-delim-re value))
1724 :initialize 'custom-initialize-reset
1725 :group 'minibuffer
1726 :type 'string)
1727
1728 (defun completion-pcm--pattern-trivial-p (pattern)
1729 (and (stringp (car pattern))
1730 ;; It can be followed by `point' and "" and still be trivial.
1731 (let ((trivial t))
1732 (dolist (elem (cdr pattern))
1733 (unless (member elem '(point ""))
1734 (setq trivial nil)))
1735 trivial)))
1736
1737 (defun completion-pcm--string->pattern (string &optional point)
1738 "Split STRING into a pattern.
1739 A pattern is a list where each element is either a string
1740 or a symbol chosen among `any', `star', `point'."
1741 (if (and point (< point (length string)))
1742 (let ((prefix (substring string 0 point))
1743 (suffix (substring string point)))
1744 (append (completion-pcm--string->pattern prefix)
1745 '(point)
1746 (completion-pcm--string->pattern suffix)))
1747 (let ((pattern nil)
1748 (p 0)
1749 (p0 0))
1750
1751 (while (and (setq p (string-match completion-pcm--delim-wild-regex
1752 string p))
1753 ;; If the char was added by minibuffer-complete-word, then
1754 ;; don't treat it as a delimiter, otherwise "M-x SPC"
1755 ;; ends up inserting a "-" rather than listing
1756 ;; all completions.
1757 (not (get-text-property p 'completion-try-word string)))
1758 ;; Usually, completion-pcm--delim-wild-regex matches a delimiter,
1759 ;; meaning that something can be added *before* it, but it can also
1760 ;; match a prefix and postfix, in which case something can be added
1761 ;; in-between (e.g. match [[:lower:]][[:upper:]]).
1762 ;; This is determined by the presence of a submatch-1 which delimits
1763 ;; the prefix.
1764 (if (match-end 1) (setq p (match-end 1)))
1765 (push (substring string p0 p) pattern)
1766 (if (eq (aref string p) ?*)
1767 (progn
1768 (push 'star pattern)
1769 (setq p0 (1+ p)))
1770 (push 'any pattern)
1771 (setq p0 p))
1772 (incf p))
1773
1774 ;; An empty string might be erroneously added at the beginning.
1775 ;; It should be avoided properly, but it's so easy to remove it here.
1776 (delete "" (nreverse (cons (substring string p0) pattern))))))
1777
1778 (defun completion-pcm--pattern->regex (pattern &optional group)
1779 (let ((re
1780 (concat "\\`"
1781 (mapconcat
1782 (lambda (x)
1783 (case x
1784 ((star any point)
1785 (if (if (consp group) (memq x group) group)
1786 "\\(.*?\\)" ".*?"))
1787 (t (regexp-quote x))))
1788 pattern
1789 ""))))
1790 ;; Avoid pathological backtracking.
1791 (while (string-match "\\.\\*\\?\\(?:\\\\[()]\\)*\\(\\.\\*\\?\\)" re)
1792 (setq re (replace-match "" t t re 1)))
1793 re))
1794
1795 (defun completion-pcm--all-completions (prefix pattern table pred)
1796 "Find all completions for PATTERN in TABLE obeying PRED.
1797 PATTERN is as returned by `completion-pcm--string->pattern'."
1798 ;; (assert (= (car (completion-boundaries prefix table pred ""))
1799 ;; (length prefix)))
1800 ;; Find an initial list of possible completions.
1801 (if (completion-pcm--pattern-trivial-p pattern)
1802
1803 ;; Minibuffer contains no delimiters -- simple case!
1804 (all-completions (concat prefix (car pattern)) table pred)
1805
1806 ;; Use all-completions to do an initial cull. This is a big win,
1807 ;; since all-completions is written in C!
1808 (let* (;; Convert search pattern to a standard regular expression.
1809 (regex (completion-pcm--pattern->regex pattern))
1810 (case-fold-search completion-ignore-case)
1811 (completion-regexp-list (cons regex completion-regexp-list))
1812 (compl (all-completions
1813 (concat prefix (if (stringp (car pattern)) (car pattern) ""))
1814 table pred)))
1815 (if (not (functionp table))
1816 ;; The internal functions already obeyed completion-regexp-list.
1817 compl
1818 (let ((poss ()))
1819 (dolist (c compl)
1820 (when (string-match-p regex c) (push c poss)))
1821 poss)))))
1822
1823 (defun completion-pcm--hilit-commonality (pattern completions)
1824 (when completions
1825 (let* ((re (completion-pcm--pattern->regex pattern '(point)))
1826 (case-fold-search completion-ignore-case))
1827 (mapcar
1828 (lambda (str)
1829 ;; Don't modify the string itself.
1830 (setq str (copy-sequence str))
1831 (unless (string-match re str)
1832 (error "Internal error: %s does not match %s" re str))
1833 (let ((pos (or (match-beginning 1) (match-end 0))))
1834 (put-text-property 0 pos
1835 'font-lock-face 'completions-common-part
1836 str)
1837 (if (> (length str) pos)
1838 (put-text-property pos (1+ pos)
1839 'font-lock-face 'completions-first-difference
1840 str)))
1841 str)
1842 completions))))
1843
1844 (defun completion-pcm--find-all-completions (string table pred point
1845 &optional filter)
1846 "Find all completions for STRING at POINT in TABLE, satisfying PRED.
1847 POINT is a position inside STRING.
1848 FILTER is a function applied to the return value, that can be used, e.g. to
1849 filter out additional entries (because TABLE migth not obey PRED)."
1850 (unless filter (setq filter 'identity))
1851 (let* ((beforepoint (substring string 0 point))
1852 (afterpoint (substring string point))
1853 (bounds (completion-boundaries beforepoint table pred afterpoint))
1854 (prefix (substring beforepoint 0 (car bounds)))
1855 (suffix (substring afterpoint (cdr bounds)))
1856 firsterror)
1857 (setq string (substring string (car bounds) (+ point (cdr bounds))))
1858 (let* ((relpoint (- point (car bounds)))
1859 (pattern (completion-pcm--string->pattern string relpoint))
1860 (all (condition-case err
1861 (funcall filter
1862 (completion-pcm--all-completions
1863 prefix pattern table pred))
1864 (error (unless firsterror (setq firsterror err)) nil))))
1865 (when (and (null all)
1866 (> (car bounds) 0)
1867 (null (ignore-errors (try-completion prefix table pred))))
1868 ;; The prefix has no completions at all, so we should try and fix
1869 ;; that first.
1870 (let ((substring (substring prefix 0 -1)))
1871 (destructuring-bind (subpat suball subprefix subsuffix)
1872 (completion-pcm--find-all-completions
1873 substring table pred (length substring) filter)
1874 (let ((sep (aref prefix (1- (length prefix))))
1875 ;; Text that goes between the new submatches and the
1876 ;; completion substring.
1877 (between nil))
1878 ;; Eliminate submatches that don't end with the separator.
1879 (dolist (submatch (prog1 suball (setq suball ())))
1880 (when (eq sep (aref submatch (1- (length submatch))))
1881 (push submatch suball)))
1882 (when suball
1883 ;; Update the boundaries and corresponding pattern.
1884 ;; We assume that all submatches result in the same boundaries
1885 ;; since we wouldn't know how to merge them otherwise anyway.
1886 ;; FIXME: COMPLETE REWRITE!!!
1887 (let* ((newbeforepoint
1888 (concat subprefix (car suball)
1889 (substring string 0 relpoint)))
1890 (leftbound (+ (length subprefix) (length (car suball))))
1891 (newbounds (completion-boundaries
1892 newbeforepoint table pred afterpoint)))
1893 (unless (or (and (eq (cdr bounds) (cdr newbounds))
1894 (eq (car newbounds) leftbound))
1895 ;; Refuse new boundaries if they step over
1896 ;; the submatch.
1897 (< (car newbounds) leftbound))
1898 ;; The new completed prefix does change the boundaries
1899 ;; of the completed substring.
1900 (setq suffix (substring afterpoint (cdr newbounds)))
1901 (setq string
1902 (concat (substring newbeforepoint (car newbounds))
1903 (substring afterpoint 0 (cdr newbounds))))
1904 (setq between (substring newbeforepoint leftbound
1905 (car newbounds)))
1906 (setq pattern (completion-pcm--string->pattern
1907 string
1908 (- (length newbeforepoint)
1909 (car newbounds)))))
1910 (dolist (submatch suball)
1911 (setq all (nconc (mapcar
1912 (lambda (s) (concat submatch between s))
1913 (funcall filter
1914 (completion-pcm--all-completions
1915 (concat subprefix submatch between)
1916 pattern table pred)))
1917 all)))
1918 ;; FIXME: This can come in handy for try-completion,
1919 ;; but isn't right for all-completions, since it lists
1920 ;; invalid completions.
1921 ;; (unless all
1922 ;; ;; Even though we found expansions in the prefix, none
1923 ;; ;; leads to a valid completion.
1924 ;; ;; Let's keep the expansions, tho.
1925 ;; (dolist (submatch suball)
1926 ;; (push (concat submatch between newsubstring) all)))
1927 ))
1928 (setq pattern (append subpat (list 'any (string sep))
1929 (if between (list between)) pattern))
1930 (setq prefix subprefix)))))
1931 (if (and (null all) firsterror)
1932 (signal (car firsterror) (cdr firsterror))
1933 (list pattern all prefix suffix)))))
1934
1935 (defun completion-pcm-all-completions (string table pred point)
1936 (destructuring-bind (pattern all &optional prefix suffix)
1937 (completion-pcm--find-all-completions string table pred point)
1938 (when all
1939 (nconc (completion-pcm--hilit-commonality pattern all)
1940 (length prefix)))))
1941
1942 (defun completion-pcm--merge-completions (strs pattern)
1943 "Extract the commonality in STRS, with the help of PATTERN."
1944 ;; When completing while ignoring case, we want to try and avoid
1945 ;; completing "fo" to "foO" when completing against "FOO" (bug#4219).
1946 ;; So we try and make sure that the string we return is all made up
1947 ;; of text from the completions rather than part from the
1948 ;; completions and part from the input.
1949 ;; FIXME: This reduces the problems of inconsistent capitalization
1950 ;; but it doesn't fully fix it: we may still end up completing
1951 ;; "fo-ba" to "foo-BAR" or "FOO-bar" when completing against
1952 ;; '("foo-barr" "FOO-BARD").
1953 (cond
1954 ((null (cdr strs)) (list (car strs)))
1955 (t
1956 (let ((re (completion-pcm--pattern->regex pattern 'group))
1957 (ccs ())) ;Chopped completions.
1958
1959 ;; First chop each string into the parts corresponding to each
1960 ;; non-constant element of `pattern', using regexp-matching.
1961 (let ((case-fold-search completion-ignore-case))
1962 (dolist (str strs)
1963 (unless (string-match re str)
1964 (error "Internal error: %s doesn't match %s" str re))
1965 (let ((chopped ())
1966 (last 0)
1967 (i 1)
1968 next)
1969 (while (setq next (match-end i))
1970 (push (substring str last next) chopped)
1971 (setq last next)
1972 (setq i (1+ i)))
1973 ;; Add the text corresponding to the implicit trailing `any'.
1974 (push (substring str last) chopped)
1975 (push (nreverse chopped) ccs))))
1976
1977 ;; Then for each of those non-constant elements, extract the
1978 ;; commonality between them.
1979 (let ((res ())
1980 (fixed ""))
1981 ;; Make the implicit trailing `any' explicit.
1982 (dolist (elem (append pattern '(any)))
1983 (if (stringp elem)
1984 (setq fixed (concat fixed elem))
1985 (let ((comps ()))
1986 (dolist (cc (prog1 ccs (setq ccs nil)))
1987 (push (car cc) comps)
1988 (push (cdr cc) ccs))
1989 ;; Might improve the likelihood to avoid choosing
1990 ;; different capitalizations in different parts.
1991 ;; In practice, it doesn't seem to make any difference.
1992 (setq ccs (nreverse ccs))
1993 (let* ((prefix (try-completion fixed comps))
1994 (unique (or (and (eq prefix t) (setq prefix fixed))
1995 (eq t (try-completion prefix comps)))))
1996 (unless (equal prefix "") (push prefix res))
1997 ;; If there's only one completion, `elem' is not useful
1998 ;; any more: it can only match the empty string.
1999 ;; FIXME: in some cases, it may be necessary to turn an
2000 ;; `any' into a `star' because the surrounding context has
2001 ;; changed such that string->pattern wouldn't add an `any'
2002 ;; here any more.
2003 (unless unique (push elem res))
2004 (setq fixed "")))))
2005 ;; We return it in reverse order.
2006 res)))))
2007
2008 (defun completion-pcm--pattern->string (pattern)
2009 (mapconcat (lambda (x) (cond
2010 ((stringp x) x)
2011 ((eq x 'star) "*")
2012 ((eq x 'any) "")
2013 ((eq x 'point) "")))
2014 pattern
2015 ""))
2016
2017 ;; We want to provide the functionality of `try', but we use `all'
2018 ;; and then merge it. In most cases, this works perfectly, but
2019 ;; if the completion table doesn't consider the same completions in
2020 ;; `try' as in `all', then we have a problem. The most common such
2021 ;; case is for filename completion where completion-ignored-extensions
2022 ;; is only obeyed by the `try' code. We paper over the difference
2023 ;; here. Note that it is not quite right either: if the completion
2024 ;; table uses completion-table-in-turn, this filtering may take place
2025 ;; too late to correctly fallback from the first to the
2026 ;; second alternative.
2027 (defun completion-pcm--filename-try-filter (all)
2028 "Filter to adjust `all' file completion to the behavior of `try'."
2029 (when all
2030 (let ((try ())
2031 (re (concat "\\(?:\\`\\.\\.?/\\|"
2032 (regexp-opt completion-ignored-extensions)
2033 "\\)\\'")))
2034 (dolist (f all)
2035 (unless (string-match-p re f) (push f try)))
2036 (or try all))))
2037
2038
2039 (defun completion-pcm--merge-try (pattern all prefix suffix)
2040 (cond
2041 ((not (consp all)) all)
2042 ((and (not (consp (cdr all))) ;Only one completion.
2043 ;; Ignore completion-ignore-case here.
2044 (equal (completion-pcm--pattern->string pattern) (car all)))
2045 t)
2046 (t
2047 (let* ((mergedpat (completion-pcm--merge-completions all pattern))
2048 ;; `mergedpat' is in reverse order. Place new point (by
2049 ;; order of preference) either at the old point, or at
2050 ;; the last place where there's something to choose, or
2051 ;; at the very end.
2052 (pointpat (or (memq 'point mergedpat)
2053 (memq 'any mergedpat)
2054 (memq 'star mergedpat)
2055 mergedpat))
2056 ;; New pos from the start.
2057 (newpos (length (completion-pcm--pattern->string pointpat)))
2058 ;; Do it afterwards because it changes `pointpat' by sideeffect.
2059 (merged (completion-pcm--pattern->string (nreverse mergedpat))))
2060
2061 (setq suffix (completion--merge-suffix merged newpos suffix))
2062 (cons (concat prefix merged suffix) (+ newpos (length prefix)))))))
2063
2064 (defun completion-pcm-try-completion (string table pred point)
2065 (destructuring-bind (pattern all prefix suffix)
2066 (completion-pcm--find-all-completions
2067 string table pred point
2068 (if minibuffer-completing-file-name
2069 'completion-pcm--filename-try-filter))
2070 (completion-pcm--merge-try pattern all prefix suffix)))
2071
2072 ;;; Initials completion
2073 ;; Complete /ums to /usr/monnier/src or lch to list-command-history.
2074
2075 (defun completion-initials-expand (str table pred)
2076 (let ((bounds (completion-boundaries str table pred "")))
2077 (unless (or (zerop (length str))
2078 ;; Only check within the boundaries, since the
2079 ;; boundary char (e.g. /) might be in delim-regexp.
2080 (string-match completion-pcm--delim-wild-regex str
2081 (car bounds)))
2082 (if (zerop (car bounds))
2083 (mapconcat 'string str "-")
2084 ;; If there's a boundary, it's trickier. The main use-case
2085 ;; we consider here is file-name completion. We'd like
2086 ;; to expand ~/eee to ~/e/e/e and /eee to /e/e/e.
2087 ;; But at the same time, we don't want /usr/share/ae to expand
2088 ;; to /usr/share/a/e just because we mistyped "ae" for "ar",
2089 ;; so we probably don't want initials to touch anything that
2090 ;; looks like /usr/share/foo. As a heuristic, we just check that
2091 ;; the text before the boundary char is at most 1 char.
2092 ;; This allows both ~/eee and /eee and not much more.
2093 ;; FIXME: It sadly also disallows the use of ~/eee when that's
2094 ;; embedded within something else (e.g. "(~/eee" in Info node
2095 ;; completion or "ancestor:/eee" in bzr-revision completion).
2096 (when (< (car bounds) 3)
2097 (let ((sep (substring str (1- (car bounds)) (car bounds))))
2098 ;; FIXME: the above string-match checks the whole string, whereas
2099 ;; we end up only caring about the after-boundary part.
2100 (concat (substring str 0 (car bounds))
2101 (mapconcat 'string (substring str (car bounds)) sep))))))))
2102
2103 (defun completion-initials-all-completions (string table pred point)
2104 (let ((newstr (completion-initials-expand string table pred)))
2105 (when newstr
2106 (completion-pcm-all-completions newstr table pred (length newstr)))))
2107
2108 (defun completion-initials-try-completion (string table pred point)
2109 (let ((newstr (completion-initials-expand string table pred)))
2110 (when newstr
2111 (completion-pcm-try-completion newstr table pred (length newstr)))))
2112
2113 \f
2114 ;; Miscellaneous
2115
2116 (defun minibuffer-insert-file-name-at-point ()
2117 "Get a file name at point in original buffer and insert it to minibuffer."
2118 (interactive)
2119 (let ((file-name-at-point
2120 (with-current-buffer (window-buffer (minibuffer-selected-window))
2121 (run-hook-with-args-until-success 'file-name-at-point-functions))))
2122 (when file-name-at-point
2123 (insert file-name-at-point))))
2124
2125 (provide 'minibuffer)
2126
2127 ;; arch-tag: ef8a0a15-1080-4790-a754-04017c02f08f
2128 ;;; minibuffer.el ends here