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 (defcustom ivy-use-ignore-default t
363 "The default policy for user-configured candidate filtering."
365 (const :tag "Ignore ignored always" always)
366 (const :tag "Ignore ignored when others exist" t)
367 (const :tag "Don't ignore" nil)))
369 (defvar ivy-use-ignore t
370 "Store policy for user-configured candidate filtering.
371 This may be changed dynamically by `ivy-toggle-ignore'.
372 Use `ivy-use-ignore-default' for a permanent configuration.")
374 (defvar ivy--default nil
375 "Default initial input.")
377 (defvar ivy--prompt nil
378 "Store the format-style prompt.
379 When non-nil, it should contain at least one %d.")
381 (defvar ivy--prompt-extra ""
382 "Temporary modifications to the prompt.")
384 (defvar ivy--old-re nil
385 "Store the old regexp.")
387 (defvar ivy--old-cands nil
388 "Store the candidates matched by `ivy--old-re'.")
390 (defvar ivy--regex-function 'ivy--regex
391 "Current function for building a regex.")
393 (defvar ivy--subexps 0
394 "Number of groups in the current `ivy--regex'.")
396 (defvar ivy--full-length nil
397 "When :dynamic-collection is non-nil, this can be the total amount of candidates.")
399 (defvar ivy--old-text ""
400 "Store old `ivy-text' for dynamic completion.")
402 (defvar ivy-case-fold-search 'auto
403 "Store the current overriding `case-fold-search'.")
405 (defvar Info-current-file)
408 (unless (fboundp 'defvar-local)
409 (defmacro defvar-local (var val &optional docstring)
410 "Define VAR as a buffer-local variable with default value VAL."
411 (declare (debug defvar) (doc-string 3))
412 (list 'progn (list 'defvar var val docstring)
413 (list 'make-variable-buffer-local (list 'quote var)))))
414 (unless (fboundp 'setq-local)
415 (defmacro setq-local (var val)
416 "Set variable VAR to value VAL in current buffer."
417 (list 'set (list 'make-local-variable (list 'quote var)) val))))
419 (defmacro ivy-quit-and-run (&rest body)
420 "Quit the minibuffer and run BODY afterwards."
422 (put 'quit 'error-message "")
425 (put 'quit 'error-message "Quit")
427 (minibuffer-keyboard-quit)))
429 (defun ivy-exit-with-action (action)
430 "Quit the minibuffer and call ACTION afterwards."
434 (ivy-set-action ',(ivy-state-action ivy-last))))
435 (setq ivy-exit 'done)
438 (defmacro with-ivy-window (&rest body)
439 "Execute BODY in the window from which `ivy-read' was called."
442 `(with-selected-window (ivy--get-window ivy-last)
445 (defun ivy--done (text)
446 "Insert TEXT and exit minibuffer."
447 (if (and ivy--directory
448 (not (eq (ivy-state-history ivy-last) 'grep-files-history)))
449 (insert (setq ivy--current (expand-file-name
450 text ivy--directory)))
451 (insert (setq ivy--current text)))
452 (setq ivy-exit 'done)
457 "Exit the minibuffer with the selected candidate."
459 (delete-minibuffer-contents)
460 (cond ((> ivy--length 0)
461 (ivy--done ivy--current))
462 ((memq (ivy-state-collection ivy-last)
463 '(read-file-name-internal internal-complete-buffer))
464 (if (or (not (eq confirm-nonexistent-file-or-buffer t))
465 (equal " (confirm)" ivy--prompt-extra))
467 (setq ivy--prompt-extra " (confirm)")
470 ((memq (ivy-state-require-match ivy-last)
471 '(nil confirm confirm-after-completion))
472 (ivy--done ivy-text))
474 (setq ivy--prompt-extra " (match required)")
478 (defvar ivy-read-action-format-function 'ivy-read-action-format-default
479 "Function used to transform the actions list into a docstring.")
481 (defun ivy-read-action-format-default (actions)
482 "Create a docstring from ACTIONS.
484 ACTIONS is a list. Each list item is a list of 3 items:
485 key (a string), cmd and doc (a string)."
487 (if (eq this-command 'ivy-read-action)
500 (defun ivy-read-action ()
501 "Change the action to one of the available ones.
503 Return nil for `minibuffer-keyboard-quit' or wrong key during the
504 selection, non-nil otherwise."
506 (let ((actions (ivy-state-action ivy-last)))
507 (if (null (ivy--actionp actions))
509 (let* ((hint (funcall ivy-read-action-format-function (cdr actions)))
510 (resize-mini-windows 'grow-only)
511 (key (string (read-key hint)))
512 (action-idx (cl-position-if
513 (lambda (x) (equal (car x) key))
515 (cond ((string= key "
\a")
518 (message "%s is not bound" key)
522 (setcar actions (1+ action-idx))
523 (ivy-set-action actions)))))))
525 (defun ivy-dispatching-done ()
526 "Select one of the available actions and call `ivy-done'."
528 (when (ivy-read-action)
531 (defun ivy-dispatching-call ()
532 "Select one of the available actions and call `ivy-call'."
534 (let ((actions (copy-sequence (ivy-state-action ivy-last))))
536 (when (ivy-read-action)
538 (ivy-set-action actions))))
540 (defun ivy-build-tramp-name (x)
541 "Reconstruct X into a path.
542 Is is a cons cell, related to `tramp-get-completion-function'."
546 (concat user "@" domain)
549 (declare-function tramp-get-completion-function "tramp")
550 (declare-function Info-find-node "info")
552 (defun ivy-alt-done (&optional arg)
553 "Exit the minibuffer with the selected candidate.
554 When ARG is t, exit with current text, ignoring the candidates."
557 (ivy-immediate-done))
559 (ivy--directory-done))
560 ((eq (ivy-state-collection ivy-last) 'Info-read-node-name-1)
561 (if (member ivy--current '("(./)" "(../)"))
563 (ivy-read "Go to file: " 'read-file-name-internal
566 (expand-file-name x ivy--directory)
572 (defun ivy--directory-done ()
573 "Handle exit from the minibuffer when completing file names."
576 ((equal ivy-text "/sudo::")
577 (setq dir (concat ivy-text ivy--directory))
582 (not (string= ivy--current "./"))
583 (setq dir (ivy-expand-file-if-directory ivy--current)))
586 ((or (and (equal ivy--directory "/")
587 (string-match "\\`[^/]+:.*:.*\\'" ivy-text))
588 (string-match "\\`/[^/]+:.*:.*\\'" ivy-text))
590 ((or (and (equal ivy--directory "/")
592 "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
595 "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
597 (setq ivy-text ivy--current))))
599 "\\`/\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
601 (let ((method (match-string 1 ivy-text))
602 (user (match-string 2 ivy-text))
603 (rest (match-string 3 ivy-text))
606 (dolist (x (tramp-get-completion-function method))
607 (setq res (append res (funcall (car x) (cadr x)))))
608 (setq res (delq nil res))
612 (setq res (cl-delete-duplicates res :test #'equal))
613 (let* ((old-ivy-last ivy-last)
614 (enable-recursive-minibuffers t)
615 (host (ivy-read "user@host: "
616 (mapcar #'ivy-build-tramp-name res)
617 :initial-input rest)))
618 (setq ivy-last old-ivy-last)
620 (setq ivy--directory "/")
621 (ivy--cd (concat "/" method ":" host ":"))))))
625 (defun ivy-expand-file-if-directory (file-name)
626 "Expand FILE-NAME as directory.
627 When this directory doesn't exist, return nil."
628 (when (stringp file-name)
630 ;; Ignore host name must not match method "ssh"
632 (file-name-as-directory
633 (expand-file-name file-name ivy--directory)))))
634 (when (and full-name (file-directory-p full-name))
637 (defcustom ivy-tab-space nil
638 "When non-nil, `ivy-partial-or-done' should insert a space."
641 (defun ivy-partial-or-done ()
642 "Complete the minibuffer text as much as possible.
643 If the text hasn't changed as a result, forward to `ivy-alt-done'."
645 (if (and (eq (ivy-state-collection ivy-last) #'read-file-name-internal)
646 (or (and (equal ivy--directory "/")
647 (string-match "\\`[^/]+:.*\\'" ivy-text))
648 (string-match "\\`/" ivy-text)))
649 (let ((default-directory ivy--directory)
651 (minibuffer-complete)
652 (setq ivy-text (ivy--input))
653 (when (setq dir (ivy-expand-file-if-directory ivy-text))
656 (when (or (eq this-command last-command)
660 (defun ivy-partial ()
661 "Complete the minibuffer text as much as possible."
663 (let* ((parts (or (split-string ivy-text " " t) (list "")))
664 (postfix (car (last parts)))
665 (completion-ignore-case t)
666 (startp (string-match "^\\^" postfix))
667 (new (try-completion (if startp
668 (substring postfix 1)
670 (mapcar (lambda (str)
671 (let ((i (string-match postfix str)))
675 (cond ((eq new t) nil)
676 ((string= new ivy-text) nil)
678 (delete-region (minibuffer-prompt-end) (point-max))
683 (insert (mapconcat #'identity parts " ")
684 (if ivy-tab-space " " ""))
687 (defun ivy-immediate-done ()
688 "Exit the minibuffer with the current input."
690 (delete-minibuffer-contents)
691 (insert (setq ivy--current
693 (expand-file-name ivy-text ivy--directory)
695 (setq ivy-exit 'done)
700 "Resume the last completion session."
702 (if (null (ivy-state-action ivy-last))
703 (user-error "The last session isn't compatible with `ivy-resume'")
704 (when (eq (ivy-state-caller ivy-last) 'swiper)
705 (switch-to-buffer (ivy-state-buffer ivy-last)))
706 (with-current-buffer (ivy-state-buffer ivy-last)
708 (ivy-state-prompt ivy-last)
709 (ivy-state-collection ivy-last)
710 :predicate (ivy-state-predicate ivy-last)
711 :require-match (ivy-state-require-match ivy-last)
712 :initial-input ivy-text
713 :history (ivy-state-history ivy-last)
714 :preselect (unless (eq (ivy-state-collection ivy-last)
715 'read-file-name-internal)
717 :keymap (ivy-state-keymap ivy-last)
718 :update-fn (ivy-state-update-fn ivy-last)
719 :sort (ivy-state-sort ivy-last)
720 :action (ivy-state-action ivy-last)
721 :unwind (ivy-state-unwind ivy-last)
722 :re-builder (ivy-state-re-builder ivy-last)
723 :matcher (ivy-state-matcher ivy-last)
724 :dynamic-collection (ivy-state-dynamic-collection ivy-last)
725 :caller (ivy-state-caller ivy-last)))))
727 (defvar-local ivy-calling nil
728 "When non-nil, call the current action when `ivy--index' changes.")
730 (defun ivy-set-index (index)
731 "Set `ivy--index' to INDEX."
732 (setq ivy--index index)
737 (defun ivy-beginning-of-buffer ()
738 "Select the first completion candidate."
742 (defun ivy-end-of-buffer ()
743 "Select the last completion candidate."
745 (ivy-set-index (1- ivy--length)))
747 (defun ivy-scroll-up-command ()
748 "Scroll the candidates upward by the minibuffer height."
750 (ivy-set-index (min (1- (+ ivy--index ivy-height))
753 (defun ivy-scroll-down-command ()
754 "Scroll the candidates downward by the minibuffer height."
756 (ivy-set-index (max (1+ (- ivy--index ivy-height))
759 (defun ivy-minibuffer-grow ()
760 "Grow the minibuffer window by 1 line."
762 (setq-local max-mini-window-height
763 (cl-incf ivy-height)))
765 (defun ivy-minibuffer-shrink ()
766 "Shrink the minibuffer window by 1 line."
768 (unless (<= ivy-height 2)
769 (setq-local max-mini-window-height
770 (cl-decf ivy-height))
771 (window-resize (selected-window) -1)))
773 (defun ivy-next-line (&optional arg)
774 "Move cursor vertically down ARG candidates."
776 (setq arg (or arg 1))
777 (let ((index (+ ivy--index arg)))
778 (if (> index (1- ivy--length))
780 (ivy-beginning-of-buffer)
781 (ivy-set-index (1- ivy--length)))
782 (ivy-set-index index))))
784 (defun ivy-next-line-or-history (&optional arg)
785 "Move cursor vertically down ARG candidates.
786 If the input is empty, select the previous history element instead."
788 (if (string= ivy-text "")
789 (ivy-previous-history-element 1)
790 (ivy-next-line arg)))
792 (defun ivy-previous-line (&optional arg)
793 "Move cursor vertically up ARG candidates."
795 (setq arg (or arg 1))
796 (let ((index (- ivy--index arg)))
801 (ivy-set-index index))))
803 (defun ivy-previous-line-or-history (arg)
804 "Move cursor vertically up ARG candidates.
805 If the input is empty, select the previous history element instead."
807 (when (string= ivy-text "")
808 (ivy-previous-history-element 1))
809 (ivy-previous-line arg))
811 (defun ivy-toggle-calling ()
812 "Flip `ivy-calling'."
814 (when (setq ivy-calling (not ivy-calling))
817 (defun ivy-toggle-ignore ()
818 "Toggle user-configured candidate filtering."
823 (or ivy-use-ignore-default t)))
825 (setq ivy--old-cands nil))
827 (defun ivy--get-action (state)
828 "Get the action function from STATE."
829 (let ((action (ivy-state-action state)))
831 (if (functionp action)
833 (cadr (nth (car action) action))))))
835 (defun ivy--get-window (state)
836 "Get the window from STATE."
837 (if (ivy-state-p state)
838 (let ((window (ivy-state-window state)))
839 (if (window-live-p window)
841 (if (= (length (window-list)) 1)
846 (defun ivy--actionp (x)
847 "Return non-nil when X is a list of actions."
848 (and x (listp x) (not (eq (car x) 'closure))))
850 (defun ivy-next-action ()
851 "When the current action is a list, scroll it forwards."
853 (let ((action (ivy-state-action ivy-last)))
854 (when (ivy--actionp action)
855 (unless (>= (car action) (1- (length action)))
856 (cl-incf (car action))))))
858 (defun ivy-prev-action ()
859 "When the current action is a list, scroll it backwards."
861 (let ((action (ivy-state-action ivy-last)))
862 (when (ivy--actionp action)
863 (unless (<= (car action) 1)
864 (cl-decf (car action))))))
866 (defun ivy-action-name ()
867 "Return the name associated with the current action."
868 (let ((action (ivy-state-action ivy-last)))
869 (if (ivy--actionp action)
873 (nth 2 (nth (car action) action)))
876 (defvar ivy-inhibit-action nil
877 "When non-nil, `ivy-call' does nothing.
881 (let* ((ivy-inhibit-action t)
882 (str (counsel-locate \"lispy.el\")))
883 ;; do whatever with str - the corresponding file will not be opened
887 "Call the current action without exiting completion."
889 (unless ivy-inhibit-action
890 (let ((action (ivy--get-action ivy-last)))
892 (let* ((collection (ivy-state-collection ivy-last))
893 (x (if (and (consp collection)
894 (consp (car collection)))
895 (cdr (assoc ivy--current collection))
896 (if (equal ivy--current "")
899 (prog1 (funcall action x)
900 (unless (or (eq ivy-exit 'done)
901 (equal (selected-window)
902 (active-minibuffer-window))
903 (null (active-minibuffer-window)))
904 (select-window (active-minibuffer-window)))))))))
906 (defun ivy-next-line-and-call (&optional arg)
907 "Move cursor vertically down ARG candidates.
908 Call the permanent action if possible."
914 (defun ivy-previous-line-and-call (&optional arg)
915 "Move cursor vertically down ARG candidates.
916 Call the permanent action if possible."
918 (ivy-previous-line arg)
922 (defun ivy-previous-history-element (arg)
923 "Forward to `previous-history-element' with ARG."
925 (previous-history-element arg)
928 (ivy--maybe-scroll-history))
930 (defun ivy-next-history-element (arg)
931 "Forward to `next-history-element' with ARG."
933 (if (and (= minibuffer-history-position 0)
936 (insert ivy--default)
937 (when (and (with-ivy-window (derived-mode-p 'prog-mode))
938 (eq (ivy-state-caller ivy-last) 'swiper)
939 (not (file-exists-p ivy--default))
940 (not (ffap-url-p ivy--default))
941 (not (ivy-state-dynamic-collection ivy-last))
942 (> (point) (minibuffer-prompt-end)))
945 (goto-char (minibuffer-prompt-end))
947 (forward-char (+ 2 (length ivy--default)))))
948 (next-history-element arg))
951 (ivy--maybe-scroll-history))
953 (defvar ivy-ffap-url-functions nil
954 "List of functions that check if the point is on a URL.")
956 (defun ivy--cd-maybe ()
957 "Check if the current input points to a different directory.
958 If so, move to that directory, while keeping only the file name."
960 (let ((input (ivy--input))
962 (if (setq url (or (ffap-url-p input)
967 ivy-ffap-url-functions
968 :initial-value nil))))
969 (ivy-exit-with-action
971 (funcall ffap-url-fetcher url)))
972 (setq input (expand-file-name input))
973 (let ((file (file-name-nondirectory input))
974 (dir (expand-file-name (file-name-directory input))))
975 (if (string= dir ivy--directory)
977 (delete-minibuffer-contents)
982 (defun ivy--maybe-scroll-history ()
983 "If the selected history element has an index, scroll there."
984 (let ((idx (ignore-errors
986 (minibuffer-prompt-end)
990 (setq ivy--index idx))))
993 "When completing file names, move to directory DIR."
994 (if (null ivy--directory)
996 (setq ivy--old-cands nil)
997 (setq ivy--old-re nil)
999 (setq ivy--all-candidates
1000 (ivy--sorted-files (setq ivy--directory dir)))
1002 (delete-minibuffer-contents)))
1004 (defun ivy-backward-delete-char ()
1005 "Forward to `backward-delete-char'.
1006 On error (read-only), call `ivy-on-del-error-function'."
1008 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
1010 (ivy--cd (file-name-directory
1011 (directory-file-name
1016 (backward-delete-char 1)
1018 (when ivy-on-del-error-function
1019 (funcall ivy-on-del-error-function))))))
1021 (defun ivy-delete-char (arg)
1022 "Forward to `delete-char' ARG."
1024 (unless (= (point) (line-end-position))
1027 (defun ivy-forward-char (arg)
1028 "Forward to `forward-char' ARG."
1030 (unless (= (point) (line-end-position))
1031 (forward-char arg)))
1033 (defun ivy-kill-word (arg)
1034 "Forward to `kill-word' ARG."
1036 (unless (= (point) (line-end-position))
1039 (defun ivy-kill-line ()
1040 "Forward to `kill-line'."
1043 (kill-region (minibuffer-prompt-end) (point))
1046 (defun ivy-backward-kill-word ()
1047 "Forward to `backward-kill-word'."
1049 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
1051 (ivy--cd (file-name-directory
1052 (directory-file-name
1059 (delete-region (point) pt)))))
1061 (defvar ivy--regexp-quote 'regexp-quote
1062 "Store the regexp quoting state.")
1064 (defun ivy-toggle-regexp-quote ()
1065 "Toggle the regexp quoting."
1067 (setq ivy--old-re nil)
1068 (cl-rotatef ivy--regex-function ivy--regexp-quote))
1070 (defvar avy-all-windows)
1073 (defvar avy-keys-alist)
1075 (defvar avy-styles-alist)
1076 (declare-function avy--process "ext:avy")
1077 (declare-function avy--style-fn "ext:avy")
1079 (eval-after-load 'avy
1080 '(add-to-list 'avy-styles-alist '(ivy-avy . pre)))
1083 "Jump to one of the current ivy candidates."
1085 (unless (require 'avy nil 'noerror)
1086 (error "Package avy isn't installed"))
1087 (let* ((avy-all-windows nil)
1088 (avy-keys (or (cdr (assq 'ivy-avy avy-keys-alist))
1090 (avy-style (or (cdr (assq 'ivy-avy
1100 (goto-char (point-min))
1102 (while (< (point) (point-max))
1108 (setq avy-action #'identity)
1110 (nreverse candidates)
1111 (avy--style-fn avy-style)))))
1112 (when (numberp candidate)
1113 (ivy-set-index (- (line-number-at-pos candidate) 2))
1117 (defun ivy-sort-file-function-default (x y)
1118 "Compare two files X and Y.
1119 Prioritize directories."
1120 (if (get-text-property 0 'dirp x)
1121 (if (get-text-property 0 'dirp y)
1124 (if (get-text-property 0 'dirp y)
1128 (defcustom ivy-sort-functions-alist
1129 '((read-file-name-internal . ivy-sort-file-function-default)
1130 (internal-complete-buffer . nil)
1131 (counsel-git-grep-function . nil)
1132 (Man-goto-section . nil)
1135 "An alist of sorting functions for each collection function.
1136 Interactive functions that call completion fit in here as well.
1138 Nil means no sorting, which is useful to turn off the sorting for
1139 functions that have candidates in the natural buffer order, like
1140 `org-refile' or `Man-goto-section'.
1142 The entry associated with t is used for all fall-through cases.
1144 See also `ivy-sort-max-size'."
1148 (const :tag "Fall-through" t)
1149 (symbol :tag "Collection"))
1151 (const :tag "Plain sort" string-lessp)
1152 (const :tag "File sort" ivy-sort-file-function-default)
1153 (const :tag "No sort" nil)
1154 (function :tag "Custom function")))
1157 (defvar ivy-index-functions-alist
1158 '((swiper . ivy-recompute-index-swiper)
1159 (swiper-multi . ivy-recompute-index-swiper)
1160 (counsel-git-grep . ivy-recompute-index-swiper)
1161 (counsel-grep . ivy-recompute-index-swiper-async)
1162 (t . ivy-recompute-index-zero))
1163 "An alist of index recomputing functions for each collection function.
1164 When the input changes, the appropriate function returns an
1165 integer - the index of the matched candidate that should be
1168 (defvar ivy-re-builders-alist
1169 '((t . ivy--regex-plus))
1170 "An alist of regex building functions for each collection function.
1172 Each key is (in order of priority):
1173 1. The actual collection function, e.g. `read-file-name-internal'.
1174 2. The symbol passed by :caller into `ivy-read'.
1178 Each value is a function that should take a string and return a
1179 valid regex or a regex sequence (see below).
1181 Possible choices: `ivy--regex', `regexp-quote',
1182 `ivy--regex-plus', `ivy--regex-fuzzy'.
1184 If a function returns a list, it should format like this:
1185 '((\"matching-regexp\" . t) (\"non-matching-regexp\") ...).
1187 The matches will be filtered in a sequence, you can mix the
1188 regexps that should match and that should not match as you
1191 (defvar ivy-initial-inputs-alist
1192 '((org-refile . "^")
1193 (org-agenda-refile . "^")
1194 (org-capture-refile . "^")
1196 (counsel-describe-function . "^")
1197 (counsel-describe-variable . "^")
1200 "Command to initial input table.")
1202 (defcustom ivy-sort-max-size 30000
1203 "Sorting won't be done for collections larger than this."
1206 (defun ivy--sorted-files (dir)
1207 "Return the list of files in DIR.
1208 Directories come first."
1209 (let* ((default-directory dir)
1210 (seq (all-completions "" 'read-file-name-internal))
1214 (setq seq (delete "./" (delete "../" seq)))
1215 (when (eq (setq sort-fn (cdr (assoc 'read-file-name-internal
1216 ivy-sort-functions-alist)))
1217 #'ivy-sort-file-function-default)
1218 (setq seq (mapcar (lambda (x)
1219 (propertize x 'dirp (string-match-p "/\\'" x)))
1222 (setq seq (cl-sort seq sort-fn)))
1223 (dolist (dir ivy-extra-directories)
1227 (defvar ivy-recursive-restore t
1228 "When non-nil, restore the above state when exiting the minibuffer.
1229 This variable is let-bound to nil by functions that take care of
1230 the restoring themselves.")
1233 (cl-defun ivy-read (prompt collection
1235 predicate require-match initial-input
1236 history preselect keymap update-fn sort
1237 action unwind re-builder matcher dynamic-collection caller)
1238 "Read a string in the minibuffer, with completion.
1240 PROMPT is a format string, normally ending in a colon and a
1241 space; %d anywhere in the string is replaced by the current
1242 number of matching candidates. For the literal % character,
1243 escape it with %%. See also `ivy-count-format'.
1245 COLLECTION is either a list of strings, a function, an alist, or
1248 If INITIAL-INPUT is not nil, then insert that input in the
1249 minibuffer initially.
1251 KEYMAP is composed with `ivy-minibuffer-map'.
1253 If PRESELECT is not nil, then select the corresponding candidate
1254 out of the ones that match the INITIAL-INPUT.
1256 UPDATE-FN is called each time the current candidate(s) is changed.
1258 When SORT is t, use `ivy-sort-functions-alist' for sorting.
1260 ACTION is a lambda function to call after selecting a result. It
1261 takes a single string argument.
1263 UNWIND is a lambda function to call before exiting.
1265 RE-BUILDER is a lambda function to call to transform text into a
1268 MATCHER is to override matching.
1270 DYNAMIC-COLLECTION is a boolean to specify if the list of
1271 candidates is updated after each input by calling COLLECTION.
1273 CALLER is a symbol to uniquely identify the caller to `ivy-read'.
1274 It is used, along with COLLECTION, to determine which
1275 customizations apply to the current completion session."
1276 (let ((extra-actions (delete-dups
1277 (append (plist-get ivy--actions-list t)
1278 (plist-get ivy--actions-list this-command)
1279 (plist-get ivy--actions-list caller)))))
1282 (cond ((functionp action)
1284 ("o" ,action "default")
1288 ("o" identity "default")
1291 (delete-dups (append action extra-actions)))))))
1292 (let ((extra-sources (plist-get ivy--sources-list caller)))
1295 (setq ivy--extra-candidates nil)
1296 (dolist (source extra-sources)
1297 (cond ((equal source '(original-source))
1298 (setq ivy--extra-candidates
1299 (cons source ivy--extra-candidates)))
1300 ((null (cdr source))
1301 (setq ivy--extra-candidates
1303 (list (car source) (funcall (car source)))
1304 ivy--extra-candidates))))))
1305 (setq ivy--extra-candidates '((original-source)))))
1306 (let ((recursive-ivy-last (and (active-minibuffer-window) ivy-last))
1308 (plist-get ivy--display-transformers-list
1309 (or caller (and (functionp collection)
1314 :collection collection
1315 :predicate predicate
1316 :require-match require-match
1317 :initial-input initial-input
1319 :preselect preselect
1321 :update-fn update-fn
1324 :window (selected-window)
1325 :buffer (current-buffer)
1327 :re-builder re-builder
1329 :dynamic-collection dynamic-collection
1330 :display-transformer-fn transformer-fn
1332 (ivy--reset-state ivy-last)
1335 (minibuffer-with-setup-hook
1336 #'ivy--minibuffer-setup
1337 (let* ((hist (or history 'ivy-history))
1338 (minibuffer-completion-table collection)
1339 (minibuffer-completion-predicate predicate)
1340 (resize-mini-windows (cond
1341 ((display-graphic-p) nil)
1342 ((null resize-mini-windows) 'grow-only)
1343 (t resize-mini-windows))))
1344 (read-from-minibuffer
1346 (ivy-state-initial-input ivy-last)
1347 (make-composed-keymap keymap ivy-minibuffer-map)
1350 (when (eq ivy-exit 'done)
1351 (let ((item (if ivy--directory
1354 (unless (equal item "")
1355 (set hist (cons (propertize item 'ivy-index ivy--index)
1357 (cdr (symbol-value hist))))))))
1359 (remove-hook 'post-command-hook #'ivy--exhibit)
1360 (when (setq unwind (ivy-state-unwind ivy-last))
1362 (unless (eq ivy-exit 'done)
1363 (when recursive-ivy-last
1364 (ivy--reset-state (setq ivy-last recursive-ivy-last)))))
1366 (when (and recursive-ivy-last
1367 ivy-recursive-restore)
1368 (ivy--reset-state (setq ivy-last recursive-ivy-last))))))
1370 (defun ivy--reset-state (state)
1371 "Reset the ivy to STATE.
1372 This is useful for recursive `ivy-read'."
1373 (let ((prompt (or (ivy-state-prompt state) ""))
1374 (collection (ivy-state-collection state))
1375 (predicate (ivy-state-predicate state))
1376 (history (ivy-state-history state))
1377 (preselect (ivy-state-preselect state))
1378 (sort (ivy-state-sort state))
1379 (re-builder (ivy-state-re-builder state))
1380 (dynamic-collection (ivy-state-dynamic-collection state))
1381 (initial-input (ivy-state-initial-input state))
1382 (require-match (ivy-state-require-match state))
1383 (caller (ivy-state-caller state)))
1384 (unless initial-input
1385 (setq initial-input (cdr (assoc this-command
1386 ivy-initial-inputs-alist))))
1387 (setq ivy--directory nil)
1388 (setq ivy-case-fold-search 'auto)
1389 (setq ivy--regex-function
1391 (and (functionp collection)
1392 (cdr (assoc collection ivy-re-builders-alist)))
1394 (cdr (assoc caller ivy-re-builders-alist)))
1395 (cdr (assoc this-command ivy-re-builders-alist))
1396 (cdr (assoc t ivy-re-builders-alist))
1398 (setq ivy--subexps 0)
1399 (setq ivy--regexp-quote 'regexp-quote)
1400 (setq ivy--old-text "")
1401 (setq ivy--full-length nil)
1403 (setq ivy-calling nil)
1404 (setq ivy-use-ignore ivy-use-ignore-default)
1406 (cond ((eq collection 'Info-read-node-name-1)
1407 (if (equal Info-current-file "dir")
1409 (mapcar (lambda (x) (format "(%s)" x))
1410 (cl-delete-duplicates
1411 (all-completions "(" collection predicate)
1413 (setq coll (all-completions "" collection predicate))))
1414 ((eq collection 'read-file-name-internal)
1415 (if (and initial-input (file-directory-p initial-input))
1417 (setq ivy--directory initial-input)
1418 (setq initial-input nil))
1419 (setq ivy--directory default-directory))
1422 (let ((preselect-directory (file-name-directory preselect)))
1423 (unless (or (null preselect-directory)
1424 (string= preselect-directory
1426 (setq ivy--directory preselect-directory))
1428 (ivy-state-preselect state)
1429 (setq preselect (file-name-nondirectory preselect)))))
1430 (setq coll (ivy--sorted-files ivy--directory))
1432 (unless (or require-match
1433 (equal initial-input default-directory)
1434 (equal initial-input ""))
1435 (setq coll (cons initial-input coll)))
1436 (unless (and (ivy-state-action ivy-last)
1437 (not (equal (ivy--get-action ivy-last) 'identity)))
1438 (setq initial-input nil))))
1439 ((eq collection 'internal-complete-buffer)
1440 (setq coll (ivy--buffer-list "" ivy-use-virtual-buffers predicate)))
1442 (setq coll (funcall collection ivy-text)))
1443 ((or (functionp collection)
1444 (byte-code-function-p collection)
1445 (vectorp collection)
1446 (and (consp collection) (listp (car collection)))
1447 (hash-table-p collection)
1448 (and (listp collection) (symbolp (car collection))))
1449 (setq coll (all-completions "" collection predicate)))
1451 (setq coll collection)))
1453 (if (and (functionp collection)
1454 (setq sort-fn (assoc collection ivy-sort-functions-alist)))
1455 (when (and (setq sort-fn (cdr sort-fn))
1456 (not (eq collection 'read-file-name-internal)))
1457 (setq coll (cl-sort coll sort-fn)))
1458 (unless (eq history 'org-refile-history)
1459 (if (and (setq sort-fn (cdr (assoc t ivy-sort-functions-alist)))
1460 (<= (length coll) ivy-sort-max-size))
1461 (setq coll (cl-sort (copy-sequence coll) sort-fn))))))
1462 (setq coll (ivy--set-candidates coll))
1464 (unless (or (and require-match
1465 (not (eq collection 'internal-complete-buffer)))
1467 (let ((re (regexp-quote preselect)))
1468 (cl-find-if (lambda (x) (string-match re x))
1470 (setq coll (cons preselect coll))))
1471 (setq ivy--old-re nil)
1472 (setq ivy--old-cands nil)
1473 (when (integerp preselect)
1474 (setq ivy--old-re "")
1475 (setq ivy--index preselect))
1477 ;; Needed for anchor to work
1478 (setq ivy--old-cands coll)
1479 (setq ivy--old-cands (ivy--filter initial-input coll)))
1480 (setq ivy--all-candidates coll)
1481 (unless (integerp preselect)
1482 (setq ivy--index (or
1483 (and dynamic-collection
1486 (ivy--preselect-index
1494 (if (region-active-p)
1498 (ivy-thing-at-point)))
1500 (cond ((string-match "%.*d" prompt)
1502 ((null ivy-count-format)
1504 "`ivy-count-format' can't be nil. Set it to an empty string instead"))
1505 ((string-match "%d.*%d" ivy-count-format)
1506 (let ((w (length (number-to-string
1507 (length ivy--all-candidates))))
1508 (s (copy-sequence ivy-count-format)))
1509 (string-match "%d" s)
1511 (string-match "%d" s (match-end 0))
1512 (setq s (replace-match (format "%%-%dd" w) nil nil s))
1513 (string-match "%d" s)
1514 (concat (replace-match (format "%%%dd" w) nil nil s)
1516 ((string-match "%.*d" ivy-count-format)
1517 (concat ivy-count-format prompt))
1522 (setf (ivy-state-initial-input ivy-last) initial-input)))
1525 (defun ivy-completing-read (prompt collection
1526 &optional predicate require-match initial-input
1527 history def inherit-input-method)
1528 "Read a string in the minibuffer, with completion.
1530 This interface conforms to `completing-read' and can be used for
1531 `completing-read-function'.
1533 PROMPT is a string that normally ends in a colon and a space.
1534 COLLECTION is either a list of strings, an alist, an obarray, or a hash table.
1535 PREDICATE limits completion to a subset of COLLECTION.
1536 REQUIRE-MATCH is a boolean value. See `completing-read'.
1537 INITIAL-INPUT is a string inserted into the minibuffer initially.
1538 HISTORY is a list of previously selected inputs.
1539 DEF is the default value.
1540 INHERIT-INPUT-METHOD is currently ignored."
1541 (if (memq this-command '(tmm-menubar tmm-shortcut))
1542 (completing-read-default prompt collection
1543 predicate require-match
1544 initial-input history
1545 def inherit-input-method)
1546 ;; See the doc of `completing-read'.
1547 (when (consp history)
1548 (when (numberp (cdr history))
1549 (setq initial-input (nth (1- (cdr history))
1550 (symbol-value (car history)))))
1551 (setq history (car history)))
1552 (ivy-read (replace-regexp-in-string "%" "%%" prompt)
1554 :predicate predicate
1555 :require-match require-match
1556 :initial-input (if (consp initial-input)
1558 (if (and (stringp initial-input)
1559 (string-match "\\+" initial-input))
1560 (replace-regexp-in-string
1561 "\\+" "\\\\+" initial-input)
1563 :preselect (if (listp def) (car def) def)
1567 (let ((sort (or (assoc this-command ivy-sort-functions-alist)
1568 (assoc t ivy-sort-functions-alist))))
1573 (defvar ivy-completion-beg nil
1574 "Completion bounds start.")
1576 (defvar ivy-completion-end nil
1577 "Completion bounds end.")
1579 (defun ivy-completion-in-region-action (str)
1580 "Insert STR, erasing the previous one.
1581 The previous string is between `ivy-completion-beg' and `ivy-completion-end'."
1584 (when ivy-completion-beg
1587 ivy-completion-end))
1588 (setq ivy-completion-beg
1589 (move-marker (make-marker) (point)))
1591 (setq ivy-completion-end
1592 (move-marker (make-marker) (point))))))
1594 (defun ivy-completion-common-length (str)
1595 "Return the length of the first 'completions-common-part face in STR."
1598 (while (and (<= pos len)
1599 (let ((prop (get-text-property pos 'face str)))
1600 (not (eq 'completions-common-part
1601 (if (listp prop) (car prop) prop)))))
1602 (setq pos (1+ pos)))
1604 (or (next-single-property-change pos 'face str) len)
1607 (defun ivy-completion-in-region (start end collection &optional predicate)
1608 "An Ivy function suitable for `completion-in-region-function'."
1609 (let* ((enable-recursive-minibuffers t)
1610 (str (buffer-substring-no-properties start end))
1611 (completion-ignore-case case-fold-search)
1613 (completion-all-completions str collection predicate (- end start))))
1615 (message "No matches")
1617 (setq ivy-completion-beg (- end (ivy-completion-common-length (car comps))))
1618 (setq ivy-completion-end end)
1619 (if (null (cdr comps))
1620 (if (string= str (car comps))
1621 (message "Sole match")
1622 (setf (ivy-state-window ivy-last) (selected-window))
1623 (ivy-completion-in-region-action
1624 (substring-no-properties
1626 (let* ((w (1+ (floor (log (length comps) 10))))
1627 (ivy-count-format (if (string= ivy-count-format "")
1629 (format "%%-%dd " w)))
1630 (prompt (format "(%s): " str)))
1632 (ivy-read (if (string= ivy-count-format "")
1634 (replace-regexp-in-string "%" "%%" prompt))
1635 ;; remove 'completions-first-difference face
1636 (mapcar #'substring-no-properties comps)
1637 :predicate predicate
1638 :action #'ivy-completion-in-region-action
1642 (defcustom ivy-do-completion-in-region t
1643 "When non-nil `ivy-mode' will set `completion-in-region-function'."
1647 (define-minor-mode ivy-mode
1648 "Toggle Ivy mode on or off.
1649 Turn Ivy mode on if ARG is positive, off otherwise.
1650 Turning on Ivy mode sets `completing-read-function' to
1651 `ivy-completing-read'.
1656 Minibuffer bindings:
1657 \\{ivy-minibuffer-map}"
1660 :keymap ivy-mode-map
1664 (setq completing-read-function 'ivy-completing-read)
1665 (when ivy-do-completion-in-region
1666 (setq completion-in-region-function 'ivy-completion-in-region)))
1667 (setq completing-read-function 'completing-read-default)
1668 (setq completion-in-region-function 'completion--in-region)))
1670 (defun ivy--preselect-index (preselect candidates)
1671 "Return the index of PRESELECT in CANDIDATES."
1672 (cond ((integerp preselect)
1674 ((cl-position preselect candidates :test #'equal))
1675 ((stringp preselect)
1676 (let ((re preselect))
1679 (string-match re x))
1684 (defvar ivy--regex-hash
1685 (make-hash-table :test #'equal)
1686 "Store pre-computed regex.")
1688 (defun ivy--split (str)
1689 "Split STR into a list by single spaces.
1690 The remaining spaces stick to their left.
1691 This allows to \"quote\" N spaces by inputting N+1 spaces."
1692 (let ((len (length str))
1697 (while (and (string-match " +" str start1)
1699 (if (and (> (match-beginning 0) 2)
1700 (string= "[^" (substring
1702 (- (match-beginning 0) 2)
1703 (match-beginning 0))))
1705 (setq start1 (match-end 0))
1707 (setq match-len (- (match-end 0) (match-beginning 0)))
1711 (setq start1 start0)
1713 (push (substring str start1 (match-beginning 0)) res)
1714 (setq start1 (match-end 0)))
1715 (setq str (replace-match
1716 (make-string (1- match-len) ?\ )
1718 (setq start0 (or start0 start1))
1719 (setq start1 (1- (match-end 0))))))
1721 (push (substring str start0) res)
1722 (setq s (substring str start1))
1723 (unless (= (length s) 0)
1727 (defun ivy--regex (str &optional greedy)
1728 "Re-build regex pattern from STR in case it has a space.
1729 When GREEDY is non-nil, join words in a greedy way."
1730 (let ((hashed (unless greedy
1731 (gethash str ivy--regex-hash))))
1734 (setq ivy--subexps (car hashed)))
1735 (when (string-match "\\([^\\]\\|^\\)\\\\$" str)
1736 (setq str (substring str 0 -1)))
1738 (let ((subs (ivy--split str)))
1739 (if (= (length subs) 1)
1741 (setq ivy--subexps 0)
1744 (setq ivy--subexps (length subs))
1747 (if (string-match "\\`\\\\([^?].*\\\\)\\'" x)
1749 (format "\\(%s\\)" x)))
1754 ivy--regex-hash)))))
1756 (defun ivy--regex-ignore-order--part (str &optional discard)
1757 "Re-build regex from STR by splitting at spaces.
1758 Ignore the order of each group."
1759 (let* ((subs (split-string str " +" t))
1760 (len (length subs)))
1765 (mapcar (lambda (x) (cons x (not discard)))
1768 (defun ivy--regex-ignore-order (str)
1769 "Re-build regex from STR by splitting at spaces.
1770 Ignore the order of each group. Everything before \"!\" should
1771 match. Everything after \"!\" should not match."
1772 (let ((parts (split-string str "!" t)))
1773 (cl-case (length parts)
1777 (if (string= (substring str 0 1) "!")
1779 (ivy--regex-ignore-order--part (car parts) t))
1780 (ivy--regex-ignore-order--part (car parts))))
1783 (ivy--regex-ignore-order--part (car parts))
1784 (ivy--regex-ignore-order--part (cadr parts) t)))
1785 (t (error "Unexpected: use only one !")))))
1787 (defun ivy--regex-plus (str)
1788 "Build a regex sequence from STR.
1789 Spaces are wild card characters, everything before \"!\" should
1790 match. Everything after \"!\" should not match."
1791 (let ((parts (split-string str "!" t)))
1792 (cl-case (length parts)
1796 (if (string= (substring str 0 1) "!")
1798 (list (ivy--regex (car parts))))
1799 (ivy--regex (car parts))))
1802 (cons (ivy--regex (car parts)) t)
1803 (mapcar #'list (split-string (cadr parts) " " t))))
1804 (t (error "Unexpected: use only one !")))))
1806 (defun ivy--regex-fuzzy (str)
1807 "Build a regex sequence from STR.
1808 Insert .* between each char."
1809 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1811 (concat (match-string 1 str)
1814 (format "\\(%c\\)" x))
1815 (string-to-list (match-string 2 str)) ".*")
1816 (match-string 3 str))
1817 (setq ivy--subexps (length (match-string 2 str))))
1820 (defcustom ivy-fixed-height-minibuffer nil
1821 "When non nil, fix the height of the minibuffer during ivy
1822 completion at `ivy-height'. This effectively sets the minimum
1823 height at this level and tries to ensure that it does not change
1824 depending on the number of candidates."
1829 (defun ivy--minibuffer-setup ()
1830 "Setup ivy completion in the minibuffer."
1831 (set (make-local-variable 'completion-show-inline-help) nil)
1832 (set (make-local-variable 'minibuffer-default-add-function)
1834 (list ivy--default)))
1835 (set (make-local-variable 'inhibit-field-text-motion) nil)
1836 (when (display-graphic-p)
1837 (setq truncate-lines t))
1838 (setq-local max-mini-window-height ivy-height)
1839 (when ivy-fixed-height-minibuffer
1840 (set-window-text-height (selected-window) ivy-height))
1841 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1842 ;; show completions with empty input
1845 (defun ivy--input ()
1846 "Return the current minibuffer input."
1847 ;; assume one-line minibuffer input
1848 (buffer-substring-no-properties
1849 (minibuffer-prompt-end)
1850 (line-end-position)))
1852 (defun ivy--cleanup ()
1853 "Delete the displayed completion candidates."
1855 (goto-char (minibuffer-prompt-end))
1856 (delete-region (line-end-position) (point-max))))
1858 (defun ivy--insert-prompt ()
1859 "Update the prompt according to `ivy--prompt'."
1861 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1862 counsel-find-symbol))
1863 (setq ivy--prompt-extra ""))
1865 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1867 (setq head (match-string 1 ivy--prompt))
1869 (setq head (substring ivy--prompt 0 -1))
1871 (let ((inhibit-read-only t)
1872 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1875 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1876 (> (minibuffer-depth) 1))
1877 (format "[%d] " (minibuffer-depth))
1880 (if (string-match "%d.*%d" ivy-count-format)
1883 (or (and (ivy-state-dynamic-collection ivy-last)
1887 (or (and (ivy-state-dynamic-collection ivy-last)
1892 (d-str (if ivy--directory
1893 (abbreviate-file-name ivy--directory)
1896 (goto-char (point-min))
1897 (delete-region (point-min) (minibuffer-prompt-end))
1898 (if (> (+ (mod (+ (length n-str) (length d-str)) (window-width))
1901 (setq n-str (concat n-str "\n" d-str))
1902 (setq n-str (concat n-str d-str)))
1903 (when ivy-add-newline-after-prompt
1904 (setq n-str (concat n-str "\n")))
1905 (let ((regex (format "\\([^\n]\\{%d\\}\\)[^\n]" (window-width))))
1906 (while (string-match regex n-str)
1907 (setq n-str (replace-match (concat (match-string 1 n-str) "\n") nil t n-str 1))))
1908 (set-text-properties 0 (length n-str)
1909 `(face minibuffer-prompt ,@std-props)
1911 (ivy--set-match-props n-str "confirm"
1912 `(face ivy-confirm-face ,@std-props))
1913 (ivy--set-match-props n-str "match required"
1914 `(face ivy-match-required-face ,@std-props))
1916 ;; get out of the prompt area
1917 (constrain-to-field nil (point-max))))))
1919 (defun ivy--set-match-props (str match props)
1920 "Set STR text properties that match MATCH to PROPS."
1921 (when (string-match match str)
1922 (set-text-properties
1928 (defvar inhibit-message)
1930 (defun ivy--sort-maybe (collection)
1931 "Sort COLLECTION if needed."
1932 (let ((sort (ivy-state-sort ivy-last))
1936 (let ((sort-fn (cond ((functionp sort)
1938 ((setq entry (assoc (ivy-state-collection ivy-last)
1939 ivy-sort-functions-alist))
1942 (cdr (assoc t ivy-sort-functions-alist))))))
1943 (if (functionp sort-fn)
1944 (cl-sort (copy-sequence collection) sort-fn)
1947 (defun ivy--magic-file-slash ()
1948 (cond ((member ivy-text ivy--all-candidates)
1949 (ivy--cd (expand-file-name ivy-text ivy--directory)))
1950 ((string-match "//\\'" ivy-text)
1951 (if (and default-directory
1952 (string-match "\\`[[:alpha:]]:/" default-directory))
1953 (ivy--cd (match-string 0 default-directory))
1955 ((string-match "[[:alpha:]]:/\\'" ivy-text)
1956 (let ((drive-root (match-string 0 ivy-text)))
1957 (when (file-exists-p drive-root)
1958 (ivy--cd drive-root))))
1959 ((and (or (> ivy--index 0)
1961 (not (string= ivy-text "/")))
1962 (let ((default-directory ivy--directory))
1963 (file-directory-p ivy--current)))
1964 (ivy--cd (expand-file-name ivy--current ivy--directory)))))
1966 (defun ivy--exhibit ()
1967 "Insert Ivy completions display.
1968 Should be run via minibuffer `post-command-hook'."
1969 (when (memq 'ivy--exhibit post-command-hook)
1970 (let ((inhibit-field-text-motion nil))
1971 (constrain-to-field nil (point-max)))
1972 (setq ivy-text (ivy--input))
1973 (if (ivy-state-dynamic-collection ivy-last)
1974 ;; while-no-input would cause annoying
1975 ;; "Waiting for process to die...done" message interruptions
1976 (let ((inhibit-message t))
1977 (unless (equal ivy--old-text ivy-text)
1979 (setq ivy--all-candidates
1981 (funcall (ivy-state-collection ivy-last) ivy-text)))
1982 (setq ivy--old-text ivy-text)))
1983 (when ivy--all-candidates
1984 (ivy--insert-minibuffer
1985 (ivy--format ivy--all-candidates))))
1986 (cond (ivy--directory
1987 (if (string-match "/\\'" ivy-text)
1988 (ivy--magic-file-slash)
1989 (if (string-match "\\`~\\'" ivy-text)
1990 (ivy--cd (expand-file-name "~/")))))
1991 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1992 (when (or (and (string-match "\\` " ivy-text)
1993 (not (string-match "\\` " ivy--old-text)))
1994 (and (string-match "\\` " ivy--old-text)
1995 (not (string-match "\\` " ivy-text))))
1996 (setq ivy--all-candidates
1997 (if (and (> (length ivy-text) 0)
1998 (eq (aref ivy-text 0)
2000 (ivy--buffer-list " ")
2001 (ivy--buffer-list "" ivy-use-virtual-buffers)))
2002 (setq ivy--old-re nil))))
2003 (ivy--insert-minibuffer
2004 (with-current-buffer (ivy-state-buffer ivy-last)
2006 (ivy--filter ivy-text ivy--all-candidates))))
2007 (setq ivy--old-text ivy-text))))
2009 (defun ivy--insert-minibuffer (text)
2010 "Insert TEXT into minibuffer with appropriate cleanup."
2011 (let ((resize-mini-windows nil)
2012 (update-fn (ivy-state-update-fn ivy-last))
2016 (funcall update-fn))
2017 (ivy--insert-prompt)
2018 ;; Do nothing if while-no-input was aborted.
2019 (when (stringp text)
2020 (let ((buffer-undo-list t))
2024 (when (display-graphic-p)
2025 (ivy--resize-minibuffer-to-fit))))
2027 (defun ivy--resize-minibuffer-to-fit ()
2028 "Resize the minibuffer window size to fit the text in the minibuffer."
2029 (unless (frame-root-window-p (minibuffer-window))
2030 (with-selected-window (minibuffer-window)
2031 (if (fboundp 'window-text-pixel-size)
2032 (let ((text-height (cdr (window-text-pixel-size)))
2033 (body-height (window-body-height nil t)))
2034 (when (> text-height body-height)
2035 ;; Note: the size increment needs to be at least frame-char-height,
2036 ;; otherwise resizing won't do anything.
2037 (let ((delta (max (- text-height body-height) (frame-char-height))))
2038 (window-resize nil delta nil t t))))
2039 (let ((text-height (count-screen-lines))
2040 (body-height (window-body-height)))
2041 (when (> text-height body-height)
2042 (window-resize nil (- text-height body-height) nil t)))))))
2044 (declare-function colir-blend-face-background "ext:colir")
2046 (defun ivy--add-face (str face)
2047 "Propertize STR with FACE.
2048 `font-lock-append-text-property' is used, since it's better than
2049 `propertize' or `add-face-text-property' in this case."
2053 (colir-blend-face-background 0 (length str) face str)
2054 (let ((foreground (face-foreground face)))
2056 (add-face-text-property
2058 `(:foreground ,foreground)
2063 (font-lock-append-text-property 0 (length str) 'face face str))))
2066 (declare-function flx-make-string-cache "ext:flx")
2067 (declare-function flx-score "ext:flx")
2069 (defvar ivy--flx-cache nil)
2071 (eval-after-load 'flx
2072 '(setq ivy--flx-cache (flx-make-string-cache)))
2074 (defun ivy-toggle-case-fold ()
2075 "Toggle the case folding between nil and auto.
2076 In any completion session, the case folding starts in auto:
2078 - when the input is all lower case, `case-fold-search' is t
2081 You can toggle this to make `case-fold-search' nil regardless of input."
2083 (setq ivy-case-fold-search
2084 (if ivy-case-fold-search
2087 ;; reset cache so that the candidate list updates
2088 (setq ivy--old-re nil))
2090 (defun ivy--re-filter (re candidates)
2091 "Return all RE matching CANDIDATES.
2092 RE is a list of cons cells, with a regexp car and a boolean cdr.
2093 When the cdr is t, the car must match.
2094 Otherwise, the car must not match."
2095 (let ((re-list (if (stringp re) (list (cons re t)) re))
2097 (dolist (re re-list)
2104 (let ((re-str (car re)))
2105 (lambda (x) (string-match re-str x)))
2109 (defun ivy--filter (name candidates)
2110 "Return all items that match NAME in CANDIDATES.
2111 CANDIDATES are assumed to be static."
2112 (let ((re (funcall ivy--regex-function name)))
2113 (if (and (equal re ivy--old-re)
2115 ;; quick caching for "C-n", "C-p" etc.
2117 (let* ((re-str (if (listp re) (caar re) re))
2118 (matcher (ivy-state-matcher ivy-last))
2120 (and ivy-case-fold-search
2121 (string= name (downcase name))))
2124 (funcall matcher re candidates))
2127 (stringp ivy--old-re)
2128 (not (string-match "\\\\" ivy--old-re))
2129 (not (equal ivy--old-re ""))
2131 (if (string-match "\\\\)\\'" ivy--old-re)
2132 (substring ivy--old-re 0 -2)
2138 (lambda (x) (string-match re x))
2141 (ivy--re-filter re candidates)))))
2142 (ivy--recompute-index name re-str cands)
2144 (if (eq ivy--regex-function 'ivy--regex-ignore-order)
2149 (setq ivy--old-cands (ivy--sort name cands))))))
2151 (defun ivy--set-candidates (x)
2152 "Update `ivy--all-candidates' with X."
2154 (dolist (source ivy--extra-candidates)
2155 (if (equal source '(original-source))
2158 (setq res (append x res)))
2159 (setq ivy--old-re nil)
2161 (ivy--filter ivy-text (cadr source))
2163 (setq ivy--all-candidates res)))
2165 (defcustom ivy-sort-matches-functions-alist '((t . nil))
2166 "An alist of functions for sorting matching candidates.
2168 Unlike `ivy-sort-functions-alist', which is used to sort the
2169 whole collection only once, this alist of functions are used to
2170 sort only matching candidates after each change in input.
2172 The alist KEY is either a collection function or t to match
2173 previously unmatched collection functions.
2175 The alist VAL is a sorting function with the signature of
2176 `ivy--prefix-sort'."
2179 (const :tag "Fall-through" t)
2180 (symbol :tag "Collection"))
2183 (const :tag "Don't sort" nil)
2184 (const :tag "Put prefix matches ahead" 'ivy--prefix-sort)
2185 (function :tag "Custom sort function"))))
2187 (defun ivy--sort-files-by-date (_name candidates)
2188 "Re-soft CANDIDATES according to file modification date."
2189 (let ((default-directory ivy--directory))
2190 (cl-sort (copy-sequence candidates)
2193 (nth 5 (file-attributes f2))
2194 (nth 5 (file-attributes f1)))))))
2196 (defun ivy--sort (name candidates)
2197 "Re-sort CANDIDATES by NAME.
2198 All CANDIDATES are assumed to match NAME."
2199 (let ((key (or (ivy-state-caller ivy-last)
2200 (when (functionp (ivy-state-collection ivy-last))
2201 (ivy-state-collection ivy-last))))
2203 (cond ((and (require 'flx nil 'noerror)
2204 (eq ivy--regex-function 'ivy--regex-fuzzy))
2205 (ivy--flx-sort name candidates))
2206 ((setq fun (cdr (or (assoc key ivy-sort-matches-functions-alist)
2207 (assoc t ivy-sort-matches-functions-alist))))
2208 (funcall fun name candidates))
2212 (defun ivy--prefix-sort (name candidates)
2213 "Re-sort CANDIDATES.
2214 Prefix matches to NAME are put ahead of the list."
2215 (if (or (string-match "^\\^" name) (string= name ""))
2217 (let ((re-prefix (concat "^" (funcall ivy--regex-function name)))
2220 (dolist (s candidates)
2221 (if (string-match re-prefix s)
2223 (push s res-noprefix)))
2225 (nreverse res-prefix)
2226 (nreverse res-noprefix)))))
2228 (defun ivy--recompute-index (name re-str cands)
2229 (let* ((caller (ivy-state-caller ivy-last))
2230 (func (or (and caller (cdr (assoc caller ivy-index-functions-alist)))
2231 (cdr (assoc t ivy-index-functions-alist))
2232 #'ivy-recompute-index-zero)))
2233 (unless (eq this-command 'ivy-resume)
2236 (cl-position (if (and (> (length name) 0)
2237 (eq ?^ (aref name 0)))
2243 (concat re-str "/") cands
2245 (and (not (string= name ""))
2246 (not (and (require 'flx nil 'noerror)
2247 (eq ivy--regex-function 'ivy--regex-fuzzy)
2248 (< (length cands) 200)))
2250 (cl-position (nth ivy--index ivy--old-cands)
2252 (funcall func re-str cands))))
2253 (when (and (or (string= name "")
2255 (not (equal ivy--old-re "")))
2257 (or (ivy--preselect-index
2258 (ivy-state-preselect ivy-last)
2262 (defun ivy-recompute-index-swiper (_re-str 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 eq to handle equal duplicates in cands
2269 (setq idx (cl-position (pop tail) cands)))
2272 (1- (length cands))))
2275 ;; already in ivy-state-buffer
2276 (let ((n (line-number-at-pos))
2280 (when (eq n (read (get-text-property 0 'display c)))
2285 (defun ivy-recompute-index-swiper-async (_re-str cands)
2286 (if (null ivy--old-cands)
2287 (let ((ln (with-ivy-window
2288 (line-number-at-pos))))
2290 ;; closest to current line going forwards
2291 (cl-position-if (lambda (x)
2292 (>= (string-to-number x) ln))
2294 ;; closest to current line going backwards
2295 (1- (length cands))))
2296 (let ((tail (nthcdr ivy--index ivy--old-cands))
2298 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2300 (while (and tail (null idx))
2301 ;; Compare with `equal', since the collection is re-created
2302 ;; each time with `split-string'
2303 (setq idx (cl-position (pop tail) cands :test #'equal)))
2307 (defun ivy-recompute-index-zero (_re-str _cands)
2310 (defcustom ivy-minibuffer-faces
2311 '(ivy-minibuffer-match-face-1
2312 ivy-minibuffer-match-face-2
2313 ivy-minibuffer-match-face-3
2314 ivy-minibuffer-match-face-4)
2315 "List of `ivy' faces for minibuffer group matches."
2316 :type '(repeat :tag "Faces"
2318 (const ivy-minibuffer-match-face-1)
2319 (const ivy-minibuffer-match-face-2)
2320 (const ivy-minibuffer-match-face-3)
2321 (const ivy-minibuffer-match-face-4)
2322 (face :tag "Other face"))))
2324 (defvar ivy-flx-limit 200
2325 "Used to conditionally turn off flx sorting.
2327 When the amount of matching candidates exceeds this limit, then
2328 no sorting is done.")
2330 (defun ivy--flx-sort (name cands)
2331 "Sort according to closeness to string NAME the string list CANDS."
2334 (< (length cands) ivy-flx-limit))
2335 (let* ((flx-name (if (string-match "^\\^" name)
2342 (let ((score (flx-score x flx-name ivy--flx-cache)))
2346 (if cands-with-score
2348 (let ((str (copy-sequence (cdr x)))
2351 (dolist (j (cdar x))
2352 (unless (eq j (1+ last-j))
2355 (ivy-add-face-text-property
2357 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2358 ivy-minibuffer-faces)
2361 (sort cands-with-score
2363 (> (caar x) (caar y)))))
2369 (defcustom ivy-format-function 'ivy-format-function-default
2370 "Function to transform the list of candidates into a string.
2371 This string is inserted into the minibuffer."
2373 (const :tag "Default" ivy-format-function-default)
2374 (const :tag "Arrow prefix" ivy-format-function-arrow)
2375 (const :tag "Full line" ivy-format-function-line)))
2377 (defun ivy--truncate-string (str width)
2378 "Truncate STR to WIDTH."
2379 (if (> (string-width str) width)
2380 (concat (substring str 0 (min (- width 3)
2381 (- (length str) 3))) "...")
2384 (defun ivy--format-function-generic (selected-fn other-fn strs separator)
2385 "Transform CAND-PAIRS into a string for minibuffer.
2386 SELECTED-FN and OTHER-FN each take one string argument.
2387 SEPARATOR is used to join the candidates."
2391 (let ((curr (eq (cl-incf i) ivy--index)))
2393 (funcall selected-fn str)
2394 (funcall other-fn str))))
2398 (defun ivy-format-function-default (cands)
2399 "Transform CAND-PAIRS into a string for minibuffer."
2400 (ivy--format-function-generic
2402 (ivy--add-face str 'ivy-current-match))
2407 (defun ivy-format-function-arrow (cands)
2408 "Transform CAND-PAIRS into a string for minibuffer."
2409 (ivy--format-function-generic
2411 (concat "> " (ivy--add-face str 'ivy-current-match)))
2417 (defun ivy-format-function-line (cands)
2418 "Transform CAND-PAIRS into a string for minibuffer."
2419 (ivy--format-function-generic
2421 (ivy--add-face (concat str "\n") 'ivy-current-match))
2427 (defun ivy-add-face-text-property (start end face str)
2428 (if (fboundp 'add-face-text-property)
2429 (add-face-text-property
2430 start end face nil str)
2431 (font-lock-append-text-property
2432 start end 'face face str)))
2434 (defun ivy--format-minibuffer-line (str)
2436 (str (copy-sequence str)))
2437 (cond ((eq ivy--regex-function 'ivy--regex-ignore-order)
2438 (when (consp ivy--old-re)
2440 (dolist (re ivy--old-re)
2441 (when (string-match (car re) str)
2442 (ivy-add-face-text-property
2443 (match-beginning 0) (match-end 0)
2444 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2445 ivy-minibuffer-faces)
2448 ((and (eq ivy-display-style 'fancy)
2449 (not (eq ivy--regex-function 'ivy--regex-fuzzy)))
2451 (setq ivy--old-re (funcall ivy--regex-function ivy-text)))
2453 (while (and (string-match ivy--old-re str start)
2454 (> (- (match-end 0) (match-beginning 0)) 0))
2455 (setq start (match-end 0))
2457 (while (<= i ivy--subexps)
2459 (cond ((zerop ivy--subexps)
2460 (cadr ivy-minibuffer-faces))
2462 (car ivy-minibuffer-faces))
2464 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2465 ivy-minibuffer-faces)))))
2466 (ivy-add-face-text-property
2467 (match-beginning i) (match-end i)
2472 (ivy-set-display-transformer
2473 'counsel-find-file 'ivy-read-file-transformer)
2474 (ivy-set-display-transformer
2475 'read-file-name-internal 'ivy-read-file-transformer)
2477 (defun ivy-read-file-transformer (str)
2478 (if (string-match-p "/\\'" str)
2479 (propertize str 'face 'ivy-subdir)
2482 (defun ivy--format (cands)
2483 "Return a string for CANDS suitable for display in the minibuffer.
2484 CANDS is a list of strings."
2485 (setq ivy--length (length cands))
2486 (when (>= ivy--index ivy--length)
2487 (setq ivy--index (max (1- ivy--length) 0)))
2489 (setq ivy--current "")
2490 (let* ((half-height (/ ivy-height 2))
2491 (start (max 0 (- ivy--index half-height)))
2492 (end (min (+ start (1- ivy-height)) ivy--length))
2493 (start (max 0 (min start (- end (1- ivy-height)))))
2494 (cands (cl-subseq cands start end))
2495 (index (- ivy--index start))
2497 (setq ivy--current (copy-sequence (nth index cands)))
2498 (when (setq transformer-fn (ivy-state-display-transformer-fn ivy-last))
2500 (setq cands (mapcar transformer-fn cands))))
2501 (let* ((ivy--index index)
2503 #'ivy--format-minibuffer-line
2505 (res (concat "\n" (funcall ivy-format-function cands))))
2506 (put-text-property 0 (length res) 'read-only nil res)
2509 (defvar ivy--virtual-buffers nil
2510 "Store the virtual buffers alist.")
2512 (defvar recentf-list)
2514 (defcustom ivy-virtual-abbreviate 'name
2515 "The mode of abbreviation for virtual buffer names."
2517 (const :tag "Only name" name)
2518 (const :tag "Full path" full)
2519 ;; eventually, uniquify
2522 (defun ivy--virtual-buffers ()
2523 "Adapted from `ido-add-virtual-buffers-to-list'."
2524 (unless recentf-mode
2526 (let ((bookmarks (and (boundp 'bookmark-alist)
2528 virtual-buffers name)
2529 (dolist (head (append
2531 (delete " - no file -"
2532 (delq nil (mapcar (lambda (bookmark)
2533 (cdr (assoc 'filename bookmark)))
2536 (if (eq ivy-virtual-abbreviate 'name)
2537 (file-name-nondirectory head)
2538 (expand-file-name head)))
2539 (when (equal name "")
2540 (setq name (file-name-nondirectory (directory-file-name head))))
2541 (when (equal name "")
2543 (and (not (equal name ""))
2544 (null (get-file-buffer head))
2545 (not (assoc name virtual-buffers))
2546 (push (cons name head) virtual-buffers)))
2547 (when virtual-buffers
2548 (dolist (comp virtual-buffers)
2549 (put-text-property 0 (length (car comp))
2552 (setq ivy--virtual-buffers (nreverse virtual-buffers))
2553 (mapcar #'car ivy--virtual-buffers))))
2555 (defcustom ivy-ignore-buffers '("\\` ")
2556 "List of regexps or functions matching buffer names to ignore."
2557 :type '(repeat (choice regexp function)))
2559 (defun ivy--buffer-list (str &optional virtual predicate)
2560 "Return the buffers that match STR.
2561 When VIRTUAL is non-nil, add virtual buffers."
2566 (if (with-current-buffer x
2568 (abbreviate-file-name default-directory)))
2569 (propertize x 'face 'ivy-remote)
2571 (all-completions str 'internal-complete-buffer predicate))
2573 (ivy--virtual-buffers)))))
2575 (defvar ivy-views (and nil
2576 `(("ivy + *scratch* {}"
2578 (file ,(expand-file-name "ivy.el"))
2579 (buffer "*scratch*")))
2580 ("swiper + *scratch* {}"
2582 (file ,(expand-file-name "swiper.el"))
2583 (buffer "*scratch*")))))
2584 "Store window configurations selectable by `ivy-switch-buffer'.
2586 The default value is given as an example.
2588 Each element is a list of (NAME TREE). NAME is a string, it's
2589 recommended to end it with a distinctive snippet e.g. \"{}\" so
2590 that it's easy to distinguish the window configurations.
2592 TREE is a nested list with the following valid cars:
2593 - vert: split the window vertically
2594 - horz: split the window horizontally
2595 - file: open the specified file
2596 - buffer: open the specified buffer
2598 TREE can be nested multiple times to have mulitple window splits.")
2600 (defun ivy-source-views ()
2601 (mapcar #'car ivy-views))
2606 (ivy-source-views)))
2608 (defun ivy-set-view-recur (view)
2609 (cond ((eq (car view) 'vert)
2610 (let ((wnd1 (selected-window))
2611 (wnd2 (split-window-vertically)))
2612 (with-selected-window wnd1
2613 (ivy-set-view-recur (nth 1 view)))
2614 (with-selected-window wnd2
2615 (ivy-set-view-recur (nth 2 view)))))
2616 ((eq (car view) 'horz)
2617 (let ((wnd1 (selected-window))
2618 (wnd2 (split-window-horizontally)))
2619 (with-selected-window wnd1
2620 (ivy-set-view-recur (nth 1 view)))
2621 (with-selected-window wnd2
2622 (ivy-set-view-recur (nth 2 view)))))
2623 ((eq (car view) 'file)
2624 (let* ((name (cadr view))
2625 (virtual (assoc name ivy--virtual-buffers))
2627 (cond ((setq buffer (get-buffer name))
2628 (switch-to-buffer buffer nil 'force-same-window))
2630 (find-file (cdr virtual)))
2631 ((file-exists-p name)
2632 (find-file name)))))
2633 ((eq (car view) 'buffer)
2634 (switch-to-buffer (cadr view)))
2635 ((eq (car view) 'sexp)
2636 (eval (cadr view)))))
2638 (defun ivy--switch-buffer-action (buffer)
2640 BUFFER may be a string or nil."
2642 (if (zerop (length buffer))
2644 ivy-text nil 'force-same-window)
2645 (let ((virtual (assoc buffer ivy--virtual-buffers))
2646 (view (assoc buffer ivy-views)))
2648 (not (get-buffer buffer)))
2649 (find-file (cdr virtual)))
2651 (delete-other-windows)
2652 (ivy-set-view-recur (cadr view)))
2655 buffer nil 'force-same-window)))))))
2657 (defun ivy--switch-buffer-other-window-action (buffer)
2658 "Switch to BUFFER in other window.
2659 BUFFER may be a string or nil."
2660 (if (zerop (length buffer))
2661 (switch-to-buffer-other-window ivy-text)
2662 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2664 (not (get-buffer buffer)))
2665 (find-file-other-window (cdr virtual))
2666 (switch-to-buffer-other-window buffer)))))
2668 (defun ivy--rename-buffer-action (buffer)
2670 (let ((new-name (read-string "Rename buffer (to new name): ")))
2671 (with-current-buffer buffer
2672 (rename-buffer new-name))))
2674 (defvar ivy-switch-buffer-map (make-sparse-keymap))
2681 (ivy--reset-state ivy-last))
2684 ivy--switch-buffer-other-window-action
2687 ivy--rename-buffer-action
2690 (defun ivy--switch-buffer-matcher (regexp candidates)
2691 "Return REGEXP-matching CANDIDATES.
2692 Skip buffers that match `ivy-ignore-buffers'."
2693 (let ((res (ivy--re-filter regexp candidates)))
2694 (if (or (null ivy-use-ignore)
2695 (null ivy-ignore-buffers))
2701 (if (functionp f-or-r)
2702 (funcall f-or-r buf)
2703 (string-match-p f-or-r buf)))
2704 ivy-ignore-buffers))
2706 (and (eq ivy-use-ignore t)
2709 (ivy-set-display-transformer
2710 'ivy-switch-buffer 'ivy-switch-buffer-transformer)
2711 (ivy-set-display-transformer
2712 'internal-complete-buffer 'ivy-switch-buffer-transformer)
2714 (defun ivy-switch-buffer-transformer (str)
2715 (let ((b (get-buffer str)))
2717 (buffer-file-name b)
2718 (buffer-modified-p b))
2719 (propertize str 'face 'ivy-modified-buffer)
2722 (defun ivy-switch-buffer-occur ()
2723 "Occur function for `ivy-switch-buffer' that uses `ibuffer'."
2725 (concat "\\(" (mapconcat #'regexp-quote ivy--old-cands "\\|") "\\)"))
2726 (new-qualifier `((name . ,cand-regexp))))
2727 (ibuffer nil (buffer-name) new-qualifier)))
2730 (defun ivy-switch-buffer ()
2731 "Switch to another buffer."
2733 (let ((this-command 'ivy-switch-buffer))
2734 (ivy-read "Switch to buffer: " 'internal-complete-buffer
2735 :matcher #'ivy--switch-buffer-matcher
2736 :preselect (buffer-name (other-buffer (current-buffer)))
2737 :action #'ivy--switch-buffer-action
2738 :keymap ivy-switch-buffer-map
2739 :caller 'ivy-switch-buffer)))
2742 (defun ivy-switch-buffer-other-window ()
2743 "Switch to another buffer in another window."
2745 (ivy-read "Switch to buffer in other window: " 'internal-complete-buffer
2746 :preselect (buffer-name (other-buffer (current-buffer)))
2747 :action #'ivy--switch-buffer-other-window-action
2748 :keymap ivy-switch-buffer-map
2749 :caller 'ivy-switch-buffer-other-window))
2752 (defun ivy-recentf ()
2753 "Find a file on `recentf-list'."
2755 (ivy-read "Recentf: " recentf-list
2760 :caller 'ivy-recentf))
2762 (defun ivy-yank-word ()
2763 "Pull next word from buffer into search string."
2768 (le (line-end-position)))
2772 (setq amend (buffer-substring-no-properties pt (point))))))
2774 (insert (replace-regexp-in-string " +" " " amend)))))
2776 (defun ivy-kill-ring-save ()
2777 "Store the current candidates into the kill ring.
2778 If the region is active, forward to `kill-ring-save' instead."
2780 (if (region-active-p)
2781 (call-interactively 'kill-ring-save)
2788 (defun ivy-insert-current ()
2789 "Make the current candidate into current input.
2790 Don't finish completion."
2792 (delete-minibuffer-contents)
2793 (if (and ivy--directory
2794 (string-match "/$" ivy--current))
2795 (insert (substring ivy--current 0 -1))
2796 (insert ivy--current)))
2798 (defun ivy-toggle-fuzzy ()
2799 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
2801 (setq ivy--old-re nil)
2802 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
2803 (setq ivy--regex-function 'ivy--regex-plus)
2804 (setq ivy--regex-function 'ivy--regex-fuzzy)))
2806 (defun ivy-reverse-i-search ()
2807 "Enter a recursive `ivy-read' session using the current history.
2808 The selected history element will be inserted into the minibuffer."
2810 (let ((enable-recursive-minibuffers t)
2811 (history (symbol-value (ivy-state-history ivy-last)))
2813 (ivy-recursive-restore nil))
2814 (ivy-read "Reverse-i-search: "
2818 (setq ivy-last old-last))
2819 (delete-minibuffer-contents)
2820 (insert (substring-no-properties x))
2823 (defun ivy-restrict-to-matches ()
2824 "Restrict candidates to current matches and erase input."
2826 (delete-minibuffer-contents)
2827 (setq ivy--all-candidates
2828 (ivy--filter ivy-text ivy--all-candidates)))
2831 (defvar-local ivy-occur-last nil
2832 "Buffer-local value of `ivy-last'.
2833 Can't re-use `ivy-last' because using e.g. `swiper' in the same
2834 buffer would modify `ivy-last'.")
2836 (defvar ivy-occur-mode-map
2837 (let ((map (make-sparse-keymap)))
2838 (define-key map [mouse-1] 'ivy-occur-click)
2839 (define-key map (kbd "RET") 'ivy-occur-press)
2840 (define-key map (kbd "j") 'ivy-occur-next-line)
2841 (define-key map (kbd "k") 'ivy-occur-previous-line)
2842 (define-key map (kbd "h") 'backward-char)
2843 (define-key map (kbd "l") 'forward-char)
2844 (define-key map (kbd "f") 'ivy-occur-press)
2845 (define-key map (kbd "g") 'ivy-occur-revert-buffer)
2846 (define-key map (kbd "a") 'ivy-occur-read-action)
2847 (define-key map (kbd "o") 'ivy-occur-dispatch)
2848 (define-key map (kbd "c") 'ivy-occur-toggle-calling)
2849 (define-key map (kbd "q") 'quit-window)
2851 "Keymap for Ivy Occur mode.")
2853 (defun ivy-occur-toggle-calling ()
2854 "Toggle `ivy-calling'."
2856 (if (setq ivy-calling (not ivy-calling))
2858 (setq mode-name "Ivy-Occur [calling]")
2860 (setq mode-name "Ivy-Occur"))
2861 (force-mode-line-update))
2863 (defun ivy-occur-next-line (&optional arg)
2864 "Move the cursor down ARG lines.
2865 When `ivy-calling' isn't nil, call `ivy-occur-press'."
2871 (defun ivy-occur-previous-line (&optional arg)
2872 "Move the cursor up ARG lines.
2873 When `ivy-calling' isn't nil, call `ivy-occur-press'."
2875 (forward-line (- arg))
2879 (define-derived-mode ivy-occur-mode fundamental-mode "Ivy-Occur"
2880 "Major mode for output from \\[ivy-occur].
2882 \\{ivy-occur-mode-map}")
2884 (defvar ivy-occur-grep-mode-map
2885 (let ((map (copy-keymap ivy-occur-mode-map)))
2886 (define-key map (kbd "C-x C-q") 'ivy-wgrep-change-to-wgrep-mode)
2888 "Keymap for Ivy Occur Grep mode.")
2890 (define-derived-mode ivy-occur-grep-mode grep-mode "Ivy-Occur"
2891 "Major mode for output from \\[ivy-occur].
2893 \\{ivy-occur-grep-mode-map}")
2895 (defvar ivy--occurs-list nil
2896 "A list of custom occur generators per command.")
2898 (defun ivy-set-occur (cmd occur)
2899 "Assign CMD a custom OCCUR function."
2900 (setq ivy--occurs-list
2901 (plist-put ivy--occurs-list cmd occur)))
2903 (ivy-set-occur 'ivy-switch-buffer 'ivy-switch-buffer-occur)
2904 (ivy-set-occur 'ivy-switch-buffer-other-window 'ivy-switch-buffer-occur)
2906 (defun ivy--occur-insert-lines (cands)
2908 (add-text-properties
2912 help-echo "mouse-1: call ivy-action")
2917 "Stop completion and put the current matches into a new buffer.
2919 The new buffer remembers current action(s).
2921 While in the *ivy-occur* buffer, selecting a candidate with RET or
2922 a mouse click will call the appropriate action for that candidate.
2924 There is no limit on the number of *ivy-occur* buffers."
2926 (if (not (window-minibuffer-p))
2927 (user-error "No completion session is active")
2928 (let* ((caller (ivy-state-caller ivy-last))
2929 (occur-fn (plist-get ivy--occurs-list caller))
2931 (generate-new-buffer
2932 (format "*ivy-occur%s \"%s\"*"
2934 (concat " " (prin1-to-string caller))
2937 (with-current-buffer buffer
2938 (let ((inhibit-read-only t))
2943 (insert (format "%d candidates:\n" (length ivy--old-cands)))
2944 (ivy--occur-insert-lines
2946 (lambda (cand) (concat " " cand))
2948 (setf (ivy-state-text ivy-last) ivy-text)
2949 (setq ivy-occur-last ivy-last)
2950 (setq-local ivy--directory ivy--directory))
2951 (ivy-exit-with-action
2952 `(lambda (_) (pop-to-buffer ,buffer))))))
2954 (defun ivy-occur-revert-buffer ()
2955 "Refresh the buffer making it up-to date with the collection.
2957 Currently only works for `swiper'. In that specific case, the
2958 *ivy-occur* buffer becomes nearly useless as the orignal buffer
2959 is updated, since the line numbers no longer match.
2961 Calling this function is as if you called `ivy-occur' on the
2962 updated original buffer."
2964 (let ((caller (ivy-state-caller ivy-occur-last))
2965 (ivy-last ivy-occur-last))
2966 (cond ((eq caller 'swiper)
2967 (let ((buffer (ivy-state-buffer ivy-occur-last)))
2968 (unless (buffer-live-p buffer)
2969 (error "buffer was killed"))
2970 (let ((inhibit-read-only t))
2972 (funcall (plist-get ivy--occurs-list caller) t))))
2973 ((memq caller '(counsel-git-grep counsel-grep counsel-ag))
2974 (let ((inhibit-read-only t))
2976 (funcall (plist-get ivy--occurs-list caller)))))))
2978 (declare-function wgrep-change-to-wgrep-mode "ext:wgrep")
2980 (defun ivy-wgrep-change-to-wgrep-mode ()
2981 "Forward to `wgrep-change-to-wgrep-mode'."
2983 (if (require 'wgrep nil 'noerror)
2984 (wgrep-change-to-wgrep-mode)
2985 (error "Package wgrep isn't installed")))
2987 (defun ivy-occur-read-action ()
2988 "Select one of the available actions as the current one."
2990 (let ((ivy-last ivy-occur-last))
2993 (defun ivy-occur-dispatch ()
2994 "Call one of the available actions on the current item."
2996 (let* ((state-action (ivy-state-action ivy-occur-last))
2997 (actions (if (symbolp state-action)
2999 (copy-sequence state-action))))
3002 (ivy-occur-read-action)
3004 (setf (ivy-state-action ivy-occur-last) actions))))
3006 (defun ivy-occur-click (event)
3007 "Execute action for the current candidate.
3008 EVENT gives the mouse position."
3010 (let ((window (posn-window (event-end event)))
3011 (pos (posn-point (event-end event))))
3012 (with-current-buffer (window-buffer window)
3014 (ivy-occur-press))))
3016 (declare-function swiper--cleanup "swiper")
3017 (declare-function swiper--add-overlays "swiper")
3018 (defvar ivy-occur-timer nil)
3019 (defvar counsel-grep-last-line)
3021 (defun ivy-occur-press ()
3022 "Execute action for the current candidate."
3024 (when (save-excursion
3026 (looking-at "\\(?:./\\| \\)\\(.*\\)$"))
3027 (when (memq (ivy-state-caller ivy-occur-last)
3028 '(swiper counsel-git-grep counsel-grep counsel-ag
3029 counsel-describe-function counsel-describe-variable))
3030 (let ((window (ivy-state-window ivy-occur-last)))
3031 (when (or (null (window-live-p window))
3032 (equal window (selected-window)))
3033 (save-selected-window
3034 (setf (ivy-state-window ivy-occur-last)
3035 (display-buffer (ivy-state-buffer ivy-occur-last)
3036 'display-buffer-pop-up-window))))))
3037 (let* ((ivy-last ivy-occur-last)
3038 (ivy-text (ivy-state-text ivy-last))
3039 (str (buffer-substring
3042 (coll (ivy-state-collection ivy-last))
3043 (action (ivy--get-action ivy-last))
3046 (setq counsel-grep-last-line nil)
3048 (if (and (consp coll)
3050 (cdr (assoc str coll))
3052 (if (memq (ivy-state-caller ivy-last)
3053 '(swiper counsel-git-grep counsel-grep))
3054 (with-current-buffer (window-buffer (selected-window))
3056 (swiper--add-overlays
3057 (ivy--regex ivy-text)
3058 (line-beginning-position)
3061 (when (timerp ivy-occur-timer)
3062 (cancel-timer ivy-occur-timer))
3063 (setq ivy-occur-timer (run-at-time 1.0 nil 'swiper--cleanup))))))))
3065 (defvar ivy-help-file (let ((default-directory
3067 (file-name-directory load-file-name)
3068 default-directory)))
3069 (if (file-exists-p "ivy-help.org")
3070 (expand-file-name "ivy-help.org")
3071 (if (file-exists-p "doc/ivy-help.org")
3072 (expand-file-name "doc/ivy-help.org"))))
3073 "The file for `ivy-help'.")
3078 (let ((buf (get-buffer "*Ivy Help*")))
3080 (setq buf (get-buffer-create "*Ivy Help*"))
3081 (with-current-buffer buf
3082 (insert-file-contents ivy-help-file)
3085 (goto-char (point-min))))
3086 (if (eq this-command 'ivy-help)
3087 (switch-to-buffer buf)
3089 (pop-to-buffer buf)))
3091 (goto-char (point-min))))
3095 ;;; ivy.el ends here