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