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\\)".
44 "Incremental vertical completion."
47 (defface ivy-current-match
48 '((((class color) (background light))
49 :background "#1a4b77" :foreground "white")
50 (((class color) (background dark))
51 :background "#65a7e2" :foreground "black"))
52 "Face used by Ivy for highlighting first match.")
54 (defface ivy-confirm-face
55 '((t :foreground "ForestGreen" :inherit minibuffer-prompt))
56 "Face used by Ivy to issue a confirmation prompt.")
58 (defface ivy-match-required-face
59 '((t :foreground "red" :inherit minibuffer-prompt))
60 "Face used by Ivy to issue a match required prompt.")
63 '((t (:inherit 'dired-directory)))
64 "Face used by Ivy for highlighting subdirs in the alternatives.")
67 '((t (:foreground "#110099")))
68 "Face used by Ivy for highlighting remotes in the alternatives.")
70 (defcustom ivy-height 10
71 "Number of lines for the minibuffer window."
74 (defcustom ivy-count-format "%-4d "
75 "The style of showing the current candidate count for `ivy-read'.
76 Set this to \"\" if you don't want the count. You can also set
77 it to e.g. \"(%d/%d) \" if you want to see both the candidate
78 index and the candidate count."
80 (const :tag "Count disabled" "")
81 (const :tag "Count matches" "%-4d ")
82 (const :tag "Count matches and show current match" "(%d/%d) ")
85 (defcustom ivy-wrap nil
86 "Whether to wrap around after the first and last candidate."
89 (defcustom ivy-display-style (unless (version< emacs-version "24.5") 'fancy)
90 "The style for formatting the minibuffer.
92 By default, the matched strings will be copied as they are.
94 With the fancy method, the matching parts of the regexp will be
95 additionally highlighted, just like `swiper' does it.
97 This setting depends on `add-face-text-property' - a C function
98 available as of 24.5. It will behave poorly in earlier Emacs
101 (const :tag "Plain" nil)
102 (const :tag "Fancy" fancy)))
104 (defcustom ivy-on-del-error-function 'minibuffer-keyboard-quit
105 "The handler for when `ivy-backward-delete-char' throws.
106 This is usually meant as a quick exit out of the minibuffer."
109 (defcustom ivy-extra-directories '("../" "./")
110 "Add this to the front of the list when completing file names.
111 Only \"./\" and \"../\" apply here. They appear in reverse order."
112 :type '(repeat :tag "Dirs"
114 (const :tag "Parent Directory" "../")
115 (const :tag "Current Directory" "./"))))
117 (defcustom ivy-use-virtual-buffers nil
118 "When non-nil, add `recentf-mode' and bookmarks to `ivy-switch-buffer'."
121 (defvar ivy--actions-list nil
122 "A list of extra actions per command.")
124 (defun ivy-set-actions (cmd actions)
125 "Set CMD extra exit points to ACTIONS."
126 (setq ivy--actions-list
127 (plist-put ivy--actions-list cmd actions)))
131 (defvar ivy-minibuffer-map
132 (let ((map (make-sparse-keymap)))
133 (define-key map (kbd "C-m") 'ivy-done)
134 (define-key map (kbd "C-M-m") 'ivy-call)
135 (define-key map (kbd "C-j") 'ivy-alt-done)
136 (define-key map (kbd "C-M-j") 'ivy-immediate-done)
137 (define-key map (kbd "TAB") 'ivy-partial-or-done)
138 (define-key map (kbd "C-n") 'ivy-next-line)
139 (define-key map (kbd "C-p") 'ivy-previous-line)
140 (define-key map (kbd "<down>") 'ivy-next-line)
141 (define-key map (kbd "<up>") 'ivy-previous-line)
142 (define-key map (kbd "C-s") 'ivy-next-line-or-history)
143 (define-key map (kbd "C-r") 'ivy-reverse-i-search)
144 (define-key map (kbd "SPC") 'self-insert-command)
145 (define-key map (kbd "DEL") 'ivy-backward-delete-char)
146 (define-key map (kbd "M-DEL") 'ivy-backward-kill-word)
147 (define-key map (kbd "C-d") 'ivy-delete-char)
148 (define-key map (kbd "C-f") 'ivy-forward-char)
149 (define-key map (kbd "M-d") 'ivy-kill-word)
150 (define-key map (kbd "M-<") 'ivy-beginning-of-buffer)
151 (define-key map (kbd "M->") 'ivy-end-of-buffer)
152 (define-key map (kbd "M-n") 'ivy-next-history-element)
153 (define-key map (kbd "M-p") 'ivy-previous-history-element)
154 (define-key map (kbd "C-g") 'minibuffer-keyboard-quit)
155 (define-key map (kbd "C-v") 'ivy-scroll-up-command)
156 (define-key map (kbd "M-v") 'ivy-scroll-down-command)
157 (define-key map (kbd "C-M-n") 'ivy-next-line-and-call)
158 (define-key map (kbd "C-M-p") 'ivy-previous-line-and-call)
159 (define-key map (kbd "M-q") 'ivy-toggle-regexp-quote)
160 (define-key map (kbd "M-j") 'ivy-yank-word)
161 (define-key map (kbd "M-i") 'ivy-insert-current)
162 (define-key map (kbd "C-o") 'hydra-ivy/body)
163 (define-key map (kbd "M-o") 'ivy-dispatching-done)
164 (define-key map (kbd "C-M-o") 'ivy-dispatching-call)
165 (define-key map (kbd "C-k") 'ivy-kill-line)
166 (define-key map (kbd "S-SPC") 'ivy-restrict-to-matches)
167 (define-key map (kbd "M-w") 'ivy-kill-ring-save)
168 (define-key map (kbd "C-'") 'ivy-avy)
170 "Keymap used in the minibuffer.")
171 (autoload 'hydra-ivy/body "ivy-hydra" "" t)
174 (let ((map (make-sparse-keymap)))
175 (define-key map [remap switch-to-buffer] 'ivy-switch-buffer)
177 "Keymap for `ivy-mode'.")
180 (cl-defstruct ivy-state
182 predicate require-match initial-input
183 history preselect keymap update-fn sort
184 ;; The window in which `ivy-read' was called
190 ;; When this is non-nil, call it for each input change to get new candidates
195 "The last parameters passed to `ivy-read'.
197 This should eventually become a stack so that you could use
198 `ivy-read' recursively.")
200 (defsubst ivy-set-action (action)
201 (setf (ivy-state-action ivy-last) action))
203 (defvar ivy-history nil
204 "History list of candidates entered in the minibuffer.
206 Maximum length of the history list is determined by the value
207 of `history-length', which see.")
209 (defvar ivy--directory nil
210 "Current directory when completing file names.")
212 (defvar ivy--length 0
213 "Store the amount of viable candidates.")
216 "Store the user's string as it is typed in.")
218 (defvar ivy--current ""
219 "Current candidate.")
222 "Store the index of the current candidate.")
225 "Store 'done if the completion was successfully selected.
226 Otherwise, store nil.")
228 (defvar ivy--all-candidates nil
229 "Store the candidates passed to `ivy-read'.")
231 (defvar ivy--default nil
232 "Default initial input.")
234 (defvar ivy--prompt nil
235 "Store the format-style prompt.
236 When non-nil, it should contain one %d.")
238 (defvar ivy--prompt-extra ""
239 "Temporary modifications to the prompt.")
241 (defvar ivy--old-re nil
242 "Store the old regexp.")
244 (defvar ivy--old-cands nil
245 "Store the candidates matched by `ivy--old-re'.")
247 (defvar ivy--regex-function 'ivy--regex
248 "Current function for building a regex.")
250 (defvar ivy--subexps 0
251 "Number of groups in the current `ivy--regex'.")
253 (defvar ivy--full-length nil
254 "When :dynamic-collection is non-nil, this can be the total amount of candidates.")
256 (defvar ivy--old-text ""
257 "Store old `ivy-text' for dynamic completion.")
259 (defvar ivy-case-fold-search 'auto
260 "Store the current overriding `case-fold-search'.")
262 (defvar Info-current-file)
264 (defmacro ivy-quit-and-run (&rest body)
265 "Quit the minibuffer and run BODY afterwards."
267 (put 'quit 'error-message "")
270 (put 'quit 'error-message "Quit")
272 (minibuffer-keyboard-quit)))
274 (defmacro with-ivy-window (&rest body)
275 "Execute BODY in the window from which `ivy-read' was called."
278 `(with-selected-window (ivy-state-window ivy-last)
281 (defun ivy--done (text)
282 "Insert TEXT and exit minibuffer."
283 (if (and ivy--directory
284 (not (eq (ivy-state-history ivy-last) 'grep-files-history)))
285 (insert (setq ivy--current (expand-file-name
286 text ivy--directory)))
287 (insert (setq ivy--current text)))
288 (setq ivy-exit 'done)
293 "Exit the minibuffer with the selected candidate."
295 (delete-minibuffer-contents)
296 (cond ((> ivy--length 0)
297 (ivy--done ivy--current))
298 ((memq (ivy-state-collection ivy-last)
299 '(read-file-name-internal internal-complete-buffer))
300 (if (or (not (eq confirm-nonexistent-file-or-buffer t))
301 (equal " (confirm)" ivy--prompt-extra))
303 (setq ivy--prompt-extra " (confirm)")
306 ((memq (ivy-state-require-match ivy-last)
307 '(nil confirm confirm-after-completion))
308 (ivy--done ivy-text))
310 (setq ivy--prompt-extra " (match required)")
314 (defun ivy-read-action ()
315 "Change the action to one of the available ones."
317 (let ((actions (ivy-state-action ivy-last)))
318 (unless (null (ivy--actionp actions))
319 (let* ((hint (concat ivy--current
326 'face 'font-lock-builtin-face)
331 (key (string (read-key hint)))
332 (action-idx (cl-position-if
333 (lambda (x) (equal (car x) key))
335 (cond ((string= key "
\a"))
337 (error "%s is not bound" key))
340 (setcar actions (1+ action-idx))
341 (ivy-set-action actions)))))))
343 (defun ivy-dispatching-done ()
344 "Select one of the available actions and call `ivy-done'."
349 (defun ivy-dispatching-call ()
350 "Select one of the available actions and call `ivy-call'."
352 (let ((actions (copy-sequence (ivy-state-action ivy-last))))
355 (ivy-set-action actions)))
357 (defun ivy-build-tramp-name (x)
358 "Reconstruct X into a path.
359 Is is a cons cell, related to `tramp-get-completion-function'."
363 (concat user "@" domain)
366 (declare-function tramp-get-completion-function "tramp")
367 (declare-function Info-find-node "info")
369 (defun ivy-alt-done (&optional arg)
370 "Exit the minibuffer with the selected candidate.
371 When ARG is t, exit with current text, ignoring the candidates."
375 (ivy-immediate-done))
379 (not (equal ivy-text ""))
380 (file-directory-p ivy-text)
381 (setq dir (expand-file-name
382 ivy-text ivy--directory)))
384 (not (string= ivy--current "./"))
385 (cl-plusp ivy--length)
387 (setq dir (expand-file-name
388 ivy--current ivy--directory))))))
391 ((eq (ivy-state-collection ivy-last) 'Info-read-node-name-1)
392 (if (or (equal ivy--current "(./)")
393 (equal ivy--current "(../)"))
395 (ivy-read "Go to file: " 'read-file-name-internal
398 (expand-file-name x ivy--directory)
402 (string-match "\\`/[^/]+:.*:.*\\'" ivy-text))
406 "\\`/\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
408 (let ((method (match-string 1 ivy-text))
409 (user (match-string 2 ivy-text))
410 (rest (match-string 3 ivy-text))
413 (dolist (x (tramp-get-completion-function method))
414 (setq res (append res (funcall (car x) (cadr x)))))
415 (setq res (delq nil res))
419 (setq res (cl-delete-duplicates res :test #'equal))
420 (let* ((old-ivy-last ivy-last)
421 (enable-recursive-minibuffers t)
422 (host (ivy-read "Find File: "
423 (mapcar #'ivy-build-tramp-name res)
424 :initial-input rest)))
425 (setq ivy-last old-ivy-last)
427 (setq ivy--directory "/")
428 (ivy--cd (concat "/" method ":" host ":"))))))
432 (defcustom ivy-tab-space nil
433 "When non-nil, `ivy-partial-or-done' should insert a space."
436 (defun ivy-partial-or-done ()
437 "Complete the minibuffer text as much as possible.
438 If the text hasn't changed as a result, forward to `ivy-alt-done'."
440 (if (and (eq (ivy-state-collection ivy-last) #'read-file-name-internal)
441 (string-match "\\`/" ivy-text))
442 (let ((default-directory ivy--directory))
443 (minibuffer-complete)
444 (setq ivy-text (ivy--input))
445 (when (and (file-directory-p ivy-text)
447 (ivy--cd (expand-file-name ivy-text))))
449 (when (or (eq this-command last-command)
453 (defun ivy-partial ()
454 "Complete the minibuffer text as much as possible."
456 (let* ((parts (or (split-string ivy-text " " t) (list "")))
457 (postfix (car (last parts)))
458 (completion-ignore-case t)
459 (startp (string-match "^\\^" postfix))
460 (new (try-completion (if startp
461 (substring postfix 1)
463 (mapcar (lambda (str)
464 (let ((i (string-match postfix str)))
468 (cond ((eq new t) nil)
469 ((string= new ivy-text) nil)
471 (delete-region (minibuffer-prompt-end) (point-max))
476 (insert (mapconcat #'identity parts " ")
477 (if ivy-tab-space " " ""))
480 (defun ivy-immediate-done ()
481 "Exit the minibuffer with the current input."
483 (delete-minibuffer-contents)
484 (insert (setq ivy--current
486 (expand-file-name ivy-text ivy--directory)
488 (setq ivy-exit 'done)
493 "Resume the last completion session."
496 (ivy-state-prompt ivy-last)
497 (ivy-state-collection ivy-last)
498 :predicate (ivy-state-predicate ivy-last)
499 :require-match (ivy-state-require-match ivy-last)
500 :initial-input ivy-text
501 :history (ivy-state-history ivy-last)
502 :preselect (unless (eq (ivy-state-collection ivy-last)
503 'read-file-name-internal)
505 :keymap (ivy-state-keymap ivy-last)
506 :update-fn (ivy-state-update-fn ivy-last)
507 :sort (ivy-state-sort ivy-last)
508 :action (ivy-state-action ivy-last)
509 :unwind (ivy-state-unwind ivy-last)
510 :re-builder (ivy-state-re-builder ivy-last)
511 :matcher (ivy-state-matcher ivy-last)
512 :dynamic-collection (ivy-state-dynamic-collection ivy-last)
513 :caller (ivy-state-caller ivy-last)))
515 (defvar ivy-calling nil
516 "When non-nil, call the current action when `ivy--index' changes.")
518 (defun ivy-set-index (index)
519 "Set `ivy--index' to INDEX."
520 (setq ivy--index index)
525 (defun ivy-beginning-of-buffer ()
526 "Select the first completion candidate."
530 (defun ivy-end-of-buffer ()
531 "Select the last completion candidate."
533 (ivy-set-index (1- ivy--length)))
535 (defun ivy-scroll-up-command ()
536 "Scroll the candidates upward by the minibuffer height."
538 (ivy-set-index (min (+ ivy--index ivy-height)
541 (defun ivy-scroll-down-command ()
542 "Scroll the candidates downward by the minibuffer height."
544 (ivy-set-index (max (- ivy--index ivy-height)
547 (defun ivy-minibuffer-grow ()
548 "Grow the minibuffer window by 1 line."
550 (setq-local max-mini-window-height
551 (cl-incf ivy-height)))
553 (defun ivy-minibuffer-shrink ()
554 "Shrink the minibuffer window by 1 line."
556 (unless (<= ivy-height 2)
557 (setq-local max-mini-window-height
558 (cl-decf ivy-height))
559 (window-resize (selected-window) -1)))
561 (defun ivy-next-line (&optional arg)
562 "Move cursor vertically down ARG candidates."
564 (setq arg (or arg 1))
565 (let ((index (+ ivy--index arg)))
566 (if (> index (1- ivy--length))
568 (ivy-beginning-of-buffer)
569 (ivy-set-index (1- ivy--length)))
570 (ivy-set-index index))))
572 (defun ivy-next-line-or-history (&optional arg)
573 "Move cursor vertically down ARG candidates.
574 If the input is empty, select the previous history element instead."
576 (when (string= ivy-text "")
577 (ivy-previous-history-element 1))
580 (defun ivy-previous-line (&optional arg)
581 "Move cursor vertically up ARG candidates."
583 (setq arg (or arg 1))
584 (let ((index (- ivy--index arg)))
589 (ivy-set-index index))))
591 (defun ivy-previous-line-or-history (arg)
592 "Move cursor vertically up ARG candidates.
593 If the input is empty, select the previous history element instead."
595 (when (string= ivy-text "")
596 (ivy-previous-history-element 1))
597 (ivy-previous-line arg))
599 (defun ivy-toggle-calling ()
600 "Flip `ivy-calling'."
602 (when (setq ivy-calling (not ivy-calling))
605 (defun ivy--get-action (state)
606 "Get the action function from STATE."
607 (let ((action (ivy-state-action state)))
609 (if (functionp action)
611 (cadr (nth (car action) action))))))
613 (defun ivy--actionp (x)
614 "Return non-nil when X is a list of actions."
615 (and x (listp x) (not (eq (car x) 'closure))))
617 (defun ivy-next-action ()
618 "When the current action is a list, scroll it forwards."
620 (let ((action (ivy-state-action ivy-last)))
621 (when (ivy--actionp action)
622 (unless (>= (car action) (1- (length action)))
623 (cl-incf (car action))))))
625 (defun ivy-prev-action ()
626 "When the current action is a list, scroll it backwards."
628 (let ((action (ivy-state-action ivy-last)))
629 (when (ivy--actionp action)
630 (unless (<= (car action) 1)
631 (cl-decf (car action))))))
633 (defun ivy-action-name ()
634 "Return the name associated with the current action."
635 (let ((action (ivy-state-action ivy-last)))
636 (if (ivy--actionp action)
640 (nth 2 (nth (car action) action)))
644 "Call the current action without exiting completion."
646 (let ((action (ivy--get-action ivy-last)))
648 (let* ((collection (ivy-state-collection ivy-last))
649 (x (if (and (consp collection)
650 (consp (car collection)))
651 (cdr (assoc ivy--current collection))
652 (if (equal ivy--current "")
655 (prog1 (funcall action x)
656 (unless (or (eq ivy-exit 'done)
657 (equal (selected-window)
658 (active-minibuffer-window))
659 (null (active-minibuffer-window)))
660 (select-window (active-minibuffer-window))))))))
662 (defun ivy-next-line-and-call (&optional arg)
663 "Move cursor vertically down ARG candidates.
664 Call the permanent action if possible."
670 (defun ivy-previous-line-and-call (&optional arg)
671 "Move cursor vertically down ARG candidates.
672 Call the permanent action if possible."
674 (ivy-previous-line arg)
678 (defun ivy-previous-history-element (arg)
679 "Forward to `previous-history-element' with ARG."
681 (previous-history-element arg)
684 (ivy--maybe-scroll-history))
686 (defun ivy-next-history-element (arg)
687 "Forward to `next-history-element' with ARG."
689 (next-history-element arg)
692 (ivy--maybe-scroll-history))
694 (defun ivy--cd-maybe ()
695 "Check if the current input points to a different directory.
696 If so, move to that directory, while keeping only the file name."
698 (let ((input (ivy--input))
700 (if (setq url (ffap-url-p input))
704 (funcall ffap-url-fetcher url)))
705 (setq ivy-exit 'done)
707 (setq input (expand-file-name input))
708 (let ((file (file-name-nondirectory input))
709 (dir (expand-file-name (file-name-directory input))))
710 (if (string= dir ivy--directory)
712 (delete-minibuffer-contents)
717 (defun ivy--maybe-scroll-history ()
718 "If the selected history element has an index, scroll there."
719 (let ((idx (ignore-errors
721 (minibuffer-prompt-end)
725 (setq ivy--index idx))))
728 "When completing file names, move to directory DIR."
729 (if (null ivy--directory)
731 (setq ivy--old-cands nil)
732 (setq ivy--old-re nil)
734 (setq ivy--all-candidates
735 (ivy--sorted-files (setq ivy--directory dir)))
737 (delete-minibuffer-contents)))
739 (defun ivy-backward-delete-char ()
740 "Forward to `backward-delete-char'.
741 On error (read-only), call `ivy-on-del-error-function'."
743 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
745 (ivy--cd (file-name-directory
751 (backward-delete-char 1)
753 (when ivy-on-del-error-function
754 (funcall ivy-on-del-error-function))))))
756 (defun ivy-delete-char (arg)
757 "Forward to `delete-char' ARG."
759 (unless (= (point) (line-end-position))
762 (defun ivy-forward-char (arg)
763 "Forward to `forward-char' ARG."
765 (unless (= (point) (line-end-position))
768 (defun ivy-kill-word (arg)
769 "Forward to `kill-word' ARG."
771 (unless (= (point) (line-end-position))
774 (defun ivy-kill-line ()
775 "Forward to `kill-line'."
778 (kill-region (minibuffer-prompt-end) (point))
781 (defun ivy-backward-kill-word ()
782 "Forward to `backward-kill-word'."
784 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
786 (ivy--cd (file-name-directory
794 (delete-region (point) pt)))))
796 (defvar ivy--regexp-quote 'regexp-quote
797 "Store the regexp quoting state.")
799 (defun ivy-toggle-regexp-quote ()
800 "Toggle the regexp quoting."
802 (setq ivy--old-re nil)
803 (cl-rotatef ivy--regex-function ivy--regexp-quote))
805 (defvar avy-all-windows)
808 (defvar avy-keys-alist)
810 (defvar avy-styles-alist)
811 (declare-function avy--process "ext:avy")
812 (declare-function avy--style-fn "ext:avy")
814 (eval-after-load 'avy
815 '(add-to-list 'avy-styles-alist '(ivy-avy . pre)))
818 "Jump to one of the current ivy candidates."
820 (unless (require 'avy nil 'noerror)
821 (error "Package avy isn't installed"))
822 (let* ((avy-all-windows nil)
823 (avy-keys (or (cdr (assq 'ivy-avy avy-keys-alist))
825 (avy-style (or (cdr (assq 'ivy-avy
835 (goto-char (point-min))
837 (while (< (point) (point-max))
843 (setq avy-action #'identity)
845 (nreverse candidates)
846 (avy--style-fn avy-style)))))
847 (ivy-set-index (- (line-number-at-pos candidate) 2))
851 (defun ivy-sort-file-function-default (x y)
852 "Compare two files X and Y.
853 Prioritize directories."
854 (if (get-text-property 0 'dirp x)
855 (if (get-text-property 0 'dirp y)
858 (if (get-text-property 0 'dirp y)
862 (defcustom ivy-sort-functions-alist
863 '((read-file-name-internal . ivy-sort-file-function-default)
864 (internal-complete-buffer . nil)
865 (counsel-git-grep-function . nil)
866 (Man-goto-section . nil)
869 "An alist of sorting functions for each collection function.
870 Interactive functions that call completion fit in here as well.
872 For each entry, nil means no sorting. It's very useful to turn
873 off the sorting for functions that have candidates in the natural
874 buffer order, like `org-refile' or `Man-goto-section'.
876 The entry associated to t is used for all fall-through cases."
880 (const :tag "All other functions" t)
881 (symbol :tag "Function"))
883 (const :tag "plain sort" string-lessp)
884 (const :tag "file sort" ivy-sort-file-function-default)
885 (const :tag "no sort" nil)))
888 (defvar ivy-index-functions-alist
889 '((swiper . ivy-recompute-index-swiper)
890 (swiper-multi . ivy-recompute-index-swiper)
891 (counsel-git-grep . ivy-recompute-index-swiper)
892 (t . ivy-recompute-index-zero))
893 "An alist of index recomputing functions for each collection function.
894 When the input changes, calling the appropriate function will
895 return an integer - the index of the matched candidate that
896 should be selected.")
898 (defvar ivy-re-builders-alist
899 '((t . ivy--regex-plus))
900 "An alist of regex building functions for each collection function.
901 Each function should take a string and return a valid regex or a
902 regex sequence (see below).
904 The entry associated to t is used for all fall-through cases.
905 Possible choices: `ivy--regex', `regexp-quote', `ivy--regex-plus'.
907 In case a function returns a list, it should look like this:
908 '((\"matching-regexp\" . t) (\"non-matching-regexp\") ...).
910 The matches will be filtered in a sequence, you can mix the
911 regexps that should match and that should not match as you
914 (defvar ivy-initial-inputs-alist
916 (org-agenda-refile . "^")
917 (org-capture-refile . "^")
919 (counsel-describe-function . "^")
920 (counsel-describe-variable . "^")
923 "Command to initial input table.")
925 (defcustom ivy-sort-max-size 30000
926 "Sorting won't be done for collections larger than this."
929 (defun ivy--sorted-files (dir)
930 "Return the list of files in DIR.
931 Directories come first."
932 (let* ((default-directory dir)
933 (seq (all-completions "" 'read-file-name-internal))
937 (setq seq (delete "./" (delete "../" seq)))
938 (when (eq (setq sort-fn (cdr (assoc 'read-file-name-internal
939 ivy-sort-functions-alist)))
940 #'ivy-sort-file-function-default)
941 (setq seq (mapcar (lambda (x)
942 (propertize x 'dirp (string-match-p "/\\'" x)))
945 (setq seq (cl-sort seq sort-fn)))
946 (dolist (dir ivy-extra-directories)
951 (cl-defun ivy-read (prompt collection
952 &key predicate require-match initial-input
953 history preselect keymap update-fn sort
954 action unwind re-builder matcher dynamic-collection caller)
955 "Read a string in the minibuffer, with completion.
957 PROMPT is a string to prompt with; normally it ends in a colon
958 and a space. When PROMPT contains %d, it will be updated with
959 the current number of matching candidates. If % appears elsewhere
960 in the PROMPT it should be quoted as %%.
961 See also `ivy-count-format'.
963 COLLECTION is a list of strings, or a function, or an alist, or a
966 If INITIAL-INPUT is non-nil, insert it in the minibuffer initially.
968 KEYMAP is composed together with `ivy-minibuffer-map'.
970 If PRESELECT is non-nil select the corresponding candidate out of
971 the ones that match INITIAL-INPUT.
973 UPDATE-FN is called each time the current candidate(s) is changed.
975 When SORT is t, refer to `ivy-sort-functions-alist' for sorting.
977 ACTION is a lambda to call after a result was selected. It should
978 take a single argument, usually a string.
980 UNWIND is a lambda to call before exiting.
982 RE-BUILDER is a lambda that transforms text into a regex.
984 MATCHER can completely override matching.
986 DYNAMIC-COLLECTION is a function to call to update the list of
987 candidates with each input.
989 CALLER is a symbol to uniquely identify the caller to `ivy-read'.
990 It's used in conjunction with COLLECTION to indentify which
991 customizations should apply to the current completion session."
992 (let ((extra-actions (plist-get ivy--actions-list this-command)))
995 (if (functionp action)
997 ("o" ,action "default")
999 (delete-dups (append action extra-actions))))))
1003 :collection collection
1004 :predicate predicate
1005 :require-match require-match
1006 :initial-input initial-input
1008 :preselect preselect
1010 :update-fn update-fn
1013 :window (selected-window)
1015 :re-builder re-builder
1017 :dynamic-collection dynamic-collection
1019 (ivy--reset-state ivy-last)
1022 (minibuffer-with-setup-hook
1023 #'ivy--minibuffer-setup
1024 (let* ((hist (or history 'ivy-history))
1025 (minibuffer-completion-table collection)
1026 (minibuffer-completion-predicate predicate)
1027 (resize-mini-windows (cond
1028 ((display-graphic-p) nil)
1029 ((null resize-mini-windows) 'grow-only)
1030 (t resize-mini-windows)))
1031 (res (read-from-minibuffer
1033 (ivy-state-initial-input ivy-last)
1034 (make-composed-keymap keymap ivy-minibuffer-map)
1037 (when (eq ivy-exit 'done)
1038 (let ((item (if ivy--directory
1041 (unless (equal item "")
1042 (set hist (cons (propertize item 'ivy-index ivy--index)
1044 (cdr (symbol-value hist)))))))
1046 (remove-hook 'post-command-hook #'ivy--exhibit)
1047 (when (setq unwind (ivy-state-unwind ivy-last))
1051 (defun ivy--reset-state (state)
1052 "Reset the ivy to STATE.
1053 This is useful for recursive `ivy-read'."
1054 (let ((prompt (ivy-state-prompt state))
1055 (collection (ivy-state-collection state))
1056 (predicate (ivy-state-predicate state))
1057 (history (ivy-state-history state))
1058 (preselect (ivy-state-preselect state))
1059 (sort (ivy-state-sort state))
1060 (re-builder (ivy-state-re-builder state))
1061 (dynamic-collection (ivy-state-dynamic-collection state))
1062 (initial-input (ivy-state-initial-input state))
1063 (require-match (ivy-state-require-match state))
1064 (matcher (ivy-state-matcher state)))
1065 (unless initial-input
1066 (setq initial-input (cdr (assoc this-command
1067 ivy-initial-inputs-alist))))
1068 (setq ivy--directory nil)
1069 (setq ivy-case-fold-search 'auto)
1070 (setq ivy--regex-function
1072 (and (functionp collection)
1073 (cdr (assoc collection ivy-re-builders-alist)))
1074 (cdr (assoc t ivy-re-builders-alist))
1076 (setq ivy--subexps 0)
1077 (setq ivy--regexp-quote 'regexp-quote)
1078 (setq ivy--old-text "")
1079 (setq ivy--full-length nil)
1081 (setq ivy-calling nil)
1083 (cond ((eq collection 'Info-read-node-name-1)
1084 (if (equal Info-current-file "dir")
1086 (mapcar (lambda (x) (format "(%s)" x))
1087 (cl-delete-duplicates
1088 (all-completions "(" collection predicate)
1090 (setq coll (all-completions "" collection predicate))))
1091 ((eq collection 'read-file-name-internal)
1092 (setq ivy--directory default-directory)
1095 (let ((preselect-directory (file-name-directory preselect)))
1096 (unless (or (null preselect-directory)
1097 (string= preselect-directory
1099 (setq ivy--directory preselect-directory))
1101 (ivy-state-preselect state)
1102 (setq preselect (file-name-nondirectory preselect)))))
1103 (setq coll (ivy--sorted-files ivy--directory))
1105 (unless (or require-match
1106 (equal initial-input default-directory)
1107 (equal initial-input ""))
1108 (setq coll (cons initial-input coll)))
1109 (setq initial-input nil)))
1110 ((eq collection 'internal-complete-buffer)
1111 (setq coll (ivy--buffer-list "" ivy-use-virtual-buffers)))
1112 ((or (functionp collection)
1113 (byte-code-function-p collection)
1114 (vectorp collection)
1115 (and (consp collection) (listp (car collection)))
1116 (hash-table-p collection))
1117 (setq coll (all-completions "" collection predicate)))
1119 (setq coll collection)))
1121 (if (and (functionp collection)
1122 (setq sort-fn (assoc collection ivy-sort-functions-alist)))
1123 (when (and (setq sort-fn (cdr sort-fn))
1124 (not (eq collection 'read-file-name-internal)))
1125 (setq coll (cl-sort coll sort-fn)))
1126 (unless (eq history 'org-refile-history)
1127 (if (and (setq sort-fn (cdr (assoc t ivy-sort-functions-alist)))
1128 (<= (length coll) ivy-sort-max-size))
1129 (setq coll (cl-sort (copy-sequence coll) sort-fn))))))
1131 (unless (or (and require-match
1132 (not (eq collection 'internal-complete-buffer)))
1133 (let ((re (regexp-quote preselect)))
1134 (cl-find-if (lambda (x) (string-match re x))
1136 (setq coll (cons preselect coll))))
1137 (setq ivy--index (or
1138 (and dynamic-collection
1141 (ivy--preselect-index
1142 coll initial-input preselect matcher))
1144 (setq ivy--old-re nil)
1145 (setq ivy--old-cands nil)
1146 (setq ivy--all-candidates coll))
1148 (setq ivy--default (or
1149 (thing-at-point 'url)
1150 (thing-at-point 'symbol)
1153 (cond ((string-match "%.*d" prompt)
1155 ((null ivy-count-format)
1157 "`ivy-count-format' can't be nil. Set it to an empty string instead"))
1158 ((string-match "%d.*%d" ivy-count-format)
1159 (let ((w (length (number-to-string
1160 (length ivy--all-candidates))))
1161 (s (copy-sequence ivy-count-format)))
1162 (string-match "%d" s)
1164 (string-match "%d" s (match-end 0))
1165 (setq s (replace-match (format "%%-%dd" w) nil nil s))
1166 (string-match "%d" s)
1167 (concat (replace-match (format "%%%dd" w) nil nil s)
1169 ((string-match "%.*d" ivy-count-format)
1170 (concat ivy-count-format prompt))
1175 (setf (ivy-state-initial-input ivy-last) initial-input)))
1178 (defun ivy-completing-read (prompt collection
1179 &optional predicate require-match initial-input
1180 history def _inherit-input-method)
1181 "Read a string in the minibuffer, with completion.
1183 This is an interface that conforms to `completing-read', so that
1184 it can be used for `completing-read-function'.
1186 PROMPT is a string to prompt with; normally it ends in a colon and a space.
1187 COLLECTION can be a list of strings, an alist, an obarray or a hash table.
1188 PREDICATE limits completion to a subset of COLLECTION.
1189 REQUIRE-MATCH is considered boolean. See `completing-read'.
1190 INITIAL-INPUT is a string that can be inserted into the minibuffer initially.
1191 _HISTORY is ignored for now.
1192 DEF is the default value.
1193 _INHERIT-INPUT-METHOD is ignored for now.
1195 The history, defaults and input-method arguments are ignored for now."
1196 (ivy-read (replace-regexp-in-string "%" "%%" prompt)
1198 :predicate predicate
1199 :require-match require-match
1200 :initial-input (if (consp initial-input)
1202 (if (and (stringp initial-input)
1203 (string-match "\\+" initial-input))
1204 (replace-regexp-in-string
1205 "\\+" "\\\\+" initial-input)
1207 :preselect (if (listp def) (car def) def)
1211 (let ((sort (assoc this-command ivy-sort-functions-alist)))
1217 (define-minor-mode ivy-mode
1218 "Toggle Ivy mode on or off.
1219 With ARG, turn Ivy mode on if arg is positive, off otherwise.
1220 Turning on Ivy mode will set `completing-read-function' to
1221 `ivy-completing-read'.
1226 Minibuffer bindings:
1227 \\{ivy-minibuffer-map}"
1230 :keymap ivy-mode-map
1233 (setq completing-read-function 'ivy-completing-read)
1234 (setq completing-read-function 'completing-read-default)))
1236 (defun ivy--preselect-index (candidates initial-input preselect matcher)
1237 "Return the index in CANDIDATES filtered by INITIAL-INPUT for PRESELECT.
1238 When MATCHER is non-nil it's used instead of `cl-remove-if-not'."
1241 (setq initial-input (ivy--regex-plus initial-input))
1244 (funcall matcher initial-input candidates)
1247 (string-match initial-input x))
1250 (setq candidates (funcall matcher "" candidates))))
1251 (or (cl-position preselect candidates :test #'equal)
1252 (and (stringp preselect)
1253 (let ((re (regexp-quote preselect)))
1256 (string-match re x))
1261 (defvar ivy--regex-hash
1262 (make-hash-table :test #'equal)
1263 "Store pre-computed regex.")
1265 (defun ivy--split (str)
1266 "Split STR into a list by single spaces.
1267 The remaining spaces stick to their left.
1268 This allows to \"quote\" N spaces by inputting N+1 spaces."
1269 (let ((len (length str))
1274 (while (and (string-match " +" str start1)
1276 (setq match-len (- (match-end 0) (match-beginning 0)))
1280 (setq start1 start0)
1282 (push (substring str start1 (match-beginning 0)) res)
1283 (setq start1 (match-end 0)))
1284 (setq str (replace-match
1285 (make-string (1- match-len) ?\ )
1287 (setq start0 (or start0 start1))
1288 (setq start1 (1- (match-end 0)))))
1290 (push (substring str start0) res)
1291 (setq s (substring str start1))
1292 (unless (= (length s) 0)
1296 (defun ivy--regex (str &optional greedy)
1297 "Re-build regex from STR in case it has a space.
1298 When GREEDY is non-nil, join words in a greedy way."
1299 (let ((hashed (unless greedy
1300 (gethash str ivy--regex-hash))))
1303 (setq ivy--subexps (car hashed)))
1304 (when (string-match "\\([^\\]\\|^\\)\\\\$" str)
1305 (setq str (substring str 0 -1)))
1307 (let ((subs (ivy--split str)))
1308 (if (= (length subs) 1)
1310 (setq ivy--subexps 0)
1313 (setq ivy--subexps (length subs))
1316 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1318 (format "\\(%s\\)" x)))
1323 ivy--regex-hash)))))
1325 (defun ivy--regex-ignore-order (str)
1326 "Re-build regex from STR by splitting it on spaces.
1327 Ignore the order of each group."
1328 (let* ((subs (split-string str " +" t))
1329 (len (length subs)))
1332 (setq ivy--subexps 0)
1335 (setq ivy--subexps len)
1336 (let ((all (mapconcat #'identity subs "\\|")))
1339 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1341 (format "\\(%s\\)" x)))
1345 (defun ivy--regex-plus (str)
1346 "Build a regex sequence from STR.
1347 Spaces are wild, everything before \"!\" should match.
1348 Everything after \"!\" should not match."
1349 (let ((parts (split-string str "!" t)))
1350 (cl-case (length parts)
1354 (ivy--regex (car parts)))
1358 (split-string (cadr parts) " " t))))
1359 (cons (cons (ivy--regex (car parts)) t)
1361 (t (error "Unexpected: use only one !")))))
1363 (defun ivy--regex-fuzzy (str)
1364 "Build a regex sequence from STR.
1365 Insert .* between each char."
1366 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1368 (concat (match-string 1 str)
1371 (format "\\(%c\\)" x))
1372 (string-to-list (match-string 2 str)) ".*")
1373 (match-string 3 str))
1374 (setq ivy--subexps (length (match-string 2 str))))
1378 (defun ivy--minibuffer-setup ()
1379 "Setup ivy completion in the minibuffer."
1380 (set (make-local-variable 'completion-show-inline-help) nil)
1381 (set (make-local-variable 'minibuffer-default-add-function)
1383 (list ivy--default)))
1384 (when (display-graphic-p)
1385 (setq truncate-lines t))
1386 (setq-local max-mini-window-height ivy-height)
1387 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1388 ;; show completions with empty input
1391 (defun ivy--input ()
1392 "Return the current minibuffer input."
1393 ;; assume one-line minibuffer input
1394 (buffer-substring-no-properties
1395 (minibuffer-prompt-end)
1396 (line-end-position)))
1398 (defun ivy--cleanup ()
1399 "Delete the displayed completion candidates."
1401 (goto-char (minibuffer-prompt-end))
1402 (delete-region (line-end-position) (point-max))))
1404 (defun ivy--insert-prompt ()
1405 "Update the prompt according to `ivy--prompt'."
1407 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1408 counsel-find-symbol))
1409 (setq ivy--prompt-extra ""))
1411 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1413 (setq head (match-string 1 ivy--prompt))
1415 (setq head (substring ivy--prompt 0 -1))
1417 (let ((inhibit-read-only t)
1418 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1421 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1422 (> (minibuffer-depth) 1))
1423 (format "[%d] " (minibuffer-depth))
1426 (if (string-match "%d.*%d" ivy-count-format)
1429 (or (and (ivy-state-dynamic-collection ivy-last)
1433 (or (and (ivy-state-dynamic-collection ivy-last)
1438 (d-str (if ivy--directory
1439 (abbreviate-file-name ivy--directory)
1442 (goto-char (point-min))
1443 (delete-region (point-min) (minibuffer-prompt-end))
1444 (if (> (+ (mod (+ (length n-str) (length d-str)) (window-width))
1447 (setq n-str (concat n-str "\n" d-str))
1448 (setq n-str (concat n-str d-str)))
1449 (let ((regex (format "\\([^\n]\\{%d\\}\\)[^\n]" (window-width))))
1450 (while (string-match regex n-str)
1451 (setq n-str (replace-match (concat (match-string 1 n-str) "\n") nil t n-str 1))))
1452 (set-text-properties 0 (length n-str)
1453 `(face minibuffer-prompt ,@std-props)
1455 (ivy--set-match-props n-str "confirm"
1456 `(face ivy-confirm-face ,@std-props))
1457 (ivy--set-match-props n-str "match required"
1458 `(face ivy-match-required-face ,@std-props))
1460 ;; get out of the prompt area
1461 (constrain-to-field nil (point-max))))))
1463 (defun ivy--set-match-props (str match props)
1464 "Set STR text proprties that match MATCH to PROPS."
1465 (when (string-match match str)
1466 (set-text-properties
1472 (defvar inhibit-message)
1474 (defun ivy--sort-maybe (collection)
1475 "Sort COLLECTION if needed."
1476 (let ((sort (ivy-state-sort ivy-last))
1480 (let ((sort-fn (cond ((functionp sort)
1482 ((setq entry (assoc (ivy-state-collection ivy-last)
1483 ivy-sort-functions-alist))
1486 (cdr (assoc t ivy-sort-functions-alist))))))
1487 (if (functionp sort-fn)
1488 (cl-sort (copy-sequence collection) sort-fn)
1491 (defun ivy--exhibit ()
1492 "Insert Ivy completions display.
1493 Should be run via minibuffer `post-command-hook'."
1494 (when (memq 'ivy--exhibit post-command-hook)
1495 (let ((inhibit-field-text-motion nil))
1496 (constrain-to-field nil (point-max)))
1497 (setq ivy-text (ivy--input))
1498 (if (ivy-state-dynamic-collection ivy-last)
1499 ;; while-no-input would cause annoying
1500 ;; "Waiting for process to die...done" message interruptions
1501 (let ((inhibit-message t))
1502 (unless (equal ivy--old-text ivy-text)
1504 (setq ivy--all-candidates
1506 (funcall (ivy-state-collection ivy-last) ivy-text)))
1507 (setq ivy--old-text ivy-text)))
1508 (when ivy--all-candidates
1509 (ivy--insert-minibuffer
1510 (ivy--format ivy--all-candidates))))
1511 (cond (ivy--directory
1512 (if (string-match "/\\'" ivy-text)
1513 (if (member ivy-text ivy--all-candidates)
1514 (ivy--cd (expand-file-name ivy-text ivy--directory))
1515 (when (string-match "//\\'" ivy-text)
1516 (if (and default-directory
1517 (string-match "\\`[[:alpha:]]:/" default-directory))
1518 (ivy--cd (match-string 0 default-directory))
1520 (when (string-match "[[:alpha:]]:/$" ivy-text)
1521 (let ((drive-root (match-string 0 ivy-text)))
1522 (when (file-exists-p drive-root)
1523 (ivy--cd drive-root)))))
1524 (if (string-match "\\`~\\'" ivy-text)
1525 (ivy--cd (expand-file-name "~/")))))
1526 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1527 (when (or (and (string-match "\\` " ivy-text)
1528 (not (string-match "\\` " ivy--old-text)))
1529 (and (string-match "\\` " ivy--old-text)
1530 (not (string-match "\\` " ivy-text))))
1531 (setq ivy--all-candidates
1532 (if (and (> (length ivy-text) 0)
1533 (eq (aref ivy-text 0)
1535 (ivy--buffer-list " ")
1536 (ivy--buffer-list "" ivy-use-virtual-buffers)))
1537 (setq ivy--old-re nil))))
1538 (ivy--insert-minibuffer
1540 (ivy--filter ivy-text ivy--all-candidates)))
1541 (setq ivy--old-text ivy-text))))
1543 (defun ivy--insert-minibuffer (text)
1544 "Insert TEXT into minibuffer with appropriate cleanup."
1545 (let ((resize-mini-windows nil)
1546 (update-fn (ivy-state-update-fn ivy-last))
1550 (funcall update-fn))
1551 (ivy--insert-prompt)
1552 ;; Do nothing if while-no-input was aborted.
1553 (when (stringp text)
1554 (let ((buffer-undo-list t))
1558 (when (display-graphic-p)
1559 (ivy--resize-minibuffer-to-fit))))
1561 (defun ivy--resize-minibuffer-to-fit ()
1562 "Resize the minibuffer window so it has enough space to display
1563 all of the text contained in the minibuffer."
1564 (with-selected-window (minibuffer-window)
1565 (if (fboundp 'window-text-pixel-size)
1566 (let ((text-height (cdr (window-text-pixel-size)))
1567 (body-height (window-body-height nil t)))
1568 (when (> text-height body-height)
1569 (window-resize nil (- text-height body-height) nil t t)))
1570 (let ((text-height (count-screen-lines))
1571 (body-height (window-body-height)))
1572 (when (> text-height body-height)
1573 (window-resize nil (- text-height body-height) nil t))))))
1575 (declare-function colir-blend-face-background "ext:colir")
1577 (defun ivy--add-face (str face)
1578 "Propertize STR with FACE.
1579 `font-lock-append-text-property' is used, since it's better than
1580 `propertize' or `add-face-text-property' in this case."
1584 (colir-blend-face-background 0 (length str) face str)
1585 (let ((foreground (face-foreground face)))
1587 (add-face-text-property
1589 `(:foreground ,foreground)
1594 (font-lock-append-text-property 0 (length str) 'face face str))))
1597 (declare-function flx-make-string-cache "ext:flx")
1598 (declare-function flx-score "ext:flx")
1600 (defvar ivy--flx-cache nil)
1602 (eval-after-load 'flx
1603 '(setq ivy--flx-cache (flx-make-string-cache)))
1605 (defun ivy-toggle-case-fold ()
1606 "Toggle the case folding between nil and auto.
1607 In any completion session, the case folding starts in auto:
1609 - when the input is all lower case, `case-fold-search' is t
1610 - otherwise it's nil.
1612 You can toggle this to make `case-fold-search' nil regardless of input."
1614 (setq ivy-case-fold-search
1615 (if ivy-case-fold-search
1618 ;; reset cache so that the candidate list updates
1619 (setq ivy--old-re nil))
1621 (defun ivy--filter (name candidates)
1622 "Return all items that match NAME in CANDIDATES.
1623 CANDIDATES are assumed to be static."
1624 (let ((re (funcall ivy--regex-function name)))
1625 (if (and (equal re ivy--old-re)
1627 ;; quick caching for "C-n", "C-p" etc.
1629 (let* ((re-str (if (listp re) (caar re) re))
1630 (matcher (ivy-state-matcher ivy-last))
1632 (and ivy-case-fold-search
1633 (string= name (downcase name))))
1636 (funcall matcher re candidates))
1639 (stringp ivy--old-re)
1640 (not (string-match "\\\\" ivy--old-re))
1641 (not (equal ivy--old-re ""))
1643 (if (string-match "\\\\)\\'" ivy--old-re)
1644 (substring ivy--old-re 0 -2)
1650 (lambda (x) (string-match re x))
1653 (let ((re-list (if (stringp re) (list (cons re t)) re))
1655 (dolist (re re-list)
1662 (let ((re-str (car re)))
1663 (lambda (x) (string-match re-str x)))
1666 (ivy--recompute-index name re-str cands)
1667 (setq ivy--old-re (if cands re-str ""))
1668 (when (and (require 'flx nil 'noerror)
1669 (eq ivy--regex-function 'ivy--regex-fuzzy))
1670 (setq cands (ivy--flx-sort name cands)))
1671 (setq ivy--old-cands cands)))))
1673 (defun ivy--recompute-index (name re-str cands)
1674 (let* ((caller (ivy-state-caller ivy-last))
1675 (func (or (and caller (cdr (assoc caller ivy-index-functions-alist)))
1676 (cdr (assoc t ivy-index-functions-alist))
1677 #'ivy-recompute-index-zero)))
1678 (unless (eq this-command 'ivy-resume)
1681 (cl-position (if (and (> (length re-str) 0)
1682 (eq ?^ (aref re-str 0)))
1683 (substring re-str 1)
1688 (concat re-str "/") cands
1690 (and (not (string= name ""))
1691 (not (and (require 'flx nil 'noerror)
1692 (eq ivy--regex-function 'ivy--regex-fuzzy)
1693 (< (length cands) 200)))
1695 (cl-position (nth ivy--index ivy--old-cands)
1697 (funcall func re-str cands))))
1698 (when (and (or (string= name "")
1700 (not (equal ivy--old-re "")))
1702 (or (ivy--preselect-index
1705 (ivy-state-preselect ivy-last)
1709 (defun ivy-recompute-index-swiper (_re-str cands)
1710 (let ((tail (nthcdr ivy--index ivy--old-cands))
1712 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
1714 (while (and tail (null idx))
1715 ;; Compare with eq to handle equal duplicates in cands
1716 (setq idx (cl-position (pop tail) cands)))
1720 (defun ivy-recompute-index-zero (_re-str _cands)
1723 (defun ivy--flx-sort (name cands)
1724 "Sort according to closeness to string NAME the string list CANDS."
1727 (< (length cands) 200))
1728 (let* ((flx-name (if (string-match "^\\^" name)
1735 (let ((score (car (flx-score x flx-name ivy--flx-cache))))
1739 (if cands-with-score
1741 (sort cands-with-score
1743 (> (car x) (car y)))))
1749 (defvar ivy-format-function 'ivy-format-function-default
1750 "Function to transform the list of candidates into a string.
1751 This string will be inserted into the minibuffer.")
1753 (defun ivy-format-function-default (cands)
1754 "Transform CANDS into a string for minibuffer."
1755 (if (bound-and-true-p truncate-lines)
1756 (mapconcat #'identity cands "\n")
1757 (let ((ww (- (window-width)
1758 (if (and (boundp 'fringe-mode) (eq fringe-mode 0)) 1 0))))
1762 (if (> (length s) ww)
1763 (concat (substring s 0 (- ww 3)) "...")
1768 (defun ivy-format-function-arrow (cands)
1769 "Transform CANDS into a string for minibuffer."
1773 (concat (if (eq (cl-incf i) ivy--index)
1779 (defface ivy-minibuffer-match-face-1
1780 '((((class color) (background light))
1781 :background "#d3d3d3")
1782 (((class color) (background dark))
1783 :background "#555555"))
1784 "The background face for `ivy' minibuffer matches.")
1786 (defface ivy-minibuffer-match-face-2
1787 '((((class color) (background light))
1788 :background "#e99ce8" :weight bold)
1789 (((class color) (background dark))
1790 :background "#777777" :weight bold))
1791 "Face for `ivy' minibuffer matches modulo 1.")
1793 (defface ivy-minibuffer-match-face-3
1794 '((((class color) (background light))
1795 :background "#bbbbff" :weight bold)
1796 (((class color) (background dark))
1797 :background "#7777ff" :weight bold))
1798 "Face for `ivy' minibuffer matches modulo 2.")
1800 (defface ivy-minibuffer-match-face-4
1801 '((((class color) (background light))
1802 :background "#ffbbff" :weight bold)
1803 (((class color) (background dark))
1804 :background "#8a498a" :weight bold))
1805 "Face for `ivy' minibuffer matches modulo 3.")
1807 (defcustom ivy-minibuffer-faces
1808 '(ivy-minibuffer-match-face-1
1809 ivy-minibuffer-match-face-2
1810 ivy-minibuffer-match-face-3
1811 ivy-minibuffer-match-face-4)
1812 "List of `ivy' faces for minibuffer group matches.")
1814 (defun ivy--format-minibuffer-line (str)
1816 (str (copy-sequence str)))
1817 (when (eq ivy-display-style 'fancy)
1819 (setq ivy--old-re (funcall ivy--regex-function ivy-text)))
1820 (while (and (string-match ivy--old-re str start)
1821 (> (- (match-end 0) (match-beginning 0)) 0))
1822 (setq start (match-end 0))
1824 (while (<= i ivy--subexps)
1826 (cond ((zerop ivy--subexps)
1827 (cadr ivy-minibuffer-faces))
1829 (car ivy-minibuffer-faces))
1831 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
1832 ivy-minibuffer-faces)))))
1833 (if (fboundp 'add-face-text-property)
1834 (add-face-text-property
1840 (font-lock-append-text-property
1849 (defun ivy--format (cands)
1850 "Return a string for CANDS suitable for display in the minibuffer.
1851 CANDS is a list of strings."
1852 (setq ivy--length (length cands))
1853 (when (>= ivy--index ivy--length)
1854 (setq ivy--index (max (1- ivy--length) 0)))
1856 (setq ivy--current "")
1857 (let* ((half-height (/ ivy-height 2))
1858 (start (max 0 (- ivy--index half-height)))
1859 (end (min (+ start (1- ivy-height)) ivy--length))
1860 (start (max 0 (min start (- end (1- ivy-height)))))
1861 (cands (cl-subseq cands start end))
1862 (index (- ivy--index start)))
1863 (when ivy--directory
1864 (setq cands (mapcar (lambda (x)
1865 (if (string-match-p "/\\'" x)
1866 (propertize x 'face 'ivy-subdir)
1869 (setq ivy--current (copy-sequence (nth index cands)))
1871 #'ivy--format-minibuffer-line
1873 (setf (nth index cands)
1874 (ivy--add-face (nth index cands) 'ivy-current-match))
1875 (let* ((ivy--index index)
1876 (res (concat "\n" (funcall ivy-format-function cands))))
1877 (put-text-property 0 (length res) 'read-only nil res)
1880 (defvar ivy--virtual-buffers nil
1881 "Store the virtual buffers alist.")
1883 (defvar recentf-list)
1885 (defface ivy-virtual '((t :inherit font-lock-builtin-face))
1886 "Face used by Ivy for matching virtual buffer names.")
1888 (defcustom ivy-virtual-abbreviate 'name
1889 "The mode of abbreviation for virtual buffer names."
1891 (const :tag "Only name" name)
1892 (const :tag "Full path" full)
1893 ;; eventually, uniquify
1896 (defun ivy--virtual-buffers ()
1897 "Adapted from `ido-add-virtual-buffers-to-list'."
1898 (unless recentf-mode
1900 (let ((bookmarks (and (boundp 'bookmark-alist)
1902 virtual-buffers name)
1903 (dolist (head (append
1905 (delete " - no file -"
1906 (delq nil (mapcar (lambda (bookmark)
1907 (cdr (assoc 'filename bookmark)))
1910 (if (eq ivy-virtual-abbreviate 'name)
1911 (file-name-nondirectory head)
1912 (expand-file-name head)))
1913 (when (equal name "")
1914 (setq name (file-name-nondirectory (directory-file-name head))))
1915 (when (equal name "")
1917 (and (not (equal name ""))
1918 (null (get-file-buffer head))
1919 (not (assoc name virtual-buffers))
1920 (push (cons name head) virtual-buffers)))
1921 (when virtual-buffers
1922 (dolist (comp virtual-buffers)
1923 (put-text-property 0 (length (car comp))
1926 (setq ivy--virtual-buffers (nreverse virtual-buffers))
1927 (mapcar #'car ivy--virtual-buffers))))
1929 (defun ivy--buffer-list (str &optional virtual)
1930 "Return the buffers that match STR.
1931 When VIRTUAL is non-nil, add virtual buffers."
1936 (if (with-current-buffer x
1938 (abbreviate-file-name default-directory)))
1939 (propertize x 'face 'ivy-remote)
1941 (all-completions str 'internal-complete-buffer))
1943 (ivy--virtual-buffers)))))
1945 (defun ivy--switch-buffer-action (buffer)
1947 BUFFER may be a string or nil."
1949 (if (zerop (length buffer))
1951 ivy-text nil 'force-same-window)
1952 (let ((virtual (assoc buffer ivy--virtual-buffers)))
1954 (not (get-buffer buffer)))
1955 (find-file (cdr virtual))
1957 buffer nil 'force-same-window))))))
1959 (defun ivy--switch-buffer-other-window-action (buffer)
1960 "Switch to BUFFER in other window.
1961 BUFFER may be a string or nil."
1962 (if (zerop (length buffer))
1963 (switch-to-buffer-other-window ivy-text)
1964 (let ((virtual (assoc buffer ivy--virtual-buffers)))
1966 (not (get-buffer buffer)))
1967 (find-file-other-window (cdr virtual))
1968 (switch-to-buffer-other-window buffer)))))
1970 (defun ivy--rename-buffer-action (buffer)
1972 (let ((new-name (read-string "Rename buffer (to new name): ")))
1973 (with-current-buffer buffer
1974 (rename-buffer new-name))))
1976 (defvar ivy-switch-buffer-map (make-sparse-keymap))
1983 (ivy--reset-state ivy-last))
1986 ivy--switch-buffer-other-window-action
1989 ivy--rename-buffer-action
1993 (defun ivy-switch-buffer ()
1994 "Switch to another buffer."
1997 (call-interactively 'switch-to-buffer)
1998 (let ((this-command 'ivy-switch-buffer))
1999 (ivy-read "Switch to buffer: " 'internal-complete-buffer
2000 :preselect (buffer-name (other-buffer (current-buffer)))
2001 :action #'ivy--switch-buffer-action
2002 :keymap ivy-switch-buffer-map))))
2005 (defun ivy-recentf ()
2006 "Find a file on `recentf-list'."
2008 (ivy-read "Recentf: " recentf-list
2014 (defun ivy-yank-word ()
2015 "Pull next word from buffer into search string."
2020 (le (line-end-position)))
2024 (setq amend (buffer-substring-no-properties pt (point))))))
2026 (insert (replace-regexp-in-string " +" " " amend)))))
2028 (defun ivy-kill-ring-save ()
2029 "Store the current candidates into the kill ring.
2030 If the region is active, forward to `kill-ring-save' instead."
2032 (if (region-active-p)
2033 (call-interactively 'kill-ring-save)
2040 (defun ivy-insert-current ()
2041 "Make the current candidate into current input.
2042 Don't finish completion."
2044 (delete-minibuffer-contents)
2045 (if (and ivy--directory
2046 (string-match "/$" ivy--current))
2047 (insert (substring ivy--current 0 -1))
2048 (insert ivy--current)))
2050 (defun ivy-toggle-fuzzy ()
2051 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
2053 (setq ivy--old-re nil)
2054 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
2055 (setq ivy--regex-function 'ivy--regex-plus)
2056 (setq ivy--regex-function 'ivy--regex-fuzzy)))
2058 (defun ivy-reverse-i-search ()
2059 "Enter a recursive `ivy-read' session using the current history.
2060 The selected history element will be inserted into the minibufer."
2062 (let ((enable-recursive-minibuffers t)
2063 (history (symbol-value (ivy-state-history ivy-last)))
2064 (old-last ivy-last))
2065 (ivy-read "Reverse-i-search: "
2069 (setq ivy-last old-last))
2070 (delete-minibuffer-contents)
2071 (insert (substring-no-properties x))
2074 (defun ivy-restrict-to-matches ()
2075 "Restrict candidates to current matches and erase input."
2077 (delete-minibuffer-contents)
2078 (setq ivy--all-candidates
2079 (ivy--filter ivy-text ivy--all-candidates)))
2083 ;;; ivy.el ends here