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