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