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 confirmation prompt.")
58 (defface ivy-match-required-face
59 '((t :foreground "red" :inherit minibuffer-prompt))
60 "Face used by Ivy for 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 those buffers visiting files.")
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 displying the current candidate count for
80 `ivy-read'. Set style to \"\" to suppress counts visiblity. Set
81 style 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 "Wrap around after the first and 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 parameter 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 to use 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, otherwise store nil.")
236 (defvar ivy--all-candidates nil
237 "Store the candidates passed to `ivy-read'.")
239 (defvar ivy--default nil
240 "Default initial input.")
242 (defvar ivy--prompt nil
243 "Store the format-style prompt.
244 When non-nil, it should contain at least one %d.")
246 (defvar ivy--prompt-extra ""
247 "Temporary modifications to the prompt.")
249 (defvar ivy--old-re nil
250 "Store the old regexp.")
252 (defvar ivy--old-cands nil
253 "Store the candidates matched by `ivy--old-re'.")
255 (defvar ivy--regex-function 'ivy--regex
256 "Current function for building a regex.")
258 (defvar ivy--subexps 0
259 "Number of groups in the current `ivy--regex'.")
261 (defvar ivy--full-length nil
262 "When :dynamic-collection is non-nil, this can be the total amount of candidates.")
264 (defvar ivy--old-text ""
265 "Store old `ivy-text' for dynamic completion.")
267 (defvar ivy-case-fold-search 'auto
268 "Store the current overriding `case-fold-search'.")
270 (defvar Info-current-file)
272 (defmacro ivy-quit-and-run (&rest body)
273 "Quit the minibuffer and run BODY afterwards."
275 (put 'quit 'error-message "")
278 (put 'quit 'error-message "Quit")
280 (minibuffer-keyboard-quit)))
282 (defun ivy-exit-with-action (action)
283 "Quit the minibuffer and call ACTION afterwards."
287 (ivy-set-action ',(ivy-state-action ivy-last))))
288 (setq ivy-exit 'done)
291 (defmacro with-ivy-window (&rest body)
292 "Execute BODY in the window from which `ivy-read' was called."
295 `(with-selected-window (ivy--get-window ivy-last)
298 (defun ivy--done (text)
299 "Insert TEXT and exit minibuffer."
300 (if (and ivy--directory
301 (not (eq (ivy-state-history ivy-last) 'grep-files-history)))
302 (insert (setq ivy--current (expand-file-name
303 text ivy--directory)))
304 (insert (setq ivy--current text)))
305 (setq ivy-exit 'done)
310 "Exit the minibuffer with the selected candidate."
312 (delete-minibuffer-contents)
313 (cond ((> ivy--length 0)
314 (ivy--done ivy--current))
315 ((memq (ivy-state-collection ivy-last)
316 '(read-file-name-internal internal-complete-buffer))
317 (if (or (not (eq confirm-nonexistent-file-or-buffer t))
318 (equal " (confirm)" ivy--prompt-extra))
320 (setq ivy--prompt-extra " (confirm)")
323 ((memq (ivy-state-require-match ivy-last)
324 '(nil confirm confirm-after-completion))
325 (ivy--done ivy-text))
327 (setq ivy--prompt-extra " (match required)")
331 (defun ivy-read-action ()
332 "Change the action to one of the available ones."
334 (let ((actions (ivy-state-action ivy-last)))
335 (unless (null (ivy--actionp actions))
336 (let* ((hint (concat ivy--current
343 'face 'font-lock-builtin-face)
348 (key (string (read-key hint)))
349 (action-idx (cl-position-if
350 (lambda (x) (equal (car x) key))
352 (cond ((string= key "
\a"))
354 (error "%s is not bound" key))
357 (setcar actions (1+ action-idx))
358 (ivy-set-action actions)))))))
360 (defun ivy-dispatching-done ()
361 "Select one of the available actions and call `ivy-done'."
366 (defun ivy-dispatching-call ()
367 "Select one of the available actions and call `ivy-call'."
369 (let ((actions (copy-sequence (ivy-state-action ivy-last))))
371 (when (ivy-read-action)
373 (ivy-set-action actions))))
375 (defun ivy-build-tramp-name (x)
376 "Reconstruct X into a path.
377 Is is a cons cell, related to `tramp-get-completion-function'."
381 (concat user "@" domain)
384 (declare-function tramp-get-completion-function "tramp")
385 (declare-function Info-find-node "info")
387 (defun ivy-alt-done (&optional arg)
388 "Exit the minibuffer with the selected candidate.
389 When ARG is t, exit with current text, ignoring the candidates."
392 (ivy-immediate-done))
394 (ivy--directory-done))
395 ((eq (ivy-state-collection ivy-last) 'Info-read-node-name-1)
396 (if (or (equal ivy--current "(./)")
397 (equal ivy--current "(../)"))
399 (ivy-read "Go to file: " 'read-file-name-internal
402 (expand-file-name x ivy--directory)
408 (defun ivy--directory-done ()
409 "Handle exit from the minibuffer when completing file names."
412 ((equal ivy-text "/sudo::")
413 (setq dir (concat ivy-text ivy--directory))
418 (not (equal ivy-text ""))
422 (file-name-as-directory
424 ivy-text ivy--directory))))))
426 (not (string= ivy--current "./"))
427 (cl-plusp ivy--length)
430 (setq dir (file-name-as-directory
432 ivy--current ivy--directory)))))))
435 ((or (and (equal ivy--directory "/")
436 (string-match "\\`[^/]+:.*:.*\\'" ivy-text))
437 (string-match "\\`/[^/]+:.*:.*\\'" ivy-text))
439 ((or (and (equal ivy--directory "/")
441 "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
444 "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
446 (setq ivy-text ivy--current))))
448 "\\`/\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
450 (let ((method (match-string 1 ivy-text))
451 (user (match-string 2 ivy-text))
452 (rest (match-string 3 ivy-text))
455 (dolist (x (tramp-get-completion-function method))
456 (setq res (append res (funcall (car x) (cadr x)))))
457 (setq res (delq nil res))
461 (setq res (cl-delete-duplicates res :test #'equal))
462 (let* ((old-ivy-last ivy-last)
463 (enable-recursive-minibuffers t)
464 (host (ivy-read "Find File: "
465 (mapcar #'ivy-build-tramp-name res)
466 :initial-input rest)))
467 (setq ivy-last old-ivy-last)
469 (setq ivy--directory "/")
470 (ivy--cd (concat "/" method ":" host ":"))))))
474 (defcustom ivy-tab-space nil
475 "When non-nil, `ivy-partial-or-done' should insert a space."
478 (defun ivy-partial-or-done ()
479 "Complete the minibuffer text as much as possible.
480 If the text hasn't changed as a result, forward to `ivy-alt-done'."
482 (if (and (eq (ivy-state-collection ivy-last) #'read-file-name-internal)
483 (or (and (equal ivy--directory "/")
484 (string-match "\\`[^/]+:.*\\'" ivy-text))
485 (string-match "\\`/" ivy-text)))
486 (let ((default-directory ivy--directory))
487 (minibuffer-complete)
488 (setq ivy-text (ivy--input))
489 (when (file-directory-p
490 (expand-file-name ivy-text ivy--directory))
491 (ivy--cd (file-name-as-directory
492 (expand-file-name ivy-text ivy--directory)))))
494 (when (or (eq this-command last-command)
498 (defun ivy-partial ()
499 "Complete the minibuffer text as much as possible."
501 (let* ((parts (or (split-string ivy-text " " t) (list "")))
502 (postfix (car (last parts)))
503 (completion-ignore-case t)
504 (startp (string-match "^\\^" postfix))
505 (new (try-completion (if startp
506 (substring postfix 1)
508 (mapcar (lambda (str)
509 (let ((i (string-match postfix str)))
513 (cond ((eq new t) nil)
514 ((string= new ivy-text) nil)
516 (delete-region (minibuffer-prompt-end) (point-max))
521 (insert (mapconcat #'identity parts " ")
522 (if ivy-tab-space " " ""))
525 (defun ivy-immediate-done ()
526 "Exit the minibuffer with the current input."
528 (delete-minibuffer-contents)
529 (insert (setq ivy--current
531 (expand-file-name ivy-text ivy--directory)
533 (setq ivy-exit 'done)
538 "Resume the last completion session."
540 (when (eq (ivy-state-caller ivy-last) 'swiper)
541 (switch-to-buffer (ivy-state-buffer ivy-last)))
542 (with-current-buffer (ivy-state-buffer ivy-last)
544 (ivy-state-prompt ivy-last)
545 (ivy-state-collection ivy-last)
546 :predicate (ivy-state-predicate ivy-last)
547 :require-match (ivy-state-require-match ivy-last)
548 :initial-input ivy-text
549 :history (ivy-state-history ivy-last)
550 :preselect (unless (eq (ivy-state-collection ivy-last)
551 'read-file-name-internal)
553 :keymap (ivy-state-keymap ivy-last)
554 :update-fn (ivy-state-update-fn ivy-last)
555 :sort (ivy-state-sort ivy-last)
556 :action (ivy-state-action ivy-last)
557 :unwind (ivy-state-unwind ivy-last)
558 :re-builder (ivy-state-re-builder ivy-last)
559 :matcher (ivy-state-matcher ivy-last)
560 :dynamic-collection (ivy-state-dynamic-collection ivy-last)
561 :caller (ivy-state-caller ivy-last))))
563 (defvar ivy-calling nil
564 "When non-nil, call the current action when `ivy--index' changes.")
566 (defun ivy-set-index (index)
567 "Set `ivy--index' to INDEX."
568 (setq ivy--index index)
573 (defun ivy-beginning-of-buffer ()
574 "Select the first completion candidate."
578 (defun ivy-end-of-buffer ()
579 "Select the last completion candidate."
581 (ivy-set-index (1- ivy--length)))
583 (defun ivy-scroll-up-command ()
584 "Scroll the candidates upward by the minibuffer height."
586 (ivy-set-index (min (1- (+ ivy--index ivy-height))
589 (defun ivy-scroll-down-command ()
590 "Scroll the candidates downward by the minibuffer height."
592 (ivy-set-index (max (1+ (- ivy--index ivy-height))
595 (defun ivy-minibuffer-grow ()
596 "Grow the minibuffer window by 1 line."
598 (setq-local max-mini-window-height
599 (cl-incf ivy-height)))
601 (defun ivy-minibuffer-shrink ()
602 "Shrink the minibuffer window by 1 line."
604 (unless (<= ivy-height 2)
605 (setq-local max-mini-window-height
606 (cl-decf ivy-height))
607 (window-resize (selected-window) -1)))
609 (defun ivy-next-line (&optional arg)
610 "Move cursor vertically down ARG candidates."
612 (setq arg (or arg 1))
613 (let ((index (+ ivy--index arg)))
614 (if (> index (1- ivy--length))
616 (ivy-beginning-of-buffer)
617 (ivy-set-index (1- ivy--length)))
618 (ivy-set-index index))))
620 (defun ivy-next-line-or-history (&optional arg)
621 "Move cursor vertically down ARG candidates.
622 If the input is empty, select the previous history element instead."
624 (when (string= ivy-text "")
625 (ivy-previous-history-element 1))
628 (defun ivy-previous-line (&optional arg)
629 "Move cursor vertically up ARG candidates."
631 (setq arg (or arg 1))
632 (let ((index (- ivy--index arg)))
637 (ivy-set-index index))))
639 (defun ivy-previous-line-or-history (arg)
640 "Move cursor vertically up ARG candidates.
641 If the input is empty, select the previous history element instead."
643 (when (string= ivy-text "")
644 (ivy-previous-history-element 1))
645 (ivy-previous-line arg))
647 (defun ivy-toggle-calling ()
648 "Flip `ivy-calling'."
650 (when (setq ivy-calling (not ivy-calling))
653 (defun ivy--get-action (state)
654 "Get the action function from STATE."
655 (let ((action (ivy-state-action state)))
657 (if (functionp action)
659 (cadr (nth (car action) action))))))
661 (defun ivy--get-window (state)
662 "Get the window from STATE."
663 (let ((window (ivy-state-window state)))
664 (if (window-live-p window)
666 (if (= (length (window-list)) 1)
670 (defun ivy--actionp (x)
671 "Return non-nil when X is a list of actions."
672 (and x (listp x) (not (eq (car x) 'closure))))
674 (defun ivy-next-action ()
675 "When the current action is a list, scroll it forwards."
677 (let ((action (ivy-state-action ivy-last)))
678 (when (ivy--actionp action)
679 (unless (>= (car action) (1- (length action)))
680 (cl-incf (car action))))))
682 (defun ivy-prev-action ()
683 "When the current action is a list, scroll it backwards."
685 (let ((action (ivy-state-action ivy-last)))
686 (when (ivy--actionp action)
687 (unless (<= (car action) 1)
688 (cl-decf (car action))))))
690 (defun ivy-action-name ()
691 "Return the name associated with the current action."
692 (let ((action (ivy-state-action ivy-last)))
693 (if (ivy--actionp action)
697 (nth 2 (nth (car action) action)))
701 "Call the current action without exiting completion."
703 (let ((action (ivy--get-action ivy-last)))
705 (let* ((collection (ivy-state-collection ivy-last))
706 (x (if (and (consp collection)
707 (consp (car collection)))
708 (cdr (assoc ivy--current collection))
709 (if (equal ivy--current "")
712 (prog1 (funcall action x)
713 (unless (or (eq ivy-exit 'done)
714 (equal (selected-window)
715 (active-minibuffer-window))
716 (null (active-minibuffer-window)))
717 (select-window (active-minibuffer-window))))))))
719 (defun ivy-next-line-and-call (&optional arg)
720 "Move cursor vertically down ARG candidates.
721 Call the permanent action if possible."
727 (defun ivy-previous-line-and-call (&optional arg)
728 "Move cursor vertically down ARG candidates.
729 Call the permanent action if possible."
731 (ivy-previous-line arg)
735 (defun ivy-previous-history-element (arg)
736 "Forward to `previous-history-element' with ARG."
738 (previous-history-element arg)
741 (ivy--maybe-scroll-history))
743 (defun ivy-next-history-element (arg)
744 "Forward to `next-history-element' with ARG."
746 (next-history-element arg)
749 (ivy--maybe-scroll-history))
751 (defun ivy--cd-maybe ()
752 "Check if the current input points to a different directory.
753 If so, move to that directory, while keeping only the file name."
755 (let ((input (ivy--input))
757 (if (setq url (ffap-url-p input))
758 (ivy-exit-with-action
760 (funcall ffap-url-fetcher url)))
761 (setq input (expand-file-name input))
762 (let ((file (file-name-nondirectory input))
763 (dir (expand-file-name (file-name-directory input))))
764 (if (string= dir ivy--directory)
766 (delete-minibuffer-contents)
771 (defun ivy--maybe-scroll-history ()
772 "If the selected history element has an index, scroll there."
773 (let ((idx (ignore-errors
775 (minibuffer-prompt-end)
779 (setq ivy--index idx))))
782 "When completing file names, move to directory DIR."
783 (if (null ivy--directory)
785 (setq ivy--old-cands nil)
786 (setq ivy--old-re nil)
788 (setq ivy--all-candidates
789 (ivy--sorted-files (setq ivy--directory dir)))
791 (delete-minibuffer-contents)))
793 (defun ivy-backward-delete-char ()
794 "Forward to `backward-delete-char'.
795 On error (read-only), call `ivy-on-del-error-function'."
797 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
799 (ivy--cd (file-name-directory
805 (backward-delete-char 1)
807 (when ivy-on-del-error-function
808 (funcall ivy-on-del-error-function))))))
810 (defun ivy-delete-char (arg)
811 "Forward to `delete-char' ARG."
813 (unless (= (point) (line-end-position))
816 (defun ivy-forward-char (arg)
817 "Forward to `forward-char' ARG."
819 (unless (= (point) (line-end-position))
822 (defun ivy-kill-word (arg)
823 "Forward to `kill-word' ARG."
825 (unless (= (point) (line-end-position))
828 (defun ivy-kill-line ()
829 "Forward to `kill-line'."
832 (kill-region (minibuffer-prompt-end) (point))
835 (defun ivy-backward-kill-word ()
836 "Forward to `backward-kill-word'."
838 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
840 (ivy--cd (file-name-directory
848 (delete-region (point) pt)))))
850 (defvar ivy--regexp-quote 'regexp-quote
851 "Store the regexp quoting state.")
853 (defun ivy-toggle-regexp-quote ()
854 "Toggle the regexp quoting."
856 (setq ivy--old-re nil)
857 (cl-rotatef ivy--regex-function ivy--regexp-quote))
859 (defvar avy-all-windows)
862 (defvar avy-keys-alist)
864 (defvar avy-styles-alist)
865 (declare-function avy--process "ext:avy")
866 (declare-function avy--style-fn "ext:avy")
868 (eval-after-load 'avy
869 '(add-to-list 'avy-styles-alist '(ivy-avy . pre)))
872 "Jump to a current ivy candidate."
874 (unless (require 'avy nil 'noerror)
875 (error "Avy package is not installed"))
876 (let* ((avy-all-windows nil)
877 (avy-keys (or (cdr (assq 'ivy-avy avy-keys-alist))
879 (avy-style (or (cdr (assq 'ivy-avy
889 (goto-char (point-min))
891 (while (< (point) (point-max))
897 (setq avy-action #'identity)
899 (nreverse candidates)
900 (avy--style-fn avy-style)))))
901 (ivy-set-index (- (line-number-at-pos candidate) 2))
905 (defun ivy-sort-file-function-default (x y)
906 "Compare two files X and Y.
907 Prioritize directories."
908 (if (get-text-property 0 'dirp x)
909 (if (get-text-property 0 'dirp y)
912 (if (get-text-property 0 'dirp y)
916 (defcustom ivy-sort-functions-alist
917 '((read-file-name-internal . ivy-sort-file-function-default)
918 (internal-complete-buffer . nil)
919 (counsel-git-grep-function . nil)
920 (Man-goto-section . nil)
923 "An alist of sorting functions for each collection function.
924 Interactive functions that call completion fit in here as well.
926 Nil means no sorting, which is useful to turn off the sorting for
927 functions that have candidates in the natural buffer order, like
928 `org-refile' or `Man-goto-section'.
930 The entry associated with t is used for all fall-through cases.
932 See also `ivy-sort-max-size'."
936 (const :tag "All other functions" t)
937 (symbol :tag "Function"))
939 (const :tag "plain sort" string-lessp)
940 (const :tag "file sort" ivy-sort-file-function-default)
941 (const :tag "no sort" nil)))
944 (defvar ivy-index-functions-alist
945 '((swiper . ivy-recompute-index-swiper)
946 (swiper-multi . ivy-recompute-index-swiper)
947 (counsel-git-grep . ivy-recompute-index-swiper)
948 (counsel-grep . ivy-recompute-index-swiper-async)
949 (t . ivy-recompute-index-zero))
950 "An alist of index recomputing functions for each collection function.
951 When the input changes, the appropriate function returns an
952 integer - the index of the matched candidate that should be
955 (defvar ivy-re-builders-alist
956 '((t . ivy--regex-plus))
957 "An alist of regex building functions for each collection function.
958 Each function should take a string and return a valid regex or a
959 regex sequence (see below).
961 The entry associated with t is used for all fall-through cases.
962 Possible choices: `ivy--regex', `regexp-quote', `ivy--regex-plus'.
964 If a function returns a list, it should format like this:
965 '((\"matching-regexp\" . t) (\"non-matching-regexp\") ...).
967 The matches will be filtered in a sequence, you can mix the
968 regexps that should match and that should not match as you
971 (defvar ivy-initial-inputs-alist
973 (org-agenda-refile . "^")
974 (org-capture-refile . "^")
976 (counsel-describe-function . "^")
977 (counsel-describe-variable . "^")
980 "Command to initial input table.")
982 (defcustom ivy-sort-max-size 30000
983 "Sorting won't be done for collections larger than this."
986 (defun ivy--sorted-files (dir)
987 "Return the list of files in DIR.
988 Directories come first."
989 (let* ((default-directory dir)
990 (seq (all-completions "" 'read-file-name-internal))
994 (setq seq (delete "./" (delete "../" seq)))
995 (when (eq (setq sort-fn (cdr (assoc 'read-file-name-internal
996 ivy-sort-functions-alist)))
997 #'ivy-sort-file-function-default)
998 (setq seq (mapcar (lambda (x)
999 (propertize x 'dirp (string-match-p "/\\'" x)))
1002 (setq seq (cl-sort seq sort-fn)))
1003 (dolist (dir ivy-extra-directories)
1008 (cl-defun ivy-read (prompt collection
1009 &key predicate require-match initial-input
1010 history preselect keymap update-fn sort
1011 action unwind re-builder matcher dynamic-collection caller)
1012 "Read a string in the minibuffer, with completion.
1014 PROMPT is a format string, normally ending in a colon and a
1015 space; %d anywhere in the string is replaced by the current
1016 number of matching candidates. For the literal % character,
1017 escape it with %%. See also `ivy-count-format'.
1019 COLLECTION is either a list of strings, a function, an alist, or
1022 If INITIAL-INPUT is not nil, then insert that input in the
1023 minibuffer initially.
1025 KEYMAP is composed with `ivy-minibuffer-map'.
1027 If PRESELECT is not nil, then select the corresponding candidate
1028 out of the ones that match the INITIAL-INPUT.
1030 UPDATE-FN is called each time the current candidate(s) is changed.
1032 When SORT is t, use `ivy-sort-functions-alist' for sorting.
1034 ACTION is a lambda function call after selecting a result. It
1035 takes a single string argument.
1037 UNWIND is a lambda function call before exiting.
1039 RE-BUILDER is a lambda function call to transform text into a
1042 MATCHER is to override matching.
1044 DYNAMIC-COLLECTION is a boolean to specify if the list of
1045 candidates is updated after each input by calling COLLECTION.
1047 CALLER is symbol to uniquely identify the caller to `ivy-read'.
1048 It is used, along with COLLECTION, to determine which
1049 customizations apply to the current completion session."
1050 (let ((extra-actions (plist-get ivy--actions-list this-command)))
1053 (if (functionp action)
1055 ("o" ,action "default")
1057 (delete-dups (append action extra-actions))))))
1058 (let ((recursive-ivy-last (and (window-minibuffer-p) ivy-last)))
1062 :collection collection
1063 :predicate predicate
1064 :require-match require-match
1065 :initial-input initial-input
1067 :preselect preselect
1069 :update-fn update-fn
1072 :window (selected-window)
1073 :buffer (current-buffer)
1075 :re-builder re-builder
1077 :dynamic-collection dynamic-collection
1079 (ivy--reset-state ivy-last)
1082 (minibuffer-with-setup-hook
1083 #'ivy--minibuffer-setup
1084 (let* ((hist (or history 'ivy-history))
1085 (minibuffer-completion-table collection)
1086 (minibuffer-completion-predicate predicate)
1087 (resize-mini-windows (cond
1088 ((display-graphic-p) nil)
1089 ((null resize-mini-windows) 'grow-only)
1090 (t resize-mini-windows)))
1091 (res (read-from-minibuffer
1093 (ivy-state-initial-input ivy-last)
1094 (make-composed-keymap keymap ivy-minibuffer-map)
1097 (when (eq ivy-exit 'done)
1098 (let ((item (if ivy--directory
1101 (unless (equal item "")
1102 (set hist (cons (propertize item 'ivy-index ivy--index)
1104 (cdr (symbol-value hist)))))))
1106 (remove-hook 'post-command-hook #'ivy--exhibit)
1107 (when (setq unwind (ivy-state-unwind ivy-last))
1110 (when recursive-ivy-last
1111 (ivy--reset-state (setq ivy-last recursive-ivy-last))))))
1113 (defun ivy--reset-state (state)
1114 "Reset the ivy to STATE.
1115 This is useful for recursive `ivy-read'."
1116 (let ((prompt (ivy-state-prompt state))
1117 (collection (ivy-state-collection state))
1118 (predicate (ivy-state-predicate state))
1119 (history (ivy-state-history state))
1120 (preselect (ivy-state-preselect state))
1121 (sort (ivy-state-sort state))
1122 (re-builder (ivy-state-re-builder state))
1123 (dynamic-collection (ivy-state-dynamic-collection state))
1124 (initial-input (ivy-state-initial-input state))
1125 (require-match (ivy-state-require-match state)))
1126 (unless initial-input
1127 (setq initial-input (cdr (assoc this-command
1128 ivy-initial-inputs-alist))))
1129 (setq ivy--directory nil)
1130 (setq ivy-case-fold-search 'auto)
1131 (setq ivy--regex-function
1133 (and (functionp collection)
1134 (cdr (assoc collection ivy-re-builders-alist)))
1135 (cdr (assoc t ivy-re-builders-alist))
1137 (setq ivy--subexps 0)
1138 (setq ivy--regexp-quote 'regexp-quote)
1139 (setq ivy--old-text "")
1140 (setq ivy--full-length nil)
1142 (setq ivy-calling nil)
1144 (cond ((eq collection 'Info-read-node-name-1)
1145 (if (equal Info-current-file "dir")
1147 (mapcar (lambda (x) (format "(%s)" x))
1148 (cl-delete-duplicates
1149 (all-completions "(" collection predicate)
1151 (setq coll (all-completions "" collection predicate))))
1152 ((eq collection 'read-file-name-internal)
1153 (setq ivy--directory default-directory)
1156 (let ((preselect-directory (file-name-directory preselect)))
1157 (unless (or (null preselect-directory)
1158 (string= preselect-directory
1160 (setq ivy--directory preselect-directory))
1162 (ivy-state-preselect state)
1163 (setq preselect (file-name-nondirectory preselect)))))
1164 (setq coll (ivy--sorted-files ivy--directory))
1166 (unless (or require-match
1167 (equal initial-input default-directory)
1168 (equal initial-input ""))
1169 (setq coll (cons initial-input coll)))
1170 (setq initial-input nil)))
1171 ((eq collection 'internal-complete-buffer)
1172 (setq coll (ivy--buffer-list "" ivy-use-virtual-buffers)))
1173 ((or (functionp collection)
1174 (byte-code-function-p collection)
1175 (vectorp collection)
1176 (and (consp collection) (listp (car collection)))
1177 (hash-table-p collection))
1178 (setq coll (all-completions "" collection predicate)))
1180 (setq coll collection)))
1182 (if (and (functionp collection)
1183 (setq sort-fn (assoc collection ivy-sort-functions-alist)))
1184 (when (and (setq sort-fn (cdr sort-fn))
1185 (not (eq collection 'read-file-name-internal)))
1186 (setq coll (cl-sort coll sort-fn)))
1187 (unless (eq history 'org-refile-history)
1188 (if (and (setq sort-fn (cdr (assoc t ivy-sort-functions-alist)))
1189 (<= (length coll) ivy-sort-max-size))
1190 (setq coll (cl-sort (copy-sequence coll) sort-fn))))))
1192 (unless (or (and require-match
1193 (not (eq collection 'internal-complete-buffer)))
1195 (let ((re (regexp-quote preselect)))
1196 (cl-find-if (lambda (x) (string-match re x))
1198 (setq coll (cons preselect coll))))
1199 (setq ivy--old-re nil)
1200 (setq ivy--old-cands nil)
1202 ;; Needed for anchor to work
1203 (setq ivy--old-cands coll)
1204 (setq ivy--old-cands (ivy--filter initial-input coll)))
1205 (setq ivy--all-candidates coll)
1206 (setq ivy--index (or
1207 (and dynamic-collection
1210 (ivy--preselect-index
1217 (setq ivy--default (or
1218 (thing-at-point 'url)
1219 (thing-at-point 'symbol)
1222 (cond ((string-match "%.*d" prompt)
1224 ((null ivy-count-format)
1226 "`ivy-count-format' can't be nil. Set it to an empty string instead"))
1227 ((string-match "%d.*%d" ivy-count-format)
1228 (let ((w (length (number-to-string
1229 (length ivy--all-candidates))))
1230 (s (copy-sequence ivy-count-format)))
1231 (string-match "%d" s)
1233 (string-match "%d" s (match-end 0))
1234 (setq s (replace-match (format "%%-%dd" w) nil nil s))
1235 (string-match "%d" s)
1236 (concat (replace-match (format "%%%dd" w) nil nil s)
1238 ((string-match "%.*d" ivy-count-format)
1239 (concat ivy-count-format prompt))
1244 (setf (ivy-state-initial-input ivy-last) initial-input)))
1247 (defun ivy-completing-read (prompt collection
1248 &optional predicate require-match initial-input
1249 history def _inherit-input-method)
1250 "Read a string in the minibuffer, with completion.
1252 This interface conforms to `completing-read' and can be used for
1253 `completing-read-function'.
1255 PROMPT is a string to prompt with; normally it ends in a colon and a space.
1256 COLLECTION can be a list of strings, an alist, an obarray or a hash table.
1257 PREDICATE limits completion to a subset of COLLECTION.
1258 REQUIRE-MATCH is specified with a boolean value. See `completing-read'.
1259 INITIAL-INPUT is a string that can be inserted into the minibuffer initially.
1260 _HISTORY is currently ignored.
1261 DEF is the default value.
1262 _INHERIT-INPUT-METHOD is currently ignored."
1264 ;; See the doc of `completing-read'.
1265 (when (consp history)
1266 (when (numberp (cdr history))
1267 (setq initial-input (nth (1- (cdr history))
1268 (symbol-value (car history)))))
1269 (setq history (car history)))
1270 (ivy-read (replace-regexp-in-string "%" "%%" prompt)
1272 :predicate predicate
1273 :require-match require-match
1274 :initial-input (if (consp initial-input)
1276 (if (and (stringp initial-input)
1277 (string-match "\\+" initial-input))
1278 (replace-regexp-in-string
1279 "\\+" "\\\\+" initial-input)
1281 :preselect (if (listp def) (car def) def)
1285 (let ((sort (assoc this-command ivy-sort-functions-alist)))
1291 (define-minor-mode ivy-mode
1292 "Toggle Ivy mode on or off.
1293 Turn Ivy mode on if ARG is positive, off otherwise.
1294 Turning on Ivy mode sets `completing-read-function' to
1295 `ivy-completing-read'.
1300 Minibuffer bindings:
1301 \\{ivy-minibuffer-map}"
1304 :keymap ivy-mode-map
1307 (setq completing-read-function 'ivy-completing-read)
1308 (setq completing-read-function 'completing-read-default)))
1310 (defun ivy--preselect-index (preselect candidates)
1311 "Return the index of PRESELECT from CANDIDATES."
1312 (cond ((integerp preselect)
1314 ((cl-position preselect candidates :test #'equal))
1315 ((stringp preselect)
1316 (let ((re (regexp-quote preselect)))
1319 (string-match re x))
1324 (defvar ivy--regex-hash
1325 (make-hash-table :test #'equal)
1326 "Store pre-computed regex.")
1328 (defun ivy--split (str)
1329 "Split STR into a list by single space characters.
1330 If any remaining consequtive spaces, stick left. This allows for
1331 \"quote\" N spaces by inputting N+1 spaces."
1332 (let ((len (length str))
1337 (while (and (string-match " +" str start1)
1339 (setq match-len (- (match-end 0) (match-beginning 0)))
1343 (setq start1 start0)
1345 (push (substring str start1 (match-beginning 0)) res)
1346 (setq start1 (match-end 0)))
1347 (setq str (replace-match
1348 (make-string (1- match-len) ?\ )
1350 (setq start0 (or start0 start1))
1351 (setq start1 (1- (match-end 0)))))
1353 (push (substring str start0) res)
1354 (setq s (substring str start1))
1355 (unless (= (length s) 0)
1359 (defun ivy--regex (str &optional greedy)
1360 "Re-build regex pattern from STR in case it has a space.
1361 When GREEDY is non-nil, join words in a greedy way."
1362 (let ((hashed (unless greedy
1363 (gethash str ivy--regex-hash))))
1366 (setq ivy--subexps (car hashed)))
1367 (when (string-match "\\([^\\]\\|^\\)\\\\$" str)
1368 (setq str (substring str 0 -1)))
1370 (let ((subs (ivy--split str)))
1371 (if (= (length subs) 1)
1373 (setq ivy--subexps 0)
1376 (setq ivy--subexps (length subs))
1379 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1381 (format "\\(%s\\)" x)))
1386 ivy--regex-hash)))))
1388 (defun ivy--regex-ignore-order (str)
1389 "Re-build regex from STR by splitting at spaces.
1390 Ignore the order of each group.
1392 ATTENTION: This is just a proof of concept and may not work as
1393 expected. Besides ignoring the order of the tokens where 'foo'
1394 and 'bar', 'bar' and 'foo' are matched, it also matches multiple
1395 occurances of 'foo' and 'bar'. To ignore the sort order and avoid
1396 multiple matches, use `ivy-restrict-to-matches' instead.
1398 (let* ((subs (split-string str " +" t))
1399 (len (length subs)))
1402 (setq ivy--subexps 0)
1405 (setq ivy--subexps len)
1406 (let ((all (mapconcat #'identity subs "\\|")))
1409 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1411 (format "\\(%s\\)" x)))
1415 (defun ivy--regex-plus (str)
1416 "Build a regex sequence from STR.
1417 Spaces are wild card characters, everything before \"!\" should
1418 match. Everything after \"!\" should not match."
1419 (let ((parts (split-string str "!" t)))
1420 (cl-case (length parts)
1424 (ivy--regex (car parts)))
1428 (split-string (cadr parts) " " t))))
1429 (cons (cons (ivy--regex (car parts)) t)
1431 (t (error "Unexpected: use only one !")))))
1433 (defun ivy--regex-fuzzy (str)
1434 "Build a regex sequence from STR.
1435 Insert .* between each char."
1436 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1438 (concat (match-string 1 str)
1441 (format "\\(%c\\)" x))
1442 (string-to-list (match-string 2 str)) ".*")
1443 (match-string 3 str))
1444 (setq ivy--subexps (length (match-string 2 str))))
1448 (defun ivy--minibuffer-setup ()
1449 "Setup ivy completion in the minibuffer."
1450 (set (make-local-variable 'completion-show-inline-help) nil)
1451 (set (make-local-variable 'minibuffer-default-add-function)
1453 (list ivy--default)))
1454 (when (display-graphic-p)
1455 (setq truncate-lines t))
1456 (setq-local max-mini-window-height ivy-height)
1457 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1458 ;; show completions with empty input
1461 (defun ivy--input ()
1462 "Return the current minibuffer input."
1463 ;; assume one-line minibuffer input
1464 (buffer-substring-no-properties
1465 (minibuffer-prompt-end)
1466 (line-end-position)))
1468 (defun ivy--cleanup ()
1469 "Delete the displayed completion candidates."
1471 (goto-char (minibuffer-prompt-end))
1472 (delete-region (line-end-position) (point-max))))
1474 (defun ivy--insert-prompt ()
1475 "Update the prompt according to `ivy--prompt'."
1477 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1478 counsel-find-symbol))
1479 (setq ivy--prompt-extra ""))
1481 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1483 (setq head (match-string 1 ivy--prompt))
1485 (setq head (substring ivy--prompt 0 -1))
1487 (let ((inhibit-read-only t)
1488 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1491 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1492 (> (minibuffer-depth) 1))
1493 (format "[%d] " (minibuffer-depth))
1496 (if (string-match "%d.*%d" ivy-count-format)
1499 (or (and (ivy-state-dynamic-collection ivy-last)
1503 (or (and (ivy-state-dynamic-collection ivy-last)
1508 (d-str (if ivy--directory
1509 (abbreviate-file-name ivy--directory)
1512 (goto-char (point-min))
1513 (delete-region (point-min) (minibuffer-prompt-end))
1514 (if (> (+ (mod (+ (length n-str) (length d-str)) (window-width))
1517 (setq n-str (concat n-str "\n" d-str))
1518 (setq n-str (concat n-str d-str)))
1519 (let ((regex (format "\\([^\n]\\{%d\\}\\)[^\n]" (window-width))))
1520 (while (string-match regex n-str)
1521 (setq n-str (replace-match (concat (match-string 1 n-str) "\n") nil t n-str 1))))
1522 (set-text-properties 0 (length n-str)
1523 `(face minibuffer-prompt ,@std-props)
1525 (ivy--set-match-props n-str "confirm"
1526 `(face ivy-confirm-face ,@std-props))
1527 (ivy--set-match-props n-str "match required"
1528 `(face ivy-match-required-face ,@std-props))
1530 ;; get out of the prompt area
1531 (constrain-to-field nil (point-max))))))
1533 (defun ivy--set-match-props (str match props)
1534 "Set STR text proprties that match MATCH to PROPS."
1535 (when (string-match match str)
1536 (set-text-properties
1542 (defvar inhibit-message)
1544 (defun ivy--sort-maybe (collection)
1545 "Sort COLLECTION if needed."
1546 (let ((sort (ivy-state-sort ivy-last))
1550 (let ((sort-fn (cond ((functionp sort)
1552 ((setq entry (assoc (ivy-state-collection ivy-last)
1553 ivy-sort-functions-alist))
1556 (cdr (assoc t ivy-sort-functions-alist))))))
1557 (if (functionp sort-fn)
1558 (cl-sort (copy-sequence collection) sort-fn)
1561 (defun ivy--exhibit ()
1562 "Insert Ivy completions display.
1563 Should be run via minibuffer `post-command-hook'."
1564 (when (memq 'ivy--exhibit post-command-hook)
1565 (let ((inhibit-field-text-motion nil))
1566 (constrain-to-field nil (point-max)))
1567 (setq ivy-text (ivy--input))
1568 (if (ivy-state-dynamic-collection ivy-last)
1569 ;; while-no-input would cause annoying
1570 ;; "Waiting for process to die...done" message interruptions
1571 (let ((inhibit-message t))
1572 (unless (equal ivy--old-text ivy-text)
1574 (setq ivy--all-candidates
1576 (funcall (ivy-state-collection ivy-last) ivy-text)))
1577 (setq ivy--old-text ivy-text)))
1578 (when ivy--all-candidates
1579 (ivy--insert-minibuffer
1580 (ivy--format ivy--all-candidates))))
1581 (cond (ivy--directory
1582 (if (string-match "/\\'" ivy-text)
1583 (if (member ivy-text ivy--all-candidates)
1584 (ivy--cd (expand-file-name ivy-text ivy--directory))
1585 (when (string-match "//\\'" ivy-text)
1586 (if (and default-directory
1587 (string-match "\\`[[:alpha:]]:/" default-directory))
1588 (ivy--cd (match-string 0 default-directory))
1590 (when (string-match "[[:alpha:]]:/$" ivy-text)
1591 (let ((drive-root (match-string 0 ivy-text)))
1592 (when (file-exists-p drive-root)
1593 (ivy--cd drive-root)))))
1594 (if (string-match "\\`~\\'" ivy-text)
1595 (ivy--cd (expand-file-name "~/")))))
1596 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1597 (when (or (and (string-match "\\` " ivy-text)
1598 (not (string-match "\\` " ivy--old-text)))
1599 (and (string-match "\\` " ivy--old-text)
1600 (not (string-match "\\` " ivy-text))))
1601 (setq ivy--all-candidates
1602 (if (and (> (length ivy-text) 0)
1603 (eq (aref ivy-text 0)
1605 (ivy--buffer-list " ")
1606 (ivy--buffer-list "" ivy-use-virtual-buffers)))
1607 (setq ivy--old-re nil))))
1608 (ivy--insert-minibuffer
1609 (with-current-buffer (ivy-state-buffer ivy-last)
1611 (ivy--filter ivy-text ivy--all-candidates))))
1612 (setq ivy--old-text ivy-text))))
1614 (defun ivy--insert-minibuffer (text)
1615 "Insert TEXT into minibuffer with appropriate cleanup."
1616 (let ((resize-mini-windows nil)
1617 (update-fn (ivy-state-update-fn ivy-last))
1621 (funcall update-fn))
1622 (ivy--insert-prompt)
1623 ;; Do nothing if while-no-input was aborted.
1624 (when (stringp text)
1625 (let ((buffer-undo-list t))
1629 (when (display-graphic-p)
1630 (ivy--resize-minibuffer-to-fit))))
1632 (defun ivy--resize-minibuffer-to-fit ()
1633 "Resize the minibuffer window size to fit the text in the minibuffer."
1634 (with-selected-window (minibuffer-window)
1635 (if (fboundp 'window-text-pixel-size)
1636 (let ((text-height (cdr (window-text-pixel-size)))
1637 (body-height (window-body-height nil t)))
1638 (when (> text-height body-height)
1639 (window-resize nil (- text-height body-height) nil t t)))
1640 (let ((text-height (count-screen-lines))
1641 (body-height (window-body-height)))
1642 (when (> text-height body-height)
1643 (window-resize nil (- text-height body-height) nil t))))))
1645 (declare-function colir-blend-face-background "ext:colir")
1647 (defun ivy--add-face (str face)
1648 "Propertize STR with FACE.
1649 `font-lock-append-text-property' is used, since it's better than
1650 `propertize' or `add-face-text-property' in this case."
1654 (colir-blend-face-background 0 (length str) face str)
1655 (let ((foreground (face-foreground face)))
1657 (add-face-text-property
1659 `(:foreground ,foreground)
1664 (font-lock-append-text-property 0 (length str) 'face face str))))
1667 (declare-function flx-make-string-cache "ext:flx")
1668 (declare-function flx-score "ext:flx")
1670 (defvar ivy--flx-cache nil)
1672 (eval-after-load 'flx
1673 '(setq ivy--flx-cache (flx-make-string-cache)))
1675 (defun ivy-toggle-case-fold ()
1676 "Toggle the case folding between nil and auto.
1677 In any completion session, the case folding starts in auto:
1679 - when the input is all lower case, `case-fold-search' is t
1682 You can toggle this to make `case-fold-search' nil regardless of input."
1684 (setq ivy-case-fold-search
1685 (if ivy-case-fold-search
1688 ;; reset cache so that the candidate list updates
1689 (setq ivy--old-re nil))
1691 (defun ivy--filter (name candidates)
1692 "Return all items that match NAME in CANDIDATES.
1693 CANDIDATES are assumed to be static."
1694 (let ((re (funcall ivy--regex-function name)))
1695 (if (and (equal re ivy--old-re)
1697 ;; quick caching for "C-n", "C-p" etc.
1699 (let* ((re-str (if (listp re) (caar re) re))
1700 (matcher (ivy-state-matcher ivy-last))
1702 (and ivy-case-fold-search
1703 (string= name (downcase name))))
1706 (funcall matcher re candidates))
1709 (stringp ivy--old-re)
1710 (not (string-match "\\\\" ivy--old-re))
1711 (not (equal ivy--old-re ""))
1713 (if (string-match "\\\\)\\'" ivy--old-re)
1714 (substring ivy--old-re 0 -2)
1720 (lambda (x) (string-match re x))
1723 (let ((re-list (if (stringp re) (list (cons re t)) re))
1725 (dolist (re re-list)
1732 (let ((re-str (car re)))
1733 (lambda (x) (string-match re-str x)))
1736 (ivy--recompute-index name re-str cands)
1737 (setq ivy--old-re (if cands re-str ""))
1738 (setq ivy--old-cands (ivy--sort name cands))))))
1740 (defcustom ivy-sort-matches-functions-alist '((t . nil))
1741 "An alist of functions for sorting after each input change.
1743 These functions are for sorting matching list of candidates after
1744 each input change. Sorting is applied repeatedly to the matching
1745 candidates if the list changes after each input change.
1747 `ivy-sort-functions-alist', on the other hand, sorts the whole
1748 collection of candidates only once.
1750 The alist KEY is a collection function or t to match previously
1751 not matched collection functions.
1753 The alist VAL is a sorting function with the signature of
1754 `ivy--prefix-sort'.")
1756 (defun ivy--sort-files-by-date (_name candidates)
1757 "Re-soft CANDIDATES according to file modification date."
1758 (let ((default-directory ivy--directory))
1759 (cl-sort (copy-sequence candidates)
1762 (nth 5 (file-attributes f2))
1763 (nth 5 (file-attributes f1)))))))
1765 (defun ivy--sort (name candidates)
1766 "Re-sort CANDIDATES by NAME.
1767 All CANDIDATES are assumed to match NAME."
1768 (let ((key (or (ivy-state-caller ivy-last)
1769 (when (functionp (ivy-state-collection ivy-last))
1770 (ivy-state-collection ivy-last))))
1772 (cond ((and (require 'flx nil 'noerror)
1773 (eq ivy--regex-function 'ivy--regex-fuzzy))
1774 (ivy--flx-sort name candidates))
1775 ((setq fun (cdr (or (assoc key ivy-sort-matches-functions-alist)
1776 (assoc t ivy-sort-matches-functions-alist))))
1777 (funcall fun name candidates))
1781 (defun ivy--prefix-sort (name candidates)
1782 "Re-sort CANDIDATES.
1783 Prefix matches to NAME are put ahead of the list."
1784 (if (or (string-match "^\\^" name) (string= name ""))
1786 (let ((re-prefix (concat "^" (funcall ivy--regex-function name)))
1789 (dolist (s candidates)
1790 (if (string-match re-prefix s)
1792 (push s res-noprefix)))
1794 (nreverse res-prefix)
1795 (nreverse res-noprefix)))))
1797 (defun ivy--recompute-index (name re-str cands)
1798 (let* ((caller (ivy-state-caller ivy-last))
1799 (func (or (and caller (cdr (assoc caller ivy-index-functions-alist)))
1800 (cdr (assoc t ivy-index-functions-alist))
1801 #'ivy-recompute-index-zero)))
1802 (unless (eq this-command 'ivy-resume)
1805 (cl-position (if (and (> (length re-str) 0)
1806 (eq ?^ (aref re-str 0)))
1807 (substring re-str 1)
1812 (concat re-str "/") cands
1814 (and (not (string= name ""))
1815 (not (and (require 'flx nil 'noerror)
1816 (eq ivy--regex-function 'ivy--regex-fuzzy)
1817 (< (length cands) 200)))
1819 (cl-position (nth ivy--index ivy--old-cands)
1821 (funcall func re-str cands))))
1822 (when (and (or (string= name "")
1824 (not (equal ivy--old-re "")))
1826 (or (ivy--preselect-index
1827 (ivy-state-preselect ivy-last)
1831 (defun ivy-recompute-index-swiper (_re-str cands)
1832 (let ((tail (nthcdr ivy--index ivy--old-cands))
1834 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
1836 (while (and tail (null idx))
1837 ;; Compare with eq to handle equal duplicates in cands
1838 (setq idx (cl-position (pop tail) cands)))
1842 ;; already in ivy-state-buffer
1843 (let ((n (line-number-at-pos))
1847 (when (eq n (read (get-text-property 0 'display c)))
1852 (defun ivy-recompute-index-swiper-async (_re-str cands)
1853 (let ((tail (nthcdr ivy--index ivy--old-cands))
1855 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
1857 (while (and tail (null idx))
1858 ;; Compare with `equal', since the collection is re-created
1859 ;; each time with `split-string'
1860 (setq idx (cl-position (pop tail) cands :test #'equal)))
1864 (defun ivy-recompute-index-zero (_re-str _cands)
1867 (defun ivy--flx-sort (name cands)
1868 "Sort according to closeness to string NAME the string list CANDS."
1871 (< (length cands) 200))
1872 (let* ((flx-name (if (string-match "^\\^" name)
1879 (let ((score (car (flx-score x flx-name ivy--flx-cache))))
1883 (if cands-with-score
1885 (sort cands-with-score
1887 (> (car x) (car y)))))
1893 (defcustom ivy-format-function 'ivy-format-function-default
1894 "Function to transform the list of candidates into a string.
1895 This string is inserted into the minibuffer."
1897 (const :tag "Default" ivy-format-function-default)
1898 (const :tag "Arrow prefix" ivy-format-function-arrow)
1899 (const :tag "Full line" ivy-format-function-line)))
1901 (defun ivy--truncate-string (str width)
1902 "Truncate STR to WIDTH."
1903 (if (> (string-width str) width)
1904 (concat (substring str 0 (min (- width 3)
1905 (- (length str) 3))) "...")
1908 (defun ivy--format-function-generic (selected-fn other-fn cand-pairs separator)
1909 "Transform CAND-PAIRS into a string for minibuffer.
1910 SELECTED-FN and OTHER-FN each take two string arguments.
1911 SEPARATOR is used to join the candidates."
1915 (let ((str (car pair))
1917 (curr (eq (cl-incf i) ivy--index)))
1919 (funcall selected-fn str extra)
1920 (funcall other-fn str extra))))
1924 (defun ivy-format-function-default (cand-pairs)
1925 "Transform CAND-PAIRS into a string for minibuffer."
1926 (ivy--format-function-generic
1928 (concat (ivy--add-face str 'ivy-current-match) extra))
1933 (defun ivy-format-function-arrow (cand-pairs)
1934 "Transform CAND-PAIRS into a string for minibuffer."
1935 (ivy--format-function-generic
1937 (concat "> " (ivy--add-face str 'ivy-current-match) extra))
1939 (concat " " str extra))
1943 (defun ivy-format-function-line (cand-pairs)
1944 "Transform CAND-PAIRS into a string for minibuffer."
1945 (ivy--format-function-generic
1947 (ivy--add-face (concat str extra "\n") 'ivy-current-match))
1949 (concat str extra "\n"))
1953 (defface ivy-minibuffer-match-face-1
1954 '((((class color) (background light))
1955 :background "#d3d3d3")
1956 (((class color) (background dark))
1957 :background "#555555"))
1958 "The background face for `ivy' minibuffer matches.")
1960 (defface ivy-minibuffer-match-face-2
1961 '((((class color) (background light))
1962 :background "#e99ce8" :weight bold)
1963 (((class color) (background dark))
1964 :background "#777777" :weight bold))
1965 "Face for `ivy' minibuffer matches modulo 1.")
1967 (defface ivy-minibuffer-match-face-3
1968 '((((class color) (background light))
1969 :background "#bbbbff" :weight bold)
1970 (((class color) (background dark))
1971 :background "#7777ff" :weight bold))
1972 "Face for `ivy' minibuffer matches modulo 2.")
1974 (defface ivy-minibuffer-match-face-4
1975 '((((class color) (background light))
1976 :background "#ffbbff" :weight bold)
1977 (((class color) (background dark))
1978 :background "#8a498a" :weight bold))
1979 "Face for `ivy' minibuffer matches modulo 3.")
1981 (defcustom ivy-minibuffer-faces
1982 '(ivy-minibuffer-match-face-1
1983 ivy-minibuffer-match-face-2
1984 ivy-minibuffer-match-face-3
1985 ivy-minibuffer-match-face-4)
1986 "List of `ivy' faces for minibuffer group matches.")
1988 (defun ivy--format-minibuffer-line (str)
1990 (str (copy-sequence str)))
1991 (when (eq ivy-display-style 'fancy)
1993 (setq ivy--old-re (funcall ivy--regex-function ivy-text)))
1994 (while (and (string-match ivy--old-re str start)
1995 (> (- (match-end 0) (match-beginning 0)) 0))
1996 (setq start (match-end 0))
1998 (while (<= i ivy--subexps)
2000 (cond ((zerop ivy--subexps)
2001 (cadr ivy-minibuffer-faces))
2003 (car ivy-minibuffer-faces))
2005 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2006 ivy-minibuffer-faces)))))
2007 (if (fboundp 'add-face-text-property)
2008 (add-face-text-property
2014 (font-lock-append-text-property
2023 (defun ivy--format (cands)
2024 "Return a string for CANDS suitable for display in the minibuffer.
2025 CANDS is a list of strings."
2026 (setq ivy--length (length cands))
2027 (when (>= ivy--index ivy--length)
2028 (setq ivy--index (max (1- ivy--length) 0)))
2030 (setq ivy--current "")
2031 (let* ((half-height (/ ivy-height 2))
2032 (start (max 0 (- ivy--index half-height)))
2033 (end (min (+ start (1- ivy-height)) ivy--length))
2034 (start (max 0 (min start (- end (1- ivy-height)))))
2035 (cands (cl-subseq cands start end))
2036 (index (- ivy--index start)))
2037 (cond (ivy--directory
2038 (setq cands (mapcar (lambda (x)
2039 (if (string-match-p "/\\'" x)
2040 (propertize x 'face 'ivy-subdir)
2043 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
2044 (setq cands (mapcar (lambda (x)
2045 (let ((b (get-buffer x)))
2047 (buffer-file-name b)
2048 (buffer-modified-p b))
2049 (propertize x 'face 'ivy-modified-buffer)
2052 (setq ivy--current (copy-sequence (nth index cands)))
2053 (let* ((ivy--index index)
2056 (cons (ivy--format-minibuffer-line cand) nil)) cands))
2057 (res (concat "\n" (funcall ivy-format-function cand-pairs))))
2058 (put-text-property 0 (length res) 'read-only nil res)
2061 (defvar ivy--virtual-buffers nil
2062 "Store the virtual buffers alist.")
2064 (defvar recentf-list)
2066 (defface ivy-virtual '((t :inherit font-lock-builtin-face))
2067 "Face used by Ivy for matching virtual buffer names.")
2069 (defcustom ivy-virtual-abbreviate 'name
2070 "The mode of abbreviation for virtual buffer names."
2072 (const :tag "Only name" name)
2073 (const :tag "Full path" full)
2074 ;; eventually, uniquify
2077 (defun ivy--virtual-buffers ()
2078 "Adapted from `ido-add-virtual-buffers-to-list'."
2079 (unless recentf-mode
2081 (let ((bookmarks (and (boundp 'bookmark-alist)
2083 virtual-buffers name)
2084 (dolist (head (append
2086 (delete " - no file -"
2087 (delq nil (mapcar (lambda (bookmark)
2088 (cdr (assoc 'filename bookmark)))
2091 (if (eq ivy-virtual-abbreviate 'name)
2092 (file-name-nondirectory head)
2093 (expand-file-name head)))
2094 (when (equal name "")
2095 (setq name (file-name-nondirectory (directory-file-name head))))
2096 (when (equal name "")
2098 (and (not (equal name ""))
2099 (null (get-file-buffer head))
2100 (not (assoc name virtual-buffers))
2101 (push (cons name head) virtual-buffers)))
2102 (when virtual-buffers
2103 (dolist (comp virtual-buffers)
2104 (put-text-property 0 (length (car comp))
2107 (setq ivy--virtual-buffers (nreverse virtual-buffers))
2108 (mapcar #'car ivy--virtual-buffers))))
2110 (defun ivy--buffer-list (str &optional virtual)
2111 "Return the buffers that match STR.
2112 When VIRTUAL is non-nil, add virtual buffers."
2117 (if (with-current-buffer x
2119 (abbreviate-file-name default-directory)))
2120 (propertize x 'face 'ivy-remote)
2122 (all-completions str 'internal-complete-buffer))
2124 (ivy--virtual-buffers)))))
2126 (defun ivy--switch-buffer-action (buffer)
2128 BUFFER may be a string or nil."
2130 (if (zerop (length buffer))
2132 ivy-text nil 'force-same-window)
2133 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2135 (not (get-buffer buffer)))
2136 (find-file (cdr virtual))
2138 buffer nil 'force-same-window))))))
2140 (defun ivy--switch-buffer-other-window-action (buffer)
2141 "Switch to BUFFER in other window.
2142 BUFFER may be a string or nil."
2143 (if (zerop (length buffer))
2144 (switch-to-buffer-other-window ivy-text)
2145 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2147 (not (get-buffer buffer)))
2148 (find-file-other-window (cdr virtual))
2149 (switch-to-buffer-other-window buffer)))))
2151 (defun ivy--rename-buffer-action (buffer)
2153 (let ((new-name (read-string "Rename buffer (to new name): ")))
2154 (with-current-buffer buffer
2155 (rename-buffer new-name))))
2157 (defvar ivy-switch-buffer-map (make-sparse-keymap))
2164 (ivy--reset-state ivy-last))
2167 ivy--switch-buffer-other-window-action
2170 ivy--rename-buffer-action
2174 (defun ivy-switch-buffer ()
2175 "Switch to another buffer."
2178 (call-interactively 'switch-to-buffer)
2179 (let ((this-command 'ivy-switch-buffer))
2180 (ivy-read "Switch to buffer: " 'internal-complete-buffer
2181 :preselect (buffer-name (other-buffer (current-buffer)))
2182 :action #'ivy--switch-buffer-action
2183 :keymap ivy-switch-buffer-map))))
2186 (defun ivy-recentf ()
2187 "Find a file on `recentf-list'."
2189 (ivy-read "Recentf: " recentf-list
2195 (defun ivy-yank-word ()
2196 "Pull next word from buffer into search string."
2201 (le (line-end-position)))
2205 (setq amend (buffer-substring-no-properties pt (point))))))
2207 (insert (replace-regexp-in-string " +" " " amend)))))
2209 (defun ivy-kill-ring-save ()
2210 "Store the current candidates into the kill ring.
2211 If the region is active, forward to `kill-ring-save' instead."
2213 (if (region-active-p)
2214 (call-interactively 'kill-ring-save)
2221 (defun ivy-insert-current ()
2222 "Make the current candidate into current input.
2223 Don't finish completion."
2225 (delete-minibuffer-contents)
2226 (if (and ivy--directory
2227 (string-match "/$" ivy--current))
2228 (insert (substring ivy--current 0 -1))
2229 (insert ivy--current)))
2231 (defun ivy-toggle-fuzzy ()
2232 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
2234 (setq ivy--old-re nil)
2235 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
2236 (setq ivy--regex-function 'ivy--regex-plus)
2237 (setq ivy--regex-function 'ivy--regex-fuzzy)))
2239 (defun ivy-reverse-i-search ()
2240 "Enter a recursive `ivy-read' session using the current history.
2241 The selected history element will be inserted into the minibufer."
2243 (let ((enable-recursive-minibuffers t)
2244 (history (symbol-value (ivy-state-history ivy-last)))
2245 (old-last ivy-last))
2246 (ivy-read "Reverse-i-search: "
2250 (setq ivy-last old-last))
2251 (delete-minibuffer-contents)
2252 (insert (substring-no-properties x))
2255 (defun ivy-restrict-to-matches ()
2256 "Restrict candidates to current matches and erase input."
2258 (delete-minibuffer-contents)
2259 (setq ivy--all-candidates
2260 (ivy--filter ivy-text ivy--all-candidates)))
2263 (defvar-local ivy-occur-last nil
2264 "Buffer-local value of `ivy-last'.
2265 Can't re-use `ivy-last' because using e.g. `swiper' in the same
2266 buffer would modify `ivy-last'.")
2268 (defvar ivy-occur-mode-map
2269 (let ((map (make-sparse-keymap)))
2270 (define-key map [mouse-1] 'ivy-occur-click)
2271 (define-key map (kbd "RET") 'ivy-occur-press)
2272 (define-key map (kbd "j") 'next-line)
2273 (define-key map (kbd "k") 'previous-line)
2274 (define-key map (kbd "h") 'backward-char)
2275 (define-key map (kbd "l") 'forward-char)
2276 (define-key map (kbd "g") 'ivy-occur-press)
2277 (define-key map (kbd "a") 'ivy-occur-read-action)
2278 (define-key map (kbd "o") 'ivy-occur-dispatch)
2279 (define-key map (kbd "q") 'quit-window)
2281 "Keymap for Ivy Occur mode.")
2283 (define-derived-mode ivy-occur-mode fundamental-mode "Ivy-Occur"
2284 "Major mode for output from \\[ivy-occur].
2286 \\{ivy-occur-mode-map}")
2288 (defvar ivy-occur-grep-mode-map
2289 (let ((map (copy-keymap ivy-occur-mode-map)))
2290 (define-key map (kbd "C-x C-q") 'ivy-wgrep-change-to-wgrep-mode)
2292 "Keymap for Ivy Occur Grep mode.")
2294 (define-derived-mode ivy-occur-grep-mode grep-mode "Ivy-Occur"
2295 "Major mode for output from \\[ivy-occur].
2297 \\{ivy-occur-grep-mode-map}")
2299 (defvar counsel-git-grep-cmd)
2302 "Stops completion and puts the current matches into a new buffer.
2304 The new buffer remembers current action(s).
2306 While in the *ivy-occur* buffer, selecting a cadidate with RET or
2307 a mouse click will call the appropriate action for that candidate.
2309 There is no limit on the number of *ivy-occur* buffers."
2312 (generate-new-buffer
2313 (format "*ivy-occur%s \"%s\"*"
2315 (if (setq caller (ivy-state-caller ivy-last))
2316 (concat " " (prin1-to-string caller))
2319 (do-grep (eq (ivy-state-caller ivy-last) 'counsel-git-grep)))
2320 (with-current-buffer buffer
2323 (setq ivy--old-cands
2325 (shell-command-to-string
2326 (format counsel-git-grep-cmd ivy--old-re))
2329 (ivy-occur-grep-mode))
2331 (setf (ivy-state-text ivy-last) ivy-text)
2332 (setq ivy-occur-last ivy-last)
2333 (setq-local ivy--directory ivy--directory)
2334 (let ((inhibit-read-only t))
2337 ;; Need precise number of header lines for `wgrep' to work.
2338 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
2339 default-directory)))
2340 (insert (format "%d candidates:\n" (length ivy--old-cands)))
2341 (dolist (cand ivy--old-cands)
2342 (let ((str (if do-grep
2344 (concat " " cand))))
2345 (add-text-properties
2349 help-echo "mouse-1: call ivy-action")
2351 (insert str "\n")))))
2352 (ivy-exit-with-action
2353 `(lambda (_) (pop-to-buffer ,buffer)))))
2355 (declare-function wgrep-change-to-wgrep-mode "ext:wgrep")
2357 (defun ivy-wgrep-change-to-wgrep-mode ()
2358 "Forward to `wgrep-change-to-wgrep-mode'."
2360 (if (require 'wgrep nil 'noerror)
2361 (wgrep-change-to-wgrep-mode)
2362 (error "Package wgrep isn't installed")))
2364 (defun ivy-occur-read-action ()
2365 "Select one of the available actions as the current one."
2367 (let ((ivy-last ivy-occur-last))
2370 (defun ivy-occur-dispatch ()
2371 "Call one of the available actions on the current item."
2373 (let* ((state-action (ivy-state-action ivy-occur-last))
2374 (actions (if (symbolp state-action)
2376 (copy-sequence state-action))))
2379 (ivy-occur-read-action)
2381 (setf (ivy-state-action ivy-occur-last) actions))))
2383 (defun ivy-occur-click (event)
2384 "Execute action for the current candidate.
2385 EVENT gives the mouse position."
2387 (let ((window (posn-window (event-end event)))
2388 (pos (posn-point (event-end event))))
2389 (with-current-buffer (window-buffer window)
2391 (ivy-occur-press))))
2393 (defun ivy-occur-press ()
2394 "Execute action for the current candidate."
2397 (when (save-excursion
2399 (looking-at "\\(?:./\\| \\)\\(.*\\)$"))
2400 (let* ((ivy-last ivy-occur-last)
2401 (ivy-text (ivy-state-text ivy-last))
2402 (str (buffer-substring
2405 (coll (ivy-state-collection ivy-last))
2406 (action (ivy--get-action ivy-last))
2410 (if (and (consp coll)
2412 (cdr (assoc str coll))
2414 (if (memq (ivy-state-caller ivy-last)
2415 '(swiper counsel-git-grep))
2416 (with-current-buffer (window-buffer (selected-window))
2418 (swiper--add-overlays
2419 (ivy--regex ivy-text)
2420 (line-beginning-position)
2423 (run-at-time 0.5 nil 'swiper--cleanup))
2424 (pulse-momentary-highlight-one-line (point)))))))
2428 ;;; ivy.el ends here