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