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]
220 (define-key map [remap switch-to-buffer-other-window]
221 'ivy-switch-buffer-other-window)
223 "Keymap for `ivy-mode'.")
226 (cl-defstruct ivy-state
228 predicate require-match initial-input
229 history preselect keymap update-fn sort
230 ;; The window in which `ivy-read' was called
232 ;; The buffer in which `ivy-read' was called
234 ;; The value of `ivy-text' to be used by `ivy-occur'
240 ;; When this is non-nil, call it for each input change to get new candidates
244 (defvar ivy-last (make-ivy-state)
245 "The last parameters passed to `ivy-read'.
247 This should eventually become a stack so that you could use
248 `ivy-read' recursively.")
250 (defsubst ivy-set-action (action)
251 (setf (ivy-state-action ivy-last) action))
253 (defvar ivy-history nil
254 "History list of candidates entered in the minibuffer.
256 Maximum length of the history list is determined by the value
257 of `history-length'.")
259 (defvar ivy--directory nil
260 "Current directory when completing file names.")
262 (defvar ivy--length 0
263 "Store the amount of viable candidates.")
266 "Store the user's string as it is typed in.")
268 (defvar ivy--current ""
269 "Current candidate.")
272 "Store the index of the current candidate.")
275 "Store 'done if the completion was successfully selected.
276 Otherwise, store nil.")
278 (defvar ivy--all-candidates nil
279 "Store the candidates passed to `ivy-read'.")
281 (defvar ivy--default nil
282 "Default initial input.")
284 (defvar ivy--prompt nil
285 "Store the format-style prompt.
286 When non-nil, it should contain at least one %d.")
288 (defvar ivy--prompt-extra ""
289 "Temporary modifications to the prompt.")
291 (defvar ivy--old-re nil
292 "Store the old regexp.")
294 (defvar ivy--old-cands nil
295 "Store the candidates matched by `ivy--old-re'.")
297 (defvar ivy--regex-function 'ivy--regex
298 "Current function for building a regex.")
300 (defvar ivy--subexps 0
301 "Number of groups in the current `ivy--regex'.")
303 (defvar ivy--full-length nil
304 "When :dynamic-collection is non-nil, this can be the total amount of candidates.")
306 (defvar ivy--old-text ""
307 "Store old `ivy-text' for dynamic completion.")
309 (defvar ivy-case-fold-search 'auto
310 "Store the current overriding `case-fold-search'.")
312 (defvar Info-current-file)
314 (defmacro ivy-quit-and-run (&rest body)
315 "Quit the minibuffer and run BODY afterwards."
317 (put 'quit 'error-message "")
320 (put 'quit 'error-message "Quit")
322 (minibuffer-keyboard-quit)))
324 (defun ivy-exit-with-action (action)
325 "Quit the minibuffer and call ACTION afterwards."
329 (ivy-set-action ',(ivy-state-action ivy-last))))
330 (setq ivy-exit 'done)
333 (defmacro with-ivy-window (&rest body)
334 "Execute BODY in the window from which `ivy-read' was called."
337 `(with-selected-window (ivy--get-window ivy-last)
340 (defun ivy--done (text)
341 "Insert TEXT and exit minibuffer."
342 (if (and ivy--directory
343 (not (eq (ivy-state-history ivy-last) 'grep-files-history)))
344 (insert (setq ivy--current (expand-file-name
345 text ivy--directory)))
346 (insert (setq ivy--current text)))
347 (setq ivy-exit 'done)
352 "Exit the minibuffer with the selected candidate."
354 (delete-minibuffer-contents)
355 (cond ((> ivy--length 0)
356 (ivy--done ivy--current))
357 ((memq (ivy-state-collection ivy-last)
358 '(read-file-name-internal internal-complete-buffer))
359 (if (or (not (eq confirm-nonexistent-file-or-buffer t))
360 (equal " (confirm)" ivy--prompt-extra))
362 (setq ivy--prompt-extra " (confirm)")
365 ((memq (ivy-state-require-match ivy-last)
366 '(nil confirm confirm-after-completion))
367 (ivy--done ivy-text))
369 (setq ivy--prompt-extra " (match required)")
373 (defun ivy-read-action ()
374 "Change the action to one of the available ones."
376 (let ((actions (ivy-state-action ivy-last)))
377 (unless (null (ivy--actionp actions))
378 (let* ((hint (concat (if (eq this-command 'ivy-read-action)
387 'face 'font-lock-builtin-face)
392 (key (string (read-key hint)))
393 (action-idx (cl-position-if
394 (lambda (x) (equal (car x) key))
396 (cond ((string= key "
\a"))
398 (error "%s is not bound" key))
401 (setcar actions (1+ action-idx))
402 (ivy-set-action actions)))))))
404 (defun ivy-dispatching-done ()
405 "Select one of the available actions and call `ivy-done'."
410 (defun ivy-dispatching-call ()
411 "Select one of the available actions and call `ivy-call'."
413 (let ((actions (copy-sequence (ivy-state-action ivy-last))))
415 (when (ivy-read-action)
417 (ivy-set-action actions))))
419 (defun ivy-build-tramp-name (x)
420 "Reconstruct X into a path.
421 Is is a cons cell, related to `tramp-get-completion-function'."
425 (concat user "@" domain)
428 (declare-function tramp-get-completion-function "tramp")
429 (declare-function Info-find-node "info")
431 (defun ivy-alt-done (&optional arg)
432 "Exit the minibuffer with the selected candidate.
433 When ARG is t, exit with current text, ignoring the candidates."
436 (ivy-immediate-done))
438 (ivy--directory-done))
439 ((eq (ivy-state-collection ivy-last) 'Info-read-node-name-1)
440 (if (or (equal ivy--current "(./)")
441 (equal ivy--current "(../)"))
443 (ivy-read "Go to file: " 'read-file-name-internal
446 (expand-file-name x ivy--directory)
452 (defun ivy--directory-done ()
453 "Handle exit from the minibuffer when completing file names."
456 ((equal ivy-text "/sudo::")
457 (setq dir (concat ivy-text ivy--directory))
462 (not (equal ivy-text ""))
466 (file-name-as-directory
468 ivy-text ivy--directory))))))
470 (not (string= ivy--current "./"))
471 (cl-plusp ivy--length)
474 (setq dir (file-name-as-directory
476 ivy--current ivy--directory)))))))
479 ((or (and (equal ivy--directory "/")
480 (string-match "\\`[^/]+:.*:.*\\'" ivy-text))
481 (string-match "\\`/[^/]+:.*:.*\\'" ivy-text))
483 ((or (and (equal ivy--directory "/")
485 "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
488 "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
490 (setq ivy-text ivy--current))))
492 "\\`/\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
494 (let ((method (match-string 1 ivy-text))
495 (user (match-string 2 ivy-text))
496 (rest (match-string 3 ivy-text))
499 (dolist (x (tramp-get-completion-function method))
500 (setq res (append res (funcall (car x) (cadr x)))))
501 (setq res (delq nil res))
505 (setq res (cl-delete-duplicates res :test #'equal))
506 (let* ((old-ivy-last ivy-last)
507 (enable-recursive-minibuffers t)
508 (host (ivy-read "user@host: "
509 (mapcar #'ivy-build-tramp-name res)
510 :initial-input rest)))
511 (setq ivy-last old-ivy-last)
513 (setq ivy--directory "/")
514 (ivy--cd (concat "/" method ":" host ":"))))))
518 (defcustom ivy-tab-space nil
519 "When non-nil, `ivy-partial-or-done' should insert a space."
522 (defun ivy-partial-or-done ()
523 "Complete the minibuffer text as much as possible.
524 If the text hasn't changed as a result, forward to `ivy-alt-done'."
526 (if (and (eq (ivy-state-collection ivy-last) #'read-file-name-internal)
527 (or (and (equal ivy--directory "/")
528 (string-match "\\`[^/]+:.*\\'" ivy-text))
529 (string-match "\\`/" ivy-text)))
530 (let ((default-directory ivy--directory))
531 (minibuffer-complete)
532 (setq ivy-text (ivy--input))
533 (when (file-directory-p
534 (expand-file-name ivy-text ivy--directory))
535 (ivy--cd (file-name-as-directory
536 (expand-file-name ivy-text ivy--directory)))))
538 (when (or (eq this-command last-command)
542 (defun ivy-partial ()
543 "Complete the minibuffer text as much as possible."
545 (let* ((parts (or (split-string ivy-text " " t) (list "")))
546 (postfix (car (last parts)))
547 (completion-ignore-case t)
548 (startp (string-match "^\\^" postfix))
549 (new (try-completion (if startp
550 (substring postfix 1)
552 (mapcar (lambda (str)
553 (let ((i (string-match postfix str)))
557 (cond ((eq new t) nil)
558 ((string= new ivy-text) nil)
560 (delete-region (minibuffer-prompt-end) (point-max))
565 (insert (mapconcat #'identity parts " ")
566 (if ivy-tab-space " " ""))
569 (defun ivy-immediate-done ()
570 "Exit the minibuffer with the current input."
572 (delete-minibuffer-contents)
573 (insert (setq ivy--current
575 (expand-file-name ivy-text ivy--directory)
577 (setq ivy-exit 'done)
582 "Resume the last completion session."
584 (when (eq (ivy-state-caller ivy-last) 'swiper)
585 (switch-to-buffer (ivy-state-buffer ivy-last)))
586 (with-current-buffer (ivy-state-buffer ivy-last)
588 (ivy-state-prompt ivy-last)
589 (ivy-state-collection ivy-last)
590 :predicate (ivy-state-predicate ivy-last)
591 :require-match (ivy-state-require-match ivy-last)
592 :initial-input ivy-text
593 :history (ivy-state-history ivy-last)
594 :preselect (unless (eq (ivy-state-collection ivy-last)
595 'read-file-name-internal)
597 :keymap (ivy-state-keymap ivy-last)
598 :update-fn (ivy-state-update-fn ivy-last)
599 :sort (ivy-state-sort ivy-last)
600 :action (ivy-state-action ivy-last)
601 :unwind (ivy-state-unwind ivy-last)
602 :re-builder (ivy-state-re-builder ivy-last)
603 :matcher (ivy-state-matcher ivy-last)
604 :dynamic-collection (ivy-state-dynamic-collection ivy-last)
605 :caller (ivy-state-caller ivy-last))))
607 (defvar ivy-calling nil
608 "When non-nil, call the current action when `ivy--index' changes.")
610 (defun ivy-set-index (index)
611 "Set `ivy--index' to INDEX."
612 (setq ivy--index index)
617 (defun ivy-beginning-of-buffer ()
618 "Select the first completion candidate."
622 (defun ivy-end-of-buffer ()
623 "Select the last completion candidate."
625 (ivy-set-index (1- ivy--length)))
627 (defun ivy-scroll-up-command ()
628 "Scroll the candidates upward by the minibuffer height."
630 (ivy-set-index (min (1- (+ ivy--index ivy-height))
633 (defun ivy-scroll-down-command ()
634 "Scroll the candidates downward by the minibuffer height."
636 (ivy-set-index (max (1+ (- ivy--index ivy-height))
639 (defun ivy-minibuffer-grow ()
640 "Grow the minibuffer window by 1 line."
642 (setq-local max-mini-window-height
643 (cl-incf ivy-height)))
645 (defun ivy-minibuffer-shrink ()
646 "Shrink the minibuffer window by 1 line."
648 (unless (<= ivy-height 2)
649 (setq-local max-mini-window-height
650 (cl-decf ivy-height))
651 (window-resize (selected-window) -1)))
653 (defun ivy-next-line (&optional arg)
654 "Move cursor vertically down ARG candidates."
656 (setq arg (or arg 1))
657 (let ((index (+ ivy--index arg)))
658 (if (> index (1- ivy--length))
660 (ivy-beginning-of-buffer)
661 (ivy-set-index (1- ivy--length)))
662 (ivy-set-index index))))
664 (defun ivy-next-line-or-history (&optional arg)
665 "Move cursor vertically down ARG candidates.
666 If the input is empty, select the previous history element instead."
668 (when (string= ivy-text "")
669 (ivy-previous-history-element 1))
672 (defun ivy-previous-line (&optional arg)
673 "Move cursor vertically up ARG candidates."
675 (setq arg (or arg 1))
676 (let ((index (- ivy--index arg)))
681 (ivy-set-index index))))
683 (defun ivy-previous-line-or-history (arg)
684 "Move cursor vertically up ARG candidates.
685 If the input is empty, select the previous history element instead."
687 (when (string= ivy-text "")
688 (ivy-previous-history-element 1))
689 (ivy-previous-line arg))
691 (defun ivy-toggle-calling ()
692 "Flip `ivy-calling'."
694 (when (setq ivy-calling (not ivy-calling))
697 (defun ivy--get-action (state)
698 "Get the action function from STATE."
699 (let ((action (ivy-state-action state)))
701 (if (functionp action)
703 (cadr (nth (car action) action))))))
705 (defun ivy--get-window (state)
706 "Get the window from STATE."
707 (if (ivy-state-p state)
708 (let ((window (ivy-state-window state)))
709 (if (window-live-p window)
711 (if (= (length (window-list)) 1)
716 (defun ivy--actionp (x)
717 "Return non-nil when X is a list of actions."
718 (and x (listp x) (not (eq (car x) 'closure))))
720 (defun ivy-next-action ()
721 "When the current action is a list, scroll it forwards."
723 (let ((action (ivy-state-action ivy-last)))
724 (when (ivy--actionp action)
725 (unless (>= (car action) (1- (length action)))
726 (cl-incf (car action))))))
728 (defun ivy-prev-action ()
729 "When the current action is a list, scroll it backwards."
731 (let ((action (ivy-state-action ivy-last)))
732 (when (ivy--actionp action)
733 (unless (<= (car action) 1)
734 (cl-decf (car action))))))
736 (defun ivy-action-name ()
737 "Return the name associated with the current action."
738 (let ((action (ivy-state-action ivy-last)))
739 (if (ivy--actionp action)
743 (nth 2 (nth (car action) action)))
746 (defvar ivy-inhibit-action nil
747 "When non-nil, `ivy-call' does nothing.
751 (let* ((ivy-inhibit-action t)
752 (str (counsel-locate \"lispy.el\")))
753 ;; do whatever with str - the corresponding file will not be opened
757 "Call the current action without exiting completion."
759 (unless ivy-inhibit-action
760 (let ((action (ivy--get-action ivy-last)))
762 (let* ((collection (ivy-state-collection ivy-last))
763 (x (if (and (consp collection)
764 (consp (car collection)))
765 (cdr (assoc ivy--current collection))
766 (if (equal ivy--current "")
769 (prog1 (funcall action x)
770 (unless (or (eq ivy-exit 'done)
771 (equal (selected-window)
772 (active-minibuffer-window))
773 (null (active-minibuffer-window)))
774 (select-window (active-minibuffer-window)))))))))
776 (defun ivy-next-line-and-call (&optional arg)
777 "Move cursor vertically down ARG candidates.
778 Call the permanent action if possible."
784 (defun ivy-previous-line-and-call (&optional arg)
785 "Move cursor vertically down ARG candidates.
786 Call the permanent action if possible."
788 (ivy-previous-line arg)
792 (defun ivy-previous-history-element (arg)
793 "Forward to `previous-history-element' with ARG."
795 (previous-history-element arg)
798 (ivy--maybe-scroll-history))
800 (defun ivy-next-history-element (arg)
801 "Forward to `next-history-element' with ARG."
803 (next-history-element arg)
806 (ivy--maybe-scroll-history))
808 (defvar ivy-ffap-url-functions nil
809 "List of functions that check if the point is on a URL.")
811 (defun ivy--cd-maybe ()
812 "Check if the current input points to a different directory.
813 If so, move to that directory, while keeping only the file name."
815 (let ((input (ivy--input))
817 (if (setq url (or (ffap-url-p input)
822 ivy-ffap-url-functions
823 :initial-value nil))))
824 (ivy-exit-with-action
826 (funcall ffap-url-fetcher url)))
827 (setq input (expand-file-name input))
828 (let ((file (file-name-nondirectory input))
829 (dir (expand-file-name (file-name-directory input))))
830 (if (string= dir ivy--directory)
832 (delete-minibuffer-contents)
837 (defun ivy--maybe-scroll-history ()
838 "If the selected history element has an index, scroll there."
839 (let ((idx (ignore-errors
841 (minibuffer-prompt-end)
845 (setq ivy--index idx))))
848 "When completing file names, move to directory DIR."
849 (if (null ivy--directory)
851 (setq ivy--old-cands nil)
852 (setq ivy--old-re nil)
854 (setq ivy--all-candidates
855 (ivy--sorted-files (setq ivy--directory dir)))
857 (delete-minibuffer-contents)))
859 (defun ivy-backward-delete-char ()
860 "Forward to `backward-delete-char'.
861 On error (read-only), call `ivy-on-del-error-function'."
863 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
865 (ivy--cd (file-name-directory
871 (backward-delete-char 1)
873 (when ivy-on-del-error-function
874 (funcall ivy-on-del-error-function))))))
876 (defun ivy-delete-char (arg)
877 "Forward to `delete-char' ARG."
879 (unless (= (point) (line-end-position))
882 (defun ivy-forward-char (arg)
883 "Forward to `forward-char' ARG."
885 (unless (= (point) (line-end-position))
888 (defun ivy-kill-word (arg)
889 "Forward to `kill-word' ARG."
891 (unless (= (point) (line-end-position))
894 (defun ivy-kill-line ()
895 "Forward to `kill-line'."
898 (kill-region (minibuffer-prompt-end) (point))
901 (defun ivy-backward-kill-word ()
902 "Forward to `backward-kill-word'."
904 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
906 (ivy--cd (file-name-directory
914 (delete-region (point) pt)))))
916 (defvar ivy--regexp-quote 'regexp-quote
917 "Store the regexp quoting state.")
919 (defun ivy-toggle-regexp-quote ()
920 "Toggle the regexp quoting."
922 (setq ivy--old-re nil)
923 (cl-rotatef ivy--regex-function ivy--regexp-quote))
925 (defvar avy-all-windows)
928 (defvar avy-keys-alist)
930 (defvar avy-styles-alist)
931 (declare-function avy--process "ext:avy")
932 (declare-function avy--style-fn "ext:avy")
934 (eval-after-load 'avy
935 '(add-to-list 'avy-styles-alist '(ivy-avy . pre)))
938 "Jump to one of the current ivy candidates."
940 (unless (require 'avy nil 'noerror)
941 (error "Package avy isn't installed"))
942 (let* ((avy-all-windows nil)
943 (avy-keys (or (cdr (assq 'ivy-avy avy-keys-alist))
945 (avy-style (or (cdr (assq 'ivy-avy
955 (goto-char (point-min))
957 (while (< (point) (point-max))
963 (setq avy-action #'identity)
965 (nreverse candidates)
966 (avy--style-fn avy-style)))))
967 (ivy-set-index (- (line-number-at-pos candidate) 2))
971 (defun ivy-sort-file-function-default (x y)
972 "Compare two files X and Y.
973 Prioritize directories."
974 (if (get-text-property 0 'dirp x)
975 (if (get-text-property 0 'dirp y)
978 (if (get-text-property 0 'dirp y)
982 (defcustom ivy-sort-functions-alist
983 '((read-file-name-internal . ivy-sort-file-function-default)
984 (internal-complete-buffer . nil)
985 (counsel-git-grep-function . nil)
986 (Man-goto-section . nil)
989 "An alist of sorting functions for each collection function.
990 Interactive functions that call completion fit in here as well.
992 Nil means no sorting, which is useful to turn off the sorting for
993 functions that have candidates in the natural buffer order, like
994 `org-refile' or `Man-goto-section'.
996 The entry associated with t is used for all fall-through cases.
998 See also `ivy-sort-max-size'."
1002 (const :tag "All other functions" t)
1003 (symbol :tag "Function"))
1005 (const :tag "plain sort" string-lessp)
1006 (const :tag "file sort" ivy-sort-file-function-default)
1007 (const :tag "no sort" nil)))
1010 (defvar ivy-index-functions-alist
1011 '((swiper . ivy-recompute-index-swiper)
1012 (swiper-multi . ivy-recompute-index-swiper)
1013 (counsel-git-grep . ivy-recompute-index-swiper)
1014 (counsel-grep . ivy-recompute-index-swiper-async)
1015 (t . ivy-recompute-index-zero))
1016 "An alist of index recomputing functions for each collection function.
1017 When the input changes, the appropriate function returns an
1018 integer - the index of the matched candidate that should be
1021 (defvar ivy-re-builders-alist
1022 '((t . ivy--regex-plus))
1023 "An alist of regex building functions for each collection function.
1025 Each key is (in order of priority):
1026 1. The actual collection function, e.g. `read-file-name-internal'.
1027 2. The symbol passed by :caller into `ivy-read'.
1031 Each value is a function that should take a string and return a
1032 valid regex or a regex sequence (see below).
1034 Possible choices: `ivy--regex', `regexp-quote',
1035 `ivy--regex-plus', `ivy--regex-fuzzy'.
1037 If a function returns a list, it should format like this:
1038 '((\"matching-regexp\" . t) (\"non-matching-regexp\") ...).
1040 The matches will be filtered in a sequence, you can mix the
1041 regexps that should match and that should not match as you
1044 (defvar ivy-initial-inputs-alist
1045 '((org-refile . "^")
1046 (org-agenda-refile . "^")
1047 (org-capture-refile . "^")
1049 (counsel-describe-function . "^")
1050 (counsel-describe-variable . "^")
1053 "Command to initial input table.")
1055 (defcustom ivy-sort-max-size 30000
1056 "Sorting won't be done for collections larger than this."
1059 (defun ivy--sorted-files (dir)
1060 "Return the list of files in DIR.
1061 Directories come first."
1062 (let* ((default-directory dir)
1063 (seq (all-completions "" 'read-file-name-internal))
1067 (setq seq (delete "./" (delete "../" seq)))
1068 (when (eq (setq sort-fn (cdr (assoc 'read-file-name-internal
1069 ivy-sort-functions-alist)))
1070 #'ivy-sort-file-function-default)
1071 (setq seq (mapcar (lambda (x)
1072 (propertize x 'dirp (string-match-p "/\\'" x)))
1075 (setq seq (cl-sort seq sort-fn)))
1076 (dolist (dir ivy-extra-directories)
1080 (defvar ivy-recursive-restore t
1081 "When non-nil, restore the above state when exiting the minibuffer.
1082 This variable is let-bound to nil by functions that take care of
1083 the restoring themselves.")
1086 (cl-defun ivy-read (prompt collection
1088 predicate require-match initial-input
1089 history preselect keymap update-fn sort
1090 action unwind re-builder matcher dynamic-collection caller)
1091 "Read a string in the minibuffer, with completion.
1093 PROMPT is a format string, normally ending in a colon and a
1094 space; %d anywhere in the string is replaced by the current
1095 number of matching candidates. For the literal % character,
1096 escape it with %%. See also `ivy-count-format'.
1098 COLLECTION is either a list of strings, a function, an alist, or
1101 If INITIAL-INPUT is not nil, then insert that input in the
1102 minibuffer initially.
1104 KEYMAP is composed with `ivy-minibuffer-map'.
1106 If PRESELECT is not nil, then select the corresponding candidate
1107 out of the ones that match the INITIAL-INPUT.
1109 UPDATE-FN is called each time the current candidate(s) is changed.
1111 When SORT is t, use `ivy-sort-functions-alist' for sorting.
1113 ACTION is a lambda function to call after selecting a result. It
1114 takes a single string argument.
1116 UNWIND is a lambda function to call before exiting.
1118 RE-BUILDER is a lambda function to call to transform text into a
1121 MATCHER is to override matching.
1123 DYNAMIC-COLLECTION is a boolean to specify if the list of
1124 candidates is updated after each input by calling COLLECTION.
1126 CALLER is a symbol to uniquely identify the caller to `ivy-read'.
1127 It is used, along with COLLECTION, to determine which
1128 customizations apply to the current completion session."
1129 (let ((extra-actions (append (plist-get ivy--actions-list t)
1130 (plist-get ivy--actions-list this-command))))
1133 (cond ((functionp action)
1135 ("o" ,action "default")
1138 (cons 1 extra-actions))
1140 (delete-dups (append action extra-actions)))))))
1141 (let ((recursive-ivy-last (and (active-minibuffer-window) ivy-last)))
1145 :collection collection
1146 :predicate predicate
1147 :require-match require-match
1148 :initial-input initial-input
1150 :preselect preselect
1152 :update-fn update-fn
1155 :window (selected-window)
1156 :buffer (current-buffer)
1158 :re-builder re-builder
1160 :dynamic-collection dynamic-collection
1162 (ivy--reset-state ivy-last)
1165 (minibuffer-with-setup-hook
1166 #'ivy--minibuffer-setup
1167 (let* ((hist (or history 'ivy-history))
1168 (minibuffer-completion-table collection)
1169 (minibuffer-completion-predicate predicate)
1170 (resize-mini-windows (cond
1171 ((display-graphic-p) nil)
1172 ((null resize-mini-windows) 'grow-only)
1173 (t resize-mini-windows))))
1174 (read-from-minibuffer
1176 (ivy-state-initial-input ivy-last)
1177 (make-composed-keymap keymap ivy-minibuffer-map)
1180 (when (eq ivy-exit 'done)
1181 (let ((item (if ivy--directory
1184 (unless (equal item "")
1185 (set hist (cons (propertize item 'ivy-index ivy--index)
1187 (cdr (symbol-value hist))))))))
1189 (remove-hook 'post-command-hook #'ivy--exhibit)
1190 (when (setq unwind (ivy-state-unwind ivy-last))
1192 (unless (eq ivy-exit 'done)
1193 (when recursive-ivy-last
1194 (ivy--reset-state (setq ivy-last recursive-ivy-last)))))
1196 (when (and recursive-ivy-last
1197 ivy-recursive-restore)
1198 (ivy--reset-state (setq ivy-last recursive-ivy-last))))))
1200 (defun ivy--reset-state (state)
1201 "Reset the ivy to STATE.
1202 This is useful for recursive `ivy-read'."
1203 (let ((prompt (or (ivy-state-prompt state) ""))
1204 (collection (ivy-state-collection state))
1205 (predicate (ivy-state-predicate state))
1206 (history (ivy-state-history state))
1207 (preselect (ivy-state-preselect state))
1208 (sort (ivy-state-sort state))
1209 (re-builder (ivy-state-re-builder state))
1210 (dynamic-collection (ivy-state-dynamic-collection state))
1211 (initial-input (ivy-state-initial-input state))
1212 (require-match (ivy-state-require-match state))
1213 (caller (ivy-state-caller state)))
1214 (unless initial-input
1215 (setq initial-input (cdr (assoc this-command
1216 ivy-initial-inputs-alist))))
1217 (setq ivy--directory nil)
1218 (setq ivy-case-fold-search 'auto)
1219 (setq ivy--regex-function
1221 (and (functionp collection)
1222 (cdr (assoc collection ivy-re-builders-alist)))
1224 (cdr (assoc caller ivy-re-builders-alist)))
1225 (cdr (assoc this-command ivy-re-builders-alist))
1226 (cdr (assoc t ivy-re-builders-alist))
1228 (setq ivy--subexps 0)
1229 (setq ivy--regexp-quote 'regexp-quote)
1230 (setq ivy--old-text "")
1231 (setq ivy--full-length nil)
1233 (setq ivy-calling nil)
1235 (cond ((eq collection 'Info-read-node-name-1)
1236 (if (equal Info-current-file "dir")
1238 (mapcar (lambda (x) (format "(%s)" x))
1239 (cl-delete-duplicates
1240 (all-completions "(" collection predicate)
1242 (setq coll (all-completions "" collection predicate))))
1243 ((eq collection 'read-file-name-internal)
1244 (setq ivy--directory default-directory)
1247 (let ((preselect-directory (file-name-directory preselect)))
1248 (unless (or (null preselect-directory)
1249 (string= preselect-directory
1251 (setq ivy--directory preselect-directory))
1253 (ivy-state-preselect state)
1254 (setq preselect (file-name-nondirectory preselect)))))
1255 (setq coll (ivy--sorted-files ivy--directory))
1257 (unless (or require-match
1258 (equal initial-input default-directory)
1259 (equal initial-input ""))
1260 (setq coll (cons initial-input coll)))
1261 (unless (ivy-state-action ivy-last)
1262 (setq initial-input nil))))
1263 ((eq collection 'internal-complete-buffer)
1264 (setq coll (ivy--buffer-list "" ivy-use-virtual-buffers)))
1266 (setq coll (funcall collection ivy-text)))
1267 ((or (functionp collection)
1268 (byte-code-function-p collection)
1269 (vectorp collection)
1270 (and (consp collection) (listp (car collection)))
1271 (hash-table-p collection))
1272 (setq coll (all-completions "" collection predicate)))
1274 (setq coll collection)))
1276 (if (and (functionp collection)
1277 (setq sort-fn (assoc collection ivy-sort-functions-alist)))
1278 (when (and (setq sort-fn (cdr sort-fn))
1279 (not (eq collection 'read-file-name-internal)))
1280 (setq coll (cl-sort coll sort-fn)))
1281 (unless (eq history 'org-refile-history)
1282 (if (and (setq sort-fn (cdr (assoc t ivy-sort-functions-alist)))
1283 (<= (length coll) ivy-sort-max-size))
1284 (setq coll (cl-sort (copy-sequence coll) sort-fn))))))
1286 (unless (or (and require-match
1287 (not (eq collection 'internal-complete-buffer)))
1289 (let ((re (regexp-quote preselect)))
1290 (cl-find-if (lambda (x) (string-match re x))
1292 (setq coll (cons preselect coll))))
1293 (setq ivy--old-re nil)
1294 (setq ivy--old-cands nil)
1295 (when (integerp preselect)
1296 (setq ivy--old-re "")
1297 (setq ivy--index preselect))
1299 ;; Needed for anchor to work
1300 (setq ivy--old-cands coll)
1301 (setq ivy--old-cands (ivy--filter initial-input coll)))
1302 (setq ivy--all-candidates coll)
1303 (unless (integerp preselect)
1304 (setq ivy--index (or
1305 (and dynamic-collection
1308 (ivy--preselect-index
1316 (if (region-active-p)
1317 (prog1 (buffer-substring
1322 (thing-at-point 'url)
1323 (thing-at-point 'symbol)
1326 (cond ((string-match "%.*d" prompt)
1328 ((null ivy-count-format)
1330 "`ivy-count-format' can't be nil. Set it to an empty string instead"))
1331 ((string-match "%d.*%d" ivy-count-format)
1332 (let ((w (length (number-to-string
1333 (length ivy--all-candidates))))
1334 (s (copy-sequence ivy-count-format)))
1335 (string-match "%d" s)
1337 (string-match "%d" s (match-end 0))
1338 (setq s (replace-match (format "%%-%dd" w) nil nil s))
1339 (string-match "%d" s)
1340 (concat (replace-match (format "%%%dd" w) nil nil s)
1342 ((string-match "%.*d" ivy-count-format)
1343 (concat ivy-count-format prompt))
1348 (setf (ivy-state-initial-input ivy-last) initial-input)))
1351 (defun ivy-completing-read (prompt collection
1352 &optional predicate require-match initial-input
1353 history def inherit-input-method)
1354 "Read a string in the minibuffer, with completion.
1356 This interface conforms to `completing-read' and can be used for
1357 `completing-read-function'.
1359 PROMPT is a string to prompt with; normally it ends in a colon and a space.
1360 COLLECTION can be a list of strings, an alist, an obarray or a hash table.
1361 PREDICATE limits completion to a subset of COLLECTION.
1362 REQUIRE-MATCH is specified with a boolean value. See `completing-read'.
1363 INITIAL-INPUT is a string that can be inserted into the minibuffer initially.
1364 HISTORY is a list of previously selected inputs.
1365 DEF is the default value.
1366 INHERIT-INPUT-METHOD is currently ignored."
1367 (if (memq this-command '(tmm-menubar tmm-shortcut))
1368 (completing-read-default prompt collection
1369 predicate require-match
1370 initial-input history
1371 def inherit-input-method)
1372 ;; See the doc of `completing-read'.
1373 (when (consp history)
1374 (when (numberp (cdr history))
1375 (setq initial-input (nth (1- (cdr history))
1376 (symbol-value (car history)))))
1377 (setq history (car history)))
1378 (ivy-read (replace-regexp-in-string "%" "%%" prompt)
1380 :predicate predicate
1381 :require-match require-match
1382 :initial-input (if (consp initial-input)
1384 (if (and (stringp initial-input)
1385 (string-match "\\+" initial-input))
1386 (replace-regexp-in-string
1387 "\\+" "\\\\+" initial-input)
1389 :preselect (if (listp def) (car def) def)
1393 (let ((sort (assoc this-command ivy-sort-functions-alist)))
1398 (defvar ivy-completion-beg nil
1399 "Completion bounds start.")
1401 (defvar ivy-completion-end nil
1402 "Completion bounds end.")
1404 (defun ivy-completion-in-region-action (str)
1405 "Insert STR, erasing the previous one.
1406 The previous string is between `ivy-completion-beg' and `ivy-completion-end'."
1409 (when ivy-completion-beg
1412 ivy-completion-end))
1413 (setq ivy-completion-beg
1414 (move-marker (make-marker) (point)))
1416 (setq ivy-completion-end
1417 (move-marker (make-marker) (point))))))
1419 (defun ivy-completion-common-length (str)
1420 "Return the length of the first 'completions-common-part face in STR."
1423 (while (and (<= pos len)
1424 (let ((prop (get-text-property pos 'face str)))
1425 (not (eq 'completions-common-part
1426 (if (listp prop) (car prop) prop)))))
1427 (setq pos (1+ pos)))
1429 (or (next-single-property-change pos 'face str) len)
1432 (defun ivy-completion-in-region (start end collection &optional predicate)
1433 "An Ivy function suitable for `completion-in-region-function'."
1434 (let* ((enable-recursive-minibuffers t)
1435 (str (buffer-substring-no-properties start end))
1437 (completion-all-completions str collection predicate (- end start))))
1439 (message "No matches")
1441 (setq ivy-completion-beg (- end (ivy-completion-common-length (car comps))))
1442 (setq ivy-completion-end end)
1443 (if (null (cdr comps))
1444 (if (string= str (car comps))
1445 (message "Sole match")
1446 (setf (ivy-state-window ivy-last) (selected-window))
1447 (ivy-completion-in-region-action
1448 (substring-no-properties
1450 (let* ((w (1+ (floor (log (length comps) 10))))
1451 (ivy-count-format (if (string= ivy-count-format "")
1453 (format "%%-%dd " w)))
1454 (prompt (format "(%s): " str)))
1456 (ivy-read (if (string= ivy-count-format "")
1458 (replace-regexp-in-string "%" "%%" prompt))
1459 ;; remove 'completions-first-difference face
1460 (mapcar #'substring-no-properties comps)
1461 :predicate predicate
1462 :action #'ivy-completion-in-region-action
1466 (defcustom ivy-do-completion-in-region t
1467 "When non-nil `ivy-mode' will set `completion-in-region-function'."
1471 (define-minor-mode ivy-mode
1472 "Toggle Ivy mode on or off.
1473 Turn Ivy mode on if ARG is positive, off otherwise.
1474 Turning on Ivy mode sets `completing-read-function' to
1475 `ivy-completing-read'.
1480 Minibuffer bindings:
1481 \\{ivy-minibuffer-map}"
1484 :keymap ivy-mode-map
1488 (setq completing-read-function 'ivy-completing-read)
1489 (when ivy-do-completion-in-region
1490 (setq completion-in-region-function 'ivy-completion-in-region)))
1491 (setq completing-read-function 'completing-read-default)
1492 (setq completion-in-region-function 'completion--in-region)))
1494 (defun ivy--preselect-index (preselect candidates)
1495 "Return the index of PRESELECT in CANDIDATES."
1496 (cond ((integerp preselect)
1498 ((cl-position preselect candidates :test #'equal))
1499 ((stringp preselect)
1500 (let ((re (regexp-quote preselect)))
1503 (string-match re x))
1508 (defvar ivy--regex-hash
1509 (make-hash-table :test #'equal)
1510 "Store pre-computed regex.")
1512 (defun ivy--split (str)
1513 "Split STR into a list by single spaces.
1514 The remaining spaces stick to their left.
1515 This allows to \"quote\" N spaces by inputting N+1 spaces."
1516 (let ((len (length str))
1521 (while (and (string-match " +" str start1)
1523 (setq match-len (- (match-end 0) (match-beginning 0)))
1527 (setq start1 start0)
1529 (push (substring str start1 (match-beginning 0)) res)
1530 (setq start1 (match-end 0)))
1531 (setq str (replace-match
1532 (make-string (1- match-len) ?\ )
1534 (setq start0 (or start0 start1))
1535 (setq start1 (1- (match-end 0)))))
1537 (push (substring str start0) res)
1538 (setq s (substring str start1))
1539 (unless (= (length s) 0)
1543 (defun ivy--regex (str &optional greedy)
1544 "Re-build regex pattern from STR in case it has a space.
1545 When GREEDY is non-nil, join words in a greedy way."
1546 (let ((hashed (unless greedy
1547 (gethash str ivy--regex-hash))))
1550 (setq ivy--subexps (car hashed)))
1551 (when (string-match "\\([^\\]\\|^\\)\\\\$" str)
1552 (setq str (substring str 0 -1)))
1554 (let ((subs (ivy--split str)))
1555 (if (= (length subs) 1)
1557 (setq ivy--subexps 0)
1560 (setq ivy--subexps (length subs))
1563 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1565 (format "\\(%s\\)" x)))
1570 ivy--regex-hash)))))
1572 (defun ivy--regex-ignore-order--part (str &optional discard)
1573 "Re-build regex from STR by splitting at spaces.
1574 Ignore the order of each group."
1575 (let* ((subs (split-string str " +" t))
1576 (len (length subs)))
1581 (mapcar (lambda (x) (cons x (not discard)))
1584 (defun ivy--regex-ignore-order (str)
1585 "Re-build regex from STR by splitting at spaces.
1586 Ignore the order of each group. Everything before \"!\" should
1587 match. Everything after \"!\" should not match."
1588 (let ((parts (split-string str "!" t)))
1589 (cl-case (length parts)
1593 (if (string= (substring str 0 1) "!")
1595 (ivy--regex-ignore-order--part (car parts) t))
1596 (ivy--regex-ignore-order--part (car parts))))
1599 (ivy--regex-ignore-order--part (car parts))
1600 (ivy--regex-ignore-order--part (cadr parts) t)))
1601 (t (error "Unexpected: use only one !")))))
1603 (defun ivy--regex-plus (str)
1604 "Build a regex sequence from STR.
1605 Spaces are wild card characters, everything before \"!\" should
1606 match. Everything after \"!\" should not match."
1607 (let ((parts (split-string str "!" t)))
1608 (cl-case (length parts)
1612 (if (string= (substring str 0 1) "!")
1614 (list (ivy--regex (car parts))))
1615 (ivy--regex (car parts))))
1618 (cons (ivy--regex (car parts)) t)
1619 (mapcar #'list (split-string (cadr parts) " " t))))
1620 (t (error "Unexpected: use only one !")))))
1622 (defun ivy--regex-fuzzy (str)
1623 "Build a regex sequence from STR.
1624 Insert .* between each char."
1625 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1627 (concat (match-string 1 str)
1630 (format "\\(%c\\)" x))
1631 (string-to-list (match-string 2 str)) ".*")
1632 (match-string 3 str))
1633 (setq ivy--subexps (length (match-string 2 str))))
1637 (defun ivy--minibuffer-setup ()
1638 "Setup ivy completion in the minibuffer."
1639 (set (make-local-variable 'completion-show-inline-help) nil)
1640 (set (make-local-variable 'minibuffer-default-add-function)
1642 (list ivy--default)))
1643 (when (display-graphic-p)
1644 (setq truncate-lines t))
1645 (setq-local max-mini-window-height ivy-height)
1646 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1647 ;; show completions with empty input
1650 (defun ivy--input ()
1651 "Return the current minibuffer input."
1652 ;; assume one-line minibuffer input
1653 (buffer-substring-no-properties
1654 (minibuffer-prompt-end)
1655 (line-end-position)))
1657 (defun ivy--cleanup ()
1658 "Delete the displayed completion candidates."
1660 (goto-char (minibuffer-prompt-end))
1661 (delete-region (line-end-position) (point-max))))
1663 (defun ivy--insert-prompt ()
1664 "Update the prompt according to `ivy--prompt'."
1666 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1667 counsel-find-symbol))
1668 (setq ivy--prompt-extra ""))
1670 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1672 (setq head (match-string 1 ivy--prompt))
1674 (setq head (substring ivy--prompt 0 -1))
1676 (let ((inhibit-read-only t)
1677 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1680 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1681 (> (minibuffer-depth) 1))
1682 (format "[%d] " (minibuffer-depth))
1685 (if (string-match "%d.*%d" ivy-count-format)
1688 (or (and (ivy-state-dynamic-collection ivy-last)
1692 (or (and (ivy-state-dynamic-collection ivy-last)
1697 (d-str (if ivy--directory
1698 (abbreviate-file-name ivy--directory)
1701 (goto-char (point-min))
1702 (delete-region (point-min) (minibuffer-prompt-end))
1703 (if (> (+ (mod (+ (length n-str) (length d-str)) (window-width))
1706 (setq n-str (concat n-str "\n" d-str))
1707 (setq n-str (concat n-str d-str)))
1708 (let ((regex (format "\\([^\n]\\{%d\\}\\)[^\n]" (window-width))))
1709 (while (string-match regex n-str)
1710 (setq n-str (replace-match (concat (match-string 1 n-str) "\n") nil t n-str 1))))
1711 (set-text-properties 0 (length n-str)
1712 `(face minibuffer-prompt ,@std-props)
1714 (ivy--set-match-props n-str "confirm"
1715 `(face ivy-confirm-face ,@std-props))
1716 (ivy--set-match-props n-str "match required"
1717 `(face ivy-match-required-face ,@std-props))
1719 ;; get out of the prompt area
1720 (constrain-to-field nil (point-max))))))
1722 (defun ivy--set-match-props (str match props)
1723 "Set STR text properties that match MATCH to PROPS."
1724 (when (string-match match str)
1725 (set-text-properties
1731 (defvar inhibit-message)
1733 (defun ivy--sort-maybe (collection)
1734 "Sort COLLECTION if needed."
1735 (let ((sort (ivy-state-sort ivy-last))
1739 (let ((sort-fn (cond ((functionp sort)
1741 ((setq entry (assoc (ivy-state-collection ivy-last)
1742 ivy-sort-functions-alist))
1745 (cdr (assoc t ivy-sort-functions-alist))))))
1746 (if (functionp sort-fn)
1747 (cl-sort (copy-sequence collection) sort-fn)
1750 (defun ivy--exhibit ()
1751 "Insert Ivy completions display.
1752 Should be run via minibuffer `post-command-hook'."
1753 (when (memq 'ivy--exhibit post-command-hook)
1754 (let ((inhibit-field-text-motion nil))
1755 (constrain-to-field nil (point-max)))
1756 (setq ivy-text (ivy--input))
1757 (if (ivy-state-dynamic-collection ivy-last)
1758 ;; while-no-input would cause annoying
1759 ;; "Waiting for process to die...done" message interruptions
1760 (let ((inhibit-message t))
1761 (unless (equal ivy--old-text ivy-text)
1763 (setq ivy--all-candidates
1765 (funcall (ivy-state-collection ivy-last) ivy-text)))
1766 (setq ivy--old-text ivy-text)))
1767 (when ivy--all-candidates
1768 (ivy--insert-minibuffer
1769 (ivy--format ivy--all-candidates))))
1770 (cond (ivy--directory
1771 (if (string-match "/\\'" ivy-text)
1772 (if (member ivy-text ivy--all-candidates)
1773 (ivy--cd (expand-file-name ivy-text ivy--directory))
1774 (when (string-match "//\\'" ivy-text)
1775 (if (and default-directory
1776 (string-match "\\`[[:alpha:]]:/" default-directory))
1777 (ivy--cd (match-string 0 default-directory))
1779 (when (string-match "[[:alpha:]]:/$" ivy-text)
1780 (let ((drive-root (match-string 0 ivy-text)))
1781 (when (file-exists-p drive-root)
1782 (ivy--cd drive-root)))))
1783 (if (string-match "\\`~\\'" ivy-text)
1784 (ivy--cd (expand-file-name "~/")))))
1785 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1786 (when (or (and (string-match "\\` " ivy-text)
1787 (not (string-match "\\` " ivy--old-text)))
1788 (and (string-match "\\` " ivy--old-text)
1789 (not (string-match "\\` " ivy-text))))
1790 (setq ivy--all-candidates
1791 (if (and (> (length ivy-text) 0)
1792 (eq (aref ivy-text 0)
1794 (ivy--buffer-list " ")
1795 (ivy--buffer-list "" ivy-use-virtual-buffers)))
1796 (setq ivy--old-re nil))))
1797 (ivy--insert-minibuffer
1798 (with-current-buffer (ivy-state-buffer ivy-last)
1800 (ivy--filter ivy-text ivy--all-candidates))))
1801 (setq ivy--old-text ivy-text))))
1803 (defun ivy--insert-minibuffer (text)
1804 "Insert TEXT into minibuffer with appropriate cleanup."
1805 (let ((resize-mini-windows nil)
1806 (update-fn (ivy-state-update-fn ivy-last))
1810 (funcall update-fn))
1811 (ivy--insert-prompt)
1812 ;; Do nothing if while-no-input was aborted.
1813 (when (stringp text)
1814 (let ((buffer-undo-list t))
1818 (when (display-graphic-p)
1819 (ivy--resize-minibuffer-to-fit))))
1821 (defun ivy--resize-minibuffer-to-fit ()
1822 "Resize the minibuffer window size to fit the text in the minibuffer."
1823 (with-selected-window (minibuffer-window)
1824 (if (fboundp 'window-text-pixel-size)
1825 (let ((text-height (cdr (window-text-pixel-size)))
1826 (body-height (window-body-height nil t)))
1827 (when (> text-height body-height)
1828 ;; Note: the size increment needs to be at least frame-char-height,
1829 ;; otherwise resizing won't do anything.
1830 (let ((delta (max (- text-height body-height) (frame-char-height))))
1831 (window-resize nil delta nil t t))))
1832 (let ((text-height (count-screen-lines))
1833 (body-height (window-body-height)))
1834 (when (> text-height body-height)
1835 (window-resize nil (- text-height body-height) nil t))))))
1837 (declare-function colir-blend-face-background "ext:colir")
1839 (defun ivy--add-face (str face)
1840 "Propertize STR with FACE.
1841 `font-lock-append-text-property' is used, since it's better than
1842 `propertize' or `add-face-text-property' in this case."
1846 (colir-blend-face-background 0 (length str) face str)
1847 (let ((foreground (face-foreground face)))
1849 (add-face-text-property
1851 `(:foreground ,foreground)
1856 (font-lock-append-text-property 0 (length str) 'face face str))))
1859 (declare-function flx-make-string-cache "ext:flx")
1860 (declare-function flx-score "ext:flx")
1862 (defvar ivy--flx-cache nil)
1864 (eval-after-load 'flx
1865 '(setq ivy--flx-cache (flx-make-string-cache)))
1867 (defun ivy-toggle-case-fold ()
1868 "Toggle the case folding between nil and auto.
1869 In any completion session, the case folding starts in auto:
1871 - when the input is all lower case, `case-fold-search' is t
1874 You can toggle this to make `case-fold-search' nil regardless of input."
1876 (setq ivy-case-fold-search
1877 (if ivy-case-fold-search
1880 ;; reset cache so that the candidate list updates
1881 (setq ivy--old-re nil))
1883 (defun ivy--re-filter (re candidates)
1884 "Return all RE matching CANDIDATES.
1885 RE is a list of cons cells, with a regexp car and a boolean cdr.
1886 When the cdr is t, the car must match.
1887 Otherwise, the car must not match."
1888 (let ((re-list (if (stringp re) (list (cons re t)) re))
1890 (dolist (re re-list)
1897 (let ((re-str (car re)))
1898 (lambda (x) (string-match re-str x)))
1902 (defun ivy--filter (name candidates)
1903 "Return all items that match NAME in CANDIDATES.
1904 CANDIDATES are assumed to be static."
1905 (let ((re (funcall ivy--regex-function name)))
1906 (if (and (equal re ivy--old-re)
1908 ;; quick caching for "C-n", "C-p" etc.
1910 (let* ((re-str (if (listp re) (caar re) re))
1911 (matcher (ivy-state-matcher ivy-last))
1913 (and ivy-case-fold-search
1914 (string= name (downcase name))))
1917 (funcall matcher re candidates))
1920 (stringp ivy--old-re)
1921 (not (string-match "\\\\" ivy--old-re))
1922 (not (equal ivy--old-re ""))
1924 (if (string-match "\\\\)\\'" ivy--old-re)
1925 (substring ivy--old-re 0 -2)
1931 (lambda (x) (string-match re x))
1934 (ivy--re-filter re candidates)))))
1935 (ivy--recompute-index name re-str cands)
1937 (if (eq ivy--regex-function 'ivy--regex-ignore-order)
1942 (setq ivy--old-cands (ivy--sort name cands))))))
1944 (defcustom ivy-sort-matches-functions-alist '((t . nil))
1945 "An alist of functions used to sort the matching candidates.
1947 This is different from `ivy-sort-functions-alist', which is used
1948 to sort the whole collection only once. The functions taken from
1949 here are instead used on each input change, but they are used
1950 only on already matching candidates, not on all of them.
1952 The alist KEY is a collection function or t to match previously
1953 not matched collection functions.
1955 The alist VAL is a sorting function with the signature of
1956 `ivy--prefix-sort'.")
1958 (defun ivy--sort-files-by-date (_name candidates)
1959 "Re-soft CANDIDATES according to file modification date."
1960 (let ((default-directory ivy--directory))
1961 (cl-sort (copy-sequence candidates)
1964 (nth 5 (file-attributes f2))
1965 (nth 5 (file-attributes f1)))))))
1967 (defun ivy--sort (name candidates)
1968 "Re-sort CANDIDATES by NAME.
1969 All CANDIDATES are assumed to match NAME."
1970 (let ((key (or (ivy-state-caller ivy-last)
1971 (when (functionp (ivy-state-collection ivy-last))
1972 (ivy-state-collection ivy-last))))
1974 (cond ((and (require 'flx nil 'noerror)
1975 (eq ivy--regex-function 'ivy--regex-fuzzy))
1976 (ivy--flx-sort name candidates))
1977 ((setq fun (cdr (or (assoc key ivy-sort-matches-functions-alist)
1978 (assoc t ivy-sort-matches-functions-alist))))
1979 (funcall fun name candidates))
1983 (defun ivy--prefix-sort (name candidates)
1984 "Re-sort CANDIDATES.
1985 Prefix matches to NAME are put ahead of the list."
1986 (if (or (string-match "^\\^" name) (string= name ""))
1988 (let ((re-prefix (concat "^" (funcall ivy--regex-function name)))
1991 (dolist (s candidates)
1992 (if (string-match re-prefix s)
1994 (push s res-noprefix)))
1996 (nreverse res-prefix)
1997 (nreverse res-noprefix)))))
1999 (defun ivy--recompute-index (name re-str cands)
2000 (let* ((caller (ivy-state-caller ivy-last))
2001 (func (or (and caller (cdr (assoc caller ivy-index-functions-alist)))
2002 (cdr (assoc t ivy-index-functions-alist))
2003 #'ivy-recompute-index-zero)))
2004 (unless (eq this-command 'ivy-resume)
2007 (cl-position (if (and (> (length name) 0)
2008 (eq ?^ (aref name 0)))
2014 (concat re-str "/") cands
2016 (and (not (string= name ""))
2017 (not (and (require 'flx nil 'noerror)
2018 (eq ivy--regex-function 'ivy--regex-fuzzy)
2019 (< (length cands) 200)))
2021 (cl-position (nth ivy--index ivy--old-cands)
2023 (funcall func re-str cands))))
2024 (when (and (or (string= name "")
2026 (not (equal ivy--old-re "")))
2028 (or (ivy--preselect-index
2029 (ivy-state-preselect ivy-last)
2033 (defun ivy-recompute-index-swiper (_re-str cands)
2034 (let ((tail (nthcdr ivy--index ivy--old-cands))
2036 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2038 (while (and tail (null idx))
2039 ;; Compare with eq to handle equal duplicates in cands
2040 (setq idx (cl-position (pop tail) cands)))
2043 (1- (length cands))))
2046 ;; already in ivy-state-buffer
2047 (let ((n (line-number-at-pos))
2051 (when (eq n (read (get-text-property 0 'display c)))
2056 (defun ivy-recompute-index-swiper-async (_re-str cands)
2057 (let ((tail (nthcdr ivy--index ivy--old-cands))
2059 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2061 (while (and tail (null idx))
2062 ;; Compare with `equal', since the collection is re-created
2063 ;; each time with `split-string'
2064 (setq idx (cl-position (pop tail) cands :test #'equal)))
2068 (defun ivy-recompute-index-zero (_re-str _cands)
2071 (defcustom ivy-minibuffer-faces
2072 '(ivy-minibuffer-match-face-1
2073 ivy-minibuffer-match-face-2
2074 ivy-minibuffer-match-face-3
2075 ivy-minibuffer-match-face-4)
2076 "List of `ivy' faces for minibuffer group matches.")
2078 (defvar ivy-flx-limit 200
2079 "Used to conditionally turn off flx sorting.
2080 When the amount of matching candidates is larger than this
2081 number, no sorting will be done.")
2083 (defun ivy--flx-sort (name cands)
2084 "Sort according to closeness to string NAME the string list CANDS."
2087 (< (length cands) ivy-flx-limit))
2088 (let* ((flx-name (if (string-match "^\\^" name)
2095 (let ((score (flx-score x flx-name ivy--flx-cache)))
2099 (if cands-with-score
2101 (let ((str (copy-sequence (cdr x)))
2104 (dolist (j (cdar x))
2105 (unless (eq j (1+ last-j))
2108 (ivy-add-face-text-property
2110 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2111 ivy-minibuffer-faces)
2114 (sort cands-with-score
2116 (> (caar x) (caar y)))))
2122 (defcustom ivy-format-function 'ivy-format-function-default
2123 "Function to transform the list of candidates into a string.
2124 This string is inserted into the minibuffer."
2126 (const :tag "Default" ivy-format-function-default)
2127 (const :tag "Arrow prefix" ivy-format-function-arrow)
2128 (const :tag "Full line" ivy-format-function-line)))
2130 (defun ivy--truncate-string (str width)
2131 "Truncate STR to WIDTH."
2132 (if (> (string-width str) width)
2133 (concat (substring str 0 (min (- width 3)
2134 (- (length str) 3))) "...")
2137 (defun ivy--format-function-generic (selected-fn other-fn cand-pairs separator)
2138 "Transform CAND-PAIRS into a string for minibuffer.
2139 SELECTED-FN and OTHER-FN each take two string arguments.
2140 SEPARATOR is used to join the candidates."
2144 (let ((str (car pair))
2146 (curr (eq (cl-incf i) ivy--index)))
2148 (funcall selected-fn str extra)
2149 (funcall other-fn str extra))))
2153 (defun ivy-format-function-default (cand-pairs)
2154 "Transform CAND-PAIRS into a string for minibuffer."
2155 (ivy--format-function-generic
2157 (concat (ivy--add-face str 'ivy-current-match) extra))
2162 (defun ivy-format-function-arrow (cand-pairs)
2163 "Transform CAND-PAIRS into a string for minibuffer."
2164 (ivy--format-function-generic
2166 (concat "> " (ivy--add-face str 'ivy-current-match) extra))
2168 (concat " " str extra))
2172 (defun ivy-format-function-line (cand-pairs)
2173 "Transform CAND-PAIRS into a string for minibuffer."
2174 (ivy--format-function-generic
2176 (ivy--add-face (concat str extra "\n") 'ivy-current-match))
2178 (concat str extra "\n"))
2182 (defun ivy-add-face-text-property (start end face str)
2183 (if (fboundp 'add-face-text-property)
2184 (add-face-text-property
2185 start end face nil str)
2186 (font-lock-append-text-property
2187 start end 'face face str)))
2189 (defun ivy--format-minibuffer-line (str)
2191 (str (copy-sequence str)))
2192 (cond ((eq ivy--regex-function 'ivy--regex-ignore-order)
2193 (when (consp ivy--old-re)
2195 (dolist (re ivy--old-re)
2196 (when (string-match (car re) str)
2197 (ivy-add-face-text-property
2198 (match-beginning 0) (match-end 0)
2199 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2200 ivy-minibuffer-faces)
2203 ((and (eq ivy-display-style 'fancy)
2204 (not (eq ivy--regex-function 'ivy--regex-fuzzy)))
2206 (setq ivy--old-re (funcall ivy--regex-function ivy-text)))
2207 (while (and (string-match ivy--old-re str start)
2208 (> (- (match-end 0) (match-beginning 0)) 0))
2209 (setq start (match-end 0))
2211 (while (<= i ivy--subexps)
2213 (cond ((zerop ivy--subexps)
2214 (cadr ivy-minibuffer-faces))
2216 (car ivy-minibuffer-faces))
2218 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2219 ivy-minibuffer-faces)))))
2220 (ivy-add-face-text-property
2221 (match-beginning i) (match-end i)
2226 (defun ivy--format (cands)
2227 "Return a string for CANDS suitable for display in the minibuffer.
2228 CANDS is a list of strings."
2229 (setq ivy--length (length cands))
2230 (when (>= ivy--index ivy--length)
2231 (setq ivy--index (max (1- ivy--length) 0)))
2233 (setq ivy--current "")
2234 (let* ((half-height (/ ivy-height 2))
2235 (start (max 0 (- ivy--index half-height)))
2236 (end (min (+ start (1- ivy-height)) ivy--length))
2237 (start (max 0 (min start (- end (1- ivy-height)))))
2238 (cands (cl-subseq cands start end))
2239 (index (- ivy--index start)))
2240 (cond (ivy--directory
2241 (setq cands (mapcar (lambda (x)
2242 (if (string-match-p "/\\'" x)
2243 (propertize x 'face 'ivy-subdir)
2246 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
2247 (setq cands (mapcar (lambda (x)
2248 (let ((b (get-buffer x)))
2250 (buffer-file-name b)
2251 (buffer-modified-p b))
2252 (propertize x 'face 'ivy-modified-buffer)
2255 (setq ivy--current (copy-sequence (nth index cands)))
2256 (let* ((ivy--index index)
2259 (cons (ivy--format-minibuffer-line cand) nil)) cands))
2260 (res (concat "\n" (funcall ivy-format-function cand-pairs))))
2261 (put-text-property 0 (length res) 'read-only nil res)
2264 (defvar ivy--virtual-buffers nil
2265 "Store the virtual buffers alist.")
2267 (defvar recentf-list)
2269 (defcustom ivy-virtual-abbreviate 'name
2270 "The mode of abbreviation for virtual buffer names."
2272 (const :tag "Only name" name)
2273 (const :tag "Full path" full)
2274 ;; eventually, uniquify
2277 (defun ivy--virtual-buffers ()
2278 "Adapted from `ido-add-virtual-buffers-to-list'."
2279 (unless recentf-mode
2281 (let ((bookmarks (and (boundp 'bookmark-alist)
2283 virtual-buffers name)
2284 (dolist (head (append
2286 (delete " - no file -"
2287 (delq nil (mapcar (lambda (bookmark)
2288 (cdr (assoc 'filename bookmark)))
2291 (if (eq ivy-virtual-abbreviate 'name)
2292 (file-name-nondirectory head)
2293 (expand-file-name head)))
2294 (when (equal name "")
2295 (setq name (file-name-nondirectory (directory-file-name head))))
2296 (when (equal name "")
2298 (and (not (equal name ""))
2299 (null (get-file-buffer head))
2300 (not (assoc name virtual-buffers))
2301 (push (cons name head) virtual-buffers)))
2302 (when virtual-buffers
2303 (dolist (comp virtual-buffers)
2304 (put-text-property 0 (length (car comp))
2307 (setq ivy--virtual-buffers (nreverse virtual-buffers))
2308 (mapcar #'car ivy--virtual-buffers))))
2310 (defcustom ivy-ignore-buffers nil
2311 "List of regexps matching buffer names to ignore."
2312 :type '(repeat regexp))
2314 (defun ivy--buffer-list (str &optional virtual)
2315 "Return the buffers that match STR.
2316 When VIRTUAL is non-nil, add virtual buffers."
2321 (string-match regexp buf))
2322 ivy-ignore-buffers))
2327 (if (with-current-buffer x
2329 (abbreviate-file-name default-directory)))
2330 (propertize x 'face 'ivy-remote)
2332 (all-completions str 'internal-complete-buffer))
2334 (ivy--virtual-buffers))))))
2336 (defun ivy--switch-buffer-action (buffer)
2338 BUFFER may be a string or nil."
2340 (if (zerop (length buffer))
2342 ivy-text nil 'force-same-window)
2343 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2345 (not (get-buffer buffer)))
2346 (find-file (cdr virtual))
2348 buffer nil 'force-same-window))))))
2350 (defun ivy--switch-buffer-other-window-action (buffer)
2351 "Switch to BUFFER in other window.
2352 BUFFER may be a string or nil."
2353 (if (zerop (length buffer))
2354 (switch-to-buffer-other-window ivy-text)
2355 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2357 (not (get-buffer buffer)))
2358 (find-file-other-window (cdr virtual))
2359 (switch-to-buffer-other-window buffer)))))
2361 (defun ivy--rename-buffer-action (buffer)
2363 (let ((new-name (read-string "Rename buffer (to new name): ")))
2364 (with-current-buffer buffer
2365 (rename-buffer new-name))))
2367 (defvar ivy-switch-buffer-map (make-sparse-keymap))
2374 (ivy--reset-state ivy-last))
2377 ivy--switch-buffer-other-window-action
2380 ivy--rename-buffer-action
2384 (defun ivy-switch-buffer ()
2385 "Switch to another buffer."
2388 (call-interactively 'switch-to-buffer)
2389 (let ((this-command 'ivy-switch-buffer))
2390 (ivy-read "Switch to buffer: " 'internal-complete-buffer
2391 :preselect (buffer-name (other-buffer (current-buffer)))
2392 :action #'ivy--switch-buffer-action
2393 :keymap ivy-switch-buffer-map))))
2396 (defun ivy-switch-buffer-other-window ()
2397 "Switch to another buffer in another window."
2399 (ivy-read "Switch to buffer in other window: " 'internal-complete-buffer
2400 :preselect (buffer-name (other-buffer (current-buffer)))
2401 :action #'ivy--switch-buffer-other-window-action
2402 :keymap ivy-switch-buffer-map))
2405 (defun ivy-recentf ()
2406 "Find a file on `recentf-list'."
2408 (ivy-read "Recentf: " recentf-list
2414 (defun ivy-yank-word ()
2415 "Pull next word from buffer into search string."
2420 (le (line-end-position)))
2424 (setq amend (buffer-substring-no-properties pt (point))))))
2426 (insert (replace-regexp-in-string " +" " " amend)))))
2428 (defun ivy-kill-ring-save ()
2429 "Store the current candidates into the kill ring.
2430 If the region is active, forward to `kill-ring-save' instead."
2432 (if (region-active-p)
2433 (call-interactively 'kill-ring-save)
2440 (defun ivy-insert-current ()
2441 "Make the current candidate into current input.
2442 Don't finish completion."
2444 (delete-minibuffer-contents)
2445 (if (and ivy--directory
2446 (string-match "/$" ivy--current))
2447 (insert (substring ivy--current 0 -1))
2448 (insert ivy--current)))
2450 (defun ivy-toggle-fuzzy ()
2451 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
2453 (setq ivy--old-re nil)
2454 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
2455 (setq ivy--regex-function 'ivy--regex-plus)
2456 (setq ivy--regex-function 'ivy--regex-fuzzy)))
2458 (defun ivy-reverse-i-search ()
2459 "Enter a recursive `ivy-read' session using the current history.
2460 The selected history element will be inserted into the minibuffer."
2462 (let ((enable-recursive-minibuffers t)
2463 (history (symbol-value (ivy-state-history ivy-last)))
2465 (ivy-recursive-restore nil))
2466 (ivy-read "Reverse-i-search: "
2470 (setq ivy-last old-last))
2471 (delete-minibuffer-contents)
2472 (insert (substring-no-properties x))
2475 (defun ivy-restrict-to-matches ()
2476 "Restrict candidates to current matches and erase input."
2478 (delete-minibuffer-contents)
2479 (setq ivy--all-candidates
2480 (ivy--filter ivy-text ivy--all-candidates)))
2483 (defvar-local ivy-occur-last nil
2484 "Buffer-local value of `ivy-last'.
2485 Can't re-use `ivy-last' because using e.g. `swiper' in the same
2486 buffer would modify `ivy-last'.")
2488 (defvar ivy-occur-mode-map
2489 (let ((map (make-sparse-keymap)))
2490 (define-key map [mouse-1] 'ivy-occur-click)
2491 (define-key map (kbd "RET") 'ivy-occur-press)
2492 (define-key map (kbd "j") 'next-line)
2493 (define-key map (kbd "k") 'previous-line)
2494 (define-key map (kbd "h") 'backward-char)
2495 (define-key map (kbd "l") 'forward-char)
2496 (define-key map (kbd "g") 'ivy-occur-press)
2497 (define-key map (kbd "a") 'ivy-occur-read-action)
2498 (define-key map (kbd "o") 'ivy-occur-dispatch)
2499 (define-key map (kbd "q") 'quit-window)
2501 "Keymap for Ivy Occur mode.")
2503 (define-derived-mode ivy-occur-mode fundamental-mode "Ivy-Occur"
2504 "Major mode for output from \\[ivy-occur].
2506 \\{ivy-occur-mode-map}")
2508 (defvar ivy-occur-grep-mode-map
2509 (let ((map (copy-keymap ivy-occur-mode-map)))
2510 (define-key map (kbd "C-x C-q") 'ivy-wgrep-change-to-wgrep-mode)
2512 "Keymap for Ivy Occur Grep mode.")
2514 (define-derived-mode ivy-occur-grep-mode grep-mode "Ivy-Occur"
2515 "Major mode for output from \\[ivy-occur].
2517 \\{ivy-occur-grep-mode-map}")
2519 (defvar counsel-git-grep-cmd)
2522 "Stop completion and put the current matches into a new buffer.
2524 The new buffer remembers current action(s).
2526 While in the *ivy-occur* buffer, selecting a candidate with RET or
2527 a mouse click will call the appropriate action for that candidate.
2529 There is no limit on the number of *ivy-occur* buffers."
2532 (generate-new-buffer
2533 (format "*ivy-occur%s \"%s\"*"
2535 (if (setq caller (ivy-state-caller ivy-last))
2536 (concat " " (prin1-to-string caller))
2539 (do-grep (eq (ivy-state-caller ivy-last) 'counsel-git-grep)))
2540 (with-current-buffer buffer
2543 (setq ivy--old-cands
2545 (shell-command-to-string
2546 (format counsel-git-grep-cmd
2547 (if (stringp ivy--old-re)
2549 (caar ivy--old-re))))
2552 (ivy-occur-grep-mode))
2554 (setf (ivy-state-text ivy-last) ivy-text)
2555 (setq ivy-occur-last ivy-last)
2556 (setq-local ivy--directory ivy--directory)
2557 (let ((inhibit-read-only t))
2560 ;; Need precise number of header lines for `wgrep' to work.
2561 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
2562 default-directory)))
2563 (insert (format "%d candidates:\n" (length ivy--old-cands)))
2564 (dolist (cand ivy--old-cands)
2565 (let ((str (if do-grep
2567 (concat " " cand))))
2568 (add-text-properties
2572 help-echo "mouse-1: call ivy-action")
2574 (insert str "\n")))))
2575 (ivy-exit-with-action
2576 `(lambda (_) (pop-to-buffer ,buffer)))))
2578 (declare-function wgrep-change-to-wgrep-mode "ext:wgrep")
2580 (defun ivy-wgrep-change-to-wgrep-mode ()
2581 "Forward to `wgrep-change-to-wgrep-mode'."
2583 (if (require 'wgrep nil 'noerror)
2584 (wgrep-change-to-wgrep-mode)
2585 (error "Package wgrep isn't installed")))
2587 (defun ivy-occur-read-action ()
2588 "Select one of the available actions as the current one."
2590 (let ((ivy-last ivy-occur-last))
2593 (defun ivy-occur-dispatch ()
2594 "Call one of the available actions on the current item."
2596 (let* ((state-action (ivy-state-action ivy-occur-last))
2597 (actions (if (symbolp state-action)
2599 (copy-sequence state-action))))
2602 (ivy-occur-read-action)
2604 (setf (ivy-state-action ivy-occur-last) actions))))
2606 (defun ivy-occur-click (event)
2607 "Execute action for the current candidate.
2608 EVENT gives the mouse position."
2610 (let ((window (posn-window (event-end event)))
2611 (pos (posn-point (event-end event))))
2612 (with-current-buffer (window-buffer window)
2614 (ivy-occur-press))))
2616 (declare-function swiper--cleanup "swiper")
2617 (declare-function swiper--add-overlays "swiper")
2619 (defun ivy-occur-press ()
2620 "Execute action for the current candidate."
2623 (when (save-excursion
2625 (looking-at "\\(?:./\\| \\)\\(.*\\)$"))
2626 (let* ((ivy-last ivy-occur-last)
2627 (ivy-text (ivy-state-text ivy-last))
2628 (str (buffer-substring
2631 (coll (ivy-state-collection ivy-last))
2632 (action (ivy--get-action ivy-last))
2636 (if (and (consp coll)
2638 (cdr (assoc str coll))
2640 (if (memq (ivy-state-caller ivy-last)
2641 '(swiper counsel-git-grep))
2642 (with-current-buffer (window-buffer (selected-window))
2644 (swiper--add-overlays
2645 (ivy--regex ivy-text)
2646 (line-beginning-position)
2649 (run-at-time 0.5 nil 'swiper--cleanup))
2650 (pulse-momentary-highlight-one-line (point)))))))
2654 ;;; ivy.el ends here