]> code.delx.au - gnu-emacs-elpa/blob - ivy.el
ivy.el: Fix defcustom :type for several variables
[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 "Fall-through" t)
1080 (symbol :tag "Collection"))
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 :type '(alist
2067 :key-type (choice
2068 (const :tag "Fall-through" t)
2069 (symbol :tag "Collection"))
2070 :value-type
2071 (choice
2072 (const :tag "Don't sort" nil)
2073 (const :tag "Put prefix matches ahead" 'ivy--prefix-sort)
2074 (function :tag "Custom sort function"))))
2075
2076 (defun ivy--sort-files-by-date (_name candidates)
2077 "Re-soft CANDIDATES according to file modification date."
2078 (let ((default-directory ivy--directory))
2079 (cl-sort (copy-sequence candidates)
2080 (lambda (f1 f2)
2081 (time-less-p
2082 (nth 5 (file-attributes f2))
2083 (nth 5 (file-attributes f1)))))))
2084
2085 (defun ivy--sort (name candidates)
2086 "Re-sort CANDIDATES by NAME.
2087 All CANDIDATES are assumed to match NAME."
2088 (let ((key (or (ivy-state-caller ivy-last)
2089 (when (functionp (ivy-state-collection ivy-last))
2090 (ivy-state-collection ivy-last))))
2091 fun)
2092 (cond ((and (require 'flx nil 'noerror)
2093 (eq ivy--regex-function 'ivy--regex-fuzzy))
2094 (ivy--flx-sort name candidates))
2095 ((setq fun (cdr (or (assoc key ivy-sort-matches-functions-alist)
2096 (assoc t ivy-sort-matches-functions-alist))))
2097 (funcall fun name candidates))
2098 (t
2099 candidates))))
2100
2101 (defun ivy--prefix-sort (name candidates)
2102 "Re-sort CANDIDATES.
2103 Prefix matches to NAME are put ahead of the list."
2104 (if (or (string-match "^\\^" name) (string= name ""))
2105 candidates
2106 (let ((re-prefix (concat "^" (funcall ivy--regex-function name)))
2107 res-prefix
2108 res-noprefix)
2109 (dolist (s candidates)
2110 (if (string-match re-prefix s)
2111 (push s res-prefix)
2112 (push s res-noprefix)))
2113 (nconc
2114 (nreverse res-prefix)
2115 (nreverse res-noprefix)))))
2116
2117 (defun ivy--recompute-index (name re-str cands)
2118 (let* ((caller (ivy-state-caller ivy-last))
2119 (func (or (and caller (cdr (assoc caller ivy-index-functions-alist)))
2120 (cdr (assoc t ivy-index-functions-alist))
2121 #'ivy-recompute-index-zero)))
2122 (unless (eq this-command 'ivy-resume)
2123 (setq ivy--index
2124 (or
2125 (cl-position (if (and (> (length name) 0)
2126 (eq ?^ (aref name 0)))
2127 (substring name 1)
2128 name) cands
2129 :test #'equal)
2130 (and ivy--directory
2131 (cl-position
2132 (concat re-str "/") cands
2133 :test #'equal))
2134 (and (not (string= name ""))
2135 (not (and (require 'flx nil 'noerror)
2136 (eq ivy--regex-function 'ivy--regex-fuzzy)
2137 (< (length cands) 200)))
2138
2139 (cl-position (nth ivy--index ivy--old-cands)
2140 cands))
2141 (funcall func re-str cands))))
2142 (when (and (or (string= name "")
2143 (string= name "^"))
2144 (not (equal ivy--old-re "")))
2145 (setq ivy--index
2146 (or (ivy--preselect-index
2147 (ivy-state-preselect ivy-last)
2148 cands)
2149 ivy--index)))))
2150
2151 (defun ivy-recompute-index-swiper (_re-str cands)
2152 (let ((tail (nthcdr ivy--index ivy--old-cands))
2153 idx)
2154 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2155 (progn
2156 (while (and tail (null idx))
2157 ;; Compare with eq to handle equal duplicates in cands
2158 (setq idx (cl-position (pop tail) cands)))
2159 (or
2160 idx
2161 (1- (length cands))))
2162 (if ivy--old-cands
2163 ivy--index
2164 ;; already in ivy-state-buffer
2165 (let ((n (line-number-at-pos))
2166 (res 0)
2167 (i 0))
2168 (dolist (c cands)
2169 (when (eq n (read (get-text-property 0 'display c)))
2170 (setq res i))
2171 (cl-incf i))
2172 res)))))
2173
2174 (defun ivy-recompute-index-swiper-async (_re-str cands)
2175 (let ((tail (nthcdr ivy--index ivy--old-cands))
2176 idx)
2177 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2178 (progn
2179 (while (and tail (null idx))
2180 ;; Compare with `equal', since the collection is re-created
2181 ;; each time with `split-string'
2182 (setq idx (cl-position (pop tail) cands :test #'equal)))
2183 (or idx 0))
2184 ivy--index)))
2185
2186 (defun ivy-recompute-index-zero (_re-str _cands)
2187 0)
2188
2189 (defcustom ivy-minibuffer-faces
2190 '(ivy-minibuffer-match-face-1
2191 ivy-minibuffer-match-face-2
2192 ivy-minibuffer-match-face-3
2193 ivy-minibuffer-match-face-4)
2194 "List of `ivy' faces for minibuffer group matches."
2195 :type '(repeat :tag "Faces"
2196 (choice
2197 (const ivy-minibuffer-match-face-1)
2198 (const ivy-minibuffer-match-face-2)
2199 (const ivy-minibuffer-match-face-3)
2200 (const ivy-minibuffer-match-face-4)
2201 (face :tag "Other face"))))
2202
2203 (defvar ivy-flx-limit 200
2204 "Used to conditionally turn off flx sorting.
2205
2206 When the amount of matching candidates exceeds this limit, then
2207 no sorting is done.")
2208
2209 (defun ivy--flx-sort (name cands)
2210 "Sort according to closeness to string NAME the string list CANDS."
2211 (condition-case nil
2212 (if (and cands
2213 (< (length cands) ivy-flx-limit))
2214 (let* ((flx-name (if (string-match "^\\^" name)
2215 (substring name 1)
2216 name))
2217 (cands-with-score
2218 (delq nil
2219 (mapcar
2220 (lambda (x)
2221 (let ((score (flx-score x flx-name ivy--flx-cache)))
2222 (and score
2223 (cons score x))))
2224 cands))))
2225 (if cands-with-score
2226 (mapcar (lambda (x)
2227 (let ((str (copy-sequence (cdr x)))
2228 (i 0)
2229 (last-j -2))
2230 (dolist (j (cdar x))
2231 (unless (eq j (1+ last-j))
2232 (cl-incf i))
2233 (setq last-j j)
2234 (ivy-add-face-text-property
2235 j (1+ j)
2236 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2237 ivy-minibuffer-faces)
2238 str))
2239 str))
2240 (sort cands-with-score
2241 (lambda (x y)
2242 (> (caar x) (caar y)))))
2243 cands))
2244 cands)
2245 (error
2246 cands)))
2247
2248 (defcustom ivy-format-function 'ivy-format-function-default
2249 "Function to transform the list of candidates into a string.
2250 This string is inserted into the minibuffer."
2251 :type '(choice
2252 (const :tag "Default" ivy-format-function-default)
2253 (const :tag "Arrow prefix" ivy-format-function-arrow)
2254 (const :tag "Full line" ivy-format-function-line)))
2255
2256 (defun ivy--truncate-string (str width)
2257 "Truncate STR to WIDTH."
2258 (if (> (string-width str) width)
2259 (concat (substring str 0 (min (- width 3)
2260 (- (length str) 3))) "...")
2261 str))
2262
2263 (defun ivy--format-function-generic (selected-fn other-fn cand-pairs separator)
2264 "Transform CAND-PAIRS into a string for minibuffer.
2265 SELECTED-FN and OTHER-FN each take two string arguments.
2266 SEPARATOR is used to join the candidates."
2267 (let ((i -1))
2268 (mapconcat
2269 (lambda (pair)
2270 (let ((str (car pair))
2271 (extra (cdr pair))
2272 (curr (eq (cl-incf i) ivy--index)))
2273 (if curr
2274 (funcall selected-fn str extra)
2275 (funcall other-fn str extra))))
2276 cand-pairs
2277 separator)))
2278
2279 (defun ivy-format-function-default (cand-pairs)
2280 "Transform CAND-PAIRS into a string for minibuffer."
2281 (ivy--format-function-generic
2282 (lambda (str extra)
2283 (concat (ivy--add-face str 'ivy-current-match) extra))
2284 #'concat
2285 cand-pairs
2286 "\n"))
2287
2288 (defun ivy-format-function-arrow (cand-pairs)
2289 "Transform CAND-PAIRS into a string for minibuffer."
2290 (ivy--format-function-generic
2291 (lambda (str extra)
2292 (concat "> " (ivy--add-face str 'ivy-current-match) extra))
2293 (lambda (str extra)
2294 (concat " " str extra))
2295 cand-pairs
2296 "\n"))
2297
2298 (defun ivy-format-function-line (cand-pairs)
2299 "Transform CAND-PAIRS into a string for minibuffer."
2300 (ivy--format-function-generic
2301 (lambda (str extra)
2302 (ivy--add-face (concat str extra "\n") 'ivy-current-match))
2303 (lambda (str extra)
2304 (concat str extra "\n"))
2305 cand-pairs
2306 ""))
2307
2308 (defun ivy-add-face-text-property (start end face str)
2309 (if (fboundp 'add-face-text-property)
2310 (add-face-text-property
2311 start end face nil str)
2312 (font-lock-append-text-property
2313 start end 'face face str)))
2314
2315 (defun ivy--format-minibuffer-line (str)
2316 (let ((start 0)
2317 (str (copy-sequence str)))
2318 (cond ((eq ivy--regex-function 'ivy--regex-ignore-order)
2319 (when (consp ivy--old-re)
2320 (let ((i 1))
2321 (dolist (re ivy--old-re)
2322 (when (string-match (car re) str)
2323 (ivy-add-face-text-property
2324 (match-beginning 0) (match-end 0)
2325 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2326 ivy-minibuffer-faces)
2327 str))
2328 (cl-incf i)))))
2329 ((and (eq ivy-display-style 'fancy)
2330 (not (eq ivy--regex-function 'ivy--regex-fuzzy)))
2331 (unless ivy--old-re
2332 (setq ivy--old-re (funcall ivy--regex-function ivy-text)))
2333 (while (and (string-match ivy--old-re str start)
2334 (> (- (match-end 0) (match-beginning 0)) 0))
2335 (setq start (match-end 0))
2336 (let ((i 0))
2337 (while (<= i ivy--subexps)
2338 (let ((face
2339 (cond ((zerop ivy--subexps)
2340 (cadr ivy-minibuffer-faces))
2341 ((zerop i)
2342 (car ivy-minibuffer-faces))
2343 (t
2344 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2345 ivy-minibuffer-faces)))))
2346 (ivy-add-face-text-property
2347 (match-beginning i) (match-end i)
2348 face str))
2349 (cl-incf i))))))
2350 str))
2351
2352 (defun ivy--format (cands)
2353 "Return a string for CANDS suitable for display in the minibuffer.
2354 CANDS is a list of strings."
2355 (setq ivy--length (length cands))
2356 (when (>= ivy--index ivy--length)
2357 (setq ivy--index (max (1- ivy--length) 0)))
2358 (if (null cands)
2359 (setq ivy--current "")
2360 (let* ((half-height (/ ivy-height 2))
2361 (start (max 0 (- ivy--index half-height)))
2362 (end (min (+ start (1- ivy-height)) ivy--length))
2363 (start (max 0 (min start (- end (1- ivy-height)))))
2364 (cands (cl-subseq cands start end))
2365 (index (- ivy--index start)))
2366 (cond (ivy--directory
2367 (setq cands (mapcar (lambda (x)
2368 (if (string-match-p "/\\'" x)
2369 (propertize x 'face 'ivy-subdir)
2370 x))
2371 cands)))
2372 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
2373 (setq cands (mapcar (lambda (x)
2374 (let ((b (get-buffer x)))
2375 (if (and b
2376 (buffer-file-name b)
2377 (buffer-modified-p b))
2378 (propertize x 'face 'ivy-modified-buffer)
2379 x)))
2380 cands))))
2381 (setq ivy--current (copy-sequence (nth index cands)))
2382 (let* ((ivy--index index)
2383 (cand-pairs (mapcar
2384 (lambda (cand)
2385 (cons (ivy--format-minibuffer-line cand) nil)) cands))
2386 (res (concat "\n" (funcall ivy-format-function cand-pairs))))
2387 (put-text-property 0 (length res) 'read-only nil res)
2388 res))))
2389
2390 (defvar ivy--virtual-buffers nil
2391 "Store the virtual buffers alist.")
2392
2393 (defvar recentf-list)
2394
2395 (defcustom ivy-virtual-abbreviate 'name
2396 "The mode of abbreviation for virtual buffer names."
2397 :type '(choice
2398 (const :tag "Only name" name)
2399 (const :tag "Full path" full)
2400 ;; eventually, uniquify
2401 ))
2402
2403 (defun ivy--virtual-buffers ()
2404 "Adapted from `ido-add-virtual-buffers-to-list'."
2405 (unless recentf-mode
2406 (recentf-mode 1))
2407 (let ((bookmarks (and (boundp 'bookmark-alist)
2408 bookmark-alist))
2409 virtual-buffers name)
2410 (dolist (head (append
2411 recentf-list
2412 (delete " - no file -"
2413 (delq nil (mapcar (lambda (bookmark)
2414 (cdr (assoc 'filename bookmark)))
2415 bookmarks)))))
2416 (setq name
2417 (if (eq ivy-virtual-abbreviate 'name)
2418 (file-name-nondirectory head)
2419 (expand-file-name head)))
2420 (when (equal name "")
2421 (setq name (file-name-nondirectory (directory-file-name head))))
2422 (when (equal name "")
2423 (setq name head))
2424 (and (not (equal name ""))
2425 (null (get-file-buffer head))
2426 (not (assoc name virtual-buffers))
2427 (push (cons name head) virtual-buffers)))
2428 (when virtual-buffers
2429 (dolist (comp virtual-buffers)
2430 (put-text-property 0 (length (car comp))
2431 'face 'ivy-virtual
2432 (car comp)))
2433 (setq ivy--virtual-buffers (nreverse virtual-buffers))
2434 (mapcar #'car ivy--virtual-buffers))))
2435
2436 (defcustom ivy-ignore-buffers nil
2437 "List of regexps matching buffer names to ignore."
2438 :type '(repeat regexp))
2439
2440 (defun ivy--buffer-list (str &optional virtual)
2441 "Return the buffers that match STR.
2442 When VIRTUAL is non-nil, add virtual buffers."
2443 (delete-dups
2444 (append
2445 (mapcar
2446 (lambda (x)
2447 (if (with-current-buffer x
2448 (file-remote-p
2449 (abbreviate-file-name default-directory)))
2450 (propertize x 'face 'ivy-remote)
2451 x))
2452 (all-completions str 'internal-complete-buffer))
2453 (and virtual
2454 (ivy--virtual-buffers)))))
2455
2456 (defun ivy--switch-buffer-action (buffer)
2457 "Switch to BUFFER.
2458 BUFFER may be a string or nil."
2459 (with-ivy-window
2460 (if (zerop (length buffer))
2461 (switch-to-buffer
2462 ivy-text nil 'force-same-window)
2463 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2464 (if (and virtual
2465 (not (get-buffer buffer)))
2466 (find-file (cdr virtual))
2467 (switch-to-buffer
2468 buffer nil 'force-same-window))))))
2469
2470 (defun ivy--switch-buffer-other-window-action (buffer)
2471 "Switch to BUFFER in other window.
2472 BUFFER may be a string or nil."
2473 (if (zerop (length buffer))
2474 (switch-to-buffer-other-window ivy-text)
2475 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2476 (if (and virtual
2477 (not (get-buffer buffer)))
2478 (find-file-other-window (cdr virtual))
2479 (switch-to-buffer-other-window buffer)))))
2480
2481 (defun ivy--rename-buffer-action (buffer)
2482 "Rename BUFFER."
2483 (let ((new-name (read-string "Rename buffer (to new name): ")))
2484 (with-current-buffer buffer
2485 (rename-buffer new-name))))
2486
2487 (defvar ivy-switch-buffer-map (make-sparse-keymap))
2488
2489 (ivy-set-actions
2490 'ivy-switch-buffer
2491 '(("k"
2492 (lambda (x)
2493 (kill-buffer x)
2494 (ivy--reset-state ivy-last))
2495 "kill")
2496 ("j"
2497 ivy--switch-buffer-other-window-action
2498 "other")
2499 ("r"
2500 ivy--rename-buffer-action
2501 "rename")))
2502
2503 (defun ivy--switch-buffer-matcher (regexp candidates)
2504 "Return REGEXP-matching CANDIDATES.
2505 Skip buffers that match `ivy-ignore-buffers'."
2506 (let ((res (ivy--re-filter regexp candidates)))
2507 (if (or (null ivy-use-ignore)
2508 (null ivy-ignore-buffers))
2509 res
2510 (or (cl-remove-if
2511 (lambda (buf)
2512 (cl-find-if
2513 (lambda (regexp)
2514 (string-match regexp buf))
2515 ivy-ignore-buffers))
2516 res)
2517 res))))
2518
2519 ;;;###autoload
2520 (defun ivy-switch-buffer ()
2521 "Switch to another buffer."
2522 (interactive)
2523 (if (not ivy-mode)
2524 (call-interactively 'switch-to-buffer)
2525 (let ((this-command 'ivy-switch-buffer))
2526 (ivy-read "Switch to buffer: " 'internal-complete-buffer
2527 :matcher #'ivy--switch-buffer-matcher
2528 :preselect (buffer-name (other-buffer (current-buffer)))
2529 :action #'ivy--switch-buffer-action
2530 :keymap ivy-switch-buffer-map
2531 :caller 'ivy-switch-buffer))))
2532
2533 ;;;###autoload
2534 (defun ivy-switch-buffer-other-window ()
2535 "Switch to another buffer in another window."
2536 (interactive)
2537 (ivy-read "Switch to buffer in other window: " 'internal-complete-buffer
2538 :preselect (buffer-name (other-buffer (current-buffer)))
2539 :action #'ivy--switch-buffer-other-window-action
2540 :keymap ivy-switch-buffer-map
2541 :caller 'ivy-switch-buffer-other-window))
2542
2543 ;;;###autoload
2544 (defun ivy-recentf ()
2545 "Find a file on `recentf-list'."
2546 (interactive)
2547 (ivy-read "Recentf: " recentf-list
2548 :action
2549 (lambda (f)
2550 (with-ivy-window
2551 (find-file f)))
2552 :caller 'ivy-recentf))
2553
2554 (defun ivy-yank-word ()
2555 "Pull next word from buffer into search string."
2556 (interactive)
2557 (let (amend)
2558 (with-ivy-window
2559 (let ((pt (point))
2560 (le (line-end-position)))
2561 (forward-word 1)
2562 (if (> (point) le)
2563 (goto-char pt)
2564 (setq amend (buffer-substring-no-properties pt (point))))))
2565 (when amend
2566 (insert (replace-regexp-in-string " +" " " amend)))))
2567
2568 (defun ivy-kill-ring-save ()
2569 "Store the current candidates into the kill ring.
2570 If the region is active, forward to `kill-ring-save' instead."
2571 (interactive)
2572 (if (region-active-p)
2573 (call-interactively 'kill-ring-save)
2574 (kill-new
2575 (mapconcat
2576 #'identity
2577 ivy--old-cands
2578 "\n"))))
2579
2580 (defun ivy-insert-current ()
2581 "Make the current candidate into current input.
2582 Don't finish completion."
2583 (interactive)
2584 (delete-minibuffer-contents)
2585 (if (and ivy--directory
2586 (string-match "/$" ivy--current))
2587 (insert (substring ivy--current 0 -1))
2588 (insert ivy--current)))
2589
2590 (defun ivy-toggle-fuzzy ()
2591 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
2592 (interactive)
2593 (setq ivy--old-re nil)
2594 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
2595 (setq ivy--regex-function 'ivy--regex-plus)
2596 (setq ivy--regex-function 'ivy--regex-fuzzy)))
2597
2598 (defun ivy-reverse-i-search ()
2599 "Enter a recursive `ivy-read' session using the current history.
2600 The selected history element will be inserted into the minibuffer."
2601 (interactive)
2602 (let ((enable-recursive-minibuffers t)
2603 (history (symbol-value (ivy-state-history ivy-last)))
2604 (old-last ivy-last)
2605 (ivy-recursive-restore nil))
2606 (ivy-read "Reverse-i-search: "
2607 history
2608 :action (lambda (x)
2609 (ivy--reset-state
2610 (setq ivy-last old-last))
2611 (delete-minibuffer-contents)
2612 (insert (substring-no-properties x))
2613 (ivy--cd-maybe)))))
2614
2615 (defun ivy-restrict-to-matches ()
2616 "Restrict candidates to current matches and erase input."
2617 (interactive)
2618 (delete-minibuffer-contents)
2619 (setq ivy--all-candidates
2620 (ivy--filter ivy-text ivy--all-candidates)))
2621
2622 ;;* Occur
2623 (defvar-local ivy-occur-last nil
2624 "Buffer-local value of `ivy-last'.
2625 Can't re-use `ivy-last' because using e.g. `swiper' in the same
2626 buffer would modify `ivy-last'.")
2627
2628 (defvar ivy-occur-mode-map
2629 (let ((map (make-sparse-keymap)))
2630 (define-key map [mouse-1] 'ivy-occur-click)
2631 (define-key map (kbd "RET") 'ivy-occur-press)
2632 (define-key map (kbd "j") 'next-line)
2633 (define-key map (kbd "k") 'previous-line)
2634 (define-key map (kbd "h") 'backward-char)
2635 (define-key map (kbd "l") 'forward-char)
2636 (define-key map (kbd "g") 'ivy-occur-press)
2637 (define-key map (kbd "a") 'ivy-occur-read-action)
2638 (define-key map (kbd "o") 'ivy-occur-dispatch)
2639 (define-key map (kbd "q") 'quit-window)
2640 map)
2641 "Keymap for Ivy Occur mode.")
2642
2643 (define-derived-mode ivy-occur-mode fundamental-mode "Ivy-Occur"
2644 "Major mode for output from \\[ivy-occur].
2645
2646 \\{ivy-occur-mode-map}")
2647
2648 (defvar ivy-occur-grep-mode-map
2649 (let ((map (copy-keymap ivy-occur-mode-map)))
2650 (define-key map (kbd "C-x C-q") 'ivy-wgrep-change-to-wgrep-mode)
2651 map)
2652 "Keymap for Ivy Occur Grep mode.")
2653
2654 (define-derived-mode ivy-occur-grep-mode grep-mode "Ivy-Occur"
2655 "Major mode for output from \\[ivy-occur].
2656
2657 \\{ivy-occur-grep-mode-map}")
2658
2659 (defvar ivy--occurs-list nil
2660 "A list of custom occur generators per command.")
2661
2662 (defun ivy-set-occur (cmd occur)
2663 "Assign CMD a custom OCCUR function."
2664 (setq ivy--occurs-list
2665 (plist-put ivy--occurs-list cmd occur)))
2666
2667 (defun ivy--occur-insert-lines (cands)
2668 (dolist (str cands)
2669 (add-text-properties
2670 0 (length str)
2671 `(mouse-face
2672 highlight
2673 help-echo "mouse-1: call ivy-action")
2674 str)
2675 (insert str "\n")))
2676
2677 (defun ivy-occur ()
2678 "Stop completion and put the current matches into a new buffer.
2679
2680 The new buffer remembers current action(s).
2681
2682 While in the *ivy-occur* buffer, selecting a candidate with RET or
2683 a mouse click will call the appropriate action for that candidate.
2684
2685 There is no limit on the number of *ivy-occur* buffers."
2686 (interactive)
2687 (if (not (window-minibuffer-p))
2688 (user-error "No completion session is active")
2689 (let* ((caller (ivy-state-caller ivy-last))
2690 (occur-fn (plist-get ivy--occurs-list caller))
2691 (buffer
2692 (generate-new-buffer
2693 (format "*ivy-occur%s \"%s\"*"
2694 (if caller
2695 (concat " " (prin1-to-string caller))
2696 "")
2697 ivy-text))))
2698 (with-current-buffer buffer
2699 (let ((inhibit-read-only t))
2700 (erase-buffer)
2701 (if occur-fn
2702 (funcall occur-fn)
2703 (ivy-occur-mode)
2704 (insert (format "%d candidates:\n" (length ivy--old-cands)))
2705 (ivy--occur-insert-lines
2706 (mapcar
2707 (lambda (cand) (concat " " cand))
2708 ivy--old-cands))))
2709 (setf (ivy-state-text ivy-last) ivy-text)
2710 (setq ivy-occur-last ivy-last)
2711 (setq-local ivy--directory ivy--directory))
2712 (ivy-exit-with-action
2713 `(lambda (_) (pop-to-buffer ,buffer))))))
2714
2715 (declare-function wgrep-change-to-wgrep-mode "ext:wgrep")
2716
2717 (defun ivy-wgrep-change-to-wgrep-mode ()
2718 "Forward to `wgrep-change-to-wgrep-mode'."
2719 (interactive)
2720 (if (require 'wgrep nil 'noerror)
2721 (wgrep-change-to-wgrep-mode)
2722 (error "Package wgrep isn't installed")))
2723
2724 (defun ivy-occur-read-action ()
2725 "Select one of the available actions as the current one."
2726 (interactive)
2727 (let ((ivy-last ivy-occur-last))
2728 (ivy-read-action)))
2729
2730 (defun ivy-occur-dispatch ()
2731 "Call one of the available actions on the current item."
2732 (interactive)
2733 (let* ((state-action (ivy-state-action ivy-occur-last))
2734 (actions (if (symbolp state-action)
2735 state-action
2736 (copy-sequence state-action))))
2737 (unwind-protect
2738 (progn
2739 (ivy-occur-read-action)
2740 (ivy-occur-press))
2741 (setf (ivy-state-action ivy-occur-last) actions))))
2742
2743 (defun ivy-occur-click (event)
2744 "Execute action for the current candidate.
2745 EVENT gives the mouse position."
2746 (interactive "e")
2747 (let ((window (posn-window (event-end event)))
2748 (pos (posn-point (event-end event))))
2749 (with-current-buffer (window-buffer window)
2750 (goto-char pos)
2751 (ivy-occur-press))))
2752
2753 (declare-function swiper--cleanup "swiper")
2754 (declare-function swiper--add-overlays "swiper")
2755
2756 (defun ivy-occur-press ()
2757 "Execute action for the current candidate."
2758 (interactive)
2759 (require 'pulse)
2760 (when (save-excursion
2761 (beginning-of-line)
2762 (looking-at "\\(?:./\\| \\)\\(.*\\)$"))
2763 (let* ((ivy-last ivy-occur-last)
2764 (ivy-text (ivy-state-text ivy-last))
2765 (str (buffer-substring
2766 (match-beginning 1)
2767 (match-end 1)))
2768 (coll (ivy-state-collection ivy-last))
2769 (action (ivy--get-action ivy-last))
2770 (ivy-exit 'done))
2771 (with-ivy-window
2772 (funcall action
2773 (if (and (consp coll)
2774 (consp (car coll)))
2775 (cdr (assoc str coll))
2776 str))
2777 (if (memq (ivy-state-caller ivy-last)
2778 '(swiper counsel-git-grep))
2779 (with-current-buffer (window-buffer (selected-window))
2780 (swiper--cleanup)
2781 (swiper--add-overlays
2782 (ivy--regex ivy-text)
2783 (line-beginning-position)
2784 (line-end-position)
2785 (selected-window))
2786 (run-at-time 0.5 nil 'swiper--cleanup))
2787 (pulse-momentary-highlight-one-line (point)))))))
2788
2789 (defvar ivy-help-file (let ((default-directory
2790 (if load-file-name
2791 (file-name-directory load-file-name)
2792 default-directory)))
2793 (if (file-exists-p "ivy-help.org")
2794 (expand-file-name "ivy-help.org")
2795 (if (file-exists-p "doc/ivy-help.org")
2796 (expand-file-name "doc/ivy-help.org"))))
2797 "The file for `ivy-help'.")
2798
2799 (defun ivy-help ()
2800 "Help for `ivy'."
2801 (interactive)
2802 (let ((buf (get-buffer "*Ivy Help*")))
2803 (unless buf
2804 (setq buf (get-buffer-create "*Ivy Help*"))
2805 (with-current-buffer buf
2806 (insert-file-contents ivy-help-file)
2807 (org-mode)
2808 (view-mode)
2809 (goto-char (point-min))))
2810 (if (eq this-command 'ivy-help)
2811 (switch-to-buffer buf)
2812 (with-ivy-window
2813 (pop-to-buffer buf)))
2814 (view-mode)
2815 (goto-char (point-min))))
2816
2817 (provide 'ivy)
2818
2819 ;;; ivy.el ends here