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