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
7 ;; Package-Requires: ((emacs "24.1"))
10 ;; This file is part of GNU Emacs.
12 ;; This file is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 3, or (at your option)
17 ;; This program is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; For a full copy of the GNU General Public License
23 ;; see <http://www.gnu.org/licenses/>.
27 ;; This package provides `ivy-read' as an alternative to
28 ;; `completing-read' and similar functions.
30 ;; There's no intricate code to determine the best candidate.
31 ;; Instead, the user can navigate to it with `ivy-next-line' and
32 ;; `ivy-previous-line'.
34 ;; The matching is done by splitting the input text by spaces and
35 ;; re-building it into a regex.
36 ;; So "for example" is transformed into "\\(for\\).*\\(example\\)".
43 "Incremental vertical completion."
46 (defface ivy-current-match
47 '((t (:inherit highlight)))
48 "Face used by Ivy for highlighting first match.")
50 (defface ivy-confirm-face
51 '((t :foreground "ForestGreen" :inherit minibuffer-prompt))
52 "Face used by Ivy to issue a confirmation prompt.")
54 (defface ivy-match-required-face
55 '((t :foreground "red" :inherit minibuffer-prompt))
56 "Face used by Ivy to issue a match required prompt.")
59 '((t (:inherit 'dired-directory)))
60 "Face used by Ivy for highlighting subdirs in the alternatives.")
63 '((t (:foreground "#110099")))
64 "Face used by Ivy for highlighting remotes in the alternatives.")
66 (defcustom ivy-height 10
67 "Number of lines for the minibuffer window."
70 (defcustom ivy-count-format "%-4d "
71 "The style of showing the current candidate count for `ivy-read'.
72 Set this to nil if you don't want the count."
75 (defcustom ivy-wrap nil
76 "Whether to wrap around after the first and last candidate."
79 (defcustom ivy-on-del-error-function 'minibuffer-keyboard-quit
80 "The handler for when `ivy-backward-delete-char' throws.
81 This is usually meant as a quick exit out of the minibuffer."
84 (defcustom ivy-extra-directories '("../" "./")
85 "Add this to the front of the list when completing file names.
86 Only \"./\" and \"../\" apply here. They appear in reverse order."
89 (defcustom ivy-use-virtual-buffers nil
90 "When non-nil, add `recentf-mode' and bookmarks to the list of buffers."
95 (defvar ivy-minibuffer-map
96 (let ((map (make-sparse-keymap)))
97 (define-key map (kbd "C-m") 'ivy-done)
98 (define-key map (kbd "C-j") 'ivy-alt-done)
99 (define-key map (kbd "TAB") 'ivy-partial-or-done)
100 (define-key map (kbd "C-n") 'ivy-next-line)
101 (define-key map (kbd "C-p") 'ivy-previous-line)
102 (define-key map (kbd "<down>") 'ivy-next-line)
103 (define-key map (kbd "<up>") 'ivy-previous-line)
104 (define-key map (kbd "C-s") 'ivy-next-line-or-history)
105 (define-key map (kbd "C-r") 'ivy-reverse-i-search)
106 (define-key map (kbd "SPC") 'self-insert-command)
107 (define-key map (kbd "DEL") 'ivy-backward-delete-char)
108 (define-key map (kbd "M-DEL") 'ivy-backward-kill-word)
109 (define-key map (kbd "C-d") 'ivy-delete-char)
110 (define-key map (kbd "C-f") 'ivy-forward-char)
111 (define-key map (kbd "M-d") 'ivy-kill-word)
112 (define-key map (kbd "M-<") 'ivy-beginning-of-buffer)
113 (define-key map (kbd "M->") 'ivy-end-of-buffer)
114 (define-key map (kbd "<left>") 'ivy-beginning-of-buffer)
115 (define-key map (kbd "<right>") 'ivy-end-of-buffer)
116 (define-key map (kbd "M-n") 'ivy-next-history-element)
117 (define-key map (kbd "M-p") 'ivy-previous-history-element)
118 (define-key map (kbd "C-g") 'minibuffer-keyboard-quit)
119 (define-key map (kbd "C-v") 'ivy-scroll-up-command)
120 (define-key map (kbd "M-v") 'ivy-scroll-down-command)
121 (define-key map (kbd "C-M-n") 'ivy-next-line-and-call)
122 (define-key map (kbd "C-M-p") 'ivy-previous-line-and-call)
123 (define-key map (kbd "M-q") 'ivy-toggle-regexp-quote)
124 (define-key map (kbd "M-j") 'ivy-yank-word)
125 (define-key map (kbd "M-i") 'ivy-insert-current)
126 (define-key map (kbd "C-o") 'hydra-ivy/body)
127 (define-key map (kbd "C-k") 'ivy-kill-line)
129 "Keymap used in the minibuffer.")
130 (autoload 'hydra-ivy/body "ivy-hydra" "" t)
133 (let ((map (make-sparse-keymap)))
134 (define-key map [remap switch-to-buffer] 'ivy-switch-buffer)
136 "Keymap for `ivy-mode'.")
139 (cl-defstruct ivy-state
141 predicate require-match initial-input
142 history preselect keymap update-fn sort
143 ;; The window in which `ivy-read' was called
149 ;; When this is non-nil, call it for each input change to get new candidates
153 "The last parameters passed to `ivy-read'.")
155 (defsubst ivy-set-action (action)
156 (setf (ivy-state-action ivy-last) action))
158 (defvar ivy-history nil
159 "History list of candidates entered in the minibuffer.
161 Maximum length of the history list is determined by the value
162 of `history-length', which see.")
164 (defvar ivy--directory nil
165 "Current directory when completing file names.")
167 (defvar ivy--length 0
168 "Store the amount of viable candidates.")
171 "Store the user's string as it is typed in.")
173 (defvar ivy--current ""
174 "Current candidate.")
177 "Store the index of the current candidate.")
180 "Store 'done if the completion was successfully selected.
181 Otherwise, store nil.")
183 (defvar ivy--all-candidates nil
184 "Store the candidates passed to `ivy-read'.")
186 (defvar ivy--default nil
187 "Default initial input.")
189 (defvar ivy--prompt nil
190 "Store the format-style prompt.
191 When non-nil, it should contain one %d.")
193 (defvar ivy--prompt-extra ""
194 "Temporary modifications to the prompt.")
196 (defvar ivy--old-re nil
197 "Store the old regexp.")
199 (defvar ivy--old-cands nil
200 "Store the candidates matched by `ivy--old-re'.")
202 (defvar ivy--regex-function 'ivy--regex
203 "Current function for building a regex.")
205 (defvar ivy--subexps 0
206 "Number of groups in the current `ivy--regex'.")
208 (defvar ivy--full-length nil
209 "When :dynamic-collection is non-nil, this can be the total amount of candidates.")
211 (defvar ivy--old-text ""
212 "Store old `ivy-text' for dynamic completion.")
214 (defvar Info-current-file)
216 (defmacro ivy-quit-and-run (&rest body)
217 "Quit the minibuffer and run BODY afterwards."
219 (put 'quit 'error-message "")
222 (put 'quit 'error-message "Quit")
224 (minibuffer-keyboard-quit)))
226 (defun ivy--done (text)
227 "Insert TEXT and exit minibuffer."
228 (if (and ivy--directory
229 (not (eq (ivy-state-history ivy-last) 'grep-files-history)))
230 (insert (setq ivy--current (expand-file-name
231 text ivy--directory)))
232 (insert (setq ivy--current text)))
233 (setq ivy-exit 'done)
238 "Exit the minibuffer with the selected candidate."
240 (delete-minibuffer-contents)
241 (cond ((> ivy--length 0)
242 (ivy--done ivy--current))
243 ((memq (ivy-state-collection ivy-last)
244 '(read-file-name-internal internal-complete-buffer))
245 (if (or (not (eq confirm-nonexistent-file-or-buffer t))
246 (equal " (confirm)" ivy--prompt-extra))
248 (setq ivy--prompt-extra " (confirm)")
251 ((memq (ivy-state-require-match ivy-last)
252 '(nil confirm confirm-after-completion))
253 (ivy--done ivy-text))
255 (setq ivy--prompt-extra " (match required)")
259 (defun ivy-build-tramp-name (x)
260 "Reconstruct X into a path.
261 Is is a cons cell, related to `tramp-get-completion-function'."
265 (concat user "@" domain)
268 (declare-function tramp-get-completion-function "tramp")
269 (declare-function Info-find-node "info")
271 (defun ivy-alt-done (&optional arg)
272 "Exit the minibuffer with the selected candidate.
273 When ARG is t, exit with current text, ignoring the candidates."
277 (ivy-immediate-done))
281 (not (string= ivy--current "./"))
282 (cl-plusp ivy--length)
284 (setq dir (expand-file-name
285 ivy--current ivy--directory))))))
288 ((eq (ivy-state-collection ivy-last) 'Info-read-node-name-1)
289 (if (or (equal ivy--current "(./)")
290 (equal ivy--current "(../)"))
292 (ivy-read "Go to file: " 'read-file-name-internal
295 (expand-file-name x ivy--directory)
299 (string-match "\\`/[^/]+:.*:.*\\'" ivy-text))
303 "\\`/\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
305 (let ((method (match-string 1 ivy-text))
306 (user (match-string 2 ivy-text))
307 (rest (match-string 3 ivy-text))
310 (dolist (x (tramp-get-completion-function method))
311 (setq res (append res (funcall (car x) (cadr x)))))
312 (setq res (delq nil res))
316 (setq res (cl-delete-duplicates res :test #'equal))
317 (let* ((old-ivy-last ivy-last)
318 (enable-recursive-minibuffers t)
319 (host (ivy-read "Find File: "
320 (mapcar #'ivy-build-tramp-name res)
321 :initial-input rest)))
322 (setq ivy-last old-ivy-last)
324 (setq ivy--directory "/")
325 (ivy--cd (concat "/" method ":" host ":"))))))
329 (defcustom ivy-tab-space nil
330 "When non-nil, `ivy-partial-or-done' should insert a space."
333 (defun ivy-partial-or-done ()
334 "Complete the minibuffer text as much as possible.
335 If the text hasn't changed as a result, forward to `ivy-alt-done'."
337 (if (and (eq (ivy-state-collection ivy-last) #'read-file-name-internal)
338 (string-match "\\`/" ivy-text))
339 (let ((default-directory ivy--directory))
340 (minibuffer-complete)
341 (setq ivy-text (ivy--input))
342 (when (and (file-directory-p ivy-text)
344 (ivy--cd (expand-file-name ivy-text))))
346 (when (or (eq this-command last-command)
350 (defun ivy-partial ()
351 "Complete the minibuffer text as much as possible."
353 (let* ((parts (or (split-string ivy-text " " t) (list "")))
354 (postfix (car (last parts)))
355 (completion-ignore-case t)
356 (startp (string-match "^\\^" postfix))
357 (new (try-completion (if startp
358 (substring postfix 1)
360 (mapcar (lambda (str) (substring str (string-match postfix str)))
362 (cond ((eq new t) nil)
363 ((string= new ivy-text) nil)
365 (delete-region (minibuffer-prompt-end) (point-max))
370 (insert (mapconcat #'identity parts " ")
371 (if ivy-tab-space " " ""))
374 (defun ivy-immediate-done ()
375 "Exit the minibuffer with the current input."
377 (delete-minibuffer-contents)
378 (insert (setq ivy--current ivy-text))
379 (setq ivy-exit 'done)
383 "Resume the last completion session."
386 (ivy-state-prompt ivy-last)
387 (ivy-state-collection ivy-last)
388 :predicate (ivy-state-predicate ivy-last)
389 :require-match (ivy-state-require-match ivy-last)
390 :initial-input ivy-text
391 :history (ivy-state-history ivy-last)
392 :preselect (unless (eq (ivy-state-collection ivy-last)
393 'read-file-name-internal)
394 (regexp-quote ivy--current))
395 :keymap (ivy-state-keymap ivy-last)
396 :update-fn (ivy-state-update-fn ivy-last)
397 :sort (ivy-state-sort ivy-last)
398 :action (ivy-state-action ivy-last)
399 :unwind (ivy-state-unwind ivy-last)
400 :re-builder (ivy-state-re-builder ivy-last)
401 :matcher (ivy-state-matcher ivy-last)
402 :dynamic-collection (ivy-state-dynamic-collection ivy-last)))
404 (defvar ivy-calling nil
405 "When non-nil, call the current action when `ivy--index' changes.")
407 (defun ivy-set-index (index)
408 "Set `ivy--index' to INDEX."
409 (setq ivy--index index)
414 (defun ivy-beginning-of-buffer ()
415 "Select the first completion candidate."
419 (defun ivy-end-of-buffer ()
420 "Select the last completion candidate."
422 (ivy-set-index (1- ivy--length)))
424 (defun ivy-scroll-up-command ()
425 "Scroll the candidates upward by the minibuffer height."
427 (ivy-set-index (min (+ ivy--index ivy-height)
430 (defun ivy-scroll-down-command ()
431 "Scroll the candidates downward by the minibuffer height."
433 (ivy-set-index (max (- ivy--index ivy-height)
435 (defun ivy-minibuffer-grow ()
436 "Grow the minibuffer window by 1 line"
438 (setq-local max-mini-window-height
439 (cl-incf ivy-height)))
441 (defun ivy-minibuffer-shrink ()
442 "Shrink the minibuffer window by 1 line."
444 (unless (<= ivy-height 2)
445 (setq-local max-mini-window-height
446 (cl-decf ivy-height))
447 (window-resize (selected-window) -1)))
449 (defun ivy-next-line (&optional arg)
450 "Move cursor vertically down ARG candidates."
452 (setq arg (or arg 1))
453 (let ((index (+ ivy--index arg)))
454 (if (> index (1- ivy--length))
456 (ivy-beginning-of-buffer)
457 (ivy-set-index (1- ivy--length)))
458 (ivy-set-index index))))
460 (defun ivy-next-line-or-history (&optional arg)
461 "Move cursor vertically down ARG candidates.
462 If the input is empty, select the previous history element instead."
464 (when (string= ivy-text "")
465 (ivy-previous-history-element 1))
468 (defun ivy-previous-line (&optional arg)
469 "Move cursor vertically up ARG candidates."
471 (setq arg (or arg 1))
472 (let ((index (- ivy--index arg)))
477 (ivy-set-index index))))
479 (defun ivy-previous-line-or-history (arg)
480 "Move cursor vertically up ARG candidates.
481 If the input is empty, select the previous history element instead."
483 (when (string= ivy-text "")
484 (ivy-previous-history-element 1))
485 (ivy-previous-line arg))
487 (defun ivy-toggle-calling ()
490 (when (setq ivy-calling (not ivy-calling))
494 "Call the current action without exiting completion."
495 (when (ivy-state-action ivy-last)
496 (with-selected-window (ivy-state-window ivy-last)
497 (funcall (ivy-state-action ivy-last) ivy--current))))
499 (defun ivy-next-line-and-call (&optional arg)
500 "Move cursor vertically down ARG candidates.
501 Call the permanent action if possible."
507 (defun ivy-previous-line-and-call (&optional arg)
508 "Move cursor vertically down ARG candidates.
509 Call the permanent action if possible."
511 (ivy-previous-line arg)
515 (defun ivy-previous-history-element (arg)
516 "Forward to `previous-history-element' with ARG."
518 (previous-history-element arg)
521 (ivy--maybe-scroll-history))
523 (defun ivy-next-history-element (arg)
524 "Forward to `next-history-element' with ARG."
526 (next-history-element arg)
529 (ivy--maybe-scroll-history))
531 (defun ivy--cd-maybe ()
532 "Check if the current input points to a different directory.
533 If so, move to that directory, while keeping only the file name."
535 (let* ((input (expand-file-name (ivy--input)))
536 (file (file-name-nondirectory input))
537 (dir (expand-file-name (file-name-directory input))))
538 (if (string= dir ivy--directory)
540 (delete-minibuffer-contents)
545 (defun ivy--maybe-scroll-history ()
546 "If the selected history element has an index, scroll there."
547 (let ((idx (ignore-errors
549 (minibuffer-prompt-end)
553 (setq ivy--index idx))))
556 "When completing file names, move to directory DIR."
557 (if (null ivy--directory)
559 (setq ivy--old-cands nil)
560 (setq ivy--old-re nil)
562 (setq ivy--all-candidates
563 (ivy--sorted-files (setq ivy--directory dir)))
565 (delete-minibuffer-contents)))
567 (defun ivy-backward-delete-char ()
568 "Forward to `backward-delete-char'.
569 On error (read-only), call `ivy-on-del-error-function'."
571 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
573 (ivy--cd (file-name-directory
579 (backward-delete-char 1)
581 (when ivy-on-del-error-function
582 (funcall ivy-on-del-error-function))))))
584 (defun ivy-delete-char (arg)
585 "Forward to `delete-char' ARG."
587 (unless (= (point) (line-end-position))
590 (defun ivy-forward-char (arg)
591 "Forward to `forward-char' ARG."
593 (unless (= (point) (line-end-position))
596 (defun ivy-kill-word (arg)
597 "Forward to `kill-word' ARG."
599 (unless (= (point) (line-end-position))
602 (defun ivy-kill-line ()
603 "Forward to `kill-line'."
606 (kill-region (minibuffer-prompt-end) (point))
609 (defun ivy-backward-kill-word ()
610 "Forward to `backward-kill-word'."
612 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
614 (ivy--cd (file-name-directory
620 (backward-kill-word 1))))
622 (defvar ivy--regexp-quote 'regexp-quote
623 "Store the regexp quoting state.")
625 (defun ivy-toggle-regexp-quote ()
626 "Toggle the regexp quoting."
628 (setq ivy--old-re nil)
629 (cl-rotatef ivy--regex-function ivy--regexp-quote))
631 (defun ivy-sort-file-function-default (x y)
632 "Compare two files X and Y.
633 Prioritize directories."
634 (if (get-text-property 0 'dirp x)
635 (if (get-text-property 0 'dirp y)
638 (if (get-text-property 0 'dirp y)
642 (defvar ivy-sort-functions-alist
643 '((read-file-name-internal . ivy-sort-file-function-default)
644 (internal-complete-buffer . nil)
645 (counsel-git-grep-function . nil)
646 (Man-goto-section . nil)
649 "An alist of sorting functions for each collection function.
650 Interactive functions that call completion fit in here as well.
652 For each entry, nil means no sorting. It's very useful to turn
653 off the sorting for functions that have candidates in the natural
654 buffer order, like `org-refile' or `Man-goto-section'.
656 The entry associated to t is used for all fall-through cases.")
658 (defvar ivy-re-builders-alist
659 '((t . ivy--regex-plus))
660 "An alist of regex building functions for each collection function.
661 Each function should take a string and return a valid regex or a
662 regex sequence (see below).
664 The entry associated to t is used for all fall-through cases.
665 Possible choices: `ivy--regex', `regexp-quote', `ivy--regex-plus'.
667 In case a function returns a list, it should look like this:
668 '((\"matching-regexp\" . t) (\"non-matching-regexp\") ...).
670 The matches will be filtered in a sequence, you can mix the
671 regexps that should match and that should not match as you
674 (defvar ivy-initial-inputs-alist
676 (org-agenda-refile . "^")
677 (org-capture-refile . "^")
679 (counsel-describe-function . "^")
680 (counsel-describe-variable . "^")
683 "Command to initial input table.")
685 (defcustom ivy-sort-max-size 30000
686 "Sorting won't be done for collections larger than this."
689 (defun ivy--sorted-files (dir)
690 "Return the list of files in DIR.
691 Directories come first."
692 (let* ((default-directory dir)
693 (seq (all-completions "" 'read-file-name-internal))
697 (setq seq (delete "./" (delete "../" seq)))
698 (when (eq (setq sort-fn (cdr (assoc 'read-file-name-internal
699 ivy-sort-functions-alist)))
700 #'ivy-sort-file-function-default)
701 (setq seq (mapcar (lambda (x)
702 (propertize x 'dirp (string-match-p "/\\'" x)))
705 (setq seq (cl-sort seq sort-fn)))
706 (dolist (dir ivy-extra-directories)
711 (cl-defun ivy-read (prompt collection
712 &key predicate require-match initial-input
713 history preselect keymap update-fn sort
714 action unwind re-builder matcher dynamic-collection)
715 "Read a string in the minibuffer, with completion.
717 PROMPT is a string to prompt with; normally it ends in a colon
718 and a space. When PROMPT contains %d, it will be updated with
719 the current number of matching candidates.
720 See also `ivy-count-format'.
722 COLLECTION is a list of strings.
724 If INITIAL-INPUT is non-nil, insert it in the minibuffer initially.
726 KEYMAP is composed together with `ivy-minibuffer-map'.
728 If PRESELECT is non-nil select the corresponding candidate out of
729 the ones that match INITIAL-INPUT.
731 UPDATE-FN is called each time the current candidate(s) is changed.
733 When SORT is t, refer to `ivy-sort-functions-alist' for sorting.
735 ACTION is a lambda to call after a result was selected. It should
736 take a single argument, usually a string.
738 UNWIND is a lambda to call before exiting.
740 RE-BUILDER is a lambda that transforms text into a regex.
742 MATCHER can completely override matching.
744 DYNAMIC-COLLECTION is a function to call to update the list of
745 candidates with each input."
749 :collection collection
751 :require-match require-match
752 :initial-input initial-input
759 :window (selected-window)
761 :re-builder re-builder
763 :dynamic-collection dynamic-collection))
764 (ivy--reset-state ivy-last)
767 (minibuffer-with-setup-hook
768 #'ivy--minibuffer-setup
769 (let* ((hist (or history 'ivy-history))
770 (minibuffer-completion-table collection)
771 (minibuffer-completion-predicate predicate)
772 (res (read-from-minibuffer
774 (ivy-state-initial-input ivy-last)
775 (make-composed-keymap keymap ivy-minibuffer-map)
778 (when (eq ivy-exit 'done)
779 (let ((item (if ivy--directory
782 (set hist (cons (propertize item 'ivy-index ivy--index)
784 (cdr (symbol-value hist))))))
786 (remove-hook 'post-command-hook #'ivy--exhibit)
787 (when (setq unwind (ivy-state-unwind ivy-last))
789 (when (setq action (ivy-state-action ivy-last))
790 (funcall action ivy--current))))
792 (defun ivy--reset-state (state)
793 "Reset the ivy to STATE.
794 This is useful for recursive `ivy-read'."
795 (let ((prompt (ivy-state-prompt state))
796 (collection (ivy-state-collection state))
797 (predicate (ivy-state-predicate state))
798 (history (ivy-state-history state))
799 (preselect (ivy-state-preselect state))
800 (sort (ivy-state-sort state))
801 (re-builder (ivy-state-re-builder state))
802 (dynamic-collection (ivy-state-dynamic-collection state))
803 (initial-input (ivy-state-initial-input state))
804 (require-match (ivy-state-require-match state)))
805 (unless initial-input
806 (setq initial-input (cdr (assoc this-command
807 ivy-initial-inputs-alist))))
808 (setq ivy--directory nil)
809 (setq ivy--regex-function
811 (and (functionp collection)
812 (cdr (assoc collection ivy-re-builders-alist)))
813 (cdr (assoc t ivy-re-builders-alist))
815 (setq ivy--subexps 0)
816 (setq ivy--regexp-quote 'regexp-quote)
817 (setq ivy--old-text "")
818 (setq ivy--full-length nil)
820 (setq ivy-calling nil)
822 (cond ((eq collection 'Info-read-node-name-1)
823 (if (equal Info-current-file "dir")
825 (mapcar (lambda (x) (format "(%s)" x))
826 (cl-delete-duplicates
827 (all-completions "(" collection predicate)
829 (setq coll (all-completions "" collection predicate))))
830 ((eq collection 'read-file-name-internal)
831 (setq ivy--directory default-directory)
834 (ivy--sorted-files default-directory))
836 (unless (or require-match
837 (equal initial-input default-directory)
838 (equal initial-input ""))
839 (setq coll (cons initial-input coll)))
840 (setq initial-input nil)))
841 ((eq collection 'internal-complete-buffer)
842 (setq coll (ivy--buffer-list "" ivy-use-virtual-buffers)))
843 ((or (functionp collection)
845 (listp (car collection)))
846 (setq coll (all-completions "" collection predicate)))
847 ((hash-table-p collection)
848 (error "Hash table as a collection unsupported"))
850 (setq coll collection)))
852 (if (and (functionp collection)
853 (setq sort-fn (assoc collection ivy-sort-functions-alist)))
854 (when (and (setq sort-fn (cdr sort-fn))
855 (not (eq collection 'read-file-name-internal)))
856 (setq coll (cl-sort coll sort-fn)))
857 (unless (eq history 'org-refile-history)
858 (if (and (setq sort-fn (cdr (assoc t ivy-sort-functions-alist)))
859 (<= (length coll) ivy-sort-max-size))
860 (setq coll (cl-sort (copy-sequence coll) sort-fn))))))
862 (unless (or (and require-match
863 (not (eq collection 'internal-complete-buffer)))
864 (let ((re (format "\\`%s" (regexp-quote preselect))))
865 (cl-find-if (lambda (x) (string-match re x))
867 (setq coll (cons preselect coll))))
869 (and dynamic-collection
872 (ivy--preselect-index
873 coll initial-input preselect))
875 (setq ivy--old-re nil)
876 (setq ivy--old-cands nil)
877 (setq ivy--all-candidates coll))
879 (setq ivy--default (or (thing-at-point 'symbol) ""))
881 (cond ((string-match "%.*d" prompt)
883 ((string-match "%.*d" ivy-count-format)
884 (concat ivy-count-format prompt))
889 (setf (ivy-state-initial-input ivy-last) initial-input)))
891 (defun ivy-completing-read (prompt collection
892 &optional predicate require-match initial-input
893 history def _inherit-input-method)
894 "Read a string in the minibuffer, with completion.
896 This is an interface that conforms to `completing-read', so that
897 it can be used for `completing-read-function'.
899 PROMPT is a string to prompt with; normally it ends in a colon and a space.
900 COLLECTION can be a list of strings, an alist, an obarray or a hash table.
901 PREDICATE limits completion to a subset of COLLECTION.
902 REQUIRE-MATCH is considered boolean. See `completing-read'.
903 INITIAL-INPUT is a string that can be inserted into the minibuffer initially.
904 _HISTORY is ignored for now.
905 DEF is the default value.
906 _INHERIT-INPUT-METHOD is ignored for now.
908 The history, defaults and input-method arguments are ignored for now."
909 (ivy-read prompt collection
911 :require-match require-match
912 :initial-input (if (consp initial-input)
915 :preselect (if (listp def) (car def) def)
919 (let ((sort (assoc this-command ivy-sort-functions-alist)))
925 (define-minor-mode ivy-mode
926 "Toggle Ivy mode on or off.
927 With ARG, turn Ivy mode on if arg is positive, off otherwise.
928 Turning on Ivy mode will set `completing-read-function' to
929 `ivy-completing-read'.
935 \\{ivy-minibuffer-map}"
941 (setq completing-read-function 'ivy-completing-read)
942 (setq completing-read-function 'completing-read-default)))
944 (defun ivy--preselect-index (candidates initial-input preselect)
945 "Return the index in CANDIDATES filtered by INITIAL-INPUT for PRESELECT."
947 (setq initial-input (ivy--regex-plus initial-input))
951 (string-match initial-input x))
953 (or (cl-position preselect candidates :test #'equal)
956 (string-match (regexp-quote preselect) x))
961 (defvar ivy--regex-hash
962 (make-hash-table :test #'equal)
963 "Store pre-computed regex.")
965 (defun ivy--split (str)
966 "Split STR into a list by single spaces.
967 The remaining spaces stick to their left.
968 This allows to \"quote\" N spaces by inputting N+1 spaces."
969 (let ((len (length str))
974 (while (and (string-match " +" str start1)
976 (setq match-len (- (match-end 0) (match-beginning 0)))
982 (push (substring str start1 (match-beginning 0)) res)
983 (setq start1 (match-end 0)))
984 (setq str (replace-match
985 (make-string (1- match-len) ?\ )
987 (setq start0 (or start0 start1))
988 (setq start1 (1- (match-end 0)))))
990 (push (substring str start0) res)
991 (setq s (substring str start1))
992 (unless (= (length s) 0)
996 (defun ivy--regex (str &optional greedy)
997 "Re-build regex from STR in case it has a space.
998 When GREEDY is non-nil, join words in a greedy way."
999 (let ((hashed (unless greedy
1000 (gethash str ivy--regex-hash))))
1003 (setq ivy--subexps (car hashed)))
1005 (let ((subs (ivy--split str)))
1006 (if (= (length subs) 1)
1008 (setq ivy--subexps 0)
1011 (setq ivy--subexps (length subs))
1014 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1016 (format "\\(%s\\)" x)))
1021 ivy--regex-hash)))))
1023 (defun ivy--regex-ignore-order (str)
1024 "Re-build regex from STR by splitting it on spaces.
1025 Ignore the order of each group."
1026 (let* ((subs (split-string str " +" t))
1027 (len (length subs)))
1030 (setq ivy--subexps 0)
1033 (setq ivy--subexps len)
1034 (let ((all (mapconcat #'identity subs "\\|")))
1037 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1039 (format "\\(%s\\)" x)))
1043 (defun ivy--regex-plus (str)
1044 "Build a regex sequence from STR.
1045 Spaces are wild, everything before \"!\" should match.
1046 Everything after \"!\" should not match."
1047 (let ((parts (split-string str "!" t)))
1048 (cl-case (length parts)
1052 (ivy--regex (car parts)))
1056 (split-string (cadr parts) " " t))))
1057 (cons (cons (ivy--regex (car parts)) t)
1059 (t (error "Unexpected: use only one !")))))
1061 (defun ivy--regex-fuzzy (str)
1062 "Build a regex sequence from STR.
1063 Insert .* between each char."
1064 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1065 (concat (match-string 1 str)
1066 (mapconcat #'string (string-to-list (match-string 2 str)) ".*")
1067 (match-string 3 str))
1071 (defun ivy--minibuffer-setup ()
1072 "Setup ivy completion in the minibuffer."
1073 (set (make-local-variable 'completion-show-inline-help) nil)
1074 (set (make-local-variable 'minibuffer-default-add-function)
1076 (list ivy--default)))
1077 (setq-local max-mini-window-height ivy-height)
1078 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1079 ;; show completions with empty input
1082 (defun ivy--input ()
1083 "Return the current minibuffer input."
1084 ;; assume one-line minibuffer input
1085 (buffer-substring-no-properties
1086 (minibuffer-prompt-end)
1087 (line-end-position)))
1089 (defun ivy--cleanup ()
1090 "Delete the displayed completion candidates."
1092 (goto-char (minibuffer-prompt-end))
1093 (delete-region (line-end-position) (point-max))))
1095 (defun ivy--insert-prompt ()
1096 "Update the prompt according to `ivy--prompt'."
1098 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1099 counsel-find-symbol))
1100 (setq ivy--prompt-extra ""))
1102 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1104 (setq head (match-string 1 ivy--prompt))
1106 (setq head (substring ivy--prompt 0 -1))
1108 (let ((inhibit-read-only t)
1109 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1113 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1114 (> (minibuffer-depth) 1))
1115 (format "[%d] " (minibuffer-depth))
1121 (abbreviate-file-name ivy--directory)
1123 (or (and (ivy-state-dynamic-collection ivy-last)
1127 (goto-char (point-min))
1128 (delete-region (point-min) (minibuffer-prompt-end))
1129 (set-text-properties 0 (length n-str)
1130 `(face minibuffer-prompt ,@std-props)
1132 (ivy--set-match-props n-str "confirm"
1133 `(face ivy-confirm-face ,@std-props))
1134 (ivy--set-match-props n-str "match required"
1135 `(face ivy-match-required-face ,@std-props))
1137 ;; get out of the prompt area
1138 (constrain-to-field nil (point-max))))))
1140 (defun ivy--set-match-props (str match props)
1141 "Set STR text proprties that match MATCH to PROPS."
1142 (when (string-match match str)
1143 (set-text-properties
1149 (defvar inhibit-message)
1151 (defun ivy--exhibit ()
1152 "Insert Ivy completions display.
1153 Should be run via minibuffer `post-command-hook'."
1154 (setq ivy-text (ivy--input))
1155 (if (ivy-state-dynamic-collection ivy-last)
1156 ;; while-no-input would cause annoying
1157 ;; "Waiting for process to die...done" message interruptions
1158 (let ((inhibit-message t))
1159 (unless (equal ivy--old-text ivy-text)
1161 ;; dynamic collection should take care of everything
1162 (funcall (ivy-state-dynamic-collection ivy-last) ivy-text)
1163 (setq ivy--old-text ivy-text)))
1164 (unless (eq ivy--full-length -1)
1165 (ivy--insert-minibuffer
1166 (ivy--format ivy--all-candidates))))
1167 (cond (ivy--directory
1168 (if (string-match "/\\'" ivy-text)
1169 (if (member ivy-text ivy--all-candidates)
1170 (ivy--cd (expand-file-name ivy-text ivy--directory))
1171 (when (string-match "//\\'" ivy-text)
1172 (if (and default-directory
1173 (string-match "\\`[[:alpha:]]:/" default-directory))
1174 (ivy--cd (match-string 0 default-directory))
1176 (when (string-match "[[:alpha:]]:/" ivy-text)
1177 (let ((drive-root (match-string 0 ivy-text)))
1178 (when (file-exists-p drive-root)
1179 (ivy--cd drive-root)))))
1180 (if (string-match "\\`~\\'" ivy-text)
1181 (ivy--cd (expand-file-name "~/")))))
1182 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1183 (when (or (and (string-match "\\` " ivy-text)
1184 (not (string-match "\\` " ivy--old-text)))
1185 (and (string-match "\\` " ivy--old-text)
1186 (not (string-match "\\` " ivy-text))))
1187 (setq ivy--all-candidates
1188 (if (and (> (length ivy-text) 0)
1189 (eq (aref ivy-text 0)
1191 (ivy--buffer-list " ")
1192 (ivy--buffer-list "" ivy-use-virtual-buffers)))
1193 (setq ivy--old-re nil))))
1194 (ivy--insert-minibuffer
1196 (ivy--filter ivy-text ivy--all-candidates)))
1197 (setq ivy--old-text ivy-text)))
1199 (defun ivy--insert-minibuffer (text)
1200 "Insert TEXT into minibuffer with appropriate cleanup."
1201 (let ((resize-mini-windows nil)
1202 (update-fn (ivy-state-update-fn ivy-last))
1206 (funcall update-fn))
1207 (ivy--insert-prompt)
1208 ;; Do nothing if while-no-input was aborted.
1209 (when (stringp text)
1210 (let ((buffer-undo-list t))
1215 (declare-function colir-blend-face-background "ext:colir")
1217 (defun ivy--add-face (str face)
1218 "Propertize STR with FACE.
1219 `font-lock-append-text-property' is used, since it's better than
1220 `propertize' or `add-face-text-property' in this case."
1223 (colir-blend-face-background 0 (length str) face str)
1226 (font-lock-append-text-property 0 (length str) 'face face str))))
1229 (defun ivy--filter (name candidates)
1230 "Return all items that match NAME in CANDIDATES.
1231 CANDIDATES are assumed to be static."
1232 (let* ((re (funcall ivy--regex-function name))
1233 (matcher (ivy-state-matcher ivy-last))
1236 (funcall matcher re candidates))
1237 ((and (equal re ivy--old-re)
1242 (stringp ivy--old-re)
1243 (not (string-match "\\\\" ivy--old-re))
1244 (not (equal ivy--old-re ""))
1246 (if (string-match "\\\\)\\'" ivy--old-re)
1247 (substring ivy--old-re 0 -2)
1253 (lambda (x) (string-match re x))
1256 (let ((re-list (if (stringp re) (list (cons re t)) re))
1258 (dolist (re re-list)
1265 (let ((re (car re)))
1266 (lambda (x) (string-match re x)))
1269 (tail (nthcdr ivy--index ivy--old-cands))
1271 (when (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
1272 (unless (and (not (equal re ivy--old-re))
1273 (or (setq ivy--index
1275 (cl-position re cands
1279 (concat re "/") cands
1281 (while (and tail (null idx))
1282 ;; Compare with eq to handle equal duplicates in cands
1283 (setq idx (cl-position (pop tail) cands)))
1284 (setq ivy--index (or idx 0))))
1285 (when (and (string= name "") (not (equal ivy--old-re "")))
1287 (or (cl-position (ivy-state-preselect ivy-last)
1288 cands :test #'equal)
1290 (setq ivy--old-re (if cands re ""))
1291 (setq ivy--old-cands cands)))
1293 (defvar ivy-format-function 'ivy-format-function-default
1294 "Function to transform the list of candidates into a string.
1295 This string will be inserted into the minibuffer.")
1297 (defun ivy-format-function-default (cands)
1298 "Transform CANDS into a string for minibuffer."
1299 (let ((ww (window-width)))
1302 (if (> (length s) ww)
1303 (concat (substring s 0 (- ww 3)) "...")
1307 (defun ivy-format-function-arrow (cands)
1308 "Transform CANDS into a string for minibuffer."
1312 (concat (if (eq (cl-incf i) ivy--index)
1318 (defun ivy--format (cands)
1319 "Return a string for CANDS suitable for display in the minibuffer.
1320 CANDS is a list of strings."
1321 (setq ivy--length (length cands))
1322 (when (>= ivy--index ivy--length)
1323 (setq ivy--index (max (1- ivy--length) 0)))
1325 (setq ivy--current "")
1326 (let* ((half-height (/ ivy-height 2))
1327 (start (max 0 (- ivy--index half-height)))
1328 (end (min (+ start (1- ivy-height)) ivy--length))
1329 (start (max 0 (min start (- end (1- ivy-height)))))
1330 (cands (cl-subseq cands start end))
1331 (index (- ivy--index start)))
1332 (when ivy--directory
1333 (setq cands (mapcar (lambda (x)
1334 (if (string-match-p "/\\'" x)
1335 (propertize x 'face 'ivy-subdir)
1338 (setq ivy--current (copy-sequence (nth index cands)))
1339 (setf (nth index cands)
1340 (ivy--add-face ivy--current 'ivy-current-match))
1343 (let ((s (copy-sequence s)))
1344 (when (fboundp 'add-face-text-property)
1345 (add-face-text-property
1347 `(:height ,(face-attribute 'default :height)
1348 :overline nil) nil s))
1351 (let* ((ivy--index index)
1352 (res (concat "\n" (funcall ivy-format-function cands))))
1353 (put-text-property 0 (length res) 'read-only nil res)
1356 (defvar ivy--virtual-buffers nil
1357 "Store the virtual buffers alist.")
1359 (defvar recentf-list)
1361 (defface ivy-virtual '((t :inherit font-lock-builtin-face))
1362 "Face used by Ivy for matching virtual buffer names.")
1364 (defun ivy--virtual-buffers ()
1365 "Adapted from `ido-add-virtual-buffers-to-list'."
1366 (unless recentf-mode
1368 (let ((bookmarks (and (boundp 'bookmark-alist)
1370 virtual-buffers name)
1371 (dolist (head (append
1373 (delete " - no file -"
1374 (delq nil (mapcar (lambda (bookmark)
1375 (cdr (assoc 'filename bookmark)))
1377 (setq name (file-name-nondirectory head))
1378 (when (equal name "")
1379 (setq name (file-name-nondirectory (directory-file-name head))))
1380 (when (equal name "")
1382 (and (not (equal name ""))
1383 (null (get-file-buffer head))
1384 (not (assoc name virtual-buffers))
1385 (push (cons name head) virtual-buffers)))
1386 (when virtual-buffers
1387 (dolist (comp virtual-buffers)
1388 (put-text-property 0 (length (car comp))
1391 (setq ivy--virtual-buffers (nreverse virtual-buffers))
1392 (mapcar #'car ivy--virtual-buffers))))
1394 (defun ivy--buffer-list (str &optional virtual)
1395 "Return the buffers that match STR.
1396 When VIRTUAL is non-nil, add virtual buffers."
1401 (if (with-current-buffer x
1403 (abbreviate-file-name default-directory)))
1404 (propertize x 'face 'ivy-remote)
1406 (all-completions str 'internal-complete-buffer))
1408 (ivy--virtual-buffers)))))
1410 (defun ivy--switch-buffer-action (buffer)
1412 BUFFER may be a string or nil."
1413 (if (zerop (length buffer))
1415 ivy-text nil 'force-same-window)
1416 (let ((virtual (assoc buffer ivy--virtual-buffers)))
1418 (not (get-buffer buffer)))
1419 (find-file (cdr virtual))
1421 buffer nil 'force-same-window)))))
1423 (defun ivy-switch-buffer ()
1424 "Switch to another buffer."
1427 (call-interactively 'switch-to-buffer)
1428 (ivy-read "Switch to buffer: " 'internal-complete-buffer
1429 :preselect (buffer-name (other-buffer (current-buffer)))
1430 :action #'ivy--switch-buffer-action)))
1432 (defun ivy-recentf ()
1433 "Find a file on `recentf-list'."
1435 (ivy-read "Recentf: " recentf-list
1436 :action #'find-file))
1438 (defun ivy-yank-word ()
1439 "Pull next word from buffer into search string."
1442 (with-selected-window (ivy-state-window ivy-last)
1444 (le (line-end-position)))
1448 (setq amend (buffer-substring-no-properties pt (point))))))
1452 (defun ivy-insert-current ()
1453 "Make the current candidate into current input.
1454 Don't finish completion."
1456 (delete-minibuffer-contents)
1457 (if (and ivy--directory
1458 (string-match "/$" ivy--current))
1459 (insert (substring ivy--current 0 -1))
1460 (insert ivy--current)))
1462 (defun ivy-toggle-fuzzy ()
1463 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
1465 (setq ivy--old-re nil)
1466 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
1467 (setq ivy--regex-function 'ivy--regex-plus)
1468 (setq ivy--regex-function 'ivy--regex-fuzzy)))
1470 (defun ivy-reverse-i-search ()
1471 "Enter a recursive `ivy-read' session using the current history.
1472 The selected history element will be inserted into the minibufer."
1474 (let ((enable-recursive-minibuffers t)
1475 (history (symbol-value (ivy-state-history ivy-last)))
1476 (old-last ivy-last))
1477 (ivy-read "Reverse-i-search: "
1481 (setq ivy-last old-last))
1482 (delete-minibuffer-contents)
1483 (insert (substring-no-properties x))
1488 ;;; ivy.el ends here