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