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