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-j") 'ivy-alt-done)
74 (define-key map (kbd "C-n") 'ivy-next-line)
75 (define-key map (kbd "C-p") 'ivy-previous-line)
76 (define-key map (kbd "C-s") 'ivy-next-line-or-history)
77 (define-key map (kbd "C-r") 'ivy-previous-line-or-history)
78 (define-key map (kbd "SPC") 'self-insert-command)
79 (define-key map (kbd "DEL") 'ivy-backward-delete-char)
80 (define-key map (kbd "M-<") 'ivy-beginning-of-buffer)
81 (define-key map (kbd "M->") 'ivy-end-of-buffer)
82 (define-key map (kbd "M-n") 'ivy-next-history-element)
83 (define-key map (kbd "M-p") 'ivy-previous-history-element)
84 (define-key map (kbd "C-g") 'minibuffer-keyboard-quit)
86 "Keymap used in the minibuffer.")
88 (defvar ivy-history nil
89 "History list of candidates entered in the minibuffer.
91 Maximum length of the history list is determined by the value
92 of `history-length', which see.")
94 (defvar ivy-require-match t
95 "Store require-match. See `completing-read'.")
97 (defvar ivy--directory nil
98 "Current directory when completing file names.")
102 "Exit the minibuffer with the selected candidate."
104 (delete-minibuffer-contents)
105 (if (zerop ivy--length)
106 (when (memq ivy-require-match '(nil confirm confirm-after-completion))
108 (setq ivy-exit 'done))
110 (insert (expand-file-name ivy--current ivy--directory))
111 (insert ivy--current))
112 (setq ivy-exit 'done))
115 (defun ivy-alt-done ()
116 "Exit the minibuffer with the selected candidate."
119 (cond ((and ivy--directory
121 (= 0 (length ivy-text)))
126 (setq dir (expand-file-name
127 ivy--current ivy--directory))))
134 (defun ivy-beginning-of-buffer ()
135 "Select the first completion candidate."
139 (defun ivy-end-of-buffer ()
140 "Select the last completion candidate."
142 (setq ivy--index (1- ivy--length)))
144 (defun ivy-next-line (&optional arg)
145 "Move cursor vertically down ARG candidates."
147 (setq arg (or arg 1))
148 (cl-incf ivy--index arg)
149 (when (>= ivy--index (1- ivy--length))
151 (ivy-beginning-of-buffer)
152 (setq ivy--index (1- ivy--length)))))
154 (defun ivy-next-line-or-history (&optional arg)
155 "Move cursor vertically down ARG candidates.
156 If the input is empty, select the previous history element instead."
158 (when (string= ivy-text "")
159 (ivy-previous-history-element 1))
162 (defun ivy-previous-line (&optional arg)
163 "Move cursor vertically up ARG candidates."
165 (setq arg (or arg 1))
166 (cl-decf ivy--index arg)
167 (when (< ivy--index 0)
170 (setq ivy--index 0))))
172 (defun ivy-previous-line-or-history (arg)
173 "Move cursor vertically up ARG candidates.
174 If the input is empty, select the previous history element instead."
176 (when (string= ivy-text "")
177 (ivy-previous-history-element 1))
178 (ivy-previous-line arg))
180 (defun ivy-previous-history-element (arg)
181 "Forward to `previous-history-element' with ARG."
183 (previous-history-element arg)
184 (move-end-of-line 1))
186 (defun ivy-next-history-element (arg)
187 "Forward to `next-history-element' with ARG."
189 (next-history-element arg)
190 (move-end-of-line 1))
193 "When completing file names, move to directory DIR."
194 (if (null ivy--directory)
196 (setq ivy--old-cands nil)
197 (setq ivy--all-candidates
198 (ivy--sorted-files (setq ivy--directory dir)))
200 (delete-minibuffer-contents)))
202 (defun ivy-backward-delete-char ()
203 "Forward to `backward-delete-char'.
204 On error (read-only), call `ivy-on-del-error-function'."
206 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
208 (ivy--cd (file-name-directory
209 (directory-file-name ivy--directory)))
212 (backward-delete-char 1)
214 (when ivy-on-del-error-function
215 (funcall ivy-on-del-error-function))))))
217 (defun ivy--sorted-files (dir)
218 "Return the list of files in DIR.
219 Directories come first."
220 (let* ((default-directory dir)
221 (seq (all-completions "" 'read-file-name-internal)))
224 (cons "./" (cons "../"
226 (delete "./" (delete "../" seq))
228 (if (file-directory-p x)
229 (if (file-directory-p y)
232 (if (file-directory-p y)
234 (string< x y))))))))))
237 (defun ivy-read (prompt collection
238 &optional predicate initial-input keymap preselect update-fn)
239 "Read a string in the minibuffer, with completion.
241 PROMPT is a string to prompt with; normally it ends in a colon
242 and a space. When PROMPT contains %d, it will be updated with
243 the current number of matching candidates.
244 See also `ivy-count-format'.
246 COLLECTION is a list of strings.
248 If INITIAL-INPUT is non-nil, insert it in the minibuffer initially.
250 KEYMAP is composed together with `ivy-minibuffer-map'.
252 If PRESELECT is non-nil select the corresponding candidate out of
253 the ones that match INITIAL-INPUT.
255 UPDATE-FN is called each time the current candidate(s) is changed."
256 (setq ivy--directory nil)
257 (cond ((eq collection 'read-file-name-internal)
258 (setq ivy--directory default-directory)
259 (setq initial-input nil)
261 (ivy--sorted-files default-directory)))
262 ((or (functionp collection)
263 (vectorp collection))
264 (setq collection (all-completions "" collection predicate)))
265 ((hash-table-p collection)
266 (error "Hash table as a collection unsupported"))
267 ((listp (car collection))
268 (setq collection (all-completions "" collection predicate))))
270 (unless (or ivy-require-match
271 (all-completions preselect collection))
272 (setq collection (cons preselect collection))))
273 (cl-case (length collection)
279 (ivy--preselect-index
280 collection initial-input preselect))
282 (setq ivy--old-re nil)
283 (setq ivy--old-cands nil)
285 (setq ivy--all-candidates collection)
286 (setq ivy--update-fn update-fn)
288 (setq ivy--default (or (thing-at-point 'symbol) ""))
290 (cond ((string-match "%.*d" prompt)
292 ((string-match "%.*d" ivy-count-format)
293 (concat ivy-count-format prompt))
298 (setq ivy--action nil)
301 (minibuffer-with-setup-hook
302 #'ivy--minibuffer-setup
303 (let ((res (read-from-minibuffer
306 (make-composed-keymap keymap ivy-minibuffer-map)
309 (when (eq ivy-exit 'done)
312 (cons ivy-text (delete ivy-text ivy-history)))
314 (remove-hook 'post-command-hook #'ivy--exhibit))
316 (funcall ivy--action))))))
318 (defun ivy-completing-read (prompt collection
319 &optional predicate require-match initial-input
320 _history def _inherit-input-method)
321 "Read a string in the minibuffer, with completion.
323 This is an interface that conforms to `completing-read', so that
324 it can be used for `completing-read-function'.
326 PROMPT is a string to prompt with; normally it ends in a colon and a space.
327 COLLECTION can be a list of strings, an alist, an obarray or a hash table.
328 PREDICATE limits completion to a subset of COLLECTION.
330 REQUIRE-MATCH is stored into `ivy-require-match'. See `completing-read'.
331 INITIAL-INPUT is a string that can be inserted into the minibuffer initially.
332 _HISTORY is ignored for now.
333 DEF is the default value.
334 _INHERIT-INPUT-METHOD is ignored for now.
336 The history, defaults and input-method arguments are ignored for now."
338 (setq def (car def)))
339 (setq ivy-require-match require-match)
340 (ivy-read prompt collection predicate initial-input nil def))
343 (define-minor-mode ivy-mode
344 "Toggle Ivy mode on or off.
345 With ARG, turn Ivy mode on if arg is positive, off otherwise.
346 Turning on Ivy mode will set `completing-read-function' to
347 `ivy-completing-read'."
352 (setq completing-read-function 'ivy-completing-read)
353 (setq completing-read-function 'completing-read-default)))
355 (defvar ivy--action nil
356 "Store a function to call at the end of `ivy--read'.")
358 (defun ivy--preselect-index (candidates initial-input preselect)
359 "Return the index in CANDIDATES filtered by INITIAL-INPUT for PRESELECT."
364 (string-match initial-input x))
368 (string-match preselect x))
372 "Stores the user's string as it is typed in.")
375 "Store 'done if the completion was successfully selected.
376 Otherwise, store nil.")
380 (defvar ivy--subexps 0
381 "Number of groups in the current `ivy--regex'.")
383 (defvar ivy--regex-hash
384 (make-hash-table :test 'equal)
385 "Store pre-computed regex.")
387 (defun ivy--regex (str)
388 "Re-build regex from STR in case it has a space."
389 (let ((hashed (gethash str ivy--regex-hash)))
392 (setq ivy--subexps (car hashed)))
394 (let ((subs (split-string str " +" t)))
395 (if (= (length subs) 1)
397 (setq ivy--subexps 0)
400 (setq ivy--subexps (length subs))
402 (lambda (x) (format "\\(%s\\)" x))
408 (defun ivy--minibuffer-setup ()
409 "Setup ivy completion in the minibuffer."
410 (set (make-local-variable 'completion-show-inline-help) nil)
411 (set (make-local-variable 'minibuffer-default-add-function)
413 (list ivy--default)))
414 (use-local-map (make-composed-keymap ivy-minibuffer-map
415 (current-local-map)))
416 (setq-local max-mini-window-height ivy-height)
417 (add-hook 'post-command-hook #'ivy--exhibit nil t)
418 ;; show completions with empty input
421 (defvar ivy--all-candidates nil
422 "Store the candidates passed to `ivy-read'.")
425 "Store the index of the current candidate.")
427 (defvar ivy--length 0
428 "Store the amount of viable candidates.")
430 (defvar ivy--current ""
431 "Current candidate.")
433 (defvar ivy--default nil
434 "Default initial input.")
436 (defvar ivy--update-fn nil
437 "Current function to call when current candidate(s) update.")
440 "Return the current minibuffer input."
441 ;; assume one-line minibuffer input
442 (buffer-substring-no-properties
443 (minibuffer-prompt-end)
444 (line-end-position)))
446 (defun ivy--cleanup ()
447 "Delete the displayed completion candidates."
449 (goto-char (minibuffer-prompt-end))
450 (delete-region (line-end-position) (point-max))))
452 (defvar ivy--prompt nil
453 "Store the format-style prompt.
454 When non-nil, it should contain one %d.")
456 (defun ivy--insert-prompt ()
457 "Update the prompt according to `ivy--prompt'."
459 (let ((inhibit-read-only t)
463 (concat ivy--prompt (abbreviate-file-name ivy--directory))
464 ivy--prompt) ivy--length)))
466 (goto-char (point-min))
467 (delete-region (point-min) (minibuffer-prompt-end))
470 '(front-sticky t rear-nonsticky t field t read-only t face minibuffer-prompt)
473 ;; get out of the prompt area
474 (constrain-to-field nil (point-max)))))
476 (defun ivy--exhibit ()
477 "Insert Ivy completions display.
478 Should be run via minibuffer `post-command-hook'."
479 (setq ivy-text (ivy--input))
482 (if (string-match "/$" ivy-text)
483 (if (member ivy-text ivy--all-candidates)
484 (ivy--cd (expand-file-name ivy-text ivy--directory))
486 (if (string-match "~$" ivy-text)
487 (ivy--cd (expand-file-name "~/")))))
488 (let ((text (ivy-completions
490 ivy--all-candidates))
494 (funcall ivy--update-fn))
496 ;; Do nothing if while-no-input was aborted.
502 (defvar ivy--old-re nil
503 "Store the old regexp.")
505 (defvar ivy--old-cands nil
506 "Store the candidates matched by `ivy--old-re'.")
508 (defun ivy--add-face (str face)
509 "Propertize STR with FACE.
510 `font-lock-append-text-property' is used, since it's better than
511 `propertize' or `add-face-text-property' in this case."
512 (font-lock-append-text-property 0 (length str) 'face face str)
515 (defun ivy-completions (name candidates)
516 "Return as text the current completions.
517 NAME is a string of words separated by spaces that is used to
519 CANDIDATES is a list of strings."
520 (let* ((re (ivy--regex name))
521 (cands (if (and (equal re ivy--old-re)
526 (lambda (x) (string-match re x))
528 (tail (nthcdr ivy--index ivy--old-cands))
531 (when (and tail ivy--old-cands)
532 (unless (and (not (equal re ivy--old-re))
533 (setq ivy--index (cl-position re cands :test 'equal)))
534 (while (and tail (null idx))
535 ;; Compare with eq to handle equal duplicates in cands
536 (setq idx (cl-position (pop tail) cands)))
537 (setq ivy--index (or idx 0))))
538 (setq ivy--old-re re)
539 (setq ivy--length (length cands))
540 (setq ivy--old-cands cands)
541 (when (>= ivy--index ivy--length)
542 (setq ivy--index (max (1- ivy--length) 0)))
545 (let* ((half-height (/ ivy-height 2))
546 (start (max 0 (- ivy--index half-height)))
547 (end (min (+ start (1- ivy-height)) ivy--length))
548 (cands (cl-subseq cands start end))
549 (index (min ivy--index half-height (1- (length cands)))))
550 (setq ivy--current (copy-sequence (nth index cands)))
551 (setf (nth index cands)
552 (ivy--add-face ivy--current 'ivy-current-match))
553 (let ((res (concat "\n" (mapconcat
555 (if (> (length s) ww)
556 (concat (substring s 0 (- ww 3)) "...")
559 (put-text-property 0 (length res) 'read-only nil res)