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