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