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