]> code.delx.au - gnu-emacs-elpa/blob - ivy.el
b9579acde2e3bd2a13e3b19d7909a46914d5bb2b
[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 (if (functionp action)
1123 `(1
1124 ("o" ,action "default")
1125 ,@extra-actions)
1126 (delete-dups (append action extra-actions))))))
1127 (let ((recursive-ivy-last (and (active-minibuffer-window) ivy-last)))
1128 (setq ivy-last
1129 (make-ivy-state
1130 :prompt prompt
1131 :collection collection
1132 :predicate predicate
1133 :require-match require-match
1134 :initial-input initial-input
1135 :history history
1136 :preselect preselect
1137 :keymap keymap
1138 :update-fn update-fn
1139 :sort sort
1140 :action action
1141 :window (selected-window)
1142 :buffer (current-buffer)
1143 :unwind unwind
1144 :re-builder re-builder
1145 :matcher matcher
1146 :dynamic-collection dynamic-collection
1147 :caller caller))
1148 (ivy--reset-state ivy-last)
1149 (prog1
1150 (unwind-protect
1151 (minibuffer-with-setup-hook
1152 #'ivy--minibuffer-setup
1153 (let* ((hist (or history 'ivy-history))
1154 (minibuffer-completion-table collection)
1155 (minibuffer-completion-predicate predicate)
1156 (resize-mini-windows (cond
1157 ((display-graphic-p) nil)
1158 ((null resize-mini-windows) 'grow-only)
1159 (t resize-mini-windows))))
1160 (read-from-minibuffer
1161 prompt
1162 (ivy-state-initial-input ivy-last)
1163 (make-composed-keymap keymap ivy-minibuffer-map)
1164 nil
1165 hist)
1166 (when (eq ivy-exit 'done)
1167 (let ((item (if ivy--directory
1168 ivy--current
1169 ivy-text)))
1170 (unless (equal item "")
1171 (set hist (cons (propertize item 'ivy-index ivy--index)
1172 (delete item
1173 (cdr (symbol-value hist))))))))
1174 ivy--current))
1175 (remove-hook 'post-command-hook #'ivy--exhibit)
1176 (when (setq unwind (ivy-state-unwind ivy-last))
1177 (funcall unwind))
1178 (unless (eq ivy-exit 'done)
1179 (when recursive-ivy-last
1180 (ivy--reset-state (setq ivy-last recursive-ivy-last)))))
1181 (ivy-call)
1182 (when (and recursive-ivy-last
1183 ivy-recursive-restore)
1184 (ivy--reset-state (setq ivy-last recursive-ivy-last))))))
1185
1186 (defun ivy--reset-state (state)
1187 "Reset the ivy to STATE.
1188 This is useful for recursive `ivy-read'."
1189 (let ((prompt (or (ivy-state-prompt state) ""))
1190 (collection (ivy-state-collection state))
1191 (predicate (ivy-state-predicate state))
1192 (history (ivy-state-history state))
1193 (preselect (ivy-state-preselect state))
1194 (sort (ivy-state-sort state))
1195 (re-builder (ivy-state-re-builder state))
1196 (dynamic-collection (ivy-state-dynamic-collection state))
1197 (initial-input (ivy-state-initial-input state))
1198 (require-match (ivy-state-require-match state))
1199 (caller (ivy-state-caller state)))
1200 (unless initial-input
1201 (setq initial-input (cdr (assoc this-command
1202 ivy-initial-inputs-alist))))
1203 (setq ivy--directory nil)
1204 (setq ivy-case-fold-search 'auto)
1205 (setq ivy--regex-function
1206 (or re-builder
1207 (and (functionp collection)
1208 (cdr (assoc collection ivy-re-builders-alist)))
1209 (and caller
1210 (cdr (assoc caller ivy-re-builders-alist)))
1211 (cdr (assoc this-command ivy-re-builders-alist))
1212 (cdr (assoc t ivy-re-builders-alist))
1213 'ivy--regex))
1214 (setq ivy--subexps 0)
1215 (setq ivy--regexp-quote 'regexp-quote)
1216 (setq ivy--old-text "")
1217 (setq ivy--full-length nil)
1218 (setq ivy-text "")
1219 (setq ivy-calling nil)
1220 (let (coll sort-fn)
1221 (cond ((eq collection 'Info-read-node-name-1)
1222 (if (equal Info-current-file "dir")
1223 (setq coll
1224 (mapcar (lambda (x) (format "(%s)" x))
1225 (cl-delete-duplicates
1226 (all-completions "(" collection predicate)
1227 :test #'equal)))
1228 (setq coll (all-completions "" collection predicate))))
1229 ((eq collection 'read-file-name-internal)
1230 (setq ivy--directory default-directory)
1231 (require 'dired)
1232 (when preselect
1233 (let ((preselect-directory (file-name-directory preselect)))
1234 (unless (or (null preselect-directory)
1235 (string= preselect-directory
1236 default-directory))
1237 (setq ivy--directory preselect-directory))
1238 (setf
1239 (ivy-state-preselect state)
1240 (setq preselect (file-name-nondirectory preselect)))))
1241 (setq coll (ivy--sorted-files ivy--directory))
1242 (when initial-input
1243 (unless (or require-match
1244 (equal initial-input default-directory)
1245 (equal initial-input ""))
1246 (setq coll (cons initial-input coll)))
1247 (unless (ivy-state-action ivy-last)
1248 (setq initial-input nil))))
1249 ((eq collection 'internal-complete-buffer)
1250 (setq coll (ivy--buffer-list "" ivy-use-virtual-buffers)))
1251 (dynamic-collection
1252 (setq coll (funcall collection ivy-text)))
1253 ((or (functionp collection)
1254 (byte-code-function-p collection)
1255 (vectorp collection)
1256 (and (consp collection) (listp (car collection)))
1257 (hash-table-p collection))
1258 (setq coll (all-completions "" collection predicate)))
1259 (t
1260 (setq coll collection)))
1261 (when sort
1262 (if (and (functionp collection)
1263 (setq sort-fn (assoc collection ivy-sort-functions-alist)))
1264 (when (and (setq sort-fn (cdr sort-fn))
1265 (not (eq collection 'read-file-name-internal)))
1266 (setq coll (cl-sort coll sort-fn)))
1267 (unless (eq history 'org-refile-history)
1268 (if (and (setq sort-fn (cdr (assoc t ivy-sort-functions-alist)))
1269 (<= (length coll) ivy-sort-max-size))
1270 (setq coll (cl-sort (copy-sequence coll) sort-fn))))))
1271 (when preselect
1272 (unless (or (and require-match
1273 (not (eq collection 'internal-complete-buffer)))
1274 dynamic-collection
1275 (let ((re (regexp-quote preselect)))
1276 (cl-find-if (lambda (x) (string-match re x))
1277 coll)))
1278 (setq coll (cons preselect coll))))
1279 (setq ivy--old-re nil)
1280 (setq ivy--old-cands nil)
1281 (when (integerp preselect)
1282 (setq ivy--old-re "")
1283 (setq ivy--index preselect))
1284 (when initial-input
1285 ;; Needed for anchor to work
1286 (setq ivy--old-cands coll)
1287 (setq ivy--old-cands (ivy--filter initial-input coll)))
1288 (setq ivy--all-candidates coll)
1289 (unless (integerp preselect)
1290 (setq ivy--index (or
1291 (and dynamic-collection
1292 ivy--index)
1293 (and preselect
1294 (ivy--preselect-index
1295 preselect
1296 (if initial-input
1297 ivy--old-cands
1298 coll)))
1299 0))))
1300 (setq ivy-exit nil)
1301 (setq ivy--default (or
1302 (thing-at-point 'url)
1303 (thing-at-point 'symbol)
1304 ""))
1305 (setq ivy--prompt
1306 (cond ((string-match "%.*d" prompt)
1307 prompt)
1308 ((null ivy-count-format)
1309 (error
1310 "`ivy-count-format' can't be nil. Set it to an empty string instead"))
1311 ((string-match "%d.*%d" ivy-count-format)
1312 (let ((w (length (number-to-string
1313 (length ivy--all-candidates))))
1314 (s (copy-sequence ivy-count-format)))
1315 (string-match "%d" s)
1316 (match-end 0)
1317 (string-match "%d" s (match-end 0))
1318 (setq s (replace-match (format "%%-%dd" w) nil nil s))
1319 (string-match "%d" s)
1320 (concat (replace-match (format "%%%dd" w) nil nil s)
1321 prompt)))
1322 ((string-match "%.*d" ivy-count-format)
1323 (concat ivy-count-format prompt))
1324 (ivy--directory
1325 prompt)
1326 (t
1327 nil)))
1328 (setf (ivy-state-initial-input ivy-last) initial-input)))
1329
1330 ;;;###autoload
1331 (defun ivy-completing-read (prompt collection
1332 &optional predicate require-match initial-input
1333 history def inherit-input-method)
1334 "Read a string in the minibuffer, with completion.
1335
1336 This interface conforms to `completing-read' and can be used for
1337 `completing-read-function'.
1338
1339 PROMPT is a string to prompt with; normally it ends in a colon and a space.
1340 COLLECTION can be a list of strings, an alist, an obarray or a hash table.
1341 PREDICATE limits completion to a subset of COLLECTION.
1342 REQUIRE-MATCH is specified with a boolean value. See `completing-read'.
1343 INITIAL-INPUT is a string that can be inserted into the minibuffer initially.
1344 HISTORY is a list of previously selected inputs.
1345 DEF is the default value.
1346 INHERIT-INPUT-METHOD is currently ignored."
1347 (if (memq this-command '(tmm-menubar tmm-shortcut))
1348 (completing-read-default prompt collection
1349 predicate require-match
1350 initial-input history
1351 def inherit-input-method)
1352 ;; See the doc of `completing-read'.
1353 (when (consp history)
1354 (when (numberp (cdr history))
1355 (setq initial-input (nth (1- (cdr history))
1356 (symbol-value (car history)))))
1357 (setq history (car history)))
1358 (ivy-read (replace-regexp-in-string "%" "%%" prompt)
1359 collection
1360 :predicate predicate
1361 :require-match require-match
1362 :initial-input (if (consp initial-input)
1363 (car initial-input)
1364 (if (and (stringp initial-input)
1365 (string-match "\\+" initial-input))
1366 (replace-regexp-in-string
1367 "\\+" "\\\\+" initial-input)
1368 initial-input))
1369 :preselect (if (listp def) (car def) def)
1370 :history history
1371 :keymap nil
1372 :sort
1373 (let ((sort (assoc this-command ivy-sort-functions-alist)))
1374 (if sort
1375 (cdr sort)
1376 t)))))
1377
1378 (defvar ivy-completion-beg nil
1379 "Completion bounds start.")
1380
1381 (defvar ivy-completion-end nil
1382 "Completion bounds end.")
1383
1384 (defun ivy-completion-in-region-action (str)
1385 "Insert STR, erasing the previous one.
1386 The previous string is between `ivy-completion-beg' and `ivy-completion-end'."
1387 (when (stringp str)
1388 (with-ivy-window
1389 (when ivy-completion-beg
1390 (delete-region
1391 ivy-completion-beg
1392 ivy-completion-end))
1393 (setq ivy-completion-beg
1394 (move-marker (make-marker) (point)))
1395 (insert str)
1396 (setq ivy-completion-end
1397 (move-marker (make-marker) (point))))))
1398
1399 (defun ivy-completion-common-length (str)
1400 "Return the length of the first 'completions-common-part face in STR."
1401 (let ((pos 0)
1402 (len (length str)))
1403 (while (and (<= pos len)
1404 (let ((prop (get-text-property pos 'face str)))
1405 (not (eq 'completions-common-part
1406 (if (listp prop) (car prop) prop)))))
1407 (setq pos (1+ pos)))
1408 (if (< pos len)
1409 (or (next-single-property-change pos 'face str) len)
1410 0)))
1411
1412 (defun ivy-completion-in-region (start end collection &optional predicate)
1413 "An Ivy function suitable for `completion-in-region-function'."
1414 (let* ((enable-recursive-minibuffers t)
1415 (str (buffer-substring-no-properties start end))
1416 (comps
1417 (completion-all-completions str collection predicate (- end start))))
1418 (if (null comps)
1419 (message "No matches")
1420 (nconc comps nil)
1421 (setq ivy-completion-beg (- end (ivy-completion-common-length (car comps))))
1422 (setq ivy-completion-end end)
1423 (if (null (cdr comps))
1424 (if (string= str (car comps))
1425 (message "Sole match")
1426 (setf (ivy-state-window ivy-last) (selected-window))
1427 (ivy-completion-in-region-action
1428 (substring-no-properties
1429 (car comps))))
1430 (let* ((w (1+ (floor (log (length comps) 10))))
1431 (ivy-count-format (if (string= ivy-count-format "")
1432 ivy-count-format
1433 (format "%%-%dd " w)))
1434 (prompt (format "(%s): " str)))
1435 (and
1436 (ivy-read (if (string= ivy-count-format "")
1437 prompt
1438 (replace-regexp-in-string "%" "%%" prompt))
1439 ;; remove 'completions-first-difference face
1440 (mapcar #'substring-no-properties comps)
1441 :predicate predicate
1442 :action #'ivy-completion-in-region-action
1443 :require-match t)
1444 t))))))
1445
1446 ;;;###autoload
1447 (define-minor-mode ivy-mode
1448 "Toggle Ivy mode on or off.
1449 Turn Ivy mode on if ARG is positive, off otherwise.
1450 Turning on Ivy mode sets `completing-read-function' to
1451 `ivy-completing-read'.
1452
1453 Global bindings:
1454 \\{ivy-mode-map}
1455
1456 Minibuffer bindings:
1457 \\{ivy-minibuffer-map}"
1458 :group 'ivy
1459 :global t
1460 :keymap ivy-mode-map
1461 :lighter " ivy"
1462 (if ivy-mode
1463 (progn
1464 (setq completing-read-function 'ivy-completing-read)
1465 (setq completion-in-region-function 'ivy-completion-in-region))
1466 (setq completing-read-function 'completing-read-default)
1467 (setq completion-in-region-function 'completion--in-region)))
1468
1469 (defun ivy--preselect-index (preselect candidates)
1470 "Return the index of PRESELECT in CANDIDATES."
1471 (cond ((integerp preselect)
1472 preselect)
1473 ((cl-position preselect candidates :test #'equal))
1474 ((stringp preselect)
1475 (let ((re (regexp-quote preselect)))
1476 (cl-position-if
1477 (lambda (x)
1478 (string-match re x))
1479 candidates)))))
1480
1481 ;;* Implementation
1482 ;;** Regex
1483 (defvar ivy--regex-hash
1484 (make-hash-table :test #'equal)
1485 "Store pre-computed regex.")
1486
1487 (defun ivy--split (str)
1488 "Split STR into a list by single spaces.
1489 The remaining spaces stick to their left.
1490 This allows to \"quote\" N spaces by inputting N+1 spaces."
1491 (let ((len (length str))
1492 start0
1493 (start1 0)
1494 res s
1495 match-len)
1496 (while (and (string-match " +" str start1)
1497 (< start1 len))
1498 (setq match-len (- (match-end 0) (match-beginning 0)))
1499 (if (= match-len 1)
1500 (progn
1501 (when start0
1502 (setq start1 start0)
1503 (setq start0 nil))
1504 (push (substring str start1 (match-beginning 0)) res)
1505 (setq start1 (match-end 0)))
1506 (setq str (replace-match
1507 (make-string (1- match-len) ?\ )
1508 nil nil str))
1509 (setq start0 (or start0 start1))
1510 (setq start1 (1- (match-end 0)))))
1511 (if start0
1512 (push (substring str start0) res)
1513 (setq s (substring str start1))
1514 (unless (= (length s) 0)
1515 (push s res)))
1516 (nreverse res)))
1517
1518 (defun ivy--regex (str &optional greedy)
1519 "Re-build regex pattern from STR in case it has a space.
1520 When GREEDY is non-nil, join words in a greedy way."
1521 (let ((hashed (unless greedy
1522 (gethash str ivy--regex-hash))))
1523 (if hashed
1524 (prog1 (cdr hashed)
1525 (setq ivy--subexps (car hashed)))
1526 (when (string-match "\\([^\\]\\|^\\)\\\\$" str)
1527 (setq str (substring str 0 -1)))
1528 (cdr (puthash str
1529 (let ((subs (ivy--split str)))
1530 (if (= (length subs) 1)
1531 (cons
1532 (setq ivy--subexps 0)
1533 (car subs))
1534 (cons
1535 (setq ivy--subexps (length subs))
1536 (mapconcat
1537 (lambda (x)
1538 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1539 x
1540 (format "\\(%s\\)" x)))
1541 subs
1542 (if greedy
1543 ".*"
1544 ".*?")))))
1545 ivy--regex-hash)))))
1546
1547 (defun ivy--regex-ignore-order--part (str &optional discard)
1548 "Re-build regex from STR by splitting at spaces.
1549 Ignore the order of each group."
1550 (let* ((subs (split-string str " +" t))
1551 (len (length subs)))
1552 (cl-case len
1553 (0
1554 "")
1555 (t
1556 (mapcar (lambda (x) (cons x (not discard)))
1557 subs)))))
1558
1559 (defun ivy--regex-ignore-order (str)
1560 "Re-build regex from STR by splitting at spaces.
1561 Ignore the order of each group. Everything before \"!\" should
1562 match. Everything after \"!\" should not match."
1563 (let ((parts (split-string str "!" t)))
1564 (cl-case (length parts)
1565 (0
1566 "")
1567 (1
1568 (if (string= (substring str 0 1) "!")
1569 (list (cons "" t)
1570 (ivy--regex-ignore-order--part (car parts) t))
1571 (ivy--regex-ignore-order--part (car parts))))
1572 (2
1573 (append
1574 (ivy--regex-ignore-order--part (car parts))
1575 (ivy--regex-ignore-order--part (cadr parts) t)))
1576 (t (error "Unexpected: use only one !")))))
1577
1578 (defun ivy--regex-plus (str)
1579 "Build a regex sequence from STR.
1580 Spaces are wild card characters, everything before \"!\" should
1581 match. Everything after \"!\" should not match."
1582 (let ((parts (split-string str "!" t)))
1583 (cl-case (length parts)
1584 (0
1585 "")
1586 (1
1587 (if (string= (substring str 0 1) "!")
1588 (list (cons "" t)
1589 (list (ivy--regex (car parts))))
1590 (ivy--regex (car parts))))
1591 (2
1592 (cons
1593 (cons (ivy--regex (car parts)) t)
1594 (mapcar #'list (split-string (cadr parts) " " t))))
1595 (t (error "Unexpected: use only one !")))))
1596
1597 (defun ivy--regex-fuzzy (str)
1598 "Build a regex sequence from STR.
1599 Insert .* between each char."
1600 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1601 (prog1
1602 (concat (match-string 1 str)
1603 (mapconcat
1604 (lambda (x)
1605 (format "\\(%c\\)" x))
1606 (string-to-list (match-string 2 str)) ".*")
1607 (match-string 3 str))
1608 (setq ivy--subexps (length (match-string 2 str))))
1609 str))
1610
1611 ;;** Rest
1612 (defun ivy--minibuffer-setup ()
1613 "Setup ivy completion in the minibuffer."
1614 (set (make-local-variable 'completion-show-inline-help) nil)
1615 (set (make-local-variable 'minibuffer-default-add-function)
1616 (lambda ()
1617 (list ivy--default)))
1618 (when (display-graphic-p)
1619 (setq truncate-lines t))
1620 (setq-local max-mini-window-height ivy-height)
1621 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1622 ;; show completions with empty input
1623 (ivy--exhibit))
1624
1625 (defun ivy--input ()
1626 "Return the current minibuffer input."
1627 ;; assume one-line minibuffer input
1628 (buffer-substring-no-properties
1629 (minibuffer-prompt-end)
1630 (line-end-position)))
1631
1632 (defun ivy--cleanup ()
1633 "Delete the displayed completion candidates."
1634 (save-excursion
1635 (goto-char (minibuffer-prompt-end))
1636 (delete-region (line-end-position) (point-max))))
1637
1638 (defun ivy--insert-prompt ()
1639 "Update the prompt according to `ivy--prompt'."
1640 (when ivy--prompt
1641 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1642 counsel-find-symbol))
1643 (setq ivy--prompt-extra ""))
1644 (let (head tail)
1645 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1646 (progn
1647 (setq head (match-string 1 ivy--prompt))
1648 (setq tail ": "))
1649 (setq head (substring ivy--prompt 0 -1))
1650 (setq tail " "))
1651 (let ((inhibit-read-only t)
1652 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1653 (n-str
1654 (concat
1655 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1656 (> (minibuffer-depth) 1))
1657 (format "[%d] " (minibuffer-depth))
1658 "")
1659 (concat
1660 (if (string-match "%d.*%d" ivy-count-format)
1661 (format head
1662 (1+ ivy--index)
1663 (or (and (ivy-state-dynamic-collection ivy-last)
1664 ivy--full-length)
1665 ivy--length))
1666 (format head
1667 (or (and (ivy-state-dynamic-collection ivy-last)
1668 ivy--full-length)
1669 ivy--length)))
1670 ivy--prompt-extra
1671 tail)))
1672 (d-str (if ivy--directory
1673 (abbreviate-file-name ivy--directory)
1674 "")))
1675 (save-excursion
1676 (goto-char (point-min))
1677 (delete-region (point-min) (minibuffer-prompt-end))
1678 (if (> (+ (mod (+ (length n-str) (length d-str)) (window-width))
1679 (length ivy-text))
1680 (window-width))
1681 (setq n-str (concat n-str "\n" d-str))
1682 (setq n-str (concat n-str d-str)))
1683 (let ((regex (format "\\([^\n]\\{%d\\}\\)[^\n]" (window-width))))
1684 (while (string-match regex n-str)
1685 (setq n-str (replace-match (concat (match-string 1 n-str) "\n") nil t n-str 1))))
1686 (set-text-properties 0 (length n-str)
1687 `(face minibuffer-prompt ,@std-props)
1688 n-str)
1689 (ivy--set-match-props n-str "confirm"
1690 `(face ivy-confirm-face ,@std-props))
1691 (ivy--set-match-props n-str "match required"
1692 `(face ivy-match-required-face ,@std-props))
1693 (insert n-str))
1694 ;; get out of the prompt area
1695 (constrain-to-field nil (point-max))))))
1696
1697 (defun ivy--set-match-props (str match props)
1698 "Set STR text properties that match MATCH to PROPS."
1699 (when (string-match match str)
1700 (set-text-properties
1701 (match-beginning 0)
1702 (match-end 0)
1703 props
1704 str)))
1705
1706 (defvar inhibit-message)
1707
1708 (defun ivy--sort-maybe (collection)
1709 "Sort COLLECTION if needed."
1710 (let ((sort (ivy-state-sort ivy-last))
1711 entry)
1712 (if (null sort)
1713 collection
1714 (let ((sort-fn (cond ((functionp sort)
1715 sort)
1716 ((setq entry (assoc (ivy-state-collection ivy-last)
1717 ivy-sort-functions-alist))
1718 (cdr entry))
1719 (t
1720 (cdr (assoc t ivy-sort-functions-alist))))))
1721 (if (functionp sort-fn)
1722 (cl-sort (copy-sequence collection) sort-fn)
1723 collection)))))
1724
1725 (defun ivy--exhibit ()
1726 "Insert Ivy completions display.
1727 Should be run via minibuffer `post-command-hook'."
1728 (when (memq 'ivy--exhibit post-command-hook)
1729 (let ((inhibit-field-text-motion nil))
1730 (constrain-to-field nil (point-max)))
1731 (setq ivy-text (ivy--input))
1732 (if (ivy-state-dynamic-collection ivy-last)
1733 ;; while-no-input would cause annoying
1734 ;; "Waiting for process to die...done" message interruptions
1735 (let ((inhibit-message t))
1736 (unless (equal ivy--old-text ivy-text)
1737 (while-no-input
1738 (setq ivy--all-candidates
1739 (ivy--sort-maybe
1740 (funcall (ivy-state-collection ivy-last) ivy-text)))
1741 (setq ivy--old-text ivy-text)))
1742 (when ivy--all-candidates
1743 (ivy--insert-minibuffer
1744 (ivy--format ivy--all-candidates))))
1745 (cond (ivy--directory
1746 (if (string-match "/\\'" ivy-text)
1747 (if (member ivy-text ivy--all-candidates)
1748 (ivy--cd (expand-file-name ivy-text ivy--directory))
1749 (when (string-match "//\\'" ivy-text)
1750 (if (and default-directory
1751 (string-match "\\`[[:alpha:]]:/" default-directory))
1752 (ivy--cd (match-string 0 default-directory))
1753 (ivy--cd "/")))
1754 (when (string-match "[[:alpha:]]:/$" ivy-text)
1755 (let ((drive-root (match-string 0 ivy-text)))
1756 (when (file-exists-p drive-root)
1757 (ivy--cd drive-root)))))
1758 (if (string-match "\\`~\\'" ivy-text)
1759 (ivy--cd (expand-file-name "~/")))))
1760 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1761 (when (or (and (string-match "\\` " ivy-text)
1762 (not (string-match "\\` " ivy--old-text)))
1763 (and (string-match "\\` " ivy--old-text)
1764 (not (string-match "\\` " ivy-text))))
1765 (setq ivy--all-candidates
1766 (if (and (> (length ivy-text) 0)
1767 (eq (aref ivy-text 0)
1768 ?\ ))
1769 (ivy--buffer-list " ")
1770 (ivy--buffer-list "" ivy-use-virtual-buffers)))
1771 (setq ivy--old-re nil))))
1772 (ivy--insert-minibuffer
1773 (with-current-buffer (ivy-state-buffer ivy-last)
1774 (ivy--format
1775 (ivy--filter ivy-text ivy--all-candidates))))
1776 (setq ivy--old-text ivy-text))))
1777
1778 (defun ivy--insert-minibuffer (text)
1779 "Insert TEXT into minibuffer with appropriate cleanup."
1780 (let ((resize-mini-windows nil)
1781 (update-fn (ivy-state-update-fn ivy-last))
1782 deactivate-mark)
1783 (ivy--cleanup)
1784 (when update-fn
1785 (funcall update-fn))
1786 (ivy--insert-prompt)
1787 ;; Do nothing if while-no-input was aborted.
1788 (when (stringp text)
1789 (let ((buffer-undo-list t))
1790 (save-excursion
1791 (forward-line 1)
1792 (insert text))))
1793 (when (display-graphic-p)
1794 (ivy--resize-minibuffer-to-fit))))
1795
1796 (defun ivy--resize-minibuffer-to-fit ()
1797 "Resize the minibuffer window size to fit the text in the minibuffer."
1798 (with-selected-window (minibuffer-window)
1799 (if (fboundp 'window-text-pixel-size)
1800 (let ((text-height (cdr (window-text-pixel-size)))
1801 (body-height (window-body-height nil t)))
1802 (when (> text-height body-height)
1803 ;; Note: the size increment needs to be at least frame-char-height,
1804 ;; otherwise resizing won't do anything.
1805 (let ((delta (max (- text-height body-height) (frame-char-height))))
1806 (window-resize nil delta nil t t))))
1807 (let ((text-height (count-screen-lines))
1808 (body-height (window-body-height)))
1809 (when (> text-height body-height)
1810 (window-resize nil (- text-height body-height) nil t))))))
1811
1812 (declare-function colir-blend-face-background "ext:colir")
1813
1814 (defun ivy--add-face (str face)
1815 "Propertize STR with FACE.
1816 `font-lock-append-text-property' is used, since it's better than
1817 `propertize' or `add-face-text-property' in this case."
1818 (require 'colir)
1819 (condition-case nil
1820 (progn
1821 (colir-blend-face-background 0 (length str) face str)
1822 (let ((foreground (face-foreground face)))
1823 (when foreground
1824 (add-face-text-property
1825 0 (length str)
1826 `(:foreground ,foreground)
1827 nil
1828 str))))
1829 (error
1830 (ignore-errors
1831 (font-lock-append-text-property 0 (length str) 'face face str))))
1832 str)
1833
1834 (declare-function flx-make-string-cache "ext:flx")
1835 (declare-function flx-score "ext:flx")
1836
1837 (defvar ivy--flx-cache nil)
1838
1839 (eval-after-load 'flx
1840 '(setq ivy--flx-cache (flx-make-string-cache)))
1841
1842 (defun ivy-toggle-case-fold ()
1843 "Toggle the case folding between nil and auto.
1844 In any completion session, the case folding starts in auto:
1845
1846 - when the input is all lower case, `case-fold-search' is t
1847 - otherwise nil.
1848
1849 You can toggle this to make `case-fold-search' nil regardless of input."
1850 (interactive)
1851 (setq ivy-case-fold-search
1852 (if ivy-case-fold-search
1853 nil
1854 'auto))
1855 ;; reset cache so that the candidate list updates
1856 (setq ivy--old-re nil))
1857
1858 (defun ivy--re-filter (re candidates)
1859 "Return all RE matching CANDIDATES.
1860 RE is a list of cons cells, with a regexp car and a boolean cdr.
1861 When the cdr is t, the car must match.
1862 Otherwise, the car must not match."
1863 (let ((re-list (if (stringp re) (list (cons re t)) re))
1864 (res candidates))
1865 (dolist (re re-list)
1866 (setq res
1867 (ignore-errors
1868 (funcall
1869 (if (cdr re)
1870 #'cl-remove-if-not
1871 #'cl-remove-if)
1872 (let ((re-str (car re)))
1873 (lambda (x) (string-match re-str x)))
1874 res))))
1875 res))
1876
1877 (defun ivy--filter (name candidates)
1878 "Return all items that match NAME in CANDIDATES.
1879 CANDIDATES are assumed to be static."
1880 (let ((re (funcall ivy--regex-function name)))
1881 (if (and (equal re ivy--old-re)
1882 ivy--old-cands)
1883 ;; quick caching for "C-n", "C-p" etc.
1884 ivy--old-cands
1885 (let* ((re-str (if (listp re) (caar re) re))
1886 (matcher (ivy-state-matcher ivy-last))
1887 (case-fold-search
1888 (and ivy-case-fold-search
1889 (string= name (downcase name))))
1890 (cands (cond
1891 (matcher
1892 (funcall matcher re candidates))
1893 ((and ivy--old-re
1894 (stringp re)
1895 (stringp ivy--old-re)
1896 (not (string-match "\\\\" ivy--old-re))
1897 (not (equal ivy--old-re ""))
1898 (memq (cl-search
1899 (if (string-match "\\\\)\\'" ivy--old-re)
1900 (substring ivy--old-re 0 -2)
1901 ivy--old-re)
1902 re)
1903 '(0 2)))
1904 (ignore-errors
1905 (cl-remove-if-not
1906 (lambda (x) (string-match re x))
1907 ivy--old-cands)))
1908 (t
1909 (ivy--re-filter re candidates)))))
1910 (ivy--recompute-index name re-str cands)
1911 (setq ivy--old-re
1912 (if (eq ivy--regex-function 'ivy--regex-ignore-order)
1913 re
1914 (if cands
1915 re-str
1916 "")))
1917 (setq ivy--old-cands (ivy--sort name cands))))))
1918
1919 (defcustom ivy-sort-matches-functions-alist '((t . nil))
1920 "An alist of functions used to sort the matching candidates.
1921
1922 This is different from `ivy-sort-functions-alist', which is used
1923 to sort the whole collection only once. The functions taken from
1924 here are instead used on each input change, but they are used
1925 only on already matching candidates, not on all of them.
1926
1927 The alist KEY is a collection function or t to match previously
1928 not matched collection functions.
1929
1930 The alist VAL is a sorting function with the signature of
1931 `ivy--prefix-sort'.")
1932
1933 (defun ivy--sort-files-by-date (_name candidates)
1934 "Re-soft CANDIDATES according to file modification date."
1935 (let ((default-directory ivy--directory))
1936 (cl-sort (copy-sequence candidates)
1937 (lambda (f1 f2)
1938 (time-less-p
1939 (nth 5 (file-attributes f2))
1940 (nth 5 (file-attributes f1)))))))
1941
1942 (defun ivy--sort (name candidates)
1943 "Re-sort CANDIDATES by NAME.
1944 All CANDIDATES are assumed to match NAME."
1945 (let ((key (or (ivy-state-caller ivy-last)
1946 (when (functionp (ivy-state-collection ivy-last))
1947 (ivy-state-collection ivy-last))))
1948 fun)
1949 (cond ((and (require 'flx nil 'noerror)
1950 (eq ivy--regex-function 'ivy--regex-fuzzy))
1951 (ivy--flx-sort name candidates))
1952 ((setq fun (cdr (or (assoc key ivy-sort-matches-functions-alist)
1953 (assoc t ivy-sort-matches-functions-alist))))
1954 (funcall fun name candidates))
1955 (t
1956 candidates))))
1957
1958 (defun ivy--prefix-sort (name candidates)
1959 "Re-sort CANDIDATES.
1960 Prefix matches to NAME are put ahead of the list."
1961 (if (or (string-match "^\\^" name) (string= name ""))
1962 candidates
1963 (let ((re-prefix (concat "^" (funcall ivy--regex-function name)))
1964 res-prefix
1965 res-noprefix)
1966 (dolist (s candidates)
1967 (if (string-match re-prefix s)
1968 (push s res-prefix)
1969 (push s res-noprefix)))
1970 (nconc
1971 (nreverse res-prefix)
1972 (nreverse res-noprefix)))))
1973
1974 (defun ivy--recompute-index (name re-str cands)
1975 (let* ((caller (ivy-state-caller ivy-last))
1976 (func (or (and caller (cdr (assoc caller ivy-index-functions-alist)))
1977 (cdr (assoc t ivy-index-functions-alist))
1978 #'ivy-recompute-index-zero)))
1979 (unless (eq this-command 'ivy-resume)
1980 (setq ivy--index
1981 (or
1982 (cl-position (if (and (> (length name) 0)
1983 (eq ?^ (aref name 0)))
1984 (substring name 1)
1985 name) cands
1986 :test #'equal)
1987 (and ivy--directory
1988 (cl-position
1989 (concat re-str "/") cands
1990 :test #'equal))
1991 (and (not (string= name ""))
1992 (not (and (require 'flx nil 'noerror)
1993 (eq ivy--regex-function 'ivy--regex-fuzzy)
1994 (< (length cands) 200)))
1995
1996 (cl-position (nth ivy--index ivy--old-cands)
1997 cands))
1998 (funcall func re-str cands))))
1999 (when (and (or (string= name "")
2000 (string= name "^"))
2001 (not (equal ivy--old-re "")))
2002 (setq ivy--index
2003 (or (ivy--preselect-index
2004 (ivy-state-preselect ivy-last)
2005 cands)
2006 ivy--index)))))
2007
2008 (defun ivy-recompute-index-swiper (_re-str cands)
2009 (let ((tail (nthcdr ivy--index ivy--old-cands))
2010 idx)
2011 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2012 (progn
2013 (while (and tail (null idx))
2014 ;; Compare with eq to handle equal duplicates in cands
2015 (setq idx (cl-position (pop tail) cands)))
2016 (or
2017 idx
2018 (1- (length cands))))
2019 (if ivy--old-cands
2020 ivy--index
2021 ;; already in ivy-state-buffer
2022 (let ((n (line-number-at-pos))
2023 (res 0)
2024 (i 0))
2025 (dolist (c cands)
2026 (when (eq n (read (get-text-property 0 'display c)))
2027 (setq res i))
2028 (cl-incf i))
2029 res)))))
2030
2031 (defun ivy-recompute-index-swiper-async (_re-str cands)
2032 (let ((tail (nthcdr ivy--index ivy--old-cands))
2033 idx)
2034 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2035 (progn
2036 (while (and tail (null idx))
2037 ;; Compare with `equal', since the collection is re-created
2038 ;; each time with `split-string'
2039 (setq idx (cl-position (pop tail) cands :test #'equal)))
2040 (or idx 0))
2041 ivy--index)))
2042
2043 (defun ivy-recompute-index-zero (_re-str _cands)
2044 0)
2045
2046 (defcustom ivy-minibuffer-faces
2047 '(ivy-minibuffer-match-face-1
2048 ivy-minibuffer-match-face-2
2049 ivy-minibuffer-match-face-3
2050 ivy-minibuffer-match-face-4)
2051 "List of `ivy' faces for minibuffer group matches.")
2052
2053 (defvar ivy-flx-limit 200
2054 "Used to conditionally turn off flx sorting.
2055 When the amount of matching candidates is larger than this
2056 number, no sorting will be done.")
2057
2058 (defun ivy--flx-sort (name cands)
2059 "Sort according to closeness to string NAME the string list CANDS."
2060 (condition-case nil
2061 (if (and cands
2062 (< (length cands) ivy-flx-limit))
2063 (let* ((flx-name (if (string-match "^\\^" name)
2064 (substring name 1)
2065 name))
2066 (cands-with-score
2067 (delq nil
2068 (mapcar
2069 (lambda (x)
2070 (let ((score (flx-score x flx-name ivy--flx-cache)))
2071 (and score
2072 (cons score x))))
2073 cands))))
2074 (if cands-with-score
2075 (mapcar (lambda (x)
2076 (let ((str (copy-sequence (cdr x)))
2077 (i 0)
2078 (last-j -2))
2079 (dolist (j (cdar x))
2080 (unless (eq j (1+ last-j))
2081 (cl-incf i))
2082 (setq last-j j)
2083 (ivy-add-face-text-property
2084 j (1+ j)
2085 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2086 ivy-minibuffer-faces)
2087 str))
2088 str))
2089 (sort cands-with-score
2090 (lambda (x y)
2091 (> (caar x) (caar y)))))
2092 cands))
2093 cands)
2094 (error
2095 cands)))
2096
2097 (defcustom ivy-format-function 'ivy-format-function-default
2098 "Function to transform the list of candidates into a string.
2099 This string is inserted into the minibuffer."
2100 :type '(choice
2101 (const :tag "Default" ivy-format-function-default)
2102 (const :tag "Arrow prefix" ivy-format-function-arrow)
2103 (const :tag "Full line" ivy-format-function-line)))
2104
2105 (defun ivy--truncate-string (str width)
2106 "Truncate STR to WIDTH."
2107 (if (> (string-width str) width)
2108 (concat (substring str 0 (min (- width 3)
2109 (- (length str) 3))) "...")
2110 str))
2111
2112 (defun ivy--format-function-generic (selected-fn other-fn cand-pairs separator)
2113 "Transform CAND-PAIRS into a string for minibuffer.
2114 SELECTED-FN and OTHER-FN each take two string arguments.
2115 SEPARATOR is used to join the candidates."
2116 (let ((i -1))
2117 (mapconcat
2118 (lambda (pair)
2119 (let ((str (car pair))
2120 (extra (cdr pair))
2121 (curr (eq (cl-incf i) ivy--index)))
2122 (if curr
2123 (funcall selected-fn str extra)
2124 (funcall other-fn str extra))))
2125 cand-pairs
2126 separator)))
2127
2128 (defun ivy-format-function-default (cand-pairs)
2129 "Transform CAND-PAIRS into a string for minibuffer."
2130 (ivy--format-function-generic
2131 (lambda (str extra)
2132 (concat (ivy--add-face str 'ivy-current-match) extra))
2133 #'concat
2134 cand-pairs
2135 "\n"))
2136
2137 (defun ivy-format-function-arrow (cand-pairs)
2138 "Transform CAND-PAIRS into a string for minibuffer."
2139 (ivy--format-function-generic
2140 (lambda (str extra)
2141 (concat "> " (ivy--add-face str 'ivy-current-match) extra))
2142 (lambda (str extra)
2143 (concat " " str extra))
2144 cand-pairs
2145 "\n"))
2146
2147 (defun ivy-format-function-line (cand-pairs)
2148 "Transform CAND-PAIRS into a string for minibuffer."
2149 (ivy--format-function-generic
2150 (lambda (str extra)
2151 (ivy--add-face (concat str extra "\n") 'ivy-current-match))
2152 (lambda (str extra)
2153 (concat str extra "\n"))
2154 cand-pairs
2155 ""))
2156
2157 (defun ivy-add-face-text-property (start end face str)
2158 (if (fboundp 'add-face-text-property)
2159 (add-face-text-property
2160 start end face nil str)
2161 (font-lock-append-text-property
2162 start end 'face face str)))
2163
2164 (defun ivy--format-minibuffer-line (str)
2165 (let ((start 0)
2166 (str (copy-sequence str)))
2167 (cond ((eq ivy--regex-function 'ivy--regex-ignore-order)
2168 (when (consp ivy--old-re)
2169 (let ((i 1))
2170 (dolist (re ivy--old-re)
2171 (when (string-match (car re) str)
2172 (ivy-add-face-text-property
2173 (match-beginning 0) (match-end 0)
2174 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2175 ivy-minibuffer-faces)
2176 str))
2177 (cl-incf i)))))
2178 ((and (eq ivy-display-style 'fancy)
2179 (not (eq ivy--regex-function 'ivy--regex-fuzzy)))
2180 (unless ivy--old-re
2181 (setq ivy--old-re (funcall ivy--regex-function ivy-text)))
2182 (while (and (string-match ivy--old-re str start)
2183 (> (- (match-end 0) (match-beginning 0)) 0))
2184 (setq start (match-end 0))
2185 (let ((i 0))
2186 (while (<= i ivy--subexps)
2187 (let ((face
2188 (cond ((zerop ivy--subexps)
2189 (cadr ivy-minibuffer-faces))
2190 ((zerop i)
2191 (car ivy-minibuffer-faces))
2192 (t
2193 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2194 ivy-minibuffer-faces)))))
2195 (ivy-add-face-text-property
2196 (match-beginning i) (match-end i)
2197 face str))
2198 (cl-incf i))))))
2199 str))
2200
2201 (defun ivy--format (cands)
2202 "Return a string for CANDS suitable for display in the minibuffer.
2203 CANDS is a list of strings."
2204 (setq ivy--length (length cands))
2205 (when (>= ivy--index ivy--length)
2206 (setq ivy--index (max (1- ivy--length) 0)))
2207 (if (null cands)
2208 (setq ivy--current "")
2209 (let* ((half-height (/ ivy-height 2))
2210 (start (max 0 (- ivy--index half-height)))
2211 (end (min (+ start (1- ivy-height)) ivy--length))
2212 (start (max 0 (min start (- end (1- ivy-height)))))
2213 (cands (cl-subseq cands start end))
2214 (index (- ivy--index start)))
2215 (cond (ivy--directory
2216 (setq cands (mapcar (lambda (x)
2217 (if (string-match-p "/\\'" x)
2218 (propertize x 'face 'ivy-subdir)
2219 x))
2220 cands)))
2221 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
2222 (setq cands (mapcar (lambda (x)
2223 (let ((b (get-buffer x)))
2224 (if (and b
2225 (buffer-file-name b)
2226 (buffer-modified-p b))
2227 (propertize x 'face 'ivy-modified-buffer)
2228 x)))
2229 cands))))
2230 (setq ivy--current (copy-sequence (nth index cands)))
2231 (let* ((ivy--index index)
2232 (cand-pairs (mapcar
2233 (lambda (cand)
2234 (cons (ivy--format-minibuffer-line cand) nil)) cands))
2235 (res (concat "\n" (funcall ivy-format-function cand-pairs))))
2236 (put-text-property 0 (length res) 'read-only nil res)
2237 res))))
2238
2239 (defvar ivy--virtual-buffers nil
2240 "Store the virtual buffers alist.")
2241
2242 (defvar recentf-list)
2243
2244 (defcustom ivy-virtual-abbreviate 'name
2245 "The mode of abbreviation for virtual buffer names."
2246 :type '(choice
2247 (const :tag "Only name" name)
2248 (const :tag "Full path" full)
2249 ;; eventually, uniquify
2250 ))
2251
2252 (defun ivy--virtual-buffers ()
2253 "Adapted from `ido-add-virtual-buffers-to-list'."
2254 (unless recentf-mode
2255 (recentf-mode 1))
2256 (let ((bookmarks (and (boundp 'bookmark-alist)
2257 bookmark-alist))
2258 virtual-buffers name)
2259 (dolist (head (append
2260 recentf-list
2261 (delete " - no file -"
2262 (delq nil (mapcar (lambda (bookmark)
2263 (cdr (assoc 'filename bookmark)))
2264 bookmarks)))))
2265 (setq name
2266 (if (eq ivy-virtual-abbreviate 'name)
2267 (file-name-nondirectory head)
2268 (expand-file-name head)))
2269 (when (equal name "")
2270 (setq name (file-name-nondirectory (directory-file-name head))))
2271 (when (equal name "")
2272 (setq name head))
2273 (and (not (equal name ""))
2274 (null (get-file-buffer head))
2275 (not (assoc name virtual-buffers))
2276 (push (cons name head) virtual-buffers)))
2277 (when virtual-buffers
2278 (dolist (comp virtual-buffers)
2279 (put-text-property 0 (length (car comp))
2280 'face 'ivy-virtual
2281 (car comp)))
2282 (setq ivy--virtual-buffers (nreverse virtual-buffers))
2283 (mapcar #'car ivy--virtual-buffers))))
2284
2285 (defun ivy--buffer-list (str &optional virtual)
2286 "Return the buffers that match STR.
2287 When VIRTUAL is non-nil, add virtual buffers."
2288 (delete-dups
2289 (append
2290 (mapcar
2291 (lambda (x)
2292 (if (with-current-buffer x
2293 (file-remote-p
2294 (abbreviate-file-name default-directory)))
2295 (propertize x 'face 'ivy-remote)
2296 x))
2297 (all-completions str 'internal-complete-buffer))
2298 (and virtual
2299 (ivy--virtual-buffers)))))
2300
2301 (defun ivy--switch-buffer-action (buffer)
2302 "Switch to BUFFER.
2303 BUFFER may be a string or nil."
2304 (with-ivy-window
2305 (if (zerop (length buffer))
2306 (switch-to-buffer
2307 ivy-text nil 'force-same-window)
2308 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2309 (if (and virtual
2310 (not (get-buffer buffer)))
2311 (find-file (cdr virtual))
2312 (switch-to-buffer
2313 buffer nil 'force-same-window))))))
2314
2315 (defun ivy--switch-buffer-other-window-action (buffer)
2316 "Switch to BUFFER in other window.
2317 BUFFER may be a string or nil."
2318 (if (zerop (length buffer))
2319 (switch-to-buffer-other-window ivy-text)
2320 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2321 (if (and virtual
2322 (not (get-buffer buffer)))
2323 (find-file-other-window (cdr virtual))
2324 (switch-to-buffer-other-window buffer)))))
2325
2326 (defun ivy--rename-buffer-action (buffer)
2327 "Rename BUFFER."
2328 (let ((new-name (read-string "Rename buffer (to new name): ")))
2329 (with-current-buffer buffer
2330 (rename-buffer new-name))))
2331
2332 (defvar ivy-switch-buffer-map (make-sparse-keymap))
2333
2334 (ivy-set-actions
2335 'ivy-switch-buffer
2336 '(("k"
2337 (lambda (x)
2338 (kill-buffer x)
2339 (ivy--reset-state ivy-last))
2340 "kill")
2341 ("j"
2342 ivy--switch-buffer-other-window-action
2343 "other")
2344 ("r"
2345 ivy--rename-buffer-action
2346 "rename")))
2347
2348 ;;;###autoload
2349 (defun ivy-switch-buffer ()
2350 "Switch to another buffer."
2351 (interactive)
2352 (if (not ivy-mode)
2353 (call-interactively 'switch-to-buffer)
2354 (let ((this-command 'ivy-switch-buffer))
2355 (ivy-read "Switch to buffer: " 'internal-complete-buffer
2356 :preselect (buffer-name (other-buffer (current-buffer)))
2357 :action #'ivy--switch-buffer-action
2358 :keymap ivy-switch-buffer-map))))
2359
2360 ;;;###autoload
2361 (defun ivy-switch-buffer-other-window ()
2362 "Switch to another buffer in another window."
2363 (interactive)
2364 (ivy-read "Switch to buffer in other window: " 'internal-complete-buffer
2365 :preselect (buffer-name (other-buffer (current-buffer)))
2366 :action #'ivy--switch-buffer-other-window-action
2367 :keymap ivy-switch-buffer-map))
2368
2369 ;;;###autoload
2370 (defun ivy-recentf ()
2371 "Find a file on `recentf-list'."
2372 (interactive)
2373 (ivy-read "Recentf: " recentf-list
2374 :action
2375 (lambda (f)
2376 (with-ivy-window
2377 (find-file f)))))
2378
2379 (defun ivy-yank-word ()
2380 "Pull next word from buffer into search string."
2381 (interactive)
2382 (let (amend)
2383 (with-ivy-window
2384 (let ((pt (point))
2385 (le (line-end-position)))
2386 (forward-word 1)
2387 (if (> (point) le)
2388 (goto-char pt)
2389 (setq amend (buffer-substring-no-properties pt (point))))))
2390 (when amend
2391 (insert (replace-regexp-in-string " +" " " amend)))))
2392
2393 (defun ivy-kill-ring-save ()
2394 "Store the current candidates into the kill ring.
2395 If the region is active, forward to `kill-ring-save' instead."
2396 (interactive)
2397 (if (region-active-p)
2398 (call-interactively 'kill-ring-save)
2399 (kill-new
2400 (mapconcat
2401 #'identity
2402 ivy--old-cands
2403 "\n"))))
2404
2405 (defun ivy-insert-current ()
2406 "Make the current candidate into current input.
2407 Don't finish completion."
2408 (interactive)
2409 (delete-minibuffer-contents)
2410 (if (and ivy--directory
2411 (string-match "/$" ivy--current))
2412 (insert (substring ivy--current 0 -1))
2413 (insert ivy--current)))
2414
2415 (defun ivy-toggle-fuzzy ()
2416 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
2417 (interactive)
2418 (setq ivy--old-re nil)
2419 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
2420 (setq ivy--regex-function 'ivy--regex-plus)
2421 (setq ivy--regex-function 'ivy--regex-fuzzy)))
2422
2423 (defun ivy-reverse-i-search ()
2424 "Enter a recursive `ivy-read' session using the current history.
2425 The selected history element will be inserted into the minibuffer."
2426 (interactive)
2427 (let ((enable-recursive-minibuffers t)
2428 (history (symbol-value (ivy-state-history ivy-last)))
2429 (old-last ivy-last)
2430 (ivy-recursive-restore nil))
2431 (ivy-read "Reverse-i-search: "
2432 history
2433 :action (lambda (x)
2434 (ivy--reset-state
2435 (setq ivy-last old-last))
2436 (delete-minibuffer-contents)
2437 (insert (substring-no-properties x))
2438 (ivy--cd-maybe)))))
2439
2440 (defun ivy-restrict-to-matches ()
2441 "Restrict candidates to current matches and erase input."
2442 (interactive)
2443 (delete-minibuffer-contents)
2444 (setq ivy--all-candidates
2445 (ivy--filter ivy-text ivy--all-candidates)))
2446
2447 ;;* Occur
2448 (defvar-local ivy-occur-last nil
2449 "Buffer-local value of `ivy-last'.
2450 Can't re-use `ivy-last' because using e.g. `swiper' in the same
2451 buffer would modify `ivy-last'.")
2452
2453 (defvar ivy-occur-mode-map
2454 (let ((map (make-sparse-keymap)))
2455 (define-key map [mouse-1] 'ivy-occur-click)
2456 (define-key map (kbd "RET") 'ivy-occur-press)
2457 (define-key map (kbd "j") 'next-line)
2458 (define-key map (kbd "k") 'previous-line)
2459 (define-key map (kbd "h") 'backward-char)
2460 (define-key map (kbd "l") 'forward-char)
2461 (define-key map (kbd "g") 'ivy-occur-press)
2462 (define-key map (kbd "a") 'ivy-occur-read-action)
2463 (define-key map (kbd "o") 'ivy-occur-dispatch)
2464 (define-key map (kbd "q") 'quit-window)
2465 map)
2466 "Keymap for Ivy Occur mode.")
2467
2468 (define-derived-mode ivy-occur-mode fundamental-mode "Ivy-Occur"
2469 "Major mode for output from \\[ivy-occur].
2470
2471 \\{ivy-occur-mode-map}")
2472
2473 (defvar ivy-occur-grep-mode-map
2474 (let ((map (copy-keymap ivy-occur-mode-map)))
2475 (define-key map (kbd "C-x C-q") 'ivy-wgrep-change-to-wgrep-mode)
2476 map)
2477 "Keymap for Ivy Occur Grep mode.")
2478
2479 (define-derived-mode ivy-occur-grep-mode grep-mode "Ivy-Occur"
2480 "Major mode for output from \\[ivy-occur].
2481
2482 \\{ivy-occur-grep-mode-map}")
2483
2484 (defvar counsel-git-grep-cmd)
2485
2486 (defun ivy-occur ()
2487 "Stop completion and put the current matches into a new buffer.
2488
2489 The new buffer remembers current action(s).
2490
2491 While in the *ivy-occur* buffer, selecting a candidate with RET or
2492 a mouse click will call the appropriate action for that candidate.
2493
2494 There is no limit on the number of *ivy-occur* buffers."
2495 (interactive)
2496 (let ((buffer
2497 (generate-new-buffer
2498 (format "*ivy-occur%s \"%s\"*"
2499 (let (caller)
2500 (if (setq caller (ivy-state-caller ivy-last))
2501 (concat " " (prin1-to-string caller))
2502 ""))
2503 ivy-text)))
2504 (do-grep (eq (ivy-state-caller ivy-last) 'counsel-git-grep)))
2505 (with-current-buffer buffer
2506 (if do-grep
2507 (progn
2508 (setq ivy--old-cands
2509 (split-string
2510 (shell-command-to-string
2511 (format counsel-git-grep-cmd
2512 (if (stringp ivy--old-re)
2513 ivy--old-re
2514 (caar ivy--old-re))))
2515 "\n"
2516 t))
2517 (ivy-occur-grep-mode))
2518 (ivy-occur-mode))
2519 (setf (ivy-state-text ivy-last) ivy-text)
2520 (setq ivy-occur-last ivy-last)
2521 (setq-local ivy--directory ivy--directory)
2522 (let ((inhibit-read-only t))
2523 (erase-buffer)
2524 (when do-grep
2525 ;; Need precise number of header lines for `wgrep' to work.
2526 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
2527 default-directory)))
2528 (insert (format "%d candidates:\n" (length ivy--old-cands)))
2529 (dolist (cand ivy--old-cands)
2530 (let ((str (if do-grep
2531 (concat "./" cand)
2532 (concat " " cand))))
2533 (add-text-properties
2534 0 (length str)
2535 `(mouse-face
2536 highlight
2537 help-echo "mouse-1: call ivy-action")
2538 str)
2539 (insert str "\n")))))
2540 (ivy-exit-with-action
2541 `(lambda (_) (pop-to-buffer ,buffer)))))
2542
2543 (declare-function wgrep-change-to-wgrep-mode "ext:wgrep")
2544
2545 (defun ivy-wgrep-change-to-wgrep-mode ()
2546 "Forward to `wgrep-change-to-wgrep-mode'."
2547 (interactive)
2548 (if (require 'wgrep nil 'noerror)
2549 (wgrep-change-to-wgrep-mode)
2550 (error "Package wgrep isn't installed")))
2551
2552 (defun ivy-occur-read-action ()
2553 "Select one of the available actions as the current one."
2554 (interactive)
2555 (let ((ivy-last ivy-occur-last))
2556 (ivy-read-action)))
2557
2558 (defun ivy-occur-dispatch ()
2559 "Call one of the available actions on the current item."
2560 (interactive)
2561 (let* ((state-action (ivy-state-action ivy-occur-last))
2562 (actions (if (symbolp state-action)
2563 state-action
2564 (copy-sequence state-action))))
2565 (unwind-protect
2566 (progn
2567 (ivy-occur-read-action)
2568 (ivy-occur-press))
2569 (setf (ivy-state-action ivy-occur-last) actions))))
2570
2571 (defun ivy-occur-click (event)
2572 "Execute action for the current candidate.
2573 EVENT gives the mouse position."
2574 (interactive "e")
2575 (let ((window (posn-window (event-end event)))
2576 (pos (posn-point (event-end event))))
2577 (with-current-buffer (window-buffer window)
2578 (goto-char pos)
2579 (ivy-occur-press))))
2580
2581 (declare-function swiper--cleanup "swiper")
2582 (declare-function swiper--add-overlays "swiper")
2583
2584 (defun ivy-occur-press ()
2585 "Execute action for the current candidate."
2586 (interactive)
2587 (require 'pulse)
2588 (when (save-excursion
2589 (beginning-of-line)
2590 (looking-at "\\(?:./\\| \\)\\(.*\\)$"))
2591 (let* ((ivy-last ivy-occur-last)
2592 (ivy-text (ivy-state-text ivy-last))
2593 (str (buffer-substring
2594 (match-beginning 1)
2595 (match-end 1)))
2596 (coll (ivy-state-collection ivy-last))
2597 (action (ivy--get-action ivy-last))
2598 (ivy-exit 'done))
2599 (with-ivy-window
2600 (funcall action
2601 (if (and (consp coll)
2602 (consp (car coll)))
2603 (cdr (assoc str coll))
2604 str))
2605 (if (memq (ivy-state-caller ivy-last)
2606 '(swiper counsel-git-grep))
2607 (with-current-buffer (window-buffer (selected-window))
2608 (swiper--cleanup)
2609 (swiper--add-overlays
2610 (ivy--regex ivy-text)
2611 (line-beginning-position)
2612 (line-end-position)
2613 (selected-window))
2614 (run-at-time 0.5 nil 'swiper--cleanup))
2615 (pulse-momentary-highlight-one-line (point)))))))
2616
2617 (provide 'ivy)
2618
2619 ;;; ivy.el ends here