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\\)".
43 "Incremental vertical completion."
46 (defface ivy-current-match
47 '((((class color) (background light))
48 :background "#1a4b77" :foreground "white")
49 (((class color) (background dark))
50 :background "#65a7e2" :foreground "black"))
51 "Face used by Ivy for highlighting first match.")
53 (defface ivy-confirm-face
54 '((t :foreground "ForestGreen" :inherit minibuffer-prompt))
55 "Face used by Ivy to issue a confirmation prompt.")
57 (defface ivy-match-required-face
58 '((t :foreground "red" :inherit minibuffer-prompt))
59 "Face used by Ivy to issue a match required prompt.")
62 '((t (:inherit 'dired-directory)))
63 "Face used by Ivy for highlighting subdirs in the alternatives.")
66 '((t (:foreground "#110099")))
67 "Face used by Ivy for highlighting remotes in the alternatives.")
69 (defcustom ivy-height 10
70 "Number of lines for the minibuffer window."
73 (defcustom ivy-count-format "%-4d "
74 "The style of showing the current candidate count for `ivy-read'.
75 Set this to \"\" if you don't want the count. You can also set
76 it to e.g. \"(%d/%d) \" if you want to see both the candidate
77 index and the candidate count."
79 (const :tag "Count disabled" "")
80 (const :tag "Count matches" "%-4d ")
81 (const :tag "Count matches and show current match" "(%d/%d) ")
84 (defcustom ivy-wrap nil
85 "Whether to wrap around after the first and last candidate."
88 (defcustom ivy-display-style (unless (version< emacs-version "24.5") 'fancy)
89 "The style for formatting the minibuffer.
91 By default, the matched strings will be copied as they are.
93 With the fancy method, the matching parts of the regexp will be
94 additionally highlighted, just like `swiper' does it.
96 This setting depends on `add-face-text-property' - a C function
97 available as of 24.5. It will behave poorly in earlier Emacs
100 (const :tag "Plain" nil)
101 (const :tag "Fancy" fancy)))
103 (defcustom ivy-on-del-error-function 'minibuffer-keyboard-quit
104 "The handler for when `ivy-backward-delete-char' throws.
105 This is usually meant as a quick exit out of the minibuffer."
108 (defcustom ivy-extra-directories '("../" "./")
109 "Add this to the front of the list when completing file names.
110 Only \"./\" and \"../\" apply here. They appear in reverse order."
113 (defcustom ivy-use-virtual-buffers nil
114 "When non-nil, add `recentf-mode' and bookmarks to `ivy-switch-buffer'."
117 (defvar ivy--actions-list nil
118 "A list of extra actions per command.")
120 (defun ivy-set-actions (cmd actions)
121 "Set CMD extra exit points to ACTIONS."
122 (setq ivy--actions-list
123 (plist-put ivy--actions-list cmd actions)))
127 (defvar ivy-minibuffer-map
128 (let ((map (make-sparse-keymap)))
129 (define-key map (kbd "C-m") 'ivy-done)
130 (define-key map (kbd "C-M-m") 'ivy-call)
131 (define-key map (kbd "C-j") 'ivy-alt-done)
132 (define-key map (kbd "C-M-j") 'ivy-immediate-done)
133 (define-key map (kbd "TAB") 'ivy-partial-or-done)
134 (define-key map (kbd "C-n") 'ivy-next-line)
135 (define-key map (kbd "C-p") 'ivy-previous-line)
136 (define-key map (kbd "<down>") 'ivy-next-line)
137 (define-key map (kbd "<up>") 'ivy-previous-line)
138 (define-key map (kbd "C-s") 'ivy-next-line-or-history)
139 (define-key map (kbd "C-r") 'ivy-reverse-i-search)
140 (define-key map (kbd "SPC") 'self-insert-command)
141 (define-key map (kbd "DEL") 'ivy-backward-delete-char)
142 (define-key map (kbd "M-DEL") 'ivy-backward-kill-word)
143 (define-key map (kbd "C-d") 'ivy-delete-char)
144 (define-key map (kbd "C-f") 'ivy-forward-char)
145 (define-key map (kbd "M-d") 'ivy-kill-word)
146 (define-key map (kbd "M-<") 'ivy-beginning-of-buffer)
147 (define-key map (kbd "M->") 'ivy-end-of-buffer)
148 (define-key map (kbd "M-n") 'ivy-next-history-element)
149 (define-key map (kbd "M-p") 'ivy-previous-history-element)
150 (define-key map (kbd "C-g") 'minibuffer-keyboard-quit)
151 (define-key map (kbd "C-v") 'ivy-scroll-up-command)
152 (define-key map (kbd "M-v") 'ivy-scroll-down-command)
153 (define-key map (kbd "C-M-n") 'ivy-next-line-and-call)
154 (define-key map (kbd "C-M-p") 'ivy-previous-line-and-call)
155 (define-key map (kbd "M-q") 'ivy-toggle-regexp-quote)
156 (define-key map (kbd "M-j") 'ivy-yank-word)
157 (define-key map (kbd "M-i") 'ivy-insert-current)
158 (define-key map (kbd "C-o") 'hydra-ivy/body)
159 (define-key map (kbd "M-o") 'ivy-dispatching-done)
160 (define-key map (kbd "C-M-o") 'ivy-dispatching-call)
161 (define-key map (kbd "C-k") 'ivy-kill-line)
162 (define-key map (kbd "S-SPC") 'ivy-restrict-to-matches)
163 (define-key map (kbd "M-w") 'ivy-kill-ring-save)
164 (define-key map (kbd "C-'") 'ivy-avy)
166 "Keymap used in the minibuffer.")
167 (autoload 'hydra-ivy/body "ivy-hydra" "" t)
170 (let ((map (make-sparse-keymap)))
171 (define-key map [remap switch-to-buffer] 'ivy-switch-buffer)
173 "Keymap for `ivy-mode'.")
176 (cl-defstruct ivy-state
178 predicate require-match initial-input
179 history preselect keymap update-fn sort
180 ;; The window in which `ivy-read' was called
186 ;; When this is non-nil, call it for each input change to get new candidates
191 "The last parameters passed to `ivy-read'.
193 This should eventually become a stack so that you could use
194 `ivy-read' recursively.")
196 (defsubst ivy-set-action (action)
197 (setf (ivy-state-action ivy-last) action))
199 (defvar ivy-history nil
200 "History list of candidates entered in the minibuffer.
202 Maximum length of the history list is determined by the value
203 of `history-length', which see.")
205 (defvar ivy--directory nil
206 "Current directory when completing file names.")
208 (defvar ivy--length 0
209 "Store the amount of viable candidates.")
212 "Store the user's string as it is typed in.")
214 (defvar ivy--current ""
215 "Current candidate.")
218 "Store the index of the current candidate.")
221 "Store 'done if the completion was successfully selected.
222 Otherwise, store nil.")
224 (defvar ivy--all-candidates nil
225 "Store the candidates passed to `ivy-read'.")
227 (defvar ivy--default nil
228 "Default initial input.")
230 (defvar ivy--prompt nil
231 "Store the format-style prompt.
232 When non-nil, it should contain one %d.")
234 (defvar ivy--prompt-extra ""
235 "Temporary modifications to the prompt.")
237 (defvar ivy--old-re nil
238 "Store the old regexp.")
240 (defvar ivy--old-cands nil
241 "Store the candidates matched by `ivy--old-re'.")
243 (defvar ivy--regex-function 'ivy--regex
244 "Current function for building a regex.")
246 (defvar ivy--subexps 0
247 "Number of groups in the current `ivy--regex'.")
249 (defvar ivy--full-length nil
250 "When :dynamic-collection is non-nil, this can be the total amount of candidates.")
252 (defvar ivy--old-text ""
253 "Store old `ivy-text' for dynamic completion.")
255 (defvar ivy-case-fold-search 'auto
256 "Store the current overriding `case-fold-search'.")
258 (defvar Info-current-file)
260 (defmacro ivy-quit-and-run (&rest body)
261 "Quit the minibuffer and run BODY afterwards."
263 (put 'quit 'error-message "")
266 (put 'quit 'error-message "Quit")
268 (minibuffer-keyboard-quit)))
270 (defmacro with-ivy-window (&rest body)
271 "Execute BODY in the window from which `ivy-read' was called."
274 `(with-selected-window (ivy-state-window ivy-last)
277 (defun ivy--done (text)
278 "Insert TEXT and exit minibuffer."
279 (if (and ivy--directory
280 (not (eq (ivy-state-history ivy-last) 'grep-files-history)))
281 (insert (setq ivy--current (expand-file-name
282 text ivy--directory)))
283 (insert (setq ivy--current text)))
284 (setq ivy-exit 'done)
289 "Exit the minibuffer with the selected candidate."
291 (delete-minibuffer-contents)
292 (cond ((> ivy--length 0)
293 (ivy--done ivy--current))
294 ((memq (ivy-state-collection ivy-last)
295 '(read-file-name-internal internal-complete-buffer))
296 (if (or (not (eq confirm-nonexistent-file-or-buffer t))
297 (equal " (confirm)" ivy--prompt-extra))
299 (setq ivy--prompt-extra " (confirm)")
302 ((memq (ivy-state-require-match ivy-last)
303 '(nil confirm confirm-after-completion))
304 (ivy--done ivy-text))
306 (setq ivy--prompt-extra " (match required)")
310 (defun ivy-read-action ()
311 "Change the action to one of the available ones."
313 (let ((actions (ivy-state-action ivy-last)))
314 (unless (null (ivy--actionp actions))
315 (let* ((hint (concat ivy--current
322 'face 'font-lock-builtin-face)
327 (key (string (read-key hint)))
328 (action-idx (cl-position-if
329 (lambda (x) (equal (car x) key))
331 (cond ((string= key "
\a"))
333 (error "%s is not bound" key))
336 (setcar actions (1+ action-idx))
337 (ivy-set-action actions)))))))
339 (defun ivy-dispatching-done ()
340 "Select one of the available actions and call `ivy-done'."
345 (defun ivy-dispatching-call ()
346 "Select one of the available actions and call `ivy-call'."
348 (let ((actions (copy-sequence (ivy-state-action ivy-last))))
351 (ivy-set-action actions)))
353 (defun ivy-build-tramp-name (x)
354 "Reconstruct X into a path.
355 Is is a cons cell, related to `tramp-get-completion-function'."
359 (concat user "@" domain)
362 (declare-function tramp-get-completion-function "tramp")
363 (declare-function Info-find-node "info")
365 (defun ivy-alt-done (&optional arg)
366 "Exit the minibuffer with the selected candidate.
367 When ARG is t, exit with current text, ignoring the candidates."
371 (ivy-immediate-done))
375 (not (string= ivy--current "./"))
376 (cl-plusp ivy--length)
378 (setq dir (expand-file-name
379 ivy--current ivy--directory))))))
382 ((eq (ivy-state-collection ivy-last) 'Info-read-node-name-1)
383 (if (or (equal ivy--current "(./)")
384 (equal ivy--current "(../)"))
386 (ivy-read "Go to file: " 'read-file-name-internal
389 (expand-file-name x ivy--directory)
393 (string-match "\\`/[^/]+:.*:.*\\'" ivy-text))
397 "\\`/\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
399 (let ((method (match-string 1 ivy-text))
400 (user (match-string 2 ivy-text))
401 (rest (match-string 3 ivy-text))
404 (dolist (x (tramp-get-completion-function method))
405 (setq res (append res (funcall (car x) (cadr x)))))
406 (setq res (delq nil res))
410 (setq res (cl-delete-duplicates res :test #'equal))
411 (let* ((old-ivy-last ivy-last)
412 (enable-recursive-minibuffers t)
413 (host (ivy-read "Find File: "
414 (mapcar #'ivy-build-tramp-name res)
415 :initial-input rest)))
416 (setq ivy-last old-ivy-last)
418 (setq ivy--directory "/")
419 (ivy--cd (concat "/" method ":" host ":"))))))
423 (defcustom ivy-tab-space nil
424 "When non-nil, `ivy-partial-or-done' should insert a space."
427 (defun ivy-partial-or-done ()
428 "Complete the minibuffer text as much as possible.
429 If the text hasn't changed as a result, forward to `ivy-alt-done'."
431 (if (and (eq (ivy-state-collection ivy-last) #'read-file-name-internal)
432 (string-match "\\`/" ivy-text))
433 (let ((default-directory ivy--directory))
434 (minibuffer-complete)
435 (setq ivy-text (ivy--input))
436 (when (and (file-directory-p ivy-text)
438 (ivy--cd (expand-file-name ivy-text))))
440 (when (or (eq this-command last-command)
444 (defun ivy-partial ()
445 "Complete the minibuffer text as much as possible."
447 (let* ((parts (or (split-string ivy-text " " t) (list "")))
448 (postfix (car (last parts)))
449 (completion-ignore-case t)
450 (startp (string-match "^\\^" postfix))
451 (new (try-completion (if startp
452 (substring postfix 1)
454 (mapcar (lambda (str) (substring str (string-match postfix str)))
456 (cond ((eq new t) nil)
457 ((string= new ivy-text) nil)
459 (delete-region (minibuffer-prompt-end) (point-max))
464 (insert (mapconcat #'identity parts " ")
465 (if ivy-tab-space " " ""))
468 (defun ivy-immediate-done ()
469 "Exit the minibuffer with the current input."
471 (delete-minibuffer-contents)
472 (insert (setq ivy--current ivy-text))
473 (setq ivy-exit 'done)
478 "Resume the last completion session."
481 (ivy-state-prompt ivy-last)
482 (ivy-state-collection ivy-last)
483 :predicate (ivy-state-predicate ivy-last)
484 :require-match (ivy-state-require-match ivy-last)
485 :initial-input ivy-text
486 :history (ivy-state-history ivy-last)
487 :preselect (unless (eq (ivy-state-collection ivy-last)
488 'read-file-name-internal)
490 :keymap (ivy-state-keymap ivy-last)
491 :update-fn (ivy-state-update-fn ivy-last)
492 :sort (ivy-state-sort ivy-last)
493 :action (ivy-state-action ivy-last)
494 :unwind (ivy-state-unwind ivy-last)
495 :re-builder (ivy-state-re-builder ivy-last)
496 :matcher (ivy-state-matcher ivy-last)
497 :dynamic-collection (ivy-state-dynamic-collection ivy-last)))
499 (defvar ivy-calling nil
500 "When non-nil, call the current action when `ivy--index' changes.")
502 (defun ivy-set-index (index)
503 "Set `ivy--index' to INDEX."
504 (setq ivy--index index)
509 (defun ivy-beginning-of-buffer ()
510 "Select the first completion candidate."
514 (defun ivy-end-of-buffer ()
515 "Select the last completion candidate."
517 (ivy-set-index (1- ivy--length)))
519 (defun ivy-scroll-up-command ()
520 "Scroll the candidates upward by the minibuffer height."
522 (ivy-set-index (min (+ ivy--index ivy-height)
525 (defun ivy-scroll-down-command ()
526 "Scroll the candidates downward by the minibuffer height."
528 (ivy-set-index (max (- ivy--index ivy-height)
531 (defun ivy-minibuffer-grow ()
532 "Grow the minibuffer window by 1 line."
534 (setq-local max-mini-window-height
535 (cl-incf ivy-height)))
537 (defun ivy-minibuffer-shrink ()
538 "Shrink the minibuffer window by 1 line."
540 (unless (<= ivy-height 2)
541 (setq-local max-mini-window-height
542 (cl-decf ivy-height))
543 (window-resize (selected-window) -1)))
545 (defun ivy-next-line (&optional arg)
546 "Move cursor vertically down ARG candidates."
548 (setq arg (or arg 1))
549 (let ((index (+ ivy--index arg)))
550 (if (> index (1- ivy--length))
552 (ivy-beginning-of-buffer)
553 (ivy-set-index (1- ivy--length)))
554 (ivy-set-index index))))
556 (defun ivy-next-line-or-history (&optional arg)
557 "Move cursor vertically down ARG candidates.
558 If the input is empty, select the previous history element instead."
560 (when (string= ivy-text "")
561 (ivy-previous-history-element 1))
564 (defun ivy-previous-line (&optional arg)
565 "Move cursor vertically up ARG candidates."
567 (setq arg (or arg 1))
568 (let ((index (- ivy--index arg)))
573 (ivy-set-index index))))
575 (defun ivy-previous-line-or-history (arg)
576 "Move cursor vertically up ARG candidates.
577 If the input is empty, select the previous history element instead."
579 (when (string= ivy-text "")
580 (ivy-previous-history-element 1))
581 (ivy-previous-line arg))
583 (defun ivy-toggle-calling ()
584 "Flip `ivy-calling'."
586 (when (setq ivy-calling (not ivy-calling))
589 (defun ivy--get-action (state)
590 "Get the action function from STATE."
591 (let ((action (ivy-state-action state)))
593 (if (functionp action)
595 (cadr (nth (car action) action))))))
597 (defun ivy--actionp (x)
598 "Return non-nil when X is a list of actions."
599 (and x (listp x) (not (eq (car x) 'closure))))
601 (defun ivy-next-action ()
602 "When the current action is a list, scroll it forwards."
604 (let ((action (ivy-state-action ivy-last)))
605 (when (ivy--actionp action)
606 (unless (>= (car action) (1- (length action)))
607 (cl-incf (car action))))))
609 (defun ivy-prev-action ()
610 "When the current action is a list, scroll it backwards."
612 (let ((action (ivy-state-action ivy-last)))
613 (when (ivy--actionp action)
614 (unless (<= (car action) 1)
615 (cl-decf (car action))))))
617 (defun ivy-action-name ()
618 "Return the name associated with the current action."
619 (let ((action (ivy-state-action ivy-last)))
620 (if (ivy--actionp action)
624 (nth 2 (nth (car action) action)))
628 "Call the current action without exiting completion."
630 (let ((action (ivy--get-action ivy-last)))
632 (let* ((collection (ivy-state-collection ivy-last))
633 (x (if (and (consp collection)
634 (consp (car collection)))
635 (cdr (assoc ivy--current collection))
636 (if (equal ivy--current "")
639 (prog1 (funcall action x)
640 (unless (or (eq ivy-exit 'done)
641 (equal (selected-window)
642 (active-minibuffer-window))
643 (null (active-minibuffer-window)))
644 (select-window (active-minibuffer-window))))))))
646 (defun ivy-next-line-and-call (&optional arg)
647 "Move cursor vertically down ARG candidates.
648 Call the permanent action if possible."
654 (defun ivy-previous-line-and-call (&optional arg)
655 "Move cursor vertically down ARG candidates.
656 Call the permanent action if possible."
658 (ivy-previous-line arg)
662 (defun ivy-previous-history-element (arg)
663 "Forward to `previous-history-element' with ARG."
665 (previous-history-element arg)
668 (ivy--maybe-scroll-history))
670 (defun ivy-next-history-element (arg)
671 "Forward to `next-history-element' with ARG."
673 (next-history-element arg)
676 (ivy--maybe-scroll-history))
678 (defun ivy--cd-maybe ()
679 "Check if the current input points to a different directory.
680 If so, move to that directory, while keeping only the file name."
682 (let* ((input (expand-file-name (ivy--input)))
683 (file (file-name-nondirectory input))
684 (dir (expand-file-name (file-name-directory input))))
685 (if (string= dir ivy--directory)
687 (delete-minibuffer-contents)
692 (defun ivy--maybe-scroll-history ()
693 "If the selected history element has an index, scroll there."
694 (let ((idx (ignore-errors
696 (minibuffer-prompt-end)
700 (setq ivy--index idx))))
703 "When completing file names, move to directory DIR."
704 (if (null ivy--directory)
706 (setq ivy--old-cands nil)
707 (setq ivy--old-re nil)
709 (setq ivy--all-candidates
710 (ivy--sorted-files (setq ivy--directory dir)))
712 (delete-minibuffer-contents)))
714 (defun ivy-backward-delete-char ()
715 "Forward to `backward-delete-char'.
716 On error (read-only), call `ivy-on-del-error-function'."
718 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
720 (ivy--cd (file-name-directory
726 (backward-delete-char 1)
728 (when ivy-on-del-error-function
729 (funcall ivy-on-del-error-function))))))
731 (defun ivy-delete-char (arg)
732 "Forward to `delete-char' ARG."
734 (unless (= (point) (line-end-position))
737 (defun ivy-forward-char (arg)
738 "Forward to `forward-char' ARG."
740 (unless (= (point) (line-end-position))
743 (defun ivy-kill-word (arg)
744 "Forward to `kill-word' ARG."
746 (unless (= (point) (line-end-position))
749 (defun ivy-kill-line ()
750 "Forward to `kill-line'."
753 (kill-region (minibuffer-prompt-end) (point))
756 (defun ivy-backward-kill-word ()
757 "Forward to `backward-kill-word'."
759 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
761 (ivy--cd (file-name-directory
769 (delete-region (point) pt)))))
771 (defvar ivy--regexp-quote 'regexp-quote
772 "Store the regexp quoting state.")
774 (defun ivy-toggle-regexp-quote ()
775 "Toggle the regexp quoting."
777 (setq ivy--old-re nil)
778 (cl-rotatef ivy--regex-function ivy--regexp-quote))
780 (defvar avy-all-windows)
783 (defvar avy-keys-alist)
785 (defvar avy-styles-alist)
786 (declare-function avy--process "ext:avy")
787 (declare-function avy--style-fn "ext:avy")
789 (eval-after-load 'avy
790 '(add-to-list 'avy-styles-alist '(ivy-avy . pre)))
793 "Jump to one of the current ivy candidates."
795 (unless (require 'avy nil 'noerror)
796 (error "Package avy isn't installed"))
797 (let* ((avy-all-windows nil)
798 (avy-keys (or (cdr (assq 'ivy-avy avy-keys-alist))
800 (avy-style (or (cdr (assq 'ivy-avy
810 (goto-char (point-min))
812 (while (< (point) (point-max))
818 (setq avy-action #'identity)
820 (nreverse candidates)
821 (avy--style-fn avy-style)))))
822 (ivy-set-index (- (line-number-at-pos candidate) 2))
826 (defun ivy-sort-file-function-default (x y)
827 "Compare two files X and Y.
828 Prioritize directories."
829 (if (get-text-property 0 'dirp x)
830 (if (get-text-property 0 'dirp y)
833 (if (get-text-property 0 'dirp y)
837 (defvar ivy-sort-functions-alist
838 '((read-file-name-internal . ivy-sort-file-function-default)
839 (internal-complete-buffer . nil)
840 (counsel-git-grep-function . nil)
841 (Man-goto-section . nil)
844 "An alist of sorting functions for each collection function.
845 Interactive functions that call completion fit in here as well.
847 For each entry, nil means no sorting. It's very useful to turn
848 off the sorting for functions that have candidates in the natural
849 buffer order, like `org-refile' or `Man-goto-section'.
851 The entry associated to t is used for all fall-through cases.")
853 (defvar ivy-index-functions-alist
854 '((swiper . ivy-recompute-index-swiper)
855 (swiper-multi . ivy-recompute-index-swiper)
856 (counsel-git-grep . ivy-recompute-index-swiper)
857 (t . ivy-recompute-index-zero))
858 "An alist of index recomputing functions for each collection function.
859 When the input changes, calling the appropriate function will
860 return an integer - the index of the matched candidate that
861 should be selected.")
863 (defvar ivy-re-builders-alist
864 '((t . ivy--regex-plus))
865 "An alist of regex building functions for each collection function.
866 Each function should take a string and return a valid regex or a
867 regex sequence (see below).
869 The entry associated to t is used for all fall-through cases.
870 Possible choices: `ivy--regex', `regexp-quote', `ivy--regex-plus'.
872 In case a function returns a list, it should look like this:
873 '((\"matching-regexp\" . t) (\"non-matching-regexp\") ...).
875 The matches will be filtered in a sequence, you can mix the
876 regexps that should match and that should not match as you
879 (defvar ivy-initial-inputs-alist
881 (org-agenda-refile . "^")
882 (org-capture-refile . "^")
884 (counsel-describe-function . "^")
885 (counsel-describe-variable . "^")
888 "Command to initial input table.")
890 (defcustom ivy-sort-max-size 30000
891 "Sorting won't be done for collections larger than this."
894 (defun ivy--sorted-files (dir)
895 "Return the list of files in DIR.
896 Directories come first."
897 (let* ((default-directory dir)
898 (seq (all-completions "" 'read-file-name-internal))
902 (setq seq (delete "./" (delete "../" seq)))
903 (when (eq (setq sort-fn (cdr (assoc 'read-file-name-internal
904 ivy-sort-functions-alist)))
905 #'ivy-sort-file-function-default)
906 (setq seq (mapcar (lambda (x)
907 (propertize x 'dirp (string-match-p "/\\'" x)))
910 (setq seq (cl-sort seq sort-fn)))
911 (dolist (dir ivy-extra-directories)
916 (cl-defun ivy-read (prompt collection
917 &key predicate require-match initial-input
918 history preselect keymap update-fn sort
919 action unwind re-builder matcher dynamic-collection caller)
920 "Read a string in the minibuffer, with completion.
922 PROMPT is a string to prompt with; normally it ends in a colon
923 and a space. When PROMPT contains %d, it will be updated with
924 the current number of matching candidates. If % appears elsewhere
925 in the PROMPT it should be quoted as %%.
926 See also `ivy-count-format'.
928 COLLECTION is a list of strings, or a function, or an alist, or a
931 If INITIAL-INPUT is non-nil, insert it in the minibuffer initially.
933 KEYMAP is composed together with `ivy-minibuffer-map'.
935 If PRESELECT is non-nil select the corresponding candidate out of
936 the ones that match INITIAL-INPUT.
938 UPDATE-FN is called each time the current candidate(s) is changed.
940 When SORT is t, refer to `ivy-sort-functions-alist' for sorting.
942 ACTION is a lambda to call after a result was selected. It should
943 take a single argument, usually a string.
945 UNWIND is a lambda to call before exiting.
947 RE-BUILDER is a lambda that transforms text into a regex.
949 MATCHER can completely override matching.
951 DYNAMIC-COLLECTION is a function to call to update the list of
952 candidates with each input.
954 CALLER is a symbol to uniquely identify the caller to `ivy-read'.
955 It's used in conjunction with COLLECTION to indentify which
956 customizations should apply to the current completion session."
957 (let ((extra-actions (plist-get ivy--actions-list this-command)))
960 (if (functionp action)
962 ("o" ,action "default")
964 (delete-dups (append action extra-actions))))))
968 :collection collection
970 :require-match require-match
971 :initial-input initial-input
978 :window (selected-window)
980 :re-builder re-builder
982 :dynamic-collection dynamic-collection
984 (ivy--reset-state ivy-last)
987 (minibuffer-with-setup-hook
988 #'ivy--minibuffer-setup
989 (let* ((hist (or history 'ivy-history))
990 (minibuffer-completion-table collection)
991 (minibuffer-completion-predicate predicate)
992 (resize-mini-windows (cond
993 ((display-graphic-p) nil)
994 ((null resize-mini-windows) 'grow-only)
995 (t resize-mini-windows)))
996 (res (read-from-minibuffer
998 (ivy-state-initial-input ivy-last)
999 (make-composed-keymap keymap ivy-minibuffer-map)
1002 (when (eq ivy-exit 'done)
1003 (let ((item (if ivy--directory
1006 (unless (equal item "")
1007 (set hist (cons (propertize item 'ivy-index ivy--index)
1009 (cdr (symbol-value hist)))))))
1011 (remove-hook 'post-command-hook #'ivy--exhibit)
1012 (when (setq unwind (ivy-state-unwind ivy-last))
1016 (defun ivy--reset-state (state)
1017 "Reset the ivy to STATE.
1018 This is useful for recursive `ivy-read'."
1019 (let ((prompt (ivy-state-prompt state))
1020 (collection (ivy-state-collection state))
1021 (predicate (ivy-state-predicate state))
1022 (history (ivy-state-history state))
1023 (preselect (ivy-state-preselect state))
1024 (sort (ivy-state-sort state))
1025 (re-builder (ivy-state-re-builder state))
1026 (dynamic-collection (ivy-state-dynamic-collection state))
1027 (initial-input (ivy-state-initial-input state))
1028 (require-match (ivy-state-require-match state))
1029 (matcher (ivy-state-matcher state)))
1030 (unless initial-input
1031 (setq initial-input (cdr (assoc this-command
1032 ivy-initial-inputs-alist))))
1033 (setq ivy--directory nil)
1034 (setq ivy-case-fold-search 'auto)
1035 (setq ivy--regex-function
1037 (and (functionp collection)
1038 (cdr (assoc collection ivy-re-builders-alist)))
1039 (cdr (assoc t ivy-re-builders-alist))
1041 (setq ivy--subexps 0)
1042 (setq ivy--regexp-quote 'regexp-quote)
1043 (setq ivy--old-text "")
1044 (setq ivy--full-length nil)
1046 (setq ivy-calling nil)
1048 (cond ((eq collection 'Info-read-node-name-1)
1049 (if (equal Info-current-file "dir")
1051 (mapcar (lambda (x) (format "(%s)" x))
1052 (cl-delete-duplicates
1053 (all-completions "(" collection predicate)
1055 (setq coll (all-completions "" collection predicate))))
1056 ((eq collection 'read-file-name-internal)
1057 (setq ivy--directory default-directory)
1060 (let ((preselect-directory (file-name-directory preselect)))
1061 (unless (or (null preselect-directory)
1062 (string= preselect-directory
1064 (setq ivy--directory preselect-directory))
1066 (ivy-state-preselect state)
1067 (setq preselect (file-name-nondirectory preselect)))))
1068 (setq coll (ivy--sorted-files ivy--directory))
1070 (unless (or require-match
1071 (equal initial-input default-directory)
1072 (equal initial-input ""))
1073 (setq coll (cons initial-input coll)))
1074 (setq initial-input nil)))
1075 ((eq collection 'internal-complete-buffer)
1076 (setq coll (ivy--buffer-list "" ivy-use-virtual-buffers)))
1077 ((or (functionp collection)
1078 (byte-code-function-p collection)
1079 (vectorp collection)
1080 (and (consp collection) (listp (car collection)))
1081 (hash-table-p collection))
1082 (setq coll (all-completions "" collection predicate)))
1084 (setq coll collection)))
1086 (if (and (functionp collection)
1087 (setq sort-fn (assoc collection ivy-sort-functions-alist)))
1088 (when (and (setq sort-fn (cdr sort-fn))
1089 (not (eq collection 'read-file-name-internal)))
1090 (setq coll (cl-sort coll sort-fn)))
1091 (unless (eq history 'org-refile-history)
1092 (if (and (setq sort-fn (cdr (assoc t ivy-sort-functions-alist)))
1093 (<= (length coll) ivy-sort-max-size))
1094 (setq coll (cl-sort (copy-sequence coll) sort-fn))))))
1096 (unless (or (and require-match
1097 (not (eq collection 'internal-complete-buffer)))
1098 (let ((re (regexp-quote preselect)))
1099 (cl-find-if (lambda (x) (string-match re x))
1101 (setq coll (cons preselect coll))))
1102 (setq ivy--index (or
1103 (and dynamic-collection
1106 (ivy--preselect-index
1107 coll initial-input preselect matcher))
1109 (setq ivy--old-re nil)
1110 (setq ivy--old-cands nil)
1111 (setq ivy--all-candidates coll))
1113 (setq ivy--default (or (thing-at-point 'symbol) ""))
1115 (cond ((string-match "%.*d" prompt)
1117 ((null ivy-count-format)
1119 "`ivy-count-format' can't be nil. Set it to an empty string instead."))
1120 ((string-match "%d.*%d" ivy-count-format)
1121 (let ((w (length (number-to-string
1122 (length ivy--all-candidates))))
1123 (s (copy-sequence ivy-count-format)))
1124 (string-match "%d" s)
1126 (string-match "%d" s (match-end 0))
1127 (setq s (replace-match (format "%%-%dd" w) nil nil s))
1128 (string-match "%d" s)
1129 (concat (replace-match (format "%%%dd" w) nil nil s)
1131 ((string-match "%.*d" ivy-count-format)
1132 (concat ivy-count-format prompt))
1137 (setf (ivy-state-initial-input ivy-last) initial-input)))
1140 (defun ivy-completing-read (prompt collection
1141 &optional predicate require-match initial-input
1142 history def _inherit-input-method)
1143 "Read a string in the minibuffer, with completion.
1145 This is an interface that conforms to `completing-read', so that
1146 it can be used for `completing-read-function'.
1148 PROMPT is a string to prompt with; normally it ends in a colon and a space.
1149 COLLECTION can be a list of strings, an alist, an obarray or a hash table.
1150 PREDICATE limits completion to a subset of COLLECTION.
1151 REQUIRE-MATCH is considered boolean. See `completing-read'.
1152 INITIAL-INPUT is a string that can be inserted into the minibuffer initially.
1153 _HISTORY is ignored for now.
1154 DEF is the default value.
1155 _INHERIT-INPUT-METHOD is ignored for now.
1157 The history, defaults and input-method arguments are ignored for now."
1158 (ivy-read (replace-regexp-in-string "%" "%%" prompt)
1160 :predicate predicate
1161 :require-match require-match
1162 :initial-input (if (consp initial-input)
1164 (if (and (stringp initial-input)
1165 (string-match "\\+" initial-input))
1166 (replace-regexp-in-string
1167 "\\+" "\\\\+" initial-input)
1169 :preselect (if (listp def) (car def) def)
1173 (let ((sort (assoc this-command ivy-sort-functions-alist)))
1179 (define-minor-mode ivy-mode
1180 "Toggle Ivy mode on or off.
1181 With ARG, turn Ivy mode on if arg is positive, off otherwise.
1182 Turning on Ivy mode will set `completing-read-function' to
1183 `ivy-completing-read'.
1188 Minibuffer bindings:
1189 \\{ivy-minibuffer-map}"
1192 :keymap ivy-mode-map
1195 (setq completing-read-function 'ivy-completing-read)
1196 (setq completing-read-function 'completing-read-default)))
1198 (defun ivy--preselect-index (candidates initial-input preselect matcher)
1199 "Return the index in CANDIDATES filtered by INITIAL-INPUT for PRESELECT.
1200 When MATCHER is non-nil it's used instead of `cl-remove-if-not'."
1203 (setq initial-input (ivy--regex-plus initial-input))
1206 (funcall matcher initial-input candidates)
1209 (string-match initial-input x))
1212 (setq candidates (funcall matcher "" candidates))))
1213 (or (cl-position preselect candidates :test #'equal)
1214 (and (stringp preselect)
1215 (let ((re (regexp-quote preselect)))
1218 (string-match re x))
1223 (defvar ivy--regex-hash
1224 (make-hash-table :test #'equal)
1225 "Store pre-computed regex.")
1227 (defun ivy--split (str)
1228 "Split STR into a list by single spaces.
1229 The remaining spaces stick to their left.
1230 This allows to \"quote\" N spaces by inputting N+1 spaces."
1231 (let ((len (length str))
1236 (while (and (string-match " +" str start1)
1238 (setq match-len (- (match-end 0) (match-beginning 0)))
1242 (setq start1 start0)
1244 (push (substring str start1 (match-beginning 0)) res)
1245 (setq start1 (match-end 0)))
1246 (setq str (replace-match
1247 (make-string (1- match-len) ?\ )
1249 (setq start0 (or start0 start1))
1250 (setq start1 (1- (match-end 0)))))
1252 (push (substring str start0) res)
1253 (setq s (substring str start1))
1254 (unless (= (length s) 0)
1258 (defun ivy--regex (str &optional greedy)
1259 "Re-build regex from STR in case it has a space.
1260 When GREEDY is non-nil, join words in a greedy way."
1261 (let ((hashed (unless greedy
1262 (gethash str ivy--regex-hash))))
1265 (setq ivy--subexps (car hashed)))
1266 (when (string-match "\\([^\\]\\|^\\)\\\\$" str)
1267 (setq str (substring str 0 -1)))
1269 (let ((subs (ivy--split str)))
1270 (if (= (length subs) 1)
1272 (setq ivy--subexps 0)
1275 (setq ivy--subexps (length subs))
1278 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1280 (format "\\(%s\\)" x)))
1285 ivy--regex-hash)))))
1287 (defun ivy--regex-ignore-order (str)
1288 "Re-build regex from STR by splitting it on spaces.
1289 Ignore the order of each group."
1290 (let* ((subs (split-string str " +" t))
1291 (len (length subs)))
1294 (setq ivy--subexps 0)
1297 (setq ivy--subexps len)
1298 (let ((all (mapconcat #'identity subs "\\|")))
1301 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1303 (format "\\(%s\\)" x)))
1307 (defun ivy--regex-plus (str)
1308 "Build a regex sequence from STR.
1309 Spaces are wild, everything before \"!\" should match.
1310 Everything after \"!\" should not match."
1311 (let ((parts (split-string str "!" t)))
1312 (cl-case (length parts)
1316 (ivy--regex (car parts)))
1320 (split-string (cadr parts) " " t))))
1321 (cons (cons (ivy--regex (car parts)) t)
1323 (t (error "Unexpected: use only one !")))))
1325 (defun ivy--regex-fuzzy (str)
1326 "Build a regex sequence from STR.
1327 Insert .* between each char."
1328 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1330 (concat (match-string 1 str)
1333 (format "\\(%c\\)" x))
1334 (string-to-list (match-string 2 str)) ".*")
1335 (match-string 3 str))
1336 (setq ivy--subexps (length (match-string 2 str))))
1340 (defun ivy--minibuffer-setup ()
1341 "Setup ivy completion in the minibuffer."
1342 (set (make-local-variable 'completion-show-inline-help) nil)
1343 (set (make-local-variable 'minibuffer-default-add-function)
1345 (list ivy--default)))
1346 (when (display-graphic-p)
1347 (setq truncate-lines t))
1348 (setq-local max-mini-window-height ivy-height)
1349 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1350 ;; show completions with empty input
1353 (defun ivy--input ()
1354 "Return the current minibuffer input."
1355 ;; assume one-line minibuffer input
1356 (buffer-substring-no-properties
1357 (minibuffer-prompt-end)
1358 (line-end-position)))
1360 (defun ivy--cleanup ()
1361 "Delete the displayed completion candidates."
1363 (goto-char (minibuffer-prompt-end))
1364 (delete-region (line-end-position) (point-max))))
1366 (defun ivy--insert-prompt ()
1367 "Update the prompt according to `ivy--prompt'."
1369 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1370 counsel-find-symbol))
1371 (setq ivy--prompt-extra ""))
1373 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1375 (setq head (match-string 1 ivy--prompt))
1377 (setq head (substring ivy--prompt 0 -1))
1379 (let ((inhibit-read-only t)
1380 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1383 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1384 (> (minibuffer-depth) 1))
1385 (format "[%d] " (minibuffer-depth))
1388 (if (string-match "%d.*%d" ivy-count-format)
1391 (or (and (ivy-state-dynamic-collection ivy-last)
1395 (or (and (ivy-state-dynamic-collection ivy-last)
1400 (d-str (if ivy--directory
1401 (abbreviate-file-name ivy--directory)
1404 (goto-char (point-min))
1405 (delete-region (point-min) (minibuffer-prompt-end))
1406 (if (> (+ (mod (+ (length n-str) (length d-str)) (window-width))
1409 (setq n-str (concat n-str "\n" d-str))
1410 (setq n-str (concat n-str d-str)))
1411 (let ((regex (format "\\([^\n]\\{%d\\}\\)[^\n]" (window-width))))
1412 (while (string-match regex n-str)
1413 (setq n-str (replace-match (concat (match-string 1 n-str) "\n") nil t n-str 1))))
1414 (set-text-properties 0 (length n-str)
1415 `(face minibuffer-prompt ,@std-props)
1417 (ivy--set-match-props n-str "confirm"
1418 `(face ivy-confirm-face ,@std-props))
1419 (ivy--set-match-props n-str "match required"
1420 `(face ivy-match-required-face ,@std-props))
1422 ;; get out of the prompt area
1423 (constrain-to-field nil (point-max))))))
1425 (defun ivy--set-match-props (str match props)
1426 "Set STR text proprties that match MATCH to PROPS."
1427 (when (string-match match str)
1428 (set-text-properties
1434 (defvar inhibit-message)
1436 (defun ivy--sort-maybe (collection)
1437 "Sort COLLECTION if needed."
1438 (let ((sort (ivy-state-sort ivy-last))
1442 (let ((sort-fn (cond ((functionp sort)
1444 ((setq entry (assoc (ivy-state-collection ivy-last)
1445 ivy-sort-functions-alist))
1448 (cdr (assoc t ivy-sort-functions-alist))))))
1449 (if (functionp sort-fn)
1450 (cl-sort (copy-sequence collection) sort-fn)
1453 (defun ivy--exhibit ()
1454 "Insert Ivy completions display.
1455 Should be run via minibuffer `post-command-hook'."
1456 (when (memq 'ivy--exhibit post-command-hook)
1457 (let ((inhibit-field-text-motion nil))
1458 (constrain-to-field nil (point-max)))
1459 (setq ivy-text (ivy--input))
1460 (if (ivy-state-dynamic-collection ivy-last)
1461 ;; while-no-input would cause annoying
1462 ;; "Waiting for process to die...done" message interruptions
1463 (let ((inhibit-message t))
1464 (unless (equal ivy--old-text ivy-text)
1466 (setq ivy--all-candidates
1468 (funcall (ivy-state-collection ivy-last) ivy-text)))
1469 (setq ivy--old-text ivy-text)))
1470 (when ivy--all-candidates
1471 (ivy--insert-minibuffer
1472 (ivy--format ivy--all-candidates))))
1473 (cond (ivy--directory
1474 (if (string-match "/\\'" ivy-text)
1475 (if (member ivy-text ivy--all-candidates)
1476 (ivy--cd (expand-file-name ivy-text ivy--directory))
1477 (when (string-match "//\\'" ivy-text)
1478 (if (and default-directory
1479 (string-match "\\`[[:alpha:]]:/" default-directory))
1480 (ivy--cd (match-string 0 default-directory))
1482 (when (string-match "[[:alpha:]]:/" ivy-text)
1483 (let ((drive-root (match-string 0 ivy-text)))
1484 (when (file-exists-p drive-root)
1485 (ivy--cd drive-root)))))
1486 (if (string-match "\\`~\\'" ivy-text)
1487 (ivy--cd (expand-file-name "~/")))))
1488 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1489 (when (or (and (string-match "\\` " ivy-text)
1490 (not (string-match "\\` " ivy--old-text)))
1491 (and (string-match "\\` " ivy--old-text)
1492 (not (string-match "\\` " ivy-text))))
1493 (setq ivy--all-candidates
1494 (if (and (> (length ivy-text) 0)
1495 (eq (aref ivy-text 0)
1497 (ivy--buffer-list " ")
1498 (ivy--buffer-list "" ivy-use-virtual-buffers)))
1499 (setq ivy--old-re nil))))
1500 (ivy--insert-minibuffer
1502 (ivy--filter ivy-text ivy--all-candidates)))
1503 (setq ivy--old-text ivy-text))))
1505 (defun ivy--insert-minibuffer (text)
1506 "Insert TEXT into minibuffer with appropriate cleanup."
1507 (let ((resize-mini-windows nil)
1508 (update-fn (ivy-state-update-fn ivy-last))
1512 (funcall update-fn))
1513 (ivy--insert-prompt)
1514 ;; Do nothing if while-no-input was aborted.
1515 (when (stringp text)
1516 (let ((buffer-undo-list t))
1520 (when (display-graphic-p)
1521 (ivy--resize-minibuffer-to-fit))))
1523 (defun ivy--resize-minibuffer-to-fit ()
1524 "Resize the minibuffer window so it has enough space to display
1525 all of the text contained in the minibuffer."
1526 (with-selected-window (minibuffer-window)
1527 (if (fboundp 'window-text-pixel-size)
1528 (let ((text-height (cdr (window-text-pixel-size)))
1529 (body-height (window-body-height nil t)))
1530 (when (> text-height body-height)
1531 (window-resize nil (- text-height body-height) nil t t)))
1532 (let ((text-height (count-screen-lines))
1533 (body-height (window-body-height)))
1534 (when (> text-height body-height)
1535 (window-resize nil (- text-height body-height) nil t))))))
1537 (declare-function colir-blend-face-background "ext:colir")
1539 (defun ivy--add-face (str face)
1540 "Propertize STR with FACE.
1541 `font-lock-append-text-property' is used, since it's better than
1542 `propertize' or `add-face-text-property' in this case."
1546 (colir-blend-face-background 0 (length str) face str)
1547 (let ((foreground (face-foreground face)))
1549 (add-face-text-property
1551 `(:foreground ,foreground)
1556 (font-lock-append-text-property 0 (length str) 'face face str))))
1559 (declare-function flx-make-string-cache "ext:flx")
1560 (declare-function flx-score "ext:flx")
1562 (defvar ivy--flx-cache nil)
1564 (eval-after-load 'flx
1565 '(setq ivy--flx-cache (flx-make-string-cache)))
1567 (defun ivy-toggle-case-fold ()
1568 "Toggle the case folding between nil and auto.
1569 In any completion session, the case folding starts in auto:
1571 - when the input is all lower case, `case-fold-search' is t
1572 - otherwise it's nil.
1574 You can toggle this to make `case-fold-search' nil regardless of input."
1576 (setq ivy-case-fold-search
1577 (if ivy-case-fold-search
1580 ;; reset cache so that the candidate list updates
1581 (setq ivy--old-re nil))
1583 (defun ivy--filter (name candidates)
1584 "Return all items that match NAME in CANDIDATES.
1585 CANDIDATES are assumed to be static."
1586 (let ((re (funcall ivy--regex-function name)))
1587 (if (and (equal re ivy--old-re)
1589 ;; quick caching for "C-n", "C-p" etc.
1591 (let* ((re-str (if (listp re) (caar re) re))
1592 (matcher (ivy-state-matcher ivy-last))
1594 (and ivy-case-fold-search
1595 (string= name (downcase name))))
1598 (funcall matcher re candidates))
1601 (stringp ivy--old-re)
1602 (not (string-match "\\\\" ivy--old-re))
1603 (not (equal ivy--old-re ""))
1605 (if (string-match "\\\\)\\'" ivy--old-re)
1606 (substring ivy--old-re 0 -2)
1612 (lambda (x) (string-match re x))
1615 (let ((re-list (if (stringp re) (list (cons re t)) re))
1617 (dolist (re re-list)
1624 (let ((re-str (car re)))
1625 (lambda (x) (string-match re-str x)))
1628 (ivy--recompute-index name re-str cands)
1629 (setq ivy--old-re (if cands re-str ""))
1630 (when (and (require 'flx nil 'noerror)
1631 (eq ivy--regex-function 'ivy--regex-fuzzy))
1632 (setq cands (ivy--flx-sort name cands)))
1633 (setq ivy--old-cands cands)))))
1635 (defun ivy--recompute-index (name re-str cands)
1636 (let* ((caller (ivy-state-caller ivy-last))
1637 (func (or (and caller (cdr (assoc caller ivy-index-functions-alist)))
1638 (cdr (assoc t ivy-index-functions-alist))
1639 #'ivy-recompute-index-zero)))
1641 (or (and (not (string= name ""))
1642 (not (and (require 'flx nil 'noerror)
1643 (eq ivy--regex-function 'ivy--regex-fuzzy)
1644 (< (length cands) 200)))
1645 (cl-position (nth ivy--index ivy--old-cands)
1647 (funcall func re-str cands)))
1648 (when (and (or (string= name "")
1650 (not (equal ivy--old-re "")))
1652 (or (ivy--preselect-index
1655 (ivy-state-preselect ivy-last)
1659 (defun ivy-recompute-index-swiper (re-str cands)
1660 (let ((tail (nthcdr ivy--index ivy--old-cands))
1662 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
1663 (or (and (not (equal re-str ivy--old-re))
1665 (cl-position (if (and (> (length re-str) 0)
1666 (eq ?^ (aref re-str 0)))
1667 (substring re-str 1)
1672 (concat re-str "/") cands
1675 (while (and tail (null idx))
1676 ;; Compare with eq to handle equal duplicates in cands
1677 (setq idx (cl-position (pop tail) cands)))
1681 (defun ivy-recompute-index-zero (_re-str _cands)
1684 (defun ivy--flx-sort (name cands)
1685 "Sort according to closeness to string NAME the string list CANDS."
1688 (< (length cands) 200))
1689 (let* ((flx-name (if (string-match "^\\^" name)
1696 (let ((score (car (flx-score x flx-name ivy--flx-cache))))
1700 (if cands-with-score
1702 (sort cands-with-score
1704 (> (car x) (car y)))))
1710 (defvar ivy-format-function 'ivy-format-function-default
1711 "Function to transform the list of candidates into a string.
1712 This string will be inserted into the minibuffer.")
1714 (defun ivy-format-function-default (cands)
1715 "Transform CANDS into a string for minibuffer."
1716 (if (bound-and-true-p truncate-lines)
1717 (mapconcat #'identity cands "\n")
1718 (let ((ww (- (window-width)
1719 (if (and (boundp 'fringe-mode) (eq fringe-mode 0)) 1 0))))
1723 (if (> (length s) ww)
1724 (concat (substring s 0 (- ww 3)) "...")
1729 (defun ivy-format-function-arrow (cands)
1730 "Transform CANDS into a string for minibuffer."
1734 (concat (if (eq (cl-incf i) ivy--index)
1740 (defcustom swiper-minibuffer-faces
1741 '(swiper-minibuffer-match-face-1
1742 swiper-minibuffer-match-face-2
1743 swiper-minibuffer-match-face-3
1744 swiper-minibuffer-match-face-4)
1745 "List of `swiper' faces for minibuffer group matches.")
1747 (defun ivy--format-minibuffer-line (str)
1749 (str (copy-sequence str)))
1750 (when (eq ivy-display-style 'fancy)
1752 (setq ivy--old-re (funcall ivy--regex-function ivy-text)))
1753 (while (and (string-match ivy--old-re str start)
1754 (> (- (match-end 0) (match-beginning 0)) 0))
1755 (setq start (match-end 0))
1757 (while (<= i ivy--subexps)
1759 (cond ((zerop ivy--subexps)
1760 (cadr swiper-minibuffer-faces))
1762 (car swiper-minibuffer-faces))
1764 (nth (1+ (mod (+ i 2) (1- (length swiper-minibuffer-faces))))
1765 swiper-minibuffer-faces)))))
1766 (if (fboundp 'add-face-text-property)
1767 (add-face-text-property
1773 (font-lock-append-text-property
1782 (defun ivy--format (cands)
1783 "Return a string for CANDS suitable for display in the minibuffer.
1784 CANDS is a list of strings."
1785 (setq ivy--length (length cands))
1786 (when (>= ivy--index ivy--length)
1787 (setq ivy--index (max (1- ivy--length) 0)))
1789 (setq ivy--current "")
1790 (let* ((half-height (/ ivy-height 2))
1791 (start (max 0 (- ivy--index half-height)))
1792 (end (min (+ start (1- ivy-height)) ivy--length))
1793 (start (max 0 (min start (- end (1- ivy-height)))))
1794 (cands (cl-subseq cands start end))
1795 (index (- ivy--index start)))
1796 (when ivy--directory
1797 (setq cands (mapcar (lambda (x)
1798 (if (string-match-p "/\\'" x)
1799 (propertize x 'face 'ivy-subdir)
1802 (setq ivy--current (copy-sequence (nth index cands)))
1804 #'ivy--format-minibuffer-line
1806 (setf (nth index cands)
1807 (ivy--add-face (nth index cands) 'ivy-current-match))
1808 (let* ((ivy--index index)
1809 (res (concat "\n" (funcall ivy-format-function cands))))
1810 (put-text-property 0 (length res) 'read-only nil res)
1813 (defvar ivy--virtual-buffers nil
1814 "Store the virtual buffers alist.")
1816 (defvar recentf-list)
1818 (defface ivy-virtual '((t :inherit font-lock-builtin-face))
1819 "Face used by Ivy for matching virtual buffer names.")
1821 (defcustom ivy-virtual-abbreviate 'name
1822 "The mode of abbreviation for virtual buffer names."
1824 (const :tag "Only name" 'name)
1825 (const :tag "Full path" 'full)
1826 ;; eventually, uniquify
1829 (defun ivy--virtual-buffers ()
1830 "Adapted from `ido-add-virtual-buffers-to-list'."
1831 (unless recentf-mode
1833 (let ((bookmarks (and (boundp 'bookmark-alist)
1835 virtual-buffers name)
1836 (dolist (head (append
1838 (delete " - no file -"
1839 (delq nil (mapcar (lambda (bookmark)
1840 (cdr (assoc 'filename bookmark)))
1843 (if (eq ivy-virtual-abbreviate 'name)
1844 (file-name-nondirectory head)
1845 (expand-file-name head)))
1846 (when (equal name "")
1847 (setq name (file-name-nondirectory (directory-file-name head))))
1848 (when (equal name "")
1850 (and (not (equal name ""))
1851 (null (get-file-buffer head))
1852 (not (assoc name virtual-buffers))
1853 (push (cons name head) virtual-buffers)))
1854 (when virtual-buffers
1855 (dolist (comp virtual-buffers)
1856 (put-text-property 0 (length (car comp))
1859 (setq ivy--virtual-buffers (nreverse virtual-buffers))
1860 (mapcar #'car ivy--virtual-buffers))))
1862 (defun ivy--buffer-list (str &optional virtual)
1863 "Return the buffers that match STR.
1864 When VIRTUAL is non-nil, add virtual buffers."
1869 (if (with-current-buffer x
1871 (abbreviate-file-name default-directory)))
1872 (propertize x 'face 'ivy-remote)
1874 (all-completions str 'internal-complete-buffer))
1876 (ivy--virtual-buffers)))))
1878 (defun ivy--switch-buffer-action (buffer)
1880 BUFFER may be a string or nil."
1882 (if (zerop (length buffer))
1884 ivy-text nil 'force-same-window)
1885 (let ((virtual (assoc buffer ivy--virtual-buffers)))
1887 (not (get-buffer buffer)))
1888 (find-file (cdr virtual))
1890 buffer nil 'force-same-window))))))
1892 (defun ivy--switch-buffer-other-window-action (buffer)
1893 "Switch to BUFFER in other window.
1894 BUFFER may be a string or nil."
1895 (if (zerop (length buffer))
1896 (switch-to-buffer-other-window ivy-text)
1897 (let ((virtual (assoc buffer ivy--virtual-buffers)))
1899 (not (get-buffer buffer)))
1900 (find-file-other-window (cdr virtual))
1901 (switch-to-buffer-other-window buffer)))))
1903 (defun ivy--rename-buffer-action (buffer)
1905 (let ((new-name (read-string "Rename buffer (to new name): ")))
1906 (with-current-buffer buffer
1907 (rename-buffer new-name))))
1909 (defvar ivy-switch-buffer-map (make-sparse-keymap))
1916 (ivy--reset-state ivy-last))
1919 ivy--switch-buffer-other-window-action
1922 ivy--rename-buffer-action
1926 (defun ivy-switch-buffer ()
1927 "Switch to another buffer."
1930 (call-interactively 'switch-to-buffer)
1931 (let ((this-command 'ivy-switch-buffer))
1932 (ivy-read "Switch to buffer: " 'internal-complete-buffer
1933 :preselect (buffer-name (other-buffer (current-buffer)))
1934 :action #'ivy--switch-buffer-action
1935 :keymap ivy-switch-buffer-map))))
1938 (defun ivy-recentf ()
1939 "Find a file on `recentf-list'."
1941 (ivy-read "Recentf: " recentf-list
1947 (defun ivy-yank-word ()
1948 "Pull next word from buffer into search string."
1953 (le (line-end-position)))
1957 (setq amend (buffer-substring-no-properties pt (point))))))
1959 (insert (replace-regexp-in-string " +" " " amend)))))
1961 (defun ivy-kill-ring-save ()
1962 "Store the current candidates into the kill ring.
1963 If the region is active, forward to `kill-ring-save' instead."
1965 (if (region-active-p)
1966 (call-interactively 'kill-ring-save)
1973 (defun ivy-insert-current ()
1974 "Make the current candidate into current input.
1975 Don't finish completion."
1977 (delete-minibuffer-contents)
1978 (if (and ivy--directory
1979 (string-match "/$" ivy--current))
1980 (insert (substring ivy--current 0 -1))
1981 (insert ivy--current)))
1983 (defun ivy-toggle-fuzzy ()
1984 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
1986 (setq ivy--old-re nil)
1987 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
1988 (setq ivy--regex-function 'ivy--regex-plus)
1989 (setq ivy--regex-function 'ivy--regex-fuzzy)))
1991 (defun ivy-reverse-i-search ()
1992 "Enter a recursive `ivy-read' session using the current history.
1993 The selected history element will be inserted into the minibufer."
1995 (let ((enable-recursive-minibuffers t)
1996 (history (symbol-value (ivy-state-history ivy-last)))
1997 (old-last ivy-last))
1998 (ivy-read "Reverse-i-search: "
2002 (setq ivy-last old-last))
2003 (delete-minibuffer-contents)
2004 (insert (substring-no-properties x))
2007 (defun ivy-restrict-to-matches ()
2008 "Restrict candidates to current matches and erase input."
2010 (delete-minibuffer-contents)
2011 (setq ivy--all-candidates
2012 (ivy--filter ivy-text ivy--all-candidates)))
2016 ;;; ivy.el ends here