Move provide to end of file for icomplete
[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 (defgroup icomplete nil
62 "Show completions dynamically in minibuffer."
63 :prefix "icomplete-"
64 :group 'minibuffer)
65
66 (defvar icomplete-prospects-length 80)
67 (make-obsolete-variable
68 'icomplete-prospects-length 'icomplete-prospects-height "23.1")
69
70 (defcustom icomplete-separator " | "
71 "String used by icomplete to separate alternatives in the minibuffer."
72 :type 'string
73 :version "24.4")
74
75 (defcustom icomplete-hide-common-prefix t
76 "When non-nil, hide common prefix from completion candidates.
77 When nil, show candidates in full."
78 :type 'boolean
79 :version "24.4"
80 :group 'icomplete)
81
82 (defface icomplete-first-match '((t :weight bold))
83 "Face used by icomplete for highlighting first match."
84 :version "24.4"
85 :group 'icomplete)
86
87 ;;;_* User Customization variables
88 (defcustom icomplete-prospects-height
89 ;; 20 is an estimated common size for the prompt + minibuffer content, to
90 ;; try to guess the number of lines used up by icomplete-prospects-length.
91 (+ 1 (/ (+ icomplete-prospects-length 20) (window-width)))
92 "Maximum number of lines to use in the minibuffer."
93 :type 'integer
94 :group 'icomplete
95 :version "23.1")
96
97 (defcustom icomplete-compute-delay .3
98 "Completions-computation stall, used only with large-number completions.
99 See `icomplete-delay-completions-threshold'."
100 :type 'number
101 :group 'icomplete)
102
103 (defcustom icomplete-delay-completions-threshold 400
104 "Pending-completions number over which to apply `icomplete-compute-delay'."
105 :type 'integer
106 :group 'icomplete)
107
108 (defcustom icomplete-max-delay-chars 3
109 "Maximum number of initial chars to apply icomplete compute delay."
110 :type 'integer
111 :group 'icomplete)
112
113 (defvar icomplete-in-buffer nil
114 "If non-nil, also use Icomplete when completing in non-mini buffers.")
115
116 (defcustom icomplete-minibuffer-setup-hook nil
117 "Icomplete-specific customization of minibuffer setup.
118
119 This hook is run during minibuffer setup if icomplete is active.
120 It is intended for use in customizing icomplete for interoperation
121 with other features and packages. For instance:
122
123 \(add-hook 'icomplete-minibuffer-setup-hook
124 \(function
125 \(lambda ()
126 \(make-local-variable 'max-mini-window-height)
127 \(setq max-mini-window-height 3))))
128
129 will constrain Emacs to a maximum minibuffer height of 3 lines when
130 icompletion is occurring."
131 :type 'hook
132 :group 'icomplete)
133
134
135 ;;;_* Initialization
136
137 ;;;_ + Internal Variables
138 ;;;_ = icomplete-eoinput nil
139 (defvar icomplete-overlay (make-overlay (point-min) (point-min) nil t t)
140 "Overlay used to display the list of completions.")
141
142 (defun icomplete-pre-command-hook ()
143 (let ((non-essential t))
144 (icomplete-tidy)))
145
146 (defun icomplete-post-command-hook ()
147 (let ((non-essential t)) ;E.g. don't prompt for password!
148 (icomplete-exhibit)))
149
150 ;;;_ = icomplete-with-completion-tables
151 (defcustom icomplete-with-completion-tables t
152 "Specialized completion tables with which icomplete should operate.
153
154 Icomplete does not operate with any specialized completion tables
155 except those on this list."
156 :version "24.4"
157 :type '(choice (const :tag "All" t)
158 (repeat function)))
159
160 (defvar icomplete-minibuffer-map
161 (let ((map (make-sparse-keymap)))
162 (define-key map [?\M-\t] 'minibuffer-force-complete)
163 (define-key map [?\C-j] 'minibuffer-force-complete-and-exit)
164 (define-key map [?\C-.] 'icomplete-forward-completions)
165 (define-key map [?\C-,] 'icomplete-backward-completions)
166 map))
167
168 (defun icomplete-forward-completions ()
169 "Step forward completions by one entry.
170 Second entry becomes the first and can be selected with
171 `minibuffer-force-complete-and-exit'."
172 (interactive)
173 (let* ((beg (icomplete--field-beg))
174 (end (icomplete--field-end))
175 (comps (completion-all-sorted-completions beg end))
176 (last (last comps)))
177 (when comps
178 (setcdr last (cons (car comps) (cdr last)))
179 (completion--cache-all-sorted-completions beg end (cdr comps)))))
180
181 (defun icomplete-backward-completions ()
182 "Step backward completions by one entry.
183 Last entry becomes the first and can be selected with
184 `minibuffer-force-complete-and-exit'."
185 (interactive)
186 (let* ((beg (icomplete--field-beg))
187 (end (icomplete--field-end))
188 (comps (completion-all-sorted-completions beg end))
189 (last-but-one (last comps 2))
190 (last (cdr last-but-one)))
191 (when (consp last) ; At least two elements in comps
192 (setcdr last-but-one (cdr last))
193 (push (car last) comps)
194 (completion--cache-all-sorted-completions beg end comps))))
195
196 ;;;_ > icomplete-mode (&optional prefix)
197 ;;;###autoload
198 (define-minor-mode icomplete-mode
199 "Toggle incremental minibuffer completion (Icomplete mode).
200 With a prefix argument ARG, enable Icomplete mode if ARG is
201 positive, and disable it otherwise. If called from Lisp, enable
202 the mode if ARG is omitted or nil."
203 :global t :group 'icomplete
204 (remove-hook 'minibuffer-setup-hook #'icomplete-minibuffer-setup)
205 (remove-hook 'completion-in-region-mode-hook #'icomplete--in-region-setup)
206 (when icomplete-mode
207 (when icomplete-in-buffer
208 (add-hook 'completion-in-region-mode-hook #'icomplete--in-region-setup))
209 (add-hook 'minibuffer-setup-hook #'icomplete-minibuffer-setup)))
210
211 (defun icomplete--completion-table ()
212 (if (window-minibuffer-p) minibuffer-completion-table
213 (or (nth 2 completion-in-region--data)
214 (message "In %S (w=%S): %S"
215 (current-buffer) (selected-window) (window-minibuffer-p)))))
216 (defun icomplete--completion-predicate ()
217 (if (window-minibuffer-p) minibuffer-completion-predicate
218 (nth 3 completion-in-region--data)))
219 (defun icomplete--field-string ()
220 (if (window-minibuffer-p) (minibuffer-contents)
221 (buffer-substring-no-properties
222 (nth 0 completion-in-region--data)
223 (nth 1 completion-in-region--data))))
224 (defun icomplete--field-beg ()
225 (if (window-minibuffer-p) (minibuffer-prompt-end)
226 (nth 0 completion-in-region--data)))
227 (defun icomplete--field-end ()
228 (if (window-minibuffer-p) (point-max)
229 (nth 1 completion-in-region--data)))
230
231 ;;;_ > icomplete-simple-completing-p ()
232 (defun icomplete-simple-completing-p ()
233 "Non-nil if current window is minibuffer that's doing simple completion.
234
235 Conditions are:
236 the selected window is a minibuffer,
237 and not in the middle of macro execution,
238 and the completion table is not a function (which would
239 indicate some non-standard, non-simple completion mechanism,
240 like file-name and other custom-func completions)."
241
242 (unless executing-kbd-macro
243 (let ((table (icomplete--completion-table)))
244 (and table
245 (or (not (functionp table))
246 (eq icomplete-with-completion-tables t)
247 (member table icomplete-with-completion-tables))))))
248
249 ;;;_ > icomplete-minibuffer-setup ()
250 (defun icomplete-minibuffer-setup ()
251 "Run in minibuffer on activation to establish incremental completion.
252 Usually run by inclusion in `minibuffer-setup-hook'."
253 (when (and icomplete-mode (icomplete-simple-completing-p))
254 (set (make-local-variable 'completion-show-inline-help) nil)
255 (use-local-map (make-composed-keymap icomplete-minibuffer-map
256 (current-local-map)))
257 (add-hook 'pre-command-hook #'icomplete-pre-command-hook nil t)
258 (add-hook 'post-command-hook #'icomplete-post-command-hook nil t)
259 (run-hooks 'icomplete-minibuffer-setup-hook)))
260
261 (defvar icomplete--in-region-buffer nil)
262
263 (defun icomplete--in-region-setup ()
264 (when (or (not completion-in-region-mode)
265 (and icomplete--in-region-buffer
266 (not (eq icomplete--in-region-buffer (current-buffer)))))
267 (with-current-buffer (or icomplete--in-region-buffer (current-buffer))
268 (setq icomplete--in-region-buffer nil)
269 (delete-overlay icomplete-overlay)
270 (kill-local-variable 'completion-show-inline-help)
271 (remove-hook 'pre-command-hook 'icomplete-pre-command-hook t)
272 (remove-hook 'post-command-hook 'icomplete-post-command-hook t)
273 (message nil)))
274 (when (and completion-in-region-mode
275 icomplete-mode (icomplete-simple-completing-p))
276 (setq icomplete--in-region-buffer (current-buffer))
277 (set (make-local-variable 'completion-show-inline-help) nil)
278 (let ((tem (assq 'completion-in-region-mode
279 minor-mode-overriding-map-alist)))
280 (unless (memq icomplete-minibuffer-map (cdr tem))
281 (setcdr tem (make-composed-keymap icomplete-minibuffer-map
282 (cdr tem)))))
283 (add-hook 'pre-command-hook 'icomplete-pre-command-hook nil t)
284 (add-hook 'post-command-hook 'icomplete-post-command-hook nil t)))
285 \f
286
287
288 ;;;_* Completion
289
290 ;;;_ > icomplete-tidy ()
291 (defun icomplete-tidy ()
292 "Remove completions display \(if any) prior to new user input.
293 Should be run in on the minibuffer `pre-command-hook'. See `icomplete-mode'
294 and `minibuffer-setup-hook'."
295 (delete-overlay icomplete-overlay))
296
297 ;;;_ > icomplete-exhibit ()
298 (defun icomplete-exhibit ()
299 "Insert icomplete completions display.
300 Should be run via minibuffer `post-command-hook'. See `icomplete-mode'
301 and `minibuffer-setup-hook'."
302 (when (and icomplete-mode
303 (icomplete-simple-completing-p)) ;Shouldn't be necessary.
304 (save-excursion
305 (goto-char (point-max))
306 ; Insert the match-status information:
307 (if (and (> (icomplete--field-end) (icomplete--field-beg))
308 buffer-undo-list ; Wait for some user input.
309 (or
310 ;; Don't bother with delay after certain number of chars:
311 (> (- (point) (icomplete--field-beg))
312 icomplete-max-delay-chars)
313 ;; Don't delay if the completions are known.
314 completion-all-sorted-completions
315 ;; Don't delay if alternatives number is small enough:
316 (and (sequencep (icomplete--completion-table))
317 (< (length (icomplete--completion-table))
318 icomplete-delay-completions-threshold))
319 ;; Delay - give some grace time for next keystroke, before
320 ;; embarking on computing completions:
321 (sit-for icomplete-compute-delay)))
322 (let* ((field-string (icomplete--field-string))
323 (text (while-no-input
324 (icomplete-completions
325 field-string
326 (icomplete--completion-table)
327 (icomplete--completion-predicate)
328 (if (window-minibuffer-p)
329 (not minibuffer-completion-confirm)))))
330 (buffer-undo-list t)
331 deactivate-mark)
332 ;; Do nothing if while-no-input was aborted.
333 (when (stringp text)
334 (move-overlay icomplete-overlay (point) (point) (current-buffer))
335 ;; The current C cursor code doesn't know to use the overlay's
336 ;; marker's stickiness to figure out whether to place the cursor
337 ;; before or after the string, so let's spoon-feed it the pos.
338 (put-text-property 0 1 'cursor t text)
339 (overlay-put icomplete-overlay 'after-string text)))))))
340
341 ;;;_ > icomplete-completions (name candidates predicate require-match)
342 (defun icomplete-completions (name candidates predicate require-match)
343 "Identify prospective candidates for minibuffer completion.
344
345 The display is updated with each minibuffer keystroke during
346 minibuffer completion.
347
348 Prospective completion suffixes (if any) are displayed, bracketed by
349 one of \(), \[], or \{} pairs. The choice of brackets is as follows:
350
351 \(...) - a single prospect is identified and matching is enforced,
352 \[...] - a single prospect is identified but matching is optional, or
353 \{...} - multiple prospects, separated by commas, are indicated, and
354 further input is required to distinguish a single one.
355
356 The displays for unambiguous matches have ` [Matched]' appended
357 \(whether complete or not), or ` \[No matches]', if no eligible
358 matches exist. \(Keybindings for uniquely matched commands
359 are exhibited within the square braces.)"
360
361 (let* ((minibuffer-completion-table candidates)
362 (minibuffer-completion-predicate predicate)
363 (md (completion--field-metadata (icomplete--field-beg)))
364 (comps (completion-all-sorted-completions
365 (icomplete--field-beg) (icomplete--field-end)))
366 (last (if (consp comps) (last comps)))
367 (base-size (cdr last))
368 (open-bracket (if require-match "(" "["))
369 (close-bracket (if require-match ")" "]")))
370 ;; `concat'/`mapconcat' is the slow part.
371 (if (not (consp comps))
372 (progn ;;(debug (format "Candidates=%S field=%S" candidates name))
373 (format " %sNo matches%s" open-bracket close-bracket))
374 (if last (setcdr last nil))
375 (let* ((most-try
376 (if (and base-size (> base-size 0))
377 (completion-try-completion
378 name candidates predicate (length name) md)
379 ;; If the `comps' are 0-based, the result should be
380 ;; the same with `comps'.
381 (completion-try-completion
382 name comps nil (length name) md)))
383 (most (if (consp most-try) (car most-try)
384 (if most-try (car comps) "")))
385 ;; Compare name and most, so we can determine if name is
386 ;; a prefix of most, or something else.
387 (compare (compare-strings name nil nil
388 most nil nil completion-ignore-case))
389 (determ (unless (or (eq t compare) (eq t most-try)
390 (= (setq compare (1- (abs compare)))
391 (length most)))
392 (concat open-bracket
393 (cond
394 ((= compare (length name))
395 ;; Typical case: name is a prefix.
396 (substring most compare))
397 ;; Don't bother truncating if it doesn't gain
398 ;; us at least 2 columns.
399 ((< compare 3) most)
400 (t (concat "…" (substring most compare))))
401 close-bracket)))
402 ;;"-prospects" - more than one candidate
403 (prospects-len (+ (string-width
404 (or determ (concat open-bracket close-bracket)))
405 (string-width icomplete-separator)
406 3 ;; take {…} into account
407 (string-width (buffer-string))))
408 (prospects-max
409 ;; Max total length to use, including the minibuffer content.
410 (* (+ icomplete-prospects-height
411 ;; If the minibuffer content already uses up more than
412 ;; one line, increase the allowable space accordingly.
413 (/ prospects-len (window-width)))
414 (window-width)))
415 ;; Find the common prefix among `comps'.
416 ;; We can't use the optimization below because its assumptions
417 ;; aren't always true, e.g. when completion-cycling (bug#10850):
418 ;; (if (eq t (compare-strings (car comps) nil (length most)
419 ;; most nil nil completion-ignore-case))
420 ;; ;; Common case.
421 ;; (length most)
422 ;; Else, use try-completion.
423 (prefix (when icomplete-hide-common-prefix
424 (try-completion "" comps)))
425 (prefix-len
426 (and (stringp prefix)
427 ;; Only hide the prefix if the corresponding info
428 ;; is already displayed via `most'.
429 (string-prefix-p prefix most t)
430 (length prefix))) ;;)
431 prospects comp limit)
432 (if (or (eq most-try t) (not (consp (cdr comps))))
433 (setq prospects nil)
434 (when (member name comps)
435 ;; NAME is complete but not unique. This scenario poses
436 ;; following UI issues:
437 ;;
438 ;; - When `icomplete-hide-common-prefix' is non-nil, NAME
439 ;; is stripped empty. This would make the entry
440 ;; inconspicuous.
441 ;;
442 ;; - Due to sorting of completions, NAME may not be the
443 ;; first of the prospects and could be hidden deep in
444 ;; the displayed string.
445 ;;
446 ;; - Because of `icomplete-prospects-height' , NAME may
447 ;; not even be displayed to the user.
448 ;;
449 ;; To circumvent all the above problems, provide a visual
450 ;; cue to the user via an "empty string" in the try
451 ;; completion field.
452 (setq determ (concat open-bracket "" close-bracket)))
453 ;; Compute prospects for display.
454 (while (and comps (not limit))
455 (setq comp
456 (if prefix-len (substring (car comps) prefix-len) (car comps))
457 comps (cdr comps))
458 (setq prospects-len
459 (+ (string-width comp)
460 (string-width icomplete-separator)
461 prospects-len))
462 (if (< prospects-len prospects-max)
463 (push comp prospects)
464 (setq limit t))))
465 (setq prospects (nreverse prospects))
466 ;; Decorate first of the prospects.
467 (when prospects
468 (let ((first (copy-sequence (pop prospects))))
469 (put-text-property 0 (length first)
470 'face 'icomplete-first-match first)
471 (push first prospects)))
472 ;; Restore the base-size info, since completion-all-sorted-completions
473 ;; is cached.
474 (if last (setcdr last base-size))
475 (if prospects
476 (concat determ
477 "{"
478 (mapconcat 'identity prospects icomplete-separator)
479 (and limit (concat icomplete-separator "…"))
480 "}")
481 (concat determ " [Matched]"))))))
482
483 ;;;_* Provide
484 (provide 'icomplete)
485
486 ;;_* Local emacs vars.
487 ;;Local variables:
488 ;;allout-layout: (-2 :)
489 ;;End:
490
491 ;;; icomplete.el ends here