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-add-newline-after-prompt nil
128 "When non-nil, add a newline after the `ivy-read' prompt."
131 (defcustom ivy-wrap nil
132 "When non-nil, wrap around after the first and the last candidate."
135 (defcustom ivy-display-style (unless (version< emacs-version "24.5") 'fancy)
136 "The style for formatting the minibuffer.
138 By default, the matched strings are copied as is.
140 The fancy display style highlights matching parts of the regexp,
141 a behavior similar to `swiper'.
143 This setting depends on `add-face-text-property' - a C function
144 available as of Emacs 24.5. Fancy style will render poorly in
145 earlier versions of Emacs."
147 (const :tag "Plain" nil)
148 (const :tag "Fancy" fancy)))
150 (defcustom ivy-on-del-error-function 'minibuffer-keyboard-quit
151 "The handler for when `ivy-backward-delete-char' throws.
152 Usually a quick exit out of the minibuffer."
155 (defcustom ivy-extra-directories '("../" "./")
156 "Add this to the front of the list when completing file names.
157 Only \"./\" and \"../\" apply here. They appear in reverse order."
158 :type '(repeat :tag "Dirs"
160 (const :tag "Parent Directory" "../")
161 (const :tag "Current Directory" "./"))))
163 (defcustom ivy-use-virtual-buffers nil
164 "When non-nil, add `recentf-mode' and bookmarks to `ivy-switch-buffer'."
167 (defvar ivy--actions-list nil
168 "A list of extra actions per command.")
170 (defun ivy-set-actions (cmd actions)
171 "Set CMD extra exit points to ACTIONS."
172 (setq ivy--actions-list
173 (plist-put ivy--actions-list cmd actions)))
175 (defvar ivy--display-transformers-list nil
176 "A list of str->str transformers per command.")
178 (defun ivy-set-display-transformer (cmd transformer)
179 "Set CMD a displayed candidate TRANSFORMER.
181 It's a lambda that takes a string one of the candidates in the
182 collection and returns a string for display, the same candidate
183 plus some extra information.
185 This lambda is called only on the `ivy-height' candidates that
186 are about to be displayed, not on the whole collection."
187 (setq ivy--display-transformers-list
188 (plist-put ivy--display-transformers-list cmd transformer)))
190 (defvar ivy--sources-list nil
191 "A list of extra sources per command.")
193 (defun ivy-set-sources (cmd sources)
194 "Attach to CMD a list of extra SOURCES.
196 Each static source is a function that takes no argument and
197 returns a list of strings.
199 The '(original-source) determines the position of the original
202 Extra dynamic sources aren't supported yet.
206 (defun small-recentf ()
207 (cl-subseq recentf-list 0 20))
214 (setq ivy--sources-list
215 (plist-put ivy--sources-list cmd sources)))
219 (defvar ivy-minibuffer-map
220 (let ((map (make-sparse-keymap)))
221 (define-key map (kbd "C-m") 'ivy-done)
222 (define-key map (kbd "C-M-m") 'ivy-call)
223 (define-key map (kbd "C-j") 'ivy-alt-done)
224 (define-key map (kbd "C-M-j") 'ivy-immediate-done)
225 (define-key map (kbd "TAB") 'ivy-partial-or-done)
226 (define-key map (kbd "C-n") 'ivy-next-line)
227 (define-key map (kbd "C-p") 'ivy-previous-line)
228 (define-key map (kbd "<down>") 'ivy-next-line)
229 (define-key map (kbd "<up>") 'ivy-previous-line)
230 (define-key map (kbd "C-s") 'ivy-next-line-or-history)
231 (define-key map (kbd "C-r") 'ivy-reverse-i-search)
232 (define-key map (kbd "SPC") 'self-insert-command)
233 (define-key map (kbd "DEL") 'ivy-backward-delete-char)
234 (define-key map (kbd "M-DEL") 'ivy-backward-kill-word)
235 (define-key map (kbd "C-d") 'ivy-delete-char)
236 (define-key map (kbd "C-f") 'ivy-forward-char)
237 (define-key map (kbd "M-d") 'ivy-kill-word)
238 (define-key map (kbd "M-<") 'ivy-beginning-of-buffer)
239 (define-key map (kbd "M->") 'ivy-end-of-buffer)
240 (define-key map (kbd "M-n") 'ivy-next-history-element)
241 (define-key map (kbd "M-p") 'ivy-previous-history-element)
242 (define-key map (kbd "C-g") 'minibuffer-keyboard-quit)
243 (define-key map (kbd "C-v") 'ivy-scroll-up-command)
244 (define-key map (kbd "M-v") 'ivy-scroll-down-command)
245 (define-key map (kbd "C-M-n") 'ivy-next-line-and-call)
246 (define-key map (kbd "C-M-p") 'ivy-previous-line-and-call)
247 (define-key map (kbd "M-q") 'ivy-toggle-regexp-quote)
248 (define-key map (kbd "M-j") 'ivy-yank-word)
249 (define-key map (kbd "M-i") 'ivy-insert-current)
250 (define-key map (kbd "C-o") 'hydra-ivy/body)
251 (define-key map (kbd "M-o") 'ivy-dispatching-done)
252 (define-key map (kbd "C-M-o") 'ivy-dispatching-call)
253 (define-key map (kbd "C-k") 'ivy-kill-line)
254 (define-key map (kbd "S-SPC") 'ivy-restrict-to-matches)
255 (define-key map (kbd "M-w") 'ivy-kill-ring-save)
256 (define-key map (kbd "C-'") 'ivy-avy)
257 (define-key map (kbd "C-M-a") 'ivy-read-action)
258 (define-key map (kbd "C-c C-o") 'ivy-occur)
259 (define-key map (kbd "C-c C-a") 'ivy-toggle-ignore)
260 (define-key map (kbd "C-h m") 'ivy-help)
262 "Keymap used in the minibuffer.")
263 (autoload 'hydra-ivy/body "ivy-hydra" "" t)
266 (let ((map (make-sparse-keymap)))
267 (define-key map [remap switch-to-buffer]
269 (define-key map [remap switch-to-buffer-other-window]
270 'ivy-switch-buffer-other-window)
272 "Keymap for `ivy-mode'.")
275 (cl-defstruct ivy-state
277 predicate require-match initial-input
278 history preselect keymap update-fn sort
279 ;; The window in which `ivy-read' was called
281 ;; The buffer in which `ivy-read' was called
283 ;; The value of `ivy-text' to be used by `ivy-occur'
289 ;; When this is non-nil, call it for each input change to get new candidates
291 ;; A lambda that transforms candidates only for display
292 display-transformer-fn
295 (defvar ivy-last (make-ivy-state)
296 "The last parameters passed to `ivy-read'.
298 This should eventually become a stack so that you could use
299 `ivy-read' recursively.")
301 (defsubst ivy-set-action (action)
302 (setf (ivy-state-action ivy-last) action))
304 (defun ivy-thing-at-point ()
305 "Return a string that corresponds to the current thing at point."
307 (thing-at-point 'url)
310 (cond ((stringp (setq s (thing-at-point 'symbol)))
311 (if (string-match "\\`[`']?\\(.*?\\)'?\\'" s)
314 ((looking-at "(+\\(\\(?:\\sw\\|\\s_\\)+\\)\\_>")
315 (match-string-no-properties 1))
319 (defvar ivy-history nil
320 "History list of candidates entered in the minibuffer.
322 Maximum length of the history list is determined by the value
323 of `history-length'.")
325 (defvar ivy--directory nil
326 "Current directory when completing file names.")
328 (defvar ivy--length 0
329 "Store the amount of viable candidates.")
332 "Store the user's string as it is typed in.")
334 (defvar ivy--current ""
335 "Current candidate.")
338 "Store the index of the current candidate.")
341 "Store 'done if the completion was successfully selected.
342 Otherwise, store nil.")
344 (defvar ivy--all-candidates nil
345 "Store the candidates passed to `ivy-read'.")
347 (defvar ivy--extra-candidates '((original-source))
348 "Store candidates added by the extra sources.
350 This is an internal-use alist. Each key is a function name, or
351 original-source (which represents where the current dynamic
352 candidates should go).
354 Each value is an evaluation of the function, in case of static
355 sources. These values will subsequently be filtered on `ivy-text'.
357 This variable is set by `ivy-read' and used by `ivy--set-candidates'.")
359 (defvar ivy-use-ignore t
360 "Store policy for user-configured candidate filtering.")
362 (defvar ivy--default nil
363 "Default initial input.")
365 (defvar ivy--prompt nil
366 "Store the format-style prompt.
367 When non-nil, it should contain at least one %d.")
369 (defvar ivy--prompt-extra ""
370 "Temporary modifications to the prompt.")
372 (defvar ivy--old-re nil
373 "Store the old regexp.")
375 (defvar ivy--old-cands nil
376 "Store the candidates matched by `ivy--old-re'.")
378 (defvar ivy--regex-function 'ivy--regex
379 "Current function for building a regex.")
381 (defvar ivy--subexps 0
382 "Number of groups in the current `ivy--regex'.")
384 (defvar ivy--full-length nil
385 "When :dynamic-collection is non-nil, this can be the total amount of candidates.")
387 (defvar ivy--old-text ""
388 "Store old `ivy-text' for dynamic completion.")
390 (defvar ivy-case-fold-search 'auto
391 "Store the current overriding `case-fold-search'.")
393 (defvar Info-current-file)
396 (unless (fboundp 'defvar-local)
397 (defmacro defvar-local (var val &optional docstring)
398 "Define VAR as a buffer-local variable with default value VAL."
399 (declare (debug defvar) (doc-string 3))
400 (list 'progn (list 'defvar var val docstring)
401 (list 'make-variable-buffer-local (list 'quote var)))))
402 (unless (fboundp 'setq-local)
403 (defmacro setq-local (var val)
404 "Set variable VAR to value VAL in current buffer."
405 (list 'set (list 'make-local-variable (list 'quote var)) val))))
407 (defmacro ivy-quit-and-run (&rest body)
408 "Quit the minibuffer and run BODY afterwards."
410 (put 'quit 'error-message "")
413 (put 'quit 'error-message "Quit")
415 (minibuffer-keyboard-quit)))
417 (defun ivy-exit-with-action (action)
418 "Quit the minibuffer and call ACTION afterwards."
422 (ivy-set-action ',(ivy-state-action ivy-last))))
423 (setq ivy-exit 'done)
426 (defmacro with-ivy-window (&rest body)
427 "Execute BODY in the window from which `ivy-read' was called."
430 `(with-selected-window (ivy--get-window ivy-last)
433 (defun ivy--done (text)
434 "Insert TEXT and exit minibuffer."
435 (if (and ivy--directory
436 (not (eq (ivy-state-history ivy-last) 'grep-files-history)))
437 (insert (setq ivy--current (expand-file-name
438 text ivy--directory)))
439 (insert (setq ivy--current text)))
440 (setq ivy-exit 'done)
445 "Exit the minibuffer with the selected candidate."
447 (delete-minibuffer-contents)
448 (cond ((> ivy--length 0)
449 (ivy--done ivy--current))
450 ((memq (ivy-state-collection ivy-last)
451 '(read-file-name-internal internal-complete-buffer))
452 (if (or (not (eq confirm-nonexistent-file-or-buffer t))
453 (equal " (confirm)" ivy--prompt-extra))
455 (setq ivy--prompt-extra " (confirm)")
458 ((memq (ivy-state-require-match ivy-last)
459 '(nil confirm confirm-after-completion))
460 (ivy--done ivy-text))
462 (setq ivy--prompt-extra " (match required)")
466 (defun ivy-read-action ()
467 "Change the action to one of the available ones.
469 Return nil for `minibuffer-keyboard-quit' or wrong key during the
470 selection, non-nil otherwise."
472 (let ((actions (ivy-state-action ivy-last)))
473 (if (null (ivy--actionp actions))
475 (let* ((hint (concat (if (eq this-command 'ivy-read-action)
484 'face 'font-lock-builtin-face)
489 (resize-mini-windows 'grow-only)
490 (key (string (read-key hint)))
491 (action-idx (cl-position-if
492 (lambda (x) (equal (car x) key))
494 (cond ((string= key "
\a")
497 (message "%s is not bound" key)
501 (setcar actions (1+ action-idx))
502 (ivy-set-action actions)))))))
504 (defun ivy-dispatching-done ()
505 "Select one of the available actions and call `ivy-done'."
507 (when (ivy-read-action)
510 (defun ivy-dispatching-call ()
511 "Select one of the available actions and call `ivy-call'."
513 (let ((actions (copy-sequence (ivy-state-action ivy-last))))
515 (when (ivy-read-action)
517 (ivy-set-action actions))))
519 (defun ivy-build-tramp-name (x)
520 "Reconstruct X into a path.
521 Is is a cons cell, related to `tramp-get-completion-function'."
525 (concat user "@" domain)
528 (declare-function tramp-get-completion-function "tramp")
529 (declare-function Info-find-node "info")
531 (defun ivy-alt-done (&optional arg)
532 "Exit the minibuffer with the selected candidate.
533 When ARG is t, exit with current text, ignoring the candidates."
536 (ivy-immediate-done))
538 (ivy--directory-done))
539 ((eq (ivy-state-collection ivy-last) 'Info-read-node-name-1)
540 (if (member ivy--current '("(./)" "(../)"))
542 (ivy-read "Go to file: " 'read-file-name-internal
545 (expand-file-name x ivy--directory)
551 (defun ivy--directory-done ()
552 "Handle exit from the minibuffer when completing file names."
555 ((equal ivy-text "/sudo::")
556 (setq dir (concat ivy-text ivy--directory))
561 (not (string= ivy--current "./"))
562 (setq dir (ivy-expand-file-if-directory ivy--current)))
565 ((or (and (equal ivy--directory "/")
566 (string-match "\\`[^/]+:.*:.*\\'" ivy-text))
567 (string-match "\\`/[^/]+:.*:.*\\'" ivy-text))
569 ((or (and (equal ivy--directory "/")
571 "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
574 "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
576 (setq ivy-text ivy--current))))
578 "\\`/\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
580 (let ((method (match-string 1 ivy-text))
581 (user (match-string 2 ivy-text))
582 (rest (match-string 3 ivy-text))
585 (dolist (x (tramp-get-completion-function method))
586 (setq res (append res (funcall (car x) (cadr x)))))
587 (setq res (delq nil res))
591 (setq res (cl-delete-duplicates res :test #'equal))
592 (let* ((old-ivy-last ivy-last)
593 (enable-recursive-minibuffers t)
594 (host (ivy-read "user@host: "
595 (mapcar #'ivy-build-tramp-name res)
596 :initial-input rest)))
597 (setq ivy-last old-ivy-last)
599 (setq ivy--directory "/")
600 (ivy--cd (concat "/" method ":" host ":"))))))
604 (defun ivy-expand-file-if-directory (file-name)
605 "Expand FILE-NAME as directory.
606 When this directory doesn't exist, return nil."
607 (when (stringp file-name)
609 ;; Ignore host name must not match method "ssh"
611 (file-name-as-directory
612 (expand-file-name file-name ivy--directory)))))
613 (when (and full-name (file-directory-p full-name))
616 (defcustom ivy-tab-space nil
617 "When non-nil, `ivy-partial-or-done' should insert a space."
620 (defun ivy-partial-or-done ()
621 "Complete the minibuffer text as much as possible.
622 If the text hasn't changed as a result, forward to `ivy-alt-done'."
624 (if (and (eq (ivy-state-collection ivy-last) #'read-file-name-internal)
625 (or (and (equal ivy--directory "/")
626 (string-match "\\`[^/]+:.*\\'" ivy-text))
627 (string-match "\\`/" ivy-text)))
628 (let ((default-directory ivy--directory)
630 (minibuffer-complete)
631 (setq ivy-text (ivy--input))
632 (when (setq dir (ivy-expand-file-if-directory ivy-text))
635 (when (or (eq this-command last-command)
639 (defun ivy-partial ()
640 "Complete the minibuffer text as much as possible."
642 (let* ((parts (or (split-string ivy-text " " t) (list "")))
643 (postfix (car (last parts)))
644 (completion-ignore-case t)
645 (startp (string-match "^\\^" postfix))
646 (new (try-completion (if startp
647 (substring postfix 1)
649 (mapcar (lambda (str)
650 (let ((i (string-match postfix str)))
654 (cond ((eq new t) nil)
655 ((string= new ivy-text) nil)
657 (delete-region (minibuffer-prompt-end) (point-max))
662 (insert (mapconcat #'identity parts " ")
663 (if ivy-tab-space " " ""))
666 (defun ivy-immediate-done ()
667 "Exit the minibuffer with the current input."
669 (delete-minibuffer-contents)
670 (insert (setq ivy--current
672 (expand-file-name ivy-text ivy--directory)
674 (setq ivy-exit 'done)
679 "Resume the last completion session."
681 (if (null (ivy-state-action ivy-last))
682 (user-error "The last session isn't compatible with `ivy-resume'")
683 (when (eq (ivy-state-caller ivy-last) 'swiper)
684 (switch-to-buffer (ivy-state-buffer ivy-last)))
685 (with-current-buffer (ivy-state-buffer ivy-last)
687 (ivy-state-prompt ivy-last)
688 (ivy-state-collection ivy-last)
689 :predicate (ivy-state-predicate ivy-last)
690 :require-match (ivy-state-require-match ivy-last)
691 :initial-input ivy-text
692 :history (ivy-state-history ivy-last)
693 :preselect (unless (eq (ivy-state-collection ivy-last)
694 'read-file-name-internal)
696 :keymap (ivy-state-keymap ivy-last)
697 :update-fn (ivy-state-update-fn ivy-last)
698 :sort (ivy-state-sort ivy-last)
699 :action (ivy-state-action ivy-last)
700 :unwind (ivy-state-unwind ivy-last)
701 :re-builder (ivy-state-re-builder ivy-last)
702 :matcher (ivy-state-matcher ivy-last)
703 :dynamic-collection (ivy-state-dynamic-collection ivy-last)
704 :caller (ivy-state-caller ivy-last)))))
706 (defvar-local ivy-calling nil
707 "When non-nil, call the current action when `ivy--index' changes.")
709 (defun ivy-set-index (index)
710 "Set `ivy--index' to INDEX."
711 (setq ivy--index index)
716 (defun ivy-beginning-of-buffer ()
717 "Select the first completion candidate."
721 (defun ivy-end-of-buffer ()
722 "Select the last completion candidate."
724 (ivy-set-index (1- ivy--length)))
726 (defun ivy-scroll-up-command ()
727 "Scroll the candidates upward by the minibuffer height."
729 (ivy-set-index (min (1- (+ ivy--index ivy-height))
732 (defun ivy-scroll-down-command ()
733 "Scroll the candidates downward by the minibuffer height."
735 (ivy-set-index (max (1+ (- ivy--index ivy-height))
738 (defun ivy-minibuffer-grow ()
739 "Grow the minibuffer window by 1 line."
741 (setq-local max-mini-window-height
742 (cl-incf ivy-height)))
744 (defun ivy-minibuffer-shrink ()
745 "Shrink the minibuffer window by 1 line."
747 (unless (<= ivy-height 2)
748 (setq-local max-mini-window-height
749 (cl-decf ivy-height))
750 (window-resize (selected-window) -1)))
752 (defun ivy-next-line (&optional arg)
753 "Move cursor vertically down ARG candidates."
755 (setq arg (or arg 1))
756 (let ((index (+ ivy--index arg)))
757 (if (> index (1- ivy--length))
759 (ivy-beginning-of-buffer)
760 (ivy-set-index (1- ivy--length)))
761 (ivy-set-index index))))
763 (defun ivy-next-line-or-history (&optional arg)
764 "Move cursor vertically down ARG candidates.
765 If the input is empty, select the previous history element instead."
767 (if (string= ivy-text "")
768 (ivy-previous-history-element 1)
769 (ivy-next-line arg)))
771 (defun ivy-previous-line (&optional arg)
772 "Move cursor vertically up ARG candidates."
774 (setq arg (or arg 1))
775 (let ((index (- ivy--index arg)))
780 (ivy-set-index index))))
782 (defun ivy-previous-line-or-history (arg)
783 "Move cursor vertically up ARG candidates.
784 If the input is empty, select the previous history element instead."
786 (when (string= ivy-text "")
787 (ivy-previous-history-element 1))
788 (ivy-previous-line arg))
790 (defun ivy-toggle-calling ()
791 "Flip `ivy-calling'."
793 (when (setq ivy-calling (not ivy-calling))
796 (defun ivy-toggle-ignore ()
797 "Toggle user-configured candidate filtering."
799 (setq ivy-use-ignore (null ivy-use-ignore))
801 (setq ivy--old-cands nil))
803 (defun ivy--get-action (state)
804 "Get the action function from STATE."
805 (let ((action (ivy-state-action state)))
807 (if (functionp action)
809 (cadr (nth (car action) action))))))
811 (defun ivy--get-window (state)
812 "Get the window from STATE."
813 (if (ivy-state-p state)
814 (let ((window (ivy-state-window state)))
815 (if (window-live-p window)
817 (if (= (length (window-list)) 1)
822 (defun ivy--actionp (x)
823 "Return non-nil when X is a list of actions."
824 (and x (listp x) (not (eq (car x) 'closure))))
826 (defun ivy-next-action ()
827 "When the current action is a list, scroll it forwards."
829 (let ((action (ivy-state-action ivy-last)))
830 (when (ivy--actionp action)
831 (unless (>= (car action) (1- (length action)))
832 (cl-incf (car action))))))
834 (defun ivy-prev-action ()
835 "When the current action is a list, scroll it backwards."
837 (let ((action (ivy-state-action ivy-last)))
838 (when (ivy--actionp action)
839 (unless (<= (car action) 1)
840 (cl-decf (car action))))))
842 (defun ivy-action-name ()
843 "Return the name associated with the current action."
844 (let ((action (ivy-state-action ivy-last)))
845 (if (ivy--actionp action)
849 (nth 2 (nth (car action) action)))
852 (defvar ivy-inhibit-action nil
853 "When non-nil, `ivy-call' does nothing.
857 (let* ((ivy-inhibit-action t)
858 (str (counsel-locate \"lispy.el\")))
859 ;; do whatever with str - the corresponding file will not be opened
863 "Call the current action without exiting completion."
865 (unless ivy-inhibit-action
866 (let ((action (ivy--get-action ivy-last)))
868 (let* ((collection (ivy-state-collection ivy-last))
869 (x (if (and (consp collection)
870 (consp (car collection)))
871 (cdr (assoc ivy--current collection))
872 (if (equal ivy--current "")
875 (prog1 (funcall action x)
876 (unless (or (eq ivy-exit 'done)
877 (equal (selected-window)
878 (active-minibuffer-window))
879 (null (active-minibuffer-window)))
880 (select-window (active-minibuffer-window)))))))))
882 (defun ivy-next-line-and-call (&optional arg)
883 "Move cursor vertically down ARG candidates.
884 Call the permanent action if possible."
890 (defun ivy-previous-line-and-call (&optional arg)
891 "Move cursor vertically down ARG candidates.
892 Call the permanent action if possible."
894 (ivy-previous-line arg)
898 (defun ivy-previous-history-element (arg)
899 "Forward to `previous-history-element' with ARG."
901 (previous-history-element arg)
904 (ivy--maybe-scroll-history))
906 (defun ivy-next-history-element (arg)
907 "Forward to `next-history-element' with ARG."
909 (if (and (= minibuffer-history-position 0)
912 (insert ivy--default)
913 (when (and (with-ivy-window (derived-mode-p 'prog-mode))
914 (not (file-exists-p ivy--default))
915 (not (ffap-url-p ivy--default))
916 (not (ivy-state-dynamic-collection ivy-last))
917 (> (point) (minibuffer-prompt-end)))
920 (goto-char (minibuffer-prompt-end))
922 (forward-char (+ 2 (length ivy--default)))))
923 (next-history-element arg))
926 (ivy--maybe-scroll-history))
928 (defvar ivy-ffap-url-functions nil
929 "List of functions that check if the point is on a URL.")
931 (defun ivy--cd-maybe ()
932 "Check if the current input points to a different directory.
933 If so, move to that directory, while keeping only the file name."
935 (let ((input (ivy--input))
937 (if (setq url (or (ffap-url-p input)
942 ivy-ffap-url-functions
943 :initial-value nil))))
944 (ivy-exit-with-action
946 (funcall ffap-url-fetcher url)))
947 (setq input (expand-file-name input))
948 (let ((file (file-name-nondirectory input))
949 (dir (expand-file-name (file-name-directory input))))
950 (if (string= dir ivy--directory)
952 (delete-minibuffer-contents)
957 (defun ivy--maybe-scroll-history ()
958 "If the selected history element has an index, scroll there."
959 (let ((idx (ignore-errors
961 (minibuffer-prompt-end)
965 (setq ivy--index idx))))
968 "When completing file names, move to directory DIR."
969 (if (null ivy--directory)
971 (setq ivy--old-cands nil)
972 (setq ivy--old-re nil)
974 (setq ivy--all-candidates
975 (ivy--sorted-files (setq ivy--directory dir)))
977 (delete-minibuffer-contents)))
979 (defun ivy-backward-delete-char ()
980 "Forward to `backward-delete-char'.
981 On error (read-only), call `ivy-on-del-error-function'."
983 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
985 (ivy--cd (file-name-directory
991 (backward-delete-char 1)
993 (when ivy-on-del-error-function
994 (funcall ivy-on-del-error-function))))))
996 (defun ivy-delete-char (arg)
997 "Forward to `delete-char' ARG."
999 (unless (= (point) (line-end-position))
1002 (defun ivy-forward-char (arg)
1003 "Forward to `forward-char' ARG."
1005 (unless (= (point) (line-end-position))
1006 (forward-char arg)))
1008 (defun ivy-kill-word (arg)
1009 "Forward to `kill-word' ARG."
1011 (unless (= (point) (line-end-position))
1014 (defun ivy-kill-line ()
1015 "Forward to `kill-line'."
1018 (kill-region (minibuffer-prompt-end) (point))
1021 (defun ivy-backward-kill-word ()
1022 "Forward to `backward-kill-word'."
1024 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
1026 (ivy--cd (file-name-directory
1027 (directory-file-name
1034 (delete-region (point) pt)))))
1036 (defvar ivy--regexp-quote 'regexp-quote
1037 "Store the regexp quoting state.")
1039 (defun ivy-toggle-regexp-quote ()
1040 "Toggle the regexp quoting."
1042 (setq ivy--old-re nil)
1043 (cl-rotatef ivy--regex-function ivy--regexp-quote))
1045 (defvar avy-all-windows)
1048 (defvar avy-keys-alist)
1050 (defvar avy-styles-alist)
1051 (declare-function avy--process "ext:avy")
1052 (declare-function avy--style-fn "ext:avy")
1054 (eval-after-load 'avy
1055 '(add-to-list 'avy-styles-alist '(ivy-avy . pre)))
1058 "Jump to one of the current ivy candidates."
1060 (unless (require 'avy nil 'noerror)
1061 (error "Package avy isn't installed"))
1062 (let* ((avy-all-windows nil)
1063 (avy-keys (or (cdr (assq 'ivy-avy avy-keys-alist))
1065 (avy-style (or (cdr (assq 'ivy-avy
1075 (goto-char (point-min))
1077 (while (< (point) (point-max))
1083 (setq avy-action #'identity)
1085 (nreverse candidates)
1086 (avy--style-fn avy-style)))))
1087 (when (numberp candidate)
1088 (ivy-set-index (- (line-number-at-pos candidate) 2))
1092 (defun ivy-sort-file-function-default (x y)
1093 "Compare two files X and Y.
1094 Prioritize directories."
1095 (if (get-text-property 0 'dirp x)
1096 (if (get-text-property 0 'dirp y)
1099 (if (get-text-property 0 'dirp y)
1103 (defcustom ivy-sort-functions-alist
1104 '((read-file-name-internal . ivy-sort-file-function-default)
1105 (internal-complete-buffer . nil)
1106 (counsel-git-grep-function . nil)
1107 (Man-goto-section . nil)
1110 "An alist of sorting functions for each collection function.
1111 Interactive functions that call completion fit in here as well.
1113 Nil means no sorting, which is useful to turn off the sorting for
1114 functions that have candidates in the natural buffer order, like
1115 `org-refile' or `Man-goto-section'.
1117 The entry associated with t is used for all fall-through cases.
1119 See also `ivy-sort-max-size'."
1123 (const :tag "Fall-through" t)
1124 (symbol :tag "Collection"))
1126 (const :tag "Plain sort" string-lessp)
1127 (const :tag "File sort" ivy-sort-file-function-default)
1128 (const :tag "No sort" nil)))
1131 (defvar ivy-index-functions-alist
1132 '((swiper . ivy-recompute-index-swiper)
1133 (swiper-multi . ivy-recompute-index-swiper)
1134 (counsel-git-grep . ivy-recompute-index-swiper)
1135 (counsel-grep . ivy-recompute-index-swiper-async)
1136 (t . ivy-recompute-index-zero))
1137 "An alist of index recomputing functions for each collection function.
1138 When the input changes, the appropriate function returns an
1139 integer - the index of the matched candidate that should be
1142 (defvar ivy-re-builders-alist
1143 '((t . ivy--regex-plus))
1144 "An alist of regex building functions for each collection function.
1146 Each key is (in order of priority):
1147 1. The actual collection function, e.g. `read-file-name-internal'.
1148 2. The symbol passed by :caller into `ivy-read'.
1152 Each value is a function that should take a string and return a
1153 valid regex or a regex sequence (see below).
1155 Possible choices: `ivy--regex', `regexp-quote',
1156 `ivy--regex-plus', `ivy--regex-fuzzy'.
1158 If a function returns a list, it should format like this:
1159 '((\"matching-regexp\" . t) (\"non-matching-regexp\") ...).
1161 The matches will be filtered in a sequence, you can mix the
1162 regexps that should match and that should not match as you
1165 (defvar ivy-initial-inputs-alist
1166 '((org-refile . "^")
1167 (org-agenda-refile . "^")
1168 (org-capture-refile . "^")
1170 (counsel-describe-function . "^")
1171 (counsel-describe-variable . "^")
1174 "Command to initial input table.")
1176 (defcustom ivy-sort-max-size 30000
1177 "Sorting won't be done for collections larger than this."
1180 (defun ivy--sorted-files (dir)
1181 "Return the list of files in DIR.
1182 Directories come first."
1183 (let* ((default-directory dir)
1184 (seq (all-completions "" 'read-file-name-internal))
1188 (setq seq (delete "./" (delete "../" seq)))
1189 (when (eq (setq sort-fn (cdr (assoc 'read-file-name-internal
1190 ivy-sort-functions-alist)))
1191 #'ivy-sort-file-function-default)
1192 (setq seq (mapcar (lambda (x)
1193 (propertize x 'dirp (string-match-p "/\\'" x)))
1196 (setq seq (cl-sort seq sort-fn)))
1197 (dolist (dir ivy-extra-directories)
1201 (defvar ivy-recursive-restore t
1202 "When non-nil, restore the above state when exiting the minibuffer.
1203 This variable is let-bound to nil by functions that take care of
1204 the restoring themselves.")
1207 (cl-defun ivy-read (prompt collection
1209 predicate require-match initial-input
1210 history preselect keymap update-fn sort
1211 action unwind re-builder matcher dynamic-collection caller)
1212 "Read a string in the minibuffer, with completion.
1214 PROMPT is a format string, normally ending in a colon and a
1215 space; %d anywhere in the string is replaced by the current
1216 number of matching candidates. For the literal % character,
1217 escape it with %%. See also `ivy-count-format'.
1219 COLLECTION is either a list of strings, a function, an alist, or
1222 If INITIAL-INPUT is not nil, then insert that input in the
1223 minibuffer initially.
1225 KEYMAP is composed with `ivy-minibuffer-map'.
1227 If PRESELECT is not nil, then select the corresponding candidate
1228 out of the ones that match the INITIAL-INPUT.
1230 UPDATE-FN is called each time the current candidate(s) is changed.
1232 When SORT is t, use `ivy-sort-functions-alist' for sorting.
1234 ACTION is a lambda function to call after selecting a result. It
1235 takes a single string argument.
1237 UNWIND is a lambda function to call before exiting.
1239 RE-BUILDER is a lambda function to call to transform text into a
1242 MATCHER is to override matching.
1244 DYNAMIC-COLLECTION is a boolean to specify if the list of
1245 candidates is updated after each input by calling COLLECTION.
1247 CALLER is a symbol to uniquely identify the caller to `ivy-read'.
1248 It is used, along with COLLECTION, to determine which
1249 customizations apply to the current completion session."
1250 (let ((extra-actions (delete-dups
1251 (append (plist-get ivy--actions-list t)
1252 (plist-get ivy--actions-list this-command)
1253 (plist-get ivy--actions-list caller)))))
1256 (cond ((functionp action)
1258 ("o" ,action "default")
1262 ("o" identity "default")
1265 (delete-dups (append action extra-actions)))))))
1266 (let ((extra-sources (plist-get ivy--sources-list caller)))
1269 (setq ivy--extra-candidates nil)
1270 (dolist (source extra-sources)
1271 (cond ((equal source '(original-source))
1272 (setq ivy--extra-candidates
1273 (cons source ivy--extra-candidates)))
1274 ((null (cdr source))
1275 (setq ivy--extra-candidates
1277 (list (car source) (funcall (car source)))
1278 ivy--extra-candidates))))))
1279 (setq ivy--extra-candidates '((original-source)))))
1280 (let ((recursive-ivy-last (and (active-minibuffer-window) ivy-last))
1282 (plist-get ivy--display-transformers-list
1283 (or caller (and (functionp collection)
1288 :collection collection
1289 :predicate predicate
1290 :require-match require-match
1291 :initial-input initial-input
1293 :preselect preselect
1295 :update-fn update-fn
1298 :window (selected-window)
1299 :buffer (current-buffer)
1301 :re-builder re-builder
1303 :dynamic-collection dynamic-collection
1304 :display-transformer-fn transformer-fn
1306 (ivy--reset-state ivy-last)
1309 (minibuffer-with-setup-hook
1310 #'ivy--minibuffer-setup
1311 (let* ((hist (or history 'ivy-history))
1312 (minibuffer-completion-table collection)
1313 (minibuffer-completion-predicate predicate)
1314 (resize-mini-windows (cond
1315 ((display-graphic-p) nil)
1316 ((null resize-mini-windows) 'grow-only)
1317 (t resize-mini-windows))))
1318 (read-from-minibuffer
1320 (ivy-state-initial-input ivy-last)
1321 (make-composed-keymap keymap ivy-minibuffer-map)
1324 (when (eq ivy-exit 'done)
1325 (let ((item (if ivy--directory
1328 (unless (equal item "")
1329 (set hist (cons (propertize item 'ivy-index ivy--index)
1331 (cdr (symbol-value hist))))))))
1333 (remove-hook 'post-command-hook #'ivy--exhibit)
1334 (when (setq unwind (ivy-state-unwind ivy-last))
1336 (unless (eq ivy-exit 'done)
1337 (when recursive-ivy-last
1338 (ivy--reset-state (setq ivy-last recursive-ivy-last)))))
1340 (when (and recursive-ivy-last
1341 ivy-recursive-restore)
1342 (ivy--reset-state (setq ivy-last recursive-ivy-last))))))
1344 (defun ivy--reset-state (state)
1345 "Reset the ivy to STATE.
1346 This is useful for recursive `ivy-read'."
1347 (let ((prompt (or (ivy-state-prompt state) ""))
1348 (collection (ivy-state-collection state))
1349 (predicate (ivy-state-predicate state))
1350 (history (ivy-state-history state))
1351 (preselect (ivy-state-preselect state))
1352 (sort (ivy-state-sort state))
1353 (re-builder (ivy-state-re-builder state))
1354 (dynamic-collection (ivy-state-dynamic-collection state))
1355 (initial-input (ivy-state-initial-input state))
1356 (require-match (ivy-state-require-match state))
1357 (caller (ivy-state-caller state)))
1358 (unless initial-input
1359 (setq initial-input (cdr (assoc this-command
1360 ivy-initial-inputs-alist))))
1361 (setq ivy--directory nil)
1362 (setq ivy-case-fold-search 'auto)
1363 (setq ivy--regex-function
1365 (and (functionp collection)
1366 (cdr (assoc collection ivy-re-builders-alist)))
1368 (cdr (assoc caller ivy-re-builders-alist)))
1369 (cdr (assoc this-command ivy-re-builders-alist))
1370 (cdr (assoc t ivy-re-builders-alist))
1372 (setq ivy--subexps 0)
1373 (setq ivy--regexp-quote 'regexp-quote)
1374 (setq ivy--old-text "")
1375 (setq ivy--full-length nil)
1377 (setq ivy-calling nil)
1378 (setq ivy-use-ignore t)
1380 (cond ((eq collection 'Info-read-node-name-1)
1381 (if (equal Info-current-file "dir")
1383 (mapcar (lambda (x) (format "(%s)" x))
1384 (cl-delete-duplicates
1385 (all-completions "(" collection predicate)
1387 (setq coll (all-completions "" collection predicate))))
1388 ((eq collection 'read-file-name-internal)
1389 (setq ivy--directory default-directory)
1392 (let ((preselect-directory (file-name-directory preselect)))
1393 (unless (or (null preselect-directory)
1394 (string= preselect-directory
1396 (setq ivy--directory preselect-directory))
1398 (ivy-state-preselect state)
1399 (setq preselect (file-name-nondirectory preselect)))))
1400 (setq coll (ivy--sorted-files ivy--directory))
1402 (unless (or require-match
1403 (equal initial-input default-directory)
1404 (equal initial-input ""))
1405 (setq coll (cons initial-input coll)))
1406 (unless (and (ivy-state-action ivy-last)
1407 (not (equal (ivy--get-action ivy-last) 'identity)))
1408 (setq initial-input nil))))
1409 ((eq collection 'internal-complete-buffer)
1410 (setq coll (ivy--buffer-list "" ivy-use-virtual-buffers)))
1412 (setq coll (funcall collection ivy-text)))
1413 ((or (functionp collection)
1414 (byte-code-function-p collection)
1415 (vectorp collection)
1416 (and (consp collection) (listp (car collection)))
1417 (hash-table-p collection)
1418 (and (listp collection) (symbolp (car collection))))
1419 (setq coll (all-completions "" collection predicate)))
1421 (setq coll collection)))
1423 (if (and (functionp collection)
1424 (setq sort-fn (assoc collection ivy-sort-functions-alist)))
1425 (when (and (setq sort-fn (cdr sort-fn))
1426 (not (eq collection 'read-file-name-internal)))
1427 (setq coll (cl-sort coll sort-fn)))
1428 (unless (eq history 'org-refile-history)
1429 (if (and (setq sort-fn (cdr (assoc t ivy-sort-functions-alist)))
1430 (<= (length coll) ivy-sort-max-size))
1431 (setq coll (cl-sort (copy-sequence coll) sort-fn))))))
1432 (setq coll (ivy--set-candidates coll))
1434 (unless (or (and require-match
1435 (not (eq collection 'internal-complete-buffer)))
1437 (let ((re (regexp-quote preselect)))
1438 (cl-find-if (lambda (x) (string-match re x))
1440 (setq coll (cons preselect coll))))
1441 (setq ivy--old-re nil)
1442 (setq ivy--old-cands nil)
1443 (when (integerp preselect)
1444 (setq ivy--old-re "")
1445 (setq ivy--index preselect))
1447 ;; Needed for anchor to work
1448 (setq ivy--old-cands coll)
1449 (setq ivy--old-cands (ivy--filter initial-input coll)))
1450 (setq ivy--all-candidates coll)
1451 (unless (integerp preselect)
1452 (setq ivy--index (or
1453 (and dynamic-collection
1456 (ivy--preselect-index
1464 (if (region-active-p)
1468 (ivy-thing-at-point)))
1470 (cond ((string-match "%.*d" prompt)
1472 ((null ivy-count-format)
1474 "`ivy-count-format' can't be nil. Set it to an empty string instead"))
1475 ((string-match "%d.*%d" ivy-count-format)
1476 (let ((w (length (number-to-string
1477 (length ivy--all-candidates))))
1478 (s (copy-sequence ivy-count-format)))
1479 (string-match "%d" s)
1481 (string-match "%d" s (match-end 0))
1482 (setq s (replace-match (format "%%-%dd" w) nil nil s))
1483 (string-match "%d" s)
1484 (concat (replace-match (format "%%%dd" w) nil nil s)
1486 ((string-match "%.*d" ivy-count-format)
1487 (concat ivy-count-format prompt))
1492 (setf (ivy-state-initial-input ivy-last) initial-input)))
1495 (defun ivy-completing-read (prompt collection
1496 &optional predicate require-match initial-input
1497 history def inherit-input-method)
1498 "Read a string in the minibuffer, with completion.
1500 This interface conforms to `completing-read' and can be used for
1501 `completing-read-function'.
1503 PROMPT is a string that normally ends in a colon and a space.
1504 COLLECTION is either a list of strings, an alist, an obarray, or a hash table.
1505 PREDICATE limits completion to a subset of COLLECTION.
1506 REQUIRE-MATCH is a boolean value. See `completing-read'.
1507 INITIAL-INPUT is a string inserted into the minibuffer initially.
1508 HISTORY is a list of previously selected inputs.
1509 DEF is the default value.
1510 INHERIT-INPUT-METHOD is currently ignored."
1511 (if (memq this-command '(tmm-menubar tmm-shortcut))
1512 (completing-read-default prompt collection
1513 predicate require-match
1514 initial-input history
1515 def inherit-input-method)
1516 ;; See the doc of `completing-read'.
1517 (when (consp history)
1518 (when (numberp (cdr history))
1519 (setq initial-input (nth (1- (cdr history))
1520 (symbol-value (car history)))))
1521 (setq history (car history)))
1522 (ivy-read (replace-regexp-in-string "%" "%%" prompt)
1524 :predicate predicate
1525 :require-match require-match
1526 :initial-input (if (consp initial-input)
1528 (if (and (stringp initial-input)
1529 (string-match "\\+" initial-input))
1530 (replace-regexp-in-string
1531 "\\+" "\\\\+" initial-input)
1533 :preselect (if (listp def) (car def) def)
1537 (let ((sort (or (assoc this-command ivy-sort-functions-alist)
1538 (assoc t ivy-sort-functions-alist))))
1543 (defvar ivy-completion-beg nil
1544 "Completion bounds start.")
1546 (defvar ivy-completion-end nil
1547 "Completion bounds end.")
1549 (defun ivy-completion-in-region-action (str)
1550 "Insert STR, erasing the previous one.
1551 The previous string is between `ivy-completion-beg' and `ivy-completion-end'."
1554 (when ivy-completion-beg
1557 ivy-completion-end))
1558 (setq ivy-completion-beg
1559 (move-marker (make-marker) (point)))
1561 (setq ivy-completion-end
1562 (move-marker (make-marker) (point))))))
1564 (defun ivy-completion-common-length (str)
1565 "Return the length of the first 'completions-common-part face in STR."
1568 (while (and (<= pos len)
1569 (let ((prop (get-text-property pos 'face str)))
1570 (not (eq 'completions-common-part
1571 (if (listp prop) (car prop) prop)))))
1572 (setq pos (1+ pos)))
1574 (or (next-single-property-change pos 'face str) len)
1577 (defun ivy-completion-in-region (start end collection &optional predicate)
1578 "An Ivy function suitable for `completion-in-region-function'."
1579 (let* ((enable-recursive-minibuffers t)
1580 (str (buffer-substring-no-properties start end))
1581 (completion-ignore-case case-fold-search)
1583 (completion-all-completions str collection predicate (- end start))))
1585 (message "No matches")
1587 (setq ivy-completion-beg (- end (ivy-completion-common-length (car comps))))
1588 (setq ivy-completion-end end)
1589 (if (null (cdr comps))
1590 (if (string= str (car comps))
1591 (message "Sole match")
1592 (setf (ivy-state-window ivy-last) (selected-window))
1593 (ivy-completion-in-region-action
1594 (substring-no-properties
1596 (let* ((w (1+ (floor (log (length comps) 10))))
1597 (ivy-count-format (if (string= ivy-count-format "")
1599 (format "%%-%dd " w)))
1600 (prompt (format "(%s): " str)))
1602 (ivy-read (if (string= ivy-count-format "")
1604 (replace-regexp-in-string "%" "%%" prompt))
1605 ;; remove 'completions-first-difference face
1606 (mapcar #'substring-no-properties comps)
1607 :predicate predicate
1608 :action #'ivy-completion-in-region-action
1612 (defcustom ivy-do-completion-in-region t
1613 "When non-nil `ivy-mode' will set `completion-in-region-function'."
1617 (define-minor-mode ivy-mode
1618 "Toggle Ivy mode on or off.
1619 Turn Ivy mode on if ARG is positive, off otherwise.
1620 Turning on Ivy mode sets `completing-read-function' to
1621 `ivy-completing-read'.
1626 Minibuffer bindings:
1627 \\{ivy-minibuffer-map}"
1630 :keymap ivy-mode-map
1634 (setq completing-read-function 'ivy-completing-read)
1635 (when ivy-do-completion-in-region
1636 (setq completion-in-region-function 'ivy-completion-in-region)))
1637 (setq completing-read-function 'completing-read-default)
1638 (setq completion-in-region-function 'completion--in-region)))
1640 (defun ivy--preselect-index (preselect candidates)
1641 "Return the index of PRESELECT in CANDIDATES."
1642 (cond ((integerp preselect)
1644 ((cl-position preselect candidates :test #'equal))
1645 ((stringp preselect)
1646 (let ((re preselect))
1649 (string-match re x))
1654 (defvar ivy--regex-hash
1655 (make-hash-table :test #'equal)
1656 "Store pre-computed regex.")
1658 (defun ivy--split (str)
1659 "Split STR into a list by single spaces.
1660 The remaining spaces stick to their left.
1661 This allows to \"quote\" N spaces by inputting N+1 spaces."
1662 (let ((len (length str))
1667 (while (and (string-match " +" str start1)
1669 (setq match-len (- (match-end 0) (match-beginning 0)))
1673 (setq start1 start0)
1675 (push (substring str start1 (match-beginning 0)) res)
1676 (setq start1 (match-end 0)))
1677 (setq str (replace-match
1678 (make-string (1- match-len) ?\ )
1680 (setq start0 (or start0 start1))
1681 (setq start1 (1- (match-end 0)))))
1683 (push (substring str start0) res)
1684 (setq s (substring str start1))
1685 (unless (= (length s) 0)
1689 (defun ivy--regex (str &optional greedy)
1690 "Re-build regex pattern from STR in case it has a space.
1691 When GREEDY is non-nil, join words in a greedy way."
1692 (let ((hashed (unless greedy
1693 (gethash str ivy--regex-hash))))
1696 (setq ivy--subexps (car hashed)))
1697 (when (string-match "\\([^\\]\\|^\\)\\\\$" str)
1698 (setq str (substring str 0 -1)))
1700 (let ((subs (ivy--split str)))
1701 (if (= (length subs) 1)
1703 (setq ivy--subexps 0)
1706 (setq ivy--subexps (length subs))
1709 (if (string-match "\\`\\\\([^?].*\\\\)\\'" x)
1711 (format "\\(%s\\)" x)))
1716 ivy--regex-hash)))))
1718 (defun ivy--regex-ignore-order--part (str &optional discard)
1719 "Re-build regex from STR by splitting at spaces.
1720 Ignore the order of each group."
1721 (let* ((subs (split-string str " +" t))
1722 (len (length subs)))
1727 (mapcar (lambda (x) (cons x (not discard)))
1730 (defun ivy--regex-ignore-order (str)
1731 "Re-build regex from STR by splitting at spaces.
1732 Ignore the order of each group. Everything before \"!\" should
1733 match. Everything after \"!\" should not match."
1734 (let ((parts (split-string str "!" t)))
1735 (cl-case (length parts)
1739 (if (string= (substring str 0 1) "!")
1741 (ivy--regex-ignore-order--part (car parts) t))
1742 (ivy--regex-ignore-order--part (car parts))))
1745 (ivy--regex-ignore-order--part (car parts))
1746 (ivy--regex-ignore-order--part (cadr parts) t)))
1747 (t (error "Unexpected: use only one !")))))
1749 (defun ivy--regex-plus (str)
1750 "Build a regex sequence from STR.
1751 Spaces are wild card characters, everything before \"!\" should
1752 match. Everything after \"!\" should not match."
1753 (let ((parts (split-string str "!" t)))
1754 (cl-case (length parts)
1758 (if (string= (substring str 0 1) "!")
1760 (list (ivy--regex (car parts))))
1761 (ivy--regex (car parts))))
1764 (cons (ivy--regex (car parts)) t)
1765 (mapcar #'list (split-string (cadr parts) " " t))))
1766 (t (error "Unexpected: use only one !")))))
1768 (defun ivy--regex-fuzzy (str)
1769 "Build a regex sequence from STR.
1770 Insert .* between each char."
1771 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1773 (concat (match-string 1 str)
1776 (format "\\(%c\\)" x))
1777 (string-to-list (match-string 2 str)) ".*")
1778 (match-string 3 str))
1779 (setq ivy--subexps (length (match-string 2 str))))
1782 (defcustom ivy-fixed-height-minibuffer nil
1783 "When non nil, fix the height of the minibuffer during ivy
1784 completion at `ivy-height'. This effectively sets the minimum
1785 height at this level and tries to ensure that it does not change
1786 depending on the number of candidates."
1791 (defun ivy--minibuffer-setup ()
1792 "Setup ivy completion in the minibuffer."
1793 (set (make-local-variable 'completion-show-inline-help) nil)
1794 (set (make-local-variable 'minibuffer-default-add-function)
1796 (list ivy--default)))
1797 (when (display-graphic-p)
1798 (setq truncate-lines t))
1799 (setq-local max-mini-window-height ivy-height)
1800 (when ivy-fixed-height-minibuffer
1801 (set-window-text-height (selected-window) ivy-height))
1802 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1803 ;; show completions with empty input
1806 (defun ivy--input ()
1807 "Return the current minibuffer input."
1808 ;; assume one-line minibuffer input
1809 (buffer-substring-no-properties
1810 (minibuffer-prompt-end)
1811 (line-end-position)))
1813 (defun ivy--cleanup ()
1814 "Delete the displayed completion candidates."
1816 (goto-char (minibuffer-prompt-end))
1817 (delete-region (line-end-position) (point-max))))
1819 (defun ivy--insert-prompt ()
1820 "Update the prompt according to `ivy--prompt'."
1822 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1823 counsel-find-symbol))
1824 (setq ivy--prompt-extra ""))
1826 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1828 (setq head (match-string 1 ivy--prompt))
1830 (setq head (substring ivy--prompt 0 -1))
1832 (let ((inhibit-read-only t)
1833 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1836 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1837 (> (minibuffer-depth) 1))
1838 (format "[%d] " (minibuffer-depth))
1841 (if (string-match "%d.*%d" ivy-count-format)
1844 (or (and (ivy-state-dynamic-collection ivy-last)
1848 (or (and (ivy-state-dynamic-collection ivy-last)
1853 (d-str (if ivy--directory
1854 (abbreviate-file-name ivy--directory)
1857 (goto-char (point-min))
1858 (delete-region (point-min) (minibuffer-prompt-end))
1859 (if (> (+ (mod (+ (length n-str) (length d-str)) (window-width))
1862 (setq n-str (concat n-str "\n" d-str))
1863 (setq n-str (concat n-str d-str)))
1864 (when ivy-add-newline-after-prompt
1865 (setq n-str (concat n-str "\n")))
1866 (let ((regex (format "\\([^\n]\\{%d\\}\\)[^\n]" (window-width))))
1867 (while (string-match regex n-str)
1868 (setq n-str (replace-match (concat (match-string 1 n-str) "\n") nil t n-str 1))))
1869 (set-text-properties 0 (length n-str)
1870 `(face minibuffer-prompt ,@std-props)
1872 (ivy--set-match-props n-str "confirm"
1873 `(face ivy-confirm-face ,@std-props))
1874 (ivy--set-match-props n-str "match required"
1875 `(face ivy-match-required-face ,@std-props))
1877 ;; get out of the prompt area
1878 (constrain-to-field nil (point-max))))))
1880 (defun ivy--set-match-props (str match props)
1881 "Set STR text properties that match MATCH to PROPS."
1882 (when (string-match match str)
1883 (set-text-properties
1889 (defvar inhibit-message)
1891 (defun ivy--sort-maybe (collection)
1892 "Sort COLLECTION if needed."
1893 (let ((sort (ivy-state-sort ivy-last))
1897 (let ((sort-fn (cond ((functionp sort)
1899 ((setq entry (assoc (ivy-state-collection ivy-last)
1900 ivy-sort-functions-alist))
1903 (cdr (assoc t ivy-sort-functions-alist))))))
1904 (if (functionp sort-fn)
1905 (cl-sort (copy-sequence collection) sort-fn)
1908 (defun ivy--exhibit ()
1909 "Insert Ivy completions display.
1910 Should be run via minibuffer `post-command-hook'."
1911 (when (memq 'ivy--exhibit post-command-hook)
1912 (let ((inhibit-field-text-motion nil))
1913 (constrain-to-field nil (point-max)))
1914 (setq ivy-text (ivy--input))
1915 (if (ivy-state-dynamic-collection ivy-last)
1916 ;; while-no-input would cause annoying
1917 ;; "Waiting for process to die...done" message interruptions
1918 (let ((inhibit-message t))
1919 (unless (equal ivy--old-text ivy-text)
1921 (setq ivy--all-candidates
1923 (funcall (ivy-state-collection ivy-last) ivy-text)))
1924 (setq ivy--old-text ivy-text)))
1925 (when ivy--all-candidates
1926 (ivy--insert-minibuffer
1927 (ivy--format ivy--all-candidates))))
1928 (cond (ivy--directory
1929 (if (string-match "/\\'" ivy-text)
1930 (if (member ivy-text ivy--all-candidates)
1931 (ivy--cd (expand-file-name ivy-text ivy--directory))
1932 (when (string-match "//\\'" ivy-text)
1933 (if (and default-directory
1934 (string-match "\\`[[:alpha:]]:/" default-directory))
1935 (ivy--cd (match-string 0 default-directory))
1937 (when (string-match "[[:alpha:]]:/$" ivy-text)
1938 (let ((drive-root (match-string 0 ivy-text)))
1939 (when (file-exists-p drive-root)
1940 (ivy--cd drive-root)))))
1941 (if (string-match "\\`~\\'" ivy-text)
1942 (ivy--cd (expand-file-name "~/")))))
1943 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1944 (when (or (and (string-match "\\` " ivy-text)
1945 (not (string-match "\\` " ivy--old-text)))
1946 (and (string-match "\\` " ivy--old-text)
1947 (not (string-match "\\` " ivy-text))))
1948 (setq ivy--all-candidates
1949 (if (and (> (length ivy-text) 0)
1950 (eq (aref ivy-text 0)
1952 (ivy--buffer-list " ")
1953 (ivy--buffer-list "" ivy-use-virtual-buffers)))
1954 (setq ivy--old-re nil))))
1955 (ivy--insert-minibuffer
1956 (with-current-buffer (ivy-state-buffer ivy-last)
1958 (ivy--filter ivy-text ivy--all-candidates))))
1959 (setq ivy--old-text ivy-text))))
1961 (defun ivy--insert-minibuffer (text)
1962 "Insert TEXT into minibuffer with appropriate cleanup."
1963 (let ((resize-mini-windows nil)
1964 (update-fn (ivy-state-update-fn ivy-last))
1968 (funcall update-fn))
1969 (ivy--insert-prompt)
1970 ;; Do nothing if while-no-input was aborted.
1971 (when (stringp text)
1972 (let ((buffer-undo-list t))
1976 (when (display-graphic-p)
1977 (ivy--resize-minibuffer-to-fit))))
1979 (defun ivy--resize-minibuffer-to-fit ()
1980 "Resize the minibuffer window size to fit the text in the minibuffer."
1981 (unless (frame-root-window-p (minibuffer-window))
1982 (with-selected-window (minibuffer-window)
1983 (if (fboundp 'window-text-pixel-size)
1984 (let ((text-height (cdr (window-text-pixel-size)))
1985 (body-height (window-body-height nil t)))
1986 (when (> text-height body-height)
1987 ;; Note: the size increment needs to be at least frame-char-height,
1988 ;; otherwise resizing won't do anything.
1989 (let ((delta (max (- text-height body-height) (frame-char-height))))
1990 (window-resize nil delta nil t t))))
1991 (let ((text-height (count-screen-lines))
1992 (body-height (window-body-height)))
1993 (when (> text-height body-height)
1994 (window-resize nil (- text-height body-height) nil t)))))))
1996 (declare-function colir-blend-face-background "ext:colir")
1998 (defun ivy--add-face (str face)
1999 "Propertize STR with FACE.
2000 `font-lock-append-text-property' is used, since it's better than
2001 `propertize' or `add-face-text-property' in this case."
2005 (colir-blend-face-background 0 (length str) face str)
2006 (let ((foreground (face-foreground face)))
2008 (add-face-text-property
2010 `(:foreground ,foreground)
2015 (font-lock-append-text-property 0 (length str) 'face face str))))
2018 (declare-function flx-make-string-cache "ext:flx")
2019 (declare-function flx-score "ext:flx")
2021 (defvar ivy--flx-cache nil)
2023 (eval-after-load 'flx
2024 '(setq ivy--flx-cache (flx-make-string-cache)))
2026 (defun ivy-toggle-case-fold ()
2027 "Toggle the case folding between nil and auto.
2028 In any completion session, the case folding starts in auto:
2030 - when the input is all lower case, `case-fold-search' is t
2033 You can toggle this to make `case-fold-search' nil regardless of input."
2035 (setq ivy-case-fold-search
2036 (if ivy-case-fold-search
2039 ;; reset cache so that the candidate list updates
2040 (setq ivy--old-re nil))
2042 (defun ivy--re-filter (re candidates)
2043 "Return all RE matching CANDIDATES.
2044 RE is a list of cons cells, with a regexp car and a boolean cdr.
2045 When the cdr is t, the car must match.
2046 Otherwise, the car must not match."
2047 (let ((re-list (if (stringp re) (list (cons re t)) re))
2049 (dolist (re re-list)
2056 (let ((re-str (car re)))
2057 (lambda (x) (string-match re-str x)))
2061 (defun ivy--filter (name candidates)
2062 "Return all items that match NAME in CANDIDATES.
2063 CANDIDATES are assumed to be static."
2064 (let ((re (funcall ivy--regex-function name)))
2065 (if (and (equal re ivy--old-re)
2067 ;; quick caching for "C-n", "C-p" etc.
2069 (let* ((re-str (if (listp re) (caar re) re))
2070 (matcher (ivy-state-matcher ivy-last))
2072 (and ivy-case-fold-search
2073 (string= name (downcase name))))
2076 (funcall matcher re candidates))
2079 (stringp ivy--old-re)
2080 (not (string-match "\\\\" ivy--old-re))
2081 (not (equal ivy--old-re ""))
2083 (if (string-match "\\\\)\\'" ivy--old-re)
2084 (substring ivy--old-re 0 -2)
2090 (lambda (x) (string-match re x))
2093 (ivy--re-filter re candidates)))))
2094 (ivy--recompute-index name re-str cands)
2096 (if (eq ivy--regex-function 'ivy--regex-ignore-order)
2101 (setq ivy--old-cands (ivy--sort name cands))))))
2103 (defun ivy--set-candidates (x)
2104 "Update `ivy--all-candidates' with X."
2106 (dolist (source ivy--extra-candidates)
2107 (if (equal source '(original-source))
2110 (setq res (append x res)))
2111 (setq ivy--old-re nil)
2113 (ivy--filter ivy-text (cadr source))
2115 (setq ivy--all-candidates res)))
2117 (defcustom ivy-sort-matches-functions-alist '((t . nil))
2118 "An alist of functions for sorting matching candidates.
2120 Unlike `ivy-sort-functions-alist', which is used to sort the
2121 whole collection only once, this alist of functions are used to
2122 sort only matching candidates after each change in input.
2124 The alist KEY is either a collection function or t to match
2125 previously unmatched collection functions.
2127 The alist VAL is a sorting function with the signature of
2128 `ivy--prefix-sort'."
2131 (const :tag "Fall-through" t)
2132 (symbol :tag "Collection"))
2135 (const :tag "Don't sort" nil)
2136 (const :tag "Put prefix matches ahead" 'ivy--prefix-sort)
2137 (function :tag "Custom sort function"))))
2139 (defun ivy--sort-files-by-date (_name candidates)
2140 "Re-soft CANDIDATES according to file modification date."
2141 (let ((default-directory ivy--directory))
2142 (cl-sort (copy-sequence candidates)
2145 (nth 5 (file-attributes f2))
2146 (nth 5 (file-attributes f1)))))))
2148 (defun ivy--sort (name candidates)
2149 "Re-sort CANDIDATES by NAME.
2150 All CANDIDATES are assumed to match NAME."
2151 (let ((key (or (ivy-state-caller ivy-last)
2152 (when (functionp (ivy-state-collection ivy-last))
2153 (ivy-state-collection ivy-last))))
2155 (cond ((and (require 'flx nil 'noerror)
2156 (eq ivy--regex-function 'ivy--regex-fuzzy))
2157 (ivy--flx-sort name candidates))
2158 ((setq fun (cdr (or (assoc key ivy-sort-matches-functions-alist)
2159 (assoc t ivy-sort-matches-functions-alist))))
2160 (funcall fun name candidates))
2164 (defun ivy--prefix-sort (name candidates)
2165 "Re-sort CANDIDATES.
2166 Prefix matches to NAME are put ahead of the list."
2167 (if (or (string-match "^\\^" name) (string= name ""))
2169 (let ((re-prefix (concat "^" (funcall ivy--regex-function name)))
2172 (dolist (s candidates)
2173 (if (string-match re-prefix s)
2175 (push s res-noprefix)))
2177 (nreverse res-prefix)
2178 (nreverse res-noprefix)))))
2180 (defun ivy--recompute-index (name re-str cands)
2181 (let* ((caller (ivy-state-caller ivy-last))
2182 (func (or (and caller (cdr (assoc caller ivy-index-functions-alist)))
2183 (cdr (assoc t ivy-index-functions-alist))
2184 #'ivy-recompute-index-zero)))
2185 (unless (eq this-command 'ivy-resume)
2188 (cl-position (if (and (> (length name) 0)
2189 (eq ?^ (aref name 0)))
2195 (concat re-str "/") cands
2197 (and (not (string= name ""))
2198 (not (and (require 'flx nil 'noerror)
2199 (eq ivy--regex-function 'ivy--regex-fuzzy)
2200 (< (length cands) 200)))
2202 (cl-position (nth ivy--index ivy--old-cands)
2204 (funcall func re-str cands))))
2205 (when (and (or (string= name "")
2207 (not (equal ivy--old-re "")))
2209 (or (ivy--preselect-index
2210 (ivy-state-preselect ivy-last)
2214 (defun ivy-recompute-index-swiper (_re-str cands)
2215 (let ((tail (nthcdr ivy--index ivy--old-cands))
2217 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2219 (while (and tail (null idx))
2220 ;; Compare with eq to handle equal duplicates in cands
2221 (setq idx (cl-position (pop tail) cands)))
2224 (1- (length cands))))
2227 ;; already in ivy-state-buffer
2228 (let ((n (line-number-at-pos))
2232 (when (eq n (read (get-text-property 0 'display c)))
2237 (defun ivy-recompute-index-swiper-async (_re-str cands)
2238 (if (null ivy--old-cands)
2239 (let ((ln (with-ivy-window
2240 (line-number-at-pos))))
2241 (or (cl-position-if (lambda (x)
2242 (>= (string-to-number x) ln))
2245 (let ((tail (nthcdr ivy--index ivy--old-cands))
2247 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2249 (while (and tail (null idx))
2250 ;; Compare with `equal', since the collection is re-created
2251 ;; each time with `split-string'
2252 (setq idx (cl-position (pop tail) cands :test #'equal)))
2256 (defun ivy-recompute-index-zero (_re-str _cands)
2259 (defcustom ivy-minibuffer-faces
2260 '(ivy-minibuffer-match-face-1
2261 ivy-minibuffer-match-face-2
2262 ivy-minibuffer-match-face-3
2263 ivy-minibuffer-match-face-4)
2264 "List of `ivy' faces for minibuffer group matches."
2265 :type '(repeat :tag "Faces"
2267 (const ivy-minibuffer-match-face-1)
2268 (const ivy-minibuffer-match-face-2)
2269 (const ivy-minibuffer-match-face-3)
2270 (const ivy-minibuffer-match-face-4)
2271 (face :tag "Other face"))))
2273 (defvar ivy-flx-limit 200
2274 "Used to conditionally turn off flx sorting.
2276 When the amount of matching candidates exceeds this limit, then
2277 no sorting is done.")
2279 (defun ivy--flx-sort (name cands)
2280 "Sort according to closeness to string NAME the string list CANDS."
2283 (< (length cands) ivy-flx-limit))
2284 (let* ((flx-name (if (string-match "^\\^" name)
2291 (let ((score (flx-score x flx-name ivy--flx-cache)))
2295 (if cands-with-score
2297 (let ((str (copy-sequence (cdr x)))
2300 (dolist (j (cdar x))
2301 (unless (eq j (1+ last-j))
2304 (ivy-add-face-text-property
2306 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2307 ivy-minibuffer-faces)
2310 (sort cands-with-score
2312 (> (caar x) (caar y)))))
2318 (defcustom ivy-format-function 'ivy-format-function-default
2319 "Function to transform the list of candidates into a string.
2320 This string is inserted into the minibuffer."
2322 (const :tag "Default" ivy-format-function-default)
2323 (const :tag "Arrow prefix" ivy-format-function-arrow)
2324 (const :tag "Full line" ivy-format-function-line)))
2326 (defun ivy--truncate-string (str width)
2327 "Truncate STR to WIDTH."
2328 (if (> (string-width str) width)
2329 (concat (substring str 0 (min (- width 3)
2330 (- (length str) 3))) "...")
2333 (defun ivy--format-function-generic (selected-fn other-fn strs separator)
2334 "Transform CAND-PAIRS into a string for minibuffer.
2335 SELECTED-FN and OTHER-FN each take one string argument.
2336 SEPARATOR is used to join the candidates."
2340 (let ((curr (eq (cl-incf i) ivy--index)))
2342 (funcall selected-fn str)
2343 (funcall other-fn str))))
2347 (defun ivy-format-function-default (cands)
2348 "Transform CAND-PAIRS into a string for minibuffer."
2349 (ivy--format-function-generic
2351 (ivy--add-face str 'ivy-current-match))
2356 (defun ivy-format-function-arrow (cands)
2357 "Transform CAND-PAIRS into a string for minibuffer."
2358 (ivy--format-function-generic
2360 (concat "> " (ivy--add-face str 'ivy-current-match)))
2366 (defun ivy-format-function-line (cands)
2367 "Transform CAND-PAIRS into a string for minibuffer."
2368 (ivy--format-function-generic
2370 (ivy--add-face (concat str "\n") 'ivy-current-match))
2376 (defun ivy-add-face-text-property (start end face str)
2377 (if (fboundp 'add-face-text-property)
2378 (add-face-text-property
2379 start end face nil str)
2380 (font-lock-append-text-property
2381 start end 'face face str)))
2383 (defun ivy--format-minibuffer-line (str)
2385 (str (copy-sequence str)))
2386 (cond ((eq ivy--regex-function 'ivy--regex-ignore-order)
2387 (when (consp ivy--old-re)
2389 (dolist (re ivy--old-re)
2390 (when (string-match (car re) str)
2391 (ivy-add-face-text-property
2392 (match-beginning 0) (match-end 0)
2393 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2394 ivy-minibuffer-faces)
2397 ((and (eq ivy-display-style 'fancy)
2398 (not (eq ivy--regex-function 'ivy--regex-fuzzy)))
2400 (setq ivy--old-re (funcall ivy--regex-function ivy-text)))
2401 (while (and (string-match ivy--old-re str start)
2402 (> (- (match-end 0) (match-beginning 0)) 0))
2403 (setq start (match-end 0))
2405 (while (<= i ivy--subexps)
2407 (cond ((zerop ivy--subexps)
2408 (cadr ivy-minibuffer-faces))
2410 (car ivy-minibuffer-faces))
2412 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2413 ivy-minibuffer-faces)))))
2414 (ivy-add-face-text-property
2415 (match-beginning i) (match-end i)
2420 (ivy-set-display-transformer
2421 'read-file-name-internal 'ivy-read-file-transformer)
2423 (defun ivy-read-file-transformer (str)
2424 (if (string-match-p "/\\'" str)
2425 (propertize str 'face 'ivy-subdir)
2428 (defun ivy--format (cands)
2429 "Return a string for CANDS suitable for display in the minibuffer.
2430 CANDS is a list of strings."
2431 (setq ivy--length (length cands))
2432 (when (>= ivy--index ivy--length)
2433 (setq ivy--index (max (1- ivy--length) 0)))
2435 (setq ivy--current "")
2436 (let* ((half-height (/ ivy-height 2))
2437 (start (max 0 (- ivy--index half-height)))
2438 (end (min (+ start (1- ivy-height)) ivy--length))
2439 (start (max 0 (min start (- end (1- ivy-height)))))
2440 (cands (cl-subseq cands start end))
2441 (index (- ivy--index start))
2443 (setq ivy--current (copy-sequence (nth index cands)))
2444 (when (setq transformer-fn (ivy-state-display-transformer-fn ivy-last))
2446 (setq cands (mapcar transformer-fn cands))))
2447 (let* ((ivy--index index)
2449 #'ivy--format-minibuffer-line
2451 (res (concat "\n" (funcall ivy-format-function cands))))
2452 (put-text-property 0 (length res) 'read-only nil res)
2455 (defvar ivy--virtual-buffers nil
2456 "Store the virtual buffers alist.")
2458 (defvar recentf-list)
2460 (defcustom ivy-virtual-abbreviate 'name
2461 "The mode of abbreviation for virtual buffer names."
2463 (const :tag "Only name" name)
2464 (const :tag "Full path" full)
2465 ;; eventually, uniquify
2468 (defun ivy--virtual-buffers ()
2469 "Adapted from `ido-add-virtual-buffers-to-list'."
2470 (unless recentf-mode
2472 (let ((bookmarks (and (boundp 'bookmark-alist)
2474 virtual-buffers name)
2475 (dolist (head (append
2477 (delete " - no file -"
2478 (delq nil (mapcar (lambda (bookmark)
2479 (cdr (assoc 'filename bookmark)))
2482 (if (eq ivy-virtual-abbreviate 'name)
2483 (file-name-nondirectory head)
2484 (expand-file-name head)))
2485 (when (equal name "")
2486 (setq name (file-name-nondirectory (directory-file-name head))))
2487 (when (equal name "")
2489 (and (not (equal name ""))
2490 (null (get-file-buffer head))
2491 (not (assoc name virtual-buffers))
2492 (push (cons name head) virtual-buffers)))
2493 (when virtual-buffers
2494 (dolist (comp virtual-buffers)
2495 (put-text-property 0 (length (car comp))
2498 (setq ivy--virtual-buffers (nreverse virtual-buffers))
2499 (mapcar #'car ivy--virtual-buffers))))
2501 (defcustom ivy-ignore-buffers '("\\` ")
2502 "List of regexps or functions matching buffer names to ignore."
2503 :type '(repeat (choice regexp function)))
2505 (defun ivy--buffer-list (str &optional virtual)
2506 "Return the buffers that match STR.
2507 When VIRTUAL is non-nil, add virtual buffers."
2512 (if (with-current-buffer x
2514 (abbreviate-file-name default-directory)))
2515 (propertize x 'face 'ivy-remote)
2517 (all-completions str 'internal-complete-buffer))
2519 (ivy--virtual-buffers)))))
2521 (defun ivy--switch-buffer-action (buffer)
2523 BUFFER may be a string or nil."
2525 (if (zerop (length buffer))
2527 ivy-text nil 'force-same-window)
2528 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2530 (not (get-buffer buffer)))
2531 (find-file (cdr virtual))
2533 buffer nil 'force-same-window))))))
2535 (defun ivy--switch-buffer-other-window-action (buffer)
2536 "Switch to BUFFER in other window.
2537 BUFFER may be a string or nil."
2538 (if (zerop (length buffer))
2539 (switch-to-buffer-other-window ivy-text)
2540 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2542 (not (get-buffer buffer)))
2543 (find-file-other-window (cdr virtual))
2544 (switch-to-buffer-other-window buffer)))))
2546 (defun ivy--rename-buffer-action (buffer)
2548 (let ((new-name (read-string "Rename buffer (to new name): ")))
2549 (with-current-buffer buffer
2550 (rename-buffer new-name))))
2552 (defvar ivy-switch-buffer-map (make-sparse-keymap))
2559 (ivy--reset-state ivy-last))
2562 ivy--switch-buffer-other-window-action
2565 ivy--rename-buffer-action
2568 (defun ivy--switch-buffer-matcher (regexp candidates)
2569 "Return REGEXP-matching CANDIDATES.
2570 Skip buffers that match `ivy-ignore-buffers'."
2571 (let ((res (ivy--re-filter regexp candidates)))
2572 (if (or (null ivy-use-ignore)
2573 (null ivy-ignore-buffers))
2579 (if (functionp f-or-r)
2580 (funcall f-or-r buf)
2581 (string-match-p f-or-r buf)))
2582 ivy-ignore-buffers))
2586 (ivy-set-display-transformer
2587 'ivy-switch-buffer 'ivy-switch-buffer-transformer)
2588 (ivy-set-display-transformer
2589 'internal-complete-buffer 'ivy-switch-buffer-transformer)
2591 (defun ivy-switch-buffer-transformer (str)
2592 (let ((b (get-buffer str)))
2594 (buffer-file-name b)
2595 (buffer-modified-p b))
2596 (propertize str 'face 'ivy-modified-buffer)
2599 (defun ivy-switch-buffer-occur ()
2600 "Occur function for `ivy-switch-buffer' that uses `ibuffer'."
2602 (concat "\\(" (mapconcat #'regexp-quote ivy--old-cands "\\|") "\\)"))
2603 (new-qualifier `((name . ,cand-regexp))))
2604 (ibuffer nil (buffer-name) new-qualifier)))
2607 (defun ivy-switch-buffer ()
2608 "Switch to another buffer."
2610 (let ((this-command 'ivy-switch-buffer))
2611 (ivy-read "Switch to buffer: " 'internal-complete-buffer
2612 :matcher #'ivy--switch-buffer-matcher
2613 :preselect (buffer-name (other-buffer (current-buffer)))
2614 :action #'ivy--switch-buffer-action
2615 :keymap ivy-switch-buffer-map
2616 :caller 'ivy-switch-buffer)))
2619 (defun ivy-switch-buffer-other-window ()
2620 "Switch to another buffer in another window."
2622 (ivy-read "Switch to buffer in other window: " 'internal-complete-buffer
2623 :preselect (buffer-name (other-buffer (current-buffer)))
2624 :action #'ivy--switch-buffer-other-window-action
2625 :keymap ivy-switch-buffer-map
2626 :caller 'ivy-switch-buffer-other-window))
2629 (defun ivy-recentf ()
2630 "Find a file on `recentf-list'."
2632 (ivy-read "Recentf: " recentf-list
2637 :caller 'ivy-recentf))
2639 (defun ivy-yank-word ()
2640 "Pull next word from buffer into search string."
2645 (le (line-end-position)))
2649 (setq amend (buffer-substring-no-properties pt (point))))))
2651 (insert (replace-regexp-in-string " +" " " amend)))))
2653 (defun ivy-kill-ring-save ()
2654 "Store the current candidates into the kill ring.
2655 If the region is active, forward to `kill-ring-save' instead."
2657 (if (region-active-p)
2658 (call-interactively 'kill-ring-save)
2665 (defun ivy-insert-current ()
2666 "Make the current candidate into current input.
2667 Don't finish completion."
2669 (delete-minibuffer-contents)
2670 (if (and ivy--directory
2671 (string-match "/$" ivy--current))
2672 (insert (substring ivy--current 0 -1))
2673 (insert ivy--current)))
2675 (defun ivy-toggle-fuzzy ()
2676 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
2678 (setq ivy--old-re nil)
2679 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
2680 (setq ivy--regex-function 'ivy--regex-plus)
2681 (setq ivy--regex-function 'ivy--regex-fuzzy)))
2683 (defun ivy-reverse-i-search ()
2684 "Enter a recursive `ivy-read' session using the current history.
2685 The selected history element will be inserted into the minibuffer."
2687 (let ((enable-recursive-minibuffers t)
2688 (history (symbol-value (ivy-state-history ivy-last)))
2690 (ivy-recursive-restore nil))
2691 (ivy-read "Reverse-i-search: "
2695 (setq ivy-last old-last))
2696 (delete-minibuffer-contents)
2697 (insert (substring-no-properties x))
2700 (defun ivy-restrict-to-matches ()
2701 "Restrict candidates to current matches and erase input."
2703 (delete-minibuffer-contents)
2704 (setq ivy--all-candidates
2705 (ivy--filter ivy-text ivy--all-candidates)))
2708 (defvar-local ivy-occur-last nil
2709 "Buffer-local value of `ivy-last'.
2710 Can't re-use `ivy-last' because using e.g. `swiper' in the same
2711 buffer would modify `ivy-last'.")
2713 (defvar ivy-occur-mode-map
2714 (let ((map (make-sparse-keymap)))
2715 (define-key map [mouse-1] 'ivy-occur-click)
2716 (define-key map (kbd "RET") 'ivy-occur-press)
2717 (define-key map (kbd "j") 'ivy-occur-next-line)
2718 (define-key map (kbd "k") 'ivy-occur-previous-line)
2719 (define-key map (kbd "h") 'backward-char)
2720 (define-key map (kbd "l") 'forward-char)
2721 (define-key map (kbd "f") 'ivy-occur-press)
2722 (define-key map (kbd "g") 'ivy-occur-revert-buffer)
2723 (define-key map (kbd "a") 'ivy-occur-read-action)
2724 (define-key map (kbd "o") 'ivy-occur-dispatch)
2725 (define-key map (kbd "c") 'ivy-occur-toggle-calling)
2726 (define-key map (kbd "q") 'quit-window)
2728 "Keymap for Ivy Occur mode.")
2730 (defun ivy-occur-toggle-calling ()
2731 "Toggle `ivy-calling'."
2733 (if (setq ivy-calling (not ivy-calling))
2735 (setq mode-name "Ivy-Occur [calling]")
2737 (setq mode-name "Ivy-Occur"))
2738 (force-mode-line-update))
2740 (defun ivy-occur-next-line (&optional arg)
2741 "Move the cursor down ARG lines.
2742 When `ivy-calling' isn't nil, call `ivy-occur-press'."
2748 (defun ivy-occur-previous-line (&optional arg)
2749 "Move the cursor up ARG lines.
2750 When `ivy-calling' isn't nil, call `ivy-occur-press'."
2752 (forward-line (- arg))
2756 (define-derived-mode ivy-occur-mode fundamental-mode "Ivy-Occur"
2757 "Major mode for output from \\[ivy-occur].
2759 \\{ivy-occur-mode-map}")
2761 (defvar ivy-occur-grep-mode-map
2762 (let ((map (copy-keymap ivy-occur-mode-map)))
2763 (define-key map (kbd "C-x C-q") 'ivy-wgrep-change-to-wgrep-mode)
2765 "Keymap for Ivy Occur Grep mode.")
2767 (define-derived-mode ivy-occur-grep-mode grep-mode "Ivy-Occur"
2768 "Major mode for output from \\[ivy-occur].
2770 \\{ivy-occur-grep-mode-map}")
2772 (defvar ivy--occurs-list nil
2773 "A list of custom occur generators per command.")
2775 (defun ivy-set-occur (cmd occur)
2776 "Assign CMD a custom OCCUR function."
2777 (setq ivy--occurs-list
2778 (plist-put ivy--occurs-list cmd occur)))
2780 (ivy-set-occur 'ivy-switch-buffer 'ivy-switch-buffer-occur)
2781 (ivy-set-occur 'ivy-switch-buffer-other-window 'ivy-switch-buffer-occur)
2783 (defun ivy--occur-insert-lines (cands)
2785 (add-text-properties
2789 help-echo "mouse-1: call ivy-action")
2794 "Stop completion and put the current matches into a new buffer.
2796 The new buffer remembers current action(s).
2798 While in the *ivy-occur* buffer, selecting a candidate with RET or
2799 a mouse click will call the appropriate action for that candidate.
2801 There is no limit on the number of *ivy-occur* buffers."
2803 (if (not (window-minibuffer-p))
2804 (user-error "No completion session is active")
2805 (let* ((caller (ivy-state-caller ivy-last))
2806 (occur-fn (plist-get ivy--occurs-list caller))
2808 (generate-new-buffer
2809 (format "*ivy-occur%s \"%s\"*"
2811 (concat " " (prin1-to-string caller))
2814 (with-current-buffer buffer
2815 (let ((inhibit-read-only t))
2820 (insert (format "%d candidates:\n" (length ivy--old-cands)))
2821 (ivy--occur-insert-lines
2823 (lambda (cand) (concat " " cand))
2825 (setf (ivy-state-text ivy-last) ivy-text)
2826 (setq ivy-occur-last ivy-last)
2827 (setq-local ivy--directory ivy--directory))
2828 (ivy-exit-with-action
2829 `(lambda (_) (pop-to-buffer ,buffer))))))
2831 (defun ivy-occur-revert-buffer ()
2832 "Refresh the buffer making it up-to date with the collection.
2834 Currently only works for `swiper'. In that specific case, the
2835 *ivy-occur* buffer becomes nearly useless as the orignal buffer
2836 is updated, since the line numbers no longer match.
2838 Calling this function is as if you called `ivy-occur' on the
2839 updated original buffer."
2841 (let ((caller (ivy-state-caller ivy-occur-last))
2842 (ivy-last ivy-occur-last))
2843 (when (eq caller 'swiper)
2844 (let ((buffer (ivy-state-buffer ivy-occur-last)))
2845 (unless (buffer-live-p buffer)
2846 (error "buffer was killed"))
2847 (let ((inhibit-read-only t))
2849 (funcall (plist-get ivy--occurs-list caller) t))))))
2851 (declare-function wgrep-change-to-wgrep-mode "ext:wgrep")
2853 (defun ivy-wgrep-change-to-wgrep-mode ()
2854 "Forward to `wgrep-change-to-wgrep-mode'."
2856 (if (require 'wgrep nil 'noerror)
2857 (wgrep-change-to-wgrep-mode)
2858 (error "Package wgrep isn't installed")))
2860 (defun ivy-occur-read-action ()
2861 "Select one of the available actions as the current one."
2863 (let ((ivy-last ivy-occur-last))
2866 (defun ivy-occur-dispatch ()
2867 "Call one of the available actions on the current item."
2869 (let* ((state-action (ivy-state-action ivy-occur-last))
2870 (actions (if (symbolp state-action)
2872 (copy-sequence state-action))))
2875 (ivy-occur-read-action)
2877 (setf (ivy-state-action ivy-occur-last) actions))))
2879 (defun ivy-occur-click (event)
2880 "Execute action for the current candidate.
2881 EVENT gives the mouse position."
2883 (let ((window (posn-window (event-end event)))
2884 (pos (posn-point (event-end event))))
2885 (with-current-buffer (window-buffer window)
2887 (ivy-occur-press))))
2889 (declare-function swiper--cleanup "swiper")
2890 (declare-function swiper--add-overlays "swiper")
2892 (defun ivy-occur-press ()
2893 "Execute action for the current candidate."
2895 (when (save-excursion
2897 (looking-at "\\(?:./\\| \\)\\(.*\\)$"))
2898 (when (memq (ivy-state-caller ivy-occur-last)
2899 '(swiper counsel-git-grep counsel-grep counsel-ag
2900 counsel-describe-function counsel-describe-variable))
2901 (let ((window (ivy-state-window ivy-occur-last)))
2902 (when (or (null (window-live-p window))
2903 (equal window (selected-window)))
2904 (save-selected-window
2905 (setf (ivy-state-window ivy-occur-last)
2906 (display-buffer (ivy-state-buffer ivy-occur-last)
2907 'display-buffer-pop-up-window))))))
2908 (let* ((ivy-last ivy-occur-last)
2909 (ivy-text (ivy-state-text ivy-last))
2910 (str (buffer-substring
2913 (coll (ivy-state-collection ivy-last))
2914 (action (ivy--get-action ivy-last))
2918 (if (and (consp coll)
2920 (cdr (assoc str coll))
2922 (if (memq (ivy-state-caller ivy-last)
2923 '(swiper counsel-git-grep))
2924 (with-current-buffer (window-buffer (selected-window))
2926 (swiper--add-overlays
2927 (ivy--regex ivy-text)
2928 (line-beginning-position)
2931 (run-at-time 0.5 nil 'swiper--cleanup)))))))
2933 (defvar ivy-help-file (let ((default-directory
2935 (file-name-directory load-file-name)
2936 default-directory)))
2937 (if (file-exists-p "ivy-help.org")
2938 (expand-file-name "ivy-help.org")
2939 (if (file-exists-p "doc/ivy-help.org")
2940 (expand-file-name "doc/ivy-help.org"))))
2941 "The file for `ivy-help'.")
2946 (let ((buf (get-buffer "*Ivy Help*")))
2948 (setq buf (get-buffer-create "*Ivy Help*"))
2949 (with-current-buffer buf
2950 (insert-file-contents ivy-help-file)
2953 (goto-char (point-min))))
2954 (if (eq this-command 'ivy-help)
2955 (switch-to-buffer buf)
2957 (pop-to-buffer buf)))
2959 (goto-char (point-min))))
2963 ;;; ivy.el ends here