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
8 ;; Package-Requires: ((emacs "24.1"))
11 ;; This file is part of GNU Emacs.
13 ;; This file is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 3, or (at your option)
18 ;; This program is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; For a full copy of the GNU General Public License
24 ;; see <http://www.gnu.org/licenses/>.
28 ;; This package provides `ivy-read' as an alternative to
29 ;; `completing-read' and similar functions.
31 ;; There's no intricate code to determine the best candidate.
32 ;; Instead, the user can navigate to it with `ivy-next-line' and
33 ;; `ivy-previous-line'.
35 ;; The matching is done by splitting the input text by spaces and
36 ;; re-building it into a regex.
37 ;; So "for example" is transformed into "\\(for\\).*\\(example\\)".
45 "Incremental vertical completion."
48 (defgroup ivy-faces nil
49 "Font-lock faces for `ivy'."
53 (defface ivy-current-match
54 '((((class color) (background light))
55 :background "#1a4b77" :foreground "white")
56 (((class color) (background dark))
57 :background "#65a7e2" :foreground "black"))
58 "Face used by Ivy for highlighting the current match.")
60 (defface ivy-minibuffer-match-face-1
61 '((((class color) (background light))
62 :background "#d3d3d3")
63 (((class color) (background dark))
64 :background "#555555"))
65 "The background face for `ivy' minibuffer matches.")
67 (defface ivy-minibuffer-match-face-2
68 '((((class color) (background light))
69 :background "#e99ce8" :weight bold)
70 (((class color) (background dark))
71 :background "#777777" :weight bold))
72 "Face for `ivy' minibuffer matches numbered 1 modulo 3.")
74 (defface ivy-minibuffer-match-face-3
75 '((((class color) (background light))
76 :background "#bbbbff" :weight bold)
77 (((class color) (background dark))
78 :background "#7777ff" :weight bold))
79 "Face for `ivy' minibuffer matches numbered 2 modulo 3.")
81 (defface ivy-minibuffer-match-face-4
82 '((((class color) (background light))
83 :background "#ffbbff" :weight bold)
84 (((class color) (background dark))
85 :background "#8a498a" :weight bold))
86 "Face for `ivy' minibuffer matches numbered 3 modulo 3.")
88 (defface ivy-confirm-face
89 '((t :foreground "ForestGreen" :inherit minibuffer-prompt))
90 "Face used by Ivy for a confirmation prompt.")
92 (defface ivy-match-required-face
93 '((t :foreground "red" :inherit minibuffer-prompt))
94 "Face used by Ivy for a match required prompt.")
97 '((t :inherit dired-directory))
98 "Face used by Ivy for highlighting subdirs in the alternatives.")
100 (defface ivy-modified-buffer
101 '((t :inherit default))
102 "Face used by Ivy for highlighting modified file visiting buffers.")
105 '((t :foreground "#110099"))
106 "Face used by Ivy for highlighting remotes in the alternatives.")
109 '((t :inherit font-lock-builtin-face))
110 "Face used by Ivy for matching virtual buffer names.")
113 '((t :inherit font-lock-builtin-face))
114 "Face used by Ivy for displaying keys in `ivy-read-action'.")
116 (setcdr (assoc load-file-name custom-current-group-alist) 'ivy)
118 (defcustom ivy-height 10
119 "Number of lines for the minibuffer window."
122 (defcustom ivy-count-format "%-4d "
123 "The style to use for displaying the current candidate count for `ivy-read'.
124 Set this to \"\" to suppress the count visibility.
125 Set this to \"(%d/%d) \" to display both the index and the count."
127 (const :tag "Count disabled" "")
128 (const :tag "Count matches" "%-4d ")
129 (const :tag "Count matches and show current match" "(%d/%d) ")
132 (defcustom ivy-add-newline-after-prompt nil
133 "When non-nil, add a newline after the `ivy-read' prompt."
136 (defcustom ivy-wrap nil
137 "When non-nil, wrap around after the first and the last candidate."
140 (defcustom ivy-display-style (unless (version< emacs-version "24.5") 'fancy)
141 "The style for formatting the minibuffer.
143 By default, the matched strings are copied as is.
145 The fancy display style highlights matching parts of the regexp,
146 a behavior similar to `swiper'.
148 This setting depends on `add-face-text-property' - a C function
149 available as of Emacs 24.5. Fancy style will render poorly in
150 earlier versions of Emacs."
152 (const :tag "Plain" nil)
153 (const :tag "Fancy" fancy)))
155 (defcustom ivy-on-del-error-function 'minibuffer-keyboard-quit
156 "The handler for when `ivy-backward-delete-char' throws.
157 Usually a quick exit out of the minibuffer."
160 (defcustom ivy-extra-directories '("../" "./")
161 "Add this to the front of the list when completing file names.
162 Only \"./\" and \"../\" apply here. They appear in reverse order."
163 :type '(repeat :tag "Dirs"
165 (const :tag "Parent Directory" "../")
166 (const :tag "Current Directory" "./"))))
168 (defcustom ivy-use-virtual-buffers nil
169 "When non-nil, add `recentf-mode' and bookmarks to `ivy-switch-buffer'."
172 (defvar ivy--actions-list nil
173 "A list of extra actions per command.")
175 (defun ivy-set-actions (cmd actions)
176 "Set CMD extra exit points to ACTIONS."
177 (setq ivy--actions-list
178 (plist-put ivy--actions-list cmd actions)))
180 (defvar ivy--display-transformers-list nil
181 "A list of str->str transformers per command.")
183 (defun ivy-set-display-transformer (cmd transformer)
184 "Set CMD a displayed candidate TRANSFORMER.
186 It's a lambda that takes a string one of the candidates in the
187 collection and returns a string for display, the same candidate
188 plus some extra information.
190 This lambda is called only on the `ivy-height' candidates that
191 are about to be displayed, not on the whole collection."
192 (setq ivy--display-transformers-list
193 (plist-put ivy--display-transformers-list cmd transformer)))
195 (defvar ivy--sources-list nil
196 "A list of extra sources per command.")
198 (defun ivy-set-sources (cmd sources)
199 "Attach to CMD a list of extra SOURCES.
201 Each static source is a function that takes no argument and
202 returns a list of strings.
204 The '(original-source) determines the position of the original
207 Extra dynamic sources aren't supported yet.
211 (defun small-recentf ()
212 (cl-subseq recentf-list 0 20))
219 (setq ivy--sources-list
220 (plist-put ivy--sources-list cmd sources)))
224 (defvar ivy-minibuffer-map
225 (let ((map (make-sparse-keymap)))
226 (define-key map (kbd "C-m") 'ivy-done)
227 (define-key map (kbd "C-M-m") 'ivy-call)
228 (define-key map (kbd "C-j") 'ivy-alt-done)
229 (define-key map (kbd "C-M-j") 'ivy-immediate-done)
230 (define-key map (kbd "TAB") 'ivy-partial-or-done)
231 (define-key map [remap next-line] 'ivy-next-line)
232 (define-key map [remap previous-line] 'ivy-previous-line)
233 (define-key map (kbd "C-s") 'ivy-next-line-or-history)
234 (define-key map (kbd "C-r") 'ivy-reverse-i-search)
235 (define-key map (kbd "SPC") 'self-insert-command)
236 (define-key map [remap delete-backward-char] 'ivy-backward-delete-char)
237 (define-key map [remap backward-kill-word] 'ivy-backward-kill-word)
238 (define-key map [remap delete-char] 'ivy-delete-char)
239 (define-key map [remap forward-char] 'ivy-forward-char)
240 (define-key map [remap kill-word] 'ivy-kill-word)
241 (define-key map [remap beginning-of-buffer] 'ivy-beginning-of-buffer)
242 (define-key map [remap end-of-buffer] 'ivy-end-of-buffer)
243 (define-key map (kbd "M-n") 'ivy-next-history-element)
244 (define-key map (kbd "M-p") 'ivy-previous-history-element)
245 (define-key map (kbd "C-g") 'minibuffer-keyboard-quit)
246 (define-key map [remap scroll-up-command] 'ivy-scroll-up-command)
247 (define-key map [remap scroll-down-command] 'ivy-scroll-down-command)
248 (define-key map (kbd "C-M-n") 'ivy-next-line-and-call)
249 (define-key map (kbd "C-M-p") 'ivy-previous-line-and-call)
250 (define-key map (kbd "M-q") 'ivy-toggle-regexp-quote)
251 (define-key map (kbd "M-j") 'ivy-yank-word)
252 (define-key map (kbd "M-i") 'ivy-insert-current)
253 (define-key map (kbd "C-o") 'hydra-ivy/body)
254 (define-key map (kbd "M-o") 'ivy-dispatching-done)
255 (define-key map (kbd "C-M-o") 'ivy-dispatching-call)
256 (define-key map [remap kill-line] 'ivy-kill-line)
257 (define-key map (kbd "S-SPC") 'ivy-restrict-to-matches)
258 (define-key map [remap kill-ring-save] 'ivy-kill-ring-save)
259 (define-key map (kbd "C-'") 'ivy-avy)
260 (define-key map (kbd "C-M-a") 'ivy-read-action)
261 (define-key map (kbd "C-c C-o") 'ivy-occur)
262 (define-key map (kbd "C-c C-a") 'ivy-toggle-ignore)
263 (define-key map [remap describe-mode] 'ivy-help)
265 "Keymap used in the minibuffer.")
266 (autoload 'hydra-ivy/body "ivy-hydra" "" t)
269 (let ((map (make-sparse-keymap)))
270 (define-key map [remap switch-to-buffer]
272 (define-key map [remap switch-to-buffer-other-window]
273 'ivy-switch-buffer-other-window)
275 "Keymap for `ivy-mode'.")
278 (cl-defstruct ivy-state
280 predicate require-match initial-input
281 history preselect keymap update-fn sort
282 ;; The window in which `ivy-read' was called
284 ;; The buffer in which `ivy-read' was called
286 ;; The value of `ivy-text' to be used by `ivy-occur'
292 ;; When this is non-nil, call it for each input change to get new candidates
294 ;; A lambda that transforms candidates only for display
295 display-transformer-fn
298 (defvar ivy-last (make-ivy-state)
299 "The last parameters passed to `ivy-read'.
301 This should eventually become a stack so that you could use
302 `ivy-read' recursively.")
304 (defsubst ivy-set-action (action)
305 (setf (ivy-state-action ivy-last) action))
307 (defun ivy-thing-at-point ()
308 "Return a string that corresponds to the current thing at point."
310 (thing-at-point 'url)
311 (and (eq (ivy-state-collection ivy-last) 'read-file-name-internal)
312 (ffap-file-at-point))
314 (cond ((stringp (setq s (thing-at-point 'symbol)))
315 (if (string-match "\\`[`']?\\(.*?\\)'?\\'" s)
318 ((looking-at "(+\\(\\(?:\\sw\\|\\s_\\)+\\)\\_>")
319 (match-string-no-properties 1))
323 (defvar ivy-history nil
324 "History list of candidates entered in the minibuffer.
326 Maximum length of the history list is determined by the value
327 of `history-length'.")
329 (defvar ivy--directory nil
330 "Current directory when completing file names.")
332 (defvar ivy--length 0
333 "Store the amount of viable candidates.")
336 "Store the user's string as it is typed in.")
338 (defvar ivy--current ""
339 "Current candidate.")
342 "Store the index of the current candidate.")
345 "Store 'done if the completion was successfully selected.
346 Otherwise, store nil.")
348 (defvar ivy--all-candidates nil
349 "Store the candidates passed to `ivy-read'.")
351 (defvar ivy--extra-candidates '((original-source))
352 "Store candidates added by the extra sources.
354 This is an internal-use alist. Each key is a function name, or
355 original-source (which represents where the current dynamic
356 candidates should go).
358 Each value is an evaluation of the function, in case of static
359 sources. These values will subsequently be filtered on `ivy-text'.
361 This variable is set by `ivy-read' and used by `ivy--set-candidates'.")
363 (defcustom ivy-use-ignore-default t
364 "The default policy for user-configured candidate filtering."
366 (const :tag "Ignore ignored always" always)
367 (const :tag "Ignore ignored when others exist" t)
368 (const :tag "Don't ignore" nil)))
370 (defvar ivy-use-ignore t
371 "Store policy for user-configured candidate filtering.
372 This may be changed dynamically by `ivy-toggle-ignore'.
373 Use `ivy-use-ignore-default' for a permanent configuration.")
375 (defvar ivy--default nil
376 "Default initial input.")
378 (defvar ivy--prompt nil
379 "Store the format-style prompt.
380 When non-nil, it should contain at least one %d.")
382 (defvar ivy--prompt-extra ""
383 "Temporary modifications to the prompt.")
385 (defvar ivy--old-re nil
386 "Store the old regexp.")
388 (defvar ivy--old-cands nil
389 "Store the candidates matched by `ivy--old-re'.")
391 (defvar ivy--regex-function 'ivy--regex
392 "Current function for building a regex.")
394 (defvar ivy--subexps 0
395 "Number of groups in the current `ivy--regex'.")
397 (defvar ivy--full-length nil
398 "When :dynamic-collection is non-nil, this can be the total amount of candidates.")
400 (defvar ivy--old-text ""
401 "Store old `ivy-text' for dynamic completion.")
403 (defvar ivy-case-fold-search 'auto
404 "Store the current overriding `case-fold-search'.")
406 (defvar Info-current-file)
409 (unless (fboundp 'defvar-local)
410 (defmacro defvar-local (var val &optional docstring)
411 "Define VAR as a buffer-local variable with default value VAL."
412 (declare (debug defvar) (doc-string 3))
413 (list 'progn (list 'defvar var val docstring)
414 (list 'make-variable-buffer-local (list 'quote var)))))
415 (unless (fboundp 'setq-local)
416 (defmacro setq-local (var val)
417 "Set variable VAR to value VAL in current buffer."
418 (list 'set (list 'make-local-variable (list 'quote var)) val))))
420 (defmacro ivy-quit-and-run (&rest body)
421 "Quit the minibuffer and run BODY afterwards."
423 (put 'quit 'error-message "")
426 (put 'quit 'error-message "Quit")
428 (minibuffer-keyboard-quit)))
430 (defun ivy-exit-with-action (action)
431 "Quit the minibuffer and call ACTION afterwards."
435 (ivy-set-action ',(ivy-state-action ivy-last))))
436 (setq ivy-exit 'done)
439 (defmacro with-ivy-window (&rest body)
440 "Execute BODY in the window from which `ivy-read' was called."
443 `(with-selected-window (ivy--get-window ivy-last)
446 (defun ivy--done (text)
447 "Insert TEXT and exit minibuffer."
448 (if (and ivy--directory
449 (not (eq (ivy-state-history ivy-last) 'grep-files-history)))
450 (insert (setq ivy--current (expand-file-name
451 text ivy--directory)))
452 (insert (setq ivy--current text)))
453 (setq ivy-exit 'done)
458 "Exit the minibuffer with the selected candidate."
460 (delete-minibuffer-contents)
461 (cond ((or (> ivy--length 0)
462 ;; the action from `ivy-dispatching-done' may not need a
464 (eq this-command 'ivy-dispatching-done))
465 (ivy--done ivy--current))
466 ((memq (ivy-state-collection ivy-last)
467 '(read-file-name-internal internal-complete-buffer))
468 (if (or (not (eq confirm-nonexistent-file-or-buffer t))
469 (equal " (confirm)" ivy--prompt-extra))
471 (setq ivy--prompt-extra " (confirm)")
474 ((memq (ivy-state-require-match ivy-last)
475 '(nil confirm confirm-after-completion))
476 (ivy--done ivy-text))
478 (setq ivy--prompt-extra " (match required)")
482 (defvar ivy-read-action-format-function 'ivy-read-action-format-default
483 "Function used to transform the actions list into a docstring.")
485 (defun ivy-read-action-format-default (actions)
486 "Create a docstring from ACTIONS.
488 ACTIONS is a list. Each list item is a list of 3 items:
489 key (a string), cmd and doc (a string)."
491 (if (eq this-command 'ivy-read-action)
504 (defun ivy-read-action ()
505 "Change the action to one of the available ones.
507 Return nil for `minibuffer-keyboard-quit' or wrong key during the
508 selection, non-nil otherwise."
510 (let ((actions (ivy-state-action ivy-last)))
511 (if (null (ivy--actionp actions))
513 (let* ((hint (funcall ivy-read-action-format-function (cdr actions)))
514 (resize-mini-windows 'grow-only)
515 (key (string (read-key hint)))
516 (action-idx (cl-position-if
517 (lambda (x) (equal (car x) key))
519 (cond ((string= key "
\a")
522 (message "%s is not bound" key)
526 (setcar actions (1+ action-idx))
527 (ivy-set-action actions)))))))
529 (defun ivy-dispatching-done ()
530 "Select one of the available actions and call `ivy-done'."
532 (when (ivy-read-action)
535 (defun ivy-dispatching-call ()
536 "Select one of the available actions and call `ivy-call'."
538 (let ((actions (copy-sequence (ivy-state-action ivy-last))))
540 (when (ivy-read-action)
542 (ivy-set-action actions))))
544 (defun ivy-build-tramp-name (x)
545 "Reconstruct X into a path.
546 Is is a cons cell, related to `tramp-get-completion-function'."
550 (concat user "@" domain)
553 (declare-function tramp-get-completion-function "tramp")
554 (declare-function Info-find-node "info")
556 (defun ivy-alt-done (&optional arg)
557 "Exit the minibuffer with the selected candidate.
558 When ARG is t, exit with current text, ignoring the candidates."
561 (ivy-immediate-done))
563 (ivy--directory-done))
564 ((eq (ivy-state-collection ivy-last) 'Info-read-node-name-1)
565 (if (member ivy--current '("(./)" "(../)"))
567 (ivy-read "Go to file: " 'read-file-name-internal
570 (expand-file-name x ivy--directory)
576 (defun ivy--directory-done ()
577 "Handle exit from the minibuffer when completing file names."
580 ((equal ivy-text "/sudo::")
581 (setq dir (concat ivy-text ivy--directory))
586 (not (string= ivy--current "./"))
587 (setq dir (ivy-expand-file-if-directory ivy--current)))
590 ((or (and (equal ivy--directory "/")
591 (string-match "\\`[^/]+:.*:.*\\'" ivy-text))
592 (string-match "\\`/[^/]+:.*:.*\\'" ivy-text))
594 ((or (and (equal ivy--directory "/")
596 "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
599 "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
601 (setq ivy-text ivy--current))))
603 "\\`/\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
605 (let ((method (match-string 1 ivy-text))
606 (user (match-string 2 ivy-text))
607 (rest (match-string 3 ivy-text))
610 (dolist (x (tramp-get-completion-function method))
611 (setq res (append res (funcall (car x) (cadr x)))))
612 (setq res (delq nil res))
616 (setq res (cl-delete-duplicates res :test #'equal))
617 (let* ((old-ivy-last ivy-last)
618 (enable-recursive-minibuffers t)
619 (host (ivy-read "user@host: "
620 (mapcar #'ivy-build-tramp-name res)
621 :initial-input rest)))
622 (setq ivy-last old-ivy-last)
624 (setq ivy--directory "/")
625 (ivy--cd (concat "/" method ":" host ":"))))))
629 (defun ivy-expand-file-if-directory (file-name)
630 "Expand FILE-NAME as directory.
631 When this directory doesn't exist, return nil."
632 (when (stringp file-name)
634 ;; Ignore host name must not match method "ssh"
636 (file-name-as-directory
637 (expand-file-name file-name ivy--directory)))))
638 (when (and full-name (file-directory-p full-name))
641 (defcustom ivy-tab-space nil
642 "When non-nil, `ivy-partial-or-done' should insert a space."
645 (defun ivy-partial-or-done ()
646 "Complete the minibuffer text as much as possible.
647 If the text hasn't changed as a result, forward to `ivy-alt-done'."
649 (if (and (eq (ivy-state-collection ivy-last) #'read-file-name-internal)
650 (or (and (equal ivy--directory "/")
651 (string-match "\\`[^/]+:.*\\'" ivy-text))
652 (string-match "\\`/" ivy-text)))
653 (let ((default-directory ivy--directory)
655 (minibuffer-complete)
656 (setq ivy-text (ivy--input))
657 (when (setq dir (ivy-expand-file-if-directory ivy-text))
660 (when (or (eq this-command last-command)
664 (defun ivy-partial ()
665 "Complete the minibuffer text as much as possible."
667 (let* ((parts (or (split-string ivy-text " " t) (list "")))
668 (postfix (car (last parts)))
669 (completion-ignore-case t)
670 (startp (string-match "^\\^" postfix))
671 (new (try-completion (if startp
672 (substring postfix 1)
674 (mapcar (lambda (str)
675 (let ((i (string-match postfix str)))
679 (cond ((eq new t) nil)
680 ((string= new ivy-text) nil)
682 (delete-region (minibuffer-prompt-end) (point-max))
687 (insert (mapconcat #'identity parts " ")
688 (if ivy-tab-space " " ""))
691 (defun ivy-immediate-done ()
692 "Exit the minibuffer with the current input."
694 (delete-minibuffer-contents)
695 (insert (setq ivy--current
697 (expand-file-name ivy-text ivy--directory)
699 (setq ivy-exit 'done)
704 "Resume the last completion session."
706 (if (null (ivy-state-action ivy-last))
707 (user-error "The last session isn't compatible with `ivy-resume'")
708 (when (eq (ivy-state-caller ivy-last) 'swiper)
709 (switch-to-buffer (ivy-state-buffer ivy-last)))
710 (with-current-buffer (ivy-state-buffer ivy-last)
712 (ivy-state-prompt ivy-last)
713 (ivy-state-collection ivy-last)
714 :predicate (ivy-state-predicate ivy-last)
715 :require-match (ivy-state-require-match ivy-last)
716 :initial-input ivy-text
717 :history (ivy-state-history ivy-last)
718 :preselect (unless (eq (ivy-state-collection ivy-last)
719 'read-file-name-internal)
721 :keymap (ivy-state-keymap ivy-last)
722 :update-fn (ivy-state-update-fn ivy-last)
723 :sort (ivy-state-sort ivy-last)
724 :action (ivy-state-action ivy-last)
725 :unwind (ivy-state-unwind ivy-last)
726 :re-builder (ivy-state-re-builder ivy-last)
727 :matcher (ivy-state-matcher ivy-last)
728 :dynamic-collection (ivy-state-dynamic-collection ivy-last)
729 :caller (ivy-state-caller ivy-last)))))
731 (defvar-local ivy-calling nil
732 "When non-nil, call the current action when `ivy--index' changes.")
734 (defun ivy-set-index (index)
735 "Set `ivy--index' to INDEX."
736 (setq ivy--index index)
741 (defun ivy-beginning-of-buffer ()
742 "Select the first completion candidate."
746 (defun ivy-end-of-buffer ()
747 "Select the last completion candidate."
749 (ivy-set-index (1- ivy--length)))
751 (defun ivy-scroll-up-command ()
752 "Scroll the candidates upward by the minibuffer height."
754 (ivy-set-index (min (1- (+ ivy--index ivy-height))
757 (defun ivy-scroll-down-command ()
758 "Scroll the candidates downward by the minibuffer height."
760 (ivy-set-index (max (1+ (- ivy--index ivy-height))
763 (defun ivy-minibuffer-grow ()
764 "Grow the minibuffer window by 1 line."
766 (setq-local max-mini-window-height
767 (cl-incf ivy-height)))
769 (defun ivy-minibuffer-shrink ()
770 "Shrink the minibuffer window by 1 line."
772 (unless (<= ivy-height 2)
773 (setq-local max-mini-window-height
774 (cl-decf ivy-height))
775 (window-resize (selected-window) -1)))
777 (defun ivy-next-line (&optional arg)
778 "Move cursor vertically down ARG candidates."
780 (setq arg (or arg 1))
781 (let ((index (+ ivy--index arg)))
782 (if (> index (1- ivy--length))
784 (ivy-beginning-of-buffer)
785 (ivy-set-index (1- ivy--length)))
786 (ivy-set-index index))))
788 (defun ivy-next-line-or-history (&optional arg)
789 "Move cursor vertically down ARG candidates.
790 If the input is empty, select the previous history element instead."
792 (if (string= ivy-text "")
793 (ivy-previous-history-element 1)
794 (ivy-next-line arg)))
796 (defun ivy-previous-line (&optional arg)
797 "Move cursor vertically up ARG candidates."
799 (setq arg (or arg 1))
800 (let ((index (- ivy--index arg)))
805 (ivy-set-index index))))
807 (defun ivy-previous-line-or-history (arg)
808 "Move cursor vertically up ARG candidates.
809 If the input is empty, select the previous history element instead."
811 (when (string= ivy-text "")
812 (ivy-previous-history-element 1))
813 (ivy-previous-line arg))
815 (defun ivy-toggle-calling ()
816 "Flip `ivy-calling'."
818 (when (setq ivy-calling (not ivy-calling))
821 (defun ivy-toggle-ignore ()
822 "Toggle user-configured candidate filtering."
827 (or ivy-use-ignore-default t)))
829 (setq ivy--old-cands nil))
831 (defun ivy--get-action (state)
832 "Get the action function from STATE."
833 (let ((action (ivy-state-action state)))
835 (if (functionp action)
837 (cadr (nth (car action) action))))))
839 (defun ivy--get-window (state)
840 "Get the window from STATE."
841 (if (ivy-state-p state)
842 (let ((window (ivy-state-window state)))
843 (if (window-live-p window)
845 (if (= (length (window-list)) 1)
850 (defun ivy--actionp (x)
851 "Return non-nil when X is a list of actions."
852 (and x (listp x) (not (eq (car x) 'closure))))
854 (defun ivy-next-action ()
855 "When the current action is a list, scroll it forwards."
857 (let ((action (ivy-state-action ivy-last)))
858 (when (ivy--actionp action)
859 (unless (>= (car action) (1- (length action)))
860 (cl-incf (car action))))))
862 (defun ivy-prev-action ()
863 "When the current action is a list, scroll it backwards."
865 (let ((action (ivy-state-action ivy-last)))
866 (when (ivy--actionp action)
867 (unless (<= (car action) 1)
868 (cl-decf (car action))))))
870 (defun ivy-action-name ()
871 "Return the name associated with the current action."
872 (let ((action (ivy-state-action ivy-last)))
873 (if (ivy--actionp action)
877 (nth 2 (nth (car action) action)))
880 (defvar ivy-inhibit-action nil
881 "When non-nil, `ivy-call' does nothing.
885 (let* ((ivy-inhibit-action t)
886 (str (counsel-locate \"lispy.el\")))
887 ;; do whatever with str - the corresponding file will not be opened
891 "Call the current action without exiting completion."
893 (unless ivy-inhibit-action
894 (let ((action (ivy--get-action ivy-last)))
896 (let* ((collection (ivy-state-collection ivy-last))
897 (x (cond ((and (consp collection)
898 (consp (car collection))
899 (cdr (assoc ivy--current collection))))
900 ((equal ivy--current "")
904 (prog1 (funcall action x)
905 (unless (or (eq ivy-exit 'done)
906 (equal (selected-window)
907 (active-minibuffer-window))
908 (null (active-minibuffer-window)))
909 (select-window (active-minibuffer-window)))))))))
911 (defun ivy-next-line-and-call (&optional arg)
912 "Move cursor vertically down ARG candidates.
913 Call the permanent action if possible."
919 (defun ivy-previous-line-and-call (&optional arg)
920 "Move cursor vertically down ARG candidates.
921 Call the permanent action if possible."
923 (ivy-previous-line arg)
927 (defun ivy-previous-history-element (arg)
928 "Forward to `previous-history-element' with ARG."
930 (previous-history-element arg)
933 (ivy--maybe-scroll-history))
935 (defun ivy-next-history-element (arg)
936 "Forward to `next-history-element' with ARG."
938 (if (and (= minibuffer-history-position 0)
941 (insert ivy--default)
942 (when (and (with-ivy-window (derived-mode-p 'prog-mode))
943 (eq (ivy-state-caller ivy-last) 'swiper)
944 (not (file-exists-p ivy--default))
945 (not (ffap-url-p ivy--default))
946 (not (ivy-state-dynamic-collection ivy-last))
947 (> (point) (minibuffer-prompt-end)))
950 (goto-char (minibuffer-prompt-end))
952 (forward-char (+ 2 (length ivy--default)))))
953 (next-history-element arg))
956 (ivy--maybe-scroll-history))
958 (defvar ivy-ffap-url-functions nil
959 "List of functions that check if the point is on a URL.")
961 (defun ivy--cd-maybe ()
962 "Check if the current input points to a different directory.
963 If so, move to that directory, while keeping only the file name."
965 (let ((input (ivy--input))
967 (if (setq url (or (ffap-url-p input)
972 ivy-ffap-url-functions
973 :initial-value nil))))
974 (ivy-exit-with-action
976 (funcall ffap-url-fetcher url)))
977 (setq input (expand-file-name input))
978 (let ((file (file-name-nondirectory input))
979 (dir (expand-file-name (file-name-directory input))))
980 (if (string= dir ivy--directory)
982 (delete-minibuffer-contents)
987 (defun ivy--maybe-scroll-history ()
988 "If the selected history element has an index, scroll there."
989 (let ((idx (ignore-errors
991 (minibuffer-prompt-end)
995 (setq ivy--index idx))))
998 "When completing file names, move to directory DIR."
999 (if (null ivy--directory)
1000 (error "Unexpected")
1001 (setq ivy--old-cands nil)
1002 (setq ivy--old-re nil)
1004 (setq ivy--all-candidates
1005 (ivy--sorted-files (setq ivy--directory dir)))
1007 (delete-minibuffer-contents)))
1009 (defun ivy-backward-delete-char ()
1010 "Forward to `backward-delete-char'.
1011 On error (read-only), call `ivy-on-del-error-function'."
1013 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
1015 (ivy--cd (file-name-directory
1016 (directory-file-name
1021 (backward-delete-char 1)
1023 (when ivy-on-del-error-function
1024 (funcall ivy-on-del-error-function))))))
1026 (defun ivy-delete-char (arg)
1027 "Forward to `delete-char' ARG."
1029 (unless (= (point) (line-end-position))
1032 (defun ivy-forward-char (arg)
1033 "Forward to `forward-char' ARG."
1035 (unless (= (point) (line-end-position))
1036 (forward-char arg)))
1038 (defun ivy-kill-word (arg)
1039 "Forward to `kill-word' ARG."
1041 (unless (= (point) (line-end-position))
1044 (defun ivy-kill-line ()
1045 "Forward to `kill-line'."
1048 (kill-region (minibuffer-prompt-end) (point))
1051 (defun ivy-backward-kill-word ()
1052 "Forward to `backward-kill-word'."
1054 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
1056 (ivy--cd (file-name-directory
1057 (directory-file-name
1064 (delete-region (point) pt)))))
1066 (defvar ivy--regexp-quote 'regexp-quote
1067 "Store the regexp quoting state.")
1069 (defun ivy-toggle-regexp-quote ()
1070 "Toggle the regexp quoting."
1072 (setq ivy--old-re nil)
1073 (cl-rotatef ivy--regex-function ivy--regexp-quote))
1075 (defvar avy-all-windows)
1078 (defvar avy-keys-alist)
1080 (defvar avy-styles-alist)
1081 (declare-function avy--process "ext:avy")
1082 (declare-function avy--style-fn "ext:avy")
1084 (eval-after-load 'avy
1085 '(add-to-list 'avy-styles-alist '(ivy-avy . pre)))
1088 "Jump to one of the current ivy candidates."
1090 (unless (require 'avy nil 'noerror)
1091 (error "Package avy isn't installed"))
1092 (let* ((avy-all-windows nil)
1093 (avy-keys (or (cdr (assq 'ivy-avy avy-keys-alist))
1095 (avy-style (or (cdr (assq 'ivy-avy
1105 (goto-char (point-min))
1107 (while (< (point) (point-max))
1113 (setq avy-action #'identity)
1115 (nreverse candidates)
1116 (avy--style-fn avy-style)))))
1117 (when (numberp candidate)
1118 (ivy-set-index (- (line-number-at-pos candidate) 2))
1122 (defun ivy-sort-file-function-default (x y)
1123 "Compare two files X and Y.
1124 Prioritize directories."
1125 (if (get-text-property 0 'dirp x)
1126 (if (get-text-property 0 'dirp y)
1129 (if (get-text-property 0 'dirp y)
1133 (defcustom ivy-sort-functions-alist
1134 '((read-file-name-internal . ivy-sort-file-function-default)
1135 (internal-complete-buffer . nil)
1136 (counsel-git-grep-function . nil)
1137 (Man-goto-section . nil)
1140 "An alist of sorting functions for each collection function.
1141 Interactive functions that call completion fit in here as well.
1143 Nil means no sorting, which is useful to turn off the sorting for
1144 functions that have candidates in the natural buffer order, like
1145 `org-refile' or `Man-goto-section'.
1147 The entry associated with t is used for all fall-through cases.
1149 See also `ivy-sort-max-size'."
1153 (const :tag "Fall-through" t)
1154 (symbol :tag "Collection"))
1156 (const :tag "Plain sort" string-lessp)
1157 (const :tag "File sort" ivy-sort-file-function-default)
1158 (const :tag "No sort" nil)
1159 (function :tag "Custom function")))
1162 (defvar ivy-index-functions-alist
1163 '((swiper . ivy-recompute-index-swiper)
1164 (swiper-multi . ivy-recompute-index-swiper)
1165 (counsel-git-grep . ivy-recompute-index-swiper)
1166 (counsel-grep . ivy-recompute-index-swiper-async)
1167 (t . ivy-recompute-index-zero))
1168 "An alist of index recomputing functions for each collection function.
1169 When the input changes, the appropriate function returns an
1170 integer - the index of the matched candidate that should be
1173 (defvar ivy-re-builders-alist
1174 '((t . ivy--regex-plus))
1175 "An alist of regex building functions for each collection function.
1177 Each key is (in order of priority):
1178 1. The actual collection function, e.g. `read-file-name-internal'.
1179 2. The symbol passed by :caller into `ivy-read'.
1183 Each value is a function that should take a string and return a
1184 valid regex or a regex sequence (see below).
1186 Possible choices: `ivy--regex', `regexp-quote',
1187 `ivy--regex-plus', `ivy--regex-fuzzy'.
1189 If a function returns a list, it should format like this:
1190 '((\"matching-regexp\" . t) (\"non-matching-regexp\") ...).
1192 The matches will be filtered in a sequence, you can mix the
1193 regexps that should match and that should not match as you
1196 (defvar ivy-initial-inputs-alist
1197 '((org-refile . "^")
1198 (org-agenda-refile . "^")
1199 (org-capture-refile . "^")
1201 (counsel-describe-function . "^")
1202 (counsel-describe-variable . "^")
1205 "Command to initial input table.")
1207 (defcustom ivy-sort-max-size 30000
1208 "Sorting won't be done for collections larger than this."
1211 (defun ivy--sorted-files (dir)
1212 "Return the list of files in DIR.
1213 Directories come first."
1214 (let* ((default-directory dir)
1215 (seq (all-completions "" 'read-file-name-internal))
1219 (setq seq (delete "./" (delete "../" seq)))
1220 (when (eq (setq sort-fn (cdr (assoc 'read-file-name-internal
1221 ivy-sort-functions-alist)))
1222 #'ivy-sort-file-function-default)
1223 (setq seq (mapcar (lambda (x)
1224 (propertize x 'dirp (string-match-p "/\\'" x)))
1227 (setq seq (cl-sort seq sort-fn)))
1228 (dolist (dir ivy-extra-directories)
1232 (defvar ivy-recursive-restore t
1233 "When non-nil, restore the above state when exiting the minibuffer.
1234 This variable is let-bound to nil by functions that take care of
1235 the restoring themselves.")
1238 (cl-defun ivy-read (prompt collection
1240 predicate require-match initial-input
1241 history preselect keymap update-fn sort
1242 action unwind re-builder matcher dynamic-collection caller)
1243 "Read a string in the minibuffer, with completion.
1245 PROMPT is a format string, normally ending in a colon and a
1246 space; %d anywhere in the string is replaced by the current
1247 number of matching candidates. For the literal % character,
1248 escape it with %%. See also `ivy-count-format'.
1250 COLLECTION is either a list of strings, a function, an alist, or
1253 If INITIAL-INPUT is not nil, then insert that input in the
1254 minibuffer initially.
1256 KEYMAP is composed with `ivy-minibuffer-map'.
1258 If PRESELECT is not nil, then select the corresponding candidate
1259 out of the ones that match the INITIAL-INPUT.
1261 UPDATE-FN is called each time the current candidate(s) is changed.
1263 When SORT is t, use `ivy-sort-functions-alist' for sorting.
1265 ACTION is a lambda function to call after selecting a result. It
1266 takes a single string argument.
1268 UNWIND is a lambda function to call before exiting.
1270 RE-BUILDER is a lambda function to call to transform text into a
1273 MATCHER is to override matching.
1275 DYNAMIC-COLLECTION is a boolean to specify if the list of
1276 candidates is updated after each input by calling COLLECTION.
1278 CALLER is a symbol to uniquely identify the caller to `ivy-read'.
1279 It is used, along with COLLECTION, to determine which
1280 customizations apply to the current completion session."
1281 (let ((extra-actions (delete-dups
1282 (append (plist-get ivy--actions-list t)
1283 (plist-get ivy--actions-list this-command)
1284 (plist-get ivy--actions-list caller)))))
1287 (cond ((functionp action)
1289 ("o" ,action "default")
1293 ("o" identity "default")
1296 (delete-dups (append action extra-actions)))))))
1297 (let ((extra-sources (plist-get ivy--sources-list caller)))
1300 (setq ivy--extra-candidates nil)
1301 (dolist (source extra-sources)
1302 (cond ((equal source '(original-source))
1303 (setq ivy--extra-candidates
1304 (cons source ivy--extra-candidates)))
1305 ((null (cdr source))
1306 (setq ivy--extra-candidates
1308 (list (car source) (funcall (car source)))
1309 ivy--extra-candidates))))))
1310 (setq ivy--extra-candidates '((original-source)))))
1311 (let ((recursive-ivy-last (and (active-minibuffer-window) ivy-last))
1313 (plist-get ivy--display-transformers-list
1314 (or caller (and (functionp collection)
1319 :collection collection
1320 :predicate predicate
1321 :require-match require-match
1322 :initial-input initial-input
1324 :preselect preselect
1326 :update-fn update-fn
1329 :window (selected-window)
1330 :buffer (current-buffer)
1332 :re-builder re-builder
1334 :dynamic-collection dynamic-collection
1335 :display-transformer-fn transformer-fn
1337 (ivy--reset-state ivy-last)
1340 (minibuffer-with-setup-hook
1341 #'ivy--minibuffer-setup
1342 (let* ((hist (or history 'ivy-history))
1343 (minibuffer-completion-table collection)
1344 (minibuffer-completion-predicate predicate)
1345 (resize-mini-windows (cond
1346 ((display-graphic-p) nil)
1347 ((null resize-mini-windows) 'grow-only)
1348 (t resize-mini-windows))))
1349 (read-from-minibuffer
1351 (ivy-state-initial-input ivy-last)
1352 (make-composed-keymap keymap ivy-minibuffer-map)
1355 (when (eq ivy-exit 'done)
1356 (let ((item (if ivy--directory
1359 (unless (equal item "")
1360 (set hist (cons (propertize item 'ivy-index ivy--index)
1362 (cdr (symbol-value hist))))))))
1364 (remove-hook 'post-command-hook #'ivy--exhibit)
1365 (when (setq unwind (ivy-state-unwind ivy-last))
1367 (unless (eq ivy-exit 'done)
1368 (when recursive-ivy-last
1369 (ivy--reset-state (setq ivy-last recursive-ivy-last)))))
1371 (when (and recursive-ivy-last
1372 ivy-recursive-restore)
1373 (ivy--reset-state (setq ivy-last recursive-ivy-last))))))
1375 (defun ivy--reset-state (state)
1376 "Reset the ivy to STATE.
1377 This is useful for recursive `ivy-read'."
1378 (let ((prompt (or (ivy-state-prompt state) ""))
1379 (collection (ivy-state-collection state))
1380 (predicate (ivy-state-predicate state))
1381 (history (ivy-state-history state))
1382 (preselect (ivy-state-preselect state))
1383 (sort (ivy-state-sort state))
1384 (re-builder (ivy-state-re-builder state))
1385 (dynamic-collection (ivy-state-dynamic-collection state))
1386 (initial-input (ivy-state-initial-input state))
1387 (require-match (ivy-state-require-match state))
1388 (caller (ivy-state-caller state)))
1389 (unless initial-input
1390 (setq initial-input (cdr (assoc this-command
1391 ivy-initial-inputs-alist))))
1392 (setq ivy--directory nil)
1393 (setq ivy-case-fold-search 'auto)
1394 (setq ivy--regex-function
1396 (and (functionp collection)
1397 (cdr (assoc collection ivy-re-builders-alist)))
1399 (cdr (assoc caller ivy-re-builders-alist)))
1400 (cdr (assoc this-command ivy-re-builders-alist))
1401 (cdr (assoc t ivy-re-builders-alist))
1403 (setq ivy--subexps 0)
1404 (setq ivy--regexp-quote 'regexp-quote)
1405 (setq ivy--old-text "")
1406 (setq ivy--full-length nil)
1408 (setq ivy-calling nil)
1409 (setq ivy-use-ignore ivy-use-ignore-default)
1411 (cond ((eq collection 'Info-read-node-name-1)
1412 (if (equal Info-current-file "dir")
1414 (mapcar (lambda (x) (format "(%s)" x))
1415 (cl-delete-duplicates
1416 (all-completions "(" collection predicate)
1418 (setq coll (all-completions "" collection predicate))))
1419 ((eq collection 'read-file-name-internal)
1420 (if (and initial-input (file-directory-p initial-input))
1422 (setq ivy--directory initial-input)
1423 (setq initial-input nil))
1424 (setq ivy--directory default-directory))
1427 (let ((preselect-directory (file-name-directory preselect)))
1428 (unless (or (null preselect-directory)
1429 (string= preselect-directory
1431 (setq ivy--directory preselect-directory))
1433 (ivy-state-preselect state)
1434 (setq preselect (file-name-nondirectory preselect)))))
1435 (setq coll (ivy--sorted-files ivy--directory))
1437 (unless (or require-match
1438 (equal initial-input default-directory)
1439 (equal initial-input ""))
1440 (setq coll (cons initial-input coll)))
1441 (unless (and (ivy-state-action ivy-last)
1442 (not (equal (ivy--get-action ivy-last) 'identity)))
1443 (setq initial-input nil))))
1444 ((eq collection 'internal-complete-buffer)
1445 (setq coll (ivy--buffer-list "" ivy-use-virtual-buffers predicate)))
1447 (setq coll (funcall collection ivy-text)))
1448 ((or (functionp collection)
1449 (byte-code-function-p collection)
1450 (vectorp collection)
1451 (and (consp collection) (listp (car collection)))
1452 (hash-table-p collection)
1453 (and (listp collection) (symbolp (car collection))))
1454 (setq coll (all-completions "" collection predicate)))
1456 (setq coll collection)))
1458 (if (and (functionp collection)
1459 (setq sort-fn (assoc collection ivy-sort-functions-alist)))
1460 (when (and (setq sort-fn (cdr sort-fn))
1461 (not (eq collection 'read-file-name-internal)))
1462 (setq coll (cl-sort coll sort-fn)))
1463 (unless (eq history 'org-refile-history)
1464 (if (and (setq sort-fn (cdr (assoc t ivy-sort-functions-alist)))
1465 (<= (length coll) ivy-sort-max-size))
1466 (setq coll (cl-sort (copy-sequence coll) sort-fn))))))
1467 (setq coll (ivy--set-candidates coll))
1469 (unless (or (and require-match
1470 (not (eq collection 'internal-complete-buffer)))
1472 (let ((re (regexp-quote preselect)))
1473 (cl-find-if (lambda (x) (string-match re x))
1475 (setq coll (cons preselect coll))))
1476 (setq ivy--old-re nil)
1477 (setq ivy--old-cands nil)
1478 (when (integerp preselect)
1479 (setq ivy--old-re "")
1480 (setq ivy--index preselect))
1482 ;; Needed for anchor to work
1483 (setq ivy--old-cands coll)
1484 (setq ivy--old-cands (ivy--filter initial-input coll)))
1485 (setq ivy--all-candidates coll)
1486 (unless (integerp preselect)
1487 (setq ivy--index (or
1488 (and dynamic-collection
1491 (ivy--preselect-index
1499 (if (region-active-p)
1503 (ivy-thing-at-point)))
1505 (cond ((string-match "%.*d" prompt)
1507 ((null ivy-count-format)
1509 "`ivy-count-format' can't be nil. Set it to an empty string instead"))
1510 ((string-match "%d.*%d" ivy-count-format)
1511 (let ((w (length (number-to-string
1512 (length ivy--all-candidates))))
1513 (s (copy-sequence ivy-count-format)))
1514 (string-match "%d" s)
1516 (string-match "%d" s (match-end 0))
1517 (setq s (replace-match (format "%%-%dd" w) nil nil s))
1518 (string-match "%d" s)
1519 (concat (replace-match (format "%%%dd" w) nil nil s)
1521 ((string-match "%.*d" ivy-count-format)
1522 (concat ivy-count-format prompt))
1527 (setf (ivy-state-initial-input ivy-last) initial-input)))
1530 (defun ivy-completing-read (prompt collection
1531 &optional predicate require-match initial-input
1532 history def inherit-input-method)
1533 "Read a string in the minibuffer, with completion.
1535 This interface conforms to `completing-read' and can be used for
1536 `completing-read-function'.
1538 PROMPT is a string that normally ends in a colon and a space.
1539 COLLECTION is either a list of strings, an alist, an obarray, or a hash table.
1540 PREDICATE limits completion to a subset of COLLECTION.
1541 REQUIRE-MATCH is a boolean value. See `completing-read'.
1542 INITIAL-INPUT is a string inserted into the minibuffer initially.
1543 HISTORY is a list of previously selected inputs.
1544 DEF is the default value.
1545 INHERIT-INPUT-METHOD is currently ignored."
1546 (if (memq this-command '(tmm-menubar tmm-shortcut))
1547 (completing-read-default prompt collection
1548 predicate require-match
1549 initial-input history
1550 def inherit-input-method)
1551 ;; See the doc of `completing-read'.
1552 (when (consp history)
1553 (when (numberp (cdr history))
1554 (setq initial-input (nth (1- (cdr history))
1555 (symbol-value (car history)))))
1556 (setq history (car history)))
1557 (ivy-read (replace-regexp-in-string "%" "%%" prompt)
1559 :predicate predicate
1560 :require-match require-match
1561 :initial-input (if (consp initial-input)
1563 (if (and (stringp initial-input)
1564 (string-match "\\+" initial-input))
1565 (replace-regexp-in-string
1566 "\\+" "\\\\+" initial-input)
1568 :preselect (if (listp def) (car def) def)
1572 (let ((sort (or (assoc this-command ivy-sort-functions-alist)
1573 (assoc t ivy-sort-functions-alist))))
1578 (defvar ivy-completion-beg nil
1579 "Completion bounds start.")
1581 (defvar ivy-completion-end nil
1582 "Completion bounds end.")
1584 (defun ivy-completion-in-region-action (str)
1585 "Insert STR, erasing the previous one.
1586 The previous string is between `ivy-completion-beg' and `ivy-completion-end'."
1589 (when ivy-completion-beg
1592 ivy-completion-end))
1593 (setq ivy-completion-beg
1594 (move-marker (make-marker) (point)))
1596 (setq ivy-completion-end
1597 (move-marker (make-marker) (point))))))
1599 (defun ivy-completion-common-length (str)
1600 "Return the length of the first 'completions-common-part face in STR."
1603 (while (and (<= pos len)
1604 (let ((prop (get-text-property pos 'face str)))
1605 (not (eq 'completions-common-part
1606 (if (listp prop) (car prop) prop)))))
1607 (setq pos (1+ pos)))
1609 (or (next-single-property-change pos 'face str) len)
1612 (defun ivy-completion-in-region (start end collection &optional predicate)
1613 "An Ivy function suitable for `completion-in-region-function'."
1614 (let* ((enable-recursive-minibuffers t)
1615 (str (buffer-substring-no-properties start end))
1616 (completion-ignore-case case-fold-search)
1618 (completion-all-completions str collection predicate (- end start))))
1620 (message "No matches")
1622 (setq ivy-completion-beg (- end (ivy-completion-common-length (car comps))))
1623 (setq ivy-completion-end end)
1624 (if (null (cdr comps))
1625 (if (string= str (car comps))
1626 (message "Sole match")
1627 (setf (ivy-state-window ivy-last) (selected-window))
1628 (ivy-completion-in-region-action
1629 (substring-no-properties
1631 (let* ((w (1+ (floor (log (length comps) 10))))
1632 (ivy-count-format (if (string= ivy-count-format "")
1634 (format "%%-%dd " w)))
1635 (prompt (format "(%s): " str)))
1637 (ivy-read (if (string= ivy-count-format "")
1639 (replace-regexp-in-string "%" "%%" prompt))
1640 ;; remove 'completions-first-difference face
1641 (mapcar #'substring-no-properties comps)
1642 :predicate predicate
1643 :action #'ivy-completion-in-region-action
1647 (defcustom ivy-do-completion-in-region t
1648 "When non-nil `ivy-mode' will set `completion-in-region-function'."
1652 (define-minor-mode ivy-mode
1653 "Toggle Ivy mode on or off.
1654 Turn Ivy mode on if ARG is positive, off otherwise.
1655 Turning on Ivy mode sets `completing-read-function' to
1656 `ivy-completing-read'.
1661 Minibuffer bindings:
1662 \\{ivy-minibuffer-map}"
1665 :keymap ivy-mode-map
1669 (setq completing-read-function 'ivy-completing-read)
1670 (when ivy-do-completion-in-region
1671 (setq completion-in-region-function 'ivy-completion-in-region)))
1672 (setq completing-read-function 'completing-read-default)
1673 (setq completion-in-region-function 'completion--in-region)))
1675 (defun ivy--preselect-index (preselect candidates)
1676 "Return the index of PRESELECT in CANDIDATES."
1677 (cond ((integerp preselect)
1679 ((cl-position preselect candidates :test #'equal))
1680 ((stringp preselect)
1681 (let ((re preselect))
1684 (string-match re x))
1689 (defvar ivy--regex-hash
1690 (make-hash-table :test #'equal)
1691 "Store pre-computed regex.")
1693 (defun ivy--split (str)
1694 "Split STR into a list by single spaces.
1695 The remaining spaces stick to their left.
1696 This allows to \"quote\" N spaces by inputting N+1 spaces."
1697 (let ((len (length str))
1702 (while (and (string-match " +" str start1)
1704 (if (and (> (match-beginning 0) 2)
1705 (string= "[^" (substring
1707 (- (match-beginning 0) 2)
1708 (match-beginning 0))))
1710 (setq start1 (match-end 0))
1712 (setq match-len (- (match-end 0) (match-beginning 0)))
1716 (setq start1 start0)
1718 (push (substring str start1 (match-beginning 0)) res)
1719 (setq start1 (match-end 0)))
1720 (setq str (replace-match
1721 (make-string (1- match-len) ?\ )
1723 (setq start0 (or start0 start1))
1724 (setq start1 (1- (match-end 0))))))
1726 (push (substring str start0) res)
1727 (setq s (substring str start1))
1728 (unless (= (length s) 0)
1732 (defun ivy--regex (str &optional greedy)
1733 "Re-build regex pattern from STR in case it has a space.
1734 When GREEDY is non-nil, join words in a greedy way."
1735 (let ((hashed (unless greedy
1736 (gethash str ivy--regex-hash))))
1739 (setq ivy--subexps (car hashed)))
1740 (when (string-match "\\([^\\]\\|^\\)\\\\$" str)
1741 (setq str (substring str 0 -1)))
1743 (let ((subs (ivy--split str)))
1744 (if (= (length subs) 1)
1746 (setq ivy--subexps 0)
1749 (setq ivy--subexps (length subs))
1752 (if (string-match "\\`\\\\([^?].*\\\\)\\'" x)
1754 (format "\\(%s\\)" x)))
1759 ivy--regex-hash)))))
1761 (defun ivy--regex-ignore-order--part (str &optional discard)
1762 "Re-build regex from STR by splitting at spaces.
1763 Ignore the order of each group."
1764 (let* ((subs (split-string str " +" t))
1765 (len (length subs)))
1770 (mapcar (lambda (x) (cons x (not discard)))
1773 (defun ivy--regex-ignore-order (str)
1774 "Re-build regex from STR by splitting at spaces.
1775 Ignore the order of each group. Everything before \"!\" should
1776 match. Everything after \"!\" should not match."
1777 (let ((parts (split-string str "!" t)))
1778 (cl-case (length parts)
1782 (if (string= (substring str 0 1) "!")
1784 (ivy--regex-ignore-order--part (car parts) t))
1785 (ivy--regex-ignore-order--part (car parts))))
1788 (ivy--regex-ignore-order--part (car parts))
1789 (ivy--regex-ignore-order--part (cadr parts) t)))
1790 (t (error "Unexpected: use only one !")))))
1792 (defun ivy--regex-plus (str)
1793 "Build a regex sequence from STR.
1794 Spaces are wild card characters, everything before \"!\" should
1795 match. Everything after \"!\" should not match."
1796 (let ((parts (split-string str "!" t)))
1797 (cl-case (length parts)
1801 (if (string= (substring str 0 1) "!")
1803 (list (ivy--regex (car parts))))
1804 (ivy--regex (car parts))))
1807 (cons (ivy--regex (car parts)) t)
1808 (mapcar #'list (split-string (cadr parts) " " t))))
1809 (t (error "Unexpected: use only one !")))))
1811 (defun ivy--regex-fuzzy (str)
1812 "Build a regex sequence from STR.
1813 Insert .* between each char."
1814 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1816 (concat (match-string 1 str)
1819 (format "\\(%c\\)" x))
1820 (string-to-list (match-string 2 str)) ".*")
1821 (match-string 3 str))
1822 (setq ivy--subexps (length (match-string 2 str))))
1825 (defcustom ivy-fixed-height-minibuffer nil
1826 "When non nil, fix the height of the minibuffer during ivy
1827 completion at `ivy-height'. This effectively sets the minimum
1828 height at this level and tries to ensure that it does not change
1829 depending on the number of candidates."
1834 (defun ivy--minibuffer-setup ()
1835 "Setup ivy completion in the minibuffer."
1836 (set (make-local-variable 'completion-show-inline-help) nil)
1837 (set (make-local-variable 'minibuffer-default-add-function)
1839 (list ivy--default)))
1840 (set (make-local-variable 'inhibit-field-text-motion) nil)
1841 (when (display-graphic-p)
1842 (setq truncate-lines t))
1843 (setq-local max-mini-window-height ivy-height)
1844 (when ivy-fixed-height-minibuffer
1845 (set-window-text-height (selected-window) ivy-height))
1846 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1847 ;; show completions with empty input
1850 (defun ivy--input ()
1851 "Return the current minibuffer input."
1852 ;; assume one-line minibuffer input
1853 (buffer-substring-no-properties
1854 (minibuffer-prompt-end)
1855 (line-end-position)))
1857 (defun ivy--cleanup ()
1858 "Delete the displayed completion candidates."
1860 (goto-char (minibuffer-prompt-end))
1861 (delete-region (line-end-position) (point-max))))
1863 (defun ivy--insert-prompt ()
1864 "Update the prompt according to `ivy--prompt'."
1866 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1867 counsel-find-symbol))
1868 (setq ivy--prompt-extra ""))
1870 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1872 (setq head (match-string 1 ivy--prompt))
1874 (setq head (substring ivy--prompt 0 -1))
1876 (let ((inhibit-read-only t)
1877 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1880 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1881 (> (minibuffer-depth) 1))
1882 (format "[%d] " (minibuffer-depth))
1885 (if (string-match "%d.*%d" ivy-count-format)
1888 (or (and (ivy-state-dynamic-collection ivy-last)
1892 (or (and (ivy-state-dynamic-collection ivy-last)
1897 (d-str (if ivy--directory
1898 (abbreviate-file-name ivy--directory)
1901 (goto-char (point-min))
1902 (delete-region (point-min) (minibuffer-prompt-end))
1903 (if (> (+ (mod (+ (length n-str) (length d-str)) (window-width))
1906 (setq n-str (concat n-str "\n" d-str))
1907 (setq n-str (concat n-str d-str)))
1908 (when ivy-add-newline-after-prompt
1909 (setq n-str (concat n-str "\n")))
1910 (let ((regex (format "\\([^\n]\\{%d\\}\\)[^\n]" (window-width))))
1911 (while (string-match regex n-str)
1912 (setq n-str (replace-match (concat (match-string 1 n-str) "\n") nil t n-str 1))))
1913 (set-text-properties 0 (length n-str)
1914 `(face minibuffer-prompt ,@std-props)
1916 (ivy--set-match-props n-str "confirm"
1917 `(face ivy-confirm-face ,@std-props))
1918 (ivy--set-match-props n-str "match required"
1919 `(face ivy-match-required-face ,@std-props))
1921 ;; get out of the prompt area
1922 (constrain-to-field nil (point-max))))))
1924 (defun ivy--set-match-props (str match props)
1925 "Set STR text properties that match MATCH to PROPS."
1926 (when (string-match match str)
1927 (set-text-properties
1933 (defvar inhibit-message)
1935 (defun ivy--sort-maybe (collection)
1936 "Sort COLLECTION if needed."
1937 (let ((sort (ivy-state-sort ivy-last))
1941 (let ((sort-fn (cond ((functionp sort)
1943 ((setq entry (assoc (ivy-state-collection ivy-last)
1944 ivy-sort-functions-alist))
1947 (cdr (assoc t ivy-sort-functions-alist))))))
1948 (if (functionp sort-fn)
1949 (cl-sort (copy-sequence collection) sort-fn)
1952 (defun ivy--magic-file-slash ()
1953 (cond ((member ivy-text ivy--all-candidates)
1954 (ivy--cd (expand-file-name ivy-text ivy--directory)))
1955 ((string-match "//\\'" ivy-text)
1956 (if (and default-directory
1957 (string-match "\\`[[:alpha:]]:/" default-directory))
1958 (ivy--cd (match-string 0 default-directory))
1960 ((string-match "[[:alpha:]]:/\\'" ivy-text)
1961 (let ((drive-root (match-string 0 ivy-text)))
1962 (when (file-exists-p drive-root)
1963 (ivy--cd drive-root))))
1964 ((and (or (> ivy--index 0)
1966 (not (string= ivy-text "/")))
1967 (let ((default-directory ivy--directory))
1969 (not (equal ivy--current ""))
1970 (file-directory-p ivy--current)
1971 (file-exists-p ivy--current))))
1972 (ivy--cd (expand-file-name ivy--current ivy--directory)))))
1974 (defun ivy--exhibit ()
1975 "Insert Ivy completions display.
1976 Should be run via minibuffer `post-command-hook'."
1977 (when (memq 'ivy--exhibit post-command-hook)
1978 (let ((inhibit-field-text-motion nil))
1979 (constrain-to-field nil (point-max)))
1980 (setq ivy-text (ivy--input))
1981 (if (ivy-state-dynamic-collection ivy-last)
1982 ;; while-no-input would cause annoying
1983 ;; "Waiting for process to die...done" message interruptions
1984 (let ((inhibit-message t))
1985 (unless (equal ivy--old-text ivy-text)
1987 (setq ivy--all-candidates
1989 (funcall (ivy-state-collection ivy-last) ivy-text)))
1990 (setq ivy--old-text ivy-text)))
1991 (when ivy--all-candidates
1992 (ivy--insert-minibuffer
1993 (ivy--format ivy--all-candidates))))
1994 (cond (ivy--directory
1995 (if (string-match "/\\'" ivy-text)
1996 (ivy--magic-file-slash)
1997 (if (string-match "\\`~\\'" ivy-text)
1998 (ivy--cd (expand-file-name "~/")))))
1999 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
2000 (when (or (and (string-match "\\` " ivy-text)
2001 (not (string-match "\\` " ivy--old-text)))
2002 (and (string-match "\\` " ivy--old-text)
2003 (not (string-match "\\` " ivy-text))))
2004 (setq ivy--all-candidates
2005 (if (and (> (length ivy-text) 0)
2006 (eq (aref ivy-text 0)
2008 (ivy--buffer-list " ")
2009 (ivy--buffer-list "" ivy-use-virtual-buffers)))
2010 (setq ivy--old-re nil))))
2011 (ivy--insert-minibuffer
2012 (with-current-buffer (ivy-state-buffer ivy-last)
2014 (ivy--filter ivy-text ivy--all-candidates))))
2015 (setq ivy--old-text ivy-text))))
2017 (defun ivy--insert-minibuffer (text)
2018 "Insert TEXT into minibuffer with appropriate cleanup."
2019 (let ((resize-mini-windows nil)
2020 (update-fn (ivy-state-update-fn ivy-last))
2024 (funcall update-fn))
2025 (ivy--insert-prompt)
2026 ;; Do nothing if while-no-input was aborted.
2027 (when (stringp text)
2028 (let ((buffer-undo-list t))
2032 (when (display-graphic-p)
2033 (ivy--resize-minibuffer-to-fit))))
2035 (defun ivy--resize-minibuffer-to-fit ()
2036 "Resize the minibuffer window size to fit the text in the minibuffer."
2037 (unless (frame-root-window-p (minibuffer-window))
2038 (with-selected-window (minibuffer-window)
2039 (if (fboundp 'window-text-pixel-size)
2040 (let ((text-height (cdr (window-text-pixel-size)))
2041 (body-height (window-body-height nil t)))
2042 (when (> text-height body-height)
2043 ;; Note: the size increment needs to be at least frame-char-height,
2044 ;; otherwise resizing won't do anything.
2045 (let ((delta (max (- text-height body-height) (frame-char-height))))
2046 (window-resize nil delta nil t t))))
2047 (let ((text-height (count-screen-lines))
2048 (body-height (window-body-height)))
2049 (when (> text-height body-height)
2050 (window-resize nil (- text-height body-height) nil t)))))))
2052 (declare-function colir-blend-face-background "ext:colir")
2054 (defun ivy--add-face (str face)
2055 "Propertize STR with FACE.
2056 `font-lock-append-text-property' is used, since it's better than
2057 `propertize' or `add-face-text-property' in this case."
2061 (colir-blend-face-background 0 (length str) face str)
2062 (let ((foreground (face-foreground face)))
2064 (add-face-text-property
2066 `(:foreground ,foreground)
2071 (font-lock-append-text-property 0 (length str) 'face face str))))
2074 (declare-function flx-make-string-cache "ext:flx")
2075 (declare-function flx-score "ext:flx")
2077 (defvar ivy--flx-cache nil)
2079 (eval-after-load 'flx
2080 '(setq ivy--flx-cache (flx-make-string-cache)))
2082 (defun ivy-toggle-case-fold ()
2083 "Toggle the case folding between nil and auto.
2084 In any completion session, the case folding starts in auto:
2086 - when the input is all lower case, `case-fold-search' is t
2089 You can toggle this to make `case-fold-search' nil regardless of input."
2091 (setq ivy-case-fold-search
2092 (if ivy-case-fold-search
2095 ;; reset cache so that the candidate list updates
2096 (setq ivy--old-re nil))
2098 (defun ivy--re-filter (re candidates)
2099 "Return all RE matching CANDIDATES.
2100 RE is a list of cons cells, with a regexp car and a boolean cdr.
2101 When the cdr is t, the car must match.
2102 Otherwise, the car must not match."
2103 (let ((re-list (if (stringp re) (list (cons re t)) re))
2105 (dolist (re re-list)
2112 (let ((re-str (car re)))
2113 (lambda (x) (string-match re-str x)))
2117 (defun ivy--filter (name candidates)
2118 "Return all items that match NAME in CANDIDATES.
2119 CANDIDATES are assumed to be static."
2120 (let ((re (funcall ivy--regex-function name)))
2121 (if (and (equal re ivy--old-re)
2123 ;; quick caching for "C-n", "C-p" etc.
2125 (let* ((re-str (if (listp re) (caar re) re))
2126 (matcher (ivy-state-matcher ivy-last))
2128 (and ivy-case-fold-search
2129 (string= name (downcase name))))
2132 (funcall matcher re candidates))
2135 (stringp ivy--old-re)
2136 (not (string-match "\\\\" ivy--old-re))
2137 (not (equal ivy--old-re ""))
2139 (if (string-match "\\\\)\\'" ivy--old-re)
2140 (substring ivy--old-re 0 -2)
2146 (lambda (x) (string-match re x))
2149 (ivy--re-filter re candidates)))))
2150 (ivy--recompute-index name re-str cands)
2152 (if (eq ivy--regex-function 'ivy--regex-ignore-order)
2157 (setq ivy--old-cands (ivy--sort name cands))))))
2159 (defun ivy--set-candidates (x)
2160 "Update `ivy--all-candidates' with X."
2162 (dolist (source ivy--extra-candidates)
2163 (if (equal source '(original-source))
2166 (setq res (append x res)))
2167 (setq ivy--old-re nil)
2169 (ivy--filter ivy-text (cadr source))
2171 (setq ivy--all-candidates res)))
2173 (defcustom ivy-sort-matches-functions-alist '((t . nil))
2174 "An alist of functions for sorting matching candidates.
2176 Unlike `ivy-sort-functions-alist', which is used to sort the
2177 whole collection only once, this alist of functions are used to
2178 sort only matching candidates after each change in input.
2180 The alist KEY is either a collection function or t to match
2181 previously unmatched collection functions.
2183 The alist VAL is a sorting function with the signature of
2184 `ivy--prefix-sort'."
2187 (const :tag "Fall-through" t)
2188 (symbol :tag "Collection"))
2191 (const :tag "Don't sort" nil)
2192 (const :tag "Put prefix matches ahead" 'ivy--prefix-sort)
2193 (function :tag "Custom sort function"))))
2195 (defun ivy--sort-files-by-date (_name candidates)
2196 "Re-soft CANDIDATES according to file modification date."
2197 (let ((default-directory ivy--directory))
2198 (cl-sort (copy-sequence candidates)
2201 (nth 5 (file-attributes f2))
2202 (nth 5 (file-attributes f1)))))))
2204 (defun ivy--sort (name candidates)
2205 "Re-sort CANDIDATES by NAME.
2206 All CANDIDATES are assumed to match NAME."
2207 (let ((key (or (ivy-state-caller ivy-last)
2208 (when (functionp (ivy-state-collection ivy-last))
2209 (ivy-state-collection ivy-last))))
2211 (cond ((and (require 'flx nil 'noerror)
2212 (eq ivy--regex-function 'ivy--regex-fuzzy))
2213 (ivy--flx-sort name candidates))
2214 ((setq fun (cdr (or (assoc key ivy-sort-matches-functions-alist)
2215 (assoc t ivy-sort-matches-functions-alist))))
2216 (funcall fun name candidates))
2220 (defun ivy--prefix-sort (name candidates)
2221 "Re-sort CANDIDATES.
2222 Prefix matches to NAME are put ahead of the list."
2223 (if (or (string-match "^\\^" name) (string= name ""))
2225 (let ((re-prefix (concat "^" (funcall ivy--regex-function name)))
2228 (dolist (s candidates)
2229 (if (string-match re-prefix s)
2231 (push s res-noprefix)))
2233 (nreverse res-prefix)
2234 (nreverse res-noprefix)))))
2236 (defun ivy--recompute-index (name re-str cands)
2237 (let* ((caller (ivy-state-caller ivy-last))
2238 (func (or (and caller (cdr (assoc caller ivy-index-functions-alist)))
2239 (cdr (assoc t ivy-index-functions-alist))
2240 #'ivy-recompute-index-zero)))
2241 (unless (eq this-command 'ivy-resume)
2244 (cl-position (if (and (> (length name) 0)
2245 (eq ?^ (aref name 0)))
2251 (concat re-str "/") cands
2253 (and (not (string= name ""))
2254 (not (and (require 'flx nil 'noerror)
2255 (eq ivy--regex-function 'ivy--regex-fuzzy)
2256 (< (length cands) 200)))
2258 (cl-position (nth ivy--index ivy--old-cands)
2260 (funcall func re-str cands))))
2261 (when (and (or (string= name "")
2263 (not (equal ivy--old-re "")))
2265 (or (ivy--preselect-index
2266 (ivy-state-preselect ivy-last)
2270 (defun ivy-recompute-index-swiper (_re-str cands)
2271 (let ((tail (nthcdr ivy--index ivy--old-cands))
2273 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2275 (while (and tail (null idx))
2276 ;; Compare with eq to handle equal duplicates in cands
2277 (setq idx (cl-position (pop tail) cands)))
2280 (1- (length cands))))
2283 ;; already in ivy-state-buffer
2284 (let ((n (line-number-at-pos))
2288 (when (eq n (read (get-text-property 0 'display c)))
2293 (defun ivy-recompute-index-swiper-async (_re-str cands)
2294 (if (null ivy--old-cands)
2295 (let ((ln (with-ivy-window
2296 (line-number-at-pos))))
2298 ;; closest to current line going forwards
2299 (cl-position-if (lambda (x)
2300 (>= (string-to-number x) ln))
2302 ;; closest to current line going backwards
2303 (1- (length cands))))
2304 (let ((tail (nthcdr ivy--index ivy--old-cands))
2306 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2308 (while (and tail (null idx))
2309 ;; Compare with `equal', since the collection is re-created
2310 ;; each time with `split-string'
2311 (setq idx (cl-position (pop tail) cands :test #'equal)))
2315 (defun ivy-recompute-index-zero (_re-str _cands)
2318 (defcustom ivy-minibuffer-faces
2319 '(ivy-minibuffer-match-face-1
2320 ivy-minibuffer-match-face-2
2321 ivy-minibuffer-match-face-3
2322 ivy-minibuffer-match-face-4)
2323 "List of `ivy' faces for minibuffer group matches."
2324 :type '(repeat :tag "Faces"
2326 (const ivy-minibuffer-match-face-1)
2327 (const ivy-minibuffer-match-face-2)
2328 (const ivy-minibuffer-match-face-3)
2329 (const ivy-minibuffer-match-face-4)
2330 (face :tag "Other face"))))
2332 (defvar ivy-flx-limit 200
2333 "Used to conditionally turn off flx sorting.
2335 When the amount of matching candidates exceeds this limit, then
2336 no sorting is done.")
2338 (defun ivy--flx-sort (name cands)
2339 "Sort according to closeness to string NAME the string list CANDS."
2342 (< (length cands) ivy-flx-limit))
2343 (let* ((flx-name (if (string-match "^\\^" name)
2350 (let ((score (flx-score x flx-name ivy--flx-cache)))
2354 (if cands-with-score
2356 (let ((str (copy-sequence (cdr x)))
2359 (dolist (j (cdar x))
2360 (unless (eq j (1+ last-j))
2363 (ivy-add-face-text-property
2365 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2366 ivy-minibuffer-faces)
2369 (sort cands-with-score
2371 (> (caar x) (caar y)))))
2377 (defcustom ivy-format-function 'ivy-format-function-default
2378 "Function to transform the list of candidates into a string.
2379 This string is inserted into the minibuffer."
2381 (const :tag "Default" ivy-format-function-default)
2382 (const :tag "Arrow prefix" ivy-format-function-arrow)
2383 (const :tag "Full line" ivy-format-function-line)))
2385 (defun ivy--truncate-string (str width)
2386 "Truncate STR to WIDTH."
2387 (if (> (string-width str) width)
2388 (concat (substring str 0 (min (- width 3)
2389 (- (length str) 3))) "...")
2392 (defun ivy--format-function-generic (selected-fn other-fn strs separator)
2393 "Transform CAND-PAIRS into a string for minibuffer.
2394 SELECTED-FN and OTHER-FN each take one string argument.
2395 SEPARATOR is used to join the candidates."
2399 (let ((curr (eq (cl-incf i) ivy--index)))
2401 (funcall selected-fn str)
2402 (funcall other-fn str))))
2406 (defun ivy-format-function-default (cands)
2407 "Transform CAND-PAIRS into a string for minibuffer."
2408 (ivy--format-function-generic
2410 (ivy--add-face str 'ivy-current-match))
2415 (defun ivy-format-function-arrow (cands)
2416 "Transform CAND-PAIRS into a string for minibuffer."
2417 (ivy--format-function-generic
2419 (concat "> " (ivy--add-face str 'ivy-current-match)))
2425 (defun ivy-format-function-line (cands)
2426 "Transform CAND-PAIRS into a string for minibuffer."
2427 (ivy--format-function-generic
2429 (ivy--add-face (concat str "\n") 'ivy-current-match))
2435 (defun ivy-add-face-text-property (start end face str)
2436 (if (fboundp 'add-face-text-property)
2437 (add-face-text-property
2438 start end face nil str)
2439 (font-lock-append-text-property
2440 start end 'face face str)))
2442 (defun ivy--format-minibuffer-line (str)
2444 (if (and (memq (ivy-state-caller ivy-last)
2445 '(counsel-git-grep counsel-ag counsel-pt))
2446 (string-match "^[^:]+:[^:]+:" str))
2449 (str (copy-sequence str)))
2450 (cond ((eq ivy--regex-function 'ivy--regex-ignore-order)
2451 (when (consp ivy--old-re)
2453 (dolist (re ivy--old-re)
2454 (when (string-match (car re) str)
2455 (ivy-add-face-text-property
2456 (match-beginning 0) (match-end 0)
2457 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2458 ivy-minibuffer-faces)
2461 ((and (eq ivy-display-style 'fancy)
2462 (not (eq ivy--regex-function 'ivy--regex-fuzzy)))
2464 (setq ivy--old-re (funcall ivy--regex-function ivy-text)))
2466 (while (and (string-match ivy--old-re str start)
2467 (> (- (match-end 0) (match-beginning 0)) 0))
2468 (setq start (match-end 0))
2470 (while (<= i ivy--subexps)
2472 (cond ((zerop ivy--subexps)
2473 (cadr ivy-minibuffer-faces))
2475 (car ivy-minibuffer-faces))
2477 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2478 ivy-minibuffer-faces)))))
2479 (ivy-add-face-text-property
2480 (match-beginning i) (match-end i)
2485 (ivy-set-display-transformer
2486 'counsel-find-file 'ivy-read-file-transformer)
2487 (ivy-set-display-transformer
2488 'read-file-name-internal 'ivy-read-file-transformer)
2490 (defun ivy-read-file-transformer (str)
2491 (if (string-match-p "/\\'" str)
2492 (propertize str 'face 'ivy-subdir)
2495 (defun ivy--format (cands)
2496 "Return a string for CANDS suitable for display in the minibuffer.
2497 CANDS is a list of strings."
2498 (setq ivy--length (length cands))
2499 (when (>= ivy--index ivy--length)
2500 (setq ivy--index (max (1- ivy--length) 0)))
2502 (setq ivy--current "")
2503 (let* ((half-height (/ ivy-height 2))
2504 (start (max 0 (- ivy--index half-height)))
2505 (end (min (+ start (1- ivy-height)) ivy--length))
2506 (start (max 0 (min start (- end (1- ivy-height)))))
2507 (cands (cl-subseq cands start end))
2508 (index (- ivy--index start))
2510 (setq ivy--current (copy-sequence (nth index cands)))
2511 (when (setq transformer-fn (ivy-state-display-transformer-fn ivy-last))
2513 (setq cands (mapcar transformer-fn cands))))
2514 (let* ((ivy--index index)
2516 #'ivy--format-minibuffer-line
2518 (res (concat "\n" (funcall ivy-format-function cands))))
2519 (put-text-property 0 (length res) 'read-only nil res)
2522 (defvar ivy--virtual-buffers nil
2523 "Store the virtual buffers alist.")
2525 (defvar recentf-list)
2527 (defcustom ivy-virtual-abbreviate 'name
2528 "The mode of abbreviation for virtual buffer names."
2530 (const :tag "Only name" name)
2531 (const :tag "Full path" full)
2532 ;; eventually, uniquify
2535 (defun ivy--virtual-buffers ()
2536 "Adapted from `ido-add-virtual-buffers-to-list'."
2537 (unless recentf-mode
2539 (let ((bookmarks (and (boundp 'bookmark-alist)
2541 virtual-buffers name)
2542 (dolist (head (append
2544 (delete " - no file -"
2545 (delq nil (mapcar (lambda (bookmark)
2546 (cdr (assoc 'filename bookmark)))
2549 (if (eq ivy-virtual-abbreviate 'name)
2550 (file-name-nondirectory head)
2551 (expand-file-name head)))
2552 (when (equal name "")
2553 (setq name (file-name-nondirectory (directory-file-name head))))
2554 (when (equal name "")
2556 (and (not (equal name ""))
2557 (null (get-file-buffer head))
2558 (not (assoc name virtual-buffers))
2559 (push (cons name head) virtual-buffers)))
2560 (when virtual-buffers
2561 (dolist (comp virtual-buffers)
2562 (put-text-property 0 (length (car comp))
2565 (setq ivy--virtual-buffers (nreverse virtual-buffers))
2566 (mapcar #'car ivy--virtual-buffers))))
2568 (defcustom ivy-ignore-buffers '("\\` ")
2569 "List of regexps or functions matching buffer names to ignore."
2570 :type '(repeat (choice regexp function)))
2572 (defun ivy--buffer-list (str &optional virtual predicate)
2573 "Return the buffers that match STR.
2574 When VIRTUAL is non-nil, add virtual buffers."
2579 (if (with-current-buffer x
2581 (abbreviate-file-name default-directory)))
2582 (propertize x 'face 'ivy-remote)
2584 (all-completions str 'internal-complete-buffer predicate))
2586 (ivy--virtual-buffers)))))
2588 (defvar ivy-views (and nil
2589 `(("ivy + *scratch* {}"
2591 (file ,(expand-file-name "ivy.el"))
2592 (buffer "*scratch*")))
2593 ("swiper + *scratch* {}"
2595 (file ,(expand-file-name "swiper.el"))
2596 (buffer "*scratch*")))))
2597 "Store window configurations selectable by `ivy-switch-buffer'.
2599 The default value is given as an example.
2601 Each element is a list of (NAME TREE). NAME is a string, it's
2602 recommended to end it with a distinctive snippet e.g. \"{}\" so
2603 that it's easy to distinguish the window configurations.
2605 TREE is a nested list with the following valid cars:
2606 - vert: split the window vertically
2607 - horz: split the window horizontally
2608 - file: open the specified file
2609 - buffer: open the specified buffer
2611 TREE can be nested multiple times to have mulitple window splits.")
2613 (defun ivy-source-views ()
2614 (mapcar #'car ivy-views))
2619 (ivy-source-views)))
2621 (defun ivy-set-view-recur (view)
2622 (cond ((eq (car view) 'vert)
2623 (let ((wnd1 (selected-window))
2624 (wnd2 (split-window-vertically)))
2625 (with-selected-window wnd1
2626 (ivy-set-view-recur (nth 1 view)))
2627 (with-selected-window wnd2
2628 (ivy-set-view-recur (nth 2 view)))))
2629 ((eq (car view) 'horz)
2630 (let ((wnd1 (selected-window))
2631 (wnd2 (split-window-horizontally)))
2632 (with-selected-window wnd1
2633 (ivy-set-view-recur (nth 1 view)))
2634 (with-selected-window wnd2
2635 (ivy-set-view-recur (nth 2 view)))))
2636 ((eq (car view) 'file)
2637 (let* ((name (cadr view))
2638 (virtual (assoc name ivy--virtual-buffers))
2640 (cond ((setq buffer (get-buffer name))
2641 (switch-to-buffer buffer nil 'force-same-window))
2643 (find-file (cdr virtual)))
2644 ((file-exists-p name)
2645 (find-file name)))))
2646 ((eq (car view) 'buffer)
2647 (switch-to-buffer (cadr view)))
2648 ((eq (car view) 'sexp)
2649 (eval (cadr view)))))
2651 (defun ivy--switch-buffer-action (buffer)
2653 BUFFER may be a string or nil."
2655 (if (zerop (length buffer))
2657 ivy-text nil 'force-same-window)
2658 (let ((virtual (assoc buffer ivy--virtual-buffers))
2659 (view (assoc buffer ivy-views)))
2661 (not (get-buffer buffer)))
2662 (find-file (cdr virtual)))
2664 (delete-other-windows)
2665 (ivy-set-view-recur (cadr view)))
2668 buffer nil 'force-same-window)))))))
2670 (defun ivy--switch-buffer-other-window-action (buffer)
2671 "Switch to BUFFER in other window.
2672 BUFFER may be a string or nil."
2673 (if (zerop (length buffer))
2674 (switch-to-buffer-other-window ivy-text)
2675 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2677 (not (get-buffer buffer)))
2678 (find-file-other-window (cdr virtual))
2679 (switch-to-buffer-other-window buffer)))))
2681 (defun ivy--rename-buffer-action (buffer)
2683 (let ((new-name (read-string "Rename buffer (to new name): ")))
2684 (with-current-buffer buffer
2685 (rename-buffer new-name))))
2687 (defvar ivy-switch-buffer-map (make-sparse-keymap))
2694 (ivy--reset-state ivy-last))
2697 ivy--switch-buffer-other-window-action
2700 ivy--rename-buffer-action
2703 (defun ivy--switch-buffer-matcher (regexp candidates)
2704 "Return REGEXP-matching CANDIDATES.
2705 Skip buffers that match `ivy-ignore-buffers'."
2706 (let ((res (ivy--re-filter regexp candidates)))
2707 (if (or (null ivy-use-ignore)
2708 (null ivy-ignore-buffers))
2714 (if (functionp f-or-r)
2715 (funcall f-or-r buf)
2716 (string-match-p f-or-r buf)))
2717 ivy-ignore-buffers))
2719 (and (eq ivy-use-ignore t)
2722 (ivy-set-display-transformer
2723 'ivy-switch-buffer 'ivy-switch-buffer-transformer)
2724 (ivy-set-display-transformer
2725 'internal-complete-buffer 'ivy-switch-buffer-transformer)
2727 (defun ivy-switch-buffer-transformer (str)
2728 (let ((b (get-buffer str)))
2730 (buffer-file-name b)
2731 (buffer-modified-p b))
2732 (propertize str 'face 'ivy-modified-buffer)
2735 (defun ivy-switch-buffer-occur ()
2736 "Occur function for `ivy-switch-buffer' that uses `ibuffer'."
2738 (concat "\\(" (mapconcat #'regexp-quote ivy--old-cands "\\|") "\\)"))
2739 (new-qualifier `((name . ,cand-regexp))))
2740 (ibuffer nil (buffer-name) new-qualifier)))
2743 (defun ivy-switch-buffer ()
2744 "Switch to another buffer."
2746 (let ((this-command 'ivy-switch-buffer))
2747 (ivy-read "Switch to buffer: " 'internal-complete-buffer
2748 :matcher #'ivy--switch-buffer-matcher
2749 :preselect (buffer-name (other-buffer (current-buffer)))
2750 :action #'ivy--switch-buffer-action
2751 :keymap ivy-switch-buffer-map
2752 :caller 'ivy-switch-buffer)))
2755 (defun ivy-switch-buffer-other-window ()
2756 "Switch to another buffer in another window."
2758 (ivy-read "Switch to buffer in other window: " 'internal-complete-buffer
2759 :preselect (buffer-name (other-buffer (current-buffer)))
2760 :action #'ivy--switch-buffer-other-window-action
2761 :keymap ivy-switch-buffer-map
2762 :caller 'ivy-switch-buffer-other-window))
2765 (defun ivy-recentf ()
2766 "Find a file on `recentf-list'."
2768 (ivy-read "Recentf: " recentf-list
2773 :caller 'ivy-recentf))
2775 (defun ivy-yank-word ()
2776 "Pull next word from buffer into search string."
2781 (le (line-end-position)))
2785 (setq amend (buffer-substring-no-properties pt (point))))))
2787 (insert (replace-regexp-in-string " +" " " amend)))))
2789 (defun ivy-kill-ring-save ()
2790 "Store the current candidates into the kill ring.
2791 If the region is active, forward to `kill-ring-save' instead."
2793 (if (region-active-p)
2794 (call-interactively 'kill-ring-save)
2801 (defun ivy-insert-current ()
2802 "Make the current candidate into current input.
2803 Don't finish completion."
2805 (delete-minibuffer-contents)
2806 (if (and ivy--directory
2807 (string-match "/$" ivy--current))
2808 (insert (substring ivy--current 0 -1))
2809 (insert ivy--current)))
2811 (defun ivy-toggle-fuzzy ()
2812 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
2814 (setq ivy--old-re nil)
2815 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
2816 (setq ivy--regex-function 'ivy--regex-plus)
2817 (setq ivy--regex-function 'ivy--regex-fuzzy)))
2819 (defun ivy-reverse-i-search ()
2820 "Enter a recursive `ivy-read' session using the current history.
2821 The selected history element will be inserted into the minibuffer."
2823 (let ((enable-recursive-minibuffers t)
2824 (history (symbol-value (ivy-state-history ivy-last)))
2826 (ivy-recursive-restore nil))
2827 (ivy-read "Reverse-i-search: "
2831 (setq ivy-last old-last))
2832 (delete-minibuffer-contents)
2833 (insert (substring-no-properties x))
2836 (defun ivy-restrict-to-matches ()
2837 "Restrict candidates to current matches and erase input."
2839 (delete-minibuffer-contents)
2840 (setq ivy--all-candidates
2841 (ivy--filter ivy-text ivy--all-candidates)))
2844 (defvar-local ivy-occur-last nil
2845 "Buffer-local value of `ivy-last'.
2846 Can't re-use `ivy-last' because using e.g. `swiper' in the same
2847 buffer would modify `ivy-last'.")
2849 (defvar ivy-occur-mode-map
2850 (let ((map (make-sparse-keymap)))
2851 (define-key map [mouse-1] 'ivy-occur-click)
2852 (define-key map (kbd "RET") 'ivy-occur-press)
2853 (define-key map (kbd "j") 'ivy-occur-next-line)
2854 (define-key map (kbd "k") 'ivy-occur-previous-line)
2855 (define-key map (kbd "h") 'backward-char)
2856 (define-key map (kbd "l") 'forward-char)
2857 (define-key map (kbd "f") 'ivy-occur-press)
2858 (define-key map (kbd "g") 'ivy-occur-revert-buffer)
2859 (define-key map (kbd "a") 'ivy-occur-read-action)
2860 (define-key map (kbd "o") 'ivy-occur-dispatch)
2861 (define-key map (kbd "c") 'ivy-occur-toggle-calling)
2862 (define-key map (kbd "q") 'quit-window)
2864 "Keymap for Ivy Occur mode.")
2866 (defun ivy-occur-toggle-calling ()
2867 "Toggle `ivy-calling'."
2869 (if (setq ivy-calling (not ivy-calling))
2871 (setq mode-name "Ivy-Occur [calling]")
2873 (setq mode-name "Ivy-Occur"))
2874 (force-mode-line-update))
2876 (defun ivy-occur-next-line (&optional arg)
2877 "Move the cursor down ARG lines.
2878 When `ivy-calling' isn't nil, call `ivy-occur-press'."
2884 (defun ivy-occur-previous-line (&optional arg)
2885 "Move the cursor up ARG lines.
2886 When `ivy-calling' isn't nil, call `ivy-occur-press'."
2888 (forward-line (- arg))
2892 (define-derived-mode ivy-occur-mode fundamental-mode "Ivy-Occur"
2893 "Major mode for output from \\[ivy-occur].
2895 \\{ivy-occur-mode-map}")
2897 (defvar ivy-occur-grep-mode-map
2898 (let ((map (copy-keymap ivy-occur-mode-map)))
2899 (define-key map (kbd "C-x C-q") 'ivy-wgrep-change-to-wgrep-mode)
2901 "Keymap for Ivy Occur Grep mode.")
2903 (define-derived-mode ivy-occur-grep-mode grep-mode "Ivy-Occur"
2904 "Major mode for output from \\[ivy-occur].
2906 \\{ivy-occur-grep-mode-map}")
2908 (defvar ivy--occurs-list nil
2909 "A list of custom occur generators per command.")
2911 (defun ivy-set-occur (cmd occur)
2912 "Assign CMD a custom OCCUR function."
2913 (setq ivy--occurs-list
2914 (plist-put ivy--occurs-list cmd occur)))
2916 (ivy-set-occur 'ivy-switch-buffer 'ivy-switch-buffer-occur)
2917 (ivy-set-occur 'ivy-switch-buffer-other-window 'ivy-switch-buffer-occur)
2919 (defun ivy--occur-insert-lines (cands)
2921 (add-text-properties
2925 help-echo "mouse-1: call ivy-action")
2930 "Stop completion and put the current matches into a new buffer.
2932 The new buffer remembers current action(s).
2934 While in the *ivy-occur* buffer, selecting a candidate with RET or
2935 a mouse click will call the appropriate action for that candidate.
2937 There is no limit on the number of *ivy-occur* buffers."
2939 (if (not (window-minibuffer-p))
2940 (user-error "No completion session is active")
2941 (let* ((caller (ivy-state-caller ivy-last))
2942 (occur-fn (plist-get ivy--occurs-list caller))
2944 (generate-new-buffer
2945 (format "*ivy-occur%s \"%s\"*"
2947 (concat " " (prin1-to-string caller))
2950 (with-current-buffer buffer
2951 (let ((inhibit-read-only t))
2956 (insert (format "%d candidates:\n" (length ivy--old-cands)))
2957 (ivy--occur-insert-lines
2959 (lambda (cand) (concat " " cand))
2961 (setf (ivy-state-text ivy-last) ivy-text)
2962 (setq ivy-occur-last ivy-last)
2963 (setq-local ivy--directory ivy--directory))
2964 (ivy-exit-with-action
2965 `(lambda (_) (pop-to-buffer ,buffer))))))
2967 (defun ivy-occur-revert-buffer ()
2968 "Refresh the buffer making it up-to date with the collection.
2970 Currently only works for `swiper'. In that specific case, the
2971 *ivy-occur* buffer becomes nearly useless as the orignal buffer
2972 is updated, since the line numbers no longer match.
2974 Calling this function is as if you called `ivy-occur' on the
2975 updated original buffer."
2977 (let ((caller (ivy-state-caller ivy-occur-last))
2978 (ivy-last ivy-occur-last))
2979 (cond ((eq caller 'swiper)
2980 (let ((buffer (ivy-state-buffer ivy-occur-last)))
2981 (unless (buffer-live-p buffer)
2982 (error "buffer was killed"))
2983 (let ((inhibit-read-only t))
2985 (funcall (plist-get ivy--occurs-list caller) t))))
2986 ((memq caller '(counsel-git-grep counsel-grep counsel-ag))
2987 (let ((inhibit-read-only t))
2989 (funcall (plist-get ivy--occurs-list caller)))))))
2991 (declare-function wgrep-change-to-wgrep-mode "ext:wgrep")
2993 (defun ivy-wgrep-change-to-wgrep-mode ()
2994 "Forward to `wgrep-change-to-wgrep-mode'."
2996 (if (require 'wgrep nil 'noerror)
2997 (wgrep-change-to-wgrep-mode)
2998 (error "Package wgrep isn't installed")))
3000 (defun ivy-occur-read-action ()
3001 "Select one of the available actions as the current one."
3003 (let ((ivy-last ivy-occur-last))
3006 (defun ivy-occur-dispatch ()
3007 "Call one of the available actions on the current item."
3009 (let* ((state-action (ivy-state-action ivy-occur-last))
3010 (actions (if (symbolp state-action)
3012 (copy-sequence state-action))))
3015 (ivy-occur-read-action)
3017 (setf (ivy-state-action ivy-occur-last) actions))))
3019 (defun ivy-occur-click (event)
3020 "Execute action for the current candidate.
3021 EVENT gives the mouse position."
3023 (let ((window (posn-window (event-end event)))
3024 (pos (posn-point (event-end event))))
3025 (with-current-buffer (window-buffer window)
3027 (ivy-occur-press))))
3029 (declare-function swiper--cleanup "swiper")
3030 (declare-function swiper--add-overlays "swiper")
3031 (defvar ivy-occur-timer nil)
3032 (defvar counsel-grep-last-line)
3034 (defun ivy-occur-press ()
3035 "Execute action for the current candidate."
3037 (when (save-excursion
3039 (looking-at "\\(?:./\\| \\)\\(.*\\)$"))
3040 (when (memq (ivy-state-caller ivy-occur-last)
3041 '(swiper counsel-git-grep counsel-grep counsel-ag
3042 counsel-describe-function counsel-describe-variable))
3043 (let ((window (ivy-state-window ivy-occur-last)))
3044 (when (or (null (window-live-p window))
3045 (equal window (selected-window)))
3046 (save-selected-window
3047 (setf (ivy-state-window ivy-occur-last)
3048 (display-buffer (ivy-state-buffer ivy-occur-last)
3049 'display-buffer-pop-up-window))))))
3050 (let* ((ivy-last ivy-occur-last)
3051 (ivy-text (ivy-state-text ivy-last))
3052 (str (buffer-substring
3055 (coll (ivy-state-collection ivy-last))
3056 (action (ivy--get-action ivy-last))
3059 (setq counsel-grep-last-line nil)
3061 (if (and (consp coll)
3063 (cdr (assoc str coll))
3065 (if (memq (ivy-state-caller ivy-last)
3066 '(swiper counsel-git-grep counsel-grep))
3067 (with-current-buffer (window-buffer (selected-window))
3069 (swiper--add-overlays
3070 (ivy--regex ivy-text)
3071 (line-beginning-position)
3074 (when (timerp ivy-occur-timer)
3075 (cancel-timer ivy-occur-timer))
3076 (setq ivy-occur-timer (run-at-time 1.0 nil 'swiper--cleanup))))))))
3078 (defvar ivy-help-file (let ((default-directory
3080 (file-name-directory load-file-name)
3081 default-directory)))
3082 (if (file-exists-p "ivy-help.org")
3083 (expand-file-name "ivy-help.org")
3084 (if (file-exists-p "doc/ivy-help.org")
3085 (expand-file-name "doc/ivy-help.org"))))
3086 "The file for `ivy-help'.")
3091 (let ((buf (get-buffer "*Ivy Help*")))
3093 (setq buf (get-buffer-create "*Ivy Help*"))
3094 (with-current-buffer buf
3095 (insert-file-contents ivy-help-file)
3098 (goto-char (point-min))))
3099 (if (eq this-command 'ivy-help)
3100 (switch-to-buffer buf)
3102 (pop-to-buffer buf)))
3104 (goto-char (point-min))))
3108 ;;; ivy.el ends here