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 (file-name-as-directory
609 (expand-file-name file-name ivy--directory))))
610 (when (file-directory-p full-name)
613 (defcustom ivy-tab-space nil
614 "When non-nil, `ivy-partial-or-done' should insert a space."
617 (defun ivy-partial-or-done ()
618 "Complete the minibuffer text as much as possible.
619 If the text hasn't changed as a result, forward to `ivy-alt-done'."
621 (if (and (eq (ivy-state-collection ivy-last) #'read-file-name-internal)
622 (or (and (equal ivy--directory "/")
623 (string-match "\\`[^/]+:.*\\'" ivy-text))
624 (string-match "\\`/" ivy-text)))
625 (let ((default-directory ivy--directory)
627 (minibuffer-complete)
628 (setq ivy-text (ivy--input))
629 (when (setq dir (ivy-expand-file-if-directory ivy-text))
632 (when (or (eq this-command last-command)
636 (defun ivy-partial ()
637 "Complete the minibuffer text as much as possible."
639 (let* ((parts (or (split-string ivy-text " " t) (list "")))
640 (postfix (car (last parts)))
641 (completion-ignore-case t)
642 (startp (string-match "^\\^" postfix))
643 (new (try-completion (if startp
644 (substring postfix 1)
646 (mapcar (lambda (str)
647 (let ((i (string-match postfix str)))
651 (cond ((eq new t) nil)
652 ((string= new ivy-text) nil)
654 (delete-region (minibuffer-prompt-end) (point-max))
659 (insert (mapconcat #'identity parts " ")
660 (if ivy-tab-space " " ""))
663 (defun ivy-immediate-done ()
664 "Exit the minibuffer with the current input."
666 (delete-minibuffer-contents)
667 (insert (setq ivy--current
669 (expand-file-name ivy-text ivy--directory)
671 (setq ivy-exit 'done)
676 "Resume the last completion session."
678 (if (null (ivy-state-action ivy-last))
679 (user-error "The last session isn't compatible with `ivy-resume'")
680 (when (eq (ivy-state-caller ivy-last) 'swiper)
681 (switch-to-buffer (ivy-state-buffer ivy-last)))
682 (with-current-buffer (ivy-state-buffer ivy-last)
684 (ivy-state-prompt ivy-last)
685 (ivy-state-collection ivy-last)
686 :predicate (ivy-state-predicate ivy-last)
687 :require-match (ivy-state-require-match ivy-last)
688 :initial-input ivy-text
689 :history (ivy-state-history ivy-last)
690 :preselect (unless (eq (ivy-state-collection ivy-last)
691 'read-file-name-internal)
693 :keymap (ivy-state-keymap ivy-last)
694 :update-fn (ivy-state-update-fn ivy-last)
695 :sort (ivy-state-sort ivy-last)
696 :action (ivy-state-action ivy-last)
697 :unwind (ivy-state-unwind ivy-last)
698 :re-builder (ivy-state-re-builder ivy-last)
699 :matcher (ivy-state-matcher ivy-last)
700 :dynamic-collection (ivy-state-dynamic-collection ivy-last)
701 :caller (ivy-state-caller ivy-last)))))
703 (defvar-local ivy-calling nil
704 "When non-nil, call the current action when `ivy--index' changes.")
706 (defun ivy-set-index (index)
707 "Set `ivy--index' to INDEX."
708 (setq ivy--index index)
713 (defun ivy-beginning-of-buffer ()
714 "Select the first completion candidate."
718 (defun ivy-end-of-buffer ()
719 "Select the last completion candidate."
721 (ivy-set-index (1- ivy--length)))
723 (defun ivy-scroll-up-command ()
724 "Scroll the candidates upward by the minibuffer height."
726 (ivy-set-index (min (1- (+ ivy--index ivy-height))
729 (defun ivy-scroll-down-command ()
730 "Scroll the candidates downward by the minibuffer height."
732 (ivy-set-index (max (1+ (- ivy--index ivy-height))
735 (defun ivy-minibuffer-grow ()
736 "Grow the minibuffer window by 1 line."
738 (setq-local max-mini-window-height
739 (cl-incf ivy-height)))
741 (defun ivy-minibuffer-shrink ()
742 "Shrink the minibuffer window by 1 line."
744 (unless (<= ivy-height 2)
745 (setq-local max-mini-window-height
746 (cl-decf ivy-height))
747 (window-resize (selected-window) -1)))
749 (defun ivy-next-line (&optional arg)
750 "Move cursor vertically down ARG candidates."
752 (setq arg (or arg 1))
753 (let ((index (+ ivy--index arg)))
754 (if (> index (1- ivy--length))
756 (ivy-beginning-of-buffer)
757 (ivy-set-index (1- ivy--length)))
758 (ivy-set-index index))))
760 (defun ivy-next-line-or-history (&optional arg)
761 "Move cursor vertically down ARG candidates.
762 If the input is empty, select the previous history element instead."
764 (if (string= ivy-text "")
765 (ivy-previous-history-element 1)
766 (ivy-next-line arg)))
768 (defun ivy-previous-line (&optional arg)
769 "Move cursor vertically up ARG candidates."
771 (setq arg (or arg 1))
772 (let ((index (- ivy--index arg)))
777 (ivy-set-index index))))
779 (defun ivy-previous-line-or-history (arg)
780 "Move cursor vertically up ARG candidates.
781 If the input is empty, select the previous history element instead."
783 (when (string= ivy-text "")
784 (ivy-previous-history-element 1))
785 (ivy-previous-line arg))
787 (defun ivy-toggle-calling ()
788 "Flip `ivy-calling'."
790 (when (setq ivy-calling (not ivy-calling))
793 (defun ivy-toggle-ignore ()
794 "Toggle user-configured candidate filtering."
796 (setq ivy-use-ignore (null ivy-use-ignore))
798 (setq ivy--old-cands nil))
800 (defun ivy--get-action (state)
801 "Get the action function from STATE."
802 (let ((action (ivy-state-action state)))
804 (if (functionp action)
806 (cadr (nth (car action) action))))))
808 (defun ivy--get-window (state)
809 "Get the window from STATE."
810 (if (ivy-state-p state)
811 (let ((window (ivy-state-window state)))
812 (if (window-live-p window)
814 (if (= (length (window-list)) 1)
819 (defun ivy--actionp (x)
820 "Return non-nil when X is a list of actions."
821 (and x (listp x) (not (eq (car x) 'closure))))
823 (defun ivy-next-action ()
824 "When the current action is a list, scroll it forwards."
826 (let ((action (ivy-state-action ivy-last)))
827 (when (ivy--actionp action)
828 (unless (>= (car action) (1- (length action)))
829 (cl-incf (car action))))))
831 (defun ivy-prev-action ()
832 "When the current action is a list, scroll it backwards."
834 (let ((action (ivy-state-action ivy-last)))
835 (when (ivy--actionp action)
836 (unless (<= (car action) 1)
837 (cl-decf (car action))))))
839 (defun ivy-action-name ()
840 "Return the name associated with the current action."
841 (let ((action (ivy-state-action ivy-last)))
842 (if (ivy--actionp action)
846 (nth 2 (nth (car action) action)))
849 (defvar ivy-inhibit-action nil
850 "When non-nil, `ivy-call' does nothing.
854 (let* ((ivy-inhibit-action t)
855 (str (counsel-locate \"lispy.el\")))
856 ;; do whatever with str - the corresponding file will not be opened
860 "Call the current action without exiting completion."
862 (unless ivy-inhibit-action
863 (let ((action (ivy--get-action ivy-last)))
865 (let* ((collection (ivy-state-collection ivy-last))
866 (x (if (and (consp collection)
867 (consp (car collection)))
868 (cdr (assoc ivy--current collection))
869 (if (equal ivy--current "")
872 (prog1 (funcall action x)
873 (unless (or (eq ivy-exit 'done)
874 (equal (selected-window)
875 (active-minibuffer-window))
876 (null (active-minibuffer-window)))
877 (select-window (active-minibuffer-window)))))))))
879 (defun ivy-next-line-and-call (&optional arg)
880 "Move cursor vertically down ARG candidates.
881 Call the permanent action if possible."
887 (defun ivy-previous-line-and-call (&optional arg)
888 "Move cursor vertically down ARG candidates.
889 Call the permanent action if possible."
891 (ivy-previous-line arg)
895 (defun ivy-previous-history-element (arg)
896 "Forward to `previous-history-element' with ARG."
898 (previous-history-element arg)
901 (ivy--maybe-scroll-history))
903 (defun ivy-next-history-element (arg)
904 "Forward to `next-history-element' with ARG."
906 (if (and (= minibuffer-history-position 0)
909 (insert ivy--default)
910 (when (and (with-ivy-window (derived-mode-p 'prog-mode))
911 (not (file-exists-p ivy--default))
912 (not (ivy-state-dynamic-collection ivy-last))
913 (> (point) (minibuffer-prompt-end)))
916 (goto-char (minibuffer-prompt-end))
918 (forward-char (+ 2 (length ivy--default)))))
919 (next-history-element arg))
922 (ivy--maybe-scroll-history))
924 (defvar ivy-ffap-url-functions nil
925 "List of functions that check if the point is on a URL.")
927 (defun ivy--cd-maybe ()
928 "Check if the current input points to a different directory.
929 If so, move to that directory, while keeping only the file name."
931 (let ((input (ivy--input))
933 (if (setq url (or (ffap-url-p input)
938 ivy-ffap-url-functions
939 :initial-value nil))))
940 (ivy-exit-with-action
942 (funcall ffap-url-fetcher url)))
943 (setq input (expand-file-name input))
944 (let ((file (file-name-nondirectory input))
945 (dir (expand-file-name (file-name-directory input))))
946 (if (string= dir ivy--directory)
948 (delete-minibuffer-contents)
953 (defun ivy--maybe-scroll-history ()
954 "If the selected history element has an index, scroll there."
955 (let ((idx (ignore-errors
957 (minibuffer-prompt-end)
961 (setq ivy--index idx))))
964 "When completing file names, move to directory DIR."
965 (if (null ivy--directory)
967 (setq ivy--old-cands nil)
968 (setq ivy--old-re nil)
970 (setq ivy--all-candidates
971 (ivy--sorted-files (setq ivy--directory dir)))
973 (delete-minibuffer-contents)))
975 (defun ivy-backward-delete-char ()
976 "Forward to `backward-delete-char'.
977 On error (read-only), call `ivy-on-del-error-function'."
979 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
981 (ivy--cd (file-name-directory
987 (backward-delete-char 1)
989 (when ivy-on-del-error-function
990 (funcall ivy-on-del-error-function))))))
992 (defun ivy-delete-char (arg)
993 "Forward to `delete-char' ARG."
995 (unless (= (point) (line-end-position))
998 (defun ivy-forward-char (arg)
999 "Forward to `forward-char' ARG."
1001 (unless (= (point) (line-end-position))
1002 (forward-char arg)))
1004 (defun ivy-kill-word (arg)
1005 "Forward to `kill-word' ARG."
1007 (unless (= (point) (line-end-position))
1010 (defun ivy-kill-line ()
1011 "Forward to `kill-line'."
1014 (kill-region (minibuffer-prompt-end) (point))
1017 (defun ivy-backward-kill-word ()
1018 "Forward to `backward-kill-word'."
1020 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
1022 (ivy--cd (file-name-directory
1023 (directory-file-name
1030 (delete-region (point) pt)))))
1032 (defvar ivy--regexp-quote 'regexp-quote
1033 "Store the regexp quoting state.")
1035 (defun ivy-toggle-regexp-quote ()
1036 "Toggle the regexp quoting."
1038 (setq ivy--old-re nil)
1039 (cl-rotatef ivy--regex-function ivy--regexp-quote))
1041 (defvar avy-all-windows)
1044 (defvar avy-keys-alist)
1046 (defvar avy-styles-alist)
1047 (declare-function avy--process "ext:avy")
1048 (declare-function avy--style-fn "ext:avy")
1050 (eval-after-load 'avy
1051 '(add-to-list 'avy-styles-alist '(ivy-avy . pre)))
1054 "Jump to one of the current ivy candidates."
1056 (unless (require 'avy nil 'noerror)
1057 (error "Package avy isn't installed"))
1058 (let* ((avy-all-windows nil)
1059 (avy-keys (or (cdr (assq 'ivy-avy avy-keys-alist))
1061 (avy-style (or (cdr (assq 'ivy-avy
1071 (goto-char (point-min))
1073 (while (< (point) (point-max))
1079 (setq avy-action #'identity)
1081 (nreverse candidates)
1082 (avy--style-fn avy-style)))))
1083 (ivy-set-index (- (line-number-at-pos candidate) 2))
1087 (defun ivy-sort-file-function-default (x y)
1088 "Compare two files X and Y.
1089 Prioritize directories."
1090 (if (get-text-property 0 'dirp x)
1091 (if (get-text-property 0 'dirp y)
1094 (if (get-text-property 0 'dirp y)
1098 (defcustom ivy-sort-functions-alist
1099 '((read-file-name-internal . ivy-sort-file-function-default)
1100 (internal-complete-buffer . nil)
1101 (counsel-git-grep-function . nil)
1102 (Man-goto-section . nil)
1105 "An alist of sorting functions for each collection function.
1106 Interactive functions that call completion fit in here as well.
1108 Nil means no sorting, which is useful to turn off the sorting for
1109 functions that have candidates in the natural buffer order, like
1110 `org-refile' or `Man-goto-section'.
1112 The entry associated with t is used for all fall-through cases.
1114 See also `ivy-sort-max-size'."
1118 (const :tag "Fall-through" t)
1119 (symbol :tag "Collection"))
1121 (const :tag "Plain sort" string-lessp)
1122 (const :tag "File sort" ivy-sort-file-function-default)
1123 (const :tag "No sort" nil)))
1126 (defvar ivy-index-functions-alist
1127 '((swiper . ivy-recompute-index-swiper)
1128 (swiper-multi . ivy-recompute-index-swiper)
1129 (counsel-git-grep . ivy-recompute-index-swiper)
1130 (counsel-grep . ivy-recompute-index-swiper-async)
1131 (t . ivy-recompute-index-zero))
1132 "An alist of index recomputing functions for each collection function.
1133 When the input changes, the appropriate function returns an
1134 integer - the index of the matched candidate that should be
1137 (defvar ivy-re-builders-alist
1138 '((t . ivy--regex-plus))
1139 "An alist of regex building functions for each collection function.
1141 Each key is (in order of priority):
1142 1. The actual collection function, e.g. `read-file-name-internal'.
1143 2. The symbol passed by :caller into `ivy-read'.
1147 Each value is a function that should take a string and return a
1148 valid regex or a regex sequence (see below).
1150 Possible choices: `ivy--regex', `regexp-quote',
1151 `ivy--regex-plus', `ivy--regex-fuzzy'.
1153 If a function returns a list, it should format like this:
1154 '((\"matching-regexp\" . t) (\"non-matching-regexp\") ...).
1156 The matches will be filtered in a sequence, you can mix the
1157 regexps that should match and that should not match as you
1160 (defvar ivy-initial-inputs-alist
1161 '((org-refile . "^")
1162 (org-agenda-refile . "^")
1163 (org-capture-refile . "^")
1165 (counsel-describe-function . "^")
1166 (counsel-describe-variable . "^")
1169 "Command to initial input table.")
1171 (defcustom ivy-sort-max-size 30000
1172 "Sorting won't be done for collections larger than this."
1175 (defun ivy--sorted-files (dir)
1176 "Return the list of files in DIR.
1177 Directories come first."
1178 (let* ((default-directory dir)
1179 (seq (all-completions "" 'read-file-name-internal))
1183 (setq seq (delete "./" (delete "../" seq)))
1184 (when (eq (setq sort-fn (cdr (assoc 'read-file-name-internal
1185 ivy-sort-functions-alist)))
1186 #'ivy-sort-file-function-default)
1187 (setq seq (mapcar (lambda (x)
1188 (propertize x 'dirp (string-match-p "/\\'" x)))
1191 (setq seq (cl-sort seq sort-fn)))
1192 (dolist (dir ivy-extra-directories)
1196 (defvar ivy-recursive-restore t
1197 "When non-nil, restore the above state when exiting the minibuffer.
1198 This variable is let-bound to nil by functions that take care of
1199 the restoring themselves.")
1202 (cl-defun ivy-read (prompt collection
1204 predicate require-match initial-input
1205 history preselect keymap update-fn sort
1206 action unwind re-builder matcher dynamic-collection caller)
1207 "Read a string in the minibuffer, with completion.
1209 PROMPT is a format string, normally ending in a colon and a
1210 space; %d anywhere in the string is replaced by the current
1211 number of matching candidates. For the literal % character,
1212 escape it with %%. See also `ivy-count-format'.
1214 COLLECTION is either a list of strings, a function, an alist, or
1217 If INITIAL-INPUT is not nil, then insert that input in the
1218 minibuffer initially.
1220 KEYMAP is composed with `ivy-minibuffer-map'.
1222 If PRESELECT is not nil, then select the corresponding candidate
1223 out of the ones that match the INITIAL-INPUT.
1225 UPDATE-FN is called each time the current candidate(s) is changed.
1227 When SORT is t, use `ivy-sort-functions-alist' for sorting.
1229 ACTION is a lambda function to call after selecting a result. It
1230 takes a single string argument.
1232 UNWIND is a lambda function to call before exiting.
1234 RE-BUILDER is a lambda function to call to transform text into a
1237 MATCHER is to override matching.
1239 DYNAMIC-COLLECTION is a boolean to specify if the list of
1240 candidates is updated after each input by calling COLLECTION.
1242 CALLER is a symbol to uniquely identify the caller to `ivy-read'.
1243 It is used, along with COLLECTION, to determine which
1244 customizations apply to the current completion session."
1245 (let ((extra-actions (delete-dups
1246 (append (plist-get ivy--actions-list t)
1247 (plist-get ivy--actions-list this-command)
1248 (plist-get ivy--actions-list caller)))))
1251 (cond ((functionp action)
1253 ("o" ,action "default")
1257 ("o" identity "default")
1260 (delete-dups (append action extra-actions)))))))
1261 (let ((extra-sources (plist-get ivy--sources-list caller)))
1264 (setq ivy--extra-candidates nil)
1265 (dolist (source extra-sources)
1266 (cond ((equal source '(original-source))
1267 (setq ivy--extra-candidates
1268 (cons source ivy--extra-candidates)))
1269 ((null (cdr source))
1270 (setq ivy--extra-candidates
1272 (list (car source) (funcall (car source)))
1273 ivy--extra-candidates))))))
1274 (setq ivy--extra-candidates '((original-source)))))
1275 (let ((recursive-ivy-last (and (active-minibuffer-window) ivy-last))
1277 (plist-get ivy--display-transformers-list
1278 (or caller (and (functionp collection)
1283 :collection collection
1284 :predicate predicate
1285 :require-match require-match
1286 :initial-input initial-input
1288 :preselect preselect
1290 :update-fn update-fn
1293 :window (selected-window)
1294 :buffer (current-buffer)
1296 :re-builder re-builder
1298 :dynamic-collection dynamic-collection
1299 :display-transformer-fn transformer-fn
1301 (ivy--reset-state ivy-last)
1304 (minibuffer-with-setup-hook
1305 #'ivy--minibuffer-setup
1306 (let* ((hist (or history 'ivy-history))
1307 (minibuffer-completion-table collection)
1308 (minibuffer-completion-predicate predicate)
1309 (resize-mini-windows (cond
1310 ((display-graphic-p) nil)
1311 ((null resize-mini-windows) 'grow-only)
1312 (t resize-mini-windows))))
1313 (read-from-minibuffer
1315 (ivy-state-initial-input ivy-last)
1316 (make-composed-keymap keymap ivy-minibuffer-map)
1319 (when (eq ivy-exit 'done)
1320 (let ((item (if ivy--directory
1323 (unless (equal item "")
1324 (set hist (cons (propertize item 'ivy-index ivy--index)
1326 (cdr (symbol-value hist))))))))
1328 (remove-hook 'post-command-hook #'ivy--exhibit)
1329 (when (setq unwind (ivy-state-unwind ivy-last))
1331 (unless (eq ivy-exit 'done)
1332 (when recursive-ivy-last
1333 (ivy--reset-state (setq ivy-last recursive-ivy-last)))))
1335 (when (numberp (car-safe (ivy-state-action ivy-last)))
1336 (setcar (ivy-state-action ivy-last) 1))
1337 (when (and recursive-ivy-last
1338 ivy-recursive-restore)
1339 (ivy--reset-state (setq ivy-last recursive-ivy-last))))))
1341 (defun ivy--reset-state (state)
1342 "Reset the ivy to STATE.
1343 This is useful for recursive `ivy-read'."
1344 (let ((prompt (or (ivy-state-prompt state) ""))
1345 (collection (ivy-state-collection state))
1346 (predicate (ivy-state-predicate state))
1347 (history (ivy-state-history state))
1348 (preselect (ivy-state-preselect state))
1349 (sort (ivy-state-sort state))
1350 (re-builder (ivy-state-re-builder state))
1351 (dynamic-collection (ivy-state-dynamic-collection state))
1352 (initial-input (ivy-state-initial-input state))
1353 (require-match (ivy-state-require-match state))
1354 (caller (ivy-state-caller state)))
1355 (unless initial-input
1356 (setq initial-input (cdr (assoc this-command
1357 ivy-initial-inputs-alist))))
1358 (setq ivy--directory nil)
1359 (setq ivy-case-fold-search 'auto)
1360 (setq ivy--regex-function
1362 (and (functionp collection)
1363 (cdr (assoc collection ivy-re-builders-alist)))
1365 (cdr (assoc caller ivy-re-builders-alist)))
1366 (cdr (assoc this-command ivy-re-builders-alist))
1367 (cdr (assoc t ivy-re-builders-alist))
1369 (setq ivy--subexps 0)
1370 (setq ivy--regexp-quote 'regexp-quote)
1371 (setq ivy--old-text "")
1372 (setq ivy--full-length nil)
1374 (setq ivy-calling nil)
1375 (setq ivy-use-ignore t)
1377 (cond ((eq collection 'Info-read-node-name-1)
1378 (if (equal Info-current-file "dir")
1380 (mapcar (lambda (x) (format "(%s)" x))
1381 (cl-delete-duplicates
1382 (all-completions "(" collection predicate)
1384 (setq coll (all-completions "" collection predicate))))
1385 ((eq collection 'read-file-name-internal)
1386 (setq ivy--directory default-directory)
1389 (let ((preselect-directory (file-name-directory preselect)))
1390 (unless (or (null preselect-directory)
1391 (string= preselect-directory
1393 (setq ivy--directory preselect-directory))
1395 (ivy-state-preselect state)
1396 (setq preselect (file-name-nondirectory preselect)))))
1397 (setq coll (ivy--sorted-files ivy--directory))
1399 (unless (or require-match
1400 (equal initial-input default-directory)
1401 (equal initial-input ""))
1402 (setq coll (cons initial-input coll)))
1403 (unless (and (ivy-state-action ivy-last)
1404 (not (equal (ivy--get-action ivy-last) 'identity)))
1405 (setq initial-input nil))))
1406 ((eq collection 'internal-complete-buffer)
1407 (setq coll (ivy--buffer-list "" ivy-use-virtual-buffers)))
1409 (setq coll (funcall collection ivy-text)))
1410 ((or (functionp collection)
1411 (byte-code-function-p collection)
1412 (vectorp collection)
1413 (and (consp collection) (listp (car collection)))
1414 (hash-table-p collection)
1415 (and (listp collection) (symbolp (car collection))))
1416 (setq coll (all-completions "" collection predicate)))
1418 (setq coll collection)))
1420 (if (and (functionp collection)
1421 (setq sort-fn (assoc collection ivy-sort-functions-alist)))
1422 (when (and (setq sort-fn (cdr sort-fn))
1423 (not (eq collection 'read-file-name-internal)))
1424 (setq coll (cl-sort coll sort-fn)))
1425 (unless (eq history 'org-refile-history)
1426 (if (and (setq sort-fn (cdr (assoc t ivy-sort-functions-alist)))
1427 (<= (length coll) ivy-sort-max-size))
1428 (setq coll (cl-sort (copy-sequence coll) sort-fn))))))
1430 (unless (or (and require-match
1431 (not (eq collection 'internal-complete-buffer)))
1433 (let ((re (regexp-quote preselect)))
1434 (cl-find-if (lambda (x) (string-match re x))
1436 (setq coll (cons preselect coll))))
1437 (setq ivy--old-re nil)
1438 (setq ivy--old-cands nil)
1439 (when (integerp preselect)
1440 (setq ivy--old-re "")
1441 (setq ivy--index preselect))
1443 ;; Needed for anchor to work
1444 (setq ivy--old-cands coll)
1445 (setq ivy--old-cands (ivy--filter initial-input coll)))
1446 (setq ivy--all-candidates coll)
1447 (unless (integerp preselect)
1448 (setq ivy--index (or
1449 (and dynamic-collection
1452 (ivy--preselect-index
1460 (if (region-active-p)
1464 (ivy-thing-at-point)))
1466 (cond ((string-match "%.*d" prompt)
1468 ((null ivy-count-format)
1470 "`ivy-count-format' can't be nil. Set it to an empty string instead"))
1471 ((string-match "%d.*%d" ivy-count-format)
1472 (let ((w (length (number-to-string
1473 (length ivy--all-candidates))))
1474 (s (copy-sequence ivy-count-format)))
1475 (string-match "%d" s)
1477 (string-match "%d" s (match-end 0))
1478 (setq s (replace-match (format "%%-%dd" w) nil nil s))
1479 (string-match "%d" s)
1480 (concat (replace-match (format "%%%dd" w) nil nil s)
1482 ((string-match "%.*d" ivy-count-format)
1483 (concat ivy-count-format prompt))
1488 (setf (ivy-state-initial-input ivy-last) initial-input)))
1491 (defun ivy-completing-read (prompt collection
1492 &optional predicate require-match initial-input
1493 history def inherit-input-method)
1494 "Read a string in the minibuffer, with completion.
1496 This interface conforms to `completing-read' and can be used for
1497 `completing-read-function'.
1499 PROMPT is a string that normally ends in a colon and a space.
1500 COLLECTION is either a list of strings, an alist, an obarray, or a hash table.
1501 PREDICATE limits completion to a subset of COLLECTION.
1502 REQUIRE-MATCH is a boolean value. See `completing-read'.
1503 INITIAL-INPUT is a string inserted into the minibuffer initially.
1504 HISTORY is a list of previously selected inputs.
1505 DEF is the default value.
1506 INHERIT-INPUT-METHOD is currently ignored."
1507 (if (memq this-command '(tmm-menubar tmm-shortcut))
1508 (completing-read-default prompt collection
1509 predicate require-match
1510 initial-input history
1511 def inherit-input-method)
1512 ;; See the doc of `completing-read'.
1513 (when (consp history)
1514 (when (numberp (cdr history))
1515 (setq initial-input (nth (1- (cdr history))
1516 (symbol-value (car history)))))
1517 (setq history (car history)))
1518 (ivy-read (replace-regexp-in-string "%" "%%" prompt)
1520 :predicate predicate
1521 :require-match require-match
1522 :initial-input (if (consp initial-input)
1524 (if (and (stringp initial-input)
1525 (string-match "\\+" initial-input))
1526 (replace-regexp-in-string
1527 "\\+" "\\\\+" initial-input)
1529 :preselect (if (listp def) (car def) def)
1533 (let ((sort (assoc this-command ivy-sort-functions-alist)))
1538 (defvar ivy-completion-beg nil
1539 "Completion bounds start.")
1541 (defvar ivy-completion-end nil
1542 "Completion bounds end.")
1544 (defun ivy-completion-in-region-action (str)
1545 "Insert STR, erasing the previous one.
1546 The previous string is between `ivy-completion-beg' and `ivy-completion-end'."
1549 (when ivy-completion-beg
1552 ivy-completion-end))
1553 (setq ivy-completion-beg
1554 (move-marker (make-marker) (point)))
1556 (setq ivy-completion-end
1557 (move-marker (make-marker) (point))))))
1559 (defun ivy-completion-common-length (str)
1560 "Return the length of the first 'completions-common-part face in STR."
1563 (while (and (<= pos len)
1564 (let ((prop (get-text-property pos 'face str)))
1565 (not (eq 'completions-common-part
1566 (if (listp prop) (car prop) prop)))))
1567 (setq pos (1+ pos)))
1569 (or (next-single-property-change pos 'face str) len)
1572 (defun ivy-completion-in-region (start end collection &optional predicate)
1573 "An Ivy function suitable for `completion-in-region-function'."
1574 (let* ((enable-recursive-minibuffers t)
1575 (str (buffer-substring-no-properties start end))
1576 (completion-ignore-case case-fold-search)
1578 (completion-all-completions str collection predicate (- end start))))
1580 (message "No matches")
1582 (setq ivy-completion-beg (- end (ivy-completion-common-length (car comps))))
1583 (setq ivy-completion-end end)
1584 (if (null (cdr comps))
1585 (if (string= str (car comps))
1586 (message "Sole match")
1587 (setf (ivy-state-window ivy-last) (selected-window))
1588 (ivy-completion-in-region-action
1589 (substring-no-properties
1591 (let* ((w (1+ (floor (log (length comps) 10))))
1592 (ivy-count-format (if (string= ivy-count-format "")
1594 (format "%%-%dd " w)))
1595 (prompt (format "(%s): " str)))
1597 (ivy-read (if (string= ivy-count-format "")
1599 (replace-regexp-in-string "%" "%%" prompt))
1600 ;; remove 'completions-first-difference face
1601 (mapcar #'substring-no-properties comps)
1602 :predicate predicate
1603 :action #'ivy-completion-in-region-action
1607 (defcustom ivy-do-completion-in-region t
1608 "When non-nil `ivy-mode' will set `completion-in-region-function'."
1612 (define-minor-mode ivy-mode
1613 "Toggle Ivy mode on or off.
1614 Turn Ivy mode on if ARG is positive, off otherwise.
1615 Turning on Ivy mode sets `completing-read-function' to
1616 `ivy-completing-read'.
1621 Minibuffer bindings:
1622 \\{ivy-minibuffer-map}"
1625 :keymap ivy-mode-map
1629 (setq completing-read-function 'ivy-completing-read)
1630 (when ivy-do-completion-in-region
1631 (setq completion-in-region-function 'ivy-completion-in-region)))
1632 (setq completing-read-function 'completing-read-default)
1633 (setq completion-in-region-function 'completion--in-region)))
1635 (defun ivy--preselect-index (preselect candidates)
1636 "Return the index of PRESELECT in CANDIDATES."
1637 (cond ((integerp preselect)
1639 ((cl-position preselect candidates :test #'equal))
1640 ((stringp preselect)
1641 (let ((re preselect))
1644 (string-match re x))
1649 (defvar ivy--regex-hash
1650 (make-hash-table :test #'equal)
1651 "Store pre-computed regex.")
1653 (defun ivy--split (str)
1654 "Split STR into a list by single spaces.
1655 The remaining spaces stick to their left.
1656 This allows to \"quote\" N spaces by inputting N+1 spaces."
1657 (let ((len (length str))
1662 (while (and (string-match " +" str start1)
1664 (setq match-len (- (match-end 0) (match-beginning 0)))
1668 (setq start1 start0)
1670 (push (substring str start1 (match-beginning 0)) res)
1671 (setq start1 (match-end 0)))
1672 (setq str (replace-match
1673 (make-string (1- match-len) ?\ )
1675 (setq start0 (or start0 start1))
1676 (setq start1 (1- (match-end 0)))))
1678 (push (substring str start0) res)
1679 (setq s (substring str start1))
1680 (unless (= (length s) 0)
1684 (defun ivy--regex (str &optional greedy)
1685 "Re-build regex pattern from STR in case it has a space.
1686 When GREEDY is non-nil, join words in a greedy way."
1687 (let ((hashed (unless greedy
1688 (gethash str ivy--regex-hash))))
1691 (setq ivy--subexps (car hashed)))
1692 (when (string-match "\\([^\\]\\|^\\)\\\\$" str)
1693 (setq str (substring str 0 -1)))
1695 (let ((subs (ivy--split str)))
1696 (if (= (length subs) 1)
1698 (setq ivy--subexps 0)
1701 (setq ivy--subexps (length subs))
1704 (if (string-match "\\`\\\\([^?].*\\\\)\\'" x)
1706 (format "\\(%s\\)" x)))
1711 ivy--regex-hash)))))
1713 (defun ivy--regex-ignore-order--part (str &optional discard)
1714 "Re-build regex from STR by splitting at spaces.
1715 Ignore the order of each group."
1716 (let* ((subs (split-string str " +" t))
1717 (len (length subs)))
1722 (mapcar (lambda (x) (cons x (not discard)))
1725 (defun ivy--regex-ignore-order (str)
1726 "Re-build regex from STR by splitting at spaces.
1727 Ignore the order of each group. Everything before \"!\" should
1728 match. Everything after \"!\" should not match."
1729 (let ((parts (split-string str "!" t)))
1730 (cl-case (length parts)
1734 (if (string= (substring str 0 1) "!")
1736 (ivy--regex-ignore-order--part (car parts) t))
1737 (ivy--regex-ignore-order--part (car parts))))
1740 (ivy--regex-ignore-order--part (car parts))
1741 (ivy--regex-ignore-order--part (cadr parts) t)))
1742 (t (error "Unexpected: use only one !")))))
1744 (defun ivy--regex-plus (str)
1745 "Build a regex sequence from STR.
1746 Spaces are wild card characters, everything before \"!\" should
1747 match. Everything after \"!\" should not match."
1748 (let ((parts (split-string str "!" t)))
1749 (cl-case (length parts)
1753 (if (string= (substring str 0 1) "!")
1755 (list (ivy--regex (car parts))))
1756 (ivy--regex (car parts))))
1759 (cons (ivy--regex (car parts)) t)
1760 (mapcar #'list (split-string (cadr parts) " " t))))
1761 (t (error "Unexpected: use only one !")))))
1763 (defun ivy--regex-fuzzy (str)
1764 "Build a regex sequence from STR.
1765 Insert .* between each char."
1766 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1768 (concat (match-string 1 str)
1771 (format "\\(%c\\)" x))
1772 (string-to-list (match-string 2 str)) ".*")
1773 (match-string 3 str))
1774 (setq ivy--subexps (length (match-string 2 str))))
1777 (defcustom ivy-fixed-height-minibuffer nil
1778 "When non nil, fix the height of the minibuffer during ivy
1779 completion at `ivy-height'. This effectively sets the minimum
1780 height at this level and tries to ensure that it does not change
1781 depending on the number of candidates."
1786 (defun ivy--minibuffer-setup ()
1787 "Setup ivy completion in the minibuffer."
1788 (set (make-local-variable 'completion-show-inline-help) nil)
1789 (set (make-local-variable 'minibuffer-default-add-function)
1791 (list ivy--default)))
1792 (when (display-graphic-p)
1793 (setq truncate-lines t))
1794 (setq-local max-mini-window-height ivy-height)
1795 (when ivy-fixed-height-minibuffer
1796 (set-window-text-height (selected-window) ivy-height))
1797 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1798 ;; show completions with empty input
1801 (defun ivy--input ()
1802 "Return the current minibuffer input."
1803 ;; assume one-line minibuffer input
1804 (buffer-substring-no-properties
1805 (minibuffer-prompt-end)
1806 (line-end-position)))
1808 (defun ivy--cleanup ()
1809 "Delete the displayed completion candidates."
1811 (goto-char (minibuffer-prompt-end))
1812 (delete-region (line-end-position) (point-max))))
1814 (defun ivy--insert-prompt ()
1815 "Update the prompt according to `ivy--prompt'."
1817 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1818 counsel-find-symbol))
1819 (setq ivy--prompt-extra ""))
1821 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1823 (setq head (match-string 1 ivy--prompt))
1825 (setq head (substring ivy--prompt 0 -1))
1827 (let ((inhibit-read-only t)
1828 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1831 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1832 (> (minibuffer-depth) 1))
1833 (format "[%d] " (minibuffer-depth))
1836 (if (string-match "%d.*%d" ivy-count-format)
1839 (or (and (ivy-state-dynamic-collection ivy-last)
1843 (or (and (ivy-state-dynamic-collection ivy-last)
1848 (d-str (if ivy--directory
1849 (abbreviate-file-name ivy--directory)
1852 (goto-char (point-min))
1853 (delete-region (point-min) (minibuffer-prompt-end))
1854 (if (> (+ (mod (+ (length n-str) (length d-str)) (window-width))
1857 (setq n-str (concat n-str "\n" d-str))
1858 (setq n-str (concat n-str d-str)))
1859 (let ((regex (format "\\([^\n]\\{%d\\}\\)[^\n]" (window-width))))
1860 (while (string-match regex n-str)
1861 (setq n-str (replace-match (concat (match-string 1 n-str) "\n") nil t n-str 1))))
1862 (set-text-properties 0 (length n-str)
1863 `(face minibuffer-prompt ,@std-props)
1865 (ivy--set-match-props n-str "confirm"
1866 `(face ivy-confirm-face ,@std-props))
1867 (ivy--set-match-props n-str "match required"
1868 `(face ivy-match-required-face ,@std-props))
1870 ;; get out of the prompt area
1871 (constrain-to-field nil (point-max))))))
1873 (defun ivy--set-match-props (str match props)
1874 "Set STR text properties that match MATCH to PROPS."
1875 (when (string-match match str)
1876 (set-text-properties
1882 (defvar inhibit-message)
1884 (defun ivy--sort-maybe (collection)
1885 "Sort COLLECTION if needed."
1886 (let ((sort (ivy-state-sort ivy-last))
1890 (let ((sort-fn (cond ((functionp sort)
1892 ((setq entry (assoc (ivy-state-collection ivy-last)
1893 ivy-sort-functions-alist))
1896 (cdr (assoc t ivy-sort-functions-alist))))))
1897 (if (functionp sort-fn)
1898 (cl-sort (copy-sequence collection) sort-fn)
1901 (defun ivy--exhibit ()
1902 "Insert Ivy completions display.
1903 Should be run via minibuffer `post-command-hook'."
1904 (when (memq 'ivy--exhibit post-command-hook)
1905 (let ((inhibit-field-text-motion nil))
1906 (constrain-to-field nil (point-max)))
1907 (setq ivy-text (ivy--input))
1908 (if (ivy-state-dynamic-collection ivy-last)
1909 ;; while-no-input would cause annoying
1910 ;; "Waiting for process to die...done" message interruptions
1911 (let ((inhibit-message t))
1912 (unless (equal ivy--old-text ivy-text)
1914 (setq ivy--all-candidates
1916 (funcall (ivy-state-collection ivy-last) ivy-text)))
1917 (setq ivy--old-text ivy-text)))
1918 (when ivy--all-candidates
1919 (ivy--insert-minibuffer
1920 (ivy--format ivy--all-candidates))))
1921 (cond (ivy--directory
1922 (if (string-match "/\\'" ivy-text)
1923 (if (member ivy-text ivy--all-candidates)
1924 (ivy--cd (expand-file-name ivy-text ivy--directory))
1925 (when (string-match "//\\'" ivy-text)
1926 (if (and default-directory
1927 (string-match "\\`[[:alpha:]]:/" default-directory))
1928 (ivy--cd (match-string 0 default-directory))
1930 (when (string-match "[[:alpha:]]:/$" ivy-text)
1931 (let ((drive-root (match-string 0 ivy-text)))
1932 (when (file-exists-p drive-root)
1933 (ivy--cd drive-root)))))
1934 (if (string-match "\\`~\\'" ivy-text)
1935 (ivy--cd (expand-file-name "~/")))))
1936 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1937 (when (or (and (string-match "\\` " ivy-text)
1938 (not (string-match "\\` " ivy--old-text)))
1939 (and (string-match "\\` " ivy--old-text)
1940 (not (string-match "\\` " ivy-text))))
1941 (setq ivy--all-candidates
1942 (if (and (> (length ivy-text) 0)
1943 (eq (aref ivy-text 0)
1945 (ivy--buffer-list " ")
1946 (ivy--buffer-list "" ivy-use-virtual-buffers)))
1947 (setq ivy--old-re nil))))
1948 (ivy--insert-minibuffer
1949 (with-current-buffer (ivy-state-buffer ivy-last)
1951 (ivy--filter ivy-text ivy--all-candidates))))
1952 (setq ivy--old-text ivy-text))))
1954 (defun ivy--insert-minibuffer (text)
1955 "Insert TEXT into minibuffer with appropriate cleanup."
1956 (let ((resize-mini-windows nil)
1957 (update-fn (ivy-state-update-fn ivy-last))
1961 (funcall update-fn))
1962 (ivy--insert-prompt)
1963 ;; Do nothing if while-no-input was aborted.
1964 (when (stringp text)
1965 (let ((buffer-undo-list t))
1969 (when (display-graphic-p)
1970 (ivy--resize-minibuffer-to-fit))))
1972 (defun ivy--resize-minibuffer-to-fit ()
1973 "Resize the minibuffer window size to fit the text in the minibuffer."
1974 (unless (frame-root-window-p (minibuffer-window))
1975 (with-selected-window (minibuffer-window)
1976 (if (fboundp 'window-text-pixel-size)
1977 (let ((text-height (cdr (window-text-pixel-size)))
1978 (body-height (window-body-height nil t)))
1979 (when (> text-height body-height)
1980 ;; Note: the size increment needs to be at least frame-char-height,
1981 ;; otherwise resizing won't do anything.
1982 (let ((delta (max (- text-height body-height) (frame-char-height))))
1983 (window-resize nil delta nil t t))))
1984 (let ((text-height (count-screen-lines))
1985 (body-height (window-body-height)))
1986 (when (> text-height body-height)
1987 (window-resize nil (- text-height body-height) nil t)))))))
1989 (declare-function colir-blend-face-background "ext:colir")
1991 (defun ivy--add-face (str face)
1992 "Propertize STR with FACE.
1993 `font-lock-append-text-property' is used, since it's better than
1994 `propertize' or `add-face-text-property' in this case."
1998 (colir-blend-face-background 0 (length str) face str)
1999 (let ((foreground (face-foreground face)))
2001 (add-face-text-property
2003 `(:foreground ,foreground)
2008 (font-lock-append-text-property 0 (length str) 'face face str))))
2011 (declare-function flx-make-string-cache "ext:flx")
2012 (declare-function flx-score "ext:flx")
2014 (defvar ivy--flx-cache nil)
2016 (eval-after-load 'flx
2017 '(setq ivy--flx-cache (flx-make-string-cache)))
2019 (defun ivy-toggle-case-fold ()
2020 "Toggle the case folding between nil and auto.
2021 In any completion session, the case folding starts in auto:
2023 - when the input is all lower case, `case-fold-search' is t
2026 You can toggle this to make `case-fold-search' nil regardless of input."
2028 (setq ivy-case-fold-search
2029 (if ivy-case-fold-search
2032 ;; reset cache so that the candidate list updates
2033 (setq ivy--old-re nil))
2035 (defun ivy--re-filter (re candidates)
2036 "Return all RE matching CANDIDATES.
2037 RE is a list of cons cells, with a regexp car and a boolean cdr.
2038 When the cdr is t, the car must match.
2039 Otherwise, the car must not match."
2040 (let ((re-list (if (stringp re) (list (cons re t)) re))
2042 (dolist (re re-list)
2049 (let ((re-str (car re)))
2050 (lambda (x) (string-match re-str x)))
2054 (defun ivy--filter (name candidates)
2055 "Return all items that match NAME in CANDIDATES.
2056 CANDIDATES are assumed to be static."
2057 (let ((re (funcall ivy--regex-function name)))
2058 (if (and (equal re ivy--old-re)
2060 ;; quick caching for "C-n", "C-p" etc.
2062 (let* ((re-str (if (listp re) (caar re) re))
2063 (matcher (ivy-state-matcher ivy-last))
2065 (and ivy-case-fold-search
2066 (string= name (downcase name))))
2069 (funcall matcher re candidates))
2072 (stringp ivy--old-re)
2073 (not (string-match "\\\\" ivy--old-re))
2074 (not (equal ivy--old-re ""))
2076 (if (string-match "\\\\)\\'" ivy--old-re)
2077 (substring ivy--old-re 0 -2)
2083 (lambda (x) (string-match re x))
2086 (ivy--re-filter re candidates)))))
2087 (ivy--recompute-index name re-str cands)
2089 (if (eq ivy--regex-function 'ivy--regex-ignore-order)
2094 (setq ivy--old-cands (ivy--sort name cands))))))
2096 (defun ivy--set-candidates (x)
2097 "Update `ivy--all-candidates' with X."
2099 (dolist (source ivy--extra-candidates)
2100 (if (equal source '(original-source))
2103 (setq res (append x res)))
2104 (setq ivy--old-re nil)
2106 (ivy--filter ivy-text (cadr source))
2108 (setq ivy--all-candidates res)))
2110 (defcustom ivy-sort-matches-functions-alist '((t . nil))
2111 "An alist of functions for sorting matching candidates.
2113 Unlike `ivy-sort-functions-alist', which is used to sort the
2114 whole collection only once, this alist of functions are used to
2115 sort only matching candidates after each change in input.
2117 The alist KEY is either a collection function or t to match
2118 previously unmatched collection functions.
2120 The alist VAL is a sorting function with the signature of
2121 `ivy--prefix-sort'."
2124 (const :tag "Fall-through" t)
2125 (symbol :tag "Collection"))
2128 (const :tag "Don't sort" nil)
2129 (const :tag "Put prefix matches ahead" 'ivy--prefix-sort)
2130 (function :tag "Custom sort function"))))
2132 (defun ivy--sort-files-by-date (_name candidates)
2133 "Re-soft CANDIDATES according to file modification date."
2134 (let ((default-directory ivy--directory))
2135 (cl-sort (copy-sequence candidates)
2138 (nth 5 (file-attributes f2))
2139 (nth 5 (file-attributes f1)))))))
2141 (defun ivy--sort (name candidates)
2142 "Re-sort CANDIDATES by NAME.
2143 All CANDIDATES are assumed to match NAME."
2144 (let ((key (or (ivy-state-caller ivy-last)
2145 (when (functionp (ivy-state-collection ivy-last))
2146 (ivy-state-collection ivy-last))))
2148 (cond ((and (require 'flx nil 'noerror)
2149 (eq ivy--regex-function 'ivy--regex-fuzzy))
2150 (ivy--flx-sort name candidates))
2151 ((setq fun (cdr (or (assoc key ivy-sort-matches-functions-alist)
2152 (assoc t ivy-sort-matches-functions-alist))))
2153 (funcall fun name candidates))
2157 (defun ivy--prefix-sort (name candidates)
2158 "Re-sort CANDIDATES.
2159 Prefix matches to NAME are put ahead of the list."
2160 (if (or (string-match "^\\^" name) (string= name ""))
2162 (let ((re-prefix (concat "^" (funcall ivy--regex-function name)))
2165 (dolist (s candidates)
2166 (if (string-match re-prefix s)
2168 (push s res-noprefix)))
2170 (nreverse res-prefix)
2171 (nreverse res-noprefix)))))
2173 (defun ivy--recompute-index (name re-str cands)
2174 (let* ((caller (ivy-state-caller ivy-last))
2175 (func (or (and caller (cdr (assoc caller ivy-index-functions-alist)))
2176 (cdr (assoc t ivy-index-functions-alist))
2177 #'ivy-recompute-index-zero)))
2178 (unless (eq this-command 'ivy-resume)
2181 (cl-position (if (and (> (length name) 0)
2182 (eq ?^ (aref name 0)))
2188 (concat re-str "/") cands
2190 (and (not (string= name ""))
2191 (not (and (require 'flx nil 'noerror)
2192 (eq ivy--regex-function 'ivy--regex-fuzzy)
2193 (< (length cands) 200)))
2195 (cl-position (nth ivy--index ivy--old-cands)
2197 (funcall func re-str cands))))
2198 (when (and (or (string= name "")
2200 (not (equal ivy--old-re "")))
2202 (or (ivy--preselect-index
2203 (ivy-state-preselect ivy-last)
2207 (defun ivy-recompute-index-swiper (_re-str cands)
2208 (let ((tail (nthcdr ivy--index ivy--old-cands))
2210 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2212 (while (and tail (null idx))
2213 ;; Compare with eq to handle equal duplicates in cands
2214 (setq idx (cl-position (pop tail) cands)))
2217 (1- (length cands))))
2220 ;; already in ivy-state-buffer
2221 (let ((n (line-number-at-pos))
2225 (when (eq n (read (get-text-property 0 'display c)))
2230 (defun ivy-recompute-index-swiper-async (_re-str cands)
2231 (let ((tail (nthcdr ivy--index ivy--old-cands))
2233 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2235 (while (and tail (null idx))
2236 ;; Compare with `equal', since the collection is re-created
2237 ;; each time with `split-string'
2238 (setq idx (cl-position (pop tail) cands :test #'equal)))
2242 (defun ivy-recompute-index-zero (_re-str _cands)
2245 (defcustom ivy-minibuffer-faces
2246 '(ivy-minibuffer-match-face-1
2247 ivy-minibuffer-match-face-2
2248 ivy-minibuffer-match-face-3
2249 ivy-minibuffer-match-face-4)
2250 "List of `ivy' faces for minibuffer group matches."
2251 :type '(repeat :tag "Faces"
2253 (const ivy-minibuffer-match-face-1)
2254 (const ivy-minibuffer-match-face-2)
2255 (const ivy-minibuffer-match-face-3)
2256 (const ivy-minibuffer-match-face-4)
2257 (face :tag "Other face"))))
2259 (defvar ivy-flx-limit 200
2260 "Used to conditionally turn off flx sorting.
2262 When the amount of matching candidates exceeds this limit, then
2263 no sorting is done.")
2265 (defun ivy--flx-sort (name cands)
2266 "Sort according to closeness to string NAME the string list CANDS."
2269 (< (length cands) ivy-flx-limit))
2270 (let* ((flx-name (if (string-match "^\\^" name)
2277 (let ((score (flx-score x flx-name ivy--flx-cache)))
2281 (if cands-with-score
2283 (let ((str (copy-sequence (cdr x)))
2286 (dolist (j (cdar x))
2287 (unless (eq j (1+ last-j))
2290 (ivy-add-face-text-property
2292 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2293 ivy-minibuffer-faces)
2296 (sort cands-with-score
2298 (> (caar x) (caar y)))))
2304 (defcustom ivy-format-function 'ivy-format-function-default
2305 "Function to transform the list of candidates into a string.
2306 This string is inserted into the minibuffer."
2308 (const :tag "Default" ivy-format-function-default)
2309 (const :tag "Arrow prefix" ivy-format-function-arrow)
2310 (const :tag "Full line" ivy-format-function-line)))
2312 (defun ivy--truncate-string (str width)
2313 "Truncate STR to WIDTH."
2314 (if (> (string-width str) width)
2315 (concat (substring str 0 (min (- width 3)
2316 (- (length str) 3))) "...")
2319 (defun ivy--format-function-generic (selected-fn other-fn strs separator)
2320 "Transform CAND-PAIRS into a string for minibuffer.
2321 SELECTED-FN and OTHER-FN each take two string arguments.
2322 SEPARATOR is used to join the candidates."
2326 (let ((curr (eq (cl-incf i) ivy--index)))
2328 (funcall selected-fn str)
2329 (funcall other-fn str))))
2333 (defun ivy-format-function-default (cands)
2334 "Transform CAND-PAIRS into a string for minibuffer."
2335 (ivy--format-function-generic
2337 (ivy--add-face str 'ivy-current-match))
2342 (defun ivy-format-function-arrow (cands)
2343 "Transform CAND-PAIRS into a string for minibuffer."
2344 (ivy--format-function-generic
2346 (concat "> " (ivy--add-face str 'ivy-current-match)))
2352 (defun ivy-format-function-line (cands)
2353 "Transform CAND-PAIRS into a string for minibuffer."
2354 (ivy--format-function-generic
2356 (ivy--add-face (concat str "\n") 'ivy-current-match))
2362 (defun ivy-add-face-text-property (start end face str)
2363 (if (fboundp 'add-face-text-property)
2364 (add-face-text-property
2365 start end face nil str)
2366 (font-lock-append-text-property
2367 start end 'face face str)))
2369 (defun ivy--format-minibuffer-line (str)
2371 (str (copy-sequence str)))
2372 (cond ((eq ivy--regex-function 'ivy--regex-ignore-order)
2373 (when (consp ivy--old-re)
2375 (dolist (re ivy--old-re)
2376 (when (string-match (car re) str)
2377 (ivy-add-face-text-property
2378 (match-beginning 0) (match-end 0)
2379 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2380 ivy-minibuffer-faces)
2383 ((and (eq ivy-display-style 'fancy)
2384 (not (eq ivy--regex-function 'ivy--regex-fuzzy)))
2386 (setq ivy--old-re (funcall ivy--regex-function ivy-text)))
2387 (while (and (string-match ivy--old-re str start)
2388 (> (- (match-end 0) (match-beginning 0)) 0))
2389 (setq start (match-end 0))
2391 (while (<= i ivy--subexps)
2393 (cond ((zerop ivy--subexps)
2394 (cadr ivy-minibuffer-faces))
2396 (car ivy-minibuffer-faces))
2398 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2399 ivy-minibuffer-faces)))))
2400 (ivy-add-face-text-property
2401 (match-beginning i) (match-end i)
2406 (ivy-set-display-transformer
2407 'read-file-name-internal 'ivy-read-file-transformer)
2409 (defun ivy-read-file-transformer (str)
2410 (if (string-match-p "/\\'" str)
2411 (propertize str 'face 'ivy-subdir)
2414 (defun ivy--format (cands)
2415 "Return a string for CANDS suitable for display in the minibuffer.
2416 CANDS is a list of strings."
2417 (setq ivy--length (length cands))
2418 (when (>= ivy--index ivy--length)
2419 (setq ivy--index (max (1- ivy--length) 0)))
2421 (setq ivy--current "")
2422 (let* ((half-height (/ ivy-height 2))
2423 (start (max 0 (- ivy--index half-height)))
2424 (end (min (+ start (1- ivy-height)) ivy--length))
2425 (start (max 0 (min start (- end (1- ivy-height)))))
2426 (cands (cl-subseq cands start end))
2427 (index (- ivy--index start))
2429 (setq ivy--current (copy-sequence (nth index cands)))
2430 (when (setq transformer-fn (ivy-state-display-transformer-fn ivy-last))
2432 (setq cands (mapcar transformer-fn cands))))
2433 (let* ((ivy--index index)
2435 #'ivy--format-minibuffer-line
2437 (res (concat "\n" (funcall ivy-format-function cands))))
2438 (put-text-property 0 (length res) 'read-only nil res)
2441 (defvar ivy--virtual-buffers nil
2442 "Store the virtual buffers alist.")
2444 (defvar recentf-list)
2446 (defcustom ivy-virtual-abbreviate 'name
2447 "The mode of abbreviation for virtual buffer names."
2449 (const :tag "Only name" name)
2450 (const :tag "Full path" full)
2451 ;; eventually, uniquify
2454 (defun ivy--virtual-buffers ()
2455 "Adapted from `ido-add-virtual-buffers-to-list'."
2456 (unless recentf-mode
2458 (let ((bookmarks (and (boundp 'bookmark-alist)
2460 virtual-buffers name)
2461 (dolist (head (append
2463 (delete " - no file -"
2464 (delq nil (mapcar (lambda (bookmark)
2465 (cdr (assoc 'filename bookmark)))
2468 (if (eq ivy-virtual-abbreviate 'name)
2469 (file-name-nondirectory head)
2470 (expand-file-name head)))
2471 (when (equal name "")
2472 (setq name (file-name-nondirectory (directory-file-name head))))
2473 (when (equal name "")
2475 (and (not (equal name ""))
2476 (null (get-file-buffer head))
2477 (not (assoc name virtual-buffers))
2478 (push (cons name head) virtual-buffers)))
2479 (when virtual-buffers
2480 (dolist (comp virtual-buffers)
2481 (put-text-property 0 (length (car comp))
2484 (setq ivy--virtual-buffers (nreverse virtual-buffers))
2485 (mapcar #'car ivy--virtual-buffers))))
2487 (defcustom ivy-ignore-buffers nil
2488 "List of regexps matching buffer names to ignore."
2489 :type '(repeat regexp))
2491 (defun ivy--buffer-list (str &optional virtual)
2492 "Return the buffers that match STR.
2493 When VIRTUAL is non-nil, add virtual buffers."
2498 (if (with-current-buffer x
2500 (abbreviate-file-name default-directory)))
2501 (propertize x 'face 'ivy-remote)
2503 (all-completions str 'internal-complete-buffer))
2505 (ivy--virtual-buffers)))))
2507 (defun ivy--switch-buffer-action (buffer)
2509 BUFFER may be a string or nil."
2511 (if (zerop (length buffer))
2513 ivy-text nil 'force-same-window)
2514 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2516 (not (get-buffer buffer)))
2517 (find-file (cdr virtual))
2519 buffer nil 'force-same-window))))))
2521 (defun ivy--switch-buffer-other-window-action (buffer)
2522 "Switch to BUFFER in other window.
2523 BUFFER may be a string or nil."
2524 (if (zerop (length buffer))
2525 (switch-to-buffer-other-window ivy-text)
2526 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2528 (not (get-buffer buffer)))
2529 (find-file-other-window (cdr virtual))
2530 (switch-to-buffer-other-window buffer)))))
2532 (defun ivy--rename-buffer-action (buffer)
2534 (let ((new-name (read-string "Rename buffer (to new name): ")))
2535 (with-current-buffer buffer
2536 (rename-buffer new-name))))
2538 (defvar ivy-switch-buffer-map (make-sparse-keymap))
2545 (ivy--reset-state ivy-last))
2548 ivy--switch-buffer-other-window-action
2551 ivy--rename-buffer-action
2554 (defun ivy--switch-buffer-matcher (regexp candidates)
2555 "Return REGEXP-matching CANDIDATES.
2556 Skip buffers that match `ivy-ignore-buffers'."
2557 (let ((res (ivy--re-filter regexp candidates)))
2558 (if (or (null ivy-use-ignore)
2559 (null ivy-ignore-buffers))
2565 (string-match regexp buf))
2566 ivy-ignore-buffers))
2570 (ivy-set-display-transformer
2571 'ivy-switch-buffer 'ivy-switch-buffer-transformer)
2572 (ivy-set-display-transformer
2573 'internal-complete-buffer 'ivy-switch-buffer-transformer)
2575 (defun ivy-switch-buffer-transformer (str)
2576 (let ((b (get-buffer str)))
2578 (buffer-file-name b)
2579 (buffer-modified-p b))
2580 (propertize str 'face 'ivy-modified-buffer)
2584 (defun ivy-switch-buffer ()
2585 "Switch to another buffer."
2587 (let ((this-command 'ivy-switch-buffer))
2588 (ivy-read "Switch to buffer: " 'internal-complete-buffer
2589 :matcher #'ivy--switch-buffer-matcher
2590 :preselect (buffer-name (other-buffer (current-buffer)))
2591 :action #'ivy--switch-buffer-action
2592 :keymap ivy-switch-buffer-map
2593 :caller 'ivy-switch-buffer)))
2596 (defun ivy-switch-buffer-other-window ()
2597 "Switch to another buffer in another window."
2599 (ivy-read "Switch to buffer in other window: " 'internal-complete-buffer
2600 :preselect (buffer-name (other-buffer (current-buffer)))
2601 :action #'ivy--switch-buffer-other-window-action
2602 :keymap ivy-switch-buffer-map
2603 :caller 'ivy-switch-buffer-other-window))
2606 (defun ivy-recentf ()
2607 "Find a file on `recentf-list'."
2609 (ivy-read "Recentf: " recentf-list
2614 :caller 'ivy-recentf))
2616 (defun ivy-yank-word ()
2617 "Pull next word from buffer into search string."
2622 (le (line-end-position)))
2626 (setq amend (buffer-substring-no-properties pt (point))))))
2628 (insert (replace-regexp-in-string " +" " " amend)))))
2630 (defun ivy-kill-ring-save ()
2631 "Store the current candidates into the kill ring.
2632 If the region is active, forward to `kill-ring-save' instead."
2634 (if (region-active-p)
2635 (call-interactively 'kill-ring-save)
2642 (defun ivy-insert-current ()
2643 "Make the current candidate into current input.
2644 Don't finish completion."
2646 (delete-minibuffer-contents)
2647 (if (and ivy--directory
2648 (string-match "/$" ivy--current))
2649 (insert (substring ivy--current 0 -1))
2650 (insert ivy--current)))
2652 (defun ivy-toggle-fuzzy ()
2653 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
2655 (setq ivy--old-re nil)
2656 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
2657 (setq ivy--regex-function 'ivy--regex-plus)
2658 (setq ivy--regex-function 'ivy--regex-fuzzy)))
2660 (defun ivy-reverse-i-search ()
2661 "Enter a recursive `ivy-read' session using the current history.
2662 The selected history element will be inserted into the minibuffer."
2664 (let ((enable-recursive-minibuffers t)
2665 (history (symbol-value (ivy-state-history ivy-last)))
2667 (ivy-recursive-restore nil))
2668 (ivy-read "Reverse-i-search: "
2672 (setq ivy-last old-last))
2673 (delete-minibuffer-contents)
2674 (insert (substring-no-properties x))
2677 (defun ivy-restrict-to-matches ()
2678 "Restrict candidates to current matches and erase input."
2680 (delete-minibuffer-contents)
2681 (setq ivy--all-candidates
2682 (ivy--filter ivy-text ivy--all-candidates)))
2685 (defvar-local ivy-occur-last nil
2686 "Buffer-local value of `ivy-last'.
2687 Can't re-use `ivy-last' because using e.g. `swiper' in the same
2688 buffer would modify `ivy-last'.")
2690 (defvar ivy-occur-mode-map
2691 (let ((map (make-sparse-keymap)))
2692 (define-key map [mouse-1] 'ivy-occur-click)
2693 (define-key map (kbd "RET") 'ivy-occur-press)
2694 (define-key map (kbd "j") 'ivy-occur-next-line)
2695 (define-key map (kbd "k") 'ivy-occur-previous-line)
2696 (define-key map (kbd "h") 'backward-char)
2697 (define-key map (kbd "l") 'forward-char)
2698 (define-key map (kbd "g") 'ivy-occur-press)
2699 (define-key map (kbd "a") 'ivy-occur-read-action)
2700 (define-key map (kbd "o") 'ivy-occur-dispatch)
2701 (define-key map (kbd "c") 'ivy-occur-toggle-calling)
2702 (define-key map (kbd "q") 'quit-window)
2704 "Keymap for Ivy Occur mode.")
2706 (defun ivy-occur-toggle-calling ()
2707 "Toggle `ivy-calling'."
2709 (if (setq ivy-calling (not ivy-calling))
2711 (setq mode-name "Ivy-Occur [calling]")
2713 (setq mode-name "Ivy-Occur"))
2714 (force-mode-line-update))
2716 (defun ivy-occur-next-line (&optional arg)
2717 "Move the cursor down ARG lines.
2718 When `ivy-calling' isn't nil, call `ivy-occur-press'."
2724 (defun ivy-occur-previous-line (&optional arg)
2725 "Move the cursor up ARG lines.
2726 When `ivy-calling' isn't nil, call `ivy-occur-press'."
2728 (forward-line (- arg))
2732 (define-derived-mode ivy-occur-mode fundamental-mode "Ivy-Occur"
2733 "Major mode for output from \\[ivy-occur].
2735 \\{ivy-occur-mode-map}")
2737 (defvar ivy-occur-grep-mode-map
2738 (let ((map (copy-keymap ivy-occur-mode-map)))
2739 (define-key map (kbd "C-x C-q") 'ivy-wgrep-change-to-wgrep-mode)
2741 "Keymap for Ivy Occur Grep mode.")
2743 (define-derived-mode ivy-occur-grep-mode grep-mode "Ivy-Occur"
2744 "Major mode for output from \\[ivy-occur].
2746 \\{ivy-occur-grep-mode-map}")
2748 (defvar ivy--occurs-list nil
2749 "A list of custom occur generators per command.")
2751 (defun ivy-set-occur (cmd occur)
2752 "Assign CMD a custom OCCUR function."
2753 (setq ivy--occurs-list
2754 (plist-put ivy--occurs-list cmd occur)))
2756 (defun ivy--occur-insert-lines (cands)
2758 (add-text-properties
2762 help-echo "mouse-1: call ivy-action")
2767 "Stop completion and put the current matches into a new buffer.
2769 The new buffer remembers current action(s).
2771 While in the *ivy-occur* buffer, selecting a candidate with RET or
2772 a mouse click will call the appropriate action for that candidate.
2774 There is no limit on the number of *ivy-occur* buffers."
2776 (if (not (window-minibuffer-p))
2777 (user-error "No completion session is active")
2778 (let* ((caller (ivy-state-caller ivy-last))
2779 (occur-fn (plist-get ivy--occurs-list caller))
2781 (generate-new-buffer
2782 (format "*ivy-occur%s \"%s\"*"
2784 (concat " " (prin1-to-string caller))
2787 (with-current-buffer buffer
2788 (let ((inhibit-read-only t))
2793 (insert (format "%d candidates:\n" (length ivy--old-cands)))
2794 (ivy--occur-insert-lines
2796 (lambda (cand) (concat " " cand))
2798 (setf (ivy-state-text ivy-last) ivy-text)
2799 (setq ivy-occur-last ivy-last)
2800 (setq-local ivy--directory ivy--directory))
2801 (ivy-exit-with-action
2802 `(lambda (_) (pop-to-buffer ,buffer))))))
2804 (declare-function wgrep-change-to-wgrep-mode "ext:wgrep")
2806 (defun ivy-wgrep-change-to-wgrep-mode ()
2807 "Forward to `wgrep-change-to-wgrep-mode'."
2809 (if (require 'wgrep nil 'noerror)
2810 (wgrep-change-to-wgrep-mode)
2811 (error "Package wgrep isn't installed")))
2813 (defun ivy-occur-read-action ()
2814 "Select one of the available actions as the current one."
2816 (let ((ivy-last ivy-occur-last))
2819 (defun ivy-occur-dispatch ()
2820 "Call one of the available actions on the current item."
2822 (let* ((state-action (ivy-state-action ivy-occur-last))
2823 (actions (if (symbolp state-action)
2825 (copy-sequence state-action))))
2828 (ivy-occur-read-action)
2830 (setf (ivy-state-action ivy-occur-last) actions))))
2832 (defun ivy-occur-click (event)
2833 "Execute action for the current candidate.
2834 EVENT gives the mouse position."
2836 (let ((window (posn-window (event-end event)))
2837 (pos (posn-point (event-end event))))
2838 (with-current-buffer (window-buffer window)
2840 (ivy-occur-press))))
2842 (declare-function swiper--cleanup "swiper")
2843 (declare-function swiper--add-overlays "swiper")
2845 (defun ivy-occur-press ()
2846 "Execute action for the current candidate."
2848 (when (save-excursion
2850 (looking-at "\\(?:./\\| \\)\\(.*\\)$"))
2851 (let* ((ivy-last ivy-occur-last)
2852 (ivy-text (ivy-state-text ivy-last))
2853 (str (buffer-substring
2856 (coll (ivy-state-collection ivy-last))
2857 (action (ivy--get-action ivy-last))
2861 (if (and (consp coll)
2863 (cdr (assoc str coll))
2865 (if (memq (ivy-state-caller ivy-last)
2866 '(swiper counsel-git-grep))
2867 (with-current-buffer (window-buffer (selected-window))
2869 (swiper--add-overlays
2870 (ivy--regex ivy-text)
2871 (line-beginning-position)
2874 (run-at-time 0.5 nil 'swiper--cleanup)))))))
2876 (defvar ivy-help-file (let ((default-directory
2878 (file-name-directory load-file-name)
2879 default-directory)))
2880 (if (file-exists-p "ivy-help.org")
2881 (expand-file-name "ivy-help.org")
2882 (if (file-exists-p "doc/ivy-help.org")
2883 (expand-file-name "doc/ivy-help.org"))))
2884 "The file for `ivy-help'.")
2889 (let ((buf (get-buffer "*Ivy Help*")))
2891 (setq buf (get-buffer-create "*Ivy Help*"))
2892 (with-current-buffer buf
2893 (insert-file-contents ivy-help-file)
2896 (goto-char (point-min))))
2897 (if (eq this-command 'ivy-help)
2898 (switch-to-buffer buf)
2900 (pop-to-buffer buf)))
2902 (goto-char (point-min))))
2906 ;;; ivy.el ends here