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\\)".
42 "Incremental vertical completion."
45 (defface ivy-current-match
46 '((t (:inherit highlight)))
47 "Face used by Ivy for highlighting first match.")
49 (defcustom ivy-height 10
50 "Number of lines for the minibuffer window."
53 (defcustom ivy-count-format "%-4d "
54 "The style of showing the current candidate count for `ivy-read'.
55 Set this to nil if you don't want the count."
58 (defcustom ivy-wrap nil
59 "Whether to wrap around after the first and last candidate."
62 (defcustom ivy-on-del-error-function 'minibuffer-keyboard-quit
63 "The handler for when `ivy-backward-delete-char' throws.
64 This is usually meant as a quick exit out of the minibuffer."
70 (defvar ivy-minibuffer-map
71 (let ((map (make-sparse-keymap)))
72 (define-key map (kbd "C-m") 'ivy-done)
73 (define-key map (kbd "C-n") 'ivy-next-line)
74 (define-key map (kbd "C-p") 'ivy-previous-line)
75 (define-key map (kbd "C-s") 'ivy-next-line-or-history)
76 (define-key map (kbd "C-r") 'ivy-previous-line-or-history)
77 (define-key map (kbd "SPC") 'self-insert-command)
78 (define-key map (kbd "DEL") 'ivy-backward-delete-char)
79 (define-key map (kbd "M-<") 'ivy-beginning-of-buffer)
80 (define-key map (kbd "M->") 'ivy-end-of-buffer)
81 (define-key map (kbd "M-n") 'ivy-next-history-element)
82 (define-key map (kbd "M-p") 'ivy-previous-history-element)
83 (define-key map (kbd "C-g") 'minibuffer-keyboard-quit)
85 "Keymap used in the minibuffer.")
87 (defvar ivy-history nil
88 "History list of candidates entered in the minibuffer.
90 Maximum length of the history list is determined by the value
91 of `history-length', which see.")
93 (defvar ivy-require-match t
94 "Store require-match. See `completing-read'.")
98 "Exit the minibuffer with the selected candidate."
100 (delete-minibuffer-contents)
101 (if (zerop ivy--length)
102 (when (memq ivy-require-match '(nil confirm confirm-after-completion))
104 (setq ivy-exit 'done))
105 (insert ivy--current)
106 (setq ivy-exit 'done))
109 (defun ivy-beginning-of-buffer ()
110 "Select the first completion candidate."
114 (defun ivy-end-of-buffer ()
115 "Select the last completion candidate."
117 (setq ivy--index (1- ivy--length)))
119 (defun ivy-next-line (&optional arg)
120 "Move cursor vertically down ARG candidates."
122 (setq arg (or arg 1))
123 (cl-incf ivy--index arg)
124 (when (>= ivy--index (1- ivy--length))
126 (ivy-beginning-of-buffer)
127 (setq ivy--index (1- ivy--length)))))
129 (defun ivy-next-line-or-history (&optional arg)
130 "Move cursor vertically down ARG candidates.
131 If the input is empty, select the previous history element instead."
133 (when (string= ivy-text "")
134 (ivy-previous-history-element 1))
137 (defun ivy-previous-line (&optional arg)
138 "Move cursor vertically up ARG candidates."
140 (setq arg (or arg 1))
141 (cl-decf ivy--index arg)
142 (when (< ivy--index 0)
145 (setq ivy--index 0))))
147 (defun ivy-previous-line-or-history (arg)
148 "Move cursor vertically up ARG candidates.
149 If the input is empty, select the previous history element instead."
151 (when (string= ivy-text "")
152 (ivy-previous-history-element 1))
153 (ivy-previous-line arg))
155 (defun ivy-previous-history-element (arg)
156 "Forward to `previous-history-element' with ARG."
158 (previous-history-element arg)
159 (move-end-of-line 1))
161 (defun ivy-next-history-element (arg)
162 "Forward to `next-history-element' with ARG."
164 (next-history-element arg)
165 (move-end-of-line 1))
167 (defun ivy-backward-delete-char ()
168 "Forward to `backward-delete-char'.
169 On error (read-only), call `ivy-on-del-error-function'."
172 (backward-delete-char 1)
174 (when ivy-on-del-error-function
175 (funcall ivy-on-del-error-function)))))
178 (defun ivy-read (prompt collection
179 &optional initial-input keymap preselect update-fn)
180 "Read a string in the minibuffer, with completion.
182 PROMPT is a string to prompt with; normally it ends in a colon
183 and a space. When PROMPT contains %d, it will be updated with
184 the current number of matching candidates.
185 See also `ivy-count-format'.
187 COLLECTION is a list of strings.
189 If INITIAL-INPUT is non-nil, insert it in the minibuffer initially.
191 KEYMAP is composed together with `ivy-minibuffer-map'.
193 If PRESELECT is non-nil select the corresponding candidate out of
194 the ones that match INITIAL-INPUT.
196 UPDATE-FN is called each time the current candidate(s) is changed."
197 (cl-case (length collection)
203 (ivy--preselect-index
204 collection initial-input preselect))
206 (setq ivy--old-re nil)
207 (setq ivy--old-cands nil)
209 (setq ivy--all-candidates collection)
210 (setq ivy--update-fn update-fn)
212 (setq ivy--default (or (thing-at-point 'symbol) ""))
214 (cond ((string-match "%.*d" prompt)
216 ((string-match "%.*d" ivy-count-format)
217 (concat ivy-count-format prompt))
220 (setq ivy--action nil)
223 (minibuffer-with-setup-hook
224 #'ivy--minibuffer-setup
225 (let ((res (read-from-minibuffer
228 (make-composed-keymap keymap ivy-minibuffer-map)
231 (when (eq ivy-exit 'done)
234 (cons ivy-text (delete ivy-text ivy-history)))
236 (remove-hook 'post-command-hook #'ivy--exhibit))
238 (funcall ivy--action))))))
240 (defun ivy-completing-read (prompt collection
241 &optional predicate require-match initial-input
242 _history def _inherit-input-method)
243 "Read a string in the minibuffer, with completion.
245 This is an interface that conforms to `completing-read', so that
246 it can be used for `completing-read-function'.
248 PROMPT is a string to prompt with; normally it ends in a colon and a space.
249 COLLECTION can be a list of strings, an alist, an obarray or a hash table.
250 PREDICATE limits completion to a subset of COLLECTION.
252 REQUIRE-MATCH is stored into `ivy-require-match'. See `completing-read'.
253 INITIAL-INPUT is a string that can be inserted into the minibuffer initially.
254 _HISTORY is ignored for now.
255 DEF is the default value.
256 _INHERIT-INPUT-METHOD is ignored for now.
258 The history, defaults and input-method arguments are ignored for now."
259 (cond ((functionp collection)
260 (setq collection (all-completions "" collection))
261 (setq initial-input nil))
262 ((hash-table-p collection)
263 (error "Hash table as a collection unsupported"))
264 ((listp (car collection))
265 (setq collection (mapcar #'car collection))))
267 (setq collection (cl-remove-if-not predicate collection)))
269 (setq def (car def)))
270 (setq ivy-require-match require-match)
271 (ivy-read prompt collection initial-input nil def))
274 (define-minor-mode ivy-mode
275 "Toggle Ivy mode on or off.
276 With ARG, turn Ivy mode on if arg is positive, off otherwise.
277 Turning on Ivy mode will set `completing-read-function' to
278 `ivy-completing-read'."
283 (setq completing-read-function 'ivy-completing-read)
284 (setq completing-read-function 'completing-read-default)))
286 (defvar ivy--action nil
287 "Store a function to call at the end of `ivy--read'.")
289 (defun ivy--preselect-index (candidates initial-input preselect)
290 "Return the index in CANDIDATES filtered by INITIAL-INPUT for PRESELECT."
295 (string-match initial-input x))
299 (string-match preselect x))
303 "Stores the user's string as it is typed in.")
306 "Store 'done if the completion was successfully selected.
307 Otherwise, store nil.")
311 (defvar ivy--subexps 0
312 "Number of groups in the current `ivy--regex'.")
314 (defvar ivy--regex-hash
315 (make-hash-table :test 'equal)
316 "Store pre-computed regex.")
318 (defun ivy--regex (str)
319 "Re-build regex from STR in case it has a space."
320 (let ((hashed (gethash str ivy--regex-hash)))
323 (setq ivy--subexps (car hashed)))
325 (let ((subs (split-string str " +" t)))
326 (if (= (length subs) 1)
328 (setq ivy--subexps 0)
331 (setq ivy--subexps (length subs))
333 (lambda (x) (format "\\(%s\\)" x))
339 (defun ivy--minibuffer-setup ()
340 "Setup ivy completion in the minibuffer."
341 (set (make-local-variable 'completion-show-inline-help) nil)
342 (set (make-local-variable 'minibuffer-default-add-function)
344 (list ivy--default)))
345 (use-local-map (make-composed-keymap ivy-minibuffer-map
346 (current-local-map)))
347 (setq-local max-mini-window-height ivy-height)
348 (add-hook 'post-command-hook #'ivy--exhibit nil t)
349 ;; show completions with empty input
352 (defvar ivy--all-candidates nil
353 "Store the candidates passed to `ivy-read'.")
356 "Store the index of the current candidate.")
358 (defvar ivy--length 0
359 "Store the amount of viable candidates.")
361 (defvar ivy--current ""
362 "Current candidate.")
364 (defvar ivy--default nil
365 "Default initial input.")
367 (defvar ivy--update-fn nil
368 "Current function to call when current candidate(s) update.")
371 "Return the current minibuffer input."
372 ;; assume one-line minibuffer input
373 (buffer-substring-no-properties
374 (minibuffer-prompt-end)
375 (line-end-position)))
377 (defun ivy--cleanup ()
378 "Delete the displayed completion candidates."
380 (goto-char (minibuffer-prompt-end))
381 (delete-region (line-end-position) (point-max))))
383 (defvar ivy--prompt nil
384 "Store the format-style prompt.
385 When non-nil, it should contain one %d.")
387 (defun ivy--insert-prompt ()
388 "Update the prompt according to `ivy--prompt'."
390 (let ((inhibit-read-only t)
391 (n-str (format ivy--prompt ivy--length)))
393 (goto-char (point-min))
394 (delete-region (point-min) (minibuffer-prompt-end))
397 '(front-sticky t rear-nonsticky t field t read-only t face minibuffer-prompt)
400 ;; get out of the prompt area
401 (constrain-to-field nil (point-max)))))
403 (defun ivy--exhibit ()
404 "Insert Ivy completions display.
405 Should be run via minibuffer `post-command-hook'."
406 (setq ivy-text (ivy--input))
408 (let ((text (ivy-completions
410 ivy--all-candidates))
414 (funcall ivy--update-fn))
416 ;; Do nothing if while-no-input was aborted.
422 (defvar ivy--old-re nil
423 "Store the old regexp.")
425 (defvar ivy--old-cands nil
426 "Store the candidates matched by `ivy--old-re'.")
428 (defun ivy--add-face (str face)
429 "Propertize STR with FACE.
430 `font-lock-append-text-property' is used, since it's better than
431 `propertize' or `add-face-text-property' in this case."
432 (font-lock-append-text-property 0 (length str) 'face face str)
435 (defun ivy-completions (name candidates)
436 "Return as text the current completions.
437 NAME is a string of words separated by spaces that is used to
439 CANDIDATES is a list of strings."
440 (let* ((re (ivy--regex name))
441 (cands (if (and (equal re ivy--old-re)
446 (lambda (x) (string-match re x))
448 (tail (nthcdr ivy--index ivy--old-cands))
451 (when (and tail ivy--old-cands)
452 (unless (and (not (equal re ivy--old-re))
453 (setq ivy--index (cl-position re cands :test 'equal)))
454 (while (and tail (null idx))
455 ;; Compare with eq to handle equal duplicates in cands
456 (setq idx (cl-position (pop tail) cands)))
457 (setq ivy--index (or idx 0))))
458 (setq ivy--old-re re)
459 (setq ivy--length (length cands))
460 (setq ivy--old-cands cands)
461 (when (>= ivy--index ivy--length)
462 (setq ivy--index (max (1- ivy--length) 0)))
465 (let* ((half-height (/ ivy-height 2))
466 (start (max 0 (- ivy--index half-height)))
467 (end (min (+ start (1- ivy-height)) ivy--length))
468 (cands (cl-subseq cands start end))
469 (index (min ivy--index half-height (1- (length cands)))))
470 (setq ivy--current (copy-sequence (nth index cands)))
471 (setf (nth index cands)
472 (ivy--add-face ivy--current 'ivy-current-match))
473 (let ((res (concat "\n" (mapconcat
475 (if (> (length s) ww)
476 (concat (substring s 0 (- ww 3)) "...")
479 (put-text-property 0 (length res) 'read-only nil res)