Merge from emacs-24; up to 2012-12-17T11:17:34Z!rgm@gnu.org
[bpt/emacs.git] / lisp / icomplete.el
1 ;;; icomplete.el --- minibuffer completion incremental feedback
2
3 ;; Copyright (C) 1992-1994, 1997, 1999, 2001-2013 Free Software
4 ;; Foundation, Inc.
5
6 ;; Author: Ken Manheimer <klm@i.am>
7 ;; Maintainer: Ken Manheimer <klm@i.am>
8 ;; Created: Mar 1993 Ken Manheimer, klm@nist.gov - first release to usenet
9 ;; Last update: Ken Manheimer <klm@i.am>, 11/18/1999.
10 ;; Keywords: help, abbrev
11
12 ;; This file is part of GNU Emacs.
13
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
18
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26
27 ;;; Commentary:
28
29 ;; Loading this package implements a more fine-grained minibuffer
30 ;; completion feedback scheme. Prospective completions are concisely
31 ;; indicated within the minibuffer itself, with each successive
32 ;; keystroke.
33
34 ;; See `icomplete-completions' docstring for a description of the
35 ;; icomplete display format.
36
37 ;; See the `icomplete-minibuffer-setup-hook' docstring for a means to
38 ;; customize icomplete setup for interoperation with other
39 ;; minibuffer-oriented packages.
40
41 ;; To activate icomplete mode, load the package and use the
42 ;; `icomplete-mode' function. You can subsequently deactivate it by
43 ;; invoking the function icomplete-mode with a negative prefix-arg
44 ;; (C-U -1 ESC-x icomplete-mode). Also, you can prevent activation of
45 ;; the mode during package load by first setting the variable
46 ;; `icomplete-mode' to nil. Icompletion can be enabled any time after
47 ;; the package is loaded by invoking icomplete-mode without a prefix
48 ;; arg.
49
50 ;; Thanks to everyone for their suggestions for refinements of this
51 ;; package. I particularly have to credit Michael Cook, who
52 ;; implemented an incremental completion style in his 'iswitch'
53 ;; functions that served as a model for icomplete. Some other
54 ;; contributors: Noah Friedman (restructuring as minor mode), Colin
55 ;; Rafferty (lemacs reconciliation), Lars Lindberg, RMS, and others.
56
57 ;; klm.
58
59 ;;; Code:
60
61 ;;;_* Provide
62 (provide 'icomplete)
63
64
65 (defgroup icomplete nil
66 "Show completions dynamically in minibuffer."
67 :prefix "icomplete-"
68 :group 'minibuffer)
69
70 (defvar icomplete-prospects-length 80)
71 (make-obsolete-variable
72 'icomplete-prospects-length 'icomplete-prospects-height "23.1")
73
74 (defcustom icomplete-separator " | "
75 "String used by icomplete to separate alternatives in the minibuffer."
76 :type 'string
77 :version "24.4")
78
79 ;;;_* User Customization variables
80 (defcustom icomplete-prospects-height
81 ;; 20 is an estimated common size for the prompt + minibuffer content, to
82 ;; try to guess the number of lines used up by icomplete-prospects-length.
83 (+ 1 (/ (+ icomplete-prospects-length 20) (window-width)))
84 "Maximum number of lines to use in the minibuffer."
85 :type 'integer
86 :group 'icomplete
87 :version "23.1")
88
89 (defcustom icomplete-compute-delay .3
90 "Completions-computation stall, used only with large-number completions.
91 See `icomplete-delay-completions-threshold'."
92 :type 'number
93 :group 'icomplete)
94
95 (defcustom icomplete-delay-completions-threshold 400
96 "Pending-completions number over which to apply `icomplete-compute-delay'."
97 :type 'integer
98 :group 'icomplete)
99
100 (defcustom icomplete-max-delay-chars 3
101 "Maximum number of initial chars to apply icomplete compute delay."
102 :type 'integer
103 :group 'icomplete)
104
105 (defcustom icomplete-minibuffer-setup-hook nil
106 "Icomplete-specific customization of minibuffer setup.
107
108 This hook is run during minibuffer setup if icomplete is active.
109 It is intended for use in customizing icomplete for interoperation
110 with other features and packages. For instance:
111
112 \(add-hook 'icomplete-minibuffer-setup-hook
113 \(function
114 \(lambda ()
115 \(make-local-variable 'max-mini-window-height)
116 \(setq max-mini-window-height 3))))
117
118 will constrain Emacs to a maximum minibuffer height of 3 lines when
119 icompletion is occurring."
120 :type 'hook
121 :group 'icomplete)
122
123
124 ;;;_* Initialization
125
126 ;;;_ + Internal Variables
127 ;;;_ = icomplete-eoinput nil
128 (defvar icomplete-overlay (make-overlay (point-min) (point-min) nil t t)
129 "Overlay used to display the list of completions.")
130
131 ;;;_ = icomplete-pre-command-hook
132 (defvar icomplete-pre-command-hook nil
133 "Incremental-minibuffer-completion pre-command-hook.
134
135 Is run in minibuffer before user input when `icomplete-mode' is non-nil.
136 Use `icomplete-mode' function to set it up properly for incremental
137 minibuffer completion.")
138 (add-hook 'icomplete-pre-command-hook 'icomplete-tidy)
139 ;;;_ = icomplete-post-command-hook
140 (defvar icomplete-post-command-hook nil
141 "Incremental-minibuffer-completion post-command-hook.
142
143 Is run in minibuffer after user input when `icomplete-mode' is non-nil.
144 Use `icomplete-mode' function to set it up properly for incremental
145 minibuffer completion.")
146 (add-hook 'icomplete-post-command-hook 'icomplete-exhibit)
147
148 ;;;_ = icomplete-with-completion-tables
149 (defvar icomplete-with-completion-tables '(internal-complete-buffer)
150 "Specialized completion tables with which icomplete should operate.
151
152 Icomplete does not operate with any specialized completion tables
153 except those on this list.")
154
155 (defvar icomplete-minibuffer-map
156 (let ((map (make-sparse-keymap)))
157 (define-key map [?\M-\t] 'minibuffer-force-complete)
158 (define-key map [?\C-j] 'minibuffer-force-complete-and-exit)
159 (define-key map [?\C-s] 'icomplete-forward-completions)
160 (define-key map [?\C-r] 'icomplete-backward-completions)
161 map))
162
163 (defun icomplete-forward-completions ()
164 "Step forward completions by one entry.
165 Second entry becomes the first and can be selected with
166 `minibuffer-force-complete-and-exit'."
167 (interactive)
168 (let* ((comps (completion-all-sorted-completions))
169 (last (last comps)))
170 (when comps
171 (setcdr last (cons (car comps) (cdr last)))
172 (completion--cache-all-sorted-completions (cdr comps)))))
173
174 (defun icomplete-backward-completions ()
175 "Step backward completions by one entry.
176 Last entry becomes the first and can be selected with
177 `minibuffer-force-complete-and-exit'."
178 (interactive)
179 (let* ((comps (completion-all-sorted-completions))
180 (last-but-one (last comps 2))
181 (last (cdr last-but-one)))
182 (when (consp last) ; At least two elements in comps
183 (setcdr last-but-one (cdr last))
184 (push (car last) comps)
185 (completion--cache-all-sorted-completions comps))))
186
187 ;;;_ > icomplete-mode (&optional prefix)
188 ;;;###autoload
189 (define-minor-mode icomplete-mode
190 "Toggle incremental minibuffer completion (Icomplete mode).
191 With a prefix argument ARG, enable Icomplete mode if ARG is
192 positive, and disable it otherwise. If called from Lisp, enable
193 the mode if ARG is omitted or nil."
194 :global t :group 'icomplete
195 (if icomplete-mode
196 ;; The following is not really necessary after first time -
197 ;; no great loss.
198 (add-hook 'minibuffer-setup-hook 'icomplete-minibuffer-setup)
199 (remove-hook 'minibuffer-setup-hook 'icomplete-minibuffer-setup)))
200
201 ;;;_ > icomplete-simple-completing-p ()
202 (defun icomplete-simple-completing-p ()
203 "Non-nil if current window is minibuffer that's doing simple completion.
204
205 Conditions are:
206 the selected window is a minibuffer,
207 and not in the middle of macro execution,
208 and `minibuffer-completion-table' is not a symbol (which would
209 indicate some non-standard, non-simple completion mechanism,
210 like file-name and other custom-func completions)."
211
212 (and (window-minibuffer-p (selected-window))
213 (not executing-kbd-macro)
214 minibuffer-completion-table
215 (or (not (functionp minibuffer-completion-table))
216 (eq icomplete-with-completion-tables t)
217 (member minibuffer-completion-table
218 icomplete-with-completion-tables))))
219
220 ;;;_ > icomplete-minibuffer-setup ()
221 (defun icomplete-minibuffer-setup ()
222 "Run in minibuffer on activation to establish incremental completion.
223 Usually run by inclusion in `minibuffer-setup-hook'."
224 (when (and icomplete-mode (icomplete-simple-completing-p))
225 (set (make-local-variable 'completion-show-inline-help) nil)
226 (use-local-map (make-composed-keymap icomplete-minibuffer-map
227 (current-local-map)))
228 (add-hook 'pre-command-hook
229 (lambda () (let ((non-essential t))
230 (run-hooks 'icomplete-pre-command-hook)))
231 nil t)
232 (add-hook 'post-command-hook
233 (lambda () (let ((non-essential t)) ;E.g. don't prompt for password!
234 (run-hooks 'icomplete-post-command-hook)))
235 nil t)
236 (run-hooks 'icomplete-minibuffer-setup-hook)))
237 ;\f
238
239
240 ;;;_* Completion
241
242 ;;;_ > icomplete-tidy ()
243 (defun icomplete-tidy ()
244 "Remove completions display \(if any) prior to new user input.
245 Should be run in on the minibuffer `pre-command-hook'. See `icomplete-mode'
246 and `minibuffer-setup-hook'."
247 (delete-overlay icomplete-overlay))
248
249 ;;;_ > icomplete-exhibit ()
250 (defun icomplete-exhibit ()
251 "Insert icomplete completions display.
252 Should be run via minibuffer `post-command-hook'. See `icomplete-mode'
253 and `minibuffer-setup-hook'."
254 (when (and icomplete-mode (icomplete-simple-completing-p))
255 (save-excursion
256 (goto-char (point-max))
257 ; Insert the match-status information:
258 (if (and (> (point-max) (minibuffer-prompt-end))
259 buffer-undo-list ; Wait for some user input.
260 (or
261 ;; Don't bother with delay after certain number of chars:
262 (> (- (point) (field-beginning)) icomplete-max-delay-chars)
263 ;; Don't delay if the completions are known.
264 completion-all-sorted-completions
265 ;; Don't delay if alternatives number is small enough:
266 (and (sequencep minibuffer-completion-table)
267 (< (length minibuffer-completion-table)
268 icomplete-delay-completions-threshold))
269 ;; Delay - give some grace time for next keystroke, before
270 ;; embarking on computing completions:
271 (sit-for icomplete-compute-delay)))
272 (let ((text (while-no-input
273 (icomplete-completions
274 (field-string)
275 minibuffer-completion-table
276 minibuffer-completion-predicate
277 (not minibuffer-completion-confirm))))
278 (buffer-undo-list t)
279 deactivate-mark)
280 ;; Do nothing if while-no-input was aborted.
281 (when (stringp text)
282 (move-overlay icomplete-overlay (point) (point) (current-buffer))
283 ;; The current C cursor code doesn't know to use the overlay's
284 ;; marker's stickiness to figure out whether to place the cursor
285 ;; before or after the string, so let's spoon-feed it the pos.
286 (put-text-property 0 1 'cursor t text)
287 (overlay-put icomplete-overlay 'after-string text)))))))
288
289 ;;;_ > icomplete-completions (name candidates predicate require-match)
290 (defun icomplete-completions (name candidates predicate require-match)
291 "Identify prospective candidates for minibuffer completion.
292
293 The display is updated with each minibuffer keystroke during
294 minibuffer completion.
295
296 Prospective completion suffixes (if any) are displayed, bracketed by
297 one of \(), \[], or \{} pairs. The choice of brackets is as follows:
298
299 \(...) - a single prospect is identified and matching is enforced,
300 \[...] - a single prospect is identified but matching is optional, or
301 \{...} - multiple prospects, separated by commas, are indicated, and
302 further input is required to distinguish a single one.
303
304 The displays for unambiguous matches have ` [Matched]' appended
305 \(whether complete or not), or ` \[No matches]', if no eligible
306 matches exist. \(Keybindings for uniquely matched commands
307 are exhibited within the square braces.)"
308
309 (let* ((md (completion--field-metadata (field-beginning)))
310 (comps (completion-all-sorted-completions))
311 (last (if (consp comps) (last comps)))
312 (base-size (cdr last))
313 (open-bracket (if require-match "(" "["))
314 (close-bracket (if require-match ")" "]")))
315 ;; `concat'/`mapconcat' is the slow part.
316 (if (not (consp comps))
317 (format " %sNo matches%s" open-bracket close-bracket)
318 (if last (setcdr last nil))
319 (let* ((most-try
320 (if (and base-size (> base-size 0))
321 (completion-try-completion
322 name candidates predicate (length name) md)
323 ;; If the `comps' are 0-based, the result should be
324 ;; the same with `comps'.
325 (completion-try-completion
326 name comps nil (length name) md)))
327 (most (if (consp most-try) (car most-try)
328 (if most-try (car comps) "")))
329 ;; Compare name and most, so we can determine if name is
330 ;; a prefix of most, or something else.
331 (compare (compare-strings name nil nil
332 most nil nil completion-ignore-case))
333 (determ (unless (or (eq t compare) (eq t most-try)
334 (= (setq compare (1- (abs compare)))
335 (length most)))
336 (concat open-bracket
337 (cond
338 ((= compare (length name))
339 ;; Typical case: name is a prefix.
340 (substring most compare))
341 ;; Don't bother truncating if it doesn't gain
342 ;; us at least 2 columns.
343 ((< compare 3) most)
344 (t (concat "…" (substring most compare))))
345 close-bracket)))
346 ;;"-prospects" - more than one candidate
347 (prospects-len (+ (length determ)
348 (string-width icomplete-separator)
349 3 ;; take {…} into account
350 (string-width (buffer-string))))
351 (prospects-max
352 ;; Max total length to use, including the minibuffer content.
353 (* (+ icomplete-prospects-height
354 ;; If the minibuffer content already uses up more than
355 ;; one line, increase the allowable space accordingly.
356 (/ prospects-len (window-width)))
357 (window-width)))
358 (prefix-len
359 ;; Find the common prefix among `comps'.
360 ;; We can't use the optimization below because its assumptions
361 ;; aren't always true, e.g. when completion-cycling (bug#10850):
362 ;; (if (eq t (compare-strings (car comps) nil (length most)
363 ;; most nil nil completion-ignore-case))
364 ;; ;; Common case.
365 ;; (length most)
366 ;; Else, use try-completion.
367 (let ((comps-prefix (try-completion "" comps)))
368 (and (stringp comps-prefix)
369 (length comps-prefix)))) ;;)
370
371 prospects most-is-exact comp limit)
372 (if (eq most-try t) ;; (or (null (cdr comps))
373 (setq prospects nil)
374 (while (and comps (not limit))
375 (setq comp
376 (if prefix-len (substring (car comps) prefix-len) (car comps))
377 comps (cdr comps))
378 (cond ((string-equal comp "") (setq most-is-exact t))
379 ((member comp prospects))
380 (t (setq prospects-len
381 (+ (string-width comp)
382 (string-width icomplete-separator)
383 prospects-len))
384 (if (< prospects-len prospects-max)
385 (push comp prospects)
386 (setq limit t))))))
387 ;; Restore the base-size info, since completion-all-sorted-completions
388 ;; is cached.
389 (if last (setcdr last base-size))
390 (if prospects
391 (concat determ
392 "{"
393 (and most-is-exact
394 (substring icomplete-separator
395 (string-match "[^ ]" icomplete-separator)))
396 (mapconcat 'identity (nreverse prospects)
397 icomplete-separator)
398 (and limit (concat icomplete-separator "…"))
399 "}")
400 (concat determ " [Matched]"))))))
401
402 ;;_* Local emacs vars.
403 ;;Local variables:
404 ;;allout-layout: (-2 :)
405 ;;End:
406
407 ;;; icomplete.el ends here