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 modulo 1.")
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 modulo 2.")
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 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)))
172 (defvar ivy-minibuffer-map
173 (let ((map (make-sparse-keymap)))
174 (define-key map (kbd "C-m") 'ivy-done)
175 (define-key map (kbd "C-M-m") 'ivy-call)
176 (define-key map (kbd "C-j") 'ivy-alt-done)
177 (define-key map (kbd "C-M-j") 'ivy-immediate-done)
178 (define-key map (kbd "TAB") 'ivy-partial-or-done)
179 (define-key map (kbd "C-n") 'ivy-next-line)
180 (define-key map (kbd "C-p") 'ivy-previous-line)
181 (define-key map (kbd "<down>") 'ivy-next-line)
182 (define-key map (kbd "<up>") 'ivy-previous-line)
183 (define-key map (kbd "C-s") 'ivy-next-line-or-history)
184 (define-key map (kbd "C-r") 'ivy-reverse-i-search)
185 (define-key map (kbd "SPC") 'self-insert-command)
186 (define-key map (kbd "DEL") 'ivy-backward-delete-char)
187 (define-key map (kbd "M-DEL") 'ivy-backward-kill-word)
188 (define-key map (kbd "C-d") 'ivy-delete-char)
189 (define-key map (kbd "C-f") 'ivy-forward-char)
190 (define-key map (kbd "M-d") 'ivy-kill-word)
191 (define-key map (kbd "M-<") 'ivy-beginning-of-buffer)
192 (define-key map (kbd "M->") 'ivy-end-of-buffer)
193 (define-key map (kbd "M-n") 'ivy-next-history-element)
194 (define-key map (kbd "M-p") 'ivy-previous-history-element)
195 (define-key map (kbd "C-g") 'minibuffer-keyboard-quit)
196 (define-key map (kbd "C-v") 'ivy-scroll-up-command)
197 (define-key map (kbd "M-v") 'ivy-scroll-down-command)
198 (define-key map (kbd "C-M-n") 'ivy-next-line-and-call)
199 (define-key map (kbd "C-M-p") 'ivy-previous-line-and-call)
200 (define-key map (kbd "M-q") 'ivy-toggle-regexp-quote)
201 (define-key map (kbd "M-j") 'ivy-yank-word)
202 (define-key map (kbd "M-i") 'ivy-insert-current)
203 (define-key map (kbd "C-o") 'hydra-ivy/body)
204 (define-key map (kbd "M-o") 'ivy-dispatching-done)
205 (define-key map (kbd "C-M-o") 'ivy-dispatching-call)
206 (define-key map (kbd "C-k") 'ivy-kill-line)
207 (define-key map (kbd "S-SPC") 'ivy-restrict-to-matches)
208 (define-key map (kbd "M-w") 'ivy-kill-ring-save)
209 (define-key map (kbd "C-'") 'ivy-avy)
210 (define-key map (kbd "C-M-a") 'ivy-read-action)
211 (define-key map (kbd "C-c C-o") 'ivy-occur)
213 "Keymap used in the minibuffer.")
214 (autoload 'hydra-ivy/body "ivy-hydra" "" t)
217 (let ((map (make-sparse-keymap)))
218 (define-key map [remap switch-to-buffer] 'ivy-switch-buffer)
220 "Keymap for `ivy-mode'.")
223 (cl-defstruct ivy-state
225 predicate require-match initial-input
226 history preselect keymap update-fn sort
227 ;; The window in which `ivy-read' was called
229 ;; The buffer in which `ivy-read' was called
231 ;; The value of `ivy-text' to be used by `ivy-occur'
237 ;; When this is non-nil, call it for each input change to get new candidates
241 (defvar ivy-last (make-ivy-state)
242 "The last parameters passed to `ivy-read'.
244 This should eventually become a stack so that you could use
245 `ivy-read' recursively.")
247 (defsubst ivy-set-action (action)
248 (setf (ivy-state-action ivy-last) action))
250 (defvar ivy-history nil
251 "History list of candidates entered in the minibuffer.
253 Maximum length of the history list is determined by the value
254 of `history-length'.")
256 (defvar ivy--directory nil
257 "Current directory when completing file names.")
259 (defvar ivy--length 0
260 "Store the amount of viable candidates.")
263 "Store the user's string as it is typed in.")
265 (defvar ivy--current ""
266 "Current candidate.")
269 "Store the index of the current candidate.")
272 "Store 'done if the completion was successfully selected.
273 Otherwise, store nil.")
275 (defvar ivy--all-candidates nil
276 "Store the candidates passed to `ivy-read'.")
278 (defvar ivy--default nil
279 "Default initial input.")
281 (defvar ivy--prompt nil
282 "Store the format-style prompt.
283 When non-nil, it should contain at least one %d.")
285 (defvar ivy--prompt-extra ""
286 "Temporary modifications to the prompt.")
288 (defvar ivy--old-re nil
289 "Store the old regexp.")
291 (defvar ivy--old-cands nil
292 "Store the candidates matched by `ivy--old-re'.")
294 (defvar ivy--regex-function 'ivy--regex
295 "Current function for building a regex.")
297 (defvar ivy--subexps 0
298 "Number of groups in the current `ivy--regex'.")
300 (defvar ivy--full-length nil
301 "When :dynamic-collection is non-nil, this can be the total amount of candidates.")
303 (defvar ivy--old-text ""
304 "Store old `ivy-text' for dynamic completion.")
306 (defvar ivy-case-fold-search 'auto
307 "Store the current overriding `case-fold-search'.")
309 (defvar Info-current-file)
311 (defmacro ivy-quit-and-run (&rest body)
312 "Quit the minibuffer and run BODY afterwards."
314 (put 'quit 'error-message "")
317 (put 'quit 'error-message "Quit")
319 (minibuffer-keyboard-quit)))
321 (defun ivy-exit-with-action (action)
322 "Quit the minibuffer and call ACTION afterwards."
326 (ivy-set-action ',(ivy-state-action ivy-last))))
327 (setq ivy-exit 'done)
330 (defmacro with-ivy-window (&rest body)
331 "Execute BODY in the window from which `ivy-read' was called."
334 `(with-selected-window (ivy--get-window ivy-last)
337 (defun ivy--done (text)
338 "Insert TEXT and exit minibuffer."
339 (if (and ivy--directory
340 (not (eq (ivy-state-history ivy-last) 'grep-files-history)))
341 (insert (setq ivy--current (expand-file-name
342 text ivy--directory)))
343 (insert (setq ivy--current text)))
344 (setq ivy-exit 'done)
349 "Exit the minibuffer with the selected candidate."
351 (delete-minibuffer-contents)
352 (cond ((> ivy--length 0)
353 (ivy--done ivy--current))
354 ((memq (ivy-state-collection ivy-last)
355 '(read-file-name-internal internal-complete-buffer))
356 (if (or (not (eq confirm-nonexistent-file-or-buffer t))
357 (equal " (confirm)" ivy--prompt-extra))
359 (setq ivy--prompt-extra " (confirm)")
362 ((memq (ivy-state-require-match ivy-last)
363 '(nil confirm confirm-after-completion))
364 (ivy--done ivy-text))
366 (setq ivy--prompt-extra " (match required)")
370 (defun ivy-read-action ()
371 "Change the action to one of the available ones."
373 (let ((actions (ivy-state-action ivy-last)))
374 (unless (null (ivy--actionp actions))
375 (let* ((hint (concat (if (eq this-command 'ivy-read-action)
384 'face 'font-lock-builtin-face)
389 (key (string (read-key hint)))
390 (action-idx (cl-position-if
391 (lambda (x) (equal (car x) key))
393 (cond ((string= key "
\a"))
395 (error "%s is not bound" key))
398 (setcar actions (1+ action-idx))
399 (ivy-set-action actions)))))))
401 (defun ivy-dispatching-done ()
402 "Select one of the available actions and call `ivy-done'."
407 (defun ivy-dispatching-call ()
408 "Select one of the available actions and call `ivy-call'."
410 (let ((actions (copy-sequence (ivy-state-action ivy-last))))
412 (when (ivy-read-action)
414 (ivy-set-action actions))))
416 (defun ivy-build-tramp-name (x)
417 "Reconstruct X into a path.
418 Is is a cons cell, related to `tramp-get-completion-function'."
422 (concat user "@" domain)
425 (declare-function tramp-get-completion-function "tramp")
426 (declare-function Info-find-node "info")
428 (defun ivy-alt-done (&optional arg)
429 "Exit the minibuffer with the selected candidate.
430 When ARG is t, exit with current text, ignoring the candidates."
433 (ivy-immediate-done))
435 (ivy--directory-done))
436 ((eq (ivy-state-collection ivy-last) 'Info-read-node-name-1)
437 (if (or (equal ivy--current "(./)")
438 (equal ivy--current "(../)"))
440 (ivy-read "Go to file: " 'read-file-name-internal
443 (expand-file-name x ivy--directory)
449 (defun ivy--directory-done ()
450 "Handle exit from the minibuffer when completing file names."
453 ((equal ivy-text "/sudo::")
454 (setq dir (concat ivy-text ivy--directory))
459 (not (equal ivy-text ""))
463 (file-name-as-directory
465 ivy-text ivy--directory))))))
467 (not (string= ivy--current "./"))
468 (cl-plusp ivy--length)
471 (setq dir (file-name-as-directory
473 ivy--current ivy--directory)))))))
476 ((or (and (equal ivy--directory "/")
477 (string-match "\\`[^/]+:.*:.*\\'" ivy-text))
478 (string-match "\\`/[^/]+:.*:.*\\'" ivy-text))
480 ((or (and (equal ivy--directory "/")
482 "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
485 "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
487 (setq ivy-text ivy--current))))
489 "\\`/\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
491 (let ((method (match-string 1 ivy-text))
492 (user (match-string 2 ivy-text))
493 (rest (match-string 3 ivy-text))
496 (dolist (x (tramp-get-completion-function method))
497 (setq res (append res (funcall (car x) (cadr x)))))
498 (setq res (delq nil res))
502 (setq res (cl-delete-duplicates res :test #'equal))
503 (let* ((old-ivy-last ivy-last)
504 (enable-recursive-minibuffers t)
505 (host (ivy-read "user@host: "
506 (mapcar #'ivy-build-tramp-name res)
507 :initial-input rest)))
508 (setq ivy-last old-ivy-last)
510 (setq ivy--directory "/")
511 (ivy--cd (concat "/" method ":" host ":"))))))
515 (defcustom ivy-tab-space nil
516 "When non-nil, `ivy-partial-or-done' should insert a space."
519 (defun ivy-partial-or-done ()
520 "Complete the minibuffer text as much as possible.
521 If the text hasn't changed as a result, forward to `ivy-alt-done'."
523 (if (and (eq (ivy-state-collection ivy-last) #'read-file-name-internal)
524 (or (and (equal ivy--directory "/")
525 (string-match "\\`[^/]+:.*\\'" ivy-text))
526 (string-match "\\`/" ivy-text)))
527 (let ((default-directory ivy--directory))
528 (minibuffer-complete)
529 (setq ivy-text (ivy--input))
530 (when (file-directory-p
531 (expand-file-name ivy-text ivy--directory))
532 (ivy--cd (file-name-as-directory
533 (expand-file-name ivy-text ivy--directory)))))
535 (when (or (eq this-command last-command)
539 (defun ivy-partial ()
540 "Complete the minibuffer text as much as possible."
542 (let* ((parts (or (split-string ivy-text " " t) (list "")))
543 (postfix (car (last parts)))
544 (completion-ignore-case t)
545 (startp (string-match "^\\^" postfix))
546 (new (try-completion (if startp
547 (substring postfix 1)
549 (mapcar (lambda (str)
550 (let ((i (string-match postfix str)))
554 (cond ((eq new t) nil)
555 ((string= new ivy-text) nil)
557 (delete-region (minibuffer-prompt-end) (point-max))
562 (insert (mapconcat #'identity parts " ")
563 (if ivy-tab-space " " ""))
566 (defun ivy-immediate-done ()
567 "Exit the minibuffer with the current input."
569 (delete-minibuffer-contents)
570 (insert (setq ivy--current
572 (expand-file-name ivy-text ivy--directory)
574 (setq ivy-exit 'done)
579 "Resume the last completion session."
581 (when (eq (ivy-state-caller ivy-last) 'swiper)
582 (switch-to-buffer (ivy-state-buffer ivy-last)))
583 (with-current-buffer (ivy-state-buffer ivy-last)
585 (ivy-state-prompt ivy-last)
586 (ivy-state-collection ivy-last)
587 :predicate (ivy-state-predicate ivy-last)
588 :require-match (ivy-state-require-match ivy-last)
589 :initial-input ivy-text
590 :history (ivy-state-history ivy-last)
591 :preselect (unless (eq (ivy-state-collection ivy-last)
592 'read-file-name-internal)
594 :keymap (ivy-state-keymap ivy-last)
595 :update-fn (ivy-state-update-fn ivy-last)
596 :sort (ivy-state-sort ivy-last)
597 :action (ivy-state-action ivy-last)
598 :unwind (ivy-state-unwind ivy-last)
599 :re-builder (ivy-state-re-builder ivy-last)
600 :matcher (ivy-state-matcher ivy-last)
601 :dynamic-collection (ivy-state-dynamic-collection ivy-last)
602 :caller (ivy-state-caller ivy-last))))
604 (defvar ivy-calling nil
605 "When non-nil, call the current action when `ivy--index' changes.")
607 (defun ivy-set-index (index)
608 "Set `ivy--index' to INDEX."
609 (setq ivy--index index)
614 (defun ivy-beginning-of-buffer ()
615 "Select the first completion candidate."
619 (defun ivy-end-of-buffer ()
620 "Select the last completion candidate."
622 (ivy-set-index (1- ivy--length)))
624 (defun ivy-scroll-up-command ()
625 "Scroll the candidates upward by the minibuffer height."
627 (ivy-set-index (min (1- (+ ivy--index ivy-height))
630 (defun ivy-scroll-down-command ()
631 "Scroll the candidates downward by the minibuffer height."
633 (ivy-set-index (max (1+ (- ivy--index ivy-height))
636 (defun ivy-minibuffer-grow ()
637 "Grow the minibuffer window by 1 line."
639 (setq-local max-mini-window-height
640 (cl-incf ivy-height)))
642 (defun ivy-minibuffer-shrink ()
643 "Shrink the minibuffer window by 1 line."
645 (unless (<= ivy-height 2)
646 (setq-local max-mini-window-height
647 (cl-decf ivy-height))
648 (window-resize (selected-window) -1)))
650 (defun ivy-next-line (&optional arg)
651 "Move cursor vertically down ARG candidates."
653 (setq arg (or arg 1))
654 (let ((index (+ ivy--index arg)))
655 (if (> index (1- ivy--length))
657 (ivy-beginning-of-buffer)
658 (ivy-set-index (1- ivy--length)))
659 (ivy-set-index index))))
661 (defun ivy-next-line-or-history (&optional arg)
662 "Move cursor vertically down ARG candidates.
663 If the input is empty, select the previous history element instead."
665 (when (string= ivy-text "")
666 (ivy-previous-history-element 1))
669 (defun ivy-previous-line (&optional arg)
670 "Move cursor vertically up ARG candidates."
672 (setq arg (or arg 1))
673 (let ((index (- ivy--index arg)))
678 (ivy-set-index index))))
680 (defun ivy-previous-line-or-history (arg)
681 "Move cursor vertically up ARG candidates.
682 If the input is empty, select the previous history element instead."
684 (when (string= ivy-text "")
685 (ivy-previous-history-element 1))
686 (ivy-previous-line arg))
688 (defun ivy-toggle-calling ()
689 "Flip `ivy-calling'."
691 (when (setq ivy-calling (not ivy-calling))
694 (defun ivy--get-action (state)
695 "Get the action function from STATE."
696 (let ((action (ivy-state-action state)))
698 (if (functionp action)
700 (cadr (nth (car action) action))))))
702 (defun ivy--get-window (state)
703 "Get the window from STATE."
704 (if (ivy-state-p state)
705 (let ((window (ivy-state-window state)))
706 (if (window-live-p window)
708 (if (= (length (window-list)) 1)
713 (defun ivy--actionp (x)
714 "Return non-nil when X is a list of actions."
715 (and x (listp x) (not (eq (car x) 'closure))))
717 (defun ivy-next-action ()
718 "When the current action is a list, scroll it forwards."
720 (let ((action (ivy-state-action ivy-last)))
721 (when (ivy--actionp action)
722 (unless (>= (car action) (1- (length action)))
723 (cl-incf (car action))))))
725 (defun ivy-prev-action ()
726 "When the current action is a list, scroll it backwards."
728 (let ((action (ivy-state-action ivy-last)))
729 (when (ivy--actionp action)
730 (unless (<= (car action) 1)
731 (cl-decf (car action))))))
733 (defun ivy-action-name ()
734 "Return the name associated with the current action."
735 (let ((action (ivy-state-action ivy-last)))
736 (if (ivy--actionp action)
740 (nth 2 (nth (car action) action)))
744 "Call the current action without exiting completion."
746 (let ((action (ivy--get-action ivy-last)))
748 (let* ((collection (ivy-state-collection ivy-last))
749 (x (if (and (consp collection)
750 (consp (car collection)))
751 (cdr (assoc ivy--current collection))
752 (if (equal ivy--current "")
755 (prog1 (funcall action x)
756 (unless (or (eq ivy-exit 'done)
757 (equal (selected-window)
758 (active-minibuffer-window))
759 (null (active-minibuffer-window)))
760 (select-window (active-minibuffer-window))))))))
762 (defun ivy-next-line-and-call (&optional arg)
763 "Move cursor vertically down ARG candidates.
764 Call the permanent action if possible."
770 (defun ivy-previous-line-and-call (&optional arg)
771 "Move cursor vertically down ARG candidates.
772 Call the permanent action if possible."
774 (ivy-previous-line arg)
778 (defun ivy-previous-history-element (arg)
779 "Forward to `previous-history-element' with ARG."
781 (previous-history-element arg)
784 (ivy--maybe-scroll-history))
786 (defun ivy-next-history-element (arg)
787 "Forward to `next-history-element' with ARG."
789 (next-history-element arg)
792 (ivy--maybe-scroll-history))
794 (defvar ivy-ffap-url-functions nil
795 "List of functions that check if the point is on a URL.")
797 (defun ivy--cd-maybe ()
798 "Check if the current input points to a different directory.
799 If so, move to that directory, while keeping only the file name."
801 (let ((input (ivy--input))
803 (if (setq url (or (ffap-url-p input)
808 ivy-ffap-url-functions
809 :initial-value nil))))
810 (ivy-exit-with-action
812 (funcall ffap-url-fetcher url)))
813 (setq input (expand-file-name input))
814 (let ((file (file-name-nondirectory input))
815 (dir (expand-file-name (file-name-directory input))))
816 (if (string= dir ivy--directory)
818 (delete-minibuffer-contents)
823 (defun ivy--maybe-scroll-history ()
824 "If the selected history element has an index, scroll there."
825 (let ((idx (ignore-errors
827 (minibuffer-prompt-end)
831 (setq ivy--index idx))))
834 "When completing file names, move to directory DIR."
835 (if (null ivy--directory)
837 (setq ivy--old-cands nil)
838 (setq ivy--old-re nil)
840 (setq ivy--all-candidates
841 (ivy--sorted-files (setq ivy--directory dir)))
843 (delete-minibuffer-contents)))
845 (defun ivy-backward-delete-char ()
846 "Forward to `backward-delete-char'.
847 On error (read-only), call `ivy-on-del-error-function'."
849 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
851 (ivy--cd (file-name-directory
857 (backward-delete-char 1)
859 (when ivy-on-del-error-function
860 (funcall ivy-on-del-error-function))))))
862 (defun ivy-delete-char (arg)
863 "Forward to `delete-char' ARG."
865 (unless (= (point) (line-end-position))
868 (defun ivy-forward-char (arg)
869 "Forward to `forward-char' ARG."
871 (unless (= (point) (line-end-position))
874 (defun ivy-kill-word (arg)
875 "Forward to `kill-word' ARG."
877 (unless (= (point) (line-end-position))
880 (defun ivy-kill-line ()
881 "Forward to `kill-line'."
884 (kill-region (minibuffer-prompt-end) (point))
887 (defun ivy-backward-kill-word ()
888 "Forward to `backward-kill-word'."
890 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
892 (ivy--cd (file-name-directory
900 (delete-region (point) pt)))))
902 (defvar ivy--regexp-quote 'regexp-quote
903 "Store the regexp quoting state.")
905 (defun ivy-toggle-regexp-quote ()
906 "Toggle the regexp quoting."
908 (setq ivy--old-re nil)
909 (cl-rotatef ivy--regex-function ivy--regexp-quote))
911 (defvar avy-all-windows)
914 (defvar avy-keys-alist)
916 (defvar avy-styles-alist)
917 (declare-function avy--process "ext:avy")
918 (declare-function avy--style-fn "ext:avy")
920 (eval-after-load 'avy
921 '(add-to-list 'avy-styles-alist '(ivy-avy . pre)))
924 "Jump to one of the current ivy candidates."
926 (unless (require 'avy nil 'noerror)
927 (error "Package avy isn't installed"))
928 (let* ((avy-all-windows nil)
929 (avy-keys (or (cdr (assq 'ivy-avy avy-keys-alist))
931 (avy-style (or (cdr (assq 'ivy-avy
941 (goto-char (point-min))
943 (while (< (point) (point-max))
949 (setq avy-action #'identity)
951 (nreverse candidates)
952 (avy--style-fn avy-style)))))
953 (ivy-set-index (- (line-number-at-pos candidate) 2))
957 (defun ivy-sort-file-function-default (x y)
958 "Compare two files X and Y.
959 Prioritize directories."
960 (if (get-text-property 0 'dirp x)
961 (if (get-text-property 0 'dirp y)
964 (if (get-text-property 0 'dirp y)
968 (defcustom ivy-sort-functions-alist
969 '((read-file-name-internal . ivy-sort-file-function-default)
970 (internal-complete-buffer . nil)
971 (counsel-git-grep-function . nil)
972 (Man-goto-section . nil)
975 "An alist of sorting functions for each collection function.
976 Interactive functions that call completion fit in here as well.
978 Nil means no sorting, which is useful to turn off the sorting for
979 functions that have candidates in the natural buffer order, like
980 `org-refile' or `Man-goto-section'.
982 The entry associated with t is used for all fall-through cases.
984 See also `ivy-sort-max-size'."
988 (const :tag "All other functions" t)
989 (symbol :tag "Function"))
991 (const :tag "plain sort" string-lessp)
992 (const :tag "file sort" ivy-sort-file-function-default)
993 (const :tag "no sort" nil)))
996 (defvar ivy-index-functions-alist
997 '((swiper . ivy-recompute-index-swiper)
998 (swiper-multi . ivy-recompute-index-swiper)
999 (counsel-git-grep . ivy-recompute-index-swiper)
1000 (counsel-grep . ivy-recompute-index-swiper-async)
1001 (t . ivy-recompute-index-zero))
1002 "An alist of index recomputing functions for each collection function.
1003 When the input changes, the appropriate function returns an
1004 integer - the index of the matched candidate that should be
1007 (defvar ivy-re-builders-alist
1008 '((t . ivy--regex-plus))
1009 "An alist of regex building functions for each collection function.
1011 Each key is (in order of priority):
1012 1. The actual collection function, e.g. `read-file-name-internal'.
1013 2. The symbol passed by :caller into `ivy-read'.
1017 Each value is a function that should take a string and return a
1018 valid regex or a regex sequence (see below).
1020 Possible choices: `ivy--regex', `regexp-quote',
1021 `ivy--regex-plus', `ivy--regex-fuzzy'.
1023 If a function returns a list, it should format like this:
1024 '((\"matching-regexp\" . t) (\"non-matching-regexp\") ...).
1026 The matches will be filtered in a sequence, you can mix the
1027 regexps that should match and that should not match as you
1030 (defvar ivy-initial-inputs-alist
1031 '((org-refile . "^")
1032 (org-agenda-refile . "^")
1033 (org-capture-refile . "^")
1035 (counsel-describe-function . "^")
1036 (counsel-describe-variable . "^")
1039 "Command to initial input table.")
1041 (defcustom ivy-sort-max-size 30000
1042 "Sorting won't be done for collections larger than this."
1045 (defun ivy--sorted-files (dir)
1046 "Return the list of files in DIR.
1047 Directories come first."
1048 (let* ((default-directory dir)
1049 (seq (all-completions "" 'read-file-name-internal))
1053 (setq seq (delete "./" (delete "../" seq)))
1054 (when (eq (setq sort-fn (cdr (assoc 'read-file-name-internal
1055 ivy-sort-functions-alist)))
1056 #'ivy-sort-file-function-default)
1057 (setq seq (mapcar (lambda (x)
1058 (propertize x 'dirp (string-match-p "/\\'" x)))
1061 (setq seq (cl-sort seq sort-fn)))
1062 (dolist (dir ivy-extra-directories)
1066 (defvar ivy-recursive-restore t
1067 "When non-nil, restore the above state when exiting the minibuffer.
1068 This variable is let-bound to nil by functions that take care of
1069 the restoring themselves.")
1072 (cl-defun ivy-read (prompt collection
1074 predicate require-match initial-input
1075 history preselect keymap update-fn sort
1076 action unwind re-builder matcher dynamic-collection caller)
1077 "Read a string in the minibuffer, with completion.
1079 PROMPT is a format string, normally ending in a colon and a
1080 space; %d anywhere in the string is replaced by the current
1081 number of matching candidates. For the literal % character,
1082 escape it with %%. See also `ivy-count-format'.
1084 COLLECTION is either a list of strings, a function, an alist, or
1087 If INITIAL-INPUT is not nil, then insert that input in the
1088 minibuffer initially.
1090 KEYMAP is composed with `ivy-minibuffer-map'.
1092 If PRESELECT is not nil, then select the corresponding candidate
1093 out of the ones that match the INITIAL-INPUT.
1095 UPDATE-FN is called each time the current candidate(s) is changed.
1097 When SORT is t, use `ivy-sort-functions-alist' for sorting.
1099 ACTION is a lambda function to call after selecting a result. It
1100 takes a single string argument.
1102 UNWIND is a lambda function to call before exiting.
1104 RE-BUILDER is a lambda function to call to transform text into a
1107 MATCHER is to override matching.
1109 DYNAMIC-COLLECTION is a boolean to specify if the list of
1110 candidates is updated after each input by calling COLLECTION.
1112 CALLER is a symbol to uniquely identify the caller to `ivy-read'.
1113 It is used, along with COLLECTION, to determine which
1114 customizations apply to the current completion session."
1115 (let ((extra-actions (append (plist-get ivy--actions-list t)
1116 (plist-get ivy--actions-list this-command))))
1119 (if (functionp action)
1121 ("o" ,action "default")
1123 (delete-dups (append action extra-actions))))))
1124 (let ((recursive-ivy-last (and (active-minibuffer-window) ivy-last)))
1128 :collection collection
1129 :predicate predicate
1130 :require-match require-match
1131 :initial-input initial-input
1133 :preselect preselect
1135 :update-fn update-fn
1138 :window (selected-window)
1139 :buffer (current-buffer)
1141 :re-builder re-builder
1143 :dynamic-collection dynamic-collection
1145 (ivy--reset-state ivy-last)
1148 (minibuffer-with-setup-hook
1149 #'ivy--minibuffer-setup
1150 (let* ((hist (or history 'ivy-history))
1151 (minibuffer-completion-table collection)
1152 (minibuffer-completion-predicate predicate)
1153 (resize-mini-windows (cond
1154 ((display-graphic-p) nil)
1155 ((null resize-mini-windows) 'grow-only)
1156 (t resize-mini-windows))))
1157 (read-from-minibuffer
1159 (ivy-state-initial-input ivy-last)
1160 (make-composed-keymap keymap ivy-minibuffer-map)
1163 (when (eq ivy-exit 'done)
1164 (let ((item (if ivy--directory
1167 (unless (equal item "")
1168 (set hist (cons (propertize item 'ivy-index ivy--index)
1170 (cdr (symbol-value hist))))))))
1172 (remove-hook 'post-command-hook #'ivy--exhibit)
1173 (when (setq unwind (ivy-state-unwind ivy-last))
1175 (unless (eq ivy-exit 'done)
1176 (when recursive-ivy-last
1177 (ivy--reset-state (setq ivy-last recursive-ivy-last)))))
1179 (when (and recursive-ivy-last
1180 ivy-recursive-restore)
1181 (ivy--reset-state (setq ivy-last recursive-ivy-last))))))
1183 (defun ivy--reset-state (state)
1184 "Reset the ivy to STATE.
1185 This is useful for recursive `ivy-read'."
1186 (let ((prompt (or (ivy-state-prompt state) ""))
1187 (collection (ivy-state-collection state))
1188 (predicate (ivy-state-predicate state))
1189 (history (ivy-state-history state))
1190 (preselect (ivy-state-preselect state))
1191 (sort (ivy-state-sort state))
1192 (re-builder (ivy-state-re-builder state))
1193 (dynamic-collection (ivy-state-dynamic-collection state))
1194 (initial-input (ivy-state-initial-input state))
1195 (require-match (ivy-state-require-match state))
1196 (caller (ivy-state-caller state)))
1197 (unless initial-input
1198 (setq initial-input (cdr (assoc this-command
1199 ivy-initial-inputs-alist))))
1200 (setq ivy--directory nil)
1201 (setq ivy-case-fold-search 'auto)
1202 (setq ivy--regex-function
1204 (and (functionp collection)
1205 (cdr (assoc collection ivy-re-builders-alist)))
1207 (cdr (assoc caller ivy-re-builders-alist)))
1208 (cdr (assoc this-command ivy-re-builders-alist))
1209 (cdr (assoc t ivy-re-builders-alist))
1211 (setq ivy--subexps 0)
1212 (setq ivy--regexp-quote 'regexp-quote)
1213 (setq ivy--old-text "")
1214 (setq ivy--full-length nil)
1216 (setq ivy-calling nil)
1218 (cond ((eq collection 'Info-read-node-name-1)
1219 (if (equal Info-current-file "dir")
1221 (mapcar (lambda (x) (format "(%s)" x))
1222 (cl-delete-duplicates
1223 (all-completions "(" collection predicate)
1225 (setq coll (all-completions "" collection predicate))))
1226 ((eq collection 'read-file-name-internal)
1227 (setq ivy--directory default-directory)
1230 (let ((preselect-directory (file-name-directory preselect)))
1231 (unless (or (null preselect-directory)
1232 (string= preselect-directory
1234 (setq ivy--directory preselect-directory))
1236 (ivy-state-preselect state)
1237 (setq preselect (file-name-nondirectory preselect)))))
1238 (setq coll (ivy--sorted-files ivy--directory))
1240 (unless (or require-match
1241 (equal initial-input default-directory)
1242 (equal initial-input ""))
1243 (setq coll (cons initial-input coll)))
1244 (unless (ivy-state-action ivy-last)
1245 (setq initial-input nil))))
1246 ((eq collection 'internal-complete-buffer)
1247 (setq coll (ivy--buffer-list "" ivy-use-virtual-buffers)))
1248 ((or (functionp collection)
1249 (byte-code-function-p collection)
1250 (vectorp collection)
1251 (and (consp collection) (listp (car collection)))
1252 (hash-table-p collection))
1253 (setq coll (all-completions "" collection predicate)))
1255 (setq coll collection)))
1257 (if (and (functionp collection)
1258 (setq sort-fn (assoc collection ivy-sort-functions-alist)))
1259 (when (and (setq sort-fn (cdr sort-fn))
1260 (not (eq collection 'read-file-name-internal)))
1261 (setq coll (cl-sort coll sort-fn)))
1262 (unless (eq history 'org-refile-history)
1263 (if (and (setq sort-fn (cdr (assoc t ivy-sort-functions-alist)))
1264 (<= (length coll) ivy-sort-max-size))
1265 (setq coll (cl-sort (copy-sequence coll) sort-fn))))))
1267 (unless (or (and require-match
1268 (not (eq collection 'internal-complete-buffer)))
1270 (let ((re (regexp-quote preselect)))
1271 (cl-find-if (lambda (x) (string-match re x))
1273 (setq coll (cons preselect coll))))
1274 (setq ivy--old-re nil)
1275 (setq ivy--old-cands nil)
1276 (when (integerp preselect)
1277 (setq ivy--old-re "")
1278 (setq ivy--index preselect))
1280 ;; Needed for anchor to work
1281 (setq ivy--old-cands coll)
1282 (setq ivy--old-cands (ivy--filter initial-input coll)))
1283 (setq ivy--all-candidates coll)
1284 (unless (integerp preselect)
1285 (setq ivy--index (or
1286 (and dynamic-collection
1289 (ivy--preselect-index
1296 (setq ivy--default (or
1297 (thing-at-point 'url)
1298 (thing-at-point 'symbol)
1301 (cond ((string-match "%.*d" prompt)
1303 ((null ivy-count-format)
1305 "`ivy-count-format' can't be nil. Set it to an empty string instead"))
1306 ((string-match "%d.*%d" ivy-count-format)
1307 (let ((w (length (number-to-string
1308 (length ivy--all-candidates))))
1309 (s (copy-sequence ivy-count-format)))
1310 (string-match "%d" s)
1312 (string-match "%d" s (match-end 0))
1313 (setq s (replace-match (format "%%-%dd" w) nil nil s))
1314 (string-match "%d" s)
1315 (concat (replace-match (format "%%%dd" w) nil nil s)
1317 ((string-match "%.*d" ivy-count-format)
1318 (concat ivy-count-format prompt))
1323 (setf (ivy-state-initial-input ivy-last) initial-input)))
1326 (defun ivy-completing-read (prompt collection
1327 &optional predicate require-match initial-input
1328 history def inherit-input-method)
1329 "Read a string in the minibuffer, with completion.
1331 This interface conforms to `completing-read' and can be used for
1332 `completing-read-function'.
1334 PROMPT is a string to prompt with; normally it ends in a colon and a space.
1335 COLLECTION can be a list of strings, an alist, an obarray or a hash table.
1336 PREDICATE limits completion to a subset of COLLECTION.
1337 REQUIRE-MATCH is specified with a boolean value. See `completing-read'.
1338 INITIAL-INPUT is a string that can be inserted into the minibuffer initially.
1339 HISTORY is a list of previously selected inputs.
1340 DEF is the default value.
1341 INHERIT-INPUT-METHOD is currently ignored."
1342 (if (memq this-command '(tmm-menubar tmm-shortcut))
1343 (completing-read-default prompt collection
1344 predicate require-match
1345 initial-input history
1346 def inherit-input-method)
1347 ;; See the doc of `completing-read'.
1348 (when (consp history)
1349 (when (numberp (cdr history))
1350 (setq initial-input (nth (1- (cdr history))
1351 (symbol-value (car history)))))
1352 (setq history (car history)))
1353 (ivy-read (replace-regexp-in-string "%" "%%" prompt)
1355 :predicate predicate
1356 :require-match require-match
1357 :initial-input (if (consp initial-input)
1359 (if (and (stringp initial-input)
1360 (string-match "\\+" initial-input))
1361 (replace-regexp-in-string
1362 "\\+" "\\\\+" initial-input)
1364 :preselect (if (listp def) (car def) def)
1368 (let ((sort (assoc this-command ivy-sort-functions-alist)))
1373 (defvar ivy-completion-beg nil
1374 "Completion bounds start.")
1376 (defvar ivy-completion-end nil
1377 "Completion bounds end.")
1379 (defun ivy-completion-in-region-action (str)
1380 "Insert STR, erasing the previous one.
1381 The previous string is between `ivy-completion-beg' and `ivy-completion-end'."
1384 (when ivy-completion-beg
1387 ivy-completion-end))
1388 (setq ivy-completion-beg
1389 (move-marker (make-marker) (point)))
1391 (setq ivy-completion-end
1392 (move-marker (make-marker) (point))))))
1394 (defun ivy-completion-common-length (str)
1395 "Return the length of the first 'completions-common-part face in STR."
1398 (while (and (<= pos len)
1399 (let ((prop (get-text-property pos 'face str)))
1400 (not (eq 'completions-common-part
1401 (if (listp prop) (car prop) prop)))))
1402 (setq pos (1+ pos)))
1404 (or (next-single-property-change pos 'face str) len)
1407 (defun ivy-completion-in-region (start end collection &optional predicate)
1408 "An Ivy function suitable for `completion-in-region-function'."
1409 (let* ((enable-recursive-minibuffers t)
1410 (str (buffer-substring-no-properties start end))
1412 (completion-all-completions str collection predicate (- end start))))
1414 (message "No matches")
1416 (setq ivy-completion-beg (- end (ivy-completion-common-length (car comps))))
1417 (setq ivy-completion-end end)
1418 (if (null (cdr comps))
1419 (if (string= str (car comps))
1420 (message "Sole match")
1421 (setf (ivy-state-window ivy-last) (selected-window))
1422 (ivy-completion-in-region-action
1423 (substring-no-properties
1425 (let* ((w (1+ (floor (log (length comps) 10))))
1426 (ivy-count-format (if (string= ivy-count-format "")
1428 (format "%%-%dd " w)))
1429 (prompt (format "(%s): " str)))
1431 (ivy-read (if (string= ivy-count-format "")
1433 (replace-regexp-in-string "%" "%%" prompt))
1434 ;; remove 'completions-first-difference face
1435 (mapcar #'substring-no-properties comps)
1436 :predicate predicate
1437 :action #'ivy-completion-in-region-action
1442 (define-minor-mode ivy-mode
1443 "Toggle Ivy mode on or off.
1444 Turn Ivy mode on if ARG is positive, off otherwise.
1445 Turning on Ivy mode sets `completing-read-function' to
1446 `ivy-completing-read'.
1451 Minibuffer bindings:
1452 \\{ivy-minibuffer-map}"
1455 :keymap ivy-mode-map
1459 (setq completing-read-function 'ivy-completing-read)
1460 (setq completion-in-region-function 'ivy-completion-in-region))
1461 (setq completing-read-function 'completing-read-default)
1462 (setq completion-in-region-function 'completion--in-region)))
1464 (defun ivy--preselect-index (preselect candidates)
1465 "Return the index of PRESELECT in CANDIDATES."
1466 (cond ((integerp preselect)
1468 ((cl-position preselect candidates :test #'equal))
1469 ((stringp preselect)
1470 (let ((re (regexp-quote preselect)))
1473 (string-match re x))
1478 (defvar ivy--regex-hash
1479 (make-hash-table :test #'equal)
1480 "Store pre-computed regex.")
1482 (defun ivy--split (str)
1483 "Split STR into a list by single spaces.
1484 The remaining spaces stick to their left.
1485 This allows to \"quote\" N spaces by inputting N+1 spaces."
1486 (let ((len (length str))
1491 (while (and (string-match " +" str start1)
1493 (setq match-len (- (match-end 0) (match-beginning 0)))
1497 (setq start1 start0)
1499 (push (substring str start1 (match-beginning 0)) res)
1500 (setq start1 (match-end 0)))
1501 (setq str (replace-match
1502 (make-string (1- match-len) ?\ )
1504 (setq start0 (or start0 start1))
1505 (setq start1 (1- (match-end 0)))))
1507 (push (substring str start0) res)
1508 (setq s (substring str start1))
1509 (unless (= (length s) 0)
1513 (defun ivy--regex (str &optional greedy)
1514 "Re-build regex pattern from STR in case it has a space.
1515 When GREEDY is non-nil, join words in a greedy way."
1516 (let ((hashed (unless greedy
1517 (gethash str ivy--regex-hash))))
1520 (setq ivy--subexps (car hashed)))
1521 (when (string-match "\\([^\\]\\|^\\)\\\\$" str)
1522 (setq str (substring str 0 -1)))
1524 (let ((subs (ivy--split str)))
1525 (if (= (length subs) 1)
1527 (setq ivy--subexps 0)
1530 (setq ivy--subexps (length subs))
1533 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1535 (format "\\(%s\\)" x)))
1540 ivy--regex-hash)))))
1542 (defun ivy--regex-ignore-order--part (str &optional discard)
1543 "Re-build regex from STR by splitting at spaces.
1544 Ignore the order of each group."
1545 (let* ((subs (split-string str " +" t))
1546 (len (length subs)))
1551 (mapcar (lambda (x) (cons x (not discard)))
1554 (defun ivy--regex-ignore-order (str)
1555 "Re-build regex from STR by splitting at spaces.
1556 Ignore the order of each group. Everything before \"!\" should
1557 match. Everything after \"!\" should not match."
1558 (let ((parts (split-string str "!" t)))
1559 (cl-case (length parts)
1563 (if (string= (substring str 0 1) "!")
1565 (ivy--regex-ignore-order--part (car parts) t))
1566 (ivy--regex-ignore-order--part (car parts))))
1569 (ivy--regex-ignore-order--part (car parts))
1570 (ivy--regex-ignore-order--part (cadr parts) t)))
1571 (t (error "Unexpected: use only one !")))))
1573 (defun ivy--regex-plus (str)
1574 "Build a regex sequence from STR.
1575 Spaces are wild card characters, everything before \"!\" should
1576 match. Everything after \"!\" should not match."
1577 (let ((parts (split-string str "!" t)))
1578 (cl-case (length parts)
1582 (if (string= (substring str 0 1) "!")
1584 (list (ivy--regex (car parts))))
1585 (ivy--regex (car parts))))
1588 (cons (ivy--regex (car parts)) t)
1589 (mapcar #'list (split-string (cadr parts) " " t))))
1590 (t (error "Unexpected: use only one !")))))
1592 (defun ivy--regex-fuzzy (str)
1593 "Build a regex sequence from STR.
1594 Insert .* between each char."
1595 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1597 (concat (match-string 1 str)
1600 (format "\\(%c\\)" x))
1601 (string-to-list (match-string 2 str)) ".*")
1602 (match-string 3 str))
1603 (setq ivy--subexps (length (match-string 2 str))))
1607 (defun ivy--minibuffer-setup ()
1608 "Setup ivy completion in the minibuffer."
1609 (set (make-local-variable 'completion-show-inline-help) nil)
1610 (set (make-local-variable 'minibuffer-default-add-function)
1612 (list ivy--default)))
1613 (when (display-graphic-p)
1614 (setq truncate-lines t))
1615 (setq-local max-mini-window-height ivy-height)
1616 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1617 ;; show completions with empty input
1620 (defun ivy--input ()
1621 "Return the current minibuffer input."
1622 ;; assume one-line minibuffer input
1623 (buffer-substring-no-properties
1624 (minibuffer-prompt-end)
1625 (line-end-position)))
1627 (defun ivy--cleanup ()
1628 "Delete the displayed completion candidates."
1630 (goto-char (minibuffer-prompt-end))
1631 (delete-region (line-end-position) (point-max))))
1633 (defun ivy--insert-prompt ()
1634 "Update the prompt according to `ivy--prompt'."
1636 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1637 counsel-find-symbol))
1638 (setq ivy--prompt-extra ""))
1640 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1642 (setq head (match-string 1 ivy--prompt))
1644 (setq head (substring ivy--prompt 0 -1))
1646 (let ((inhibit-read-only t)
1647 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1650 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1651 (> (minibuffer-depth) 1))
1652 (format "[%d] " (minibuffer-depth))
1655 (if (string-match "%d.*%d" ivy-count-format)
1658 (or (and (ivy-state-dynamic-collection ivy-last)
1662 (or (and (ivy-state-dynamic-collection ivy-last)
1667 (d-str (if ivy--directory
1668 (abbreviate-file-name ivy--directory)
1671 (goto-char (point-min))
1672 (delete-region (point-min) (minibuffer-prompt-end))
1673 (if (> (+ (mod (+ (length n-str) (length d-str)) (window-width))
1676 (setq n-str (concat n-str "\n" d-str))
1677 (setq n-str (concat n-str d-str)))
1678 (let ((regex (format "\\([^\n]\\{%d\\}\\)[^\n]" (window-width))))
1679 (while (string-match regex n-str)
1680 (setq n-str (replace-match (concat (match-string 1 n-str) "\n") nil t n-str 1))))
1681 (set-text-properties 0 (length n-str)
1682 `(face minibuffer-prompt ,@std-props)
1684 (ivy--set-match-props n-str "confirm"
1685 `(face ivy-confirm-face ,@std-props))
1686 (ivy--set-match-props n-str "match required"
1687 `(face ivy-match-required-face ,@std-props))
1689 ;; get out of the prompt area
1690 (constrain-to-field nil (point-max))))))
1692 (defun ivy--set-match-props (str match props)
1693 "Set STR text properties that match MATCH to PROPS."
1694 (when (string-match match str)
1695 (set-text-properties
1701 (defvar inhibit-message)
1703 (defun ivy--sort-maybe (collection)
1704 "Sort COLLECTION if needed."
1705 (let ((sort (ivy-state-sort ivy-last))
1709 (let ((sort-fn (cond ((functionp sort)
1711 ((setq entry (assoc (ivy-state-collection ivy-last)
1712 ivy-sort-functions-alist))
1715 (cdr (assoc t ivy-sort-functions-alist))))))
1716 (if (functionp sort-fn)
1717 (cl-sort (copy-sequence collection) sort-fn)
1720 (defun ivy--exhibit ()
1721 "Insert Ivy completions display.
1722 Should be run via minibuffer `post-command-hook'."
1723 (when (memq 'ivy--exhibit post-command-hook)
1724 (let ((inhibit-field-text-motion nil))
1725 (constrain-to-field nil (point-max)))
1726 (setq ivy-text (ivy--input))
1727 (if (ivy-state-dynamic-collection ivy-last)
1728 ;; while-no-input would cause annoying
1729 ;; "Waiting for process to die...done" message interruptions
1730 (let ((inhibit-message t))
1731 (unless (equal ivy--old-text ivy-text)
1733 (setq ivy--all-candidates
1735 (funcall (ivy-state-collection ivy-last) ivy-text)))
1736 (setq ivy--old-text ivy-text)))
1737 (when ivy--all-candidates
1738 (ivy--insert-minibuffer
1739 (ivy--format ivy--all-candidates))))
1740 (cond (ivy--directory
1741 (if (string-match "/\\'" ivy-text)
1742 (if (member ivy-text ivy--all-candidates)
1743 (ivy--cd (expand-file-name ivy-text ivy--directory))
1744 (when (string-match "//\\'" ivy-text)
1745 (if (and default-directory
1746 (string-match "\\`[[:alpha:]]:/" default-directory))
1747 (ivy--cd (match-string 0 default-directory))
1749 (when (string-match "[[:alpha:]]:/$" ivy-text)
1750 (let ((drive-root (match-string 0 ivy-text)))
1751 (when (file-exists-p drive-root)
1752 (ivy--cd drive-root)))))
1753 (if (string-match "\\`~\\'" ivy-text)
1754 (ivy--cd (expand-file-name "~/")))))
1755 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1756 (when (or (and (string-match "\\` " ivy-text)
1757 (not (string-match "\\` " ivy--old-text)))
1758 (and (string-match "\\` " ivy--old-text)
1759 (not (string-match "\\` " ivy-text))))
1760 (setq ivy--all-candidates
1761 (if (and (> (length ivy-text) 0)
1762 (eq (aref ivy-text 0)
1764 (ivy--buffer-list " ")
1765 (ivy--buffer-list "" ivy-use-virtual-buffers)))
1766 (setq ivy--old-re nil))))
1767 (ivy--insert-minibuffer
1768 (with-current-buffer (ivy-state-buffer ivy-last)
1770 (ivy--filter ivy-text ivy--all-candidates))))
1771 (setq ivy--old-text ivy-text))))
1773 (defun ivy--insert-minibuffer (text)
1774 "Insert TEXT into minibuffer with appropriate cleanup."
1775 (let ((resize-mini-windows nil)
1776 (update-fn (ivy-state-update-fn ivy-last))
1780 (funcall update-fn))
1781 (ivy--insert-prompt)
1782 ;; Do nothing if while-no-input was aborted.
1783 (when (stringp text)
1784 (let ((buffer-undo-list t))
1788 (when (display-graphic-p)
1789 (ivy--resize-minibuffer-to-fit))))
1791 (defun ivy--resize-minibuffer-to-fit ()
1792 "Resize the minibuffer window size to fit the text in the minibuffer."
1793 (with-selected-window (minibuffer-window)
1794 (if (fboundp 'window-text-pixel-size)
1795 (let ((text-height (cdr (window-text-pixel-size)))
1796 (body-height (window-body-height nil t)))
1797 (when (> text-height body-height)
1798 ;; Note: the size increment needs to be at least frame-char-height,
1799 ;; otherwise resizing won't do anything.
1800 (let ((delta (max (- text-height body-height) (frame-char-height))))
1801 (window-resize nil delta nil t t))))
1802 (let ((text-height (count-screen-lines))
1803 (body-height (window-body-height)))
1804 (when (> text-height body-height)
1805 (window-resize nil (- text-height body-height) nil t))))))
1807 (declare-function colir-blend-face-background "ext:colir")
1809 (defun ivy--add-face (str face)
1810 "Propertize STR with FACE.
1811 `font-lock-append-text-property' is used, since it's better than
1812 `propertize' or `add-face-text-property' in this case."
1816 (colir-blend-face-background 0 (length str) face str)
1817 (let ((foreground (face-foreground face)))
1819 (add-face-text-property
1821 `(:foreground ,foreground)
1826 (font-lock-append-text-property 0 (length str) 'face face str))))
1829 (declare-function flx-make-string-cache "ext:flx")
1830 (declare-function flx-score "ext:flx")
1832 (defvar ivy--flx-cache nil)
1834 (eval-after-load 'flx
1835 '(setq ivy--flx-cache (flx-make-string-cache)))
1837 (defun ivy-toggle-case-fold ()
1838 "Toggle the case folding between nil and auto.
1839 In any completion session, the case folding starts in auto:
1841 - when the input is all lower case, `case-fold-search' is t
1844 You can toggle this to make `case-fold-search' nil regardless of input."
1846 (setq ivy-case-fold-search
1847 (if ivy-case-fold-search
1850 ;; reset cache so that the candidate list updates
1851 (setq ivy--old-re nil))
1853 (defun ivy--re-filter (re candidates)
1854 "Return all RE matching CANDIDATES.
1855 RE is a list of cons cells, with a regexp car and a boolean cdr.
1856 When the cdr is t, the car must match.
1857 Otherwise, the car must not match."
1858 (let ((re-list (if (stringp re) (list (cons re t)) re))
1860 (dolist (re re-list)
1867 (let ((re-str (car re)))
1868 (lambda (x) (string-match re-str x)))
1872 (defun ivy--filter (name candidates)
1873 "Return all items that match NAME in CANDIDATES.
1874 CANDIDATES are assumed to be static."
1875 (let ((re (funcall ivy--regex-function name)))
1876 (if (and (equal re ivy--old-re)
1878 ;; quick caching for "C-n", "C-p" etc.
1880 (let* ((re-str (if (listp re) (caar re) re))
1881 (matcher (ivy-state-matcher ivy-last))
1883 (and ivy-case-fold-search
1884 (string= name (downcase name))))
1887 (funcall matcher re candidates))
1890 (stringp ivy--old-re)
1891 (not (string-match "\\\\" ivy--old-re))
1892 (not (equal ivy--old-re ""))
1894 (if (string-match "\\\\)\\'" ivy--old-re)
1895 (substring ivy--old-re 0 -2)
1901 (lambda (x) (string-match re x))
1904 (ivy--re-filter re candidates)))))
1905 (ivy--recompute-index name re-str cands)
1907 (if (eq ivy--regex-function 'ivy--regex-ignore-order)
1912 (setq ivy--old-cands (ivy--sort name cands))))))
1914 (defcustom ivy-sort-matches-functions-alist '((t . nil))
1915 "An alist of functions used to sort the matching candidates.
1917 This is different from `ivy-sort-functions-alist', which is used
1918 to sort the whole collection only once. The functions taken from
1919 here are instead used on each input change, but they are used
1920 only on already matching candidates, not on all of them.
1922 The alist KEY is a collection function or t to match previously
1923 not matched collection functions.
1925 The alist VAL is a sorting function with the signature of
1926 `ivy--prefix-sort'.")
1928 (defun ivy--sort-files-by-date (_name candidates)
1929 "Re-soft CANDIDATES according to file modification date."
1930 (let ((default-directory ivy--directory))
1931 (cl-sort (copy-sequence candidates)
1934 (nth 5 (file-attributes f2))
1935 (nth 5 (file-attributes f1)))))))
1937 (defun ivy--sort (name candidates)
1938 "Re-sort CANDIDATES by NAME.
1939 All CANDIDATES are assumed to match NAME."
1940 (let ((key (or (ivy-state-caller ivy-last)
1941 (when (functionp (ivy-state-collection ivy-last))
1942 (ivy-state-collection ivy-last))))
1944 (cond ((and (require 'flx nil 'noerror)
1945 (eq ivy--regex-function 'ivy--regex-fuzzy))
1946 (ivy--flx-sort name candidates))
1947 ((setq fun (cdr (or (assoc key ivy-sort-matches-functions-alist)
1948 (assoc t ivy-sort-matches-functions-alist))))
1949 (funcall fun name candidates))
1953 (defun ivy--prefix-sort (name candidates)
1954 "Re-sort CANDIDATES.
1955 Prefix matches to NAME are put ahead of the list."
1956 (if (or (string-match "^\\^" name) (string= name ""))
1958 (let ((re-prefix (concat "^" (funcall ivy--regex-function name)))
1961 (dolist (s candidates)
1962 (if (string-match re-prefix s)
1964 (push s res-noprefix)))
1966 (nreverse res-prefix)
1967 (nreverse res-noprefix)))))
1969 (defun ivy--recompute-index (name re-str cands)
1970 (let* ((caller (ivy-state-caller ivy-last))
1971 (func (or (and caller (cdr (assoc caller ivy-index-functions-alist)))
1972 (cdr (assoc t ivy-index-functions-alist))
1973 #'ivy-recompute-index-zero)))
1974 (unless (eq this-command 'ivy-resume)
1977 (cl-position (if (and (> (length name) 0)
1978 (eq ?^ (aref name 0)))
1984 (concat re-str "/") cands
1986 (and (not (string= name ""))
1987 (not (and (require 'flx nil 'noerror)
1988 (eq ivy--regex-function 'ivy--regex-fuzzy)
1989 (< (length cands) 200)))
1991 (cl-position (nth ivy--index ivy--old-cands)
1993 (funcall func re-str cands))))
1994 (when (and (or (string= name "")
1996 (not (equal ivy--old-re "")))
1998 (or (ivy--preselect-index
1999 (ivy-state-preselect ivy-last)
2003 (defun ivy-recompute-index-swiper (_re-str cands)
2004 (let ((tail (nthcdr ivy--index ivy--old-cands))
2006 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2008 (while (and tail (null idx))
2009 ;; Compare with eq to handle equal duplicates in cands
2010 (setq idx (cl-position (pop tail) cands)))
2013 (1- (length cands))))
2016 ;; already in ivy-state-buffer
2017 (let ((n (line-number-at-pos))
2021 (when (eq n (read (get-text-property 0 'display c)))
2026 (defun ivy-recompute-index-swiper-async (_re-str cands)
2027 (let ((tail (nthcdr ivy--index ivy--old-cands))
2029 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2031 (while (and tail (null idx))
2032 ;; Compare with `equal', since the collection is re-created
2033 ;; each time with `split-string'
2034 (setq idx (cl-position (pop tail) cands :test #'equal)))
2038 (defun ivy-recompute-index-zero (_re-str _cands)
2041 (defcustom ivy-minibuffer-faces
2042 '(ivy-minibuffer-match-face-1
2043 ivy-minibuffer-match-face-2
2044 ivy-minibuffer-match-face-3
2045 ivy-minibuffer-match-face-4)
2046 "List of `ivy' faces for minibuffer group matches.")
2048 (defvar ivy-flx-limit 200
2049 "Used to conditionally turn off flx sorting.
2050 When the amount of matching candidates is larger than this
2051 number, no sorting will be done.")
2053 (defun ivy--flx-sort (name cands)
2054 "Sort according to closeness to string NAME the string list CANDS."
2057 (< (length cands) ivy-flx-limit))
2058 (let* ((flx-name (if (string-match "^\\^" name)
2065 (let ((score (flx-score x flx-name ivy--flx-cache)))
2069 (if cands-with-score
2071 (let ((str (copy-sequence (cdr x)))
2074 (dolist (j (cdar x))
2075 (unless (eq j (1+ last-j))
2078 (ivy-add-face-text-property
2080 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2081 ivy-minibuffer-faces)
2084 (sort cands-with-score
2086 (> (caar x) (caar y)))))
2092 (defcustom ivy-format-function 'ivy-format-function-default
2093 "Function to transform the list of candidates into a string.
2094 This string is inserted into the minibuffer."
2096 (const :tag "Default" ivy-format-function-default)
2097 (const :tag "Arrow prefix" ivy-format-function-arrow)
2098 (const :tag "Full line" ivy-format-function-line)))
2100 (defun ivy--truncate-string (str width)
2101 "Truncate STR to WIDTH."
2102 (if (> (string-width str) width)
2103 (concat (substring str 0 (min (- width 3)
2104 (- (length str) 3))) "...")
2107 (defun ivy--format-function-generic (selected-fn other-fn cand-pairs separator)
2108 "Transform CAND-PAIRS into a string for minibuffer.
2109 SELECTED-FN and OTHER-FN each take two string arguments.
2110 SEPARATOR is used to join the candidates."
2114 (let ((str (car pair))
2116 (curr (eq (cl-incf i) ivy--index)))
2118 (funcall selected-fn str extra)
2119 (funcall other-fn str extra))))
2123 (defun ivy-format-function-default (cand-pairs)
2124 "Transform CAND-PAIRS into a string for minibuffer."
2125 (ivy--format-function-generic
2127 (concat (ivy--add-face str 'ivy-current-match) extra))
2132 (defun ivy-format-function-arrow (cand-pairs)
2133 "Transform CAND-PAIRS into a string for minibuffer."
2134 (ivy--format-function-generic
2136 (concat "> " (ivy--add-face str 'ivy-current-match) extra))
2138 (concat " " str extra))
2142 (defun ivy-format-function-line (cand-pairs)
2143 "Transform CAND-PAIRS into a string for minibuffer."
2144 (ivy--format-function-generic
2146 (ivy--add-face (concat str extra "\n") 'ivy-current-match))
2148 (concat str extra "\n"))
2152 (defun ivy-add-face-text-property (start end face str)
2153 (if (fboundp 'add-face-text-property)
2154 (add-face-text-property
2155 start end face nil str)
2156 (font-lock-append-text-property
2157 start end 'face face str)))
2159 (defun ivy--format-minibuffer-line (str)
2161 (str (copy-sequence str)))
2162 (cond ((eq ivy--regex-function 'ivy--regex-ignore-order)
2163 (when (consp ivy--old-re)
2165 (dolist (re ivy--old-re)
2166 (when (string-match (car re) str)
2167 (ivy-add-face-text-property
2168 (match-beginning 0) (match-end 0)
2169 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2170 ivy-minibuffer-faces)
2173 ((and (eq ivy-display-style 'fancy)
2174 (not (eq ivy--regex-function 'ivy--regex-fuzzy)))
2176 (setq ivy--old-re (funcall ivy--regex-function ivy-text)))
2177 (while (and (string-match ivy--old-re str start)
2178 (> (- (match-end 0) (match-beginning 0)) 0))
2179 (setq start (match-end 0))
2181 (while (<= i ivy--subexps)
2183 (cond ((zerop ivy--subexps)
2184 (cadr ivy-minibuffer-faces))
2186 (car ivy-minibuffer-faces))
2188 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2189 ivy-minibuffer-faces)))))
2190 (ivy-add-face-text-property
2191 (match-beginning i) (match-end i)
2196 (defun ivy--format (cands)
2197 "Return a string for CANDS suitable for display in the minibuffer.
2198 CANDS is a list of strings."
2199 (setq ivy--length (length cands))
2200 (when (>= ivy--index ivy--length)
2201 (setq ivy--index (max (1- ivy--length) 0)))
2203 (setq ivy--current "")
2204 (let* ((half-height (/ ivy-height 2))
2205 (start (max 0 (- ivy--index half-height)))
2206 (end (min (+ start (1- ivy-height)) ivy--length))
2207 (start (max 0 (min start (- end (1- ivy-height)))))
2208 (cands (cl-subseq cands start end))
2209 (index (- ivy--index start)))
2210 (cond (ivy--directory
2211 (setq cands (mapcar (lambda (x)
2212 (if (string-match-p "/\\'" x)
2213 (propertize x 'face 'ivy-subdir)
2216 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
2217 (setq cands (mapcar (lambda (x)
2218 (let ((b (get-buffer x)))
2220 (buffer-file-name b)
2221 (buffer-modified-p b))
2222 (propertize x 'face 'ivy-modified-buffer)
2225 (setq ivy--current (copy-sequence (nth index cands)))
2226 (let* ((ivy--index index)
2229 (cons (ivy--format-minibuffer-line cand) nil)) cands))
2230 (res (concat "\n" (funcall ivy-format-function cand-pairs))))
2231 (put-text-property 0 (length res) 'read-only nil res)
2234 (defvar ivy--virtual-buffers nil
2235 "Store the virtual buffers alist.")
2237 (defvar recentf-list)
2239 (defcustom ivy-virtual-abbreviate 'name
2240 "The mode of abbreviation for virtual buffer names."
2242 (const :tag "Only name" name)
2243 (const :tag "Full path" full)
2244 ;; eventually, uniquify
2247 (defun ivy--virtual-buffers ()
2248 "Adapted from `ido-add-virtual-buffers-to-list'."
2249 (unless recentf-mode
2251 (let ((bookmarks (and (boundp 'bookmark-alist)
2253 virtual-buffers name)
2254 (dolist (head (append
2256 (delete " - no file -"
2257 (delq nil (mapcar (lambda (bookmark)
2258 (cdr (assoc 'filename bookmark)))
2261 (if (eq ivy-virtual-abbreviate 'name)
2262 (file-name-nondirectory head)
2263 (expand-file-name head)))
2264 (when (equal name "")
2265 (setq name (file-name-nondirectory (directory-file-name head))))
2266 (when (equal name "")
2268 (and (not (equal name ""))
2269 (null (get-file-buffer head))
2270 (not (assoc name virtual-buffers))
2271 (push (cons name head) virtual-buffers)))
2272 (when virtual-buffers
2273 (dolist (comp virtual-buffers)
2274 (put-text-property 0 (length (car comp))
2277 (setq ivy--virtual-buffers (nreverse virtual-buffers))
2278 (mapcar #'car ivy--virtual-buffers))))
2280 (defun ivy--buffer-list (str &optional virtual)
2281 "Return the buffers that match STR.
2282 When VIRTUAL is non-nil, add virtual buffers."
2287 (if (with-current-buffer x
2289 (abbreviate-file-name default-directory)))
2290 (propertize x 'face 'ivy-remote)
2292 (all-completions str 'internal-complete-buffer))
2294 (ivy--virtual-buffers)))))
2296 (defun ivy--switch-buffer-action (buffer)
2298 BUFFER may be a string or nil."
2300 (if (zerop (length buffer))
2302 ivy-text nil 'force-same-window)
2303 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2305 (not (get-buffer buffer)))
2306 (find-file (cdr virtual))
2308 buffer nil 'force-same-window))))))
2310 (defun ivy--switch-buffer-other-window-action (buffer)
2311 "Switch to BUFFER in other window.
2312 BUFFER may be a string or nil."
2313 (if (zerop (length buffer))
2314 (switch-to-buffer-other-window ivy-text)
2315 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2317 (not (get-buffer buffer)))
2318 (find-file-other-window (cdr virtual))
2319 (switch-to-buffer-other-window buffer)))))
2321 (defun ivy--rename-buffer-action (buffer)
2323 (let ((new-name (read-string "Rename buffer (to new name): ")))
2324 (with-current-buffer buffer
2325 (rename-buffer new-name))))
2327 (defvar ivy-switch-buffer-map (make-sparse-keymap))
2334 (ivy--reset-state ivy-last))
2337 ivy--switch-buffer-other-window-action
2340 ivy--rename-buffer-action
2344 (defun ivy-switch-buffer ()
2345 "Switch to another buffer."
2348 (call-interactively 'switch-to-buffer)
2349 (let ((this-command 'ivy-switch-buffer))
2350 (ivy-read "Switch to buffer: " 'internal-complete-buffer
2351 :preselect (buffer-name (other-buffer (current-buffer)))
2352 :action #'ivy--switch-buffer-action
2353 :keymap ivy-switch-buffer-map))))
2356 (defun ivy-recentf ()
2357 "Find a file on `recentf-list'."
2359 (ivy-read "Recentf: " recentf-list
2365 (defun ivy-yank-word ()
2366 "Pull next word from buffer into search string."
2371 (le (line-end-position)))
2375 (setq amend (buffer-substring-no-properties pt (point))))))
2377 (insert (replace-regexp-in-string " +" " " amend)))))
2379 (defun ivy-kill-ring-save ()
2380 "Store the current candidates into the kill ring.
2381 If the region is active, forward to `kill-ring-save' instead."
2383 (if (region-active-p)
2384 (call-interactively 'kill-ring-save)
2391 (defun ivy-insert-current ()
2392 "Make the current candidate into current input.
2393 Don't finish completion."
2395 (delete-minibuffer-contents)
2396 (if (and ivy--directory
2397 (string-match "/$" ivy--current))
2398 (insert (substring ivy--current 0 -1))
2399 (insert ivy--current)))
2401 (defun ivy-toggle-fuzzy ()
2402 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
2404 (setq ivy--old-re nil)
2405 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
2406 (setq ivy--regex-function 'ivy--regex-plus)
2407 (setq ivy--regex-function 'ivy--regex-fuzzy)))
2409 (defun ivy-reverse-i-search ()
2410 "Enter a recursive `ivy-read' session using the current history.
2411 The selected history element will be inserted into the minibuffer."
2413 (let ((enable-recursive-minibuffers t)
2414 (history (symbol-value (ivy-state-history ivy-last)))
2416 (ivy-recursive-restore nil))
2417 (ivy-read "Reverse-i-search: "
2421 (setq ivy-last old-last))
2422 (delete-minibuffer-contents)
2423 (insert (substring-no-properties x))
2426 (defun ivy-restrict-to-matches ()
2427 "Restrict candidates to current matches and erase input."
2429 (delete-minibuffer-contents)
2430 (setq ivy--all-candidates
2431 (ivy--filter ivy-text ivy--all-candidates)))
2434 (defvar-local ivy-occur-last nil
2435 "Buffer-local value of `ivy-last'.
2436 Can't re-use `ivy-last' because using e.g. `swiper' in the same
2437 buffer would modify `ivy-last'.")
2439 (defvar ivy-occur-mode-map
2440 (let ((map (make-sparse-keymap)))
2441 (define-key map [mouse-1] 'ivy-occur-click)
2442 (define-key map (kbd "RET") 'ivy-occur-press)
2443 (define-key map (kbd "j") 'next-line)
2444 (define-key map (kbd "k") 'previous-line)
2445 (define-key map (kbd "h") 'backward-char)
2446 (define-key map (kbd "l") 'forward-char)
2447 (define-key map (kbd "g") 'ivy-occur-press)
2448 (define-key map (kbd "a") 'ivy-occur-read-action)
2449 (define-key map (kbd "o") 'ivy-occur-dispatch)
2450 (define-key map (kbd "q") 'quit-window)
2452 "Keymap for Ivy Occur mode.")
2454 (define-derived-mode ivy-occur-mode fundamental-mode "Ivy-Occur"
2455 "Major mode for output from \\[ivy-occur].
2457 \\{ivy-occur-mode-map}")
2459 (defvar ivy-occur-grep-mode-map
2460 (let ((map (copy-keymap ivy-occur-mode-map)))
2461 (define-key map (kbd "C-x C-q") 'ivy-wgrep-change-to-wgrep-mode)
2463 "Keymap for Ivy Occur Grep mode.")
2465 (define-derived-mode ivy-occur-grep-mode grep-mode "Ivy-Occur"
2466 "Major mode for output from \\[ivy-occur].
2468 \\{ivy-occur-grep-mode-map}")
2470 (defvar counsel-git-grep-cmd)
2473 "Stop completion and put the current matches into a new buffer.
2475 The new buffer remembers current action(s).
2477 While in the *ivy-occur* buffer, selecting a candidate with RET or
2478 a mouse click will call the appropriate action for that candidate.
2480 There is no limit on the number of *ivy-occur* buffers."
2483 (generate-new-buffer
2484 (format "*ivy-occur%s \"%s\"*"
2486 (if (setq caller (ivy-state-caller ivy-last))
2487 (concat " " (prin1-to-string caller))
2490 (do-grep (eq (ivy-state-caller ivy-last) 'counsel-git-grep)))
2491 (with-current-buffer buffer
2494 (setq ivy--old-cands
2496 (shell-command-to-string
2497 (format counsel-git-grep-cmd
2498 (if (stringp ivy--old-re)
2500 (caar ivy--old-re))))
2503 (ivy-occur-grep-mode))
2505 (setf (ivy-state-text ivy-last) ivy-text)
2506 (setq ivy-occur-last ivy-last)
2507 (setq-local ivy--directory ivy--directory)
2508 (let ((inhibit-read-only t))
2511 ;; Need precise number of header lines for `wgrep' to work.
2512 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
2513 default-directory)))
2514 (insert (format "%d candidates:\n" (length ivy--old-cands)))
2515 (dolist (cand ivy--old-cands)
2516 (let ((str (if do-grep
2518 (concat " " cand))))
2519 (add-text-properties
2523 help-echo "mouse-1: call ivy-action")
2525 (insert str "\n")))))
2526 (ivy-exit-with-action
2527 `(lambda (_) (pop-to-buffer ,buffer)))))
2529 (declare-function wgrep-change-to-wgrep-mode "ext:wgrep")
2531 (defun ivy-wgrep-change-to-wgrep-mode ()
2532 "Forward to `wgrep-change-to-wgrep-mode'."
2534 (if (require 'wgrep nil 'noerror)
2535 (wgrep-change-to-wgrep-mode)
2536 (error "Package wgrep isn't installed")))
2538 (defun ivy-occur-read-action ()
2539 "Select one of the available actions as the current one."
2541 (let ((ivy-last ivy-occur-last))
2544 (defun ivy-occur-dispatch ()
2545 "Call one of the available actions on the current item."
2547 (let* ((state-action (ivy-state-action ivy-occur-last))
2548 (actions (if (symbolp state-action)
2550 (copy-sequence state-action))))
2553 (ivy-occur-read-action)
2555 (setf (ivy-state-action ivy-occur-last) actions))))
2557 (defun ivy-occur-click (event)
2558 "Execute action for the current candidate.
2559 EVENT gives the mouse position."
2561 (let ((window (posn-window (event-end event)))
2562 (pos (posn-point (event-end event))))
2563 (with-current-buffer (window-buffer window)
2565 (ivy-occur-press))))
2567 (declare-function swiper--cleanup "swiper")
2568 (declare-function swiper--add-overlays "swiper")
2570 (defun ivy-occur-press ()
2571 "Execute action for the current candidate."
2574 (when (save-excursion
2576 (looking-at "\\(?:./\\| \\)\\(.*\\)$"))
2577 (let* ((ivy-last ivy-occur-last)
2578 (ivy-text (ivy-state-text ivy-last))
2579 (str (buffer-substring
2582 (coll (ivy-state-collection ivy-last))
2583 (action (ivy--get-action ivy-last))
2587 (if (and (consp coll)
2589 (cdr (assoc str coll))
2591 (if (memq (ivy-state-caller ivy-last)
2592 '(swiper counsel-git-grep))
2593 (with-current-buffer (window-buffer (selected-window))
2595 (swiper--add-overlays
2596 (ivy--regex ivy-text)
2597 (line-beginning-position)
2600 (run-at-time 0.5 nil 'swiper--cleanup))
2601 (pulse-momentary-highlight-one-line (point)))))))
2605 ;;; ivy.el ends here