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