]> code.delx.au - gnu-emacs-elpa/blob - ivy.el
Add ignore pattern toggling
[gnu-emacs-elpa] / ivy.el
1 ;;; ivy.el --- Incremental Vertical completYon -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2015 Free Software Foundation, Inc.
4
5 ;; Author: Oleh Krehel <ohwoeowho@gmail.com>
6 ;; URL: https://github.com/abo-abo/swiper
7 ;; Package-Requires: ((emacs "24.1"))
8 ;; Keywords: matching
9
10 ;; This file is part of GNU Emacs.
11
12 ;; This file is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 3, or (at your option)
15 ;; any later version.
16
17 ;; This program is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; For a full copy of the GNU General Public License
23 ;; see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26 ;;
27 ;; This package provides `ivy-read' as an alternative to
28 ;; `completing-read' and similar functions.
29 ;;
30 ;; There's no intricate code to determine the best candidate.
31 ;; Instead, the user can navigate to it with `ivy-next-line' and
32 ;; `ivy-previous-line'.
33 ;;
34 ;; The matching is done by splitting the input text by spaces and
35 ;; re-building it into a regex.
36 ;; So "for example" is transformed into "\\(for\\).*\\(example\\)".
37
38 ;;; Code:
39 (require 'cl-lib)
40 (require 'ffap)
41
42 ;;* Customization
43 (defgroup ivy nil
44 "Incremental vertical completion."
45 :group 'convenience)
46
47 (defgroup ivy-faces nil
48 "Font-lock faces for `ivy'."
49 :group 'ivy)
50
51 (defface ivy-current-match
52 '((((class color) (background light))
53 :background "#1a4b77" :foreground "white")
54 (((class color) (background dark))
55 :background "#65a7e2" :foreground "black"))
56 "Face used by Ivy for highlighting the current match.")
57
58 (defface ivy-minibuffer-match-face-1
59 '((((class color) (background light))
60 :background "#d3d3d3")
61 (((class color) (background dark))
62 :background "#555555"))
63 "The background face for `ivy' minibuffer matches.")
64
65 (defface ivy-minibuffer-match-face-2
66 '((((class color) (background light))
67 :background "#e99ce8" :weight bold)
68 (((class color) (background dark))
69 :background "#777777" :weight bold))
70 "Face for `ivy' minibuffer matches modulo 1.")
71
72 (defface ivy-minibuffer-match-face-3
73 '((((class color) (background light))
74 :background "#bbbbff" :weight bold)
75 (((class color) (background dark))
76 :background "#7777ff" :weight bold))
77 "Face for `ivy' minibuffer matches modulo 2.")
78
79 (defface ivy-minibuffer-match-face-4
80 '((((class color) (background light))
81 :background "#ffbbff" :weight bold)
82 (((class color) (background dark))
83 :background "#8a498a" :weight bold))
84 "Face for `ivy' minibuffer matches modulo 3.")
85
86 (defface ivy-confirm-face
87 '((t :foreground "ForestGreen" :inherit minibuffer-prompt))
88 "Face used by Ivy for a confirmation prompt.")
89
90 (defface ivy-match-required-face
91 '((t :foreground "red" :inherit minibuffer-prompt))
92 "Face used by Ivy for a match required prompt.")
93
94 (setcdr (assoc load-file-name custom-current-group-alist) 'ivy)
95
96 (defface ivy-subdir
97 '((t (:inherit 'dired-directory)))
98 "Face used by Ivy for highlighting subdirs in the alternatives.")
99
100 (defface ivy-modified-buffer
101 '((t :inherit 'default))
102 "Face used by Ivy for highlighting modified file visiting buffers.")
103
104 (defface ivy-remote
105 '((t (:foreground "#110099")))
106 "Face used by Ivy for highlighting remotes in the alternatives.")
107
108 (defface ivy-virtual
109 '((t :inherit font-lock-builtin-face))
110 "Face used by Ivy for matching virtual buffer names.")
111
112 (defcustom ivy-height 10
113 "Number of lines for the minibuffer window."
114 :type 'integer)
115
116 (defcustom ivy-count-format "%-4d "
117 "The style to use for displaying the current candidate count for `ivy-read'.
118 Set this to \"\" to suppress the count visibility.
119 Set this to \"(%d/%d) \" to display both the index and the count."
120 :type '(choice
121 (const :tag "Count disabled" "")
122 (const :tag "Count matches" "%-4d ")
123 (const :tag "Count matches and show current match" "(%d/%d) ")
124 string))
125
126 (defcustom ivy-wrap nil
127 "When non-nil, wrap around after the first and the last candidate."
128 :type 'boolean)
129
130 (defcustom ivy-display-style (unless (version< emacs-version "24.5") 'fancy)
131 "The style for formatting the minibuffer.
132
133 By default, the matched strings are copied as is.
134
135 The fancy display style highlights matching parts of the regexp,
136 a behavior similar to `swiper'.
137
138 This setting depends on `add-face-text-property' - a C function
139 available as of Emacs 24.5. Fancy style will render poorly in
140 earlier versions of Emacs."
141 :type '(choice
142 (const :tag "Plain" nil)
143 (const :tag "Fancy" fancy)))
144
145 (defcustom ivy-on-del-error-function 'minibuffer-keyboard-quit
146 "The handler for when `ivy-backward-delete-char' throws.
147 Usually a quick exit out of the minibuffer."
148 :type 'function)
149
150 (defcustom ivy-extra-directories '("../" "./")
151 "Add this to the front of the list when completing file names.
152 Only \"./\" and \"../\" apply here. They appear in reverse order."
153 :type '(repeat :tag "Dirs"
154 (choice
155 (const :tag "Parent Directory" "../")
156 (const :tag "Current Directory" "./"))))
157
158 (defcustom ivy-use-virtual-buffers nil
159 "When non-nil, add `recentf-mode' and bookmarks to `ivy-switch-buffer'."
160 :type 'boolean)
161
162 (defvar ivy--actions-list nil
163 "A list of extra actions per command.")
164
165 (defun ivy-set-actions (cmd actions)
166 "Set CMD extra exit points to ACTIONS."
167 (setq ivy--actions-list
168 (plist-put ivy--actions-list cmd actions)))
169
170 (defvar ivy--sources-list nil
171 "A list of extra sources per command.")
172
173 (defun ivy-set-sources (cmd sources)
174 "Attach to CMD a list of extra SOURCES.
175
176 Each static source is a function that takes no argument and
177 returns a list of strings.
178
179 The '(original-source) determines the position of the original
180 dynamic source.
181
182 Extra dynamic sources aren't supported yet.
183
184 Example:
185
186 (defun small-recentf ()
187 (cl-subseq recentf-list 0 20))
188
189 (ivy-set-sources
190 'counsel-locate
191 '((small-recentf)
192 (original-source)))
193 "
194 (setq ivy--sources-list
195 (plist-put ivy--sources-list cmd sources)))
196
197 ;;* Keymap
198 (require 'delsel)
199 (defvar ivy-minibuffer-map
200 (let ((map (make-sparse-keymap)))
201 (define-key map (kbd "C-m") 'ivy-done)
202 (define-key map (kbd "C-M-m") 'ivy-call)
203 (define-key map (kbd "C-j") 'ivy-alt-done)
204 (define-key map (kbd "C-M-j") 'ivy-immediate-done)
205 (define-key map (kbd "TAB") 'ivy-partial-or-done)
206 (define-key map (kbd "C-n") 'ivy-next-line)
207 (define-key map (kbd "C-p") 'ivy-previous-line)
208 (define-key map (kbd "<down>") 'ivy-next-line)
209 (define-key map (kbd "<up>") 'ivy-previous-line)
210 (define-key map (kbd "C-s") 'ivy-next-line-or-history)
211 (define-key map (kbd "C-r") 'ivy-reverse-i-search)
212 (define-key map (kbd "SPC") 'self-insert-command)
213 (define-key map (kbd "DEL") 'ivy-backward-delete-char)
214 (define-key map (kbd "M-DEL") 'ivy-backward-kill-word)
215 (define-key map (kbd "C-d") 'ivy-delete-char)
216 (define-key map (kbd "C-f") 'ivy-forward-char)
217 (define-key map (kbd "M-d") 'ivy-kill-word)
218 (define-key map (kbd "M-<") 'ivy-beginning-of-buffer)
219 (define-key map (kbd "M->") 'ivy-end-of-buffer)
220 (define-key map (kbd "M-n") 'ivy-next-history-element)
221 (define-key map (kbd "M-p") 'ivy-previous-history-element)
222 (define-key map (kbd "C-g") 'minibuffer-keyboard-quit)
223 (define-key map (kbd "C-v") 'ivy-scroll-up-command)
224 (define-key map (kbd "M-v") 'ivy-scroll-down-command)
225 (define-key map (kbd "C-M-n") 'ivy-next-line-and-call)
226 (define-key map (kbd "C-M-p") 'ivy-previous-line-and-call)
227 (define-key map (kbd "M-q") 'ivy-toggle-regexp-quote)
228 (define-key map (kbd "M-j") 'ivy-yank-word)
229 (define-key map (kbd "M-i") 'ivy-insert-current)
230 (define-key map (kbd "C-o") 'hydra-ivy/body)
231 (define-key map (kbd "M-o") 'ivy-dispatching-done)
232 (define-key map (kbd "C-M-o") 'ivy-dispatching-call)
233 (define-key map (kbd "C-k") 'ivy-kill-line)
234 (define-key map (kbd "S-SPC") 'ivy-restrict-to-matches)
235 (define-key map (kbd "M-w") 'ivy-kill-ring-save)
236 (define-key map (kbd "C-'") 'ivy-avy)
237 (define-key map (kbd "C-M-a") 'ivy-read-action)
238 (define-key map (kbd "C-c C-o") 'ivy-occur)
239 (define-key map (kbd "C-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 (when (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 (next-history-element arg)
855 (ivy--cd-maybe)
856 (move-end-of-line 1)
857 (ivy--maybe-scroll-history))
858
859 (defvar ivy-ffap-url-functions nil
860 "List of functions that check if the point is on a URL.")
861
862 (defun ivy--cd-maybe ()
863 "Check if the current input points to a different directory.
864 If so, move to that directory, while keeping only the file name."
865 (when ivy--directory
866 (let ((input (ivy--input))
867 url)
868 (if (setq url (or (ffap-url-p input)
869 (with-ivy-window
870 (cl-reduce
871 (lambda (a b)
872 (or a (funcall b)))
873 ivy-ffap-url-functions
874 :initial-value nil))))
875 (ivy-exit-with-action
876 (lambda (_)
877 (funcall ffap-url-fetcher url)))
878 (setq input (expand-file-name input))
879 (let ((file (file-name-nondirectory input))
880 (dir (expand-file-name (file-name-directory input))))
881 (if (string= dir ivy--directory)
882 (progn
883 (delete-minibuffer-contents)
884 (insert file))
885 (ivy--cd dir)
886 (insert file)))))))
887
888 (defun ivy--maybe-scroll-history ()
889 "If the selected history element has an index, scroll there."
890 (let ((idx (ignore-errors
891 (get-text-property
892 (minibuffer-prompt-end)
893 'ivy-index))))
894 (when idx
895 (ivy--exhibit)
896 (setq ivy--index idx))))
897
898 (defun ivy--cd (dir)
899 "When completing file names, move to directory DIR."
900 (if (null ivy--directory)
901 (error "Unexpected")
902 (setq ivy--old-cands nil)
903 (setq ivy--old-re nil)
904 (setq ivy--index 0)
905 (setq ivy--all-candidates
906 (ivy--sorted-files (setq ivy--directory dir)))
907 (setq ivy-text "")
908 (delete-minibuffer-contents)))
909
910 (defun ivy-backward-delete-char ()
911 "Forward to `backward-delete-char'.
912 On error (read-only), call `ivy-on-del-error-function'."
913 (interactive)
914 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
915 (progn
916 (ivy--cd (file-name-directory
917 (directory-file-name
918 (expand-file-name
919 ivy--directory))))
920 (ivy--exhibit))
921 (condition-case nil
922 (backward-delete-char 1)
923 (error
924 (when ivy-on-del-error-function
925 (funcall ivy-on-del-error-function))))))
926
927 (defun ivy-delete-char (arg)
928 "Forward to `delete-char' ARG."
929 (interactive "p")
930 (unless (= (point) (line-end-position))
931 (delete-char arg)))
932
933 (defun ivy-forward-char (arg)
934 "Forward to `forward-char' ARG."
935 (interactive "p")
936 (unless (= (point) (line-end-position))
937 (forward-char arg)))
938
939 (defun ivy-kill-word (arg)
940 "Forward to `kill-word' ARG."
941 (interactive "p")
942 (unless (= (point) (line-end-position))
943 (kill-word arg)))
944
945 (defun ivy-kill-line ()
946 "Forward to `kill-line'."
947 (interactive)
948 (if (eolp)
949 (kill-region (minibuffer-prompt-end) (point))
950 (kill-line)))
951
952 (defun ivy-backward-kill-word ()
953 "Forward to `backward-kill-word'."
954 (interactive)
955 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
956 (progn
957 (ivy--cd (file-name-directory
958 (directory-file-name
959 (expand-file-name
960 ivy--directory))))
961 (ivy--exhibit))
962 (ignore-errors
963 (let ((pt (point)))
964 (forward-word -1)
965 (delete-region (point) pt)))))
966
967 (defvar ivy--regexp-quote 'regexp-quote
968 "Store the regexp quoting state.")
969
970 (defun ivy-toggle-regexp-quote ()
971 "Toggle the regexp quoting."
972 (interactive)
973 (setq ivy--old-re nil)
974 (cl-rotatef ivy--regex-function ivy--regexp-quote))
975
976 (defvar avy-all-windows)
977 (defvar avy-action)
978 (defvar avy-keys)
979 (defvar avy-keys-alist)
980 (defvar avy-style)
981 (defvar avy-styles-alist)
982 (declare-function avy--process "ext:avy")
983 (declare-function avy--style-fn "ext:avy")
984
985 (eval-after-load 'avy
986 '(add-to-list 'avy-styles-alist '(ivy-avy . pre)))
987
988 (defun ivy-avy ()
989 "Jump to one of the current ivy candidates."
990 (interactive)
991 (unless (require 'avy nil 'noerror)
992 (error "Package avy isn't installed"))
993 (let* ((avy-all-windows nil)
994 (avy-keys (or (cdr (assq 'ivy-avy avy-keys-alist))
995 avy-keys))
996 (avy-style (or (cdr (assq 'ivy-avy
997 avy-styles-alist))
998 avy-style))
999 (candidate
1000 (let ((candidates))
1001 (save-excursion
1002 (save-restriction
1003 (narrow-to-region
1004 (window-start)
1005 (window-end))
1006 (goto-char (point-min))
1007 (forward-line)
1008 (while (< (point) (point-max))
1009 (push
1010 (cons (point)
1011 (selected-window))
1012 candidates)
1013 (forward-line))))
1014 (setq avy-action #'identity)
1015 (avy--process
1016 (nreverse candidates)
1017 (avy--style-fn avy-style)))))
1018 (ivy-set-index (- (line-number-at-pos candidate) 2))
1019 (ivy--exhibit)
1020 (ivy-done)))
1021
1022 (defun ivy-sort-file-function-default (x y)
1023 "Compare two files X and Y.
1024 Prioritize directories."
1025 (if (get-text-property 0 'dirp x)
1026 (if (get-text-property 0 'dirp y)
1027 (string< x y)
1028 t)
1029 (if (get-text-property 0 'dirp y)
1030 nil
1031 (string< x y))))
1032
1033 (defcustom ivy-sort-functions-alist
1034 '((read-file-name-internal . ivy-sort-file-function-default)
1035 (internal-complete-buffer . nil)
1036 (counsel-git-grep-function . nil)
1037 (Man-goto-section . nil)
1038 (org-refile . nil)
1039 (t . string-lessp))
1040 "An alist of sorting functions for each collection function.
1041 Interactive functions that call completion fit in here as well.
1042
1043 Nil means no sorting, which is useful to turn off the sorting for
1044 functions that have candidates in the natural buffer order, like
1045 `org-refile' or `Man-goto-section'.
1046
1047 The entry associated with t is used for all fall-through cases.
1048
1049 See also `ivy-sort-max-size'."
1050 :type
1051 '(alist
1052 :key-type (choice
1053 (const :tag "All other functions" t)
1054 (symbol :tag "Function"))
1055 :value-type (choice
1056 (const :tag "plain sort" string-lessp)
1057 (const :tag "file sort" ivy-sort-file-function-default)
1058 (const :tag "no sort" nil)))
1059 :group 'ivy)
1060
1061 (defvar ivy-index-functions-alist
1062 '((swiper . ivy-recompute-index-swiper)
1063 (swiper-multi . ivy-recompute-index-swiper)
1064 (counsel-git-grep . ivy-recompute-index-swiper)
1065 (counsel-grep . ivy-recompute-index-swiper-async)
1066 (t . ivy-recompute-index-zero))
1067 "An alist of index recomputing functions for each collection function.
1068 When the input changes, the appropriate function returns an
1069 integer - the index of the matched candidate that should be
1070 selected.")
1071
1072 (defvar ivy-re-builders-alist
1073 '((t . ivy--regex-plus))
1074 "An alist of regex building functions for each collection function.
1075
1076 Each key is (in order of priority):
1077 1. The actual collection function, e.g. `read-file-name-internal'.
1078 2. The symbol passed by :caller into `ivy-read'.
1079 3. `this-command'.
1080 4. t.
1081
1082 Each value is a function that should take a string and return a
1083 valid regex or a regex sequence (see below).
1084
1085 Possible choices: `ivy--regex', `regexp-quote',
1086 `ivy--regex-plus', `ivy--regex-fuzzy'.
1087
1088 If a function returns a list, it should format like this:
1089 '((\"matching-regexp\" . t) (\"non-matching-regexp\") ...).
1090
1091 The matches will be filtered in a sequence, you can mix the
1092 regexps that should match and that should not match as you
1093 like.")
1094
1095 (defvar ivy-initial-inputs-alist
1096 '((org-refile . "^")
1097 (org-agenda-refile . "^")
1098 (org-capture-refile . "^")
1099 (counsel-M-x . "^")
1100 (counsel-describe-function . "^")
1101 (counsel-describe-variable . "^")
1102 (man . "^")
1103 (woman . "^"))
1104 "Command to initial input table.")
1105
1106 (defcustom ivy-sort-max-size 30000
1107 "Sorting won't be done for collections larger than this."
1108 :type 'integer)
1109
1110 (defun ivy--sorted-files (dir)
1111 "Return the list of files in DIR.
1112 Directories come first."
1113 (let* ((default-directory dir)
1114 (seq (all-completions "" 'read-file-name-internal))
1115 sort-fn)
1116 (if (equal dir "/")
1117 seq
1118 (setq seq (delete "./" (delete "../" seq)))
1119 (when (eq (setq sort-fn (cdr (assoc 'read-file-name-internal
1120 ivy-sort-functions-alist)))
1121 #'ivy-sort-file-function-default)
1122 (setq seq (mapcar (lambda (x)
1123 (propertize x 'dirp (string-match-p "/\\'" x)))
1124 seq)))
1125 (when sort-fn
1126 (setq seq (cl-sort seq sort-fn)))
1127 (dolist (dir ivy-extra-directories)
1128 (push dir seq))
1129 seq)))
1130
1131 (defvar ivy-recursive-restore t
1132 "When non-nil, restore the above state when exiting the minibuffer.
1133 This variable is let-bound to nil by functions that take care of
1134 the restoring themselves.")
1135
1136 ;;** Entry Point
1137 (cl-defun ivy-read (prompt collection
1138 &key
1139 predicate require-match initial-input
1140 history preselect keymap update-fn sort
1141 action unwind re-builder matcher dynamic-collection caller)
1142 "Read a string in the minibuffer, with completion.
1143
1144 PROMPT is a format string, normally ending in a colon and a
1145 space; %d anywhere in the string is replaced by the current
1146 number of matching candidates. For the literal % character,
1147 escape it with %%. See also `ivy-count-format'.
1148
1149 COLLECTION is either a list of strings, a function, an alist, or
1150 a hash table.
1151
1152 If INITIAL-INPUT is not nil, then insert that input in the
1153 minibuffer initially.
1154
1155 KEYMAP is composed with `ivy-minibuffer-map'.
1156
1157 If PRESELECT is not nil, then select the corresponding candidate
1158 out of the ones that match the INITIAL-INPUT.
1159
1160 UPDATE-FN is called each time the current candidate(s) is changed.
1161
1162 When SORT is t, use `ivy-sort-functions-alist' for sorting.
1163
1164 ACTION is a lambda function to call after selecting a result. It
1165 takes a single string argument.
1166
1167 UNWIND is a lambda function to call before exiting.
1168
1169 RE-BUILDER is a lambda function to call to transform text into a
1170 regex pattern.
1171
1172 MATCHER is to override matching.
1173
1174 DYNAMIC-COLLECTION is a boolean to specify if the list of
1175 candidates is updated after each input by calling COLLECTION.
1176
1177 CALLER is a symbol to uniquely identify the caller to `ivy-read'.
1178 It is used, along with COLLECTION, to determine which
1179 customizations apply to the current completion session."
1180 (let ((extra-actions (append (plist-get ivy--actions-list t)
1181 (plist-get ivy--actions-list this-command))))
1182 (when extra-actions
1183 (setq action
1184 (cond ((functionp action)
1185 `(1
1186 ("o" ,action "default")
1187 ,@extra-actions))
1188 ((null action)
1189 (cons 1 extra-actions))
1190 (t
1191 (delete-dups (append action extra-actions)))))))
1192 (let ((extra-sources (plist-get ivy--sources-list caller)))
1193 (if extra-sources
1194 (progn
1195 (setq ivy--extra-candidates nil)
1196 (dolist (source extra-sources)
1197 (cond ((equal source '(original-source))
1198 (setq ivy--extra-candidates
1199 (cons source ivy--extra-candidates)))
1200 ((null (cdr source))
1201 (setq ivy--extra-candidates
1202 (cons
1203 (list (car source) (funcall (car source)))
1204 ivy--extra-candidates))))))
1205 (setq ivy--extra-candidates '((original-source)))))
1206 (let ((recursive-ivy-last (and (active-minibuffer-window) ivy-last)))
1207 (setq ivy-last
1208 (make-ivy-state
1209 :prompt prompt
1210 :collection collection
1211 :predicate predicate
1212 :require-match require-match
1213 :initial-input initial-input
1214 :history history
1215 :preselect preselect
1216 :keymap keymap
1217 :update-fn update-fn
1218 :sort sort
1219 :action action
1220 :window (selected-window)
1221 :buffer (current-buffer)
1222 :unwind unwind
1223 :re-builder re-builder
1224 :matcher matcher
1225 :dynamic-collection dynamic-collection
1226 :caller caller))
1227 (ivy--reset-state ivy-last)
1228 (prog1
1229 (unwind-protect
1230 (minibuffer-with-setup-hook
1231 #'ivy--minibuffer-setup
1232 (let* ((hist (or history 'ivy-history))
1233 (minibuffer-completion-table collection)
1234 (minibuffer-completion-predicate predicate)
1235 (resize-mini-windows (cond
1236 ((display-graphic-p) nil)
1237 ((null resize-mini-windows) 'grow-only)
1238 (t resize-mini-windows))))
1239 (read-from-minibuffer
1240 prompt
1241 (ivy-state-initial-input ivy-last)
1242 (make-composed-keymap keymap ivy-minibuffer-map)
1243 nil
1244 hist)
1245 (when (eq ivy-exit 'done)
1246 (let ((item (if ivy--directory
1247 ivy--current
1248 ivy-text)))
1249 (unless (equal item "")
1250 (set hist (cons (propertize item 'ivy-index ivy--index)
1251 (delete item
1252 (cdr (symbol-value hist))))))))
1253 ivy--current))
1254 (remove-hook 'post-command-hook #'ivy--exhibit)
1255 (when (setq unwind (ivy-state-unwind ivy-last))
1256 (funcall unwind))
1257 (unless (eq ivy-exit 'done)
1258 (when recursive-ivy-last
1259 (ivy--reset-state (setq ivy-last recursive-ivy-last)))))
1260 (ivy-call)
1261 (when (and recursive-ivy-last
1262 ivy-recursive-restore)
1263 (ivy--reset-state (setq ivy-last recursive-ivy-last))))))
1264
1265 (defun ivy--reset-state (state)
1266 "Reset the ivy to STATE.
1267 This is useful for recursive `ivy-read'."
1268 (let ((prompt (or (ivy-state-prompt state) ""))
1269 (collection (ivy-state-collection state))
1270 (predicate (ivy-state-predicate state))
1271 (history (ivy-state-history state))
1272 (preselect (ivy-state-preselect state))
1273 (sort (ivy-state-sort state))
1274 (re-builder (ivy-state-re-builder state))
1275 (dynamic-collection (ivy-state-dynamic-collection state))
1276 (initial-input (ivy-state-initial-input state))
1277 (require-match (ivy-state-require-match state))
1278 (caller (ivy-state-caller state)))
1279 (unless initial-input
1280 (setq initial-input (cdr (assoc this-command
1281 ivy-initial-inputs-alist))))
1282 (setq ivy--directory nil)
1283 (setq ivy-case-fold-search 'auto)
1284 (setq ivy--regex-function
1285 (or re-builder
1286 (and (functionp collection)
1287 (cdr (assoc collection ivy-re-builders-alist)))
1288 (and caller
1289 (cdr (assoc caller ivy-re-builders-alist)))
1290 (cdr (assoc this-command ivy-re-builders-alist))
1291 (cdr (assoc t ivy-re-builders-alist))
1292 'ivy--regex))
1293 (setq ivy--subexps 0)
1294 (setq ivy--regexp-quote 'regexp-quote)
1295 (setq ivy--old-text "")
1296 (setq ivy--full-length nil)
1297 (setq ivy-text "")
1298 (setq ivy-calling nil)
1299 (setq ivy-use-ignore t)
1300 (let (coll sort-fn)
1301 (cond ((eq collection 'Info-read-node-name-1)
1302 (if (equal Info-current-file "dir")
1303 (setq coll
1304 (mapcar (lambda (x) (format "(%s)" x))
1305 (cl-delete-duplicates
1306 (all-completions "(" collection predicate)
1307 :test #'equal)))
1308 (setq coll (all-completions "" collection predicate))))
1309 ((eq collection 'read-file-name-internal)
1310 (setq ivy--directory default-directory)
1311 (require 'dired)
1312 (when preselect
1313 (let ((preselect-directory (file-name-directory preselect)))
1314 (unless (or (null preselect-directory)
1315 (string= preselect-directory
1316 default-directory))
1317 (setq ivy--directory preselect-directory))
1318 (setf
1319 (ivy-state-preselect state)
1320 (setq preselect (file-name-nondirectory preselect)))))
1321 (setq coll (ivy--sorted-files ivy--directory))
1322 (when initial-input
1323 (unless (or require-match
1324 (equal initial-input default-directory)
1325 (equal initial-input ""))
1326 (setq coll (cons initial-input coll)))
1327 (unless (ivy-state-action ivy-last)
1328 (setq initial-input nil))))
1329 ((eq collection 'internal-complete-buffer)
1330 (setq coll (ivy--buffer-list "" ivy-use-virtual-buffers)))
1331 (dynamic-collection
1332 (setq coll (funcall collection ivy-text)))
1333 ((or (functionp collection)
1334 (byte-code-function-p collection)
1335 (vectorp collection)
1336 (and (consp collection) (listp (car collection)))
1337 (hash-table-p collection)
1338 (and (listp collection) (symbolp (car collection))))
1339 (setq coll (all-completions "" collection predicate)))
1340 (t
1341 (setq coll collection)))
1342 (when sort
1343 (if (and (functionp collection)
1344 (setq sort-fn (assoc collection ivy-sort-functions-alist)))
1345 (when (and (setq sort-fn (cdr sort-fn))
1346 (not (eq collection 'read-file-name-internal)))
1347 (setq coll (cl-sort coll sort-fn)))
1348 (unless (eq history 'org-refile-history)
1349 (if (and (setq sort-fn (cdr (assoc t ivy-sort-functions-alist)))
1350 (<= (length coll) ivy-sort-max-size))
1351 (setq coll (cl-sort (copy-sequence coll) sort-fn))))))
1352 (when preselect
1353 (unless (or (and require-match
1354 (not (eq collection 'internal-complete-buffer)))
1355 dynamic-collection
1356 (let ((re (regexp-quote preselect)))
1357 (cl-find-if (lambda (x) (string-match re x))
1358 coll)))
1359 (setq coll (cons preselect coll))))
1360 (setq ivy--old-re nil)
1361 (setq ivy--old-cands nil)
1362 (when (integerp preselect)
1363 (setq ivy--old-re "")
1364 (setq ivy--index preselect))
1365 (when initial-input
1366 ;; Needed for anchor to work
1367 (setq ivy--old-cands coll)
1368 (setq ivy--old-cands (ivy--filter initial-input coll)))
1369 (setq ivy--all-candidates coll)
1370 (unless (integerp preselect)
1371 (setq ivy--index (or
1372 (and dynamic-collection
1373 ivy--index)
1374 (and preselect
1375 (ivy--preselect-index
1376 preselect
1377 (if initial-input
1378 ivy--old-cands
1379 coll)))
1380 0))))
1381 (setq ivy-exit nil)
1382 (setq ivy--default
1383 (if (region-active-p)
1384 (buffer-substring
1385 (region-beginning)
1386 (region-end))
1387 (or
1388 (thing-at-point 'url)
1389 (thing-at-point 'symbol)
1390 "")))
1391 (setq ivy--prompt
1392 (cond ((string-match "%.*d" prompt)
1393 prompt)
1394 ((null ivy-count-format)
1395 (error
1396 "`ivy-count-format' can't be nil. Set it to an empty string instead"))
1397 ((string-match "%d.*%d" ivy-count-format)
1398 (let ((w (length (number-to-string
1399 (length ivy--all-candidates))))
1400 (s (copy-sequence ivy-count-format)))
1401 (string-match "%d" s)
1402 (match-end 0)
1403 (string-match "%d" s (match-end 0))
1404 (setq s (replace-match (format "%%-%dd" w) nil nil s))
1405 (string-match "%d" s)
1406 (concat (replace-match (format "%%%dd" w) nil nil s)
1407 prompt)))
1408 ((string-match "%.*d" ivy-count-format)
1409 (concat ivy-count-format prompt))
1410 (ivy--directory
1411 prompt)
1412 (t
1413 nil)))
1414 (setf (ivy-state-initial-input ivy-last) initial-input)))
1415
1416 ;;;###autoload
1417 (defun ivy-completing-read (prompt collection
1418 &optional predicate require-match initial-input
1419 history def inherit-input-method)
1420 "Read a string in the minibuffer, with completion.
1421
1422 This interface conforms to `completing-read' and can be used for
1423 `completing-read-function'.
1424
1425 PROMPT is a string to prompt with; normally it ends in a colon and a space.
1426 COLLECTION can be a list of strings, an alist, an obarray or a hash table.
1427 PREDICATE limits completion to a subset of COLLECTION.
1428 REQUIRE-MATCH is specified with a boolean value. See `completing-read'.
1429 INITIAL-INPUT is a string that can be inserted into the minibuffer initially.
1430 HISTORY is a list of previously selected inputs.
1431 DEF is the default value.
1432 INHERIT-INPUT-METHOD is currently ignored."
1433 (if (memq this-command '(tmm-menubar tmm-shortcut))
1434 (completing-read-default prompt collection
1435 predicate require-match
1436 initial-input history
1437 def inherit-input-method)
1438 ;; See the doc of `completing-read'.
1439 (when (consp history)
1440 (when (numberp (cdr history))
1441 (setq initial-input (nth (1- (cdr history))
1442 (symbol-value (car history)))))
1443 (setq history (car history)))
1444 (ivy-read (replace-regexp-in-string "%" "%%" prompt)
1445 collection
1446 :predicate predicate
1447 :require-match require-match
1448 :initial-input (if (consp initial-input)
1449 (car initial-input)
1450 (if (and (stringp initial-input)
1451 (string-match "\\+" initial-input))
1452 (replace-regexp-in-string
1453 "\\+" "\\\\+" initial-input)
1454 initial-input))
1455 :preselect (if (listp def) (car def) def)
1456 :history history
1457 :keymap nil
1458 :sort
1459 (let ((sort (assoc this-command ivy-sort-functions-alist)))
1460 (if sort
1461 (cdr sort)
1462 t)))))
1463
1464 (defvar ivy-completion-beg nil
1465 "Completion bounds start.")
1466
1467 (defvar ivy-completion-end nil
1468 "Completion bounds end.")
1469
1470 (defun ivy-completion-in-region-action (str)
1471 "Insert STR, erasing the previous one.
1472 The previous string is between `ivy-completion-beg' and `ivy-completion-end'."
1473 (when (stringp str)
1474 (with-ivy-window
1475 (when ivy-completion-beg
1476 (delete-region
1477 ivy-completion-beg
1478 ivy-completion-end))
1479 (setq ivy-completion-beg
1480 (move-marker (make-marker) (point)))
1481 (insert str)
1482 (setq ivy-completion-end
1483 (move-marker (make-marker) (point))))))
1484
1485 (defun ivy-completion-common-length (str)
1486 "Return the length of the first 'completions-common-part face in STR."
1487 (let ((pos 0)
1488 (len (length str)))
1489 (while (and (<= pos len)
1490 (let ((prop (get-text-property pos 'face str)))
1491 (not (eq 'completions-common-part
1492 (if (listp prop) (car prop) prop)))))
1493 (setq pos (1+ pos)))
1494 (if (< pos len)
1495 (or (next-single-property-change pos 'face str) len)
1496 0)))
1497
1498 (defun ivy-completion-in-region (start end collection &optional predicate)
1499 "An Ivy function suitable for `completion-in-region-function'."
1500 (let* ((enable-recursive-minibuffers t)
1501 (str (buffer-substring-no-properties start end))
1502 (comps
1503 (completion-all-completions str collection predicate (- end start))))
1504 (if (null comps)
1505 (message "No matches")
1506 (nconc comps nil)
1507 (setq ivy-completion-beg (- end (ivy-completion-common-length (car comps))))
1508 (setq ivy-completion-end end)
1509 (if (null (cdr comps))
1510 (if (string= str (car comps))
1511 (message "Sole match")
1512 (setf (ivy-state-window ivy-last) (selected-window))
1513 (ivy-completion-in-region-action
1514 (substring-no-properties
1515 (car comps))))
1516 (let* ((w (1+ (floor (log (length comps) 10))))
1517 (ivy-count-format (if (string= ivy-count-format "")
1518 ivy-count-format
1519 (format "%%-%dd " w)))
1520 (prompt (format "(%s): " str)))
1521 (and
1522 (ivy-read (if (string= ivy-count-format "")
1523 prompt
1524 (replace-regexp-in-string "%" "%%" prompt))
1525 ;; remove 'completions-first-difference face
1526 (mapcar #'substring-no-properties comps)
1527 :predicate predicate
1528 :action #'ivy-completion-in-region-action
1529 :require-match t)
1530 t))))))
1531
1532 (defcustom ivy-do-completion-in-region t
1533 "When non-nil `ivy-mode' will set `completion-in-region-function'."
1534 :type 'boolean)
1535
1536 ;;;###autoload
1537 (define-minor-mode ivy-mode
1538 "Toggle Ivy mode on or off.
1539 Turn Ivy mode on if ARG is positive, off otherwise.
1540 Turning on Ivy mode sets `completing-read-function' to
1541 `ivy-completing-read'.
1542
1543 Global bindings:
1544 \\{ivy-mode-map}
1545
1546 Minibuffer bindings:
1547 \\{ivy-minibuffer-map}"
1548 :group 'ivy
1549 :global t
1550 :keymap ivy-mode-map
1551 :lighter " ivy"
1552 (if ivy-mode
1553 (progn
1554 (setq completing-read-function 'ivy-completing-read)
1555 (when ivy-do-completion-in-region
1556 (setq completion-in-region-function 'ivy-completion-in-region)))
1557 (setq completing-read-function 'completing-read-default)
1558 (setq completion-in-region-function 'completion--in-region)))
1559
1560 (defun ivy--preselect-index (preselect candidates)
1561 "Return the index of PRESELECT in CANDIDATES."
1562 (cond ((integerp preselect)
1563 preselect)
1564 ((cl-position preselect candidates :test #'equal))
1565 ((stringp preselect)
1566 (let ((re (regexp-quote preselect)))
1567 (cl-position-if
1568 (lambda (x)
1569 (string-match re x))
1570 candidates)))))
1571
1572 ;;* Implementation
1573 ;;** Regex
1574 (defvar ivy--regex-hash
1575 (make-hash-table :test #'equal)
1576 "Store pre-computed regex.")
1577
1578 (defun ivy--split (str)
1579 "Split STR into a list by single spaces.
1580 The remaining spaces stick to their left.
1581 This allows to \"quote\" N spaces by inputting N+1 spaces."
1582 (let ((len (length str))
1583 start0
1584 (start1 0)
1585 res s
1586 match-len)
1587 (while (and (string-match " +" str start1)
1588 (< start1 len))
1589 (setq match-len (- (match-end 0) (match-beginning 0)))
1590 (if (= match-len 1)
1591 (progn
1592 (when start0
1593 (setq start1 start0)
1594 (setq start0 nil))
1595 (push (substring str start1 (match-beginning 0)) res)
1596 (setq start1 (match-end 0)))
1597 (setq str (replace-match
1598 (make-string (1- match-len) ?\ )
1599 nil nil str))
1600 (setq start0 (or start0 start1))
1601 (setq start1 (1- (match-end 0)))))
1602 (if start0
1603 (push (substring str start0) res)
1604 (setq s (substring str start1))
1605 (unless (= (length s) 0)
1606 (push s res)))
1607 (nreverse res)))
1608
1609 (defun ivy--regex (str &optional greedy)
1610 "Re-build regex pattern from STR in case it has a space.
1611 When GREEDY is non-nil, join words in a greedy way."
1612 (let ((hashed (unless greedy
1613 (gethash str ivy--regex-hash))))
1614 (if hashed
1615 (prog1 (cdr hashed)
1616 (setq ivy--subexps (car hashed)))
1617 (when (string-match "\\([^\\]\\|^\\)\\\\$" str)
1618 (setq str (substring str 0 -1)))
1619 (cdr (puthash str
1620 (let ((subs (ivy--split str)))
1621 (if (= (length subs) 1)
1622 (cons
1623 (setq ivy--subexps 0)
1624 (car subs))
1625 (cons
1626 (setq ivy--subexps (length subs))
1627 (mapconcat
1628 (lambda (x)
1629 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1630 x
1631 (format "\\(%s\\)" x)))
1632 subs
1633 (if greedy
1634 ".*"
1635 ".*?")))))
1636 ivy--regex-hash)))))
1637
1638 (defun ivy--regex-ignore-order--part (str &optional discard)
1639 "Re-build regex from STR by splitting at spaces.
1640 Ignore the order of each group."
1641 (let* ((subs (split-string str " +" t))
1642 (len (length subs)))
1643 (cl-case len
1644 (0
1645 "")
1646 (t
1647 (mapcar (lambda (x) (cons x (not discard)))
1648 subs)))))
1649
1650 (defun ivy--regex-ignore-order (str)
1651 "Re-build regex from STR by splitting at spaces.
1652 Ignore the order of each group. Everything before \"!\" should
1653 match. Everything after \"!\" should not match."
1654 (let ((parts (split-string str "!" t)))
1655 (cl-case (length parts)
1656 (0
1657 "")
1658 (1
1659 (if (string= (substring str 0 1) "!")
1660 (list (cons "" t)
1661 (ivy--regex-ignore-order--part (car parts) t))
1662 (ivy--regex-ignore-order--part (car parts))))
1663 (2
1664 (append
1665 (ivy--regex-ignore-order--part (car parts))
1666 (ivy--regex-ignore-order--part (cadr parts) t)))
1667 (t (error "Unexpected: use only one !")))))
1668
1669 (defun ivy--regex-plus (str)
1670 "Build a regex sequence from STR.
1671 Spaces are wild card characters, everything before \"!\" should
1672 match. Everything after \"!\" should not match."
1673 (let ((parts (split-string str "!" t)))
1674 (cl-case (length parts)
1675 (0
1676 "")
1677 (1
1678 (if (string= (substring str 0 1) "!")
1679 (list (cons "" t)
1680 (list (ivy--regex (car parts))))
1681 (ivy--regex (car parts))))
1682 (2
1683 (cons
1684 (cons (ivy--regex (car parts)) t)
1685 (mapcar #'list (split-string (cadr parts) " " t))))
1686 (t (error "Unexpected: use only one !")))))
1687
1688 (defun ivy--regex-fuzzy (str)
1689 "Build a regex sequence from STR.
1690 Insert .* between each char."
1691 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1692 (prog1
1693 (concat (match-string 1 str)
1694 (mapconcat
1695 (lambda (x)
1696 (format "\\(%c\\)" x))
1697 (string-to-list (match-string 2 str)) ".*")
1698 (match-string 3 str))
1699 (setq ivy--subexps (length (match-string 2 str))))
1700 str))
1701
1702 ;;** Rest
1703 (defun ivy--minibuffer-setup ()
1704 "Setup ivy completion in the minibuffer."
1705 (set (make-local-variable 'completion-show-inline-help) nil)
1706 (set (make-local-variable 'minibuffer-default-add-function)
1707 (lambda ()
1708 (list ivy--default)))
1709 (when (display-graphic-p)
1710 (setq truncate-lines t))
1711 (setq-local max-mini-window-height ivy-height)
1712 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1713 ;; show completions with empty input
1714 (ivy--exhibit))
1715
1716 (defun ivy--input ()
1717 "Return the current minibuffer input."
1718 ;; assume one-line minibuffer input
1719 (buffer-substring-no-properties
1720 (minibuffer-prompt-end)
1721 (line-end-position)))
1722
1723 (defun ivy--cleanup ()
1724 "Delete the displayed completion candidates."
1725 (save-excursion
1726 (goto-char (minibuffer-prompt-end))
1727 (delete-region (line-end-position) (point-max))))
1728
1729 (defun ivy--insert-prompt ()
1730 "Update the prompt according to `ivy--prompt'."
1731 (when ivy--prompt
1732 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1733 counsel-find-symbol))
1734 (setq ivy--prompt-extra ""))
1735 (let (head tail)
1736 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1737 (progn
1738 (setq head (match-string 1 ivy--prompt))
1739 (setq tail ": "))
1740 (setq head (substring ivy--prompt 0 -1))
1741 (setq tail " "))
1742 (let ((inhibit-read-only t)
1743 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1744 (n-str
1745 (concat
1746 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1747 (> (minibuffer-depth) 1))
1748 (format "[%d] " (minibuffer-depth))
1749 "")
1750 (concat
1751 (if (string-match "%d.*%d" ivy-count-format)
1752 (format head
1753 (1+ ivy--index)
1754 (or (and (ivy-state-dynamic-collection ivy-last)
1755 ivy--full-length)
1756 ivy--length))
1757 (format head
1758 (or (and (ivy-state-dynamic-collection ivy-last)
1759 ivy--full-length)
1760 ivy--length)))
1761 ivy--prompt-extra
1762 tail)))
1763 (d-str (if ivy--directory
1764 (abbreviate-file-name ivy--directory)
1765 "")))
1766 (save-excursion
1767 (goto-char (point-min))
1768 (delete-region (point-min) (minibuffer-prompt-end))
1769 (if (> (+ (mod (+ (length n-str) (length d-str)) (window-width))
1770 (length ivy-text))
1771 (window-width))
1772 (setq n-str (concat n-str "\n" d-str))
1773 (setq n-str (concat n-str d-str)))
1774 (let ((regex (format "\\([^\n]\\{%d\\}\\)[^\n]" (window-width))))
1775 (while (string-match regex n-str)
1776 (setq n-str (replace-match (concat (match-string 1 n-str) "\n") nil t n-str 1))))
1777 (set-text-properties 0 (length n-str)
1778 `(face minibuffer-prompt ,@std-props)
1779 n-str)
1780 (ivy--set-match-props n-str "confirm"
1781 `(face ivy-confirm-face ,@std-props))
1782 (ivy--set-match-props n-str "match required"
1783 `(face ivy-match-required-face ,@std-props))
1784 (insert n-str))
1785 ;; get out of the prompt area
1786 (constrain-to-field nil (point-max))))))
1787
1788 (defun ivy--set-match-props (str match props)
1789 "Set STR text properties that match MATCH to PROPS."
1790 (when (string-match match str)
1791 (set-text-properties
1792 (match-beginning 0)
1793 (match-end 0)
1794 props
1795 str)))
1796
1797 (defvar inhibit-message)
1798
1799 (defun ivy--sort-maybe (collection)
1800 "Sort COLLECTION if needed."
1801 (let ((sort (ivy-state-sort ivy-last))
1802 entry)
1803 (if (null sort)
1804 collection
1805 (let ((sort-fn (cond ((functionp sort)
1806 sort)
1807 ((setq entry (assoc (ivy-state-collection ivy-last)
1808 ivy-sort-functions-alist))
1809 (cdr entry))
1810 (t
1811 (cdr (assoc t ivy-sort-functions-alist))))))
1812 (if (functionp sort-fn)
1813 (cl-sort (copy-sequence collection) sort-fn)
1814 collection)))))
1815
1816 (defun ivy--exhibit ()
1817 "Insert Ivy completions display.
1818 Should be run via minibuffer `post-command-hook'."
1819 (when (memq 'ivy--exhibit post-command-hook)
1820 (let ((inhibit-field-text-motion nil))
1821 (constrain-to-field nil (point-max)))
1822 (setq ivy-text (ivy--input))
1823 (if (ivy-state-dynamic-collection ivy-last)
1824 ;; while-no-input would cause annoying
1825 ;; "Waiting for process to die...done" message interruptions
1826 (let ((inhibit-message t))
1827 (unless (equal ivy--old-text ivy-text)
1828 (while-no-input
1829 (setq ivy--all-candidates
1830 (ivy--sort-maybe
1831 (funcall (ivy-state-collection ivy-last) ivy-text)))
1832 (setq ivy--old-text ivy-text)))
1833 (when ivy--all-candidates
1834 (ivy--insert-minibuffer
1835 (ivy--format ivy--all-candidates))))
1836 (cond (ivy--directory
1837 (if (string-match "/\\'" ivy-text)
1838 (if (member ivy-text ivy--all-candidates)
1839 (ivy--cd (expand-file-name ivy-text ivy--directory))
1840 (when (string-match "//\\'" ivy-text)
1841 (if (and default-directory
1842 (string-match "\\`[[:alpha:]]:/" default-directory))
1843 (ivy--cd (match-string 0 default-directory))
1844 (ivy--cd "/")))
1845 (when (string-match "[[:alpha:]]:/$" ivy-text)
1846 (let ((drive-root (match-string 0 ivy-text)))
1847 (when (file-exists-p drive-root)
1848 (ivy--cd drive-root)))))
1849 (if (string-match "\\`~\\'" ivy-text)
1850 (ivy--cd (expand-file-name "~/")))))
1851 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1852 (when (or (and (string-match "\\` " ivy-text)
1853 (not (string-match "\\` " ivy--old-text)))
1854 (and (string-match "\\` " ivy--old-text)
1855 (not (string-match "\\` " ivy-text))))
1856 (setq ivy--all-candidates
1857 (if (and (> (length ivy-text) 0)
1858 (eq (aref ivy-text 0)
1859 ?\ ))
1860 (ivy--buffer-list " ")
1861 (ivy--buffer-list "" ivy-use-virtual-buffers)))
1862 (setq ivy--old-re nil))))
1863 (ivy--insert-minibuffer
1864 (with-current-buffer (ivy-state-buffer ivy-last)
1865 (ivy--format
1866 (ivy--filter ivy-text ivy--all-candidates))))
1867 (setq ivy--old-text ivy-text))))
1868
1869 (defun ivy--insert-minibuffer (text)
1870 "Insert TEXT into minibuffer with appropriate cleanup."
1871 (let ((resize-mini-windows nil)
1872 (update-fn (ivy-state-update-fn ivy-last))
1873 deactivate-mark)
1874 (ivy--cleanup)
1875 (when update-fn
1876 (funcall update-fn))
1877 (ivy--insert-prompt)
1878 ;; Do nothing if while-no-input was aborted.
1879 (when (stringp text)
1880 (let ((buffer-undo-list t))
1881 (save-excursion
1882 (forward-line 1)
1883 (insert text))))
1884 (when (display-graphic-p)
1885 (ivy--resize-minibuffer-to-fit))))
1886
1887 (defun ivy--resize-minibuffer-to-fit ()
1888 "Resize the minibuffer window size to fit the text in the minibuffer."
1889 (unless (frame-root-window-p (minibuffer-window))
1890 (with-selected-window (minibuffer-window)
1891 (if (fboundp 'window-text-pixel-size)
1892 (let ((text-height (cdr (window-text-pixel-size)))
1893 (body-height (window-body-height nil t)))
1894 (when (> text-height body-height)
1895 ;; Note: the size increment needs to be at least frame-char-height,
1896 ;; otherwise resizing won't do anything.
1897 (let ((delta (max (- text-height body-height) (frame-char-height))))
1898 (window-resize nil delta nil t t))))
1899 (let ((text-height (count-screen-lines))
1900 (body-height (window-body-height)))
1901 (when (> text-height body-height)
1902 (window-resize nil (- text-height body-height) nil t)))))))
1903
1904 (declare-function colir-blend-face-background "ext:colir")
1905
1906 (defun ivy--add-face (str face)
1907 "Propertize STR with FACE.
1908 `font-lock-append-text-property' is used, since it's better than
1909 `propertize' or `add-face-text-property' in this case."
1910 (require 'colir)
1911 (condition-case nil
1912 (progn
1913 (colir-blend-face-background 0 (length str) face str)
1914 (let ((foreground (face-foreground face)))
1915 (when foreground
1916 (add-face-text-property
1917 0 (length str)
1918 `(:foreground ,foreground)
1919 nil
1920 str))))
1921 (error
1922 (ignore-errors
1923 (font-lock-append-text-property 0 (length str) 'face face str))))
1924 str)
1925
1926 (declare-function flx-make-string-cache "ext:flx")
1927 (declare-function flx-score "ext:flx")
1928
1929 (defvar ivy--flx-cache nil)
1930
1931 (eval-after-load 'flx
1932 '(setq ivy--flx-cache (flx-make-string-cache)))
1933
1934 (defun ivy-toggle-case-fold ()
1935 "Toggle the case folding between nil and auto.
1936 In any completion session, the case folding starts in auto:
1937
1938 - when the input is all lower case, `case-fold-search' is t
1939 - otherwise nil.
1940
1941 You can toggle this to make `case-fold-search' nil regardless of input."
1942 (interactive)
1943 (setq ivy-case-fold-search
1944 (if ivy-case-fold-search
1945 nil
1946 'auto))
1947 ;; reset cache so that the candidate list updates
1948 (setq ivy--old-re nil))
1949
1950 (defun ivy--re-filter (re candidates)
1951 "Return all RE matching CANDIDATES.
1952 RE is a list of cons cells, with a regexp car and a boolean cdr.
1953 When the cdr is t, the car must match.
1954 Otherwise, the car must not match."
1955 (let ((re-list (if (stringp re) (list (cons re t)) re))
1956 (res candidates))
1957 (dolist (re re-list)
1958 (setq res
1959 (ignore-errors
1960 (funcall
1961 (if (cdr re)
1962 #'cl-remove-if-not
1963 #'cl-remove-if)
1964 (let ((re-str (car re)))
1965 (lambda (x) (string-match re-str x)))
1966 res))))
1967 res))
1968
1969 (defun ivy--filter (name candidates)
1970 "Return all items that match NAME in CANDIDATES.
1971 CANDIDATES are assumed to be static."
1972 (let ((re (funcall ivy--regex-function name)))
1973 (if (and (equal re ivy--old-re)
1974 ivy--old-cands)
1975 ;; quick caching for "C-n", "C-p" etc.
1976 ivy--old-cands
1977 (let* ((re-str (if (listp re) (caar re) re))
1978 (matcher (ivy-state-matcher ivy-last))
1979 (case-fold-search
1980 (and ivy-case-fold-search
1981 (string= name (downcase name))))
1982 (cands (cond
1983 (matcher
1984 (funcall matcher re candidates))
1985 ((and ivy--old-re
1986 (stringp re)
1987 (stringp ivy--old-re)
1988 (not (string-match "\\\\" ivy--old-re))
1989 (not (equal ivy--old-re ""))
1990 (memq (cl-search
1991 (if (string-match "\\\\)\\'" ivy--old-re)
1992 (substring ivy--old-re 0 -2)
1993 ivy--old-re)
1994 re)
1995 '(0 2)))
1996 (ignore-errors
1997 (cl-remove-if-not
1998 (lambda (x) (string-match re x))
1999 ivy--old-cands)))
2000 (t
2001 (ivy--re-filter re candidates)))))
2002 (ivy--recompute-index name re-str cands)
2003 (setq ivy--old-re
2004 (if (eq ivy--regex-function 'ivy--regex-ignore-order)
2005 re
2006 (if cands
2007 re-str
2008 "")))
2009 (setq ivy--old-cands (ivy--sort name cands))))))
2010
2011 (defun ivy--set-candidates (x)
2012 "Update `ivy--all-candidates' with X."
2013 (let (res)
2014 (dolist (source ivy--extra-candidates)
2015 (if (equal source '(original-source))
2016 (if (null res)
2017 (setq res x)
2018 (setq res (append x res)))
2019 (setq ivy--old-re nil)
2020 (setq res (append
2021 (ivy--filter ivy-text (cadr source))
2022 res))))
2023 (setq ivy--all-candidates res)))
2024
2025 (defcustom ivy-sort-matches-functions-alist '((t . nil))
2026 "An alist of functions used to sort the matching candidates.
2027
2028 This is different from `ivy-sort-functions-alist', which is used
2029 to sort the whole collection only once. The functions taken from
2030 here are instead used on each input change, but they are used
2031 only on already matching candidates, not on all of them.
2032
2033 The alist KEY is a collection function or t to match previously
2034 not matched collection functions.
2035
2036 The alist VAL is a sorting function with the signature of
2037 `ivy--prefix-sort'.")
2038
2039 (defun ivy--sort-files-by-date (_name candidates)
2040 "Re-soft CANDIDATES according to file modification date."
2041 (let ((default-directory ivy--directory))
2042 (cl-sort (copy-sequence candidates)
2043 (lambda (f1 f2)
2044 (time-less-p
2045 (nth 5 (file-attributes f2))
2046 (nth 5 (file-attributes f1)))))))
2047
2048 (defun ivy--sort (name candidates)
2049 "Re-sort CANDIDATES by NAME.
2050 All CANDIDATES are assumed to match NAME."
2051 (let ((key (or (ivy-state-caller ivy-last)
2052 (when (functionp (ivy-state-collection ivy-last))
2053 (ivy-state-collection ivy-last))))
2054 fun)
2055 (cond ((and (require 'flx nil 'noerror)
2056 (eq ivy--regex-function 'ivy--regex-fuzzy))
2057 (ivy--flx-sort name candidates))
2058 ((setq fun (cdr (or (assoc key ivy-sort-matches-functions-alist)
2059 (assoc t ivy-sort-matches-functions-alist))))
2060 (funcall fun name candidates))
2061 (t
2062 candidates))))
2063
2064 (defun ivy--prefix-sort (name candidates)
2065 "Re-sort CANDIDATES.
2066 Prefix matches to NAME are put ahead of the list."
2067 (if (or (string-match "^\\^" name) (string= name ""))
2068 candidates
2069 (let ((re-prefix (concat "^" (funcall ivy--regex-function name)))
2070 res-prefix
2071 res-noprefix)
2072 (dolist (s candidates)
2073 (if (string-match re-prefix s)
2074 (push s res-prefix)
2075 (push s res-noprefix)))
2076 (nconc
2077 (nreverse res-prefix)
2078 (nreverse res-noprefix)))))
2079
2080 (defun ivy--recompute-index (name re-str cands)
2081 (let* ((caller (ivy-state-caller ivy-last))
2082 (func (or (and caller (cdr (assoc caller ivy-index-functions-alist)))
2083 (cdr (assoc t ivy-index-functions-alist))
2084 #'ivy-recompute-index-zero)))
2085 (unless (eq this-command 'ivy-resume)
2086 (setq ivy--index
2087 (or
2088 (cl-position (if (and (> (length name) 0)
2089 (eq ?^ (aref name 0)))
2090 (substring name 1)
2091 name) cands
2092 :test #'equal)
2093 (and ivy--directory
2094 (cl-position
2095 (concat re-str "/") cands
2096 :test #'equal))
2097 (and (not (string= name ""))
2098 (not (and (require 'flx nil 'noerror)
2099 (eq ivy--regex-function 'ivy--regex-fuzzy)
2100 (< (length cands) 200)))
2101
2102 (cl-position (nth ivy--index ivy--old-cands)
2103 cands))
2104 (funcall func re-str cands))))
2105 (when (and (or (string= name "")
2106 (string= name "^"))
2107 (not (equal ivy--old-re "")))
2108 (setq ivy--index
2109 (or (ivy--preselect-index
2110 (ivy-state-preselect ivy-last)
2111 cands)
2112 ivy--index)))))
2113
2114 (defun ivy-recompute-index-swiper (_re-str cands)
2115 (let ((tail (nthcdr ivy--index ivy--old-cands))
2116 idx)
2117 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2118 (progn
2119 (while (and tail (null idx))
2120 ;; Compare with eq to handle equal duplicates in cands
2121 (setq idx (cl-position (pop tail) cands)))
2122 (or
2123 idx
2124 (1- (length cands))))
2125 (if ivy--old-cands
2126 ivy--index
2127 ;; already in ivy-state-buffer
2128 (let ((n (line-number-at-pos))
2129 (res 0)
2130 (i 0))
2131 (dolist (c cands)
2132 (when (eq n (read (get-text-property 0 'display c)))
2133 (setq res i))
2134 (cl-incf i))
2135 res)))))
2136
2137 (defun ivy-recompute-index-swiper-async (_re-str cands)
2138 (let ((tail (nthcdr ivy--index ivy--old-cands))
2139 idx)
2140 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2141 (progn
2142 (while (and tail (null idx))
2143 ;; Compare with `equal', since the collection is re-created
2144 ;; each time with `split-string'
2145 (setq idx (cl-position (pop tail) cands :test #'equal)))
2146 (or idx 0))
2147 ivy--index)))
2148
2149 (defun ivy-recompute-index-zero (_re-str _cands)
2150 0)
2151
2152 (defcustom ivy-minibuffer-faces
2153 '(ivy-minibuffer-match-face-1
2154 ivy-minibuffer-match-face-2
2155 ivy-minibuffer-match-face-3
2156 ivy-minibuffer-match-face-4)
2157 "List of `ivy' faces for minibuffer group matches.")
2158
2159 (defvar ivy-flx-limit 200
2160 "Used to conditionally turn off flx sorting.
2161 When the amount of matching candidates is larger than this
2162 number, no sorting will be done.")
2163
2164 (defun ivy--flx-sort (name cands)
2165 "Sort according to closeness to string NAME the string list CANDS."
2166 (condition-case nil
2167 (if (and cands
2168 (< (length cands) ivy-flx-limit))
2169 (let* ((flx-name (if (string-match "^\\^" name)
2170 (substring name 1)
2171 name))
2172 (cands-with-score
2173 (delq nil
2174 (mapcar
2175 (lambda (x)
2176 (let ((score (flx-score x flx-name ivy--flx-cache)))
2177 (and score
2178 (cons score x))))
2179 cands))))
2180 (if cands-with-score
2181 (mapcar (lambda (x)
2182 (let ((str (copy-sequence (cdr x)))
2183 (i 0)
2184 (last-j -2))
2185 (dolist (j (cdar x))
2186 (unless (eq j (1+ last-j))
2187 (cl-incf i))
2188 (setq last-j j)
2189 (ivy-add-face-text-property
2190 j (1+ j)
2191 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2192 ivy-minibuffer-faces)
2193 str))
2194 str))
2195 (sort cands-with-score
2196 (lambda (x y)
2197 (> (caar x) (caar y)))))
2198 cands))
2199 cands)
2200 (error
2201 cands)))
2202
2203 (defcustom ivy-format-function 'ivy-format-function-default
2204 "Function to transform the list of candidates into a string.
2205 This string is inserted into the minibuffer."
2206 :type '(choice
2207 (const :tag "Default" ivy-format-function-default)
2208 (const :tag "Arrow prefix" ivy-format-function-arrow)
2209 (const :tag "Full line" ivy-format-function-line)))
2210
2211 (defun ivy--truncate-string (str width)
2212 "Truncate STR to WIDTH."
2213 (if (> (string-width str) width)
2214 (concat (substring str 0 (min (- width 3)
2215 (- (length str) 3))) "...")
2216 str))
2217
2218 (defun ivy--format-function-generic (selected-fn other-fn cand-pairs separator)
2219 "Transform CAND-PAIRS into a string for minibuffer.
2220 SELECTED-FN and OTHER-FN each take two string arguments.
2221 SEPARATOR is used to join the candidates."
2222 (let ((i -1))
2223 (mapconcat
2224 (lambda (pair)
2225 (let ((str (car pair))
2226 (extra (cdr pair))
2227 (curr (eq (cl-incf i) ivy--index)))
2228 (if curr
2229 (funcall selected-fn str extra)
2230 (funcall other-fn str extra))))
2231 cand-pairs
2232 separator)))
2233
2234 (defun ivy-format-function-default (cand-pairs)
2235 "Transform CAND-PAIRS into a string for minibuffer."
2236 (ivy--format-function-generic
2237 (lambda (str extra)
2238 (concat (ivy--add-face str 'ivy-current-match) extra))
2239 #'concat
2240 cand-pairs
2241 "\n"))
2242
2243 (defun ivy-format-function-arrow (cand-pairs)
2244 "Transform CAND-PAIRS into a string for minibuffer."
2245 (ivy--format-function-generic
2246 (lambda (str extra)
2247 (concat "> " (ivy--add-face str 'ivy-current-match) extra))
2248 (lambda (str extra)
2249 (concat " " str extra))
2250 cand-pairs
2251 "\n"))
2252
2253 (defun ivy-format-function-line (cand-pairs)
2254 "Transform CAND-PAIRS into a string for minibuffer."
2255 (ivy--format-function-generic
2256 (lambda (str extra)
2257 (ivy--add-face (concat str extra "\n") 'ivy-current-match))
2258 (lambda (str extra)
2259 (concat str extra "\n"))
2260 cand-pairs
2261 ""))
2262
2263 (defun ivy-add-face-text-property (start end face str)
2264 (if (fboundp 'add-face-text-property)
2265 (add-face-text-property
2266 start end face nil str)
2267 (font-lock-append-text-property
2268 start end 'face face str)))
2269
2270 (defun ivy--format-minibuffer-line (str)
2271 (let ((start 0)
2272 (str (copy-sequence str)))
2273 (cond ((eq ivy--regex-function 'ivy--regex-ignore-order)
2274 (when (consp ivy--old-re)
2275 (let ((i 1))
2276 (dolist (re ivy--old-re)
2277 (when (string-match (car re) str)
2278 (ivy-add-face-text-property
2279 (match-beginning 0) (match-end 0)
2280 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2281 ivy-minibuffer-faces)
2282 str))
2283 (cl-incf i)))))
2284 ((and (eq ivy-display-style 'fancy)
2285 (not (eq ivy--regex-function 'ivy--regex-fuzzy)))
2286 (unless ivy--old-re
2287 (setq ivy--old-re (funcall ivy--regex-function ivy-text)))
2288 (while (and (string-match ivy--old-re str start)
2289 (> (- (match-end 0) (match-beginning 0)) 0))
2290 (setq start (match-end 0))
2291 (let ((i 0))
2292 (while (<= i ivy--subexps)
2293 (let ((face
2294 (cond ((zerop ivy--subexps)
2295 (cadr ivy-minibuffer-faces))
2296 ((zerop i)
2297 (car ivy-minibuffer-faces))
2298 (t
2299 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2300 ivy-minibuffer-faces)))))
2301 (ivy-add-face-text-property
2302 (match-beginning i) (match-end i)
2303 face str))
2304 (cl-incf i))))))
2305 str))
2306
2307 (defun ivy--format (cands)
2308 "Return a string for CANDS suitable for display in the minibuffer.
2309 CANDS is a list of strings."
2310 (setq ivy--length (length cands))
2311 (when (>= ivy--index ivy--length)
2312 (setq ivy--index (max (1- ivy--length) 0)))
2313 (if (null cands)
2314 (setq ivy--current "")
2315 (let* ((half-height (/ ivy-height 2))
2316 (start (max 0 (- ivy--index half-height)))
2317 (end (min (+ start (1- ivy-height)) ivy--length))
2318 (start (max 0 (min start (- end (1- ivy-height)))))
2319 (cands (cl-subseq cands start end))
2320 (index (- ivy--index start)))
2321 (cond (ivy--directory
2322 (setq cands (mapcar (lambda (x)
2323 (if (string-match-p "/\\'" x)
2324 (propertize x 'face 'ivy-subdir)
2325 x))
2326 cands)))
2327 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
2328 (setq cands (mapcar (lambda (x)
2329 (let ((b (get-buffer x)))
2330 (if (and b
2331 (buffer-file-name b)
2332 (buffer-modified-p b))
2333 (propertize x 'face 'ivy-modified-buffer)
2334 x)))
2335 cands))))
2336 (setq ivy--current (copy-sequence (nth index cands)))
2337 (let* ((ivy--index index)
2338 (cand-pairs (mapcar
2339 (lambda (cand)
2340 (cons (ivy--format-minibuffer-line cand) nil)) cands))
2341 (res (concat "\n" (funcall ivy-format-function cand-pairs))))
2342 (put-text-property 0 (length res) 'read-only nil res)
2343 res))))
2344
2345 (defvar ivy--virtual-buffers nil
2346 "Store the virtual buffers alist.")
2347
2348 (defvar recentf-list)
2349
2350 (defcustom ivy-virtual-abbreviate 'name
2351 "The mode of abbreviation for virtual buffer names."
2352 :type '(choice
2353 (const :tag "Only name" name)
2354 (const :tag "Full path" full)
2355 ;; eventually, uniquify
2356 ))
2357
2358 (defun ivy--virtual-buffers ()
2359 "Adapted from `ido-add-virtual-buffers-to-list'."
2360 (unless recentf-mode
2361 (recentf-mode 1))
2362 (let ((bookmarks (and (boundp 'bookmark-alist)
2363 bookmark-alist))
2364 virtual-buffers name)
2365 (dolist (head (append
2366 recentf-list
2367 (delete " - no file -"
2368 (delq nil (mapcar (lambda (bookmark)
2369 (cdr (assoc 'filename bookmark)))
2370 bookmarks)))))
2371 (setq name
2372 (if (eq ivy-virtual-abbreviate 'name)
2373 (file-name-nondirectory head)
2374 (expand-file-name head)))
2375 (when (equal name "")
2376 (setq name (file-name-nondirectory (directory-file-name head))))
2377 (when (equal name "")
2378 (setq name head))
2379 (and (not (equal name ""))
2380 (null (get-file-buffer head))
2381 (not (assoc name virtual-buffers))
2382 (push (cons name head) virtual-buffers)))
2383 (when virtual-buffers
2384 (dolist (comp virtual-buffers)
2385 (put-text-property 0 (length (car comp))
2386 'face 'ivy-virtual
2387 (car comp)))
2388 (setq ivy--virtual-buffers (nreverse virtual-buffers))
2389 (mapcar #'car ivy--virtual-buffers))))
2390
2391 (defcustom ivy-ignore-buffers nil
2392 "List of regexps matching buffer names to ignore."
2393 :type '(repeat regexp))
2394
2395 (defun ivy--buffer-list (str &optional virtual)
2396 "Return the buffers that match STR.
2397 When VIRTUAL is non-nil, add virtual buffers."
2398 (delete-dups
2399 (append
2400 (mapcar
2401 (lambda (x)
2402 (if (with-current-buffer x
2403 (file-remote-p
2404 (abbreviate-file-name default-directory)))
2405 (propertize x 'face 'ivy-remote)
2406 x))
2407 (all-completions str 'internal-complete-buffer))
2408 (and virtual
2409 (ivy--virtual-buffers)))))
2410
2411 (defun ivy--switch-buffer-action (buffer)
2412 "Switch to BUFFER.
2413 BUFFER may be a string or nil."
2414 (with-ivy-window
2415 (if (zerop (length buffer))
2416 (switch-to-buffer
2417 ivy-text nil 'force-same-window)
2418 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2419 (if (and virtual
2420 (not (get-buffer buffer)))
2421 (find-file (cdr virtual))
2422 (switch-to-buffer
2423 buffer nil 'force-same-window))))))
2424
2425 (defun ivy--switch-buffer-other-window-action (buffer)
2426 "Switch to BUFFER in other window.
2427 BUFFER may be a string or nil."
2428 (if (zerop (length buffer))
2429 (switch-to-buffer-other-window ivy-text)
2430 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2431 (if (and virtual
2432 (not (get-buffer buffer)))
2433 (find-file-other-window (cdr virtual))
2434 (switch-to-buffer-other-window buffer)))))
2435
2436 (defun ivy--rename-buffer-action (buffer)
2437 "Rename BUFFER."
2438 (let ((new-name (read-string "Rename buffer (to new name): ")))
2439 (with-current-buffer buffer
2440 (rename-buffer new-name))))
2441
2442 (defvar ivy-switch-buffer-map (make-sparse-keymap))
2443
2444 (ivy-set-actions
2445 'ivy-switch-buffer
2446 '(("k"
2447 (lambda (x)
2448 (kill-buffer x)
2449 (ivy--reset-state ivy-last))
2450 "kill")
2451 ("j"
2452 ivy--switch-buffer-other-window-action
2453 "other")
2454 ("r"
2455 ivy--rename-buffer-action
2456 "rename")))
2457
2458 (defun ivy--switch-buffer-matcher (regexp candidates)
2459 "Return REGEXP-matching CANDIDATES.
2460 Skip buffers that match `ivy-ignore-buffers'."
2461 (let ((res (ivy--re-filter regexp candidates)))
2462 (if (or (null ivy-use-ignore)
2463 (null ivy-ignore-buffers))
2464 res
2465 (or (cl-remove-if
2466 (lambda (buf)
2467 (cl-find-if
2468 (lambda (regexp)
2469 (string-match regexp buf))
2470 ivy-ignore-buffers))
2471 res)
2472 res))))
2473
2474 ;;;###autoload
2475 (defun ivy-switch-buffer ()
2476 "Switch to another buffer."
2477 (interactive)
2478 (if (not ivy-mode)
2479 (call-interactively 'switch-to-buffer)
2480 (let ((this-command 'ivy-switch-buffer))
2481 (ivy-read "Switch to buffer: " 'internal-complete-buffer
2482 :matcher #'ivy--switch-buffer-matcher
2483 :preselect (buffer-name (other-buffer (current-buffer)))
2484 :action #'ivy--switch-buffer-action
2485 :keymap ivy-switch-buffer-map))))
2486
2487 ;;;###autoload
2488 (defun ivy-switch-buffer-other-window ()
2489 "Switch to another buffer in another window."
2490 (interactive)
2491 (ivy-read "Switch to buffer in other window: " 'internal-complete-buffer
2492 :preselect (buffer-name (other-buffer (current-buffer)))
2493 :action #'ivy--switch-buffer-other-window-action
2494 :keymap ivy-switch-buffer-map))
2495
2496 ;;;###autoload
2497 (defun ivy-recentf ()
2498 "Find a file on `recentf-list'."
2499 (interactive)
2500 (ivy-read "Recentf: " recentf-list
2501 :action
2502 (lambda (f)
2503 (with-ivy-window
2504 (find-file f)))))
2505
2506 (defun ivy-yank-word ()
2507 "Pull next word from buffer into search string."
2508 (interactive)
2509 (let (amend)
2510 (with-ivy-window
2511 (let ((pt (point))
2512 (le (line-end-position)))
2513 (forward-word 1)
2514 (if (> (point) le)
2515 (goto-char pt)
2516 (setq amend (buffer-substring-no-properties pt (point))))))
2517 (when amend
2518 (insert (replace-regexp-in-string " +" " " amend)))))
2519
2520 (defun ivy-kill-ring-save ()
2521 "Store the current candidates into the kill ring.
2522 If the region is active, forward to `kill-ring-save' instead."
2523 (interactive)
2524 (if (region-active-p)
2525 (call-interactively 'kill-ring-save)
2526 (kill-new
2527 (mapconcat
2528 #'identity
2529 ivy--old-cands
2530 "\n"))))
2531
2532 (defun ivy-insert-current ()
2533 "Make the current candidate into current input.
2534 Don't finish completion."
2535 (interactive)
2536 (delete-minibuffer-contents)
2537 (if (and ivy--directory
2538 (string-match "/$" ivy--current))
2539 (insert (substring ivy--current 0 -1))
2540 (insert ivy--current)))
2541
2542 (defun ivy-toggle-fuzzy ()
2543 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
2544 (interactive)
2545 (setq ivy--old-re nil)
2546 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
2547 (setq ivy--regex-function 'ivy--regex-plus)
2548 (setq ivy--regex-function 'ivy--regex-fuzzy)))
2549
2550 (defun ivy-reverse-i-search ()
2551 "Enter a recursive `ivy-read' session using the current history.
2552 The selected history element will be inserted into the minibuffer."
2553 (interactive)
2554 (let ((enable-recursive-minibuffers t)
2555 (history (symbol-value (ivy-state-history ivy-last)))
2556 (old-last ivy-last)
2557 (ivy-recursive-restore nil))
2558 (ivy-read "Reverse-i-search: "
2559 history
2560 :action (lambda (x)
2561 (ivy--reset-state
2562 (setq ivy-last old-last))
2563 (delete-minibuffer-contents)
2564 (insert (substring-no-properties x))
2565 (ivy--cd-maybe)))))
2566
2567 (defun ivy-restrict-to-matches ()
2568 "Restrict candidates to current matches and erase input."
2569 (interactive)
2570 (delete-minibuffer-contents)
2571 (setq ivy--all-candidates
2572 (ivy--filter ivy-text ivy--all-candidates)))
2573
2574 ;;* Occur
2575 (defvar-local ivy-occur-last nil
2576 "Buffer-local value of `ivy-last'.
2577 Can't re-use `ivy-last' because using e.g. `swiper' in the same
2578 buffer would modify `ivy-last'.")
2579
2580 (defvar ivy-occur-mode-map
2581 (let ((map (make-sparse-keymap)))
2582 (define-key map [mouse-1] 'ivy-occur-click)
2583 (define-key map (kbd "RET") 'ivy-occur-press)
2584 (define-key map (kbd "j") 'next-line)
2585 (define-key map (kbd "k") 'previous-line)
2586 (define-key map (kbd "h") 'backward-char)
2587 (define-key map (kbd "l") 'forward-char)
2588 (define-key map (kbd "g") 'ivy-occur-press)
2589 (define-key map (kbd "a") 'ivy-occur-read-action)
2590 (define-key map (kbd "o") 'ivy-occur-dispatch)
2591 (define-key map (kbd "q") 'quit-window)
2592 map)
2593 "Keymap for Ivy Occur mode.")
2594
2595 (define-derived-mode ivy-occur-mode fundamental-mode "Ivy-Occur"
2596 "Major mode for output from \\[ivy-occur].
2597
2598 \\{ivy-occur-mode-map}")
2599
2600 (defvar ivy-occur-grep-mode-map
2601 (let ((map (copy-keymap ivy-occur-mode-map)))
2602 (define-key map (kbd "C-x C-q") 'ivy-wgrep-change-to-wgrep-mode)
2603 map)
2604 "Keymap for Ivy Occur Grep mode.")
2605
2606 (define-derived-mode ivy-occur-grep-mode grep-mode "Ivy-Occur"
2607 "Major mode for output from \\[ivy-occur].
2608
2609 \\{ivy-occur-grep-mode-map}")
2610
2611 (defvar counsel-git-grep-cmd)
2612
2613 (defun ivy-occur ()
2614 "Stop completion and put the current matches into a new buffer.
2615
2616 The new buffer remembers current action(s).
2617
2618 While in the *ivy-occur* buffer, selecting a candidate with RET or
2619 a mouse click will call the appropriate action for that candidate.
2620
2621 There is no limit on the number of *ivy-occur* buffers."
2622 (interactive)
2623 (let ((buffer
2624 (generate-new-buffer
2625 (format "*ivy-occur%s \"%s\"*"
2626 (let (caller)
2627 (if (setq caller (ivy-state-caller ivy-last))
2628 (concat " " (prin1-to-string caller))
2629 ""))
2630 ivy-text)))
2631 (do-grep (eq (ivy-state-caller ivy-last) 'counsel-git-grep)))
2632 (with-current-buffer buffer
2633 (if do-grep
2634 (progn
2635 (setq ivy--old-cands
2636 (split-string
2637 (shell-command-to-string
2638 (format counsel-git-grep-cmd
2639 (if (stringp ivy--old-re)
2640 ivy--old-re
2641 (caar ivy--old-re))))
2642 "\n"
2643 t))
2644 (ivy-occur-grep-mode))
2645 (ivy-occur-mode))
2646 (setf (ivy-state-text ivy-last) ivy-text)
2647 (setq ivy-occur-last ivy-last)
2648 (setq-local ivy--directory ivy--directory)
2649 (let ((inhibit-read-only t))
2650 (erase-buffer)
2651 (when do-grep
2652 ;; Need precise number of header lines for `wgrep' to work.
2653 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
2654 default-directory)))
2655 (insert (format "%d candidates:\n" (length ivy--old-cands)))
2656 (dolist (cand ivy--old-cands)
2657 (let ((str (if do-grep
2658 (concat "./" cand)
2659 (concat " " cand))))
2660 (add-text-properties
2661 0 (length str)
2662 `(mouse-face
2663 highlight
2664 help-echo "mouse-1: call ivy-action")
2665 str)
2666 (insert str "\n")))))
2667 (ivy-exit-with-action
2668 `(lambda (_) (pop-to-buffer ,buffer)))))
2669
2670 (declare-function wgrep-change-to-wgrep-mode "ext:wgrep")
2671
2672 (defun ivy-wgrep-change-to-wgrep-mode ()
2673 "Forward to `wgrep-change-to-wgrep-mode'."
2674 (interactive)
2675 (if (require 'wgrep nil 'noerror)
2676 (wgrep-change-to-wgrep-mode)
2677 (error "Package wgrep isn't installed")))
2678
2679 (defun ivy-occur-read-action ()
2680 "Select one of the available actions as the current one."
2681 (interactive)
2682 (let ((ivy-last ivy-occur-last))
2683 (ivy-read-action)))
2684
2685 (defun ivy-occur-dispatch ()
2686 "Call one of the available actions on the current item."
2687 (interactive)
2688 (let* ((state-action (ivy-state-action ivy-occur-last))
2689 (actions (if (symbolp state-action)
2690 state-action
2691 (copy-sequence state-action))))
2692 (unwind-protect
2693 (progn
2694 (ivy-occur-read-action)
2695 (ivy-occur-press))
2696 (setf (ivy-state-action ivy-occur-last) actions))))
2697
2698 (defun ivy-occur-click (event)
2699 "Execute action for the current candidate.
2700 EVENT gives the mouse position."
2701 (interactive "e")
2702 (let ((window (posn-window (event-end event)))
2703 (pos (posn-point (event-end event))))
2704 (with-current-buffer (window-buffer window)
2705 (goto-char pos)
2706 (ivy-occur-press))))
2707
2708 (declare-function swiper--cleanup "swiper")
2709 (declare-function swiper--add-overlays "swiper")
2710
2711 (defun ivy-occur-press ()
2712 "Execute action for the current candidate."
2713 (interactive)
2714 (require 'pulse)
2715 (when (save-excursion
2716 (beginning-of-line)
2717 (looking-at "\\(?:./\\| \\)\\(.*\\)$"))
2718 (let* ((ivy-last ivy-occur-last)
2719 (ivy-text (ivy-state-text ivy-last))
2720 (str (buffer-substring
2721 (match-beginning 1)
2722 (match-end 1)))
2723 (coll (ivy-state-collection ivy-last))
2724 (action (ivy--get-action ivy-last))
2725 (ivy-exit 'done))
2726 (with-ivy-window
2727 (funcall action
2728 (if (and (consp coll)
2729 (consp (car coll)))
2730 (cdr (assoc str coll))
2731 str))
2732 (if (memq (ivy-state-caller ivy-last)
2733 '(swiper counsel-git-grep))
2734 (with-current-buffer (window-buffer (selected-window))
2735 (swiper--cleanup)
2736 (swiper--add-overlays
2737 (ivy--regex ivy-text)
2738 (line-beginning-position)
2739 (line-end-position)
2740 (selected-window))
2741 (run-at-time 0.5 nil 'swiper--cleanup))
2742 (pulse-momentary-highlight-one-line (point)))))))
2743
2744 (defvar ivy-help-file (let ((default-directory
2745 (if load-file-name
2746 (file-name-directory load-file-name)
2747 default-directory)))
2748 (if (file-exists-p "ivy-help.org")
2749 (expand-file-name "ivy-help.org")
2750 (if (file-exists-p "doc/ivy-help.org")
2751 (expand-file-name "doc/ivy-help.org"))))
2752 "The file for `ivy-help'.")
2753
2754 (defun ivy-help ()
2755 "Help for `ivy'."
2756 (interactive)
2757 (let ((buf (get-buffer "*Ivy Help*")))
2758 (unless buf
2759 (setq buf (get-buffer-create "*Ivy Help*"))
2760 (with-current-buffer buf
2761 (insert-file-contents ivy-help-file)
2762 (org-mode)
2763 (view-mode)
2764 (goto-char (point-min))))
2765 (if (eq this-command 'ivy-help)
2766 (switch-to-buffer buf)
2767 (with-ivy-window
2768 (pop-to-buffer buf)))
2769 (view-mode)
2770 (goto-char (point-min))))
2771
2772 (provide 'ivy)
2773
2774 ;;; ivy.el ends here