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