]> code.delx.au - gnu-emacs-elpa/blob - ivy.el
ivy.el (ivy-ffap-url-functions): Customize "C-x C-f M-n"
[gnu-emacs-elpa] / ivy.el
1 ;;; ivy.el --- Incremental Vertical completYon -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2015 Free Software Foundation, Inc.
4
5 ;; Author: Oleh Krehel <ohwoeowho@gmail.com>
6 ;; URL: https://github.com/abo-abo/swiper
7 ;; Package-Requires: ((emacs "24.1"))
8 ;; Keywords: matching
9
10 ;; This file is part of GNU Emacs.
11
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)
15 ;; any later version.
16
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.
21
22 ;; For a full copy of the GNU General Public License
23 ;; see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26 ;;
27 ;; This package provides `ivy-read' as an alternative to
28 ;; `completing-read' and similar functions.
29 ;;
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'.
33 ;;
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\\)".
37
38 ;;; Code:
39 (require 'cl-lib)
40 (require 'ffap)
41
42 ;;* Customization
43 (defgroup ivy nil
44 "Incremental vertical completion."
45 :group 'convenience)
46
47 (defgroup ivy-faces nil
48 "Font-lock faces for `ivy'."
49 :group 'ivy)
50
51 (defface ivy-current-match
52 '((((class color) (background light))
53 :background "#1a4b77" :foreground "white")
54 (((class color) (background dark))
55 :background "#65a7e2" :foreground "black"))
56 "Face used by Ivy for highlighting the current match.")
57
58 (defface ivy-minibuffer-match-face-1
59 '((((class color) (background light))
60 :background "#d3d3d3")
61 (((class color) (background dark))
62 :background "#555555"))
63 "The background face for `ivy' minibuffer matches.")
64
65 (defface ivy-minibuffer-match-face-2
66 '((((class color) (background light))
67 :background "#e99ce8" :weight bold)
68 (((class color) (background dark))
69 :background "#777777" :weight bold))
70 "Face for `ivy' minibuffer matches modulo 1.")
71
72 (defface ivy-minibuffer-match-face-3
73 '((((class color) (background light))
74 :background "#bbbbff" :weight bold)
75 (((class color) (background dark))
76 :background "#7777ff" :weight bold))
77 "Face for `ivy' minibuffer matches modulo 2.")
78
79 (defface ivy-minibuffer-match-face-4
80 '((((class color) (background light))
81 :background "#ffbbff" :weight bold)
82 (((class color) (background dark))
83 :background "#8a498a" :weight bold))
84 "Face for `ivy' minibuffer matches modulo 3.")
85
86 (defface ivy-confirm-face
87 '((t :foreground "ForestGreen" :inherit minibuffer-prompt))
88 "Face used by Ivy for a confirmation prompt.")
89
90 (defface ivy-match-required-face
91 '((t :foreground "red" :inherit minibuffer-prompt))
92 "Face used by Ivy for a match required prompt.")
93
94 (setcdr (assoc load-file-name custom-current-group-alist) 'ivy)
95
96 (defface ivy-subdir
97 '((t (:inherit 'dired-directory)))
98 "Face used by Ivy for highlighting subdirs in the alternatives.")
99
100 (defface ivy-modified-buffer
101 '((t :inherit 'default))
102 "Face used by Ivy for highlighting modified file visiting buffers.")
103
104 (defface ivy-remote
105 '((t (:foreground "#110099")))
106 "Face used by Ivy for highlighting remotes in the alternatives.")
107
108 (defface ivy-virtual
109 '((t :inherit font-lock-builtin-face))
110 "Face used by Ivy for matching virtual buffer names.")
111
112 (defcustom ivy-height 10
113 "Number of lines for the minibuffer window."
114 :type 'integer)
115
116 (defcustom ivy-count-format "%-4d "
117 "The style to use for displaying the current candidate count for `ivy-read'.
118 Set this to \"\" to suppress the count visibility.
119 Set this to \"(%d/%d) \" to display both the index and the count."
120 :type '(choice
121 (const :tag "Count disabled" "")
122 (const :tag "Count matches" "%-4d ")
123 (const :tag "Count matches and show current match" "(%d/%d) ")
124 string))
125
126 (defcustom ivy-wrap nil
127 "When non-nil, wrap around after the first and the last candidate."
128 :type 'boolean)
129
130 (defcustom ivy-display-style (unless (version< emacs-version "24.5") 'fancy)
131 "The style for formatting the minibuffer.
132
133 By default, the matched strings are copied as is.
134
135 The fancy display style highlights matching parts of the regexp,
136 a behavior similar to `swiper'.
137
138 This setting depends on `add-face-text-property' - a C function
139 available as of Emacs 24.5. Fancy style will render poorly in
140 earlier versions of Emacs."
141 :type '(choice
142 (const :tag "Plain" nil)
143 (const :tag "Fancy" fancy)))
144
145 (defcustom ivy-on-del-error-function 'minibuffer-keyboard-quit
146 "The handler for when `ivy-backward-delete-char' throws.
147 Usually a quick exit out of the minibuffer."
148 :type 'function)
149
150 (defcustom ivy-extra-directories '("../" "./")
151 "Add this to the front of the list when completing file names.
152 Only \"./\" and \"../\" apply here. They appear in reverse order."
153 :type '(repeat :tag "Dirs"
154 (choice
155 (const :tag "Parent Directory" "../")
156 (const :tag "Current Directory" "./"))))
157
158 (defcustom ivy-use-virtual-buffers nil
159 "When non-nil, add `recentf-mode' and bookmarks to `ivy-switch-buffer'."
160 :type 'boolean)
161
162 (defvar ivy--actions-list nil
163 "A list of extra actions per command.")
164
165 (defun ivy-set-actions (cmd actions)
166 "Set CMD extra exit points to ACTIONS."
167 (setq ivy--actions-list
168 (plist-put ivy--actions-list cmd actions)))
169
170 ;;* Keymap
171 (require 'delsel)
172 (defvar ivy-minibuffer-map
173 (let ((map (make-sparse-keymap)))
174 (define-key map (kbd "C-m") 'ivy-done)
175 (define-key map (kbd "C-M-m") 'ivy-call)
176 (define-key map (kbd "C-j") 'ivy-alt-done)
177 (define-key map (kbd "C-M-j") 'ivy-immediate-done)
178 (define-key map (kbd "TAB") 'ivy-partial-or-done)
179 (define-key map (kbd "C-n") 'ivy-next-line)
180 (define-key map (kbd "C-p") 'ivy-previous-line)
181 (define-key map (kbd "<down>") 'ivy-next-line)
182 (define-key map (kbd "<up>") 'ivy-previous-line)
183 (define-key map (kbd "C-s") 'ivy-next-line-or-history)
184 (define-key map (kbd "C-r") 'ivy-reverse-i-search)
185 (define-key map (kbd "SPC") 'self-insert-command)
186 (define-key map (kbd "DEL") 'ivy-backward-delete-char)
187 (define-key map (kbd "M-DEL") 'ivy-backward-kill-word)
188 (define-key map (kbd "C-d") 'ivy-delete-char)
189 (define-key map (kbd "C-f") 'ivy-forward-char)
190 (define-key map (kbd "M-d") 'ivy-kill-word)
191 (define-key map (kbd "M-<") 'ivy-beginning-of-buffer)
192 (define-key map (kbd "M->") 'ivy-end-of-buffer)
193 (define-key map (kbd "M-n") 'ivy-next-history-element)
194 (define-key map (kbd "M-p") 'ivy-previous-history-element)
195 (define-key map (kbd "C-g") 'minibuffer-keyboard-quit)
196 (define-key map (kbd "C-v") 'ivy-scroll-up-command)
197 (define-key map (kbd "M-v") 'ivy-scroll-down-command)
198 (define-key map (kbd "C-M-n") 'ivy-next-line-and-call)
199 (define-key map (kbd "C-M-p") 'ivy-previous-line-and-call)
200 (define-key map (kbd "M-q") 'ivy-toggle-regexp-quote)
201 (define-key map (kbd "M-j") 'ivy-yank-word)
202 (define-key map (kbd "M-i") 'ivy-insert-current)
203 (define-key map (kbd "C-o") 'hydra-ivy/body)
204 (define-key map (kbd "M-o") 'ivy-dispatching-done)
205 (define-key map (kbd "C-M-o") 'ivy-dispatching-call)
206 (define-key map (kbd "C-k") 'ivy-kill-line)
207 (define-key map (kbd "S-SPC") 'ivy-restrict-to-matches)
208 (define-key map (kbd "M-w") 'ivy-kill-ring-save)
209 (define-key map (kbd "C-'") 'ivy-avy)
210 (define-key map (kbd "C-M-a") 'ivy-read-action)
211 (define-key map (kbd "C-c C-o") 'ivy-occur)
212 map)
213 "Keymap used in the minibuffer.")
214 (autoload 'hydra-ivy/body "ivy-hydra" "" t)
215
216 (defvar ivy-mode-map
217 (let ((map (make-sparse-keymap)))
218 (define-key map [remap switch-to-buffer] 'ivy-switch-buffer)
219 map)
220 "Keymap for `ivy-mode'.")
221
222 ;;* Globals
223 (cl-defstruct ivy-state
224 prompt collection
225 predicate require-match initial-input
226 history preselect keymap update-fn sort
227 ;; The window in which `ivy-read' was called
228 window
229 ;; The buffer in which `ivy-read' was called
230 buffer
231 ;; The value of `ivy-text' to be used by `ivy-occur'
232 text
233 action
234 unwind
235 re-builder
236 matcher
237 ;; When this is non-nil, call it for each input change to get new candidates
238 dynamic-collection
239 caller)
240
241 (defvar ivy-last (make-ivy-state)
242 "The last parameters passed to `ivy-read'.
243
244 This should eventually become a stack so that you could use
245 `ivy-read' recursively.")
246
247 (defsubst ivy-set-action (action)
248 (setf (ivy-state-action ivy-last) action))
249
250 (defvar ivy-history nil
251 "History list of candidates entered in the minibuffer.
252
253 Maximum length of the history list is determined by the value
254 of `history-length'.")
255
256 (defvar ivy--directory nil
257 "Current directory when completing file names.")
258
259 (defvar ivy--length 0
260 "Store the amount of viable candidates.")
261
262 (defvar ivy-text ""
263 "Store the user's string as it is typed in.")
264
265 (defvar ivy--current ""
266 "Current candidate.")
267
268 (defvar ivy--index 0
269 "Store the index of the current candidate.")
270
271 (defvar ivy-exit nil
272 "Store 'done if the completion was successfully selected.
273 Otherwise, store nil.")
274
275 (defvar ivy--all-candidates nil
276 "Store the candidates passed to `ivy-read'.")
277
278 (defvar ivy--default nil
279 "Default initial input.")
280
281 (defvar ivy--prompt nil
282 "Store the format-style prompt.
283 When non-nil, it should contain at least one %d.")
284
285 (defvar ivy--prompt-extra ""
286 "Temporary modifications to the prompt.")
287
288 (defvar ivy--old-re nil
289 "Store the old regexp.")
290
291 (defvar ivy--old-cands nil
292 "Store the candidates matched by `ivy--old-re'.")
293
294 (defvar ivy--regex-function 'ivy--regex
295 "Current function for building a regex.")
296
297 (defvar ivy--subexps 0
298 "Number of groups in the current `ivy--regex'.")
299
300 (defvar ivy--full-length nil
301 "When :dynamic-collection is non-nil, this can be the total amount of candidates.")
302
303 (defvar ivy--old-text ""
304 "Store old `ivy-text' for dynamic completion.")
305
306 (defvar ivy-case-fold-search 'auto
307 "Store the current overriding `case-fold-search'.")
308
309 (defvar Info-current-file)
310
311 (defmacro ivy-quit-and-run (&rest body)
312 "Quit the minibuffer and run BODY afterwards."
313 `(progn
314 (put 'quit 'error-message "")
315 (run-at-time nil nil
316 (lambda ()
317 (put 'quit 'error-message "Quit")
318 ,@body))
319 (minibuffer-keyboard-quit)))
320
321 (defun ivy-exit-with-action (action)
322 "Quit the minibuffer and call ACTION afterwards."
323 (ivy-set-action
324 `(lambda (x)
325 (funcall ',action x)
326 (ivy-set-action ',(ivy-state-action ivy-last))))
327 (setq ivy-exit 'done)
328 (exit-minibuffer))
329
330 (defmacro with-ivy-window (&rest body)
331 "Execute BODY in the window from which `ivy-read' was called."
332 (declare (indent 0)
333 (debug t))
334 `(with-selected-window (ivy--get-window ivy-last)
335 ,@body))
336
337 (defun ivy--done (text)
338 "Insert TEXT and exit minibuffer."
339 (if (and ivy--directory
340 (not (eq (ivy-state-history ivy-last) 'grep-files-history)))
341 (insert (setq ivy--current (expand-file-name
342 text ivy--directory)))
343 (insert (setq ivy--current text)))
344 (setq ivy-exit 'done)
345 (exit-minibuffer))
346
347 ;;* Commands
348 (defun ivy-done ()
349 "Exit the minibuffer with the selected candidate."
350 (interactive)
351 (delete-minibuffer-contents)
352 (cond ((> ivy--length 0)
353 (ivy--done ivy--current))
354 ((memq (ivy-state-collection ivy-last)
355 '(read-file-name-internal internal-complete-buffer))
356 (if (or (not (eq confirm-nonexistent-file-or-buffer t))
357 (equal " (confirm)" ivy--prompt-extra))
358 (ivy--done ivy-text)
359 (setq ivy--prompt-extra " (confirm)")
360 (insert ivy-text)
361 (ivy--exhibit)))
362 ((memq (ivy-state-require-match ivy-last)
363 '(nil confirm confirm-after-completion))
364 (ivy--done ivy-text))
365 (t
366 (setq ivy--prompt-extra " (match required)")
367 (insert ivy-text)
368 (ivy--exhibit))))
369
370 (defun ivy-read-action ()
371 "Change the action to one of the available ones."
372 (interactive)
373 (let ((actions (ivy-state-action ivy-last)))
374 (unless (null (ivy--actionp actions))
375 (let* ((hint (concat (if (eq this-command 'ivy-read-action)
376 "Select action: "
377 ivy--current)
378 "\n"
379 (mapconcat
380 (lambda (x)
381 (format "%s: %s"
382 (propertize
383 (car x)
384 'face 'font-lock-builtin-face)
385 (nth 2 x)))
386 (cdr actions)
387 "\n")
388 "\n"))
389 (key (string (read-key hint)))
390 (action-idx (cl-position-if
391 (lambda (x) (equal (car x) key))
392 (cdr actions))))
393 (cond ((string= key "\a"))
394 ((null action-idx)
395 (error "%s is not bound" key))
396 (t
397 (message "")
398 (setcar actions (1+ action-idx))
399 (ivy-set-action actions)))))))
400
401 (defun ivy-dispatching-done ()
402 "Select one of the available actions and call `ivy-done'."
403 (interactive)
404 (ivy-read-action)
405 (ivy-done))
406
407 (defun ivy-dispatching-call ()
408 "Select one of the available actions and call `ivy-call'."
409 (interactive)
410 (let ((actions (copy-sequence (ivy-state-action ivy-last))))
411 (unwind-protect
412 (when (ivy-read-action)
413 (ivy-call))
414 (ivy-set-action actions))))
415
416 (defun ivy-build-tramp-name (x)
417 "Reconstruct X into a path.
418 Is is a cons cell, related to `tramp-get-completion-function'."
419 (let ((user (car x))
420 (domain (cadr x)))
421 (if user
422 (concat user "@" domain)
423 domain)))
424
425 (declare-function tramp-get-completion-function "tramp")
426 (declare-function Info-find-node "info")
427
428 (defun ivy-alt-done (&optional arg)
429 "Exit the minibuffer with the selected candidate.
430 When ARG is t, exit with current text, ignoring the candidates."
431 (interactive "P")
432 (cond (arg
433 (ivy-immediate-done))
434 (ivy--directory
435 (ivy--directory-done))
436 ((eq (ivy-state-collection ivy-last) 'Info-read-node-name-1)
437 (if (or (equal ivy--current "(./)")
438 (equal ivy--current "(../)"))
439 (ivy-quit-and-run
440 (ivy-read "Go to file: " 'read-file-name-internal
441 :action (lambda (x)
442 (Info-find-node
443 (expand-file-name x ivy--directory)
444 "Top"))))
445 (ivy-done)))
446 (t
447 (ivy-done))))
448
449 (defun ivy--directory-done ()
450 "Handle exit from the minibuffer when completing file names."
451 (let (dir)
452 (cond
453 ((equal ivy-text "/sudo::")
454 (setq dir (concat ivy-text ivy--directory))
455 (ivy--cd dir)
456 (ivy--exhibit))
457 ((or
458 (and
459 (not (equal ivy-text ""))
460 (ignore-errors
461 (file-directory-p
462 (setq dir
463 (file-name-as-directory
464 (expand-file-name
465 ivy-text ivy--directory))))))
466 (and
467 (not (string= ivy--current "./"))
468 (cl-plusp ivy--length)
469 (ignore-errors
470 (file-directory-p
471 (setq dir (file-name-as-directory
472 (expand-file-name
473 ivy--current ivy--directory)))))))
474 (ivy--cd dir)
475 (ivy--exhibit))
476 ((or (and (equal ivy--directory "/")
477 (string-match "\\`[^/]+:.*:.*\\'" ivy-text))
478 (string-match "\\`/[^/]+:.*:.*\\'" ivy-text))
479 (ivy-done))
480 ((or (and (equal ivy--directory "/")
481 (cond ((string-match
482 "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
483 ivy-text))
484 ((string-match
485 "\\`\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
486 ivy--current)
487 (setq ivy-text ivy--current))))
488 (string-match
489 "\\`/\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
490 ivy-text))
491 (let ((method (match-string 1 ivy-text))
492 (user (match-string 2 ivy-text))
493 (rest (match-string 3 ivy-text))
494 res)
495 (require 'tramp)
496 (dolist (x (tramp-get-completion-function method))
497 (setq res (append res (funcall (car x) (cadr x)))))
498 (setq res (delq nil res))
499 (when user
500 (dolist (x res)
501 (setcar x user)))
502 (setq res (cl-delete-duplicates res :test #'equal))
503 (let* ((old-ivy-last ivy-last)
504 (enable-recursive-minibuffers t)
505 (host (ivy-read "user@host: "
506 (mapcar #'ivy-build-tramp-name res)
507 :initial-input rest)))
508 (setq ivy-last old-ivy-last)
509 (when host
510 (setq ivy--directory "/")
511 (ivy--cd (concat "/" method ":" host ":"))))))
512 (t
513 (ivy-done)))))
514
515 (defcustom ivy-tab-space nil
516 "When non-nil, `ivy-partial-or-done' should insert a space."
517 :type 'boolean)
518
519 (defun ivy-partial-or-done ()
520 "Complete the minibuffer text as much as possible.
521 If the text hasn't changed as a result, forward to `ivy-alt-done'."
522 (interactive)
523 (if (and (eq (ivy-state-collection ivy-last) #'read-file-name-internal)
524 (or (and (equal ivy--directory "/")
525 (string-match "\\`[^/]+:.*\\'" ivy-text))
526 (string-match "\\`/" ivy-text)))
527 (let ((default-directory ivy--directory))
528 (minibuffer-complete)
529 (setq ivy-text (ivy--input))
530 (when (file-directory-p
531 (expand-file-name ivy-text ivy--directory))
532 (ivy--cd (file-name-as-directory
533 (expand-file-name ivy-text ivy--directory)))))
534 (or (ivy-partial)
535 (when (or (eq this-command last-command)
536 (eq ivy--length 1))
537 (ivy-alt-done)))))
538
539 (defun ivy-partial ()
540 "Complete the minibuffer text as much as possible."
541 (interactive)
542 (let* ((parts (or (split-string ivy-text " " t) (list "")))
543 (postfix (car (last parts)))
544 (completion-ignore-case t)
545 (startp (string-match "^\\^" postfix))
546 (new (try-completion (if startp
547 (substring postfix 1)
548 postfix)
549 (mapcar (lambda (str)
550 (let ((i (string-match postfix str)))
551 (when i
552 (substring str i))))
553 ivy--old-cands))))
554 (cond ((eq new t) nil)
555 ((string= new ivy-text) nil)
556 (new
557 (delete-region (minibuffer-prompt-end) (point-max))
558 (setcar (last parts)
559 (if startp
560 (concat "^" new)
561 new))
562 (insert (mapconcat #'identity parts " ")
563 (if ivy-tab-space " " ""))
564 t))))
565
566 (defun ivy-immediate-done ()
567 "Exit the minibuffer with the current input."
568 (interactive)
569 (delete-minibuffer-contents)
570 (insert (setq ivy--current
571 (if ivy--directory
572 (expand-file-name ivy-text ivy--directory)
573 ivy-text)))
574 (setq ivy-exit 'done)
575 (exit-minibuffer))
576
577 ;;;###autoload
578 (defun ivy-resume ()
579 "Resume the last completion session."
580 (interactive)
581 (when (eq (ivy-state-caller ivy-last) 'swiper)
582 (switch-to-buffer (ivy-state-buffer ivy-last)))
583 (with-current-buffer (ivy-state-buffer ivy-last)
584 (ivy-read
585 (ivy-state-prompt ivy-last)
586 (ivy-state-collection ivy-last)
587 :predicate (ivy-state-predicate ivy-last)
588 :require-match (ivy-state-require-match ivy-last)
589 :initial-input ivy-text
590 :history (ivy-state-history ivy-last)
591 :preselect (unless (eq (ivy-state-collection ivy-last)
592 'read-file-name-internal)
593 ivy--current)
594 :keymap (ivy-state-keymap ivy-last)
595 :update-fn (ivy-state-update-fn ivy-last)
596 :sort (ivy-state-sort ivy-last)
597 :action (ivy-state-action ivy-last)
598 :unwind (ivy-state-unwind ivy-last)
599 :re-builder (ivy-state-re-builder ivy-last)
600 :matcher (ivy-state-matcher ivy-last)
601 :dynamic-collection (ivy-state-dynamic-collection ivy-last)
602 :caller (ivy-state-caller ivy-last))))
603
604 (defvar ivy-calling nil
605 "When non-nil, call the current action when `ivy--index' changes.")
606
607 (defun ivy-set-index (index)
608 "Set `ivy--index' to INDEX."
609 (setq ivy--index index)
610 (when ivy-calling
611 (ivy--exhibit)
612 (ivy-call)))
613
614 (defun ivy-beginning-of-buffer ()
615 "Select the first completion candidate."
616 (interactive)
617 (ivy-set-index 0))
618
619 (defun ivy-end-of-buffer ()
620 "Select the last completion candidate."
621 (interactive)
622 (ivy-set-index (1- ivy--length)))
623
624 (defun ivy-scroll-up-command ()
625 "Scroll the candidates upward by the minibuffer height."
626 (interactive)
627 (ivy-set-index (min (1- (+ ivy--index ivy-height))
628 (1- ivy--length))))
629
630 (defun ivy-scroll-down-command ()
631 "Scroll the candidates downward by the minibuffer height."
632 (interactive)
633 (ivy-set-index (max (1+ (- ivy--index ivy-height))
634 0)))
635
636 (defun ivy-minibuffer-grow ()
637 "Grow the minibuffer window by 1 line."
638 (interactive)
639 (setq-local max-mini-window-height
640 (cl-incf ivy-height)))
641
642 (defun ivy-minibuffer-shrink ()
643 "Shrink the minibuffer window by 1 line."
644 (interactive)
645 (unless (<= ivy-height 2)
646 (setq-local max-mini-window-height
647 (cl-decf ivy-height))
648 (window-resize (selected-window) -1)))
649
650 (defun ivy-next-line (&optional arg)
651 "Move cursor vertically down ARG candidates."
652 (interactive "p")
653 (setq arg (or arg 1))
654 (let ((index (+ ivy--index arg)))
655 (if (> index (1- ivy--length))
656 (if ivy-wrap
657 (ivy-beginning-of-buffer)
658 (ivy-set-index (1- ivy--length)))
659 (ivy-set-index index))))
660
661 (defun ivy-next-line-or-history (&optional arg)
662 "Move cursor vertically down ARG candidates.
663 If the input is empty, select the previous history element instead."
664 (interactive "p")
665 (when (string= ivy-text "")
666 (ivy-previous-history-element 1))
667 (ivy-next-line arg))
668
669 (defun ivy-previous-line (&optional arg)
670 "Move cursor vertically up ARG candidates."
671 (interactive "p")
672 (setq arg (or arg 1))
673 (let ((index (- ivy--index arg)))
674 (if (< index 0)
675 (if ivy-wrap
676 (ivy-end-of-buffer)
677 (ivy-set-index 0))
678 (ivy-set-index index))))
679
680 (defun ivy-previous-line-or-history (arg)
681 "Move cursor vertically up ARG candidates.
682 If the input is empty, select the previous history element instead."
683 (interactive "p")
684 (when (string= ivy-text "")
685 (ivy-previous-history-element 1))
686 (ivy-previous-line arg))
687
688 (defun ivy-toggle-calling ()
689 "Flip `ivy-calling'."
690 (interactive)
691 (when (setq ivy-calling (not ivy-calling))
692 (ivy-call)))
693
694 (defun ivy--get-action (state)
695 "Get the action function from STATE."
696 (let ((action (ivy-state-action state)))
697 (when action
698 (if (functionp action)
699 action
700 (cadr (nth (car action) action))))))
701
702 (defun ivy--get-window (state)
703 "Get the window from STATE."
704 (if (ivy-state-p state)
705 (let ((window (ivy-state-window state)))
706 (if (window-live-p window)
707 window
708 (if (= (length (window-list)) 1)
709 (selected-window)
710 (next-window))))
711 (selected-window)))
712
713 (defun ivy--actionp (x)
714 "Return non-nil when X is a list of actions."
715 (and x (listp x) (not (eq (car x) 'closure))))
716
717 (defun ivy-next-action ()
718 "When the current action is a list, scroll it forwards."
719 (interactive)
720 (let ((action (ivy-state-action ivy-last)))
721 (when (ivy--actionp action)
722 (unless (>= (car action) (1- (length action)))
723 (cl-incf (car action))))))
724
725 (defun ivy-prev-action ()
726 "When the current action is a list, scroll it backwards."
727 (interactive)
728 (let ((action (ivy-state-action ivy-last)))
729 (when (ivy--actionp action)
730 (unless (<= (car action) 1)
731 (cl-decf (car action))))))
732
733 (defun ivy-action-name ()
734 "Return the name associated with the current action."
735 (let ((action (ivy-state-action ivy-last)))
736 (if (ivy--actionp action)
737 (format "[%d/%d] %s"
738 (car action)
739 (1- (length action))
740 (nth 2 (nth (car action) action)))
741 "[1/1] default")))
742
743 (defun ivy-call ()
744 "Call the current action without exiting completion."
745 (interactive)
746 (let ((action (ivy--get-action ivy-last)))
747 (when action
748 (let* ((collection (ivy-state-collection ivy-last))
749 (x (if (and (consp collection)
750 (consp (car collection)))
751 (cdr (assoc ivy--current collection))
752 (if (equal ivy--current "")
753 ivy-text
754 ivy--current))))
755 (prog1 (funcall action x)
756 (unless (or (eq ivy-exit 'done)
757 (equal (selected-window)
758 (active-minibuffer-window))
759 (null (active-minibuffer-window)))
760 (select-window (active-minibuffer-window))))))))
761
762 (defun ivy-next-line-and-call (&optional arg)
763 "Move cursor vertically down ARG candidates.
764 Call the permanent action if possible."
765 (interactive "p")
766 (ivy-next-line arg)
767 (ivy--exhibit)
768 (ivy-call))
769
770 (defun ivy-previous-line-and-call (&optional arg)
771 "Move cursor vertically down ARG candidates.
772 Call the permanent action if possible."
773 (interactive "p")
774 (ivy-previous-line arg)
775 (ivy--exhibit)
776 (ivy-call))
777
778 (defun ivy-previous-history-element (arg)
779 "Forward to `previous-history-element' with ARG."
780 (interactive "p")
781 (previous-history-element arg)
782 (ivy--cd-maybe)
783 (move-end-of-line 1)
784 (ivy--maybe-scroll-history))
785
786 (defun ivy-next-history-element (arg)
787 "Forward to `next-history-element' with ARG."
788 (interactive "p")
789 (next-history-element arg)
790 (ivy--cd-maybe)
791 (move-end-of-line 1)
792 (ivy--maybe-scroll-history))
793
794 (defvar ivy-ffap-url-functions nil
795 "List of functions that check if the point is on a URL.")
796
797 (defun ivy--cd-maybe ()
798 "Check if the current input points to a different directory.
799 If so, move to that directory, while keeping only the file name."
800 (when ivy--directory
801 (let ((input (ivy--input))
802 url)
803 (if (setq url (or (ffap-url-p input)
804 (with-ivy-window
805 (cl-reduce
806 (lambda (a b)
807 (or a (funcall b)))
808 ivy-ffap-url-functions
809 :initial-value nil))))
810 (ivy-exit-with-action
811 (lambda (_)
812 (funcall ffap-url-fetcher url)))
813 (setq input (expand-file-name input))
814 (let ((file (file-name-nondirectory input))
815 (dir (expand-file-name (file-name-directory input))))
816 (if (string= dir ivy--directory)
817 (progn
818 (delete-minibuffer-contents)
819 (insert file))
820 (ivy--cd dir)
821 (insert file)))))))
822
823 (defun ivy--maybe-scroll-history ()
824 "If the selected history element has an index, scroll there."
825 (let ((idx (ignore-errors
826 (get-text-property
827 (minibuffer-prompt-end)
828 'ivy-index))))
829 (when idx
830 (ivy--exhibit)
831 (setq ivy--index idx))))
832
833 (defun ivy--cd (dir)
834 "When completing file names, move to directory DIR."
835 (if (null ivy--directory)
836 (error "Unexpected")
837 (setq ivy--old-cands nil)
838 (setq ivy--old-re nil)
839 (setq ivy--index 0)
840 (setq ivy--all-candidates
841 (ivy--sorted-files (setq ivy--directory dir)))
842 (setq ivy-text "")
843 (delete-minibuffer-contents)))
844
845 (defun ivy-backward-delete-char ()
846 "Forward to `backward-delete-char'.
847 On error (read-only), call `ivy-on-del-error-function'."
848 (interactive)
849 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
850 (progn
851 (ivy--cd (file-name-directory
852 (directory-file-name
853 (expand-file-name
854 ivy--directory))))
855 (ivy--exhibit))
856 (condition-case nil
857 (backward-delete-char 1)
858 (error
859 (when ivy-on-del-error-function
860 (funcall ivy-on-del-error-function))))))
861
862 (defun ivy-delete-char (arg)
863 "Forward to `delete-char' ARG."
864 (interactive "p")
865 (unless (= (point) (line-end-position))
866 (delete-char arg)))
867
868 (defun ivy-forward-char (arg)
869 "Forward to `forward-char' ARG."
870 (interactive "p")
871 (unless (= (point) (line-end-position))
872 (forward-char arg)))
873
874 (defun ivy-kill-word (arg)
875 "Forward to `kill-word' ARG."
876 (interactive "p")
877 (unless (= (point) (line-end-position))
878 (kill-word arg)))
879
880 (defun ivy-kill-line ()
881 "Forward to `kill-line'."
882 (interactive)
883 (if (eolp)
884 (kill-region (minibuffer-prompt-end) (point))
885 (kill-line)))
886
887 (defun ivy-backward-kill-word ()
888 "Forward to `backward-kill-word'."
889 (interactive)
890 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
891 (progn
892 (ivy--cd (file-name-directory
893 (directory-file-name
894 (expand-file-name
895 ivy--directory))))
896 (ivy--exhibit))
897 (ignore-errors
898 (let ((pt (point)))
899 (forward-word -1)
900 (delete-region (point) pt)))))
901
902 (defvar ivy--regexp-quote 'regexp-quote
903 "Store the regexp quoting state.")
904
905 (defun ivy-toggle-regexp-quote ()
906 "Toggle the regexp quoting."
907 (interactive)
908 (setq ivy--old-re nil)
909 (cl-rotatef ivy--regex-function ivy--regexp-quote))
910
911 (defvar avy-all-windows)
912 (defvar avy-action)
913 (defvar avy-keys)
914 (defvar avy-keys-alist)
915 (defvar avy-style)
916 (defvar avy-styles-alist)
917 (declare-function avy--process "ext:avy")
918 (declare-function avy--style-fn "ext:avy")
919
920 (eval-after-load 'avy
921 '(add-to-list 'avy-styles-alist '(ivy-avy . pre)))
922
923 (defun ivy-avy ()
924 "Jump to one of the current ivy candidates."
925 (interactive)
926 (unless (require 'avy nil 'noerror)
927 (error "Package avy isn't installed"))
928 (let* ((avy-all-windows nil)
929 (avy-keys (or (cdr (assq 'ivy-avy avy-keys-alist))
930 avy-keys))
931 (avy-style (or (cdr (assq 'ivy-avy
932 avy-styles-alist))
933 avy-style))
934 (candidate
935 (let ((candidates))
936 (save-excursion
937 (save-restriction
938 (narrow-to-region
939 (window-start)
940 (window-end))
941 (goto-char (point-min))
942 (forward-line)
943 (while (< (point) (point-max))
944 (push
945 (cons (point)
946 (selected-window))
947 candidates)
948 (forward-line))))
949 (setq avy-action #'identity)
950 (avy--process
951 (nreverse candidates)
952 (avy--style-fn avy-style)))))
953 (ivy-set-index (- (line-number-at-pos candidate) 2))
954 (ivy--exhibit)
955 (ivy-done)))
956
957 (defun ivy-sort-file-function-default (x y)
958 "Compare two files X and Y.
959 Prioritize directories."
960 (if (get-text-property 0 'dirp x)
961 (if (get-text-property 0 'dirp y)
962 (string< x y)
963 t)
964 (if (get-text-property 0 'dirp y)
965 nil
966 (string< x y))))
967
968 (defcustom ivy-sort-functions-alist
969 '((read-file-name-internal . ivy-sort-file-function-default)
970 (internal-complete-buffer . nil)
971 (counsel-git-grep-function . nil)
972 (Man-goto-section . nil)
973 (org-refile . nil)
974 (t . string-lessp))
975 "An alist of sorting functions for each collection function.
976 Interactive functions that call completion fit in here as well.
977
978 Nil means no sorting, which is useful to turn off the sorting for
979 functions that have candidates in the natural buffer order, like
980 `org-refile' or `Man-goto-section'.
981
982 The entry associated with t is used for all fall-through cases.
983
984 See also `ivy-sort-max-size'."
985 :type
986 '(alist
987 :key-type (choice
988 (const :tag "All other functions" t)
989 (symbol :tag "Function"))
990 :value-type (choice
991 (const :tag "plain sort" string-lessp)
992 (const :tag "file sort" ivy-sort-file-function-default)
993 (const :tag "no sort" nil)))
994 :group 'ivy)
995
996 (defvar ivy-index-functions-alist
997 '((swiper . ivy-recompute-index-swiper)
998 (swiper-multi . ivy-recompute-index-swiper)
999 (counsel-git-grep . ivy-recompute-index-swiper)
1000 (counsel-grep . ivy-recompute-index-swiper-async)
1001 (t . ivy-recompute-index-zero))
1002 "An alist of index recomputing functions for each collection function.
1003 When the input changes, the appropriate function returns an
1004 integer - the index of the matched candidate that should be
1005 selected.")
1006
1007 (defvar ivy-re-builders-alist
1008 '((t . ivy--regex-plus))
1009 "An alist of regex building functions for each collection function.
1010
1011 Each key is (in order of priority):
1012 1. The actual collection function, e.g. `read-file-name-internal'.
1013 2. The symbol passed by :caller into `ivy-read'.
1014 3. `this-command'.
1015 4. t.
1016
1017 Each value is a function that should take a string and return a
1018 valid regex or a regex sequence (see below).
1019
1020 Possible choices: `ivy--regex', `regexp-quote',
1021 `ivy--regex-plus', `ivy--regex-fuzzy'.
1022
1023 If a function returns a list, it should format like this:
1024 '((\"matching-regexp\" . t) (\"non-matching-regexp\") ...).
1025
1026 The matches will be filtered in a sequence, you can mix the
1027 regexps that should match and that should not match as you
1028 like.")
1029
1030 (defvar ivy-initial-inputs-alist
1031 '((org-refile . "^")
1032 (org-agenda-refile . "^")
1033 (org-capture-refile . "^")
1034 (counsel-M-x . "^")
1035 (counsel-describe-function . "^")
1036 (counsel-describe-variable . "^")
1037 (man . "^")
1038 (woman . "^"))
1039 "Command to initial input table.")
1040
1041 (defcustom ivy-sort-max-size 30000
1042 "Sorting won't be done for collections larger than this."
1043 :type 'integer)
1044
1045 (defun ivy--sorted-files (dir)
1046 "Return the list of files in DIR.
1047 Directories come first."
1048 (let* ((default-directory dir)
1049 (seq (all-completions "" 'read-file-name-internal))
1050 sort-fn)
1051 (if (equal dir "/")
1052 seq
1053 (setq seq (delete "./" (delete "../" seq)))
1054 (when (eq (setq sort-fn (cdr (assoc 'read-file-name-internal
1055 ivy-sort-functions-alist)))
1056 #'ivy-sort-file-function-default)
1057 (setq seq (mapcar (lambda (x)
1058 (propertize x 'dirp (string-match-p "/\\'" x)))
1059 seq)))
1060 (when sort-fn
1061 (setq seq (cl-sort seq sort-fn)))
1062 (dolist (dir ivy-extra-directories)
1063 (push dir seq))
1064 seq)))
1065
1066 (defvar ivy-recursive-restore t
1067 "When non-nil, restore the above state when exiting the minibuffer.
1068 This variable is let-bound to nil by functions that take care of
1069 the restoring themselves.")
1070
1071 ;;** Entry Point
1072 (cl-defun ivy-read (prompt collection
1073 &key
1074 predicate require-match initial-input
1075 history preselect keymap update-fn sort
1076 action unwind re-builder matcher dynamic-collection caller)
1077 "Read a string in the minibuffer, with completion.
1078
1079 PROMPT is a format string, normally ending in a colon and a
1080 space; %d anywhere in the string is replaced by the current
1081 number of matching candidates. For the literal % character,
1082 escape it with %%. See also `ivy-count-format'.
1083
1084 COLLECTION is either a list of strings, a function, an alist, or
1085 a hash table.
1086
1087 If INITIAL-INPUT is not nil, then insert that input in the
1088 minibuffer initially.
1089
1090 KEYMAP is composed with `ivy-minibuffer-map'.
1091
1092 If PRESELECT is not nil, then select the corresponding candidate
1093 out of the ones that match the INITIAL-INPUT.
1094
1095 UPDATE-FN is called each time the current candidate(s) is changed.
1096
1097 When SORT is t, use `ivy-sort-functions-alist' for sorting.
1098
1099 ACTION is a lambda function to call after selecting a result. It
1100 takes a single string argument.
1101
1102 UNWIND is a lambda function to call before exiting.
1103
1104 RE-BUILDER is a lambda function to call to transform text into a
1105 regex pattern.
1106
1107 MATCHER is to override matching.
1108
1109 DYNAMIC-COLLECTION is a boolean to specify if the list of
1110 candidates is updated after each input by calling COLLECTION.
1111
1112 CALLER is a symbol to uniquely identify the caller to `ivy-read'.
1113 It is used, along with COLLECTION, to determine which
1114 customizations apply to the current completion session."
1115 (let ((extra-actions (append (plist-get ivy--actions-list t)
1116 (plist-get ivy--actions-list this-command))))
1117 (when extra-actions
1118 (setq action
1119 (if (functionp action)
1120 `(1
1121 ("o" ,action "default")
1122 ,@extra-actions)
1123 (delete-dups (append action extra-actions))))))
1124 (let ((recursive-ivy-last (and (active-minibuffer-window) ivy-last)))
1125 (setq ivy-last
1126 (make-ivy-state
1127 :prompt prompt
1128 :collection collection
1129 :predicate predicate
1130 :require-match require-match
1131 :initial-input initial-input
1132 :history history
1133 :preselect preselect
1134 :keymap keymap
1135 :update-fn update-fn
1136 :sort sort
1137 :action action
1138 :window (selected-window)
1139 :buffer (current-buffer)
1140 :unwind unwind
1141 :re-builder re-builder
1142 :matcher matcher
1143 :dynamic-collection dynamic-collection
1144 :caller caller))
1145 (ivy--reset-state ivy-last)
1146 (prog1
1147 (unwind-protect
1148 (minibuffer-with-setup-hook
1149 #'ivy--minibuffer-setup
1150 (let* ((hist (or history 'ivy-history))
1151 (minibuffer-completion-table collection)
1152 (minibuffer-completion-predicate predicate)
1153 (resize-mini-windows (cond
1154 ((display-graphic-p) nil)
1155 ((null resize-mini-windows) 'grow-only)
1156 (t resize-mini-windows))))
1157 (read-from-minibuffer
1158 prompt
1159 (ivy-state-initial-input ivy-last)
1160 (make-composed-keymap keymap ivy-minibuffer-map)
1161 nil
1162 hist)
1163 (when (eq ivy-exit 'done)
1164 (let ((item (if ivy--directory
1165 ivy--current
1166 ivy-text)))
1167 (unless (equal item "")
1168 (set hist (cons (propertize item 'ivy-index ivy--index)
1169 (delete item
1170 (cdr (symbol-value hist))))))))
1171 ivy--current))
1172 (remove-hook 'post-command-hook #'ivy--exhibit)
1173 (when (setq unwind (ivy-state-unwind ivy-last))
1174 (funcall unwind))
1175 (unless (eq ivy-exit 'done)
1176 (when recursive-ivy-last
1177 (ivy--reset-state (setq ivy-last recursive-ivy-last)))))
1178 (ivy-call)
1179 (when (and recursive-ivy-last
1180 ivy-recursive-restore)
1181 (ivy--reset-state (setq ivy-last recursive-ivy-last))))))
1182
1183 (defun ivy--reset-state (state)
1184 "Reset the ivy to STATE.
1185 This is useful for recursive `ivy-read'."
1186 (let ((prompt (or (ivy-state-prompt state) ""))
1187 (collection (ivy-state-collection state))
1188 (predicate (ivy-state-predicate state))
1189 (history (ivy-state-history state))
1190 (preselect (ivy-state-preselect state))
1191 (sort (ivy-state-sort state))
1192 (re-builder (ivy-state-re-builder state))
1193 (dynamic-collection (ivy-state-dynamic-collection state))
1194 (initial-input (ivy-state-initial-input state))
1195 (require-match (ivy-state-require-match state))
1196 (caller (ivy-state-caller state)))
1197 (unless initial-input
1198 (setq initial-input (cdr (assoc this-command
1199 ivy-initial-inputs-alist))))
1200 (setq ivy--directory nil)
1201 (setq ivy-case-fold-search 'auto)
1202 (setq ivy--regex-function
1203 (or re-builder
1204 (and (functionp collection)
1205 (cdr (assoc collection ivy-re-builders-alist)))
1206 (and caller
1207 (cdr (assoc caller ivy-re-builders-alist)))
1208 (cdr (assoc this-command ivy-re-builders-alist))
1209 (cdr (assoc t ivy-re-builders-alist))
1210 'ivy--regex))
1211 (setq ivy--subexps 0)
1212 (setq ivy--regexp-quote 'regexp-quote)
1213 (setq ivy--old-text "")
1214 (setq ivy--full-length nil)
1215 (setq ivy-text "")
1216 (setq ivy-calling nil)
1217 (let (coll sort-fn)
1218 (cond ((eq collection 'Info-read-node-name-1)
1219 (if (equal Info-current-file "dir")
1220 (setq coll
1221 (mapcar (lambda (x) (format "(%s)" x))
1222 (cl-delete-duplicates
1223 (all-completions "(" collection predicate)
1224 :test #'equal)))
1225 (setq coll (all-completions "" collection predicate))))
1226 ((eq collection 'read-file-name-internal)
1227 (setq ivy--directory default-directory)
1228 (require 'dired)
1229 (when preselect
1230 (let ((preselect-directory (file-name-directory preselect)))
1231 (unless (or (null preselect-directory)
1232 (string= preselect-directory
1233 default-directory))
1234 (setq ivy--directory preselect-directory))
1235 (setf
1236 (ivy-state-preselect state)
1237 (setq preselect (file-name-nondirectory preselect)))))
1238 (setq coll (ivy--sorted-files ivy--directory))
1239 (when initial-input
1240 (unless (or require-match
1241 (equal initial-input default-directory)
1242 (equal initial-input ""))
1243 (setq coll (cons initial-input coll)))
1244 (unless (ivy-state-action ivy-last)
1245 (setq initial-input nil))))
1246 ((eq collection 'internal-complete-buffer)
1247 (setq coll (ivy--buffer-list "" ivy-use-virtual-buffers)))
1248 ((or (functionp collection)
1249 (byte-code-function-p collection)
1250 (vectorp collection)
1251 (and (consp collection) (listp (car collection)))
1252 (hash-table-p collection))
1253 (setq coll (all-completions "" collection predicate)))
1254 (t
1255 (setq coll collection)))
1256 (when sort
1257 (if (and (functionp collection)
1258 (setq sort-fn (assoc collection ivy-sort-functions-alist)))
1259 (when (and (setq sort-fn (cdr sort-fn))
1260 (not (eq collection 'read-file-name-internal)))
1261 (setq coll (cl-sort coll sort-fn)))
1262 (unless (eq history 'org-refile-history)
1263 (if (and (setq sort-fn (cdr (assoc t ivy-sort-functions-alist)))
1264 (<= (length coll) ivy-sort-max-size))
1265 (setq coll (cl-sort (copy-sequence coll) sort-fn))))))
1266 (when preselect
1267 (unless (or (and require-match
1268 (not (eq collection 'internal-complete-buffer)))
1269 dynamic-collection
1270 (let ((re (regexp-quote preselect)))
1271 (cl-find-if (lambda (x) (string-match re x))
1272 coll)))
1273 (setq coll (cons preselect coll))))
1274 (setq ivy--old-re nil)
1275 (setq ivy--old-cands nil)
1276 (when (integerp preselect)
1277 (setq ivy--old-re "")
1278 (setq ivy--index preselect))
1279 (when initial-input
1280 ;; Needed for anchor to work
1281 (setq ivy--old-cands coll)
1282 (setq ivy--old-cands (ivy--filter initial-input coll)))
1283 (setq ivy--all-candidates coll)
1284 (unless (integerp preselect)
1285 (setq ivy--index (or
1286 (and dynamic-collection
1287 ivy--index)
1288 (and preselect
1289 (ivy--preselect-index
1290 preselect
1291 (if initial-input
1292 ivy--old-cands
1293 coll)))
1294 0))))
1295 (setq ivy-exit nil)
1296 (setq ivy--default (or
1297 (thing-at-point 'url)
1298 (thing-at-point 'symbol)
1299 ""))
1300 (setq ivy--prompt
1301 (cond ((string-match "%.*d" prompt)
1302 prompt)
1303 ((null ivy-count-format)
1304 (error
1305 "`ivy-count-format' can't be nil. Set it to an empty string instead"))
1306 ((string-match "%d.*%d" ivy-count-format)
1307 (let ((w (length (number-to-string
1308 (length ivy--all-candidates))))
1309 (s (copy-sequence ivy-count-format)))
1310 (string-match "%d" s)
1311 (match-end 0)
1312 (string-match "%d" s (match-end 0))
1313 (setq s (replace-match (format "%%-%dd" w) nil nil s))
1314 (string-match "%d" s)
1315 (concat (replace-match (format "%%%dd" w) nil nil s)
1316 prompt)))
1317 ((string-match "%.*d" ivy-count-format)
1318 (concat ivy-count-format prompt))
1319 (ivy--directory
1320 prompt)
1321 (t
1322 nil)))
1323 (setf (ivy-state-initial-input ivy-last) initial-input)))
1324
1325 ;;;###autoload
1326 (defun ivy-completing-read (prompt collection
1327 &optional predicate require-match initial-input
1328 history def inherit-input-method)
1329 "Read a string in the minibuffer, with completion.
1330
1331 This interface conforms to `completing-read' and can be used for
1332 `completing-read-function'.
1333
1334 PROMPT is a string to prompt with; normally it ends in a colon and a space.
1335 COLLECTION can be a list of strings, an alist, an obarray or a hash table.
1336 PREDICATE limits completion to a subset of COLLECTION.
1337 REQUIRE-MATCH is specified with a boolean value. See `completing-read'.
1338 INITIAL-INPUT is a string that can be inserted into the minibuffer initially.
1339 HISTORY is a list of previously selected inputs.
1340 DEF is the default value.
1341 INHERIT-INPUT-METHOD is currently ignored."
1342 (if (memq this-command '(tmm-menubar tmm-shortcut))
1343 (completing-read-default prompt collection
1344 predicate require-match
1345 initial-input history
1346 def inherit-input-method)
1347 ;; See the doc of `completing-read'.
1348 (when (consp history)
1349 (when (numberp (cdr history))
1350 (setq initial-input (nth (1- (cdr history))
1351 (symbol-value (car history)))))
1352 (setq history (car history)))
1353 (ivy-read (replace-regexp-in-string "%" "%%" prompt)
1354 collection
1355 :predicate predicate
1356 :require-match require-match
1357 :initial-input (if (consp initial-input)
1358 (car initial-input)
1359 (if (and (stringp initial-input)
1360 (string-match "\\+" initial-input))
1361 (replace-regexp-in-string
1362 "\\+" "\\\\+" initial-input)
1363 initial-input))
1364 :preselect (if (listp def) (car def) def)
1365 :history history
1366 :keymap nil
1367 :sort
1368 (let ((sort (assoc this-command ivy-sort-functions-alist)))
1369 (if sort
1370 (cdr sort)
1371 t)))))
1372
1373 (defvar ivy-completion-beg nil
1374 "Completion bounds start.")
1375
1376 (defvar ivy-completion-end nil
1377 "Completion bounds end.")
1378
1379 (defun ivy-completion-in-region-action (str)
1380 "Insert STR, erasing the previous one.
1381 The previous string is between `ivy-completion-beg' and `ivy-completion-end'."
1382 (when (stringp str)
1383 (with-ivy-window
1384 (when ivy-completion-beg
1385 (delete-region
1386 ivy-completion-beg
1387 ivy-completion-end))
1388 (setq ivy-completion-beg
1389 (move-marker (make-marker) (point)))
1390 (insert str)
1391 (setq ivy-completion-end
1392 (move-marker (make-marker) (point))))))
1393
1394 (defun ivy-completion-common-length (str)
1395 "Return the length of the first 'completions-common-part face in STR."
1396 (let ((pos 0)
1397 (len (length str)))
1398 (while (and (<= pos len)
1399 (let ((prop (get-text-property pos 'face str)))
1400 (not (eq 'completions-common-part
1401 (if (listp prop) (car prop) prop)))))
1402 (setq pos (1+ pos)))
1403 (if (< pos len)
1404 (or (next-single-property-change pos 'face str) len)
1405 0)))
1406
1407 (defun ivy-completion-in-region (start end collection &optional predicate)
1408 "An Ivy function suitable for `completion-in-region-function'."
1409 (let* ((enable-recursive-minibuffers t)
1410 (str (buffer-substring-no-properties start end))
1411 (comps
1412 (completion-all-completions str collection predicate (- end start))))
1413 (if (null comps)
1414 (message "No matches")
1415 (nconc comps nil)
1416 (setq ivy-completion-beg (- end (ivy-completion-common-length (car comps))))
1417 (setq ivy-completion-end end)
1418 (if (null (cdr comps))
1419 (if (string= str (car comps))
1420 (message "Sole match")
1421 (setf (ivy-state-window ivy-last) (selected-window))
1422 (ivy-completion-in-region-action
1423 (substring-no-properties
1424 (car comps))))
1425 (let* ((w (1+ (floor (log (length comps) 10))))
1426 (ivy-count-format (if (string= ivy-count-format "")
1427 ivy-count-format
1428 (format "%%-%dd " w)))
1429 (prompt (format "(%s): " str)))
1430 (and
1431 (ivy-read (if (string= ivy-count-format "")
1432 prompt
1433 (replace-regexp-in-string "%" "%%" prompt))
1434 ;; remove 'completions-first-difference face
1435 (mapcar #'substring-no-properties comps)
1436 :predicate predicate
1437 :action #'ivy-completion-in-region-action
1438 :require-match t)
1439 t))))))
1440
1441 ;;;###autoload
1442 (define-minor-mode ivy-mode
1443 "Toggle Ivy mode on or off.
1444 Turn Ivy mode on if ARG is positive, off otherwise.
1445 Turning on Ivy mode sets `completing-read-function' to
1446 `ivy-completing-read'.
1447
1448 Global bindings:
1449 \\{ivy-mode-map}
1450
1451 Minibuffer bindings:
1452 \\{ivy-minibuffer-map}"
1453 :group 'ivy
1454 :global t
1455 :keymap ivy-mode-map
1456 :lighter " ivy"
1457 (if ivy-mode
1458 (progn
1459 (setq completing-read-function 'ivy-completing-read)
1460 (setq completion-in-region-function 'ivy-completion-in-region))
1461 (setq completing-read-function 'completing-read-default)
1462 (setq completion-in-region-function 'completion--in-region)))
1463
1464 (defun ivy--preselect-index (preselect candidates)
1465 "Return the index of PRESELECT in CANDIDATES."
1466 (cond ((integerp preselect)
1467 preselect)
1468 ((cl-position preselect candidates :test #'equal))
1469 ((stringp preselect)
1470 (let ((re (regexp-quote preselect)))
1471 (cl-position-if
1472 (lambda (x)
1473 (string-match re x))
1474 candidates)))))
1475
1476 ;;* Implementation
1477 ;;** Regex
1478 (defvar ivy--regex-hash
1479 (make-hash-table :test #'equal)
1480 "Store pre-computed regex.")
1481
1482 (defun ivy--split (str)
1483 "Split STR into a list by single spaces.
1484 The remaining spaces stick to their left.
1485 This allows to \"quote\" N spaces by inputting N+1 spaces."
1486 (let ((len (length str))
1487 start0
1488 (start1 0)
1489 res s
1490 match-len)
1491 (while (and (string-match " +" str start1)
1492 (< start1 len))
1493 (setq match-len (- (match-end 0) (match-beginning 0)))
1494 (if (= match-len 1)
1495 (progn
1496 (when start0
1497 (setq start1 start0)
1498 (setq start0 nil))
1499 (push (substring str start1 (match-beginning 0)) res)
1500 (setq start1 (match-end 0)))
1501 (setq str (replace-match
1502 (make-string (1- match-len) ?\ )
1503 nil nil str))
1504 (setq start0 (or start0 start1))
1505 (setq start1 (1- (match-end 0)))))
1506 (if start0
1507 (push (substring str start0) res)
1508 (setq s (substring str start1))
1509 (unless (= (length s) 0)
1510 (push s res)))
1511 (nreverse res)))
1512
1513 (defun ivy--regex (str &optional greedy)
1514 "Re-build regex pattern from STR in case it has a space.
1515 When GREEDY is non-nil, join words in a greedy way."
1516 (let ((hashed (unless greedy
1517 (gethash str ivy--regex-hash))))
1518 (if hashed
1519 (prog1 (cdr hashed)
1520 (setq ivy--subexps (car hashed)))
1521 (when (string-match "\\([^\\]\\|^\\)\\\\$" str)
1522 (setq str (substring str 0 -1)))
1523 (cdr (puthash str
1524 (let ((subs (ivy--split str)))
1525 (if (= (length subs) 1)
1526 (cons
1527 (setq ivy--subexps 0)
1528 (car subs))
1529 (cons
1530 (setq ivy--subexps (length subs))
1531 (mapconcat
1532 (lambda (x)
1533 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1534 x
1535 (format "\\(%s\\)" x)))
1536 subs
1537 (if greedy
1538 ".*"
1539 ".*?")))))
1540 ivy--regex-hash)))))
1541
1542 (defun ivy--regex-ignore-order--part (str &optional discard)
1543 "Re-build regex from STR by splitting at spaces.
1544 Ignore the order of each group."
1545 (let* ((subs (split-string str " +" t))
1546 (len (length subs)))
1547 (cl-case len
1548 (0
1549 "")
1550 (t
1551 (mapcar (lambda (x) (cons x (not discard)))
1552 subs)))))
1553
1554 (defun ivy--regex-ignore-order (str)
1555 "Re-build regex from STR by splitting at spaces.
1556 Ignore the order of each group. Everything before \"!\" should
1557 match. Everything after \"!\" should not match."
1558 (let ((parts (split-string str "!" t)))
1559 (cl-case (length parts)
1560 (0
1561 "")
1562 (1
1563 (if (string= (substring str 0 1) "!")
1564 (list (cons "" t)
1565 (ivy--regex-ignore-order--part (car parts) t))
1566 (ivy--regex-ignore-order--part (car parts))))
1567 (2
1568 (append
1569 (ivy--regex-ignore-order--part (car parts))
1570 (ivy--regex-ignore-order--part (cadr parts) t)))
1571 (t (error "Unexpected: use only one !")))))
1572
1573 (defun ivy--regex-plus (str)
1574 "Build a regex sequence from STR.
1575 Spaces are wild card characters, everything before \"!\" should
1576 match. Everything after \"!\" should not match."
1577 (let ((parts (split-string str "!" t)))
1578 (cl-case (length parts)
1579 (0
1580 "")
1581 (1
1582 (if (string= (substring str 0 1) "!")
1583 (list (cons "" t)
1584 (list (ivy--regex (car parts))))
1585 (ivy--regex (car parts))))
1586 (2
1587 (cons
1588 (cons (ivy--regex (car parts)) t)
1589 (mapcar #'list (split-string (cadr parts) " " t))))
1590 (t (error "Unexpected: use only one !")))))
1591
1592 (defun ivy--regex-fuzzy (str)
1593 "Build a regex sequence from STR.
1594 Insert .* between each char."
1595 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1596 (prog1
1597 (concat (match-string 1 str)
1598 (mapconcat
1599 (lambda (x)
1600 (format "\\(%c\\)" x))
1601 (string-to-list (match-string 2 str)) ".*")
1602 (match-string 3 str))
1603 (setq ivy--subexps (length (match-string 2 str))))
1604 str))
1605
1606 ;;** Rest
1607 (defun ivy--minibuffer-setup ()
1608 "Setup ivy completion in the minibuffer."
1609 (set (make-local-variable 'completion-show-inline-help) nil)
1610 (set (make-local-variable 'minibuffer-default-add-function)
1611 (lambda ()
1612 (list ivy--default)))
1613 (when (display-graphic-p)
1614 (setq truncate-lines t))
1615 (setq-local max-mini-window-height ivy-height)
1616 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1617 ;; show completions with empty input
1618 (ivy--exhibit))
1619
1620 (defun ivy--input ()
1621 "Return the current minibuffer input."
1622 ;; assume one-line minibuffer input
1623 (buffer-substring-no-properties
1624 (minibuffer-prompt-end)
1625 (line-end-position)))
1626
1627 (defun ivy--cleanup ()
1628 "Delete the displayed completion candidates."
1629 (save-excursion
1630 (goto-char (minibuffer-prompt-end))
1631 (delete-region (line-end-position) (point-max))))
1632
1633 (defun ivy--insert-prompt ()
1634 "Update the prompt according to `ivy--prompt'."
1635 (when ivy--prompt
1636 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1637 counsel-find-symbol))
1638 (setq ivy--prompt-extra ""))
1639 (let (head tail)
1640 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1641 (progn
1642 (setq head (match-string 1 ivy--prompt))
1643 (setq tail ": "))
1644 (setq head (substring ivy--prompt 0 -1))
1645 (setq tail " "))
1646 (let ((inhibit-read-only t)
1647 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1648 (n-str
1649 (concat
1650 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1651 (> (minibuffer-depth) 1))
1652 (format "[%d] " (minibuffer-depth))
1653 "")
1654 (concat
1655 (if (string-match "%d.*%d" ivy-count-format)
1656 (format head
1657 (1+ ivy--index)
1658 (or (and (ivy-state-dynamic-collection ivy-last)
1659 ivy--full-length)
1660 ivy--length))
1661 (format head
1662 (or (and (ivy-state-dynamic-collection ivy-last)
1663 ivy--full-length)
1664 ivy--length)))
1665 ivy--prompt-extra
1666 tail)))
1667 (d-str (if ivy--directory
1668 (abbreviate-file-name ivy--directory)
1669 "")))
1670 (save-excursion
1671 (goto-char (point-min))
1672 (delete-region (point-min) (minibuffer-prompt-end))
1673 (if (> (+ (mod (+ (length n-str) (length d-str)) (window-width))
1674 (length ivy-text))
1675 (window-width))
1676 (setq n-str (concat n-str "\n" d-str))
1677 (setq n-str (concat n-str d-str)))
1678 (let ((regex (format "\\([^\n]\\{%d\\}\\)[^\n]" (window-width))))
1679 (while (string-match regex n-str)
1680 (setq n-str (replace-match (concat (match-string 1 n-str) "\n") nil t n-str 1))))
1681 (set-text-properties 0 (length n-str)
1682 `(face minibuffer-prompt ,@std-props)
1683 n-str)
1684 (ivy--set-match-props n-str "confirm"
1685 `(face ivy-confirm-face ,@std-props))
1686 (ivy--set-match-props n-str "match required"
1687 `(face ivy-match-required-face ,@std-props))
1688 (insert n-str))
1689 ;; get out of the prompt area
1690 (constrain-to-field nil (point-max))))))
1691
1692 (defun ivy--set-match-props (str match props)
1693 "Set STR text properties that match MATCH to PROPS."
1694 (when (string-match match str)
1695 (set-text-properties
1696 (match-beginning 0)
1697 (match-end 0)
1698 props
1699 str)))
1700
1701 (defvar inhibit-message)
1702
1703 (defun ivy--sort-maybe (collection)
1704 "Sort COLLECTION if needed."
1705 (let ((sort (ivy-state-sort ivy-last))
1706 entry)
1707 (if (null sort)
1708 collection
1709 (let ((sort-fn (cond ((functionp sort)
1710 sort)
1711 ((setq entry (assoc (ivy-state-collection ivy-last)
1712 ivy-sort-functions-alist))
1713 (cdr entry))
1714 (t
1715 (cdr (assoc t ivy-sort-functions-alist))))))
1716 (if (functionp sort-fn)
1717 (cl-sort (copy-sequence collection) sort-fn)
1718 collection)))))
1719
1720 (defun ivy--exhibit ()
1721 "Insert Ivy completions display.
1722 Should be run via minibuffer `post-command-hook'."
1723 (when (memq 'ivy--exhibit post-command-hook)
1724 (let ((inhibit-field-text-motion nil))
1725 (constrain-to-field nil (point-max)))
1726 (setq ivy-text (ivy--input))
1727 (if (ivy-state-dynamic-collection ivy-last)
1728 ;; while-no-input would cause annoying
1729 ;; "Waiting for process to die...done" message interruptions
1730 (let ((inhibit-message t))
1731 (unless (equal ivy--old-text ivy-text)
1732 (while-no-input
1733 (setq ivy--all-candidates
1734 (ivy--sort-maybe
1735 (funcall (ivy-state-collection ivy-last) ivy-text)))
1736 (setq ivy--old-text ivy-text)))
1737 (when ivy--all-candidates
1738 (ivy--insert-minibuffer
1739 (ivy--format ivy--all-candidates))))
1740 (cond (ivy--directory
1741 (if (string-match "/\\'" ivy-text)
1742 (if (member ivy-text ivy--all-candidates)
1743 (ivy--cd (expand-file-name ivy-text ivy--directory))
1744 (when (string-match "//\\'" ivy-text)
1745 (if (and default-directory
1746 (string-match "\\`[[:alpha:]]:/" default-directory))
1747 (ivy--cd (match-string 0 default-directory))
1748 (ivy--cd "/")))
1749 (when (string-match "[[:alpha:]]:/$" ivy-text)
1750 (let ((drive-root (match-string 0 ivy-text)))
1751 (when (file-exists-p drive-root)
1752 (ivy--cd drive-root)))))
1753 (if (string-match "\\`~\\'" ivy-text)
1754 (ivy--cd (expand-file-name "~/")))))
1755 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1756 (when (or (and (string-match "\\` " ivy-text)
1757 (not (string-match "\\` " ivy--old-text)))
1758 (and (string-match "\\` " ivy--old-text)
1759 (not (string-match "\\` " ivy-text))))
1760 (setq ivy--all-candidates
1761 (if (and (> (length ivy-text) 0)
1762 (eq (aref ivy-text 0)
1763 ?\ ))
1764 (ivy--buffer-list " ")
1765 (ivy--buffer-list "" ivy-use-virtual-buffers)))
1766 (setq ivy--old-re nil))))
1767 (ivy--insert-minibuffer
1768 (with-current-buffer (ivy-state-buffer ivy-last)
1769 (ivy--format
1770 (ivy--filter ivy-text ivy--all-candidates))))
1771 (setq ivy--old-text ivy-text))))
1772
1773 (defun ivy--insert-minibuffer (text)
1774 "Insert TEXT into minibuffer with appropriate cleanup."
1775 (let ((resize-mini-windows nil)
1776 (update-fn (ivy-state-update-fn ivy-last))
1777 deactivate-mark)
1778 (ivy--cleanup)
1779 (when update-fn
1780 (funcall update-fn))
1781 (ivy--insert-prompt)
1782 ;; Do nothing if while-no-input was aborted.
1783 (when (stringp text)
1784 (let ((buffer-undo-list t))
1785 (save-excursion
1786 (forward-line 1)
1787 (insert text))))
1788 (when (display-graphic-p)
1789 (ivy--resize-minibuffer-to-fit))))
1790
1791 (defun ivy--resize-minibuffer-to-fit ()
1792 "Resize the minibuffer window size to fit the text in the minibuffer."
1793 (with-selected-window (minibuffer-window)
1794 (if (fboundp 'window-text-pixel-size)
1795 (let ((text-height (cdr (window-text-pixel-size)))
1796 (body-height (window-body-height nil t)))
1797 (when (> text-height body-height)
1798 ;; Note: the size increment needs to be at least frame-char-height,
1799 ;; otherwise resizing won't do anything.
1800 (let ((delta (max (- text-height body-height) (frame-char-height))))
1801 (window-resize nil delta nil t t))))
1802 (let ((text-height (count-screen-lines))
1803 (body-height (window-body-height)))
1804 (when (> text-height body-height)
1805 (window-resize nil (- text-height body-height) nil t))))))
1806
1807 (declare-function colir-blend-face-background "ext:colir")
1808
1809 (defun ivy--add-face (str face)
1810 "Propertize STR with FACE.
1811 `font-lock-append-text-property' is used, since it's better than
1812 `propertize' or `add-face-text-property' in this case."
1813 (require 'colir)
1814 (condition-case nil
1815 (progn
1816 (colir-blend-face-background 0 (length str) face str)
1817 (let ((foreground (face-foreground face)))
1818 (when foreground
1819 (add-face-text-property
1820 0 (length str)
1821 `(:foreground ,foreground)
1822 nil
1823 str))))
1824 (error
1825 (ignore-errors
1826 (font-lock-append-text-property 0 (length str) 'face face str))))
1827 str)
1828
1829 (declare-function flx-make-string-cache "ext:flx")
1830 (declare-function flx-score "ext:flx")
1831
1832 (defvar ivy--flx-cache nil)
1833
1834 (eval-after-load 'flx
1835 '(setq ivy--flx-cache (flx-make-string-cache)))
1836
1837 (defun ivy-toggle-case-fold ()
1838 "Toggle the case folding between nil and auto.
1839 In any completion session, the case folding starts in auto:
1840
1841 - when the input is all lower case, `case-fold-search' is t
1842 - otherwise nil.
1843
1844 You can toggle this to make `case-fold-search' nil regardless of input."
1845 (interactive)
1846 (setq ivy-case-fold-search
1847 (if ivy-case-fold-search
1848 nil
1849 'auto))
1850 ;; reset cache so that the candidate list updates
1851 (setq ivy--old-re nil))
1852
1853 (defun ivy--re-filter (re candidates)
1854 "Return all RE matching CANDIDATES.
1855 RE is a list of cons cells, with a regexp car and a boolean cdr.
1856 When the cdr is t, the car must match.
1857 Otherwise, the car must not match."
1858 (let ((re-list (if (stringp re) (list (cons re t)) re))
1859 (res candidates))
1860 (dolist (re re-list)
1861 (setq res
1862 (ignore-errors
1863 (funcall
1864 (if (cdr re)
1865 #'cl-remove-if-not
1866 #'cl-remove-if)
1867 (let ((re-str (car re)))
1868 (lambda (x) (string-match re-str x)))
1869 res))))
1870 res))
1871
1872 (defun ivy--filter (name candidates)
1873 "Return all items that match NAME in CANDIDATES.
1874 CANDIDATES are assumed to be static."
1875 (let ((re (funcall ivy--regex-function name)))
1876 (if (and (equal re ivy--old-re)
1877 ivy--old-cands)
1878 ;; quick caching for "C-n", "C-p" etc.
1879 ivy--old-cands
1880 (let* ((re-str (if (listp re) (caar re) re))
1881 (matcher (ivy-state-matcher ivy-last))
1882 (case-fold-search
1883 (and ivy-case-fold-search
1884 (string= name (downcase name))))
1885 (cands (cond
1886 (matcher
1887 (funcall matcher re candidates))
1888 ((and ivy--old-re
1889 (stringp re)
1890 (stringp ivy--old-re)
1891 (not (string-match "\\\\" ivy--old-re))
1892 (not (equal ivy--old-re ""))
1893 (memq (cl-search
1894 (if (string-match "\\\\)\\'" ivy--old-re)
1895 (substring ivy--old-re 0 -2)
1896 ivy--old-re)
1897 re)
1898 '(0 2)))
1899 (ignore-errors
1900 (cl-remove-if-not
1901 (lambda (x) (string-match re x))
1902 ivy--old-cands)))
1903 (t
1904 (ivy--re-filter re candidates)))))
1905 (ivy--recompute-index name re-str cands)
1906 (setq ivy--old-re
1907 (if (eq ivy--regex-function 'ivy--regex-ignore-order)
1908 re
1909 (if cands
1910 re-str
1911 "")))
1912 (setq ivy--old-cands (ivy--sort name cands))))))
1913
1914 (defcustom ivy-sort-matches-functions-alist '((t . nil))
1915 "An alist of functions used to sort the matching candidates.
1916
1917 This is different from `ivy-sort-functions-alist', which is used
1918 to sort the whole collection only once. The functions taken from
1919 here are instead used on each input change, but they are used
1920 only on already matching candidates, not on all of them.
1921
1922 The alist KEY is a collection function or t to match previously
1923 not matched collection functions.
1924
1925 The alist VAL is a sorting function with the signature of
1926 `ivy--prefix-sort'.")
1927
1928 (defun ivy--sort-files-by-date (_name candidates)
1929 "Re-soft CANDIDATES according to file modification date."
1930 (let ((default-directory ivy--directory))
1931 (cl-sort (copy-sequence candidates)
1932 (lambda (f1 f2)
1933 (time-less-p
1934 (nth 5 (file-attributes f2))
1935 (nth 5 (file-attributes f1)))))))
1936
1937 (defun ivy--sort (name candidates)
1938 "Re-sort CANDIDATES by NAME.
1939 All CANDIDATES are assumed to match NAME."
1940 (let ((key (or (ivy-state-caller ivy-last)
1941 (when (functionp (ivy-state-collection ivy-last))
1942 (ivy-state-collection ivy-last))))
1943 fun)
1944 (cond ((and (require 'flx nil 'noerror)
1945 (eq ivy--regex-function 'ivy--regex-fuzzy))
1946 (ivy--flx-sort name candidates))
1947 ((setq fun (cdr (or (assoc key ivy-sort-matches-functions-alist)
1948 (assoc t ivy-sort-matches-functions-alist))))
1949 (funcall fun name candidates))
1950 (t
1951 candidates))))
1952
1953 (defun ivy--prefix-sort (name candidates)
1954 "Re-sort CANDIDATES.
1955 Prefix matches to NAME are put ahead of the list."
1956 (if (or (string-match "^\\^" name) (string= name ""))
1957 candidates
1958 (let ((re-prefix (concat "^" (funcall ivy--regex-function name)))
1959 res-prefix
1960 res-noprefix)
1961 (dolist (s candidates)
1962 (if (string-match re-prefix s)
1963 (push s res-prefix)
1964 (push s res-noprefix)))
1965 (nconc
1966 (nreverse res-prefix)
1967 (nreverse res-noprefix)))))
1968
1969 (defun ivy--recompute-index (name re-str cands)
1970 (let* ((caller (ivy-state-caller ivy-last))
1971 (func (or (and caller (cdr (assoc caller ivy-index-functions-alist)))
1972 (cdr (assoc t ivy-index-functions-alist))
1973 #'ivy-recompute-index-zero)))
1974 (unless (eq this-command 'ivy-resume)
1975 (setq ivy--index
1976 (or
1977 (cl-position (if (and (> (length name) 0)
1978 (eq ?^ (aref name 0)))
1979 (substring name 1)
1980 name) cands
1981 :test #'equal)
1982 (and ivy--directory
1983 (cl-position
1984 (concat re-str "/") cands
1985 :test #'equal))
1986 (and (not (string= name ""))
1987 (not (and (require 'flx nil 'noerror)
1988 (eq ivy--regex-function 'ivy--regex-fuzzy)
1989 (< (length cands) 200)))
1990
1991 (cl-position (nth ivy--index ivy--old-cands)
1992 cands))
1993 (funcall func re-str cands))))
1994 (when (and (or (string= name "")
1995 (string= name "^"))
1996 (not (equal ivy--old-re "")))
1997 (setq ivy--index
1998 (or (ivy--preselect-index
1999 (ivy-state-preselect ivy-last)
2000 cands)
2001 ivy--index)))))
2002
2003 (defun ivy-recompute-index-swiper (_re-str cands)
2004 (let ((tail (nthcdr ivy--index ivy--old-cands))
2005 idx)
2006 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2007 (progn
2008 (while (and tail (null idx))
2009 ;; Compare with eq to handle equal duplicates in cands
2010 (setq idx (cl-position (pop tail) cands)))
2011 (or
2012 idx
2013 (1- (length cands))))
2014 (if ivy--old-cands
2015 ivy--index
2016 ;; already in ivy-state-buffer
2017 (let ((n (line-number-at-pos))
2018 (res 0)
2019 (i 0))
2020 (dolist (c cands)
2021 (when (eq n (read (get-text-property 0 'display c)))
2022 (setq res i))
2023 (cl-incf i))
2024 res)))))
2025
2026 (defun ivy-recompute-index-swiper-async (_re-str cands)
2027 (let ((tail (nthcdr ivy--index ivy--old-cands))
2028 idx)
2029 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2030 (progn
2031 (while (and tail (null idx))
2032 ;; Compare with `equal', since the collection is re-created
2033 ;; each time with `split-string'
2034 (setq idx (cl-position (pop tail) cands :test #'equal)))
2035 (or idx 0))
2036 ivy--index)))
2037
2038 (defun ivy-recompute-index-zero (_re-str _cands)
2039 0)
2040
2041 (defcustom ivy-minibuffer-faces
2042 '(ivy-minibuffer-match-face-1
2043 ivy-minibuffer-match-face-2
2044 ivy-minibuffer-match-face-3
2045 ivy-minibuffer-match-face-4)
2046 "List of `ivy' faces for minibuffer group matches.")
2047
2048 (defvar ivy-flx-limit 200
2049 "Used to conditionally turn off flx sorting.
2050 When the amount of matching candidates is larger than this
2051 number, no sorting will be done.")
2052
2053 (defun ivy--flx-sort (name cands)
2054 "Sort according to closeness to string NAME the string list CANDS."
2055 (condition-case nil
2056 (if (and cands
2057 (< (length cands) ivy-flx-limit))
2058 (let* ((flx-name (if (string-match "^\\^" name)
2059 (substring name 1)
2060 name))
2061 (cands-with-score
2062 (delq nil
2063 (mapcar
2064 (lambda (x)
2065 (let ((score (flx-score x flx-name ivy--flx-cache)))
2066 (and score
2067 (cons score x))))
2068 cands))))
2069 (if cands-with-score
2070 (mapcar (lambda (x)
2071 (let ((str (copy-sequence (cdr x)))
2072 (i 0)
2073 (last-j -2))
2074 (dolist (j (cdar x))
2075 (unless (eq j (1+ last-j))
2076 (cl-incf i))
2077 (setq last-j j)
2078 (ivy-add-face-text-property
2079 j (1+ j)
2080 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2081 ivy-minibuffer-faces)
2082 str))
2083 str))
2084 (sort cands-with-score
2085 (lambda (x y)
2086 (> (caar x) (caar y)))))
2087 cands))
2088 cands)
2089 (error
2090 cands)))
2091
2092 (defcustom ivy-format-function 'ivy-format-function-default
2093 "Function to transform the list of candidates into a string.
2094 This string is inserted into the minibuffer."
2095 :type '(choice
2096 (const :tag "Default" ivy-format-function-default)
2097 (const :tag "Arrow prefix" ivy-format-function-arrow)
2098 (const :tag "Full line" ivy-format-function-line)))
2099
2100 (defun ivy--truncate-string (str width)
2101 "Truncate STR to WIDTH."
2102 (if (> (string-width str) width)
2103 (concat (substring str 0 (min (- width 3)
2104 (- (length str) 3))) "...")
2105 str))
2106
2107 (defun ivy--format-function-generic (selected-fn other-fn cand-pairs separator)
2108 "Transform CAND-PAIRS into a string for minibuffer.
2109 SELECTED-FN and OTHER-FN each take two string arguments.
2110 SEPARATOR is used to join the candidates."
2111 (let ((i -1))
2112 (mapconcat
2113 (lambda (pair)
2114 (let ((str (car pair))
2115 (extra (cdr pair))
2116 (curr (eq (cl-incf i) ivy--index)))
2117 (if curr
2118 (funcall selected-fn str extra)
2119 (funcall other-fn str extra))))
2120 cand-pairs
2121 separator)))
2122
2123 (defun ivy-format-function-default (cand-pairs)
2124 "Transform CAND-PAIRS into a string for minibuffer."
2125 (ivy--format-function-generic
2126 (lambda (str extra)
2127 (concat (ivy--add-face str 'ivy-current-match) extra))
2128 #'concat
2129 cand-pairs
2130 "\n"))
2131
2132 (defun ivy-format-function-arrow (cand-pairs)
2133 "Transform CAND-PAIRS into a string for minibuffer."
2134 (ivy--format-function-generic
2135 (lambda (str extra)
2136 (concat "> " (ivy--add-face str 'ivy-current-match) extra))
2137 (lambda (str extra)
2138 (concat " " str extra))
2139 cand-pairs
2140 "\n"))
2141
2142 (defun ivy-format-function-line (cand-pairs)
2143 "Transform CAND-PAIRS into a string for minibuffer."
2144 (ivy--format-function-generic
2145 (lambda (str extra)
2146 (ivy--add-face (concat str extra "\n") 'ivy-current-match))
2147 (lambda (str extra)
2148 (concat str extra "\n"))
2149 cand-pairs
2150 ""))
2151
2152 (defun ivy-add-face-text-property (start end face str)
2153 (if (fboundp 'add-face-text-property)
2154 (add-face-text-property
2155 start end face nil str)
2156 (font-lock-append-text-property
2157 start end 'face face str)))
2158
2159 (defun ivy--format-minibuffer-line (str)
2160 (let ((start 0)
2161 (str (copy-sequence str)))
2162 (cond ((eq ivy--regex-function 'ivy--regex-ignore-order)
2163 (when (consp ivy--old-re)
2164 (let ((i 1))
2165 (dolist (re ivy--old-re)
2166 (when (string-match (car re) str)
2167 (ivy-add-face-text-property
2168 (match-beginning 0) (match-end 0)
2169 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2170 ivy-minibuffer-faces)
2171 str))
2172 (cl-incf i)))))
2173 ((and (eq ivy-display-style 'fancy)
2174 (not (eq ivy--regex-function 'ivy--regex-fuzzy)))
2175 (unless ivy--old-re
2176 (setq ivy--old-re (funcall ivy--regex-function ivy-text)))
2177 (while (and (string-match ivy--old-re str start)
2178 (> (- (match-end 0) (match-beginning 0)) 0))
2179 (setq start (match-end 0))
2180 (let ((i 0))
2181 (while (<= i ivy--subexps)
2182 (let ((face
2183 (cond ((zerop ivy--subexps)
2184 (cadr ivy-minibuffer-faces))
2185 ((zerop i)
2186 (car ivy-minibuffer-faces))
2187 (t
2188 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2189 ivy-minibuffer-faces)))))
2190 (ivy-add-face-text-property
2191 (match-beginning i) (match-end i)
2192 face str))
2193 (cl-incf i))))))
2194 str))
2195
2196 (defun ivy--format (cands)
2197 "Return a string for CANDS suitable for display in the minibuffer.
2198 CANDS is a list of strings."
2199 (setq ivy--length (length cands))
2200 (when (>= ivy--index ivy--length)
2201 (setq ivy--index (max (1- ivy--length) 0)))
2202 (if (null cands)
2203 (setq ivy--current "")
2204 (let* ((half-height (/ ivy-height 2))
2205 (start (max 0 (- ivy--index half-height)))
2206 (end (min (+ start (1- ivy-height)) ivy--length))
2207 (start (max 0 (min start (- end (1- ivy-height)))))
2208 (cands (cl-subseq cands start end))
2209 (index (- ivy--index start)))
2210 (cond (ivy--directory
2211 (setq cands (mapcar (lambda (x)
2212 (if (string-match-p "/\\'" x)
2213 (propertize x 'face 'ivy-subdir)
2214 x))
2215 cands)))
2216 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
2217 (setq cands (mapcar (lambda (x)
2218 (let ((b (get-buffer x)))
2219 (if (and b
2220 (buffer-file-name b)
2221 (buffer-modified-p b))
2222 (propertize x 'face 'ivy-modified-buffer)
2223 x)))
2224 cands))))
2225 (setq ivy--current (copy-sequence (nth index cands)))
2226 (let* ((ivy--index index)
2227 (cand-pairs (mapcar
2228 (lambda (cand)
2229 (cons (ivy--format-minibuffer-line cand) nil)) cands))
2230 (res (concat "\n" (funcall ivy-format-function cand-pairs))))
2231 (put-text-property 0 (length res) 'read-only nil res)
2232 res))))
2233
2234 (defvar ivy--virtual-buffers nil
2235 "Store the virtual buffers alist.")
2236
2237 (defvar recentf-list)
2238
2239 (defcustom ivy-virtual-abbreviate 'name
2240 "The mode of abbreviation for virtual buffer names."
2241 :type '(choice
2242 (const :tag "Only name" name)
2243 (const :tag "Full path" full)
2244 ;; eventually, uniquify
2245 ))
2246
2247 (defun ivy--virtual-buffers ()
2248 "Adapted from `ido-add-virtual-buffers-to-list'."
2249 (unless recentf-mode
2250 (recentf-mode 1))
2251 (let ((bookmarks (and (boundp 'bookmark-alist)
2252 bookmark-alist))
2253 virtual-buffers name)
2254 (dolist (head (append
2255 recentf-list
2256 (delete " - no file -"
2257 (delq nil (mapcar (lambda (bookmark)
2258 (cdr (assoc 'filename bookmark)))
2259 bookmarks)))))
2260 (setq name
2261 (if (eq ivy-virtual-abbreviate 'name)
2262 (file-name-nondirectory head)
2263 (expand-file-name head)))
2264 (when (equal name "")
2265 (setq name (file-name-nondirectory (directory-file-name head))))
2266 (when (equal name "")
2267 (setq name head))
2268 (and (not (equal name ""))
2269 (null (get-file-buffer head))
2270 (not (assoc name virtual-buffers))
2271 (push (cons name head) virtual-buffers)))
2272 (when virtual-buffers
2273 (dolist (comp virtual-buffers)
2274 (put-text-property 0 (length (car comp))
2275 'face 'ivy-virtual
2276 (car comp)))
2277 (setq ivy--virtual-buffers (nreverse virtual-buffers))
2278 (mapcar #'car ivy--virtual-buffers))))
2279
2280 (defun ivy--buffer-list (str &optional virtual)
2281 "Return the buffers that match STR.
2282 When VIRTUAL is non-nil, add virtual buffers."
2283 (delete-dups
2284 (append
2285 (mapcar
2286 (lambda (x)
2287 (if (with-current-buffer x
2288 (file-remote-p
2289 (abbreviate-file-name default-directory)))
2290 (propertize x 'face 'ivy-remote)
2291 x))
2292 (all-completions str 'internal-complete-buffer))
2293 (and virtual
2294 (ivy--virtual-buffers)))))
2295
2296 (defun ivy--switch-buffer-action (buffer)
2297 "Switch to BUFFER.
2298 BUFFER may be a string or nil."
2299 (with-ivy-window
2300 (if (zerop (length buffer))
2301 (switch-to-buffer
2302 ivy-text nil 'force-same-window)
2303 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2304 (if (and virtual
2305 (not (get-buffer buffer)))
2306 (find-file (cdr virtual))
2307 (switch-to-buffer
2308 buffer nil 'force-same-window))))))
2309
2310 (defun ivy--switch-buffer-other-window-action (buffer)
2311 "Switch to BUFFER in other window.
2312 BUFFER may be a string or nil."
2313 (if (zerop (length buffer))
2314 (switch-to-buffer-other-window ivy-text)
2315 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2316 (if (and virtual
2317 (not (get-buffer buffer)))
2318 (find-file-other-window (cdr virtual))
2319 (switch-to-buffer-other-window buffer)))))
2320
2321 (defun ivy--rename-buffer-action (buffer)
2322 "Rename BUFFER."
2323 (let ((new-name (read-string "Rename buffer (to new name): ")))
2324 (with-current-buffer buffer
2325 (rename-buffer new-name))))
2326
2327 (defvar ivy-switch-buffer-map (make-sparse-keymap))
2328
2329 (ivy-set-actions
2330 'ivy-switch-buffer
2331 '(("k"
2332 (lambda (x)
2333 (kill-buffer x)
2334 (ivy--reset-state ivy-last))
2335 "kill")
2336 ("j"
2337 ivy--switch-buffer-other-window-action
2338 "other")
2339 ("r"
2340 ivy--rename-buffer-action
2341 "rename")))
2342
2343 ;;;###autoload
2344 (defun ivy-switch-buffer ()
2345 "Switch to another buffer."
2346 (interactive)
2347 (if (not ivy-mode)
2348 (call-interactively 'switch-to-buffer)
2349 (let ((this-command 'ivy-switch-buffer))
2350 (ivy-read "Switch to buffer: " 'internal-complete-buffer
2351 :preselect (buffer-name (other-buffer (current-buffer)))
2352 :action #'ivy--switch-buffer-action
2353 :keymap ivy-switch-buffer-map))))
2354
2355 ;;;###autoload
2356 (defun ivy-recentf ()
2357 "Find a file on `recentf-list'."
2358 (interactive)
2359 (ivy-read "Recentf: " recentf-list
2360 :action
2361 (lambda (f)
2362 (with-ivy-window
2363 (find-file f)))))
2364
2365 (defun ivy-yank-word ()
2366 "Pull next word from buffer into search string."
2367 (interactive)
2368 (let (amend)
2369 (with-ivy-window
2370 (let ((pt (point))
2371 (le (line-end-position)))
2372 (forward-word 1)
2373 (if (> (point) le)
2374 (goto-char pt)
2375 (setq amend (buffer-substring-no-properties pt (point))))))
2376 (when amend
2377 (insert (replace-regexp-in-string " +" " " amend)))))
2378
2379 (defun ivy-kill-ring-save ()
2380 "Store the current candidates into the kill ring.
2381 If the region is active, forward to `kill-ring-save' instead."
2382 (interactive)
2383 (if (region-active-p)
2384 (call-interactively 'kill-ring-save)
2385 (kill-new
2386 (mapconcat
2387 #'identity
2388 ivy--old-cands
2389 "\n"))))
2390
2391 (defun ivy-insert-current ()
2392 "Make the current candidate into current input.
2393 Don't finish completion."
2394 (interactive)
2395 (delete-minibuffer-contents)
2396 (if (and ivy--directory
2397 (string-match "/$" ivy--current))
2398 (insert (substring ivy--current 0 -1))
2399 (insert ivy--current)))
2400
2401 (defun ivy-toggle-fuzzy ()
2402 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
2403 (interactive)
2404 (setq ivy--old-re nil)
2405 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
2406 (setq ivy--regex-function 'ivy--regex-plus)
2407 (setq ivy--regex-function 'ivy--regex-fuzzy)))
2408
2409 (defun ivy-reverse-i-search ()
2410 "Enter a recursive `ivy-read' session using the current history.
2411 The selected history element will be inserted into the minibuffer."
2412 (interactive)
2413 (let ((enable-recursive-minibuffers t)
2414 (history (symbol-value (ivy-state-history ivy-last)))
2415 (old-last ivy-last)
2416 (ivy-recursive-restore nil))
2417 (ivy-read "Reverse-i-search: "
2418 history
2419 :action (lambda (x)
2420 (ivy--reset-state
2421 (setq ivy-last old-last))
2422 (delete-minibuffer-contents)
2423 (insert (substring-no-properties x))
2424 (ivy--cd-maybe)))))
2425
2426 (defun ivy-restrict-to-matches ()
2427 "Restrict candidates to current matches and erase input."
2428 (interactive)
2429 (delete-minibuffer-contents)
2430 (setq ivy--all-candidates
2431 (ivy--filter ivy-text ivy--all-candidates)))
2432
2433 ;;* Occur
2434 (defvar-local ivy-occur-last nil
2435 "Buffer-local value of `ivy-last'.
2436 Can't re-use `ivy-last' because using e.g. `swiper' in the same
2437 buffer would modify `ivy-last'.")
2438
2439 (defvar ivy-occur-mode-map
2440 (let ((map (make-sparse-keymap)))
2441 (define-key map [mouse-1] 'ivy-occur-click)
2442 (define-key map (kbd "RET") 'ivy-occur-press)
2443 (define-key map (kbd "j") 'next-line)
2444 (define-key map (kbd "k") 'previous-line)
2445 (define-key map (kbd "h") 'backward-char)
2446 (define-key map (kbd "l") 'forward-char)
2447 (define-key map (kbd "g") 'ivy-occur-press)
2448 (define-key map (kbd "a") 'ivy-occur-read-action)
2449 (define-key map (kbd "o") 'ivy-occur-dispatch)
2450 (define-key map (kbd "q") 'quit-window)
2451 map)
2452 "Keymap for Ivy Occur mode.")
2453
2454 (define-derived-mode ivy-occur-mode fundamental-mode "Ivy-Occur"
2455 "Major mode for output from \\[ivy-occur].
2456
2457 \\{ivy-occur-mode-map}")
2458
2459 (defvar ivy-occur-grep-mode-map
2460 (let ((map (copy-keymap ivy-occur-mode-map)))
2461 (define-key map (kbd "C-x C-q") 'ivy-wgrep-change-to-wgrep-mode)
2462 map)
2463 "Keymap for Ivy Occur Grep mode.")
2464
2465 (define-derived-mode ivy-occur-grep-mode grep-mode "Ivy-Occur"
2466 "Major mode for output from \\[ivy-occur].
2467
2468 \\{ivy-occur-grep-mode-map}")
2469
2470 (defvar counsel-git-grep-cmd)
2471
2472 (defun ivy-occur ()
2473 "Stop completion and put the current matches into a new buffer.
2474
2475 The new buffer remembers current action(s).
2476
2477 While in the *ivy-occur* buffer, selecting a candidate with RET or
2478 a mouse click will call the appropriate action for that candidate.
2479
2480 There is no limit on the number of *ivy-occur* buffers."
2481 (interactive)
2482 (let ((buffer
2483 (generate-new-buffer
2484 (format "*ivy-occur%s \"%s\"*"
2485 (let (caller)
2486 (if (setq caller (ivy-state-caller ivy-last))
2487 (concat " " (prin1-to-string caller))
2488 ""))
2489 ivy-text)))
2490 (do-grep (eq (ivy-state-caller ivy-last) 'counsel-git-grep)))
2491 (with-current-buffer buffer
2492 (if do-grep
2493 (progn
2494 (setq ivy--old-cands
2495 (split-string
2496 (shell-command-to-string
2497 (format counsel-git-grep-cmd
2498 (if (stringp ivy--old-re)
2499 ivy--old-re
2500 (caar ivy--old-re))))
2501 "\n"
2502 t))
2503 (ivy-occur-grep-mode))
2504 (ivy-occur-mode))
2505 (setf (ivy-state-text ivy-last) ivy-text)
2506 (setq ivy-occur-last ivy-last)
2507 (setq-local ivy--directory ivy--directory)
2508 (let ((inhibit-read-only t))
2509 (erase-buffer)
2510 (when do-grep
2511 ;; Need precise number of header lines for `wgrep' to work.
2512 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
2513 default-directory)))
2514 (insert (format "%d candidates:\n" (length ivy--old-cands)))
2515 (dolist (cand ivy--old-cands)
2516 (let ((str (if do-grep
2517 (concat "./" cand)
2518 (concat " " cand))))
2519 (add-text-properties
2520 0 (length str)
2521 `(mouse-face
2522 highlight
2523 help-echo "mouse-1: call ivy-action")
2524 str)
2525 (insert str "\n")))))
2526 (ivy-exit-with-action
2527 `(lambda (_) (pop-to-buffer ,buffer)))))
2528
2529 (declare-function wgrep-change-to-wgrep-mode "ext:wgrep")
2530
2531 (defun ivy-wgrep-change-to-wgrep-mode ()
2532 "Forward to `wgrep-change-to-wgrep-mode'."
2533 (interactive)
2534 (if (require 'wgrep nil 'noerror)
2535 (wgrep-change-to-wgrep-mode)
2536 (error "Package wgrep isn't installed")))
2537
2538 (defun ivy-occur-read-action ()
2539 "Select one of the available actions as the current one."
2540 (interactive)
2541 (let ((ivy-last ivy-occur-last))
2542 (ivy-read-action)))
2543
2544 (defun ivy-occur-dispatch ()
2545 "Call one of the available actions on the current item."
2546 (interactive)
2547 (let* ((state-action (ivy-state-action ivy-occur-last))
2548 (actions (if (symbolp state-action)
2549 state-action
2550 (copy-sequence state-action))))
2551 (unwind-protect
2552 (progn
2553 (ivy-occur-read-action)
2554 (ivy-occur-press))
2555 (setf (ivy-state-action ivy-occur-last) actions))))
2556
2557 (defun ivy-occur-click (event)
2558 "Execute action for the current candidate.
2559 EVENT gives the mouse position."
2560 (interactive "e")
2561 (let ((window (posn-window (event-end event)))
2562 (pos (posn-point (event-end event))))
2563 (with-current-buffer (window-buffer window)
2564 (goto-char pos)
2565 (ivy-occur-press))))
2566
2567 (declare-function swiper--cleanup "swiper")
2568 (declare-function swiper--add-overlays "swiper")
2569
2570 (defun ivy-occur-press ()
2571 "Execute action for the current candidate."
2572 (interactive)
2573 (require 'pulse)
2574 (when (save-excursion
2575 (beginning-of-line)
2576 (looking-at "\\(?:./\\| \\)\\(.*\\)$"))
2577 (let* ((ivy-last ivy-occur-last)
2578 (ivy-text (ivy-state-text ivy-last))
2579 (str (buffer-substring
2580 (match-beginning 1)
2581 (match-end 1)))
2582 (coll (ivy-state-collection ivy-last))
2583 (action (ivy--get-action ivy-last))
2584 (ivy-exit 'done))
2585 (with-ivy-window
2586 (funcall action
2587 (if (and (consp coll)
2588 (consp (car coll)))
2589 (cdr (assoc str coll))
2590 str))
2591 (if (memq (ivy-state-caller ivy-last)
2592 '(swiper counsel-git-grep))
2593 (with-current-buffer (window-buffer (selected-window))
2594 (swiper--cleanup)
2595 (swiper--add-overlays
2596 (ivy--regex ivy-text)
2597 (line-beginning-position)
2598 (line-end-position)
2599 (selected-window))
2600 (run-at-time 0.5 nil 'swiper--cleanup))
2601 (pulse-momentary-highlight-one-line (point)))))))
2602
2603 (provide 'ivy)
2604
2605 ;;; ivy.el ends here