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