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.")
53 "Face used by Ivy for highlighting subdirs in the alternatives.")
55 (defcustom ivy-height 10
56 "Number of lines for the minibuffer window."
59 (defcustom ivy-count-format "%-4d "
60 "The style of showing the current candidate count for `ivy-read'.
61 Set this to nil if you don't want the count."
64 (defcustom ivy-wrap nil
65 "Whether to wrap around after the first and last candidate."
68 (defcustom ivy-on-del-error-function 'minibuffer-keyboard-quit
69 "The handler for when `ivy-backward-delete-char' throws.
70 This is usually meant as a quick exit out of the minibuffer."
73 (defcustom ivy-extra-directories '("../" "./")
74 "Add this to the front of the list when completing file names.
75 Only \"./\" and \"../\" apply here. They appear in reverse order."
81 (defvar ivy-minibuffer-map
82 (let ((map (make-sparse-keymap)))
83 (define-key map (kbd "C-m") 'ivy-done)
84 (define-key map (kbd "C-j") 'ivy-alt-done)
85 (define-key map (kbd "C-n") 'ivy-next-line)
86 (define-key map (kbd "C-p") 'ivy-previous-line)
87 (define-key map (kbd "C-s") 'ivy-next-line-or-history)
88 (define-key map (kbd "C-r") 'ivy-previous-line-or-history)
89 (define-key map (kbd "SPC") 'self-insert-command)
90 (define-key map (kbd "DEL") 'ivy-backward-delete-char)
91 (define-key map (kbd "M-<") 'ivy-beginning-of-buffer)
92 (define-key map (kbd "M->") 'ivy-end-of-buffer)
93 (define-key map (kbd "M-n") 'ivy-next-history-element)
94 (define-key map (kbd "M-p") 'ivy-previous-history-element)
95 (define-key map (kbd "C-g") 'minibuffer-keyboard-quit)
96 (define-key map (kbd "C-v") 'ivy-scroll-up-command)
97 (define-key map (kbd "M-v") 'ivy-scroll-down-command)
99 "Keymap used in the minibuffer.")
101 (defvar ivy-history nil
102 "History list of candidates entered in the minibuffer.
104 Maximum length of the history list is determined by the value
105 of `history-length', which see.")
107 (defvar ivy-require-match t
108 "Store require-match. See `completing-read'.")
110 (defvar ivy--directory nil
111 "Current directory when completing file names.")
113 (defvar ivy--length 0
114 "Store the amount of viable candidates.")
117 "Store the user's string as it is typed in.")
119 (defvar ivy--current ""
120 "Current candidate.")
123 "Store the index of the current candidate.")
126 "Store 'done if the completion was successfully selected.
127 Otherwise, store nil.")
129 (defvar ivy--action nil
130 "Store a function to call at the end of `ivy--read'.")
132 (defvar ivy--all-candidates nil
133 "Store the candidates passed to `ivy-read'.")
135 (defvar ivy--default nil
136 "Default initial input.")
138 (defvar ivy--update-fn nil
139 "Current function to call when current candidate(s) update.")
141 (defvar ivy--prompt nil
142 "Store the format-style prompt.
143 When non-nil, it should contain one %d.")
145 (defvar ivy--old-re nil
146 "Store the old regexp.")
148 (defvar ivy--old-cands nil
149 "Store the candidates matched by `ivy--old-re'.")
153 "Exit the minibuffer with the selected candidate."
155 (delete-minibuffer-contents)
156 (cond (ivy--directory
158 (cond ((string= ivy-text "")
159 (if (equal ivy--current "./")
163 (expand-file-name ivy-text ivy--directory))
165 (expand-file-name ivy--current ivy--directory))))
166 (setq ivy-exit 'done))
168 (when (memq ivy-require-match
169 '(nil confirm confirm-after-completion))
171 (setq ivy-exit 'done)))
173 (insert ivy--current)
174 (setq ivy-exit 'done)))
177 (defun ivy-alt-done ()
178 "Exit the minibuffer with the selected candidate."
181 (cond ((and ivy--directory
183 (= 0 (length ivy-text)))
189 (setq dir (expand-file-name
190 ivy--current ivy--directory))))
197 (defun ivy-beginning-of-buffer ()
198 "Select the first completion candidate."
202 (defun ivy-end-of-buffer ()
203 "Select the last completion candidate."
205 (setq ivy--index (1- ivy--length)))
207 (defun ivy-scroll-up-command ()
208 "Scroll the candidates upward by the minibuffer height."
210 (setq ivy--index (min (+ ivy--index ivy-height)
213 (defun ivy-scroll-down-command ()
214 "Scroll the candidates downward by the minibuffer height."
216 (setq ivy--index (max (- ivy--index ivy-height)
219 (defun ivy-next-line (&optional arg)
220 "Move cursor vertically down ARG candidates."
222 (setq arg (or arg 1))
223 (cl-incf ivy--index arg)
224 (when (>= ivy--index (1- ivy--length))
226 (ivy-beginning-of-buffer)
227 (setq ivy--index (1- ivy--length)))))
229 (defun ivy-next-line-or-history (&optional arg)
230 "Move cursor vertically down ARG candidates.
231 If the input is empty, select the previous history element instead."
233 (when (string= ivy-text "")
234 (ivy-previous-history-element 1))
237 (defun ivy-previous-line (&optional arg)
238 "Move cursor vertically up ARG candidates."
240 (setq arg (or arg 1))
241 (cl-decf ivy--index arg)
242 (when (< ivy--index 0)
245 (setq ivy--index 0))))
247 (defun ivy-previous-line-or-history (arg)
248 "Move cursor vertically up ARG candidates.
249 If the input is empty, select the previous history element instead."
251 (when (string= ivy-text "")
252 (ivy-previous-history-element 1))
253 (ivy-previous-line arg))
255 (defun ivy-previous-history-element (arg)
256 "Forward to `previous-history-element' with ARG."
258 (previous-history-element arg)
259 (move-end-of-line 1))
261 (defun ivy-next-history-element (arg)
262 "Forward to `next-history-element' with ARG."
264 (next-history-element arg)
265 (move-end-of-line 1))
268 "When completing file names, move to directory DIR."
269 (if (null ivy--directory)
271 (setq ivy--old-cands nil)
272 (setq ivy--all-candidates
273 (ivy--sorted-files (setq ivy--directory dir)))
275 (delete-minibuffer-contents)))
277 (defun ivy-backward-delete-char ()
278 "Forward to `backward-delete-char'.
279 On error (read-only), call `ivy-on-del-error-function'."
281 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
283 (ivy--cd (file-name-directory
284 (directory-file-name ivy--directory)))
287 (backward-delete-char 1)
289 (when ivy-on-del-error-function
290 (funcall ivy-on-del-error-function))))))
292 (defun ivy-sort-file-function-default (x y)
293 "Compare two files X and Y.
294 Prioritize directories."
295 (if (get-text-property 0 'dirp x)
296 (if (get-text-property 0 'dirp y)
299 (if (get-text-property 0 'dirp y)
303 (defvar ivy-sort-file-function 'ivy-sort-file-function-default
304 "The function that compares file names.
305 It should take two string arguments and return nil and non-nil.")
307 (defun ivy--sorted-files (dir)
308 "Return the list of files in DIR.
309 Directories come first."
310 (let* ((default-directory dir)
311 (seq (all-completions "" 'read-file-name-internal)))
314 (setq seq (delete "./" (delete "../" seq)))
315 (when (eq ivy-sort-file-function 'ivy-sort-file-function-default)
316 (setq seq (mapcar (lambda (x)
317 (propertize x 'dirp (string-match-p "/$" x)))
318 (delete "./" (delete "../" seq)))))
319 (setq seq (cl-sort seq ivy-sort-file-function))
320 (dolist (dir ivy-extra-directories)
325 (defun ivy-read (prompt collection
326 &optional predicate initial-input keymap preselect update-fn)
327 "Read a string in the minibuffer, with completion.
329 PROMPT is a string to prompt with; normally it ends in a colon
330 and a space. When PROMPT contains %d, it will be updated with
331 the current number of matching candidates.
332 See also `ivy-count-format'.
334 COLLECTION is a list of strings.
336 If INITIAL-INPUT is non-nil, insert it in the minibuffer initially.
338 KEYMAP is composed together with `ivy-minibuffer-map'.
340 If PRESELECT is non-nil select the corresponding candidate out of
341 the ones that match INITIAL-INPUT.
343 UPDATE-FN is called each time the current candidate(s) is changed."
344 (setq ivy--directory nil)
345 (cond ((eq collection 'Info-read-node-name-1)
346 (if (equal Info-current-file "dir")
348 (mapcar (lambda (x) (format "(%s)" x))
349 (cl-delete-duplicates
350 (all-completions "(" collection predicate)
352 (setq collection (all-completions "" collection predicate))))
353 ((eq collection 'read-file-name-internal)
354 (setq ivy--directory default-directory)
355 (setq initial-input nil)
357 (ivy--sorted-files default-directory)))
358 ((or (functionp collection)
359 (vectorp collection))
360 (setq collection (all-completions "" collection predicate)))
361 ((hash-table-p collection)
362 (error "Hash table as a collection unsupported"))
363 ((listp (car collection))
364 (setq collection (all-completions "" collection predicate))))
366 (unless (or ivy-require-match
367 (all-completions preselect collection))
368 (setq collection (cons preselect collection))))
369 (cl-case (length collection)
375 (ivy--preselect-index
376 collection initial-input preselect))
378 (setq ivy--old-re nil)
379 (setq ivy--old-cands nil)
381 (setq ivy--all-candidates collection)
382 (setq ivy--update-fn update-fn)
384 (setq ivy--default (or (thing-at-point 'symbol) ""))
386 (cond ((string-match "%.*d" prompt)
388 ((string-match "%.*d" ivy-count-format)
389 (concat ivy-count-format prompt))
394 (setq ivy--action nil)
397 (minibuffer-with-setup-hook
398 #'ivy--minibuffer-setup
399 (let ((res (read-from-minibuffer
402 (make-composed-keymap keymap ivy-minibuffer-map)
405 (when (eq ivy-exit 'done)
408 (cons ivy-text (delete ivy-text ivy-history)))
410 (remove-hook 'post-command-hook #'ivy--exhibit))
412 (funcall ivy--action))))))
414 (defun ivy-completing-read (prompt collection
415 &optional predicate require-match initial-input
416 _history def _inherit-input-method)
417 "Read a string in the minibuffer, with completion.
419 This is an interface that conforms to `completing-read', so that
420 it can be used for `completing-read-function'.
422 PROMPT is a string to prompt with; normally it ends in a colon and a space.
423 COLLECTION can be a list of strings, an alist, an obarray or a hash table.
424 PREDICATE limits completion to a subset of COLLECTION.
426 REQUIRE-MATCH is stored into `ivy-require-match'. See `completing-read'.
427 INITIAL-INPUT is a string that can be inserted into the minibuffer initially.
428 _HISTORY is ignored for now.
429 DEF is the default value.
430 _INHERIT-INPUT-METHOD is ignored for now.
432 The history, defaults and input-method arguments are ignored for now."
434 (setq def (car def)))
435 (setq ivy-require-match require-match)
436 (ivy-read prompt collection predicate initial-input nil def))
439 (define-minor-mode ivy-mode
440 "Toggle Ivy mode on or off.
441 With ARG, turn Ivy mode on if arg is positive, off otherwise.
442 Turning on Ivy mode will set `completing-read-function' to
443 `ivy-completing-read'.
445 \\{ivy-minibuffer-map}"
450 (setq completing-read-function 'ivy-completing-read)
451 (setq completing-read-function 'completing-read-default)))
453 (defun ivy--preselect-index (candidates initial-input preselect)
454 "Return the index in CANDIDATES filtered by INITIAL-INPUT for PRESELECT."
459 (string-match initial-input x))
461 (or (cl-position preselect candidates :test 'equal)
464 (string-match preselect x))
469 (defvar ivy--subexps 0
470 "Number of groups in the current `ivy--regex'.")
472 (defvar ivy--regex-hash
473 (make-hash-table :test 'equal)
474 "Store pre-computed regex.")
476 (defun ivy--regex (str)
477 "Re-build regex from STR in case it has a space."
478 (let ((hashed (gethash str ivy--regex-hash)))
481 (setq ivy--subexps (car hashed)))
483 (let ((subs (split-string str " +" t)))
484 (if (= (length subs) 1)
486 (setq ivy--subexps 0)
489 (setq ivy--subexps (length subs))
491 (lambda (x) (format "\\(%s\\)" x))
497 (defun ivy--minibuffer-setup ()
498 "Setup ivy completion in the minibuffer."
499 (set (make-local-variable 'completion-show-inline-help) nil)
500 (set (make-local-variable 'minibuffer-default-add-function)
502 (list ivy--default)))
503 (use-local-map (make-composed-keymap ivy-minibuffer-map
504 (current-local-map)))
505 (setq-local max-mini-window-height ivy-height)
506 (add-hook 'post-command-hook #'ivy--exhibit nil t)
507 ;; show completions with empty input
511 "Return the current minibuffer input."
512 ;; assume one-line minibuffer input
513 (buffer-substring-no-properties
514 (minibuffer-prompt-end)
515 (line-end-position)))
517 (defun ivy--cleanup ()
518 "Delete the displayed completion candidates."
520 (goto-char (minibuffer-prompt-end))
521 (delete-region (line-end-position) (point-max))))
523 (defun ivy--insert-prompt ()
524 "Update the prompt according to `ivy--prompt'."
526 (let ((inhibit-read-only t)
530 (concat ivy--prompt (abbreviate-file-name ivy--directory))
531 ivy--prompt) ivy--length)))
533 (goto-char (point-min))
534 (delete-region (point-min) (minibuffer-prompt-end))
537 '(front-sticky t rear-nonsticky t field t read-only t face minibuffer-prompt)
540 ;; get out of the prompt area
541 (constrain-to-field nil (point-max)))))
543 (defun ivy--exhibit ()
544 "Insert Ivy completions display.
545 Should be run via minibuffer `post-command-hook'."
546 (setq ivy-text (ivy--input))
549 (if (string-match "/$" ivy-text)
550 (if (member ivy-text ivy--all-candidates)
551 (ivy--cd (expand-file-name ivy-text ivy--directory))
553 (if (string-match "~$" ivy-text)
554 (ivy--cd (expand-file-name "~/")))))
555 (let ((text (ivy-completions
557 ivy--all-candidates))
561 (funcall ivy--update-fn))
563 ;; Do nothing if while-no-input was aborted.
569 (defun ivy--add-face (str face)
570 "Propertize STR with FACE.
571 `font-lock-append-text-property' is used, since it's better than
572 `propertize' or `add-face-text-property' in this case."
573 (font-lock-append-text-property 0 (length str) 'face face str)
576 (defun ivy-completions (name candidates)
577 "Return as text the current completions.
578 NAME is a string of words separated by spaces that is used to
580 CANDIDATES is a list of strings."
581 (let* ((re (ivy--regex name))
582 (cands (cond ((and (equal re ivy--old-re)
586 (not (equal ivy--old-re ""))
587 (eq 0 (cl-search ivy--old-re re)))
590 (lambda (x) (string-match re x))
595 (lambda (x) (string-match re x))
597 (tail (nthcdr ivy--index ivy--old-cands))
600 (when (and tail ivy--old-cands)
601 (unless (and (not (equal re ivy--old-re))
602 (setq ivy--index (cl-position re cands :test 'equal)))
603 (while (and tail (null idx))
604 ;; Compare with eq to handle equal duplicates in cands
605 (setq idx (cl-position (pop tail) cands)))
606 (setq ivy--index (or idx 0))))
607 (setq ivy--old-re re)
608 (setq ivy--length (length cands))
609 (setq ivy--old-cands cands)
610 (when (>= ivy--index ivy--length)
611 (setq ivy--index (max (1- ivy--length) 0)))
614 (let* ((half-height (/ ivy-height 2))
615 (start (max 0 (- ivy--index half-height)))
616 (end (min (+ start (1- ivy-height)) ivy--length))
617 (cands (cl-subseq cands start end))
618 (index (min ivy--index half-height (1- (length cands)))))
620 (setq cands (mapcar (lambda (x)
621 (if (string-match-p "/$" x)
622 (propertize x 'face 'ivy-subdir)
625 (setq ivy--current (copy-sequence (nth index cands)))
626 (setf (nth index cands)
627 (ivy--add-face ivy--current 'ivy-current-match))
628 (let ((res (concat "\n" (mapconcat
630 (if (> (length s) ww)
631 (concat (substring s 0 (- ww 3)) "...")
634 (put-text-property 0 (length res) 'read-only nil res)