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