* minibuffer.el (completion-boundaries): Change calling convention, so
[bpt/emacs.git] / lisp / minibuffer.el
1 ;;; minibuffer.el --- Minibuffer completion functions
2
3 ;; Copyright (C) 2008 Free Software Foundation, Inc.
4
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software: you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
21
22 ;;; Commentary:
23
24 ;; Names with "--" are for functions and variables that are meant to be for
25 ;; internal use only.
26
27 ;; Functional completion tables have an extended calling conventions:
28 ;; - If completion-all-completions-with-base-size is set, then all-completions
29 ;; should return the base-size in the last cdr.
30 ;; - The `action' can be (additionally to nil, t, and lambda) of the form
31 ;; (boundaries . SUFFIX) in which case it should return
32 ;; (boundaries START . END). See `completion-boundaries'.
33 ;; Any other return value should be ignored (so we ignore values returned
34 ;; from completion tables that don't know about this new `action' form).
35 ;; See `completion-boundaries'.
36
37 ;;; Bugs:
38
39 ;; - completion-ignored-extensions is ignored by partial-completion because
40 ;; pcm merges the `all' output to synthesize a `try' output and
41 ;; read-file-name-internal's `all' output doesn't obey
42 ;; completion-ignored-extensions.
43 ;; - choose-completion can't automatically figure out the boundaries
44 ;; corresponding to the displayed completions. `base-size' gives the left
45 ;; boundary, but not the righthand one. So we need to add
46 ;; completion-extra-size (and also completion-no-auto-exit).
47
48 ;;; Todo:
49
50 ;; - add support for ** to pcm.
51 ;; - Make read-file-name-predicate obsolete.
52 ;; - Add vc-file-name-completion-table to read-file-name-internal.
53 ;; - A feature like completing-help.el.
54 ;; - Make the `hide-spaces' arg of all-completions obsolete?
55
56 ;;; Code:
57
58 (eval-when-compile (require 'cl))
59
60 (defvar completion-all-completions-with-base-size nil
61 "If non-nil, `all-completions' may return the base-size in the last cdr.
62 The base-size is the length of the prefix that is elided from each
63 element in the returned list of completions. See `completion-base-size'.")
64
65 ;;; Completion table manipulation
66
67 ;; New completion-table operation.
68 (defun completion-boundaries (string table pred suffix)
69 "Return the boundaries of the completions returned by TABLE for STRING.
70 STRING is the string on which completion will be performed.
71 SUFFIX is the string after point.
72 The result is of the form (START . END) where START is the position
73 in STRING of the beginning of the completion field and END is the position
74 in SUFFIX of the end of the completion field.
75 I.e. START is the same as the `completion-base-size'.
76 E.g. for simple completion tables, the result is always (0 . (length SUFFIX))
77 and for file names the result is the positions delimited by
78 the closest directory separators."
79 (let ((boundaries (if (functionp table)
80 (funcall table string pred (cons 'boundaries suffix)))))
81 (if (not (eq (car-safe boundaries) 'boundaries))
82 (setq boundaries nil))
83 (cons (or (cadr boundaries) 0)
84 (or (cddr boundaries) (length suffix)))))
85
86 (defun completion--some (fun xs)
87 "Apply FUN to each element of XS in turn.
88 Return the first non-nil returned value.
89 Like CL's `some'."
90 (let ((firsterror nil)
91 res)
92 (while (and (not res) xs)
93 (condition-case err
94 (setq res (funcall fun (pop xs)))
95 (error (unless firsterror (setq firsterror err)) nil)))
96 (or res
97 (if firsterror (signal (car firsterror) (cdr firsterror))))))
98
99 (defun apply-partially (fun &rest args)
100 "Do a \"curried\" partial application of FUN to ARGS.
101 ARGS is a list of the first N arguments to pass to FUN.
102 The result is a new function that takes the remaining arguments,
103 and calls FUN."
104 (lexical-let ((fun fun) (args1 args))
105 (lambda (&rest args2) (apply fun (append args1 args2)))))
106
107 (defun complete-with-action (action table string pred)
108 "Perform completion ACTION.
109 STRING is the string to complete.
110 TABLE is the completion table, which should not be a function.
111 PRED is a completion predicate.
112 ACTION can be one of nil, t or `lambda'."
113 (cond
114 ((functionp table) (funcall table string pred action))
115 ((eq (car-safe action) 'boundaries)
116 (cons 'boundaries (completion-boundaries string table pred (cdr action))))
117 (t
118 (funcall
119 (cond
120 ((null action) 'try-completion)
121 ((eq action t) 'all-completions)
122 (t 'test-completion))
123 string table pred))))
124
125 (defun completion-table-dynamic (fun)
126 "Use function FUN as a dynamic completion table.
127 FUN is called with one argument, the string for which completion is required,
128 and it should return an alist containing all the intended possible completions.
129 This alist may be a full list of possible completions so that FUN can ignore
130 the value of its argument. If completion is performed in the minibuffer,
131 FUN will be called in the buffer from which the minibuffer was entered.
132
133 The result of the `dynamic-completion-table' form is a function
134 that can be used as the ALIST argument to `try-completion' and
135 `all-completions'. See Info node `(elisp)Programmed Completion'."
136 (lexical-let ((fun fun))
137 (lambda (string pred action)
138 (with-current-buffer (let ((win (minibuffer-selected-window)))
139 (if (window-live-p win) (window-buffer win)
140 (current-buffer)))
141 (complete-with-action action (funcall fun string) string pred)))))
142
143 (defmacro lazy-completion-table (var fun)
144 "Initialize variable VAR as a lazy completion table.
145 If the completion table VAR is used for the first time (e.g., by passing VAR
146 as an argument to `try-completion'), the function FUN is called with no
147 arguments. FUN must return the completion table that will be stored in VAR.
148 If completion is requested in the minibuffer, FUN will be called in the buffer
149 from which the minibuffer was entered. The return value of
150 `lazy-completion-table' must be used to initialize the value of VAR.
151
152 You should give VAR a non-nil `risky-local-variable' property."
153 (declare (debug (symbolp lambda-expr)))
154 (let ((str (make-symbol "string")))
155 `(completion-table-dynamic
156 (lambda (,str)
157 (when (functionp ,var)
158 (setq ,var (,fun)))
159 ,var))))
160
161 (defun completion-table-with-context (prefix table string pred action)
162 ;; TODO: add `suffix' maybe?
163 ;; Notice that `pred' may not be a function in some abusive cases.
164 (when (functionp pred)
165 (setq pred
166 (lexical-let ((pred pred))
167 ;; Predicates are called differently depending on the nature of
168 ;; the completion table :-(
169 (cond
170 ((vectorp table) ;Obarray.
171 (lambda (sym) (funcall pred (concat prefix (symbol-name sym)))))
172 ((hash-table-p table)
173 (lambda (s v) (funcall pred (concat prefix s))))
174 ((functionp table)
175 (lambda (s) (funcall pred (concat prefix s))))
176 (t ;Lists and alists.
177 (lambda (s)
178 (funcall pred (concat prefix (if (consp s) (car s) s)))))))))
179 (if (eq (car-safe action) 'boundaries)
180 (let* ((len (length prefix))
181 (bound (completion-boundaries string table pred (cdr action))))
182 (list* 'boundaries (+ (car bound) len) (cdr bound)))
183 (let ((comp (complete-with-action action table string pred)))
184 (cond
185 ;; In case of try-completion, add the prefix.
186 ((stringp comp) (concat prefix comp))
187 ;; In case of non-empty all-completions,
188 ;; add the prefix size to the base-size.
189 ((consp comp)
190 (let ((last (last comp)))
191 (when completion-all-completions-with-base-size
192 (setcdr last (+ (or (cdr last) 0) (length prefix))))
193 comp))
194 (t comp)))))
195
196 (defun completion-table-with-terminator (terminator table string pred action)
197 (cond
198 ((eq action nil)
199 (let ((comp (try-completion string table pred)))
200 (if (eq comp t)
201 (concat string terminator)
202 (if (and (stringp comp)
203 (eq (try-completion comp table pred) t))
204 (concat comp terminator)
205 comp))))
206 ((eq action t)
207 ;; FIXME: We generally want the `try' and `all' behaviors to be
208 ;; consistent so pcm can merge the `all' output to get the `try' output,
209 ;; but that sometimes clashes with the need for `all' output to look
210 ;; good in *Completions*.
211 ;; (let* ((all (all-completions string table pred))
212 ;; (last (last all))
213 ;; (base-size (cdr last)))
214 ;; (when all
215 ;; (setcdr all nil)
216 ;; (nconc (mapcar (lambda (s) (concat s terminator)) all) base-size)))
217 (all-completions string table pred))
218 ;; completion-table-with-terminator is always used for
219 ;; "sub-completions" so it's only called if the terminator is missing,
220 ;; in which case `test-completion' should return nil.
221 ((eq action 'lambda) nil)))
222
223 (defun completion-table-with-predicate (table pred1 strict string pred2 action)
224 "Make a completion table equivalent to TABLE but filtered through PRED1.
225 PRED1 is a function of one argument which returns non-nil if and only if the
226 argument is an element of TABLE which should be considered for completion.
227 STRING, PRED2, and ACTION are the usual arguments to completion tables,
228 as described in `try-completion', `all-completions', and `test-completion'.
229 If STRICT is t, the predicate always applies; if nil it only applies if
230 it does not reduce the set of possible completions to nothing.
231 Note: TABLE needs to be a proper completion table which obeys predicates."
232 (cond
233 ((and (not strict) (eq action 'lambda))
234 ;; Ignore pred1 since it doesn't really have to apply anyway.
235 (test-completion string table pred2))
236 (t
237 (or (complete-with-action action table string
238 (if (null pred2) pred1
239 (lexical-let ((pred1 pred2) (pred2 pred2))
240 (lambda (x)
241 ;; Call `pred1' first, so that `pred2'
242 ;; really can't tell that `x' is in table.
243 (if (funcall pred1 x) (funcall pred2 x))))))
244 ;; If completion failed and we're not applying pred1 strictly, try
245 ;; again without pred1.
246 (and (not strict)
247 (complete-with-action action table string pred2))))))
248
249 (defun completion-table-in-turn (&rest tables)
250 "Create a completion table that tries each table in TABLES in turn."
251 (lexical-let ((tables tables))
252 (lambda (string pred action)
253 (completion--some (lambda (table)
254 (complete-with-action action table string pred))
255 tables))))
256
257 ;; (defmacro complete-in-turn (a b) `(completion-table-in-turn ,a ,b))
258 ;; (defmacro dynamic-completion-table (fun) `(completion-table-dynamic ,fun))
259 (define-obsolete-function-alias
260 'complete-in-turn 'completion-table-in-turn "23.1")
261 (define-obsolete-function-alias
262 'dynamic-completion-table 'completion-table-dynamic "23.1")
263
264 ;;; Minibuffer completion
265
266 (defgroup minibuffer nil
267 "Controlling the behavior of the minibuffer."
268 :link '(custom-manual "(emacs)Minibuffer")
269 :group 'environment)
270
271 (defun minibuffer-message (message &rest args)
272 "Temporarily display MESSAGE at the end of the minibuffer.
273 The text is displayed for `minibuffer-message-timeout' seconds,
274 or until the next input event arrives, whichever comes first.
275 Enclose MESSAGE in [...] if this is not yet the case.
276 If ARGS are provided, then pass MESSAGE through `format'."
277 ;; Clear out any old echo-area message to make way for our new thing.
278 (message nil)
279 (setq message (if (and (null args) (string-match "\\[.+\\]" message))
280 ;; Make sure we can put-text-property.
281 (copy-sequence message)
282 (concat " [" message "]")))
283 (when args (setq message (apply 'format message args)))
284 (let ((ol (make-overlay (point-max) (point-max) nil t t)))
285 (unwind-protect
286 (progn
287 (unless (zerop (length message))
288 ;; The current C cursor code doesn't know to use the overlay's
289 ;; marker's stickiness to figure out whether to place the cursor
290 ;; before or after the string, so let's spoon-feed it the pos.
291 (put-text-property 0 1 'cursor t message))
292 (overlay-put ol 'after-string message)
293 (sit-for (or minibuffer-message-timeout 1000000)))
294 (delete-overlay ol))))
295
296 (defun minibuffer-completion-contents ()
297 "Return the user input in a minibuffer before point as a string.
298 That is what completion commands operate on."
299 (buffer-substring (field-beginning) (point)))
300
301 (defun delete-minibuffer-contents ()
302 "Delete all user input in a minibuffer.
303 If the current buffer is not a minibuffer, erase its entire contents."
304 (delete-field))
305
306 (defcustom completion-auto-help t
307 "Non-nil means automatically provide help for invalid completion input.
308 If the value is t the *Completion* buffer is displayed whenever completion
309 is requested but cannot be done.
310 If the value is `lazy', the *Completions* buffer is only displayed after
311 the second failed attempt to complete."
312 :type '(choice (const nil) (const t) (const lazy))
313 :group 'minibuffer)
314
315 (defvar completion-styles-alist
316 '((basic completion-basic-try-completion completion-basic-all-completions)
317 (emacs22 completion-emacs22-try-completion completion-emacs22-all-completions)
318 (emacs21 completion-emacs21-try-completion completion-emacs21-all-completions)
319 (partial-completion
320 completion-pcm-try-completion completion-pcm-all-completions))
321 "List of available completion styles.
322 Each element has the form (NAME TRY-COMPLETION ALL-COMPLETIONS)
323 where NAME is the name that should be used in `completion-styles',
324 TRY-COMPLETION is the function that does the completion, and
325 ALL-COMPLETIONS is the function that lists the completions.")
326
327 (defcustom completion-styles '(basic partial-completion)
328 "List of completion styles to use."
329 :type `(repeat (choice ,@(mapcar (lambda (x) (list 'const (car x)))
330 completion-styles-alist)))
331 :group 'minibuffer
332 :version "23.1")
333
334 (defun completion-try-completion (string table pred point)
335 "Try to complete STRING using completion table TABLE.
336 Only the elements of table that satisfy predicate PRED are considered.
337 POINT is the position of point within STRING.
338 The return value can be either nil to indicate that there is no completion,
339 t to indicate that STRING is the only possible completion,
340 or a pair (STRING . NEWPOINT) of the completed result string together with
341 a new position for point."
342 ;; The property `completion-styles' indicates that this functional
343 ;; completion-table claims to take care of completion styles itself.
344 ;; [I.e. It will most likely call us back at some point. ]
345 (if (and (symbolp table) (get table 'completion-styles))
346 ;; Extended semantics for functional completion-tables:
347 ;; They accept a 4th argument `point' and when called with action=nil
348 ;; and this 4th argument (a position inside `string'), they should
349 ;; return instead of a string a pair (STRING . NEWPOINT).
350 (funcall table string pred nil point)
351 (completion--some (lambda (style)
352 (funcall (nth 1 (assq style completion-styles-alist))
353 string table pred point))
354 completion-styles)))
355
356 (defun completion-all-completions (string table pred point)
357 "List the possible completions of STRING in completion table TABLE.
358 Only the elements of table that satisfy predicate PRED are considered.
359 POINT is the position of point within STRING.
360 The return value is a list of completions and may contain the base-size
361 in the last `cdr'."
362 (let ((completion-all-completions-with-base-size t))
363 ;; The property `completion-styles' indicates that this functional
364 ;; completion-table claims to take care of completion styles itself.
365 ;; [I.e. It will most likely call us back at some point. ]
366 (if (and (symbolp table) (get table 'completion-styles))
367 ;; Extended semantics for functional completion-tables:
368 ;; They accept a 4th argument `point' and when called with action=t
369 ;; and this 4th argument (a position inside `string'), they may
370 ;; return BASE-SIZE in the last `cdr'.
371 (funcall table string pred t point)
372 (completion--some (lambda (style)
373 (funcall (nth 2 (assq style completion-styles-alist))
374 string table pred point))
375 completion-styles))))
376
377 (defun minibuffer--bitset (modified completions exact)
378 (logior (if modified 4 0)
379 (if completions 2 0)
380 (if exact 1 0)))
381
382 (defun completion--do-completion (&optional try-completion-function)
383 "Do the completion and return a summary of what happened.
384 M = completion was performed, the text was Modified.
385 C = there were available Completions.
386 E = after completion we now have an Exact match.
387
388 MCE
389 000 0 no possible completion
390 001 1 was already an exact and unique completion
391 010 2 no completion happened
392 011 3 was already an exact completion
393 100 4 ??? impossible
394 101 5 ??? impossible
395 110 6 some completion happened
396 111 7 completed to an exact completion"
397 (let* ((beg (field-beginning))
398 (end (field-end))
399 (string (buffer-substring beg end))
400 (comp (funcall (or try-completion-function
401 'completion-try-completion)
402 string
403 minibuffer-completion-table
404 minibuffer-completion-predicate
405 (- (point) beg))))
406 (cond
407 ((null comp)
408 (ding) (minibuffer-message "No match") (minibuffer--bitset nil nil nil))
409 ((eq t comp) (minibuffer--bitset nil nil t)) ;Exact and unique match.
410 (t
411 ;; `completed' should be t if some completion was done, which doesn't
412 ;; include simply changing the case of the entered string. However,
413 ;; for appearance, the string is rewritten if the case changes.
414 (let* ((comp-pos (cdr comp))
415 (completion (car comp))
416 (completed (not (eq t (compare-strings completion nil nil
417 string nil nil t))))
418 (unchanged (eq t (compare-strings completion nil nil
419 string nil nil nil))))
420 (unless unchanged
421
422 ;; Insert in minibuffer the chars we got.
423 (goto-char end)
424 (insert completion)
425 (delete-region beg end))
426 ;; Move point.
427 (goto-char (+ beg comp-pos))
428
429 (if (not (or unchanged completed))
430 ;; The case of the string changed, but that's all. We're not sure
431 ;; whether this is a unique completion or not, so try again using
432 ;; the real case (this shouldn't recurse again, because the next
433 ;; time try-completion will return either t or the exact string).
434 (completion--do-completion try-completion-function)
435
436 ;; It did find a match. Do we match some possibility exactly now?
437 (let ((exact (test-completion completion
438 minibuffer-completion-table
439 minibuffer-completion-predicate)))
440 (unless completed
441 ;; Show the completion table, if requested.
442 (cond
443 ((not exact)
444 (if (case completion-auto-help
445 (lazy (eq this-command last-command))
446 (t completion-auto-help))
447 (minibuffer-completion-help)
448 (minibuffer-message "Next char not unique")))
449 ;; If the last exact completion and this one were the same,
450 ;; it means we've already given a "Complete but not unique"
451 ;; message and the user's hit TAB again, so now we give him help.
452 ((eq this-command last-command)
453 (if completion-auto-help (minibuffer-completion-help)))))
454
455 (minibuffer--bitset completed t exact))))))))
456
457 (defun minibuffer-complete ()
458 "Complete the minibuffer contents as far as possible.
459 Return nil if there is no valid completion, else t.
460 If no characters can be completed, display a list of possible completions.
461 If you repeat this command after it displayed such a list,
462 scroll the window of possible completions."
463 (interactive)
464 ;; If the previous command was not this,
465 ;; mark the completion buffer obsolete.
466 (unless (eq this-command last-command)
467 (setq minibuffer-scroll-window nil))
468
469 (let ((window minibuffer-scroll-window))
470 ;; If there's a fresh completion window with a live buffer,
471 ;; and this command is repeated, scroll that window.
472 (if (window-live-p window)
473 (with-current-buffer (window-buffer window)
474 (if (pos-visible-in-window-p (point-max) window)
475 ;; If end is in view, scroll up to the beginning.
476 (set-window-start window (point-min) nil)
477 ;; Else scroll down one screen.
478 (scroll-other-window))
479 nil)
480
481 (case (completion--do-completion)
482 (#b000 nil)
483 (#b001 (goto-char (field-end))
484 (minibuffer-message "Sole completion")
485 t)
486 (#b011 (goto-char (field-end))
487 (minibuffer-message "Complete, but not unique")
488 t)
489 (t t)))))
490
491 (defvar completion-all-sorted-completions nil)
492 (make-variable-buffer-local 'completion-all-sorted-completions)
493
494 (defun completion--flush-all-sorted-completions (&rest ignore)
495 (setq completion-all-sorted-completions nil))
496
497 (defun completion-all-sorted-completions ()
498 (or completion-all-sorted-completions
499 (let* ((start (field-beginning))
500 (end (field-end))
501 (all (completion-all-completions (buffer-substring start end)
502 minibuffer-completion-table
503 minibuffer-completion-predicate
504 (- (point) start)))
505 (last (last all))
506 (base-size (or (cdr last) 0)))
507 (when last
508 (setcdr last nil)
509 ;; Prefer shorter completions.
510 (setq all (sort all (lambda (c1 c2) (< (length c1) (length c2)))))
511 ;; Prefer recently used completions.
512 (let ((hist (symbol-value minibuffer-history-variable)))
513 (setq all (sort all (lambda (c1 c2)
514 (> (length (member c1 hist))
515 (length (member c2 hist)))))))
516 ;; Cache the result. This is not just for speed, but also so that
517 ;; repeated calls to minibuffer-force-complete can cycle through
518 ;; all possibilities.
519 (add-hook 'after-change-functions
520 'completion--flush-all-sorted-completions nil t)
521 (setq completion-all-sorted-completions
522 (nconc all base-size))))))
523
524 (defun minibuffer-force-complete ()
525 "Complete the minibuffer to an exact match.
526 Repeated uses step through the possible completions."
527 (interactive)
528 ;; FIXME: Need to deal with the extra-size issue here as well.
529 (let* ((start (field-beginning))
530 (end (field-end))
531 (all (completion-all-sorted-completions)))
532 (if (not (consp all))
533 (minibuffer-message (if all "No more completions" "No completions"))
534 (goto-char end)
535 (insert (car all))
536 (delete-region (+ start (cdr (last all))) end)
537 ;; If completing file names, (car all) may be a directory, so we'd now
538 ;; have a new set of possible completions and might want to reset
539 ;; completion-all-sorted-completions to nil, but we prefer not to,
540 ;; so that repeated calls minibuffer-force-complete still cycle
541 ;; through the previous possible completions.
542 (setq completion-all-sorted-completions (cdr all)))))
543
544 (defun minibuffer-complete-and-exit ()
545 "If the minibuffer contents is a valid completion then exit.
546 Otherwise try to complete it. If completion leads to a valid completion,
547 a repetition of this command will exit.
548 If `minibuffer-completion-confirm' is equal to `confirm', then do not
549 try to complete, but simply ask for confirmation and accept any
550 input if confirmed."
551 (interactive)
552 (let ((beg (field-beginning))
553 (end (field-end)))
554 (cond
555 ;; Allow user to specify null string
556 ((= beg end) (exit-minibuffer))
557 ((test-completion (buffer-substring beg end)
558 minibuffer-completion-table
559 minibuffer-completion-predicate)
560 (when completion-ignore-case
561 ;; Fixup case of the field, if necessary.
562 (let* ((string (buffer-substring beg end))
563 (compl (try-completion
564 string
565 minibuffer-completion-table
566 minibuffer-completion-predicate)))
567 (when (and (stringp compl)
568 ;; If it weren't for this piece of paranoia, I'd replace
569 ;; the whole thing with a call to do-completion.
570 (= (length string) (length compl)))
571 (goto-char end)
572 (insert compl)
573 (delete-region beg end))))
574 (exit-minibuffer))
575
576 ((eq minibuffer-completion-confirm 'confirm-only)
577 ;; The user is permitted to exit with an input that's rejected
578 ;; by test-completion, but at the condition to confirm her choice.
579 (if (eq last-command this-command)
580 (exit-minibuffer)
581 (minibuffer-message "Confirm")
582 nil))
583
584 (t
585 ;; Call do-completion, but ignore errors.
586 (case (condition-case nil
587 (completion--do-completion)
588 (error 1))
589 ((#b001 #b011) (exit-minibuffer))
590 (#b111 (if (not minibuffer-completion-confirm)
591 (exit-minibuffer)
592 (minibuffer-message "Confirm")
593 nil))
594 (t nil))))))
595
596 (defun completion--try-word-completion (string table predicate point)
597 (let ((comp (completion-try-completion string table predicate point)))
598 (if (not (consp comp))
599 comp
600
601 ;; If completion finds next char not unique,
602 ;; consider adding a space or a hyphen.
603 (when (= (length string) (length (car comp)))
604 (let ((exts '(" " "-"))
605 (before (substring string 0 point))
606 (after (substring string point))
607 ;; If the user hasn't entered any text yet, then she
608 ;; presumably hits SPC to see the *completions*, but
609 ;; partial-completion will often find a " " or a "-" to match.
610 ;; So disable partial-completion in that situation.
611 (completion-styles
612 (or (and (equal string "")
613 (remove 'partial-completion completion-styles))
614 completion-styles))
615 tem)
616 (while (and exts (not (consp tem)))
617 (setq tem (completion-try-completion
618 (concat before (pop exts) after)
619 table predicate (1+ point))))
620 (if (consp tem) (setq comp tem))))
621
622 ;; Completing a single word is actually more difficult than completing
623 ;; as much as possible, because we first have to find the "current
624 ;; position" in `completion' in order to find the end of the word
625 ;; we're completing. Normally, `string' is a prefix of `completion',
626 ;; which makes it trivial to find the position, but with fancier
627 ;; completion (plus env-var expansion, ...) `completion' might not
628 ;; look anything like `string' at all.
629 (let* ((comppoint (cdr comp))
630 (completion (car comp))
631 (before (substring string 0 point))
632 (combined (concat before "\n" completion)))
633 ;; Find in completion the longest text that was right before point.
634 (when (string-match "\\(.+\\)\n.*?\\1" combined)
635 (let* ((prefix (match-string 1 before))
636 ;; We used non-greedy match to make `rem' as long as possible.
637 (rem (substring combined (match-end 0)))
638 ;; Find in the remainder of completion the longest text
639 ;; that was right after point.
640 (after (substring string point))
641 (suffix (if (string-match "\\`\\(.+\\).*\n.*\\1"
642 (concat after "\n" rem))
643 (match-string 1 after))))
644 ;; The general idea is to try and guess what text was inserted
645 ;; at point by the completion. Problem is: if we guess wrong,
646 ;; we may end up treating as "added by completion" text that was
647 ;; actually painfully typed by the user. So if we then cut
648 ;; after the first word, we may throw away things the
649 ;; user wrote. So let's try to be as conservative as possible:
650 ;; only cut after the first word, if we're reasonably sure that
651 ;; our guess is correct.
652 ;; Note: a quick survey on emacs-devel seemed to indicate that
653 ;; nobody actually cares about the "word-at-a-time" feature of
654 ;; minibuffer-complete-word, whose real raison-d'être is that it
655 ;; tries to add "-" or " ". One more reason to only cut after
656 ;; the first word, if we're really sure we're right.
657 (when (and (or suffix (zerop (length after)))
658 (string-match (concat
659 ;; Make submatch 1 as small as possible
660 ;; to reduce the risk of cutting
661 ;; valuable text.
662 ".*" (regexp-quote prefix) "\\(.*?\\)"
663 (if suffix (regexp-quote suffix) "\\'"))
664 completion)
665 ;; The new point in `completion' should also be just
666 ;; before the suffix, otherwise something more complex
667 ;; is going on, and we're not sure where we are.
668 (eq (match-end 1) comppoint)
669 ;; (match-beginning 1)..comppoint is now the stretch
670 ;; of text in `completion' that was completed at point.
671 (string-match "\\W" completion (match-beginning 1))
672 ;; Is there really something to cut?
673 (> comppoint (match-end 0)))
674 ;; Cut after the first word.
675 (let ((cutpos (match-end 0)))
676 (setq completion (concat (substring completion 0 cutpos)
677 (substring completion comppoint)))
678 (setq comppoint cutpos)))))
679
680 (cons completion comppoint)))))
681
682
683 (defun minibuffer-complete-word ()
684 "Complete the minibuffer contents at most a single word.
685 After one word is completed as much as possible, a space or hyphen
686 is added, provided that matches some possible completion.
687 Return nil if there is no valid completion, else t."
688 (interactive)
689 (case (completion--do-completion 'completion--try-word-completion)
690 (#b000 nil)
691 (#b001 (goto-char (field-end))
692 (minibuffer-message "Sole completion")
693 t)
694 (#b011 (goto-char (field-end))
695 (minibuffer-message "Complete, but not unique")
696 t)
697 (t t)))
698
699 (defun completion--insert-strings (strings)
700 "Insert a list of STRINGS into the current buffer.
701 Uses columns to keep the listing readable but compact.
702 It also eliminates runs of equal strings."
703 (when (consp strings)
704 (let* ((length (apply 'max
705 (mapcar (lambda (s)
706 (if (consp s)
707 (+ (string-width (car s))
708 (string-width (cadr s)))
709 (string-width s)))
710 strings)))
711 (window (get-buffer-window (current-buffer) 0))
712 (wwidth (if window (1- (window-width window)) 79))
713 (columns (min
714 ;; At least 2 columns; at least 2 spaces between columns.
715 (max 2 (/ wwidth (+ 2 length)))
716 ;; Don't allocate more columns than we can fill.
717 ;; Windows can't show less than 3 lines anyway.
718 (max 1 (/ (length strings) 2))))
719 (colwidth (/ wwidth columns))
720 (column 0)
721 (laststring nil))
722 ;; The insertion should be "sensible" no matter what choices were made
723 ;; for the parameters above.
724 (dolist (str strings)
725 (unless (equal laststring str) ; Remove (consecutive) duplicates.
726 (setq laststring str)
727 (unless (bolp)
728 (insert " \t")
729 (setq column (+ column colwidth))
730 ;; Leave the space unpropertized so that in the case we're
731 ;; already past the goal column, there is still
732 ;; a space displayed.
733 (set-text-properties (- (point) 1) (point)
734 ;; We can't just set tab-width, because
735 ;; completion-setup-function will kill all
736 ;; local variables :-(
737 `(display (space :align-to ,column)))
738 (when (< wwidth (+ (max colwidth
739 (if (consp str)
740 (+ (string-width (car str))
741 (string-width (cadr str)))
742 (string-width str)))
743 column))
744 (delete-char -2) (insert "\n") (setq column 0)))
745 (if (not (consp str))
746 (put-text-property (point) (progn (insert str) (point))
747 'mouse-face 'highlight)
748 (put-text-property (point) (progn (insert (car str)) (point))
749 'mouse-face 'highlight)
750 (put-text-property (point) (progn (insert (cadr str)) (point))
751 'mouse-face nil)))))))
752
753 (defvar completion-common-substring nil)
754 (make-obsolete-variable 'completion-common-substring nil "23.1")
755
756 (defvar completion-setup-hook nil
757 "Normal hook run at the end of setting up a completion list buffer.
758 When this hook is run, the current buffer is the one in which the
759 command to display the completion list buffer was run.
760 The completion list buffer is available as the value of `standard-output'.
761 See also `display-completion-list'.")
762
763 (defface completions-first-difference
764 '((t (:inherit bold)))
765 "Face put on the first uncommon character in completions in *Completions* buffer."
766 :group 'completion)
767
768 (defface completions-common-part
769 '((t (:inherit default)))
770 "Face put on the common prefix substring in completions in *Completions* buffer.
771 The idea of `completions-common-part' is that you can use it to
772 make the common parts less visible than normal, so that the rest
773 of the differing parts is, by contrast, slightly highlighted."
774 :group 'completion)
775
776 (defun completion-hilit-commonality (completions prefix-len)
777 (when completions
778 (let* ((last (last completions))
779 (base-size (cdr last))
780 (com-str-len (- prefix-len (or base-size 0))))
781 ;; Remove base-size during mapcar, and add it back later.
782 (setcdr last nil)
783 (nconc
784 (mapcar
785 (lambda (elem)
786 (let ((str
787 ;; Don't modify the string itself, but a copy, since the
788 ;; the string may be read-only or used for other purposes.
789 ;; Furthermore, since `completions' may come from
790 ;; display-completion-list, `elem' may be a list.
791 (if (consp elem)
792 (car (setq elem (cons (copy-sequence (car elem))
793 (cdr elem))))
794 (setq elem (copy-sequence elem)))))
795 (put-text-property 0 com-str-len
796 'font-lock-face 'completions-common-part
797 str)
798 (if (> (length str) com-str-len)
799 (put-text-property com-str-len (1+ com-str-len)
800 'font-lock-face 'completions-first-difference
801 str)))
802 elem)
803 completions)
804 base-size))))
805
806 (defun display-completion-list (completions &optional common-substring)
807 "Display the list of completions, COMPLETIONS, using `standard-output'.
808 Each element may be just a symbol or string
809 or may be a list of two strings to be printed as if concatenated.
810 If it is a list of two strings, the first is the actual completion
811 alternative, the second serves as annotation.
812 `standard-output' must be a buffer.
813 The actual completion alternatives, as inserted, are given `mouse-face'
814 properties of `highlight'.
815 At the end, this runs the normal hook `completion-setup-hook'.
816 It can find the completion buffer in `standard-output'.
817 The obsolete optional second arg COMMON-SUBSTRING is a string.
818 It is used to put faces, `completions-first-difference' and
819 `completions-common-part' on the completion buffer. The
820 `completions-common-part' face is put on the common substring
821 specified by COMMON-SUBSTRING."
822 (if common-substring
823 (setq completions (completion-hilit-commonality
824 completions (length common-substring))))
825 (if (not (bufferp standard-output))
826 ;; This *never* (ever) happens, so there's no point trying to be clever.
827 (with-temp-buffer
828 (let ((standard-output (current-buffer))
829 (completion-setup-hook nil))
830 (display-completion-list completions))
831 (princ (buffer-string)))
832
833 (with-current-buffer standard-output
834 (goto-char (point-max))
835 (if (null completions)
836 (insert "There are no possible completions of what you have typed.")
837
838 (insert "Possible completions are:\n")
839 (let ((last (last completions)))
840 ;; Get the base-size from the tail of the list.
841 (set (make-local-variable 'completion-base-size) (or (cdr last) 0))
842 (setcdr last nil)) ;Make completions a properly nil-terminated list.
843 (completion--insert-strings completions))))
844
845 ;; The hilit used to be applied via completion-setup-hook, so there
846 ;; may still be some code that uses completion-common-substring.
847 (let ((completion-common-substring common-substring))
848 (run-hooks 'completion-setup-hook))
849 nil)
850
851 (defun minibuffer-completion-help ()
852 "Display a list of possible completions of the current minibuffer contents."
853 (interactive)
854 (message "Making completion list...")
855 (let* ((string (field-string))
856 (completions (completion-all-completions
857 string
858 minibuffer-completion-table
859 minibuffer-completion-predicate
860 (- (point) (field-beginning)))))
861 (message nil)
862 (if (and completions
863 (or (consp (cdr completions))
864 (not (equal (car completions) string))))
865 (with-output-to-temp-buffer "*Completions*"
866 (let* ((last (last completions))
867 (base-size (cdr last)))
868 ;; Remove the base-size tail because `sort' requires a properly
869 ;; nil-terminated list.
870 (when last (setcdr last nil))
871 (display-completion-list (nconc (sort completions 'string-lessp)
872 base-size))))
873
874 ;; If there are no completions, or if the current input is already the
875 ;; only possible completion, then hide (previous&stale) completions.
876 (let ((window (and (get-buffer "*Completions*")
877 (get-buffer-window "*Completions*" 0))))
878 (when (and (window-live-p window) (window-dedicated-p window))
879 (condition-case ()
880 (delete-window window)
881 (error (iconify-frame (window-frame window))))))
882 (ding)
883 (minibuffer-message
884 (if completions "Sole completion" "No completions")))
885 nil))
886
887 (defun exit-minibuffer ()
888 "Terminate this minibuffer argument."
889 (interactive)
890 ;; If the command that uses this has made modifications in the minibuffer,
891 ;; we don't want them to cause deactivation of the mark in the original
892 ;; buffer.
893 ;; A better solution would be to make deactivate-mark buffer-local
894 ;; (or to turn it into a list of buffers, ...), but in the mean time,
895 ;; this should do the trick in most cases.
896 (setq deactivate-mark nil)
897 (throw 'exit nil))
898
899 (defun self-insert-and-exit ()
900 "Terminate minibuffer input."
901 (interactive)
902 (if (characterp last-command-char)
903 (call-interactively 'self-insert-command)
904 (ding))
905 (exit-minibuffer))
906
907 ;;; Key bindings.
908
909 (let ((map minibuffer-local-map))
910 (define-key map "\C-g" 'abort-recursive-edit)
911 (define-key map "\r" 'exit-minibuffer)
912 (define-key map "\n" 'exit-minibuffer))
913
914 (let ((map minibuffer-local-completion-map))
915 (define-key map "\t" 'minibuffer-complete)
916 ;; M-TAB is already abused for many other purposes, so we should find
917 ;; another binding for it.
918 ;; (define-key map "\e\t" 'minibuffer-force-complete)
919 (define-key map " " 'minibuffer-complete-word)
920 (define-key map "?" 'minibuffer-completion-help))
921
922 (let ((map minibuffer-local-must-match-map))
923 (define-key map "\r" 'minibuffer-complete-and-exit)
924 (define-key map "\n" 'minibuffer-complete-and-exit))
925
926 (let ((map minibuffer-local-filename-completion-map))
927 (define-key map " " nil))
928 (let ((map minibuffer-local-must-match-filename-map))
929 (define-key map " " nil))
930
931 (let ((map minibuffer-local-ns-map))
932 (define-key map " " 'exit-minibuffer)
933 (define-key map "\t" 'exit-minibuffer)
934 (define-key map "?" 'self-insert-and-exit))
935
936 ;;; Completion tables.
937
938 (defun minibuffer--double-dollars (str)
939 (replace-regexp-in-string "\\$" "$$" str))
940
941 (defun completion--make-envvar-table ()
942 (mapcar (lambda (enventry)
943 (substring enventry 0 (string-match "=" enventry)))
944 process-environment))
945
946 (defconst completion--embedded-envvar-re
947 (concat "\\(?:^\\|[^$]\\(?:\\$\\$\\)*\\)"
948 "$\\([[:alnum:]_]*\\|{\\([^}]*\\)\\)\\'"))
949
950 (defun completion--embedded-envvar-table (string pred action)
951 (if (eq (car-safe action) 'boundaries)
952 ;; Compute the boundaries of the subfield to which this
953 ;; completion applies.
954 (let ((suffix (cdr action)))
955 (if (string-match completion--embedded-envvar-re string)
956 (list* 'boundaries
957 (or (match-beginning 2) (match-beginning 1))
958 (when (string-match "[^[:alnum:]_]" suffix)
959 (match-beginning 0)))))
960 (when (string-match completion--embedded-envvar-re string)
961 (let* ((beg (or (match-beginning 2) (match-beginning 1)))
962 (table (completion--make-envvar-table))
963 (prefix (substring string 0 beg)))
964 (if (eq (aref string (1- beg)) ?{)
965 (setq table (apply-partially 'completion-table-with-terminator
966 "}" table)))
967 (completion-table-with-context
968 prefix table (substring string beg) pred action)))))
969
970 (defun completion--file-name-table (string pred action)
971 "Internal subroutine for `read-file-name'. Do not call this."
972 (cond
973 ((and (zerop (length string)) (eq 'lambda action))
974 nil) ; FIXME: why?
975 ((eq (car-safe action) 'boundaries)
976 ;; FIXME: Actually, this is not always right in the presence of
977 ;; envvars, but there's not much we can do, I think.
978 (let ((start (length (file-name-directory string)))
979 (end (string-match "/" (cdr action))))
980 (list* 'boundaries start end)))
981
982 (t
983 (let* ((dir (if (stringp pred)
984 ;; It used to be that `pred' was abused to pass `dir'
985 ;; as an argument.
986 (prog1 (expand-file-name pred) (setq pred nil))
987 default-directory))
988 (str (condition-case nil
989 (substitute-in-file-name string)
990 (error string)))
991 (name (file-name-nondirectory str))
992 (specdir (file-name-directory str))
993 (realdir (if specdir (expand-file-name specdir dir)
994 (file-name-as-directory dir))))
995
996 (cond
997 ((null action)
998 (let ((comp (file-name-completion name realdir
999 read-file-name-predicate)))
1000 (if (stringp comp)
1001 ;; Requote the $s before returning the completion.
1002 (minibuffer--double-dollars (concat specdir comp))
1003 ;; Requote the $s before checking for changes.
1004 (setq str (minibuffer--double-dollars str))
1005 (if (string-equal string str)
1006 comp
1007 ;; If there's no real completion, but substitute-in-file-name
1008 ;; changed the string, then return the new string.
1009 str))))
1010
1011 ((eq action t)
1012 (let ((all (file-name-all-completions name realdir))
1013 ;; FIXME: Actually, this is not always right in the presence
1014 ;; of envvars, but there's not much we can do, I think.
1015 (base-size (length (file-name-directory string))))
1016
1017 ;; Check the predicate, if necessary.
1018 (unless (memq read-file-name-predicate '(nil file-exists-p))
1019 (let ((comp ())
1020 (pred
1021 (if (eq read-file-name-predicate 'file-directory-p)
1022 ;; Brute-force speed up for directory checking:
1023 ;; Discard strings which don't end in a slash.
1024 (lambda (s)
1025 (let ((len (length s)))
1026 (and (> len 0) (eq (aref s (1- len)) ?/))))
1027 ;; Must do it the hard (and slow) way.
1028 read-file-name-predicate)))
1029 (let ((default-directory realdir))
1030 (dolist (tem all)
1031 (if (funcall pred tem) (push tem comp))))
1032 (setq all (nreverse comp))))
1033
1034 (if (and completion-all-completions-with-base-size (consp all))
1035 ;; Add base-size, but only if the list is non-empty.
1036 (nconc all base-size)
1037 all)))
1038
1039 (t
1040 ;; Only other case actually used is ACTION = lambda.
1041 (let ((default-directory dir))
1042 (funcall (or read-file-name-predicate 'file-exists-p) str))))))))
1043
1044 (defalias 'read-file-name-internal
1045 (completion-table-in-turn 'completion--embedded-envvar-table
1046 'completion--file-name-table)
1047 "Internal subroutine for `read-file-name'. Do not call this.")
1048
1049 (defvar read-file-name-function nil
1050 "If this is non-nil, `read-file-name' does its work by calling this function.")
1051
1052 (defvar read-file-name-predicate nil
1053 "Current predicate used by `read-file-name-internal'.")
1054
1055 (defcustom read-file-name-completion-ignore-case
1056 (if (memq system-type '(ms-dos windows-nt darwin macos vax-vms axp-vms))
1057 t nil)
1058 "Non-nil means when reading a file name completion ignores case."
1059 :group 'minibuffer
1060 :type 'boolean
1061 :version "22.1")
1062
1063 (defcustom insert-default-directory t
1064 "Non-nil means when reading a filename start with default dir in minibuffer.
1065
1066 When the initial minibuffer contents show a name of a file or a directory,
1067 typing RETURN without editing the initial contents is equivalent to typing
1068 the default file name.
1069
1070 If this variable is non-nil, the minibuffer contents are always
1071 initially non-empty, and typing RETURN without editing will fetch the
1072 default name, if one is provided. Note however that this default name
1073 is not necessarily the same as initial contents inserted in the minibuffer,
1074 if the initial contents is just the default directory.
1075
1076 If this variable is nil, the minibuffer often starts out empty. In
1077 that case you may have to explicitly fetch the next history element to
1078 request the default name; typing RETURN without editing will leave
1079 the minibuffer empty.
1080
1081 For some commands, exiting with an empty minibuffer has a special meaning,
1082 such as making the current buffer visit no file in the case of
1083 `set-visited-file-name'."
1084 :group 'minibuffer
1085 :type 'boolean)
1086
1087 ;; Not always defined, but only called if next-read-file-uses-dialog-p says so.
1088 (declare-function x-file-dialog "xfns.c"
1089 (prompt dir &optional default-filename mustmatch only-dir-p))
1090
1091 (defun read-file-name (prompt &optional dir default-filename mustmatch initial predicate)
1092 "Read file name, prompting with PROMPT and completing in directory DIR.
1093 Value is not expanded---you must call `expand-file-name' yourself.
1094 Default name to DEFAULT-FILENAME if user exits the minibuffer with
1095 the same non-empty string that was inserted by this function.
1096 (If DEFAULT-FILENAME is omitted, the visited file name is used,
1097 except that if INITIAL is specified, that combined with DIR is used.)
1098 If the user exits with an empty minibuffer, this function returns
1099 an empty string. (This can only happen if the user erased the
1100 pre-inserted contents or if `insert-default-directory' is nil.)
1101 Fourth arg MUSTMATCH non-nil means require existing file's name.
1102 Non-nil and non-t means also require confirmation after completion.
1103 Fifth arg INITIAL specifies text to start with.
1104 If optional sixth arg PREDICATE is non-nil, possible completions and
1105 the resulting file name must satisfy (funcall PREDICATE NAME).
1106 DIR should be an absolute directory name. It defaults to the value of
1107 `default-directory'.
1108
1109 If this command was invoked with the mouse, use a file dialog box if
1110 `use-dialog-box' is non-nil, and the window system or X toolkit in use
1111 provides a file dialog box.
1112
1113 See also `read-file-name-completion-ignore-case'
1114 and `read-file-name-function'."
1115 (unless dir (setq dir default-directory))
1116 (unless (file-name-absolute-p dir) (setq dir (expand-file-name dir)))
1117 (unless default-filename
1118 (setq default-filename (if initial (expand-file-name initial dir)
1119 buffer-file-name)))
1120 ;; If dir starts with user's homedir, change that to ~.
1121 (setq dir (abbreviate-file-name dir))
1122 ;; Likewise for default-filename.
1123 (if default-filename
1124 (setq default-filename (abbreviate-file-name default-filename)))
1125 (let ((insdef (cond
1126 ((and insert-default-directory (stringp dir))
1127 (if initial
1128 (cons (minibuffer--double-dollars (concat dir initial))
1129 (length (minibuffer--double-dollars dir)))
1130 (minibuffer--double-dollars dir)))
1131 (initial (cons (minibuffer--double-dollars initial) 0)))))
1132
1133 (if read-file-name-function
1134 (funcall read-file-name-function
1135 prompt dir default-filename mustmatch initial predicate)
1136 (let ((completion-ignore-case read-file-name-completion-ignore-case)
1137 (minibuffer-completing-file-name t)
1138 (read-file-name-predicate (or predicate 'file-exists-p))
1139 (add-to-history nil))
1140
1141 (let* ((val
1142 (if (not (next-read-file-uses-dialog-p))
1143 ;; We used to pass `dir' to `read-file-name-internal' by
1144 ;; abusing the `predicate' argument. It's better to
1145 ;; just use `default-directory', but in order to avoid
1146 ;; changing `default-directory' in the current buffer,
1147 ;; we don't let-bind it.
1148 (lexical-let ((dir (file-name-as-directory
1149 (expand-file-name dir))))
1150 (minibuffer-with-setup-hook
1151 (lambda () (setq default-directory dir))
1152 (completing-read prompt 'read-file-name-internal
1153 nil mustmatch insdef 'file-name-history
1154 default-filename)))
1155 ;; If DIR contains a file name, split it.
1156 (let ((file (file-name-nondirectory dir)))
1157 (when (and default-filename (not (zerop (length file))))
1158 (setq default-filename file)
1159 (setq dir (file-name-directory dir)))
1160 (if default-filename
1161 (setq default-filename
1162 (expand-file-name default-filename dir)))
1163 (setq add-to-history t)
1164 (x-file-dialog prompt dir default-filename mustmatch
1165 (eq predicate 'file-directory-p)))))
1166
1167 (replace-in-history (eq (car-safe file-name-history) val)))
1168 ;; If completing-read returned the inserted default string itself
1169 ;; (rather than a new string with the same contents),
1170 ;; it has to mean that the user typed RET with the minibuffer empty.
1171 ;; In that case, we really want to return ""
1172 ;; so that commands such as set-visited-file-name can distinguish.
1173 (when (eq val default-filename)
1174 ;; In this case, completing-read has not added an element
1175 ;; to the history. Maybe we should.
1176 (if (not replace-in-history)
1177 (setq add-to-history t))
1178 (setq val ""))
1179 (unless val (error "No file name specified"))
1180
1181 (if (and default-filename
1182 (string-equal val (if (consp insdef) (car insdef) insdef)))
1183 (setq val default-filename))
1184 (setq val (substitute-in-file-name val))
1185
1186 (if replace-in-history
1187 ;; Replace what Fcompleting_read added to the history
1188 ;; with what we will actually return.
1189 (let ((val1 (minibuffer--double-dollars val)))
1190 (if history-delete-duplicates
1191 (setcdr file-name-history
1192 (delete val1 (cdr file-name-history))))
1193 (setcar file-name-history val1))
1194 (if add-to-history
1195 ;; Add the value to the history--but not if it matches
1196 ;; the last value already there.
1197 (let ((val1 (minibuffer--double-dollars val)))
1198 (unless (and (consp file-name-history)
1199 (equal (car file-name-history) val1))
1200 (setq file-name-history
1201 (cons val1
1202 (if history-delete-duplicates
1203 (delete val1 file-name-history)
1204 file-name-history)))))))
1205 val)))))
1206
1207 (defun internal-complete-buffer-except (&optional buffer)
1208 "Perform completion on all buffers excluding BUFFER.
1209 Like `internal-complete-buffer', but removes BUFFER from the completion list."
1210 (lexical-let ((except (if (stringp buffer) buffer (buffer-name buffer))))
1211 (apply-partially 'completion-table-with-predicate
1212 'internal-complete-buffer
1213 (lambda (name)
1214 (not (equal (if (consp name) (car name) name) except)))
1215 nil)))
1216
1217 ;;; Old-style completion, used in Emacs-21.
1218
1219 (defun completion-emacs21-try-completion (string table pred point)
1220 (let ((completion (try-completion string table pred)))
1221 (if (stringp completion)
1222 (cons completion (length completion))
1223 completion)))
1224
1225 (defun completion-emacs21-all-completions (string table pred point)
1226 (completion-hilit-commonality
1227 (all-completions string table pred t)
1228 (length string)))
1229
1230 ;;; Basic completion, used in Emacs-22.
1231
1232 (defun completion-emacs22-try-completion (string table pred point)
1233 (let ((suffix (substring string point))
1234 (completion (try-completion (substring string 0 point) table pred)))
1235 (if (not (stringp completion))
1236 completion
1237 ;; Merge a trailing / in completion with a / after point.
1238 ;; We used to only do it for word completion, but it seems to make
1239 ;; sense for all completions.
1240 ;; Actually, claiming this feature was part of Emacs-22 completion
1241 ;; is pushing it a bit: it was only done in minibuffer-completion-word,
1242 ;; which was (by default) not bound during file completion, where such
1243 ;; slashes are most likely to occur.
1244 (if (and (not (zerop (length completion)))
1245 (eq ?/ (aref completion (1- (length completion))))
1246 (not (zerop (length suffix)))
1247 (eq ?/ (aref suffix 0)))
1248 ;; This leaves point after the / .
1249 (setq suffix (substring suffix 1)))
1250 (cons (concat completion suffix) (length completion)))))
1251
1252 (defun completion-emacs22-all-completions (string table pred point)
1253 (completion-hilit-commonality
1254 (all-completions (substring string 0 point) table pred t)
1255 point))
1256
1257 (defun completion-basic-try-completion (string table pred point)
1258 (let ((suffix (substring string point))
1259 (completion (try-completion (substring string 0 point) table pred)))
1260 (if (not (stringp completion))
1261 completion
1262 ;; Merge end of completion with beginning of suffix.
1263 ;; Simple generalization of the "merge trailing /" done in Emacs-22.
1264 (when (and (not (zerop (length suffix)))
1265 (string-match "\\(.+\\)\n\\1" (concat completion "\n" suffix)
1266 ;; Make sure we don't compress things to less
1267 ;; than we started with.
1268 point)
1269 ;; Just make sure we didn't match some other \n.
1270 (eq (match-end 1) (length completion)))
1271 (setq suffix (substring suffix (- (match-end 1) (match-beginning 1)))))
1272
1273 (cons (concat completion suffix) (length completion)))))
1274
1275 (defalias 'completion-basic-all-completions 'completion-emacs22-all-completions)
1276
1277 ;;; Partial-completion-mode style completion.
1278
1279 ;; BUGS:
1280
1281 ;; - "minibuffer-s- TAB" with minibuffer-selected-window ends up with
1282 ;; "minibuffer--s-" which matches other options.
1283
1284 (defvar completion-pcm--delim-wild-regex nil)
1285
1286 (defun completion-pcm--prepare-delim-re (delims)
1287 (setq completion-pcm--delim-wild-regex (concat "[" delims "*]")))
1288
1289 (defcustom completion-pcm-word-delimiters "-_. "
1290 "A string of characters treated as word delimiters for completion.
1291 Some arcane rules:
1292 If `]' is in this string, it must come first.
1293 If `^' is in this string, it must not come first.
1294 If `-' is in this string, it must come first or right after `]'.
1295 In other words, if S is this string, then `[S]' must be a valid Emacs regular
1296 expression (not containing character ranges like `a-z')."
1297 :set (lambda (symbol value)
1298 (set-default symbol value)
1299 ;; Refresh other vars.
1300 (completion-pcm--prepare-delim-re value))
1301 :initialize 'custom-initialize-reset
1302 :group 'minibuffer
1303 :type 'string)
1304
1305 (defun completion-pcm--pattern-trivial-p (pattern)
1306 (and (stringp (car pattern)) (null (cdr pattern))))
1307
1308 (defun completion-pcm--string->pattern (string &optional point)
1309 "Split STRING into a pattern.
1310 A pattern is a list where each element is either a string
1311 or a symbol chosen among `any', `star', `point'."
1312 (if (and point (< point (length string)))
1313 (let ((prefix (substring string 0 point))
1314 (suffix (substring string point)))
1315 (append (completion-pcm--string->pattern prefix)
1316 '(point)
1317 (completion-pcm--string->pattern suffix)))
1318 (let ((pattern nil)
1319 (p 0)
1320 (p0 0))
1321
1322 (while (setq p (string-match completion-pcm--delim-wild-regex string p))
1323 (push (substring string p0 p) pattern)
1324 (if (eq (aref string p) ?*)
1325 (progn
1326 (push 'star pattern)
1327 (setq p0 (1+ p)))
1328 (push 'any pattern)
1329 (setq p0 p))
1330 (incf p))
1331
1332 ;; An empty string might be erroneously added at the beginning.
1333 ;; It should be avoided properly, but it's so easy to remove it here.
1334 (delete "" (nreverse (cons (substring string p0) pattern))))))
1335
1336 (defun completion-pcm--pattern->regex (pattern &optional group)
1337 (let ((re
1338 (concat "\\`"
1339 (mapconcat
1340 (lambda (x)
1341 (case x
1342 ((star any point)
1343 (if (if (consp group) (memq x group) group)
1344 "\\(.*?\\)" ".*?"))
1345 (t (regexp-quote x))))
1346 pattern
1347 ""))))
1348 ;; Avoid pathological backtracking.
1349 (while (string-match "\\.\\*\\?\\(?:\\\\[()]\\)*\\(\\.\\*\\?\\)" re)
1350 (setq re (replace-match "" t t re 1)))
1351 re))
1352
1353 (defun completion-pcm--all-completions (prefix pattern table pred)
1354 "Find all completions for PATTERN in TABLE obeying PRED.
1355 PATTERN is as returned by `completion-pcm--string->pattern'."
1356 ;; Find an initial list of possible completions.
1357 (if (completion-pcm--pattern-trivial-p pattern)
1358
1359 ;; Minibuffer contains no delimiters -- simple case!
1360 (let* ((all (all-completions (concat prefix (car pattern)) table pred))
1361 (last (last all)))
1362 (if last (setcdr last nil))
1363 all)
1364
1365 ;; Use all-completions to do an initial cull. This is a big win,
1366 ;; since all-completions is written in C!
1367 (let* (;; Convert search pattern to a standard regular expression.
1368 (regex (completion-pcm--pattern->regex pattern))
1369 (completion-regexp-list (cons regex completion-regexp-list))
1370 (compl (all-completions
1371 (concat prefix (if (stringp (car pattern)) (car pattern) ""))
1372 table pred))
1373 (last (last compl)))
1374 (when last
1375 (if (and (numberp (cdr last)) (/= (cdr last) (length prefix)))
1376 (message "Inconsistent base-size returned by completion table %s"
1377 table))
1378 (setcdr last nil))
1379 (if (not (functionp table))
1380 ;; The internal functions already obeyed completion-regexp-list.
1381 compl
1382 (let ((case-fold-search completion-ignore-case)
1383 (poss ()))
1384 (dolist (c compl)
1385 (when (string-match regex c) (push c poss)))
1386 poss)))))
1387
1388 (defun completion-pcm--hilit-commonality (pattern completions)
1389 (when completions
1390 (let* ((re (completion-pcm--pattern->regex pattern '(point)))
1391 (last (last completions))
1392 (base-size (cdr last)))
1393 ;; Remove base-size during mapcar, and add it back later.
1394 (setcdr last nil)
1395 (nconc
1396 (mapcar
1397 (lambda (str)
1398 ;; Don't modify the string itself.
1399 (setq str (copy-sequence str))
1400 (unless (string-match re str)
1401 (error "Internal error: %s does not match %s" re str))
1402 (let ((pos (or (match-beginning 1) (match-end 0))))
1403 (put-text-property 0 pos
1404 'font-lock-face 'completions-common-part
1405 str)
1406 (if (> (length str) pos)
1407 (put-text-property pos (1+ pos)
1408 'font-lock-face 'completions-first-difference
1409 str)))
1410 str)
1411 completions)
1412 base-size))))
1413
1414 (defun completion-pcm--find-all-completions (string table pred point)
1415 (let* ((beforepoint (substring string 0 point))
1416 (afterpoint (substring string point))
1417 (bounds (completion-boundaries beforepoint table pred afterpoint))
1418 (prefix (substring beforepoint 0 (car bounds)))
1419 (suffix (substring afterpoint (cdr bounds)))
1420 firsterror)
1421 (setq string (substring string (car bounds) (+ point (cdr bounds))))
1422 (let* ((relpoint (- point (car bounds)))
1423 (pattern (completion-pcm--string->pattern string relpoint))
1424 (all (condition-case err
1425 (completion-pcm--all-completions prefix pattern table pred)
1426 (error (unless firsterror (setq firsterror err)) nil))))
1427 (when (and (null all)
1428 (> (car bounds) 0)
1429 (null (ignore-errors (try-completion prefix table pred))))
1430 ;; The prefix has no completions at all, so we should try and fix
1431 ;; that first.
1432 (let ((substring (substring prefix 0 -1)))
1433 (destructuring-bind (subpat suball subprefix subsuffix)
1434 (completion-pcm--find-all-completions
1435 substring table pred (length substring))
1436 (let ((sep (aref prefix (1- (length prefix))))
1437 ;; Text that goes between the new submatches and the
1438 ;; completion substring.
1439 (between nil))
1440 ;; Eliminate submatches that don't end with the separator.
1441 (dolist (submatch (prog1 suball (setq suball ())))
1442 (when (eq sep (aref submatch (1- (length submatch))))
1443 (push submatch suball)))
1444 (when suball
1445 ;; Update the boundaries and corresponding pattern.
1446 ;; We assume that all submatches result in the same boundaries
1447 ;; since we wouldn't know how to merge them otherwise anyway.
1448 ;; FIXME: COMPLETE REWRITE!!!
1449 (let* ((newbeforepoint
1450 (concat subprefix (car suball)
1451 (substring string 0 relpoint)))
1452 (leftbound (+ (length subprefix) (length (car suball))))
1453 (newbounds (completion-boundaries
1454 newbeforepoint table pred afterpoint)))
1455 (unless (or (and (eq (cdr bounds) (cdr newbounds))
1456 (eq (car newbounds) leftbound))
1457 ;; Refuse new boundaries if they step over
1458 ;; the submatch.
1459 (< (car newbounds) leftbound))
1460 ;; The new completed prefix does change the boundaries
1461 ;; of the completed substring.
1462 (setq suffix (substring afterpoint (cdr newbounds)))
1463 (setq string
1464 (concat (substring newbeforepoint (car newbounds))
1465 (substring afterpoint 0 (cdr newbounds))))
1466 (setq between (substring newbeforepoint leftbound
1467 (car newbounds)))
1468 (setq pattern (completion-pcm--string->pattern
1469 string
1470 (- (length newbeforepoint)
1471 (car newbounds)))))
1472 (dolist (submatch suball)
1473 (setq all (nconc (mapcar
1474 (lambda (s) (concat submatch between s))
1475 (completion-pcm--all-completions
1476 (concat subprefix submatch between)
1477 pattern table pred))
1478 all)))
1479 ;; FIXME: This can come in handy for try-completion,
1480 ;; but isn't right for all-completions, since it lists
1481 ;; invalid completions.
1482 ;; (unless all
1483 ;; ;; Even though we found expansions in the prefix, none
1484 ;; ;; leads to a valid completion.
1485 ;; ;; Let's keep the expansions, tho.
1486 ;; (dolist (submatch suball)
1487 ;; (push (concat submatch between newsubstring) all)))
1488 ))
1489 (setq pattern (append subpat (list 'any (string sep))
1490 (if between (list between)) pattern))
1491 (setq prefix subprefix)))))
1492 (if (and (null all) firsterror)
1493 (signal (car firsterror) (cdr firsterror))
1494 (list pattern all prefix suffix)))))
1495
1496 (defun completion-pcm-all-completions (string table pred point)
1497 (destructuring-bind (pattern all &optional prefix suffix)
1498 (completion-pcm--find-all-completions string table pred point)
1499 (completion-pcm--hilit-commonality pattern all)))
1500
1501 (defun completion-pcm--merge-completions (strs pattern)
1502 "Extract the commonality in STRS, with the help of PATTERN."
1503 (cond
1504 ((null (cdr strs)) (list (car strs)))
1505 (t
1506 (let ((re (completion-pcm--pattern->regex pattern 'group))
1507 (ccs ())) ;Chopped completions.
1508
1509 ;; First chop each string into the parts corresponding to each
1510 ;; non-constant element of `pattern', using regexp-matching.
1511 (let ((case-fold-search completion-ignore-case))
1512 (dolist (str strs)
1513 (unless (string-match re str)
1514 (error "Internal error: %s doesn't match %s" str re))
1515 (let ((chopped ())
1516 (i 1))
1517 (while (match-beginning i)
1518 (push (match-string i str) chopped)
1519 (setq i (1+ i)))
1520 ;; Add the text corresponding to the implicit trailing `any'.
1521 (push (substring str (match-end 0)) chopped)
1522 (push (nreverse chopped) ccs))))
1523
1524 ;; Then for each of those non-constant elements, extract the
1525 ;; commonality between them.
1526 (let ((res ()))
1527 ;; Make the implicit `any' explicit. We could make it explicit
1528 ;; everywhere, but it would slow down regexp-matching a little bit.
1529 (dolist (elem (append pattern '(any)))
1530 (if (stringp elem)
1531 (push elem res)
1532 (let ((comps ()))
1533 (dolist (cc (prog1 ccs (setq ccs nil)))
1534 (push (car cc) comps)
1535 (push (cdr cc) ccs))
1536 (let* ((prefix (try-completion "" comps))
1537 (unique (or (and (eq prefix t) (setq prefix ""))
1538 (eq t (try-completion prefix comps)))))
1539 (unless (equal prefix "") (push prefix res))
1540 ;; If there's only one completion, `elem' is not useful
1541 ;; any more: it can only match the empty string.
1542 ;; FIXME: in some cases, it may be necessary to turn an
1543 ;; `any' into a `star' because the surrounding context has
1544 ;; changed such that string->pattern wouldn't add an `any'
1545 ;; here any more.
1546 (unless unique (push elem res))))))
1547 ;; We return it in reverse order.
1548 res)))))
1549
1550 (defun completion-pcm--pattern->string (pattern)
1551 (mapconcat (lambda (x) (cond
1552 ((stringp x) x)
1553 ((eq x 'star) "*")
1554 ((eq x 'any) "")
1555 ((eq x 'point) "")))
1556 pattern
1557 ""))
1558
1559 (defun completion-pcm-try-completion (string table pred point)
1560 (destructuring-bind (pattern all prefix suffix)
1561 (completion-pcm--find-all-completions string table pred point)
1562 (when all
1563 (let* ((mergedpat (completion-pcm--merge-completions all pattern))
1564 ;; `mergedpat' is in reverse order. Place new point (by
1565 ;; order of preference) either at the old point, or at
1566 ;; the last place where there's something to choose, or
1567 ;; at the very end.
1568 (pointpat (or (memq 'point mergedpat) (memq 'any mergedpat)
1569 mergedpat))
1570 ;; New pos from the start.
1571 (newpos (length (completion-pcm--pattern->string pointpat)))
1572 ;; Do it afterwards because it changes `pointpat' by sideeffect.
1573 (merged (completion-pcm--pattern->string (nreverse mergedpat))))
1574 (if (and (> (length merged) 0) (> (length suffix) 0)
1575 (eq (aref merged (1- (length merged))) (aref suffix 0)))
1576 (setq suffix (substring suffix 1)))
1577 (cons (concat prefix merged suffix) (+ newpos (length prefix)))))))
1578
1579
1580 (provide 'minibuffer)
1581
1582 ;; arch-tag: ef8a0a15-1080-4790-a754-04017c02f08f
1583 ;;; minibuffer.el ends here