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.")
112 '((t :inherit font-lock-builtin-face))
113 "Face used by Ivy for displaying keys in `ivy-read-action'.")
115 (setcdr (assoc load-file-name custom-current-group-alist) 'ivy)
117 (defcustom ivy-height 10
118 "Number of lines for the minibuffer window."
121 (defcustom ivy-count-format "%-4d "
122 "The style to use for displaying the current candidate count for `ivy-read'.
123 Set this to \"\" to suppress the count visibility.
124 Set this to \"(%d/%d) \" to display both the index and the count."
126 (const :tag "Count disabled" "")
127 (const :tag "Count matches" "%-4d ")
128 (const :tag "Count matches and show current match" "(%d/%d) ")
131 (defcustom ivy-add-newline-after-prompt nil
132 "When non-nil, add a newline after the `ivy-read' prompt."
135 (defcustom ivy-wrap nil
136 "When non-nil, wrap around after the first and the last candidate."
139 (defcustom ivy-display-style (unless (version< emacs-version "24.5") 'fancy)
140 "The style for formatting the minibuffer.
142 By default, the matched strings are copied as is.
144 The fancy display style highlights matching parts of the regexp,
145 a behavior similar to `swiper'.
147 This setting depends on `add-face-text-property' - a C function
148 available as of Emacs 24.5. Fancy style will render poorly in
149 earlier versions of Emacs."
151 (const :tag "Plain" nil)
152 (const :tag "Fancy" fancy)))
154 (defcustom ivy-on-del-error-function 'minibuffer-keyboard-quit
155 "The handler for when `ivy-backward-delete-char' throws.
156 Usually a quick exit out of the minibuffer."
159 (defcustom ivy-extra-directories '("../" "./")
160 "Add this to the front of the list when completing file names.
161 Only \"./\" and \"../\" apply here. They appear in reverse order."
162 :type '(repeat :tag "Dirs"
164 (const :tag "Parent Directory" "../")
165 (const :tag "Current Directory" "./"))))
167 (defcustom ivy-use-virtual-buffers nil
168 "When non-nil, add `recentf-mode' and bookmarks to `ivy-switch-buffer'."
171 (defvar ivy--actions-list nil
172 "A list of extra actions per command.")
174 (defun ivy-set-actions (cmd actions)
175 "Set CMD extra exit points to ACTIONS."
176 (setq ivy--actions-list
177 (plist-put ivy--actions-list cmd actions)))
179 (defvar ivy--display-transformers-list nil
180 "A list of str->str transformers per command.")
182 (defun ivy-set-display-transformer (cmd transformer)
183 "Set CMD a displayed candidate TRANSFORMER.
185 It's a lambda that takes a string one of the candidates in the
186 collection and returns a string for display, the same candidate
187 plus some extra information.
189 This lambda is called only on the `ivy-height' candidates that
190 are about to be displayed, not on the whole collection."
191 (setq ivy--display-transformers-list
192 (plist-put ivy--display-transformers-list cmd transformer)))
194 (defvar ivy--sources-list nil
195 "A list of extra sources per command.")
197 (defun ivy-set-sources (cmd sources)
198 "Attach to CMD a list of extra SOURCES.
200 Each static source is a function that takes no argument and
201 returns a list of strings.
203 The '(original-source) determines the position of the original
206 Extra dynamic sources aren't supported yet.
210 (defun small-recentf ()
211 (cl-subseq recentf-list 0 20))
218 (setq ivy--sources-list
219 (plist-put ivy--sources-list cmd sources)))
223 (defvar ivy-minibuffer-map
224 (let ((map (make-sparse-keymap)))
225 (define-key map (kbd "C-m") 'ivy-done)
226 (define-key map (kbd "C-M-m") 'ivy-call)
227 (define-key map (kbd "C-j") 'ivy-alt-done)
228 (define-key map (kbd "C-M-j") 'ivy-immediate-done)
229 (define-key map (kbd "TAB") 'ivy-partial-or-done)
230 (define-key map [remap next-line] 'ivy-next-line)
231 (define-key map [remap previous-line] 'ivy-previous-line)
232 (define-key map (kbd "C-s") 'ivy-next-line-or-history)
233 (define-key map (kbd "C-r") 'ivy-reverse-i-search)
234 (define-key map (kbd "SPC") 'self-insert-command)
235 (define-key map [remap delete-backward-char] 'ivy-backward-delete-char)
236 (define-key map [remap backward-kill-word] 'ivy-backward-kill-word)
237 (define-key map [remap delete-char] 'ivy-delete-char)
238 (define-key map [remap forward-char] 'ivy-forward-char)
239 (define-key map [remap kill-word] 'ivy-kill-word)
240 (define-key map [remap beginning-of-buffer] 'ivy-beginning-of-buffer)
241 (define-key map [remap end-of-buffer] 'ivy-end-of-buffer)
242 (define-key map (kbd "M-n") 'ivy-next-history-element)
243 (define-key map (kbd "M-p") 'ivy-previous-history-element)
244 (define-key map (kbd "C-g") 'minibuffer-keyboard-quit)
245 (define-key map [remap scroll-up-command] 'ivy-scroll-up-command)
246 (define-key map [remap scroll-down-command] 'ivy-scroll-down-command)
247 (define-key map (kbd "C-M-n") 'ivy-next-line-and-call)
248 (define-key map (kbd "C-M-p") 'ivy-previous-line-and-call)
249 (define-key map (kbd "M-q") 'ivy-toggle-regexp-quote)
250 (define-key map (kbd "M-j") 'ivy-yank-word)
251 (define-key map (kbd "M-i") 'ivy-insert-current)
252 (define-key map (kbd "C-o") 'hydra-ivy/body)
253 (define-key map (kbd "M-o") 'ivy-dispatching-done)
254 (define-key map (kbd "C-M-o") 'ivy-dispatching-call)
255 (define-key map [remap kill-line] 'ivy-kill-line)
256 (define-key map (kbd "S-SPC") 'ivy-restrict-to-matches)
257 (define-key map [remap kill-ring-save] 'ivy-kill-ring-save)
258 (define-key map (kbd "C-'") 'ivy-avy)
259 (define-key map (kbd "C-M-a") 'ivy-read-action)
260 (define-key map (kbd "C-c C-o") 'ivy-occur)
261 (define-key map (kbd "C-c C-a") 'ivy-toggle-ignore)
262 (define-key map [remap describe-mode] 'ivy-help)
264 "Keymap used in the minibuffer.")
265 (autoload 'hydra-ivy/body "ivy-hydra" "" t)
268 (let ((map (make-sparse-keymap)))
269 (define-key map [remap switch-to-buffer]
271 (define-key map [remap switch-to-buffer-other-window]
272 'ivy-switch-buffer-other-window)
274 "Keymap for `ivy-mode'.")
277 (cl-defstruct ivy-state
279 predicate require-match initial-input
280 history preselect keymap update-fn sort
281 ;; The window in which `ivy-read' was called
283 ;; The buffer in which `ivy-read' was called
285 ;; The value of `ivy-text' to be used by `ivy-occur'
291 ;; When this is non-nil, call it for each input change to get new candidates
293 ;; A lambda that transforms candidates only for display
294 display-transformer-fn
297 (defvar ivy-last (make-ivy-state)
298 "The last parameters passed to `ivy-read'.
300 This should eventually become a stack so that you could use
301 `ivy-read' recursively.")
303 (defsubst ivy-set-action (action)
304 (setf (ivy-state-action ivy-last) action))
306 (defun ivy-thing-at-point ()
307 "Return a string that corresponds to the current thing at point."
309 (thing-at-point 'url)
310 (and (eq (ivy-state-collection ivy-last) 'read-file-name-internal)
311 (ffap-file-at-point))
313 (cond ((stringp (setq s (thing-at-point 'symbol)))
314 (if (string-match "\\`[`']?\\(.*?\\)'?\\'" s)
317 ((looking-at "(+\\(\\(?:\\sw\\|\\s_\\)+\\)\\_>")
318 (match-string-no-properties 1))
322 (defvar ivy-history nil
323 "History list of candidates entered in the minibuffer.
325 Maximum length of the history list is determined by the value
326 of `history-length'.")
328 (defvar ivy--directory nil
329 "Current directory when completing file names.")
331 (defvar ivy--length 0
332 "Store the amount of viable candidates.")
335 "Store the user's string as it is typed in.")
337 (defvar ivy--current ""
338 "Current candidate.")
341 "Store the index of the current candidate.")
344 "Store 'done if the completion was successfully selected.
345 Otherwise, store nil.")
347 (defvar ivy--all-candidates nil
348 "Store the candidates passed to `ivy-read'.")
350 (defvar ivy--extra-candidates '((original-source))
351 "Store candidates added by the extra sources.
353 This is an internal-use alist. Each key is a function name, or
354 original-source (which represents where the current dynamic
355 candidates should go).
357 Each value is an evaluation of the function, in case of static
358 sources. These values will subsequently be filtered on `ivy-text'.
360 This variable is set by `ivy-read' and used by `ivy--set-candidates'.")
362 (defvar ivy-use-ignore t
363 "Store policy for user-configured candidate filtering.")
365 (defvar ivy--default nil
366 "Default initial input.")
368 (defvar ivy--prompt nil
369 "Store the format-style prompt.
370 When non-nil, it should contain at least one %d.")
372 (defvar ivy--prompt-extra ""
373 "Temporary modifications to the prompt.")
375 (defvar ivy--old-re nil
376 "Store the old regexp.")
378 (defvar ivy--old-cands nil
379 "Store the candidates matched by `ivy--old-re'.")
381 (defvar ivy--regex-function 'ivy--regex
382 "Current function for building a regex.")
384 (defvar ivy--subexps 0
385 "Number of groups in the current `ivy--regex'.")
387 (defvar ivy--full-length nil
388 "When :dynamic-collection is non-nil, this can be the total amount of candidates.")
390 (defvar ivy--old-text ""
391 "Store old `ivy-text' for dynamic completion.")
393 (defvar ivy-case-fold-search 'auto
394 "Store the current overriding `case-fold-search'.")
396 (defvar Info-current-file)
399 (unless (fboundp 'defvar-local)
400 (defmacro defvar-local (var val &optional docstring)
401 "Define VAR as a buffer-local variable with default value VAL."
402 (declare (debug defvar) (doc-string 3))
403 (list 'progn (list 'defvar var val docstring)
404 (list 'make-variable-buffer-local (list 'quote var)))))
405 (unless (fboundp 'setq-local)
406 (defmacro setq-local (var val)
407 "Set variable VAR to value VAL in current buffer."
408 (list 'set (list 'make-local-variable (list 'quote var)) val))))
410 (defmacro ivy-quit-and-run (&rest body)
411 "Quit the minibuffer and run BODY afterwards."
413 (put 'quit 'error-message "")
416 (put 'quit 'error-message "Quit")
418 (minibuffer-keyboard-quit)))
420 (defun ivy-exit-with-action (action)
421 "Quit the minibuffer and call ACTION afterwards."
425 (ivy-set-action ',(ivy-state-action ivy-last))))
426 (setq ivy-exit 'done)
429 (defmacro with-ivy-window (&rest body)
430 "Execute BODY in the window from which `ivy-read' was called."
433 `(with-selected-window (ivy--get-window ivy-last)
436 (defun ivy--done (text)
437 "Insert TEXT and exit minibuffer."
438 (if (and ivy--directory
439 (not (eq (ivy-state-history ivy-last) 'grep-files-history)))
440 (insert (setq ivy--current (expand-file-name
441 text ivy--directory)))
442 (insert (setq ivy--current text)))
443 (setq ivy-exit 'done)
448 "Exit the minibuffer with the selected candidate."
450 (delete-minibuffer-contents)
451 (cond ((> ivy--length 0)
452 (ivy--done ivy--current))
453 ((memq (ivy-state-collection ivy-last)
454 '(read-file-name-internal internal-complete-buffer))
455 (if (or (not (eq confirm-nonexistent-file-or-buffer t))
456 (equal " (confirm)" ivy--prompt-extra))
458 (setq ivy--prompt-extra " (confirm)")
461 ((memq (ivy-state-require-match ivy-last)
462 '(nil confirm confirm-after-completion))
463 (ivy--done ivy-text))
465 (setq ivy--prompt-extra " (match required)")
469 (defvar ivy-read-action-format-function 'ivy-read-action-format-default
470 "Function used to transform the actions list into a docstring.")
472 (defun ivy-read-action-format-default (actions)
473 "Create a docstring from ACTIONS.
475 ACTIONS is a list. Each list item is a list of 3 items:
476 key (a string), cmd and doc (a string)."
478 (if (eq this-command 'ivy-read-action)
491 (defun ivy-read-action ()
492 "Change the action to one of the available ones.
494 Return nil for `minibuffer-keyboard-quit' or wrong key during the
495 selection, non-nil otherwise."
497 (let ((actions (ivy-state-action ivy-last)))
498 (if (null (ivy--actionp actions))
500 (let* ((hint (funcall ivy-read-action-format-function (cdr actions)))
501 (resize-mini-windows 'grow-only)
502 (key (string (read-key hint)))
503 (action-idx (cl-position-if
504 (lambda (x) (equal (car x) key))
506 (cond ((string= key "
\a")
509 (message "%s is not bound" key)
513 (setcar actions (1+ action-idx))
514 (ivy-set-action actions)))))))
516 (defun ivy-dispatching-done ()
517 "Select one of the available actions and call `ivy-done'."
519 (when (ivy-read-action)
522 (defun ivy-dispatching-call ()
523 "Select one of the available actions and call `ivy-call'."
525 (let ((actions (copy-sequence (ivy-state-action ivy-last))))
527 (when (ivy-read-action)
529 (ivy-set-action actions))))
531 (defun ivy-build-tramp-name (x)
532 "Reconstruct X into a path.
533 Is is a cons cell, related to `tramp-get-completion-function'."
537 (concat user "@" domain)
540 (declare-function tramp-get-completion-function "tramp")
541 (declare-function Info-find-node "info")
543 (defun ivy-alt-done (&optional arg)
544 "Exit the minibuffer with the selected candidate.
545 When ARG is t, exit with current text, ignoring the candidates."
548 (ivy-immediate-done))
550 (ivy--directory-done))
551 ((eq (ivy-state-collection ivy-last) 'Info-read-node-name-1)
552 (if (member ivy--current '("(./)" "(../)"))
554 (ivy-read "Go to file: " 'read-file-name-internal
557 (expand-file-name x ivy--directory)
563 (defun ivy--directory-done ()
564 "Handle exit from the minibuffer when completing file names."
567 ((equal ivy-text "/sudo::")
568 (setq dir (concat ivy-text ivy--directory))
573 (not (string= ivy--current "./"))
574 (setq dir (ivy-expand-file-if-directory ivy--current)))
577 ((or (and (equal ivy--directory "/")
578 (string-match "\\`[^/]+:.*:.*\\'" ivy-text))
579 (string-match "\\`/[^/]+:.*:.*\\'" ivy-text))
581 ((or (and (equal ivy--directory "/")
583 "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
586 "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
588 (setq ivy-text ivy--current))))
590 "\\`/\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
592 (let ((method (match-string 1 ivy-text))
593 (user (match-string 2 ivy-text))
594 (rest (match-string 3 ivy-text))
597 (dolist (x (tramp-get-completion-function method))
598 (setq res (append res (funcall (car x) (cadr x)))))
599 (setq res (delq nil res))
603 (setq res (cl-delete-duplicates res :test #'equal))
604 (let* ((old-ivy-last ivy-last)
605 (enable-recursive-minibuffers t)
606 (host (ivy-read "user@host: "
607 (mapcar #'ivy-build-tramp-name res)
608 :initial-input rest)))
609 (setq ivy-last old-ivy-last)
611 (setq ivy--directory "/")
612 (ivy--cd (concat "/" method ":" host ":"))))))
616 (defun ivy-expand-file-if-directory (file-name)
617 "Expand FILE-NAME as directory.
618 When this directory doesn't exist, return nil."
619 (when (stringp file-name)
621 ;; Ignore host name must not match method "ssh"
623 (file-name-as-directory
624 (expand-file-name file-name ivy--directory)))))
625 (when (and full-name (file-directory-p full-name))
628 (defcustom ivy-tab-space nil
629 "When non-nil, `ivy-partial-or-done' should insert a space."
632 (defun ivy-partial-or-done ()
633 "Complete the minibuffer text as much as possible.
634 If the text hasn't changed as a result, forward to `ivy-alt-done'."
636 (if (and (eq (ivy-state-collection ivy-last) #'read-file-name-internal)
637 (or (and (equal ivy--directory "/")
638 (string-match "\\`[^/]+:.*\\'" ivy-text))
639 (string-match "\\`/" ivy-text)))
640 (let ((default-directory ivy--directory)
642 (minibuffer-complete)
643 (setq ivy-text (ivy--input))
644 (when (setq dir (ivy-expand-file-if-directory ivy-text))
647 (when (or (eq this-command last-command)
651 (defun ivy-partial ()
652 "Complete the minibuffer text as much as possible."
654 (let* ((parts (or (split-string ivy-text " " t) (list "")))
655 (postfix (car (last parts)))
656 (completion-ignore-case t)
657 (startp (string-match "^\\^" postfix))
658 (new (try-completion (if startp
659 (substring postfix 1)
661 (mapcar (lambda (str)
662 (let ((i (string-match postfix str)))
666 (cond ((eq new t) nil)
667 ((string= new ivy-text) nil)
669 (delete-region (minibuffer-prompt-end) (point-max))
674 (insert (mapconcat #'identity parts " ")
675 (if ivy-tab-space " " ""))
678 (defun ivy-immediate-done ()
679 "Exit the minibuffer with the current input."
681 (delete-minibuffer-contents)
682 (insert (setq ivy--current
684 (expand-file-name ivy-text ivy--directory)
686 (setq ivy-exit 'done)
691 "Resume the last completion session."
693 (if (null (ivy-state-action ivy-last))
694 (user-error "The last session isn't compatible with `ivy-resume'")
695 (when (eq (ivy-state-caller ivy-last) 'swiper)
696 (switch-to-buffer (ivy-state-buffer ivy-last)))
697 (with-current-buffer (ivy-state-buffer ivy-last)
699 (ivy-state-prompt ivy-last)
700 (ivy-state-collection ivy-last)
701 :predicate (ivy-state-predicate ivy-last)
702 :require-match (ivy-state-require-match ivy-last)
703 :initial-input ivy-text
704 :history (ivy-state-history ivy-last)
705 :preselect (unless (eq (ivy-state-collection ivy-last)
706 'read-file-name-internal)
708 :keymap (ivy-state-keymap ivy-last)
709 :update-fn (ivy-state-update-fn ivy-last)
710 :sort (ivy-state-sort ivy-last)
711 :action (ivy-state-action ivy-last)
712 :unwind (ivy-state-unwind ivy-last)
713 :re-builder (ivy-state-re-builder ivy-last)
714 :matcher (ivy-state-matcher ivy-last)
715 :dynamic-collection (ivy-state-dynamic-collection ivy-last)
716 :caller (ivy-state-caller ivy-last)))))
718 (defvar-local ivy-calling nil
719 "When non-nil, call the current action when `ivy--index' changes.")
721 (defun ivy-set-index (index)
722 "Set `ivy--index' to INDEX."
723 (setq ivy--index index)
728 (defun ivy-beginning-of-buffer ()
729 "Select the first completion candidate."
733 (defun ivy-end-of-buffer ()
734 "Select the last completion candidate."
736 (ivy-set-index (1- ivy--length)))
738 (defun ivy-scroll-up-command ()
739 "Scroll the candidates upward by the minibuffer height."
741 (ivy-set-index (min (1- (+ ivy--index ivy-height))
744 (defun ivy-scroll-down-command ()
745 "Scroll the candidates downward by the minibuffer height."
747 (ivy-set-index (max (1+ (- ivy--index ivy-height))
750 (defun ivy-minibuffer-grow ()
751 "Grow the minibuffer window by 1 line."
753 (setq-local max-mini-window-height
754 (cl-incf ivy-height)))
756 (defun ivy-minibuffer-shrink ()
757 "Shrink the minibuffer window by 1 line."
759 (unless (<= ivy-height 2)
760 (setq-local max-mini-window-height
761 (cl-decf ivy-height))
762 (window-resize (selected-window) -1)))
764 (defun ivy-next-line (&optional arg)
765 "Move cursor vertically down ARG candidates."
767 (setq arg (or arg 1))
768 (let ((index (+ ivy--index arg)))
769 (if (> index (1- ivy--length))
771 (ivy-beginning-of-buffer)
772 (ivy-set-index (1- ivy--length)))
773 (ivy-set-index index))))
775 (defun ivy-next-line-or-history (&optional arg)
776 "Move cursor vertically down ARG candidates.
777 If the input is empty, select the previous history element instead."
779 (if (string= ivy-text "")
780 (ivy-previous-history-element 1)
781 (ivy-next-line arg)))
783 (defun ivy-previous-line (&optional arg)
784 "Move cursor vertically up ARG candidates."
786 (setq arg (or arg 1))
787 (let ((index (- ivy--index arg)))
792 (ivy-set-index index))))
794 (defun ivy-previous-line-or-history (arg)
795 "Move cursor vertically up ARG candidates.
796 If the input is empty, select the previous history element instead."
798 (when (string= ivy-text "")
799 (ivy-previous-history-element 1))
800 (ivy-previous-line arg))
802 (defun ivy-toggle-calling ()
803 "Flip `ivy-calling'."
805 (when (setq ivy-calling (not ivy-calling))
808 (defun ivy-toggle-ignore ()
809 "Toggle user-configured candidate filtering."
811 (setq ivy-use-ignore (null ivy-use-ignore))
813 (setq ivy--old-cands nil))
815 (defun ivy--get-action (state)
816 "Get the action function from STATE."
817 (let ((action (ivy-state-action state)))
819 (if (functionp action)
821 (cadr (nth (car action) action))))))
823 (defun ivy--get-window (state)
824 "Get the window from STATE."
825 (if (ivy-state-p state)
826 (let ((window (ivy-state-window state)))
827 (if (window-live-p window)
829 (if (= (length (window-list)) 1)
834 (defun ivy--actionp (x)
835 "Return non-nil when X is a list of actions."
836 (and x (listp x) (not (eq (car x) 'closure))))
838 (defun ivy-next-action ()
839 "When the current action is a list, scroll it forwards."
841 (let ((action (ivy-state-action ivy-last)))
842 (when (ivy--actionp action)
843 (unless (>= (car action) (1- (length action)))
844 (cl-incf (car action))))))
846 (defun ivy-prev-action ()
847 "When the current action is a list, scroll it backwards."
849 (let ((action (ivy-state-action ivy-last)))
850 (when (ivy--actionp action)
851 (unless (<= (car action) 1)
852 (cl-decf (car action))))))
854 (defun ivy-action-name ()
855 "Return the name associated with the current action."
856 (let ((action (ivy-state-action ivy-last)))
857 (if (ivy--actionp action)
861 (nth 2 (nth (car action) action)))
864 (defvar ivy-inhibit-action nil
865 "When non-nil, `ivy-call' does nothing.
869 (let* ((ivy-inhibit-action t)
870 (str (counsel-locate \"lispy.el\")))
871 ;; do whatever with str - the corresponding file will not be opened
875 "Call the current action without exiting completion."
877 (unless ivy-inhibit-action
878 (let ((action (ivy--get-action ivy-last)))
880 (let* ((collection (ivy-state-collection ivy-last))
881 (x (if (and (consp collection)
882 (consp (car collection)))
883 (cdr (assoc ivy--current collection))
884 (if (equal ivy--current "")
887 (prog1 (funcall action x)
888 (unless (or (eq ivy-exit 'done)
889 (equal (selected-window)
890 (active-minibuffer-window))
891 (null (active-minibuffer-window)))
892 (select-window (active-minibuffer-window)))))))))
894 (defun ivy-next-line-and-call (&optional arg)
895 "Move cursor vertically down ARG candidates.
896 Call the permanent action if possible."
902 (defun ivy-previous-line-and-call (&optional arg)
903 "Move cursor vertically down ARG candidates.
904 Call the permanent action if possible."
906 (ivy-previous-line arg)
910 (defun ivy-previous-history-element (arg)
911 "Forward to `previous-history-element' with ARG."
913 (previous-history-element arg)
916 (ivy--maybe-scroll-history))
918 (defun ivy-next-history-element (arg)
919 "Forward to `next-history-element' with ARG."
921 (if (and (= minibuffer-history-position 0)
924 (insert ivy--default)
925 (when (and (with-ivy-window (derived-mode-p 'prog-mode))
926 (eq (ivy-state-caller ivy-last) 'swiper)
927 (not (file-exists-p ivy--default))
928 (not (ffap-url-p ivy--default))
929 (not (ivy-state-dynamic-collection ivy-last))
930 (> (point) (minibuffer-prompt-end)))
933 (goto-char (minibuffer-prompt-end))
935 (forward-char (+ 2 (length ivy--default)))))
936 (next-history-element arg))
939 (ivy--maybe-scroll-history))
941 (defvar ivy-ffap-url-functions nil
942 "List of functions that check if the point is on a URL.")
944 (defun ivy--cd-maybe ()
945 "Check if the current input points to a different directory.
946 If so, move to that directory, while keeping only the file name."
948 (let ((input (ivy--input))
950 (if (setq url (or (ffap-url-p input)
955 ivy-ffap-url-functions
956 :initial-value nil))))
957 (ivy-exit-with-action
959 (funcall ffap-url-fetcher url)))
960 (setq input (expand-file-name input))
961 (let ((file (file-name-nondirectory input))
962 (dir (expand-file-name (file-name-directory input))))
963 (if (string= dir ivy--directory)
965 (delete-minibuffer-contents)
970 (defun ivy--maybe-scroll-history ()
971 "If the selected history element has an index, scroll there."
972 (let ((idx (ignore-errors
974 (minibuffer-prompt-end)
978 (setq ivy--index idx))))
981 "When completing file names, move to directory DIR."
982 (if (null ivy--directory)
984 (setq ivy--old-cands nil)
985 (setq ivy--old-re nil)
987 (setq ivy--all-candidates
988 (ivy--sorted-files (setq ivy--directory dir)))
990 (delete-minibuffer-contents)))
992 (defun ivy-backward-delete-char ()
993 "Forward to `backward-delete-char'.
994 On error (read-only), call `ivy-on-del-error-function'."
996 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
998 (ivy--cd (file-name-directory
1004 (backward-delete-char 1)
1006 (when ivy-on-del-error-function
1007 (funcall ivy-on-del-error-function))))))
1009 (defun ivy-delete-char (arg)
1010 "Forward to `delete-char' ARG."
1012 (unless (= (point) (line-end-position))
1015 (defun ivy-forward-char (arg)
1016 "Forward to `forward-char' ARG."
1018 (unless (= (point) (line-end-position))
1019 (forward-char arg)))
1021 (defun ivy-kill-word (arg)
1022 "Forward to `kill-word' ARG."
1024 (unless (= (point) (line-end-position))
1027 (defun ivy-kill-line ()
1028 "Forward to `kill-line'."
1031 (kill-region (minibuffer-prompt-end) (point))
1034 (defun ivy-backward-kill-word ()
1035 "Forward to `backward-kill-word'."
1037 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
1039 (ivy--cd (file-name-directory
1040 (directory-file-name
1047 (delete-region (point) pt)))))
1049 (defvar ivy--regexp-quote 'regexp-quote
1050 "Store the regexp quoting state.")
1052 (defun ivy-toggle-regexp-quote ()
1053 "Toggle the regexp quoting."
1055 (setq ivy--old-re nil)
1056 (cl-rotatef ivy--regex-function ivy--regexp-quote))
1058 (defvar avy-all-windows)
1061 (defvar avy-keys-alist)
1063 (defvar avy-styles-alist)
1064 (declare-function avy--process "ext:avy")
1065 (declare-function avy--style-fn "ext:avy")
1067 (eval-after-load 'avy
1068 '(add-to-list 'avy-styles-alist '(ivy-avy . pre)))
1071 "Jump to one of the current ivy candidates."
1073 (unless (require 'avy nil 'noerror)
1074 (error "Package avy isn't installed"))
1075 (let* ((avy-all-windows nil)
1076 (avy-keys (or (cdr (assq 'ivy-avy avy-keys-alist))
1078 (avy-style (or (cdr (assq 'ivy-avy
1088 (goto-char (point-min))
1090 (while (< (point) (point-max))
1096 (setq avy-action #'identity)
1098 (nreverse candidates)
1099 (avy--style-fn avy-style)))))
1100 (when (numberp candidate)
1101 (ivy-set-index (- (line-number-at-pos candidate) 2))
1105 (defun ivy-sort-file-function-default (x y)
1106 "Compare two files X and Y.
1107 Prioritize directories."
1108 (if (get-text-property 0 'dirp x)
1109 (if (get-text-property 0 'dirp y)
1112 (if (get-text-property 0 'dirp y)
1116 (defcustom ivy-sort-functions-alist
1117 '((read-file-name-internal . ivy-sort-file-function-default)
1118 (internal-complete-buffer . nil)
1119 (counsel-git-grep-function . nil)
1120 (Man-goto-section . nil)
1123 "An alist of sorting functions for each collection function.
1124 Interactive functions that call completion fit in here as well.
1126 Nil means no sorting, which is useful to turn off the sorting for
1127 functions that have candidates in the natural buffer order, like
1128 `org-refile' or `Man-goto-section'.
1130 The entry associated with t is used for all fall-through cases.
1132 See also `ivy-sort-max-size'."
1136 (const :tag "Fall-through" t)
1137 (symbol :tag "Collection"))
1139 (const :tag "Plain sort" string-lessp)
1140 (const :tag "File sort" ivy-sort-file-function-default)
1141 (const :tag "No sort" nil)
1142 (function :tag "Custom function")))
1145 (defvar ivy-index-functions-alist
1146 '((swiper . ivy-recompute-index-swiper)
1147 (swiper-multi . ivy-recompute-index-swiper)
1148 (counsel-git-grep . ivy-recompute-index-swiper)
1149 (counsel-grep . ivy-recompute-index-swiper-async)
1150 (t . ivy-recompute-index-zero))
1151 "An alist of index recomputing functions for each collection function.
1152 When the input changes, the appropriate function returns an
1153 integer - the index of the matched candidate that should be
1156 (defvar ivy-re-builders-alist
1157 '((t . ivy--regex-plus))
1158 "An alist of regex building functions for each collection function.
1160 Each key is (in order of priority):
1161 1. The actual collection function, e.g. `read-file-name-internal'.
1162 2. The symbol passed by :caller into `ivy-read'.
1166 Each value is a function that should take a string and return a
1167 valid regex or a regex sequence (see below).
1169 Possible choices: `ivy--regex', `regexp-quote',
1170 `ivy--regex-plus', `ivy--regex-fuzzy'.
1172 If a function returns a list, it should format like this:
1173 '((\"matching-regexp\" . t) (\"non-matching-regexp\") ...).
1175 The matches will be filtered in a sequence, you can mix the
1176 regexps that should match and that should not match as you
1179 (defvar ivy-initial-inputs-alist
1180 '((org-refile . "^")
1181 (org-agenda-refile . "^")
1182 (org-capture-refile . "^")
1184 (counsel-describe-function . "^")
1185 (counsel-describe-variable . "^")
1188 "Command to initial input table.")
1190 (defcustom ivy-sort-max-size 30000
1191 "Sorting won't be done for collections larger than this."
1194 (defun ivy--sorted-files (dir)
1195 "Return the list of files in DIR.
1196 Directories come first."
1197 (let* ((default-directory dir)
1198 (seq (all-completions "" 'read-file-name-internal))
1202 (setq seq (delete "./" (delete "../" seq)))
1203 (when (eq (setq sort-fn (cdr (assoc 'read-file-name-internal
1204 ivy-sort-functions-alist)))
1205 #'ivy-sort-file-function-default)
1206 (setq seq (mapcar (lambda (x)
1207 (propertize x 'dirp (string-match-p "/\\'" x)))
1210 (setq seq (cl-sort seq sort-fn)))
1211 (dolist (dir ivy-extra-directories)
1215 (defvar ivy-recursive-restore t
1216 "When non-nil, restore the above state when exiting the minibuffer.
1217 This variable is let-bound to nil by functions that take care of
1218 the restoring themselves.")
1221 (cl-defun ivy-read (prompt collection
1223 predicate require-match initial-input
1224 history preselect keymap update-fn sort
1225 action unwind re-builder matcher dynamic-collection caller)
1226 "Read a string in the minibuffer, with completion.
1228 PROMPT is a format string, normally ending in a colon and a
1229 space; %d anywhere in the string is replaced by the current
1230 number of matching candidates. For the literal % character,
1231 escape it with %%. See also `ivy-count-format'.
1233 COLLECTION is either a list of strings, a function, an alist, or
1236 If INITIAL-INPUT is not nil, then insert that input in the
1237 minibuffer initially.
1239 KEYMAP is composed with `ivy-minibuffer-map'.
1241 If PRESELECT is not nil, then select the corresponding candidate
1242 out of the ones that match the INITIAL-INPUT.
1244 UPDATE-FN is called each time the current candidate(s) is changed.
1246 When SORT is t, use `ivy-sort-functions-alist' for sorting.
1248 ACTION is a lambda function to call after selecting a result. It
1249 takes a single string argument.
1251 UNWIND is a lambda function to call before exiting.
1253 RE-BUILDER is a lambda function to call to transform text into a
1256 MATCHER is to override matching.
1258 DYNAMIC-COLLECTION is a boolean to specify if the list of
1259 candidates is updated after each input by calling COLLECTION.
1261 CALLER is a symbol to uniquely identify the caller to `ivy-read'.
1262 It is used, along with COLLECTION, to determine which
1263 customizations apply to the current completion session."
1264 (let ((extra-actions (delete-dups
1265 (append (plist-get ivy--actions-list t)
1266 (plist-get ivy--actions-list this-command)
1267 (plist-get ivy--actions-list caller)))))
1270 (cond ((functionp action)
1272 ("o" ,action "default")
1276 ("o" identity "default")
1279 (delete-dups (append action extra-actions)))))))
1280 (let ((extra-sources (plist-get ivy--sources-list caller)))
1283 (setq ivy--extra-candidates nil)
1284 (dolist (source extra-sources)
1285 (cond ((equal source '(original-source))
1286 (setq ivy--extra-candidates
1287 (cons source ivy--extra-candidates)))
1288 ((null (cdr source))
1289 (setq ivy--extra-candidates
1291 (list (car source) (funcall (car source)))
1292 ivy--extra-candidates))))))
1293 (setq ivy--extra-candidates '((original-source)))))
1294 (let ((recursive-ivy-last (and (active-minibuffer-window) ivy-last))
1296 (plist-get ivy--display-transformers-list
1297 (or caller (and (functionp collection)
1302 :collection collection
1303 :predicate predicate
1304 :require-match require-match
1305 :initial-input initial-input
1307 :preselect preselect
1309 :update-fn update-fn
1312 :window (selected-window)
1313 :buffer (current-buffer)
1315 :re-builder re-builder
1317 :dynamic-collection dynamic-collection
1318 :display-transformer-fn transformer-fn
1320 (ivy--reset-state ivy-last)
1323 (minibuffer-with-setup-hook
1324 #'ivy--minibuffer-setup
1325 (let* ((hist (or history 'ivy-history))
1326 (minibuffer-completion-table collection)
1327 (minibuffer-completion-predicate predicate)
1328 (resize-mini-windows (cond
1329 ((display-graphic-p) nil)
1330 ((null resize-mini-windows) 'grow-only)
1331 (t resize-mini-windows))))
1332 (read-from-minibuffer
1334 (ivy-state-initial-input ivy-last)
1335 (make-composed-keymap keymap ivy-minibuffer-map)
1338 (when (eq ivy-exit 'done)
1339 (let ((item (if ivy--directory
1342 (unless (equal item "")
1343 (set hist (cons (propertize item 'ivy-index ivy--index)
1345 (cdr (symbol-value hist))))))))
1347 (remove-hook 'post-command-hook #'ivy--exhibit)
1348 (when (setq unwind (ivy-state-unwind ivy-last))
1350 (unless (eq ivy-exit 'done)
1351 (when recursive-ivy-last
1352 (ivy--reset-state (setq ivy-last recursive-ivy-last)))))
1354 (when (and recursive-ivy-last
1355 ivy-recursive-restore)
1356 (ivy--reset-state (setq ivy-last recursive-ivy-last))))))
1358 (defun ivy--reset-state (state)
1359 "Reset the ivy to STATE.
1360 This is useful for recursive `ivy-read'."
1361 (let ((prompt (or (ivy-state-prompt state) ""))
1362 (collection (ivy-state-collection state))
1363 (predicate (ivy-state-predicate state))
1364 (history (ivy-state-history state))
1365 (preselect (ivy-state-preselect state))
1366 (sort (ivy-state-sort state))
1367 (re-builder (ivy-state-re-builder state))
1368 (dynamic-collection (ivy-state-dynamic-collection state))
1369 (initial-input (ivy-state-initial-input state))
1370 (require-match (ivy-state-require-match state))
1371 (caller (ivy-state-caller state)))
1372 (unless initial-input
1373 (setq initial-input (cdr (assoc this-command
1374 ivy-initial-inputs-alist))))
1375 (setq ivy--directory nil)
1376 (setq ivy-case-fold-search 'auto)
1377 (setq ivy--regex-function
1379 (and (functionp collection)
1380 (cdr (assoc collection ivy-re-builders-alist)))
1382 (cdr (assoc caller ivy-re-builders-alist)))
1383 (cdr (assoc this-command ivy-re-builders-alist))
1384 (cdr (assoc t ivy-re-builders-alist))
1386 (setq ivy--subexps 0)
1387 (setq ivy--regexp-quote 'regexp-quote)
1388 (setq ivy--old-text "")
1389 (setq ivy--full-length nil)
1391 (setq ivy-calling nil)
1392 (setq ivy-use-ignore t)
1394 (cond ((eq collection 'Info-read-node-name-1)
1395 (if (equal Info-current-file "dir")
1397 (mapcar (lambda (x) (format "(%s)" x))
1398 (cl-delete-duplicates
1399 (all-completions "(" collection predicate)
1401 (setq coll (all-completions "" collection predicate))))
1402 ((eq collection 'read-file-name-internal)
1403 (setq ivy--directory default-directory)
1406 (let ((preselect-directory (file-name-directory preselect)))
1407 (unless (or (null preselect-directory)
1408 (string= preselect-directory
1410 (setq ivy--directory preselect-directory))
1412 (ivy-state-preselect state)
1413 (setq preselect (file-name-nondirectory preselect)))))
1414 (setq coll (ivy--sorted-files ivy--directory))
1416 (unless (or require-match
1417 (equal initial-input default-directory)
1418 (equal initial-input ""))
1419 (setq coll (cons initial-input coll)))
1420 (unless (and (ivy-state-action ivy-last)
1421 (not (equal (ivy--get-action ivy-last) 'identity)))
1422 (setq initial-input nil))))
1423 ((eq collection 'internal-complete-buffer)
1424 (setq coll (ivy--buffer-list "" ivy-use-virtual-buffers predicate)))
1426 (setq coll (funcall collection ivy-text)))
1427 ((or (functionp collection)
1428 (byte-code-function-p collection)
1429 (vectorp collection)
1430 (and (consp collection) (listp (car collection)))
1431 (hash-table-p collection)
1432 (and (listp collection) (symbolp (car collection))))
1433 (setq coll (all-completions "" collection predicate)))
1435 (setq coll collection)))
1437 (if (and (functionp collection)
1438 (setq sort-fn (assoc collection ivy-sort-functions-alist)))
1439 (when (and (setq sort-fn (cdr sort-fn))
1440 (not (eq collection 'read-file-name-internal)))
1441 (setq coll (cl-sort coll sort-fn)))
1442 (unless (eq history 'org-refile-history)
1443 (if (and (setq sort-fn (cdr (assoc t ivy-sort-functions-alist)))
1444 (<= (length coll) ivy-sort-max-size))
1445 (setq coll (cl-sort (copy-sequence coll) sort-fn))))))
1446 (setq coll (ivy--set-candidates coll))
1448 (unless (or (and require-match
1449 (not (eq collection 'internal-complete-buffer)))
1451 (let ((re (regexp-quote preselect)))
1452 (cl-find-if (lambda (x) (string-match re x))
1454 (setq coll (cons preselect coll))))
1455 (setq ivy--old-re nil)
1456 (setq ivy--old-cands nil)
1457 (when (integerp preselect)
1458 (setq ivy--old-re "")
1459 (setq ivy--index preselect))
1461 ;; Needed for anchor to work
1462 (setq ivy--old-cands coll)
1463 (setq ivy--old-cands (ivy--filter initial-input coll)))
1464 (setq ivy--all-candidates coll)
1465 (unless (integerp preselect)
1466 (setq ivy--index (or
1467 (and dynamic-collection
1470 (ivy--preselect-index
1478 (if (region-active-p)
1482 (ivy-thing-at-point)))
1484 (cond ((string-match "%.*d" prompt)
1486 ((null ivy-count-format)
1488 "`ivy-count-format' can't be nil. Set it to an empty string instead"))
1489 ((string-match "%d.*%d" ivy-count-format)
1490 (let ((w (length (number-to-string
1491 (length ivy--all-candidates))))
1492 (s (copy-sequence ivy-count-format)))
1493 (string-match "%d" s)
1495 (string-match "%d" s (match-end 0))
1496 (setq s (replace-match (format "%%-%dd" w) nil nil s))
1497 (string-match "%d" s)
1498 (concat (replace-match (format "%%%dd" w) nil nil s)
1500 ((string-match "%.*d" ivy-count-format)
1501 (concat ivy-count-format prompt))
1506 (setf (ivy-state-initial-input ivy-last) initial-input)))
1509 (defun ivy-completing-read (prompt collection
1510 &optional predicate require-match initial-input
1511 history def inherit-input-method)
1512 "Read a string in the minibuffer, with completion.
1514 This interface conforms to `completing-read' and can be used for
1515 `completing-read-function'.
1517 PROMPT is a string that normally ends in a colon and a space.
1518 COLLECTION is either a list of strings, an alist, an obarray, or a hash table.
1519 PREDICATE limits completion to a subset of COLLECTION.
1520 REQUIRE-MATCH is a boolean value. See `completing-read'.
1521 INITIAL-INPUT is a string inserted into the minibuffer initially.
1522 HISTORY is a list of previously selected inputs.
1523 DEF is the default value.
1524 INHERIT-INPUT-METHOD is currently ignored."
1525 (if (memq this-command '(tmm-menubar tmm-shortcut))
1526 (completing-read-default prompt collection
1527 predicate require-match
1528 initial-input history
1529 def inherit-input-method)
1530 ;; See the doc of `completing-read'.
1531 (when (consp history)
1532 (when (numberp (cdr history))
1533 (setq initial-input (nth (1- (cdr history))
1534 (symbol-value (car history)))))
1535 (setq history (car history)))
1536 (ivy-read (replace-regexp-in-string "%" "%%" prompt)
1538 :predicate predicate
1539 :require-match require-match
1540 :initial-input (if (consp initial-input)
1542 (if (and (stringp initial-input)
1543 (string-match "\\+" initial-input))
1544 (replace-regexp-in-string
1545 "\\+" "\\\\+" initial-input)
1547 :preselect (if (listp def) (car def) def)
1551 (let ((sort (or (assoc this-command ivy-sort-functions-alist)
1552 (assoc t ivy-sort-functions-alist))))
1557 (defvar ivy-completion-beg nil
1558 "Completion bounds start.")
1560 (defvar ivy-completion-end nil
1561 "Completion bounds end.")
1563 (defun ivy-completion-in-region-action (str)
1564 "Insert STR, erasing the previous one.
1565 The previous string is between `ivy-completion-beg' and `ivy-completion-end'."
1568 (when ivy-completion-beg
1571 ivy-completion-end))
1572 (setq ivy-completion-beg
1573 (move-marker (make-marker) (point)))
1575 (setq ivy-completion-end
1576 (move-marker (make-marker) (point))))))
1578 (defun ivy-completion-common-length (str)
1579 "Return the length of the first 'completions-common-part face in STR."
1582 (while (and (<= pos len)
1583 (let ((prop (get-text-property pos 'face str)))
1584 (not (eq 'completions-common-part
1585 (if (listp prop) (car prop) prop)))))
1586 (setq pos (1+ pos)))
1588 (or (next-single-property-change pos 'face str) len)
1591 (defun ivy-completion-in-region (start end collection &optional predicate)
1592 "An Ivy function suitable for `completion-in-region-function'."
1593 (let* ((enable-recursive-minibuffers t)
1594 (str (buffer-substring-no-properties start end))
1595 (completion-ignore-case case-fold-search)
1597 (completion-all-completions str collection predicate (- end start))))
1599 (message "No matches")
1601 (setq ivy-completion-beg (- end (ivy-completion-common-length (car comps))))
1602 (setq ivy-completion-end end)
1603 (if (null (cdr comps))
1604 (if (string= str (car comps))
1605 (message "Sole match")
1606 (setf (ivy-state-window ivy-last) (selected-window))
1607 (ivy-completion-in-region-action
1608 (substring-no-properties
1610 (let* ((w (1+ (floor (log (length comps) 10))))
1611 (ivy-count-format (if (string= ivy-count-format "")
1613 (format "%%-%dd " w)))
1614 (prompt (format "(%s): " str)))
1616 (ivy-read (if (string= ivy-count-format "")
1618 (replace-regexp-in-string "%" "%%" prompt))
1619 ;; remove 'completions-first-difference face
1620 (mapcar #'substring-no-properties comps)
1621 :predicate predicate
1622 :action #'ivy-completion-in-region-action
1626 (defcustom ivy-do-completion-in-region t
1627 "When non-nil `ivy-mode' will set `completion-in-region-function'."
1631 (define-minor-mode ivy-mode
1632 "Toggle Ivy mode on or off.
1633 Turn Ivy mode on if ARG is positive, off otherwise.
1634 Turning on Ivy mode sets `completing-read-function' to
1635 `ivy-completing-read'.
1640 Minibuffer bindings:
1641 \\{ivy-minibuffer-map}"
1644 :keymap ivy-mode-map
1648 (setq completing-read-function 'ivy-completing-read)
1649 (when ivy-do-completion-in-region
1650 (setq completion-in-region-function 'ivy-completion-in-region)))
1651 (setq completing-read-function 'completing-read-default)
1652 (setq completion-in-region-function 'completion--in-region)))
1654 (defun ivy--preselect-index (preselect candidates)
1655 "Return the index of PRESELECT in CANDIDATES."
1656 (cond ((integerp preselect)
1658 ((cl-position preselect candidates :test #'equal))
1659 ((stringp preselect)
1660 (let ((re preselect))
1663 (string-match re x))
1668 (defvar ivy--regex-hash
1669 (make-hash-table :test #'equal)
1670 "Store pre-computed regex.")
1672 (defun ivy--split (str)
1673 "Split STR into a list by single spaces.
1674 The remaining spaces stick to their left.
1675 This allows to \"quote\" N spaces by inputting N+1 spaces."
1676 (let ((len (length str))
1681 (while (and (string-match " +" str start1)
1683 (setq match-len (- (match-end 0) (match-beginning 0)))
1687 (setq start1 start0)
1689 (push (substring str start1 (match-beginning 0)) res)
1690 (setq start1 (match-end 0)))
1691 (setq str (replace-match
1692 (make-string (1- match-len) ?\ )
1694 (setq start0 (or start0 start1))
1695 (setq start1 (1- (match-end 0)))))
1697 (push (substring str start0) res)
1698 (setq s (substring str start1))
1699 (unless (= (length s) 0)
1703 (defun ivy--regex (str &optional greedy)
1704 "Re-build regex pattern from STR in case it has a space.
1705 When GREEDY is non-nil, join words in a greedy way."
1706 (let ((hashed (unless greedy
1707 (gethash str ivy--regex-hash))))
1710 (setq ivy--subexps (car hashed)))
1711 (when (string-match "\\([^\\]\\|^\\)\\\\$" str)
1712 (setq str (substring str 0 -1)))
1714 (let ((subs (ivy--split str)))
1715 (if (= (length subs) 1)
1717 (setq ivy--subexps 0)
1720 (setq ivy--subexps (length subs))
1723 (if (string-match "\\`\\\\([^?].*\\\\)\\'" x)
1725 (format "\\(%s\\)" x)))
1730 ivy--regex-hash)))))
1732 (defun ivy--regex-ignore-order--part (str &optional discard)
1733 "Re-build regex from STR by splitting at spaces.
1734 Ignore the order of each group."
1735 (let* ((subs (split-string str " +" t))
1736 (len (length subs)))
1741 (mapcar (lambda (x) (cons x (not discard)))
1744 (defun ivy--regex-ignore-order (str)
1745 "Re-build regex from STR by splitting at spaces.
1746 Ignore the order of each group. 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 (ivy--regex-ignore-order--part (car parts) t))
1756 (ivy--regex-ignore-order--part (car parts))))
1759 (ivy--regex-ignore-order--part (car parts))
1760 (ivy--regex-ignore-order--part (cadr parts) t)))
1761 (t (error "Unexpected: use only one !")))))
1763 (defun ivy--regex-plus (str)
1764 "Build a regex sequence from STR.
1765 Spaces are wild card characters, everything before \"!\" should
1766 match. Everything after \"!\" should not match."
1767 (let ((parts (split-string str "!" t)))
1768 (cl-case (length parts)
1772 (if (string= (substring str 0 1) "!")
1774 (list (ivy--regex (car parts))))
1775 (ivy--regex (car parts))))
1778 (cons (ivy--regex (car parts)) t)
1779 (mapcar #'list (split-string (cadr parts) " " t))))
1780 (t (error "Unexpected: use only one !")))))
1782 (defun ivy--regex-fuzzy (str)
1783 "Build a regex sequence from STR.
1784 Insert .* between each char."
1785 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1787 (concat (match-string 1 str)
1790 (format "\\(%c\\)" x))
1791 (string-to-list (match-string 2 str)) ".*")
1792 (match-string 3 str))
1793 (setq ivy--subexps (length (match-string 2 str))))
1796 (defcustom ivy-fixed-height-minibuffer nil
1797 "When non nil, fix the height of the minibuffer during ivy
1798 completion at `ivy-height'. This effectively sets the minimum
1799 height at this level and tries to ensure that it does not change
1800 depending on the number of candidates."
1805 (defun ivy--minibuffer-setup ()
1806 "Setup ivy completion in the minibuffer."
1807 (set (make-local-variable 'completion-show-inline-help) nil)
1808 (set (make-local-variable 'minibuffer-default-add-function)
1810 (list ivy--default)))
1811 (set (make-local-variable 'inhibit-field-text-motion) nil)
1812 (when (display-graphic-p)
1813 (setq truncate-lines t))
1814 (setq-local max-mini-window-height ivy-height)
1815 (when ivy-fixed-height-minibuffer
1816 (set-window-text-height (selected-window) ivy-height))
1817 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1818 ;; show completions with empty input
1821 (defun ivy--input ()
1822 "Return the current minibuffer input."
1823 ;; assume one-line minibuffer input
1824 (buffer-substring-no-properties
1825 (minibuffer-prompt-end)
1826 (line-end-position)))
1828 (defun ivy--cleanup ()
1829 "Delete the displayed completion candidates."
1831 (goto-char (minibuffer-prompt-end))
1832 (delete-region (line-end-position) (point-max))))
1834 (defun ivy--insert-prompt ()
1835 "Update the prompt according to `ivy--prompt'."
1837 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1838 counsel-find-symbol))
1839 (setq ivy--prompt-extra ""))
1841 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1843 (setq head (match-string 1 ivy--prompt))
1845 (setq head (substring ivy--prompt 0 -1))
1847 (let ((inhibit-read-only t)
1848 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1851 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1852 (> (minibuffer-depth) 1))
1853 (format "[%d] " (minibuffer-depth))
1856 (if (string-match "%d.*%d" ivy-count-format)
1859 (or (and (ivy-state-dynamic-collection ivy-last)
1863 (or (and (ivy-state-dynamic-collection ivy-last)
1868 (d-str (if ivy--directory
1869 (abbreviate-file-name ivy--directory)
1872 (goto-char (point-min))
1873 (delete-region (point-min) (minibuffer-prompt-end))
1874 (if (> (+ (mod (+ (length n-str) (length d-str)) (window-width))
1877 (setq n-str (concat n-str "\n" d-str))
1878 (setq n-str (concat n-str d-str)))
1879 (when ivy-add-newline-after-prompt
1880 (setq n-str (concat n-str "\n")))
1881 (let ((regex (format "\\([^\n]\\{%d\\}\\)[^\n]" (window-width))))
1882 (while (string-match regex n-str)
1883 (setq n-str (replace-match (concat (match-string 1 n-str) "\n") nil t n-str 1))))
1884 (set-text-properties 0 (length n-str)
1885 `(face minibuffer-prompt ,@std-props)
1887 (ivy--set-match-props n-str "confirm"
1888 `(face ivy-confirm-face ,@std-props))
1889 (ivy--set-match-props n-str "match required"
1890 `(face ivy-match-required-face ,@std-props))
1892 ;; get out of the prompt area
1893 (constrain-to-field nil (point-max))))))
1895 (defun ivy--set-match-props (str match props)
1896 "Set STR text properties that match MATCH to PROPS."
1897 (when (string-match match str)
1898 (set-text-properties
1904 (defvar inhibit-message)
1906 (defun ivy--sort-maybe (collection)
1907 "Sort COLLECTION if needed."
1908 (let ((sort (ivy-state-sort ivy-last))
1912 (let ((sort-fn (cond ((functionp sort)
1914 ((setq entry (assoc (ivy-state-collection ivy-last)
1915 ivy-sort-functions-alist))
1918 (cdr (assoc t ivy-sort-functions-alist))))))
1919 (if (functionp sort-fn)
1920 (cl-sort (copy-sequence collection) sort-fn)
1923 (defun ivy--exhibit ()
1924 "Insert Ivy completions display.
1925 Should be run via minibuffer `post-command-hook'."
1926 (when (memq 'ivy--exhibit post-command-hook)
1927 (let ((inhibit-field-text-motion nil))
1928 (constrain-to-field nil (point-max)))
1929 (setq ivy-text (ivy--input))
1930 (if (ivy-state-dynamic-collection ivy-last)
1931 ;; while-no-input would cause annoying
1932 ;; "Waiting for process to die...done" message interruptions
1933 (let ((inhibit-message t))
1934 (unless (equal ivy--old-text ivy-text)
1936 (setq ivy--all-candidates
1938 (funcall (ivy-state-collection ivy-last) ivy-text)))
1939 (setq ivy--old-text ivy-text)))
1940 (when ivy--all-candidates
1941 (ivy--insert-minibuffer
1942 (ivy--format ivy--all-candidates))))
1943 (cond (ivy--directory
1944 (if (string-match "/\\'" ivy-text)
1945 (if (member ivy-text ivy--all-candidates)
1946 (ivy--cd (expand-file-name ivy-text ivy--directory))
1947 (when (string-match "//\\'" ivy-text)
1948 (if (and default-directory
1949 (string-match "\\`[[:alpha:]]:/" default-directory))
1950 (ivy--cd (match-string 0 default-directory))
1952 (when (string-match "[[:alpha:]]:/$" ivy-text)
1953 (let ((drive-root (match-string 0 ivy-text)))
1954 (when (file-exists-p drive-root)
1955 (ivy--cd drive-root)))))
1956 (if (string-match "\\`~\\'" ivy-text)
1957 (ivy--cd (expand-file-name "~/")))))
1958 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1959 (when (or (and (string-match "\\` " ivy-text)
1960 (not (string-match "\\` " ivy--old-text)))
1961 (and (string-match "\\` " ivy--old-text)
1962 (not (string-match "\\` " ivy-text))))
1963 (setq ivy--all-candidates
1964 (if (and (> (length ivy-text) 0)
1965 (eq (aref ivy-text 0)
1967 (ivy--buffer-list " ")
1968 (ivy--buffer-list "" ivy-use-virtual-buffers)))
1969 (setq ivy--old-re nil))))
1970 (ivy--insert-minibuffer
1971 (with-current-buffer (ivy-state-buffer ivy-last)
1973 (ivy--filter ivy-text ivy--all-candidates))))
1974 (setq ivy--old-text ivy-text))))
1976 (defun ivy--insert-minibuffer (text)
1977 "Insert TEXT into minibuffer with appropriate cleanup."
1978 (let ((resize-mini-windows nil)
1979 (update-fn (ivy-state-update-fn ivy-last))
1983 (funcall update-fn))
1984 (ivy--insert-prompt)
1985 ;; Do nothing if while-no-input was aborted.
1986 (when (stringp text)
1987 (let ((buffer-undo-list t))
1991 (when (display-graphic-p)
1992 (ivy--resize-minibuffer-to-fit))))
1994 (defun ivy--resize-minibuffer-to-fit ()
1995 "Resize the minibuffer window size to fit the text in the minibuffer."
1996 (unless (frame-root-window-p (minibuffer-window))
1997 (with-selected-window (minibuffer-window)
1998 (if (fboundp 'window-text-pixel-size)
1999 (let ((text-height (cdr (window-text-pixel-size)))
2000 (body-height (window-body-height nil t)))
2001 (when (> text-height body-height)
2002 ;; Note: the size increment needs to be at least frame-char-height,
2003 ;; otherwise resizing won't do anything.
2004 (let ((delta (max (- text-height body-height) (frame-char-height))))
2005 (window-resize nil delta nil t t))))
2006 (let ((text-height (count-screen-lines))
2007 (body-height (window-body-height)))
2008 (when (> text-height body-height)
2009 (window-resize nil (- text-height body-height) nil t)))))))
2011 (declare-function colir-blend-face-background "ext:colir")
2013 (defun ivy--add-face (str face)
2014 "Propertize STR with FACE.
2015 `font-lock-append-text-property' is used, since it's better than
2016 `propertize' or `add-face-text-property' in this case."
2020 (colir-blend-face-background 0 (length str) face str)
2021 (let ((foreground (face-foreground face)))
2023 (add-face-text-property
2025 `(:foreground ,foreground)
2030 (font-lock-append-text-property 0 (length str) 'face face str))))
2033 (declare-function flx-make-string-cache "ext:flx")
2034 (declare-function flx-score "ext:flx")
2036 (defvar ivy--flx-cache nil)
2038 (eval-after-load 'flx
2039 '(setq ivy--flx-cache (flx-make-string-cache)))
2041 (defun ivy-toggle-case-fold ()
2042 "Toggle the case folding between nil and auto.
2043 In any completion session, the case folding starts in auto:
2045 - when the input is all lower case, `case-fold-search' is t
2048 You can toggle this to make `case-fold-search' nil regardless of input."
2050 (setq ivy-case-fold-search
2051 (if ivy-case-fold-search
2054 ;; reset cache so that the candidate list updates
2055 (setq ivy--old-re nil))
2057 (defun ivy--re-filter (re candidates)
2058 "Return all RE matching CANDIDATES.
2059 RE is a list of cons cells, with a regexp car and a boolean cdr.
2060 When the cdr is t, the car must match.
2061 Otherwise, the car must not match."
2062 (let ((re-list (if (stringp re) (list (cons re t)) re))
2064 (dolist (re re-list)
2071 (let ((re-str (car re)))
2072 (lambda (x) (string-match re-str x)))
2076 (defun ivy--filter (name candidates)
2077 "Return all items that match NAME in CANDIDATES.
2078 CANDIDATES are assumed to be static."
2079 (let ((re (funcall ivy--regex-function name)))
2080 (if (and (equal re ivy--old-re)
2082 ;; quick caching for "C-n", "C-p" etc.
2084 (let* ((re-str (if (listp re) (caar re) re))
2085 (matcher (ivy-state-matcher ivy-last))
2087 (and ivy-case-fold-search
2088 (string= name (downcase name))))
2091 (funcall matcher re candidates))
2094 (stringp ivy--old-re)
2095 (not (string-match "\\\\" ivy--old-re))
2096 (not (equal ivy--old-re ""))
2098 (if (string-match "\\\\)\\'" ivy--old-re)
2099 (substring ivy--old-re 0 -2)
2105 (lambda (x) (string-match re x))
2108 (ivy--re-filter re candidates)))))
2109 (ivy--recompute-index name re-str cands)
2111 (if (eq ivy--regex-function 'ivy--regex-ignore-order)
2116 (setq ivy--old-cands (ivy--sort name cands))))))
2118 (defun ivy--set-candidates (x)
2119 "Update `ivy--all-candidates' with X."
2121 (dolist (source ivy--extra-candidates)
2122 (if (equal source '(original-source))
2125 (setq res (append x res)))
2126 (setq ivy--old-re nil)
2128 (ivy--filter ivy-text (cadr source))
2130 (setq ivy--all-candidates res)))
2132 (defcustom ivy-sort-matches-functions-alist '((t . nil))
2133 "An alist of functions for sorting matching candidates.
2135 Unlike `ivy-sort-functions-alist', which is used to sort the
2136 whole collection only once, this alist of functions are used to
2137 sort only matching candidates after each change in input.
2139 The alist KEY is either a collection function or t to match
2140 previously unmatched collection functions.
2142 The alist VAL is a sorting function with the signature of
2143 `ivy--prefix-sort'."
2146 (const :tag "Fall-through" t)
2147 (symbol :tag "Collection"))
2150 (const :tag "Don't sort" nil)
2151 (const :tag "Put prefix matches ahead" 'ivy--prefix-sort)
2152 (function :tag "Custom sort function"))))
2154 (defun ivy--sort-files-by-date (_name candidates)
2155 "Re-soft CANDIDATES according to file modification date."
2156 (let ((default-directory ivy--directory))
2157 (cl-sort (copy-sequence candidates)
2160 (nth 5 (file-attributes f2))
2161 (nth 5 (file-attributes f1)))))))
2163 (defun ivy--sort (name candidates)
2164 "Re-sort CANDIDATES by NAME.
2165 All CANDIDATES are assumed to match NAME."
2166 (let ((key (or (ivy-state-caller ivy-last)
2167 (when (functionp (ivy-state-collection ivy-last))
2168 (ivy-state-collection ivy-last))))
2170 (cond ((and (require 'flx nil 'noerror)
2171 (eq ivy--regex-function 'ivy--regex-fuzzy))
2172 (ivy--flx-sort name candidates))
2173 ((setq fun (cdr (or (assoc key ivy-sort-matches-functions-alist)
2174 (assoc t ivy-sort-matches-functions-alist))))
2175 (funcall fun name candidates))
2179 (defun ivy--prefix-sort (name candidates)
2180 "Re-sort CANDIDATES.
2181 Prefix matches to NAME are put ahead of the list."
2182 (if (or (string-match "^\\^" name) (string= name ""))
2184 (let ((re-prefix (concat "^" (funcall ivy--regex-function name)))
2187 (dolist (s candidates)
2188 (if (string-match re-prefix s)
2190 (push s res-noprefix)))
2192 (nreverse res-prefix)
2193 (nreverse res-noprefix)))))
2195 (defun ivy--recompute-index (name re-str cands)
2196 (let* ((caller (ivy-state-caller ivy-last))
2197 (func (or (and caller (cdr (assoc caller ivy-index-functions-alist)))
2198 (cdr (assoc t ivy-index-functions-alist))
2199 #'ivy-recompute-index-zero)))
2200 (unless (eq this-command 'ivy-resume)
2203 (cl-position (if (and (> (length name) 0)
2204 (eq ?^ (aref name 0)))
2210 (concat re-str "/") cands
2212 (and (not (string= name ""))
2213 (not (and (require 'flx nil 'noerror)
2214 (eq ivy--regex-function 'ivy--regex-fuzzy)
2215 (< (length cands) 200)))
2217 (cl-position (nth ivy--index ivy--old-cands)
2219 (funcall func re-str cands))))
2220 (when (and (or (string= name "")
2222 (not (equal ivy--old-re "")))
2224 (or (ivy--preselect-index
2225 (ivy-state-preselect ivy-last)
2229 (defun ivy-recompute-index-swiper (_re-str cands)
2230 (let ((tail (nthcdr ivy--index ivy--old-cands))
2232 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2234 (while (and tail (null idx))
2235 ;; Compare with eq to handle equal duplicates in cands
2236 (setq idx (cl-position (pop tail) cands)))
2239 (1- (length cands))))
2242 ;; already in ivy-state-buffer
2243 (let ((n (line-number-at-pos))
2247 (when (eq n (read (get-text-property 0 'display c)))
2252 (defun ivy-recompute-index-swiper-async (_re-str cands)
2253 (if (null ivy--old-cands)
2254 (let ((ln (with-ivy-window
2255 (line-number-at-pos))))
2257 ;; closest to current line going forwards
2258 (cl-position-if (lambda (x)
2259 (>= (string-to-number x) ln))
2261 ;; closest to current line going backwards
2262 (1- (length cands))))
2263 (let ((tail (nthcdr ivy--index ivy--old-cands))
2265 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2267 (while (and tail (null idx))
2268 ;; Compare with `equal', since the collection is re-created
2269 ;; each time with `split-string'
2270 (setq idx (cl-position (pop tail) cands :test #'equal)))
2274 (defun ivy-recompute-index-zero (_re-str _cands)
2277 (defcustom ivy-minibuffer-faces
2278 '(ivy-minibuffer-match-face-1
2279 ivy-minibuffer-match-face-2
2280 ivy-minibuffer-match-face-3
2281 ivy-minibuffer-match-face-4)
2282 "List of `ivy' faces for minibuffer group matches."
2283 :type '(repeat :tag "Faces"
2285 (const ivy-minibuffer-match-face-1)
2286 (const ivy-minibuffer-match-face-2)
2287 (const ivy-minibuffer-match-face-3)
2288 (const ivy-minibuffer-match-face-4)
2289 (face :tag "Other face"))))
2291 (defvar ivy-flx-limit 200
2292 "Used to conditionally turn off flx sorting.
2294 When the amount of matching candidates exceeds this limit, then
2295 no sorting is done.")
2297 (defun ivy--flx-sort (name cands)
2298 "Sort according to closeness to string NAME the string list CANDS."
2301 (< (length cands) ivy-flx-limit))
2302 (let* ((flx-name (if (string-match "^\\^" name)
2309 (let ((score (flx-score x flx-name ivy--flx-cache)))
2313 (if cands-with-score
2315 (let ((str (copy-sequence (cdr x)))
2318 (dolist (j (cdar x))
2319 (unless (eq j (1+ last-j))
2322 (ivy-add-face-text-property
2324 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2325 ivy-minibuffer-faces)
2328 (sort cands-with-score
2330 (> (caar x) (caar y)))))
2336 (defcustom ivy-format-function 'ivy-format-function-default
2337 "Function to transform the list of candidates into a string.
2338 This string is inserted into the minibuffer."
2340 (const :tag "Default" ivy-format-function-default)
2341 (const :tag "Arrow prefix" ivy-format-function-arrow)
2342 (const :tag "Full line" ivy-format-function-line)))
2344 (defun ivy--truncate-string (str width)
2345 "Truncate STR to WIDTH."
2346 (if (> (string-width str) width)
2347 (concat (substring str 0 (min (- width 3)
2348 (- (length str) 3))) "...")
2351 (defun ivy--format-function-generic (selected-fn other-fn strs separator)
2352 "Transform CAND-PAIRS into a string for minibuffer.
2353 SELECTED-FN and OTHER-FN each take one string argument.
2354 SEPARATOR is used to join the candidates."
2358 (let ((curr (eq (cl-incf i) ivy--index)))
2360 (funcall selected-fn str)
2361 (funcall other-fn str))))
2365 (defun ivy-format-function-default (cands)
2366 "Transform CAND-PAIRS into a string for minibuffer."
2367 (ivy--format-function-generic
2369 (ivy--add-face str 'ivy-current-match))
2374 (defun ivy-format-function-arrow (cands)
2375 "Transform CAND-PAIRS into a string for minibuffer."
2376 (ivy--format-function-generic
2378 (concat "> " (ivy--add-face str 'ivy-current-match)))
2384 (defun ivy-format-function-line (cands)
2385 "Transform CAND-PAIRS into a string for minibuffer."
2386 (ivy--format-function-generic
2388 (ivy--add-face (concat str "\n") 'ivy-current-match))
2394 (defun ivy-add-face-text-property (start end face str)
2395 (if (fboundp 'add-face-text-property)
2396 (add-face-text-property
2397 start end face nil str)
2398 (font-lock-append-text-property
2399 start end 'face face str)))
2401 (defun ivy--format-minibuffer-line (str)
2403 (str (copy-sequence str)))
2404 (cond ((eq ivy--regex-function 'ivy--regex-ignore-order)
2405 (when (consp ivy--old-re)
2407 (dolist (re ivy--old-re)
2408 (when (string-match (car re) str)
2409 (ivy-add-face-text-property
2410 (match-beginning 0) (match-end 0)
2411 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2412 ivy-minibuffer-faces)
2415 ((and (eq ivy-display-style 'fancy)
2416 (not (eq ivy--regex-function 'ivy--regex-fuzzy)))
2418 (setq ivy--old-re (funcall ivy--regex-function ivy-text)))
2419 (while (and (string-match ivy--old-re str start)
2420 (> (- (match-end 0) (match-beginning 0)) 0))
2421 (setq start (match-end 0))
2423 (while (<= i ivy--subexps)
2425 (cond ((zerop ivy--subexps)
2426 (cadr ivy-minibuffer-faces))
2428 (car ivy-minibuffer-faces))
2430 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2431 ivy-minibuffer-faces)))))
2432 (ivy-add-face-text-property
2433 (match-beginning i) (match-end i)
2438 (ivy-set-display-transformer
2439 'counsel-find-file 'ivy-read-file-transformer)
2440 (ivy-set-display-transformer
2441 'read-file-name-internal 'ivy-read-file-transformer)
2443 (defun ivy-read-file-transformer (str)
2444 (if (string-match-p "/\\'" str)
2445 (propertize str 'face 'ivy-subdir)
2448 (defun ivy--format (cands)
2449 "Return a string for CANDS suitable for display in the minibuffer.
2450 CANDS is a list of strings."
2451 (setq ivy--length (length cands))
2452 (when (>= ivy--index ivy--length)
2453 (setq ivy--index (max (1- ivy--length) 0)))
2455 (setq ivy--current "")
2456 (let* ((half-height (/ ivy-height 2))
2457 (start (max 0 (- ivy--index half-height)))
2458 (end (min (+ start (1- ivy-height)) ivy--length))
2459 (start (max 0 (min start (- end (1- ivy-height)))))
2460 (cands (cl-subseq cands start end))
2461 (index (- ivy--index start))
2463 (setq ivy--current (copy-sequence (nth index cands)))
2464 (when (setq transformer-fn (ivy-state-display-transformer-fn ivy-last))
2466 (setq cands (mapcar transformer-fn cands))))
2467 (let* ((ivy--index index)
2469 #'ivy--format-minibuffer-line
2471 (res (concat "\n" (funcall ivy-format-function cands))))
2472 (put-text-property 0 (length res) 'read-only nil res)
2475 (defvar ivy--virtual-buffers nil
2476 "Store the virtual buffers alist.")
2478 (defvar recentf-list)
2480 (defcustom ivy-virtual-abbreviate 'name
2481 "The mode of abbreviation for virtual buffer names."
2483 (const :tag "Only name" name)
2484 (const :tag "Full path" full)
2485 ;; eventually, uniquify
2488 (defun ivy--virtual-buffers ()
2489 "Adapted from `ido-add-virtual-buffers-to-list'."
2490 (unless recentf-mode
2492 (let ((bookmarks (and (boundp 'bookmark-alist)
2494 virtual-buffers name)
2495 (dolist (head (append
2497 (delete " - no file -"
2498 (delq nil (mapcar (lambda (bookmark)
2499 (cdr (assoc 'filename bookmark)))
2502 (if (eq ivy-virtual-abbreviate 'name)
2503 (file-name-nondirectory head)
2504 (expand-file-name head)))
2505 (when (equal name "")
2506 (setq name (file-name-nondirectory (directory-file-name head))))
2507 (when (equal name "")
2509 (and (not (equal name ""))
2510 (null (get-file-buffer head))
2511 (not (assoc name virtual-buffers))
2512 (push (cons name head) virtual-buffers)))
2513 (when virtual-buffers
2514 (dolist (comp virtual-buffers)
2515 (put-text-property 0 (length (car comp))
2518 (setq ivy--virtual-buffers (nreverse virtual-buffers))
2519 (mapcar #'car ivy--virtual-buffers))))
2521 (defcustom ivy-ignore-buffers '("\\` ")
2522 "List of regexps or functions matching buffer names to ignore."
2523 :type '(repeat (choice regexp function)))
2525 (defun ivy--buffer-list (str &optional virtual predicate)
2526 "Return the buffers that match STR.
2527 When VIRTUAL is non-nil, add virtual buffers."
2532 (if (with-current-buffer x
2534 (abbreviate-file-name default-directory)))
2535 (propertize x 'face 'ivy-remote)
2537 (all-completions str 'internal-complete-buffer predicate))
2539 (ivy--virtual-buffers)))))
2541 (defvar ivy-views (and nil
2542 `(("ivy + *scratch* {}"
2544 (file ,(expand-file-name "ivy.el"))
2545 (buffer "*scratch*")))
2546 ("swiper + *scratch* {}"
2548 (file ,(expand-file-name "swiper.el"))
2549 (buffer "*scratch*")))))
2550 "Store window configurations selectable by `ivy-switch-buffer'.
2552 The default value is given as an example.
2554 Each element is a list of (NAME TREE). NAME is a string, it's
2555 recommended to end it with a distinctive snippet e.g. \"{}\" so
2556 that it's easy to distinguish the window configurations.
2558 TREE is a nested list with the following valid cars:
2559 - vert: split the window vertically
2560 - horz: split the window horizontally
2561 - file: open the specified file
2562 - buffer: open the specified buffer
2564 TREE can be nested multiple times to have mulitple window splits.")
2566 (defun ivy-source-views ()
2567 (mapcar #'car ivy-views))
2572 (ivy-source-views)))
2574 (defun ivy-set-view-recur (view)
2575 (cond ((eq (car view) 'vert)
2576 (let ((wnd1 (selected-window))
2577 (wnd2 (split-window-vertically)))
2578 (with-selected-window wnd1
2579 (ivy-set-view-recur (nth 1 view)))
2580 (with-selected-window wnd2
2581 (ivy-set-view-recur (nth 2 view)))))
2582 ((eq (car view) 'horz)
2583 (let ((wnd1 (selected-window))
2584 (wnd2 (split-window-horizontally)))
2585 (with-selected-window wnd1
2586 (ivy-set-view-recur (nth 1 view)))
2587 (with-selected-window wnd2
2588 (ivy-set-view-recur (nth 2 view)))))
2589 ((eq (car view) 'file)
2590 (let* ((name (cadr view))
2591 (virtual (assoc name ivy--virtual-buffers))
2593 (cond ((setq buffer (get-buffer name))
2594 (switch-to-buffer buffer nil 'force-same-window))
2596 (find-file (cdr virtual)))
2597 ((file-exists-p name)
2598 (find-file name)))))
2599 ((eq (car view) 'buffer)
2600 (switch-to-buffer (cadr view)))))
2602 (defun ivy--switch-buffer-action (buffer)
2604 BUFFER may be a string or nil."
2606 (if (zerop (length buffer))
2608 ivy-text nil 'force-same-window)
2609 (let ((virtual (assoc buffer ivy--virtual-buffers))
2610 (view (assoc buffer ivy-views)))
2612 (not (get-buffer buffer)))
2613 (find-file (cdr virtual)))
2615 (delete-other-windows)
2616 (ivy-set-view-recur (cadr view)))
2619 buffer nil 'force-same-window)))))))
2621 (defun ivy--switch-buffer-other-window-action (buffer)
2622 "Switch to BUFFER in other window.
2623 BUFFER may be a string or nil."
2624 (if (zerop (length buffer))
2625 (switch-to-buffer-other-window ivy-text)
2626 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2628 (not (get-buffer buffer)))
2629 (find-file-other-window (cdr virtual))
2630 (switch-to-buffer-other-window buffer)))))
2632 (defun ivy--rename-buffer-action (buffer)
2634 (let ((new-name (read-string "Rename buffer (to new name): ")))
2635 (with-current-buffer buffer
2636 (rename-buffer new-name))))
2638 (defvar ivy-switch-buffer-map (make-sparse-keymap))
2645 (ivy--reset-state ivy-last))
2648 ivy--switch-buffer-other-window-action
2651 ivy--rename-buffer-action
2654 (defun ivy--switch-buffer-matcher (regexp candidates)
2655 "Return REGEXP-matching CANDIDATES.
2656 Skip buffers that match `ivy-ignore-buffers'."
2657 (let ((res (ivy--re-filter regexp candidates)))
2658 (if (or (null ivy-use-ignore)
2659 (null ivy-ignore-buffers))
2665 (if (functionp f-or-r)
2666 (funcall f-or-r buf)
2667 (string-match-p f-or-r buf)))
2668 ivy-ignore-buffers))
2672 (ivy-set-display-transformer
2673 'ivy-switch-buffer 'ivy-switch-buffer-transformer)
2674 (ivy-set-display-transformer
2675 'internal-complete-buffer 'ivy-switch-buffer-transformer)
2677 (defun ivy-switch-buffer-transformer (str)
2678 (let ((b (get-buffer str)))
2680 (buffer-file-name b)
2681 (buffer-modified-p b))
2682 (propertize str 'face 'ivy-modified-buffer)
2685 (defun ivy-switch-buffer-occur ()
2686 "Occur function for `ivy-switch-buffer' that uses `ibuffer'."
2688 (concat "\\(" (mapconcat #'regexp-quote ivy--old-cands "\\|") "\\)"))
2689 (new-qualifier `((name . ,cand-regexp))))
2690 (ibuffer nil (buffer-name) new-qualifier)))
2693 (defun ivy-switch-buffer ()
2694 "Switch to another buffer."
2696 (let ((this-command 'ivy-switch-buffer))
2697 (ivy-read "Switch to buffer: " 'internal-complete-buffer
2698 :matcher #'ivy--switch-buffer-matcher
2699 :preselect (buffer-name (other-buffer (current-buffer)))
2700 :action #'ivy--switch-buffer-action
2701 :keymap ivy-switch-buffer-map
2702 :caller 'ivy-switch-buffer)))
2705 (defun ivy-switch-buffer-other-window ()
2706 "Switch to another buffer in another window."
2708 (ivy-read "Switch to buffer in other window: " 'internal-complete-buffer
2709 :preselect (buffer-name (other-buffer (current-buffer)))
2710 :action #'ivy--switch-buffer-other-window-action
2711 :keymap ivy-switch-buffer-map
2712 :caller 'ivy-switch-buffer-other-window))
2715 (defun ivy-recentf ()
2716 "Find a file on `recentf-list'."
2718 (ivy-read "Recentf: " recentf-list
2723 :caller 'ivy-recentf))
2725 (defun ivy-yank-word ()
2726 "Pull next word from buffer into search string."
2731 (le (line-end-position)))
2735 (setq amend (buffer-substring-no-properties pt (point))))))
2737 (insert (replace-regexp-in-string " +" " " amend)))))
2739 (defun ivy-kill-ring-save ()
2740 "Store the current candidates into the kill ring.
2741 If the region is active, forward to `kill-ring-save' instead."
2743 (if (region-active-p)
2744 (call-interactively 'kill-ring-save)
2751 (defun ivy-insert-current ()
2752 "Make the current candidate into current input.
2753 Don't finish completion."
2755 (delete-minibuffer-contents)
2756 (if (and ivy--directory
2757 (string-match "/$" ivy--current))
2758 (insert (substring ivy--current 0 -1))
2759 (insert ivy--current)))
2761 (defun ivy-toggle-fuzzy ()
2762 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
2764 (setq ivy--old-re nil)
2765 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
2766 (setq ivy--regex-function 'ivy--regex-plus)
2767 (setq ivy--regex-function 'ivy--regex-fuzzy)))
2769 (defun ivy-reverse-i-search ()
2770 "Enter a recursive `ivy-read' session using the current history.
2771 The selected history element will be inserted into the minibuffer."
2773 (let ((enable-recursive-minibuffers t)
2774 (history (symbol-value (ivy-state-history ivy-last)))
2776 (ivy-recursive-restore nil))
2777 (ivy-read "Reverse-i-search: "
2781 (setq ivy-last old-last))
2782 (delete-minibuffer-contents)
2783 (insert (substring-no-properties x))
2786 (defun ivy-restrict-to-matches ()
2787 "Restrict candidates to current matches and erase input."
2789 (delete-minibuffer-contents)
2790 (setq ivy--all-candidates
2791 (ivy--filter ivy-text ivy--all-candidates)))
2794 (defvar-local ivy-occur-last nil
2795 "Buffer-local value of `ivy-last'.
2796 Can't re-use `ivy-last' because using e.g. `swiper' in the same
2797 buffer would modify `ivy-last'.")
2799 (defvar ivy-occur-mode-map
2800 (let ((map (make-sparse-keymap)))
2801 (define-key map [mouse-1] 'ivy-occur-click)
2802 (define-key map (kbd "RET") 'ivy-occur-press)
2803 (define-key map (kbd "j") 'ivy-occur-next-line)
2804 (define-key map (kbd "k") 'ivy-occur-previous-line)
2805 (define-key map (kbd "h") 'backward-char)
2806 (define-key map (kbd "l") 'forward-char)
2807 (define-key map (kbd "f") 'ivy-occur-press)
2808 (define-key map (kbd "g") 'ivy-occur-revert-buffer)
2809 (define-key map (kbd "a") 'ivy-occur-read-action)
2810 (define-key map (kbd "o") 'ivy-occur-dispatch)
2811 (define-key map (kbd "c") 'ivy-occur-toggle-calling)
2812 (define-key map (kbd "q") 'quit-window)
2814 "Keymap for Ivy Occur mode.")
2816 (defun ivy-occur-toggle-calling ()
2817 "Toggle `ivy-calling'."
2819 (if (setq ivy-calling (not ivy-calling))
2821 (setq mode-name "Ivy-Occur [calling]")
2823 (setq mode-name "Ivy-Occur"))
2824 (force-mode-line-update))
2826 (defun ivy-occur-next-line (&optional arg)
2827 "Move the cursor down ARG lines.
2828 When `ivy-calling' isn't nil, call `ivy-occur-press'."
2834 (defun ivy-occur-previous-line (&optional arg)
2835 "Move the cursor up ARG lines.
2836 When `ivy-calling' isn't nil, call `ivy-occur-press'."
2838 (forward-line (- arg))
2842 (define-derived-mode ivy-occur-mode fundamental-mode "Ivy-Occur"
2843 "Major mode for output from \\[ivy-occur].
2845 \\{ivy-occur-mode-map}")
2847 (defvar ivy-occur-grep-mode-map
2848 (let ((map (copy-keymap ivy-occur-mode-map)))
2849 (define-key map (kbd "C-x C-q") 'ivy-wgrep-change-to-wgrep-mode)
2851 "Keymap for Ivy Occur Grep mode.")
2853 (define-derived-mode ivy-occur-grep-mode grep-mode "Ivy-Occur"
2854 "Major mode for output from \\[ivy-occur].
2856 \\{ivy-occur-grep-mode-map}")
2858 (defvar ivy--occurs-list nil
2859 "A list of custom occur generators per command.")
2861 (defun ivy-set-occur (cmd occur)
2862 "Assign CMD a custom OCCUR function."
2863 (setq ivy--occurs-list
2864 (plist-put ivy--occurs-list cmd occur)))
2866 (ivy-set-occur 'ivy-switch-buffer 'ivy-switch-buffer-occur)
2867 (ivy-set-occur 'ivy-switch-buffer-other-window 'ivy-switch-buffer-occur)
2869 (defun ivy--occur-insert-lines (cands)
2871 (add-text-properties
2875 help-echo "mouse-1: call ivy-action")
2880 "Stop completion and put the current matches into a new buffer.
2882 The new buffer remembers current action(s).
2884 While in the *ivy-occur* buffer, selecting a candidate with RET or
2885 a mouse click will call the appropriate action for that candidate.
2887 There is no limit on the number of *ivy-occur* buffers."
2889 (if (not (window-minibuffer-p))
2890 (user-error "No completion session is active")
2891 (let* ((caller (ivy-state-caller ivy-last))
2892 (occur-fn (plist-get ivy--occurs-list caller))
2894 (generate-new-buffer
2895 (format "*ivy-occur%s \"%s\"*"
2897 (concat " " (prin1-to-string caller))
2900 (with-current-buffer buffer
2901 (let ((inhibit-read-only t))
2906 (insert (format "%d candidates:\n" (length ivy--old-cands)))
2907 (ivy--occur-insert-lines
2909 (lambda (cand) (concat " " cand))
2911 (setf (ivy-state-text ivy-last) ivy-text)
2912 (setq ivy-occur-last ivy-last)
2913 (setq-local ivy--directory ivy--directory))
2914 (ivy-exit-with-action
2915 `(lambda (_) (pop-to-buffer ,buffer))))))
2917 (defun ivy-occur-revert-buffer ()
2918 "Refresh the buffer making it up-to date with the collection.
2920 Currently only works for `swiper'. In that specific case, the
2921 *ivy-occur* buffer becomes nearly useless as the orignal buffer
2922 is updated, since the line numbers no longer match.
2924 Calling this function is as if you called `ivy-occur' on the
2925 updated original buffer."
2927 (let ((caller (ivy-state-caller ivy-occur-last))
2928 (ivy-last ivy-occur-last))
2929 (cond ((eq caller 'swiper)
2930 (let ((buffer (ivy-state-buffer ivy-occur-last)))
2931 (unless (buffer-live-p buffer)
2932 (error "buffer was killed"))
2933 (let ((inhibit-read-only t))
2935 (funcall (plist-get ivy--occurs-list caller) t))))
2936 ((memq caller '(counsel-git-grep counsel-grep counsel-ag))
2937 (let ((inhibit-read-only t))
2939 (funcall (plist-get ivy--occurs-list caller)))))))
2941 (declare-function wgrep-change-to-wgrep-mode "ext:wgrep")
2943 (defun ivy-wgrep-change-to-wgrep-mode ()
2944 "Forward to `wgrep-change-to-wgrep-mode'."
2946 (if (require 'wgrep nil 'noerror)
2947 (wgrep-change-to-wgrep-mode)
2948 (error "Package wgrep isn't installed")))
2950 (defun ivy-occur-read-action ()
2951 "Select one of the available actions as the current one."
2953 (let ((ivy-last ivy-occur-last))
2956 (defun ivy-occur-dispatch ()
2957 "Call one of the available actions on the current item."
2959 (let* ((state-action (ivy-state-action ivy-occur-last))
2960 (actions (if (symbolp state-action)
2962 (copy-sequence state-action))))
2965 (ivy-occur-read-action)
2967 (setf (ivy-state-action ivy-occur-last) actions))))
2969 (defun ivy-occur-click (event)
2970 "Execute action for the current candidate.
2971 EVENT gives the mouse position."
2973 (let ((window (posn-window (event-end event)))
2974 (pos (posn-point (event-end event))))
2975 (with-current-buffer (window-buffer window)
2977 (ivy-occur-press))))
2979 (declare-function swiper--cleanup "swiper")
2980 (declare-function swiper--add-overlays "swiper")
2981 (defvar ivy-occur-timer nil)
2983 (defun ivy-occur-press ()
2984 "Execute action for the current candidate."
2986 (when (save-excursion
2988 (looking-at "\\(?:./\\| \\)\\(.*\\)$"))
2989 (when (memq (ivy-state-caller ivy-occur-last)
2990 '(swiper counsel-git-grep counsel-grep counsel-ag
2991 counsel-describe-function counsel-describe-variable))
2992 (let ((window (ivy-state-window ivy-occur-last)))
2993 (when (or (null (window-live-p window))
2994 (equal window (selected-window)))
2995 (save-selected-window
2996 (setf (ivy-state-window ivy-occur-last)
2997 (display-buffer (ivy-state-buffer ivy-occur-last)
2998 'display-buffer-pop-up-window))))))
2999 (let* ((ivy-last ivy-occur-last)
3000 (ivy-text (ivy-state-text ivy-last))
3001 (str (buffer-substring
3004 (coll (ivy-state-collection ivy-last))
3005 (action (ivy--get-action ivy-last))
3009 (if (and (consp coll)
3011 (cdr (assoc str coll))
3013 (if (memq (ivy-state-caller ivy-last)
3014 '(swiper counsel-git-grep counsel-grep))
3015 (with-current-buffer (window-buffer (selected-window))
3017 (swiper--add-overlays
3018 (ivy--regex ivy-text)
3019 (line-beginning-position)
3022 (when (timerp ivy-occur-timer)
3023 (cancel-timer ivy-occur-timer))
3024 (setq ivy-occur-timer (run-at-time 1.0 nil 'swiper--cleanup))))))))
3026 (defvar ivy-help-file (let ((default-directory
3028 (file-name-directory load-file-name)
3029 default-directory)))
3030 (if (file-exists-p "ivy-help.org")
3031 (expand-file-name "ivy-help.org")
3032 (if (file-exists-p "doc/ivy-help.org")
3033 (expand-file-name "doc/ivy-help.org"))))
3034 "The file for `ivy-help'.")
3039 (let ((buf (get-buffer "*Ivy Help*")))
3041 (setq buf (get-buffer-create "*Ivy Help*"))
3042 (with-current-buffer buf
3043 (insert-file-contents ivy-help-file)
3046 (goto-char (point-min))))
3047 (if (eq this-command 'ivy-help)
3048 (switch-to-buffer buf)
3050 (pop-to-buffer buf)))
3052 (goto-char (point-min))))
3056 ;;; ivy.el ends here