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-j") 'ivy-alt-done)
76 (define-key map (kbd "C-n") 'ivy-next-line)
77 (define-key map (kbd "C-p") 'ivy-previous-line)
78 (define-key map (kbd "C-s") 'ivy-next-line-or-history)
79 (define-key map (kbd "C-r") 'ivy-previous-line-or-history)
80 (define-key map (kbd "SPC") 'self-insert-command)
81 (define-key map (kbd "DEL") 'ivy-backward-delete-char)
82 (define-key map (kbd "M-<") 'ivy-beginning-of-buffer)
83 (define-key map (kbd "M->") 'ivy-end-of-buffer)
84 (define-key map (kbd "M-n") 'ivy-next-history-element)
85 (define-key map (kbd "M-p") 'ivy-previous-history-element)
86 (define-key map (kbd "C-g") 'minibuffer-keyboard-quit)
88 "Keymap used in the minibuffer.")
90 (defvar ivy-history nil
91 "History list of candidates entered in the minibuffer.
93 Maximum length of the history list is determined by the value
94 of `history-length', which see.")
96 (defvar ivy-require-match t
97 "Store require-match. See `completing-read'.")
99 (defvar ivy--directory nil
100 "Current directory when completing file names.")
104 "Exit the minibuffer with the selected candidate."
106 (delete-minibuffer-contents)
107 (if (zerop ivy--length)
108 (when (memq ivy-require-match '(nil confirm confirm-after-completion))
110 (setq ivy-exit 'done))
112 (insert (expand-file-name ivy--current ivy--directory))
113 (insert ivy--current))
114 (setq ivy-exit 'done))
117 (defun ivy-alt-done ()
118 "Exit the minibuffer with the selected candidate."
120 (if (and ivy--directory
122 (expand-file-name ivy--current ivy--directory)))
124 (delete-minibuffer-contents)
126 (expand-file-name ivy--current ivy--directory))
127 (setq ivy--old-cands nil)
128 (setq ivy--all-candidates
129 (let ((default-directory ivy--directory))
130 (all-completions "" 'read-file-name-internal)))
135 (defun ivy-beginning-of-buffer ()
136 "Select the first completion candidate."
140 (defun ivy-end-of-buffer ()
141 "Select the last completion candidate."
143 (setq ivy--index (1- ivy--length)))
145 (defun ivy-next-line (&optional arg)
146 "Move cursor vertically down ARG candidates."
148 (setq arg (or arg 1))
149 (cl-incf ivy--index arg)
150 (when (>= ivy--index (1- ivy--length))
152 (ivy-beginning-of-buffer)
153 (setq ivy--index (1- ivy--length)))))
155 (defun ivy-next-line-or-history (&optional arg)
156 "Move cursor vertically down ARG candidates.
157 If the input is empty, select the previous history element instead."
159 (when (string= ivy-text "")
160 (ivy-previous-history-element 1))
163 (defun ivy-previous-line (&optional arg)
164 "Move cursor vertically up ARG candidates."
166 (setq arg (or arg 1))
167 (cl-decf ivy--index arg)
168 (when (< ivy--index 0)
171 (setq ivy--index 0))))
173 (defun ivy-previous-line-or-history (arg)
174 "Move cursor vertically up ARG candidates.
175 If the input is empty, select the previous history element instead."
177 (when (string= ivy-text "")
178 (ivy-previous-history-element 1))
179 (ivy-previous-line arg))
181 (defun ivy-previous-history-element (arg)
182 "Forward to `previous-history-element' with ARG."
184 (previous-history-element arg)
185 (move-end-of-line 1))
187 (defun ivy-next-history-element (arg)
188 "Forward to `next-history-element' with ARG."
190 (next-history-element arg)
191 (move-end-of-line 1))
193 (defun ivy-backward-delete-char ()
194 "Forward to `backward-delete-char'.
195 On error (read-only), call `ivy-on-del-error-function'."
197 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
199 (setq ivy--old-cands nil)
200 (setq ivy--all-candidates
201 (let ((default-directory (setq ivy--directory
203 (directory-file-name ivy--directory)))))
204 (all-completions "" 'read-file-name-internal)))
207 (backward-delete-char 1)
209 (when ivy-on-del-error-function
210 (funcall ivy-on-del-error-function))))))
213 (defun ivy-read (prompt collection
214 &optional predicate initial-input keymap preselect update-fn)
215 "Read a string in the minibuffer, with completion.
217 PROMPT is a string to prompt with; normally it ends in a colon
218 and a space. When PROMPT contains %d, it will be updated with
219 the current number of matching candidates.
220 See also `ivy-count-format'.
222 COLLECTION is a list of strings.
224 If INITIAL-INPUT is non-nil, insert it in the minibuffer initially.
226 KEYMAP is composed together with `ivy-minibuffer-map'.
228 If PRESELECT is non-nil select the corresponding candidate out of
229 the ones that match INITIAL-INPUT.
231 UPDATE-FN is called each time the current candidate(s) is changed."
232 (setq ivy--directory nil)
233 (cond ((or (functionp collection)
234 (vectorp collection))
235 (when (eq collection 'read-file-name-internal)
236 (setq ivy--directory default-directory)
237 (setq initial-input nil))
238 (setq collection (all-completions "" collection predicate)))
239 ((hash-table-p collection)
240 (error "Hash table as a collection unsupported"))
241 ((listp (car collection))
242 (setq collection (all-completions "" collection predicate))))
243 (cl-case (length collection)
249 (ivy--preselect-index
250 collection initial-input preselect))
252 (setq ivy--old-re nil)
253 (setq ivy--old-cands nil)
255 (setq ivy--all-candidates collection)
256 (setq ivy--update-fn update-fn)
258 (setq ivy--default (or (thing-at-point 'symbol) ""))
260 (cond ((string-match "%.*d" prompt)
262 ((string-match "%.*d" ivy-count-format)
263 (concat ivy-count-format prompt))
268 (setq ivy--action nil)
271 (minibuffer-with-setup-hook
272 #'ivy--minibuffer-setup
273 (let ((res (read-from-minibuffer
276 (make-composed-keymap keymap ivy-minibuffer-map)
279 (when (eq ivy-exit 'done)
282 (cons ivy-text (delete ivy-text ivy-history)))
284 (remove-hook 'post-command-hook #'ivy--exhibit))
286 (funcall ivy--action))))))
288 (defun ivy-completing-read (prompt collection
289 &optional predicate require-match initial-input
290 _history def _inherit-input-method)
291 "Read a string in the minibuffer, with completion.
293 This is an interface that conforms to `completing-read', so that
294 it can be used for `completing-read-function'.
296 PROMPT is a string to prompt with; normally it ends in a colon and a space.
297 COLLECTION can be a list of strings, an alist, an obarray or a hash table.
298 PREDICATE limits completion to a subset of COLLECTION.
300 REQUIRE-MATCH is stored into `ivy-require-match'. See `completing-read'.
301 INITIAL-INPUT is a string that can be inserted into the minibuffer initially.
302 _HISTORY is ignored for now.
303 DEF is the default value.
304 _INHERIT-INPUT-METHOD is ignored for now.
306 The history, defaults and input-method arguments are ignored for now."
308 (setq def (car def)))
309 (setq ivy-require-match require-match)
310 (ivy-read prompt collection predicate initial-input nil def))
313 (define-minor-mode ivy-mode
314 "Toggle Ivy mode on or off.
315 With ARG, turn Ivy mode on if arg is positive, off otherwise.
316 Turning on Ivy mode will set `completing-read-function' to
317 `ivy-completing-read'."
322 (setq completing-read-function 'ivy-completing-read)
323 (setq completing-read-function 'completing-read-default)))
325 (defvar ivy--action nil
326 "Store a function to call at the end of `ivy--read'.")
328 (defun ivy--preselect-index (candidates initial-input preselect)
329 "Return the index in CANDIDATES filtered by INITIAL-INPUT for PRESELECT."
334 (string-match initial-input x))
338 (string-match preselect x))
342 "Stores the user's string as it is typed in.")
345 "Store 'done if the completion was successfully selected.
346 Otherwise, store nil.")
350 (defvar ivy--subexps 0
351 "Number of groups in the current `ivy--regex'.")
353 (defvar ivy--regex-hash
354 (make-hash-table :test 'equal)
355 "Store pre-computed regex.")
357 (defun ivy--regex (str)
358 "Re-build regex from STR in case it has a space."
359 (let ((hashed (gethash str ivy--regex-hash)))
362 (setq ivy--subexps (car hashed)))
364 (let ((subs (split-string str " +" t)))
365 (if (= (length subs) 1)
367 (setq ivy--subexps 0)
370 (setq ivy--subexps (length subs))
372 (lambda (x) (format "\\(%s\\)" x))
378 (defun ivy--minibuffer-setup ()
379 "Setup ivy completion in the minibuffer."
380 (set (make-local-variable 'completion-show-inline-help) nil)
381 (set (make-local-variable 'minibuffer-default-add-function)
383 (list ivy--default)))
384 (use-local-map (make-composed-keymap ivy-minibuffer-map
385 (current-local-map)))
386 (setq-local max-mini-window-height ivy-height)
387 (add-hook 'post-command-hook #'ivy--exhibit nil t)
388 ;; show completions with empty input
391 (defvar ivy--all-candidates nil
392 "Store the candidates passed to `ivy-read'.")
395 "Store the index of the current candidate.")
397 (defvar ivy--length 0
398 "Store the amount of viable candidates.")
400 (defvar ivy--current ""
401 "Current candidate.")
403 (defvar ivy--default nil
404 "Default initial input.")
406 (defvar ivy--update-fn nil
407 "Current function to call when current candidate(s) update.")
410 "Return the current minibuffer input."
411 ;; assume one-line minibuffer input
412 (buffer-substring-no-properties
413 (minibuffer-prompt-end)
414 (line-end-position)))
416 (defun ivy--cleanup ()
417 "Delete the displayed completion candidates."
419 (goto-char (minibuffer-prompt-end))
420 (delete-region (line-end-position) (point-max))))
422 (defvar ivy--prompt nil
423 "Store the format-style prompt.
424 When non-nil, it should contain one %d.")
426 (defun ivy--insert-prompt ()
427 "Update the prompt according to `ivy--prompt'."
429 (let ((inhibit-read-only t)
433 (concat ivy--prompt (abbreviate-file-name ivy--directory))
434 ivy--prompt) ivy--length)))
436 (goto-char (point-min))
437 (delete-region (point-min) (minibuffer-prompt-end))
440 '(front-sticky t rear-nonsticky t field t read-only t face minibuffer-prompt)
443 ;; get out of the prompt area
444 (constrain-to-field nil (point-max)))))
446 (defun ivy--exhibit ()
447 "Insert Ivy completions display.
448 Should be run via minibuffer `post-command-hook'."
449 (setq ivy-text (ivy--input))
451 (let ((text (ivy-completions
453 ivy--all-candidates))
457 (funcall ivy--update-fn))
459 ;; Do nothing if while-no-input was aborted.
465 (defvar ivy--old-re nil
466 "Store the old regexp.")
468 (defvar ivy--old-cands nil
469 "Store the candidates matched by `ivy--old-re'.")
471 (defun ivy--add-face (str face)
472 "Propertize STR with FACE.
473 `font-lock-append-text-property' is used, since it's better than
474 `propertize' or `add-face-text-property' in this case."
475 (font-lock-append-text-property 0 (length str) 'face face str)
478 (defun ivy-completions (name candidates)
479 "Return as text the current completions.
480 NAME is a string of words separated by spaces that is used to
482 CANDIDATES is a list of strings."
483 (let* ((re (ivy--regex name))
484 (cands (if (and (equal re ivy--old-re)
489 (lambda (x) (string-match re x))
491 (tail (nthcdr ivy--index ivy--old-cands))
494 (when (and tail ivy--old-cands)
495 (unless (and (not (equal re ivy--old-re))
496 (setq ivy--index (cl-position re cands :test 'equal)))
497 (while (and tail (null idx))
498 ;; Compare with eq to handle equal duplicates in cands
499 (setq idx (cl-position (pop tail) cands)))
500 (setq ivy--index (or idx 0))))
501 (setq ivy--old-re re)
502 (setq ivy--length (length cands))
503 (setq ivy--old-cands cands)
504 (when (>= ivy--index ivy--length)
505 (setq ivy--index (max (1- ivy--length) 0)))
508 (let* ((half-height (/ ivy-height 2))
509 (start (max 0 (- ivy--index half-height)))
510 (end (min (+ start (1- ivy-height)) ivy--length))
511 (cands (cl-subseq cands start end))
512 (index (min ivy--index half-height (1- (length cands)))))
513 (setq ivy--current (copy-sequence (nth index cands)))
514 (setf (nth index cands)
515 (ivy--add-face ivy--current 'ivy-current-match))
516 (let ((res (concat "\n" (mapconcat
518 (if (> (length s) ww)
519 (concat (substring s 0 (- ww 3)) "...")
522 (put-text-property 0 (length res) 'read-only nil res)