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