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 Info-current-file)
257 (defmacro ivy-quit-and-run (&rest body)
258 "Quit the minibuffer and run BODY afterwards."
260 (put 'quit 'error-message "")
263 (put 'quit 'error-message "Quit")
265 (minibuffer-keyboard-quit)))
267 (defmacro with-ivy-window (&rest body)
268 "Execute BODY in the window from which `ivy-read' was called."
271 `(with-selected-window (ivy-state-window ivy-last)
274 (defun ivy--done (text)
275 "Insert TEXT and exit minibuffer."
276 (if (and ivy--directory
277 (not (eq (ivy-state-history ivy-last) 'grep-files-history)))
278 (insert (setq ivy--current (expand-file-name
279 text ivy--directory)))
280 (insert (setq ivy--current text)))
281 (setq ivy-exit 'done)
286 "Exit the minibuffer with the selected candidate."
288 (delete-minibuffer-contents)
289 (cond ((> ivy--length 0)
290 (ivy--done ivy--current))
291 ((memq (ivy-state-collection ivy-last)
292 '(read-file-name-internal internal-complete-buffer))
293 (if (or (not (eq confirm-nonexistent-file-or-buffer t))
294 (equal " (confirm)" ivy--prompt-extra))
296 (setq ivy--prompt-extra " (confirm)")
299 ((memq (ivy-state-require-match ivy-last)
300 '(nil confirm confirm-after-completion))
301 (ivy--done ivy-text))
303 (setq ivy--prompt-extra " (match required)")
307 (defun ivy-read-action ()
308 "Change the action to one of the available ones."
310 (let ((actions (ivy-state-action ivy-last)))
311 (unless (null (ivy--actionp actions))
312 (let* ((hint (concat ivy--current
319 'face 'font-lock-builtin-face)
324 (key (string (read-key hint)))
325 (action-idx (cl-position-if
326 (lambda (x) (equal (car x) key))
328 (cond ((string= key "
\a"))
330 (error "%s is not bound" key))
333 (setcar actions (1+ action-idx))
334 (ivy-set-action actions)))))))
336 (defun ivy-dispatching-done ()
337 "Select one of the available actions and call `ivy-done'."
342 (defun ivy-dispatching-call ()
343 "Select one of the available actions and call `ivy-call'."
345 (let ((actions (copy-sequence (ivy-state-action ivy-last))))
348 (ivy-set-action actions)))
350 (defun ivy-build-tramp-name (x)
351 "Reconstruct X into a path.
352 Is is a cons cell, related to `tramp-get-completion-function'."
356 (concat user "@" domain)
359 (declare-function tramp-get-completion-function "tramp")
360 (declare-function Info-find-node "info")
362 (defun ivy-alt-done (&optional arg)
363 "Exit the minibuffer with the selected candidate.
364 When ARG is t, exit with current text, ignoring the candidates."
368 (ivy-immediate-done))
372 (not (string= ivy--current "./"))
373 (cl-plusp ivy--length)
375 (setq dir (expand-file-name
376 ivy--current ivy--directory))))))
379 ((eq (ivy-state-collection ivy-last) 'Info-read-node-name-1)
380 (if (or (equal ivy--current "(./)")
381 (equal ivy--current "(../)"))
383 (ivy-read "Go to file: " 'read-file-name-internal
386 (expand-file-name x ivy--directory)
390 (string-match "\\`/[^/]+:.*:.*\\'" ivy-text))
394 "\\`/\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
396 (let ((method (match-string 1 ivy-text))
397 (user (match-string 2 ivy-text))
398 (rest (match-string 3 ivy-text))
401 (dolist (x (tramp-get-completion-function method))
402 (setq res (append res (funcall (car x) (cadr x)))))
403 (setq res (delq nil res))
407 (setq res (cl-delete-duplicates res :test #'equal))
408 (let* ((old-ivy-last ivy-last)
409 (enable-recursive-minibuffers t)
410 (host (ivy-read "Find File: "
411 (mapcar #'ivy-build-tramp-name res)
412 :initial-input rest)))
413 (setq ivy-last old-ivy-last)
415 (setq ivy--directory "/")
416 (ivy--cd (concat "/" method ":" host ":"))))))
420 (defcustom ivy-tab-space nil
421 "When non-nil, `ivy-partial-or-done' should insert a space."
424 (defun ivy-partial-or-done ()
425 "Complete the minibuffer text as much as possible.
426 If the text hasn't changed as a result, forward to `ivy-alt-done'."
428 (if (and (eq (ivy-state-collection ivy-last) #'read-file-name-internal)
429 (string-match "\\`/" ivy-text))
430 (let ((default-directory ivy--directory))
431 (minibuffer-complete)
432 (setq ivy-text (ivy--input))
433 (when (and (file-directory-p ivy-text)
435 (ivy--cd (expand-file-name ivy-text))))
437 (when (or (eq this-command last-command)
441 (defun ivy-partial ()
442 "Complete the minibuffer text as much as possible."
444 (let* ((parts (or (split-string ivy-text " " t) (list "")))
445 (postfix (car (last parts)))
446 (completion-ignore-case t)
447 (startp (string-match "^\\^" postfix))
448 (new (try-completion (if startp
449 (substring postfix 1)
451 (mapcar (lambda (str) (substring str (string-match postfix str)))
453 (cond ((eq new t) nil)
454 ((string= new ivy-text) nil)
456 (delete-region (minibuffer-prompt-end) (point-max))
461 (insert (mapconcat #'identity parts " ")
462 (if ivy-tab-space " " ""))
465 (defun ivy-immediate-done ()
466 "Exit the minibuffer with the current input."
468 (delete-minibuffer-contents)
469 (insert (setq ivy--current ivy-text))
470 (setq ivy-exit 'done)
475 "Resume the last completion session."
478 (ivy-state-prompt ivy-last)
479 (ivy-state-collection ivy-last)
480 :predicate (ivy-state-predicate ivy-last)
481 :require-match (ivy-state-require-match ivy-last)
482 :initial-input ivy-text
483 :history (ivy-state-history ivy-last)
484 :preselect (unless (eq (ivy-state-collection ivy-last)
485 'read-file-name-internal)
487 :keymap (ivy-state-keymap ivy-last)
488 :update-fn (ivy-state-update-fn ivy-last)
489 :sort (ivy-state-sort ivy-last)
490 :action (ivy-state-action ivy-last)
491 :unwind (ivy-state-unwind ivy-last)
492 :re-builder (ivy-state-re-builder ivy-last)
493 :matcher (ivy-state-matcher ivy-last)
494 :dynamic-collection (ivy-state-dynamic-collection ivy-last)))
496 (defvar ivy-calling nil
497 "When non-nil, call the current action when `ivy--index' changes.")
499 (defun ivy-set-index (index)
500 "Set `ivy--index' to INDEX."
501 (setq ivy--index index)
506 (defun ivy-beginning-of-buffer ()
507 "Select the first completion candidate."
511 (defun ivy-end-of-buffer ()
512 "Select the last completion candidate."
514 (ivy-set-index (1- ivy--length)))
516 (defun ivy-scroll-up-command ()
517 "Scroll the candidates upward by the minibuffer height."
519 (ivy-set-index (min (+ ivy--index ivy-height)
522 (defun ivy-scroll-down-command ()
523 "Scroll the candidates downward by the minibuffer height."
525 (ivy-set-index (max (- ivy--index ivy-height)
528 (defun ivy-minibuffer-grow ()
529 "Grow the minibuffer window by 1 line."
531 (setq-local max-mini-window-height
532 (cl-incf ivy-height)))
534 (defun ivy-minibuffer-shrink ()
535 "Shrink the minibuffer window by 1 line."
537 (unless (<= ivy-height 2)
538 (setq-local max-mini-window-height
539 (cl-decf ivy-height))
540 (window-resize (selected-window) -1)))
542 (defun ivy-next-line (&optional arg)
543 "Move cursor vertically down ARG candidates."
545 (setq arg (or arg 1))
546 (let ((index (+ ivy--index arg)))
547 (if (> index (1- ivy--length))
549 (ivy-beginning-of-buffer)
550 (ivy-set-index (1- ivy--length)))
551 (ivy-set-index index))))
553 (defun ivy-next-line-or-history (&optional arg)
554 "Move cursor vertically down ARG candidates.
555 If the input is empty, select the previous history element instead."
557 (when (string= ivy-text "")
558 (ivy-previous-history-element 1))
561 (defun ivy-previous-line (&optional arg)
562 "Move cursor vertically up ARG candidates."
564 (setq arg (or arg 1))
565 (let ((index (- ivy--index arg)))
570 (ivy-set-index index))))
572 (defun ivy-previous-line-or-history (arg)
573 "Move cursor vertically up ARG candidates.
574 If the input is empty, select the previous history element instead."
576 (when (string= ivy-text "")
577 (ivy-previous-history-element 1))
578 (ivy-previous-line arg))
580 (defun ivy-toggle-calling ()
581 "Flip `ivy-calling'."
583 (when (setq ivy-calling (not ivy-calling))
586 (defun ivy--get-action (state)
587 "Get the action function from STATE."
588 (let ((action (ivy-state-action state)))
590 (if (functionp action)
592 (cadr (nth (car action) action))))))
594 (defun ivy--actionp (x)
595 "Return non-nil when X is a list of actions."
596 (and x (listp x) (not (eq (car x) 'closure))))
598 (defun ivy-next-action ()
599 "When the current action is a list, scroll it forwards."
601 (let ((action (ivy-state-action ivy-last)))
602 (when (ivy--actionp action)
603 (unless (>= (car action) (1- (length action)))
604 (cl-incf (car action))))))
606 (defun ivy-prev-action ()
607 "When the current action is a list, scroll it backwards."
609 (let ((action (ivy-state-action ivy-last)))
610 (when (ivy--actionp action)
611 (unless (<= (car action) 1)
612 (cl-decf (car action))))))
614 (defun ivy-action-name ()
615 "Return the name associated with the current action."
616 (let ((action (ivy-state-action ivy-last)))
617 (if (ivy--actionp action)
621 (nth 2 (nth (car action) action)))
625 "Call the current action without exiting completion."
627 (let ((action (ivy--get-action ivy-last)))
629 (let* ((collection (ivy-state-collection ivy-last))
630 (x (if (and (consp collection)
631 (consp (car collection)))
632 (cdr (assoc ivy--current collection))
633 (if (equal ivy--current "")
636 (prog1 (funcall action x)
637 (unless (or (eq ivy-exit 'done)
638 (equal (selected-window)
639 (active-minibuffer-window))
640 (null (active-minibuffer-window)))
641 (select-window (active-minibuffer-window))))))))
643 (defun ivy-next-line-and-call (&optional arg)
644 "Move cursor vertically down ARG candidates.
645 Call the permanent action if possible."
651 (defun ivy-previous-line-and-call (&optional arg)
652 "Move cursor vertically down ARG candidates.
653 Call the permanent action if possible."
655 (ivy-previous-line arg)
659 (defun ivy-previous-history-element (arg)
660 "Forward to `previous-history-element' with ARG."
662 (previous-history-element arg)
665 (ivy--maybe-scroll-history))
667 (defun ivy-next-history-element (arg)
668 "Forward to `next-history-element' with ARG."
670 (next-history-element arg)
673 (ivy--maybe-scroll-history))
675 (defun ivy--cd-maybe ()
676 "Check if the current input points to a different directory.
677 If so, move to that directory, while keeping only the file name."
679 (let* ((input (expand-file-name (ivy--input)))
680 (file (file-name-nondirectory input))
681 (dir (expand-file-name (file-name-directory input))))
682 (if (string= dir ivy--directory)
684 (delete-minibuffer-contents)
689 (defun ivy--maybe-scroll-history ()
690 "If the selected history element has an index, scroll there."
691 (let ((idx (ignore-errors
693 (minibuffer-prompt-end)
697 (setq ivy--index idx))))
700 "When completing file names, move to directory DIR."
701 (if (null ivy--directory)
703 (setq ivy--old-cands nil)
704 (setq ivy--old-re nil)
706 (setq ivy--all-candidates
707 (ivy--sorted-files (setq ivy--directory dir)))
709 (delete-minibuffer-contents)))
711 (defun ivy-backward-delete-char ()
712 "Forward to `backward-delete-char'.
713 On error (read-only), call `ivy-on-del-error-function'."
715 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
717 (ivy--cd (file-name-directory
723 (backward-delete-char 1)
725 (when ivy-on-del-error-function
726 (funcall ivy-on-del-error-function))))))
728 (defun ivy-delete-char (arg)
729 "Forward to `delete-char' ARG."
731 (unless (= (point) (line-end-position))
734 (defun ivy-forward-char (arg)
735 "Forward to `forward-char' ARG."
737 (unless (= (point) (line-end-position))
740 (defun ivy-kill-word (arg)
741 "Forward to `kill-word' ARG."
743 (unless (= (point) (line-end-position))
746 (defun ivy-kill-line ()
747 "Forward to `kill-line'."
750 (kill-region (minibuffer-prompt-end) (point))
753 (defun ivy-backward-kill-word ()
754 "Forward to `backward-kill-word'."
756 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
758 (ivy--cd (file-name-directory
766 (delete-region (point) pt)))))
768 (defvar ivy--regexp-quote 'regexp-quote
769 "Store the regexp quoting state.")
771 (defun ivy-toggle-regexp-quote ()
772 "Toggle the regexp quoting."
774 (setq ivy--old-re nil)
775 (cl-rotatef ivy--regex-function ivy--regexp-quote))
777 (defvar avy-all-windows)
780 (defvar avy-keys-alist)
782 (defvar avy-styles-alist)
783 (declare-function avy--process "ext:avy")
784 (declare-function avy--style-fn "ext:avy")
786 (eval-after-load 'avy
787 '(add-to-list 'avy-styles-alist '(ivy-avy . pre)))
790 "Jump to one of the current ivy candidates."
792 (unless (require 'avy nil 'noerror)
793 (error "Package avy isn't installed"))
794 (let* ((avy-all-windows nil)
795 (avy-keys (or (cdr (assq 'ivy-avy avy-keys-alist))
797 (avy-style (or (cdr (assq 'ivy-avy
807 (goto-char (point-min))
809 (while (< (point) (point-max))
815 (setq avy-action #'identity)
817 (nreverse candidates)
818 (avy--style-fn avy-style)))))
819 (ivy-set-index (- (line-number-at-pos candidate) 2))
823 (defun ivy-sort-file-function-default (x y)
824 "Compare two files X and Y.
825 Prioritize directories."
826 (if (get-text-property 0 'dirp x)
827 (if (get-text-property 0 'dirp y)
830 (if (get-text-property 0 'dirp y)
834 (defvar ivy-sort-functions-alist
835 '((read-file-name-internal . ivy-sort-file-function-default)
836 (internal-complete-buffer . nil)
837 (counsel-git-grep-function . nil)
838 (Man-goto-section . nil)
841 "An alist of sorting functions for each collection function.
842 Interactive functions that call completion fit in here as well.
844 For each entry, nil means no sorting. It's very useful to turn
845 off the sorting for functions that have candidates in the natural
846 buffer order, like `org-refile' or `Man-goto-section'.
848 The entry associated to t is used for all fall-through cases.")
850 (defvar ivy-index-functions-alist
851 '((swiper . ivy-recompute-index-swiper)
852 (swiper-multi . ivy-recompute-index-swiper)
853 (counsel-git-grep . ivy-recompute-index-swiper)
854 (t . ivy-recompute-index-zero))
855 "An alist of index recomputing functions for each collection function.
856 When the input changes, calling the appropriate function will
857 return an integer - the index of the matched candidate that
858 should be selected.")
860 (defvar ivy-re-builders-alist
861 '((t . ivy--regex-plus))
862 "An alist of regex building functions for each collection function.
863 Each function should take a string and return a valid regex or a
864 regex sequence (see below).
866 The entry associated to t is used for all fall-through cases.
867 Possible choices: `ivy--regex', `regexp-quote', `ivy--regex-plus'.
869 In case a function returns a list, it should look like this:
870 '((\"matching-regexp\" . t) (\"non-matching-regexp\") ...).
872 The matches will be filtered in a sequence, you can mix the
873 regexps that should match and that should not match as you
876 (defvar ivy-initial-inputs-alist
878 (org-agenda-refile . "^")
879 (org-capture-refile . "^")
881 (counsel-describe-function . "^")
882 (counsel-describe-variable . "^")
885 "Command to initial input table.")
887 (defcustom ivy-sort-max-size 30000
888 "Sorting won't be done for collections larger than this."
891 (defun ivy--sorted-files (dir)
892 "Return the list of files in DIR.
893 Directories come first."
894 (let* ((default-directory dir)
895 (seq (all-completions "" 'read-file-name-internal))
899 (setq seq (delete "./" (delete "../" seq)))
900 (when (eq (setq sort-fn (cdr (assoc 'read-file-name-internal
901 ivy-sort-functions-alist)))
902 #'ivy-sort-file-function-default)
903 (setq seq (mapcar (lambda (x)
904 (propertize x 'dirp (string-match-p "/\\'" x)))
907 (setq seq (cl-sort seq sort-fn)))
908 (dolist (dir ivy-extra-directories)
913 (cl-defun ivy-read (prompt collection
914 &key predicate require-match initial-input
915 history preselect keymap update-fn sort
916 action unwind re-builder matcher dynamic-collection caller)
917 "Read a string in the minibuffer, with completion.
919 PROMPT is a string to prompt with; normally it ends in a colon
920 and a space. When PROMPT contains %d, it will be updated with
921 the current number of matching candidates. If % appears elsewhere
922 in the PROMPT it should be quoted as %%.
923 See also `ivy-count-format'.
925 COLLECTION is a list of strings, or a function, or an alist, or a
928 If INITIAL-INPUT is non-nil, insert it in the minibuffer initially.
930 KEYMAP is composed together with `ivy-minibuffer-map'.
932 If PRESELECT is non-nil select the corresponding candidate out of
933 the ones that match INITIAL-INPUT.
935 UPDATE-FN is called each time the current candidate(s) is changed.
937 When SORT is t, refer to `ivy-sort-functions-alist' for sorting.
939 ACTION is a lambda to call after a result was selected. It should
940 take a single argument, usually a string.
942 UNWIND is a lambda to call before exiting.
944 RE-BUILDER is a lambda that transforms text into a regex.
946 MATCHER can completely override matching.
948 DYNAMIC-COLLECTION is a function to call to update the list of
949 candidates with each input.
951 CALLER is a symbol to uniquely identify the caller to `ivy-read'.
952 It's used in conjunction with COLLECTION to indentify which
953 customizations should apply to the current completion session."
954 (let ((extra-actions (plist-get ivy--actions-list this-command)))
957 (if (functionp action)
959 ("o" ,action "default")
961 (delete-dups (append action extra-actions))))))
965 :collection collection
967 :require-match require-match
968 :initial-input initial-input
975 :window (selected-window)
977 :re-builder re-builder
979 :dynamic-collection dynamic-collection
981 (ivy--reset-state ivy-last)
984 (minibuffer-with-setup-hook
985 #'ivy--minibuffer-setup
986 (let* ((hist (or history 'ivy-history))
987 (minibuffer-completion-table collection)
988 (minibuffer-completion-predicate predicate)
989 (resize-mini-windows (cond
990 ((display-graphic-p) nil)
991 ((null resize-mini-windows) 'grow-only)
992 (t resize-mini-windows)))
993 (res (read-from-minibuffer
995 (ivy-state-initial-input ivy-last)
996 (make-composed-keymap keymap ivy-minibuffer-map)
999 (when (eq ivy-exit 'done)
1000 (let ((item (if ivy--directory
1003 (unless (equal item "")
1004 (set hist (cons (propertize item 'ivy-index ivy--index)
1006 (cdr (symbol-value hist)))))))
1008 (remove-hook 'post-command-hook #'ivy--exhibit)
1009 (when (setq unwind (ivy-state-unwind ivy-last))
1013 (defun ivy--reset-state (state)
1014 "Reset the ivy to STATE.
1015 This is useful for recursive `ivy-read'."
1016 (let ((prompt (ivy-state-prompt state))
1017 (collection (ivy-state-collection state))
1018 (predicate (ivy-state-predicate state))
1019 (history (ivy-state-history state))
1020 (preselect (ivy-state-preselect state))
1021 (sort (ivy-state-sort state))
1022 (re-builder (ivy-state-re-builder state))
1023 (dynamic-collection (ivy-state-dynamic-collection state))
1024 (initial-input (ivy-state-initial-input state))
1025 (require-match (ivy-state-require-match state))
1026 (matcher (ivy-state-matcher state)))
1027 (unless initial-input
1028 (setq initial-input (cdr (assoc this-command
1029 ivy-initial-inputs-alist))))
1030 (setq ivy--directory nil)
1031 (setq ivy--regex-function
1033 (and (functionp collection)
1034 (cdr (assoc collection ivy-re-builders-alist)))
1035 (cdr (assoc t ivy-re-builders-alist))
1037 (setq ivy--subexps 0)
1038 (setq ivy--regexp-quote 'regexp-quote)
1039 (setq ivy--old-text "")
1040 (setq ivy--full-length nil)
1042 (setq ivy-calling nil)
1044 (cond ((eq collection 'Info-read-node-name-1)
1045 (if (equal Info-current-file "dir")
1047 (mapcar (lambda (x) (format "(%s)" x))
1048 (cl-delete-duplicates
1049 (all-completions "(" collection predicate)
1051 (setq coll (all-completions "" collection predicate))))
1052 ((eq collection 'read-file-name-internal)
1053 (setq ivy--directory default-directory)
1056 (let ((preselect-directory (file-name-directory preselect)))
1057 (unless (or (null preselect-directory)
1058 (string= preselect-directory
1060 (setq ivy--directory preselect-directory))
1062 (ivy-state-preselect state)
1063 (setq preselect (file-name-nondirectory preselect)))))
1064 (setq coll (ivy--sorted-files ivy--directory))
1066 (unless (or require-match
1067 (equal initial-input default-directory)
1068 (equal initial-input ""))
1069 (setq coll (cons initial-input coll)))
1070 (setq initial-input nil)))
1071 ((eq collection 'internal-complete-buffer)
1072 (setq coll (ivy--buffer-list "" ivy-use-virtual-buffers)))
1073 ((or (functionp collection)
1074 (byte-code-function-p collection)
1075 (vectorp collection)
1076 (and (consp collection) (listp (car collection)))
1077 (hash-table-p collection))
1078 (setq coll (all-completions "" collection predicate)))
1080 (setq coll collection)))
1082 (if (and (functionp collection)
1083 (setq sort-fn (assoc collection ivy-sort-functions-alist)))
1084 (when (and (setq sort-fn (cdr sort-fn))
1085 (not (eq collection 'read-file-name-internal)))
1086 (setq coll (cl-sort coll sort-fn)))
1087 (unless (eq history 'org-refile-history)
1088 (if (and (setq sort-fn (cdr (assoc t ivy-sort-functions-alist)))
1089 (<= (length coll) ivy-sort-max-size))
1090 (setq coll (cl-sort (copy-sequence coll) sort-fn))))))
1092 (unless (or (and require-match
1093 (not (eq collection 'internal-complete-buffer)))
1094 (let ((re (regexp-quote preselect)))
1095 (cl-find-if (lambda (x) (string-match re x))
1097 (setq coll (cons preselect coll))))
1098 (setq ivy--index (or
1099 (and dynamic-collection
1102 (ivy--preselect-index
1103 coll initial-input preselect matcher))
1105 (setq ivy--old-re nil)
1106 (setq ivy--old-cands nil)
1107 (setq ivy--all-candidates coll))
1109 (setq ivy--default (or (thing-at-point 'symbol) ""))
1111 (cond ((string-match "%.*d" prompt)
1113 ((null ivy-count-format)
1115 "`ivy-count-format' can't be nil. Set it to an empty string instead."))
1116 ((string-match "%d.*%d" ivy-count-format)
1117 (let ((w (length (number-to-string
1118 (length ivy--all-candidates))))
1119 (s (copy-sequence ivy-count-format)))
1120 (string-match "%d" s)
1122 (string-match "%d" s (match-end 0))
1123 (setq s (replace-match (format "%%-%dd" w) nil nil s))
1124 (string-match "%d" s)
1125 (concat (replace-match (format "%%%dd" w) nil nil s)
1127 ((string-match "%.*d" ivy-count-format)
1128 (concat ivy-count-format prompt))
1133 (setf (ivy-state-initial-input ivy-last) initial-input)))
1136 (defun ivy-completing-read (prompt collection
1137 &optional predicate require-match initial-input
1138 history def _inherit-input-method)
1139 "Read a string in the minibuffer, with completion.
1141 This is an interface that conforms to `completing-read', so that
1142 it can be used for `completing-read-function'.
1144 PROMPT is a string to prompt with; normally it ends in a colon and a space.
1145 COLLECTION can be a list of strings, an alist, an obarray or a hash table.
1146 PREDICATE limits completion to a subset of COLLECTION.
1147 REQUIRE-MATCH is considered boolean. See `completing-read'.
1148 INITIAL-INPUT is a string that can be inserted into the minibuffer initially.
1149 _HISTORY is ignored for now.
1150 DEF is the default value.
1151 _INHERIT-INPUT-METHOD is ignored for now.
1153 The history, defaults and input-method arguments are ignored for now."
1154 (ivy-read (replace-regexp-in-string "%" "%%" prompt)
1156 :predicate predicate
1157 :require-match require-match
1158 :initial-input (if (consp initial-input)
1160 (if (and (stringp initial-input)
1161 (string-match "\\+" initial-input))
1162 (replace-regexp-in-string
1163 "\\+" "\\\\+" initial-input)
1165 :preselect (if (listp def) (car def) def)
1169 (let ((sort (assoc this-command ivy-sort-functions-alist)))
1175 (define-minor-mode ivy-mode
1176 "Toggle Ivy mode on or off.
1177 With ARG, turn Ivy mode on if arg is positive, off otherwise.
1178 Turning on Ivy mode will set `completing-read-function' to
1179 `ivy-completing-read'.
1184 Minibuffer bindings:
1185 \\{ivy-minibuffer-map}"
1188 :keymap ivy-mode-map
1191 (setq completing-read-function 'ivy-completing-read)
1192 (setq completing-read-function 'completing-read-default)))
1194 (defun ivy--preselect-index (candidates initial-input preselect matcher)
1195 "Return the index in CANDIDATES filtered by INITIAL-INPUT for PRESELECT.
1196 When MATCHER is non-nil it's used instead of `cl-remove-if-not'."
1199 (setq initial-input (ivy--regex-plus initial-input))
1202 (funcall matcher initial-input candidates)
1205 (string-match initial-input x))
1208 (setq candidates (funcall matcher "" candidates))))
1209 (or (cl-position preselect candidates :test #'equal)
1210 (and (stringp preselect)
1211 (let ((re (regexp-quote preselect)))
1214 (string-match re x))
1219 (defvar ivy--regex-hash
1220 (make-hash-table :test #'equal)
1221 "Store pre-computed regex.")
1223 (defun ivy--split (str)
1224 "Split STR into a list by single spaces.
1225 The remaining spaces stick to their left.
1226 This allows to \"quote\" N spaces by inputting N+1 spaces."
1227 (let ((len (length str))
1232 (while (and (string-match " +" str start1)
1234 (setq match-len (- (match-end 0) (match-beginning 0)))
1238 (setq start1 start0)
1240 (push (substring str start1 (match-beginning 0)) res)
1241 (setq start1 (match-end 0)))
1242 (setq str (replace-match
1243 (make-string (1- match-len) ?\ )
1245 (setq start0 (or start0 start1))
1246 (setq start1 (1- (match-end 0)))))
1248 (push (substring str start0) res)
1249 (setq s (substring str start1))
1250 (unless (= (length s) 0)
1254 (defun ivy--regex (str &optional greedy)
1255 "Re-build regex from STR in case it has a space.
1256 When GREEDY is non-nil, join words in a greedy way."
1257 (let ((hashed (unless greedy
1258 (gethash str ivy--regex-hash))))
1261 (setq ivy--subexps (car hashed)))
1262 (when (string-match "\\([^\\]\\|^\\)\\\\$" str)
1263 (setq str (substring str 0 -1)))
1265 (let ((subs (ivy--split str)))
1266 (if (= (length subs) 1)
1268 (setq ivy--subexps 0)
1271 (setq ivy--subexps (length subs))
1274 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1276 (format "\\(%s\\)" x)))
1281 ivy--regex-hash)))))
1283 (defun ivy--regex-ignore-order (str)
1284 "Re-build regex from STR by splitting it on spaces.
1285 Ignore the order of each group."
1286 (let* ((subs (split-string str " +" t))
1287 (len (length subs)))
1290 (setq ivy--subexps 0)
1293 (setq ivy--subexps len)
1294 (let ((all (mapconcat #'identity subs "\\|")))
1297 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1299 (format "\\(%s\\)" x)))
1303 (defun ivy--regex-plus (str)
1304 "Build a regex sequence from STR.
1305 Spaces are wild, everything before \"!\" should match.
1306 Everything after \"!\" should not match."
1307 (let ((parts (split-string str "!" t)))
1308 (cl-case (length parts)
1312 (ivy--regex (car parts)))
1316 (split-string (cadr parts) " " t))))
1317 (cons (cons (ivy--regex (car parts)) t)
1319 (t (error "Unexpected: use only one !")))))
1321 (defun ivy--regex-fuzzy (str)
1322 "Build a regex sequence from STR.
1323 Insert .* between each char."
1324 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1326 (concat (match-string 1 str)
1329 (format "\\(%c\\)" x))
1330 (string-to-list (match-string 2 str)) ".*")
1331 (match-string 3 str))
1332 (setq ivy--subexps (length (match-string 2 str))))
1336 (defun ivy--minibuffer-setup ()
1337 "Setup ivy completion in the minibuffer."
1338 (set (make-local-variable 'completion-show-inline-help) nil)
1339 (set (make-local-variable 'minibuffer-default-add-function)
1341 (list ivy--default)))
1342 (when (display-graphic-p)
1343 (setq truncate-lines t))
1344 (setq-local max-mini-window-height ivy-height)
1345 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1346 ;; show completions with empty input
1349 (defun ivy--input ()
1350 "Return the current minibuffer input."
1351 ;; assume one-line minibuffer input
1352 (buffer-substring-no-properties
1353 (minibuffer-prompt-end)
1354 (line-end-position)))
1356 (defun ivy--cleanup ()
1357 "Delete the displayed completion candidates."
1359 (goto-char (minibuffer-prompt-end))
1360 (delete-region (line-end-position) (point-max))))
1362 (defun ivy--insert-prompt ()
1363 "Update the prompt according to `ivy--prompt'."
1365 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1366 counsel-find-symbol))
1367 (setq ivy--prompt-extra ""))
1369 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1371 (setq head (match-string 1 ivy--prompt))
1373 (setq head (substring ivy--prompt 0 -1))
1375 (let ((inhibit-read-only t)
1376 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1379 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1380 (> (minibuffer-depth) 1))
1381 (format "[%d] " (minibuffer-depth))
1384 (if (string-match "%d.*%d" ivy-count-format)
1387 (or (and (ivy-state-dynamic-collection ivy-last)
1391 (or (and (ivy-state-dynamic-collection ivy-last)
1396 (d-str (if ivy--directory
1397 (abbreviate-file-name ivy--directory)
1400 (goto-char (point-min))
1401 (delete-region (point-min) (minibuffer-prompt-end))
1402 (if (> (+ (mod (+ (length n-str) (length d-str)) (window-width))
1405 (setq n-str (concat n-str "\n" d-str))
1406 (setq n-str (concat n-str d-str)))
1407 (let ((regex (format "\\([^\n]\\{%d\\}\\)[^\n]" (window-width))))
1408 (while (string-match regex n-str)
1409 (setq n-str (replace-match (concat (match-string 1 n-str) "\n") nil t n-str 1))))
1410 (set-text-properties 0 (length n-str)
1411 `(face minibuffer-prompt ,@std-props)
1413 (ivy--set-match-props n-str "confirm"
1414 `(face ivy-confirm-face ,@std-props))
1415 (ivy--set-match-props n-str "match required"
1416 `(face ivy-match-required-face ,@std-props))
1418 ;; get out of the prompt area
1419 (constrain-to-field nil (point-max))))))
1421 (defun ivy--set-match-props (str match props)
1422 "Set STR text proprties that match MATCH to PROPS."
1423 (when (string-match match str)
1424 (set-text-properties
1430 (defvar inhibit-message)
1432 (defun ivy--sort-maybe (collection)
1433 "Sort COLLECTION if needed."
1434 (let ((sort (ivy-state-sort ivy-last))
1438 (let ((sort-fn (cond ((functionp sort)
1440 ((setq entry (assoc (ivy-state-collection ivy-last)
1441 ivy-sort-functions-alist))
1444 (cdr (assoc t ivy-sort-functions-alist))))))
1445 (if (functionp sort-fn)
1446 (cl-sort (copy-sequence collection) sort-fn)
1449 (defun ivy--exhibit ()
1450 "Insert Ivy completions display.
1451 Should be run via minibuffer `post-command-hook'."
1452 (when (memq 'ivy--exhibit post-command-hook)
1453 (setq ivy-text (ivy--input))
1454 (if (ivy-state-dynamic-collection ivy-last)
1455 ;; while-no-input would cause annoying
1456 ;; "Waiting for process to die...done" message interruptions
1457 (let ((inhibit-message t))
1458 (unless (equal ivy--old-text ivy-text)
1460 (setq ivy--all-candidates
1462 (funcall (ivy-state-collection ivy-last) ivy-text)))
1463 (setq ivy--old-text ivy-text)))
1464 (when ivy--all-candidates
1465 (ivy--insert-minibuffer
1466 (ivy--format ivy--all-candidates))))
1467 (cond (ivy--directory
1468 (if (string-match "/\\'" ivy-text)
1469 (if (member ivy-text ivy--all-candidates)
1470 (ivy--cd (expand-file-name ivy-text ivy--directory))
1471 (when (string-match "//\\'" ivy-text)
1472 (if (and default-directory
1473 (string-match "\\`[[:alpha:]]:/" default-directory))
1474 (ivy--cd (match-string 0 default-directory))
1476 (when (string-match "[[:alpha:]]:/" ivy-text)
1477 (let ((drive-root (match-string 0 ivy-text)))
1478 (when (file-exists-p drive-root)
1479 (ivy--cd drive-root)))))
1480 (if (string-match "\\`~\\'" ivy-text)
1481 (ivy--cd (expand-file-name "~/")))))
1482 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1483 (when (or (and (string-match "\\` " ivy-text)
1484 (not (string-match "\\` " ivy--old-text)))
1485 (and (string-match "\\` " ivy--old-text)
1486 (not (string-match "\\` " ivy-text))))
1487 (setq ivy--all-candidates
1488 (if (and (> (length ivy-text) 0)
1489 (eq (aref ivy-text 0)
1491 (ivy--buffer-list " ")
1492 (ivy--buffer-list "" ivy-use-virtual-buffers)))
1493 (setq ivy--old-re nil))))
1494 (ivy--insert-minibuffer
1496 (ivy--filter ivy-text ivy--all-candidates)))
1497 (setq ivy--old-text ivy-text))))
1499 (defun ivy--insert-minibuffer (text)
1500 "Insert TEXT into minibuffer with appropriate cleanup."
1501 (let ((resize-mini-windows nil)
1502 (update-fn (ivy-state-update-fn ivy-last))
1506 (funcall update-fn))
1507 (ivy--insert-prompt)
1508 ;; Do nothing if while-no-input was aborted.
1509 (when (stringp text)
1510 (let ((buffer-undo-list t))
1514 (when (display-graphic-p)
1515 (ivy--resize-minibuffer-to-fit))))
1517 (defun ivy--resize-minibuffer-to-fit ()
1518 "Resize the minibuffer window so it has enough space to display
1519 all of the text contained in the minibuffer."
1520 (with-selected-window (minibuffer-window)
1521 (if (fboundp 'window-text-pixel-size)
1522 (let ((text-height (cdr (window-text-pixel-size)))
1523 (body-height (window-body-height nil t)))
1524 (when (> text-height body-height)
1525 (window-resize nil (- text-height body-height) nil t t)))
1526 (let ((text-height (count-screen-lines))
1527 (body-height (window-body-height)))
1528 (when (> text-height body-height)
1529 (window-resize nil (- text-height body-height) nil t))))))
1531 (declare-function colir-blend-face-background "ext:colir")
1533 (defun ivy--add-face (str face)
1534 "Propertize STR with FACE.
1535 `font-lock-append-text-property' is used, since it's better than
1536 `propertize' or `add-face-text-property' in this case."
1540 (colir-blend-face-background 0 (length str) face str)
1541 (let ((foreground (face-foreground face)))
1543 (add-face-text-property
1545 `(:foreground ,foreground)
1550 (font-lock-append-text-property 0 (length str) 'face face str))))
1553 (declare-function flx-make-string-cache "ext:flx")
1554 (declare-function flx-score "ext:flx")
1556 (defvar ivy--flx-cache nil)
1558 (eval-after-load 'flx
1559 '(setq ivy--flx-cache (flx-make-string-cache)))
1561 (defun ivy--filter (name candidates)
1562 "Return all items that match NAME in CANDIDATES.
1563 CANDIDATES are assumed to be static."
1564 (let ((re (funcall ivy--regex-function name)))
1565 (if (and (equal re ivy--old-re)
1567 ;; quick caching for "C-n", "C-p" etc.
1569 (let* ((re-str (if (listp re) (caar re) re))
1570 (matcher (ivy-state-matcher ivy-last))
1571 (case-fold-search (string= name (downcase name)))
1574 (funcall matcher re candidates))
1577 (stringp ivy--old-re)
1578 (not (string-match "\\\\" ivy--old-re))
1579 (not (equal ivy--old-re ""))
1581 (if (string-match "\\\\)\\'" ivy--old-re)
1582 (substring ivy--old-re 0 -2)
1588 (lambda (x) (string-match re x))
1591 (let ((re-list (if (stringp re) (list (cons re t)) re))
1593 (dolist (re re-list)
1600 (let ((re-str (car re)))
1601 (lambda (x) (string-match re-str x)))
1604 (ivy--recompute-index name re-str cands)
1605 (setq ivy--old-re (if cands re-str ""))
1606 (when (and (require 'flx nil 'noerror)
1607 (eq ivy--regex-function 'ivy--regex-fuzzy))
1608 (setq cands (ivy--flx-sort name cands)))
1609 (setq ivy--old-cands cands)))))
1611 (defun ivy--recompute-index (name re-str cands)
1612 (let* ((caller (ivy-state-caller ivy-last))
1613 (func (or (and caller (cdr (assoc caller ivy-index-functions-alist)))
1614 (cdr (assoc t ivy-index-functions-alist))
1615 #'ivy-recompute-index-zero)))
1617 (or (and (not (string= name ""))
1618 (cl-position (nth ivy--index ivy--old-cands)
1620 (funcall func re-str cands)))
1621 (when (and (or (string= name "")
1623 (not (equal ivy--old-re "")))
1625 (or (ivy--preselect-index
1628 (ivy-state-preselect ivy-last)
1632 (defun ivy-recompute-index-swiper (re-str cands)
1633 (let ((tail (nthcdr ivy--index ivy--old-cands))
1635 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
1636 (or (and (not (equal re-str ivy--old-re))
1638 (cl-position (if (and (> (length re-str) 0)
1639 (eq ?^ (aref re-str 0)))
1640 (substring re-str 1)
1645 (concat re-str "/") cands
1648 (while (and tail (null idx))
1649 ;; Compare with eq to handle equal duplicates in cands
1650 (setq idx (cl-position (pop tail) cands)))
1654 (defun ivy-recompute-index-zero (_re-str _cands)
1657 (defun ivy--flx-sort (name cands)
1658 "Sort according to closeness to string NAME the string list CANDS."
1661 (< (length cands) 200))
1662 (let* ((flx-name (if (string-match "^\\^" name)
1669 (let ((score (car (flx-score x flx-name ivy--flx-cache))))
1673 (if cands-with-score
1675 (sort cands-with-score
1677 (> (car x) (car y)))))
1683 (defvar ivy-format-function 'ivy-format-function-default
1684 "Function to transform the list of candidates into a string.
1685 This string will be inserted into the minibuffer.")
1687 (defun ivy-format-function-default (cands)
1688 "Transform CANDS into a string for minibuffer."
1689 (if (bound-and-true-p truncate-lines)
1690 (mapconcat #'identity cands "\n")
1691 (let ((ww (- (window-width)
1692 (if (and (boundp 'fringe-mode) (eq fringe-mode 0)) 1 0))))
1696 (if (> (length s) ww)
1697 (concat (substring s 0 (- ww 3)) "...")
1702 (defun ivy-format-function-arrow (cands)
1703 "Transform CANDS into a string for minibuffer."
1707 (concat (if (eq (cl-incf i) ivy--index)
1713 (defcustom swiper-minibuffer-faces
1714 '(swiper-minibuffer-match-face-1
1715 swiper-minibuffer-match-face-2
1716 swiper-minibuffer-match-face-3
1717 swiper-minibuffer-match-face-4)
1718 "List of `swiper' faces for minibuffer group matches.")
1720 (defun ivy--format-minibuffer-line (str)
1722 (str (copy-sequence str)))
1723 (when (eq ivy-display-style 'fancy)
1725 (setq ivy--old-re (funcall ivy--regex-function ivy-text)))
1726 (while (and (string-match ivy--old-re str start)
1727 (> (- (match-end 0) (match-beginning 0)) 0))
1728 (setq start (match-end 0))
1730 (while (<= i ivy--subexps)
1732 (cond ((zerop ivy--subexps)
1733 (cadr swiper-minibuffer-faces))
1735 (car swiper-minibuffer-faces))
1737 (nth (1+ (mod (+ i 2) (1- (length swiper-minibuffer-faces))))
1738 swiper-minibuffer-faces)))))
1739 (if (fboundp 'add-face-text-property)
1740 (add-face-text-property
1746 (font-lock-append-text-property
1755 (defun ivy--format (cands)
1756 "Return a string for CANDS suitable for display in the minibuffer.
1757 CANDS is a list of strings."
1758 (setq ivy--length (length cands))
1759 (when (>= ivy--index ivy--length)
1760 (setq ivy--index (max (1- ivy--length) 0)))
1762 (setq ivy--current "")
1763 (let* ((half-height (/ ivy-height 2))
1764 (start (max 0 (- ivy--index half-height)))
1765 (end (min (+ start (1- ivy-height)) ivy--length))
1766 (start (max 0 (min start (- end (1- ivy-height)))))
1767 (cands (cl-subseq cands start end))
1768 (index (- ivy--index start)))
1769 (when ivy--directory
1770 (setq cands (mapcar (lambda (x)
1771 (if (string-match-p "/\\'" x)
1772 (propertize x 'face 'ivy-subdir)
1775 (setq ivy--current (copy-sequence (nth index cands)))
1777 #'ivy--format-minibuffer-line
1779 (setf (nth index cands)
1780 (ivy--add-face (nth index cands) 'ivy-current-match))
1781 (let* ((ivy--index index)
1782 (res (concat "\n" (funcall ivy-format-function cands))))
1783 (put-text-property 0 (length res) 'read-only nil res)
1786 (defvar ivy--virtual-buffers nil
1787 "Store the virtual buffers alist.")
1789 (defvar recentf-list)
1791 (defface ivy-virtual '((t :inherit font-lock-builtin-face))
1792 "Face used by Ivy for matching virtual buffer names.")
1794 (defcustom ivy-virtual-abbreviate 'name
1795 "The mode of abbreviation for virtual buffer names."
1797 (const :tag "Only name" 'name)
1798 (const :tag "Full path" 'full)
1799 ;; eventually, uniquify
1802 (defun ivy--virtual-buffers ()
1803 "Adapted from `ido-add-virtual-buffers-to-list'."
1804 (unless recentf-mode
1806 (let ((bookmarks (and (boundp 'bookmark-alist)
1808 virtual-buffers name)
1809 (dolist (head (append
1811 (delete " - no file -"
1812 (delq nil (mapcar (lambda (bookmark)
1813 (cdr (assoc 'filename bookmark)))
1816 (if (eq ivy-virtual-abbreviate 'name)
1817 (file-name-nondirectory head)
1818 (expand-file-name head)))
1819 (when (equal name "")
1820 (setq name (file-name-nondirectory (directory-file-name head))))
1821 (when (equal name "")
1823 (and (not (equal name ""))
1824 (null (get-file-buffer head))
1825 (not (assoc name virtual-buffers))
1826 (push (cons name head) virtual-buffers)))
1827 (when virtual-buffers
1828 (dolist (comp virtual-buffers)
1829 (put-text-property 0 (length (car comp))
1832 (setq ivy--virtual-buffers (nreverse virtual-buffers))
1833 (mapcar #'car ivy--virtual-buffers))))
1835 (defun ivy--buffer-list (str &optional virtual)
1836 "Return the buffers that match STR.
1837 When VIRTUAL is non-nil, add virtual buffers."
1842 (if (with-current-buffer x
1844 (abbreviate-file-name default-directory)))
1845 (propertize x 'face 'ivy-remote)
1847 (all-completions str 'internal-complete-buffer))
1849 (ivy--virtual-buffers)))))
1851 (defun ivy--switch-buffer-action (buffer)
1853 BUFFER may be a string or nil."
1855 (if (zerop (length buffer))
1857 ivy-text nil 'force-same-window)
1858 (let ((virtual (assoc buffer ivy--virtual-buffers)))
1860 (not (get-buffer buffer)))
1861 (find-file (cdr virtual))
1863 buffer nil 'force-same-window))))))
1865 (defun ivy--switch-buffer-other-window-action (buffer)
1866 "Switch to BUFFER in other window.
1867 BUFFER may be a string or nil."
1868 (if (zerop (length buffer))
1869 (switch-to-buffer-other-window ivy-text)
1870 (let ((virtual (assoc buffer ivy--virtual-buffers)))
1872 (not (get-buffer buffer)))
1873 (find-file-other-window (cdr virtual))
1874 (switch-to-buffer-other-window buffer)))))
1876 (defun ivy--rename-buffer-action (buffer)
1878 (let ((new-name (read-string "Rename buffer (to new name): ")))
1879 (with-current-buffer buffer
1880 (rename-buffer new-name))))
1882 (defvar ivy-switch-buffer-map (make-sparse-keymap))
1889 (ivy--reset-state ivy-last))
1892 ivy--switch-buffer-other-window-action
1895 ivy--rename-buffer-action
1899 (defun ivy-switch-buffer ()
1900 "Switch to another buffer."
1903 (call-interactively 'switch-to-buffer)
1904 (let ((this-command 'ivy-switch-buffer))
1905 (ivy-read "Switch to buffer: " 'internal-complete-buffer
1906 :preselect (buffer-name (other-buffer (current-buffer)))
1907 :action #'ivy--switch-buffer-action
1908 :keymap ivy-switch-buffer-map))))
1911 (defun ivy-recentf ()
1912 "Find a file on `recentf-list'."
1914 (ivy-read "Recentf: " recentf-list
1920 (defun ivy-yank-word ()
1921 "Pull next word from buffer into search string."
1926 (le (line-end-position)))
1930 (setq amend (buffer-substring-no-properties pt (point))))))
1932 (insert (replace-regexp-in-string " +" " " amend)))))
1934 (defun ivy-kill-ring-save ()
1935 "Store the current candidates into the kill ring.
1936 If the region is active, forward to `kill-ring-save' instead."
1938 (if (region-active-p)
1939 (call-interactively 'kill-ring-save)
1946 (defun ivy-insert-current ()
1947 "Make the current candidate into current input.
1948 Don't finish completion."
1950 (delete-minibuffer-contents)
1951 (if (and ivy--directory
1952 (string-match "/$" ivy--current))
1953 (insert (substring ivy--current 0 -1))
1954 (insert ivy--current)))
1956 (defun ivy-toggle-fuzzy ()
1957 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
1959 (setq ivy--old-re nil)
1960 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
1961 (setq ivy--regex-function 'ivy--regex-plus)
1962 (setq ivy--regex-function 'ivy--regex-fuzzy)))
1964 (defun ivy-reverse-i-search ()
1965 "Enter a recursive `ivy-read' session using the current history.
1966 The selected history element will be inserted into the minibufer."
1968 (let ((enable-recursive-minibuffers t)
1969 (history (symbol-value (ivy-state-history ivy-last)))
1970 (old-last ivy-last))
1971 (ivy-read "Reverse-i-search: "
1975 (setq ivy-last old-last))
1976 (delete-minibuffer-contents)
1977 (insert (substring-no-properties x))
1980 (defun ivy-restrict-to-matches ()
1981 "Restrict candidates to current matches and erase input."
1983 (delete-minibuffer-contents)
1984 (setq ivy--all-candidates
1985 (ivy--filter ivy-text ivy--all-candidates)))
1989 ;;; ivy.el ends here