(looking-back): Fix doc-string typo.
[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-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).
46
47 ;;; Todo:
48
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?
56
57 ;;; Code:
58
59 (eval-when-compile (require 'cl))
60
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'.")
65
66 ;;; Completion table manipulation
67
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)))))
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 complete-with-action (action table string pred)
100 "Perform completion ACTION.
101 STRING is the string to complete.
102 TABLE is the completion table, which should not be a function.
103 PRED is a completion predicate.
104 ACTION can be one of nil, t or `lambda'."
105 (cond
106 ((functionp table) (funcall table string pred action))
107 ((eq (car-safe action) 'boundaries)
108 (cons 'boundaries (completion-boundaries string table pred (cdr action))))
109 (t
110 (funcall
111 (cond
112 ((null action) 'try-completion)
113 ((eq action t) 'all-completions)
114 (t 'test-completion))
115 string table pred))))
116
117 (defun completion-table-dynamic (fun)
118 "Use function FUN as a dynamic completion table.
119 FUN is called with one argument, the string for which completion is required,
120 and it should return an alist containing all the intended possible completions.
121 This alist may be a full list of possible completions so that FUN can ignore
122 the value of its argument. If completion is performed in the minibuffer,
123 FUN will be called in the buffer from which the minibuffer was entered.
124
125 The result of the `completion-table-dynamic' form is a function
126 that can be used as the COLLECTION argument to `try-completion' and
127 `all-completions'. See Info node `(elisp)Programmed Completion'."
128 (lexical-let ((fun fun))
129 (lambda (string pred action)
130 (with-current-buffer (let ((win (minibuffer-selected-window)))
131 (if (window-live-p win) (window-buffer win)
132 (current-buffer)))
133 (complete-with-action action (funcall fun string) string pred)))))
134
135 (defmacro lazy-completion-table (var fun)
136 "Initialize variable VAR as a lazy completion table.
137 If the completion table VAR is used for the first time (e.g., by passing VAR
138 as an argument to `try-completion'), the function FUN is called with no
139 arguments. FUN must return the completion table that will be stored in VAR.
140 If completion is requested in the minibuffer, FUN will be called in the buffer
141 from which the minibuffer was entered. The return value of
142 `lazy-completion-table' must be used to initialize the value of VAR.
143
144 You should give VAR a non-nil `risky-local-variable' property."
145 (declare (debug (symbolp lambda-expr)))
146 (let ((str (make-symbol "string")))
147 `(completion-table-dynamic
148 (lambda (,str)
149 (when (functionp ,var)
150 (setq ,var (,fun)))
151 ,var))))
152
153 (defun completion-table-with-context (prefix table string pred action)
154 ;; TODO: add `suffix' maybe?
155 ;; Notice that `pred' may not be a function in some abusive cases.
156 (when (functionp pred)
157 (setq pred
158 (lexical-let ((pred pred))
159 ;; Predicates are called differently depending on the nature of
160 ;; the completion table :-(
161 (cond
162 ((vectorp table) ;Obarray.
163 (lambda (sym) (funcall pred (concat prefix (symbol-name sym)))))
164 ((hash-table-p table)
165 (lambda (s v) (funcall pred (concat prefix s))))
166 ((functionp table)
167 (lambda (s) (funcall pred (concat prefix s))))
168 (t ;Lists and alists.
169 (lambda (s)
170 (funcall pred (concat prefix (if (consp s) (car s) s)))))))))
171 (if (eq (car-safe action) 'boundaries)
172 (let* ((len (length prefix))
173 (bound (completion-boundaries string table pred (cdr action))))
174 (list* 'boundaries (+ (car bound) len) (cdr bound)))
175 (let ((comp (complete-with-action action table string pred)))
176 (cond
177 ;; In case of try-completion, add the prefix.
178 ((stringp comp) (concat prefix comp))
179 ;; In case of non-empty all-completions,
180 ;; add the prefix size to the base-size.
181 ((consp comp)
182 (let ((last (last comp)))
183 (when completion-all-completions-with-base-size
184 (setcdr last (+ (or (cdr last) 0) (length prefix))))
185 comp))
186 (t comp)))))
187
188 (defun completion-table-with-terminator (terminator table string pred action)
189 (cond
190 ((eq action nil)
191 (let ((comp (try-completion string table pred)))
192 (if (eq comp t)
193 (concat string terminator)
194 (if (and (stringp comp)
195 (eq (try-completion comp table pred) t))
196 (concat comp terminator)
197 comp))))
198 ((eq action t)
199 ;; FIXME: We generally want the `try' and `all' behaviors to be
200 ;; consistent so pcm can merge the `all' output to get the `try' output,
201 ;; but that sometimes clashes with the need for `all' output to look
202 ;; good in *Completions*.
203 ;; (let* ((all (all-completions string table pred))
204 ;; (last (last all))
205 ;; (base-size (cdr last)))
206 ;; (when all
207 ;; (setcdr all nil)
208 ;; (nconc (mapcar (lambda (s) (concat s terminator)) all) base-size)))
209 (all-completions string table pred))
210 ;; completion-table-with-terminator is always used for
211 ;; "sub-completions" so it's only called if the terminator is missing,
212 ;; in which case `test-completion' should return nil.
213 ((eq action 'lambda) nil)))
214
215 (defun completion-table-with-predicate (table pred1 strict string pred2 action)
216 "Make a completion table equivalent to TABLE but filtered through PRED1.
217 PRED1 is a function of one argument which returns non-nil if and only if the
218 argument is an element of TABLE which should be considered for completion.
219 STRING, PRED2, and ACTION are the usual arguments to completion tables,
220 as described in `try-completion', `all-completions', and `test-completion'.
221 If STRICT is t, the predicate always applies; if nil it only applies if
222 it does not reduce the set of possible completions to nothing.
223 Note: TABLE needs to be a proper completion table which obeys predicates."
224 (cond
225 ((and (not strict) (eq action 'lambda))
226 ;; Ignore pred1 since it doesn't really have to apply anyway.
227 (test-completion string table pred2))
228 (t
229 (or (complete-with-action action table string
230 (if (null pred2) pred1
231 (lexical-let ((pred1 pred2) (pred2 pred2))
232 (lambda (x)
233 ;; Call `pred1' first, so that `pred2'
234 ;; really can't tell that `x' is in table.
235 (if (funcall pred1 x) (funcall pred2 x))))))
236 ;; If completion failed and we're not applying pred1 strictly, try
237 ;; again without pred1.
238 (and (not strict)
239 (complete-with-action action table string pred2))))))
240
241 (defun completion-table-in-turn (&rest tables)
242 "Create a completion table that tries each table in TABLES in turn."
243 (lexical-let ((tables tables))
244 (lambda (string pred action)
245 (completion--some (lambda (table)
246 (complete-with-action action table string pred))
247 tables))))
248
249 ;; (defmacro complete-in-turn (a b) `(completion-table-in-turn ,a ,b))
250 ;; (defmacro dynamic-completion-table (fun) `(completion-table-dynamic ,fun))
251 (define-obsolete-function-alias
252 'complete-in-turn 'completion-table-in-turn "23.1")
253 (define-obsolete-function-alias
254 'dynamic-completion-table 'completion-table-dynamic "23.1")
255
256 ;;; Minibuffer completion
257
258 (defgroup minibuffer nil
259 "Controlling the behavior of the minibuffer."
260 :link '(custom-manual "(emacs)Minibuffer")
261 :group 'environment)
262
263 (defun minibuffer-message (message &rest args)
264 "Temporarily display MESSAGE at the end of the minibuffer.
265 The text is displayed for `minibuffer-message-timeout' seconds,
266 or until the next input event arrives, whichever comes first.
267 Enclose MESSAGE in [...] if this is not yet the case.
268 If ARGS are provided, then pass MESSAGE through `format'."
269 ;; Clear out any old echo-area message to make way for our new thing.
270 (message nil)
271 (setq message (if (and (null args) (string-match "\\[.+\\]" message))
272 ;; Make sure we can put-text-property.
273 (copy-sequence message)
274 (concat " [" message "]")))
275 (when args (setq message (apply 'format message args)))
276 (let ((ol (make-overlay (point-max) (point-max) nil t t))
277 ;; A quit during sit-for normally only interrupts the sit-for,
278 ;; but since minibuffer-message is used at the end of a command,
279 ;; at a time when the command has virtually finished already, a C-g
280 ;; should really cause an abort-recursive-edit instead (i.e. as if
281 ;; the C-g had been typed at top-level). Binding inhibit-quit here
282 ;; is an attempt to get that behavior.
283 (inhibit-quit t))
284 (unwind-protect
285 (progn
286 (unless (zerop (length message))
287 ;; The current C cursor code doesn't know to use the overlay's
288 ;; marker's stickiness to figure out whether to place the cursor
289 ;; before or after the string, so let's spoon-feed it the pos.
290 (put-text-property 0 1 'cursor t message))
291 (overlay-put ol 'after-string message)
292 (sit-for (or minibuffer-message-timeout 1000000)))
293 (delete-overlay ol))))
294
295 (defun minibuffer-completion-contents ()
296 "Return the user input in a minibuffer before point as a string.
297 That is what completion commands operate on."
298 (buffer-substring (field-beginning) (point)))
299
300 (defun delete-minibuffer-contents ()
301 "Delete all user input in a minibuffer.
302 If the current buffer is not a minibuffer, erase its entire contents."
303 ;; We used to do `delete-field' here, but when file name shadowing
304 ;; is on, the field doesn't cover the entire minibuffer contents.
305 (delete-region (minibuffer-prompt-end) (point-max)))
306
307 (defcustom completion-auto-help t
308 "Non-nil means automatically provide help for invalid completion input.
309 If the value is t the *Completion* buffer is displayed whenever completion
310 is requested but cannot be done.
311 If the value is `lazy', the *Completions* buffer is only displayed after
312 the second failed attempt to complete."
313 :type '(choice (const nil) (const t) (const lazy))
314 :group 'minibuffer)
315
316 (defvar completion-styles-alist
317 '((basic completion-basic-try-completion completion-basic-all-completions)
318 (emacs22 completion-emacs22-try-completion completion-emacs22-all-completions)
319 (emacs21 completion-emacs21-try-completion completion-emacs21-all-completions)
320 (partial-completion
321 completion-pcm-try-completion completion-pcm-all-completions))
322 "List of available completion styles.
323 Each element has the form (NAME TRY-COMPLETION ALL-COMPLETIONS)
324 where NAME is the name that should be used in `completion-styles',
325 TRY-COMPLETION is the function that does the completion, and
326 ALL-COMPLETIONS is the function that lists the completions.")
327
328 (defcustom completion-styles '(basic partial-completion)
329 "List of completion styles to use."
330 :type `(repeat (choice ,@(mapcar (lambda (x) (list 'const (car x)))
331 completion-styles-alist)))
332 :group 'minibuffer
333 :version "23.1")
334
335 (defun completion-try-completion (string table pred point)
336 "Try to complete STRING using completion table TABLE.
337 Only the elements of table that satisfy predicate PRED are considered.
338 POINT is the position of point within STRING.
339 The return value can be either nil to indicate that there is no completion,
340 t to indicate that STRING is the only possible completion,
341 or a pair (STRING . NEWPOINT) of the completed result string together with
342 a new position for point."
343 ;; The property `completion-styles' indicates that this functional
344 ;; completion-table claims to take care of completion styles itself.
345 ;; [I.e. It will most likely call us back at some point. ]
346 (if (and (symbolp table) (get table 'completion-styles))
347 ;; Extended semantics for functional completion-tables:
348 ;; They accept a 4th argument `point' and when called with action=nil
349 ;; and this 4th argument (a position inside `string'), they should
350 ;; return instead of a string a pair (STRING . NEWPOINT).
351 (funcall table string pred nil point)
352 (completion--some (lambda (style)
353 (funcall (nth 1 (assq style completion-styles-alist))
354 string table pred point))
355 completion-styles)))
356
357 (defun completion-all-completions (string table pred point)
358 "List the possible completions of STRING in completion table TABLE.
359 Only the elements of table that satisfy predicate PRED are considered.
360 POINT is the position of point within STRING.
361 The return value is a list of completions and may contain the base-size
362 in the last `cdr'."
363 (let ((completion-all-completions-with-base-size t))
364 ;; The property `completion-styles' indicates that this functional
365 ;; completion-table claims to take care of completion styles itself.
366 ;; [I.e. It will most likely call us back at some point. ]
367 (if (and (symbolp table) (get table 'completion-styles))
368 ;; Extended semantics for functional completion-tables:
369 ;; They accept a 4th argument `point' and when called with action=t
370 ;; and this 4th argument (a position inside `string'), they may
371 ;; return BASE-SIZE in the last `cdr'.
372 (funcall table string pred t point)
373 (completion--some (lambda (style)
374 (funcall (nth 2 (assq style completion-styles-alist))
375 string table pred point))
376 completion-styles))))
377
378 (defun minibuffer--bitset (modified completions exact)
379 (logior (if modified 4 0)
380 (if completions 2 0)
381 (if exact 1 0)))
382
383 (defun completion--do-completion (&optional try-completion-function)
384 "Do the completion and return a summary of what happened.
385 M = completion was performed, the text was Modified.
386 C = there were available Completions.
387 E = after completion we now have an Exact match.
388
389 MCE
390 000 0 no possible completion
391 001 1 was already an exact and unique completion
392 010 2 no completion happened
393 011 3 was already an exact completion
394 100 4 ??? impossible
395 101 5 ??? impossible
396 110 6 some completion happened
397 111 7 completed to an exact completion"
398 (let* ((beg (field-beginning))
399 (end (field-end))
400 (string (buffer-substring beg end))
401 (comp (funcall (or try-completion-function
402 'completion-try-completion)
403 string
404 minibuffer-completion-table
405 minibuffer-completion-predicate
406 (- (point) beg))))
407 (cond
408 ((null comp)
409 (ding) (minibuffer-message "No match") (minibuffer--bitset nil nil nil))
410 ((eq t comp) (minibuffer--bitset nil nil t)) ;Exact and unique match.
411 (t
412 ;; `completed' should be t if some completion was done, which doesn't
413 ;; include simply changing the case of the entered string. However,
414 ;; for appearance, the string is rewritten if the case changes.
415 (let* ((comp-pos (cdr comp))
416 (completion (car comp))
417 (completed (not (eq t (compare-strings completion nil nil
418 string nil nil t))))
419 (unchanged (eq t (compare-strings completion nil nil
420 string nil nil nil))))
421 (unless unchanged
422
423 ;; Insert in minibuffer the chars we got.
424 (goto-char end)
425 (insert completion)
426 (delete-region beg end))
427 ;; Move point.
428 (goto-char (+ beg comp-pos))
429
430 (if (not (or unchanged completed))
431 ;; The case of the string changed, but that's all. We're not sure
432 ;; whether this is a unique completion or not, so try again using
433 ;; the real case (this shouldn't recurse again, because the next
434 ;; time try-completion will return either t or the exact string).
435 (completion--do-completion try-completion-function)
436
437 ;; It did find a match. Do we match some possibility exactly now?
438 (let ((exact (test-completion completion
439 minibuffer-completion-table
440 minibuffer-completion-predicate)))
441 (unless completed
442 ;; Show the completion table, if requested.
443 (cond
444 ((not exact)
445 (if (case completion-auto-help
446 (lazy (eq this-command last-command))
447 (t completion-auto-help))
448 (minibuffer-completion-help)
449 (minibuffer-message "Next char not unique")))
450 ;; If the last exact completion and this one were the same,
451 ;; it means we've already given a "Complete but not unique"
452 ;; message and the user's hit TAB again, so now we give him help.
453 ((eq this-command last-command)
454 (if completion-auto-help (minibuffer-completion-help)))))
455
456 (minibuffer--bitset completed t exact))))))))
457
458 (defun minibuffer-complete ()
459 "Complete the minibuffer contents as far as possible.
460 Return nil if there is no valid completion, else t.
461 If no characters can be completed, display a list of possible completions.
462 If you repeat this command after it displayed such a list,
463 scroll the window of possible completions."
464 (interactive)
465 ;; If the previous command was not this,
466 ;; mark the completion buffer obsolete.
467 (unless (eq this-command last-command)
468 (setq minibuffer-scroll-window nil))
469
470 (let ((window minibuffer-scroll-window))
471 ;; If there's a fresh completion window with a live buffer,
472 ;; and this command is repeated, scroll that window.
473 (if (window-live-p window)
474 (with-current-buffer (window-buffer window)
475 (if (pos-visible-in-window-p (point-max) window)
476 ;; If end is in view, scroll up to the beginning.
477 (set-window-start window (point-min) nil)
478 ;; Else scroll down one screen.
479 (scroll-other-window))
480 nil)
481
482 (case (completion--do-completion)
483 (#b000 nil)
484 (#b001 (goto-char (field-end))
485 (minibuffer-message "Sole completion")
486 t)
487 (#b011 (goto-char (field-end))
488 (minibuffer-message "Complete, but not unique")
489 t)
490 (t t)))))
491
492 (defvar completion-all-sorted-completions nil)
493 (make-variable-buffer-local 'completion-all-sorted-completions)
494
495 (defun completion--flush-all-sorted-completions (&rest ignore)
496 (setq completion-all-sorted-completions nil))
497
498 (defun completion-all-sorted-completions ()
499 (or completion-all-sorted-completions
500 (let* ((start (field-beginning))
501 (end (field-end))
502 (all (completion-all-completions (buffer-substring start end)
503 minibuffer-completion-table
504 minibuffer-completion-predicate
505 (- (point) start)))
506 (last (last all))
507 (base-size (or (cdr last) 0)))
508 (when last
509 (setcdr last nil)
510 ;; Prefer shorter completions.
511 (setq all (sort all (lambda (c1 c2) (< (length c1) (length c2)))))
512 ;; Prefer recently used completions.
513 (let ((hist (symbol-value minibuffer-history-variable)))
514 (setq all (sort all (lambda (c1 c2)
515 (> (length (member c1 hist))
516 (length (member c2 hist)))))))
517 ;; Cache the result. This is not just for speed, but also so that
518 ;; repeated calls to minibuffer-force-complete can cycle through
519 ;; all possibilities.
520 (add-hook 'after-change-functions
521 'completion--flush-all-sorted-completions nil t)
522 (setq completion-all-sorted-completions
523 (nconc all base-size))))))
524
525 (defun minibuffer-force-complete ()
526 "Complete the minibuffer to an exact match.
527 Repeated uses step through the possible completions."
528 (interactive)
529 ;; FIXME: Need to deal with the extra-size issue here as well.
530 (let* ((start (field-beginning))
531 (end (field-end))
532 (all (completion-all-sorted-completions)))
533 (if (not (consp all))
534 (minibuffer-message (if all "No more completions" "No completions"))
535 (goto-char end)
536 (insert (car all))
537 (delete-region (+ start (cdr (last all))) end)
538 ;; If completing file names, (car all) may be a directory, so we'd now
539 ;; have a new set of possible completions and might want to reset
540 ;; completion-all-sorted-completions to nil, but we prefer not to,
541 ;; so that repeated calls minibuffer-force-complete still cycle
542 ;; through the previous possible completions.
543 (setq completion-all-sorted-completions (cdr all)))))
544
545 (defun minibuffer-complete-and-exit ()
546 "If the minibuffer contents is a valid completion then exit.
547 Otherwise try to complete it. If completion leads to a valid completion,
548 a repetition of this command will exit.
549 If `minibuffer-completion-confirm' is equal to `confirm', then do not
550 try to complete, but simply ask for confirmation and accept any
551 input if confirmed."
552 (interactive)
553 (let ((beg (field-beginning))
554 (end (field-end)))
555 (cond
556 ;; Allow user to specify null string
557 ((= beg end) (exit-minibuffer))
558 ((test-completion (buffer-substring beg end)
559 minibuffer-completion-table
560 minibuffer-completion-predicate)
561 (when completion-ignore-case
562 ;; Fixup case of the field, if necessary.
563 (let* ((string (buffer-substring beg end))
564 (compl (try-completion
565 string
566 minibuffer-completion-table
567 minibuffer-completion-predicate)))
568 (when (and (stringp compl)
569 ;; If it weren't for this piece of paranoia, I'd replace
570 ;; the whole thing with a call to do-completion.
571 ;; This is important, e.g. when the current minibuffer's
572 ;; content is a directory which only contains a single
573 ;; file, so `try-completion' actually completes to
574 ;; that file.
575 (= (length string) (length compl)))
576 (goto-char end)
577 (insert compl)
578 (delete-region beg end))))
579 (exit-minibuffer))
580
581 ((eq minibuffer-completion-confirm 'confirm-only)
582 ;; The user is permitted to exit with an input that's rejected
583 ;; by test-completion, but at the condition to confirm her choice.
584 (if (eq last-command this-command)
585 (exit-minibuffer)
586 (minibuffer-message "Confirm")
587 nil))
588
589 (t
590 ;; Call do-completion, but ignore errors.
591 (case (condition-case nil
592 (completion--do-completion)
593 (error 1))
594 ((#b001 #b011) (exit-minibuffer))
595 (#b111 (if (not minibuffer-completion-confirm)
596 (exit-minibuffer)
597 (minibuffer-message "Confirm")
598 nil))
599 (t nil))))))
600
601 (defun completion--try-word-completion (string table predicate point)
602 (let ((comp (completion-try-completion string table predicate point)))
603 (if (not (consp comp))
604 comp
605
606 ;; If completion finds next char not unique,
607 ;; consider adding a space or a hyphen.
608 (when (= (length string) (length (car comp)))
609 (let ((exts '(" " "-"))
610 (before (substring string 0 point))
611 (after (substring string point))
612 ;; Disable partial-completion for this.
613 (completion-styles
614 (remove 'partial-completion 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
818 The obsolete optional arg COMMON-SUBSTRING, if non-nil, should be a string
819 specifying a common substring for adding the faces
820 `completions-first-difference' and `completions-common-part' to
821 the completions buffer."
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 common-substring))
831 (princ (buffer-string)))
832
833 (let ((mainbuf (current-buffer)))
834 (with-current-buffer standard-output
835 (goto-char (point-max))
836 (if (null completions)
837 (insert "There are no possible completions of what you have typed.")
838 (insert "Possible completions are:\n")
839 (let ((last (last completions)))
840 ;; Set base-size from the tail of the list.
841 (set (make-local-variable 'completion-base-size)
842 (or (cdr last)
843 (and (minibufferp mainbuf) 0)))
844 (setcdr last nil)) ; Make completions a properly nil-terminated list.
845 (completion--insert-strings completions)))))
846
847 ;; The hilit used to be applied via completion-setup-hook, so there
848 ;; may still be some code that uses completion-common-substring.
849 (with-no-warnings
850 (let ((completion-common-substring common-substring))
851 (run-hooks 'completion-setup-hook)))
852 nil)
853
854 (defun minibuffer-completion-help ()
855 "Display a list of possible completions of the current minibuffer contents."
856 (interactive)
857 (message "Making completion list...")
858 (let* ((string (field-string))
859 (completions (completion-all-completions
860 string
861 minibuffer-completion-table
862 minibuffer-completion-predicate
863 (- (point) (field-beginning)))))
864 (message nil)
865 (if (and completions
866 (or (consp (cdr completions))
867 (not (equal (car completions) string))))
868 (with-output-to-temp-buffer "*Completions*"
869 (let* ((last (last completions))
870 (base-size (cdr last)))
871 ;; Remove the base-size tail because `sort' requires a properly
872 ;; nil-terminated list.
873 (when last (setcdr last nil))
874 (display-completion-list (nconc (sort completions 'string-lessp)
875 base-size))))
876
877 ;; If there are no completions, or if the current input is already the
878 ;; only possible completion, then hide (previous&stale) completions.
879 (let ((window (and (get-buffer "*Completions*")
880 (get-buffer-window "*Completions*" 0))))
881 (when (and (window-live-p window) (window-dedicated-p window))
882 (condition-case ()
883 (delete-window window)
884 (error (iconify-frame (window-frame window))))))
885 (ding)
886 (minibuffer-message
887 (if completions "Sole completion" "No completions")))
888 nil))
889
890 (defun exit-minibuffer ()
891 "Terminate this minibuffer argument."
892 (interactive)
893 ;; If the command that uses this has made modifications in the minibuffer,
894 ;; we don't want them to cause deactivation of the mark in the original
895 ;; buffer.
896 ;; A better solution would be to make deactivate-mark buffer-local
897 ;; (or to turn it into a list of buffers, ...), but in the mean time,
898 ;; this should do the trick in most cases.
899 (setq deactivate-mark nil)
900 (throw 'exit nil))
901
902 (defun self-insert-and-exit ()
903 "Terminate minibuffer input."
904 (interactive)
905 (if (characterp last-command-char)
906 (call-interactively 'self-insert-command)
907 (ding))
908 (exit-minibuffer))
909
910 ;;; Key bindings.
911
912 (define-obsolete-variable-alias 'minibuffer-local-must-match-filename-map
913 'minibuffer-local-filename-must-match-map "23.1")
914
915 (let ((map minibuffer-local-map))
916 (define-key map "\C-g" 'abort-recursive-edit)
917 (define-key map "\r" 'exit-minibuffer)
918 (define-key map "\n" 'exit-minibuffer))
919
920 (let ((map minibuffer-local-completion-map))
921 (define-key map "\t" 'minibuffer-complete)
922 ;; M-TAB is already abused for many other purposes, so we should find
923 ;; another binding for it.
924 ;; (define-key map "\e\t" 'minibuffer-force-complete)
925 (define-key map " " 'minibuffer-complete-word)
926 (define-key map "?" 'minibuffer-completion-help))
927
928 (let ((map minibuffer-local-must-match-map))
929 (define-key map "\r" 'minibuffer-complete-and-exit)
930 (define-key map "\n" 'minibuffer-complete-and-exit))
931
932 (let ((map minibuffer-local-filename-completion-map))
933 (define-key map " " nil))
934 (let ((map minibuffer-local-filename-must-match-map))
935 (define-key map " " nil))
936
937 (let ((map minibuffer-local-ns-map))
938 (define-key map " " 'exit-minibuffer)
939 (define-key map "\t" 'exit-minibuffer)
940 (define-key map "?" 'self-insert-and-exit))
941
942 ;;; Completion tables.
943
944 (defun minibuffer--double-dollars (str)
945 (replace-regexp-in-string "\\$" "$$" str))
946
947 (defun completion--make-envvar-table ()
948 (mapcar (lambda (enventry)
949 (substring enventry 0 (string-match "=" enventry)))
950 process-environment))
951
952 (defconst completion--embedded-envvar-re
953 (concat "\\(?:^\\|[^$]\\(?:\\$\\$\\)*\\)"
954 "$\\([[:alnum:]_]*\\|{\\([^}]*\\)\\)\\'"))
955
956 (defun completion--embedded-envvar-table (string pred action)
957 (if (eq (car-safe action) 'boundaries)
958 ;; Compute the boundaries of the subfield to which this
959 ;; completion applies.
960 (let ((suffix (cdr action)))
961 (if (string-match completion--embedded-envvar-re string)
962 (list* 'boundaries
963 (or (match-beginning 2) (match-beginning 1))
964 (when (string-match "[^[:alnum:]_]" suffix)
965 (match-beginning 0)))))
966 (when (string-match completion--embedded-envvar-re string)
967 (let* ((beg (or (match-beginning 2) (match-beginning 1)))
968 (table (completion--make-envvar-table))
969 (prefix (substring string 0 beg)))
970 (if (eq (aref string (1- beg)) ?{)
971 (setq table (apply-partially 'completion-table-with-terminator
972 "}" table)))
973 (completion-table-with-context
974 prefix table (substring string beg) pred action)))))
975
976 (defun completion--file-name-table (string pred action)
977 "Internal subroutine for `read-file-name'. Do not call this."
978 (cond
979 ((and (zerop (length string)) (eq 'lambda action))
980 nil) ; FIXME: why?
981 ((eq (car-safe action) 'boundaries)
982 ;; FIXME: Actually, this is not always right in the presence of
983 ;; envvars, but there's not much we can do, I think.
984 (let ((start (length (file-name-directory string)))
985 (end (string-match "/" (cdr action))))
986 (list* 'boundaries start end)))
987
988 (t
989 (let* ((dir (if (stringp pred)
990 ;; It used to be that `pred' was abused to pass `dir'
991 ;; as an argument.
992 (prog1 (expand-file-name pred) (setq pred nil))
993 default-directory))
994 (str (condition-case nil
995 (substitute-in-file-name string)
996 (error string)))
997 (name (file-name-nondirectory str))
998 (specdir (file-name-directory str))
999 (realdir (if specdir (expand-file-name specdir dir)
1000 (file-name-as-directory dir))))
1001
1002 (cond
1003 ((null action)
1004 (let ((comp (file-name-completion name realdir
1005 read-file-name-predicate)))
1006 (if (stringp comp)
1007 ;; Requote the $s before returning the completion.
1008 (minibuffer--double-dollars (concat specdir comp))
1009 ;; Requote the $s before checking for changes.
1010 (setq str (minibuffer--double-dollars str))
1011 (if (string-equal string str)
1012 comp
1013 ;; If there's no real completion, but substitute-in-file-name
1014 ;; changed the string, then return the new string.
1015 str))))
1016
1017 ((eq action t)
1018 (let ((all (file-name-all-completions name realdir))
1019 ;; FIXME: Actually, this is not always right in the presence
1020 ;; of envvars, but there's not much we can do, I think.
1021 (base-size (length (file-name-directory string))))
1022
1023 ;; Check the predicate, if necessary.
1024 (unless (memq read-file-name-predicate '(nil file-exists-p))
1025 (let ((comp ())
1026 (pred
1027 (if (eq read-file-name-predicate 'file-directory-p)
1028 ;; Brute-force speed up for directory checking:
1029 ;; Discard strings which don't end in a slash.
1030 (lambda (s)
1031 (let ((len (length s)))
1032 (and (> len 0) (eq (aref s (1- len)) ?/))))
1033 ;; Must do it the hard (and slow) way.
1034 read-file-name-predicate)))
1035 (let ((default-directory realdir))
1036 (dolist (tem all)
1037 (if (funcall pred tem) (push tem comp))))
1038 (setq all (nreverse comp))))
1039
1040 (if (and completion-all-completions-with-base-size (consp all))
1041 ;; Add base-size, but only if the list is non-empty.
1042 (nconc all base-size)
1043 all)))
1044
1045 (t
1046 ;; Only other case actually used is ACTION = lambda.
1047 (let ((default-directory dir))
1048 (funcall (or read-file-name-predicate 'file-exists-p) str))))))))
1049
1050 (defalias 'read-file-name-internal
1051 (completion-table-in-turn 'completion--embedded-envvar-table
1052 'completion--file-name-table)
1053 "Internal subroutine for `read-file-name'. Do not call this.")
1054
1055 (defvar read-file-name-function nil
1056 "If this is non-nil, `read-file-name' does its work by calling this function.")
1057
1058 (defvar read-file-name-predicate nil
1059 "Current predicate used by `read-file-name-internal'.")
1060
1061 (defcustom read-file-name-completion-ignore-case
1062 (if (memq system-type '(ms-dos windows-nt darwin cygwin))
1063 t nil)
1064 "Non-nil means when reading a file name completion ignores case."
1065 :group 'minibuffer
1066 :type 'boolean
1067 :version "22.1")
1068
1069 (defcustom insert-default-directory t
1070 "Non-nil means when reading a filename start with default dir in minibuffer.
1071
1072 When the initial minibuffer contents show a name of a file or a directory,
1073 typing RETURN without editing the initial contents is equivalent to typing
1074 the default file name.
1075
1076 If this variable is non-nil, the minibuffer contents are always
1077 initially non-empty, and typing RETURN without editing will fetch the
1078 default name, if one is provided. Note however that this default name
1079 is not necessarily the same as initial contents inserted in the minibuffer,
1080 if the initial contents is just the default directory.
1081
1082 If this variable is nil, the minibuffer often starts out empty. In
1083 that case you may have to explicitly fetch the next history element to
1084 request the default name; typing RETURN without editing will leave
1085 the minibuffer empty.
1086
1087 For some commands, exiting with an empty minibuffer has a special meaning,
1088 such as making the current buffer visit no file in the case of
1089 `set-visited-file-name'."
1090 :group 'minibuffer
1091 :type 'boolean)
1092
1093 ;; Not always defined, but only called if next-read-file-uses-dialog-p says so.
1094 (declare-function x-file-dialog "xfns.c"
1095 (prompt dir &optional default-filename mustmatch only-dir-p))
1096
1097 (defun read-file-name (prompt &optional dir default-filename mustmatch initial predicate)
1098 "Read file name, prompting with PROMPT and completing in directory DIR.
1099 Value is not expanded---you must call `expand-file-name' yourself.
1100 Default name to DEFAULT-FILENAME if user exits the minibuffer with
1101 the same non-empty string that was inserted by this function.
1102 (If DEFAULT-FILENAME is omitted, the visited file name is used,
1103 except that if INITIAL is specified, that combined with DIR is used.)
1104 If the user exits with an empty minibuffer, this function returns
1105 an empty string. (This can only happen if the user erased the
1106 pre-inserted contents or if `insert-default-directory' is nil.)
1107 Fourth arg MUSTMATCH non-nil means require existing file's name.
1108 Non-nil and non-t means also require confirmation after completion.
1109 Fifth arg INITIAL specifies text to start with.
1110 If optional sixth arg PREDICATE is non-nil, possible completions and
1111 the resulting file name must satisfy (funcall PREDICATE NAME).
1112 DIR should be an absolute directory name. It defaults to the value of
1113 `default-directory'.
1114
1115 If this command was invoked with the mouse, use a file dialog box if
1116 `use-dialog-box' is non-nil, and the window system or X toolkit in use
1117 provides a file dialog box.
1118
1119 See also `read-file-name-completion-ignore-case'
1120 and `read-file-name-function'."
1121 (unless dir (setq dir default-directory))
1122 (unless (file-name-absolute-p dir) (setq dir (expand-file-name dir)))
1123 (unless default-filename
1124 (setq default-filename (if initial (expand-file-name initial dir)
1125 buffer-file-name)))
1126 ;; If dir starts with user's homedir, change that to ~.
1127 (setq dir (abbreviate-file-name dir))
1128 ;; Likewise for default-filename.
1129 (if default-filename
1130 (setq default-filename (abbreviate-file-name default-filename)))
1131 (let ((insdef (cond
1132 ((and insert-default-directory (stringp dir))
1133 (if initial
1134 (cons (minibuffer--double-dollars (concat dir initial))
1135 (length (minibuffer--double-dollars dir)))
1136 (minibuffer--double-dollars dir)))
1137 (initial (cons (minibuffer--double-dollars initial) 0)))))
1138
1139 (if read-file-name-function
1140 (funcall read-file-name-function
1141 prompt dir default-filename mustmatch initial predicate)
1142 (let ((completion-ignore-case read-file-name-completion-ignore-case)
1143 (minibuffer-completing-file-name t)
1144 (read-file-name-predicate (or predicate 'file-exists-p))
1145 (add-to-history nil))
1146
1147 (let* ((val
1148 (if (not (next-read-file-uses-dialog-p))
1149 ;; We used to pass `dir' to `read-file-name-internal' by
1150 ;; abusing the `predicate' argument. It's better to
1151 ;; just use `default-directory', but in order to avoid
1152 ;; changing `default-directory' in the current buffer,
1153 ;; we don't let-bind it.
1154 (lexical-let ((dir (file-name-as-directory
1155 (expand-file-name dir))))
1156 (minibuffer-with-setup-hook
1157 (lambda () (setq default-directory dir))
1158 (completing-read prompt 'read-file-name-internal
1159 nil mustmatch insdef 'file-name-history
1160 default-filename)))
1161 ;; If DIR contains a file name, split it.
1162 (let ((file (file-name-nondirectory dir)))
1163 (when (and default-filename (not (zerop (length file))))
1164 (setq default-filename file)
1165 (setq dir (file-name-directory dir)))
1166 (if default-filename
1167 (setq default-filename
1168 (expand-file-name default-filename dir)))
1169 (setq add-to-history t)
1170 (x-file-dialog prompt dir default-filename mustmatch
1171 (eq predicate 'file-directory-p)))))
1172
1173 (replace-in-history (eq (car-safe file-name-history) val)))
1174 ;; If completing-read returned the inserted default string itself
1175 ;; (rather than a new string with the same contents),
1176 ;; it has to mean that the user typed RET with the minibuffer empty.
1177 ;; In that case, we really want to return ""
1178 ;; so that commands such as set-visited-file-name can distinguish.
1179 (when (eq val default-filename)
1180 ;; In this case, completing-read has not added an element
1181 ;; to the history. Maybe we should.
1182 (if (not replace-in-history)
1183 (setq add-to-history t))
1184 (setq val ""))
1185 (unless val (error "No file name specified"))
1186
1187 (if (and default-filename
1188 (string-equal val (if (consp insdef) (car insdef) insdef)))
1189 (setq val default-filename))
1190 (setq val (substitute-in-file-name val))
1191
1192 (if replace-in-history
1193 ;; Replace what Fcompleting_read added to the history
1194 ;; with what we will actually return.
1195 (let ((val1 (minibuffer--double-dollars val)))
1196 (if history-delete-duplicates
1197 (setcdr file-name-history
1198 (delete val1 (cdr file-name-history))))
1199 (setcar file-name-history val1))
1200 (if add-to-history
1201 ;; Add the value to the history--but not if it matches
1202 ;; the last value already there.
1203 (let ((val1 (minibuffer--double-dollars val)))
1204 (unless (and (consp file-name-history)
1205 (equal (car file-name-history) val1))
1206 (setq file-name-history
1207 (cons val1
1208 (if history-delete-duplicates
1209 (delete val1 file-name-history)
1210 file-name-history)))))))
1211 val)))))
1212
1213 (defun internal-complete-buffer-except (&optional buffer)
1214 "Perform completion on all buffers excluding BUFFER.
1215 Like `internal-complete-buffer', but removes BUFFER from the completion list."
1216 (lexical-let ((except (if (stringp buffer) buffer (buffer-name buffer))))
1217 (apply-partially 'completion-table-with-predicate
1218 'internal-complete-buffer
1219 (lambda (name)
1220 (not (equal (if (consp name) (car name) name) except)))
1221 nil)))
1222
1223 ;;; Old-style completion, used in Emacs-21 and Emacs-22.
1224
1225 (defun completion-emacs21-try-completion (string table pred point)
1226 (let ((completion (try-completion string table pred)))
1227 (if (stringp completion)
1228 (cons completion (length completion))
1229 completion)))
1230
1231 (defun completion-emacs21-all-completions (string table pred point)
1232 (completion-hilit-commonality
1233 (all-completions string table pred)
1234 (length string)))
1235
1236 (defun completion-emacs22-try-completion (string table pred point)
1237 (let ((suffix (substring string point))
1238 (completion (try-completion (substring string 0 point) table pred)))
1239 (if (not (stringp completion))
1240 completion
1241 ;; Merge a trailing / in completion with a / after point.
1242 ;; We used to only do it for word completion, but it seems to make
1243 ;; sense for all completions.
1244 ;; Actually, claiming this feature was part of Emacs-22 completion
1245 ;; is pushing it a bit: it was only done in minibuffer-completion-word,
1246 ;; which was (by default) not bound during file completion, where such
1247 ;; slashes are most likely to occur.
1248 (if (and (not (zerop (length completion)))
1249 (eq ?/ (aref completion (1- (length completion))))
1250 (not (zerop (length suffix)))
1251 (eq ?/ (aref suffix 0)))
1252 ;; This leaves point after the / .
1253 (setq suffix (substring suffix 1)))
1254 (cons (concat completion suffix) (length completion)))))
1255
1256 (defun completion-emacs22-all-completions (string table pred point)
1257 (completion-hilit-commonality
1258 (all-completions (substring string 0 point) table pred)
1259 point))
1260
1261 ;;; Basic completion.
1262
1263 (defun completion--merge-suffix (completion point suffix)
1264 "Merge end of COMPLETION with beginning of SUFFIX.
1265 Simple generalization of the \"merge trailing /\" done in Emacs-22.
1266 Return the new suffix."
1267 (if (and (not (zerop (length suffix)))
1268 (string-match "\\(.+\\)\n\\1" (concat completion "\n" suffix)
1269 ;; Make sure we don't compress things to less
1270 ;; than we started with.
1271 point)
1272 ;; Just make sure we didn't match some other \n.
1273 (eq (match-end 1) (length completion)))
1274 (substring suffix (- (match-end 1) (match-beginning 1)))
1275 ;; Nothing to merge.
1276 suffix))
1277
1278 (defun completion-basic-try-completion (string table pred point)
1279 (let* ((beforepoint (substring string 0 point))
1280 (afterpoint (substring string point))
1281 (bounds (completion-boundaries beforepoint table pred afterpoint)))
1282 (if (zerop (cdr bounds))
1283 ;; `try-completion' may return a subtly different result
1284 ;; than `all+merge', so try to use it whenever possible.
1285 (let ((completion (try-completion beforepoint table pred)))
1286 (if (not (stringp completion))
1287 completion
1288 (cons
1289 (concat completion
1290 (completion--merge-suffix completion point afterpoint))
1291 (length completion))))
1292 (let* ((suffix (substring afterpoint (cdr bounds)))
1293 (prefix (substring beforepoint 0 (car bounds)))
1294 (pattern (delete
1295 "" (list (substring beforepoint (car bounds))
1296 'point
1297 (substring afterpoint 0 (cdr bounds)))))
1298 (all (completion-pcm--all-completions prefix pattern table pred)))
1299 (if minibuffer-completing-file-name
1300 (setq all (completion-pcm--filename-try-filter all)))
1301 (completion-pcm--merge-try pattern all prefix suffix)))))
1302
1303 (defun completion-basic-all-completions (string table pred point)
1304 (let* ((beforepoint (substring string 0 point))
1305 (afterpoint (substring string point))
1306 (bounds (completion-boundaries beforepoint table pred afterpoint))
1307 (suffix (substring afterpoint (cdr bounds)))
1308 (prefix (substring beforepoint 0 (car bounds)))
1309 (pattern (delete
1310 "" (list (substring beforepoint (car bounds))
1311 'point
1312 (substring afterpoint 0 (cdr bounds)))))
1313 (all (completion-pcm--all-completions prefix pattern table pred)))
1314 (completion-hilit-commonality
1315 (if (consp all) (nconc all (car bounds)) all)
1316 point)))
1317
1318 ;;; Partial-completion-mode style completion.
1319
1320 (defvar completion-pcm--delim-wild-regex nil)
1321
1322 (defun completion-pcm--prepare-delim-re (delims)
1323 (setq completion-pcm--delim-wild-regex (concat "[" delims "*]")))
1324
1325 (defcustom completion-pcm-word-delimiters "-_. "
1326 "A string of characters treated as word delimiters for completion.
1327 Some arcane rules:
1328 If `]' is in this string, it must come first.
1329 If `^' is in this string, it must not come first.
1330 If `-' is in this string, it must come first or right after `]'.
1331 In other words, if S is this string, then `[S]' must be a valid Emacs regular
1332 expression (not containing character ranges like `a-z')."
1333 :set (lambda (symbol value)
1334 (set-default symbol value)
1335 ;; Refresh other vars.
1336 (completion-pcm--prepare-delim-re value))
1337 :initialize 'custom-initialize-reset
1338 :group 'minibuffer
1339 :type 'string)
1340
1341 (defun completion-pcm--pattern-trivial-p (pattern)
1342 (and (stringp (car pattern)) (null (cdr pattern))))
1343
1344 (defun completion-pcm--string->pattern (string &optional point)
1345 "Split STRING into a pattern.
1346 A pattern is a list where each element is either a string
1347 or a symbol chosen among `any', `star', `point'."
1348 (if (and point (< point (length string)))
1349 (let ((prefix (substring string 0 point))
1350 (suffix (substring string point)))
1351 (append (completion-pcm--string->pattern prefix)
1352 '(point)
1353 (completion-pcm--string->pattern suffix)))
1354 (let ((pattern nil)
1355 (p 0)
1356 (p0 0))
1357
1358 (while (setq p (string-match completion-pcm--delim-wild-regex string p))
1359 (push (substring string p0 p) pattern)
1360 (if (eq (aref string p) ?*)
1361 (progn
1362 (push 'star pattern)
1363 (setq p0 (1+ p)))
1364 (push 'any pattern)
1365 (setq p0 p))
1366 (incf p))
1367
1368 ;; An empty string might be erroneously added at the beginning.
1369 ;; It should be avoided properly, but it's so easy to remove it here.
1370 (delete "" (nreverse (cons (substring string p0) pattern))))))
1371
1372 (defun completion-pcm--pattern->regex (pattern &optional group)
1373 (let ((re
1374 (concat "\\`"
1375 (mapconcat
1376 (lambda (x)
1377 (case x
1378 ((star any point)
1379 (if (if (consp group) (memq x group) group)
1380 "\\(.*?\\)" ".*?"))
1381 (t (regexp-quote x))))
1382 pattern
1383 ""))))
1384 ;; Avoid pathological backtracking.
1385 (while (string-match "\\.\\*\\?\\(?:\\\\[()]\\)*\\(\\.\\*\\?\\)" re)
1386 (setq re (replace-match "" t t re 1)))
1387 re))
1388
1389 (defun completion-pcm--all-completions (prefix pattern table pred)
1390 "Find all completions for PATTERN in TABLE obeying PRED.
1391 PATTERN is as returned by `completion-pcm--string->pattern'."
1392 ;; Find an initial list of possible completions.
1393 (if (completion-pcm--pattern-trivial-p pattern)
1394
1395 ;; Minibuffer contains no delimiters -- simple case!
1396 (let* ((all (all-completions (concat prefix (car pattern)) table pred))
1397 (last (last all)))
1398 (if last (setcdr last nil))
1399 all)
1400
1401 ;; Use all-completions to do an initial cull. This is a big win,
1402 ;; since all-completions is written in C!
1403 (let* (;; Convert search pattern to a standard regular expression.
1404 (regex (completion-pcm--pattern->regex pattern))
1405 (case-fold-search completion-ignore-case)
1406 (completion-regexp-list (cons regex completion-regexp-list))
1407 (compl (all-completions
1408 (concat prefix (if (stringp (car pattern)) (car pattern) ""))
1409 table pred))
1410 (last (last compl)))
1411 (when last
1412 (if (and (numberp (cdr last)) (/= (cdr last) (length prefix)))
1413 (message "Inconsistent base-size returned by completion table %s"
1414 table))
1415 (setcdr last nil))
1416 (if (not (functionp table))
1417 ;; The internal functions already obeyed completion-regexp-list.
1418 compl
1419 (let ((poss ()))
1420 (dolist (c compl)
1421 (when (string-match regex c) (push c poss)))
1422 poss)))))
1423
1424 (defun completion-pcm--hilit-commonality (pattern completions)
1425 (when completions
1426 (let* ((re (completion-pcm--pattern->regex pattern '(point)))
1427 (case-fold-search completion-ignore-case)
1428 (last (last completions))
1429 (base-size (cdr last)))
1430 ;; Remove base-size during mapcar, and add it back later.
1431 (setcdr last nil)
1432 (nconc
1433 (mapcar
1434 (lambda (str)
1435 ;; Don't modify the string itself.
1436 (setq str (copy-sequence str))
1437 (unless (string-match re str)
1438 (error "Internal error: %s does not match %s" re str))
1439 (let ((pos (or (match-beginning 1) (match-end 0))))
1440 (put-text-property 0 pos
1441 'font-lock-face 'completions-common-part
1442 str)
1443 (if (> (length str) pos)
1444 (put-text-property pos (1+ pos)
1445 'font-lock-face 'completions-first-difference
1446 str)))
1447 str)
1448 completions)
1449 base-size))))
1450
1451 (defun completion-pcm--find-all-completions (string table pred point
1452 &optional filter)
1453 "Find all completions for STRING at POINT in TABLE, satisfying PRED.
1454 POINT is a position inside STRING.
1455 FILTER is a function applied to the return value, that can be used, e.g. to
1456 filter out additional entries (because TABLE migth not obey PRED)."
1457 (unless filter (setq filter 'identity))
1458 (let* ((beforepoint (substring string 0 point))
1459 (afterpoint (substring string point))
1460 (bounds (completion-boundaries beforepoint table pred afterpoint))
1461 (prefix (substring beforepoint 0 (car bounds)))
1462 (suffix (substring afterpoint (cdr bounds)))
1463 firsterror)
1464 (setq string (substring string (car bounds) (+ point (cdr bounds))))
1465 (let* ((relpoint (- point (car bounds)))
1466 (pattern (completion-pcm--string->pattern string relpoint))
1467 (all (condition-case err
1468 (funcall filter
1469 (completion-pcm--all-completions
1470 prefix pattern table pred))
1471 (error (unless firsterror (setq firsterror err)) nil))))
1472 (when (and (null all)
1473 (> (car bounds) 0)
1474 (null (ignore-errors (try-completion prefix table pred))))
1475 ;; The prefix has no completions at all, so we should try and fix
1476 ;; that first.
1477 (let ((substring (substring prefix 0 -1)))
1478 (destructuring-bind (subpat suball subprefix subsuffix)
1479 (completion-pcm--find-all-completions
1480 substring table pred (length substring) filter)
1481 (let ((sep (aref prefix (1- (length prefix))))
1482 ;; Text that goes between the new submatches and the
1483 ;; completion substring.
1484 (between nil))
1485 ;; Eliminate submatches that don't end with the separator.
1486 (dolist (submatch (prog1 suball (setq suball ())))
1487 (when (eq sep (aref submatch (1- (length submatch))))
1488 (push submatch suball)))
1489 (when suball
1490 ;; Update the boundaries and corresponding pattern.
1491 ;; We assume that all submatches result in the same boundaries
1492 ;; since we wouldn't know how to merge them otherwise anyway.
1493 ;; FIXME: COMPLETE REWRITE!!!
1494 (let* ((newbeforepoint
1495 (concat subprefix (car suball)
1496 (substring string 0 relpoint)))
1497 (leftbound (+ (length subprefix) (length (car suball))))
1498 (newbounds (completion-boundaries
1499 newbeforepoint table pred afterpoint)))
1500 (unless (or (and (eq (cdr bounds) (cdr newbounds))
1501 (eq (car newbounds) leftbound))
1502 ;; Refuse new boundaries if they step over
1503 ;; the submatch.
1504 (< (car newbounds) leftbound))
1505 ;; The new completed prefix does change the boundaries
1506 ;; of the completed substring.
1507 (setq suffix (substring afterpoint (cdr newbounds)))
1508 (setq string
1509 (concat (substring newbeforepoint (car newbounds))
1510 (substring afterpoint 0 (cdr newbounds))))
1511 (setq between (substring newbeforepoint leftbound
1512 (car newbounds)))
1513 (setq pattern (completion-pcm--string->pattern
1514 string
1515 (- (length newbeforepoint)
1516 (car newbounds)))))
1517 (dolist (submatch suball)
1518 (setq all (nconc (mapcar
1519 (lambda (s) (concat submatch between s))
1520 (funcall filter
1521 (completion-pcm--all-completions
1522 (concat subprefix submatch between)
1523 pattern table pred)))
1524 all)))
1525 ;; FIXME: This can come in handy for try-completion,
1526 ;; but isn't right for all-completions, since it lists
1527 ;; invalid completions.
1528 ;; (unless all
1529 ;; ;; Even though we found expansions in the prefix, none
1530 ;; ;; leads to a valid completion.
1531 ;; ;; Let's keep the expansions, tho.
1532 ;; (dolist (submatch suball)
1533 ;; (push (concat submatch between newsubstring) all)))
1534 ))
1535 (setq pattern (append subpat (list 'any (string sep))
1536 (if between (list between)) pattern))
1537 (setq prefix subprefix)))))
1538 (if (and (null all) firsterror)
1539 (signal (car firsterror) (cdr firsterror))
1540 (list pattern all prefix suffix)))))
1541
1542 (defun completion-pcm-all-completions (string table pred point)
1543 (destructuring-bind (pattern all &optional prefix suffix)
1544 (completion-pcm--find-all-completions string table pred point)
1545 (when all
1546 (nconc (completion-pcm--hilit-commonality pattern all)
1547 (length prefix)))))
1548
1549 (defun completion-pcm--merge-completions (strs pattern)
1550 "Extract the commonality in STRS, with the help of PATTERN."
1551 (cond
1552 ((null (cdr strs)) (list (car strs)))
1553 (t
1554 (let ((re (completion-pcm--pattern->regex pattern 'group))
1555 (ccs ())) ;Chopped completions.
1556
1557 ;; First chop each string into the parts corresponding to each
1558 ;; non-constant element of `pattern', using regexp-matching.
1559 (let ((case-fold-search completion-ignore-case))
1560 (dolist (str strs)
1561 (unless (string-match re str)
1562 (error "Internal error: %s doesn't match %s" str re))
1563 (let ((chopped ())
1564 (i 1))
1565 (while (match-beginning i)
1566 (push (match-string i str) chopped)
1567 (setq i (1+ i)))
1568 ;; Add the text corresponding to the implicit trailing `any'.
1569 (push (substring str (match-end 0)) chopped)
1570 (push (nreverse chopped) ccs))))
1571
1572 ;; Then for each of those non-constant elements, extract the
1573 ;; commonality between them.
1574 (let ((res ()))
1575 ;; Make the implicit `any' explicit. We could make it explicit
1576 ;; everywhere, but it would slow down regexp-matching a little bit.
1577 (dolist (elem (append pattern '(any)))
1578 (if (stringp elem)
1579 (push elem res)
1580 (let ((comps ()))
1581 (dolist (cc (prog1 ccs (setq ccs nil)))
1582 (push (car cc) comps)
1583 (push (cdr cc) ccs))
1584 (let* ((prefix (try-completion "" comps))
1585 (unique (or (and (eq prefix t) (setq prefix ""))
1586 (eq t (try-completion prefix comps)))))
1587 (unless (equal prefix "") (push prefix res))
1588 ;; If there's only one completion, `elem' is not useful
1589 ;; any more: it can only match the empty string.
1590 ;; FIXME: in some cases, it may be necessary to turn an
1591 ;; `any' into a `star' because the surrounding context has
1592 ;; changed such that string->pattern wouldn't add an `any'
1593 ;; here any more.
1594 (unless unique (push elem res))))))
1595 ;; We return it in reverse order.
1596 res)))))
1597
1598 (defun completion-pcm--pattern->string (pattern)
1599 (mapconcat (lambda (x) (cond
1600 ((stringp x) x)
1601 ((eq x 'star) "*")
1602 ((eq x 'any) "")
1603 ((eq x 'point) "")))
1604 pattern
1605 ""))
1606
1607 ;; We want to provide the functionality of `try', but we use `all'
1608 ;; and then merge it. In most cases, this works perfectly, but
1609 ;; if the completion table doesn't consider the same completions in
1610 ;; `try' as in `all', then we have a problem. The most common such
1611 ;; case is for filename completion where completion-ignored-extensions
1612 ;; is only obeyed by the `try' code. We paper over the difference
1613 ;; here. Note that it is not quite right either: if the completion
1614 ;; table uses completion-table-in-turn, this filtering may take place
1615 ;; too late to correctly fallback from the first to the
1616 ;; second alternative.
1617 (defun completion-pcm--filename-try-filter (all)
1618 "Filter to adjust `all' file completion to the behavior of `try'."
1619 (when all
1620 (let ((try ())
1621 (re (concat "\\(?:\\`\\.\\.?/\\|"
1622 (regexp-opt completion-ignored-extensions)
1623 "\\)\\'")))
1624 (dolist (f all)
1625 (unless (string-match re f) (push f try)))
1626 (or try all))))
1627
1628
1629 (defun completion-pcm--merge-try (pattern all prefix suffix)
1630 (cond
1631 ((not (consp all)) all)
1632 ((and (not (consp (cdr all))) ;Only one completion.
1633 ;; Ignore completion-ignore-case here.
1634 (equal (completion-pcm--pattern->string pattern) (car all)))
1635 t)
1636 (t
1637 (let* ((mergedpat (completion-pcm--merge-completions all pattern))
1638 ;; `mergedpat' is in reverse order. Place new point (by
1639 ;; order of preference) either at the old point, or at
1640 ;; the last place where there's something to choose, or
1641 ;; at the very end.
1642 (pointpat (or (memq 'point mergedpat) (memq 'any mergedpat)
1643 mergedpat))
1644 ;; New pos from the start.
1645 (newpos (length (completion-pcm--pattern->string pointpat)))
1646 ;; Do it afterwards because it changes `pointpat' by sideeffect.
1647 (merged (completion-pcm--pattern->string (nreverse mergedpat))))
1648
1649 (setq suffix (completion--merge-suffix merged newpos suffix))
1650 (cons (concat prefix merged suffix) (+ newpos (length prefix)))))))
1651
1652 (defun completion-pcm-try-completion (string table pred point)
1653 (destructuring-bind (pattern all prefix suffix)
1654 (completion-pcm--find-all-completions
1655 string table pred point
1656 (if minibuffer-completing-file-name
1657 'completion-pcm--filename-try-filter))
1658 (completion-pcm--merge-try pattern all prefix suffix)))
1659
1660
1661 (provide 'minibuffer)
1662
1663 ;; arch-tag: ef8a0a15-1080-4790-a754-04017c02f08f
1664 ;;; minibuffer.el ends here