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)
305 (cond ((stringp (setq s (thing-at-point 'symbol)))
306 (if (string-match "\\`[`']?\\(.*?\\)'?\\'" s)
309 ((looking-at "(+\\(\\(?:\\sw\\|\\s_\\)+\\)\\_>")
310 (match-string-no-properties 1))
314 (defvar ivy-history nil
315 "History list of candidates entered in the minibuffer.
317 Maximum length of the history list is determined by the value
318 of `history-length'.")
320 (defvar ivy--directory nil
321 "Current directory when completing file names.")
323 (defvar ivy--length 0
324 "Store the amount of viable candidates.")
327 "Store the user's string as it is typed in.")
329 (defvar ivy--current ""
330 "Current candidate.")
333 "Store the index of the current candidate.")
336 "Store 'done if the completion was successfully selected.
337 Otherwise, store nil.")
339 (defvar ivy--all-candidates nil
340 "Store the candidates passed to `ivy-read'.")
342 (defvar ivy--extra-candidates '((original-source))
343 "Store candidates added by the extra sources.
345 This is an internal-use alist. Each key is a function name, or
346 original-source (which represents where the current dynamic
347 candidates should go).
349 Each value is an evaluation of the function, in case of static
350 sources. These values will subsequently be filtered on `ivy-text'.
352 This variable is set by `ivy-read' and used by `ivy--set-candidates'.")
354 (defvar ivy-use-ignore t
355 "Store policy for user-configured candidate filtering.")
357 (defvar ivy--default nil
358 "Default initial input.")
360 (defvar ivy--prompt nil
361 "Store the format-style prompt.
362 When non-nil, it should contain at least one %d.")
364 (defvar ivy--prompt-extra ""
365 "Temporary modifications to the prompt.")
367 (defvar ivy--old-re nil
368 "Store the old regexp.")
370 (defvar ivy--old-cands nil
371 "Store the candidates matched by `ivy--old-re'.")
373 (defvar ivy--regex-function 'ivy--regex
374 "Current function for building a regex.")
376 (defvar ivy--subexps 0
377 "Number of groups in the current `ivy--regex'.")
379 (defvar ivy--full-length nil
380 "When :dynamic-collection is non-nil, this can be the total amount of candidates.")
382 (defvar ivy--old-text ""
383 "Store old `ivy-text' for dynamic completion.")
385 (defvar ivy-case-fold-search 'auto
386 "Store the current overriding `case-fold-search'.")
388 (defvar Info-current-file)
391 (unless (fboundp 'defvar-local)
392 (defmacro defvar-local (var val &optional docstring)
393 "Define VAR as a buffer-local variable with default value VAL."
394 (declare (debug defvar) (doc-string 3))
395 (list 'progn (list 'defvar var val docstring)
396 (list 'make-variable-buffer-local (list 'quote var)))))
397 (unless (fboundp 'setq-local)
398 (defmacro setq-local (var val)
399 "Set variable VAR to value VAL in current buffer."
400 (list 'set (list 'make-local-variable (list 'quote var)) val))))
402 (defmacro ivy-quit-and-run (&rest body)
403 "Quit the minibuffer and run BODY afterwards."
405 (put 'quit 'error-message "")
408 (put 'quit 'error-message "Quit")
410 (minibuffer-keyboard-quit)))
412 (defun ivy-exit-with-action (action)
413 "Quit the minibuffer and call ACTION afterwards."
417 (ivy-set-action ',(ivy-state-action ivy-last))))
418 (setq ivy-exit 'done)
421 (defmacro with-ivy-window (&rest body)
422 "Execute BODY in the window from which `ivy-read' was called."
425 `(with-selected-window (ivy--get-window ivy-last)
428 (defun ivy--done (text)
429 "Insert TEXT and exit minibuffer."
430 (if (and ivy--directory
431 (not (eq (ivy-state-history ivy-last) 'grep-files-history)))
432 (insert (setq ivy--current (expand-file-name
433 text ivy--directory)))
434 (insert (setq ivy--current text)))
435 (setq ivy-exit 'done)
440 "Exit the minibuffer with the selected candidate."
442 (delete-minibuffer-contents)
443 (cond ((> ivy--length 0)
444 (ivy--done ivy--current))
445 ((memq (ivy-state-collection ivy-last)
446 '(read-file-name-internal internal-complete-buffer))
447 (if (or (not (eq confirm-nonexistent-file-or-buffer t))
448 (equal " (confirm)" ivy--prompt-extra))
450 (setq ivy--prompt-extra " (confirm)")
453 ((memq (ivy-state-require-match ivy-last)
454 '(nil confirm confirm-after-completion))
455 (ivy--done ivy-text))
457 (setq ivy--prompt-extra " (match required)")
461 (defun ivy-read-action ()
462 "Change the action to one of the available ones.
464 Return nil for `minibuffer-keyboard-quit' or wrong key during the
465 selection, non-nil otherwise."
467 (let ((actions (ivy-state-action ivy-last)))
468 (if (null (ivy--actionp actions))
470 (let* ((hint (concat (if (eq this-command 'ivy-read-action)
479 'face 'font-lock-builtin-face)
484 (resize-mini-windows 'grow-only)
485 (key (string (read-key hint)))
486 (action-idx (cl-position-if
487 (lambda (x) (equal (car x) key))
489 (cond ((string= key "
\a")
492 (message "%s is not bound" key)
496 (setcar actions (1+ action-idx))
497 (ivy-set-action actions)))))))
499 (defun ivy-dispatching-done ()
500 "Select one of the available actions and call `ivy-done'."
502 (when (ivy-read-action)
505 (defun ivy-dispatching-call ()
506 "Select one of the available actions and call `ivy-call'."
508 (let ((actions (copy-sequence (ivy-state-action ivy-last))))
510 (when (ivy-read-action)
512 (ivy-set-action actions))))
514 (defun ivy-build-tramp-name (x)
515 "Reconstruct X into a path.
516 Is is a cons cell, related to `tramp-get-completion-function'."
520 (concat user "@" domain)
523 (declare-function tramp-get-completion-function "tramp")
524 (declare-function Info-find-node "info")
526 (defun ivy-alt-done (&optional arg)
527 "Exit the minibuffer with the selected candidate.
528 When ARG is t, exit with current text, ignoring the candidates."
531 (ivy-immediate-done))
533 (ivy--directory-done))
534 ((eq (ivy-state-collection ivy-last) 'Info-read-node-name-1)
535 (if (member ivy--current '("(./)" "(../)"))
537 (ivy-read "Go to file: " 'read-file-name-internal
540 (expand-file-name x ivy--directory)
546 (defun ivy--directory-done ()
547 "Handle exit from the minibuffer when completing file names."
550 ((equal ivy-text "/sudo::")
551 (setq dir (concat ivy-text ivy--directory))
556 (not (string= ivy-text ""))
557 (setq dir (ivy-expand-file-if-directory ivy-text)))
560 (not (string= ivy--current "./"))
561 (setq dir (ivy-expand-file-if-directory ivy--current))))
564 ((or (and (equal ivy--directory "/")
565 (string-match "\\`[^/]+:.*:.*\\'" ivy-text))
566 (string-match "\\`/[^/]+:.*:.*\\'" ivy-text))
568 ((or (and (equal ivy--directory "/")
570 "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
573 "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
575 (setq ivy-text ivy--current))))
577 "\\`/\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
579 (let ((method (match-string 1 ivy-text))
580 (user (match-string 2 ivy-text))
581 (rest (match-string 3 ivy-text))
584 (dolist (x (tramp-get-completion-function method))
585 (setq res (append res (funcall (car x) (cadr x)))))
586 (setq res (delq nil res))
590 (setq res (cl-delete-duplicates res :test #'equal))
591 (let* ((old-ivy-last ivy-last)
592 (enable-recursive-minibuffers t)
593 (host (ivy-read "user@host: "
594 (mapcar #'ivy-build-tramp-name res)
595 :initial-input rest)))
596 (setq ivy-last old-ivy-last)
598 (setq ivy--directory "/")
599 (ivy--cd (concat "/" method ":" host ":"))))))
603 (defun ivy-expand-file-if-directory (file-name)
604 "Expand FILE-NAME as directory.
605 When this directory doesn't exist, return nil."
606 (when (stringp file-name)
608 ;; Ignore host name must not match method "ssh"
610 (file-name-as-directory
611 (expand-file-name file-name ivy--directory)))))
612 (when (and full-name (file-directory-p full-name))
615 (defcustom ivy-tab-space nil
616 "When non-nil, `ivy-partial-or-done' should insert a space."
619 (defun ivy-partial-or-done ()
620 "Complete the minibuffer text as much as possible.
621 If the text hasn't changed as a result, forward to `ivy-alt-done'."
623 (if (and (eq (ivy-state-collection ivy-last) #'read-file-name-internal)
624 (or (and (equal ivy--directory "/")
625 (string-match "\\`[^/]+:.*\\'" ivy-text))
626 (string-match "\\`/" ivy-text)))
627 (let ((default-directory ivy--directory)
629 (minibuffer-complete)
630 (setq ivy-text (ivy--input))
631 (when (setq dir (ivy-expand-file-if-directory ivy-text))
634 (when (or (eq this-command last-command)
638 (defun ivy-partial ()
639 "Complete the minibuffer text as much as possible."
641 (let* ((parts (or (split-string ivy-text " " t) (list "")))
642 (postfix (car (last parts)))
643 (completion-ignore-case t)
644 (startp (string-match "^\\^" postfix))
645 (new (try-completion (if startp
646 (substring postfix 1)
648 (mapcar (lambda (str)
649 (let ((i (string-match postfix str)))
653 (cond ((eq new t) nil)
654 ((string= new ivy-text) nil)
656 (delete-region (minibuffer-prompt-end) (point-max))
661 (insert (mapconcat #'identity parts " ")
662 (if ivy-tab-space " " ""))
665 (defun ivy-immediate-done ()
666 "Exit the minibuffer with the current input."
668 (delete-minibuffer-contents)
669 (insert (setq ivy--current
671 (expand-file-name ivy-text ivy--directory)
673 (setq ivy-exit 'done)
678 "Resume the last completion session."
680 (if (null (ivy-state-action ivy-last))
681 (user-error "The last session isn't compatible with `ivy-resume'")
682 (when (eq (ivy-state-caller ivy-last) 'swiper)
683 (switch-to-buffer (ivy-state-buffer ivy-last)))
684 (with-current-buffer (ivy-state-buffer ivy-last)
686 (ivy-state-prompt ivy-last)
687 (ivy-state-collection ivy-last)
688 :predicate (ivy-state-predicate ivy-last)
689 :require-match (ivy-state-require-match ivy-last)
690 :initial-input ivy-text
691 :history (ivy-state-history ivy-last)
692 :preselect (unless (eq (ivy-state-collection ivy-last)
693 'read-file-name-internal)
695 :keymap (ivy-state-keymap ivy-last)
696 :update-fn (ivy-state-update-fn ivy-last)
697 :sort (ivy-state-sort ivy-last)
698 :action (ivy-state-action ivy-last)
699 :unwind (ivy-state-unwind ivy-last)
700 :re-builder (ivy-state-re-builder ivy-last)
701 :matcher (ivy-state-matcher ivy-last)
702 :dynamic-collection (ivy-state-dynamic-collection ivy-last)
703 :caller (ivy-state-caller ivy-last)))))
705 (defvar-local ivy-calling nil
706 "When non-nil, call the current action when `ivy--index' changes.")
708 (defun ivy-set-index (index)
709 "Set `ivy--index' to INDEX."
710 (setq ivy--index index)
715 (defun ivy-beginning-of-buffer ()
716 "Select the first completion candidate."
720 (defun ivy-end-of-buffer ()
721 "Select the last completion candidate."
723 (ivy-set-index (1- ivy--length)))
725 (defun ivy-scroll-up-command ()
726 "Scroll the candidates upward by the minibuffer height."
728 (ivy-set-index (min (1- (+ ivy--index ivy-height))
731 (defun ivy-scroll-down-command ()
732 "Scroll the candidates downward by the minibuffer height."
734 (ivy-set-index (max (1+ (- ivy--index ivy-height))
737 (defun ivy-minibuffer-grow ()
738 "Grow the minibuffer window by 1 line."
740 (setq-local max-mini-window-height
741 (cl-incf ivy-height)))
743 (defun ivy-minibuffer-shrink ()
744 "Shrink the minibuffer window by 1 line."
746 (unless (<= ivy-height 2)
747 (setq-local max-mini-window-height
748 (cl-decf ivy-height))
749 (window-resize (selected-window) -1)))
751 (defun ivy-next-line (&optional arg)
752 "Move cursor vertically down ARG candidates."
754 (setq arg (or arg 1))
755 (let ((index (+ ivy--index arg)))
756 (if (> index (1- ivy--length))
758 (ivy-beginning-of-buffer)
759 (ivy-set-index (1- ivy--length)))
760 (ivy-set-index index))))
762 (defun ivy-next-line-or-history (&optional arg)
763 "Move cursor vertically down ARG candidates.
764 If the input is empty, select the previous history element instead."
766 (if (string= ivy-text "")
767 (ivy-previous-history-element 1)
768 (ivy-next-line arg)))
770 (defun ivy-previous-line (&optional arg)
771 "Move cursor vertically up ARG candidates."
773 (setq arg (or arg 1))
774 (let ((index (- ivy--index arg)))
779 (ivy-set-index index))))
781 (defun ivy-previous-line-or-history (arg)
782 "Move cursor vertically up ARG candidates.
783 If the input is empty, select the previous history element instead."
785 (when (string= ivy-text "")
786 (ivy-previous-history-element 1))
787 (ivy-previous-line arg))
789 (defun ivy-toggle-calling ()
790 "Flip `ivy-calling'."
792 (when (setq ivy-calling (not ivy-calling))
795 (defun ivy-toggle-ignore ()
796 "Toggle user-configured candidate filtering."
798 (setq ivy-use-ignore (null ivy-use-ignore))
800 (setq ivy--old-cands nil))
802 (defun ivy--get-action (state)
803 "Get the action function from STATE."
804 (let ((action (ivy-state-action state)))
806 (if (functionp action)
808 (cadr (nth (car action) action))))))
810 (defun ivy--get-window (state)
811 "Get the window from STATE."
812 (if (ivy-state-p state)
813 (let ((window (ivy-state-window state)))
814 (if (window-live-p window)
816 (if (= (length (window-list)) 1)
821 (defun ivy--actionp (x)
822 "Return non-nil when X is a list of actions."
823 (and x (listp x) (not (eq (car x) 'closure))))
825 (defun ivy-next-action ()
826 "When the current action is a list, scroll it forwards."
828 (let ((action (ivy-state-action ivy-last)))
829 (when (ivy--actionp action)
830 (unless (>= (car action) (1- (length action)))
831 (cl-incf (car action))))))
833 (defun ivy-prev-action ()
834 "When the current action is a list, scroll it backwards."
836 (let ((action (ivy-state-action ivy-last)))
837 (when (ivy--actionp action)
838 (unless (<= (car action) 1)
839 (cl-decf (car action))))))
841 (defun ivy-action-name ()
842 "Return the name associated with the current action."
843 (let ((action (ivy-state-action ivy-last)))
844 (if (ivy--actionp action)
848 (nth 2 (nth (car action) action)))
851 (defvar ivy-inhibit-action nil
852 "When non-nil, `ivy-call' does nothing.
856 (let* ((ivy-inhibit-action t)
857 (str (counsel-locate \"lispy.el\")))
858 ;; do whatever with str - the corresponding file will not be opened
862 "Call the current action without exiting completion."
864 (unless ivy-inhibit-action
865 (let ((action (ivy--get-action ivy-last)))
867 (let* ((collection (ivy-state-collection ivy-last))
868 (x (if (and (consp collection)
869 (consp (car collection)))
870 (cdr (assoc ivy--current collection))
871 (if (equal ivy--current "")
874 (prog1 (funcall action x)
875 (unless (or (eq ivy-exit 'done)
876 (equal (selected-window)
877 (active-minibuffer-window))
878 (null (active-minibuffer-window)))
879 (select-window (active-minibuffer-window)))))))))
881 (defun ivy-next-line-and-call (&optional arg)
882 "Move cursor vertically down ARG candidates.
883 Call the permanent action if possible."
889 (defun ivy-previous-line-and-call (&optional arg)
890 "Move cursor vertically down ARG candidates.
891 Call the permanent action if possible."
893 (ivy-previous-line arg)
897 (defun ivy-previous-history-element (arg)
898 "Forward to `previous-history-element' with ARG."
900 (previous-history-element arg)
903 (ivy--maybe-scroll-history))
905 (defun ivy-next-history-element (arg)
906 "Forward to `next-history-element' with ARG."
908 (if (and (= minibuffer-history-position 0)
911 (insert ivy--default)
912 (when (and (with-ivy-window (derived-mode-p 'prog-mode))
913 (not (file-exists-p ivy--default))
914 (not (ivy-state-dynamic-collection ivy-last))
915 (> (point) (minibuffer-prompt-end)))
918 (goto-char (minibuffer-prompt-end))
920 (forward-char (+ 2 (length ivy--default)))))
921 (next-history-element arg))
924 (ivy--maybe-scroll-history))
926 (defvar ivy-ffap-url-functions nil
927 "List of functions that check if the point is on a URL.")
929 (defun ivy--cd-maybe ()
930 "Check if the current input points to a different directory.
931 If so, move to that directory, while keeping only the file name."
933 (let ((input (ivy--input))
935 (if (setq url (or (ffap-url-p input)
940 ivy-ffap-url-functions
941 :initial-value nil))))
942 (ivy-exit-with-action
944 (funcall ffap-url-fetcher url)))
945 (setq input (expand-file-name input))
946 (let ((file (file-name-nondirectory input))
947 (dir (expand-file-name (file-name-directory input))))
948 (if (string= dir ivy--directory)
950 (delete-minibuffer-contents)
955 (defun ivy--maybe-scroll-history ()
956 "If the selected history element has an index, scroll there."
957 (let ((idx (ignore-errors
959 (minibuffer-prompt-end)
963 (setq ivy--index idx))))
966 "When completing file names, move to directory DIR."
967 (if (null ivy--directory)
969 (setq ivy--old-cands nil)
970 (setq ivy--old-re nil)
972 (setq ivy--all-candidates
973 (ivy--sorted-files (setq ivy--directory dir)))
975 (delete-minibuffer-contents)))
977 (defun ivy-backward-delete-char ()
978 "Forward to `backward-delete-char'.
979 On error (read-only), call `ivy-on-del-error-function'."
981 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
983 (ivy--cd (file-name-directory
989 (backward-delete-char 1)
991 (when ivy-on-del-error-function
992 (funcall ivy-on-del-error-function))))))
994 (defun ivy-delete-char (arg)
995 "Forward to `delete-char' ARG."
997 (unless (= (point) (line-end-position))
1000 (defun ivy-forward-char (arg)
1001 "Forward to `forward-char' ARG."
1003 (unless (= (point) (line-end-position))
1004 (forward-char arg)))
1006 (defun ivy-kill-word (arg)
1007 "Forward to `kill-word' ARG."
1009 (unless (= (point) (line-end-position))
1012 (defun ivy-kill-line ()
1013 "Forward to `kill-line'."
1016 (kill-region (minibuffer-prompt-end) (point))
1019 (defun ivy-backward-kill-word ()
1020 "Forward to `backward-kill-word'."
1022 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
1024 (ivy--cd (file-name-directory
1025 (directory-file-name
1032 (delete-region (point) pt)))))
1034 (defvar ivy--regexp-quote 'regexp-quote
1035 "Store the regexp quoting state.")
1037 (defun ivy-toggle-regexp-quote ()
1038 "Toggle the regexp quoting."
1040 (setq ivy--old-re nil)
1041 (cl-rotatef ivy--regex-function ivy--regexp-quote))
1043 (defvar avy-all-windows)
1046 (defvar avy-keys-alist)
1048 (defvar avy-styles-alist)
1049 (declare-function avy--process "ext:avy")
1050 (declare-function avy--style-fn "ext:avy")
1052 (eval-after-load 'avy
1053 '(add-to-list 'avy-styles-alist '(ivy-avy . pre)))
1056 "Jump to one of the current ivy candidates."
1058 (unless (require 'avy nil 'noerror)
1059 (error "Package avy isn't installed"))
1060 (let* ((avy-all-windows nil)
1061 (avy-keys (or (cdr (assq 'ivy-avy avy-keys-alist))
1063 (avy-style (or (cdr (assq 'ivy-avy
1073 (goto-char (point-min))
1075 (while (< (point) (point-max))
1081 (setq avy-action #'identity)
1083 (nreverse candidates)
1084 (avy--style-fn avy-style)))))
1085 (ivy-set-index (- (line-number-at-pos candidate) 2))
1089 (defun ivy-sort-file-function-default (x y)
1090 "Compare two files X and Y.
1091 Prioritize directories."
1092 (if (get-text-property 0 'dirp x)
1093 (if (get-text-property 0 'dirp y)
1096 (if (get-text-property 0 'dirp y)
1100 (defcustom ivy-sort-functions-alist
1101 '((read-file-name-internal . ivy-sort-file-function-default)
1102 (internal-complete-buffer . nil)
1103 (counsel-git-grep-function . nil)
1104 (Man-goto-section . nil)
1107 "An alist of sorting functions for each collection function.
1108 Interactive functions that call completion fit in here as well.
1110 Nil means no sorting, which is useful to turn off the sorting for
1111 functions that have candidates in the natural buffer order, like
1112 `org-refile' or `Man-goto-section'.
1114 The entry associated with t is used for all fall-through cases.
1116 See also `ivy-sort-max-size'."
1120 (const :tag "Fall-through" t)
1121 (symbol :tag "Collection"))
1123 (const :tag "Plain sort" string-lessp)
1124 (const :tag "File sort" ivy-sort-file-function-default)
1125 (const :tag "No sort" nil)))
1128 (defvar ivy-index-functions-alist
1129 '((swiper . ivy-recompute-index-swiper)
1130 (swiper-multi . ivy-recompute-index-swiper)
1131 (counsel-git-grep . ivy-recompute-index-swiper)
1132 (counsel-grep . ivy-recompute-index-swiper-async)
1133 (t . ivy-recompute-index-zero))
1134 "An alist of index recomputing functions for each collection function.
1135 When the input changes, the appropriate function returns an
1136 integer - the index of the matched candidate that should be
1139 (defvar ivy-re-builders-alist
1140 '((t . ivy--regex-plus))
1141 "An alist of regex building functions for each collection function.
1143 Each key is (in order of priority):
1144 1. The actual collection function, e.g. `read-file-name-internal'.
1145 2. The symbol passed by :caller into `ivy-read'.
1149 Each value is a function that should take a string and return a
1150 valid regex or a regex sequence (see below).
1152 Possible choices: `ivy--regex', `regexp-quote',
1153 `ivy--regex-plus', `ivy--regex-fuzzy'.
1155 If a function returns a list, it should format like this:
1156 '((\"matching-regexp\" . t) (\"non-matching-regexp\") ...).
1158 The matches will be filtered in a sequence, you can mix the
1159 regexps that should match and that should not match as you
1162 (defvar ivy-initial-inputs-alist
1163 '((org-refile . "^")
1164 (org-agenda-refile . "^")
1165 (org-capture-refile . "^")
1167 (counsel-describe-function . "^")
1168 (counsel-describe-variable . "^")
1171 "Command to initial input table.")
1173 (defcustom ivy-sort-max-size 30000
1174 "Sorting won't be done for collections larger than this."
1177 (defun ivy--sorted-files (dir)
1178 "Return the list of files in DIR.
1179 Directories come first."
1180 (let* ((default-directory dir)
1181 (seq (all-completions "" 'read-file-name-internal))
1185 (setq seq (delete "./" (delete "../" seq)))
1186 (when (eq (setq sort-fn (cdr (assoc 'read-file-name-internal
1187 ivy-sort-functions-alist)))
1188 #'ivy-sort-file-function-default)
1189 (setq seq (mapcar (lambda (x)
1190 (propertize x 'dirp (string-match-p "/\\'" x)))
1193 (setq seq (cl-sort seq sort-fn)))
1194 (dolist (dir ivy-extra-directories)
1198 (defvar ivy-recursive-restore t
1199 "When non-nil, restore the above state when exiting the minibuffer.
1200 This variable is let-bound to nil by functions that take care of
1201 the restoring themselves.")
1204 (cl-defun ivy-read (prompt collection
1206 predicate require-match initial-input
1207 history preselect keymap update-fn sort
1208 action unwind re-builder matcher dynamic-collection caller)
1209 "Read a string in the minibuffer, with completion.
1211 PROMPT is a format string, normally ending in a colon and a
1212 space; %d anywhere in the string is replaced by the current
1213 number of matching candidates. For the literal % character,
1214 escape it with %%. See also `ivy-count-format'.
1216 COLLECTION is either a list of strings, a function, an alist, or
1219 If INITIAL-INPUT is not nil, then insert that input in the
1220 minibuffer initially.
1222 KEYMAP is composed with `ivy-minibuffer-map'.
1224 If PRESELECT is not nil, then select the corresponding candidate
1225 out of the ones that match the INITIAL-INPUT.
1227 UPDATE-FN is called each time the current candidate(s) is changed.
1229 When SORT is t, use `ivy-sort-functions-alist' for sorting.
1231 ACTION is a lambda function to call after selecting a result. It
1232 takes a single string argument.
1234 UNWIND is a lambda function to call before exiting.
1236 RE-BUILDER is a lambda function to call to transform text into a
1239 MATCHER is to override matching.
1241 DYNAMIC-COLLECTION is a boolean to specify if the list of
1242 candidates is updated after each input by calling COLLECTION.
1244 CALLER is a symbol to uniquely identify the caller to `ivy-read'.
1245 It is used, along with COLLECTION, to determine which
1246 customizations apply to the current completion session."
1247 (let ((extra-actions (delete-dups
1248 (append (plist-get ivy--actions-list t)
1249 (plist-get ivy--actions-list this-command)
1250 (plist-get ivy--actions-list caller)))))
1253 (cond ((functionp action)
1255 ("o" ,action "default")
1259 ("o" identity "default")
1262 (delete-dups (append action extra-actions)))))))
1263 (let ((extra-sources (plist-get ivy--sources-list caller)))
1266 (setq ivy--extra-candidates nil)
1267 (dolist (source extra-sources)
1268 (cond ((equal source '(original-source))
1269 (setq ivy--extra-candidates
1270 (cons source ivy--extra-candidates)))
1271 ((null (cdr source))
1272 (setq ivy--extra-candidates
1274 (list (car source) (funcall (car source)))
1275 ivy--extra-candidates))))))
1276 (setq ivy--extra-candidates '((original-source)))))
1277 (let ((recursive-ivy-last (and (active-minibuffer-window) ivy-last))
1279 (plist-get ivy--display-transformers-list
1280 (or caller (and (functionp collection)
1285 :collection collection
1286 :predicate predicate
1287 :require-match require-match
1288 :initial-input initial-input
1290 :preselect preselect
1292 :update-fn update-fn
1295 :window (selected-window)
1296 :buffer (current-buffer)
1298 :re-builder re-builder
1300 :dynamic-collection dynamic-collection
1301 :display-transformer-fn transformer-fn
1303 (ivy--reset-state ivy-last)
1306 (minibuffer-with-setup-hook
1307 #'ivy--minibuffer-setup
1308 (let* ((hist (or history 'ivy-history))
1309 (minibuffer-completion-table collection)
1310 (minibuffer-completion-predicate predicate)
1311 (resize-mini-windows (cond
1312 ((display-graphic-p) nil)
1313 ((null resize-mini-windows) 'grow-only)
1314 (t resize-mini-windows))))
1315 (read-from-minibuffer
1317 (ivy-state-initial-input ivy-last)
1318 (make-composed-keymap keymap ivy-minibuffer-map)
1321 (when (eq ivy-exit 'done)
1322 (let ((item (if ivy--directory
1325 (unless (equal item "")
1326 (set hist (cons (propertize item 'ivy-index ivy--index)
1328 (cdr (symbol-value hist))))))))
1330 (remove-hook 'post-command-hook #'ivy--exhibit)
1331 (when (setq unwind (ivy-state-unwind ivy-last))
1333 (unless (eq ivy-exit 'done)
1334 (when recursive-ivy-last
1335 (ivy--reset-state (setq ivy-last recursive-ivy-last)))))
1337 (when (numberp (car-safe (ivy-state-action ivy-last)))
1338 (setcar (ivy-state-action ivy-last) 1))
1339 (when (and recursive-ivy-last
1340 ivy-recursive-restore)
1341 (ivy--reset-state (setq ivy-last recursive-ivy-last))))))
1343 (defun ivy--reset-state (state)
1344 "Reset the ivy to STATE.
1345 This is useful for recursive `ivy-read'."
1346 (let ((prompt (or (ivy-state-prompt state) ""))
1347 (collection (ivy-state-collection state))
1348 (predicate (ivy-state-predicate state))
1349 (history (ivy-state-history state))
1350 (preselect (ivy-state-preselect state))
1351 (sort (ivy-state-sort state))
1352 (re-builder (ivy-state-re-builder state))
1353 (dynamic-collection (ivy-state-dynamic-collection state))
1354 (initial-input (ivy-state-initial-input state))
1355 (require-match (ivy-state-require-match state))
1356 (caller (ivy-state-caller state)))
1357 (unless initial-input
1358 (setq initial-input (cdr (assoc this-command
1359 ivy-initial-inputs-alist))))
1360 (setq ivy--directory nil)
1361 (setq ivy-case-fold-search 'auto)
1362 (setq ivy--regex-function
1364 (and (functionp collection)
1365 (cdr (assoc collection ivy-re-builders-alist)))
1367 (cdr (assoc caller ivy-re-builders-alist)))
1368 (cdr (assoc this-command ivy-re-builders-alist))
1369 (cdr (assoc t ivy-re-builders-alist))
1371 (setq ivy--subexps 0)
1372 (setq ivy--regexp-quote 'regexp-quote)
1373 (setq ivy--old-text "")
1374 (setq ivy--full-length nil)
1376 (setq ivy-calling nil)
1377 (setq ivy-use-ignore t)
1379 (cond ((eq collection 'Info-read-node-name-1)
1380 (if (equal Info-current-file "dir")
1382 (mapcar (lambda (x) (format "(%s)" x))
1383 (cl-delete-duplicates
1384 (all-completions "(" collection predicate)
1386 (setq coll (all-completions "" collection predicate))))
1387 ((eq collection 'read-file-name-internal)
1388 (setq ivy--directory default-directory)
1391 (let ((preselect-directory (file-name-directory preselect)))
1392 (unless (or (null preselect-directory)
1393 (string= preselect-directory
1395 (setq ivy--directory preselect-directory))
1397 (ivy-state-preselect state)
1398 (setq preselect (file-name-nondirectory preselect)))))
1399 (setq coll (ivy--sorted-files ivy--directory))
1401 (unless (or require-match
1402 (equal initial-input default-directory)
1403 (equal initial-input ""))
1404 (setq coll (cons initial-input coll)))
1405 (unless (and (ivy-state-action ivy-last)
1406 (not (equal (ivy--get-action ivy-last) 'identity)))
1407 (setq initial-input nil))))
1408 ((eq collection 'internal-complete-buffer)
1409 (setq coll (ivy--buffer-list "" ivy-use-virtual-buffers)))
1411 (setq coll (funcall collection ivy-text)))
1412 ((or (functionp collection)
1413 (byte-code-function-p collection)
1414 (vectorp collection)
1415 (and (consp collection) (listp (car collection)))
1416 (hash-table-p collection)
1417 (and (listp collection) (symbolp (car collection))))
1418 (setq coll (all-completions "" collection predicate)))
1420 (setq coll collection)))
1422 (if (and (functionp collection)
1423 (setq sort-fn (assoc collection ivy-sort-functions-alist)))
1424 (when (and (setq sort-fn (cdr sort-fn))
1425 (not (eq collection 'read-file-name-internal)))
1426 (setq coll (cl-sort coll sort-fn)))
1427 (unless (eq history 'org-refile-history)
1428 (if (and (setq sort-fn (cdr (assoc t ivy-sort-functions-alist)))
1429 (<= (length coll) ivy-sort-max-size))
1430 (setq coll (cl-sort (copy-sequence coll) sort-fn))))))
1432 (unless (or (and require-match
1433 (not (eq collection 'internal-complete-buffer)))
1435 (let ((re (regexp-quote preselect)))
1436 (cl-find-if (lambda (x) (string-match re x))
1438 (setq coll (cons preselect coll))))
1439 (setq ivy--old-re nil)
1440 (setq ivy--old-cands nil)
1441 (when (integerp preselect)
1442 (setq ivy--old-re "")
1443 (setq ivy--index preselect))
1445 ;; Needed for anchor to work
1446 (setq ivy--old-cands coll)
1447 (setq ivy--old-cands (ivy--filter initial-input coll)))
1448 (setq ivy--all-candidates coll)
1449 (unless (integerp preselect)
1450 (setq ivy--index (or
1451 (and dynamic-collection
1454 (ivy--preselect-index
1462 (if (region-active-p)
1466 (ivy-thing-at-point)))
1468 (cond ((string-match "%.*d" prompt)
1470 ((null ivy-count-format)
1472 "`ivy-count-format' can't be nil. Set it to an empty string instead"))
1473 ((string-match "%d.*%d" ivy-count-format)
1474 (let ((w (length (number-to-string
1475 (length ivy--all-candidates))))
1476 (s (copy-sequence ivy-count-format)))
1477 (string-match "%d" s)
1479 (string-match "%d" s (match-end 0))
1480 (setq s (replace-match (format "%%-%dd" w) nil nil s))
1481 (string-match "%d" s)
1482 (concat (replace-match (format "%%%dd" w) nil nil s)
1484 ((string-match "%.*d" ivy-count-format)
1485 (concat ivy-count-format prompt))
1490 (setf (ivy-state-initial-input ivy-last) initial-input)))
1493 (defun ivy-completing-read (prompt collection
1494 &optional predicate require-match initial-input
1495 history def inherit-input-method)
1496 "Read a string in the minibuffer, with completion.
1498 This interface conforms to `completing-read' and can be used for
1499 `completing-read-function'.
1501 PROMPT is a string that normally ends in a colon and a space.
1502 COLLECTION is either a list of strings, an alist, an obarray, or a hash table.
1503 PREDICATE limits completion to a subset of COLLECTION.
1504 REQUIRE-MATCH is a boolean value. See `completing-read'.
1505 INITIAL-INPUT is a string inserted into the minibuffer initially.
1506 HISTORY is a list of previously selected inputs.
1507 DEF is the default value.
1508 INHERIT-INPUT-METHOD is currently ignored."
1509 (if (memq this-command '(tmm-menubar tmm-shortcut))
1510 (completing-read-default prompt collection
1511 predicate require-match
1512 initial-input history
1513 def inherit-input-method)
1514 ;; See the doc of `completing-read'.
1515 (when (consp history)
1516 (when (numberp (cdr history))
1517 (setq initial-input (nth (1- (cdr history))
1518 (symbol-value (car history)))))
1519 (setq history (car history)))
1520 (ivy-read (replace-regexp-in-string "%" "%%" prompt)
1522 :predicate predicate
1523 :require-match require-match
1524 :initial-input (if (consp initial-input)
1526 (if (and (stringp initial-input)
1527 (string-match "\\+" initial-input))
1528 (replace-regexp-in-string
1529 "\\+" "\\\\+" initial-input)
1531 :preselect (if (listp def) (car def) def)
1535 (let ((sort (assoc this-command ivy-sort-functions-alist)))
1540 (defvar ivy-completion-beg nil
1541 "Completion bounds start.")
1543 (defvar ivy-completion-end nil
1544 "Completion bounds end.")
1546 (defun ivy-completion-in-region-action (str)
1547 "Insert STR, erasing the previous one.
1548 The previous string is between `ivy-completion-beg' and `ivy-completion-end'."
1551 (when ivy-completion-beg
1554 ivy-completion-end))
1555 (setq ivy-completion-beg
1556 (move-marker (make-marker) (point)))
1558 (setq ivy-completion-end
1559 (move-marker (make-marker) (point))))))
1561 (defun ivy-completion-common-length (str)
1562 "Return the length of the first 'completions-common-part face in STR."
1565 (while (and (<= pos len)
1566 (let ((prop (get-text-property pos 'face str)))
1567 (not (eq 'completions-common-part
1568 (if (listp prop) (car prop) prop)))))
1569 (setq pos (1+ pos)))
1571 (or (next-single-property-change pos 'face str) len)
1574 (defun ivy-completion-in-region (start end collection &optional predicate)
1575 "An Ivy function suitable for `completion-in-region-function'."
1576 (let* ((enable-recursive-minibuffers t)
1577 (str (buffer-substring-no-properties start end))
1578 (completion-ignore-case case-fold-search)
1580 (completion-all-completions str collection predicate (- end start))))
1582 (message "No matches")
1584 (setq ivy-completion-beg (- end (ivy-completion-common-length (car comps))))
1585 (setq ivy-completion-end end)
1586 (if (null (cdr comps))
1587 (if (string= str (car comps))
1588 (message "Sole match")
1589 (setf (ivy-state-window ivy-last) (selected-window))
1590 (ivy-completion-in-region-action
1591 (substring-no-properties
1593 (let* ((w (1+ (floor (log (length comps) 10))))
1594 (ivy-count-format (if (string= ivy-count-format "")
1596 (format "%%-%dd " w)))
1597 (prompt (format "(%s): " str)))
1599 (ivy-read (if (string= ivy-count-format "")
1601 (replace-regexp-in-string "%" "%%" prompt))
1602 ;; remove 'completions-first-difference face
1603 (mapcar #'substring-no-properties comps)
1604 :predicate predicate
1605 :action #'ivy-completion-in-region-action
1609 (defcustom ivy-do-completion-in-region t
1610 "When non-nil `ivy-mode' will set `completion-in-region-function'."
1614 (define-minor-mode ivy-mode
1615 "Toggle Ivy mode on or off.
1616 Turn Ivy mode on if ARG is positive, off otherwise.
1617 Turning on Ivy mode sets `completing-read-function' to
1618 `ivy-completing-read'.
1623 Minibuffer bindings:
1624 \\{ivy-minibuffer-map}"
1627 :keymap ivy-mode-map
1631 (setq completing-read-function 'ivy-completing-read)
1632 (when ivy-do-completion-in-region
1633 (setq completion-in-region-function 'ivy-completion-in-region)))
1634 (setq completing-read-function 'completing-read-default)
1635 (setq completion-in-region-function 'completion--in-region)))
1637 (defun ivy--preselect-index (preselect candidates)
1638 "Return the index of PRESELECT in CANDIDATES."
1639 (cond ((integerp preselect)
1641 ((cl-position preselect candidates :test #'equal))
1642 ((stringp preselect)
1643 (let ((re preselect))
1646 (string-match re x))
1651 (defvar ivy--regex-hash
1652 (make-hash-table :test #'equal)
1653 "Store pre-computed regex.")
1655 (defun ivy--split (str)
1656 "Split STR into a list by single spaces.
1657 The remaining spaces stick to their left.
1658 This allows to \"quote\" N spaces by inputting N+1 spaces."
1659 (let ((len (length str))
1664 (while (and (string-match " +" str start1)
1666 (setq match-len (- (match-end 0) (match-beginning 0)))
1670 (setq start1 start0)
1672 (push (substring str start1 (match-beginning 0)) res)
1673 (setq start1 (match-end 0)))
1674 (setq str (replace-match
1675 (make-string (1- match-len) ?\ )
1677 (setq start0 (or start0 start1))
1678 (setq start1 (1- (match-end 0)))))
1680 (push (substring str start0) res)
1681 (setq s (substring str start1))
1682 (unless (= (length s) 0)
1686 (defun ivy--regex (str &optional greedy)
1687 "Re-build regex pattern from STR in case it has a space.
1688 When GREEDY is non-nil, join words in a greedy way."
1689 (let ((hashed (unless greedy
1690 (gethash str ivy--regex-hash))))
1693 (setq ivy--subexps (car hashed)))
1694 (when (string-match "\\([^\\]\\|^\\)\\\\$" str)
1695 (setq str (substring str 0 -1)))
1697 (let ((subs (ivy--split str)))
1698 (if (= (length subs) 1)
1700 (setq ivy--subexps 0)
1703 (setq ivy--subexps (length subs))
1706 (if (string-match "\\`\\\\([^?].*\\\\)\\'" x)
1708 (format "\\(%s\\)" x)))
1713 ivy--regex-hash)))))
1715 (defun ivy--regex-ignore-order--part (str &optional discard)
1716 "Re-build regex from STR by splitting at spaces.
1717 Ignore the order of each group."
1718 (let* ((subs (split-string str " +" t))
1719 (len (length subs)))
1724 (mapcar (lambda (x) (cons x (not discard)))
1727 (defun ivy--regex-ignore-order (str)
1728 "Re-build regex from STR by splitting at spaces.
1729 Ignore the order of each group. Everything before \"!\" should
1730 match. Everything after \"!\" should not match."
1731 (let ((parts (split-string str "!" t)))
1732 (cl-case (length parts)
1736 (if (string= (substring str 0 1) "!")
1738 (ivy--regex-ignore-order--part (car parts) t))
1739 (ivy--regex-ignore-order--part (car parts))))
1742 (ivy--regex-ignore-order--part (car parts))
1743 (ivy--regex-ignore-order--part (cadr parts) t)))
1744 (t (error "Unexpected: use only one !")))))
1746 (defun ivy--regex-plus (str)
1747 "Build a regex sequence from STR.
1748 Spaces are wild card characters, everything before \"!\" should
1749 match. Everything after \"!\" should not match."
1750 (let ((parts (split-string str "!" t)))
1751 (cl-case (length parts)
1755 (if (string= (substring str 0 1) "!")
1757 (list (ivy--regex (car parts))))
1758 (ivy--regex (car parts))))
1761 (cons (ivy--regex (car parts)) t)
1762 (mapcar #'list (split-string (cadr parts) " " t))))
1763 (t (error "Unexpected: use only one !")))))
1765 (defun ivy--regex-fuzzy (str)
1766 "Build a regex sequence from STR.
1767 Insert .* between each char."
1768 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1770 (concat (match-string 1 str)
1773 (format "\\(%c\\)" x))
1774 (string-to-list (match-string 2 str)) ".*")
1775 (match-string 3 str))
1776 (setq ivy--subexps (length (match-string 2 str))))
1779 (defcustom ivy-fixed-height-minibuffer nil
1780 "When non nil, fix the height of the minibuffer during ivy
1781 completion at `ivy-height'. This effectively sets the minimum
1782 height at this level and tries to ensure that it does not change
1783 depending on the number of candidates."
1788 (defun ivy--minibuffer-setup ()
1789 "Setup ivy completion in the minibuffer."
1790 (set (make-local-variable 'completion-show-inline-help) nil)
1791 (set (make-local-variable 'minibuffer-default-add-function)
1793 (list ivy--default)))
1794 (when (display-graphic-p)
1795 (setq truncate-lines t))
1796 (setq-local max-mini-window-height ivy-height)
1797 (when ivy-fixed-height-minibuffer
1798 (set-window-text-height (selected-window) ivy-height))
1799 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1800 ;; show completions with empty input
1803 (defun ivy--input ()
1804 "Return the current minibuffer input."
1805 ;; assume one-line minibuffer input
1806 (buffer-substring-no-properties
1807 (minibuffer-prompt-end)
1808 (line-end-position)))
1810 (defun ivy--cleanup ()
1811 "Delete the displayed completion candidates."
1813 (goto-char (minibuffer-prompt-end))
1814 (delete-region (line-end-position) (point-max))))
1816 (defun ivy--insert-prompt ()
1817 "Update the prompt according to `ivy--prompt'."
1819 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1820 counsel-find-symbol))
1821 (setq ivy--prompt-extra ""))
1823 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1825 (setq head (match-string 1 ivy--prompt))
1827 (setq head (substring ivy--prompt 0 -1))
1829 (let ((inhibit-read-only t)
1830 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1833 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1834 (> (minibuffer-depth) 1))
1835 (format "[%d] " (minibuffer-depth))
1838 (if (string-match "%d.*%d" ivy-count-format)
1841 (or (and (ivy-state-dynamic-collection ivy-last)
1845 (or (and (ivy-state-dynamic-collection ivy-last)
1850 (d-str (if ivy--directory
1851 (abbreviate-file-name ivy--directory)
1854 (goto-char (point-min))
1855 (delete-region (point-min) (minibuffer-prompt-end))
1856 (if (> (+ (mod (+ (length n-str) (length d-str)) (window-width))
1859 (setq n-str (concat n-str "\n" d-str))
1860 (setq n-str (concat n-str d-str)))
1861 (let ((regex (format "\\([^\n]\\{%d\\}\\)[^\n]" (window-width))))
1862 (while (string-match regex n-str)
1863 (setq n-str (replace-match (concat (match-string 1 n-str) "\n") nil t n-str 1))))
1864 (set-text-properties 0 (length n-str)
1865 `(face minibuffer-prompt ,@std-props)
1867 (ivy--set-match-props n-str "confirm"
1868 `(face ivy-confirm-face ,@std-props))
1869 (ivy--set-match-props n-str "match required"
1870 `(face ivy-match-required-face ,@std-props))
1872 ;; get out of the prompt area
1873 (constrain-to-field nil (point-max))))))
1875 (defun ivy--set-match-props (str match props)
1876 "Set STR text properties that match MATCH to PROPS."
1877 (when (string-match match str)
1878 (set-text-properties
1884 (defvar inhibit-message)
1886 (defun ivy--sort-maybe (collection)
1887 "Sort COLLECTION if needed."
1888 (let ((sort (ivy-state-sort ivy-last))
1892 (let ((sort-fn (cond ((functionp sort)
1894 ((setq entry (assoc (ivy-state-collection ivy-last)
1895 ivy-sort-functions-alist))
1898 (cdr (assoc t ivy-sort-functions-alist))))))
1899 (if (functionp sort-fn)
1900 (cl-sort (copy-sequence collection) sort-fn)
1903 (defun ivy--exhibit ()
1904 "Insert Ivy completions display.
1905 Should be run via minibuffer `post-command-hook'."
1906 (when (memq 'ivy--exhibit post-command-hook)
1907 (let ((inhibit-field-text-motion nil))
1908 (constrain-to-field nil (point-max)))
1909 (setq ivy-text (ivy--input))
1910 (if (ivy-state-dynamic-collection ivy-last)
1911 ;; while-no-input would cause annoying
1912 ;; "Waiting for process to die...done" message interruptions
1913 (let ((inhibit-message t))
1914 (unless (equal ivy--old-text ivy-text)
1916 (setq ivy--all-candidates
1918 (funcall (ivy-state-collection ivy-last) ivy-text)))
1919 (setq ivy--old-text ivy-text)))
1920 (when ivy--all-candidates
1921 (ivy--insert-minibuffer
1922 (ivy--format ivy--all-candidates))))
1923 (cond (ivy--directory
1924 (if (string-match "/\\'" ivy-text)
1925 (if (member ivy-text ivy--all-candidates)
1926 (ivy--cd (expand-file-name ivy-text ivy--directory))
1927 (when (string-match "//\\'" ivy-text)
1928 (if (and default-directory
1929 (string-match "\\`[[:alpha:]]:/" default-directory))
1930 (ivy--cd (match-string 0 default-directory))
1932 (when (string-match "[[:alpha:]]:/$" ivy-text)
1933 (let ((drive-root (match-string 0 ivy-text)))
1934 (when (file-exists-p drive-root)
1935 (ivy--cd drive-root)))))
1936 (if (string-match "\\`~\\'" ivy-text)
1937 (ivy--cd (expand-file-name "~/")))))
1938 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1939 (when (or (and (string-match "\\` " ivy-text)
1940 (not (string-match "\\` " ivy--old-text)))
1941 (and (string-match "\\` " ivy--old-text)
1942 (not (string-match "\\` " ivy-text))))
1943 (setq ivy--all-candidates
1944 (if (and (> (length ivy-text) 0)
1945 (eq (aref ivy-text 0)
1947 (ivy--buffer-list " ")
1948 (ivy--buffer-list "" ivy-use-virtual-buffers)))
1949 (setq ivy--old-re nil))))
1950 (ivy--insert-minibuffer
1951 (with-current-buffer (ivy-state-buffer ivy-last)
1953 (ivy--filter ivy-text ivy--all-candidates))))
1954 (setq ivy--old-text ivy-text))))
1956 (defun ivy--insert-minibuffer (text)
1957 "Insert TEXT into minibuffer with appropriate cleanup."
1958 (let ((resize-mini-windows nil)
1959 (update-fn (ivy-state-update-fn ivy-last))
1963 (funcall update-fn))
1964 (ivy--insert-prompt)
1965 ;; Do nothing if while-no-input was aborted.
1966 (when (stringp text)
1967 (let ((buffer-undo-list t))
1971 (when (display-graphic-p)
1972 (ivy--resize-minibuffer-to-fit))))
1974 (defun ivy--resize-minibuffer-to-fit ()
1975 "Resize the minibuffer window size to fit the text in the minibuffer."
1976 (unless (frame-root-window-p (minibuffer-window))
1977 (with-selected-window (minibuffer-window)
1978 (if (fboundp 'window-text-pixel-size)
1979 (let ((text-height (cdr (window-text-pixel-size)))
1980 (body-height (window-body-height nil t)))
1981 (when (> text-height body-height)
1982 ;; Note: the size increment needs to be at least frame-char-height,
1983 ;; otherwise resizing won't do anything.
1984 (let ((delta (max (- text-height body-height) (frame-char-height))))
1985 (window-resize nil delta nil t t))))
1986 (let ((text-height (count-screen-lines))
1987 (body-height (window-body-height)))
1988 (when (> text-height body-height)
1989 (window-resize nil (- text-height body-height) nil t)))))))
1991 (declare-function colir-blend-face-background "ext:colir")
1993 (defun ivy--add-face (str face)
1994 "Propertize STR with FACE.
1995 `font-lock-append-text-property' is used, since it's better than
1996 `propertize' or `add-face-text-property' in this case."
2000 (colir-blend-face-background 0 (length str) face str)
2001 (let ((foreground (face-foreground face)))
2003 (add-face-text-property
2005 `(:foreground ,foreground)
2010 (font-lock-append-text-property 0 (length str) 'face face str))))
2013 (declare-function flx-make-string-cache "ext:flx")
2014 (declare-function flx-score "ext:flx")
2016 (defvar ivy--flx-cache nil)
2018 (eval-after-load 'flx
2019 '(setq ivy--flx-cache (flx-make-string-cache)))
2021 (defun ivy-toggle-case-fold ()
2022 "Toggle the case folding between nil and auto.
2023 In any completion session, the case folding starts in auto:
2025 - when the input is all lower case, `case-fold-search' is t
2028 You can toggle this to make `case-fold-search' nil regardless of input."
2030 (setq ivy-case-fold-search
2031 (if ivy-case-fold-search
2034 ;; reset cache so that the candidate list updates
2035 (setq ivy--old-re nil))
2037 (defun ivy--re-filter (re candidates)
2038 "Return all RE matching CANDIDATES.
2039 RE is a list of cons cells, with a regexp car and a boolean cdr.
2040 When the cdr is t, the car must match.
2041 Otherwise, the car must not match."
2042 (let ((re-list (if (stringp re) (list (cons re t)) re))
2044 (dolist (re re-list)
2051 (let ((re-str (car re)))
2052 (lambda (x) (string-match re-str x)))
2056 (defun ivy--filter (name candidates)
2057 "Return all items that match NAME in CANDIDATES.
2058 CANDIDATES are assumed to be static."
2059 (let ((re (funcall ivy--regex-function name)))
2060 (if (and (equal re ivy--old-re)
2062 ;; quick caching for "C-n", "C-p" etc.
2064 (let* ((re-str (if (listp re) (caar re) re))
2065 (matcher (ivy-state-matcher ivy-last))
2067 (and ivy-case-fold-search
2068 (string= name (downcase name))))
2071 (funcall matcher re candidates))
2074 (stringp ivy--old-re)
2075 (not (string-match "\\\\" ivy--old-re))
2076 (not (equal ivy--old-re ""))
2078 (if (string-match "\\\\)\\'" ivy--old-re)
2079 (substring ivy--old-re 0 -2)
2085 (lambda (x) (string-match re x))
2088 (ivy--re-filter re candidates)))))
2089 (ivy--recompute-index name re-str cands)
2091 (if (eq ivy--regex-function 'ivy--regex-ignore-order)
2096 (setq ivy--old-cands (ivy--sort name cands))))))
2098 (defun ivy--set-candidates (x)
2099 "Update `ivy--all-candidates' with X."
2101 (dolist (source ivy--extra-candidates)
2102 (if (equal source '(original-source))
2105 (setq res (append x res)))
2106 (setq ivy--old-re nil)
2108 (ivy--filter ivy-text (cadr source))
2110 (setq ivy--all-candidates res)))
2112 (defcustom ivy-sort-matches-functions-alist '((t . nil))
2113 "An alist of functions for sorting matching candidates.
2115 Unlike `ivy-sort-functions-alist', which is used to sort the
2116 whole collection only once, this alist of functions are used to
2117 sort only matching candidates after each change in input.
2119 The alist KEY is either a collection function or t to match
2120 previously unmatched collection functions.
2122 The alist VAL is a sorting function with the signature of
2123 `ivy--prefix-sort'."
2126 (const :tag "Fall-through" t)
2127 (symbol :tag "Collection"))
2130 (const :tag "Don't sort" nil)
2131 (const :tag "Put prefix matches ahead" 'ivy--prefix-sort)
2132 (function :tag "Custom sort function"))))
2134 (defun ivy--sort-files-by-date (_name candidates)
2135 "Re-soft CANDIDATES according to file modification date."
2136 (let ((default-directory ivy--directory))
2137 (cl-sort (copy-sequence candidates)
2140 (nth 5 (file-attributes f2))
2141 (nth 5 (file-attributes f1)))))))
2143 (defun ivy--sort (name candidates)
2144 "Re-sort CANDIDATES by NAME.
2145 All CANDIDATES are assumed to match NAME."
2146 (let ((key (or (ivy-state-caller ivy-last)
2147 (when (functionp (ivy-state-collection ivy-last))
2148 (ivy-state-collection ivy-last))))
2150 (cond ((and (require 'flx nil 'noerror)
2151 (eq ivy--regex-function 'ivy--regex-fuzzy))
2152 (ivy--flx-sort name candidates))
2153 ((setq fun (cdr (or (assoc key ivy-sort-matches-functions-alist)
2154 (assoc t ivy-sort-matches-functions-alist))))
2155 (funcall fun name candidates))
2159 (defun ivy--prefix-sort (name candidates)
2160 "Re-sort CANDIDATES.
2161 Prefix matches to NAME are put ahead of the list."
2162 (if (or (string-match "^\\^" name) (string= name ""))
2164 (let ((re-prefix (concat "^" (funcall ivy--regex-function name)))
2167 (dolist (s candidates)
2168 (if (string-match re-prefix s)
2170 (push s res-noprefix)))
2172 (nreverse res-prefix)
2173 (nreverse res-noprefix)))))
2175 (defun ivy--recompute-index (name re-str cands)
2176 (let* ((caller (ivy-state-caller ivy-last))
2177 (func (or (and caller (cdr (assoc caller ivy-index-functions-alist)))
2178 (cdr (assoc t ivy-index-functions-alist))
2179 #'ivy-recompute-index-zero)))
2180 (unless (eq this-command 'ivy-resume)
2183 (cl-position (if (and (> (length name) 0)
2184 (eq ?^ (aref name 0)))
2190 (concat re-str "/") cands
2192 (and (not (string= name ""))
2193 (not (and (require 'flx nil 'noerror)
2194 (eq ivy--regex-function 'ivy--regex-fuzzy)
2195 (< (length cands) 200)))
2197 (cl-position (nth ivy--index ivy--old-cands)
2199 (funcall func re-str cands))))
2200 (when (and (or (string= name "")
2202 (not (equal ivy--old-re "")))
2204 (or (ivy--preselect-index
2205 (ivy-state-preselect ivy-last)
2209 (defun ivy-recompute-index-swiper (_re-str cands)
2210 (let ((tail (nthcdr ivy--index ivy--old-cands))
2212 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2214 (while (and tail (null idx))
2215 ;; Compare with eq to handle equal duplicates in cands
2216 (setq idx (cl-position (pop tail) cands)))
2219 (1- (length cands))))
2222 ;; already in ivy-state-buffer
2223 (let ((n (line-number-at-pos))
2227 (when (eq n (read (get-text-property 0 'display c)))
2232 (defun ivy-recompute-index-swiper-async (_re-str cands)
2233 (let ((tail (nthcdr ivy--index ivy--old-cands))
2235 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2237 (while (and tail (null idx))
2238 ;; Compare with `equal', since the collection is re-created
2239 ;; each time with `split-string'
2240 (setq idx (cl-position (pop tail) cands :test #'equal)))
2244 (defun ivy-recompute-index-zero (_re-str _cands)
2247 (defcustom ivy-minibuffer-faces
2248 '(ivy-minibuffer-match-face-1
2249 ivy-minibuffer-match-face-2
2250 ivy-minibuffer-match-face-3
2251 ivy-minibuffer-match-face-4)
2252 "List of `ivy' faces for minibuffer group matches."
2253 :type '(repeat :tag "Faces"
2255 (const ivy-minibuffer-match-face-1)
2256 (const ivy-minibuffer-match-face-2)
2257 (const ivy-minibuffer-match-face-3)
2258 (const ivy-minibuffer-match-face-4)
2259 (face :tag "Other face"))))
2261 (defvar ivy-flx-limit 200
2262 "Used to conditionally turn off flx sorting.
2264 When the amount of matching candidates exceeds this limit, then
2265 no sorting is done.")
2267 (defun ivy--flx-sort (name cands)
2268 "Sort according to closeness to string NAME the string list CANDS."
2271 (< (length cands) ivy-flx-limit))
2272 (let* ((flx-name (if (string-match "^\\^" name)
2279 (let ((score (flx-score x flx-name ivy--flx-cache)))
2283 (if cands-with-score
2285 (let ((str (copy-sequence (cdr x)))
2288 (dolist (j (cdar x))
2289 (unless (eq j (1+ last-j))
2292 (ivy-add-face-text-property
2294 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2295 ivy-minibuffer-faces)
2298 (sort cands-with-score
2300 (> (caar x) (caar y)))))
2306 (defcustom ivy-format-function 'ivy-format-function-default
2307 "Function to transform the list of candidates into a string.
2308 This string is inserted into the minibuffer."
2310 (const :tag "Default" ivy-format-function-default)
2311 (const :tag "Arrow prefix" ivy-format-function-arrow)
2312 (const :tag "Full line" ivy-format-function-line)))
2314 (defun ivy--truncate-string (str width)
2315 "Truncate STR to WIDTH."
2316 (if (> (string-width str) width)
2317 (concat (substring str 0 (min (- width 3)
2318 (- (length str) 3))) "...")
2321 (defun ivy--format-function-generic (selected-fn other-fn strs separator)
2322 "Transform CAND-PAIRS into a string for minibuffer.
2323 SELECTED-FN and OTHER-FN each take two string arguments.
2324 SEPARATOR is used to join the candidates."
2328 (let ((curr (eq (cl-incf i) ivy--index)))
2330 (funcall selected-fn str)
2331 (funcall other-fn str))))
2335 (defun ivy-format-function-default (cands)
2336 "Transform CAND-PAIRS into a string for minibuffer."
2337 (ivy--format-function-generic
2339 (ivy--add-face str 'ivy-current-match))
2344 (defun ivy-format-function-arrow (cands)
2345 "Transform CAND-PAIRS into a string for minibuffer."
2346 (ivy--format-function-generic
2348 (concat "> " (ivy--add-face str 'ivy-current-match)))
2354 (defun ivy-format-function-line (cands)
2355 "Transform CAND-PAIRS into a string for minibuffer."
2356 (ivy--format-function-generic
2358 (ivy--add-face (concat str "\n") 'ivy-current-match))
2364 (defun ivy-add-face-text-property (start end face str)
2365 (if (fboundp 'add-face-text-property)
2366 (add-face-text-property
2367 start end face nil str)
2368 (font-lock-append-text-property
2369 start end 'face face str)))
2371 (defun ivy--format-minibuffer-line (str)
2373 (str (copy-sequence str)))
2374 (cond ((eq ivy--regex-function 'ivy--regex-ignore-order)
2375 (when (consp ivy--old-re)
2377 (dolist (re ivy--old-re)
2378 (when (string-match (car re) str)
2379 (ivy-add-face-text-property
2380 (match-beginning 0) (match-end 0)
2381 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2382 ivy-minibuffer-faces)
2385 ((and (eq ivy-display-style 'fancy)
2386 (not (eq ivy--regex-function 'ivy--regex-fuzzy)))
2388 (setq ivy--old-re (funcall ivy--regex-function ivy-text)))
2389 (while (and (string-match ivy--old-re str start)
2390 (> (- (match-end 0) (match-beginning 0)) 0))
2391 (setq start (match-end 0))
2393 (while (<= i ivy--subexps)
2395 (cond ((zerop ivy--subexps)
2396 (cadr ivy-minibuffer-faces))
2398 (car ivy-minibuffer-faces))
2400 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2401 ivy-minibuffer-faces)))))
2402 (ivy-add-face-text-property
2403 (match-beginning i) (match-end i)
2408 (ivy-set-display-transformer
2409 'read-file-name-internal 'ivy-read-file-transformer)
2411 (defun ivy-read-file-transformer (str)
2412 (if (string-match-p "/\\'" str)
2413 (propertize str 'face 'ivy-subdir)
2416 (defun ivy--format (cands)
2417 "Return a string for CANDS suitable for display in the minibuffer.
2418 CANDS is a list of strings."
2419 (setq ivy--length (length cands))
2420 (when (>= ivy--index ivy--length)
2421 (setq ivy--index (max (1- ivy--length) 0)))
2423 (setq ivy--current "")
2424 (let* ((half-height (/ ivy-height 2))
2425 (start (max 0 (- ivy--index half-height)))
2426 (end (min (+ start (1- ivy-height)) ivy--length))
2427 (start (max 0 (min start (- end (1- ivy-height)))))
2428 (cands (cl-subseq cands start end))
2429 (index (- ivy--index start))
2431 (setq ivy--current (copy-sequence (nth index cands)))
2432 (when (setq transformer-fn (ivy-state-display-transformer-fn ivy-last))
2434 (setq cands (mapcar transformer-fn cands))))
2435 (let* ((ivy--index index)
2437 #'ivy--format-minibuffer-line
2439 (res (concat "\n" (funcall ivy-format-function cands))))
2440 (put-text-property 0 (length res) 'read-only nil res)
2443 (defvar ivy--virtual-buffers nil
2444 "Store the virtual buffers alist.")
2446 (defvar recentf-list)
2448 (defcustom ivy-virtual-abbreviate 'name
2449 "The mode of abbreviation for virtual buffer names."
2451 (const :tag "Only name" name)
2452 (const :tag "Full path" full)
2453 ;; eventually, uniquify
2456 (defun ivy--virtual-buffers ()
2457 "Adapted from `ido-add-virtual-buffers-to-list'."
2458 (unless recentf-mode
2460 (let ((bookmarks (and (boundp 'bookmark-alist)
2462 virtual-buffers name)
2463 (dolist (head (append
2465 (delete " - no file -"
2466 (delq nil (mapcar (lambda (bookmark)
2467 (cdr (assoc 'filename bookmark)))
2470 (if (eq ivy-virtual-abbreviate 'name)
2471 (file-name-nondirectory head)
2472 (expand-file-name head)))
2473 (when (equal name "")
2474 (setq name (file-name-nondirectory (directory-file-name head))))
2475 (when (equal name "")
2477 (and (not (equal name ""))
2478 (null (get-file-buffer head))
2479 (not (assoc name virtual-buffers))
2480 (push (cons name head) virtual-buffers)))
2481 (when virtual-buffers
2482 (dolist (comp virtual-buffers)
2483 (put-text-property 0 (length (car comp))
2486 (setq ivy--virtual-buffers (nreverse virtual-buffers))
2487 (mapcar #'car ivy--virtual-buffers))))
2489 (defcustom ivy-ignore-buffers nil
2490 "List of regexps matching buffer names to ignore."
2491 :type '(repeat regexp))
2493 (defun ivy--buffer-list (str &optional virtual)
2494 "Return the buffers that match STR.
2495 When VIRTUAL is non-nil, add virtual buffers."
2500 (if (with-current-buffer x
2502 (abbreviate-file-name default-directory)))
2503 (propertize x 'face 'ivy-remote)
2505 (all-completions str 'internal-complete-buffer))
2507 (ivy--virtual-buffers)))))
2509 (defun ivy--switch-buffer-action (buffer)
2511 BUFFER may be a string or nil."
2513 (if (zerop (length buffer))
2515 ivy-text nil 'force-same-window)
2516 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2518 (not (get-buffer buffer)))
2519 (find-file (cdr virtual))
2521 buffer nil 'force-same-window))))))
2523 (defun ivy--switch-buffer-other-window-action (buffer)
2524 "Switch to BUFFER in other window.
2525 BUFFER may be a string or nil."
2526 (if (zerop (length buffer))
2527 (switch-to-buffer-other-window ivy-text)
2528 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2530 (not (get-buffer buffer)))
2531 (find-file-other-window (cdr virtual))
2532 (switch-to-buffer-other-window buffer)))))
2534 (defun ivy--rename-buffer-action (buffer)
2536 (let ((new-name (read-string "Rename buffer (to new name): ")))
2537 (with-current-buffer buffer
2538 (rename-buffer new-name))))
2540 (defvar ivy-switch-buffer-map (make-sparse-keymap))
2547 (ivy--reset-state ivy-last))
2550 ivy--switch-buffer-other-window-action
2553 ivy--rename-buffer-action
2556 (defun ivy--switch-buffer-matcher (regexp candidates)
2557 "Return REGEXP-matching CANDIDATES.
2558 Skip buffers that match `ivy-ignore-buffers'."
2559 (let ((res (ivy--re-filter regexp candidates)))
2560 (if (or (null ivy-use-ignore)
2561 (null ivy-ignore-buffers))
2567 (string-match regexp buf))
2568 ivy-ignore-buffers))
2572 (ivy-set-display-transformer
2573 'ivy-switch-buffer 'ivy-switch-buffer-transformer)
2574 (ivy-set-display-transformer
2575 'internal-complete-buffer 'ivy-switch-buffer-transformer)
2577 (defun ivy-switch-buffer-transformer (str)
2578 (let ((b (get-buffer str)))
2580 (buffer-file-name b)
2581 (buffer-modified-p b))
2582 (propertize str 'face 'ivy-modified-buffer)
2585 (defun ivy-switch-buffer-occur ()
2586 "Occur function for `ivy-switch-buffer' that uses `ibuffer'."
2588 (concat "\\(" (mapconcat #'regexp-quote ivy--old-cands "\\|") "\\)"))
2589 (new-qualifier `((name . ,cand-regexp))))
2590 (ibuffer nil (buffer-name) new-qualifier)))
2593 (defun ivy-switch-buffer ()
2594 "Switch to another buffer."
2596 (let ((this-command 'ivy-switch-buffer))
2597 (ivy-read "Switch to buffer: " 'internal-complete-buffer
2598 :matcher #'ivy--switch-buffer-matcher
2599 :preselect (buffer-name (other-buffer (current-buffer)))
2600 :action #'ivy--switch-buffer-action
2601 :keymap ivy-switch-buffer-map
2602 :caller 'ivy-switch-buffer)))
2605 (defun ivy-switch-buffer-other-window ()
2606 "Switch to another buffer in another window."
2608 (ivy-read "Switch to buffer in other window: " 'internal-complete-buffer
2609 :preselect (buffer-name (other-buffer (current-buffer)))
2610 :action #'ivy--switch-buffer-other-window-action
2611 :keymap ivy-switch-buffer-map
2612 :caller 'ivy-switch-buffer-other-window))
2615 (defun ivy-recentf ()
2616 "Find a file on `recentf-list'."
2618 (ivy-read "Recentf: " recentf-list
2623 :caller 'ivy-recentf))
2625 (defun ivy-yank-word ()
2626 "Pull next word from buffer into search string."
2631 (le (line-end-position)))
2635 (setq amend (buffer-substring-no-properties pt (point))))))
2637 (insert (replace-regexp-in-string " +" " " amend)))))
2639 (defun ivy-kill-ring-save ()
2640 "Store the current candidates into the kill ring.
2641 If the region is active, forward to `kill-ring-save' instead."
2643 (if (region-active-p)
2644 (call-interactively 'kill-ring-save)
2651 (defun ivy-insert-current ()
2652 "Make the current candidate into current input.
2653 Don't finish completion."
2655 (delete-minibuffer-contents)
2656 (if (and ivy--directory
2657 (string-match "/$" ivy--current))
2658 (insert (substring ivy--current 0 -1))
2659 (insert ivy--current)))
2661 (defun ivy-toggle-fuzzy ()
2662 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
2664 (setq ivy--old-re nil)
2665 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
2666 (setq ivy--regex-function 'ivy--regex-plus)
2667 (setq ivy--regex-function 'ivy--regex-fuzzy)))
2669 (defun ivy-reverse-i-search ()
2670 "Enter a recursive `ivy-read' session using the current history.
2671 The selected history element will be inserted into the minibuffer."
2673 (let ((enable-recursive-minibuffers t)
2674 (history (symbol-value (ivy-state-history ivy-last)))
2676 (ivy-recursive-restore nil))
2677 (ivy-read "Reverse-i-search: "
2681 (setq ivy-last old-last))
2682 (delete-minibuffer-contents)
2683 (insert (substring-no-properties x))
2686 (defun ivy-restrict-to-matches ()
2687 "Restrict candidates to current matches and erase input."
2689 (delete-minibuffer-contents)
2690 (setq ivy--all-candidates
2691 (ivy--filter ivy-text ivy--all-candidates)))
2694 (defvar-local ivy-occur-last nil
2695 "Buffer-local value of `ivy-last'.
2696 Can't re-use `ivy-last' because using e.g. `swiper' in the same
2697 buffer would modify `ivy-last'.")
2699 (defvar ivy-occur-mode-map
2700 (let ((map (make-sparse-keymap)))
2701 (define-key map [mouse-1] 'ivy-occur-click)
2702 (define-key map (kbd "RET") 'ivy-occur-press)
2703 (define-key map (kbd "j") 'ivy-occur-next-line)
2704 (define-key map (kbd "k") 'ivy-occur-previous-line)
2705 (define-key map (kbd "h") 'backward-char)
2706 (define-key map (kbd "l") 'forward-char)
2707 (define-key map (kbd "f") 'ivy-occur-press)
2708 (define-key map (kbd "g") 'ivy-occur-revert-buffer)
2709 (define-key map (kbd "a") 'ivy-occur-read-action)
2710 (define-key map (kbd "o") 'ivy-occur-dispatch)
2711 (define-key map (kbd "c") 'ivy-occur-toggle-calling)
2712 (define-key map (kbd "q") 'quit-window)
2714 "Keymap for Ivy Occur mode.")
2716 (defun ivy-occur-toggle-calling ()
2717 "Toggle `ivy-calling'."
2719 (if (setq ivy-calling (not ivy-calling))
2721 (setq mode-name "Ivy-Occur [calling]")
2723 (setq mode-name "Ivy-Occur"))
2724 (force-mode-line-update))
2726 (defun ivy-occur-next-line (&optional arg)
2727 "Move the cursor down ARG lines.
2728 When `ivy-calling' isn't nil, call `ivy-occur-press'."
2734 (defun ivy-occur-previous-line (&optional arg)
2735 "Move the cursor up ARG lines.
2736 When `ivy-calling' isn't nil, call `ivy-occur-press'."
2738 (forward-line (- arg))
2742 (define-derived-mode ivy-occur-mode fundamental-mode "Ivy-Occur"
2743 "Major mode for output from \\[ivy-occur].
2745 \\{ivy-occur-mode-map}")
2747 (defvar ivy-occur-grep-mode-map
2748 (let ((map (copy-keymap ivy-occur-mode-map)))
2749 (define-key map (kbd "C-x C-q") 'ivy-wgrep-change-to-wgrep-mode)
2751 "Keymap for Ivy Occur Grep mode.")
2753 (define-derived-mode ivy-occur-grep-mode grep-mode "Ivy-Occur"
2754 "Major mode for output from \\[ivy-occur].
2756 \\{ivy-occur-grep-mode-map}")
2758 (defvar ivy--occurs-list nil
2759 "A list of custom occur generators per command.")
2761 (defun ivy-set-occur (cmd occur)
2762 "Assign CMD a custom OCCUR function."
2763 (setq ivy--occurs-list
2764 (plist-put ivy--occurs-list cmd occur)))
2766 (ivy-set-occur 'ivy-switch-buffer 'ivy-switch-buffer-occur)
2767 (ivy-set-occur 'ivy-switch-buffer-other-window 'ivy-switch-buffer-occur)
2769 (defun ivy--occur-insert-lines (cands)
2771 (add-text-properties
2775 help-echo "mouse-1: call ivy-action")
2780 "Stop completion and put the current matches into a new buffer.
2782 The new buffer remembers current action(s).
2784 While in the *ivy-occur* buffer, selecting a candidate with RET or
2785 a mouse click will call the appropriate action for that candidate.
2787 There is no limit on the number of *ivy-occur* buffers."
2789 (if (not (window-minibuffer-p))
2790 (user-error "No completion session is active")
2791 (let* ((caller (ivy-state-caller ivy-last))
2792 (occur-fn (plist-get ivy--occurs-list caller))
2794 (generate-new-buffer
2795 (format "*ivy-occur%s \"%s\"*"
2797 (concat " " (prin1-to-string caller))
2800 (with-current-buffer buffer
2801 (let ((inhibit-read-only t))
2806 (insert (format "%d candidates:\n" (length ivy--old-cands)))
2807 (ivy--occur-insert-lines
2809 (lambda (cand) (concat " " cand))
2811 (setf (ivy-state-text ivy-last) ivy-text)
2812 (setq ivy-occur-last ivy-last)
2813 (setq-local ivy--directory ivy--directory))
2814 (ivy-exit-with-action
2815 `(lambda (_) (pop-to-buffer ,buffer))))))
2817 (defun ivy-occur-revert-buffer ()
2818 "Refresh the buffer making it up-to date with the collection.
2820 Currently only works for `swiper'. In that specific case, the
2821 *ivy-occur* buffer becomes nearly useless as the orignal buffer
2822 is updated, since the line numbers no longer match.
2824 Calling this function is as if you called `ivy-occur' on the
2825 updated original buffer."
2827 (let ((caller (ivy-state-caller ivy-occur-last))
2828 (ivy-last ivy-occur-last))
2829 (when (eq caller 'swiper)
2830 (let ((buffer (ivy-state-buffer ivy-occur-last)))
2831 (unless (buffer-live-p buffer)
2832 (error "buffer was killed"))
2833 (let ((inhibit-read-only t))
2835 (funcall (plist-get ivy--occurs-list caller) t))))))
2837 (declare-function wgrep-change-to-wgrep-mode "ext:wgrep")
2839 (defun ivy-wgrep-change-to-wgrep-mode ()
2840 "Forward to `wgrep-change-to-wgrep-mode'."
2842 (if (require 'wgrep nil 'noerror)
2843 (wgrep-change-to-wgrep-mode)
2844 (error "Package wgrep isn't installed")))
2846 (defun ivy-occur-read-action ()
2847 "Select one of the available actions as the current one."
2849 (let ((ivy-last ivy-occur-last))
2852 (defun ivy-occur-dispatch ()
2853 "Call one of the available actions on the current item."
2855 (let* ((state-action (ivy-state-action ivy-occur-last))
2856 (actions (if (symbolp state-action)
2858 (copy-sequence state-action))))
2861 (ivy-occur-read-action)
2863 (setf (ivy-state-action ivy-occur-last) actions))))
2865 (defun ivy-occur-click (event)
2866 "Execute action for the current candidate.
2867 EVENT gives the mouse position."
2869 (let ((window (posn-window (event-end event)))
2870 (pos (posn-point (event-end event))))
2871 (with-current-buffer (window-buffer window)
2873 (ivy-occur-press))))
2875 (declare-function swiper--cleanup "swiper")
2876 (declare-function swiper--add-overlays "swiper")
2878 (defun ivy-occur-press ()
2879 "Execute action for the current candidate."
2881 (when (save-excursion
2883 (looking-at "\\(?:./\\| \\)\\(.*\\)$"))
2884 (when (memq (ivy-state-caller ivy-occur-last)
2885 '(swiper counsel-git-grep counsel-grep counsel-ag))
2886 (let ((window (ivy-state-window ivy-occur-last)))
2887 (when (or (null (window-live-p window))
2888 (equal window (selected-window)))
2889 (save-selected-window
2890 (setf (ivy-state-window ivy-occur-last)
2891 (display-buffer (ivy-state-buffer ivy-occur-last)
2892 'display-buffer-pop-up-window))))))
2893 (let* ((ivy-last ivy-occur-last)
2894 (ivy-text (ivy-state-text ivy-last))
2895 (str (buffer-substring
2898 (coll (ivy-state-collection ivy-last))
2899 (action (ivy--get-action ivy-last))
2903 (if (and (consp coll)
2905 (cdr (assoc str coll))
2907 (if (memq (ivy-state-caller ivy-last)
2908 '(swiper counsel-git-grep))
2909 (with-current-buffer (window-buffer (selected-window))
2911 (swiper--add-overlays
2912 (ivy--regex ivy-text)
2913 (line-beginning-position)
2916 (run-at-time 0.5 nil 'swiper--cleanup)))))))
2918 (defvar ivy-help-file (let ((default-directory
2920 (file-name-directory load-file-name)
2921 default-directory)))
2922 (if (file-exists-p "ivy-help.org")
2923 (expand-file-name "ivy-help.org")
2924 (if (file-exists-p "doc/ivy-help.org")
2925 (expand-file-name "doc/ivy-help.org"))))
2926 "The file for `ivy-help'.")
2931 (let ((buf (get-buffer "*Ivy Help*")))
2933 (setq buf (get-buffer-create "*Ivy Help*"))
2934 (with-current-buffer buf
2935 (insert-file-contents ivy-help-file)
2938 (goto-char (point-min))))
2939 (if (eq this-command 'ivy-help)
2940 (switch-to-buffer buf)
2942 (pop-to-buffer buf)))
2944 (goto-char (point-min))))
2948 ;;; ivy.el ends here