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