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