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