1 ;;; ivy.el --- Incremental Vertical completYon -*- lexical-binding: t -*-
3 ;; Copyright (C) 2015 Free Software Foundation, Inc.
5 ;; Author: Oleh Krehel <ohwoeowho@gmail.com>
6 ;; URL: https://github.com/abo-abo/swiper
8 ;; Package-Requires: ((emacs "24.1"))
11 ;; This file is part of GNU Emacs.
13 ;; This file is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 3, or (at your option)
18 ;; This program is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; For a full copy of the GNU General Public License
24 ;; see <http://www.gnu.org/licenses/>.
28 ;; This package provides `ivy-read' as an alternative to
29 ;; `completing-read' and similar functions.
31 ;; There's no intricate code to determine the best candidate.
32 ;; Instead, the user can navigate to it with `ivy-next-line' and
33 ;; `ivy-previous-line'.
35 ;; The matching is done by splitting the input text by spaces and
36 ;; re-building it into a regex.
37 ;; So "for example" is transformed into "\\(for\\).*\\(example\\)".
44 "Incremental vertical completion."
47 (defface ivy-current-match
48 '((t (:inherit highlight)))
49 "Face used by Ivy for highlighting first match.")
51 (defcustom ivy-height 10
52 "Number of lines for the minibuffer window."
55 (defcustom ivy-count-format "%-4d "
56 "The style of showing the current candidate count for `ivy-read'.
57 Set this to nil if you don't want the count."
60 (defcustom ivy-wrap nil
61 "Whether to wrap around after the first and last candidate."
64 (defcustom ivy-on-del-error-function 'minibuffer-keyboard-quit
65 "The handler for when `ivy-backward-delete-char' throws.
66 This is usually meant as a quick exit out of the minibuffer."
72 (defvar ivy-minibuffer-map
73 (let ((map (make-sparse-keymap)))
74 (define-key map (kbd "C-m") 'ivy-done)
75 (define-key map (kbd "C-n") 'ivy-next-line)
76 (define-key map (kbd "C-p") 'ivy-previous-line)
77 (define-key map (kbd "C-s") 'ivy-next-line-or-history)
78 (define-key map (kbd "C-r") 'ivy-previous-line-or-history)
79 (define-key map (kbd "SPC") 'self-insert-command)
80 (define-key map (kbd "DEL") 'ivy-backward-delete-char)
81 (define-key map (kbd "M-<") 'ivy-beginning-of-buffer)
82 (define-key map (kbd "M->") 'ivy-end-of-buffer)
83 (define-key map (kbd "M-n") 'ivy-next-history-element)
84 (define-key map (kbd "M-p") 'ivy-previous-history-element)
85 (define-key map (kbd "C-g") 'minibuffer-keyboard-quit)
87 "Keymap used in the minibuffer.")
89 (defvar ivy-history nil
90 "History list of candidates entered in the minibuffer.
92 Maximum length of the history list is determined by the value
93 of `history-length', which see.")
95 (defvar ivy-require-match t
96 "Store require-match. See `completing-read'.")
100 "Exit the minibuffer with the selected candidate."
102 (delete-minibuffer-contents)
103 (if (zerop ivy--length)
104 (when (memq ivy-require-match '(nil confirm confirm-after-completion))
106 (setq ivy-exit 'done))
107 (insert ivy--current)
108 (setq ivy-exit 'done))
111 (defun ivy-beginning-of-buffer ()
112 "Select the first completion candidate."
116 (defun ivy-end-of-buffer ()
117 "Select the last completion candidate."
119 (setq ivy--index (1- ivy--length)))
121 (defun ivy-next-line (&optional arg)
122 "Move cursor vertically down ARG candidates."
124 (setq arg (or arg 1))
125 (cl-incf ivy--index arg)
126 (when (>= ivy--index (1- ivy--length))
128 (ivy-beginning-of-buffer)
129 (setq ivy--index (1- ivy--length)))))
131 (defun ivy-next-line-or-history (&optional arg)
132 "Move cursor vertically down ARG candidates.
133 If the input is empty, select the previous history element instead."
135 (when (string= ivy-text "")
136 (ivy-previous-history-element 1))
139 (defun ivy-previous-line (&optional arg)
140 "Move cursor vertically up ARG candidates."
142 (setq arg (or arg 1))
143 (cl-decf ivy--index arg)
144 (when (< ivy--index 0)
147 (setq ivy--index 0))))
149 (defun ivy-previous-line-or-history (arg)
150 "Move cursor vertically up ARG candidates.
151 If the input is empty, select the previous history element instead."
153 (when (string= ivy-text "")
154 (ivy-previous-history-element 1))
155 (ivy-previous-line arg))
157 (defun ivy-previous-history-element (arg)
158 "Forward to `previous-history-element' with ARG."
160 (previous-history-element arg)
161 (move-end-of-line 1))
163 (defun ivy-next-history-element (arg)
164 "Forward to `next-history-element' with ARG."
166 (next-history-element arg)
167 (move-end-of-line 1))
169 (defun ivy-backward-delete-char ()
170 "Forward to `backward-delete-char'.
171 On error (read-only), call `ivy-on-del-error-function'."
174 (backward-delete-char 1)
176 (when ivy-on-del-error-function
177 (funcall ivy-on-del-error-function)))))
180 (defun ivy-read (prompt collection
181 &optional initial-input keymap preselect update-fn)
182 "Read a string in the minibuffer, with completion.
184 PROMPT is a string to prompt with; normally it ends in a colon
185 and a space. When PROMPT contains %d, it will be updated with
186 the current number of matching candidates.
187 See also `ivy-count-format'.
189 COLLECTION is a list of strings.
191 If INITIAL-INPUT is non-nil, insert it in the minibuffer initially.
193 KEYMAP is composed together with `ivy-minibuffer-map'.
195 If PRESELECT is non-nil select the corresponding candidate out of
196 the ones that match INITIAL-INPUT.
198 UPDATE-FN is called each time the current candidate(s) is changed."
199 (cl-case (length collection)
205 (ivy--preselect-index
206 collection initial-input preselect))
208 (setq ivy--old-re nil)
209 (setq ivy--old-cands nil)
211 (setq ivy--all-candidates collection)
212 (setq ivy--update-fn update-fn)
214 (setq ivy--default (or (thing-at-point 'symbol) ""))
216 (cond ((string-match "%.*d" prompt)
218 ((string-match "%.*d" ivy-count-format)
219 (concat ivy-count-format prompt))
222 (setq ivy--action nil)
225 (minibuffer-with-setup-hook
226 #'ivy--minibuffer-setup
227 (let ((res (read-from-minibuffer
230 (make-composed-keymap keymap ivy-minibuffer-map)
233 (when (eq ivy-exit 'done)
236 (cons ivy-text (delete ivy-text ivy-history)))
238 (remove-hook 'post-command-hook #'ivy--exhibit))
240 (funcall ivy--action))))))
242 (defun ivy-completing-read (prompt collection
243 &optional predicate require-match initial-input
244 _history def _inherit-input-method)
245 "Read a string in the minibuffer, with completion.
247 This is an interface that conforms to `completing-read', so that
248 it can be used for `completing-read-function'.
250 PROMPT is a string to prompt with; normally it ends in a colon and a space.
251 COLLECTION can be a list of strings, an alist, an obarray or a hash table.
252 PREDICATE limits completion to a subset of COLLECTION.
254 REQUIRE-MATCH is stored into `ivy-require-match'. See `completing-read'.
255 INITIAL-INPUT is a string that can be inserted into the minibuffer initially.
256 _HISTORY is ignored for now.
257 DEF is the default value.
258 _INHERIT-INPUT-METHOD is ignored for now.
260 The history, defaults and input-method arguments are ignored for now."
261 (cond ((or (functionp collection)
262 (vectorp collection))
263 (setq collection (all-completions "" collection predicate))
264 ;; find-file is problematic
265 (setq initial-input nil))
266 ((hash-table-p collection)
267 (error "Hash table as a collection unsupported"))
268 ((listp (car collection))
269 (setq collection (all-completions "" collection predicate))))
271 (setq def (car def)))
272 (setq ivy-require-match require-match)
273 (ivy-read prompt collection initial-input nil def))
276 (define-minor-mode ivy-mode
277 "Toggle Ivy mode on or off.
278 With ARG, turn Ivy mode on if arg is positive, off otherwise.
279 Turning on Ivy mode will set `completing-read-function' to
280 `ivy-completing-read'."
285 (setq completing-read-function 'ivy-completing-read)
286 (setq completing-read-function 'completing-read-default)))
288 (defvar ivy--action nil
289 "Store a function to call at the end of `ivy--read'.")
291 (defun ivy--preselect-index (candidates initial-input preselect)
292 "Return the index in CANDIDATES filtered by INITIAL-INPUT for PRESELECT."
297 (string-match initial-input x))
301 (string-match preselect x))
305 "Stores the user's string as it is typed in.")
308 "Store 'done if the completion was successfully selected.
309 Otherwise, store nil.")
313 (defvar ivy--subexps 0
314 "Number of groups in the current `ivy--regex'.")
316 (defvar ivy--regex-hash
317 (make-hash-table :test 'equal)
318 "Store pre-computed regex.")
320 (defun ivy--regex (str)
321 "Re-build regex from STR in case it has a space."
322 (let ((hashed (gethash str ivy--regex-hash)))
325 (setq ivy--subexps (car hashed)))
327 (let ((subs (split-string str " +" t)))
328 (if (= (length subs) 1)
330 (setq ivy--subexps 0)
333 (setq ivy--subexps (length subs))
335 (lambda (x) (format "\\(%s\\)" x))
341 (defun ivy--minibuffer-setup ()
342 "Setup ivy completion in the minibuffer."
343 (set (make-local-variable 'completion-show-inline-help) nil)
344 (set (make-local-variable 'minibuffer-default-add-function)
346 (list ivy--default)))
347 (use-local-map (make-composed-keymap ivy-minibuffer-map
348 (current-local-map)))
349 (setq-local max-mini-window-height ivy-height)
350 (add-hook 'post-command-hook #'ivy--exhibit nil t)
351 ;; show completions with empty input
354 (defvar ivy--all-candidates nil
355 "Store the candidates passed to `ivy-read'.")
358 "Store the index of the current candidate.")
360 (defvar ivy--length 0
361 "Store the amount of viable candidates.")
363 (defvar ivy--current ""
364 "Current candidate.")
366 (defvar ivy--default nil
367 "Default initial input.")
369 (defvar ivy--update-fn nil
370 "Current function to call when current candidate(s) update.")
373 "Return the current minibuffer input."
374 ;; assume one-line minibuffer input
375 (buffer-substring-no-properties
376 (minibuffer-prompt-end)
377 (line-end-position)))
379 (defun ivy--cleanup ()
380 "Delete the displayed completion candidates."
382 (goto-char (minibuffer-prompt-end))
383 (delete-region (line-end-position) (point-max))))
385 (defvar ivy--prompt nil
386 "Store the format-style prompt.
387 When non-nil, it should contain one %d.")
389 (defun ivy--insert-prompt ()
390 "Update the prompt according to `ivy--prompt'."
392 (let ((inhibit-read-only t)
393 (n-str (format ivy--prompt ivy--length)))
395 (goto-char (point-min))
396 (delete-region (point-min) (minibuffer-prompt-end))
399 '(front-sticky t rear-nonsticky t field t read-only t face minibuffer-prompt)
402 ;; get out of the prompt area
403 (constrain-to-field nil (point-max)))))
405 (defun ivy--exhibit ()
406 "Insert Ivy completions display.
407 Should be run via minibuffer `post-command-hook'."
408 (setq ivy-text (ivy--input))
410 (let ((text (ivy-completions
412 ivy--all-candidates))
416 (funcall ivy--update-fn))
418 ;; Do nothing if while-no-input was aborted.
424 (defvar ivy--old-re nil
425 "Store the old regexp.")
427 (defvar ivy--old-cands nil
428 "Store the candidates matched by `ivy--old-re'.")
430 (defun ivy--add-face (str face)
431 "Propertize STR with FACE.
432 `font-lock-append-text-property' is used, since it's better than
433 `propertize' or `add-face-text-property' in this case."
434 (font-lock-append-text-property 0 (length str) 'face face str)
437 (defun ivy-completions (name candidates)
438 "Return as text the current completions.
439 NAME is a string of words separated by spaces that is used to
441 CANDIDATES is a list of strings."
442 (let* ((re (ivy--regex name))
443 (cands (if (and (equal re ivy--old-re)
448 (lambda (x) (string-match re x))
450 (tail (nthcdr ivy--index ivy--old-cands))
453 (when (and tail ivy--old-cands)
454 (unless (and (not (equal re ivy--old-re))
455 (setq ivy--index (cl-position re cands :test 'equal)))
456 (while (and tail (null idx))
457 ;; Compare with eq to handle equal duplicates in cands
458 (setq idx (cl-position (pop tail) cands)))
459 (setq ivy--index (or idx 0))))
460 (setq ivy--old-re re)
461 (setq ivy--length (length cands))
462 (setq ivy--old-cands cands)
463 (when (>= ivy--index ivy--length)
464 (setq ivy--index (max (1- ivy--length) 0)))
467 (let* ((half-height (/ ivy-height 2))
468 (start (max 0 (- ivy--index half-height)))
469 (end (min (+ start (1- ivy-height)) ivy--length))
470 (cands (cl-subseq cands start end))
471 (index (min ivy--index half-height (1- (length cands)))))
472 (setq ivy--current (copy-sequence (nth index cands)))
473 (setf (nth index cands)
474 (ivy--add-face ivy--current 'ivy-current-match))
475 (let ((res (concat "\n" (mapconcat
477 (if (> (length s) ww)
478 (concat (substring s 0 (- ww 3)) "...")
481 (put-text-property 0 (length res) 'read-only nil res)