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