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