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