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