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