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 (defgroup ivy-faces nil
48 "Font-lock faces for `ivy'."
51 (defface ivy-current-match
52 '((((class color) (background light))
53 :background "#1a4b77" :foreground "white")
54 (((class color) (background dark))
55 :background "#65a7e2" :foreground "black"))
56 "Face used by Ivy for highlighting the current match.")
58 (defface ivy-minibuffer-match-face-1
59 '((((class color) (background light))
60 :background "#d3d3d3")
61 (((class color) (background dark))
62 :background "#555555"))
63 "The background face for `ivy' minibuffer matches.")
65 (defface ivy-minibuffer-match-face-2
66 '((((class color) (background light))
67 :background "#e99ce8" :weight bold)
68 (((class color) (background dark))
69 :background "#777777" :weight bold))
70 "Face for `ivy' minibuffer matches numbered 1 modulo 3.")
72 (defface ivy-minibuffer-match-face-3
73 '((((class color) (background light))
74 :background "#bbbbff" :weight bold)
75 (((class color) (background dark))
76 :background "#7777ff" :weight bold))
77 "Face for `ivy' minibuffer matches numbered 2 modulo 3.")
79 (defface ivy-minibuffer-match-face-4
80 '((((class color) (background light))
81 :background "#ffbbff" :weight bold)
82 (((class color) (background dark))
83 :background "#8a498a" :weight bold))
84 "Face for `ivy' minibuffer matches numbered 3 modulo 3.")
86 (defface ivy-confirm-face
87 '((t :foreground "ForestGreen" :inherit minibuffer-prompt))
88 "Face used by Ivy for a confirmation prompt.")
90 (defface ivy-match-required-face
91 '((t :foreground "red" :inherit minibuffer-prompt))
92 "Face used by Ivy for a match required prompt.")
94 (setcdr (assoc load-file-name custom-current-group-alist) 'ivy)
97 '((t (:inherit 'dired-directory)))
98 "Face used by Ivy for highlighting subdirs in the alternatives.")
100 (defface ivy-modified-buffer
101 '((t :inherit 'default))
102 "Face used by Ivy for highlighting modified file visiting buffers.")
105 '((t (:foreground "#110099")))
106 "Face used by Ivy for highlighting remotes in the alternatives.")
109 '((t :inherit font-lock-builtin-face))
110 "Face used by Ivy for matching virtual buffer names.")
112 (defcustom ivy-height 10
113 "Number of lines for the minibuffer window."
116 (defcustom ivy-count-format "%-4d "
117 "The style to use for displaying the current candidate count for `ivy-read'.
118 Set this to \"\" to suppress the count visibility.
119 Set this to \"(%d/%d) \" to display both the index and the count."
121 (const :tag "Count disabled" "")
122 (const :tag "Count matches" "%-4d ")
123 (const :tag "Count matches and show current match" "(%d/%d) ")
126 (defcustom ivy-wrap nil
127 "When non-nil, wrap around after the first and the last candidate."
130 (defcustom ivy-display-style (unless (version< emacs-version "24.5") 'fancy)
131 "The style for formatting the minibuffer.
133 By default, the matched strings are copied as is.
135 The fancy display style highlights matching parts of the regexp,
136 a behavior similar to `swiper'.
138 This setting depends on `add-face-text-property' - a C function
139 available as of Emacs 24.5. Fancy style will render poorly in
140 earlier versions of Emacs."
142 (const :tag "Plain" nil)
143 (const :tag "Fancy" fancy)))
145 (defcustom ivy-on-del-error-function 'minibuffer-keyboard-quit
146 "The handler for when `ivy-backward-delete-char' throws.
147 Usually a quick exit out of the minibuffer."
150 (defcustom ivy-extra-directories '("../" "./")
151 "Add this to the front of the list when completing file names.
152 Only \"./\" and \"../\" apply here. They appear in reverse order."
153 :type '(repeat :tag "Dirs"
155 (const :tag "Parent Directory" "../")
156 (const :tag "Current Directory" "./"))))
158 (defcustom ivy-use-virtual-buffers nil
159 "When non-nil, add `recentf-mode' and bookmarks to `ivy-switch-buffer'."
162 (defvar ivy--actions-list nil
163 "A list of extra actions per command.")
165 (defun ivy-set-actions (cmd actions)
166 "Set CMD extra exit points to ACTIONS."
167 (setq ivy--actions-list
168 (plist-put ivy--actions-list cmd actions)))
170 (defvar ivy--sources-list nil
171 "A list of extra sources per command.")
173 (defun ivy-set-sources (cmd sources)
174 "Attach to CMD a list of extra SOURCES.
176 Each static source is a function that takes no argument and
177 returns a list of strings.
179 The '(original-source) determines the position of the original
182 Extra dynamic sources aren't supported yet.
186 (defun small-recentf ()
187 (cl-subseq recentf-list 0 20))
194 (setq ivy--sources-list
195 (plist-put ivy--sources-list cmd sources)))
199 (defvar ivy-minibuffer-map
200 (let ((map (make-sparse-keymap)))
201 (define-key map (kbd "C-m") 'ivy-done)
202 (define-key map (kbd "C-M-m") 'ivy-call)
203 (define-key map (kbd "C-j") 'ivy-alt-done)
204 (define-key map (kbd "C-M-j") 'ivy-immediate-done)
205 (define-key map (kbd "TAB") 'ivy-partial-or-done)
206 (define-key map (kbd "C-n") 'ivy-next-line)
207 (define-key map (kbd "C-p") 'ivy-previous-line)
208 (define-key map (kbd "<down>") 'ivy-next-line)
209 (define-key map (kbd "<up>") 'ivy-previous-line)
210 (define-key map (kbd "C-s") 'ivy-next-line-or-history)
211 (define-key map (kbd "C-r") 'ivy-reverse-i-search)
212 (define-key map (kbd "SPC") 'self-insert-command)
213 (define-key map (kbd "DEL") 'ivy-backward-delete-char)
214 (define-key map (kbd "M-DEL") 'ivy-backward-kill-word)
215 (define-key map (kbd "C-d") 'ivy-delete-char)
216 (define-key map (kbd "C-f") 'ivy-forward-char)
217 (define-key map (kbd "M-d") 'ivy-kill-word)
218 (define-key map (kbd "M-<") 'ivy-beginning-of-buffer)
219 (define-key map (kbd "M->") 'ivy-end-of-buffer)
220 (define-key map (kbd "M-n") 'ivy-next-history-element)
221 (define-key map (kbd "M-p") 'ivy-previous-history-element)
222 (define-key map (kbd "C-g") 'minibuffer-keyboard-quit)
223 (define-key map (kbd "C-v") 'ivy-scroll-up-command)
224 (define-key map (kbd "M-v") 'ivy-scroll-down-command)
225 (define-key map (kbd "C-M-n") 'ivy-next-line-and-call)
226 (define-key map (kbd "C-M-p") 'ivy-previous-line-and-call)
227 (define-key map (kbd "M-q") 'ivy-toggle-regexp-quote)
228 (define-key map (kbd "M-j") 'ivy-yank-word)
229 (define-key map (kbd "M-i") 'ivy-insert-current)
230 (define-key map (kbd "C-o") 'hydra-ivy/body)
231 (define-key map (kbd "M-o") 'ivy-dispatching-done)
232 (define-key map (kbd "C-M-o") 'ivy-dispatching-call)
233 (define-key map (kbd "C-k") 'ivy-kill-line)
234 (define-key map (kbd "S-SPC") 'ivy-restrict-to-matches)
235 (define-key map (kbd "M-w") 'ivy-kill-ring-save)
236 (define-key map (kbd "C-'") 'ivy-avy)
237 (define-key map (kbd "C-M-a") 'ivy-read-action)
238 (define-key map (kbd "C-c C-o") 'ivy-occur)
239 (define-key map (kbd "C-c C-a") 'ivy-toggle-ignore)
240 (define-key map (kbd "C-h m") 'ivy-help)
242 "Keymap used in the minibuffer.")
243 (autoload 'hydra-ivy/body "ivy-hydra" "" t)
246 (let ((map (make-sparse-keymap)))
247 (define-key map [remap switch-to-buffer]
249 (define-key map [remap switch-to-buffer-other-window]
250 'ivy-switch-buffer-other-window)
252 "Keymap for `ivy-mode'.")
255 (cl-defstruct ivy-state
257 predicate require-match initial-input
258 history preselect keymap update-fn sort
259 ;; The window in which `ivy-read' was called
261 ;; The buffer in which `ivy-read' was called
263 ;; The value of `ivy-text' to be used by `ivy-occur'
269 ;; When this is non-nil, call it for each input change to get new candidates
273 (defvar ivy-last (make-ivy-state)
274 "The last parameters passed to `ivy-read'.
276 This should eventually become a stack so that you could use
277 `ivy-read' recursively.")
279 (defsubst ivy-set-action (action)
280 (setf (ivy-state-action ivy-last) action))
282 (defvar ivy-history nil
283 "History list of candidates entered in the minibuffer.
285 Maximum length of the history list is determined by the value
286 of `history-length'.")
288 (defvar ivy--directory nil
289 "Current directory when completing file names.")
291 (defvar ivy--length 0
292 "Store the amount of viable candidates.")
295 "Store the user's string as it is typed in.")
297 (defvar ivy--current ""
298 "Current candidate.")
301 "Store the index of the current candidate.")
304 "Store 'done if the completion was successfully selected.
305 Otherwise, store nil.")
307 (defvar ivy--all-candidates nil
308 "Store the candidates passed to `ivy-read'.")
310 (defvar ivy--extra-candidates '((original-source))
311 "Store candidates added by the extra sources.
313 This is an internal-use alist. Each key is a function name, or
314 original-source (which represents where the current dynamic
315 candidates should go).
317 Each value is an evaluation of the function, in case of static
318 sources. These values will subsequently be filtered on `ivy-text'.
320 This variable is set by `ivy-read' and used by `ivy--set-candidates'.")
322 (defvar ivy-use-ignore t
323 "Store policy for user-configured candidate filtering.")
325 (defvar ivy--default nil
326 "Default initial input.")
328 (defvar ivy--prompt nil
329 "Store the format-style prompt.
330 When non-nil, it should contain at least one %d.")
332 (defvar ivy--prompt-extra ""
333 "Temporary modifications to the prompt.")
335 (defvar ivy--old-re nil
336 "Store the old regexp.")
338 (defvar ivy--old-cands nil
339 "Store the candidates matched by `ivy--old-re'.")
341 (defvar ivy--regex-function 'ivy--regex
342 "Current function for building a regex.")
344 (defvar ivy--subexps 0
345 "Number of groups in the current `ivy--regex'.")
347 (defvar ivy--full-length nil
348 "When :dynamic-collection is non-nil, this can be the total amount of candidates.")
350 (defvar ivy--old-text ""
351 "Store old `ivy-text' for dynamic completion.")
353 (defvar ivy-case-fold-search 'auto
354 "Store the current overriding `case-fold-search'.")
356 (defvar Info-current-file)
358 (defmacro ivy-quit-and-run (&rest body)
359 "Quit the minibuffer and run BODY afterwards."
361 (put 'quit 'error-message "")
364 (put 'quit 'error-message "Quit")
366 (minibuffer-keyboard-quit)))
368 (defun ivy-exit-with-action (action)
369 "Quit the minibuffer and call ACTION afterwards."
373 (ivy-set-action ',(ivy-state-action ivy-last))))
374 (setq ivy-exit 'done)
377 (defmacro with-ivy-window (&rest body)
378 "Execute BODY in the window from which `ivy-read' was called."
381 `(with-selected-window (ivy--get-window ivy-last)
384 (defun ivy--done (text)
385 "Insert TEXT and exit minibuffer."
386 (if (and ivy--directory
387 (not (eq (ivy-state-history ivy-last) 'grep-files-history)))
388 (insert (setq ivy--current (expand-file-name
389 text ivy--directory)))
390 (insert (setq ivy--current text)))
391 (setq ivy-exit 'done)
396 "Exit the minibuffer with the selected candidate."
398 (delete-minibuffer-contents)
399 (cond ((> ivy--length 0)
400 (ivy--done ivy--current))
401 ((memq (ivy-state-collection ivy-last)
402 '(read-file-name-internal internal-complete-buffer))
403 (if (or (not (eq confirm-nonexistent-file-or-buffer t))
404 (equal " (confirm)" ivy--prompt-extra))
406 (setq ivy--prompt-extra " (confirm)")
409 ((memq (ivy-state-require-match ivy-last)
410 '(nil confirm confirm-after-completion))
411 (ivy--done ivy-text))
413 (setq ivy--prompt-extra " (match required)")
417 (defun ivy-read-action ()
418 "Change the action to one of the available ones."
420 (let ((actions (ivy-state-action ivy-last)))
421 (unless (null (ivy--actionp actions))
422 (let* ((hint (concat (if (eq this-command 'ivy-read-action)
431 'face 'font-lock-builtin-face)
436 (key (string (read-key hint)))
437 (action-idx (cl-position-if
438 (lambda (x) (equal (car x) key))
440 (cond ((string= key "
\a"))
442 (error "%s is not bound" key))
445 (setcar actions (1+ action-idx))
446 (ivy-set-action actions)))))))
448 (defun ivy-dispatching-done ()
449 "Select one of the available actions and call `ivy-done'."
454 (defun ivy-dispatching-call ()
455 "Select one of the available actions and call `ivy-call'."
457 (let ((actions (copy-sequence (ivy-state-action ivy-last))))
459 (when (ivy-read-action)
461 (ivy-set-action actions))))
463 (defun ivy-build-tramp-name (x)
464 "Reconstruct X into a path.
465 Is is a cons cell, related to `tramp-get-completion-function'."
469 (concat user "@" domain)
472 (declare-function tramp-get-completion-function "tramp")
473 (declare-function Info-find-node "info")
475 (defun ivy-alt-done (&optional arg)
476 "Exit the minibuffer with the selected candidate.
477 When ARG is t, exit with current text, ignoring the candidates."
480 (ivy-immediate-done))
482 (ivy--directory-done))
483 ((eq (ivy-state-collection ivy-last) 'Info-read-node-name-1)
484 (if (or (equal ivy--current "(./)")
485 (equal ivy--current "(../)"))
487 (ivy-read "Go to file: " 'read-file-name-internal
490 (expand-file-name x ivy--directory)
496 (defun ivy--directory-done ()
497 "Handle exit from the minibuffer when completing file names."
500 ((equal ivy-text "/sudo::")
501 (setq dir (concat ivy-text ivy--directory))
506 (not (equal ivy-text ""))
510 (file-name-as-directory
512 ivy-text ivy--directory))))))
514 (not (string= ivy--current "./"))
515 (cl-plusp ivy--length)
518 (setq dir (file-name-as-directory
520 ivy--current ivy--directory)))))))
523 ((or (and (equal ivy--directory "/")
524 (string-match "\\`[^/]+:.*:.*\\'" ivy-text))
525 (string-match "\\`/[^/]+:.*:.*\\'" ivy-text))
527 ((or (and (equal ivy--directory "/")
529 "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
532 "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
534 (setq ivy-text ivy--current))))
536 "\\`/\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
538 (let ((method (match-string 1 ivy-text))
539 (user (match-string 2 ivy-text))
540 (rest (match-string 3 ivy-text))
543 (dolist (x (tramp-get-completion-function method))
544 (setq res (append res (funcall (car x) (cadr x)))))
545 (setq res (delq nil res))
549 (setq res (cl-delete-duplicates res :test #'equal))
550 (let* ((old-ivy-last ivy-last)
551 (enable-recursive-minibuffers t)
552 (host (ivy-read "user@host: "
553 (mapcar #'ivy-build-tramp-name res)
554 :initial-input rest)))
555 (setq ivy-last old-ivy-last)
557 (setq ivy--directory "/")
558 (ivy--cd (concat "/" method ":" host ":"))))))
562 (defcustom ivy-tab-space nil
563 "When non-nil, `ivy-partial-or-done' should insert a space."
566 (defun ivy-partial-or-done ()
567 "Complete the minibuffer text as much as possible.
568 If the text hasn't changed as a result, forward to `ivy-alt-done'."
570 (if (and (eq (ivy-state-collection ivy-last) #'read-file-name-internal)
571 (or (and (equal ivy--directory "/")
572 (string-match "\\`[^/]+:.*\\'" ivy-text))
573 (string-match "\\`/" ivy-text)))
574 (let ((default-directory ivy--directory))
575 (minibuffer-complete)
576 (setq ivy-text (ivy--input))
577 (when (file-directory-p
578 (expand-file-name ivy-text ivy--directory))
579 (ivy--cd (file-name-as-directory
580 (expand-file-name ivy-text ivy--directory)))))
582 (when (or (eq this-command last-command)
586 (defun ivy-partial ()
587 "Complete the minibuffer text as much as possible."
589 (let* ((parts (or (split-string ivy-text " " t) (list "")))
590 (postfix (car (last parts)))
591 (completion-ignore-case t)
592 (startp (string-match "^\\^" postfix))
593 (new (try-completion (if startp
594 (substring postfix 1)
596 (mapcar (lambda (str)
597 (let ((i (string-match postfix str)))
601 (cond ((eq new t) nil)
602 ((string= new ivy-text) nil)
604 (delete-region (minibuffer-prompt-end) (point-max))
609 (insert (mapconcat #'identity parts " ")
610 (if ivy-tab-space " " ""))
613 (defun ivy-immediate-done ()
614 "Exit the minibuffer with the current input."
616 (delete-minibuffer-contents)
617 (insert (setq ivy--current
619 (expand-file-name ivy-text ivy--directory)
621 (setq ivy-exit 'done)
626 "Resume the last completion session."
628 (when (eq (ivy-state-caller ivy-last) 'swiper)
629 (switch-to-buffer (ivy-state-buffer ivy-last)))
630 (with-current-buffer (ivy-state-buffer ivy-last)
632 (ivy-state-prompt ivy-last)
633 (ivy-state-collection ivy-last)
634 :predicate (ivy-state-predicate ivy-last)
635 :require-match (ivy-state-require-match ivy-last)
636 :initial-input ivy-text
637 :history (ivy-state-history ivy-last)
638 :preselect (unless (eq (ivy-state-collection ivy-last)
639 'read-file-name-internal)
641 :keymap (ivy-state-keymap ivy-last)
642 :update-fn (ivy-state-update-fn ivy-last)
643 :sort (ivy-state-sort ivy-last)
644 :action (ivy-state-action ivy-last)
645 :unwind (ivy-state-unwind ivy-last)
646 :re-builder (ivy-state-re-builder ivy-last)
647 :matcher (ivy-state-matcher ivy-last)
648 :dynamic-collection (ivy-state-dynamic-collection ivy-last)
649 :caller (ivy-state-caller ivy-last))))
651 (defvar ivy-calling nil
652 "When non-nil, call the current action when `ivy--index' changes.")
654 (defun ivy-set-index (index)
655 "Set `ivy--index' to INDEX."
656 (setq ivy--index index)
661 (defun ivy-beginning-of-buffer ()
662 "Select the first completion candidate."
666 (defun ivy-end-of-buffer ()
667 "Select the last completion candidate."
669 (ivy-set-index (1- ivy--length)))
671 (defun ivy-scroll-up-command ()
672 "Scroll the candidates upward by the minibuffer height."
674 (ivy-set-index (min (1- (+ ivy--index ivy-height))
677 (defun ivy-scroll-down-command ()
678 "Scroll the candidates downward by the minibuffer height."
680 (ivy-set-index (max (1+ (- ivy--index ivy-height))
683 (defun ivy-minibuffer-grow ()
684 "Grow the minibuffer window by 1 line."
686 (setq-local max-mini-window-height
687 (cl-incf ivy-height)))
689 (defun ivy-minibuffer-shrink ()
690 "Shrink the minibuffer window by 1 line."
692 (unless (<= ivy-height 2)
693 (setq-local max-mini-window-height
694 (cl-decf ivy-height))
695 (window-resize (selected-window) -1)))
697 (defun ivy-next-line (&optional arg)
698 "Move cursor vertically down ARG candidates."
700 (setq arg (or arg 1))
701 (let ((index (+ ivy--index arg)))
702 (if (> index (1- ivy--length))
704 (ivy-beginning-of-buffer)
705 (ivy-set-index (1- ivy--length)))
706 (ivy-set-index index))))
708 (defun ivy-next-line-or-history (&optional arg)
709 "Move cursor vertically down ARG candidates.
710 If the input is empty, select the previous history element instead."
712 (if (string= ivy-text "")
713 (ivy-previous-history-element 1)
714 (ivy-next-line arg)))
716 (defun ivy-previous-line (&optional arg)
717 "Move cursor vertically up ARG candidates."
719 (setq arg (or arg 1))
720 (let ((index (- ivy--index arg)))
725 (ivy-set-index index))))
727 (defun ivy-previous-line-or-history (arg)
728 "Move cursor vertically up ARG candidates.
729 If the input is empty, select the previous history element instead."
731 (when (string= ivy-text "")
732 (ivy-previous-history-element 1))
733 (ivy-previous-line arg))
735 (defun ivy-toggle-calling ()
736 "Flip `ivy-calling'."
738 (when (setq ivy-calling (not ivy-calling))
741 (defun ivy-toggle-ignore ()
742 "Toggle user-configured candidate filtering."
744 (setq ivy-use-ignore (null ivy-use-ignore))
746 (setq ivy--old-cands nil))
748 (defun ivy--get-action (state)
749 "Get the action function from STATE."
750 (let ((action (ivy-state-action state)))
752 (if (functionp action)
754 (cadr (nth (car action) action))))))
756 (defun ivy--get-window (state)
757 "Get the window from STATE."
758 (if (ivy-state-p state)
759 (let ((window (ivy-state-window state)))
760 (if (window-live-p window)
762 (if (= (length (window-list)) 1)
767 (defun ivy--actionp (x)
768 "Return non-nil when X is a list of actions."
769 (and x (listp x) (not (eq (car x) 'closure))))
771 (defun ivy-next-action ()
772 "When the current action is a list, scroll it forwards."
774 (let ((action (ivy-state-action ivy-last)))
775 (when (ivy--actionp action)
776 (unless (>= (car action) (1- (length action)))
777 (cl-incf (car action))))))
779 (defun ivy-prev-action ()
780 "When the current action is a list, scroll it backwards."
782 (let ((action (ivy-state-action ivy-last)))
783 (when (ivy--actionp action)
784 (unless (<= (car action) 1)
785 (cl-decf (car action))))))
787 (defun ivy-action-name ()
788 "Return the name associated with the current action."
789 (let ((action (ivy-state-action ivy-last)))
790 (if (ivy--actionp action)
794 (nth 2 (nth (car action) action)))
797 (defvar ivy-inhibit-action nil
798 "When non-nil, `ivy-call' does nothing.
802 (let* ((ivy-inhibit-action t)
803 (str (counsel-locate \"lispy.el\")))
804 ;; do whatever with str - the corresponding file will not be opened
808 "Call the current action without exiting completion."
810 (unless ivy-inhibit-action
811 (let ((action (ivy--get-action ivy-last)))
813 (let* ((collection (ivy-state-collection ivy-last))
814 (x (if (and (consp collection)
815 (consp (car collection)))
816 (cdr (assoc ivy--current collection))
817 (if (equal ivy--current "")
820 (prog1 (funcall action x)
821 (unless (or (eq ivy-exit 'done)
822 (equal (selected-window)
823 (active-minibuffer-window))
824 (null (active-minibuffer-window)))
825 (select-window (active-minibuffer-window)))))))))
827 (defun ivy-next-line-and-call (&optional arg)
828 "Move cursor vertically down ARG candidates.
829 Call the permanent action if possible."
835 (defun ivy-previous-line-and-call (&optional arg)
836 "Move cursor vertically down ARG candidates.
837 Call the permanent action if possible."
839 (ivy-previous-line arg)
843 (defun ivy-previous-history-element (arg)
844 "Forward to `previous-history-element' with ARG."
846 (previous-history-element arg)
849 (ivy--maybe-scroll-history))
851 (defun ivy-next-history-element (arg)
852 "Forward to `next-history-element' with ARG."
854 (if (and (= minibuffer-history-position 0)
857 (insert ivy--default)
858 (when (and (with-ivy-window (derived-mode-p 'prog-mode))
859 (> (point) (minibuffer-prompt-end)))
862 (goto-char (minibuffer-prompt-end))
864 (forward-char (+ 2 (length ivy--default)))))
865 (next-history-element arg))
868 (ivy--maybe-scroll-history))
870 (defvar ivy-ffap-url-functions nil
871 "List of functions that check if the point is on a URL.")
873 (defun ivy--cd-maybe ()
874 "Check if the current input points to a different directory.
875 If so, move to that directory, while keeping only the file name."
877 (let ((input (ivy--input))
879 (if (setq url (or (ffap-url-p input)
884 ivy-ffap-url-functions
885 :initial-value nil))))
886 (ivy-exit-with-action
888 (funcall ffap-url-fetcher url)))
889 (setq input (expand-file-name input))
890 (let ((file (file-name-nondirectory input))
891 (dir (expand-file-name (file-name-directory input))))
892 (if (string= dir ivy--directory)
894 (delete-minibuffer-contents)
899 (defun ivy--maybe-scroll-history ()
900 "If the selected history element has an index, scroll there."
901 (let ((idx (ignore-errors
903 (minibuffer-prompt-end)
907 (setq ivy--index idx))))
910 "When completing file names, move to directory DIR."
911 (if (null ivy--directory)
913 (setq ivy--old-cands nil)
914 (setq ivy--old-re nil)
916 (setq ivy--all-candidates
917 (ivy--sorted-files (setq ivy--directory dir)))
919 (delete-minibuffer-contents)))
921 (defun ivy-backward-delete-char ()
922 "Forward to `backward-delete-char'.
923 On error (read-only), call `ivy-on-del-error-function'."
925 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
927 (ivy--cd (file-name-directory
933 (backward-delete-char 1)
935 (when ivy-on-del-error-function
936 (funcall ivy-on-del-error-function))))))
938 (defun ivy-delete-char (arg)
939 "Forward to `delete-char' ARG."
941 (unless (= (point) (line-end-position))
944 (defun ivy-forward-char (arg)
945 "Forward to `forward-char' ARG."
947 (unless (= (point) (line-end-position))
950 (defun ivy-kill-word (arg)
951 "Forward to `kill-word' ARG."
953 (unless (= (point) (line-end-position))
956 (defun ivy-kill-line ()
957 "Forward to `kill-line'."
960 (kill-region (minibuffer-prompt-end) (point))
963 (defun ivy-backward-kill-word ()
964 "Forward to `backward-kill-word'."
966 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
968 (ivy--cd (file-name-directory
976 (delete-region (point) pt)))))
978 (defvar ivy--regexp-quote 'regexp-quote
979 "Store the regexp quoting state.")
981 (defun ivy-toggle-regexp-quote ()
982 "Toggle the regexp quoting."
984 (setq ivy--old-re nil)
985 (cl-rotatef ivy--regex-function ivy--regexp-quote))
987 (defvar avy-all-windows)
990 (defvar avy-keys-alist)
992 (defvar avy-styles-alist)
993 (declare-function avy--process "ext:avy")
994 (declare-function avy--style-fn "ext:avy")
996 (eval-after-load 'avy
997 '(add-to-list 'avy-styles-alist '(ivy-avy . pre)))
1000 "Jump to one of the current ivy candidates."
1002 (unless (require 'avy nil 'noerror)
1003 (error "Package avy isn't installed"))
1004 (let* ((avy-all-windows nil)
1005 (avy-keys (or (cdr (assq 'ivy-avy avy-keys-alist))
1007 (avy-style (or (cdr (assq 'ivy-avy
1017 (goto-char (point-min))
1019 (while (< (point) (point-max))
1025 (setq avy-action #'identity)
1027 (nreverse candidates)
1028 (avy--style-fn avy-style)))))
1029 (ivy-set-index (- (line-number-at-pos candidate) 2))
1033 (defun ivy-sort-file-function-default (x y)
1034 "Compare two files X and Y.
1035 Prioritize directories."
1036 (if (get-text-property 0 'dirp x)
1037 (if (get-text-property 0 'dirp y)
1040 (if (get-text-property 0 'dirp y)
1044 (defcustom ivy-sort-functions-alist
1045 '((read-file-name-internal . ivy-sort-file-function-default)
1046 (internal-complete-buffer . nil)
1047 (counsel-git-grep-function . nil)
1048 (Man-goto-section . nil)
1051 "An alist of sorting functions for each collection function.
1052 Interactive functions that call completion fit in here as well.
1054 Nil means no sorting, which is useful to turn off the sorting for
1055 functions that have candidates in the natural buffer order, like
1056 `org-refile' or `Man-goto-section'.
1058 The entry associated with t is used for all fall-through cases.
1060 See also `ivy-sort-max-size'."
1064 (const :tag "All other functions" t)
1065 (symbol :tag "Function"))
1067 (const :tag "plain sort" string-lessp)
1068 (const :tag "file sort" ivy-sort-file-function-default)
1069 (const :tag "no sort" nil)))
1072 (defvar ivy-index-functions-alist
1073 '((swiper . ivy-recompute-index-swiper)
1074 (swiper-multi . ivy-recompute-index-swiper)
1075 (counsel-git-grep . ivy-recompute-index-swiper)
1076 (counsel-grep . ivy-recompute-index-swiper-async)
1077 (t . ivy-recompute-index-zero))
1078 "An alist of index recomputing functions for each collection function.
1079 When the input changes, the appropriate function returns an
1080 integer - the index of the matched candidate that should be
1083 (defvar ivy-re-builders-alist
1084 '((t . ivy--regex-plus))
1085 "An alist of regex building functions for each collection function.
1087 Each key is (in order of priority):
1088 1. The actual collection function, e.g. `read-file-name-internal'.
1089 2. The symbol passed by :caller into `ivy-read'.
1093 Each value is a function that should take a string and return a
1094 valid regex or a regex sequence (see below).
1096 Possible choices: `ivy--regex', `regexp-quote',
1097 `ivy--regex-plus', `ivy--regex-fuzzy'.
1099 If a function returns a list, it should format like this:
1100 '((\"matching-regexp\" . t) (\"non-matching-regexp\") ...).
1102 The matches will be filtered in a sequence, you can mix the
1103 regexps that should match and that should not match as you
1106 (defvar ivy-initial-inputs-alist
1107 '((org-refile . "^")
1108 (org-agenda-refile . "^")
1109 (org-capture-refile . "^")
1111 (counsel-describe-function . "^")
1112 (counsel-describe-variable . "^")
1115 "Command to initial input table.")
1117 (defcustom ivy-sort-max-size 30000
1118 "Sorting won't be done for collections larger than this."
1121 (defun ivy--sorted-files (dir)
1122 "Return the list of files in DIR.
1123 Directories come first."
1124 (let* ((default-directory dir)
1125 (seq (all-completions "" 'read-file-name-internal))
1129 (setq seq (delete "./" (delete "../" seq)))
1130 (when (eq (setq sort-fn (cdr (assoc 'read-file-name-internal
1131 ivy-sort-functions-alist)))
1132 #'ivy-sort-file-function-default)
1133 (setq seq (mapcar (lambda (x)
1134 (propertize x 'dirp (string-match-p "/\\'" x)))
1137 (setq seq (cl-sort seq sort-fn)))
1138 (dolist (dir ivy-extra-directories)
1142 (defvar ivy-recursive-restore t
1143 "When non-nil, restore the above state when exiting the minibuffer.
1144 This variable is let-bound to nil by functions that take care of
1145 the restoring themselves.")
1148 (cl-defun ivy-read (prompt collection
1150 predicate require-match initial-input
1151 history preselect keymap update-fn sort
1152 action unwind re-builder matcher dynamic-collection caller)
1153 "Read a string in the minibuffer, with completion.
1155 PROMPT is a format string, normally ending in a colon and a
1156 space; %d anywhere in the string is replaced by the current
1157 number of matching candidates. For the literal % character,
1158 escape it with %%. See also `ivy-count-format'.
1160 COLLECTION is either a list of strings, a function, an alist, or
1163 If INITIAL-INPUT is not nil, then insert that input in the
1164 minibuffer initially.
1166 KEYMAP is composed with `ivy-minibuffer-map'.
1168 If PRESELECT is not nil, then select the corresponding candidate
1169 out of the ones that match the INITIAL-INPUT.
1171 UPDATE-FN is called each time the current candidate(s) is changed.
1173 When SORT is t, use `ivy-sort-functions-alist' for sorting.
1175 ACTION is a lambda function to call after selecting a result. It
1176 takes a single string argument.
1178 UNWIND is a lambda function to call before exiting.
1180 RE-BUILDER is a lambda function to call to transform text into a
1183 MATCHER is to override matching.
1185 DYNAMIC-COLLECTION is a boolean to specify if the list of
1186 candidates is updated after each input by calling COLLECTION.
1188 CALLER is a symbol to uniquely identify the caller to `ivy-read'.
1189 It is used, along with COLLECTION, to determine which
1190 customizations apply to the current completion session."
1191 (let ((extra-actions (delete-dups
1192 (append (plist-get ivy--actions-list t)
1193 (plist-get ivy--actions-list this-command)
1194 (plist-get ivy--actions-list caller)))))
1197 (cond ((functionp action)
1199 ("o" ,action "default")
1203 ("o" identity "default")
1206 (delete-dups (append action extra-actions)))))))
1207 (let ((extra-sources (plist-get ivy--sources-list caller)))
1210 (setq ivy--extra-candidates nil)
1211 (dolist (source extra-sources)
1212 (cond ((equal source '(original-source))
1213 (setq ivy--extra-candidates
1214 (cons source ivy--extra-candidates)))
1215 ((null (cdr source))
1216 (setq ivy--extra-candidates
1218 (list (car source) (funcall (car source)))
1219 ivy--extra-candidates))))))
1220 (setq ivy--extra-candidates '((original-source)))))
1221 (let ((recursive-ivy-last (and (active-minibuffer-window) ivy-last)))
1225 :collection collection
1226 :predicate predicate
1227 :require-match require-match
1228 :initial-input initial-input
1230 :preselect preselect
1232 :update-fn update-fn
1235 :window (selected-window)
1236 :buffer (current-buffer)
1238 :re-builder re-builder
1240 :dynamic-collection dynamic-collection
1242 (ivy--reset-state ivy-last)
1245 (minibuffer-with-setup-hook
1246 #'ivy--minibuffer-setup
1247 (let* ((hist (or history 'ivy-history))
1248 (minibuffer-completion-table collection)
1249 (minibuffer-completion-predicate predicate)
1250 (resize-mini-windows (cond
1251 ((display-graphic-p) nil)
1252 ((null resize-mini-windows) 'grow-only)
1253 (t resize-mini-windows))))
1254 (read-from-minibuffer
1256 (ivy-state-initial-input ivy-last)
1257 (make-composed-keymap keymap ivy-minibuffer-map)
1260 (when (eq ivy-exit 'done)
1261 (let ((item (if ivy--directory
1264 (unless (equal item "")
1265 (set hist (cons (propertize item 'ivy-index ivy--index)
1267 (cdr (symbol-value hist))))))))
1269 (remove-hook 'post-command-hook #'ivy--exhibit)
1270 (when (setq unwind (ivy-state-unwind ivy-last))
1272 (unless (eq ivy-exit 'done)
1273 (when recursive-ivy-last
1274 (ivy--reset-state (setq ivy-last recursive-ivy-last)))))
1276 (when (and recursive-ivy-last
1277 ivy-recursive-restore)
1278 (ivy--reset-state (setq ivy-last recursive-ivy-last))))))
1280 (defun ivy--reset-state (state)
1281 "Reset the ivy to STATE.
1282 This is useful for recursive `ivy-read'."
1283 (let ((prompt (or (ivy-state-prompt state) ""))
1284 (collection (ivy-state-collection state))
1285 (predicate (ivy-state-predicate state))
1286 (history (ivy-state-history state))
1287 (preselect (ivy-state-preselect state))
1288 (sort (ivy-state-sort state))
1289 (re-builder (ivy-state-re-builder state))
1290 (dynamic-collection (ivy-state-dynamic-collection state))
1291 (initial-input (ivy-state-initial-input state))
1292 (require-match (ivy-state-require-match state))
1293 (caller (ivy-state-caller state)))
1294 (unless initial-input
1295 (setq initial-input (cdr (assoc this-command
1296 ivy-initial-inputs-alist))))
1297 (setq ivy--directory nil)
1298 (setq ivy-case-fold-search 'auto)
1299 (setq ivy--regex-function
1301 (and (functionp collection)
1302 (cdr (assoc collection ivy-re-builders-alist)))
1304 (cdr (assoc caller ivy-re-builders-alist)))
1305 (cdr (assoc this-command ivy-re-builders-alist))
1306 (cdr (assoc t ivy-re-builders-alist))
1308 (setq ivy--subexps 0)
1309 (setq ivy--regexp-quote 'regexp-quote)
1310 (setq ivy--old-text "")
1311 (setq ivy--full-length nil)
1313 (setq ivy-calling nil)
1314 (setq ivy-use-ignore t)
1316 (cond ((eq collection 'Info-read-node-name-1)
1317 (if (equal Info-current-file "dir")
1319 (mapcar (lambda (x) (format "(%s)" x))
1320 (cl-delete-duplicates
1321 (all-completions "(" collection predicate)
1323 (setq coll (all-completions "" collection predicate))))
1324 ((eq collection 'read-file-name-internal)
1325 (setq ivy--directory default-directory)
1328 (let ((preselect-directory (file-name-directory preselect)))
1329 (unless (or (null preselect-directory)
1330 (string= preselect-directory
1332 (setq ivy--directory preselect-directory))
1334 (ivy-state-preselect state)
1335 (setq preselect (file-name-nondirectory preselect)))))
1336 (setq coll (ivy--sorted-files ivy--directory))
1338 (unless (or require-match
1339 (equal initial-input default-directory)
1340 (equal initial-input ""))
1341 (setq coll (cons initial-input coll)))
1342 (unless (and (ivy-state-action ivy-last)
1343 (not (equal (ivy--get-action ivy-last) 'identity)))
1344 (setq initial-input nil))))
1345 ((eq collection 'internal-complete-buffer)
1346 (setq coll (ivy--buffer-list "" ivy-use-virtual-buffers)))
1348 (setq coll (funcall collection ivy-text)))
1349 ((or (functionp collection)
1350 (byte-code-function-p collection)
1351 (vectorp collection)
1352 (and (consp collection) (listp (car collection)))
1353 (hash-table-p collection)
1354 (and (listp collection) (symbolp (car collection))))
1355 (setq coll (all-completions "" collection predicate)))
1357 (setq coll collection)))
1359 (if (and (functionp collection)
1360 (setq sort-fn (assoc collection ivy-sort-functions-alist)))
1361 (when (and (setq sort-fn (cdr sort-fn))
1362 (not (eq collection 'read-file-name-internal)))
1363 (setq coll (cl-sort coll sort-fn)))
1364 (unless (eq history 'org-refile-history)
1365 (if (and (setq sort-fn (cdr (assoc t ivy-sort-functions-alist)))
1366 (<= (length coll) ivy-sort-max-size))
1367 (setq coll (cl-sort (copy-sequence coll) sort-fn))))))
1369 (unless (or (and require-match
1370 (not (eq collection 'internal-complete-buffer)))
1372 (let ((re (regexp-quote preselect)))
1373 (cl-find-if (lambda (x) (string-match re x))
1375 (setq coll (cons preselect coll))))
1376 (setq ivy--old-re nil)
1377 (setq ivy--old-cands nil)
1378 (when (integerp preselect)
1379 (setq ivy--old-re "")
1380 (setq ivy--index preselect))
1382 ;; Needed for anchor to work
1383 (setq ivy--old-cands coll)
1384 (setq ivy--old-cands (ivy--filter initial-input coll)))
1385 (setq ivy--all-candidates coll)
1386 (unless (integerp preselect)
1387 (setq ivy--index (or
1388 (and dynamic-collection
1391 (ivy--preselect-index
1399 (if (region-active-p)
1404 (thing-at-point 'url)
1405 (thing-at-point 'symbol)
1408 (cond ((string-match "%.*d" prompt)
1410 ((null ivy-count-format)
1412 "`ivy-count-format' can't be nil. Set it to an empty string instead"))
1413 ((string-match "%d.*%d" ivy-count-format)
1414 (let ((w (length (number-to-string
1415 (length ivy--all-candidates))))
1416 (s (copy-sequence ivy-count-format)))
1417 (string-match "%d" s)
1419 (string-match "%d" s (match-end 0))
1420 (setq s (replace-match (format "%%-%dd" w) nil nil s))
1421 (string-match "%d" s)
1422 (concat (replace-match (format "%%%dd" w) nil nil s)
1424 ((string-match "%.*d" ivy-count-format)
1425 (concat ivy-count-format prompt))
1430 (setf (ivy-state-initial-input ivy-last) initial-input)))
1433 (defun ivy-completing-read (prompt collection
1434 &optional predicate require-match initial-input
1435 history def inherit-input-method)
1436 "Read a string in the minibuffer, with completion.
1438 This interface conforms to `completing-read' and can be used for
1439 `completing-read-function'.
1441 PROMPT is a string that normally ends in a colon and a space.
1442 COLLECTION is either a list of strings, an alist, an obarray, or a hash table.
1443 PREDICATE limits completion to a subset of COLLECTION.
1444 REQUIRE-MATCH is a boolean value. See `completing-read'.
1445 INITIAL-INPUT is a string inserted into the minibuffer initially.
1446 HISTORY is a list of previously selected inputs.
1447 DEF is the default value.
1448 INHERIT-INPUT-METHOD is currently ignored."
1449 (if (memq this-command '(tmm-menubar tmm-shortcut))
1450 (completing-read-default prompt collection
1451 predicate require-match
1452 initial-input history
1453 def inherit-input-method)
1454 ;; See the doc of `completing-read'.
1455 (when (consp history)
1456 (when (numberp (cdr history))
1457 (setq initial-input (nth (1- (cdr history))
1458 (symbol-value (car history)))))
1459 (setq history (car history)))
1460 (ivy-read (replace-regexp-in-string "%" "%%" prompt)
1462 :predicate predicate
1463 :require-match require-match
1464 :initial-input (if (consp initial-input)
1466 (if (and (stringp initial-input)
1467 (string-match "\\+" initial-input))
1468 (replace-regexp-in-string
1469 "\\+" "\\\\+" initial-input)
1471 :preselect (if (listp def) (car def) def)
1475 (let ((sort (assoc this-command ivy-sort-functions-alist)))
1480 (defvar ivy-completion-beg nil
1481 "Completion bounds start.")
1483 (defvar ivy-completion-end nil
1484 "Completion bounds end.")
1486 (defun ivy-completion-in-region-action (str)
1487 "Insert STR, erasing the previous one.
1488 The previous string is between `ivy-completion-beg' and `ivy-completion-end'."
1491 (when ivy-completion-beg
1494 ivy-completion-end))
1495 (setq ivy-completion-beg
1496 (move-marker (make-marker) (point)))
1498 (setq ivy-completion-end
1499 (move-marker (make-marker) (point))))))
1501 (defun ivy-completion-common-length (str)
1502 "Return the length of the first 'completions-common-part face in STR."
1505 (while (and (<= pos len)
1506 (let ((prop (get-text-property pos 'face str)))
1507 (not (eq 'completions-common-part
1508 (if (listp prop) (car prop) prop)))))
1509 (setq pos (1+ pos)))
1511 (or (next-single-property-change pos 'face str) len)
1514 (defun ivy-completion-in-region (start end collection &optional predicate)
1515 "An Ivy function suitable for `completion-in-region-function'."
1516 (let* ((enable-recursive-minibuffers t)
1517 (str (buffer-substring-no-properties start end))
1518 (completion-ignore-case case-fold-search)
1520 (completion-all-completions str collection predicate (- end start))))
1522 (message "No matches")
1524 (setq ivy-completion-beg (- end (ivy-completion-common-length (car comps))))
1525 (setq ivy-completion-end end)
1526 (if (null (cdr comps))
1527 (if (string= str (car comps))
1528 (message "Sole match")
1529 (setf (ivy-state-window ivy-last) (selected-window))
1530 (ivy-completion-in-region-action
1531 (substring-no-properties
1533 (let* ((w (1+ (floor (log (length comps) 10))))
1534 (ivy-count-format (if (string= ivy-count-format "")
1536 (format "%%-%dd " w)))
1537 (prompt (format "(%s): " str)))
1539 (ivy-read (if (string= ivy-count-format "")
1541 (replace-regexp-in-string "%" "%%" prompt))
1542 ;; remove 'completions-first-difference face
1543 (mapcar #'substring-no-properties comps)
1544 :predicate predicate
1545 :action #'ivy-completion-in-region-action
1549 (defcustom ivy-do-completion-in-region t
1550 "When non-nil `ivy-mode' will set `completion-in-region-function'."
1554 (define-minor-mode ivy-mode
1555 "Toggle Ivy mode on or off.
1556 Turn Ivy mode on if ARG is positive, off otherwise.
1557 Turning on Ivy mode sets `completing-read-function' to
1558 `ivy-completing-read'.
1563 Minibuffer bindings:
1564 \\{ivy-minibuffer-map}"
1567 :keymap ivy-mode-map
1571 (setq completing-read-function 'ivy-completing-read)
1572 (when ivy-do-completion-in-region
1573 (setq completion-in-region-function 'ivy-completion-in-region)))
1574 (setq completing-read-function 'completing-read-default)
1575 (setq completion-in-region-function 'completion--in-region)))
1577 (defun ivy--preselect-index (preselect candidates)
1578 "Return the index of PRESELECT in CANDIDATES."
1579 (cond ((integerp preselect)
1581 ((cl-position preselect candidates :test #'equal))
1582 ((stringp preselect)
1583 (let ((re (regexp-quote preselect)))
1586 (string-match re x))
1591 (defvar ivy--regex-hash
1592 (make-hash-table :test #'equal)
1593 "Store pre-computed regex.")
1595 (defun ivy--split (str)
1596 "Split STR into a list by single spaces.
1597 The remaining spaces stick to their left.
1598 This allows to \"quote\" N spaces by inputting N+1 spaces."
1599 (let ((len (length str))
1604 (while (and (string-match " +" str start1)
1606 (setq match-len (- (match-end 0) (match-beginning 0)))
1610 (setq start1 start0)
1612 (push (substring str start1 (match-beginning 0)) res)
1613 (setq start1 (match-end 0)))
1614 (setq str (replace-match
1615 (make-string (1- match-len) ?\ )
1617 (setq start0 (or start0 start1))
1618 (setq start1 (1- (match-end 0)))))
1620 (push (substring str start0) res)
1621 (setq s (substring str start1))
1622 (unless (= (length s) 0)
1626 (defun ivy--regex (str &optional greedy)
1627 "Re-build regex pattern from STR in case it has a space.
1628 When GREEDY is non-nil, join words in a greedy way."
1629 (let ((hashed (unless greedy
1630 (gethash str ivy--regex-hash))))
1633 (setq ivy--subexps (car hashed)))
1634 (when (string-match "\\([^\\]\\|^\\)\\\\$" str)
1635 (setq str (substring str 0 -1)))
1637 (let ((subs (ivy--split str)))
1638 (if (= (length subs) 1)
1640 (setq ivy--subexps 0)
1643 (setq ivy--subexps (length subs))
1646 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1648 (format "\\(%s\\)" x)))
1653 ivy--regex-hash)))))
1655 (defun ivy--regex-ignore-order--part (str &optional discard)
1656 "Re-build regex from STR by splitting at spaces.
1657 Ignore the order of each group."
1658 (let* ((subs (split-string str " +" t))
1659 (len (length subs)))
1664 (mapcar (lambda (x) (cons x (not discard)))
1667 (defun ivy--regex-ignore-order (str)
1668 "Re-build regex from STR by splitting at spaces.
1669 Ignore the order of each group. Everything before \"!\" should
1670 match. Everything after \"!\" should not match."
1671 (let ((parts (split-string str "!" t)))
1672 (cl-case (length parts)
1676 (if (string= (substring str 0 1) "!")
1678 (ivy--regex-ignore-order--part (car parts) t))
1679 (ivy--regex-ignore-order--part (car parts))))
1682 (ivy--regex-ignore-order--part (car parts))
1683 (ivy--regex-ignore-order--part (cadr parts) t)))
1684 (t (error "Unexpected: use only one !")))))
1686 (defun ivy--regex-plus (str)
1687 "Build a regex sequence from STR.
1688 Spaces are wild card characters, everything before \"!\" should
1689 match. Everything after \"!\" should not match."
1690 (let ((parts (split-string str "!" t)))
1691 (cl-case (length parts)
1695 (if (string= (substring str 0 1) "!")
1697 (list (ivy--regex (car parts))))
1698 (ivy--regex (car parts))))
1701 (cons (ivy--regex (car parts)) t)
1702 (mapcar #'list (split-string (cadr parts) " " t))))
1703 (t (error "Unexpected: use only one !")))))
1705 (defun ivy--regex-fuzzy (str)
1706 "Build a regex sequence from STR.
1707 Insert .* between each char."
1708 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1710 (concat (match-string 1 str)
1713 (format "\\(%c\\)" x))
1714 (string-to-list (match-string 2 str)) ".*")
1715 (match-string 3 str))
1716 (setq ivy--subexps (length (match-string 2 str))))
1720 (defun ivy--minibuffer-setup ()
1721 "Setup ivy completion in the minibuffer."
1722 (set (make-local-variable 'completion-show-inline-help) nil)
1723 (set (make-local-variable 'minibuffer-default-add-function)
1725 (list ivy--default)))
1726 (when (display-graphic-p)
1727 (setq truncate-lines t))
1728 (setq-local max-mini-window-height ivy-height)
1729 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1730 ;; show completions with empty input
1733 (defun ivy--input ()
1734 "Return the current minibuffer input."
1735 ;; assume one-line minibuffer input
1736 (buffer-substring-no-properties
1737 (minibuffer-prompt-end)
1738 (line-end-position)))
1740 (defun ivy--cleanup ()
1741 "Delete the displayed completion candidates."
1743 (goto-char (minibuffer-prompt-end))
1744 (delete-region (line-end-position) (point-max))))
1746 (defun ivy--insert-prompt ()
1747 "Update the prompt according to `ivy--prompt'."
1749 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1750 counsel-find-symbol))
1751 (setq ivy--prompt-extra ""))
1753 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1755 (setq head (match-string 1 ivy--prompt))
1757 (setq head (substring ivy--prompt 0 -1))
1759 (let ((inhibit-read-only t)
1760 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1763 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1764 (> (minibuffer-depth) 1))
1765 (format "[%d] " (minibuffer-depth))
1768 (if (string-match "%d.*%d" ivy-count-format)
1771 (or (and (ivy-state-dynamic-collection ivy-last)
1775 (or (and (ivy-state-dynamic-collection ivy-last)
1780 (d-str (if ivy--directory
1781 (abbreviate-file-name ivy--directory)
1784 (goto-char (point-min))
1785 (delete-region (point-min) (minibuffer-prompt-end))
1786 (if (> (+ (mod (+ (length n-str) (length d-str)) (window-width))
1789 (setq n-str (concat n-str "\n" d-str))
1790 (setq n-str (concat n-str d-str)))
1791 (let ((regex (format "\\([^\n]\\{%d\\}\\)[^\n]" (window-width))))
1792 (while (string-match regex n-str)
1793 (setq n-str (replace-match (concat (match-string 1 n-str) "\n") nil t n-str 1))))
1794 (set-text-properties 0 (length n-str)
1795 `(face minibuffer-prompt ,@std-props)
1797 (ivy--set-match-props n-str "confirm"
1798 `(face ivy-confirm-face ,@std-props))
1799 (ivy--set-match-props n-str "match required"
1800 `(face ivy-match-required-face ,@std-props))
1802 ;; get out of the prompt area
1803 (constrain-to-field nil (point-max))))))
1805 (defun ivy--set-match-props (str match props)
1806 "Set STR text properties that match MATCH to PROPS."
1807 (when (string-match match str)
1808 (set-text-properties
1814 (defvar inhibit-message)
1816 (defun ivy--sort-maybe (collection)
1817 "Sort COLLECTION if needed."
1818 (let ((sort (ivy-state-sort ivy-last))
1822 (let ((sort-fn (cond ((functionp sort)
1824 ((setq entry (assoc (ivy-state-collection ivy-last)
1825 ivy-sort-functions-alist))
1828 (cdr (assoc t ivy-sort-functions-alist))))))
1829 (if (functionp sort-fn)
1830 (cl-sort (copy-sequence collection) sort-fn)
1833 (defun ivy--exhibit ()
1834 "Insert Ivy completions display.
1835 Should be run via minibuffer `post-command-hook'."
1836 (when (memq 'ivy--exhibit post-command-hook)
1837 (let ((inhibit-field-text-motion nil))
1838 (constrain-to-field nil (point-max)))
1839 (setq ivy-text (ivy--input))
1840 (if (ivy-state-dynamic-collection ivy-last)
1841 ;; while-no-input would cause annoying
1842 ;; "Waiting for process to die...done" message interruptions
1843 (let ((inhibit-message t))
1844 (unless (equal ivy--old-text ivy-text)
1846 (setq ivy--all-candidates
1848 (funcall (ivy-state-collection ivy-last) ivy-text)))
1849 (setq ivy--old-text ivy-text)))
1850 (when ivy--all-candidates
1851 (ivy--insert-minibuffer
1852 (ivy--format ivy--all-candidates))))
1853 (cond (ivy--directory
1854 (if (string-match "/\\'" ivy-text)
1855 (if (member ivy-text ivy--all-candidates)
1856 (ivy--cd (expand-file-name ivy-text ivy--directory))
1857 (when (string-match "//\\'" ivy-text)
1858 (if (and default-directory
1859 (string-match "\\`[[:alpha:]]:/" default-directory))
1860 (ivy--cd (match-string 0 default-directory))
1862 (when (string-match "[[:alpha:]]:/$" ivy-text)
1863 (let ((drive-root (match-string 0 ivy-text)))
1864 (when (file-exists-p drive-root)
1865 (ivy--cd drive-root)))))
1866 (if (string-match "\\`~\\'" ivy-text)
1867 (ivy--cd (expand-file-name "~/")))))
1868 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1869 (when (or (and (string-match "\\` " ivy-text)
1870 (not (string-match "\\` " ivy--old-text)))
1871 (and (string-match "\\` " ivy--old-text)
1872 (not (string-match "\\` " ivy-text))))
1873 (setq ivy--all-candidates
1874 (if (and (> (length ivy-text) 0)
1875 (eq (aref ivy-text 0)
1877 (ivy--buffer-list " ")
1878 (ivy--buffer-list "" ivy-use-virtual-buffers)))
1879 (setq ivy--old-re nil))))
1880 (ivy--insert-minibuffer
1881 (with-current-buffer (ivy-state-buffer ivy-last)
1883 (ivy--filter ivy-text ivy--all-candidates))))
1884 (setq ivy--old-text ivy-text))))
1886 (defun ivy--insert-minibuffer (text)
1887 "Insert TEXT into minibuffer with appropriate cleanup."
1888 (let ((resize-mini-windows nil)
1889 (update-fn (ivy-state-update-fn ivy-last))
1893 (funcall update-fn))
1894 (ivy--insert-prompt)
1895 ;; Do nothing if while-no-input was aborted.
1896 (when (stringp text)
1897 (let ((buffer-undo-list t))
1901 (when (display-graphic-p)
1902 (ivy--resize-minibuffer-to-fit))))
1904 (defun ivy--resize-minibuffer-to-fit ()
1905 "Resize the minibuffer window size to fit the text in the minibuffer."
1906 (unless (frame-root-window-p (minibuffer-window))
1907 (with-selected-window (minibuffer-window)
1908 (if (fboundp 'window-text-pixel-size)
1909 (let ((text-height (cdr (window-text-pixel-size)))
1910 (body-height (window-body-height nil t)))
1911 (when (> text-height body-height)
1912 ;; Note: the size increment needs to be at least frame-char-height,
1913 ;; otherwise resizing won't do anything.
1914 (let ((delta (max (- text-height body-height) (frame-char-height))))
1915 (window-resize nil delta nil t t))))
1916 (let ((text-height (count-screen-lines))
1917 (body-height (window-body-height)))
1918 (when (> text-height body-height)
1919 (window-resize nil (- text-height body-height) nil t)))))))
1921 (declare-function colir-blend-face-background "ext:colir")
1923 (defun ivy--add-face (str face)
1924 "Propertize STR with FACE.
1925 `font-lock-append-text-property' is used, since it's better than
1926 `propertize' or `add-face-text-property' in this case."
1930 (colir-blend-face-background 0 (length str) face str)
1931 (let ((foreground (face-foreground face)))
1933 (add-face-text-property
1935 `(:foreground ,foreground)
1940 (font-lock-append-text-property 0 (length str) 'face face str))))
1943 (declare-function flx-make-string-cache "ext:flx")
1944 (declare-function flx-score "ext:flx")
1946 (defvar ivy--flx-cache nil)
1948 (eval-after-load 'flx
1949 '(setq ivy--flx-cache (flx-make-string-cache)))
1951 (defun ivy-toggle-case-fold ()
1952 "Toggle the case folding between nil and auto.
1953 In any completion session, the case folding starts in auto:
1955 - when the input is all lower case, `case-fold-search' is t
1958 You can toggle this to make `case-fold-search' nil regardless of input."
1960 (setq ivy-case-fold-search
1961 (if ivy-case-fold-search
1964 ;; reset cache so that the candidate list updates
1965 (setq ivy--old-re nil))
1967 (defun ivy--re-filter (re candidates)
1968 "Return all RE matching CANDIDATES.
1969 RE is a list of cons cells, with a regexp car and a boolean cdr.
1970 When the cdr is t, the car must match.
1971 Otherwise, the car must not match."
1972 (let ((re-list (if (stringp re) (list (cons re t)) re))
1974 (dolist (re re-list)
1981 (let ((re-str (car re)))
1982 (lambda (x) (string-match re-str x)))
1986 (defun ivy--filter (name candidates)
1987 "Return all items that match NAME in CANDIDATES.
1988 CANDIDATES are assumed to be static."
1989 (let ((re (funcall ivy--regex-function name)))
1990 (if (and (equal re ivy--old-re)
1992 ;; quick caching for "C-n", "C-p" etc.
1994 (let* ((re-str (if (listp re) (caar re) re))
1995 (matcher (ivy-state-matcher ivy-last))
1997 (and ivy-case-fold-search
1998 (string= name (downcase name))))
2001 (funcall matcher re candidates))
2004 (stringp ivy--old-re)
2005 (not (string-match "\\\\" ivy--old-re))
2006 (not (equal ivy--old-re ""))
2008 (if (string-match "\\\\)\\'" ivy--old-re)
2009 (substring ivy--old-re 0 -2)
2015 (lambda (x) (string-match re x))
2018 (ivy--re-filter re candidates)))))
2019 (ivy--recompute-index name re-str cands)
2021 (if (eq ivy--regex-function 'ivy--regex-ignore-order)
2026 (setq ivy--old-cands (ivy--sort name cands))))))
2028 (defun ivy--set-candidates (x)
2029 "Update `ivy--all-candidates' with X."
2031 (dolist (source ivy--extra-candidates)
2032 (if (equal source '(original-source))
2035 (setq res (append x res)))
2036 (setq ivy--old-re nil)
2038 (ivy--filter ivy-text (cadr source))
2040 (setq ivy--all-candidates res)))
2042 (defcustom ivy-sort-matches-functions-alist '((t . nil))
2043 "An alist of functions for sorting matching candidates.
2045 Unlike `ivy-sort-functions-alist', which is used to sort the
2046 whole collection only once, this alist of functions are used to
2047 sort only matching candidates after each change in input.
2049 The alist KEY is either a collection function or t to match
2050 previously unmatched collection functions.
2052 The alist VAL is a sorting function with the signature of
2053 `ivy--prefix-sort'.")
2055 (defun ivy--sort-files-by-date (_name candidates)
2056 "Re-soft CANDIDATES according to file modification date."
2057 (let ((default-directory ivy--directory))
2058 (cl-sort (copy-sequence candidates)
2061 (nth 5 (file-attributes f2))
2062 (nth 5 (file-attributes f1)))))))
2064 (defun ivy--sort (name candidates)
2065 "Re-sort CANDIDATES by NAME.
2066 All CANDIDATES are assumed to match NAME."
2067 (let ((key (or (ivy-state-caller ivy-last)
2068 (when (functionp (ivy-state-collection ivy-last))
2069 (ivy-state-collection ivy-last))))
2071 (cond ((and (require 'flx nil 'noerror)
2072 (eq ivy--regex-function 'ivy--regex-fuzzy))
2073 (ivy--flx-sort name candidates))
2074 ((setq fun (cdr (or (assoc key ivy-sort-matches-functions-alist)
2075 (assoc t ivy-sort-matches-functions-alist))))
2076 (funcall fun name candidates))
2080 (defun ivy--prefix-sort (name candidates)
2081 "Re-sort CANDIDATES.
2082 Prefix matches to NAME are put ahead of the list."
2083 (if (or (string-match "^\\^" name) (string= name ""))
2085 (let ((re-prefix (concat "^" (funcall ivy--regex-function name)))
2088 (dolist (s candidates)
2089 (if (string-match re-prefix s)
2091 (push s res-noprefix)))
2093 (nreverse res-prefix)
2094 (nreverse res-noprefix)))))
2096 (defun ivy--recompute-index (name re-str cands)
2097 (let* ((caller (ivy-state-caller ivy-last))
2098 (func (or (and caller (cdr (assoc caller ivy-index-functions-alist)))
2099 (cdr (assoc t ivy-index-functions-alist))
2100 #'ivy-recompute-index-zero)))
2101 (unless (eq this-command 'ivy-resume)
2104 (cl-position (if (and (> (length name) 0)
2105 (eq ?^ (aref name 0)))
2111 (concat re-str "/") cands
2113 (and (not (string= name ""))
2114 (not (and (require 'flx nil 'noerror)
2115 (eq ivy--regex-function 'ivy--regex-fuzzy)
2116 (< (length cands) 200)))
2118 (cl-position (nth ivy--index ivy--old-cands)
2120 (funcall func re-str cands))))
2121 (when (and (or (string= name "")
2123 (not (equal ivy--old-re "")))
2125 (or (ivy--preselect-index
2126 (ivy-state-preselect ivy-last)
2130 (defun ivy-recompute-index-swiper (_re-str cands)
2131 (let ((tail (nthcdr ivy--index ivy--old-cands))
2133 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2135 (while (and tail (null idx))
2136 ;; Compare with eq to handle equal duplicates in cands
2137 (setq idx (cl-position (pop tail) cands)))
2140 (1- (length cands))))
2143 ;; already in ivy-state-buffer
2144 (let ((n (line-number-at-pos))
2148 (when (eq n (read (get-text-property 0 'display c)))
2153 (defun ivy-recompute-index-swiper-async (_re-str cands)
2154 (let ((tail (nthcdr ivy--index ivy--old-cands))
2156 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2158 (while (and tail (null idx))
2159 ;; Compare with `equal', since the collection is re-created
2160 ;; each time with `split-string'
2161 (setq idx (cl-position (pop tail) cands :test #'equal)))
2165 (defun ivy-recompute-index-zero (_re-str _cands)
2168 (defcustom ivy-minibuffer-faces
2169 '(ivy-minibuffer-match-face-1
2170 ivy-minibuffer-match-face-2
2171 ivy-minibuffer-match-face-3
2172 ivy-minibuffer-match-face-4)
2173 "List of `ivy' faces for minibuffer group matches.")
2175 (defvar ivy-flx-limit 200
2176 "Used to conditionally turn off flx sorting.
2178 When the amount of matching candidates exceeds this limit, then
2179 no sorting is done.")
2181 (defun ivy--flx-sort (name cands)
2182 "Sort according to closeness to string NAME the string list CANDS."
2185 (< (length cands) ivy-flx-limit))
2186 (let* ((flx-name (if (string-match "^\\^" name)
2193 (let ((score (flx-score x flx-name ivy--flx-cache)))
2197 (if cands-with-score
2199 (let ((str (copy-sequence (cdr x)))
2202 (dolist (j (cdar x))
2203 (unless (eq j (1+ last-j))
2206 (ivy-add-face-text-property
2208 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2209 ivy-minibuffer-faces)
2212 (sort cands-with-score
2214 (> (caar x) (caar y)))))
2220 (defcustom ivy-format-function 'ivy-format-function-default
2221 "Function to transform the list of candidates into a string.
2222 This string is inserted into the minibuffer."
2224 (const :tag "Default" ivy-format-function-default)
2225 (const :tag "Arrow prefix" ivy-format-function-arrow)
2226 (const :tag "Full line" ivy-format-function-line)))
2228 (defun ivy--truncate-string (str width)
2229 "Truncate STR to WIDTH."
2230 (if (> (string-width str) width)
2231 (concat (substring str 0 (min (- width 3)
2232 (- (length str) 3))) "...")
2235 (defun ivy--format-function-generic (selected-fn other-fn cand-pairs separator)
2236 "Transform CAND-PAIRS into a string for minibuffer.
2237 SELECTED-FN and OTHER-FN each take two string arguments.
2238 SEPARATOR is used to join the candidates."
2242 (let ((str (car pair))
2244 (curr (eq (cl-incf i) ivy--index)))
2246 (funcall selected-fn str extra)
2247 (funcall other-fn str extra))))
2251 (defun ivy-format-function-default (cand-pairs)
2252 "Transform CAND-PAIRS into a string for minibuffer."
2253 (ivy--format-function-generic
2255 (concat (ivy--add-face str 'ivy-current-match) extra))
2260 (defun ivy-format-function-arrow (cand-pairs)
2261 "Transform CAND-PAIRS into a string for minibuffer."
2262 (ivy--format-function-generic
2264 (concat "> " (ivy--add-face str 'ivy-current-match) extra))
2266 (concat " " str extra))
2270 (defun ivy-format-function-line (cand-pairs)
2271 "Transform CAND-PAIRS into a string for minibuffer."
2272 (ivy--format-function-generic
2274 (ivy--add-face (concat str extra "\n") 'ivy-current-match))
2276 (concat str extra "\n"))
2280 (defun ivy-add-face-text-property (start end face str)
2281 (if (fboundp 'add-face-text-property)
2282 (add-face-text-property
2283 start end face nil str)
2284 (font-lock-append-text-property
2285 start end 'face face str)))
2287 (defun ivy--format-minibuffer-line (str)
2289 (str (copy-sequence str)))
2290 (cond ((eq ivy--regex-function 'ivy--regex-ignore-order)
2291 (when (consp ivy--old-re)
2293 (dolist (re ivy--old-re)
2294 (when (string-match (car re) str)
2295 (ivy-add-face-text-property
2296 (match-beginning 0) (match-end 0)
2297 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2298 ivy-minibuffer-faces)
2301 ((and (eq ivy-display-style 'fancy)
2302 (not (eq ivy--regex-function 'ivy--regex-fuzzy)))
2304 (setq ivy--old-re (funcall ivy--regex-function ivy-text)))
2305 (while (and (string-match ivy--old-re str start)
2306 (> (- (match-end 0) (match-beginning 0)) 0))
2307 (setq start (match-end 0))
2309 (while (<= i ivy--subexps)
2311 (cond ((zerop ivy--subexps)
2312 (cadr ivy-minibuffer-faces))
2314 (car ivy-minibuffer-faces))
2316 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2317 ivy-minibuffer-faces)))))
2318 (ivy-add-face-text-property
2319 (match-beginning i) (match-end i)
2324 (defun ivy--format (cands)
2325 "Return a string for CANDS suitable for display in the minibuffer.
2326 CANDS is a list of strings."
2327 (setq ivy--length (length cands))
2328 (when (>= ivy--index ivy--length)
2329 (setq ivy--index (max (1- ivy--length) 0)))
2331 (setq ivy--current "")
2332 (let* ((half-height (/ ivy-height 2))
2333 (start (max 0 (- ivy--index half-height)))
2334 (end (min (+ start (1- ivy-height)) ivy--length))
2335 (start (max 0 (min start (- end (1- ivy-height)))))
2336 (cands (cl-subseq cands start end))
2337 (index (- ivy--index start)))
2338 (cond (ivy--directory
2339 (setq cands (mapcar (lambda (x)
2340 (if (string-match-p "/\\'" x)
2341 (propertize x 'face 'ivy-subdir)
2344 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
2345 (setq cands (mapcar (lambda (x)
2346 (let ((b (get-buffer x)))
2348 (buffer-file-name b)
2349 (buffer-modified-p b))
2350 (propertize x 'face 'ivy-modified-buffer)
2353 (setq ivy--current (copy-sequence (nth index cands)))
2354 (let* ((ivy--index index)
2357 (cons (ivy--format-minibuffer-line cand) nil)) cands))
2358 (res (concat "\n" (funcall ivy-format-function cand-pairs))))
2359 (put-text-property 0 (length res) 'read-only nil res)
2362 (defvar ivy--virtual-buffers nil
2363 "Store the virtual buffers alist.")
2365 (defvar recentf-list)
2367 (defcustom ivy-virtual-abbreviate 'name
2368 "The mode of abbreviation for virtual buffer names."
2370 (const :tag "Only name" name)
2371 (const :tag "Full path" full)
2372 ;; eventually, uniquify
2375 (defun ivy--virtual-buffers ()
2376 "Adapted from `ido-add-virtual-buffers-to-list'."
2377 (unless recentf-mode
2379 (let ((bookmarks (and (boundp 'bookmark-alist)
2381 virtual-buffers name)
2382 (dolist (head (append
2384 (delete " - no file -"
2385 (delq nil (mapcar (lambda (bookmark)
2386 (cdr (assoc 'filename bookmark)))
2389 (if (eq ivy-virtual-abbreviate 'name)
2390 (file-name-nondirectory head)
2391 (expand-file-name head)))
2392 (when (equal name "")
2393 (setq name (file-name-nondirectory (directory-file-name head))))
2394 (when (equal name "")
2396 (and (not (equal name ""))
2397 (null (get-file-buffer head))
2398 (not (assoc name virtual-buffers))
2399 (push (cons name head) virtual-buffers)))
2400 (when virtual-buffers
2401 (dolist (comp virtual-buffers)
2402 (put-text-property 0 (length (car comp))
2405 (setq ivy--virtual-buffers (nreverse virtual-buffers))
2406 (mapcar #'car ivy--virtual-buffers))))
2408 (defcustom ivy-ignore-buffers nil
2409 "List of regexps matching buffer names to ignore."
2410 :type '(repeat regexp))
2412 (defun ivy--buffer-list (str &optional virtual)
2413 "Return the buffers that match STR.
2414 When VIRTUAL is non-nil, add virtual buffers."
2419 (if (with-current-buffer x
2421 (abbreviate-file-name default-directory)))
2422 (propertize x 'face 'ivy-remote)
2424 (all-completions str 'internal-complete-buffer))
2426 (ivy--virtual-buffers)))))
2428 (defun ivy--switch-buffer-action (buffer)
2430 BUFFER may be a string or nil."
2432 (if (zerop (length buffer))
2434 ivy-text nil 'force-same-window)
2435 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2437 (not (get-buffer buffer)))
2438 (find-file (cdr virtual))
2440 buffer nil 'force-same-window))))))
2442 (defun ivy--switch-buffer-other-window-action (buffer)
2443 "Switch to BUFFER in other window.
2444 BUFFER may be a string or nil."
2445 (if (zerop (length buffer))
2446 (switch-to-buffer-other-window ivy-text)
2447 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2449 (not (get-buffer buffer)))
2450 (find-file-other-window (cdr virtual))
2451 (switch-to-buffer-other-window buffer)))))
2453 (defun ivy--rename-buffer-action (buffer)
2455 (let ((new-name (read-string "Rename buffer (to new name): ")))
2456 (with-current-buffer buffer
2457 (rename-buffer new-name))))
2459 (defvar ivy-switch-buffer-map (make-sparse-keymap))
2466 (ivy--reset-state ivy-last))
2469 ivy--switch-buffer-other-window-action
2472 ivy--rename-buffer-action
2475 (defun ivy--switch-buffer-matcher (regexp candidates)
2476 "Return REGEXP-matching CANDIDATES.
2477 Skip buffers that match `ivy-ignore-buffers'."
2478 (let ((res (ivy--re-filter regexp candidates)))
2479 (if (or (null ivy-use-ignore)
2480 (null ivy-ignore-buffers))
2486 (string-match regexp buf))
2487 ivy-ignore-buffers))
2492 (defun ivy-switch-buffer ()
2493 "Switch to another buffer."
2496 (call-interactively 'switch-to-buffer)
2497 (let ((this-command 'ivy-switch-buffer))
2498 (ivy-read "Switch to buffer: " 'internal-complete-buffer
2499 :matcher #'ivy--switch-buffer-matcher
2500 :preselect (buffer-name (other-buffer (current-buffer)))
2501 :action #'ivy--switch-buffer-action
2502 :keymap ivy-switch-buffer-map
2503 :caller 'ivy-switch-buffer))))
2506 (defun ivy-switch-buffer-other-window ()
2507 "Switch to another buffer in another window."
2509 (ivy-read "Switch to buffer in other window: " 'internal-complete-buffer
2510 :preselect (buffer-name (other-buffer (current-buffer)))
2511 :action #'ivy--switch-buffer-other-window-action
2512 :keymap ivy-switch-buffer-map
2513 :caller 'ivy-switch-buffer-other-window))
2516 (defun ivy-recentf ()
2517 "Find a file on `recentf-list'."
2519 (ivy-read "Recentf: " recentf-list
2524 :caller 'ivy-recentf))
2526 (defun ivy-yank-word ()
2527 "Pull next word from buffer into search string."
2532 (le (line-end-position)))
2536 (setq amend (buffer-substring-no-properties pt (point))))))
2538 (insert (replace-regexp-in-string " +" " " amend)))))
2540 (defun ivy-kill-ring-save ()
2541 "Store the current candidates into the kill ring.
2542 If the region is active, forward to `kill-ring-save' instead."
2544 (if (region-active-p)
2545 (call-interactively 'kill-ring-save)
2552 (defun ivy-insert-current ()
2553 "Make the current candidate into current input.
2554 Don't finish completion."
2556 (delete-minibuffer-contents)
2557 (if (and ivy--directory
2558 (string-match "/$" ivy--current))
2559 (insert (substring ivy--current 0 -1))
2560 (insert ivy--current)))
2562 (defun ivy-toggle-fuzzy ()
2563 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
2565 (setq ivy--old-re nil)
2566 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
2567 (setq ivy--regex-function 'ivy--regex-plus)
2568 (setq ivy--regex-function 'ivy--regex-fuzzy)))
2570 (defun ivy-reverse-i-search ()
2571 "Enter a recursive `ivy-read' session using the current history.
2572 The selected history element will be inserted into the minibuffer."
2574 (let ((enable-recursive-minibuffers t)
2575 (history (symbol-value (ivy-state-history ivy-last)))
2577 (ivy-recursive-restore nil))
2578 (ivy-read "Reverse-i-search: "
2582 (setq ivy-last old-last))
2583 (delete-minibuffer-contents)
2584 (insert (substring-no-properties x))
2587 (defun ivy-restrict-to-matches ()
2588 "Restrict candidates to current matches and erase input."
2590 (delete-minibuffer-contents)
2591 (setq ivy--all-candidates
2592 (ivy--filter ivy-text ivy--all-candidates)))
2595 (defvar-local ivy-occur-last nil
2596 "Buffer-local value of `ivy-last'.
2597 Can't re-use `ivy-last' because using e.g. `swiper' in the same
2598 buffer would modify `ivy-last'.")
2600 (defvar ivy-occur-mode-map
2601 (let ((map (make-sparse-keymap)))
2602 (define-key map [mouse-1] 'ivy-occur-click)
2603 (define-key map (kbd "RET") 'ivy-occur-press)
2604 (define-key map (kbd "j") 'next-line)
2605 (define-key map (kbd "k") 'previous-line)
2606 (define-key map (kbd "h") 'backward-char)
2607 (define-key map (kbd "l") 'forward-char)
2608 (define-key map (kbd "g") 'ivy-occur-press)
2609 (define-key map (kbd "a") 'ivy-occur-read-action)
2610 (define-key map (kbd "o") 'ivy-occur-dispatch)
2611 (define-key map (kbd "q") 'quit-window)
2613 "Keymap for Ivy Occur mode.")
2615 (define-derived-mode ivy-occur-mode fundamental-mode "Ivy-Occur"
2616 "Major mode for output from \\[ivy-occur].
2618 \\{ivy-occur-mode-map}")
2620 (defvar ivy-occur-grep-mode-map
2621 (let ((map (copy-keymap ivy-occur-mode-map)))
2622 (define-key map (kbd "C-x C-q") 'ivy-wgrep-change-to-wgrep-mode)
2624 "Keymap for Ivy Occur Grep mode.")
2626 (define-derived-mode ivy-occur-grep-mode grep-mode "Ivy-Occur"
2627 "Major mode for output from \\[ivy-occur].
2629 \\{ivy-occur-grep-mode-map}")
2631 (defvar ivy--occurs-list nil
2632 "A list of custom occur generators per command.")
2634 (defun ivy-set-occur (cmd occur)
2635 "Assign CMD a custom OCCUR function."
2636 (setq ivy--occurs-list
2637 (plist-put ivy--occurs-list cmd occur)))
2639 (defun ivy--occur-insert-lines (cands)
2641 (add-text-properties
2645 help-echo "mouse-1: call ivy-action")
2650 "Stop completion and put the current matches into a new buffer.
2652 The new buffer remembers current action(s).
2654 While in the *ivy-occur* buffer, selecting a candidate with RET or
2655 a mouse click will call the appropriate action for that candidate.
2657 There is no limit on the number of *ivy-occur* buffers."
2659 (let* ((caller (ivy-state-caller ivy-last))
2660 (occur-fn (plist-get ivy--occurs-list caller))
2662 (generate-new-buffer
2663 (format "*ivy-occur%s \"%s\"*"
2665 (concat " " (prin1-to-string caller))
2668 (with-current-buffer buffer
2669 (let ((inhibit-read-only t))
2674 (insert (format "%d candidates:\n" (length ivy--old-cands)))
2675 (ivy--occur-insert-lines
2677 (lambda (cand) (concat " " cand))
2679 (setf (ivy-state-text ivy-last) ivy-text)
2680 (setq ivy-occur-last ivy-last)
2681 (setq-local ivy--directory ivy--directory))
2682 (ivy-exit-with-action
2683 `(lambda (_) (pop-to-buffer ,buffer)))))
2685 (declare-function wgrep-change-to-wgrep-mode "ext:wgrep")
2687 (defun ivy-wgrep-change-to-wgrep-mode ()
2688 "Forward to `wgrep-change-to-wgrep-mode'."
2690 (if (require 'wgrep nil 'noerror)
2691 (wgrep-change-to-wgrep-mode)
2692 (error "Package wgrep isn't installed")))
2694 (defun ivy-occur-read-action ()
2695 "Select one of the available actions as the current one."
2697 (let ((ivy-last ivy-occur-last))
2700 (defun ivy-occur-dispatch ()
2701 "Call one of the available actions on the current item."
2703 (let* ((state-action (ivy-state-action ivy-occur-last))
2704 (actions (if (symbolp state-action)
2706 (copy-sequence state-action))))
2709 (ivy-occur-read-action)
2711 (setf (ivy-state-action ivy-occur-last) actions))))
2713 (defun ivy-occur-click (event)
2714 "Execute action for the current candidate.
2715 EVENT gives the mouse position."
2717 (let ((window (posn-window (event-end event)))
2718 (pos (posn-point (event-end event))))
2719 (with-current-buffer (window-buffer window)
2721 (ivy-occur-press))))
2723 (declare-function swiper--cleanup "swiper")
2724 (declare-function swiper--add-overlays "swiper")
2726 (defun ivy-occur-press ()
2727 "Execute action for the current candidate."
2730 (when (save-excursion
2732 (looking-at "\\(?:./\\| \\)\\(.*\\)$"))
2733 (let* ((ivy-last ivy-occur-last)
2734 (ivy-text (ivy-state-text ivy-last))
2735 (str (buffer-substring
2738 (coll (ivy-state-collection ivy-last))
2739 (action (ivy--get-action ivy-last))
2743 (if (and (consp coll)
2745 (cdr (assoc str coll))
2747 (if (memq (ivy-state-caller ivy-last)
2748 '(swiper counsel-git-grep))
2749 (with-current-buffer (window-buffer (selected-window))
2751 (swiper--add-overlays
2752 (ivy--regex ivy-text)
2753 (line-beginning-position)
2756 (run-at-time 0.5 nil 'swiper--cleanup))
2757 (pulse-momentary-highlight-one-line (point)))))))
2759 (defvar ivy-help-file (let ((default-directory
2761 (file-name-directory load-file-name)
2762 default-directory)))
2763 (if (file-exists-p "ivy-help.org")
2764 (expand-file-name "ivy-help.org")
2765 (if (file-exists-p "doc/ivy-help.org")
2766 (expand-file-name "doc/ivy-help.org"))))
2767 "The file for `ivy-help'.")
2772 (let ((buf (get-buffer "*Ivy Help*")))
2774 (setq buf (get-buffer-create "*Ivy Help*"))
2775 (with-current-buffer buf
2776 (insert-file-contents ivy-help-file)
2779 (goto-char (point-min))))
2780 (if (eq this-command 'ivy-help)
2781 (switch-to-buffer buf)
2783 (pop-to-buffer buf)))
2785 (goto-char (point-min))))
2789 ;;; ivy.el ends here