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