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--current "./"))
558 (setq dir (ivy-expand-file-if-directory ivy--current)))
561 ((or (and (equal ivy--directory "/")
562 (string-match "\\`[^/]+:.*:.*\\'" ivy-text))
563 (string-match "\\`/[^/]+:.*:.*\\'" ivy-text))
565 ((or (and (equal ivy--directory "/")
567 "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
570 "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
572 (setq ivy-text ivy--current))))
574 "\\`/\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
576 (let ((method (match-string 1 ivy-text))
577 (user (match-string 2 ivy-text))
578 (rest (match-string 3 ivy-text))
581 (dolist (x (tramp-get-completion-function method))
582 (setq res (append res (funcall (car x) (cadr x)))))
583 (setq res (delq nil res))
587 (setq res (cl-delete-duplicates res :test #'equal))
588 (let* ((old-ivy-last ivy-last)
589 (enable-recursive-minibuffers t)
590 (host (ivy-read "user@host: "
591 (mapcar #'ivy-build-tramp-name res)
592 :initial-input rest)))
593 (setq ivy-last old-ivy-last)
595 (setq ivy--directory "/")
596 (ivy--cd (concat "/" method ":" host ":"))))))
600 (defun ivy-expand-file-if-directory (file-name)
601 "Expand FILE-NAME as directory.
602 When this directory doesn't exist, return nil."
603 (when (stringp file-name)
605 ;; Ignore host name must not match method "ssh"
607 (file-name-as-directory
608 (expand-file-name file-name ivy--directory)))))
609 (when (and full-name (file-directory-p full-name))
612 (defcustom ivy-tab-space nil
613 "When non-nil, `ivy-partial-or-done' should insert a space."
616 (defun ivy-partial-or-done ()
617 "Complete the minibuffer text as much as possible.
618 If the text hasn't changed as a result, forward to `ivy-alt-done'."
620 (if (and (eq (ivy-state-collection ivy-last) #'read-file-name-internal)
621 (or (and (equal ivy--directory "/")
622 (string-match "\\`[^/]+:.*\\'" ivy-text))
623 (string-match "\\`/" ivy-text)))
624 (let ((default-directory ivy--directory)
626 (minibuffer-complete)
627 (setq ivy-text (ivy--input))
628 (when (setq dir (ivy-expand-file-if-directory ivy-text))
631 (when (or (eq this-command last-command)
635 (defun ivy-partial ()
636 "Complete the minibuffer text as much as possible."
638 (let* ((parts (or (split-string ivy-text " " t) (list "")))
639 (postfix (car (last parts)))
640 (completion-ignore-case t)
641 (startp (string-match "^\\^" postfix))
642 (new (try-completion (if startp
643 (substring postfix 1)
645 (mapcar (lambda (str)
646 (let ((i (string-match postfix str)))
650 (cond ((eq new t) nil)
651 ((string= new ivy-text) nil)
653 (delete-region (minibuffer-prompt-end) (point-max))
658 (insert (mapconcat #'identity parts " ")
659 (if ivy-tab-space " " ""))
662 (defun ivy-immediate-done ()
663 "Exit the minibuffer with the current input."
665 (delete-minibuffer-contents)
666 (insert (setq ivy--current
668 (expand-file-name ivy-text ivy--directory)
670 (setq ivy-exit 'done)
675 "Resume the last completion session."
677 (if (null (ivy-state-action ivy-last))
678 (user-error "The last session isn't compatible with `ivy-resume'")
679 (when (eq (ivy-state-caller ivy-last) 'swiper)
680 (switch-to-buffer (ivy-state-buffer ivy-last)))
681 (with-current-buffer (ivy-state-buffer ivy-last)
683 (ivy-state-prompt ivy-last)
684 (ivy-state-collection ivy-last)
685 :predicate (ivy-state-predicate ivy-last)
686 :require-match (ivy-state-require-match ivy-last)
687 :initial-input ivy-text
688 :history (ivy-state-history ivy-last)
689 :preselect (unless (eq (ivy-state-collection ivy-last)
690 'read-file-name-internal)
692 :keymap (ivy-state-keymap ivy-last)
693 :update-fn (ivy-state-update-fn ivy-last)
694 :sort (ivy-state-sort ivy-last)
695 :action (ivy-state-action ivy-last)
696 :unwind (ivy-state-unwind ivy-last)
697 :re-builder (ivy-state-re-builder ivy-last)
698 :matcher (ivy-state-matcher ivy-last)
699 :dynamic-collection (ivy-state-dynamic-collection ivy-last)
700 :caller (ivy-state-caller ivy-last)))))
702 (defvar-local ivy-calling nil
703 "When non-nil, call the current action when `ivy--index' changes.")
705 (defun ivy-set-index (index)
706 "Set `ivy--index' to INDEX."
707 (setq ivy--index index)
712 (defun ivy-beginning-of-buffer ()
713 "Select the first completion candidate."
717 (defun ivy-end-of-buffer ()
718 "Select the last completion candidate."
720 (ivy-set-index (1- ivy--length)))
722 (defun ivy-scroll-up-command ()
723 "Scroll the candidates upward by the minibuffer height."
725 (ivy-set-index (min (1- (+ ivy--index ivy-height))
728 (defun ivy-scroll-down-command ()
729 "Scroll the candidates downward by the minibuffer height."
731 (ivy-set-index (max (1+ (- ivy--index ivy-height))
734 (defun ivy-minibuffer-grow ()
735 "Grow the minibuffer window by 1 line."
737 (setq-local max-mini-window-height
738 (cl-incf ivy-height)))
740 (defun ivy-minibuffer-shrink ()
741 "Shrink the minibuffer window by 1 line."
743 (unless (<= ivy-height 2)
744 (setq-local max-mini-window-height
745 (cl-decf ivy-height))
746 (window-resize (selected-window) -1)))
748 (defun ivy-next-line (&optional arg)
749 "Move cursor vertically down ARG candidates."
751 (setq arg (or arg 1))
752 (let ((index (+ ivy--index arg)))
753 (if (> index (1- ivy--length))
755 (ivy-beginning-of-buffer)
756 (ivy-set-index (1- ivy--length)))
757 (ivy-set-index index))))
759 (defun ivy-next-line-or-history (&optional arg)
760 "Move cursor vertically down ARG candidates.
761 If the input is empty, select the previous history element instead."
763 (if (string= ivy-text "")
764 (ivy-previous-history-element 1)
765 (ivy-next-line arg)))
767 (defun ivy-previous-line (&optional arg)
768 "Move cursor vertically up ARG candidates."
770 (setq arg (or arg 1))
771 (let ((index (- ivy--index arg)))
776 (ivy-set-index index))))
778 (defun ivy-previous-line-or-history (arg)
779 "Move cursor vertically up ARG candidates.
780 If the input is empty, select the previous history element instead."
782 (when (string= ivy-text "")
783 (ivy-previous-history-element 1))
784 (ivy-previous-line arg))
786 (defun ivy-toggle-calling ()
787 "Flip `ivy-calling'."
789 (when (setq ivy-calling (not ivy-calling))
792 (defun ivy-toggle-ignore ()
793 "Toggle user-configured candidate filtering."
795 (setq ivy-use-ignore (null ivy-use-ignore))
797 (setq ivy--old-cands nil))
799 (defun ivy--get-action (state)
800 "Get the action function from STATE."
801 (let ((action (ivy-state-action state)))
803 (if (functionp action)
805 (cadr (nth (car action) action))))))
807 (defun ivy--get-window (state)
808 "Get the window from STATE."
809 (if (ivy-state-p state)
810 (let ((window (ivy-state-window state)))
811 (if (window-live-p window)
813 (if (= (length (window-list)) 1)
818 (defun ivy--actionp (x)
819 "Return non-nil when X is a list of actions."
820 (and x (listp x) (not (eq (car x) 'closure))))
822 (defun ivy-next-action ()
823 "When the current action is a list, scroll it forwards."
825 (let ((action (ivy-state-action ivy-last)))
826 (when (ivy--actionp action)
827 (unless (>= (car action) (1- (length action)))
828 (cl-incf (car action))))))
830 (defun ivy-prev-action ()
831 "When the current action is a list, scroll it backwards."
833 (let ((action (ivy-state-action ivy-last)))
834 (when (ivy--actionp action)
835 (unless (<= (car action) 1)
836 (cl-decf (car action))))))
838 (defun ivy-action-name ()
839 "Return the name associated with the current action."
840 (let ((action (ivy-state-action ivy-last)))
841 (if (ivy--actionp action)
845 (nth 2 (nth (car action) action)))
848 (defvar ivy-inhibit-action nil
849 "When non-nil, `ivy-call' does nothing.
853 (let* ((ivy-inhibit-action t)
854 (str (counsel-locate \"lispy.el\")))
855 ;; do whatever with str - the corresponding file will not be opened
859 "Call the current action without exiting completion."
861 (unless ivy-inhibit-action
862 (let ((action (ivy--get-action ivy-last)))
864 (let* ((collection (ivy-state-collection ivy-last))
865 (x (if (and (consp collection)
866 (consp (car collection)))
867 (cdr (assoc ivy--current collection))
868 (if (equal ivy--current "")
871 (prog1 (funcall action x)
872 (unless (or (eq ivy-exit 'done)
873 (equal (selected-window)
874 (active-minibuffer-window))
875 (null (active-minibuffer-window)))
876 (select-window (active-minibuffer-window)))))))))
878 (defun ivy-next-line-and-call (&optional arg)
879 "Move cursor vertically down ARG candidates.
880 Call the permanent action if possible."
886 (defun ivy-previous-line-and-call (&optional arg)
887 "Move cursor vertically down ARG candidates.
888 Call the permanent action if possible."
890 (ivy-previous-line arg)
894 (defun ivy-previous-history-element (arg)
895 "Forward to `previous-history-element' with ARG."
897 (previous-history-element arg)
900 (ivy--maybe-scroll-history))
902 (defun ivy-next-history-element (arg)
903 "Forward to `next-history-element' with ARG."
905 (if (and (= minibuffer-history-position 0)
908 (insert ivy--default)
909 (when (and (with-ivy-window (derived-mode-p 'prog-mode))
910 (not (file-exists-p ivy--default))
911 (not (ffap-url-p ivy--default))
912 (not (ivy-state-dynamic-collection ivy-last))
913 (> (point) (minibuffer-prompt-end)))
916 (goto-char (minibuffer-prompt-end))
918 (forward-char (+ 2 (length ivy--default)))))
919 (next-history-element arg))
922 (ivy--maybe-scroll-history))
924 (defvar ivy-ffap-url-functions nil
925 "List of functions that check if the point is on a URL.")
927 (defun ivy--cd-maybe ()
928 "Check if the current input points to a different directory.
929 If so, move to that directory, while keeping only the file name."
931 (let ((input (ivy--input))
933 (if (setq url (or (ffap-url-p input)
938 ivy-ffap-url-functions
939 :initial-value nil))))
940 (ivy-exit-with-action
942 (funcall ffap-url-fetcher url)))
943 (setq input (expand-file-name input))
944 (let ((file (file-name-nondirectory input))
945 (dir (expand-file-name (file-name-directory input))))
946 (if (string= dir ivy--directory)
948 (delete-minibuffer-contents)
953 (defun ivy--maybe-scroll-history ()
954 "If the selected history element has an index, scroll there."
955 (let ((idx (ignore-errors
957 (minibuffer-prompt-end)
961 (setq ivy--index idx))))
964 "When completing file names, move to directory DIR."
965 (if (null ivy--directory)
967 (setq ivy--old-cands nil)
968 (setq ivy--old-re nil)
970 (setq ivy--all-candidates
971 (ivy--sorted-files (setq ivy--directory dir)))
973 (delete-minibuffer-contents)))
975 (defun ivy-backward-delete-char ()
976 "Forward to `backward-delete-char'.
977 On error (read-only), call `ivy-on-del-error-function'."
979 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
981 (ivy--cd (file-name-directory
987 (backward-delete-char 1)
989 (when ivy-on-del-error-function
990 (funcall ivy-on-del-error-function))))))
992 (defun ivy-delete-char (arg)
993 "Forward to `delete-char' ARG."
995 (unless (= (point) (line-end-position))
998 (defun ivy-forward-char (arg)
999 "Forward to `forward-char' ARG."
1001 (unless (= (point) (line-end-position))
1002 (forward-char arg)))
1004 (defun ivy-kill-word (arg)
1005 "Forward to `kill-word' ARG."
1007 (unless (= (point) (line-end-position))
1010 (defun ivy-kill-line ()
1011 "Forward to `kill-line'."
1014 (kill-region (minibuffer-prompt-end) (point))
1017 (defun ivy-backward-kill-word ()
1018 "Forward to `backward-kill-word'."
1020 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
1022 (ivy--cd (file-name-directory
1023 (directory-file-name
1030 (delete-region (point) pt)))))
1032 (defvar ivy--regexp-quote 'regexp-quote
1033 "Store the regexp quoting state.")
1035 (defun ivy-toggle-regexp-quote ()
1036 "Toggle the regexp quoting."
1038 (setq ivy--old-re nil)
1039 (cl-rotatef ivy--regex-function ivy--regexp-quote))
1041 (defvar avy-all-windows)
1044 (defvar avy-keys-alist)
1046 (defvar avy-styles-alist)
1047 (declare-function avy--process "ext:avy")
1048 (declare-function avy--style-fn "ext:avy")
1050 (eval-after-load 'avy
1051 '(add-to-list 'avy-styles-alist '(ivy-avy . pre)))
1054 "Jump to one of the current ivy candidates."
1056 (unless (require 'avy nil 'noerror)
1057 (error "Package avy isn't installed"))
1058 (let* ((avy-all-windows nil)
1059 (avy-keys (or (cdr (assq 'ivy-avy avy-keys-alist))
1061 (avy-style (or (cdr (assq 'ivy-avy
1071 (goto-char (point-min))
1073 (while (< (point) (point-max))
1079 (setq avy-action #'identity)
1081 (nreverse candidates)
1082 (avy--style-fn avy-style)))))
1083 (when (numberp candidate)
1084 (ivy-set-index (- (line-number-at-pos candidate) 2))
1088 (defun ivy-sort-file-function-default (x y)
1089 "Compare two files X and Y.
1090 Prioritize directories."
1091 (if (get-text-property 0 'dirp x)
1092 (if (get-text-property 0 'dirp y)
1095 (if (get-text-property 0 'dirp y)
1099 (defcustom ivy-sort-functions-alist
1100 '((read-file-name-internal . ivy-sort-file-function-default)
1101 (internal-complete-buffer . nil)
1102 (counsel-git-grep-function . nil)
1103 (Man-goto-section . nil)
1106 "An alist of sorting functions for each collection function.
1107 Interactive functions that call completion fit in here as well.
1109 Nil means no sorting, which is useful to turn off the sorting for
1110 functions that have candidates in the natural buffer order, like
1111 `org-refile' or `Man-goto-section'.
1113 The entry associated with t is used for all fall-through cases.
1115 See also `ivy-sort-max-size'."
1119 (const :tag "Fall-through" t)
1120 (symbol :tag "Collection"))
1122 (const :tag "Plain sort" string-lessp)
1123 (const :tag "File sort" ivy-sort-file-function-default)
1124 (const :tag "No sort" nil)))
1127 (defvar ivy-index-functions-alist
1128 '((swiper . ivy-recompute-index-swiper)
1129 (swiper-multi . ivy-recompute-index-swiper)
1130 (counsel-git-grep . ivy-recompute-index-swiper)
1131 (counsel-grep . ivy-recompute-index-swiper-async)
1132 (t . ivy-recompute-index-zero))
1133 "An alist of index recomputing functions for each collection function.
1134 When the input changes, the appropriate function returns an
1135 integer - the index of the matched candidate that should be
1138 (defvar ivy-re-builders-alist
1139 '((t . ivy--regex-plus))
1140 "An alist of regex building functions for each collection function.
1142 Each key is (in order of priority):
1143 1. The actual collection function, e.g. `read-file-name-internal'.
1144 2. The symbol passed by :caller into `ivy-read'.
1148 Each value is a function that should take a string and return a
1149 valid regex or a regex sequence (see below).
1151 Possible choices: `ivy--regex', `regexp-quote',
1152 `ivy--regex-plus', `ivy--regex-fuzzy'.
1154 If a function returns a list, it should format like this:
1155 '((\"matching-regexp\" . t) (\"non-matching-regexp\") ...).
1157 The matches will be filtered in a sequence, you can mix the
1158 regexps that should match and that should not match as you
1161 (defvar ivy-initial-inputs-alist
1162 '((org-refile . "^")
1163 (org-agenda-refile . "^")
1164 (org-capture-refile . "^")
1166 (counsel-describe-function . "^")
1167 (counsel-describe-variable . "^")
1170 "Command to initial input table.")
1172 (defcustom ivy-sort-max-size 30000
1173 "Sorting won't be done for collections larger than this."
1176 (defun ivy--sorted-files (dir)
1177 "Return the list of files in DIR.
1178 Directories come first."
1179 (let* ((default-directory dir)
1180 (seq (all-completions "" 'read-file-name-internal))
1184 (setq seq (delete "./" (delete "../" seq)))
1185 (when (eq (setq sort-fn (cdr (assoc 'read-file-name-internal
1186 ivy-sort-functions-alist)))
1187 #'ivy-sort-file-function-default)
1188 (setq seq (mapcar (lambda (x)
1189 (propertize x 'dirp (string-match-p "/\\'" x)))
1192 (setq seq (cl-sort seq sort-fn)))
1193 (dolist (dir ivy-extra-directories)
1197 (defvar ivy-recursive-restore t
1198 "When non-nil, restore the above state when exiting the minibuffer.
1199 This variable is let-bound to nil by functions that take care of
1200 the restoring themselves.")
1203 (cl-defun ivy-read (prompt collection
1205 predicate require-match initial-input
1206 history preselect keymap update-fn sort
1207 action unwind re-builder matcher dynamic-collection caller)
1208 "Read a string in the minibuffer, with completion.
1210 PROMPT is a format string, normally ending in a colon and a
1211 space; %d anywhere in the string is replaced by the current
1212 number of matching candidates. For the literal % character,
1213 escape it with %%. See also `ivy-count-format'.
1215 COLLECTION is either a list of strings, a function, an alist, or
1218 If INITIAL-INPUT is not nil, then insert that input in the
1219 minibuffer initially.
1221 KEYMAP is composed with `ivy-minibuffer-map'.
1223 If PRESELECT is not nil, then select the corresponding candidate
1224 out of the ones that match the INITIAL-INPUT.
1226 UPDATE-FN is called each time the current candidate(s) is changed.
1228 When SORT is t, use `ivy-sort-functions-alist' for sorting.
1230 ACTION is a lambda function to call after selecting a result. It
1231 takes a single string argument.
1233 UNWIND is a lambda function to call before exiting.
1235 RE-BUILDER is a lambda function to call to transform text into a
1238 MATCHER is to override matching.
1240 DYNAMIC-COLLECTION is a boolean to specify if the list of
1241 candidates is updated after each input by calling COLLECTION.
1243 CALLER is a symbol to uniquely identify the caller to `ivy-read'.
1244 It is used, along with COLLECTION, to determine which
1245 customizations apply to the current completion session."
1246 (let ((extra-actions (delete-dups
1247 (append (plist-get ivy--actions-list t)
1248 (plist-get ivy--actions-list this-command)
1249 (plist-get ivy--actions-list caller)))))
1252 (cond ((functionp action)
1254 ("o" ,action "default")
1258 ("o" identity "default")
1261 (delete-dups (append action extra-actions)))))))
1262 (let ((extra-sources (plist-get ivy--sources-list caller)))
1265 (setq ivy--extra-candidates nil)
1266 (dolist (source extra-sources)
1267 (cond ((equal source '(original-source))
1268 (setq ivy--extra-candidates
1269 (cons source ivy--extra-candidates)))
1270 ((null (cdr source))
1271 (setq ivy--extra-candidates
1273 (list (car source) (funcall (car source)))
1274 ivy--extra-candidates))))))
1275 (setq ivy--extra-candidates '((original-source)))))
1276 (let ((recursive-ivy-last (and (active-minibuffer-window) ivy-last))
1278 (plist-get ivy--display-transformers-list
1279 (or caller (and (functionp collection)
1284 :collection collection
1285 :predicate predicate
1286 :require-match require-match
1287 :initial-input initial-input
1289 :preselect preselect
1291 :update-fn update-fn
1294 :window (selected-window)
1295 :buffer (current-buffer)
1297 :re-builder re-builder
1299 :dynamic-collection dynamic-collection
1300 :display-transformer-fn transformer-fn
1302 (ivy--reset-state ivy-last)
1305 (minibuffer-with-setup-hook
1306 #'ivy--minibuffer-setup
1307 (let* ((hist (or history 'ivy-history))
1308 (minibuffer-completion-table collection)
1309 (minibuffer-completion-predicate predicate)
1310 (resize-mini-windows (cond
1311 ((display-graphic-p) nil)
1312 ((null resize-mini-windows) 'grow-only)
1313 (t resize-mini-windows))))
1314 (read-from-minibuffer
1316 (ivy-state-initial-input ivy-last)
1317 (make-composed-keymap keymap ivy-minibuffer-map)
1320 (when (eq ivy-exit 'done)
1321 (let ((item (if ivy--directory
1324 (unless (equal item "")
1325 (set hist (cons (propertize item 'ivy-index ivy--index)
1327 (cdr (symbol-value hist))))))))
1329 (remove-hook 'post-command-hook #'ivy--exhibit)
1330 (when (setq unwind (ivy-state-unwind ivy-last))
1332 (unless (eq ivy-exit 'done)
1333 (when recursive-ivy-last
1334 (ivy--reset-state (setq ivy-last recursive-ivy-last)))))
1336 (when (and recursive-ivy-last
1337 ivy-recursive-restore)
1338 (ivy--reset-state (setq ivy-last recursive-ivy-last))))))
1340 (defun ivy--reset-state (state)
1341 "Reset the ivy to STATE.
1342 This is useful for recursive `ivy-read'."
1343 (let ((prompt (or (ivy-state-prompt state) ""))
1344 (collection (ivy-state-collection state))
1345 (predicate (ivy-state-predicate state))
1346 (history (ivy-state-history state))
1347 (preselect (ivy-state-preselect state))
1348 (sort (ivy-state-sort state))
1349 (re-builder (ivy-state-re-builder state))
1350 (dynamic-collection (ivy-state-dynamic-collection state))
1351 (initial-input (ivy-state-initial-input state))
1352 (require-match (ivy-state-require-match state))
1353 (caller (ivy-state-caller state)))
1354 (unless initial-input
1355 (setq initial-input (cdr (assoc this-command
1356 ivy-initial-inputs-alist))))
1357 (setq ivy--directory nil)
1358 (setq ivy-case-fold-search 'auto)
1359 (setq ivy--regex-function
1361 (and (functionp collection)
1362 (cdr (assoc collection ivy-re-builders-alist)))
1364 (cdr (assoc caller ivy-re-builders-alist)))
1365 (cdr (assoc this-command ivy-re-builders-alist))
1366 (cdr (assoc t ivy-re-builders-alist))
1368 (setq ivy--subexps 0)
1369 (setq ivy--regexp-quote 'regexp-quote)
1370 (setq ivy--old-text "")
1371 (setq ivy--full-length nil)
1373 (setq ivy-calling nil)
1374 (setq ivy-use-ignore t)
1376 (cond ((eq collection 'Info-read-node-name-1)
1377 (if (equal Info-current-file "dir")
1379 (mapcar (lambda (x) (format "(%s)" x))
1380 (cl-delete-duplicates
1381 (all-completions "(" collection predicate)
1383 (setq coll (all-completions "" collection predicate))))
1384 ((eq collection 'read-file-name-internal)
1385 (setq ivy--directory default-directory)
1388 (let ((preselect-directory (file-name-directory preselect)))
1389 (unless (or (null preselect-directory)
1390 (string= preselect-directory
1392 (setq ivy--directory preselect-directory))
1394 (ivy-state-preselect state)
1395 (setq preselect (file-name-nondirectory preselect)))))
1396 (setq coll (ivy--sorted-files ivy--directory))
1398 (unless (or require-match
1399 (equal initial-input default-directory)
1400 (equal initial-input ""))
1401 (setq coll (cons initial-input coll)))
1402 (unless (and (ivy-state-action ivy-last)
1403 (not (equal (ivy--get-action ivy-last) 'identity)))
1404 (setq initial-input nil))))
1405 ((eq collection 'internal-complete-buffer)
1406 (setq coll (ivy--buffer-list "" ivy-use-virtual-buffers)))
1408 (setq coll (funcall collection ivy-text)))
1409 ((or (functionp collection)
1410 (byte-code-function-p collection)
1411 (vectorp collection)
1412 (and (consp collection) (listp (car collection)))
1413 (hash-table-p collection)
1414 (and (listp collection) (symbolp (car collection))))
1415 (setq coll (all-completions "" collection predicate)))
1417 (setq coll collection)))
1419 (if (and (functionp collection)
1420 (setq sort-fn (assoc collection ivy-sort-functions-alist)))
1421 (when (and (setq sort-fn (cdr sort-fn))
1422 (not (eq collection 'read-file-name-internal)))
1423 (setq coll (cl-sort coll sort-fn)))
1424 (unless (eq history 'org-refile-history)
1425 (if (and (setq sort-fn (cdr (assoc t ivy-sort-functions-alist)))
1426 (<= (length coll) ivy-sort-max-size))
1427 (setq coll (cl-sort (copy-sequence coll) sort-fn))))))
1429 (unless (or (and require-match
1430 (not (eq collection 'internal-complete-buffer)))
1432 (let ((re (regexp-quote preselect)))
1433 (cl-find-if (lambda (x) (string-match re x))
1435 (setq coll (cons preselect coll))))
1436 (setq ivy--old-re nil)
1437 (setq ivy--old-cands nil)
1438 (when (integerp preselect)
1439 (setq ivy--old-re "")
1440 (setq ivy--index preselect))
1442 ;; Needed for anchor to work
1443 (setq ivy--old-cands coll)
1444 (setq ivy--old-cands (ivy--filter initial-input coll)))
1445 (setq ivy--all-candidates coll)
1446 (unless (integerp preselect)
1447 (setq ivy--index (or
1448 (and dynamic-collection
1451 (ivy--preselect-index
1459 (if (region-active-p)
1463 (ivy-thing-at-point)))
1465 (cond ((string-match "%.*d" prompt)
1467 ((null ivy-count-format)
1469 "`ivy-count-format' can't be nil. Set it to an empty string instead"))
1470 ((string-match "%d.*%d" ivy-count-format)
1471 (let ((w (length (number-to-string
1472 (length ivy--all-candidates))))
1473 (s (copy-sequence ivy-count-format)))
1474 (string-match "%d" s)
1476 (string-match "%d" s (match-end 0))
1477 (setq s (replace-match (format "%%-%dd" w) nil nil s))
1478 (string-match "%d" s)
1479 (concat (replace-match (format "%%%dd" w) nil nil s)
1481 ((string-match "%.*d" ivy-count-format)
1482 (concat ivy-count-format prompt))
1487 (setf (ivy-state-initial-input ivy-last) initial-input)))
1490 (defun ivy-completing-read (prompt collection
1491 &optional predicate require-match initial-input
1492 history def inherit-input-method)
1493 "Read a string in the minibuffer, with completion.
1495 This interface conforms to `completing-read' and can be used for
1496 `completing-read-function'.
1498 PROMPT is a string that normally ends in a colon and a space.
1499 COLLECTION is either a list of strings, an alist, an obarray, or a hash table.
1500 PREDICATE limits completion to a subset of COLLECTION.
1501 REQUIRE-MATCH is a boolean value. See `completing-read'.
1502 INITIAL-INPUT is a string inserted into the minibuffer initially.
1503 HISTORY is a list of previously selected inputs.
1504 DEF is the default value.
1505 INHERIT-INPUT-METHOD is currently ignored."
1506 (if (memq this-command '(tmm-menubar tmm-shortcut))
1507 (completing-read-default prompt collection
1508 predicate require-match
1509 initial-input history
1510 def inherit-input-method)
1511 ;; See the doc of `completing-read'.
1512 (when (consp history)
1513 (when (numberp (cdr history))
1514 (setq initial-input (nth (1- (cdr history))
1515 (symbol-value (car history)))))
1516 (setq history (car history)))
1517 (ivy-read (replace-regexp-in-string "%" "%%" prompt)
1519 :predicate predicate
1520 :require-match require-match
1521 :initial-input (if (consp initial-input)
1523 (if (and (stringp initial-input)
1524 (string-match "\\+" initial-input))
1525 (replace-regexp-in-string
1526 "\\+" "\\\\+" initial-input)
1528 :preselect (if (listp def) (car def) def)
1532 (let ((sort (assoc this-command ivy-sort-functions-alist)))
1537 (defvar ivy-completion-beg nil
1538 "Completion bounds start.")
1540 (defvar ivy-completion-end nil
1541 "Completion bounds end.")
1543 (defun ivy-completion-in-region-action (str)
1544 "Insert STR, erasing the previous one.
1545 The previous string is between `ivy-completion-beg' and `ivy-completion-end'."
1548 (when ivy-completion-beg
1551 ivy-completion-end))
1552 (setq ivy-completion-beg
1553 (move-marker (make-marker) (point)))
1555 (setq ivy-completion-end
1556 (move-marker (make-marker) (point))))))
1558 (defun ivy-completion-common-length (str)
1559 "Return the length of the first 'completions-common-part face in STR."
1562 (while (and (<= pos len)
1563 (let ((prop (get-text-property pos 'face str)))
1564 (not (eq 'completions-common-part
1565 (if (listp prop) (car prop) prop)))))
1566 (setq pos (1+ pos)))
1568 (or (next-single-property-change pos 'face str) len)
1571 (defun ivy-completion-in-region (start end collection &optional predicate)
1572 "An Ivy function suitable for `completion-in-region-function'."
1573 (let* ((enable-recursive-minibuffers t)
1574 (str (buffer-substring-no-properties start end))
1575 (completion-ignore-case case-fold-search)
1577 (completion-all-completions str collection predicate (- end start))))
1579 (message "No matches")
1581 (setq ivy-completion-beg (- end (ivy-completion-common-length (car comps))))
1582 (setq ivy-completion-end end)
1583 (if (null (cdr comps))
1584 (if (string= str (car comps))
1585 (message "Sole match")
1586 (setf (ivy-state-window ivy-last) (selected-window))
1587 (ivy-completion-in-region-action
1588 (substring-no-properties
1590 (let* ((w (1+ (floor (log (length comps) 10))))
1591 (ivy-count-format (if (string= ivy-count-format "")
1593 (format "%%-%dd " w)))
1594 (prompt (format "(%s): " str)))
1596 (ivy-read (if (string= ivy-count-format "")
1598 (replace-regexp-in-string "%" "%%" prompt))
1599 ;; remove 'completions-first-difference face
1600 (mapcar #'substring-no-properties comps)
1601 :predicate predicate
1602 :action #'ivy-completion-in-region-action
1606 (defcustom ivy-do-completion-in-region t
1607 "When non-nil `ivy-mode' will set `completion-in-region-function'."
1611 (define-minor-mode ivy-mode
1612 "Toggle Ivy mode on or off.
1613 Turn Ivy mode on if ARG is positive, off otherwise.
1614 Turning on Ivy mode sets `completing-read-function' to
1615 `ivy-completing-read'.
1620 Minibuffer bindings:
1621 \\{ivy-minibuffer-map}"
1624 :keymap ivy-mode-map
1628 (setq completing-read-function 'ivy-completing-read)
1629 (when ivy-do-completion-in-region
1630 (setq completion-in-region-function 'ivy-completion-in-region)))
1631 (setq completing-read-function 'completing-read-default)
1632 (setq completion-in-region-function 'completion--in-region)))
1634 (defun ivy--preselect-index (preselect candidates)
1635 "Return the index of PRESELECT in CANDIDATES."
1636 (cond ((integerp preselect)
1638 ((cl-position preselect candidates :test #'equal))
1639 ((stringp preselect)
1640 (let ((re preselect))
1643 (string-match re x))
1648 (defvar ivy--regex-hash
1649 (make-hash-table :test #'equal)
1650 "Store pre-computed regex.")
1652 (defun ivy--split (str)
1653 "Split STR into a list by single spaces.
1654 The remaining spaces stick to their left.
1655 This allows to \"quote\" N spaces by inputting N+1 spaces."
1656 (let ((len (length str))
1661 (while (and (string-match " +" str start1)
1663 (setq match-len (- (match-end 0) (match-beginning 0)))
1667 (setq start1 start0)
1669 (push (substring str start1 (match-beginning 0)) res)
1670 (setq start1 (match-end 0)))
1671 (setq str (replace-match
1672 (make-string (1- match-len) ?\ )
1674 (setq start0 (or start0 start1))
1675 (setq start1 (1- (match-end 0)))))
1677 (push (substring str start0) res)
1678 (setq s (substring str start1))
1679 (unless (= (length s) 0)
1683 (defun ivy--regex (str &optional greedy)
1684 "Re-build regex pattern from STR in case it has a space.
1685 When GREEDY is non-nil, join words in a greedy way."
1686 (let ((hashed (unless greedy
1687 (gethash str ivy--regex-hash))))
1690 (setq ivy--subexps (car hashed)))
1691 (when (string-match "\\([^\\]\\|^\\)\\\\$" str)
1692 (setq str (substring str 0 -1)))
1694 (let ((subs (ivy--split str)))
1695 (if (= (length subs) 1)
1697 (setq ivy--subexps 0)
1700 (setq ivy--subexps (length subs))
1703 (if (string-match "\\`\\\\([^?].*\\\\)\\'" x)
1705 (format "\\(%s\\)" x)))
1710 ivy--regex-hash)))))
1712 (defun ivy--regex-ignore-order--part (str &optional discard)
1713 "Re-build regex from STR by splitting at spaces.
1714 Ignore the order of each group."
1715 (let* ((subs (split-string str " +" t))
1716 (len (length subs)))
1721 (mapcar (lambda (x) (cons x (not discard)))
1724 (defun ivy--regex-ignore-order (str)
1725 "Re-build regex from STR by splitting at spaces.
1726 Ignore the order of each group. Everything before \"!\" should
1727 match. Everything after \"!\" should not match."
1728 (let ((parts (split-string str "!" t)))
1729 (cl-case (length parts)
1733 (if (string= (substring str 0 1) "!")
1735 (ivy--regex-ignore-order--part (car parts) t))
1736 (ivy--regex-ignore-order--part (car parts))))
1739 (ivy--regex-ignore-order--part (car parts))
1740 (ivy--regex-ignore-order--part (cadr parts) t)))
1741 (t (error "Unexpected: use only one !")))))
1743 (defun ivy--regex-plus (str)
1744 "Build a regex sequence from STR.
1745 Spaces are wild card characters, everything before \"!\" should
1746 match. Everything after \"!\" should not match."
1747 (let ((parts (split-string str "!" t)))
1748 (cl-case (length parts)
1752 (if (string= (substring str 0 1) "!")
1754 (list (ivy--regex (car parts))))
1755 (ivy--regex (car parts))))
1758 (cons (ivy--regex (car parts)) t)
1759 (mapcar #'list (split-string (cadr parts) " " t))))
1760 (t (error "Unexpected: use only one !")))))
1762 (defun ivy--regex-fuzzy (str)
1763 "Build a regex sequence from STR.
1764 Insert .* between each char."
1765 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1767 (concat (match-string 1 str)
1770 (format "\\(%c\\)" x))
1771 (string-to-list (match-string 2 str)) ".*")
1772 (match-string 3 str))
1773 (setq ivy--subexps (length (match-string 2 str))))
1776 (defcustom ivy-fixed-height-minibuffer nil
1777 "When non nil, fix the height of the minibuffer during ivy
1778 completion at `ivy-height'. This effectively sets the minimum
1779 height at this level and tries to ensure that it does not change
1780 depending on the number of candidates."
1785 (defun ivy--minibuffer-setup ()
1786 "Setup ivy completion in the minibuffer."
1787 (set (make-local-variable 'completion-show-inline-help) nil)
1788 (set (make-local-variable 'minibuffer-default-add-function)
1790 (list ivy--default)))
1791 (when (display-graphic-p)
1792 (setq truncate-lines t))
1793 (setq-local max-mini-window-height ivy-height)
1794 (when ivy-fixed-height-minibuffer
1795 (set-window-text-height (selected-window) ivy-height))
1796 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1797 ;; show completions with empty input
1800 (defun ivy--input ()
1801 "Return the current minibuffer input."
1802 ;; assume one-line minibuffer input
1803 (buffer-substring-no-properties
1804 (minibuffer-prompt-end)
1805 (line-end-position)))
1807 (defun ivy--cleanup ()
1808 "Delete the displayed completion candidates."
1810 (goto-char (minibuffer-prompt-end))
1811 (delete-region (line-end-position) (point-max))))
1813 (defun ivy--insert-prompt ()
1814 "Update the prompt according to `ivy--prompt'."
1816 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1817 counsel-find-symbol))
1818 (setq ivy--prompt-extra ""))
1820 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1822 (setq head (match-string 1 ivy--prompt))
1824 (setq head (substring ivy--prompt 0 -1))
1826 (let ((inhibit-read-only t)
1827 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1830 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1831 (> (minibuffer-depth) 1))
1832 (format "[%d] " (minibuffer-depth))
1835 (if (string-match "%d.*%d" ivy-count-format)
1838 (or (and (ivy-state-dynamic-collection ivy-last)
1842 (or (and (ivy-state-dynamic-collection ivy-last)
1847 (d-str (if ivy--directory
1848 (abbreviate-file-name ivy--directory)
1851 (goto-char (point-min))
1852 (delete-region (point-min) (minibuffer-prompt-end))
1853 (if (> (+ (mod (+ (length n-str) (length d-str)) (window-width))
1856 (setq n-str (concat n-str "\n" d-str))
1857 (setq n-str (concat n-str d-str)))
1858 (let ((regex (format "\\([^\n]\\{%d\\}\\)[^\n]" (window-width))))
1859 (while (string-match regex n-str)
1860 (setq n-str (replace-match (concat (match-string 1 n-str) "\n") nil t n-str 1))))
1861 (set-text-properties 0 (length n-str)
1862 `(face minibuffer-prompt ,@std-props)
1864 (ivy--set-match-props n-str "confirm"
1865 `(face ivy-confirm-face ,@std-props))
1866 (ivy--set-match-props n-str "match required"
1867 `(face ivy-match-required-face ,@std-props))
1869 ;; get out of the prompt area
1870 (constrain-to-field nil (point-max))))))
1872 (defun ivy--set-match-props (str match props)
1873 "Set STR text properties that match MATCH to PROPS."
1874 (when (string-match match str)
1875 (set-text-properties
1881 (defvar inhibit-message)
1883 (defun ivy--sort-maybe (collection)
1884 "Sort COLLECTION if needed."
1885 (let ((sort (ivy-state-sort ivy-last))
1889 (let ((sort-fn (cond ((functionp sort)
1891 ((setq entry (assoc (ivy-state-collection ivy-last)
1892 ivy-sort-functions-alist))
1895 (cdr (assoc t ivy-sort-functions-alist))))))
1896 (if (functionp sort-fn)
1897 (cl-sort (copy-sequence collection) sort-fn)
1900 (defun ivy--exhibit ()
1901 "Insert Ivy completions display.
1902 Should be run via minibuffer `post-command-hook'."
1903 (when (memq 'ivy--exhibit post-command-hook)
1904 (let ((inhibit-field-text-motion nil))
1905 (constrain-to-field nil (point-max)))
1906 (setq ivy-text (ivy--input))
1907 (if (ivy-state-dynamic-collection ivy-last)
1908 ;; while-no-input would cause annoying
1909 ;; "Waiting for process to die...done" message interruptions
1910 (let ((inhibit-message t))
1911 (unless (equal ivy--old-text ivy-text)
1913 (setq ivy--all-candidates
1915 (funcall (ivy-state-collection ivy-last) ivy-text)))
1916 (setq ivy--old-text ivy-text)))
1917 (when ivy--all-candidates
1918 (ivy--insert-minibuffer
1919 (ivy--format ivy--all-candidates))))
1920 (cond (ivy--directory
1921 (if (string-match "/\\'" ivy-text)
1922 (if (member ivy-text ivy--all-candidates)
1923 (ivy--cd (expand-file-name ivy-text ivy--directory))
1924 (when (string-match "//\\'" ivy-text)
1925 (if (and default-directory
1926 (string-match "\\`[[:alpha:]]:/" default-directory))
1927 (ivy--cd (match-string 0 default-directory))
1929 (when (string-match "[[:alpha:]]:/$" ivy-text)
1930 (let ((drive-root (match-string 0 ivy-text)))
1931 (when (file-exists-p drive-root)
1932 (ivy--cd drive-root)))))
1933 (if (string-match "\\`~\\'" ivy-text)
1934 (ivy--cd (expand-file-name "~/")))))
1935 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1936 (when (or (and (string-match "\\` " ivy-text)
1937 (not (string-match "\\` " ivy--old-text)))
1938 (and (string-match "\\` " ivy--old-text)
1939 (not (string-match "\\` " ivy-text))))
1940 (setq ivy--all-candidates
1941 (if (and (> (length ivy-text) 0)
1942 (eq (aref ivy-text 0)
1944 (ivy--buffer-list " ")
1945 (ivy--buffer-list "" ivy-use-virtual-buffers)))
1946 (setq ivy--old-re nil))))
1947 (ivy--insert-minibuffer
1948 (with-current-buffer (ivy-state-buffer ivy-last)
1950 (ivy--filter ivy-text ivy--all-candidates))))
1951 (setq ivy--old-text ivy-text))))
1953 (defun ivy--insert-minibuffer (text)
1954 "Insert TEXT into minibuffer with appropriate cleanup."
1955 (let ((resize-mini-windows nil)
1956 (update-fn (ivy-state-update-fn ivy-last))
1960 (funcall update-fn))
1961 (ivy--insert-prompt)
1962 ;; Do nothing if while-no-input was aborted.
1963 (when (stringp text)
1964 (let ((buffer-undo-list t))
1968 (when (display-graphic-p)
1969 (ivy--resize-minibuffer-to-fit))))
1971 (defun ivy--resize-minibuffer-to-fit ()
1972 "Resize the minibuffer window size to fit the text in the minibuffer."
1973 (unless (frame-root-window-p (minibuffer-window))
1974 (with-selected-window (minibuffer-window)
1975 (if (fboundp 'window-text-pixel-size)
1976 (let ((text-height (cdr (window-text-pixel-size)))
1977 (body-height (window-body-height nil t)))
1978 (when (> text-height body-height)
1979 ;; Note: the size increment needs to be at least frame-char-height,
1980 ;; otherwise resizing won't do anything.
1981 (let ((delta (max (- text-height body-height) (frame-char-height))))
1982 (window-resize nil delta nil t t))))
1983 (let ((text-height (count-screen-lines))
1984 (body-height (window-body-height)))
1985 (when (> text-height body-height)
1986 (window-resize nil (- text-height body-height) nil t)))))))
1988 (declare-function colir-blend-face-background "ext:colir")
1990 (defun ivy--add-face (str face)
1991 "Propertize STR with FACE.
1992 `font-lock-append-text-property' is used, since it's better than
1993 `propertize' or `add-face-text-property' in this case."
1997 (colir-blend-face-background 0 (length str) face str)
1998 (let ((foreground (face-foreground face)))
2000 (add-face-text-property
2002 `(:foreground ,foreground)
2007 (font-lock-append-text-property 0 (length str) 'face face str))))
2010 (declare-function flx-make-string-cache "ext:flx")
2011 (declare-function flx-score "ext:flx")
2013 (defvar ivy--flx-cache nil)
2015 (eval-after-load 'flx
2016 '(setq ivy--flx-cache (flx-make-string-cache)))
2018 (defun ivy-toggle-case-fold ()
2019 "Toggle the case folding between nil and auto.
2020 In any completion session, the case folding starts in auto:
2022 - when the input is all lower case, `case-fold-search' is t
2025 You can toggle this to make `case-fold-search' nil regardless of input."
2027 (setq ivy-case-fold-search
2028 (if ivy-case-fold-search
2031 ;; reset cache so that the candidate list updates
2032 (setq ivy--old-re nil))
2034 (defun ivy--re-filter (re candidates)
2035 "Return all RE matching CANDIDATES.
2036 RE is a list of cons cells, with a regexp car and a boolean cdr.
2037 When the cdr is t, the car must match.
2038 Otherwise, the car must not match."
2039 (let ((re-list (if (stringp re) (list (cons re t)) re))
2041 (dolist (re re-list)
2048 (let ((re-str (car re)))
2049 (lambda (x) (string-match re-str x)))
2053 (defun ivy--filter (name candidates)
2054 "Return all items that match NAME in CANDIDATES.
2055 CANDIDATES are assumed to be static."
2056 (let ((re (funcall ivy--regex-function name)))
2057 (if (and (equal re ivy--old-re)
2059 ;; quick caching for "C-n", "C-p" etc.
2061 (let* ((re-str (if (listp re) (caar re) re))
2062 (matcher (ivy-state-matcher ivy-last))
2064 (and ivy-case-fold-search
2065 (string= name (downcase name))))
2068 (funcall matcher re candidates))
2071 (stringp ivy--old-re)
2072 (not (string-match "\\\\" ivy--old-re))
2073 (not (equal ivy--old-re ""))
2075 (if (string-match "\\\\)\\'" ivy--old-re)
2076 (substring ivy--old-re 0 -2)
2082 (lambda (x) (string-match re x))
2085 (ivy--re-filter re candidates)))))
2086 (ivy--recompute-index name re-str cands)
2088 (if (eq ivy--regex-function 'ivy--regex-ignore-order)
2093 (setq ivy--old-cands (ivy--sort name cands))))))
2095 (defun ivy--set-candidates (x)
2096 "Update `ivy--all-candidates' with X."
2098 (dolist (source ivy--extra-candidates)
2099 (if (equal source '(original-source))
2102 (setq res (append x res)))
2103 (setq ivy--old-re nil)
2105 (ivy--filter ivy-text (cadr source))
2107 (setq ivy--all-candidates res)))
2109 (defcustom ivy-sort-matches-functions-alist '((t . nil))
2110 "An alist of functions for sorting matching candidates.
2112 Unlike `ivy-sort-functions-alist', which is used to sort the
2113 whole collection only once, this alist of functions are used to
2114 sort only matching candidates after each change in input.
2116 The alist KEY is either a collection function or t to match
2117 previously unmatched collection functions.
2119 The alist VAL is a sorting function with the signature of
2120 `ivy--prefix-sort'."
2123 (const :tag "Fall-through" t)
2124 (symbol :tag "Collection"))
2127 (const :tag "Don't sort" nil)
2128 (const :tag "Put prefix matches ahead" 'ivy--prefix-sort)
2129 (function :tag "Custom sort function"))))
2131 (defun ivy--sort-files-by-date (_name candidates)
2132 "Re-soft CANDIDATES according to file modification date."
2133 (let ((default-directory ivy--directory))
2134 (cl-sort (copy-sequence candidates)
2137 (nth 5 (file-attributes f2))
2138 (nth 5 (file-attributes f1)))))))
2140 (defun ivy--sort (name candidates)
2141 "Re-sort CANDIDATES by NAME.
2142 All CANDIDATES are assumed to match NAME."
2143 (let ((key (or (ivy-state-caller ivy-last)
2144 (when (functionp (ivy-state-collection ivy-last))
2145 (ivy-state-collection ivy-last))))
2147 (cond ((and (require 'flx nil 'noerror)
2148 (eq ivy--regex-function 'ivy--regex-fuzzy))
2149 (ivy--flx-sort name candidates))
2150 ((setq fun (cdr (or (assoc key ivy-sort-matches-functions-alist)
2151 (assoc t ivy-sort-matches-functions-alist))))
2152 (funcall fun name candidates))
2156 (defun ivy--prefix-sort (name candidates)
2157 "Re-sort CANDIDATES.
2158 Prefix matches to NAME are put ahead of the list."
2159 (if (or (string-match "^\\^" name) (string= name ""))
2161 (let ((re-prefix (concat "^" (funcall ivy--regex-function name)))
2164 (dolist (s candidates)
2165 (if (string-match re-prefix s)
2167 (push s res-noprefix)))
2169 (nreverse res-prefix)
2170 (nreverse res-noprefix)))))
2172 (defun ivy--recompute-index (name re-str cands)
2173 (let* ((caller (ivy-state-caller ivy-last))
2174 (func (or (and caller (cdr (assoc caller ivy-index-functions-alist)))
2175 (cdr (assoc t ivy-index-functions-alist))
2176 #'ivy-recompute-index-zero)))
2177 (unless (eq this-command 'ivy-resume)
2180 (cl-position (if (and (> (length name) 0)
2181 (eq ?^ (aref name 0)))
2187 (concat re-str "/") cands
2189 (and (not (string= name ""))
2190 (not (and (require 'flx nil 'noerror)
2191 (eq ivy--regex-function 'ivy--regex-fuzzy)
2192 (< (length cands) 200)))
2194 (cl-position (nth ivy--index ivy--old-cands)
2196 (funcall func re-str cands))))
2197 (when (and (or (string= name "")
2199 (not (equal ivy--old-re "")))
2201 (or (ivy--preselect-index
2202 (ivy-state-preselect ivy-last)
2206 (defun ivy-recompute-index-swiper (_re-str cands)
2207 (let ((tail (nthcdr ivy--index ivy--old-cands))
2209 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2211 (while (and tail (null idx))
2212 ;; Compare with eq to handle equal duplicates in cands
2213 (setq idx (cl-position (pop tail) cands)))
2216 (1- (length cands))))
2219 ;; already in ivy-state-buffer
2220 (let ((n (line-number-at-pos))
2224 (when (eq n (read (get-text-property 0 'display c)))
2229 (defun ivy-recompute-index-swiper-async (_re-str cands)
2230 (if (null ivy--old-cands)
2231 (let ((ln (with-ivy-window
2232 (line-number-at-pos))))
2233 (or (cl-position-if (lambda (x)
2234 (>= (string-to-number x) ln))
2237 (let ((tail (nthcdr ivy--index ivy--old-cands))
2239 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2241 (while (and tail (null idx))
2242 ;; Compare with `equal', since the collection is re-created
2243 ;; each time with `split-string'
2244 (setq idx (cl-position (pop tail) cands :test #'equal)))
2248 (defun ivy-recompute-index-zero (_re-str _cands)
2251 (defcustom ivy-minibuffer-faces
2252 '(ivy-minibuffer-match-face-1
2253 ivy-minibuffer-match-face-2
2254 ivy-minibuffer-match-face-3
2255 ivy-minibuffer-match-face-4)
2256 "List of `ivy' faces for minibuffer group matches."
2257 :type '(repeat :tag "Faces"
2259 (const ivy-minibuffer-match-face-1)
2260 (const ivy-minibuffer-match-face-2)
2261 (const ivy-minibuffer-match-face-3)
2262 (const ivy-minibuffer-match-face-4)
2263 (face :tag "Other face"))))
2265 (defvar ivy-flx-limit 200
2266 "Used to conditionally turn off flx sorting.
2268 When the amount of matching candidates exceeds this limit, then
2269 no sorting is done.")
2271 (defun ivy--flx-sort (name cands)
2272 "Sort according to closeness to string NAME the string list CANDS."
2275 (< (length cands) ivy-flx-limit))
2276 (let* ((flx-name (if (string-match "^\\^" name)
2283 (let ((score (flx-score x flx-name ivy--flx-cache)))
2287 (if cands-with-score
2289 (let ((str (copy-sequence (cdr x)))
2292 (dolist (j (cdar x))
2293 (unless (eq j (1+ last-j))
2296 (ivy-add-face-text-property
2298 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2299 ivy-minibuffer-faces)
2302 (sort cands-with-score
2304 (> (caar x) (caar y)))))
2310 (defcustom ivy-format-function 'ivy-format-function-default
2311 "Function to transform the list of candidates into a string.
2312 This string is inserted into the minibuffer."
2314 (const :tag "Default" ivy-format-function-default)
2315 (const :tag "Arrow prefix" ivy-format-function-arrow)
2316 (const :tag "Full line" ivy-format-function-line)))
2318 (defun ivy--truncate-string (str width)
2319 "Truncate STR to WIDTH."
2320 (if (> (string-width str) width)
2321 (concat (substring str 0 (min (- width 3)
2322 (- (length str) 3))) "...")
2325 (defun ivy--format-function-generic (selected-fn other-fn strs separator)
2326 "Transform CAND-PAIRS into a string for minibuffer.
2327 SELECTED-FN and OTHER-FN each take one string argument.
2328 SEPARATOR is used to join the candidates."
2332 (let ((curr (eq (cl-incf i) ivy--index)))
2334 (funcall selected-fn str)
2335 (funcall other-fn str))))
2339 (defun ivy-format-function-default (cands)
2340 "Transform CAND-PAIRS into a string for minibuffer."
2341 (ivy--format-function-generic
2343 (ivy--add-face str 'ivy-current-match))
2348 (defun ivy-format-function-arrow (cands)
2349 "Transform CAND-PAIRS into a string for minibuffer."
2350 (ivy--format-function-generic
2352 (concat "> " (ivy--add-face str 'ivy-current-match)))
2358 (defun ivy-format-function-line (cands)
2359 "Transform CAND-PAIRS into a string for minibuffer."
2360 (ivy--format-function-generic
2362 (ivy--add-face (concat str "\n") 'ivy-current-match))
2368 (defun ivy-add-face-text-property (start end face str)
2369 (if (fboundp 'add-face-text-property)
2370 (add-face-text-property
2371 start end face nil str)
2372 (font-lock-append-text-property
2373 start end 'face face str)))
2375 (defun ivy--format-minibuffer-line (str)
2377 (str (copy-sequence str)))
2378 (cond ((eq ivy--regex-function 'ivy--regex-ignore-order)
2379 (when (consp ivy--old-re)
2381 (dolist (re ivy--old-re)
2382 (when (string-match (car re) str)
2383 (ivy-add-face-text-property
2384 (match-beginning 0) (match-end 0)
2385 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2386 ivy-minibuffer-faces)
2389 ((and (eq ivy-display-style 'fancy)
2390 (not (eq ivy--regex-function 'ivy--regex-fuzzy)))
2392 (setq ivy--old-re (funcall ivy--regex-function ivy-text)))
2393 (while (and (string-match ivy--old-re str start)
2394 (> (- (match-end 0) (match-beginning 0)) 0))
2395 (setq start (match-end 0))
2397 (while (<= i ivy--subexps)
2399 (cond ((zerop ivy--subexps)
2400 (cadr ivy-minibuffer-faces))
2402 (car ivy-minibuffer-faces))
2404 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2405 ivy-minibuffer-faces)))))
2406 (ivy-add-face-text-property
2407 (match-beginning i) (match-end i)
2412 (ivy-set-display-transformer
2413 'read-file-name-internal 'ivy-read-file-transformer)
2415 (defun ivy-read-file-transformer (str)
2416 (if (string-match-p "/\\'" str)
2417 (propertize str 'face 'ivy-subdir)
2420 (defun ivy--format (cands)
2421 "Return a string for CANDS suitable for display in the minibuffer.
2422 CANDS is a list of strings."
2423 (setq ivy--length (length cands))
2424 (when (>= ivy--index ivy--length)
2425 (setq ivy--index (max (1- ivy--length) 0)))
2427 (setq ivy--current "")
2428 (let* ((half-height (/ ivy-height 2))
2429 (start (max 0 (- ivy--index half-height)))
2430 (end (min (+ start (1- ivy-height)) ivy--length))
2431 (start (max 0 (min start (- end (1- ivy-height)))))
2432 (cands (cl-subseq cands start end))
2433 (index (- ivy--index start))
2435 (setq ivy--current (copy-sequence (nth index cands)))
2436 (when (setq transformer-fn (ivy-state-display-transformer-fn ivy-last))
2438 (setq cands (mapcar transformer-fn cands))))
2439 (let* ((ivy--index index)
2441 #'ivy--format-minibuffer-line
2443 (res (concat "\n" (funcall ivy-format-function cands))))
2444 (put-text-property 0 (length res) 'read-only nil res)
2447 (defvar ivy--virtual-buffers nil
2448 "Store the virtual buffers alist.")
2450 (defvar recentf-list)
2452 (defcustom ivy-virtual-abbreviate 'name
2453 "The mode of abbreviation for virtual buffer names."
2455 (const :tag "Only name" name)
2456 (const :tag "Full path" full)
2457 ;; eventually, uniquify
2460 (defun ivy--virtual-buffers ()
2461 "Adapted from `ido-add-virtual-buffers-to-list'."
2462 (unless recentf-mode
2464 (let ((bookmarks (and (boundp 'bookmark-alist)
2466 virtual-buffers name)
2467 (dolist (head (append
2469 (delete " - no file -"
2470 (delq nil (mapcar (lambda (bookmark)
2471 (cdr (assoc 'filename bookmark)))
2474 (if (eq ivy-virtual-abbreviate 'name)
2475 (file-name-nondirectory head)
2476 (expand-file-name head)))
2477 (when (equal name "")
2478 (setq name (file-name-nondirectory (directory-file-name head))))
2479 (when (equal name "")
2481 (and (not (equal name ""))
2482 (null (get-file-buffer head))
2483 (not (assoc name virtual-buffers))
2484 (push (cons name head) virtual-buffers)))
2485 (when virtual-buffers
2486 (dolist (comp virtual-buffers)
2487 (put-text-property 0 (length (car comp))
2490 (setq ivy--virtual-buffers (nreverse virtual-buffers))
2491 (mapcar #'car ivy--virtual-buffers))))
2493 (defcustom ivy-ignore-buffers '("\\` ")
2494 "List of regexps or functions matching buffer names to ignore."
2495 :type '(repeat (choice regexp function)))
2497 (defun ivy--buffer-list (str &optional virtual)
2498 "Return the buffers that match STR.
2499 When VIRTUAL is non-nil, add virtual buffers."
2504 (if (with-current-buffer x
2506 (abbreviate-file-name default-directory)))
2507 (propertize x 'face 'ivy-remote)
2509 (all-completions str 'internal-complete-buffer))
2511 (ivy--virtual-buffers)))))
2513 (defun ivy--switch-buffer-action (buffer)
2515 BUFFER may be a string or nil."
2517 (if (zerop (length buffer))
2519 ivy-text nil 'force-same-window)
2520 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2522 (not (get-buffer buffer)))
2523 (find-file (cdr virtual))
2525 buffer nil 'force-same-window))))))
2527 (defun ivy--switch-buffer-other-window-action (buffer)
2528 "Switch to BUFFER in other window.
2529 BUFFER may be a string or nil."
2530 (if (zerop (length buffer))
2531 (switch-to-buffer-other-window ivy-text)
2532 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2534 (not (get-buffer buffer)))
2535 (find-file-other-window (cdr virtual))
2536 (switch-to-buffer-other-window buffer)))))
2538 (defun ivy--rename-buffer-action (buffer)
2540 (let ((new-name (read-string "Rename buffer (to new name): ")))
2541 (with-current-buffer buffer
2542 (rename-buffer new-name))))
2544 (defvar ivy-switch-buffer-map (make-sparse-keymap))
2551 (ivy--reset-state ivy-last))
2554 ivy--switch-buffer-other-window-action
2557 ivy--rename-buffer-action
2560 (defun ivy--switch-buffer-matcher (regexp candidates)
2561 "Return REGEXP-matching CANDIDATES.
2562 Skip buffers that match `ivy-ignore-buffers'."
2563 (let ((res (ivy--re-filter regexp candidates)))
2564 (if (or (null ivy-use-ignore)
2565 (null ivy-ignore-buffers))
2571 (if (functionp f-or-r)
2572 (funcall f-or-r buf)
2573 (string-match-p f-or-r buf)))
2574 ivy-ignore-buffers))
2578 (ivy-set-display-transformer
2579 'ivy-switch-buffer 'ivy-switch-buffer-transformer)
2580 (ivy-set-display-transformer
2581 'internal-complete-buffer 'ivy-switch-buffer-transformer)
2583 (defun ivy-switch-buffer-transformer (str)
2584 (let ((b (get-buffer str)))
2586 (buffer-file-name b)
2587 (buffer-modified-p b))
2588 (propertize str 'face 'ivy-modified-buffer)
2591 (defun ivy-switch-buffer-occur ()
2592 "Occur function for `ivy-switch-buffer' that uses `ibuffer'."
2594 (concat "\\(" (mapconcat #'regexp-quote ivy--old-cands "\\|") "\\)"))
2595 (new-qualifier `((name . ,cand-regexp))))
2596 (ibuffer nil (buffer-name) new-qualifier)))
2599 (defun ivy-switch-buffer ()
2600 "Switch to another buffer."
2602 (let ((this-command 'ivy-switch-buffer))
2603 (ivy-read "Switch to buffer: " 'internal-complete-buffer
2604 :matcher #'ivy--switch-buffer-matcher
2605 :preselect (buffer-name (other-buffer (current-buffer)))
2606 :action #'ivy--switch-buffer-action
2607 :keymap ivy-switch-buffer-map
2608 :caller 'ivy-switch-buffer)))
2611 (defun ivy-switch-buffer-other-window ()
2612 "Switch to another buffer in another window."
2614 (ivy-read "Switch to buffer in other window: " 'internal-complete-buffer
2615 :preselect (buffer-name (other-buffer (current-buffer)))
2616 :action #'ivy--switch-buffer-other-window-action
2617 :keymap ivy-switch-buffer-map
2618 :caller 'ivy-switch-buffer-other-window))
2621 (defun ivy-recentf ()
2622 "Find a file on `recentf-list'."
2624 (ivy-read "Recentf: " recentf-list
2629 :caller 'ivy-recentf))
2631 (defun ivy-yank-word ()
2632 "Pull next word from buffer into search string."
2637 (le (line-end-position)))
2641 (setq amend (buffer-substring-no-properties pt (point))))))
2643 (insert (replace-regexp-in-string " +" " " amend)))))
2645 (defun ivy-kill-ring-save ()
2646 "Store the current candidates into the kill ring.
2647 If the region is active, forward to `kill-ring-save' instead."
2649 (if (region-active-p)
2650 (call-interactively 'kill-ring-save)
2657 (defun ivy-insert-current ()
2658 "Make the current candidate into current input.
2659 Don't finish completion."
2661 (delete-minibuffer-contents)
2662 (if (and ivy--directory
2663 (string-match "/$" ivy--current))
2664 (insert (substring ivy--current 0 -1))
2665 (insert ivy--current)))
2667 (defun ivy-toggle-fuzzy ()
2668 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
2670 (setq ivy--old-re nil)
2671 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
2672 (setq ivy--regex-function 'ivy--regex-plus)
2673 (setq ivy--regex-function 'ivy--regex-fuzzy)))
2675 (defun ivy-reverse-i-search ()
2676 "Enter a recursive `ivy-read' session using the current history.
2677 The selected history element will be inserted into the minibuffer."
2679 (let ((enable-recursive-minibuffers t)
2680 (history (symbol-value (ivy-state-history ivy-last)))
2682 (ivy-recursive-restore nil))
2683 (ivy-read "Reverse-i-search: "
2687 (setq ivy-last old-last))
2688 (delete-minibuffer-contents)
2689 (insert (substring-no-properties x))
2692 (defun ivy-restrict-to-matches ()
2693 "Restrict candidates to current matches and erase input."
2695 (delete-minibuffer-contents)
2696 (setq ivy--all-candidates
2697 (ivy--filter ivy-text ivy--all-candidates)))
2700 (defvar-local ivy-occur-last nil
2701 "Buffer-local value of `ivy-last'.
2702 Can't re-use `ivy-last' because using e.g. `swiper' in the same
2703 buffer would modify `ivy-last'.")
2705 (defvar ivy-occur-mode-map
2706 (let ((map (make-sparse-keymap)))
2707 (define-key map [mouse-1] 'ivy-occur-click)
2708 (define-key map (kbd "RET") 'ivy-occur-press)
2709 (define-key map (kbd "j") 'ivy-occur-next-line)
2710 (define-key map (kbd "k") 'ivy-occur-previous-line)
2711 (define-key map (kbd "h") 'backward-char)
2712 (define-key map (kbd "l") 'forward-char)
2713 (define-key map (kbd "f") 'ivy-occur-press)
2714 (define-key map (kbd "g") 'ivy-occur-revert-buffer)
2715 (define-key map (kbd "a") 'ivy-occur-read-action)
2716 (define-key map (kbd "o") 'ivy-occur-dispatch)
2717 (define-key map (kbd "c") 'ivy-occur-toggle-calling)
2718 (define-key map (kbd "q") 'quit-window)
2720 "Keymap for Ivy Occur mode.")
2722 (defun ivy-occur-toggle-calling ()
2723 "Toggle `ivy-calling'."
2725 (if (setq ivy-calling (not ivy-calling))
2727 (setq mode-name "Ivy-Occur [calling]")
2729 (setq mode-name "Ivy-Occur"))
2730 (force-mode-line-update))
2732 (defun ivy-occur-next-line (&optional arg)
2733 "Move the cursor down ARG lines.
2734 When `ivy-calling' isn't nil, call `ivy-occur-press'."
2740 (defun ivy-occur-previous-line (&optional arg)
2741 "Move the cursor up ARG lines.
2742 When `ivy-calling' isn't nil, call `ivy-occur-press'."
2744 (forward-line (- arg))
2748 (define-derived-mode ivy-occur-mode fundamental-mode "Ivy-Occur"
2749 "Major mode for output from \\[ivy-occur].
2751 \\{ivy-occur-mode-map}")
2753 (defvar ivy-occur-grep-mode-map
2754 (let ((map (copy-keymap ivy-occur-mode-map)))
2755 (define-key map (kbd "C-x C-q") 'ivy-wgrep-change-to-wgrep-mode)
2757 "Keymap for Ivy Occur Grep mode.")
2759 (define-derived-mode ivy-occur-grep-mode grep-mode "Ivy-Occur"
2760 "Major mode for output from \\[ivy-occur].
2762 \\{ivy-occur-grep-mode-map}")
2764 (defvar ivy--occurs-list nil
2765 "A list of custom occur generators per command.")
2767 (defun ivy-set-occur (cmd occur)
2768 "Assign CMD a custom OCCUR function."
2769 (setq ivy--occurs-list
2770 (plist-put ivy--occurs-list cmd occur)))
2772 (ivy-set-occur 'ivy-switch-buffer 'ivy-switch-buffer-occur)
2773 (ivy-set-occur 'ivy-switch-buffer-other-window 'ivy-switch-buffer-occur)
2775 (defun ivy--occur-insert-lines (cands)
2777 (add-text-properties
2781 help-echo "mouse-1: call ivy-action")
2786 "Stop completion and put the current matches into a new buffer.
2788 The new buffer remembers current action(s).
2790 While in the *ivy-occur* buffer, selecting a candidate with RET or
2791 a mouse click will call the appropriate action for that candidate.
2793 There is no limit on the number of *ivy-occur* buffers."
2795 (if (not (window-minibuffer-p))
2796 (user-error "No completion session is active")
2797 (let* ((caller (ivy-state-caller ivy-last))
2798 (occur-fn (plist-get ivy--occurs-list caller))
2800 (generate-new-buffer
2801 (format "*ivy-occur%s \"%s\"*"
2803 (concat " " (prin1-to-string caller))
2806 (with-current-buffer buffer
2807 (let ((inhibit-read-only t))
2812 (insert (format "%d candidates:\n" (length ivy--old-cands)))
2813 (ivy--occur-insert-lines
2815 (lambda (cand) (concat " " cand))
2817 (setf (ivy-state-text ivy-last) ivy-text)
2818 (setq ivy-occur-last ivy-last)
2819 (setq-local ivy--directory ivy--directory))
2820 (ivy-exit-with-action
2821 `(lambda (_) (pop-to-buffer ,buffer))))))
2823 (defun ivy-occur-revert-buffer ()
2824 "Refresh the buffer making it up-to date with the collection.
2826 Currently only works for `swiper'. In that specific case, the
2827 *ivy-occur* buffer becomes nearly useless as the orignal buffer
2828 is updated, since the line numbers no longer match.
2830 Calling this function is as if you called `ivy-occur' on the
2831 updated original buffer."
2833 (let ((caller (ivy-state-caller ivy-occur-last))
2834 (ivy-last ivy-occur-last))
2835 (when (eq caller 'swiper)
2836 (let ((buffer (ivy-state-buffer ivy-occur-last)))
2837 (unless (buffer-live-p buffer)
2838 (error "buffer was killed"))
2839 (let ((inhibit-read-only t))
2841 (funcall (plist-get ivy--occurs-list caller) t))))))
2843 (declare-function wgrep-change-to-wgrep-mode "ext:wgrep")
2845 (defun ivy-wgrep-change-to-wgrep-mode ()
2846 "Forward to `wgrep-change-to-wgrep-mode'."
2848 (if (require 'wgrep nil 'noerror)
2849 (wgrep-change-to-wgrep-mode)
2850 (error "Package wgrep isn't installed")))
2852 (defun ivy-occur-read-action ()
2853 "Select one of the available actions as the current one."
2855 (let ((ivy-last ivy-occur-last))
2858 (defun ivy-occur-dispatch ()
2859 "Call one of the available actions on the current item."
2861 (let* ((state-action (ivy-state-action ivy-occur-last))
2862 (actions (if (symbolp state-action)
2864 (copy-sequence state-action))))
2867 (ivy-occur-read-action)
2869 (setf (ivy-state-action ivy-occur-last) actions))))
2871 (defun ivy-occur-click (event)
2872 "Execute action for the current candidate.
2873 EVENT gives the mouse position."
2875 (let ((window (posn-window (event-end event)))
2876 (pos (posn-point (event-end event))))
2877 (with-current-buffer (window-buffer window)
2879 (ivy-occur-press))))
2881 (declare-function swiper--cleanup "swiper")
2882 (declare-function swiper--add-overlays "swiper")
2884 (defun ivy-occur-press ()
2885 "Execute action for the current candidate."
2887 (when (save-excursion
2889 (looking-at "\\(?:./\\| \\)\\(.*\\)$"))
2890 (when (memq (ivy-state-caller ivy-occur-last)
2891 '(swiper counsel-git-grep counsel-grep counsel-ag
2892 counsel-describe-function counsel-describe-variable))
2893 (let ((window (ivy-state-window ivy-occur-last)))
2894 (when (or (null (window-live-p window))
2895 (equal window (selected-window)))
2896 (save-selected-window
2897 (setf (ivy-state-window ivy-occur-last)
2898 (display-buffer (ivy-state-buffer ivy-occur-last)
2899 'display-buffer-pop-up-window))))))
2900 (let* ((ivy-last ivy-occur-last)
2901 (ivy-text (ivy-state-text ivy-last))
2902 (str (buffer-substring
2905 (coll (ivy-state-collection ivy-last))
2906 (action (ivy--get-action ivy-last))
2910 (if (and (consp coll)
2912 (cdr (assoc str coll))
2914 (if (memq (ivy-state-caller ivy-last)
2915 '(swiper counsel-git-grep))
2916 (with-current-buffer (window-buffer (selected-window))
2918 (swiper--add-overlays
2919 (ivy--regex ivy-text)
2920 (line-beginning-position)
2923 (run-at-time 0.5 nil 'swiper--cleanup)))))))
2925 (defvar ivy-help-file (let ((default-directory
2927 (file-name-directory load-file-name)
2928 default-directory)))
2929 (if (file-exists-p "ivy-help.org")
2930 (expand-file-name "ivy-help.org")
2931 (if (file-exists-p "doc/ivy-help.org")
2932 (expand-file-name "doc/ivy-help.org"))))
2933 "The file for `ivy-help'.")
2938 (let ((buf (get-buffer "*Ivy Help*")))
2940 (setq buf (get-buffer-create "*Ivy Help*"))
2941 (with-current-buffer buf
2942 (insert-file-contents ivy-help-file)
2945 (goto-char (point-min))))
2946 (if (eq this-command 'ivy-help)
2947 (switch-to-buffer buf)
2949 (pop-to-buffer buf)))
2951 (goto-char (point-min))))
2955 ;;; ivy.el ends here