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