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