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