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 (defface ivy-current-match
48 '((((class color) (background light))
49 :background "#1a4b77" :foreground "white")
50 (((class color) (background dark))
51 :background "#65a7e2" :foreground "black"))
52 "Face used by Ivy for highlighting first match.")
54 (defface ivy-confirm-face
55 '((t :foreground "ForestGreen" :inherit minibuffer-prompt))
56 "Face used by Ivy for a confirmation prompt.")
58 (defface ivy-match-required-face
59 '((t :foreground "red" :inherit minibuffer-prompt))
60 "Face used by Ivy for a match required prompt.")
63 '((t (:inherit 'dired-directory)))
64 "Face used by Ivy for highlighting subdirs in the alternatives.")
66 (defface ivy-modified-buffer
67 '((t :inherit 'default))
68 "Face used by Ivy for highlighting modified file visiting buffers.")
71 '((t (:foreground "#110099")))
72 "Face used by Ivy for highlighting remotes in the alternatives.")
74 (defcustom ivy-height 10
75 "Number of lines for the minibuffer window."
78 (defcustom ivy-count-format "%-4d "
79 "The style to use for displaying the current candidate count for `ivy-read'.
80 Set this to \"\" to suppress the count visibility.
81 Set this to \"(%d/%d) \" to display both the index and the count."
83 (const :tag "Count disabled" "")
84 (const :tag "Count matches" "%-4d ")
85 (const :tag "Count matches and show current match" "(%d/%d) ")
88 (defcustom ivy-wrap nil
89 "When non-nil, wrap around after the first and the last candidate."
92 (defcustom ivy-display-style (unless (version< emacs-version "24.5") 'fancy)
93 "The style for formatting the minibuffer.
95 By default, the matched strings are copied as is.
97 The fancy display style highlights matching parts of the regexp,
98 a behavior similar to `swiper'.
100 This setting depends on `add-face-text-property' - a C function
101 available as of Emacs 24.5. Fancy style will render poorly in
102 earlier versions of Emacs."
104 (const :tag "Plain" nil)
105 (const :tag "Fancy" fancy)))
107 (defcustom ivy-on-del-error-function 'minibuffer-keyboard-quit
108 "The handler for when `ivy-backward-delete-char' throws.
109 Usually a quick exit out of the minibuffer."
112 (defcustom ivy-extra-directories '("../" "./")
113 "Add this to the front of the list when completing file names.
114 Only \"./\" and \"../\" apply here. They appear in reverse order."
115 :type '(repeat :tag "Dirs"
117 (const :tag "Parent Directory" "../")
118 (const :tag "Current Directory" "./"))))
120 (defcustom ivy-use-virtual-buffers nil
121 "When non-nil, add `recentf-mode' and bookmarks to `ivy-switch-buffer'."
124 (defvar ivy--actions-list nil
125 "A list of extra actions per command.")
127 (defun ivy-set-actions (cmd actions)
128 "Set CMD extra exit points to ACTIONS."
129 (setq ivy--actions-list
130 (plist-put ivy--actions-list cmd actions)))
134 (defvar ivy-minibuffer-map
135 (let ((map (make-sparse-keymap)))
136 (define-key map (kbd "C-m") 'ivy-done)
137 (define-key map (kbd "C-M-m") 'ivy-call)
138 (define-key map (kbd "C-j") 'ivy-alt-done)
139 (define-key map (kbd "C-M-j") 'ivy-immediate-done)
140 (define-key map (kbd "TAB") 'ivy-partial-or-done)
141 (define-key map (kbd "C-n") 'ivy-next-line)
142 (define-key map (kbd "C-p") 'ivy-previous-line)
143 (define-key map (kbd "<down>") 'ivy-next-line)
144 (define-key map (kbd "<up>") 'ivy-previous-line)
145 (define-key map (kbd "C-s") 'ivy-next-line-or-history)
146 (define-key map (kbd "C-r") 'ivy-reverse-i-search)
147 (define-key map (kbd "SPC") 'self-insert-command)
148 (define-key map (kbd "DEL") 'ivy-backward-delete-char)
149 (define-key map (kbd "M-DEL") 'ivy-backward-kill-word)
150 (define-key map (kbd "C-d") 'ivy-delete-char)
151 (define-key map (kbd "C-f") 'ivy-forward-char)
152 (define-key map (kbd "M-d") 'ivy-kill-word)
153 (define-key map (kbd "M-<") 'ivy-beginning-of-buffer)
154 (define-key map (kbd "M->") 'ivy-end-of-buffer)
155 (define-key map (kbd "M-n") 'ivy-next-history-element)
156 (define-key map (kbd "M-p") 'ivy-previous-history-element)
157 (define-key map (kbd "C-g") 'minibuffer-keyboard-quit)
158 (define-key map (kbd "C-v") 'ivy-scroll-up-command)
159 (define-key map (kbd "M-v") 'ivy-scroll-down-command)
160 (define-key map (kbd "C-M-n") 'ivy-next-line-and-call)
161 (define-key map (kbd "C-M-p") 'ivy-previous-line-and-call)
162 (define-key map (kbd "M-q") 'ivy-toggle-regexp-quote)
163 (define-key map (kbd "M-j") 'ivy-yank-word)
164 (define-key map (kbd "M-i") 'ivy-insert-current)
165 (define-key map (kbd "C-o") 'hydra-ivy/body)
166 (define-key map (kbd "M-o") 'ivy-dispatching-done)
167 (define-key map (kbd "C-M-o") 'ivy-dispatching-call)
168 (define-key map (kbd "C-k") 'ivy-kill-line)
169 (define-key map (kbd "S-SPC") 'ivy-restrict-to-matches)
170 (define-key map (kbd "M-w") 'ivy-kill-ring-save)
171 (define-key map (kbd "C-'") 'ivy-avy)
172 (define-key map (kbd "C-M-a") 'ivy-read-action)
173 (define-key map (kbd "C-c C-o") 'ivy-occur)
175 "Keymap used in the minibuffer.")
176 (autoload 'hydra-ivy/body "ivy-hydra" "" t)
179 (let ((map (make-sparse-keymap)))
180 (define-key map [remap switch-to-buffer] 'ivy-switch-buffer)
182 "Keymap for `ivy-mode'.")
185 (cl-defstruct ivy-state
187 predicate require-match initial-input
188 history preselect keymap update-fn sort
189 ;; The window in which `ivy-read' was called
191 ;; The buffer in which `ivy-read' was called
193 ;; The value of `ivy-text' to be used by `ivy-occur'
199 ;; When this is non-nil, call it for each input change to get new candidates
204 "The last parameters passed to `ivy-read'.
206 This should eventually become a stack so that you could use
207 `ivy-read' recursively.")
209 (defsubst ivy-set-action (action)
210 (setf (ivy-state-action ivy-last) action))
212 (defvar ivy-history nil
213 "History list of candidates entered in the minibuffer.
215 Maximum length of the history list is determined by the value
216 of `history-length'.")
218 (defvar ivy--directory nil
219 "Current directory when completing file names.")
221 (defvar ivy--length 0
222 "Store the amount of viable candidates.")
225 "Store the user's string as it is typed in.")
227 (defvar ivy--current ""
228 "Current candidate.")
231 "Store the index of the current candidate.")
234 "Store 'done if the completion was successfully selected.
235 Otherwise, store nil.")
237 (defvar ivy--all-candidates nil
238 "Store the candidates passed to `ivy-read'.")
240 (defvar ivy--default nil
241 "Default initial input.")
243 (defvar ivy--prompt nil
244 "Store the format-style prompt.
245 When non-nil, it should contain at least one %d.")
247 (defvar ivy--prompt-extra ""
248 "Temporary modifications to the prompt.")
250 (defvar ivy--old-re nil
251 "Store the old regexp.")
253 (defvar ivy--old-cands nil
254 "Store the candidates matched by `ivy--old-re'.")
256 (defvar ivy--regex-function 'ivy--regex
257 "Current function for building a regex.")
259 (defvar ivy--subexps 0
260 "Number of groups in the current `ivy--regex'.")
262 (defvar ivy--full-length nil
263 "When :dynamic-collection is non-nil, this can be the total amount of candidates.")
265 (defvar ivy--old-text ""
266 "Store old `ivy-text' for dynamic completion.")
268 (defvar ivy-case-fold-search 'auto
269 "Store the current overriding `case-fold-search'.")
271 (defvar Info-current-file)
273 (defmacro ivy-quit-and-run (&rest body)
274 "Quit the minibuffer and run BODY afterwards."
276 (put 'quit 'error-message "")
279 (put 'quit 'error-message "Quit")
281 (minibuffer-keyboard-quit)))
283 (defun ivy-exit-with-action (action)
284 "Quit the minibuffer and call ACTION afterwards."
288 (ivy-set-action ',(ivy-state-action ivy-last))))
289 (setq ivy-exit 'done)
292 (defmacro with-ivy-window (&rest body)
293 "Execute BODY in the window from which `ivy-read' was called."
296 `(with-selected-window (ivy--get-window ivy-last)
299 (defun ivy--done (text)
300 "Insert TEXT and exit minibuffer."
301 (if (and ivy--directory
302 (not (eq (ivy-state-history ivy-last) 'grep-files-history)))
303 (insert (setq ivy--current (expand-file-name
304 text ivy--directory)))
305 (insert (setq ivy--current text)))
306 (setq ivy-exit 'done)
311 "Exit the minibuffer with the selected candidate."
313 (delete-minibuffer-contents)
314 (cond ((> ivy--length 0)
315 (ivy--done ivy--current))
316 ((memq (ivy-state-collection ivy-last)
317 '(read-file-name-internal internal-complete-buffer))
318 (if (or (not (eq confirm-nonexistent-file-or-buffer t))
319 (equal " (confirm)" ivy--prompt-extra))
321 (setq ivy--prompt-extra " (confirm)")
324 ((memq (ivy-state-require-match ivy-last)
325 '(nil confirm confirm-after-completion))
326 (ivy--done ivy-text))
328 (setq ivy--prompt-extra " (match required)")
332 (defun ivy-read-action ()
333 "Change the action to one of the available ones."
335 (let ((actions (ivy-state-action ivy-last)))
336 (unless (null (ivy--actionp actions))
337 (let* ((hint (concat ivy--current
344 'face 'font-lock-builtin-face)
349 (key (string (read-key hint)))
350 (action-idx (cl-position-if
351 (lambda (x) (equal (car x) key))
353 (cond ((string= key "
\a"))
355 (error "%s is not bound" key))
358 (setcar actions (1+ action-idx))
359 (ivy-set-action actions)))))))
361 (defun ivy-dispatching-done ()
362 "Select one of the available actions and call `ivy-done'."
367 (defun ivy-dispatching-call ()
368 "Select one of the available actions and call `ivy-call'."
370 (let ((actions (copy-sequence (ivy-state-action ivy-last))))
372 (when (ivy-read-action)
374 (ivy-set-action actions))))
376 (defun ivy-build-tramp-name (x)
377 "Reconstruct X into a path.
378 Is is a cons cell, related to `tramp-get-completion-function'."
382 (concat user "@" domain)
385 (declare-function tramp-get-completion-function "tramp")
386 (declare-function Info-find-node "info")
388 (defun ivy-alt-done (&optional arg)
389 "Exit the minibuffer with the selected candidate.
390 When ARG is t, exit with current text, ignoring the candidates."
393 (ivy-immediate-done))
395 (ivy--directory-done))
396 ((eq (ivy-state-collection ivy-last) 'Info-read-node-name-1)
397 (if (or (equal ivy--current "(./)")
398 (equal ivy--current "(../)"))
400 (ivy-read "Go to file: " 'read-file-name-internal
403 (expand-file-name x ivy--directory)
409 (defun ivy--directory-done ()
410 "Handle exit from the minibuffer when completing file names."
413 ((equal ivy-text "/sudo::")
414 (setq dir (concat ivy-text ivy--directory))
419 (not (equal ivy-text ""))
423 (file-name-as-directory
425 ivy-text ivy--directory))))))
427 (not (string= ivy--current "./"))
428 (cl-plusp ivy--length)
431 (setq dir (file-name-as-directory
433 ivy--current ivy--directory)))))))
436 ((or (and (equal ivy--directory "/")
437 (string-match "\\`[^/]+:.*:.*\\'" ivy-text))
438 (string-match "\\`/[^/]+:.*:.*\\'" ivy-text))
440 ((or (and (equal ivy--directory "/")
442 "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
445 "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
447 (setq ivy-text ivy--current))))
449 "\\`/\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
451 (let ((method (match-string 1 ivy-text))
452 (user (match-string 2 ivy-text))
453 (rest (match-string 3 ivy-text))
456 (dolist (x (tramp-get-completion-function method))
457 (setq res (append res (funcall (car x) (cadr x)))))
458 (setq res (delq nil res))
462 (setq res (cl-delete-duplicates res :test #'equal))
463 (let* ((old-ivy-last ivy-last)
464 (enable-recursive-minibuffers t)
465 (host (ivy-read "Find File: "
466 (mapcar #'ivy-build-tramp-name res)
467 :initial-input rest)))
468 (setq ivy-last old-ivy-last)
470 (setq ivy--directory "/")
471 (ivy--cd (concat "/" method ":" host ":"))))))
475 (defcustom ivy-tab-space nil
476 "When non-nil, `ivy-partial-or-done' should insert a space."
479 (defun ivy-partial-or-done ()
480 "Complete the minibuffer text as much as possible.
481 If the text hasn't changed as a result, forward to `ivy-alt-done'."
483 (if (and (eq (ivy-state-collection ivy-last) #'read-file-name-internal)
484 (or (and (equal ivy--directory "/")
485 (string-match "\\`[^/]+:.*\\'" ivy-text))
486 (string-match "\\`/" ivy-text)))
487 (let ((default-directory ivy--directory))
488 (minibuffer-complete)
489 (setq ivy-text (ivy--input))
490 (when (file-directory-p
491 (expand-file-name ivy-text ivy--directory))
492 (ivy--cd (file-name-as-directory
493 (expand-file-name ivy-text ivy--directory)))))
495 (when (or (eq this-command last-command)
499 (defun ivy-partial ()
500 "Complete the minibuffer text as much as possible."
502 (let* ((parts (or (split-string ivy-text " " t) (list "")))
503 (postfix (car (last parts)))
504 (completion-ignore-case t)
505 (startp (string-match "^\\^" postfix))
506 (new (try-completion (if startp
507 (substring postfix 1)
509 (mapcar (lambda (str)
510 (let ((i (string-match postfix str)))
514 (cond ((eq new t) nil)
515 ((string= new ivy-text) nil)
517 (delete-region (minibuffer-prompt-end) (point-max))
522 (insert (mapconcat #'identity parts " ")
523 (if ivy-tab-space " " ""))
526 (defun ivy-immediate-done ()
527 "Exit the minibuffer with the current input."
529 (delete-minibuffer-contents)
530 (insert (setq ivy--current
532 (expand-file-name ivy-text ivy--directory)
534 (setq ivy-exit 'done)
539 "Resume the last completion session."
541 (when (eq (ivy-state-caller ivy-last) 'swiper)
542 (switch-to-buffer (ivy-state-buffer ivy-last)))
543 (with-current-buffer (ivy-state-buffer ivy-last)
545 (ivy-state-prompt ivy-last)
546 (ivy-state-collection ivy-last)
547 :predicate (ivy-state-predicate ivy-last)
548 :require-match (ivy-state-require-match ivy-last)
549 :initial-input ivy-text
550 :history (ivy-state-history ivy-last)
551 :preselect (unless (eq (ivy-state-collection ivy-last)
552 'read-file-name-internal)
554 :keymap (ivy-state-keymap ivy-last)
555 :update-fn (ivy-state-update-fn ivy-last)
556 :sort (ivy-state-sort ivy-last)
557 :action (ivy-state-action ivy-last)
558 :unwind (ivy-state-unwind ivy-last)
559 :re-builder (ivy-state-re-builder ivy-last)
560 :matcher (ivy-state-matcher ivy-last)
561 :dynamic-collection (ivy-state-dynamic-collection ivy-last)
562 :caller (ivy-state-caller ivy-last))))
564 (defvar ivy-calling nil
565 "When non-nil, call the current action when `ivy--index' changes.")
567 (defun ivy-set-index (index)
568 "Set `ivy--index' to INDEX."
569 (setq ivy--index index)
574 (defun ivy-beginning-of-buffer ()
575 "Select the first completion candidate."
579 (defun ivy-end-of-buffer ()
580 "Select the last completion candidate."
582 (ivy-set-index (1- ivy--length)))
584 (defun ivy-scroll-up-command ()
585 "Scroll the candidates upward by the minibuffer height."
587 (ivy-set-index (min (1- (+ ivy--index ivy-height))
590 (defun ivy-scroll-down-command ()
591 "Scroll the candidates downward by the minibuffer height."
593 (ivy-set-index (max (1+ (- ivy--index ivy-height))
596 (defun ivy-minibuffer-grow ()
597 "Grow the minibuffer window by 1 line."
599 (setq-local max-mini-window-height
600 (cl-incf ivy-height)))
602 (defun ivy-minibuffer-shrink ()
603 "Shrink the minibuffer window by 1 line."
605 (unless (<= ivy-height 2)
606 (setq-local max-mini-window-height
607 (cl-decf ivy-height))
608 (window-resize (selected-window) -1)))
610 (defun ivy-next-line (&optional arg)
611 "Move cursor vertically down ARG candidates."
613 (setq arg (or arg 1))
614 (let ((index (+ ivy--index arg)))
615 (if (> index (1- ivy--length))
617 (ivy-beginning-of-buffer)
618 (ivy-set-index (1- ivy--length)))
619 (ivy-set-index index))))
621 (defun ivy-next-line-or-history (&optional arg)
622 "Move cursor vertically down ARG candidates.
623 If the input is empty, select the previous history element instead."
625 (when (string= ivy-text "")
626 (ivy-previous-history-element 1))
629 (defun ivy-previous-line (&optional arg)
630 "Move cursor vertically up ARG candidates."
632 (setq arg (or arg 1))
633 (let ((index (- ivy--index arg)))
638 (ivy-set-index index))))
640 (defun ivy-previous-line-or-history (arg)
641 "Move cursor vertically up ARG candidates.
642 If the input is empty, select the previous history element instead."
644 (when (string= ivy-text "")
645 (ivy-previous-history-element 1))
646 (ivy-previous-line arg))
648 (defun ivy-toggle-calling ()
649 "Flip `ivy-calling'."
651 (when (setq ivy-calling (not ivy-calling))
654 (defun ivy--get-action (state)
655 "Get the action function from STATE."
656 (let ((action (ivy-state-action state)))
658 (if (functionp action)
660 (cadr (nth (car action) action))))))
662 (defun ivy--get-window (state)
663 "Get the window from STATE."
664 (let ((window (ivy-state-window state)))
665 (if (window-live-p window)
667 (if (= (length (window-list)) 1)
671 (defun ivy--actionp (x)
672 "Return non-nil when X is a list of actions."
673 (and x (listp x) (not (eq (car x) 'closure))))
675 (defun ivy-next-action ()
676 "When the current action is a list, scroll it forwards."
678 (let ((action (ivy-state-action ivy-last)))
679 (when (ivy--actionp action)
680 (unless (>= (car action) (1- (length action)))
681 (cl-incf (car action))))))
683 (defun ivy-prev-action ()
684 "When the current action is a list, scroll it backwards."
686 (let ((action (ivy-state-action ivy-last)))
687 (when (ivy--actionp action)
688 (unless (<= (car action) 1)
689 (cl-decf (car action))))))
691 (defun ivy-action-name ()
692 "Return the name associated with the current action."
693 (let ((action (ivy-state-action ivy-last)))
694 (if (ivy--actionp action)
698 (nth 2 (nth (car action) action)))
702 "Call the current action without exiting completion."
704 (let ((action (ivy--get-action ivy-last)))
706 (let* ((collection (ivy-state-collection ivy-last))
707 (x (if (and (consp collection)
708 (consp (car collection)))
709 (cdr (assoc ivy--current collection))
710 (if (equal ivy--current "")
713 (prog1 (funcall action x)
714 (unless (or (eq ivy-exit 'done)
715 (equal (selected-window)
716 (active-minibuffer-window))
717 (null (active-minibuffer-window)))
718 (select-window (active-minibuffer-window))))))))
720 (defun ivy-next-line-and-call (&optional arg)
721 "Move cursor vertically down ARG candidates.
722 Call the permanent action if possible."
728 (defun ivy-previous-line-and-call (&optional arg)
729 "Move cursor vertically down ARG candidates.
730 Call the permanent action if possible."
732 (ivy-previous-line arg)
736 (defun ivy-previous-history-element (arg)
737 "Forward to `previous-history-element' with ARG."
739 (previous-history-element arg)
742 (ivy--maybe-scroll-history))
744 (defun ivy-next-history-element (arg)
745 "Forward to `next-history-element' with ARG."
747 (next-history-element arg)
750 (ivy--maybe-scroll-history))
752 (defun ivy--cd-maybe ()
753 "Check if the current input points to a different directory.
754 If so, move to that directory, while keeping only the file name."
756 (let ((input (ivy--input))
758 (if (setq url (ffap-url-p input))
759 (ivy-exit-with-action
761 (funcall ffap-url-fetcher url)))
762 (setq input (expand-file-name input))
763 (let ((file (file-name-nondirectory input))
764 (dir (expand-file-name (file-name-directory input))))
765 (if (string= dir ivy--directory)
767 (delete-minibuffer-contents)
772 (defun ivy--maybe-scroll-history ()
773 "If the selected history element has an index, scroll there."
774 (let ((idx (ignore-errors
776 (minibuffer-prompt-end)
780 (setq ivy--index idx))))
783 "When completing file names, move to directory DIR."
784 (if (null ivy--directory)
786 (setq ivy--old-cands nil)
787 (setq ivy--old-re nil)
789 (setq ivy--all-candidates
790 (ivy--sorted-files (setq ivy--directory dir)))
792 (delete-minibuffer-contents)))
794 (defun ivy-backward-delete-char ()
795 "Forward to `backward-delete-char'.
796 On error (read-only), call `ivy-on-del-error-function'."
798 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
800 (ivy--cd (file-name-directory
806 (backward-delete-char 1)
808 (when ivy-on-del-error-function
809 (funcall ivy-on-del-error-function))))))
811 (defun ivy-delete-char (arg)
812 "Forward to `delete-char' ARG."
814 (unless (= (point) (line-end-position))
817 (defun ivy-forward-char (arg)
818 "Forward to `forward-char' ARG."
820 (unless (= (point) (line-end-position))
823 (defun ivy-kill-word (arg)
824 "Forward to `kill-word' ARG."
826 (unless (= (point) (line-end-position))
829 (defun ivy-kill-line ()
830 "Forward to `kill-line'."
833 (kill-region (minibuffer-prompt-end) (point))
836 (defun ivy-backward-kill-word ()
837 "Forward to `backward-kill-word'."
839 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
841 (ivy--cd (file-name-directory
849 (delete-region (point) pt)))))
851 (defvar ivy--regexp-quote 'regexp-quote
852 "Store the regexp quoting state.")
854 (defun ivy-toggle-regexp-quote ()
855 "Toggle the regexp quoting."
857 (setq ivy--old-re nil)
858 (cl-rotatef ivy--regex-function ivy--regexp-quote))
860 (defvar avy-all-windows)
863 (defvar avy-keys-alist)
865 (defvar avy-styles-alist)
866 (declare-function avy--process "ext:avy")
867 (declare-function avy--style-fn "ext:avy")
869 (eval-after-load 'avy
870 '(add-to-list 'avy-styles-alist '(ivy-avy . pre)))
873 "Jump to one of the current ivy candidates."
875 (unless (require 'avy nil 'noerror)
876 (error "Package avy isn't installed"))
877 (let* ((avy-all-windows nil)
878 (avy-keys (or (cdr (assq 'ivy-avy avy-keys-alist))
880 (avy-style (or (cdr (assq 'ivy-avy
890 (goto-char (point-min))
892 (while (< (point) (point-max))
898 (setq avy-action #'identity)
900 (nreverse candidates)
901 (avy--style-fn avy-style)))))
902 (ivy-set-index (- (line-number-at-pos candidate) 2))
906 (defun ivy-sort-file-function-default (x y)
907 "Compare two files X and Y.
908 Prioritize directories."
909 (if (get-text-property 0 'dirp x)
910 (if (get-text-property 0 'dirp y)
913 (if (get-text-property 0 'dirp y)
917 (defcustom ivy-sort-functions-alist
918 '((read-file-name-internal . ivy-sort-file-function-default)
919 (internal-complete-buffer . nil)
920 (counsel-git-grep-function . nil)
921 (Man-goto-section . nil)
924 "An alist of sorting functions for each collection function.
925 Interactive functions that call completion fit in here as well.
927 Nil means no sorting, which is useful to turn off the sorting for
928 functions that have candidates in the natural buffer order, like
929 `org-refile' or `Man-goto-section'.
931 The entry associated with t is used for all fall-through cases.
933 See also `ivy-sort-max-size'."
937 (const :tag "All other functions" t)
938 (symbol :tag "Function"))
940 (const :tag "plain sort" string-lessp)
941 (const :tag "file sort" ivy-sort-file-function-default)
942 (const :tag "no sort" nil)))
945 (defvar ivy-index-functions-alist
946 '((swiper . ivy-recompute-index-swiper)
947 (swiper-multi . ivy-recompute-index-swiper)
948 (counsel-git-grep . ivy-recompute-index-swiper)
949 (counsel-grep . ivy-recompute-index-swiper-async)
950 (t . ivy-recompute-index-zero))
951 "An alist of index recomputing functions for each collection function.
952 When the input changes, the appropriate function returns an
953 integer - the index of the matched candidate that should be
956 (defvar ivy-re-builders-alist
957 '((t . ivy--regex-plus))
958 "An alist of regex building functions for each collection function.
959 Each function should take a string and return a valid regex or a
960 regex sequence (see below).
962 The entry associated with t is used for all fall-through cases.
963 Possible choices: `ivy--regex', `regexp-quote', `ivy--regex-plus'.
965 If a function returns a list, it should format like this:
966 '((\"matching-regexp\" . t) (\"non-matching-regexp\") ...).
968 The matches will be filtered in a sequence, you can mix the
969 regexps that should match and that should not match as you
972 (defvar ivy-initial-inputs-alist
974 (org-agenda-refile . "^")
975 (org-capture-refile . "^")
977 (counsel-describe-function . "^")
978 (counsel-describe-variable . "^")
981 "Command to initial input table.")
983 (defcustom ivy-sort-max-size 30000
984 "Sorting won't be done for collections larger than this."
987 (defun ivy--sorted-files (dir)
988 "Return the list of files in DIR.
989 Directories come first."
990 (let* ((default-directory dir)
991 (seq (all-completions "" 'read-file-name-internal))
995 (setq seq (delete "./" (delete "../" seq)))
996 (when (eq (setq sort-fn (cdr (assoc 'read-file-name-internal
997 ivy-sort-functions-alist)))
998 #'ivy-sort-file-function-default)
999 (setq seq (mapcar (lambda (x)
1000 (propertize x 'dirp (string-match-p "/\\'" x)))
1003 (setq seq (cl-sort seq sort-fn)))
1004 (dolist (dir ivy-extra-directories)
1009 (cl-defun ivy-read (prompt collection
1010 &key predicate require-match initial-input
1011 history preselect keymap update-fn sort
1012 action unwind re-builder matcher dynamic-collection caller)
1013 "Read a string in the minibuffer, with completion.
1015 PROMPT is a format string, normally ending in a colon and a
1016 space; %d anywhere in the string is replaced by the current
1017 number of matching candidates. For the literal % character,
1018 escape it with %%. See also `ivy-count-format'.
1020 COLLECTION is either a list of strings, a function, an alist, or
1023 If INITIAL-INPUT is not nil, then insert that input in the
1024 minibuffer initially.
1026 KEYMAP is composed with `ivy-minibuffer-map'.
1028 If PRESELECT is not nil, then select the corresponding candidate
1029 out of the ones that match the INITIAL-INPUT.
1031 UPDATE-FN is called each time the current candidate(s) is changed.
1033 When SORT is t, use `ivy-sort-functions-alist' for sorting.
1035 ACTION is a lambda function to call after selecting a result. It
1036 takes a single string argument.
1038 UNWIND is a lambda function to call before exiting.
1040 RE-BUILDER is a lambda function to call to transform text into a
1043 MATCHER is to override matching.
1045 DYNAMIC-COLLECTION is a boolean to specify if the list of
1046 candidates is updated after each input by calling COLLECTION.
1048 CALLER is a symbol to uniquely identify the caller to `ivy-read'.
1049 It is used, along with COLLECTION, to determine which
1050 customizations apply to the current completion session."
1051 (let ((extra-actions (plist-get ivy--actions-list this-command)))
1054 (if (functionp action)
1056 ("o" ,action "default")
1058 (delete-dups (append action extra-actions))))))
1059 (let ((recursive-ivy-last ivy-last))
1063 :collection collection
1064 :predicate predicate
1065 :require-match require-match
1066 :initial-input initial-input
1068 :preselect preselect
1070 :update-fn update-fn
1073 :window (selected-window)
1074 :buffer (current-buffer)
1076 :re-builder re-builder
1078 :dynamic-collection dynamic-collection
1080 (ivy--reset-state ivy-last)
1083 (minibuffer-with-setup-hook
1084 #'ivy--minibuffer-setup
1085 (let* ((hist (or history 'ivy-history))
1086 (minibuffer-completion-table collection)
1087 (minibuffer-completion-predicate predicate)
1088 (resize-mini-windows (cond
1089 ((display-graphic-p) nil)
1090 ((null resize-mini-windows) 'grow-only)
1091 (t resize-mini-windows)))
1092 (res (read-from-minibuffer
1094 (ivy-state-initial-input ivy-last)
1095 (make-composed-keymap keymap ivy-minibuffer-map)
1098 (when (eq ivy-exit 'done)
1099 (let ((item (if ivy--directory
1102 (unless (equal item "")
1103 (set hist (cons (propertize item 'ivy-index ivy--index)
1105 (cdr (symbol-value hist)))))))
1107 (remove-hook 'post-command-hook #'ivy--exhibit)
1108 (when (setq unwind (ivy-state-unwind ivy-last))
1111 (when recursive-ivy-last
1112 (ivy--reset-state (setq ivy-last recursive-ivy-last))))))
1114 (defun ivy--reset-state (state)
1115 "Reset the ivy to STATE.
1116 This is useful for recursive `ivy-read'."
1117 (let ((prompt (or (ivy-state-prompt state) ""))
1118 (collection (ivy-state-collection state))
1119 (predicate (ivy-state-predicate state))
1120 (history (ivy-state-history state))
1121 (preselect (ivy-state-preselect state))
1122 (sort (ivy-state-sort state))
1123 (re-builder (ivy-state-re-builder state))
1124 (dynamic-collection (ivy-state-dynamic-collection state))
1125 (initial-input (ivy-state-initial-input state))
1126 (require-match (ivy-state-require-match state)))
1127 (unless initial-input
1128 (setq initial-input (cdr (assoc this-command
1129 ivy-initial-inputs-alist))))
1130 (setq ivy--directory nil)
1131 (setq ivy-case-fold-search 'auto)
1132 (setq ivy--regex-function
1134 (and (functionp collection)
1135 (cdr (assoc collection ivy-re-builders-alist)))
1136 (cdr (assoc t ivy-re-builders-alist))
1138 (setq ivy--subexps 0)
1139 (setq ivy--regexp-quote 'regexp-quote)
1140 (setq ivy--old-text "")
1141 (setq ivy--full-length nil)
1143 (setq ivy-calling nil)
1145 (cond ((eq collection 'Info-read-node-name-1)
1146 (if (equal Info-current-file "dir")
1148 (mapcar (lambda (x) (format "(%s)" x))
1149 (cl-delete-duplicates
1150 (all-completions "(" collection predicate)
1152 (setq coll (all-completions "" collection predicate))))
1153 ((eq collection 'read-file-name-internal)
1154 (setq ivy--directory default-directory)
1157 (let ((preselect-directory (file-name-directory preselect)))
1158 (unless (or (null preselect-directory)
1159 (string= preselect-directory
1161 (setq ivy--directory preselect-directory))
1163 (ivy-state-preselect state)
1164 (setq preselect (file-name-nondirectory preselect)))))
1165 (setq coll (ivy--sorted-files ivy--directory))
1167 (unless (or require-match
1168 (equal initial-input default-directory)
1169 (equal initial-input ""))
1170 (setq coll (cons initial-input coll)))
1171 (setq initial-input nil)))
1172 ((eq collection 'internal-complete-buffer)
1173 (setq coll (ivy--buffer-list "" ivy-use-virtual-buffers)))
1174 ((or (functionp collection)
1175 (byte-code-function-p collection)
1176 (vectorp collection)
1177 (and (consp collection) (listp (car collection)))
1178 (hash-table-p collection))
1179 (setq coll (all-completions "" collection predicate)))
1181 (setq coll collection)))
1183 (if (and (functionp collection)
1184 (setq sort-fn (assoc collection ivy-sort-functions-alist)))
1185 (when (and (setq sort-fn (cdr sort-fn))
1186 (not (eq collection 'read-file-name-internal)))
1187 (setq coll (cl-sort coll sort-fn)))
1188 (unless (eq history 'org-refile-history)
1189 (if (and (setq sort-fn (cdr (assoc t ivy-sort-functions-alist)))
1190 (<= (length coll) ivy-sort-max-size))
1191 (setq coll (cl-sort (copy-sequence coll) sort-fn))))))
1193 (unless (or (and require-match
1194 (not (eq collection 'internal-complete-buffer)))
1196 (let ((re (regexp-quote preselect)))
1197 (cl-find-if (lambda (x) (string-match re x))
1199 (setq coll (cons preselect coll))))
1200 (setq ivy--old-re nil)
1201 (setq ivy--old-cands nil)
1202 (when (integerp preselect)
1203 (setq ivy--old-re "")
1204 (setq ivy--index preselect))
1206 ;; Needed for anchor to work
1207 (setq ivy--old-cands coll)
1208 (setq ivy--old-cands (ivy--filter initial-input coll)))
1209 (setq ivy--all-candidates coll)
1210 (unless (integerp preselect)
1211 (setq ivy--index (or
1212 (and dynamic-collection
1215 (ivy--preselect-index
1222 (setq ivy--default (or
1223 (thing-at-point 'url)
1224 (thing-at-point 'symbol)
1227 (cond ((string-match "%.*d" prompt)
1229 ((null ivy-count-format)
1231 "`ivy-count-format' can't be nil. Set it to an empty string instead"))
1232 ((string-match "%d.*%d" ivy-count-format)
1233 (let ((w (length (number-to-string
1234 (length ivy--all-candidates))))
1235 (s (copy-sequence ivy-count-format)))
1236 (string-match "%d" s)
1238 (string-match "%d" s (match-end 0))
1239 (setq s (replace-match (format "%%-%dd" w) nil nil s))
1240 (string-match "%d" s)
1241 (concat (replace-match (format "%%%dd" w) nil nil s)
1243 ((string-match "%.*d" ivy-count-format)
1244 (concat ivy-count-format prompt))
1249 (setf (ivy-state-initial-input ivy-last) initial-input)))
1252 (defun ivy-completing-read (prompt collection
1253 &optional predicate require-match initial-input
1254 history def _inherit-input-method)
1255 "Read a string in the minibuffer, with completion.
1257 This interface conforms to `completing-read' and can be used for
1258 `completing-read-function'.
1260 PROMPT is a string to prompt with; normally it ends in a colon and a space.
1261 COLLECTION can be a list of strings, an alist, an obarray or a hash table.
1262 PREDICATE limits completion to a subset of COLLECTION.
1263 REQUIRE-MATCH is specified with a boolean value. See `completing-read'.
1264 INITIAL-INPUT is a string that can be inserted into the minibuffer initially.
1265 HISTORY is a list of previously selected inputs.
1266 DEF is the default value.
1267 _INHERIT-INPUT-METHOD is currently ignored."
1269 ;; See the doc of `completing-read'.
1270 (when (consp history)
1271 (when (numberp (cdr history))
1272 (setq initial-input (nth (1- (cdr history))
1273 (symbol-value (car history)))))
1274 (setq history (car history)))
1275 (ivy-read (replace-regexp-in-string "%" "%%" prompt)
1277 :predicate predicate
1278 :require-match require-match
1279 :initial-input (if (consp initial-input)
1281 (if (and (stringp initial-input)
1282 (string-match "\\+" initial-input))
1283 (replace-regexp-in-string
1284 "\\+" "\\\\+" initial-input)
1286 :preselect (if (listp def) (car def) def)
1290 (let ((sort (assoc this-command ivy-sort-functions-alist)))
1296 (define-minor-mode ivy-mode
1297 "Toggle Ivy mode on or off.
1298 Turn Ivy mode on if ARG is positive, off otherwise.
1299 Turning on Ivy mode sets `completing-read-function' to
1300 `ivy-completing-read'.
1305 Minibuffer bindings:
1306 \\{ivy-minibuffer-map}"
1309 :keymap ivy-mode-map
1312 (setq completing-read-function 'ivy-completing-read)
1313 (setq completing-read-function 'completing-read-default)))
1315 (defun ivy--preselect-index (preselect candidates)
1316 "Return the index of PRESELECT in CANDIDATES."
1317 (cond ((integerp preselect)
1319 ((cl-position preselect candidates :test #'equal))
1320 ((stringp preselect)
1321 (let ((re (regexp-quote preselect)))
1324 (string-match re x))
1329 (defvar ivy--regex-hash
1330 (make-hash-table :test #'equal)
1331 "Store pre-computed regex.")
1333 (defun ivy--split (str)
1334 "Split STR into a list by single spaces.
1335 The remaining spaces stick to their left.
1336 This allows to \"quote\" N spaces by inputting N+1 spaces."
1337 (let ((len (length str))
1342 (while (and (string-match " +" str start1)
1344 (setq match-len (- (match-end 0) (match-beginning 0)))
1348 (setq start1 start0)
1350 (push (substring str start1 (match-beginning 0)) res)
1351 (setq start1 (match-end 0)))
1352 (setq str (replace-match
1353 (make-string (1- match-len) ?\ )
1355 (setq start0 (or start0 start1))
1356 (setq start1 (1- (match-end 0)))))
1358 (push (substring str start0) res)
1359 (setq s (substring str start1))
1360 (unless (= (length s) 0)
1364 (defun ivy--regex (str &optional greedy)
1365 "Re-build regex pattern from STR in case it has a space.
1366 When GREEDY is non-nil, join words in a greedy way."
1367 (let ((hashed (unless greedy
1368 (gethash str ivy--regex-hash))))
1371 (setq ivy--subexps (car hashed)))
1372 (when (string-match "\\([^\\]\\|^\\)\\\\$" str)
1373 (setq str (substring str 0 -1)))
1375 (let ((subs (ivy--split str)))
1376 (if (= (length subs) 1)
1378 (setq ivy--subexps 0)
1381 (setq ivy--subexps (length subs))
1384 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1386 (format "\\(%s\\)" x)))
1391 ivy--regex-hash)))))
1393 (defun ivy--regex-ignore-order (str)
1394 "Re-build regex from STR by splitting at spaces.
1395 Ignore the order of each group.
1397 ATTENTION: This is just a proof of concept and may not work as
1398 expected. Besides ignoring the order of the tokens where 'foo'
1399 and 'bar', 'bar' and 'foo' are matched, it also matches multiple
1400 occurrences of 'foo' and 'bar'. To ignore the sort order and avoid
1401 multiple matches, use `ivy-restrict-to-matches' instead.
1403 (let* ((subs (split-string str " +" t))
1404 (len (length subs)))
1407 (setq ivy--subexps 0)
1410 (setq ivy--subexps len)
1411 (let ((all (mapconcat #'identity subs "\\|")))
1414 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1416 (format "\\(%s\\)" x)))
1420 (defun ivy--regex-plus (str)
1421 "Build a regex sequence from STR.
1422 Spaces are wild card characters, everything before \"!\" should
1423 match. Everything after \"!\" should not match."
1424 (let ((parts (split-string str "!" t)))
1425 (cl-case (length parts)
1429 (ivy--regex (car parts)))
1433 (split-string (cadr parts) " " t))))
1434 (cons (cons (ivy--regex (car parts)) t)
1436 (t (error "Unexpected: use only one !")))))
1438 (defun ivy--regex-fuzzy (str)
1439 "Build a regex sequence from STR.
1440 Insert .* between each char."
1441 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1443 (concat (match-string 1 str)
1446 (format "\\(%c\\)" x))
1447 (string-to-list (match-string 2 str)) ".*")
1448 (match-string 3 str))
1449 (setq ivy--subexps (length (match-string 2 str))))
1453 (defun ivy--minibuffer-setup ()
1454 "Setup ivy completion in the minibuffer."
1455 (set (make-local-variable 'completion-show-inline-help) nil)
1456 (set (make-local-variable 'minibuffer-default-add-function)
1458 (list ivy--default)))
1459 (when (display-graphic-p)
1460 (setq truncate-lines t))
1461 (setq-local max-mini-window-height ivy-height)
1462 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1463 ;; show completions with empty input
1466 (defun ivy--input ()
1467 "Return the current minibuffer input."
1468 ;; assume one-line minibuffer input
1469 (buffer-substring-no-properties
1470 (minibuffer-prompt-end)
1471 (line-end-position)))
1473 (defun ivy--cleanup ()
1474 "Delete the displayed completion candidates."
1476 (goto-char (minibuffer-prompt-end))
1477 (delete-region (line-end-position) (point-max))))
1479 (defun ivy--insert-prompt ()
1480 "Update the prompt according to `ivy--prompt'."
1482 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1483 counsel-find-symbol))
1484 (setq ivy--prompt-extra ""))
1486 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1488 (setq head (match-string 1 ivy--prompt))
1490 (setq head (substring ivy--prompt 0 -1))
1492 (let ((inhibit-read-only t)
1493 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1496 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1497 (> (minibuffer-depth) 1))
1498 (format "[%d] " (minibuffer-depth))
1501 (if (string-match "%d.*%d" ivy-count-format)
1504 (or (and (ivy-state-dynamic-collection ivy-last)
1508 (or (and (ivy-state-dynamic-collection ivy-last)
1513 (d-str (if ivy--directory
1514 (abbreviate-file-name ivy--directory)
1517 (goto-char (point-min))
1518 (delete-region (point-min) (minibuffer-prompt-end))
1519 (if (> (+ (mod (+ (length n-str) (length d-str)) (window-width))
1522 (setq n-str (concat n-str "\n" d-str))
1523 (setq n-str (concat n-str d-str)))
1524 (let ((regex (format "\\([^\n]\\{%d\\}\\)[^\n]" (window-width))))
1525 (while (string-match regex n-str)
1526 (setq n-str (replace-match (concat (match-string 1 n-str) "\n") nil t n-str 1))))
1527 (set-text-properties 0 (length n-str)
1528 `(face minibuffer-prompt ,@std-props)
1530 (ivy--set-match-props n-str "confirm"
1531 `(face ivy-confirm-face ,@std-props))
1532 (ivy--set-match-props n-str "match required"
1533 `(face ivy-match-required-face ,@std-props))
1535 ;; get out of the prompt area
1536 (constrain-to-field nil (point-max))))))
1538 (defun ivy--set-match-props (str match props)
1539 "Set STR text properties that match MATCH to PROPS."
1540 (when (string-match match str)
1541 (set-text-properties
1547 (defvar inhibit-message)
1549 (defun ivy--sort-maybe (collection)
1550 "Sort COLLECTION if needed."
1551 (let ((sort (ivy-state-sort ivy-last))
1555 (let ((sort-fn (cond ((functionp sort)
1557 ((setq entry (assoc (ivy-state-collection ivy-last)
1558 ivy-sort-functions-alist))
1561 (cdr (assoc t ivy-sort-functions-alist))))))
1562 (if (functionp sort-fn)
1563 (cl-sort (copy-sequence collection) sort-fn)
1566 (defun ivy--exhibit ()
1567 "Insert Ivy completions display.
1568 Should be run via minibuffer `post-command-hook'."
1569 (when (memq 'ivy--exhibit post-command-hook)
1570 (let ((inhibit-field-text-motion nil))
1571 (constrain-to-field nil (point-max)))
1572 (setq ivy-text (ivy--input))
1573 (if (ivy-state-dynamic-collection ivy-last)
1574 ;; while-no-input would cause annoying
1575 ;; "Waiting for process to die...done" message interruptions
1576 (let ((inhibit-message t))
1577 (unless (equal ivy--old-text ivy-text)
1579 (setq ivy--all-candidates
1581 (funcall (ivy-state-collection ivy-last) ivy-text)))
1582 (setq ivy--old-text ivy-text)))
1583 (when ivy--all-candidates
1584 (ivy--insert-minibuffer
1585 (ivy--format ivy--all-candidates))))
1586 (cond (ivy--directory
1587 (if (string-match "/\\'" ivy-text)
1588 (if (member ivy-text ivy--all-candidates)
1589 (ivy--cd (expand-file-name ivy-text ivy--directory))
1590 (when (string-match "//\\'" ivy-text)
1591 (if (and default-directory
1592 (string-match "\\`[[:alpha:]]:/" default-directory))
1593 (ivy--cd (match-string 0 default-directory))
1595 (when (string-match "[[:alpha:]]:/$" ivy-text)
1596 (let ((drive-root (match-string 0 ivy-text)))
1597 (when (file-exists-p drive-root)
1598 (ivy--cd drive-root)))))
1599 (if (string-match "\\`~\\'" ivy-text)
1600 (ivy--cd (expand-file-name "~/")))))
1601 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1602 (when (or (and (string-match "\\` " ivy-text)
1603 (not (string-match "\\` " ivy--old-text)))
1604 (and (string-match "\\` " ivy--old-text)
1605 (not (string-match "\\` " ivy-text))))
1606 (setq ivy--all-candidates
1607 (if (and (> (length ivy-text) 0)
1608 (eq (aref ivy-text 0)
1610 (ivy--buffer-list " ")
1611 (ivy--buffer-list "" ivy-use-virtual-buffers)))
1612 (setq ivy--old-re nil))))
1613 (ivy--insert-minibuffer
1614 (with-current-buffer (ivy-state-buffer ivy-last)
1616 (ivy--filter ivy-text ivy--all-candidates))))
1617 (setq ivy--old-text ivy-text))))
1619 (defun ivy--insert-minibuffer (text)
1620 "Insert TEXT into minibuffer with appropriate cleanup."
1621 (let ((resize-mini-windows nil)
1622 (update-fn (ivy-state-update-fn ivy-last))
1626 (funcall update-fn))
1627 (ivy--insert-prompt)
1628 ;; Do nothing if while-no-input was aborted.
1629 (when (stringp text)
1630 (let ((buffer-undo-list t))
1634 (when (display-graphic-p)
1635 (ivy--resize-minibuffer-to-fit))))
1637 (defun ivy--resize-minibuffer-to-fit ()
1638 "Resize the minibuffer window size to fit the text in the minibuffer."
1639 (with-selected-window (minibuffer-window)
1640 (if (fboundp 'window-text-pixel-size)
1641 (let ((text-height (cdr (window-text-pixel-size)))
1642 (body-height (window-body-height nil t)))
1643 (when (> text-height body-height)
1644 (window-resize nil (- text-height body-height) nil t t)))
1645 (let ((text-height (count-screen-lines))
1646 (body-height (window-body-height)))
1647 (when (> text-height body-height)
1648 (window-resize nil (- text-height body-height) nil t))))))
1650 (declare-function colir-blend-face-background "ext:colir")
1652 (defun ivy--add-face (str face)
1653 "Propertize STR with FACE.
1654 `font-lock-append-text-property' is used, since it's better than
1655 `propertize' or `add-face-text-property' in this case."
1659 (colir-blend-face-background 0 (length str) face str)
1660 (let ((foreground (face-foreground face)))
1662 (add-face-text-property
1664 `(:foreground ,foreground)
1669 (font-lock-append-text-property 0 (length str) 'face face str))))
1672 (declare-function flx-make-string-cache "ext:flx")
1673 (declare-function flx-score "ext:flx")
1675 (defvar ivy--flx-cache nil)
1677 (eval-after-load 'flx
1678 '(setq ivy--flx-cache (flx-make-string-cache)))
1680 (defun ivy-toggle-case-fold ()
1681 "Toggle the case folding between nil and auto.
1682 In any completion session, the case folding starts in auto:
1684 - when the input is all lower case, `case-fold-search' is t
1687 You can toggle this to make `case-fold-search' nil regardless of input."
1689 (setq ivy-case-fold-search
1690 (if ivy-case-fold-search
1693 ;; reset cache so that the candidate list updates
1694 (setq ivy--old-re nil))
1696 (defun ivy--filter (name candidates)
1697 "Return all items that match NAME in CANDIDATES.
1698 CANDIDATES are assumed to be static."
1699 (let ((re (funcall ivy--regex-function name)))
1700 (if (and (equal re ivy--old-re)
1702 ;; quick caching for "C-n", "C-p" etc.
1704 (let* ((re-str (if (listp re) (caar re) re))
1705 (matcher (ivy-state-matcher ivy-last))
1707 (and ivy-case-fold-search
1708 (string= name (downcase name))))
1711 (funcall matcher re candidates))
1714 (stringp ivy--old-re)
1715 (not (string-match "\\\\" ivy--old-re))
1716 (not (equal ivy--old-re ""))
1718 (if (string-match "\\\\)\\'" ivy--old-re)
1719 (substring ivy--old-re 0 -2)
1725 (lambda (x) (string-match re x))
1728 (let ((re-list (if (stringp re) (list (cons re t)) re))
1730 (dolist (re re-list)
1737 (let ((re-str (car re)))
1738 (lambda (x) (string-match re-str x)))
1741 (ivy--recompute-index name re-str cands)
1742 (setq ivy--old-re (if cands re-str ""))
1743 (setq ivy--old-cands (ivy--sort name cands))))))
1745 (defcustom ivy-sort-matches-functions-alist '((t . nil))
1746 "An alist of functions used to sort the matching candidates.
1748 This is different from `ivy-sort-functions-alist', which is used
1749 to sort the whole collection only once. The functions taken from
1750 here are instead used on each input change, but they are used
1751 only on already matching candidates, not on all of them.
1753 The alist KEY is a collection function or t to match previously
1754 not matched collection functions.
1756 The alist VAL is a sorting function with the signature of
1757 `ivy--prefix-sort'.")
1759 (defun ivy--sort-files-by-date (_name candidates)
1760 "Re-soft CANDIDATES according to file modification date."
1761 (let ((default-directory ivy--directory))
1762 (cl-sort (copy-sequence candidates)
1765 (nth 5 (file-attributes f2))
1766 (nth 5 (file-attributes f1)))))))
1768 (defun ivy--sort (name candidates)
1769 "Re-sort CANDIDATES by NAME.
1770 All CANDIDATES are assumed to match NAME."
1771 (let ((key (or (ivy-state-caller ivy-last)
1772 (when (functionp (ivy-state-collection ivy-last))
1773 (ivy-state-collection ivy-last))))
1775 (cond ((and (require 'flx nil 'noerror)
1776 (eq ivy--regex-function 'ivy--regex-fuzzy))
1777 (ivy--flx-sort name candidates))
1778 ((setq fun (cdr (or (assoc key ivy-sort-matches-functions-alist)
1779 (assoc t ivy-sort-matches-functions-alist))))
1780 (funcall fun name candidates))
1784 (defun ivy--prefix-sort (name candidates)
1785 "Re-sort CANDIDATES.
1786 Prefix matches to NAME are put ahead of the list."
1787 (if (or (string-match "^\\^" name) (string= name ""))
1789 (let ((re-prefix (concat "^" (funcall ivy--regex-function name)))
1792 (dolist (s candidates)
1793 (if (string-match re-prefix s)
1795 (push s res-noprefix)))
1797 (nreverse res-prefix)
1798 (nreverse res-noprefix)))))
1800 (defun ivy--recompute-index (name re-str cands)
1801 (let* ((caller (ivy-state-caller ivy-last))
1802 (func (or (and caller (cdr (assoc caller ivy-index-functions-alist)))
1803 (cdr (assoc t ivy-index-functions-alist))
1804 #'ivy-recompute-index-zero)))
1805 (unless (eq this-command 'ivy-resume)
1808 (cl-position (if (and (> (length re-str) 0)
1809 (eq ?^ (aref re-str 0)))
1810 (substring re-str 1)
1815 (concat re-str "/") cands
1817 (and (not (string= name ""))
1818 (not (and (require 'flx nil 'noerror)
1819 (eq ivy--regex-function 'ivy--regex-fuzzy)
1820 (< (length cands) 200)))
1822 (cl-position (nth ivy--index ivy--old-cands)
1824 (funcall func re-str cands))))
1825 (when (and (or (string= name "")
1827 (not (equal ivy--old-re "")))
1829 (or (ivy--preselect-index
1830 (ivy-state-preselect ivy-last)
1834 (defun ivy-recompute-index-swiper (_re-str cands)
1835 (let ((tail (nthcdr ivy--index ivy--old-cands))
1837 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
1839 (while (and tail (null idx))
1840 ;; Compare with eq to handle equal duplicates in cands
1841 (setq idx (cl-position (pop tail) cands)))
1845 ;; already in ivy-state-buffer
1846 (let ((n (line-number-at-pos))
1850 (when (eq n (read (get-text-property 0 'display c)))
1855 (defun ivy-recompute-index-swiper-async (_re-str cands)
1856 (let ((tail (nthcdr ivy--index ivy--old-cands))
1858 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
1860 (while (and tail (null idx))
1861 ;; Compare with `equal', since the collection is re-created
1862 ;; each time with `split-string'
1863 (setq idx (cl-position (pop tail) cands :test #'equal)))
1867 (defun ivy-recompute-index-zero (_re-str _cands)
1870 (defun ivy--flx-sort (name cands)
1871 "Sort according to closeness to string NAME the string list CANDS."
1874 (< (length cands) 200))
1875 (let* ((flx-name (if (string-match "^\\^" name)
1882 (let ((score (car (flx-score x flx-name ivy--flx-cache))))
1886 (if cands-with-score
1888 (sort cands-with-score
1890 (> (car x) (car y)))))
1896 (defcustom ivy-format-function 'ivy-format-function-default
1897 "Function to transform the list of candidates into a string.
1898 This string is inserted into the minibuffer."
1900 (const :tag "Default" ivy-format-function-default)
1901 (const :tag "Arrow prefix" ivy-format-function-arrow)
1902 (const :tag "Full line" ivy-format-function-line)))
1904 (defun ivy--truncate-string (str width)
1905 "Truncate STR to WIDTH."
1906 (if (> (string-width str) width)
1907 (concat (substring str 0 (min (- width 3)
1908 (- (length str) 3))) "...")
1911 (defun ivy--format-function-generic (selected-fn other-fn cand-pairs separator)
1912 "Transform CAND-PAIRS into a string for minibuffer.
1913 SELECTED-FN and OTHER-FN each take two string arguments.
1914 SEPARATOR is used to join the candidates."
1918 (let ((str (car pair))
1920 (curr (eq (cl-incf i) ivy--index)))
1922 (funcall selected-fn str extra)
1923 (funcall other-fn str extra))))
1927 (defun ivy-format-function-default (cand-pairs)
1928 "Transform CAND-PAIRS into a string for minibuffer."
1929 (ivy--format-function-generic
1931 (concat (ivy--add-face str 'ivy-current-match) extra))
1936 (defun ivy-format-function-arrow (cand-pairs)
1937 "Transform CAND-PAIRS into a string for minibuffer."
1938 (ivy--format-function-generic
1940 (concat "> " (ivy--add-face str 'ivy-current-match) extra))
1942 (concat " " str extra))
1946 (defun ivy-format-function-line (cand-pairs)
1947 "Transform CAND-PAIRS into a string for minibuffer."
1948 (ivy--format-function-generic
1950 (ivy--add-face (concat str extra "\n") 'ivy-current-match))
1952 (concat str extra "\n"))
1956 (defface ivy-minibuffer-match-face-1
1957 '((((class color) (background light))
1958 :background "#d3d3d3")
1959 (((class color) (background dark))
1960 :background "#555555"))
1961 "The background face for `ivy' minibuffer matches.")
1963 (defface ivy-minibuffer-match-face-2
1964 '((((class color) (background light))
1965 :background "#e99ce8" :weight bold)
1966 (((class color) (background dark))
1967 :background "#777777" :weight bold))
1968 "Face for `ivy' minibuffer matches modulo 1.")
1970 (defface ivy-minibuffer-match-face-3
1971 '((((class color) (background light))
1972 :background "#bbbbff" :weight bold)
1973 (((class color) (background dark))
1974 :background "#7777ff" :weight bold))
1975 "Face for `ivy' minibuffer matches modulo 2.")
1977 (defface ivy-minibuffer-match-face-4
1978 '((((class color) (background light))
1979 :background "#ffbbff" :weight bold)
1980 (((class color) (background dark))
1981 :background "#8a498a" :weight bold))
1982 "Face for `ivy' minibuffer matches modulo 3.")
1984 (defcustom ivy-minibuffer-faces
1985 '(ivy-minibuffer-match-face-1
1986 ivy-minibuffer-match-face-2
1987 ivy-minibuffer-match-face-3
1988 ivy-minibuffer-match-face-4)
1989 "List of `ivy' faces for minibuffer group matches.")
1991 (defun ivy--format-minibuffer-line (str)
1993 (str (copy-sequence str)))
1994 (when (eq ivy-display-style 'fancy)
1996 (setq ivy--old-re (funcall ivy--regex-function ivy-text)))
1997 (while (and (string-match ivy--old-re str start)
1998 (> (- (match-end 0) (match-beginning 0)) 0))
1999 (setq start (match-end 0))
2001 (while (<= i ivy--subexps)
2003 (cond ((zerop ivy--subexps)
2004 (cadr ivy-minibuffer-faces))
2006 (car ivy-minibuffer-faces))
2008 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2009 ivy-minibuffer-faces)))))
2010 (if (fboundp 'add-face-text-property)
2011 (add-face-text-property
2017 (font-lock-append-text-property
2026 (defun ivy--format (cands)
2027 "Return a string for CANDS suitable for display in the minibuffer.
2028 CANDS is a list of strings."
2029 (setq ivy--length (length cands))
2030 (when (>= ivy--index ivy--length)
2031 (setq ivy--index (max (1- ivy--length) 0)))
2033 (setq ivy--current "")
2034 (let* ((half-height (/ ivy-height 2))
2035 (start (max 0 (- ivy--index half-height)))
2036 (end (min (+ start (1- ivy-height)) ivy--length))
2037 (start (max 0 (min start (- end (1- ivy-height)))))
2038 (cands (cl-subseq cands start end))
2039 (index (- ivy--index start)))
2040 (cond (ivy--directory
2041 (setq cands (mapcar (lambda (x)
2042 (if (string-match-p "/\\'" x)
2043 (propertize x 'face 'ivy-subdir)
2046 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
2047 (setq cands (mapcar (lambda (x)
2048 (let ((b (get-buffer x)))
2050 (buffer-file-name b)
2051 (buffer-modified-p b))
2052 (propertize x 'face 'ivy-modified-buffer)
2055 (setq ivy--current (copy-sequence (nth index cands)))
2056 (let* ((ivy--index index)
2059 (cons (ivy--format-minibuffer-line cand) nil)) cands))
2060 (res (concat "\n" (funcall ivy-format-function cand-pairs))))
2061 (put-text-property 0 (length res) 'read-only nil res)
2064 (defvar ivy--virtual-buffers nil
2065 "Store the virtual buffers alist.")
2067 (defvar recentf-list)
2069 (defface ivy-virtual '((t :inherit font-lock-builtin-face))
2070 "Face used by Ivy for matching virtual buffer names.")
2072 (defcustom ivy-virtual-abbreviate 'name
2073 "The mode of abbreviation for virtual buffer names."
2075 (const :tag "Only name" name)
2076 (const :tag "Full path" full)
2077 ;; eventually, uniquify
2080 (defun ivy--virtual-buffers ()
2081 "Adapted from `ido-add-virtual-buffers-to-list'."
2082 (unless recentf-mode
2084 (let ((bookmarks (and (boundp 'bookmark-alist)
2086 virtual-buffers name)
2087 (dolist (head (append
2089 (delete " - no file -"
2090 (delq nil (mapcar (lambda (bookmark)
2091 (cdr (assoc 'filename bookmark)))
2094 (if (eq ivy-virtual-abbreviate 'name)
2095 (file-name-nondirectory head)
2096 (expand-file-name head)))
2097 (when (equal name "")
2098 (setq name (file-name-nondirectory (directory-file-name head))))
2099 (when (equal name "")
2101 (and (not (equal name ""))
2102 (null (get-file-buffer head))
2103 (not (assoc name virtual-buffers))
2104 (push (cons name head) virtual-buffers)))
2105 (when virtual-buffers
2106 (dolist (comp virtual-buffers)
2107 (put-text-property 0 (length (car comp))
2110 (setq ivy--virtual-buffers (nreverse virtual-buffers))
2111 (mapcar #'car ivy--virtual-buffers))))
2113 (defun ivy--buffer-list (str &optional virtual)
2114 "Return the buffers that match STR.
2115 When VIRTUAL is non-nil, add virtual buffers."
2120 (if (with-current-buffer x
2122 (abbreviate-file-name default-directory)))
2123 (propertize x 'face 'ivy-remote)
2125 (all-completions str 'internal-complete-buffer))
2127 (ivy--virtual-buffers)))))
2129 (defun ivy--switch-buffer-action (buffer)
2131 BUFFER may be a string or nil."
2133 (if (zerop (length buffer))
2135 ivy-text nil 'force-same-window)
2136 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2138 (not (get-buffer buffer)))
2139 (find-file (cdr virtual))
2141 buffer nil 'force-same-window))))))
2143 (defun ivy--switch-buffer-other-window-action (buffer)
2144 "Switch to BUFFER in other window.
2145 BUFFER may be a string or nil."
2146 (if (zerop (length buffer))
2147 (switch-to-buffer-other-window ivy-text)
2148 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2150 (not (get-buffer buffer)))
2151 (find-file-other-window (cdr virtual))
2152 (switch-to-buffer-other-window buffer)))))
2154 (defun ivy--rename-buffer-action (buffer)
2156 (let ((new-name (read-string "Rename buffer (to new name): ")))
2157 (with-current-buffer buffer
2158 (rename-buffer new-name))))
2160 (defvar ivy-switch-buffer-map (make-sparse-keymap))
2167 (ivy--reset-state ivy-last))
2170 ivy--switch-buffer-other-window-action
2173 ivy--rename-buffer-action
2177 (defun ivy-switch-buffer ()
2178 "Switch to another buffer."
2181 (call-interactively 'switch-to-buffer)
2182 (let ((this-command 'ivy-switch-buffer))
2183 (ivy-read "Switch to buffer: " 'internal-complete-buffer
2184 :preselect (buffer-name (other-buffer (current-buffer)))
2185 :action #'ivy--switch-buffer-action
2186 :keymap ivy-switch-buffer-map))))
2189 (defun ivy-recentf ()
2190 "Find a file on `recentf-list'."
2192 (ivy-read "Recentf: " recentf-list
2198 (defun ivy-yank-word ()
2199 "Pull next word from buffer into search string."
2204 (le (line-end-position)))
2208 (setq amend (buffer-substring-no-properties pt (point))))))
2210 (insert (replace-regexp-in-string " +" " " amend)))))
2212 (defun ivy-kill-ring-save ()
2213 "Store the current candidates into the kill ring.
2214 If the region is active, forward to `kill-ring-save' instead."
2216 (if (region-active-p)
2217 (call-interactively 'kill-ring-save)
2224 (defun ivy-insert-current ()
2225 "Make the current candidate into current input.
2226 Don't finish completion."
2228 (delete-minibuffer-contents)
2229 (if (and ivy--directory
2230 (string-match "/$" ivy--current))
2231 (insert (substring ivy--current 0 -1))
2232 (insert ivy--current)))
2234 (defun ivy-toggle-fuzzy ()
2235 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
2237 (setq ivy--old-re nil)
2238 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
2239 (setq ivy--regex-function 'ivy--regex-plus)
2240 (setq ivy--regex-function 'ivy--regex-fuzzy)))
2242 (defun ivy-reverse-i-search ()
2243 "Enter a recursive `ivy-read' session using the current history.
2244 The selected history element will be inserted into the minibuffer."
2246 (let ((enable-recursive-minibuffers t)
2247 (history (symbol-value (ivy-state-history ivy-last)))
2248 (old-last ivy-last))
2249 (ivy-read "Reverse-i-search: "
2253 (setq ivy-last old-last))
2254 (delete-minibuffer-contents)
2255 (insert (substring-no-properties x))
2258 (defun ivy-restrict-to-matches ()
2259 "Restrict candidates to current matches and erase input."
2261 (delete-minibuffer-contents)
2262 (setq ivy--all-candidates
2263 (ivy--filter ivy-text ivy--all-candidates)))
2266 (defvar-local ivy-occur-last nil
2267 "Buffer-local value of `ivy-last'.
2268 Can't re-use `ivy-last' because using e.g. `swiper' in the same
2269 buffer would modify `ivy-last'.")
2271 (defvar ivy-occur-mode-map
2272 (let ((map (make-sparse-keymap)))
2273 (define-key map [mouse-1] 'ivy-occur-click)
2274 (define-key map (kbd "RET") 'ivy-occur-press)
2275 (define-key map (kbd "j") 'next-line)
2276 (define-key map (kbd "k") 'previous-line)
2277 (define-key map (kbd "h") 'backward-char)
2278 (define-key map (kbd "l") 'forward-char)
2279 (define-key map (kbd "g") 'ivy-occur-press)
2280 (define-key map (kbd "a") 'ivy-occur-read-action)
2281 (define-key map (kbd "o") 'ivy-occur-dispatch)
2282 (define-key map (kbd "q") 'quit-window)
2284 "Keymap for Ivy Occur mode.")
2286 (define-derived-mode ivy-occur-mode fundamental-mode "Ivy-Occur"
2287 "Major mode for output from \\[ivy-occur].
2289 \\{ivy-occur-mode-map}")
2291 (defvar ivy-occur-grep-mode-map
2292 (let ((map (copy-keymap ivy-occur-mode-map)))
2293 (define-key map (kbd "C-x C-q") 'ivy-wgrep-change-to-wgrep-mode)
2295 "Keymap for Ivy Occur Grep mode.")
2297 (define-derived-mode ivy-occur-grep-mode grep-mode "Ivy-Occur"
2298 "Major mode for output from \\[ivy-occur].
2300 \\{ivy-occur-grep-mode-map}")
2302 (defvar counsel-git-grep-cmd)
2305 "Stop completion and put the current matches into a new buffer.
2307 The new buffer remembers current action(s).
2309 While in the *ivy-occur* buffer, selecting a candidate with RET or
2310 a mouse click will call the appropriate action for that candidate.
2312 There is no limit on the number of *ivy-occur* buffers."
2315 (generate-new-buffer
2316 (format "*ivy-occur%s \"%s\"*"
2318 (if (setq caller (ivy-state-caller ivy-last))
2319 (concat " " (prin1-to-string caller))
2322 (do-grep (eq (ivy-state-caller ivy-last) 'counsel-git-grep)))
2323 (with-current-buffer buffer
2326 (setq ivy--old-cands
2328 (shell-command-to-string
2329 (format counsel-git-grep-cmd ivy--old-re))
2332 (ivy-occur-grep-mode))
2334 (setf (ivy-state-text ivy-last) ivy-text)
2335 (setq ivy-occur-last ivy-last)
2336 (setq-local ivy--directory ivy--directory)
2337 (let ((inhibit-read-only t))
2340 ;; Need precise number of header lines for `wgrep' to work.
2341 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
2342 default-directory)))
2343 (insert (format "%d candidates:\n" (length ivy--old-cands)))
2344 (dolist (cand ivy--old-cands)
2345 (let ((str (if do-grep
2347 (concat " " cand))))
2348 (add-text-properties
2352 help-echo "mouse-1: call ivy-action")
2354 (insert str "\n")))))
2355 (ivy-exit-with-action
2356 `(lambda (_) (pop-to-buffer ,buffer)))))
2358 (declare-function wgrep-change-to-wgrep-mode "ext:wgrep")
2360 (defun ivy-wgrep-change-to-wgrep-mode ()
2361 "Forward to `wgrep-change-to-wgrep-mode'."
2363 (if (require 'wgrep nil 'noerror)
2364 (wgrep-change-to-wgrep-mode)
2365 (error "Package wgrep isn't installed")))
2367 (defun ivy-occur-read-action ()
2368 "Select one of the available actions as the current one."
2370 (let ((ivy-last ivy-occur-last))
2373 (defun ivy-occur-dispatch ()
2374 "Call one of the available actions on the current item."
2376 (let* ((state-action (ivy-state-action ivy-occur-last))
2377 (actions (if (symbolp state-action)
2379 (copy-sequence state-action))))
2382 (ivy-occur-read-action)
2384 (setf (ivy-state-action ivy-occur-last) actions))))
2386 (defun ivy-occur-click (event)
2387 "Execute action for the current candidate.
2388 EVENT gives the mouse position."
2390 (let ((window (posn-window (event-end event)))
2391 (pos (posn-point (event-end event))))
2392 (with-current-buffer (window-buffer window)
2394 (ivy-occur-press))))
2396 (defun ivy-occur-press ()
2397 "Execute action for the current candidate."
2400 (when (save-excursion
2402 (looking-at "\\(?:./\\| \\)\\(.*\\)$"))
2403 (let* ((ivy-last ivy-occur-last)
2404 (ivy-text (ivy-state-text ivy-last))
2405 (str (buffer-substring
2408 (coll (ivy-state-collection ivy-last))
2409 (action (ivy--get-action ivy-last))
2413 (if (and (consp coll)
2415 (cdr (assoc str coll))
2417 (if (memq (ivy-state-caller ivy-last)
2418 '(swiper counsel-git-grep))
2419 (with-current-buffer (window-buffer (selected-window))
2421 (swiper--add-overlays
2422 (ivy--regex ivy-text)
2423 (line-beginning-position)
2426 (run-at-time 0.5 nil 'swiper--cleanup))
2427 (pulse-momentary-highlight-one-line (point)))))))
2431 ;;; ivy.el ends here