ns-emacs.texi: Update version. (Introduction): Correct menu location for options...
[emacs/old-mirror.git] / lisp / minibuffer.el
blobd33bd5f9836bb0a3447bd64a3908cc772c8d843e
1 ;;; minibuffer.el --- Minibuffer completion functions
3 ;; Copyright (C) 2008 Free Software Foundation, Inc.
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
7 ;; This file is part of GNU Emacs.
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.
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.
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/>.
22 ;;; Commentary:
24 ;; Names with "--" are for functions and variables that are meant to be for
25 ;; internal use only.
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'.
37 ;;; Bugs:
39 ;; - completion-all-sorted-completions list all the completions, whereas
40 ;; it should only lists the ones that `try-completion' would consider.
41 ;; E.g. it should honor completion-ignored-extensions.
42 ;; - choose-completion can't automatically figure out the boundaries
43 ;; corresponding to the displayed completions. `base-size' gives the left
44 ;; boundary, but not the righthand one. So we need to add
45 ;; completion-extra-size (and also completion-no-auto-exit).
47 ;;; Todo:
49 ;; - make lisp-complete-symbol and sym-comp use it.
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 lisp/complete.el obsolete.
55 ;; - Make the `hide-spaces' arg of all-completions obsolete?
57 ;;; Code:
59 (eval-when-compile (require 'cl))
61 (defvar completion-all-completions-with-base-size nil
62 "If non-nil, `all-completions' may return the base-size in the last cdr.
63 The base-size is the length of the prefix that is elided from each
64 element in the returned list of completions. See `completion-base-size'.")
66 ;;; Completion table manipulation
68 ;; New completion-table operation.
69 (defun completion-boundaries (string table pred suffix)
70 "Return the boundaries of the completions returned by TABLE for STRING.
71 STRING is the string on which completion will be performed.
72 SUFFIX is the string after point.
73 The result is of the form (START . END) where START is the position
74 in STRING of the beginning of the completion field and END is the position
75 in SUFFIX of the end of the completion field.
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)))))
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))))))
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)))))
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))))
118 (funcall
119 (cond
120 ((null action) 'try-completion)
121 ((eq action t) 'all-completions)
122 (t 'test-completion))
123 string table pred))))
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.
133 The result of the `completion-table-dynamic' form is a function
134 that can be used as the COLLECTION 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)))))
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.
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))))
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)))))
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)))
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))
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))))))
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))))
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")
264 ;;; Minibuffer completion
266 (defgroup minibuffer nil
267 "Controlling the behavior of the minibuffer."
268 :link '(custom-manual "(emacs)Minibuffer")
269 :group 'environment)
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 ;; A quit during sit-for normally only interrupts the sit-for,
286 ;; but since minibuffer-message is used at the end of a command,
287 ;; at a time when the command has virtually finished already, a C-g
288 ;; should really cause an abort-recursive-edit instead (i.e. as if
289 ;; the C-g had been typed at top-level). Binding inhibit-quit here
290 ;; is an attempt to get that behavior.
291 (inhibit-quit t))
292 (unwind-protect
293 (progn
294 (unless (zerop (length message))
295 ;; The current C cursor code doesn't know to use the overlay's
296 ;; marker's stickiness to figure out whether to place the cursor
297 ;; before or after the string, so let's spoon-feed it the pos.
298 (put-text-property 0 1 'cursor t message))
299 (overlay-put ol 'after-string message)
300 (sit-for (or minibuffer-message-timeout 1000000)))
301 (delete-overlay ol))))
303 (defun minibuffer-completion-contents ()
304 "Return the user input in a minibuffer before point as a string.
305 That is what completion commands operate on."
306 (buffer-substring (field-beginning) (point)))
308 (defun delete-minibuffer-contents ()
309 "Delete all user input in a minibuffer.
310 If the current buffer is not a minibuffer, erase its entire contents."
311 (delete-field))
313 (defcustom completion-auto-help t
314 "Non-nil means automatically provide help for invalid completion input.
315 If the value is t the *Completion* buffer is displayed whenever completion
316 is requested but cannot be done.
317 If the value is `lazy', the *Completions* buffer is only displayed after
318 the second failed attempt to complete."
319 :type '(choice (const nil) (const t) (const lazy))
320 :group 'minibuffer)
322 (defvar completion-styles-alist
323 '((basic completion-basic-try-completion completion-basic-all-completions)
324 (emacs22 completion-emacs22-try-completion completion-emacs22-all-completions)
325 (emacs21 completion-emacs21-try-completion completion-emacs21-all-completions)
326 (partial-completion
327 completion-pcm-try-completion completion-pcm-all-completions))
328 "List of available completion styles.
329 Each element has the form (NAME TRY-COMPLETION ALL-COMPLETIONS)
330 where NAME is the name that should be used in `completion-styles',
331 TRY-COMPLETION is the function that does the completion, and
332 ALL-COMPLETIONS is the function that lists the completions.")
334 (defcustom completion-styles '(basic partial-completion)
335 "List of completion styles to use."
336 :type `(repeat (choice ,@(mapcar (lambda (x) (list 'const (car x)))
337 completion-styles-alist)))
338 :group 'minibuffer
339 :version "23.1")
341 (defun completion-try-completion (string table pred point)
342 "Try to complete STRING using completion table TABLE.
343 Only the elements of table that satisfy predicate PRED are considered.
344 POINT is the position of point within STRING.
345 The return value can be either nil to indicate that there is no completion,
346 t to indicate that STRING is the only possible completion,
347 or a pair (STRING . NEWPOINT) of the completed result string together with
348 a new position for point."
349 ;; The property `completion-styles' indicates that this functional
350 ;; completion-table claims to take care of completion styles itself.
351 ;; [I.e. It will most likely call us back at some point. ]
352 (if (and (symbolp table) (get table 'completion-styles))
353 ;; Extended semantics for functional completion-tables:
354 ;; They accept a 4th argument `point' and when called with action=nil
355 ;; and this 4th argument (a position inside `string'), they should
356 ;; return instead of a string a pair (STRING . NEWPOINT).
357 (funcall table string pred nil point)
358 (completion--some (lambda (style)
359 (funcall (nth 1 (assq style completion-styles-alist))
360 string table pred point))
361 completion-styles)))
363 (defun completion-all-completions (string table pred point)
364 "List the possible completions of STRING in completion table TABLE.
365 Only the elements of table that satisfy predicate PRED are considered.
366 POINT is the position of point within STRING.
367 The return value is a list of completions and may contain the base-size
368 in the last `cdr'."
369 (let ((completion-all-completions-with-base-size t))
370 ;; The property `completion-styles' indicates that this functional
371 ;; completion-table claims to take care of completion styles itself.
372 ;; [I.e. It will most likely call us back at some point. ]
373 (if (and (symbolp table) (get table 'completion-styles))
374 ;; Extended semantics for functional completion-tables:
375 ;; They accept a 4th argument `point' and when called with action=t
376 ;; and this 4th argument (a position inside `string'), they may
377 ;; return BASE-SIZE in the last `cdr'.
378 (funcall table string pred t point)
379 (completion--some (lambda (style)
380 (funcall (nth 2 (assq style completion-styles-alist))
381 string table pred point))
382 completion-styles))))
384 (defun minibuffer--bitset (modified completions exact)
385 (logior (if modified 4 0)
386 (if completions 2 0)
387 (if exact 1 0)))
389 (defun completion--do-completion (&optional try-completion-function)
390 "Do the completion and return a summary of what happened.
391 M = completion was performed, the text was Modified.
392 C = there were available Completions.
393 E = after completion we now have an Exact match.
396 000 0 no possible completion
397 001 1 was already an exact and unique completion
398 010 2 no completion happened
399 011 3 was already an exact completion
400 100 4 ??? impossible
401 101 5 ??? impossible
402 110 6 some completion happened
403 111 7 completed to an exact completion"
404 (let* ((beg (field-beginning))
405 (end (field-end))
406 (string (buffer-substring beg end))
407 (comp (funcall (or try-completion-function
408 'completion-try-completion)
409 string
410 minibuffer-completion-table
411 minibuffer-completion-predicate
412 (- (point) beg))))
413 (cond
414 ((null comp)
415 (ding) (minibuffer-message "No match") (minibuffer--bitset nil nil nil))
416 ((eq t comp) (minibuffer--bitset nil nil t)) ;Exact and unique match.
418 ;; `completed' should be t if some completion was done, which doesn't
419 ;; include simply changing the case of the entered string. However,
420 ;; for appearance, the string is rewritten if the case changes.
421 (let* ((comp-pos (cdr comp))
422 (completion (car comp))
423 (completed (not (eq t (compare-strings completion nil nil
424 string nil nil t))))
425 (unchanged (eq t (compare-strings completion nil nil
426 string nil nil nil))))
427 (unless unchanged
429 ;; Insert in minibuffer the chars we got.
430 (goto-char end)
431 (insert completion)
432 (delete-region beg end))
433 ;; Move point.
434 (goto-char (+ beg comp-pos))
436 (if (not (or unchanged completed))
437 ;; The case of the string changed, but that's all. We're not sure
438 ;; whether this is a unique completion or not, so try again using
439 ;; the real case (this shouldn't recurse again, because the next
440 ;; time try-completion will return either t or the exact string).
441 (completion--do-completion try-completion-function)
443 ;; It did find a match. Do we match some possibility exactly now?
444 (let ((exact (test-completion completion
445 minibuffer-completion-table
446 minibuffer-completion-predicate)))
447 (unless completed
448 ;; Show the completion table, if requested.
449 (cond
450 ((not exact)
451 (if (case completion-auto-help
452 (lazy (eq this-command last-command))
453 (t completion-auto-help))
454 (minibuffer-completion-help)
455 (minibuffer-message "Next char not unique")))
456 ;; If the last exact completion and this one were the same,
457 ;; it means we've already given a "Complete but not unique"
458 ;; message and the user's hit TAB again, so now we give him help.
459 ((eq this-command last-command)
460 (if completion-auto-help (minibuffer-completion-help)))))
462 (minibuffer--bitset completed t exact))))))))
464 (defun minibuffer-complete ()
465 "Complete the minibuffer contents as far as possible.
466 Return nil if there is no valid completion, else t.
467 If no characters can be completed, display a list of possible completions.
468 If you repeat this command after it displayed such a list,
469 scroll the window of possible completions."
470 (interactive)
471 ;; If the previous command was not this,
472 ;; mark the completion buffer obsolete.
473 (unless (eq this-command last-command)
474 (setq minibuffer-scroll-window nil))
476 (let ((window minibuffer-scroll-window))
477 ;; If there's a fresh completion window with a live buffer,
478 ;; and this command is repeated, scroll that window.
479 (if (window-live-p window)
480 (with-current-buffer (window-buffer window)
481 (if (pos-visible-in-window-p (point-max) window)
482 ;; If end is in view, scroll up to the beginning.
483 (set-window-start window (point-min) nil)
484 ;; Else scroll down one screen.
485 (scroll-other-window))
486 nil)
488 (case (completion--do-completion)
489 (#b000 nil)
490 (#b001 (goto-char (field-end))
491 (minibuffer-message "Sole completion")
493 (#b011 (goto-char (field-end))
494 (minibuffer-message "Complete, but not unique")
496 (t t)))))
498 (defvar completion-all-sorted-completions nil)
499 (make-variable-buffer-local 'completion-all-sorted-completions)
501 (defun completion--flush-all-sorted-completions (&rest ignore)
502 (setq completion-all-sorted-completions nil))
504 (defun completion-all-sorted-completions ()
505 (or completion-all-sorted-completions
506 (let* ((start (field-beginning))
507 (end (field-end))
508 (all (completion-all-completions (buffer-substring start end)
509 minibuffer-completion-table
510 minibuffer-completion-predicate
511 (- (point) start)))
512 (last (last all))
513 (base-size (or (cdr last) 0)))
514 (when last
515 (setcdr last nil)
516 ;; Prefer shorter completions.
517 (setq all (sort all (lambda (c1 c2) (< (length c1) (length c2)))))
518 ;; Prefer recently used completions.
519 (let ((hist (symbol-value minibuffer-history-variable)))
520 (setq all (sort all (lambda (c1 c2)
521 (> (length (member c1 hist))
522 (length (member c2 hist)))))))
523 ;; Cache the result. This is not just for speed, but also so that
524 ;; repeated calls to minibuffer-force-complete can cycle through
525 ;; all possibilities.
526 (add-hook 'after-change-functions
527 'completion--flush-all-sorted-completions nil t)
528 (setq completion-all-sorted-completions
529 (nconc all base-size))))))
531 (defun minibuffer-force-complete ()
532 "Complete the minibuffer to an exact match.
533 Repeated uses step through the possible completions."
534 (interactive)
535 ;; FIXME: Need to deal with the extra-size issue here as well.
536 (let* ((start (field-beginning))
537 (end (field-end))
538 (all (completion-all-sorted-completions)))
539 (if (not (consp all))
540 (minibuffer-message (if all "No more completions" "No completions"))
541 (goto-char end)
542 (insert (car all))
543 (delete-region (+ start (cdr (last all))) end)
544 ;; If completing file names, (car all) may be a directory, so we'd now
545 ;; have a new set of possible completions and might want to reset
546 ;; completion-all-sorted-completions to nil, but we prefer not to,
547 ;; so that repeated calls minibuffer-force-complete still cycle
548 ;; through the previous possible completions.
549 (setq completion-all-sorted-completions (cdr all)))))
551 (defun minibuffer-complete-and-exit ()
552 "If the minibuffer contents is a valid completion then exit.
553 Otherwise try to complete it. If completion leads to a valid completion,
554 a repetition of this command will exit.
555 If `minibuffer-completion-confirm' is equal to `confirm', then do not
556 try to complete, but simply ask for confirmation and accept any
557 input if confirmed."
558 (interactive)
559 (let ((beg (field-beginning))
560 (end (field-end)))
561 (cond
562 ;; Allow user to specify null string
563 ((= beg end) (exit-minibuffer))
564 ((test-completion (buffer-substring beg end)
565 minibuffer-completion-table
566 minibuffer-completion-predicate)
567 (when completion-ignore-case
568 ;; Fixup case of the field, if necessary.
569 (let* ((string (buffer-substring beg end))
570 (compl (try-completion
571 string
572 minibuffer-completion-table
573 minibuffer-completion-predicate)))
574 (when (and (stringp compl)
575 ;; If it weren't for this piece of paranoia, I'd replace
576 ;; the whole thing with a call to do-completion.
577 ;; This is important, e.g. when the current minibuffer's
578 ;; content is a directory which only contains a single
579 ;; file, so `try-completion' actually completes to
580 ;; that file.
581 (= (length string) (length compl)))
582 (goto-char end)
583 (insert compl)
584 (delete-region beg end))))
585 (exit-minibuffer))
587 ((eq minibuffer-completion-confirm 'confirm-only)
588 ;; The user is permitted to exit with an input that's rejected
589 ;; by test-completion, but at the condition to confirm her choice.
590 (if (eq last-command this-command)
591 (exit-minibuffer)
592 (minibuffer-message "Confirm")
593 nil))
596 ;; Call do-completion, but ignore errors.
597 (case (condition-case nil
598 (completion--do-completion)
599 (error 1))
600 ((#b001 #b011) (exit-minibuffer))
601 (#b111 (if (not minibuffer-completion-confirm)
602 (exit-minibuffer)
603 (minibuffer-message "Confirm")
604 nil))
605 (t nil))))))
607 (defun completion--try-word-completion (string table predicate point)
608 (let ((comp (completion-try-completion string table predicate point)))
609 (if (not (consp comp))
610 comp
612 ;; If completion finds next char not unique,
613 ;; consider adding a space or a hyphen.
614 (when (= (length string) (length (car comp)))
615 (let ((exts '(" " "-"))
616 (before (substring string 0 point))
617 (after (substring string point))
618 ;; If the user hasn't entered any text yet, then she
619 ;; presumably hits SPC to see the *completions*, but
620 ;; partial-completion will often find a " " or a "-" to match.
621 ;; So disable partial-completion in that situation.
622 (completion-styles
623 (or (and (equal string "")
624 (remove 'partial-completion completion-styles))
625 completion-styles))
626 tem)
627 (while (and exts (not (consp tem)))
628 (setq tem (completion-try-completion
629 (concat before (pop exts) after)
630 table predicate (1+ point))))
631 (if (consp tem) (setq comp tem))))
633 ;; Completing a single word is actually more difficult than completing
634 ;; as much as possible, because we first have to find the "current
635 ;; position" in `completion' in order to find the end of the word
636 ;; we're completing. Normally, `string' is a prefix of `completion',
637 ;; which makes it trivial to find the position, but with fancier
638 ;; completion (plus env-var expansion, ...) `completion' might not
639 ;; look anything like `string' at all.
640 (let* ((comppoint (cdr comp))
641 (completion (car comp))
642 (before (substring string 0 point))
643 (combined (concat before "\n" completion)))
644 ;; Find in completion the longest text that was right before point.
645 (when (string-match "\\(.+\\)\n.*?\\1" combined)
646 (let* ((prefix (match-string 1 before))
647 ;; We used non-greedy match to make `rem' as long as possible.
648 (rem (substring combined (match-end 0)))
649 ;; Find in the remainder of completion the longest text
650 ;; that was right after point.
651 (after (substring string point))
652 (suffix (if (string-match "\\`\\(.+\\).*\n.*\\1"
653 (concat after "\n" rem))
654 (match-string 1 after))))
655 ;; The general idea is to try and guess what text was inserted
656 ;; at point by the completion. Problem is: if we guess wrong,
657 ;; we may end up treating as "added by completion" text that was
658 ;; actually painfully typed by the user. So if we then cut
659 ;; after the first word, we may throw away things the
660 ;; user wrote. So let's try to be as conservative as possible:
661 ;; only cut after the first word, if we're reasonably sure that
662 ;; our guess is correct.
663 ;; Note: a quick survey on emacs-devel seemed to indicate that
664 ;; nobody actually cares about the "word-at-a-time" feature of
665 ;; minibuffer-complete-word, whose real raison-d'être is that it
666 ;; tries to add "-" or " ". One more reason to only cut after
667 ;; the first word, if we're really sure we're right.
668 (when (and (or suffix (zerop (length after)))
669 (string-match (concat
670 ;; Make submatch 1 as small as possible
671 ;; to reduce the risk of cutting
672 ;; valuable text.
673 ".*" (regexp-quote prefix) "\\(.*?\\)"
674 (if suffix (regexp-quote suffix) "\\'"))
675 completion)
676 ;; The new point in `completion' should also be just
677 ;; before the suffix, otherwise something more complex
678 ;; is going on, and we're not sure where we are.
679 (eq (match-end 1) comppoint)
680 ;; (match-beginning 1)..comppoint is now the stretch
681 ;; of text in `completion' that was completed at point.
682 (string-match "\\W" completion (match-beginning 1))
683 ;; Is there really something to cut?
684 (> comppoint (match-end 0)))
685 ;; Cut after the first word.
686 (let ((cutpos (match-end 0)))
687 (setq completion (concat (substring completion 0 cutpos)
688 (substring completion comppoint)))
689 (setq comppoint cutpos)))))
691 (cons completion comppoint)))))
694 (defun minibuffer-complete-word ()
695 "Complete the minibuffer contents at most a single word.
696 After one word is completed as much as possible, a space or hyphen
697 is added, provided that matches some possible completion.
698 Return nil if there is no valid completion, else t."
699 (interactive)
700 (case (completion--do-completion 'completion--try-word-completion)
701 (#b000 nil)
702 (#b001 (goto-char (field-end))
703 (minibuffer-message "Sole completion")
705 (#b011 (goto-char (field-end))
706 (minibuffer-message "Complete, but not unique")
708 (t t)))
710 (defun completion--insert-strings (strings)
711 "Insert a list of STRINGS into the current buffer.
712 Uses columns to keep the listing readable but compact.
713 It also eliminates runs of equal strings."
714 (when (consp strings)
715 (let* ((length (apply 'max
716 (mapcar (lambda (s)
717 (if (consp s)
718 (+ (string-width (car s))
719 (string-width (cadr s)))
720 (string-width s)))
721 strings)))
722 (window (get-buffer-window (current-buffer) 0))
723 (wwidth (if window (1- (window-width window)) 79))
724 (columns (min
725 ;; At least 2 columns; at least 2 spaces between columns.
726 (max 2 (/ wwidth (+ 2 length)))
727 ;; Don't allocate more columns than we can fill.
728 ;; Windows can't show less than 3 lines anyway.
729 (max 1 (/ (length strings) 2))))
730 (colwidth (/ wwidth columns))
731 (column 0)
732 (laststring nil))
733 ;; The insertion should be "sensible" no matter what choices were made
734 ;; for the parameters above.
735 (dolist (str strings)
736 (unless (equal laststring str) ; Remove (consecutive) duplicates.
737 (setq laststring str)
738 (unless (bolp)
739 (insert " \t")
740 (setq column (+ column colwidth))
741 ;; Leave the space unpropertized so that in the case we're
742 ;; already past the goal column, there is still
743 ;; a space displayed.
744 (set-text-properties (- (point) 1) (point)
745 ;; We can't just set tab-width, because
746 ;; completion-setup-function will kill all
747 ;; local variables :-(
748 `(display (space :align-to ,column)))
749 (when (< wwidth (+ (max colwidth
750 (if (consp str)
751 (+ (string-width (car str))
752 (string-width (cadr str)))
753 (string-width str)))
754 column))
755 (delete-char -2) (insert "\n") (setq column 0)))
756 (if (not (consp str))
757 (put-text-property (point) (progn (insert str) (point))
758 'mouse-face 'highlight)
759 (put-text-property (point) (progn (insert (car str)) (point))
760 'mouse-face 'highlight)
761 (put-text-property (point) (progn (insert (cadr str)) (point))
762 'mouse-face nil)))))))
764 (defvar completion-common-substring nil)
765 (make-obsolete-variable 'completion-common-substring nil "23.1")
767 (defvar completion-setup-hook nil
768 "Normal hook run at the end of setting up a completion list buffer.
769 When this hook is run, the current buffer is the one in which the
770 command to display the completion list buffer was run.
771 The completion list buffer is available as the value of `standard-output'.
772 See also `display-completion-list'.")
774 (defface completions-first-difference
775 '((t (:inherit bold)))
776 "Face put on the first uncommon character in completions in *Completions* buffer."
777 :group 'completion)
779 (defface completions-common-part
780 '((t (:inherit default)))
781 "Face put on the common prefix substring in completions in *Completions* buffer.
782 The idea of `completions-common-part' is that you can use it to
783 make the common parts less visible than normal, so that the rest
784 of the differing parts is, by contrast, slightly highlighted."
785 :group 'completion)
787 (defun completion-hilit-commonality (completions prefix-len)
788 (when completions
789 (let* ((last (last completions))
790 (base-size (cdr last))
791 (com-str-len (- prefix-len (or base-size 0))))
792 ;; Remove base-size during mapcar, and add it back later.
793 (setcdr last nil)
794 (nconc
795 (mapcar
796 (lambda (elem)
797 (let ((str
798 ;; Don't modify the string itself, but a copy, since the
799 ;; the string may be read-only or used for other purposes.
800 ;; Furthermore, since `completions' may come from
801 ;; display-completion-list, `elem' may be a list.
802 (if (consp elem)
803 (car (setq elem (cons (copy-sequence (car elem))
804 (cdr elem))))
805 (setq elem (copy-sequence elem)))))
806 (put-text-property 0 com-str-len
807 'font-lock-face 'completions-common-part
808 str)
809 (if (> (length str) com-str-len)
810 (put-text-property com-str-len (1+ com-str-len)
811 'font-lock-face 'completions-first-difference
812 str)))
813 elem)
814 completions)
815 base-size))))
817 (defun display-completion-list (completions &optional common-substring)
818 "Display the list of completions, COMPLETIONS, using `standard-output'.
819 Each element may be just a symbol or string
820 or may be a list of two strings to be printed as if concatenated.
821 If it is a list of two strings, the first is the actual completion
822 alternative, the second serves as annotation.
823 `standard-output' must be a buffer.
824 The actual completion alternatives, as inserted, are given `mouse-face'
825 properties of `highlight'.
826 At the end, this runs the normal hook `completion-setup-hook'.
827 It can find the completion buffer in `standard-output'.
829 The obsolete optional arg COMMON-SUBSTRING, if non-nil, should be a string
830 specifying a common substring for adding the faces
831 `completions-first-difference' and `completions-common-part' to
832 the completions buffer."
833 (if common-substring
834 (setq completions (completion-hilit-commonality
835 completions (length common-substring))))
836 (if (not (bufferp standard-output))
837 ;; This *never* (ever) happens, so there's no point trying to be clever.
838 (with-temp-buffer
839 (let ((standard-output (current-buffer))
840 (completion-setup-hook nil))
841 (display-completion-list completions common-substring))
842 (princ (buffer-string)))
844 (let ((mainbuf (current-buffer)))
845 (with-current-buffer standard-output
846 (goto-char (point-max))
847 (if (null completions)
848 (insert "There are no possible completions of what you have typed.")
849 (insert "Possible completions are:\n")
850 (let ((last (last completions)))
851 ;; Set base-size from the tail of the list.
852 (set (make-local-variable 'completion-base-size)
853 (or (cdr last)
854 (and (minibufferp mainbuf) 0)))
855 (setcdr last nil)) ; Make completions a properly nil-terminated list.
856 (completion--insert-strings completions)))))
858 ;; The hilit used to be applied via completion-setup-hook, so there
859 ;; may still be some code that uses completion-common-substring.
860 (with-no-warnings
861 (let ((completion-common-substring common-substring))
862 (run-hooks 'completion-setup-hook)))
863 nil)
865 (defun minibuffer-completion-help ()
866 "Display a list of possible completions of the current minibuffer contents."
867 (interactive)
868 (message "Making completion list...")
869 (let* ((string (field-string))
870 (completions (completion-all-completions
871 string
872 minibuffer-completion-table
873 minibuffer-completion-predicate
874 (- (point) (field-beginning)))))
875 (message nil)
876 (if (and completions
877 (or (consp (cdr completions))
878 (not (equal (car completions) string))))
879 (with-output-to-temp-buffer "*Completions*"
880 (let* ((last (last completions))
881 (base-size (cdr last)))
882 ;; Remove the base-size tail because `sort' requires a properly
883 ;; nil-terminated list.
884 (when last (setcdr last nil))
885 (display-completion-list (nconc (sort completions 'string-lessp)
886 base-size))))
888 ;; If there are no completions, or if the current input is already the
889 ;; only possible completion, then hide (previous&stale) completions.
890 (let ((window (and (get-buffer "*Completions*")
891 (get-buffer-window "*Completions*" 0))))
892 (when (and (window-live-p window) (window-dedicated-p window))
893 (condition-case ()
894 (delete-window window)
895 (error (iconify-frame (window-frame window))))))
896 (ding)
897 (minibuffer-message
898 (if completions "Sole completion" "No completions")))
899 nil))
901 (defun exit-minibuffer ()
902 "Terminate this minibuffer argument."
903 (interactive)
904 ;; If the command that uses this has made modifications in the minibuffer,
905 ;; we don't want them to cause deactivation of the mark in the original
906 ;; buffer.
907 ;; A better solution would be to make deactivate-mark buffer-local
908 ;; (or to turn it into a list of buffers, ...), but in the mean time,
909 ;; this should do the trick in most cases.
910 (setq deactivate-mark nil)
911 (throw 'exit nil))
913 (defun self-insert-and-exit ()
914 "Terminate minibuffer input."
915 (interactive)
916 (if (characterp last-command-char)
917 (call-interactively 'self-insert-command)
918 (ding))
919 (exit-minibuffer))
921 ;;; Key bindings.
923 (define-obsolete-variable-alias 'minibuffer-local-must-match-filename-map
924 'minibuffer-local-filename-must-match-map "23.1")
926 (let ((map minibuffer-local-map))
927 (define-key map "\C-g" 'abort-recursive-edit)
928 (define-key map "\r" 'exit-minibuffer)
929 (define-key map "\n" 'exit-minibuffer))
931 (let ((map minibuffer-local-completion-map))
932 (define-key map "\t" 'minibuffer-complete)
933 ;; M-TAB is already abused for many other purposes, so we should find
934 ;; another binding for it.
935 ;; (define-key map "\e\t" 'minibuffer-force-complete)
936 (define-key map " " 'minibuffer-complete-word)
937 (define-key map "?" 'minibuffer-completion-help))
939 (let ((map minibuffer-local-must-match-map))
940 (define-key map "\r" 'minibuffer-complete-and-exit)
941 (define-key map "\n" 'minibuffer-complete-and-exit))
943 (let ((map minibuffer-local-filename-completion-map))
944 (define-key map " " nil))
945 (let ((map minibuffer-local-filename-must-match-map))
946 (define-key map " " nil))
948 (let ((map minibuffer-local-ns-map))
949 (define-key map " " 'exit-minibuffer)
950 (define-key map "\t" 'exit-minibuffer)
951 (define-key map "?" 'self-insert-and-exit))
953 ;;; Completion tables.
955 (defun minibuffer--double-dollars (str)
956 (replace-regexp-in-string "\\$" "$$" str))
958 (defun completion--make-envvar-table ()
959 (mapcar (lambda (enventry)
960 (substring enventry 0 (string-match "=" enventry)))
961 process-environment))
963 (defconst completion--embedded-envvar-re
964 (concat "\\(?:^\\|[^$]\\(?:\\$\\$\\)*\\)"
965 "$\\([[:alnum:]_]*\\|{\\([^}]*\\)\\)\\'"))
967 (defun completion--embedded-envvar-table (string pred action)
968 (if (eq (car-safe action) 'boundaries)
969 ;; Compute the boundaries of the subfield to which this
970 ;; completion applies.
971 (let ((suffix (cdr action)))
972 (if (string-match completion--embedded-envvar-re string)
973 (list* 'boundaries
974 (or (match-beginning 2) (match-beginning 1))
975 (when (string-match "[^[:alnum:]_]" suffix)
976 (match-beginning 0)))))
977 (when (string-match completion--embedded-envvar-re string)
978 (let* ((beg (or (match-beginning 2) (match-beginning 1)))
979 (table (completion--make-envvar-table))
980 (prefix (substring string 0 beg)))
981 (if (eq (aref string (1- beg)) ?{)
982 (setq table (apply-partially 'completion-table-with-terminator
983 "}" table)))
984 (completion-table-with-context
985 prefix table (substring string beg) pred action)))))
987 (defun completion--file-name-table (string pred action)
988 "Internal subroutine for `read-file-name'. Do not call this."
989 (cond
990 ((and (zerop (length string)) (eq 'lambda action))
991 nil) ; FIXME: why?
992 ((eq (car-safe action) 'boundaries)
993 ;; FIXME: Actually, this is not always right in the presence of
994 ;; envvars, but there's not much we can do, I think.
995 (let ((start (length (file-name-directory string)))
996 (end (string-match "/" (cdr action))))
997 (list* 'boundaries start end)))
1000 (let* ((dir (if (stringp pred)
1001 ;; It used to be that `pred' was abused to pass `dir'
1002 ;; as an argument.
1003 (prog1 (expand-file-name pred) (setq pred nil))
1004 default-directory))
1005 (str (condition-case nil
1006 (substitute-in-file-name string)
1007 (error string)))
1008 (name (file-name-nondirectory str))
1009 (specdir (file-name-directory str))
1010 (realdir (if specdir (expand-file-name specdir dir)
1011 (file-name-as-directory dir))))
1013 (cond
1014 ((null action)
1015 (let ((comp (file-name-completion name realdir
1016 read-file-name-predicate)))
1017 (if (stringp comp)
1018 ;; Requote the $s before returning the completion.
1019 (minibuffer--double-dollars (concat specdir comp))
1020 ;; Requote the $s before checking for changes.
1021 (setq str (minibuffer--double-dollars str))
1022 (if (string-equal string str)
1023 comp
1024 ;; If there's no real completion, but substitute-in-file-name
1025 ;; changed the string, then return the new string.
1026 str))))
1028 ((eq action t)
1029 (let ((all (file-name-all-completions name realdir))
1030 ;; FIXME: Actually, this is not always right in the presence
1031 ;; of envvars, but there's not much we can do, I think.
1032 (base-size (length (file-name-directory string))))
1034 ;; Check the predicate, if necessary.
1035 (unless (memq read-file-name-predicate '(nil file-exists-p))
1036 (let ((comp ())
1037 (pred
1038 (if (eq read-file-name-predicate 'file-directory-p)
1039 ;; Brute-force speed up for directory checking:
1040 ;; Discard strings which don't end in a slash.
1041 (lambda (s)
1042 (let ((len (length s)))
1043 (and (> len 0) (eq (aref s (1- len)) ?/))))
1044 ;; Must do it the hard (and slow) way.
1045 read-file-name-predicate)))
1046 (let ((default-directory realdir))
1047 (dolist (tem all)
1048 (if (funcall pred tem) (push tem comp))))
1049 (setq all (nreverse comp))))
1051 (if (and completion-all-completions-with-base-size (consp all))
1052 ;; Add base-size, but only if the list is non-empty.
1053 (nconc all base-size)
1054 all)))
1057 ;; Only other case actually used is ACTION = lambda.
1058 (let ((default-directory dir))
1059 (funcall (or read-file-name-predicate 'file-exists-p) str))))))))
1061 (defalias 'read-file-name-internal
1062 (completion-table-in-turn 'completion--embedded-envvar-table
1063 'completion--file-name-table)
1064 "Internal subroutine for `read-file-name'. Do not call this.")
1066 (defvar read-file-name-function nil
1067 "If this is non-nil, `read-file-name' does its work by calling this function.")
1069 (defvar read-file-name-predicate nil
1070 "Current predicate used by `read-file-name-internal'.")
1072 (defcustom read-file-name-completion-ignore-case
1073 (if (memq system-type '(ms-dos windows-nt darwin cygwin))
1074 t nil)
1075 "Non-nil means when reading a file name completion ignores case."
1076 :group 'minibuffer
1077 :type 'boolean
1078 :version "22.1")
1080 (defcustom insert-default-directory t
1081 "Non-nil means when reading a filename start with default dir in minibuffer.
1083 When the initial minibuffer contents show a name of a file or a directory,
1084 typing RETURN without editing the initial contents is equivalent to typing
1085 the default file name.
1087 If this variable is non-nil, the minibuffer contents are always
1088 initially non-empty, and typing RETURN without editing will fetch the
1089 default name, if one is provided. Note however that this default name
1090 is not necessarily the same as initial contents inserted in the minibuffer,
1091 if the initial contents is just the default directory.
1093 If this variable is nil, the minibuffer often starts out empty. In
1094 that case you may have to explicitly fetch the next history element to
1095 request the default name; typing RETURN without editing will leave
1096 the minibuffer empty.
1098 For some commands, exiting with an empty minibuffer has a special meaning,
1099 such as making the current buffer visit no file in the case of
1100 `set-visited-file-name'."
1101 :group 'minibuffer
1102 :type 'boolean)
1104 ;; Not always defined, but only called if next-read-file-uses-dialog-p says so.
1105 (declare-function x-file-dialog "xfns.c"
1106 (prompt dir &optional default-filename mustmatch only-dir-p))
1108 (defun read-file-name (prompt &optional dir default-filename mustmatch initial predicate)
1109 "Read file name, prompting with PROMPT and completing in directory DIR.
1110 Value is not expanded---you must call `expand-file-name' yourself.
1111 Default name to DEFAULT-FILENAME if user exits the minibuffer with
1112 the same non-empty string that was inserted by this function.
1113 (If DEFAULT-FILENAME is omitted, the visited file name is used,
1114 except that if INITIAL is specified, that combined with DIR is used.)
1115 If the user exits with an empty minibuffer, this function returns
1116 an empty string. (This can only happen if the user erased the
1117 pre-inserted contents or if `insert-default-directory' is nil.)
1118 Fourth arg MUSTMATCH non-nil means require existing file's name.
1119 Non-nil and non-t means also require confirmation after completion.
1120 Fifth arg INITIAL specifies text to start with.
1121 If optional sixth arg PREDICATE is non-nil, possible completions and
1122 the resulting file name must satisfy (funcall PREDICATE NAME).
1123 DIR should be an absolute directory name. It defaults to the value of
1124 `default-directory'.
1126 If this command was invoked with the mouse, use a file dialog box if
1127 `use-dialog-box' is non-nil, and the window system or X toolkit in use
1128 provides a file dialog box.
1130 See also `read-file-name-completion-ignore-case'
1131 and `read-file-name-function'."
1132 (unless dir (setq dir default-directory))
1133 (unless (file-name-absolute-p dir) (setq dir (expand-file-name dir)))
1134 (unless default-filename
1135 (setq default-filename (if initial (expand-file-name initial dir)
1136 buffer-file-name)))
1137 ;; If dir starts with user's homedir, change that to ~.
1138 (setq dir (abbreviate-file-name dir))
1139 ;; Likewise for default-filename.
1140 (if default-filename
1141 (setq default-filename (abbreviate-file-name default-filename)))
1142 (let ((insdef (cond
1143 ((and insert-default-directory (stringp dir))
1144 (if initial
1145 (cons (minibuffer--double-dollars (concat dir initial))
1146 (length (minibuffer--double-dollars dir)))
1147 (minibuffer--double-dollars dir)))
1148 (initial (cons (minibuffer--double-dollars initial) 0)))))
1150 (if read-file-name-function
1151 (funcall read-file-name-function
1152 prompt dir default-filename mustmatch initial predicate)
1153 (let ((completion-ignore-case read-file-name-completion-ignore-case)
1154 (minibuffer-completing-file-name t)
1155 (read-file-name-predicate (or predicate 'file-exists-p))
1156 (add-to-history nil))
1158 (let* ((val
1159 (if (not (next-read-file-uses-dialog-p))
1160 ;; We used to pass `dir' to `read-file-name-internal' by
1161 ;; abusing the `predicate' argument. It's better to
1162 ;; just use `default-directory', but in order to avoid
1163 ;; changing `default-directory' in the current buffer,
1164 ;; we don't let-bind it.
1165 (lexical-let ((dir (file-name-as-directory
1166 (expand-file-name dir))))
1167 (minibuffer-with-setup-hook
1168 (lambda () (setq default-directory dir))
1169 (completing-read prompt 'read-file-name-internal
1170 nil mustmatch insdef 'file-name-history
1171 default-filename)))
1172 ;; If DIR contains a file name, split it.
1173 (let ((file (file-name-nondirectory dir)))
1174 (when (and default-filename (not (zerop (length file))))
1175 (setq default-filename file)
1176 (setq dir (file-name-directory dir)))
1177 (if default-filename
1178 (setq default-filename
1179 (expand-file-name default-filename dir)))
1180 (setq add-to-history t)
1181 (x-file-dialog prompt dir default-filename mustmatch
1182 (eq predicate 'file-directory-p)))))
1184 (replace-in-history (eq (car-safe file-name-history) val)))
1185 ;; If completing-read returned the inserted default string itself
1186 ;; (rather than a new string with the same contents),
1187 ;; it has to mean that the user typed RET with the minibuffer empty.
1188 ;; In that case, we really want to return ""
1189 ;; so that commands such as set-visited-file-name can distinguish.
1190 (when (eq val default-filename)
1191 ;; In this case, completing-read has not added an element
1192 ;; to the history. Maybe we should.
1193 (if (not replace-in-history)
1194 (setq add-to-history t))
1195 (setq val ""))
1196 (unless val (error "No file name specified"))
1198 (if (and default-filename
1199 (string-equal val (if (consp insdef) (car insdef) insdef)))
1200 (setq val default-filename))
1201 (setq val (substitute-in-file-name val))
1203 (if replace-in-history
1204 ;; Replace what Fcompleting_read added to the history
1205 ;; with what we will actually return.
1206 (let ((val1 (minibuffer--double-dollars val)))
1207 (if history-delete-duplicates
1208 (setcdr file-name-history
1209 (delete val1 (cdr file-name-history))))
1210 (setcar file-name-history val1))
1211 (if add-to-history
1212 ;; Add the value to the history--but not if it matches
1213 ;; the last value already there.
1214 (let ((val1 (minibuffer--double-dollars val)))
1215 (unless (and (consp file-name-history)
1216 (equal (car file-name-history) val1))
1217 (setq file-name-history
1218 (cons val1
1219 (if history-delete-duplicates
1220 (delete val1 file-name-history)
1221 file-name-history)))))))
1222 val)))))
1224 (defun internal-complete-buffer-except (&optional buffer)
1225 "Perform completion on all buffers excluding BUFFER.
1226 Like `internal-complete-buffer', but removes BUFFER from the completion list."
1227 (lexical-let ((except (if (stringp buffer) buffer (buffer-name buffer))))
1228 (apply-partially 'completion-table-with-predicate
1229 'internal-complete-buffer
1230 (lambda (name)
1231 (not (equal (if (consp name) (car name) name) except)))
1232 nil)))
1234 ;;; Old-style completion, used in Emacs-21 and Emacs-22.
1236 (defun completion-emacs21-try-completion (string table pred point)
1237 (let ((completion (try-completion string table pred)))
1238 (if (stringp completion)
1239 (cons completion (length completion))
1240 completion)))
1242 (defun completion-emacs21-all-completions (string table pred point)
1243 (completion-hilit-commonality
1244 (all-completions string table pred)
1245 (length string)))
1247 (defun completion-emacs22-try-completion (string table pred point)
1248 (let ((suffix (substring string point))
1249 (completion (try-completion (substring string 0 point) table pred)))
1250 (if (not (stringp completion))
1251 completion
1252 ;; Merge a trailing / in completion with a / after point.
1253 ;; We used to only do it for word completion, but it seems to make
1254 ;; sense for all completions.
1255 ;; Actually, claiming this feature was part of Emacs-22 completion
1256 ;; is pushing it a bit: it was only done in minibuffer-completion-word,
1257 ;; which was (by default) not bound during file completion, where such
1258 ;; slashes are most likely to occur.
1259 (if (and (not (zerop (length completion)))
1260 (eq ?/ (aref completion (1- (length completion))))
1261 (not (zerop (length suffix)))
1262 (eq ?/ (aref suffix 0)))
1263 ;; This leaves point after the / .
1264 (setq suffix (substring suffix 1)))
1265 (cons (concat completion suffix) (length completion)))))
1267 (defun completion-emacs22-all-completions (string table pred point)
1268 (completion-hilit-commonality
1269 (all-completions (substring string 0 point) table pred)
1270 point))
1272 ;;; Basic completion.
1274 (defun completion--merge-suffix (completion point suffix)
1275 "Merge end of COMPLETION with beginning of SUFFIX.
1276 Simple generalization of the \"merge trailing /\" done in Emacs-22.
1277 Return the new suffix."
1278 (if (and (not (zerop (length suffix)))
1279 (string-match "\\(.+\\)\n\\1" (concat completion "\n" suffix)
1280 ;; Make sure we don't compress things to less
1281 ;; than we started with.
1282 point)
1283 ;; Just make sure we didn't match some other \n.
1284 (eq (match-end 1) (length completion)))
1285 (substring suffix (- (match-end 1) (match-beginning 1)))
1286 ;; Nothing to merge.
1287 suffix))
1289 (defun completion-basic-try-completion (string table pred point)
1290 (let* ((beforepoint (substring string 0 point))
1291 (afterpoint (substring string point))
1292 (bounds (completion-boundaries beforepoint table pred afterpoint)))
1293 (if (zerop (cdr bounds))
1294 ;; `try-completion' may return a subtly different result
1295 ;; than `all+merge', so try to use it whenever possible.
1296 (let ((completion (try-completion beforepoint table pred)))
1297 (if (not (stringp completion))
1298 completion
1299 (cons
1300 (concat completion
1301 (completion--merge-suffix completion point afterpoint))
1302 (length completion))))
1303 (let* ((suffix (substring afterpoint (cdr bounds)))
1304 (prefix (substring beforepoint 0 (car bounds)))
1305 (pattern (delete
1306 "" (list (substring beforepoint (car bounds))
1307 'point
1308 (substring afterpoint 0 (cdr bounds)))))
1309 (all (completion-pcm--all-completions prefix pattern table pred)))
1310 (if minibuffer-completing-file-name
1311 (setq all (completion-pcm--filename-try-filter all)))
1312 (completion-pcm--merge-try pattern all prefix suffix)))))
1314 (defun completion-basic-all-completions (string table pred point)
1315 (let* ((beforepoint (substring string 0 point))
1316 (afterpoint (substring string point))
1317 (bounds (completion-boundaries beforepoint table pred afterpoint))
1318 (suffix (substring afterpoint (cdr bounds)))
1319 (prefix (substring beforepoint 0 (car bounds)))
1320 (pattern (delete
1321 "" (list (substring beforepoint (car bounds))
1322 'point
1323 (substring afterpoint 0 (cdr bounds)))))
1324 (all (completion-pcm--all-completions prefix pattern table pred)))
1325 (completion-hilit-commonality
1326 (if (consp all) (nconc all (car bounds)) all)
1327 point)))
1329 ;;; Partial-completion-mode style completion.
1331 (defvar completion-pcm--delim-wild-regex nil)
1333 (defun completion-pcm--prepare-delim-re (delims)
1334 (setq completion-pcm--delim-wild-regex (concat "[" delims "*]")))
1336 (defcustom completion-pcm-word-delimiters "-_. "
1337 "A string of characters treated as word delimiters for completion.
1338 Some arcane rules:
1339 If `]' is in this string, it must come first.
1340 If `^' is in this string, it must not come first.
1341 If `-' is in this string, it must come first or right after `]'.
1342 In other words, if S is this string, then `[S]' must be a valid Emacs regular
1343 expression (not containing character ranges like `a-z')."
1344 :set (lambda (symbol value)
1345 (set-default symbol value)
1346 ;; Refresh other vars.
1347 (completion-pcm--prepare-delim-re value))
1348 :initialize 'custom-initialize-reset
1349 :group 'minibuffer
1350 :type 'string)
1352 (defun completion-pcm--pattern-trivial-p (pattern)
1353 (and (stringp (car pattern)) (null (cdr pattern))))
1355 (defun completion-pcm--string->pattern (string &optional point)
1356 "Split STRING into a pattern.
1357 A pattern is a list where each element is either a string
1358 or a symbol chosen among `any', `star', `point'."
1359 (if (and point (< point (length string)))
1360 (let ((prefix (substring string 0 point))
1361 (suffix (substring string point)))
1362 (append (completion-pcm--string->pattern prefix)
1363 '(point)
1364 (completion-pcm--string->pattern suffix)))
1365 (let ((pattern nil)
1366 (p 0)
1367 (p0 0))
1369 (while (setq p (string-match completion-pcm--delim-wild-regex string p))
1370 (push (substring string p0 p) pattern)
1371 (if (eq (aref string p) ?*)
1372 (progn
1373 (push 'star pattern)
1374 (setq p0 (1+ p)))
1375 (push 'any pattern)
1376 (setq p0 p))
1377 (incf p))
1379 ;; An empty string might be erroneously added at the beginning.
1380 ;; It should be avoided properly, but it's so easy to remove it here.
1381 (delete "" (nreverse (cons (substring string p0) pattern))))))
1383 (defun completion-pcm--pattern->regex (pattern &optional group)
1384 (let ((re
1385 (concat "\\`"
1386 (mapconcat
1387 (lambda (x)
1388 (case x
1389 ((star any point)
1390 (if (if (consp group) (memq x group) group)
1391 "\\(.*?\\)" ".*?"))
1392 (t (regexp-quote x))))
1393 pattern
1394 ""))))
1395 ;; Avoid pathological backtracking.
1396 (while (string-match "\\.\\*\\?\\(?:\\\\[()]\\)*\\(\\.\\*\\?\\)" re)
1397 (setq re (replace-match "" t t re 1)))
1398 re))
1400 (defun completion-pcm--all-completions (prefix pattern table pred)
1401 "Find all completions for PATTERN in TABLE obeying PRED.
1402 PATTERN is as returned by `completion-pcm--string->pattern'."
1403 ;; Find an initial list of possible completions.
1404 (if (completion-pcm--pattern-trivial-p pattern)
1406 ;; Minibuffer contains no delimiters -- simple case!
1407 (let* ((all (all-completions (concat prefix (car pattern)) table pred))
1408 (last (last all)))
1409 (if last (setcdr last nil))
1410 all)
1412 ;; Use all-completions to do an initial cull. This is a big win,
1413 ;; since all-completions is written in C!
1414 (let* (;; Convert search pattern to a standard regular expression.
1415 (regex (completion-pcm--pattern->regex pattern))
1416 (completion-regexp-list (cons regex completion-regexp-list))
1417 (compl (all-completions
1418 (concat prefix (if (stringp (car pattern)) (car pattern) ""))
1419 table pred))
1420 (last (last compl)))
1421 (when last
1422 (if (and (numberp (cdr last)) (/= (cdr last) (length prefix)))
1423 (message "Inconsistent base-size returned by completion table %s"
1424 table))
1425 (setcdr last nil))
1426 (if (not (functionp table))
1427 ;; The internal functions already obeyed completion-regexp-list.
1428 compl
1429 (let ((case-fold-search completion-ignore-case)
1430 (poss ()))
1431 (dolist (c compl)
1432 (when (string-match regex c) (push c poss)))
1433 poss)))))
1435 (defun completion-pcm--hilit-commonality (pattern completions)
1436 (when completions
1437 (let* ((re (completion-pcm--pattern->regex pattern '(point)))
1438 (last (last completions))
1439 (base-size (cdr last)))
1440 ;; Remove base-size during mapcar, and add it back later.
1441 (setcdr last nil)
1442 (nconc
1443 (mapcar
1444 (lambda (str)
1445 ;; Don't modify the string itself.
1446 (setq str (copy-sequence str))
1447 (unless (string-match re str)
1448 (error "Internal error: %s does not match %s" re str))
1449 (let ((pos (or (match-beginning 1) (match-end 0))))
1450 (put-text-property 0 pos
1451 'font-lock-face 'completions-common-part
1452 str)
1453 (if (> (length str) pos)
1454 (put-text-property pos (1+ pos)
1455 'font-lock-face 'completions-first-difference
1456 str)))
1457 str)
1458 completions)
1459 base-size))))
1461 (defun completion-pcm--find-all-completions (string table pred point
1462 &optional filter)
1463 "Find all completions for STRING at POINT in TABLE, satisfying PRED.
1464 POINT is a position inside STRING.
1465 FILTER is a function applied to the return value, that can be used, e.g. to
1466 filter out additional entries (because TABLE migth not obey PRED)."
1467 (unless filter (setq filter 'identity))
1468 (let* ((beforepoint (substring string 0 point))
1469 (afterpoint (substring string point))
1470 (bounds (completion-boundaries beforepoint table pred afterpoint))
1471 (prefix (substring beforepoint 0 (car bounds)))
1472 (suffix (substring afterpoint (cdr bounds)))
1473 firsterror)
1474 (setq string (substring string (car bounds) (+ point (cdr bounds))))
1475 (let* ((relpoint (- point (car bounds)))
1476 (pattern (completion-pcm--string->pattern string relpoint))
1477 (all (condition-case err
1478 (funcall filter
1479 (completion-pcm--all-completions
1480 prefix pattern table pred))
1481 (error (unless firsterror (setq firsterror err)) nil))))
1482 (when (and (null all)
1483 (> (car bounds) 0)
1484 (null (ignore-errors (try-completion prefix table pred))))
1485 ;; The prefix has no completions at all, so we should try and fix
1486 ;; that first.
1487 (let ((substring (substring prefix 0 -1)))
1488 (destructuring-bind (subpat suball subprefix subsuffix)
1489 (completion-pcm--find-all-completions
1490 substring table pred (length substring) filter)
1491 (let ((sep (aref prefix (1- (length prefix))))
1492 ;; Text that goes between the new submatches and the
1493 ;; completion substring.
1494 (between nil))
1495 ;; Eliminate submatches that don't end with the separator.
1496 (dolist (submatch (prog1 suball (setq suball ())))
1497 (when (eq sep (aref submatch (1- (length submatch))))
1498 (push submatch suball)))
1499 (when suball
1500 ;; Update the boundaries and corresponding pattern.
1501 ;; We assume that all submatches result in the same boundaries
1502 ;; since we wouldn't know how to merge them otherwise anyway.
1503 ;; FIXME: COMPLETE REWRITE!!!
1504 (let* ((newbeforepoint
1505 (concat subprefix (car suball)
1506 (substring string 0 relpoint)))
1507 (leftbound (+ (length subprefix) (length (car suball))))
1508 (newbounds (completion-boundaries
1509 newbeforepoint table pred afterpoint)))
1510 (unless (or (and (eq (cdr bounds) (cdr newbounds))
1511 (eq (car newbounds) leftbound))
1512 ;; Refuse new boundaries if they step over
1513 ;; the submatch.
1514 (< (car newbounds) leftbound))
1515 ;; The new completed prefix does change the boundaries
1516 ;; of the completed substring.
1517 (setq suffix (substring afterpoint (cdr newbounds)))
1518 (setq string
1519 (concat (substring newbeforepoint (car newbounds))
1520 (substring afterpoint 0 (cdr newbounds))))
1521 (setq between (substring newbeforepoint leftbound
1522 (car newbounds)))
1523 (setq pattern (completion-pcm--string->pattern
1524 string
1525 (- (length newbeforepoint)
1526 (car newbounds)))))
1527 (dolist (submatch suball)
1528 (setq all (nconc (mapcar
1529 (lambda (s) (concat submatch between s))
1530 (funcall filter
1531 (completion-pcm--all-completions
1532 (concat subprefix submatch between)
1533 pattern table pred)))
1534 all)))
1535 ;; FIXME: This can come in handy for try-completion,
1536 ;; but isn't right for all-completions, since it lists
1537 ;; invalid completions.
1538 ;; (unless all
1539 ;; ;; Even though we found expansions in the prefix, none
1540 ;; ;; leads to a valid completion.
1541 ;; ;; Let's keep the expansions, tho.
1542 ;; (dolist (submatch suball)
1543 ;; (push (concat submatch between newsubstring) all)))
1545 (setq pattern (append subpat (list 'any (string sep))
1546 (if between (list between)) pattern))
1547 (setq prefix subprefix)))))
1548 (if (and (null all) firsterror)
1549 (signal (car firsterror) (cdr firsterror))
1550 (list pattern all prefix suffix)))))
1552 (defun completion-pcm-all-completions (string table pred point)
1553 (destructuring-bind (pattern all &optional prefix suffix)
1554 (completion-pcm--find-all-completions string table pred point)
1555 (when all
1556 (nconc (completion-pcm--hilit-commonality pattern all)
1557 (length prefix)))))
1559 (defun completion-pcm--merge-completions (strs pattern)
1560 "Extract the commonality in STRS, with the help of PATTERN."
1561 (cond
1562 ((null (cdr strs)) (list (car strs)))
1564 (let ((re (completion-pcm--pattern->regex pattern 'group))
1565 (ccs ())) ;Chopped completions.
1567 ;; First chop each string into the parts corresponding to each
1568 ;; non-constant element of `pattern', using regexp-matching.
1569 (let ((case-fold-search completion-ignore-case))
1570 (dolist (str strs)
1571 (unless (string-match re str)
1572 (error "Internal error: %s doesn't match %s" str re))
1573 (let ((chopped ())
1574 (i 1))
1575 (while (match-beginning i)
1576 (push (match-string i str) chopped)
1577 (setq i (1+ i)))
1578 ;; Add the text corresponding to the implicit trailing `any'.
1579 (push (substring str (match-end 0)) chopped)
1580 (push (nreverse chopped) ccs))))
1582 ;; Then for each of those non-constant elements, extract the
1583 ;; commonality between them.
1584 (let ((res ()))
1585 ;; Make the implicit `any' explicit. We could make it explicit
1586 ;; everywhere, but it would slow down regexp-matching a little bit.
1587 (dolist (elem (append pattern '(any)))
1588 (if (stringp elem)
1589 (push elem res)
1590 (let ((comps ()))
1591 (dolist (cc (prog1 ccs (setq ccs nil)))
1592 (push (car cc) comps)
1593 (push (cdr cc) ccs))
1594 (let* ((prefix (try-completion "" comps))
1595 (unique (or (and (eq prefix t) (setq prefix ""))
1596 (eq t (try-completion prefix comps)))))
1597 (unless (equal prefix "") (push prefix res))
1598 ;; If there's only one completion, `elem' is not useful
1599 ;; any more: it can only match the empty string.
1600 ;; FIXME: in some cases, it may be necessary to turn an
1601 ;; `any' into a `star' because the surrounding context has
1602 ;; changed such that string->pattern wouldn't add an `any'
1603 ;; here any more.
1604 (unless unique (push elem res))))))
1605 ;; We return it in reverse order.
1606 res)))))
1608 (defun completion-pcm--pattern->string (pattern)
1609 (mapconcat (lambda (x) (cond
1610 ((stringp x) x)
1611 ((eq x 'star) "*")
1612 ((eq x 'any) "")
1613 ((eq x 'point) "")))
1614 pattern
1615 ""))
1617 ;; We want to provide the functionality of `try', but we use `all'
1618 ;; and then merge it. In most cases, this works perfectly, but
1619 ;; if the completion table doesn't consider the same completions in
1620 ;; `try' as in `all', then we have a problem. The most common such
1621 ;; case is for filename completion where completion-ignored-extensions
1622 ;; is only obeyed by the `try' code. We paper over the difference
1623 ;; here. Note that it is not quite right either: if the completion
1624 ;; table uses completion-table-in-turn, this filtering may take place
1625 ;; too late to correctly fallback from the first to the
1626 ;; second alternative.
1627 (defun completion-pcm--filename-try-filter (all)
1628 "Filter to adjust `all' file completion to the behavior of `try'."
1629 (when all
1630 (let ((try ())
1631 (re (concat "\\(?:\\`\\.\\.?/\\|"
1632 (regexp-opt completion-ignored-extensions)
1633 "\\)\\'")))
1634 (dolist (f all)
1635 (unless (string-match re f) (push f try)))
1636 (or try all))))
1639 (defun completion-pcm--merge-try (pattern all prefix suffix)
1640 (cond
1641 ((not (consp all)) all)
1642 ((and (not (consp (cdr all))) ;Only one completion.
1643 ;; Ignore completion-ignore-case here.
1644 (equal (completion-pcm--pattern->string pattern) (car all)))
1647 (let* ((mergedpat (completion-pcm--merge-completions all pattern))
1648 ;; `mergedpat' is in reverse order. Place new point (by
1649 ;; order of preference) either at the old point, or at
1650 ;; the last place where there's something to choose, or
1651 ;; at the very end.
1652 (pointpat (or (memq 'point mergedpat) (memq 'any mergedpat)
1653 mergedpat))
1654 ;; New pos from the start.
1655 (newpos (length (completion-pcm--pattern->string pointpat)))
1656 ;; Do it afterwards because it changes `pointpat' by sideeffect.
1657 (merged (completion-pcm--pattern->string (nreverse mergedpat))))
1659 (setq suffix (completion--merge-suffix merged newpos suffix))
1660 (cons (concat prefix merged suffix) (+ newpos (length prefix)))))))
1662 (defun completion-pcm-try-completion (string table pred point)
1663 (destructuring-bind (pattern all prefix suffix)
1664 (completion-pcm--find-all-completions
1665 string table pred point
1666 (if minibuffer-completing-file-name
1667 'completion-pcm--filename-try-filter))
1668 (completion-pcm--merge-try pattern all prefix suffix)))
1671 (provide 'minibuffer)
1673 ;; arch-tag: ef8a0a15-1080-4790-a754-04017c02f08f
1674 ;;; minibuffer.el ends here