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
1315 (setq ivy--default (or
1316 (thing-at-point 'url)
1317 (thing-at-point 'symbol)
1320 (cond ((string-match "%.*d" prompt)
1322 ((null ivy-count-format)
1324 "`ivy-count-format' can't be nil. Set it to an empty string instead"))
1325 ((string-match "%d.*%d" ivy-count-format)
1326 (let ((w (length (number-to-string
1327 (length ivy--all-candidates))))
1328 (s (copy-sequence ivy-count-format)))
1329 (string-match "%d" s)
1331 (string-match "%d" s (match-end 0))
1332 (setq s (replace-match (format "%%-%dd" w) nil nil s))
1333 (string-match "%d" s)
1334 (concat (replace-match (format "%%%dd" w) nil nil s)
1336 ((string-match "%.*d" ivy-count-format)
1337 (concat ivy-count-format prompt))
1342 (setf (ivy-state-initial-input ivy-last) initial-input)))
1345 (defun ivy-completing-read (prompt collection
1346 &optional predicate require-match initial-input
1347 history def inherit-input-method)
1348 "Read a string in the minibuffer, with completion.
1350 This interface conforms to `completing-read' and can be used for
1351 `completing-read-function'.
1353 PROMPT is a string to prompt with; normally it ends in a colon and a space.
1354 COLLECTION can be a list of strings, an alist, an obarray or a hash table.
1355 PREDICATE limits completion to a subset of COLLECTION.
1356 REQUIRE-MATCH is specified with a boolean value. See `completing-read'.
1357 INITIAL-INPUT is a string that can be inserted into the minibuffer initially.
1358 HISTORY is a list of previously selected inputs.
1359 DEF is the default value.
1360 INHERIT-INPUT-METHOD is currently ignored."
1361 (if (memq this-command '(tmm-menubar tmm-shortcut))
1362 (completing-read-default prompt collection
1363 predicate require-match
1364 initial-input history
1365 def inherit-input-method)
1366 ;; See the doc of `completing-read'.
1367 (when (consp history)
1368 (when (numberp (cdr history))
1369 (setq initial-input (nth (1- (cdr history))
1370 (symbol-value (car history)))))
1371 (setq history (car history)))
1372 (ivy-read (replace-regexp-in-string "%" "%%" prompt)
1374 :predicate predicate
1375 :require-match require-match
1376 :initial-input (if (consp initial-input)
1378 (if (and (stringp initial-input)
1379 (string-match "\\+" initial-input))
1380 (replace-regexp-in-string
1381 "\\+" "\\\\+" initial-input)
1383 :preselect (if (listp def) (car def) def)
1387 (let ((sort (assoc this-command ivy-sort-functions-alist)))
1392 (defvar ivy-completion-beg nil
1393 "Completion bounds start.")
1395 (defvar ivy-completion-end nil
1396 "Completion bounds end.")
1398 (defun ivy-completion-in-region-action (str)
1399 "Insert STR, erasing the previous one.
1400 The previous string is between `ivy-completion-beg' and `ivy-completion-end'."
1403 (when ivy-completion-beg
1406 ivy-completion-end))
1407 (setq ivy-completion-beg
1408 (move-marker (make-marker) (point)))
1410 (setq ivy-completion-end
1411 (move-marker (make-marker) (point))))))
1413 (defun ivy-completion-common-length (str)
1414 "Return the length of the first 'completions-common-part face in STR."
1417 (while (and (<= pos len)
1418 (let ((prop (get-text-property pos 'face str)))
1419 (not (eq 'completions-common-part
1420 (if (listp prop) (car prop) prop)))))
1421 (setq pos (1+ pos)))
1423 (or (next-single-property-change pos 'face str) len)
1426 (defun ivy-completion-in-region (start end collection &optional predicate)
1427 "An Ivy function suitable for `completion-in-region-function'."
1428 (let* ((enable-recursive-minibuffers t)
1429 (str (buffer-substring-no-properties start end))
1431 (completion-all-completions str collection predicate (- end start))))
1433 (message "No matches")
1435 (setq ivy-completion-beg (- end (ivy-completion-common-length (car comps))))
1436 (setq ivy-completion-end end)
1437 (if (null (cdr comps))
1438 (if (string= str (car comps))
1439 (message "Sole match")
1440 (setf (ivy-state-window ivy-last) (selected-window))
1441 (ivy-completion-in-region-action
1442 (substring-no-properties
1444 (let* ((w (1+ (floor (log (length comps) 10))))
1445 (ivy-count-format (if (string= ivy-count-format "")
1447 (format "%%-%dd " w)))
1448 (prompt (format "(%s): " str)))
1450 (ivy-read (if (string= ivy-count-format "")
1452 (replace-regexp-in-string "%" "%%" prompt))
1453 ;; remove 'completions-first-difference face
1454 (mapcar #'substring-no-properties comps)
1455 :predicate predicate
1456 :action #'ivy-completion-in-region-action
1460 (defcustom ivy-do-completion-in-region t
1461 "When non-nil `ivy-mode' will set `completion-in-region-function'."
1465 (define-minor-mode ivy-mode
1466 "Toggle Ivy mode on or off.
1467 Turn Ivy mode on if ARG is positive, off otherwise.
1468 Turning on Ivy mode sets `completing-read-function' to
1469 `ivy-completing-read'.
1474 Minibuffer bindings:
1475 \\{ivy-minibuffer-map}"
1478 :keymap ivy-mode-map
1482 (setq completing-read-function 'ivy-completing-read)
1483 (when ivy-do-completion-in-region
1484 (setq completion-in-region-function 'ivy-completion-in-region)))
1485 (setq completing-read-function 'completing-read-default)
1486 (setq completion-in-region-function 'completion--in-region)))
1488 (defun ivy--preselect-index (preselect candidates)
1489 "Return the index of PRESELECT in CANDIDATES."
1490 (cond ((integerp preselect)
1492 ((cl-position preselect candidates :test #'equal))
1493 ((stringp preselect)
1494 (let ((re (regexp-quote preselect)))
1497 (string-match re x))
1502 (defvar ivy--regex-hash
1503 (make-hash-table :test #'equal)
1504 "Store pre-computed regex.")
1506 (defun ivy--split (str)
1507 "Split STR into a list by single spaces.
1508 The remaining spaces stick to their left.
1509 This allows to \"quote\" N spaces by inputting N+1 spaces."
1510 (let ((len (length str))
1515 (while (and (string-match " +" str start1)
1517 (setq match-len (- (match-end 0) (match-beginning 0)))
1521 (setq start1 start0)
1523 (push (substring str start1 (match-beginning 0)) res)
1524 (setq start1 (match-end 0)))
1525 (setq str (replace-match
1526 (make-string (1- match-len) ?\ )
1528 (setq start0 (or start0 start1))
1529 (setq start1 (1- (match-end 0)))))
1531 (push (substring str start0) res)
1532 (setq s (substring str start1))
1533 (unless (= (length s) 0)
1537 (defun ivy--regex (str &optional greedy)
1538 "Re-build regex pattern from STR in case it has a space.
1539 When GREEDY is non-nil, join words in a greedy way."
1540 (let ((hashed (unless greedy
1541 (gethash str ivy--regex-hash))))
1544 (setq ivy--subexps (car hashed)))
1545 (when (string-match "\\([^\\]\\|^\\)\\\\$" str)
1546 (setq str (substring str 0 -1)))
1548 (let ((subs (ivy--split str)))
1549 (if (= (length subs) 1)
1551 (setq ivy--subexps 0)
1554 (setq ivy--subexps (length subs))
1557 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1559 (format "\\(%s\\)" x)))
1564 ivy--regex-hash)))))
1566 (defun ivy--regex-ignore-order--part (str &optional discard)
1567 "Re-build regex from STR by splitting at spaces.
1568 Ignore the order of each group."
1569 (let* ((subs (split-string str " +" t))
1570 (len (length subs)))
1575 (mapcar (lambda (x) (cons x (not discard)))
1578 (defun ivy--regex-ignore-order (str)
1579 "Re-build regex from STR by splitting at spaces.
1580 Ignore the order of each group. Everything before \"!\" should
1581 match. Everything after \"!\" should not match."
1582 (let ((parts (split-string str "!" t)))
1583 (cl-case (length parts)
1587 (if (string= (substring str 0 1) "!")
1589 (ivy--regex-ignore-order--part (car parts) t))
1590 (ivy--regex-ignore-order--part (car parts))))
1593 (ivy--regex-ignore-order--part (car parts))
1594 (ivy--regex-ignore-order--part (cadr parts) t)))
1595 (t (error "Unexpected: use only one !")))))
1597 (defun ivy--regex-plus (str)
1598 "Build a regex sequence from STR.
1599 Spaces are wild card characters, everything before \"!\" should
1600 match. Everything after \"!\" should not match."
1601 (let ((parts (split-string str "!" t)))
1602 (cl-case (length parts)
1606 (if (string= (substring str 0 1) "!")
1608 (list (ivy--regex (car parts))))
1609 (ivy--regex (car parts))))
1612 (cons (ivy--regex (car parts)) t)
1613 (mapcar #'list (split-string (cadr parts) " " t))))
1614 (t (error "Unexpected: use only one !")))))
1616 (defun ivy--regex-fuzzy (str)
1617 "Build a regex sequence from STR.
1618 Insert .* between each char."
1619 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1621 (concat (match-string 1 str)
1624 (format "\\(%c\\)" x))
1625 (string-to-list (match-string 2 str)) ".*")
1626 (match-string 3 str))
1627 (setq ivy--subexps (length (match-string 2 str))))
1631 (defun ivy--minibuffer-setup ()
1632 "Setup ivy completion in the minibuffer."
1633 (set (make-local-variable 'completion-show-inline-help) nil)
1634 (set (make-local-variable 'minibuffer-default-add-function)
1636 (list ivy--default)))
1637 (when (display-graphic-p)
1638 (setq truncate-lines t))
1639 (setq-local max-mini-window-height ivy-height)
1640 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1641 ;; show completions with empty input
1644 (defun ivy--input ()
1645 "Return the current minibuffer input."
1646 ;; assume one-line minibuffer input
1647 (buffer-substring-no-properties
1648 (minibuffer-prompt-end)
1649 (line-end-position)))
1651 (defun ivy--cleanup ()
1652 "Delete the displayed completion candidates."
1654 (goto-char (minibuffer-prompt-end))
1655 (delete-region (line-end-position) (point-max))))
1657 (defun ivy--insert-prompt ()
1658 "Update the prompt according to `ivy--prompt'."
1660 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1661 counsel-find-symbol))
1662 (setq ivy--prompt-extra ""))
1664 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1666 (setq head (match-string 1 ivy--prompt))
1668 (setq head (substring ivy--prompt 0 -1))
1670 (let ((inhibit-read-only t)
1671 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1674 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1675 (> (minibuffer-depth) 1))
1676 (format "[%d] " (minibuffer-depth))
1679 (if (string-match "%d.*%d" ivy-count-format)
1682 (or (and (ivy-state-dynamic-collection ivy-last)
1686 (or (and (ivy-state-dynamic-collection ivy-last)
1691 (d-str (if ivy--directory
1692 (abbreviate-file-name ivy--directory)
1695 (goto-char (point-min))
1696 (delete-region (point-min) (minibuffer-prompt-end))
1697 (if (> (+ (mod (+ (length n-str) (length d-str)) (window-width))
1700 (setq n-str (concat n-str "\n" d-str))
1701 (setq n-str (concat n-str d-str)))
1702 (let ((regex (format "\\([^\n]\\{%d\\}\\)[^\n]" (window-width))))
1703 (while (string-match regex n-str)
1704 (setq n-str (replace-match (concat (match-string 1 n-str) "\n") nil t n-str 1))))
1705 (set-text-properties 0 (length n-str)
1706 `(face minibuffer-prompt ,@std-props)
1708 (ivy--set-match-props n-str "confirm"
1709 `(face ivy-confirm-face ,@std-props))
1710 (ivy--set-match-props n-str "match required"
1711 `(face ivy-match-required-face ,@std-props))
1713 ;; get out of the prompt area
1714 (constrain-to-field nil (point-max))))))
1716 (defun ivy--set-match-props (str match props)
1717 "Set STR text properties that match MATCH to PROPS."
1718 (when (string-match match str)
1719 (set-text-properties
1725 (defvar inhibit-message)
1727 (defun ivy--sort-maybe (collection)
1728 "Sort COLLECTION if needed."
1729 (let ((sort (ivy-state-sort ivy-last))
1733 (let ((sort-fn (cond ((functionp sort)
1735 ((setq entry (assoc (ivy-state-collection ivy-last)
1736 ivy-sort-functions-alist))
1739 (cdr (assoc t ivy-sort-functions-alist))))))
1740 (if (functionp sort-fn)
1741 (cl-sort (copy-sequence collection) sort-fn)
1744 (defun ivy--exhibit ()
1745 "Insert Ivy completions display.
1746 Should be run via minibuffer `post-command-hook'."
1747 (when (memq 'ivy--exhibit post-command-hook)
1748 (let ((inhibit-field-text-motion nil))
1749 (constrain-to-field nil (point-max)))
1750 (setq ivy-text (ivy--input))
1751 (if (ivy-state-dynamic-collection ivy-last)
1752 ;; while-no-input would cause annoying
1753 ;; "Waiting for process to die...done" message interruptions
1754 (let ((inhibit-message t))
1755 (unless (equal ivy--old-text ivy-text)
1757 (setq ivy--all-candidates
1759 (funcall (ivy-state-collection ivy-last) ivy-text)))
1760 (setq ivy--old-text ivy-text)))
1761 (when ivy--all-candidates
1762 (ivy--insert-minibuffer
1763 (ivy--format ivy--all-candidates))))
1764 (cond (ivy--directory
1765 (if (string-match "/\\'" ivy-text)
1766 (if (member ivy-text ivy--all-candidates)
1767 (ivy--cd (expand-file-name ivy-text ivy--directory))
1768 (when (string-match "//\\'" ivy-text)
1769 (if (and default-directory
1770 (string-match "\\`[[:alpha:]]:/" default-directory))
1771 (ivy--cd (match-string 0 default-directory))
1773 (when (string-match "[[:alpha:]]:/$" ivy-text)
1774 (let ((drive-root (match-string 0 ivy-text)))
1775 (when (file-exists-p drive-root)
1776 (ivy--cd drive-root)))))
1777 (if (string-match "\\`~\\'" ivy-text)
1778 (ivy--cd (expand-file-name "~/")))))
1779 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1780 (when (or (and (string-match "\\` " ivy-text)
1781 (not (string-match "\\` " ivy--old-text)))
1782 (and (string-match "\\` " ivy--old-text)
1783 (not (string-match "\\` " ivy-text))))
1784 (setq ivy--all-candidates
1785 (if (and (> (length ivy-text) 0)
1786 (eq (aref ivy-text 0)
1788 (ivy--buffer-list " ")
1789 (ivy--buffer-list "" ivy-use-virtual-buffers)))
1790 (setq ivy--old-re nil))))
1791 (ivy--insert-minibuffer
1792 (with-current-buffer (ivy-state-buffer ivy-last)
1794 (ivy--filter ivy-text ivy--all-candidates))))
1795 (setq ivy--old-text ivy-text))))
1797 (defun ivy--insert-minibuffer (text)
1798 "Insert TEXT into minibuffer with appropriate cleanup."
1799 (let ((resize-mini-windows nil)
1800 (update-fn (ivy-state-update-fn ivy-last))
1804 (funcall update-fn))
1805 (ivy--insert-prompt)
1806 ;; Do nothing if while-no-input was aborted.
1807 (when (stringp text)
1808 (let ((buffer-undo-list t))
1812 (when (display-graphic-p)
1813 (ivy--resize-minibuffer-to-fit))))
1815 (defun ivy--resize-minibuffer-to-fit ()
1816 "Resize the minibuffer window size to fit the text in the minibuffer."
1817 (with-selected-window (minibuffer-window)
1818 (if (fboundp 'window-text-pixel-size)
1819 (let ((text-height (cdr (window-text-pixel-size)))
1820 (body-height (window-body-height nil t)))
1821 (when (> text-height body-height)
1822 ;; Note: the size increment needs to be at least frame-char-height,
1823 ;; otherwise resizing won't do anything.
1824 (let ((delta (max (- text-height body-height) (frame-char-height))))
1825 (window-resize nil delta nil t t))))
1826 (let ((text-height (count-screen-lines))
1827 (body-height (window-body-height)))
1828 (when (> text-height body-height)
1829 (window-resize nil (- text-height body-height) nil t))))))
1831 (declare-function colir-blend-face-background "ext:colir")
1833 (defun ivy--add-face (str face)
1834 "Propertize STR with FACE.
1835 `font-lock-append-text-property' is used, since it's better than
1836 `propertize' or `add-face-text-property' in this case."
1840 (colir-blend-face-background 0 (length str) face str)
1841 (let ((foreground (face-foreground face)))
1843 (add-face-text-property
1845 `(:foreground ,foreground)
1850 (font-lock-append-text-property 0 (length str) 'face face str))))
1853 (declare-function flx-make-string-cache "ext:flx")
1854 (declare-function flx-score "ext:flx")
1856 (defvar ivy--flx-cache nil)
1858 (eval-after-load 'flx
1859 '(setq ivy--flx-cache (flx-make-string-cache)))
1861 (defun ivy-toggle-case-fold ()
1862 "Toggle the case folding between nil and auto.
1863 In any completion session, the case folding starts in auto:
1865 - when the input is all lower case, `case-fold-search' is t
1868 You can toggle this to make `case-fold-search' nil regardless of input."
1870 (setq ivy-case-fold-search
1871 (if ivy-case-fold-search
1874 ;; reset cache so that the candidate list updates
1875 (setq ivy--old-re nil))
1877 (defun ivy--re-filter (re candidates)
1878 "Return all RE matching CANDIDATES.
1879 RE is a list of cons cells, with a regexp car and a boolean cdr.
1880 When the cdr is t, the car must match.
1881 Otherwise, the car must not match."
1882 (let ((re-list (if (stringp re) (list (cons re t)) re))
1884 (dolist (re re-list)
1891 (let ((re-str (car re)))
1892 (lambda (x) (string-match re-str x)))
1896 (defun ivy--filter (name candidates)
1897 "Return all items that match NAME in CANDIDATES.
1898 CANDIDATES are assumed to be static."
1899 (let ((re (funcall ivy--regex-function name)))
1900 (if (and (equal re ivy--old-re)
1902 ;; quick caching for "C-n", "C-p" etc.
1904 (let* ((re-str (if (listp re) (caar re) re))
1905 (matcher (ivy-state-matcher ivy-last))
1907 (and ivy-case-fold-search
1908 (string= name (downcase name))))
1911 (funcall matcher re candidates))
1914 (stringp ivy--old-re)
1915 (not (string-match "\\\\" ivy--old-re))
1916 (not (equal ivy--old-re ""))
1918 (if (string-match "\\\\)\\'" ivy--old-re)
1919 (substring ivy--old-re 0 -2)
1925 (lambda (x) (string-match re x))
1928 (ivy--re-filter re candidates)))))
1929 (ivy--recompute-index name re-str cands)
1931 (if (eq ivy--regex-function 'ivy--regex-ignore-order)
1936 (setq ivy--old-cands (ivy--sort name cands))))))
1938 (defcustom ivy-sort-matches-functions-alist '((t . nil))
1939 "An alist of functions used to sort the matching candidates.
1941 This is different from `ivy-sort-functions-alist', which is used
1942 to sort the whole collection only once. The functions taken from
1943 here are instead used on each input change, but they are used
1944 only on already matching candidates, not on all of them.
1946 The alist KEY is a collection function or t to match previously
1947 not matched collection functions.
1949 The alist VAL is a sorting function with the signature of
1950 `ivy--prefix-sort'.")
1952 (defun ivy--sort-files-by-date (_name candidates)
1953 "Re-soft CANDIDATES according to file modification date."
1954 (let ((default-directory ivy--directory))
1955 (cl-sort (copy-sequence candidates)
1958 (nth 5 (file-attributes f2))
1959 (nth 5 (file-attributes f1)))))))
1961 (defun ivy--sort (name candidates)
1962 "Re-sort CANDIDATES by NAME.
1963 All CANDIDATES are assumed to match NAME."
1964 (let ((key (or (ivy-state-caller ivy-last)
1965 (when (functionp (ivy-state-collection ivy-last))
1966 (ivy-state-collection ivy-last))))
1968 (cond ((and (require 'flx nil 'noerror)
1969 (eq ivy--regex-function 'ivy--regex-fuzzy))
1970 (ivy--flx-sort name candidates))
1971 ((setq fun (cdr (or (assoc key ivy-sort-matches-functions-alist)
1972 (assoc t ivy-sort-matches-functions-alist))))
1973 (funcall fun name candidates))
1977 (defun ivy--prefix-sort (name candidates)
1978 "Re-sort CANDIDATES.
1979 Prefix matches to NAME are put ahead of the list."
1980 (if (or (string-match "^\\^" name) (string= name ""))
1982 (let ((re-prefix (concat "^" (funcall ivy--regex-function name)))
1985 (dolist (s candidates)
1986 (if (string-match re-prefix s)
1988 (push s res-noprefix)))
1990 (nreverse res-prefix)
1991 (nreverse res-noprefix)))))
1993 (defun ivy--recompute-index (name re-str cands)
1994 (let* ((caller (ivy-state-caller ivy-last))
1995 (func (or (and caller (cdr (assoc caller ivy-index-functions-alist)))
1996 (cdr (assoc t ivy-index-functions-alist))
1997 #'ivy-recompute-index-zero)))
1998 (unless (eq this-command 'ivy-resume)
2001 (cl-position (if (and (> (length name) 0)
2002 (eq ?^ (aref name 0)))
2008 (concat re-str "/") cands
2010 (and (not (string= name ""))
2011 (not (and (require 'flx nil 'noerror)
2012 (eq ivy--regex-function 'ivy--regex-fuzzy)
2013 (< (length cands) 200)))
2015 (cl-position (nth ivy--index ivy--old-cands)
2017 (funcall func re-str cands))))
2018 (when (and (or (string= name "")
2020 (not (equal ivy--old-re "")))
2022 (or (ivy--preselect-index
2023 (ivy-state-preselect ivy-last)
2027 (defun ivy-recompute-index-swiper (_re-str cands)
2028 (let ((tail (nthcdr ivy--index ivy--old-cands))
2030 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2032 (while (and tail (null idx))
2033 ;; Compare with eq to handle equal duplicates in cands
2034 (setq idx (cl-position (pop tail) cands)))
2037 (1- (length cands))))
2040 ;; already in ivy-state-buffer
2041 (let ((n (line-number-at-pos))
2045 (when (eq n (read (get-text-property 0 'display c)))
2050 (defun ivy-recompute-index-swiper-async (_re-str cands)
2051 (let ((tail (nthcdr ivy--index ivy--old-cands))
2053 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2055 (while (and tail (null idx))
2056 ;; Compare with `equal', since the collection is re-created
2057 ;; each time with `split-string'
2058 (setq idx (cl-position (pop tail) cands :test #'equal)))
2062 (defun ivy-recompute-index-zero (_re-str _cands)
2065 (defcustom ivy-minibuffer-faces
2066 '(ivy-minibuffer-match-face-1
2067 ivy-minibuffer-match-face-2
2068 ivy-minibuffer-match-face-3
2069 ivy-minibuffer-match-face-4)
2070 "List of `ivy' faces for minibuffer group matches.")
2072 (defvar ivy-flx-limit 200
2073 "Used to conditionally turn off flx sorting.
2074 When the amount of matching candidates is larger than this
2075 number, no sorting will be done.")
2077 (defun ivy--flx-sort (name cands)
2078 "Sort according to closeness to string NAME the string list CANDS."
2081 (< (length cands) ivy-flx-limit))
2082 (let* ((flx-name (if (string-match "^\\^" name)
2089 (let ((score (flx-score x flx-name ivy--flx-cache)))
2093 (if cands-with-score
2095 (let ((str (copy-sequence (cdr x)))
2098 (dolist (j (cdar x))
2099 (unless (eq j (1+ last-j))
2102 (ivy-add-face-text-property
2104 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2105 ivy-minibuffer-faces)
2108 (sort cands-with-score
2110 (> (caar x) (caar y)))))
2116 (defcustom ivy-format-function 'ivy-format-function-default
2117 "Function to transform the list of candidates into a string.
2118 This string is inserted into the minibuffer."
2120 (const :tag "Default" ivy-format-function-default)
2121 (const :tag "Arrow prefix" ivy-format-function-arrow)
2122 (const :tag "Full line" ivy-format-function-line)))
2124 (defun ivy--truncate-string (str width)
2125 "Truncate STR to WIDTH."
2126 (if (> (string-width str) width)
2127 (concat (substring str 0 (min (- width 3)
2128 (- (length str) 3))) "...")
2131 (defun ivy--format-function-generic (selected-fn other-fn cand-pairs separator)
2132 "Transform CAND-PAIRS into a string for minibuffer.
2133 SELECTED-FN and OTHER-FN each take two string arguments.
2134 SEPARATOR is used to join the candidates."
2138 (let ((str (car pair))
2140 (curr (eq (cl-incf i) ivy--index)))
2142 (funcall selected-fn str extra)
2143 (funcall other-fn str extra))))
2147 (defun ivy-format-function-default (cand-pairs)
2148 "Transform CAND-PAIRS into a string for minibuffer."
2149 (ivy--format-function-generic
2151 (concat (ivy--add-face str 'ivy-current-match) extra))
2156 (defun ivy-format-function-arrow (cand-pairs)
2157 "Transform CAND-PAIRS into a string for minibuffer."
2158 (ivy--format-function-generic
2160 (concat "> " (ivy--add-face str 'ivy-current-match) extra))
2162 (concat " " str extra))
2166 (defun ivy-format-function-line (cand-pairs)
2167 "Transform CAND-PAIRS into a string for minibuffer."
2168 (ivy--format-function-generic
2170 (ivy--add-face (concat str extra "\n") 'ivy-current-match))
2172 (concat str extra "\n"))
2176 (defun ivy-add-face-text-property (start end face str)
2177 (if (fboundp 'add-face-text-property)
2178 (add-face-text-property
2179 start end face nil str)
2180 (font-lock-append-text-property
2181 start end 'face face str)))
2183 (defun ivy--format-minibuffer-line (str)
2185 (str (copy-sequence str)))
2186 (cond ((eq ivy--regex-function 'ivy--regex-ignore-order)
2187 (when (consp ivy--old-re)
2189 (dolist (re ivy--old-re)
2190 (when (string-match (car re) str)
2191 (ivy-add-face-text-property
2192 (match-beginning 0) (match-end 0)
2193 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2194 ivy-minibuffer-faces)
2197 ((and (eq ivy-display-style 'fancy)
2198 (not (eq ivy--regex-function 'ivy--regex-fuzzy)))
2200 (setq ivy--old-re (funcall ivy--regex-function ivy-text)))
2201 (while (and (string-match ivy--old-re str start)
2202 (> (- (match-end 0) (match-beginning 0)) 0))
2203 (setq start (match-end 0))
2205 (while (<= i ivy--subexps)
2207 (cond ((zerop ivy--subexps)
2208 (cadr ivy-minibuffer-faces))
2210 (car ivy-minibuffer-faces))
2212 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2213 ivy-minibuffer-faces)))))
2214 (ivy-add-face-text-property
2215 (match-beginning i) (match-end i)
2220 (defun ivy--format (cands)
2221 "Return a string for CANDS suitable for display in the minibuffer.
2222 CANDS is a list of strings."
2223 (setq ivy--length (length cands))
2224 (when (>= ivy--index ivy--length)
2225 (setq ivy--index (max (1- ivy--length) 0)))
2227 (setq ivy--current "")
2228 (let* ((half-height (/ ivy-height 2))
2229 (start (max 0 (- ivy--index half-height)))
2230 (end (min (+ start (1- ivy-height)) ivy--length))
2231 (start (max 0 (min start (- end (1- ivy-height)))))
2232 (cands (cl-subseq cands start end))
2233 (index (- ivy--index start)))
2234 (cond (ivy--directory
2235 (setq cands (mapcar (lambda (x)
2236 (if (string-match-p "/\\'" x)
2237 (propertize x 'face 'ivy-subdir)
2240 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
2241 (setq cands (mapcar (lambda (x)
2242 (let ((b (get-buffer x)))
2244 (buffer-file-name b)
2245 (buffer-modified-p b))
2246 (propertize x 'face 'ivy-modified-buffer)
2249 (setq ivy--current (copy-sequence (nth index cands)))
2250 (let* ((ivy--index index)
2253 (cons (ivy--format-minibuffer-line cand) nil)) cands))
2254 (res (concat "\n" (funcall ivy-format-function cand-pairs))))
2255 (put-text-property 0 (length res) 'read-only nil res)
2258 (defvar ivy--virtual-buffers nil
2259 "Store the virtual buffers alist.")
2261 (defvar recentf-list)
2263 (defcustom ivy-virtual-abbreviate 'name
2264 "The mode of abbreviation for virtual buffer names."
2266 (const :tag "Only name" name)
2267 (const :tag "Full path" full)
2268 ;; eventually, uniquify
2271 (defun ivy--virtual-buffers ()
2272 "Adapted from `ido-add-virtual-buffers-to-list'."
2273 (unless recentf-mode
2275 (let ((bookmarks (and (boundp 'bookmark-alist)
2277 virtual-buffers name)
2278 (dolist (head (append
2280 (delete " - no file -"
2281 (delq nil (mapcar (lambda (bookmark)
2282 (cdr (assoc 'filename bookmark)))
2285 (if (eq ivy-virtual-abbreviate 'name)
2286 (file-name-nondirectory head)
2287 (expand-file-name head)))
2288 (when (equal name "")
2289 (setq name (file-name-nondirectory (directory-file-name head))))
2290 (when (equal name "")
2292 (and (not (equal name ""))
2293 (null (get-file-buffer head))
2294 (not (assoc name virtual-buffers))
2295 (push (cons name head) virtual-buffers)))
2296 (when virtual-buffers
2297 (dolist (comp virtual-buffers)
2298 (put-text-property 0 (length (car comp))
2301 (setq ivy--virtual-buffers (nreverse virtual-buffers))
2302 (mapcar #'car ivy--virtual-buffers))))
2304 (defcustom ivy-ignore-buffers nil
2305 "List of regexps matching buffer names to ignore."
2306 :type '(repeat regexp))
2308 (defun ivy--buffer-list (str &optional virtual)
2309 "Return the buffers that match STR.
2310 When VIRTUAL is non-nil, add virtual buffers."
2315 (string-match regexp buf))
2316 ivy-ignore-buffers))
2321 (if (with-current-buffer x
2323 (abbreviate-file-name default-directory)))
2324 (propertize x 'face 'ivy-remote)
2326 (all-completions str 'internal-complete-buffer))
2328 (ivy--virtual-buffers))))))
2330 (defun ivy--switch-buffer-action (buffer)
2332 BUFFER may be a string or nil."
2334 (if (zerop (length buffer))
2336 ivy-text nil 'force-same-window)
2337 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2339 (not (get-buffer buffer)))
2340 (find-file (cdr virtual))
2342 buffer nil 'force-same-window))))))
2344 (defun ivy--switch-buffer-other-window-action (buffer)
2345 "Switch to BUFFER in other window.
2346 BUFFER may be a string or nil."
2347 (if (zerop (length buffer))
2348 (switch-to-buffer-other-window ivy-text)
2349 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2351 (not (get-buffer buffer)))
2352 (find-file-other-window (cdr virtual))
2353 (switch-to-buffer-other-window buffer)))))
2355 (defun ivy--rename-buffer-action (buffer)
2357 (let ((new-name (read-string "Rename buffer (to new name): ")))
2358 (with-current-buffer buffer
2359 (rename-buffer new-name))))
2361 (defvar ivy-switch-buffer-map (make-sparse-keymap))
2368 (ivy--reset-state ivy-last))
2371 ivy--switch-buffer-other-window-action
2374 ivy--rename-buffer-action
2378 (defun ivy-switch-buffer ()
2379 "Switch to another buffer."
2382 (call-interactively 'switch-to-buffer)
2383 (let ((this-command 'ivy-switch-buffer))
2384 (ivy-read "Switch to buffer: " 'internal-complete-buffer
2385 :preselect (buffer-name (other-buffer (current-buffer)))
2386 :action #'ivy--switch-buffer-action
2387 :keymap ivy-switch-buffer-map))))
2390 (defun ivy-switch-buffer-other-window ()
2391 "Switch to another buffer in another window."
2393 (ivy-read "Switch to buffer in other window: " 'internal-complete-buffer
2394 :preselect (buffer-name (other-buffer (current-buffer)))
2395 :action #'ivy--switch-buffer-other-window-action
2396 :keymap ivy-switch-buffer-map))
2399 (defun ivy-recentf ()
2400 "Find a file on `recentf-list'."
2402 (ivy-read "Recentf: " recentf-list
2408 (defun ivy-yank-word ()
2409 "Pull next word from buffer into search string."
2414 (le (line-end-position)))
2418 (setq amend (buffer-substring-no-properties pt (point))))))
2420 (insert (replace-regexp-in-string " +" " " amend)))))
2422 (defun ivy-kill-ring-save ()
2423 "Store the current candidates into the kill ring.
2424 If the region is active, forward to `kill-ring-save' instead."
2426 (if (region-active-p)
2427 (call-interactively 'kill-ring-save)
2434 (defun ivy-insert-current ()
2435 "Make the current candidate into current input.
2436 Don't finish completion."
2438 (delete-minibuffer-contents)
2439 (if (and ivy--directory
2440 (string-match "/$" ivy--current))
2441 (insert (substring ivy--current 0 -1))
2442 (insert ivy--current)))
2444 (defun ivy-toggle-fuzzy ()
2445 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
2447 (setq ivy--old-re nil)
2448 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
2449 (setq ivy--regex-function 'ivy--regex-plus)
2450 (setq ivy--regex-function 'ivy--regex-fuzzy)))
2452 (defun ivy-reverse-i-search ()
2453 "Enter a recursive `ivy-read' session using the current history.
2454 The selected history element will be inserted into the minibuffer."
2456 (let ((enable-recursive-minibuffers t)
2457 (history (symbol-value (ivy-state-history ivy-last)))
2459 (ivy-recursive-restore nil))
2460 (ivy-read "Reverse-i-search: "
2464 (setq ivy-last old-last))
2465 (delete-minibuffer-contents)
2466 (insert (substring-no-properties x))
2469 (defun ivy-restrict-to-matches ()
2470 "Restrict candidates to current matches and erase input."
2472 (delete-minibuffer-contents)
2473 (setq ivy--all-candidates
2474 (ivy--filter ivy-text ivy--all-candidates)))
2477 (defvar-local ivy-occur-last nil
2478 "Buffer-local value of `ivy-last'.
2479 Can't re-use `ivy-last' because using e.g. `swiper' in the same
2480 buffer would modify `ivy-last'.")
2482 (defvar ivy-occur-mode-map
2483 (let ((map (make-sparse-keymap)))
2484 (define-key map [mouse-1] 'ivy-occur-click)
2485 (define-key map (kbd "RET") 'ivy-occur-press)
2486 (define-key map (kbd "j") 'next-line)
2487 (define-key map (kbd "k") 'previous-line)
2488 (define-key map (kbd "h") 'backward-char)
2489 (define-key map (kbd "l") 'forward-char)
2490 (define-key map (kbd "g") 'ivy-occur-press)
2491 (define-key map (kbd "a") 'ivy-occur-read-action)
2492 (define-key map (kbd "o") 'ivy-occur-dispatch)
2493 (define-key map (kbd "q") 'quit-window)
2495 "Keymap for Ivy Occur mode.")
2497 (define-derived-mode ivy-occur-mode fundamental-mode "Ivy-Occur"
2498 "Major mode for output from \\[ivy-occur].
2500 \\{ivy-occur-mode-map}")
2502 (defvar ivy-occur-grep-mode-map
2503 (let ((map (copy-keymap ivy-occur-mode-map)))
2504 (define-key map (kbd "C-x C-q") 'ivy-wgrep-change-to-wgrep-mode)
2506 "Keymap for Ivy Occur Grep mode.")
2508 (define-derived-mode ivy-occur-grep-mode grep-mode "Ivy-Occur"
2509 "Major mode for output from \\[ivy-occur].
2511 \\{ivy-occur-grep-mode-map}")
2513 (defvar counsel-git-grep-cmd)
2516 "Stop completion and put the current matches into a new buffer.
2518 The new buffer remembers current action(s).
2520 While in the *ivy-occur* buffer, selecting a candidate with RET or
2521 a mouse click will call the appropriate action for that candidate.
2523 There is no limit on the number of *ivy-occur* buffers."
2526 (generate-new-buffer
2527 (format "*ivy-occur%s \"%s\"*"
2529 (if (setq caller (ivy-state-caller ivy-last))
2530 (concat " " (prin1-to-string caller))
2533 (do-grep (eq (ivy-state-caller ivy-last) 'counsel-git-grep)))
2534 (with-current-buffer buffer
2537 (setq ivy--old-cands
2539 (shell-command-to-string
2540 (format counsel-git-grep-cmd
2541 (if (stringp ivy--old-re)
2543 (caar ivy--old-re))))
2546 (ivy-occur-grep-mode))
2548 (setf (ivy-state-text ivy-last) ivy-text)
2549 (setq ivy-occur-last ivy-last)
2550 (setq-local ivy--directory ivy--directory)
2551 (let ((inhibit-read-only t))
2554 ;; Need precise number of header lines for `wgrep' to work.
2555 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
2556 default-directory)))
2557 (insert (format "%d candidates:\n" (length ivy--old-cands)))
2558 (dolist (cand ivy--old-cands)
2559 (let ((str (if do-grep
2561 (concat " " cand))))
2562 (add-text-properties
2566 help-echo "mouse-1: call ivy-action")
2568 (insert str "\n")))))
2569 (ivy-exit-with-action
2570 `(lambda (_) (pop-to-buffer ,buffer)))))
2572 (declare-function wgrep-change-to-wgrep-mode "ext:wgrep")
2574 (defun ivy-wgrep-change-to-wgrep-mode ()
2575 "Forward to `wgrep-change-to-wgrep-mode'."
2577 (if (require 'wgrep nil 'noerror)
2578 (wgrep-change-to-wgrep-mode)
2579 (error "Package wgrep isn't installed")))
2581 (defun ivy-occur-read-action ()
2582 "Select one of the available actions as the current one."
2584 (let ((ivy-last ivy-occur-last))
2587 (defun ivy-occur-dispatch ()
2588 "Call one of the available actions on the current item."
2590 (let* ((state-action (ivy-state-action ivy-occur-last))
2591 (actions (if (symbolp state-action)
2593 (copy-sequence state-action))))
2596 (ivy-occur-read-action)
2598 (setf (ivy-state-action ivy-occur-last) actions))))
2600 (defun ivy-occur-click (event)
2601 "Execute action for the current candidate.
2602 EVENT gives the mouse position."
2604 (let ((window (posn-window (event-end event)))
2605 (pos (posn-point (event-end event))))
2606 (with-current-buffer (window-buffer window)
2608 (ivy-occur-press))))
2610 (declare-function swiper--cleanup "swiper")
2611 (declare-function swiper--add-overlays "swiper")
2613 (defun ivy-occur-press ()
2614 "Execute action for the current candidate."
2617 (when (save-excursion
2619 (looking-at "\\(?:./\\| \\)\\(.*\\)$"))
2620 (let* ((ivy-last ivy-occur-last)
2621 (ivy-text (ivy-state-text ivy-last))
2622 (str (buffer-substring
2625 (coll (ivy-state-collection ivy-last))
2626 (action (ivy--get-action ivy-last))
2630 (if (and (consp coll)
2632 (cdr (assoc str coll))
2634 (if (memq (ivy-state-caller ivy-last)
2635 '(swiper counsel-git-grep))
2636 (with-current-buffer (window-buffer (selected-window))
2638 (swiper--add-overlays
2639 (ivy--regex ivy-text)
2640 (line-beginning-position)
2643 (run-at-time 0.5 nil 'swiper--cleanup))
2644 (pulse-momentary-highlight-one-line (point)))))))
2648 ;;; ivy.el ends here