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'."
52 (defface ivy-current-match
53 '((((class color) (background light))
54 :background "#1a4b77" :foreground "white")
55 (((class color) (background dark))
56 :background "#65a7e2" :foreground "black"))
57 "Face used by Ivy for highlighting the current match.")
59 (defface ivy-minibuffer-match-face-1
60 '((((class color) (background light))
61 :background "#d3d3d3")
62 (((class color) (background dark))
63 :background "#555555"))
64 "The background face for `ivy' minibuffer matches.")
66 (defface ivy-minibuffer-match-face-2
67 '((((class color) (background light))
68 :background "#e99ce8" :weight bold)
69 (((class color) (background dark))
70 :background "#777777" :weight bold))
71 "Face for `ivy' minibuffer matches numbered 1 modulo 3.")
73 (defface ivy-minibuffer-match-face-3
74 '((((class color) (background light))
75 :background "#bbbbff" :weight bold)
76 (((class color) (background dark))
77 :background "#7777ff" :weight bold))
78 "Face for `ivy' minibuffer matches numbered 2 modulo 3.")
80 (defface ivy-minibuffer-match-face-4
81 '((((class color) (background light))
82 :background "#ffbbff" :weight bold)
83 (((class color) (background dark))
84 :background "#8a498a" :weight bold))
85 "Face for `ivy' minibuffer matches numbered 3 modulo 3.")
87 (defface ivy-confirm-face
88 '((t :foreground "ForestGreen" :inherit minibuffer-prompt))
89 "Face used by Ivy for a confirmation prompt.")
91 (defface ivy-match-required-face
92 '((t :foreground "red" :inherit minibuffer-prompt))
93 "Face used by Ivy for a match required prompt.")
96 '((t :inherit dired-directory))
97 "Face used by Ivy for highlighting subdirs in the alternatives.")
99 (defface ivy-modified-buffer
100 '((t :inherit default))
101 "Face used by Ivy for highlighting modified file visiting buffers.")
104 '((t :foreground "#110099"))
105 "Face used by Ivy for highlighting remotes in the alternatives.")
108 '((t :inherit font-lock-builtin-face))
109 "Face used by Ivy for matching virtual buffer names.")
111 (setcdr (assoc load-file-name custom-current-group-alist) 'ivy)
113 (defcustom ivy-height 10
114 "Number of lines for the minibuffer window."
117 (defcustom ivy-count-format "%-4d "
118 "The style to use for displaying the current candidate count for `ivy-read'.
119 Set this to \"\" to suppress the count visibility.
120 Set this to \"(%d/%d) \" to display both the index and the count."
122 (const :tag "Count disabled" "")
123 (const :tag "Count matches" "%-4d ")
124 (const :tag "Count matches and show current match" "(%d/%d) ")
127 (defcustom ivy-wrap nil
128 "When non-nil, wrap around after the first and the last candidate."
131 (defcustom ivy-display-style (unless (version< emacs-version "24.5") 'fancy)
132 "The style for formatting the minibuffer.
134 By default, the matched strings are copied as is.
136 The fancy display style highlights matching parts of the regexp,
137 a behavior similar to `swiper'.
139 This setting depends on `add-face-text-property' - a C function
140 available as of Emacs 24.5. Fancy style will render poorly in
141 earlier versions of Emacs."
143 (const :tag "Plain" nil)
144 (const :tag "Fancy" fancy)))
146 (defcustom ivy-on-del-error-function 'minibuffer-keyboard-quit
147 "The handler for when `ivy-backward-delete-char' throws.
148 Usually a quick exit out of the minibuffer."
151 (defcustom ivy-extra-directories '("../" "./")
152 "Add this to the front of the list when completing file names.
153 Only \"./\" and \"../\" apply here. They appear in reverse order."
154 :type '(repeat :tag "Dirs"
156 (const :tag "Parent Directory" "../")
157 (const :tag "Current Directory" "./"))))
159 (defcustom ivy-use-virtual-buffers nil
160 "When non-nil, add `recentf-mode' and bookmarks to `ivy-switch-buffer'."
163 (defvar ivy--actions-list nil
164 "A list of extra actions per command.")
166 (defun ivy-set-actions (cmd actions)
167 "Set CMD extra exit points to ACTIONS."
168 (setq ivy--actions-list
169 (plist-put ivy--actions-list cmd actions)))
171 (defvar ivy--display-transformers-list nil
172 "A list of str->str transformers per command.")
174 (defun ivy-set-display-transformer (cmd transformer)
175 "Set CMD a displayed candidate TRANSFORMER.
177 It's a lambda that takes a string one of the candidates in the
178 collection and returns a string for display, the same candidate
179 plus some extra information.
181 This lambda is called only on the `ivy-height' candidates that
182 are about to be displayed, not on the whole collection."
183 (setq ivy--display-transformers-list
184 (plist-put ivy--display-transformers-list cmd transformer)))
186 (defvar ivy--sources-list nil
187 "A list of extra sources per command.")
189 (defun ivy-set-sources (cmd sources)
190 "Attach to CMD a list of extra SOURCES.
192 Each static source is a function that takes no argument and
193 returns a list of strings.
195 The '(original-source) determines the position of the original
198 Extra dynamic sources aren't supported yet.
202 (defun small-recentf ()
203 (cl-subseq recentf-list 0 20))
210 (setq ivy--sources-list
211 (plist-put ivy--sources-list cmd sources)))
215 (defvar ivy-minibuffer-map
216 (let ((map (make-sparse-keymap)))
217 (define-key map (kbd "C-m") 'ivy-done)
218 (define-key map (kbd "C-M-m") 'ivy-call)
219 (define-key map (kbd "C-j") 'ivy-alt-done)
220 (define-key map (kbd "C-M-j") 'ivy-immediate-done)
221 (define-key map (kbd "TAB") 'ivy-partial-or-done)
222 (define-key map (kbd "C-n") 'ivy-next-line)
223 (define-key map (kbd "C-p") 'ivy-previous-line)
224 (define-key map (kbd "<down>") 'ivy-next-line)
225 (define-key map (kbd "<up>") 'ivy-previous-line)
226 (define-key map (kbd "C-s") 'ivy-next-line-or-history)
227 (define-key map (kbd "C-r") 'ivy-reverse-i-search)
228 (define-key map (kbd "SPC") 'self-insert-command)
229 (define-key map (kbd "DEL") 'ivy-backward-delete-char)
230 (define-key map (kbd "M-DEL") 'ivy-backward-kill-word)
231 (define-key map (kbd "C-d") 'ivy-delete-char)
232 (define-key map (kbd "C-f") 'ivy-forward-char)
233 (define-key map (kbd "M-d") 'ivy-kill-word)
234 (define-key map (kbd "M-<") 'ivy-beginning-of-buffer)
235 (define-key map (kbd "M->") 'ivy-end-of-buffer)
236 (define-key map (kbd "M-n") 'ivy-next-history-element)
237 (define-key map (kbd "M-p") 'ivy-previous-history-element)
238 (define-key map (kbd "C-g") 'minibuffer-keyboard-quit)
239 (define-key map (kbd "C-v") 'ivy-scroll-up-command)
240 (define-key map (kbd "M-v") 'ivy-scroll-down-command)
241 (define-key map (kbd "C-M-n") 'ivy-next-line-and-call)
242 (define-key map (kbd "C-M-p") 'ivy-previous-line-and-call)
243 (define-key map (kbd "M-q") 'ivy-toggle-regexp-quote)
244 (define-key map (kbd "M-j") 'ivy-yank-word)
245 (define-key map (kbd "M-i") 'ivy-insert-current)
246 (define-key map (kbd "C-o") 'hydra-ivy/body)
247 (define-key map (kbd "M-o") 'ivy-dispatching-done)
248 (define-key map (kbd "C-M-o") 'ivy-dispatching-call)
249 (define-key map (kbd "C-k") 'ivy-kill-line)
250 (define-key map (kbd "S-SPC") 'ivy-restrict-to-matches)
251 (define-key map (kbd "M-w") 'ivy-kill-ring-save)
252 (define-key map (kbd "C-'") 'ivy-avy)
253 (define-key map (kbd "C-M-a") 'ivy-read-action)
254 (define-key map (kbd "C-c C-o") 'ivy-occur)
255 (define-key map (kbd "C-c C-a") 'ivy-toggle-ignore)
256 (define-key map (kbd "C-h m") 'ivy-help)
258 "Keymap used in the minibuffer.")
259 (autoload 'hydra-ivy/body "ivy-hydra" "" t)
262 (let ((map (make-sparse-keymap)))
263 (define-key map [remap switch-to-buffer]
265 (define-key map [remap switch-to-buffer-other-window]
266 'ivy-switch-buffer-other-window)
268 "Keymap for `ivy-mode'.")
271 (cl-defstruct ivy-state
273 predicate require-match initial-input
274 history preselect keymap update-fn sort
275 ;; The window in which `ivy-read' was called
277 ;; The buffer in which `ivy-read' was called
279 ;; The value of `ivy-text' to be used by `ivy-occur'
285 ;; When this is non-nil, call it for each input change to get new candidates
287 ;; A lambda that transforms candidates only for display
288 display-transformer-fn
291 (defvar ivy-last (make-ivy-state)
292 "The last parameters passed to `ivy-read'.
294 This should eventually become a stack so that you could use
295 `ivy-read' recursively.")
297 (defsubst ivy-set-action (action)
298 (setf (ivy-state-action ivy-last) action))
300 (defun ivy-thing-at-point ()
301 "Return a string that corresponds to the current thing at point."
303 (thing-at-point 'url)
306 (cond ((stringp (setq s (thing-at-point 'symbol)))
307 (if (string-match "\\`[`']?\\(.*?\\)'?\\'" s)
310 ((looking-at "(+\\(\\(?:\\sw\\|\\s_\\)+\\)\\_>")
311 (match-string-no-properties 1))
315 (defvar ivy-history nil
316 "History list of candidates entered in the minibuffer.
318 Maximum length of the history list is determined by the value
319 of `history-length'.")
321 (defvar ivy--directory nil
322 "Current directory when completing file names.")
324 (defvar ivy--length 0
325 "Store the amount of viable candidates.")
328 "Store the user's string as it is typed in.")
330 (defvar ivy--current ""
331 "Current candidate.")
334 "Store the index of the current candidate.")
337 "Store 'done if the completion was successfully selected.
338 Otherwise, store nil.")
340 (defvar ivy--all-candidates nil
341 "Store the candidates passed to `ivy-read'.")
343 (defvar ivy--extra-candidates '((original-source))
344 "Store candidates added by the extra sources.
346 This is an internal-use alist. Each key is a function name, or
347 original-source (which represents where the current dynamic
348 candidates should go).
350 Each value is an evaluation of the function, in case of static
351 sources. These values will subsequently be filtered on `ivy-text'.
353 This variable is set by `ivy-read' and used by `ivy--set-candidates'.")
355 (defvar ivy-use-ignore t
356 "Store policy for user-configured candidate filtering.")
358 (defvar ivy--default nil
359 "Default initial input.")
361 (defvar ivy--prompt nil
362 "Store the format-style prompt.
363 When non-nil, it should contain at least one %d.")
365 (defvar ivy--prompt-extra ""
366 "Temporary modifications to the prompt.")
368 (defvar ivy--old-re nil
369 "Store the old regexp.")
371 (defvar ivy--old-cands nil
372 "Store the candidates matched by `ivy--old-re'.")
374 (defvar ivy--regex-function 'ivy--regex
375 "Current function for building a regex.")
377 (defvar ivy--subexps 0
378 "Number of groups in the current `ivy--regex'.")
380 (defvar ivy--full-length nil
381 "When :dynamic-collection is non-nil, this can be the total amount of candidates.")
383 (defvar ivy--old-text ""
384 "Store old `ivy-text' for dynamic completion.")
386 (defvar ivy-case-fold-search 'auto
387 "Store the current overriding `case-fold-search'.")
389 (defvar Info-current-file)
392 (unless (fboundp 'defvar-local)
393 (defmacro defvar-local (var val &optional docstring)
394 "Define VAR as a buffer-local variable with default value VAL."
395 (declare (debug defvar) (doc-string 3))
396 (list 'progn (list 'defvar var val docstring)
397 (list 'make-variable-buffer-local (list 'quote var)))))
398 (unless (fboundp 'setq-local)
399 (defmacro setq-local (var val)
400 "Set variable VAR to value VAL in current buffer."
401 (list 'set (list 'make-local-variable (list 'quote var)) val))))
403 (defmacro ivy-quit-and-run (&rest body)
404 "Quit the minibuffer and run BODY afterwards."
406 (put 'quit 'error-message "")
409 (put 'quit 'error-message "Quit")
411 (minibuffer-keyboard-quit)))
413 (defun ivy-exit-with-action (action)
414 "Quit the minibuffer and call ACTION afterwards."
418 (ivy-set-action ',(ivy-state-action ivy-last))))
419 (setq ivy-exit 'done)
422 (defmacro with-ivy-window (&rest body)
423 "Execute BODY in the window from which `ivy-read' was called."
426 `(with-selected-window (ivy--get-window ivy-last)
429 (defun ivy--done (text)
430 "Insert TEXT and exit minibuffer."
431 (if (and ivy--directory
432 (not (eq (ivy-state-history ivy-last) 'grep-files-history)))
433 (insert (setq ivy--current (expand-file-name
434 text ivy--directory)))
435 (insert (setq ivy--current text)))
436 (setq ivy-exit 'done)
441 "Exit the minibuffer with the selected candidate."
443 (delete-minibuffer-contents)
444 (cond ((> ivy--length 0)
445 (ivy--done ivy--current))
446 ((memq (ivy-state-collection ivy-last)
447 '(read-file-name-internal internal-complete-buffer))
448 (if (or (not (eq confirm-nonexistent-file-or-buffer t))
449 (equal " (confirm)" ivy--prompt-extra))
451 (setq ivy--prompt-extra " (confirm)")
454 ((memq (ivy-state-require-match ivy-last)
455 '(nil confirm confirm-after-completion))
456 (ivy--done ivy-text))
458 (setq ivy--prompt-extra " (match required)")
462 (defun ivy-read-action ()
463 "Change the action to one of the available ones.
465 Return nil for `minibuffer-keyboard-quit' or wrong key during the
466 selection, non-nil otherwise."
468 (let ((actions (ivy-state-action ivy-last)))
469 (if (null (ivy--actionp actions))
471 (let* ((hint (concat (if (eq this-command 'ivy-read-action)
480 'face 'font-lock-builtin-face)
485 (resize-mini-windows 'grow-only)
486 (key (string (read-key hint)))
487 (action-idx (cl-position-if
488 (lambda (x) (equal (car x) key))
490 (cond ((string= key "
\a")
493 (message "%s is not bound" key)
497 (setcar actions (1+ action-idx))
498 (ivy-set-action actions)))))))
500 (defun ivy-dispatching-done ()
501 "Select one of the available actions and call `ivy-done'."
503 (when (ivy-read-action)
506 (defun ivy-dispatching-call ()
507 "Select one of the available actions and call `ivy-call'."
509 (let ((actions (copy-sequence (ivy-state-action ivy-last))))
511 (when (ivy-read-action)
513 (ivy-set-action actions))))
515 (defun ivy-build-tramp-name (x)
516 "Reconstruct X into a path.
517 Is is a cons cell, related to `tramp-get-completion-function'."
521 (concat user "@" domain)
524 (declare-function tramp-get-completion-function "tramp")
525 (declare-function Info-find-node "info")
527 (defun ivy-alt-done (&optional arg)
528 "Exit the minibuffer with the selected candidate.
529 When ARG is t, exit with current text, ignoring the candidates."
532 (ivy-immediate-done))
534 (ivy--directory-done))
535 ((eq (ivy-state-collection ivy-last) 'Info-read-node-name-1)
536 (if (member ivy--current '("(./)" "(../)"))
538 (ivy-read "Go to file: " 'read-file-name-internal
541 (expand-file-name x ivy--directory)
547 (defun ivy--directory-done ()
548 "Handle exit from the minibuffer when completing file names."
551 ((equal ivy-text "/sudo::")
552 (setq dir (concat ivy-text ivy--directory))
557 (not (string= ivy-text ""))
558 (setq dir (ivy-expand-file-if-directory ivy-text)))
561 (not (string= ivy--current "./"))
562 (setq dir (ivy-expand-file-if-directory ivy--current))))
565 ((or (and (equal ivy--directory "/")
566 (string-match "\\`[^/]+:.*:.*\\'" ivy-text))
567 (string-match "\\`/[^/]+:.*:.*\\'" ivy-text))
569 ((or (and (equal ivy--directory "/")
571 "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
574 "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
576 (setq ivy-text ivy--current))))
578 "\\`/\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
580 (let ((method (match-string 1 ivy-text))
581 (user (match-string 2 ivy-text))
582 (rest (match-string 3 ivy-text))
585 (dolist (x (tramp-get-completion-function method))
586 (setq res (append res (funcall (car x) (cadr x)))))
587 (setq res (delq nil res))
591 (setq res (cl-delete-duplicates res :test #'equal))
592 (let* ((old-ivy-last ivy-last)
593 (enable-recursive-minibuffers t)
594 (host (ivy-read "user@host: "
595 (mapcar #'ivy-build-tramp-name res)
596 :initial-input rest)))
597 (setq ivy-last old-ivy-last)
599 (setq ivy--directory "/")
600 (ivy--cd (concat "/" method ":" host ":"))))))
604 (defun ivy-expand-file-if-directory (file-name)
605 "Expand FILE-NAME as directory.
606 When this directory doesn't exist, return nil."
607 (when (stringp file-name)
609 ;; Ignore host name must not match method "ssh"
611 (file-name-as-directory
612 (expand-file-name file-name ivy--directory)))))
613 (when (and full-name (file-directory-p full-name))
616 (defcustom ivy-tab-space nil
617 "When non-nil, `ivy-partial-or-done' should insert a space."
620 (defun ivy-partial-or-done ()
621 "Complete the minibuffer text as much as possible.
622 If the text hasn't changed as a result, forward to `ivy-alt-done'."
624 (if (and (eq (ivy-state-collection ivy-last) #'read-file-name-internal)
625 (or (and (equal ivy--directory "/")
626 (string-match "\\`[^/]+:.*\\'" ivy-text))
627 (string-match "\\`/" ivy-text)))
628 (let ((default-directory ivy--directory)
630 (minibuffer-complete)
631 (setq ivy-text (ivy--input))
632 (when (setq dir (ivy-expand-file-if-directory ivy-text))
635 (when (or (eq this-command last-command)
639 (defun ivy-partial ()
640 "Complete the minibuffer text as much as possible."
642 (let* ((parts (or (split-string ivy-text " " t) (list "")))
643 (postfix (car (last parts)))
644 (completion-ignore-case t)
645 (startp (string-match "^\\^" postfix))
646 (new (try-completion (if startp
647 (substring postfix 1)
649 (mapcar (lambda (str)
650 (let ((i (string-match postfix str)))
654 (cond ((eq new t) nil)
655 ((string= new ivy-text) nil)
657 (delete-region (minibuffer-prompt-end) (point-max))
662 (insert (mapconcat #'identity parts " ")
663 (if ivy-tab-space " " ""))
666 (defun ivy-immediate-done ()
667 "Exit the minibuffer with the current input."
669 (delete-minibuffer-contents)
670 (insert (setq ivy--current
672 (expand-file-name ivy-text ivy--directory)
674 (setq ivy-exit 'done)
679 "Resume the last completion session."
681 (if (null (ivy-state-action ivy-last))
682 (user-error "The last session isn't compatible with `ivy-resume'")
683 (when (eq (ivy-state-caller ivy-last) 'swiper)
684 (switch-to-buffer (ivy-state-buffer ivy-last)))
685 (with-current-buffer (ivy-state-buffer ivy-last)
687 (ivy-state-prompt ivy-last)
688 (ivy-state-collection ivy-last)
689 :predicate (ivy-state-predicate ivy-last)
690 :require-match (ivy-state-require-match ivy-last)
691 :initial-input ivy-text
692 :history (ivy-state-history ivy-last)
693 :preselect (unless (eq (ivy-state-collection ivy-last)
694 'read-file-name-internal)
696 :keymap (ivy-state-keymap ivy-last)
697 :update-fn (ivy-state-update-fn ivy-last)
698 :sort (ivy-state-sort ivy-last)
699 :action (ivy-state-action ivy-last)
700 :unwind (ivy-state-unwind ivy-last)
701 :re-builder (ivy-state-re-builder ivy-last)
702 :matcher (ivy-state-matcher ivy-last)
703 :dynamic-collection (ivy-state-dynamic-collection ivy-last)
704 :caller (ivy-state-caller ivy-last)))))
706 (defvar-local ivy-calling nil
707 "When non-nil, call the current action when `ivy--index' changes.")
709 (defun ivy-set-index (index)
710 "Set `ivy--index' to INDEX."
711 (setq ivy--index index)
716 (defun ivy-beginning-of-buffer ()
717 "Select the first completion candidate."
721 (defun ivy-end-of-buffer ()
722 "Select the last completion candidate."
724 (ivy-set-index (1- ivy--length)))
726 (defun ivy-scroll-up-command ()
727 "Scroll the candidates upward by the minibuffer height."
729 (ivy-set-index (min (1- (+ ivy--index ivy-height))
732 (defun ivy-scroll-down-command ()
733 "Scroll the candidates downward by the minibuffer height."
735 (ivy-set-index (max (1+ (- ivy--index ivy-height))
738 (defun ivy-minibuffer-grow ()
739 "Grow the minibuffer window by 1 line."
741 (setq-local max-mini-window-height
742 (cl-incf ivy-height)))
744 (defun ivy-minibuffer-shrink ()
745 "Shrink the minibuffer window by 1 line."
747 (unless (<= ivy-height 2)
748 (setq-local max-mini-window-height
749 (cl-decf ivy-height))
750 (window-resize (selected-window) -1)))
752 (defun ivy-next-line (&optional arg)
753 "Move cursor vertically down ARG candidates."
755 (setq arg (or arg 1))
756 (let ((index (+ ivy--index arg)))
757 (if (> index (1- ivy--length))
759 (ivy-beginning-of-buffer)
760 (ivy-set-index (1- ivy--length)))
761 (ivy-set-index index))))
763 (defun ivy-next-line-or-history (&optional arg)
764 "Move cursor vertically down ARG candidates.
765 If the input is empty, select the previous history element instead."
767 (if (string= ivy-text "")
768 (ivy-previous-history-element 1)
769 (ivy-next-line arg)))
771 (defun ivy-previous-line (&optional arg)
772 "Move cursor vertically up ARG candidates."
774 (setq arg (or arg 1))
775 (let ((index (- ivy--index arg)))
780 (ivy-set-index index))))
782 (defun ivy-previous-line-or-history (arg)
783 "Move cursor vertically up ARG candidates.
784 If the input is empty, select the previous history element instead."
786 (when (string= ivy-text "")
787 (ivy-previous-history-element 1))
788 (ivy-previous-line arg))
790 (defun ivy-toggle-calling ()
791 "Flip `ivy-calling'."
793 (when (setq ivy-calling (not ivy-calling))
796 (defun ivy-toggle-ignore ()
797 "Toggle user-configured candidate filtering."
799 (setq ivy-use-ignore (null ivy-use-ignore))
801 (setq ivy--old-cands nil))
803 (defun ivy--get-action (state)
804 "Get the action function from STATE."
805 (let ((action (ivy-state-action state)))
807 (if (functionp action)
809 (cadr (nth (car action) action))))))
811 (defun ivy--get-window (state)
812 "Get the window from STATE."
813 (if (ivy-state-p state)
814 (let ((window (ivy-state-window state)))
815 (if (window-live-p window)
817 (if (= (length (window-list)) 1)
822 (defun ivy--actionp (x)
823 "Return non-nil when X is a list of actions."
824 (and x (listp x) (not (eq (car x) 'closure))))
826 (defun ivy-next-action ()
827 "When the current action is a list, scroll it forwards."
829 (let ((action (ivy-state-action ivy-last)))
830 (when (ivy--actionp action)
831 (unless (>= (car action) (1- (length action)))
832 (cl-incf (car action))))))
834 (defun ivy-prev-action ()
835 "When the current action is a list, scroll it backwards."
837 (let ((action (ivy-state-action ivy-last)))
838 (when (ivy--actionp action)
839 (unless (<= (car action) 1)
840 (cl-decf (car action))))))
842 (defun ivy-action-name ()
843 "Return the name associated with the current action."
844 (let ((action (ivy-state-action ivy-last)))
845 (if (ivy--actionp action)
849 (nth 2 (nth (car action) action)))
852 (defvar ivy-inhibit-action nil
853 "When non-nil, `ivy-call' does nothing.
857 (let* ((ivy-inhibit-action t)
858 (str (counsel-locate \"lispy.el\")))
859 ;; do whatever with str - the corresponding file will not be opened
863 "Call the current action without exiting completion."
865 (unless ivy-inhibit-action
866 (let ((action (ivy--get-action ivy-last)))
868 (let* ((collection (ivy-state-collection ivy-last))
869 (x (if (and (consp collection)
870 (consp (car collection)))
871 (cdr (assoc ivy--current collection))
872 (if (equal ivy--current "")
875 (prog1 (funcall action x)
876 (unless (or (eq ivy-exit 'done)
877 (equal (selected-window)
878 (active-minibuffer-window))
879 (null (active-minibuffer-window)))
880 (select-window (active-minibuffer-window)))))))))
882 (defun ivy-next-line-and-call (&optional arg)
883 "Move cursor vertically down ARG candidates.
884 Call the permanent action if possible."
890 (defun ivy-previous-line-and-call (&optional arg)
891 "Move cursor vertically down ARG candidates.
892 Call the permanent action if possible."
894 (ivy-previous-line arg)
898 (defun ivy-previous-history-element (arg)
899 "Forward to `previous-history-element' with ARG."
901 (previous-history-element arg)
904 (ivy--maybe-scroll-history))
906 (defun ivy-next-history-element (arg)
907 "Forward to `next-history-element' with ARG."
909 (if (and (= minibuffer-history-position 0)
912 (insert ivy--default)
913 (when (and (with-ivy-window (derived-mode-p 'prog-mode))
914 (not (file-exists-p ivy--default))
915 (not (ivy-state-dynamic-collection ivy-last))
916 (> (point) (minibuffer-prompt-end)))
919 (goto-char (minibuffer-prompt-end))
921 (forward-char (+ 2 (length ivy--default)))))
922 (next-history-element arg))
925 (ivy--maybe-scroll-history))
927 (defvar ivy-ffap-url-functions nil
928 "List of functions that check if the point is on a URL.")
930 (defun ivy--cd-maybe ()
931 "Check if the current input points to a different directory.
932 If so, move to that directory, while keeping only the file name."
934 (let ((input (ivy--input))
936 (if (setq url (or (ffap-url-p input)
941 ivy-ffap-url-functions
942 :initial-value nil))))
943 (ivy-exit-with-action
945 (funcall ffap-url-fetcher url)))
946 (setq input (expand-file-name input))
947 (let ((file (file-name-nondirectory input))
948 (dir (expand-file-name (file-name-directory input))))
949 (if (string= dir ivy--directory)
951 (delete-minibuffer-contents)
956 (defun ivy--maybe-scroll-history ()
957 "If the selected history element has an index, scroll there."
958 (let ((idx (ignore-errors
960 (minibuffer-prompt-end)
964 (setq ivy--index idx))))
967 "When completing file names, move to directory DIR."
968 (if (null ivy--directory)
970 (setq ivy--old-cands nil)
971 (setq ivy--old-re nil)
973 (setq ivy--all-candidates
974 (ivy--sorted-files (setq ivy--directory dir)))
976 (delete-minibuffer-contents)))
978 (defun ivy-backward-delete-char ()
979 "Forward to `backward-delete-char'.
980 On error (read-only), call `ivy-on-del-error-function'."
982 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
984 (ivy--cd (file-name-directory
990 (backward-delete-char 1)
992 (when ivy-on-del-error-function
993 (funcall ivy-on-del-error-function))))))
995 (defun ivy-delete-char (arg)
996 "Forward to `delete-char' ARG."
998 (unless (= (point) (line-end-position))
1001 (defun ivy-forward-char (arg)
1002 "Forward to `forward-char' ARG."
1004 (unless (= (point) (line-end-position))
1005 (forward-char arg)))
1007 (defun ivy-kill-word (arg)
1008 "Forward to `kill-word' ARG."
1010 (unless (= (point) (line-end-position))
1013 (defun ivy-kill-line ()
1014 "Forward to `kill-line'."
1017 (kill-region (minibuffer-prompt-end) (point))
1020 (defun ivy-backward-kill-word ()
1021 "Forward to `backward-kill-word'."
1023 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
1025 (ivy--cd (file-name-directory
1026 (directory-file-name
1033 (delete-region (point) pt)))))
1035 (defvar ivy--regexp-quote 'regexp-quote
1036 "Store the regexp quoting state.")
1038 (defun ivy-toggle-regexp-quote ()
1039 "Toggle the regexp quoting."
1041 (setq ivy--old-re nil)
1042 (cl-rotatef ivy--regex-function ivy--regexp-quote))
1044 (defvar avy-all-windows)
1047 (defvar avy-keys-alist)
1049 (defvar avy-styles-alist)
1050 (declare-function avy--process "ext:avy")
1051 (declare-function avy--style-fn "ext:avy")
1053 (eval-after-load 'avy
1054 '(add-to-list 'avy-styles-alist '(ivy-avy . pre)))
1057 "Jump to one of the current ivy candidates."
1059 (unless (require 'avy nil 'noerror)
1060 (error "Package avy isn't installed"))
1061 (let* ((avy-all-windows nil)
1062 (avy-keys (or (cdr (assq 'ivy-avy avy-keys-alist))
1064 (avy-style (or (cdr (assq 'ivy-avy
1074 (goto-char (point-min))
1076 (while (< (point) (point-max))
1082 (setq avy-action #'identity)
1084 (nreverse candidates)
1085 (avy--style-fn avy-style)))))
1086 (ivy-set-index (- (line-number-at-pos candidate) 2))
1090 (defun ivy-sort-file-function-default (x y)
1091 "Compare two files X and Y.
1092 Prioritize directories."
1093 (if (get-text-property 0 'dirp x)
1094 (if (get-text-property 0 'dirp y)
1097 (if (get-text-property 0 'dirp y)
1101 (defcustom ivy-sort-functions-alist
1102 '((read-file-name-internal . ivy-sort-file-function-default)
1103 (internal-complete-buffer . nil)
1104 (counsel-git-grep-function . nil)
1105 (Man-goto-section . nil)
1108 "An alist of sorting functions for each collection function.
1109 Interactive functions that call completion fit in here as well.
1111 Nil means no sorting, which is useful to turn off the sorting for
1112 functions that have candidates in the natural buffer order, like
1113 `org-refile' or `Man-goto-section'.
1115 The entry associated with t is used for all fall-through cases.
1117 See also `ivy-sort-max-size'."
1121 (const :tag "Fall-through" t)
1122 (symbol :tag "Collection"))
1124 (const :tag "Plain sort" string-lessp)
1125 (const :tag "File sort" ivy-sort-file-function-default)
1126 (const :tag "No sort" nil)))
1129 (defvar ivy-index-functions-alist
1130 '((swiper . ivy-recompute-index-swiper)
1131 (swiper-multi . ivy-recompute-index-swiper)
1132 (counsel-git-grep . ivy-recompute-index-swiper)
1133 (counsel-grep . ivy-recompute-index-swiper-async)
1134 (t . ivy-recompute-index-zero))
1135 "An alist of index recomputing functions for each collection function.
1136 When the input changes, the appropriate function returns an
1137 integer - the index of the matched candidate that should be
1140 (defvar ivy-re-builders-alist
1141 '((t . ivy--regex-plus))
1142 "An alist of regex building functions for each collection function.
1144 Each key is (in order of priority):
1145 1. The actual collection function, e.g. `read-file-name-internal'.
1146 2. The symbol passed by :caller into `ivy-read'.
1150 Each value is a function that should take a string and return a
1151 valid regex or a regex sequence (see below).
1153 Possible choices: `ivy--regex', `regexp-quote',
1154 `ivy--regex-plus', `ivy--regex-fuzzy'.
1156 If a function returns a list, it should format like this:
1157 '((\"matching-regexp\" . t) (\"non-matching-regexp\") ...).
1159 The matches will be filtered in a sequence, you can mix the
1160 regexps that should match and that should not match as you
1163 (defvar ivy-initial-inputs-alist
1164 '((org-refile . "^")
1165 (org-agenda-refile . "^")
1166 (org-capture-refile . "^")
1168 (counsel-describe-function . "^")
1169 (counsel-describe-variable . "^")
1172 "Command to initial input table.")
1174 (defcustom ivy-sort-max-size 30000
1175 "Sorting won't be done for collections larger than this."
1178 (defun ivy--sorted-files (dir)
1179 "Return the list of files in DIR.
1180 Directories come first."
1181 (let* ((default-directory dir)
1182 (seq (all-completions "" 'read-file-name-internal))
1186 (setq seq (delete "./" (delete "../" seq)))
1187 (when (eq (setq sort-fn (cdr (assoc 'read-file-name-internal
1188 ivy-sort-functions-alist)))
1189 #'ivy-sort-file-function-default)
1190 (setq seq (mapcar (lambda (x)
1191 (propertize x 'dirp (string-match-p "/\\'" x)))
1194 (setq seq (cl-sort seq sort-fn)))
1195 (dolist (dir ivy-extra-directories)
1199 (defvar ivy-recursive-restore t
1200 "When non-nil, restore the above state when exiting the minibuffer.
1201 This variable is let-bound to nil by functions that take care of
1202 the restoring themselves.")
1205 (cl-defun ivy-read (prompt collection
1207 predicate require-match initial-input
1208 history preselect keymap update-fn sort
1209 action unwind re-builder matcher dynamic-collection caller)
1210 "Read a string in the minibuffer, with completion.
1212 PROMPT is a format string, normally ending in a colon and a
1213 space; %d anywhere in the string is replaced by the current
1214 number of matching candidates. For the literal % character,
1215 escape it with %%. See also `ivy-count-format'.
1217 COLLECTION is either a list of strings, a function, an alist, or
1220 If INITIAL-INPUT is not nil, then insert that input in the
1221 minibuffer initially.
1223 KEYMAP is composed with `ivy-minibuffer-map'.
1225 If PRESELECT is not nil, then select the corresponding candidate
1226 out of the ones that match the INITIAL-INPUT.
1228 UPDATE-FN is called each time the current candidate(s) is changed.
1230 When SORT is t, use `ivy-sort-functions-alist' for sorting.
1232 ACTION is a lambda function to call after selecting a result. It
1233 takes a single string argument.
1235 UNWIND is a lambda function to call before exiting.
1237 RE-BUILDER is a lambda function to call to transform text into a
1240 MATCHER is to override matching.
1242 DYNAMIC-COLLECTION is a boolean to specify if the list of
1243 candidates is updated after each input by calling COLLECTION.
1245 CALLER is a symbol to uniquely identify the caller to `ivy-read'.
1246 It is used, along with COLLECTION, to determine which
1247 customizations apply to the current completion session."
1248 (let ((extra-actions (delete-dups
1249 (append (plist-get ivy--actions-list t)
1250 (plist-get ivy--actions-list this-command)
1251 (plist-get ivy--actions-list caller)))))
1254 (cond ((functionp action)
1256 ("o" ,action "default")
1260 ("o" identity "default")
1263 (delete-dups (append action extra-actions)))))))
1264 (let ((extra-sources (plist-get ivy--sources-list caller)))
1267 (setq ivy--extra-candidates nil)
1268 (dolist (source extra-sources)
1269 (cond ((equal source '(original-source))
1270 (setq ivy--extra-candidates
1271 (cons source ivy--extra-candidates)))
1272 ((null (cdr source))
1273 (setq ivy--extra-candidates
1275 (list (car source) (funcall (car source)))
1276 ivy--extra-candidates))))))
1277 (setq ivy--extra-candidates '((original-source)))))
1278 (let ((recursive-ivy-last (and (active-minibuffer-window) ivy-last))
1280 (plist-get ivy--display-transformers-list
1281 (or caller (and (functionp collection)
1286 :collection collection
1287 :predicate predicate
1288 :require-match require-match
1289 :initial-input initial-input
1291 :preselect preselect
1293 :update-fn update-fn
1296 :window (selected-window)
1297 :buffer (current-buffer)
1299 :re-builder re-builder
1301 :dynamic-collection dynamic-collection
1302 :display-transformer-fn transformer-fn
1304 (ivy--reset-state ivy-last)
1307 (minibuffer-with-setup-hook
1308 #'ivy--minibuffer-setup
1309 (let* ((hist (or history 'ivy-history))
1310 (minibuffer-completion-table collection)
1311 (minibuffer-completion-predicate predicate)
1312 (resize-mini-windows (cond
1313 ((display-graphic-p) nil)
1314 ((null resize-mini-windows) 'grow-only)
1315 (t resize-mini-windows))))
1316 (read-from-minibuffer
1318 (ivy-state-initial-input ivy-last)
1319 (make-composed-keymap keymap ivy-minibuffer-map)
1322 (when (eq ivy-exit 'done)
1323 (let ((item (if ivy--directory
1326 (unless (equal item "")
1327 (set hist (cons (propertize item 'ivy-index ivy--index)
1329 (cdr (symbol-value hist))))))))
1331 (remove-hook 'post-command-hook #'ivy--exhibit)
1332 (when (setq unwind (ivy-state-unwind ivy-last))
1334 (unless (eq ivy-exit 'done)
1335 (when recursive-ivy-last
1336 (ivy--reset-state (setq ivy-last recursive-ivy-last)))))
1338 (when (numberp (car-safe (ivy-state-action ivy-last)))
1339 (setcar (ivy-state-action ivy-last) 1))
1340 (when (and recursive-ivy-last
1341 ivy-recursive-restore)
1342 (ivy--reset-state (setq ivy-last recursive-ivy-last))))))
1344 (defun ivy--reset-state (state)
1345 "Reset the ivy to STATE.
1346 This is useful for recursive `ivy-read'."
1347 (let ((prompt (or (ivy-state-prompt state) ""))
1348 (collection (ivy-state-collection state))
1349 (predicate (ivy-state-predicate state))
1350 (history (ivy-state-history state))
1351 (preselect (ivy-state-preselect state))
1352 (sort (ivy-state-sort state))
1353 (re-builder (ivy-state-re-builder state))
1354 (dynamic-collection (ivy-state-dynamic-collection state))
1355 (initial-input (ivy-state-initial-input state))
1356 (require-match (ivy-state-require-match state))
1357 (caller (ivy-state-caller state)))
1358 (unless initial-input
1359 (setq initial-input (cdr (assoc this-command
1360 ivy-initial-inputs-alist))))
1361 (setq ivy--directory nil)
1362 (setq ivy-case-fold-search 'auto)
1363 (setq ivy--regex-function
1365 (and (functionp collection)
1366 (cdr (assoc collection ivy-re-builders-alist)))
1368 (cdr (assoc caller ivy-re-builders-alist)))
1369 (cdr (assoc this-command ivy-re-builders-alist))
1370 (cdr (assoc t ivy-re-builders-alist))
1372 (setq ivy--subexps 0)
1373 (setq ivy--regexp-quote 'regexp-quote)
1374 (setq ivy--old-text "")
1375 (setq ivy--full-length nil)
1377 (setq ivy-calling nil)
1378 (setq ivy-use-ignore t)
1380 (cond ((eq collection 'Info-read-node-name-1)
1381 (if (equal Info-current-file "dir")
1383 (mapcar (lambda (x) (format "(%s)" x))
1384 (cl-delete-duplicates
1385 (all-completions "(" collection predicate)
1387 (setq coll (all-completions "" collection predicate))))
1388 ((eq collection 'read-file-name-internal)
1389 (setq ivy--directory default-directory)
1392 (let ((preselect-directory (file-name-directory preselect)))
1393 (unless (or (null preselect-directory)
1394 (string= preselect-directory
1396 (setq ivy--directory preselect-directory))
1398 (ivy-state-preselect state)
1399 (setq preselect (file-name-nondirectory preselect)))))
1400 (setq coll (ivy--sorted-files ivy--directory))
1402 (unless (or require-match
1403 (equal initial-input default-directory)
1404 (equal initial-input ""))
1405 (setq coll (cons initial-input coll)))
1406 (unless (and (ivy-state-action ivy-last)
1407 (not (equal (ivy--get-action ivy-last) 'identity)))
1408 (setq initial-input nil))))
1409 ((eq collection 'internal-complete-buffer)
1410 (setq coll (ivy--buffer-list "" ivy-use-virtual-buffers)))
1412 (setq coll (funcall collection ivy-text)))
1413 ((or (functionp collection)
1414 (byte-code-function-p collection)
1415 (vectorp collection)
1416 (and (consp collection) (listp (car collection)))
1417 (hash-table-p collection)
1418 (and (listp collection) (symbolp (car collection))))
1419 (setq coll (all-completions "" collection predicate)))
1421 (setq coll collection)))
1423 (if (and (functionp collection)
1424 (setq sort-fn (assoc collection ivy-sort-functions-alist)))
1425 (when (and (setq sort-fn (cdr sort-fn))
1426 (not (eq collection 'read-file-name-internal)))
1427 (setq coll (cl-sort coll sort-fn)))
1428 (unless (eq history 'org-refile-history)
1429 (if (and (setq sort-fn (cdr (assoc t ivy-sort-functions-alist)))
1430 (<= (length coll) ivy-sort-max-size))
1431 (setq coll (cl-sort (copy-sequence coll) sort-fn))))))
1433 (unless (or (and require-match
1434 (not (eq collection 'internal-complete-buffer)))
1436 (let ((re (regexp-quote preselect)))
1437 (cl-find-if (lambda (x) (string-match re x))
1439 (setq coll (cons preselect coll))))
1440 (setq ivy--old-re nil)
1441 (setq ivy--old-cands nil)
1442 (when (integerp preselect)
1443 (setq ivy--old-re "")
1444 (setq ivy--index preselect))
1446 ;; Needed for anchor to work
1447 (setq ivy--old-cands coll)
1448 (setq ivy--old-cands (ivy--filter initial-input coll)))
1449 (setq ivy--all-candidates coll)
1450 (unless (integerp preselect)
1451 (setq ivy--index (or
1452 (and dynamic-collection
1455 (ivy--preselect-index
1463 (if (region-active-p)
1467 (ivy-thing-at-point)))
1469 (cond ((string-match "%.*d" prompt)
1471 ((null ivy-count-format)
1473 "`ivy-count-format' can't be nil. Set it to an empty string instead"))
1474 ((string-match "%d.*%d" ivy-count-format)
1475 (let ((w (length (number-to-string
1476 (length ivy--all-candidates))))
1477 (s (copy-sequence ivy-count-format)))
1478 (string-match "%d" s)
1480 (string-match "%d" s (match-end 0))
1481 (setq s (replace-match (format "%%-%dd" w) nil nil s))
1482 (string-match "%d" s)
1483 (concat (replace-match (format "%%%dd" w) nil nil s)
1485 ((string-match "%.*d" ivy-count-format)
1486 (concat ivy-count-format prompt))
1491 (setf (ivy-state-initial-input ivy-last) initial-input)))
1494 (defun ivy-completing-read (prompt collection
1495 &optional predicate require-match initial-input
1496 history def inherit-input-method)
1497 "Read a string in the minibuffer, with completion.
1499 This interface conforms to `completing-read' and can be used for
1500 `completing-read-function'.
1502 PROMPT is a string that normally ends in a colon and a space.
1503 COLLECTION is either a list of strings, an alist, an obarray, or a hash table.
1504 PREDICATE limits completion to a subset of COLLECTION.
1505 REQUIRE-MATCH is a boolean value. See `completing-read'.
1506 INITIAL-INPUT is a string inserted into the minibuffer initially.
1507 HISTORY is a list of previously selected inputs.
1508 DEF is the default value.
1509 INHERIT-INPUT-METHOD is currently ignored."
1510 (if (memq this-command '(tmm-menubar tmm-shortcut))
1511 (completing-read-default prompt collection
1512 predicate require-match
1513 initial-input history
1514 def inherit-input-method)
1515 ;; See the doc of `completing-read'.
1516 (when (consp history)
1517 (when (numberp (cdr history))
1518 (setq initial-input (nth (1- (cdr history))
1519 (symbol-value (car history)))))
1520 (setq history (car history)))
1521 (ivy-read (replace-regexp-in-string "%" "%%" prompt)
1523 :predicate predicate
1524 :require-match require-match
1525 :initial-input (if (consp initial-input)
1527 (if (and (stringp initial-input)
1528 (string-match "\\+" initial-input))
1529 (replace-regexp-in-string
1530 "\\+" "\\\\+" initial-input)
1532 :preselect (if (listp def) (car def) def)
1536 (let ((sort (assoc this-command ivy-sort-functions-alist)))
1541 (defvar ivy-completion-beg nil
1542 "Completion bounds start.")
1544 (defvar ivy-completion-end nil
1545 "Completion bounds end.")
1547 (defun ivy-completion-in-region-action (str)
1548 "Insert STR, erasing the previous one.
1549 The previous string is between `ivy-completion-beg' and `ivy-completion-end'."
1552 (when ivy-completion-beg
1555 ivy-completion-end))
1556 (setq ivy-completion-beg
1557 (move-marker (make-marker) (point)))
1559 (setq ivy-completion-end
1560 (move-marker (make-marker) (point))))))
1562 (defun ivy-completion-common-length (str)
1563 "Return the length of the first 'completions-common-part face in STR."
1566 (while (and (<= pos len)
1567 (let ((prop (get-text-property pos 'face str)))
1568 (not (eq 'completions-common-part
1569 (if (listp prop) (car prop) prop)))))
1570 (setq pos (1+ pos)))
1572 (or (next-single-property-change pos 'face str) len)
1575 (defun ivy-completion-in-region (start end collection &optional predicate)
1576 "An Ivy function suitable for `completion-in-region-function'."
1577 (let* ((enable-recursive-minibuffers t)
1578 (str (buffer-substring-no-properties start end))
1579 (completion-ignore-case case-fold-search)
1581 (completion-all-completions str collection predicate (- end start))))
1583 (message "No matches")
1585 (setq ivy-completion-beg (- end (ivy-completion-common-length (car comps))))
1586 (setq ivy-completion-end end)
1587 (if (null (cdr comps))
1588 (if (string= str (car comps))
1589 (message "Sole match")
1590 (setf (ivy-state-window ivy-last) (selected-window))
1591 (ivy-completion-in-region-action
1592 (substring-no-properties
1594 (let* ((w (1+ (floor (log (length comps) 10))))
1595 (ivy-count-format (if (string= ivy-count-format "")
1597 (format "%%-%dd " w)))
1598 (prompt (format "(%s): " str)))
1600 (ivy-read (if (string= ivy-count-format "")
1602 (replace-regexp-in-string "%" "%%" prompt))
1603 ;; remove 'completions-first-difference face
1604 (mapcar #'substring-no-properties comps)
1605 :predicate predicate
1606 :action #'ivy-completion-in-region-action
1610 (defcustom ivy-do-completion-in-region t
1611 "When non-nil `ivy-mode' will set `completion-in-region-function'."
1615 (define-minor-mode ivy-mode
1616 "Toggle Ivy mode on or off.
1617 Turn Ivy mode on if ARG is positive, off otherwise.
1618 Turning on Ivy mode sets `completing-read-function' to
1619 `ivy-completing-read'.
1624 Minibuffer bindings:
1625 \\{ivy-minibuffer-map}"
1628 :keymap ivy-mode-map
1632 (setq completing-read-function 'ivy-completing-read)
1633 (when ivy-do-completion-in-region
1634 (setq completion-in-region-function 'ivy-completion-in-region)))
1635 (setq completing-read-function 'completing-read-default)
1636 (setq completion-in-region-function 'completion--in-region)))
1638 (defun ivy--preselect-index (preselect candidates)
1639 "Return the index of PRESELECT in CANDIDATES."
1640 (cond ((integerp preselect)
1642 ((cl-position preselect candidates :test #'equal))
1643 ((stringp preselect)
1644 (let ((re preselect))
1647 (string-match re x))
1652 (defvar ivy--regex-hash
1653 (make-hash-table :test #'equal)
1654 "Store pre-computed regex.")
1656 (defun ivy--split (str)
1657 "Split STR into a list by single spaces.
1658 The remaining spaces stick to their left.
1659 This allows to \"quote\" N spaces by inputting N+1 spaces."
1660 (let ((len (length str))
1665 (while (and (string-match " +" str start1)
1667 (setq match-len (- (match-end 0) (match-beginning 0)))
1671 (setq start1 start0)
1673 (push (substring str start1 (match-beginning 0)) res)
1674 (setq start1 (match-end 0)))
1675 (setq str (replace-match
1676 (make-string (1- match-len) ?\ )
1678 (setq start0 (or start0 start1))
1679 (setq start1 (1- (match-end 0)))))
1681 (push (substring str start0) res)
1682 (setq s (substring str start1))
1683 (unless (= (length s) 0)
1687 (defun ivy--regex (str &optional greedy)
1688 "Re-build regex pattern from STR in case it has a space.
1689 When GREEDY is non-nil, join words in a greedy way."
1690 (let ((hashed (unless greedy
1691 (gethash str ivy--regex-hash))))
1694 (setq ivy--subexps (car hashed)))
1695 (when (string-match "\\([^\\]\\|^\\)\\\\$" str)
1696 (setq str (substring str 0 -1)))
1698 (let ((subs (ivy--split str)))
1699 (if (= (length subs) 1)
1701 (setq ivy--subexps 0)
1704 (setq ivy--subexps (length subs))
1707 (if (string-match "\\`\\\\([^?].*\\\\)\\'" x)
1709 (format "\\(%s\\)" x)))
1714 ivy--regex-hash)))))
1716 (defun ivy--regex-ignore-order--part (str &optional discard)
1717 "Re-build regex from STR by splitting at spaces.
1718 Ignore the order of each group."
1719 (let* ((subs (split-string str " +" t))
1720 (len (length subs)))
1725 (mapcar (lambda (x) (cons x (not discard)))
1728 (defun ivy--regex-ignore-order (str)
1729 "Re-build regex from STR by splitting at spaces.
1730 Ignore the order of each group. Everything before \"!\" should
1731 match. Everything after \"!\" should not match."
1732 (let ((parts (split-string str "!" t)))
1733 (cl-case (length parts)
1737 (if (string= (substring str 0 1) "!")
1739 (ivy--regex-ignore-order--part (car parts) t))
1740 (ivy--regex-ignore-order--part (car parts))))
1743 (ivy--regex-ignore-order--part (car parts))
1744 (ivy--regex-ignore-order--part (cadr parts) t)))
1745 (t (error "Unexpected: use only one !")))))
1747 (defun ivy--regex-plus (str)
1748 "Build a regex sequence from STR.
1749 Spaces are wild card characters, everything before \"!\" should
1750 match. Everything after \"!\" should not match."
1751 (let ((parts (split-string str "!" t)))
1752 (cl-case (length parts)
1756 (if (string= (substring str 0 1) "!")
1758 (list (ivy--regex (car parts))))
1759 (ivy--regex (car parts))))
1762 (cons (ivy--regex (car parts)) t)
1763 (mapcar #'list (split-string (cadr parts) " " t))))
1764 (t (error "Unexpected: use only one !")))))
1766 (defun ivy--regex-fuzzy (str)
1767 "Build a regex sequence from STR.
1768 Insert .* between each char."
1769 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1771 (concat (match-string 1 str)
1774 (format "\\(%c\\)" x))
1775 (string-to-list (match-string 2 str)) ".*")
1776 (match-string 3 str))
1777 (setq ivy--subexps (length (match-string 2 str))))
1780 (defcustom ivy-fixed-height-minibuffer nil
1781 "When non nil, fix the height of the minibuffer during ivy
1782 completion at `ivy-height'. This effectively sets the minimum
1783 height at this level and tries to ensure that it does not change
1784 depending on the number of candidates."
1789 (defun ivy--minibuffer-setup ()
1790 "Setup ivy completion in the minibuffer."
1791 (set (make-local-variable 'completion-show-inline-help) nil)
1792 (set (make-local-variable 'minibuffer-default-add-function)
1794 (list ivy--default)))
1795 (when (display-graphic-p)
1796 (setq truncate-lines t))
1797 (setq-local max-mini-window-height ivy-height)
1798 (when ivy-fixed-height-minibuffer
1799 (set-window-text-height (selected-window) ivy-height))
1800 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1801 ;; show completions with empty input
1804 (defun ivy--input ()
1805 "Return the current minibuffer input."
1806 ;; assume one-line minibuffer input
1807 (buffer-substring-no-properties
1808 (minibuffer-prompt-end)
1809 (line-end-position)))
1811 (defun ivy--cleanup ()
1812 "Delete the displayed completion candidates."
1814 (goto-char (minibuffer-prompt-end))
1815 (delete-region (line-end-position) (point-max))))
1817 (defun ivy--insert-prompt ()
1818 "Update the prompt according to `ivy--prompt'."
1820 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1821 counsel-find-symbol))
1822 (setq ivy--prompt-extra ""))
1824 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1826 (setq head (match-string 1 ivy--prompt))
1828 (setq head (substring ivy--prompt 0 -1))
1830 (let ((inhibit-read-only t)
1831 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1834 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1835 (> (minibuffer-depth) 1))
1836 (format "[%d] " (minibuffer-depth))
1839 (if (string-match "%d.*%d" ivy-count-format)
1842 (or (and (ivy-state-dynamic-collection ivy-last)
1846 (or (and (ivy-state-dynamic-collection ivy-last)
1851 (d-str (if ivy--directory
1852 (abbreviate-file-name ivy--directory)
1855 (goto-char (point-min))
1856 (delete-region (point-min) (minibuffer-prompt-end))
1857 (if (> (+ (mod (+ (length n-str) (length d-str)) (window-width))
1860 (setq n-str (concat n-str "\n" d-str))
1861 (setq n-str (concat n-str d-str)))
1862 (let ((regex (format "\\([^\n]\\{%d\\}\\)[^\n]" (window-width))))
1863 (while (string-match regex n-str)
1864 (setq n-str (replace-match (concat (match-string 1 n-str) "\n") nil t n-str 1))))
1865 (set-text-properties 0 (length n-str)
1866 `(face minibuffer-prompt ,@std-props)
1868 (ivy--set-match-props n-str "confirm"
1869 `(face ivy-confirm-face ,@std-props))
1870 (ivy--set-match-props n-str "match required"
1871 `(face ivy-match-required-face ,@std-props))
1873 ;; get out of the prompt area
1874 (constrain-to-field nil (point-max))))))
1876 (defun ivy--set-match-props (str match props)
1877 "Set STR text properties that match MATCH to PROPS."
1878 (when (string-match match str)
1879 (set-text-properties
1885 (defvar inhibit-message)
1887 (defun ivy--sort-maybe (collection)
1888 "Sort COLLECTION if needed."
1889 (let ((sort (ivy-state-sort ivy-last))
1893 (let ((sort-fn (cond ((functionp sort)
1895 ((setq entry (assoc (ivy-state-collection ivy-last)
1896 ivy-sort-functions-alist))
1899 (cdr (assoc t ivy-sort-functions-alist))))))
1900 (if (functionp sort-fn)
1901 (cl-sort (copy-sequence collection) sort-fn)
1904 (defun ivy--exhibit ()
1905 "Insert Ivy completions display.
1906 Should be run via minibuffer `post-command-hook'."
1907 (when (memq 'ivy--exhibit post-command-hook)
1908 (let ((inhibit-field-text-motion nil))
1909 (constrain-to-field nil (point-max)))
1910 (setq ivy-text (ivy--input))
1911 (if (ivy-state-dynamic-collection ivy-last)
1912 ;; while-no-input would cause annoying
1913 ;; "Waiting for process to die...done" message interruptions
1914 (let ((inhibit-message t))
1915 (unless (equal ivy--old-text ivy-text)
1917 (setq ivy--all-candidates
1919 (funcall (ivy-state-collection ivy-last) ivy-text)))
1920 (setq ivy--old-text ivy-text)))
1921 (when ivy--all-candidates
1922 (ivy--insert-minibuffer
1923 (ivy--format ivy--all-candidates))))
1924 (cond (ivy--directory
1925 (if (string-match "/\\'" ivy-text)
1926 (if (member ivy-text ivy--all-candidates)
1927 (ivy--cd (expand-file-name ivy-text ivy--directory))
1928 (when (string-match "//\\'" ivy-text)
1929 (if (and default-directory
1930 (string-match "\\`[[:alpha:]]:/" default-directory))
1931 (ivy--cd (match-string 0 default-directory))
1933 (when (string-match "[[:alpha:]]:/$" ivy-text)
1934 (let ((drive-root (match-string 0 ivy-text)))
1935 (when (file-exists-p drive-root)
1936 (ivy--cd drive-root)))))
1937 (if (string-match "\\`~\\'" ivy-text)
1938 (ivy--cd (expand-file-name "~/")))))
1939 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1940 (when (or (and (string-match "\\` " ivy-text)
1941 (not (string-match "\\` " ivy--old-text)))
1942 (and (string-match "\\` " ivy--old-text)
1943 (not (string-match "\\` " ivy-text))))
1944 (setq ivy--all-candidates
1945 (if (and (> (length ivy-text) 0)
1946 (eq (aref ivy-text 0)
1948 (ivy--buffer-list " ")
1949 (ivy--buffer-list "" ivy-use-virtual-buffers)))
1950 (setq ivy--old-re nil))))
1951 (ivy--insert-minibuffer
1952 (with-current-buffer (ivy-state-buffer ivy-last)
1954 (ivy--filter ivy-text ivy--all-candidates))))
1955 (setq ivy--old-text ivy-text))))
1957 (defun ivy--insert-minibuffer (text)
1958 "Insert TEXT into minibuffer with appropriate cleanup."
1959 (let ((resize-mini-windows nil)
1960 (update-fn (ivy-state-update-fn ivy-last))
1964 (funcall update-fn))
1965 (ivy--insert-prompt)
1966 ;; Do nothing if while-no-input was aborted.
1967 (when (stringp text)
1968 (let ((buffer-undo-list t))
1972 (when (display-graphic-p)
1973 (ivy--resize-minibuffer-to-fit))))
1975 (defun ivy--resize-minibuffer-to-fit ()
1976 "Resize the minibuffer window size to fit the text in the minibuffer."
1977 (unless (frame-root-window-p (minibuffer-window))
1978 (with-selected-window (minibuffer-window)
1979 (if (fboundp 'window-text-pixel-size)
1980 (let ((text-height (cdr (window-text-pixel-size)))
1981 (body-height (window-body-height nil t)))
1982 (when (> text-height body-height)
1983 ;; Note: the size increment needs to be at least frame-char-height,
1984 ;; otherwise resizing won't do anything.
1985 (let ((delta (max (- text-height body-height) (frame-char-height))))
1986 (window-resize nil delta nil t t))))
1987 (let ((text-height (count-screen-lines))
1988 (body-height (window-body-height)))
1989 (when (> text-height body-height)
1990 (window-resize nil (- text-height body-height) nil t)))))))
1992 (declare-function colir-blend-face-background "ext:colir")
1994 (defun ivy--add-face (str face)
1995 "Propertize STR with FACE.
1996 `font-lock-append-text-property' is used, since it's better than
1997 `propertize' or `add-face-text-property' in this case."
2001 (colir-blend-face-background 0 (length str) face str)
2002 (let ((foreground (face-foreground face)))
2004 (add-face-text-property
2006 `(:foreground ,foreground)
2011 (font-lock-append-text-property 0 (length str) 'face face str))))
2014 (declare-function flx-make-string-cache "ext:flx")
2015 (declare-function flx-score "ext:flx")
2017 (defvar ivy--flx-cache nil)
2019 (eval-after-load 'flx
2020 '(setq ivy--flx-cache (flx-make-string-cache)))
2022 (defun ivy-toggle-case-fold ()
2023 "Toggle the case folding between nil and auto.
2024 In any completion session, the case folding starts in auto:
2026 - when the input is all lower case, `case-fold-search' is t
2029 You can toggle this to make `case-fold-search' nil regardless of input."
2031 (setq ivy-case-fold-search
2032 (if ivy-case-fold-search
2035 ;; reset cache so that the candidate list updates
2036 (setq ivy--old-re nil))
2038 (defun ivy--re-filter (re candidates)
2039 "Return all RE matching CANDIDATES.
2040 RE is a list of cons cells, with a regexp car and a boolean cdr.
2041 When the cdr is t, the car must match.
2042 Otherwise, the car must not match."
2043 (let ((re-list (if (stringp re) (list (cons re t)) re))
2045 (dolist (re re-list)
2052 (let ((re-str (car re)))
2053 (lambda (x) (string-match re-str x)))
2057 (defun ivy--filter (name candidates)
2058 "Return all items that match NAME in CANDIDATES.
2059 CANDIDATES are assumed to be static."
2060 (let ((re (funcall ivy--regex-function name)))
2061 (if (and (equal re ivy--old-re)
2063 ;; quick caching for "C-n", "C-p" etc.
2065 (let* ((re-str (if (listp re) (caar re) re))
2066 (matcher (ivy-state-matcher ivy-last))
2068 (and ivy-case-fold-search
2069 (string= name (downcase name))))
2072 (funcall matcher re candidates))
2075 (stringp ivy--old-re)
2076 (not (string-match "\\\\" ivy--old-re))
2077 (not (equal ivy--old-re ""))
2079 (if (string-match "\\\\)\\'" ivy--old-re)
2080 (substring ivy--old-re 0 -2)
2086 (lambda (x) (string-match re x))
2089 (ivy--re-filter re candidates)))))
2090 (ivy--recompute-index name re-str cands)
2092 (if (eq ivy--regex-function 'ivy--regex-ignore-order)
2097 (setq ivy--old-cands (ivy--sort name cands))))))
2099 (defun ivy--set-candidates (x)
2100 "Update `ivy--all-candidates' with X."
2102 (dolist (source ivy--extra-candidates)
2103 (if (equal source '(original-source))
2106 (setq res (append x res)))
2107 (setq ivy--old-re nil)
2109 (ivy--filter ivy-text (cadr source))
2111 (setq ivy--all-candidates res)))
2113 (defcustom ivy-sort-matches-functions-alist '((t . nil))
2114 "An alist of functions for sorting matching candidates.
2116 Unlike `ivy-sort-functions-alist', which is used to sort the
2117 whole collection only once, this alist of functions are used to
2118 sort only matching candidates after each change in input.
2120 The alist KEY is either a collection function or t to match
2121 previously unmatched collection functions.
2123 The alist VAL is a sorting function with the signature of
2124 `ivy--prefix-sort'."
2127 (const :tag "Fall-through" t)
2128 (symbol :tag "Collection"))
2131 (const :tag "Don't sort" nil)
2132 (const :tag "Put prefix matches ahead" 'ivy--prefix-sort)
2133 (function :tag "Custom sort function"))))
2135 (defun ivy--sort-files-by-date (_name candidates)
2136 "Re-soft CANDIDATES according to file modification date."
2137 (let ((default-directory ivy--directory))
2138 (cl-sort (copy-sequence candidates)
2141 (nth 5 (file-attributes f2))
2142 (nth 5 (file-attributes f1)))))))
2144 (defun ivy--sort (name candidates)
2145 "Re-sort CANDIDATES by NAME.
2146 All CANDIDATES are assumed to match NAME."
2147 (let ((key (or (ivy-state-caller ivy-last)
2148 (when (functionp (ivy-state-collection ivy-last))
2149 (ivy-state-collection ivy-last))))
2151 (cond ((and (require 'flx nil 'noerror)
2152 (eq ivy--regex-function 'ivy--regex-fuzzy))
2153 (ivy--flx-sort name candidates))
2154 ((setq fun (cdr (or (assoc key ivy-sort-matches-functions-alist)
2155 (assoc t ivy-sort-matches-functions-alist))))
2156 (funcall fun name candidates))
2160 (defun ivy--prefix-sort (name candidates)
2161 "Re-sort CANDIDATES.
2162 Prefix matches to NAME are put ahead of the list."
2163 (if (or (string-match "^\\^" name) (string= name ""))
2165 (let ((re-prefix (concat "^" (funcall ivy--regex-function name)))
2168 (dolist (s candidates)
2169 (if (string-match re-prefix s)
2171 (push s res-noprefix)))
2173 (nreverse res-prefix)
2174 (nreverse res-noprefix)))))
2176 (defun ivy--recompute-index (name re-str cands)
2177 (let* ((caller (ivy-state-caller ivy-last))
2178 (func (or (and caller (cdr (assoc caller ivy-index-functions-alist)))
2179 (cdr (assoc t ivy-index-functions-alist))
2180 #'ivy-recompute-index-zero)))
2181 (unless (eq this-command 'ivy-resume)
2184 (cl-position (if (and (> (length name) 0)
2185 (eq ?^ (aref name 0)))
2191 (concat re-str "/") cands
2193 (and (not (string= name ""))
2194 (not (and (require 'flx nil 'noerror)
2195 (eq ivy--regex-function 'ivy--regex-fuzzy)
2196 (< (length cands) 200)))
2198 (cl-position (nth ivy--index ivy--old-cands)
2200 (funcall func re-str cands))))
2201 (when (and (or (string= name "")
2203 (not (equal ivy--old-re "")))
2205 (or (ivy--preselect-index
2206 (ivy-state-preselect ivy-last)
2210 (defun ivy-recompute-index-swiper (_re-str cands)
2211 (let ((tail (nthcdr ivy--index ivy--old-cands))
2213 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2215 (while (and tail (null idx))
2216 ;; Compare with eq to handle equal duplicates in cands
2217 (setq idx (cl-position (pop tail) cands)))
2220 (1- (length cands))))
2223 ;; already in ivy-state-buffer
2224 (let ((n (line-number-at-pos))
2228 (when (eq n (read (get-text-property 0 'display c)))
2233 (defun ivy-recompute-index-swiper-async (_re-str cands)
2234 (let ((tail (nthcdr ivy--index ivy--old-cands))
2236 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2238 (while (and tail (null idx))
2239 ;; Compare with `equal', since the collection is re-created
2240 ;; each time with `split-string'
2241 (setq idx (cl-position (pop tail) cands :test #'equal)))
2245 (defun ivy-recompute-index-zero (_re-str _cands)
2248 (defcustom ivy-minibuffer-faces
2249 '(ivy-minibuffer-match-face-1
2250 ivy-minibuffer-match-face-2
2251 ivy-minibuffer-match-face-3
2252 ivy-minibuffer-match-face-4)
2253 "List of `ivy' faces for minibuffer group matches."
2254 :type '(repeat :tag "Faces"
2256 (const ivy-minibuffer-match-face-1)
2257 (const ivy-minibuffer-match-face-2)
2258 (const ivy-minibuffer-match-face-3)
2259 (const ivy-minibuffer-match-face-4)
2260 (face :tag "Other face"))))
2262 (defvar ivy-flx-limit 200
2263 "Used to conditionally turn off flx sorting.
2265 When the amount of matching candidates exceeds this limit, then
2266 no sorting is done.")
2268 (defun ivy--flx-sort (name cands)
2269 "Sort according to closeness to string NAME the string list CANDS."
2272 (< (length cands) ivy-flx-limit))
2273 (let* ((flx-name (if (string-match "^\\^" name)
2280 (let ((score (flx-score x flx-name ivy--flx-cache)))
2284 (if cands-with-score
2286 (let ((str (copy-sequence (cdr x)))
2289 (dolist (j (cdar x))
2290 (unless (eq j (1+ last-j))
2293 (ivy-add-face-text-property
2295 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2296 ivy-minibuffer-faces)
2299 (sort cands-with-score
2301 (> (caar x) (caar y)))))
2307 (defcustom ivy-format-function 'ivy-format-function-default
2308 "Function to transform the list of candidates into a string.
2309 This string is inserted into the minibuffer."
2311 (const :tag "Default" ivy-format-function-default)
2312 (const :tag "Arrow prefix" ivy-format-function-arrow)
2313 (const :tag "Full line" ivy-format-function-line)))
2315 (defun ivy--truncate-string (str width)
2316 "Truncate STR to WIDTH."
2317 (if (> (string-width str) width)
2318 (concat (substring str 0 (min (- width 3)
2319 (- (length str) 3))) "...")
2322 (defun ivy--format-function-generic (selected-fn other-fn strs separator)
2323 "Transform CAND-PAIRS into a string for minibuffer.
2324 SELECTED-FN and OTHER-FN each take two string arguments.
2325 SEPARATOR is used to join the candidates."
2329 (let ((curr (eq (cl-incf i) ivy--index)))
2331 (funcall selected-fn str)
2332 (funcall other-fn str))))
2336 (defun ivy-format-function-default (cands)
2337 "Transform CAND-PAIRS into a string for minibuffer."
2338 (ivy--format-function-generic
2340 (ivy--add-face str 'ivy-current-match))
2345 (defun ivy-format-function-arrow (cands)
2346 "Transform CAND-PAIRS into a string for minibuffer."
2347 (ivy--format-function-generic
2349 (concat "> " (ivy--add-face str 'ivy-current-match)))
2355 (defun ivy-format-function-line (cands)
2356 "Transform CAND-PAIRS into a string for minibuffer."
2357 (ivy--format-function-generic
2359 (ivy--add-face (concat str "\n") 'ivy-current-match))
2365 (defun ivy-add-face-text-property (start end face str)
2366 (if (fboundp 'add-face-text-property)
2367 (add-face-text-property
2368 start end face nil str)
2369 (font-lock-append-text-property
2370 start end 'face face str)))
2372 (defun ivy--format-minibuffer-line (str)
2374 (str (copy-sequence str)))
2375 (cond ((eq ivy--regex-function 'ivy--regex-ignore-order)
2376 (when (consp ivy--old-re)
2378 (dolist (re ivy--old-re)
2379 (when (string-match (car re) str)
2380 (ivy-add-face-text-property
2381 (match-beginning 0) (match-end 0)
2382 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2383 ivy-minibuffer-faces)
2386 ((and (eq ivy-display-style 'fancy)
2387 (not (eq ivy--regex-function 'ivy--regex-fuzzy)))
2389 (setq ivy--old-re (funcall ivy--regex-function ivy-text)))
2390 (while (and (string-match ivy--old-re str start)
2391 (> (- (match-end 0) (match-beginning 0)) 0))
2392 (setq start (match-end 0))
2394 (while (<= i ivy--subexps)
2396 (cond ((zerop ivy--subexps)
2397 (cadr ivy-minibuffer-faces))
2399 (car ivy-minibuffer-faces))
2401 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2402 ivy-minibuffer-faces)))))
2403 (ivy-add-face-text-property
2404 (match-beginning i) (match-end i)
2409 (ivy-set-display-transformer
2410 'read-file-name-internal 'ivy-read-file-transformer)
2412 (defun ivy-read-file-transformer (str)
2413 (if (string-match-p "/\\'" str)
2414 (propertize str 'face 'ivy-subdir)
2417 (defun ivy--format (cands)
2418 "Return a string for CANDS suitable for display in the minibuffer.
2419 CANDS is a list of strings."
2420 (setq ivy--length (length cands))
2421 (when (>= ivy--index ivy--length)
2422 (setq ivy--index (max (1- ivy--length) 0)))
2424 (setq ivy--current "")
2425 (let* ((half-height (/ ivy-height 2))
2426 (start (max 0 (- ivy--index half-height)))
2427 (end (min (+ start (1- ivy-height)) ivy--length))
2428 (start (max 0 (min start (- end (1- ivy-height)))))
2429 (cands (cl-subseq cands start end))
2430 (index (- ivy--index start))
2432 (setq ivy--current (copy-sequence (nth index cands)))
2433 (when (setq transformer-fn (ivy-state-display-transformer-fn ivy-last))
2435 (setq cands (mapcar transformer-fn cands))))
2436 (let* ((ivy--index index)
2438 #'ivy--format-minibuffer-line
2440 (res (concat "\n" (funcall ivy-format-function cands))))
2441 (put-text-property 0 (length res) 'read-only nil res)
2444 (defvar ivy--virtual-buffers nil
2445 "Store the virtual buffers alist.")
2447 (defvar recentf-list)
2449 (defcustom ivy-virtual-abbreviate 'name
2450 "The mode of abbreviation for virtual buffer names."
2452 (const :tag "Only name" name)
2453 (const :tag "Full path" full)
2454 ;; eventually, uniquify
2457 (defun ivy--virtual-buffers ()
2458 "Adapted from `ido-add-virtual-buffers-to-list'."
2459 (unless recentf-mode
2461 (let ((bookmarks (and (boundp 'bookmark-alist)
2463 virtual-buffers name)
2464 (dolist (head (append
2466 (delete " - no file -"
2467 (delq nil (mapcar (lambda (bookmark)
2468 (cdr (assoc 'filename bookmark)))
2471 (if (eq ivy-virtual-abbreviate 'name)
2472 (file-name-nondirectory head)
2473 (expand-file-name head)))
2474 (when (equal name "")
2475 (setq name (file-name-nondirectory (directory-file-name head))))
2476 (when (equal name "")
2478 (and (not (equal name ""))
2479 (null (get-file-buffer head))
2480 (not (assoc name virtual-buffers))
2481 (push (cons name head) virtual-buffers)))
2482 (when virtual-buffers
2483 (dolist (comp virtual-buffers)
2484 (put-text-property 0 (length (car comp))
2487 (setq ivy--virtual-buffers (nreverse virtual-buffers))
2488 (mapcar #'car ivy--virtual-buffers))))
2490 (defcustom ivy-ignore-buffers nil
2491 "List of regexps matching buffer names to ignore."
2492 :type '(repeat regexp))
2494 (defun ivy--buffer-list (str &optional virtual)
2495 "Return the buffers that match STR.
2496 When VIRTUAL is non-nil, add virtual buffers."
2501 (if (with-current-buffer x
2503 (abbreviate-file-name default-directory)))
2504 (propertize x 'face 'ivy-remote)
2506 (all-completions str 'internal-complete-buffer))
2508 (ivy--virtual-buffers)))))
2510 (defun ivy--switch-buffer-action (buffer)
2512 BUFFER may be a string or nil."
2514 (if (zerop (length buffer))
2516 ivy-text nil 'force-same-window)
2517 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2519 (not (get-buffer buffer)))
2520 (find-file (cdr virtual))
2522 buffer nil 'force-same-window))))))
2524 (defun ivy--switch-buffer-other-window-action (buffer)
2525 "Switch to BUFFER in other window.
2526 BUFFER may be a string or nil."
2527 (if (zerop (length buffer))
2528 (switch-to-buffer-other-window ivy-text)
2529 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2531 (not (get-buffer buffer)))
2532 (find-file-other-window (cdr virtual))
2533 (switch-to-buffer-other-window buffer)))))
2535 (defun ivy--rename-buffer-action (buffer)
2537 (let ((new-name (read-string "Rename buffer (to new name): ")))
2538 (with-current-buffer buffer
2539 (rename-buffer new-name))))
2541 (defvar ivy-switch-buffer-map (make-sparse-keymap))
2548 (ivy--reset-state ivy-last))
2551 ivy--switch-buffer-other-window-action
2554 ivy--rename-buffer-action
2557 (defun ivy--switch-buffer-matcher (regexp candidates)
2558 "Return REGEXP-matching CANDIDATES.
2559 Skip buffers that match `ivy-ignore-buffers'."
2560 (let ((res (ivy--re-filter regexp candidates)))
2561 (if (or (null ivy-use-ignore)
2562 (null ivy-ignore-buffers))
2568 (string-match regexp buf))
2569 ivy-ignore-buffers))
2573 (ivy-set-display-transformer
2574 'ivy-switch-buffer 'ivy-switch-buffer-transformer)
2575 (ivy-set-display-transformer
2576 'internal-complete-buffer 'ivy-switch-buffer-transformer)
2578 (defun ivy-switch-buffer-transformer (str)
2579 (let ((b (get-buffer str)))
2581 (buffer-file-name b)
2582 (buffer-modified-p b))
2583 (propertize str 'face 'ivy-modified-buffer)
2586 (defun ivy-switch-buffer-occur ()
2587 "Occur function for `ivy-switch-buffer' that uses `ibuffer'."
2589 (concat "\\(" (mapconcat #'regexp-quote ivy--old-cands "\\|") "\\)"))
2590 (new-qualifier `((name . ,cand-regexp))))
2591 (ibuffer nil (buffer-name) new-qualifier)))
2594 (defun ivy-switch-buffer ()
2595 "Switch to another buffer."
2597 (let ((this-command 'ivy-switch-buffer))
2598 (ivy-read "Switch to buffer: " 'internal-complete-buffer
2599 :matcher #'ivy--switch-buffer-matcher
2600 :preselect (buffer-name (other-buffer (current-buffer)))
2601 :action #'ivy--switch-buffer-action
2602 :keymap ivy-switch-buffer-map
2603 :caller 'ivy-switch-buffer)))
2606 (defun ivy-switch-buffer-other-window ()
2607 "Switch to another buffer in another window."
2609 (ivy-read "Switch to buffer in other window: " 'internal-complete-buffer
2610 :preselect (buffer-name (other-buffer (current-buffer)))
2611 :action #'ivy--switch-buffer-other-window-action
2612 :keymap ivy-switch-buffer-map
2613 :caller 'ivy-switch-buffer-other-window))
2616 (defun ivy-recentf ()
2617 "Find a file on `recentf-list'."
2619 (ivy-read "Recentf: " recentf-list
2624 :caller 'ivy-recentf))
2626 (defun ivy-yank-word ()
2627 "Pull next word from buffer into search string."
2632 (le (line-end-position)))
2636 (setq amend (buffer-substring-no-properties pt (point))))))
2638 (insert (replace-regexp-in-string " +" " " amend)))))
2640 (defun ivy-kill-ring-save ()
2641 "Store the current candidates into the kill ring.
2642 If the region is active, forward to `kill-ring-save' instead."
2644 (if (region-active-p)
2645 (call-interactively 'kill-ring-save)
2652 (defun ivy-insert-current ()
2653 "Make the current candidate into current input.
2654 Don't finish completion."
2656 (delete-minibuffer-contents)
2657 (if (and ivy--directory
2658 (string-match "/$" ivy--current))
2659 (insert (substring ivy--current 0 -1))
2660 (insert ivy--current)))
2662 (defun ivy-toggle-fuzzy ()
2663 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
2665 (setq ivy--old-re nil)
2666 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
2667 (setq ivy--regex-function 'ivy--regex-plus)
2668 (setq ivy--regex-function 'ivy--regex-fuzzy)))
2670 (defun ivy-reverse-i-search ()
2671 "Enter a recursive `ivy-read' session using the current history.
2672 The selected history element will be inserted into the minibuffer."
2674 (let ((enable-recursive-minibuffers t)
2675 (history (symbol-value (ivy-state-history ivy-last)))
2677 (ivy-recursive-restore nil))
2678 (ivy-read "Reverse-i-search: "
2682 (setq ivy-last old-last))
2683 (delete-minibuffer-contents)
2684 (insert (substring-no-properties x))
2687 (defun ivy-restrict-to-matches ()
2688 "Restrict candidates to current matches and erase input."
2690 (delete-minibuffer-contents)
2691 (setq ivy--all-candidates
2692 (ivy--filter ivy-text ivy--all-candidates)))
2695 (defvar-local ivy-occur-last nil
2696 "Buffer-local value of `ivy-last'.
2697 Can't re-use `ivy-last' because using e.g. `swiper' in the same
2698 buffer would modify `ivy-last'.")
2700 (defvar ivy-occur-mode-map
2701 (let ((map (make-sparse-keymap)))
2702 (define-key map [mouse-1] 'ivy-occur-click)
2703 (define-key map (kbd "RET") 'ivy-occur-press)
2704 (define-key map (kbd "j") 'ivy-occur-next-line)
2705 (define-key map (kbd "k") 'ivy-occur-previous-line)
2706 (define-key map (kbd "h") 'backward-char)
2707 (define-key map (kbd "l") 'forward-char)
2708 (define-key map (kbd "f") 'ivy-occur-press)
2709 (define-key map (kbd "g") 'ivy-occur-revert-buffer)
2710 (define-key map (kbd "a") 'ivy-occur-read-action)
2711 (define-key map (kbd "o") 'ivy-occur-dispatch)
2712 (define-key map (kbd "c") 'ivy-occur-toggle-calling)
2713 (define-key map (kbd "q") 'quit-window)
2715 "Keymap for Ivy Occur mode.")
2717 (defun ivy-occur-toggle-calling ()
2718 "Toggle `ivy-calling'."
2720 (if (setq ivy-calling (not ivy-calling))
2722 (setq mode-name "Ivy-Occur [calling]")
2724 (setq mode-name "Ivy-Occur"))
2725 (force-mode-line-update))
2727 (defun ivy-occur-next-line (&optional arg)
2728 "Move the cursor down ARG lines.
2729 When `ivy-calling' isn't nil, call `ivy-occur-press'."
2735 (defun ivy-occur-previous-line (&optional arg)
2736 "Move the cursor up ARG lines.
2737 When `ivy-calling' isn't nil, call `ivy-occur-press'."
2739 (forward-line (- arg))
2743 (define-derived-mode ivy-occur-mode fundamental-mode "Ivy-Occur"
2744 "Major mode for output from \\[ivy-occur].
2746 \\{ivy-occur-mode-map}")
2748 (defvar ivy-occur-grep-mode-map
2749 (let ((map (copy-keymap ivy-occur-mode-map)))
2750 (define-key map (kbd "C-x C-q") 'ivy-wgrep-change-to-wgrep-mode)
2752 "Keymap for Ivy Occur Grep mode.")
2754 (define-derived-mode ivy-occur-grep-mode grep-mode "Ivy-Occur"
2755 "Major mode for output from \\[ivy-occur].
2757 \\{ivy-occur-grep-mode-map}")
2759 (defvar ivy--occurs-list nil
2760 "A list of custom occur generators per command.")
2762 (defun ivy-set-occur (cmd occur)
2763 "Assign CMD a custom OCCUR function."
2764 (setq ivy--occurs-list
2765 (plist-put ivy--occurs-list cmd occur)))
2767 (ivy-set-occur 'ivy-switch-buffer 'ivy-switch-buffer-occur)
2768 (ivy-set-occur 'ivy-switch-buffer-other-window 'ivy-switch-buffer-occur)
2770 (defun ivy--occur-insert-lines (cands)
2772 (add-text-properties
2776 help-echo "mouse-1: call ivy-action")
2781 "Stop completion and put the current matches into a new buffer.
2783 The new buffer remembers current action(s).
2785 While in the *ivy-occur* buffer, selecting a candidate with RET or
2786 a mouse click will call the appropriate action for that candidate.
2788 There is no limit on the number of *ivy-occur* buffers."
2790 (if (not (window-minibuffer-p))
2791 (user-error "No completion session is active")
2792 (let* ((caller (ivy-state-caller ivy-last))
2793 (occur-fn (plist-get ivy--occurs-list caller))
2795 (generate-new-buffer
2796 (format "*ivy-occur%s \"%s\"*"
2798 (concat " " (prin1-to-string caller))
2801 (with-current-buffer buffer
2802 (let ((inhibit-read-only t))
2807 (insert (format "%d candidates:\n" (length ivy--old-cands)))
2808 (ivy--occur-insert-lines
2810 (lambda (cand) (concat " " cand))
2812 (setf (ivy-state-text ivy-last) ivy-text)
2813 (setq ivy-occur-last ivy-last)
2814 (setq-local ivy--directory ivy--directory))
2815 (ivy-exit-with-action
2816 `(lambda (_) (pop-to-buffer ,buffer))))))
2818 (defun ivy-occur-revert-buffer ()
2819 "Refresh the buffer making it up-to date with the collection.
2821 Currently only works for `swiper'. In that specific case, the
2822 *ivy-occur* buffer becomes nearly useless as the orignal buffer
2823 is updated, since the line numbers no longer match.
2825 Calling this function is as if you called `ivy-occur' on the
2826 updated original buffer."
2828 (let ((caller (ivy-state-caller ivy-occur-last))
2829 (ivy-last ivy-occur-last))
2830 (when (eq caller 'swiper)
2831 (let ((buffer (ivy-state-buffer ivy-occur-last)))
2832 (unless (buffer-live-p buffer)
2833 (error "buffer was killed"))
2834 (let ((inhibit-read-only t))
2836 (funcall (plist-get ivy--occurs-list caller) t))))))
2838 (declare-function wgrep-change-to-wgrep-mode "ext:wgrep")
2840 (defun ivy-wgrep-change-to-wgrep-mode ()
2841 "Forward to `wgrep-change-to-wgrep-mode'."
2843 (if (require 'wgrep nil 'noerror)
2844 (wgrep-change-to-wgrep-mode)
2845 (error "Package wgrep isn't installed")))
2847 (defun ivy-occur-read-action ()
2848 "Select one of the available actions as the current one."
2850 (let ((ivy-last ivy-occur-last))
2853 (defun ivy-occur-dispatch ()
2854 "Call one of the available actions on the current item."
2856 (let* ((state-action (ivy-state-action ivy-occur-last))
2857 (actions (if (symbolp state-action)
2859 (copy-sequence state-action))))
2862 (ivy-occur-read-action)
2864 (setf (ivy-state-action ivy-occur-last) actions))))
2866 (defun ivy-occur-click (event)
2867 "Execute action for the current candidate.
2868 EVENT gives the mouse position."
2870 (let ((window (posn-window (event-end event)))
2871 (pos (posn-point (event-end event))))
2872 (with-current-buffer (window-buffer window)
2874 (ivy-occur-press))))
2876 (declare-function swiper--cleanup "swiper")
2877 (declare-function swiper--add-overlays "swiper")
2879 (defun ivy-occur-press ()
2880 "Execute action for the current candidate."
2882 (when (save-excursion
2884 (looking-at "\\(?:./\\| \\)\\(.*\\)$"))
2885 (when (memq (ivy-state-caller ivy-occur-last)
2886 '(swiper counsel-git-grep counsel-grep counsel-ag))
2887 (let ((window (ivy-state-window ivy-occur-last)))
2888 (when (or (null (window-live-p window))
2889 (equal window (selected-window)))
2890 (save-selected-window
2891 (setf (ivy-state-window ivy-occur-last)
2892 (display-buffer (ivy-state-buffer ivy-occur-last)
2893 'display-buffer-pop-up-window))))))
2894 (let* ((ivy-last ivy-occur-last)
2895 (ivy-text (ivy-state-text ivy-last))
2896 (str (buffer-substring
2899 (coll (ivy-state-collection ivy-last))
2900 (action (ivy--get-action ivy-last))
2904 (if (and (consp coll)
2906 (cdr (assoc str coll))
2908 (if (memq (ivy-state-caller ivy-last)
2909 '(swiper counsel-git-grep))
2910 (with-current-buffer (window-buffer (selected-window))
2912 (swiper--add-overlays
2913 (ivy--regex ivy-text)
2914 (line-beginning-position)
2917 (run-at-time 0.5 nil 'swiper--cleanup)))))))
2919 (defvar ivy-help-file (let ((default-directory
2921 (file-name-directory load-file-name)
2922 default-directory)))
2923 (if (file-exists-p "ivy-help.org")
2924 (expand-file-name "ivy-help.org")
2925 (if (file-exists-p "doc/ivy-help.org")
2926 (expand-file-name "doc/ivy-help.org"))))
2927 "The file for `ivy-help'.")
2932 (let ((buf (get-buffer "*Ivy Help*")))
2934 (setq buf (get-buffer-create "*Ivy Help*"))
2935 (with-current-buffer buf
2936 (insert-file-contents ivy-help-file)
2939 (goto-char (point-min))))
2940 (if (eq this-command 'ivy-help)
2941 (switch-to-buffer buf)
2943 (pop-to-buffer buf)))
2945 (goto-char (point-min))))
2949 ;;; ivy.el ends here