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