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-previous-line-or-history)
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 (host (ivy-read "Find File: "
319 (mapcar #'ivy-build-tramp-name res)
320 :initial-input rest)))
321 (setq ivy-last old-ivy-last)
323 (setq ivy--directory "/")
324 (ivy--cd (concat "/" method ":" host ":"))))))
328 (defcustom ivy-tab-space nil
329 "When non-nil, `ivy-partial-or-done' should insert a space."
332 (defun ivy-partial-or-done ()
333 "Complete the minibuffer text as much as possible.
334 If the text hasn't changed as a result, forward to `ivy-alt-done'."
336 (if (and (eq (ivy-state-collection ivy-last) #'read-file-name-internal)
337 (string-match "\\`/" ivy-text))
338 (let ((default-directory ivy--directory))
339 (minibuffer-complete)
340 (setq ivy-text (ivy--input))
341 (when (and (file-directory-p ivy-text)
343 (ivy--cd (expand-file-name ivy-text))))
345 (when (or (eq this-command last-command)
349 (defun ivy-partial ()
350 "Complete the minibuffer text as much as possible."
352 (let* ((parts (or (split-string ivy-text " " t) (list "")))
353 (postfix (car (last parts)))
354 (completion-ignore-case t)
355 (startp (string-match "^\\^" postfix))
356 (new (try-completion (if startp
357 (substring postfix 1)
359 (mapcar (lambda (str) (substring str (string-match postfix str)))
361 (cond ((eq new t) nil)
362 ((string= new ivy-text) nil)
364 (delete-region (minibuffer-prompt-end) (point-max))
369 (insert (mapconcat #'identity parts " ")
370 (if ivy-tab-space " " ""))
373 (defun ivy-immediate-done ()
374 "Exit the minibuffer with the current input."
376 (delete-minibuffer-contents)
377 (insert (setq ivy--current ivy-text))
378 (setq ivy-exit 'done)
382 "Resume the last completion session."
385 (ivy-state-prompt ivy-last)
386 (ivy-state-collection ivy-last)
387 :predicate (ivy-state-predicate ivy-last)
388 :require-match (ivy-state-require-match ivy-last)
389 :initial-input ivy-text
390 :history (ivy-state-history ivy-last)
391 :preselect (unless (eq (ivy-state-collection ivy-last)
392 'read-file-name-internal)
393 (regexp-quote ivy--current))
394 :keymap (ivy-state-keymap ivy-last)
395 :update-fn (ivy-state-update-fn ivy-last)
396 :sort (ivy-state-sort ivy-last)
397 :action (ivy-state-action ivy-last)
398 :unwind (ivy-state-unwind ivy-last)
399 :re-builder (ivy-state-re-builder ivy-last)
400 :matcher (ivy-state-matcher ivy-last)
401 :dynamic-collection (ivy-state-dynamic-collection ivy-last)))
403 (defvar ivy-calling nil
404 "When non-nil, call the current action when `ivy--index' changes.")
406 (defun ivy-set-index (index)
407 "Set `ivy--index' to INDEX."
408 (setq ivy--index index)
413 (defun ivy-beginning-of-buffer ()
414 "Select the first completion candidate."
418 (defun ivy-end-of-buffer ()
419 "Select the last completion candidate."
421 (ivy-set-index (1- ivy--length)))
423 (defun ivy-scroll-up-command ()
424 "Scroll the candidates upward by the minibuffer height."
426 (ivy-set-index (min (+ ivy--index ivy-height)
429 (defun ivy-scroll-down-command ()
430 "Scroll the candidates downward by the minibuffer height."
432 (ivy-set-index (max (- ivy--index ivy-height)
434 (defun ivy-minibuffer-grow ()
435 "Grow the minibuffer window by 1 line"
437 (setq-local max-mini-window-height
438 (cl-incf ivy-height)))
440 (defun ivy-minibuffer-shrink ()
441 "Shrink the minibuffer window by 1 line."
443 (unless (<= ivy-height 2)
444 (setq-local max-mini-window-height
445 (cl-decf ivy-height))
446 (window-resize (selected-window) -1)))
448 (defun ivy-next-line (&optional arg)
449 "Move cursor vertically down ARG candidates."
451 (setq arg (or arg 1))
452 (let ((index (+ ivy--index arg)))
453 (if (> index (1- ivy--length))
455 (ivy-beginning-of-buffer)
456 (ivy-set-index (1- ivy--length)))
457 (ivy-set-index index))))
459 (defun ivy-next-line-or-history (&optional arg)
460 "Move cursor vertically down ARG candidates.
461 If the input is empty, select the previous history element instead."
463 (when (string= ivy-text "")
464 (ivy-previous-history-element 1))
467 (defun ivy-previous-line (&optional arg)
468 "Move cursor vertically up ARG candidates."
470 (setq arg (or arg 1))
471 (let ((index (- ivy--index arg)))
476 (ivy-set-index index))))
478 (defun ivy-previous-line-or-history (arg)
479 "Move cursor vertically up ARG candidates.
480 If the input is empty, select the previous history element instead."
482 (when (string= ivy-text "")
483 (ivy-previous-history-element 1))
484 (ivy-previous-line arg))
486 (defun ivy-toggle-calling ()
489 (when (setq ivy-calling (not ivy-calling))
493 "Call the current action without exiting completion."
494 (when (ivy-state-action ivy-last)
495 (with-selected-window (ivy-state-window ivy-last)
496 (funcall (ivy-state-action ivy-last) ivy--current))))
498 (defun ivy-next-line-and-call (&optional arg)
499 "Move cursor vertically down ARG candidates.
500 Call the permanent action if possible."
506 (defun ivy-previous-line-and-call (&optional arg)
507 "Move cursor vertically down ARG candidates.
508 Call the permanent action if possible."
510 (ivy-previous-line arg)
514 (defun ivy-previous-history-element (arg)
515 "Forward to `previous-history-element' with ARG."
517 (previous-history-element arg)
520 (ivy--maybe-scroll-history))
522 (defun ivy-next-history-element (arg)
523 "Forward to `next-history-element' with ARG."
525 (next-history-element arg)
528 (ivy--maybe-scroll-history))
530 (defun ivy--cd-maybe ()
531 "Check if the current input points to a different directory.
532 If so, move to that directory, while keeping only the file name."
534 (let* ((input (expand-file-name (ivy--input)))
535 (file (file-name-nondirectory input))
536 (dir (expand-file-name (file-name-directory input))))
537 (if (string= dir ivy--directory)
539 (delete-minibuffer-contents)
544 (defun ivy--maybe-scroll-history ()
545 "If the selected history element has an index, scroll there."
546 (let ((idx (ignore-errors
548 (minibuffer-prompt-end)
552 (setq ivy--index idx))))
555 "When completing file names, move to directory DIR."
556 (if (null ivy--directory)
558 (setq ivy--old-cands nil)
559 (setq ivy--old-re nil)
561 (setq ivy--all-candidates
562 (ivy--sorted-files (setq ivy--directory dir)))
564 (delete-minibuffer-contents)))
566 (defun ivy-backward-delete-char ()
567 "Forward to `backward-delete-char'.
568 On error (read-only), call `ivy-on-del-error-function'."
570 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
572 (ivy--cd (file-name-directory
578 (backward-delete-char 1)
580 (when ivy-on-del-error-function
581 (funcall ivy-on-del-error-function))))))
583 (defun ivy-delete-char (arg)
584 "Forward to `delete-char' ARG."
586 (unless (= (point) (line-end-position))
589 (defun ivy-forward-char (arg)
590 "Forward to `forward-char' ARG."
592 (unless (= (point) (line-end-position))
595 (defun ivy-kill-word (arg)
596 "Forward to `kill-word' ARG."
598 (unless (= (point) (line-end-position))
601 (defun ivy-kill-line ()
602 "Forward to `kill-line'."
605 (kill-region (minibuffer-prompt-end) (point))
608 (defun ivy-backward-kill-word ()
609 "Forward to `backward-kill-word'."
611 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
613 (ivy--cd (file-name-directory
619 (backward-kill-word 1))))
621 (defvar ivy--regexp-quote 'regexp-quote
622 "Store the regexp quoting state.")
624 (defun ivy-toggle-regexp-quote ()
625 "Toggle the regexp quoting."
627 (setq ivy--old-re nil)
628 (cl-rotatef ivy--regex-function ivy--regexp-quote))
630 (defun ivy-sort-file-function-default (x y)
631 "Compare two files X and Y.
632 Prioritize directories."
633 (if (get-text-property 0 'dirp x)
634 (if (get-text-property 0 'dirp y)
637 (if (get-text-property 0 'dirp y)
641 (defvar ivy-sort-functions-alist
642 '((read-file-name-internal . ivy-sort-file-function-default)
643 (internal-complete-buffer . nil)
644 (counsel-git-grep-function . nil)
645 (Man-goto-section . nil)
648 "An alist of sorting functions for each collection function.
649 Interactive functions that call completion fit in here as well.
651 For each entry, nil means no sorting. It's very useful to turn
652 off the sorting for functions that have candidates in the natural
653 buffer order, like `org-refile' or `Man-goto-section'.
655 The entry associated to t is used for all fall-through cases.")
657 (defvar ivy-re-builders-alist
658 '((t . ivy--regex-plus))
659 "An alist of regex building functions for each collection function.
660 Each function should take a string and return a valid regex or a
661 regex sequence (see below).
663 The entry associated to t is used for all fall-through cases.
664 Possible choices: `ivy--regex', `regexp-quote', `ivy--regex-plus'.
666 In case a function returns a list, it should look like this:
667 '((\"matching-regexp\" . t) (\"non-matching-regexp\") ...).
669 The matches will be filtered in a sequence, you can mix the
670 regexps that should match and that should not match as you
673 (defvar ivy-initial-inputs-alist
676 (counsel-describe-function . "^")
677 (counsel-describe-variable . "^")
680 "Command to initial input table.")
682 (defcustom ivy-sort-max-size 30000
683 "Sorting won't be done for collections larger than this."
686 (defun ivy--sorted-files (dir)
687 "Return the list of files in DIR.
688 Directories come first."
689 (let* ((default-directory dir)
690 (seq (all-completions "" 'read-file-name-internal))
694 (setq seq (delete "./" (delete "../" seq)))
695 (when (eq (setq sort-fn (cdr (assoc 'read-file-name-internal
696 ivy-sort-functions-alist)))
697 #'ivy-sort-file-function-default)
698 (setq seq (mapcar (lambda (x)
699 (propertize x 'dirp (string-match-p "/\\'" x)))
702 (setq seq (cl-sort seq sort-fn)))
703 (dolist (dir ivy-extra-directories)
708 (cl-defun ivy-read (prompt collection
709 &key predicate require-match initial-input
710 history preselect keymap update-fn sort
711 action unwind re-builder matcher dynamic-collection)
712 "Read a string in the minibuffer, with completion.
714 PROMPT is a string to prompt with; normally it ends in a colon
715 and a space. When PROMPT contains %d, it will be updated with
716 the current number of matching candidates.
717 See also `ivy-count-format'.
719 COLLECTION is a list of strings.
721 If INITIAL-INPUT is non-nil, insert it in the minibuffer initially.
723 KEYMAP is composed together with `ivy-minibuffer-map'.
725 If PRESELECT is non-nil select the corresponding candidate out of
726 the ones that match INITIAL-INPUT.
728 UPDATE-FN is called each time the current candidate(s) is changed.
730 When SORT is t, refer to `ivy-sort-functions-alist' for sorting.
732 ACTION is a lambda to call after a result was selected. It should
733 take a single argument, usually a string.
735 UNWIND is a lambda to call before exiting.
737 RE-BUILDER is a lambda that transforms text into a regex.
739 MATCHER can completely override matching.
741 DYNAMIC-COLLECTION is a function to call to update the list of
742 candidates with each input."
743 (unless initial-input
744 (setq initial-input (cdr (assoc this-command
745 ivy-initial-inputs-alist))))
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 (setq ivy--directory nil)
765 (setq ivy--regex-function
767 (and (functionp collection)
768 (cdr (assoc collection ivy-re-builders-alist)))
769 (cdr (assoc t ivy-re-builders-alist))
771 (setq ivy--subexps 0)
772 (setq ivy--regexp-quote 'regexp-quote)
773 (setq ivy--old-text "")
775 (setq ivy-calling nil)
777 (cond ((eq collection 'Info-read-node-name-1)
778 (if (equal Info-current-file "dir")
780 (mapcar (lambda (x) (format "(%s)" x))
781 (cl-delete-duplicates
782 (all-completions "(" collection predicate)
784 (setq coll (all-completions "" collection predicate))))
785 ((eq collection 'read-file-name-internal)
786 (setq ivy--directory default-directory)
789 (ivy--sorted-files default-directory))
791 (unless (or require-match
792 (equal initial-input default-directory)
793 (equal initial-input ""))
794 (setq coll (cons initial-input coll)))
795 (setq initial-input nil)))
796 ((eq collection 'internal-complete-buffer)
797 (setq coll (ivy--buffer-list "" ivy-use-virtual-buffers)))
798 ((or (functionp collection)
800 (listp (car collection)))
801 (setq coll (all-completions "" collection predicate)))
802 ((hash-table-p collection)
803 (error "Hash table as a collection unsupported"))
805 (setq coll collection)))
807 (if (and (functionp collection)
808 (setq sort-fn (assoc collection ivy-sort-functions-alist)))
809 (when (and (setq sort-fn (cdr sort-fn))
810 (not (eq collection 'read-file-name-internal)))
811 (setq coll (cl-sort coll sort-fn)))
812 (unless (eq history 'org-refile-history)
813 (if (and (setq sort-fn (cdr (assoc t ivy-sort-functions-alist)))
814 (<= (length coll) ivy-sort-max-size))
815 (setq coll (cl-sort (copy-sequence coll) sort-fn))))))
817 (unless (or (and require-match
818 (not (eq collection 'internal-complete-buffer)))
819 (let ((re (format "\\`%s" (regexp-quote preselect))))
820 (cl-find-if (lambda (x) (string-match re x))
822 (setq coll (cons preselect coll))))
824 (and dynamic-collection
827 (ivy--preselect-index
828 coll initial-input preselect))
830 (setq ivy--old-re nil)
831 (setq ivy--old-cands nil)
832 (setq ivy--all-candidates coll)
834 (setq ivy--default (or (thing-at-point 'symbol) ""))
836 (cond ((string-match "%.*d" prompt)
838 ((string-match "%.*d" ivy-count-format)
839 (concat ivy-count-format prompt))
846 (minibuffer-with-setup-hook
847 #'ivy--minibuffer-setup
848 (let* ((hist (or history 'ivy-history))
849 (minibuffer-completion-table collection)
850 (minibuffer-completion-predicate predicate)
851 (res (read-from-minibuffer
854 (make-composed-keymap keymap ivy-minibuffer-map)
857 (when (eq ivy-exit 'done)
858 (let ((item (if ivy--directory
861 (set hist (cons (propertize item 'ivy-index ivy--index)
863 (cdr (symbol-value hist))))))
865 (remove-hook 'post-command-hook #'ivy--exhibit)
866 (when (setq unwind (ivy-state-unwind ivy-last))
868 (when (setq action (ivy-state-action ivy-last))
869 (funcall action ivy--current)))))
871 (defun ivy-completing-read (prompt collection
872 &optional predicate require-match initial-input
873 history def _inherit-input-method)
874 "Read a string in the minibuffer, with completion.
876 This is an interface that conforms to `completing-read', so that
877 it can be used for `completing-read-function'.
879 PROMPT is a string to prompt with; normally it ends in a colon and a space.
880 COLLECTION can be a list of strings, an alist, an obarray or a hash table.
881 PREDICATE limits completion to a subset of COLLECTION.
882 REQUIRE-MATCH is considered boolean. See `completing-read'.
883 INITIAL-INPUT is a string that can be inserted into the minibuffer initially.
884 _HISTORY is ignored for now.
885 DEF is the default value.
886 _INHERIT-INPUT-METHOD is ignored for now.
888 The history, defaults and input-method arguments are ignored for now."
889 (ivy-read prompt collection
891 :require-match require-match
892 :initial-input (if (consp initial-input)
895 :preselect (if (listp def) (car def) def)
899 (let ((sort (assoc this-command ivy-sort-functions-alist)))
905 (define-minor-mode ivy-mode
906 "Toggle Ivy mode on or off.
907 With ARG, turn Ivy mode on if arg is positive, off otherwise.
908 Turning on Ivy mode will set `completing-read-function' to
909 `ivy-completing-read'.
915 \\{ivy-minibuffer-map}"
921 (setq completing-read-function 'ivy-completing-read)
922 (setq completing-read-function 'completing-read-default)))
924 (defun ivy--preselect-index (candidates initial-input preselect)
925 "Return the index in CANDIDATES filtered by INITIAL-INPUT for PRESELECT."
927 (setq initial-input (ivy--regex-plus initial-input))
931 (string-match initial-input x))
933 (or (cl-position preselect candidates :test #'equal)
936 (string-match (regexp-quote preselect) x))
941 (defvar ivy--regex-hash
942 (make-hash-table :test #'equal)
943 "Store pre-computed regex.")
945 (defun ivy--split (str)
946 "Split STR into a list by single spaces.
947 The remaining spaces stick to their left.
948 This allows to \"quote\" N spaces by inputting N+1 spaces."
949 (let ((len (length str))
954 (while (and (string-match " +" str start1)
956 (setq match-len (- (match-end 0) (match-beginning 0)))
962 (push (substring str start1 (match-beginning 0)) res)
963 (setq start1 (match-end 0)))
964 (setq str (replace-match
965 (make-string (1- match-len) ?\ )
967 (setq start0 (or start0 start1))
968 (setq start1 (1- (match-end 0)))))
970 (push (substring str start0) res)
971 (setq s (substring str start1))
972 (unless (= (length s) 0)
976 (defun ivy--regex (str &optional greedy)
977 "Re-build regex from STR in case it has a space.
978 When GREEDY is non-nil, join words in a greedy way."
979 (let ((hashed (unless greedy
980 (gethash str ivy--regex-hash))))
983 (setq ivy--subexps (car hashed)))
985 (let ((subs (ivy--split str)))
986 (if (= (length subs) 1)
988 (setq ivy--subexps 0)
991 (setq ivy--subexps (length subs))
994 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
996 (format "\\(%s\\)" x)))
1001 ivy--regex-hash)))))
1003 (defun ivy--regex-ignore-order (str)
1004 "Re-build regex from STR by splitting it on spaces.
1005 Ignore the order of each group."
1006 (let* ((subs (split-string str " +" t))
1007 (len (length subs)))
1010 (setq ivy--subexps 0)
1013 (setq ivy--subexps len)
1014 (let ((all (mapconcat #'identity subs "\\|")))
1017 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1019 (format "\\(%s\\)" x)))
1023 (defun ivy--regex-plus (str)
1024 "Build a regex sequence from STR.
1025 Spaces are wild, everything before \"!\" should match.
1026 Everything after \"!\" should not match."
1027 (let ((parts (split-string str "!" t)))
1028 (cl-case (length parts)
1032 (ivy--regex (car parts)))
1036 (split-string (cadr parts) " " t))))
1037 (cons (cons (ivy--regex (car parts)) t)
1039 (t (error "Unexpected: use only one !")))))
1041 (defun ivy--regex-fuzzy (str)
1042 "Build a regex sequence from STR.
1043 Insert .* between each char."
1044 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1045 (concat (match-string 1 str)
1046 (mapconcat #'string (string-to-list (match-string 2 str)) ".*")
1047 (match-string 3 str))
1051 (defun ivy--minibuffer-setup ()
1052 "Setup ivy completion in the minibuffer."
1053 (set (make-local-variable 'completion-show-inline-help) nil)
1054 (set (make-local-variable 'minibuffer-default-add-function)
1056 (list ivy--default)))
1057 (setq-local max-mini-window-height ivy-height)
1058 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1059 ;; show completions with empty input
1062 (defun ivy--input ()
1063 "Return the current minibuffer input."
1064 ;; assume one-line minibuffer input
1065 (buffer-substring-no-properties
1066 (minibuffer-prompt-end)
1067 (line-end-position)))
1069 (defun ivy--cleanup ()
1070 "Delete the displayed completion candidates."
1072 (goto-char (minibuffer-prompt-end))
1073 (delete-region (line-end-position) (point-max))))
1075 (defun ivy--insert-prompt ()
1076 "Update the prompt according to `ivy--prompt'."
1078 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1079 counsel-find-symbol))
1080 (setq ivy--prompt-extra ""))
1082 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1084 (setq head (match-string 1 ivy--prompt))
1086 (setq head (substring ivy--prompt 0 -1))
1088 (let ((inhibit-read-only t)
1089 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1093 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1094 (> (minibuffer-depth) 1))
1095 (format "[%d] " (minibuffer-depth))
1101 (abbreviate-file-name ivy--directory)
1103 (or (and (ivy-state-dynamic-collection ivy-last)
1107 (goto-char (point-min))
1108 (delete-region (point-min) (minibuffer-prompt-end))
1109 (set-text-properties 0 (length n-str)
1110 `(face minibuffer-prompt ,@std-props)
1112 (ivy--set-match-props n-str "confirm"
1113 `(face ivy-confirm-face ,@std-props))
1114 (ivy--set-match-props n-str "match required"
1115 `(face ivy-match-required-face ,@std-props))
1117 ;; get out of the prompt area
1118 (constrain-to-field nil (point-max))))))
1120 (defun ivy--set-match-props (str match props)
1121 "Set STR text proprties that match MATCH to PROPS."
1122 (when (string-match match str)
1123 (set-text-properties
1129 (defvar inhibit-message)
1131 (defun ivy--exhibit ()
1132 "Insert Ivy completions display.
1133 Should be run via minibuffer `post-command-hook'."
1134 (setq ivy-text (ivy--input))
1135 (if (ivy-state-dynamic-collection ivy-last)
1136 ;; while-no-input would cause annoying
1137 ;; "Waiting for process to die...done" message interruptions
1138 (let ((inhibit-message t))
1139 (unless (equal ivy--old-text ivy-text)
1141 ;; dynamic collection should take care of everything
1142 (funcall (ivy-state-dynamic-collection ivy-last) ivy-text)
1143 (setq ivy--old-text ivy-text)))
1144 (unless (eq ivy--full-length -1)
1145 (ivy--insert-minibuffer
1146 (ivy--format ivy--all-candidates))))
1147 (cond (ivy--directory
1148 (if (string-match "/\\'" ivy-text)
1149 (if (member ivy-text ivy--all-candidates)
1150 (ivy--cd (expand-file-name ivy-text ivy--directory))
1151 (when (string-match "//\\'" ivy-text)
1153 (if (string-match "~\\'" ivy-text)
1154 (ivy--cd (expand-file-name "~/")))))
1155 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1156 (when (or (and (string-match "\\` " ivy-text)
1157 (not (string-match "\\` " ivy--old-text)))
1158 (and (string-match "\\` " ivy--old-text)
1159 (not (string-match "\\` " ivy-text))))
1160 (setq ivy--all-candidates
1161 (if (and (> (length ivy-text) 0)
1162 (eq (aref ivy-text 0)
1164 (ivy--buffer-list " ")
1165 (ivy--buffer-list "" ivy-use-virtual-buffers)))
1166 (setq ivy--old-re nil))))
1167 (ivy--insert-minibuffer
1169 (ivy--filter ivy-text ivy--all-candidates)))
1170 (setq ivy--old-text ivy-text)))
1172 (defun ivy--insert-minibuffer (text)
1173 "Insert TEXT into minibuffer with appropriate cleanup."
1174 (let ((resize-mini-windows nil)
1175 (update-fn (ivy-state-update-fn ivy-last))
1179 (funcall update-fn))
1180 (ivy--insert-prompt)
1181 ;; Do nothing if while-no-input was aborted.
1182 (when (stringp text)
1183 (let ((buffer-undo-list t))
1188 (declare-function colir-blend-face-background "ext:colir")
1190 (defun ivy--add-face (str face)
1191 "Propertize STR with FACE.
1192 `font-lock-append-text-property' is used, since it's better than
1193 `propertize' or `add-face-text-property' in this case."
1196 (colir-blend-face-background 0 (length str) face str)
1199 (font-lock-append-text-property 0 (length str) 'face face str))))
1202 (defun ivy--filter (name candidates)
1203 "Return all items that match NAME in CANDIDATES.
1204 CANDIDATES are assumed to be static."
1205 (let* ((re (funcall ivy--regex-function name))
1206 (matcher (ivy-state-matcher ivy-last))
1209 (funcall matcher re candidates))
1210 ((and (equal re ivy--old-re)
1215 (stringp ivy--old-re)
1216 (not (string-match "\\\\" ivy--old-re))
1217 (not (equal ivy--old-re ""))
1219 (if (string-match "\\\\)\\'" ivy--old-re)
1220 (substring ivy--old-re 0 -2)
1226 (lambda (x) (string-match re x))
1229 (let ((re-list (if (stringp re) (list (cons re t)) re))
1231 (dolist (re re-list)
1238 (let ((re (car re)))
1239 (lambda (x) (string-match re x)))
1242 (tail (nthcdr ivy--index ivy--old-cands))
1244 (when (and tail ivy--old-cands)
1245 (unless (and (not (equal re ivy--old-re))
1246 (or (setq ivy--index
1248 (cl-position re cands
1252 (concat re "/") cands
1254 (while (and tail (null idx))
1255 ;; Compare with eq to handle equal duplicates in cands
1256 (setq idx (cl-position (pop tail) cands)))
1257 (setq ivy--index (or idx 0))))
1258 (when (and (string= name "") (not (equal ivy--old-re "")))
1260 (or (cl-position (ivy-state-preselect ivy-last)
1261 cands :test #'equal)
1263 (setq ivy--old-re (if cands re ""))
1264 (setq ivy--old-cands cands)))
1266 (defvar ivy-format-function 'ivy-format-function-default
1267 "Function to transform the list of candidates into a string.
1268 This string will be inserted into the minibuffer.")
1270 (defun ivy-format-function-default (cands)
1271 "Transform CANDS into a string for minibuffer."
1272 (let ((ww (window-width)))
1275 (if (> (length s) ww)
1276 (concat (substring s 0 (- ww 3)) "...")
1280 (defun ivy-format-function-arrow (cands)
1281 "Transform CANDS into a string for minibuffer."
1285 (concat (if (eq (cl-incf i) ivy--index)
1291 (defun ivy--format (cands)
1292 "Return a string for CANDS suitable for display in the minibuffer.
1293 CANDS is a list of strings."
1294 (setq ivy--length (length cands))
1295 (when (>= ivy--index ivy--length)
1296 (setq ivy--index (max (1- ivy--length) 0)))
1298 (setq ivy--current "")
1299 (let* ((half-height (/ ivy-height 2))
1300 (start (max 0 (- ivy--index half-height)))
1301 (end (min (+ start (1- ivy-height)) ivy--length))
1302 (start (max 0 (min start (- end (1- ivy-height)))))
1303 (cands (cl-subseq cands start end))
1304 (index (- ivy--index start)))
1305 (when ivy--directory
1306 (setq cands (mapcar (lambda (x)
1307 (if (string-match-p "/\\'" x)
1308 (propertize x 'face 'ivy-subdir)
1311 (setq ivy--current (copy-sequence (nth index cands)))
1312 (setf (nth index cands)
1313 (ivy--add-face ivy--current 'ivy-current-match))
1314 (let* ((ivy--index index)
1315 (res (concat "\n" (funcall ivy-format-function cands))))
1316 (put-text-property 0 (length res) 'read-only nil res)
1319 (defvar ivy--virtual-buffers nil
1320 "Store the virtual buffers alist.")
1322 (defvar recentf-list)
1324 (defface ivy-virtual '((t :inherit font-lock-builtin-face))
1325 "Face used by Ivy for matching virtual buffer names.")
1327 (defun ivy--virtual-buffers ()
1328 "Adapted from `ido-add-virtual-buffers-to-list'."
1329 (unless recentf-mode
1331 (let ((bookmarks (and (boundp 'bookmark-alist)
1333 virtual-buffers name)
1334 (dolist (head (append
1336 (delete " - no file -"
1337 (delq nil (mapcar (lambda (bookmark)
1338 (cdr (assoc 'filename bookmark)))
1340 (setq name (file-name-nondirectory head))
1341 (when (equal name "")
1342 (setq name (file-name-nondirectory (directory-file-name head))))
1343 (when (equal name "")
1345 (and (not (equal name ""))
1346 (null (get-file-buffer head))
1347 (not (assoc name virtual-buffers))
1348 (push (cons name head) virtual-buffers)))
1349 (when virtual-buffers
1350 (dolist (comp virtual-buffers)
1351 (put-text-property 0 (length (car comp))
1354 (setq ivy--virtual-buffers (nreverse virtual-buffers))
1355 (mapcar #'car ivy--virtual-buffers))))
1357 (defun ivy--buffer-list (str &optional virtual)
1358 "Return the buffers that match STR.
1359 When VIRTUAL is non-nil, add virtual buffers."
1364 (if (with-current-buffer x
1366 (abbreviate-file-name default-directory)))
1367 (propertize x 'face 'ivy-remote)
1369 (all-completions str 'internal-complete-buffer))
1371 (ivy--virtual-buffers)))))
1373 (defun ivy--switch-buffer-action (buffer)
1375 BUFFER may be a string or nil."
1376 (if (zerop (length buffer))
1378 ivy-text nil 'force-same-window)
1379 (let ((virtual (assoc buffer ivy--virtual-buffers)))
1381 (not (get-buffer buffer)))
1382 (find-file (cdr virtual))
1384 buffer nil 'force-same-window)))))
1386 (defun ivy-switch-buffer ()
1387 "Switch to another buffer."
1390 (call-interactively 'switch-to-buffer)
1391 (ivy-read "Switch to buffer: " 'internal-complete-buffer
1392 :preselect (buffer-name (other-buffer (current-buffer)))
1393 :action #'ivy--switch-buffer-action)))
1395 (defun ivy-recentf ()
1396 "Find a file on `recentf-list'."
1398 (ivy-read "Recentf: " recentf-list
1399 :action #'find-file))
1401 (defun ivy-yank-word ()
1402 "Pull next word from buffer into search string."
1405 (with-selected-window (ivy-state-window ivy-last)
1407 (le (line-end-position)))
1411 (setq amend (buffer-substring-no-properties pt (point))))))
1415 (defun ivy-insert-current ()
1416 "Make the current candidate into current input.
1417 Don't finish completion."
1419 (delete-minibuffer-contents)
1420 (if (and ivy--directory
1421 (string-match "/$" ivy--current))
1422 (insert (substring ivy--current 0 -1))
1423 (insert ivy--current)))
1425 (defun ivy-toggle-fuzzy ()
1426 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
1428 (setq ivy--old-re nil)
1429 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
1430 (setq ivy--regex-function 'ivy--regex-plus)
1431 (setq ivy--regex-function 'ivy--regex-fuzzy)))
1435 ;;; ivy.el ends here