]> code.delx.au - gnu-emacs-elpa/blob - ivy.el
swiper.el (swiper-font-lock-ensure): Add occur-mode
[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 (defface ivy-current-match
48 '((((class color) (background light))
49 :background "#1a4b77" :foreground "white")
50 (((class color) (background dark))
51 :background "#65a7e2" :foreground "black"))
52 "Face used by Ivy for highlighting first match.")
53
54 (defface ivy-confirm-face
55 '((t :foreground "ForestGreen" :inherit minibuffer-prompt))
56 "Face used by Ivy to issue a confirmation prompt.")
57
58 (defface ivy-match-required-face
59 '((t :foreground "red" :inherit minibuffer-prompt))
60 "Face used by Ivy to issue a match required prompt.")
61
62 (defface ivy-subdir
63 '((t (:inherit 'dired-directory)))
64 "Face used by Ivy for highlighting subdirs in the alternatives.")
65
66 (defface ivy-modified-buffer
67 '((t :inherit 'default))
68 "Face used by Ivy for highlighting modified file visiting buffers.")
69
70 (defface ivy-remote
71 '((t (:foreground "#110099")))
72 "Face used by Ivy for highlighting remotes in the alternatives.")
73
74 (defcustom ivy-height 10
75 "Number of lines for the minibuffer window."
76 :type 'integer)
77
78 (defcustom ivy-count-format "%-4d "
79 "The style of showing the current candidate count for `ivy-read'.
80 Set this to \"\" if you don't want the count. You can also set
81 it to e.g. \"(%d/%d) \" if you want to see both the candidate
82 index and the candidate count."
83 :type '(choice
84 (const :tag "Count disabled" "")
85 (const :tag "Count matches" "%-4d ")
86 (const :tag "Count matches and show current match" "(%d/%d) ")
87 string))
88
89 (defcustom ivy-wrap nil
90 "Whether to wrap around after the first and last candidate."
91 :type 'boolean)
92
93 (defcustom ivy-display-style (unless (version< emacs-version "24.5") 'fancy)
94 "The style for formatting the minibuffer.
95
96 By default, the matched strings will be copied as they are.
97
98 With the fancy method, the matching parts of the regexp will be
99 additionally highlighted, just like `swiper' does it.
100
101 This setting depends on `add-face-text-property' - a C function
102 available as of 24.5. It will behave poorly in earlier Emacs
103 versions."
104 :type '(choice
105 (const :tag "Plain" nil)
106 (const :tag "Fancy" fancy)))
107
108 (defcustom ivy-on-del-error-function 'minibuffer-keyboard-quit
109 "The handler for when `ivy-backward-delete-char' throws.
110 This is usually meant as a quick exit out of the minibuffer."
111 :type 'function)
112
113 (defcustom ivy-extra-directories '("../" "./")
114 "Add this to the front of the list when completing file names.
115 Only \"./\" and \"../\" apply here. They appear in reverse order."
116 :type '(repeat :tag "Dirs"
117 (choice
118 (const :tag "Parent Directory" "../")
119 (const :tag "Current Directory" "./"))))
120
121 (defcustom ivy-use-virtual-buffers nil
122 "When non-nil, add `recentf-mode' and bookmarks to `ivy-switch-buffer'."
123 :type 'boolean)
124
125 (defvar ivy--actions-list nil
126 "A list of extra actions per command.")
127
128 (defun ivy-set-actions (cmd actions)
129 "Set CMD extra exit points to ACTIONS."
130 (setq ivy--actions-list
131 (plist-put ivy--actions-list cmd actions)))
132
133 ;;* Keymap
134 (require 'delsel)
135 (defvar ivy-minibuffer-map
136 (let ((map (make-sparse-keymap)))
137 (define-key map (kbd "C-m") 'ivy-done)
138 (define-key map (kbd "C-M-m") 'ivy-call)
139 (define-key map (kbd "C-j") 'ivy-alt-done)
140 (define-key map (kbd "C-M-j") 'ivy-immediate-done)
141 (define-key map (kbd "TAB") 'ivy-partial-or-done)
142 (define-key map (kbd "C-n") 'ivy-next-line)
143 (define-key map (kbd "C-p") 'ivy-previous-line)
144 (define-key map (kbd "<down>") 'ivy-next-line)
145 (define-key map (kbd "<up>") 'ivy-previous-line)
146 (define-key map (kbd "C-s") 'ivy-next-line-or-history)
147 (define-key map (kbd "C-r") 'ivy-reverse-i-search)
148 (define-key map (kbd "SPC") 'self-insert-command)
149 (define-key map (kbd "DEL") 'ivy-backward-delete-char)
150 (define-key map (kbd "M-DEL") 'ivy-backward-kill-word)
151 (define-key map (kbd "C-d") 'ivy-delete-char)
152 (define-key map (kbd "C-f") 'ivy-forward-char)
153 (define-key map (kbd "M-d") 'ivy-kill-word)
154 (define-key map (kbd "M-<") 'ivy-beginning-of-buffer)
155 (define-key map (kbd "M->") 'ivy-end-of-buffer)
156 (define-key map (kbd "M-n") 'ivy-next-history-element)
157 (define-key map (kbd "M-p") 'ivy-previous-history-element)
158 (define-key map (kbd "C-g") 'minibuffer-keyboard-quit)
159 (define-key map (kbd "C-v") 'ivy-scroll-up-command)
160 (define-key map (kbd "M-v") 'ivy-scroll-down-command)
161 (define-key map (kbd "C-M-n") 'ivy-next-line-and-call)
162 (define-key map (kbd "C-M-p") 'ivy-previous-line-and-call)
163 (define-key map (kbd "M-q") 'ivy-toggle-regexp-quote)
164 (define-key map (kbd "M-j") 'ivy-yank-word)
165 (define-key map (kbd "M-i") 'ivy-insert-current)
166 (define-key map (kbd "C-o") 'hydra-ivy/body)
167 (define-key map (kbd "M-o") 'ivy-dispatching-done)
168 (define-key map (kbd "C-M-o") 'ivy-dispatching-call)
169 (define-key map (kbd "C-k") 'ivy-kill-line)
170 (define-key map (kbd "S-SPC") 'ivy-restrict-to-matches)
171 (define-key map (kbd "M-w") 'ivy-kill-ring-save)
172 (define-key map (kbd "C-'") 'ivy-avy)
173 (define-key map (kbd "C-M-a") 'ivy-read-action)
174 (define-key map (kbd "C-c C-o") 'ivy-occur)
175 map)
176 "Keymap used in the minibuffer.")
177 (autoload 'hydra-ivy/body "ivy-hydra" "" t)
178
179 (defvar ivy-mode-map
180 (let ((map (make-sparse-keymap)))
181 (define-key map [remap switch-to-buffer] 'ivy-switch-buffer)
182 map)
183 "Keymap for `ivy-mode'.")
184
185 ;;* Globals
186 (cl-defstruct ivy-state
187 prompt collection
188 predicate require-match initial-input
189 history preselect keymap update-fn sort
190 ;; The window in which `ivy-read' was called
191 window
192 ;; The buffer in which `ivy-read' was called
193 buffer
194 ;; The value of `ivy-text' to be used by `ivy-occur'
195 text
196 action
197 unwind
198 re-builder
199 matcher
200 ;; When this is non-nil, call it for each input change to get new candidates
201 dynamic-collection
202 caller)
203
204 (defvar ivy-last nil
205 "The last parameters passed to `ivy-read'.
206
207 This should eventually become a stack so that you could use
208 `ivy-read' recursively.")
209
210 (defsubst ivy-set-action (action)
211 (setf (ivy-state-action ivy-last) action))
212
213 (defvar ivy-history nil
214 "History list of candidates entered in the minibuffer.
215
216 Maximum length of the history list is determined by the value
217 of `history-length', which see.")
218
219 (defvar ivy--directory nil
220 "Current directory when completing file names.")
221
222 (defvar ivy--length 0
223 "Store the amount of viable candidates.")
224
225 (defvar ivy-text ""
226 "Store the user's string as it is typed in.")
227
228 (defvar ivy--current ""
229 "Current candidate.")
230
231 (defvar ivy--index 0
232 "Store the index of the current candidate.")
233
234 (defvar ivy-exit nil
235 "Store 'done if the completion was successfully selected.
236 Otherwise, store nil.")
237
238 (defvar ivy--all-candidates nil
239 "Store the candidates passed to `ivy-read'.")
240
241 (defvar ivy--default nil
242 "Default initial input.")
243
244 (defvar ivy--prompt nil
245 "Store the format-style prompt.
246 When non-nil, it should contain one %d.")
247
248 (defvar ivy--prompt-extra ""
249 "Temporary modifications to the prompt.")
250
251 (defvar ivy--old-re nil
252 "Store the old regexp.")
253
254 (defvar ivy--old-cands nil
255 "Store the candidates matched by `ivy--old-re'.")
256
257 (defvar ivy--regex-function 'ivy--regex
258 "Current function for building a regex.")
259
260 (defvar ivy--subexps 0
261 "Number of groups in the current `ivy--regex'.")
262
263 (defvar ivy--full-length nil
264 "When :dynamic-collection is non-nil, this can be the total amount of candidates.")
265
266 (defvar ivy--old-text ""
267 "Store old `ivy-text' for dynamic completion.")
268
269 (defvar ivy-case-fold-search 'auto
270 "Store the current overriding `case-fold-search'.")
271
272 (defvar Info-current-file)
273
274 (defmacro ivy-quit-and-run (&rest body)
275 "Quit the minibuffer and run BODY afterwards."
276 `(progn
277 (put 'quit 'error-message "")
278 (run-at-time nil nil
279 (lambda ()
280 (put 'quit 'error-message "Quit")
281 ,@body))
282 (minibuffer-keyboard-quit)))
283
284 (defun ivy-exit-with-action (action)
285 "Quit the minibuffer and call ACTION afterwards."
286 (ivy-set-action
287 `(lambda (x)
288 (funcall ,action x)
289 (ivy-set-action ',(ivy-state-action ivy-last))))
290 (setq ivy-exit 'done)
291 (exit-minibuffer))
292
293 (defmacro with-ivy-window (&rest body)
294 "Execute BODY in the window from which `ivy-read' was called."
295 (declare (indent 0)
296 (debug t))
297 `(with-selected-window (ivy--get-window ivy-last)
298 ,@body))
299
300 (defun ivy--done (text)
301 "Insert TEXT and exit minibuffer."
302 (if (and ivy--directory
303 (not (eq (ivy-state-history ivy-last) 'grep-files-history)))
304 (insert (setq ivy--current (expand-file-name
305 text ivy--directory)))
306 (insert (setq ivy--current text)))
307 (setq ivy-exit 'done)
308 (exit-minibuffer))
309
310 ;;* Commands
311 (defun ivy-done ()
312 "Exit the minibuffer with the selected candidate."
313 (interactive)
314 (delete-minibuffer-contents)
315 (cond ((> ivy--length 0)
316 (ivy--done ivy--current))
317 ((memq (ivy-state-collection ivy-last)
318 '(read-file-name-internal internal-complete-buffer))
319 (if (or (not (eq confirm-nonexistent-file-or-buffer t))
320 (equal " (confirm)" ivy--prompt-extra))
321 (ivy--done ivy-text)
322 (setq ivy--prompt-extra " (confirm)")
323 (insert ivy-text)
324 (ivy--exhibit)))
325 ((memq (ivy-state-require-match ivy-last)
326 '(nil confirm confirm-after-completion))
327 (ivy--done ivy-text))
328 (t
329 (setq ivy--prompt-extra " (match required)")
330 (insert ivy-text)
331 (ivy--exhibit))))
332
333 (defun ivy-read-action ()
334 "Change the action to one of the available ones."
335 (interactive)
336 (let ((actions (ivy-state-action ivy-last)))
337 (unless (null (ivy--actionp actions))
338 (let* ((hint (concat ivy--current
339 "\n"
340 (mapconcat
341 (lambda (x)
342 (format "%s: %s"
343 (propertize
344 (car x)
345 'face 'font-lock-builtin-face)
346 (nth 2 x)))
347 (cdr actions)
348 "\n")
349 "\n"))
350 (key (string (read-key hint)))
351 (action-idx (cl-position-if
352 (lambda (x) (equal (car x) key))
353 (cdr actions))))
354 (cond ((string= key "\a"))
355 ((null action-idx)
356 (error "%s is not bound" key))
357 (t
358 (message "")
359 (setcar actions (1+ action-idx))
360 (ivy-set-action actions)))))))
361
362 (defun ivy-dispatching-done ()
363 "Select one of the available actions and call `ivy-done'."
364 (interactive)
365 (ivy-read-action)
366 (ivy-done))
367
368 (defun ivy-dispatching-call ()
369 "Select one of the available actions and call `ivy-call'."
370 (interactive)
371 (let ((actions (copy-sequence (ivy-state-action ivy-last))))
372 (unwind-protect
373 (when (ivy-read-action)
374 (ivy-call))
375 (ivy-set-action actions))))
376
377 (defun ivy-build-tramp-name (x)
378 "Reconstruct X into a path.
379 Is is a cons cell, related to `tramp-get-completion-function'."
380 (let ((user (car x))
381 (domain (cadr x)))
382 (if user
383 (concat user "@" domain)
384 domain)))
385
386 (declare-function tramp-get-completion-function "tramp")
387 (declare-function Info-find-node "info")
388
389 (defun ivy-alt-done (&optional arg)
390 "Exit the minibuffer with the selected candidate.
391 When ARG is t, exit with current text, ignoring the candidates."
392 (interactive "P")
393 (let (dir)
394 (cond (arg
395 (ivy-immediate-done))
396 ((and ivy--directory
397 (equal ivy-text "/sudo::"))
398 (setq dir (concat ivy-text ivy--directory))
399 (ivy--cd dir)
400 (ivy--exhibit))
401 ((and ivy--directory
402 (or
403 (and
404 (not (equal ivy-text ""))
405 (ignore-errors
406 (file-directory-p
407 (setq dir
408 (file-name-as-directory
409 (expand-file-name
410 ivy-text ivy--directory))))))
411 (and
412 (not (string= ivy--current "./"))
413 (cl-plusp ivy--length)
414 (file-directory-p
415 (setq dir (expand-file-name
416 ivy--current ivy--directory))))))
417 (ivy--cd dir)
418 (ivy--exhibit))
419 ((eq (ivy-state-collection ivy-last) 'Info-read-node-name-1)
420 (if (or (equal ivy--current "(./)")
421 (equal ivy--current "(../)"))
422 (ivy-quit-and-run
423 (ivy-read "Go to file: " 'read-file-name-internal
424 :action (lambda (x)
425 (Info-find-node
426 (expand-file-name x ivy--directory)
427 "Top"))))
428 (ivy-done)))
429 ((and ivy--directory
430 (string-match "\\`/[^/]+:.*:.*\\'" ivy-text))
431 (ivy-done))
432 ((and ivy--directory
433 (string-match
434 "\\`/\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
435 ivy-text))
436 (let ((method (match-string 1 ivy-text))
437 (user (match-string 2 ivy-text))
438 (rest (match-string 3 ivy-text))
439 res)
440 (require 'tramp)
441 (dolist (x (tramp-get-completion-function method))
442 (setq res (append res (funcall (car x) (cadr x)))))
443 (setq res (delq nil res))
444 (when user
445 (dolist (x res)
446 (setcar x user)))
447 (setq res (cl-delete-duplicates res :test #'equal))
448 (let* ((old-ivy-last ivy-last)
449 (enable-recursive-minibuffers t)
450 (host (ivy-read "Find File: "
451 (mapcar #'ivy-build-tramp-name res)
452 :initial-input rest)))
453 (setq ivy-last old-ivy-last)
454 (when host
455 (setq ivy--directory "/")
456 (ivy--cd (concat "/" method ":" host ":"))))))
457 (t
458 (ivy-done)))))
459
460 (defcustom ivy-tab-space nil
461 "When non-nil, `ivy-partial-or-done' should insert a space."
462 :type 'boolean)
463
464 (defun ivy-partial-or-done ()
465 "Complete the minibuffer text as much as possible.
466 If the text hasn't changed as a result, forward to `ivy-alt-done'."
467 (interactive)
468 (if (and (eq (ivy-state-collection ivy-last) #'read-file-name-internal)
469 (string-match "\\`/" ivy-text))
470 (let ((default-directory ivy--directory))
471 (minibuffer-complete)
472 (setq ivy-text (ivy--input))
473 (when (and (file-directory-p ivy-text)
474 (= ivy--length 1))
475 (ivy--cd (expand-file-name ivy-text))))
476 (or (ivy-partial)
477 (when (or (eq this-command last-command)
478 (eq ivy--length 1))
479 (ivy-alt-done)))))
480
481 (defun ivy-partial ()
482 "Complete the minibuffer text as much as possible."
483 (interactive)
484 (let* ((parts (or (split-string ivy-text " " t) (list "")))
485 (postfix (car (last parts)))
486 (completion-ignore-case t)
487 (startp (string-match "^\\^" postfix))
488 (new (try-completion (if startp
489 (substring postfix 1)
490 postfix)
491 (mapcar (lambda (str)
492 (let ((i (string-match postfix str)))
493 (when i
494 (substring str i))))
495 ivy--old-cands))))
496 (cond ((eq new t) nil)
497 ((string= new ivy-text) nil)
498 (new
499 (delete-region (minibuffer-prompt-end) (point-max))
500 (setcar (last parts)
501 (if startp
502 (concat "^" new)
503 new))
504 (insert (mapconcat #'identity parts " ")
505 (if ivy-tab-space " " ""))
506 t))))
507
508 (defun ivy-immediate-done ()
509 "Exit the minibuffer with the current input."
510 (interactive)
511 (delete-minibuffer-contents)
512 (insert (setq ivy--current
513 (if ivy--directory
514 (expand-file-name ivy-text ivy--directory)
515 ivy-text)))
516 (setq ivy-exit 'done)
517 (exit-minibuffer))
518
519 ;;;###autoload
520 (defun ivy-resume ()
521 "Resume the last completion session."
522 (interactive)
523 (with-current-buffer (ivy-state-buffer ivy-last)
524 (ivy-read
525 (ivy-state-prompt ivy-last)
526 (ivy-state-collection ivy-last)
527 :predicate (ivy-state-predicate ivy-last)
528 :require-match (ivy-state-require-match ivy-last)
529 :initial-input ivy-text
530 :history (ivy-state-history ivy-last)
531 :preselect (unless (eq (ivy-state-collection ivy-last)
532 'read-file-name-internal)
533 ivy--current)
534 :keymap (ivy-state-keymap ivy-last)
535 :update-fn (ivy-state-update-fn ivy-last)
536 :sort (ivy-state-sort ivy-last)
537 :action (ivy-state-action ivy-last)
538 :unwind (ivy-state-unwind ivy-last)
539 :re-builder (ivy-state-re-builder ivy-last)
540 :matcher (ivy-state-matcher ivy-last)
541 :dynamic-collection (ivy-state-dynamic-collection ivy-last)
542 :caller (ivy-state-caller ivy-last))))
543
544 (defvar ivy-calling nil
545 "When non-nil, call the current action when `ivy--index' changes.")
546
547 (defun ivy-set-index (index)
548 "Set `ivy--index' to INDEX."
549 (setq ivy--index index)
550 (when ivy-calling
551 (ivy--exhibit)
552 (ivy-call)))
553
554 (defun ivy-beginning-of-buffer ()
555 "Select the first completion candidate."
556 (interactive)
557 (ivy-set-index 0))
558
559 (defun ivy-end-of-buffer ()
560 "Select the last completion candidate."
561 (interactive)
562 (ivy-set-index (1- ivy--length)))
563
564 (defun ivy-scroll-up-command ()
565 "Scroll the candidates upward by the minibuffer height."
566 (interactive)
567 (ivy-set-index (min (1- (+ ivy--index ivy-height))
568 (1- ivy--length))))
569
570 (defun ivy-scroll-down-command ()
571 "Scroll the candidates downward by the minibuffer height."
572 (interactive)
573 (ivy-set-index (max (1+ (- ivy--index ivy-height))
574 0)))
575
576 (defun ivy-minibuffer-grow ()
577 "Grow the minibuffer window by 1 line."
578 (interactive)
579 (setq-local max-mini-window-height
580 (cl-incf ivy-height)))
581
582 (defun ivy-minibuffer-shrink ()
583 "Shrink the minibuffer window by 1 line."
584 (interactive)
585 (unless (<= ivy-height 2)
586 (setq-local max-mini-window-height
587 (cl-decf ivy-height))
588 (window-resize (selected-window) -1)))
589
590 (defun ivy-next-line (&optional arg)
591 "Move cursor vertically down ARG candidates."
592 (interactive "p")
593 (setq arg (or arg 1))
594 (let ((index (+ ivy--index arg)))
595 (if (> index (1- ivy--length))
596 (if ivy-wrap
597 (ivy-beginning-of-buffer)
598 (ivy-set-index (1- ivy--length)))
599 (ivy-set-index index))))
600
601 (defun ivy-next-line-or-history (&optional arg)
602 "Move cursor vertically down ARG candidates.
603 If the input is empty, select the previous history element instead."
604 (interactive "p")
605 (when (string= ivy-text "")
606 (ivy-previous-history-element 1))
607 (ivy-next-line arg))
608
609 (defun ivy-previous-line (&optional arg)
610 "Move cursor vertically up ARG candidates."
611 (interactive "p")
612 (setq arg (or arg 1))
613 (let ((index (- ivy--index arg)))
614 (if (< index 0)
615 (if ivy-wrap
616 (ivy-end-of-buffer)
617 (ivy-set-index 0))
618 (ivy-set-index index))))
619
620 (defun ivy-previous-line-or-history (arg)
621 "Move cursor vertically up ARG candidates.
622 If the input is empty, select the previous history element instead."
623 (interactive "p")
624 (when (string= ivy-text "")
625 (ivy-previous-history-element 1))
626 (ivy-previous-line arg))
627
628 (defun ivy-toggle-calling ()
629 "Flip `ivy-calling'."
630 (interactive)
631 (when (setq ivy-calling (not ivy-calling))
632 (ivy-call)))
633
634 (defun ivy--get-action (state)
635 "Get the action function from STATE."
636 (let ((action (ivy-state-action state)))
637 (when action
638 (if (functionp action)
639 action
640 (cadr (nth (car action) action))))))
641
642 (defun ivy--get-window (state)
643 "Get the window from STATE."
644 (let ((window (ivy-state-window state)))
645 (if (window-live-p window)
646 window
647 (if (= (length (window-list)) 1)
648 (selected-window)
649 (next-window)))))
650
651 (defun ivy--actionp (x)
652 "Return non-nil when X is a list of actions."
653 (and x (listp x) (not (eq (car x) 'closure))))
654
655 (defun ivy-next-action ()
656 "When the current action is a list, scroll it forwards."
657 (interactive)
658 (let ((action (ivy-state-action ivy-last)))
659 (when (ivy--actionp action)
660 (unless (>= (car action) (1- (length action)))
661 (cl-incf (car action))))))
662
663 (defun ivy-prev-action ()
664 "When the current action is a list, scroll it backwards."
665 (interactive)
666 (let ((action (ivy-state-action ivy-last)))
667 (when (ivy--actionp action)
668 (unless (<= (car action) 1)
669 (cl-decf (car action))))))
670
671 (defun ivy-action-name ()
672 "Return the name associated with the current action."
673 (let ((action (ivy-state-action ivy-last)))
674 (if (ivy--actionp action)
675 (format "[%d/%d] %s"
676 (car action)
677 (1- (length action))
678 (nth 2 (nth (car action) action)))
679 "[1/1] default")))
680
681 (defun ivy-call ()
682 "Call the current action without exiting completion."
683 (interactive)
684 (let ((action (ivy--get-action ivy-last)))
685 (when action
686 (let* ((collection (ivy-state-collection ivy-last))
687 (x (if (and (consp collection)
688 (consp (car collection)))
689 (cdr (assoc ivy--current collection))
690 (if (equal ivy--current "")
691 ivy-text
692 ivy--current))))
693 (prog1 (funcall action x)
694 (unless (or (eq ivy-exit 'done)
695 (equal (selected-window)
696 (active-minibuffer-window))
697 (null (active-minibuffer-window)))
698 (select-window (active-minibuffer-window))))))))
699
700 (defun ivy-next-line-and-call (&optional arg)
701 "Move cursor vertically down ARG candidates.
702 Call the permanent action if possible."
703 (interactive "p")
704 (ivy-next-line arg)
705 (ivy--exhibit)
706 (ivy-call))
707
708 (defun ivy-previous-line-and-call (&optional arg)
709 "Move cursor vertically down ARG candidates.
710 Call the permanent action if possible."
711 (interactive "p")
712 (ivy-previous-line arg)
713 (ivy--exhibit)
714 (ivy-call))
715
716 (defun ivy-previous-history-element (arg)
717 "Forward to `previous-history-element' with ARG."
718 (interactive "p")
719 (previous-history-element arg)
720 (ivy--cd-maybe)
721 (move-end-of-line 1)
722 (ivy--maybe-scroll-history))
723
724 (defun ivy-next-history-element (arg)
725 "Forward to `next-history-element' with ARG."
726 (interactive "p")
727 (next-history-element arg)
728 (ivy--cd-maybe)
729 (move-end-of-line 1)
730 (ivy--maybe-scroll-history))
731
732 (defun ivy--cd-maybe ()
733 "Check if the current input points to a different directory.
734 If so, move to that directory, while keeping only the file name."
735 (when ivy--directory
736 (let ((input (ivy--input))
737 url)
738 (if (setq url (ffap-url-p input))
739 (progn
740 (ivy-set-action
741 (lambda (_)
742 (funcall ffap-url-fetcher url)))
743 (setq ivy-exit 'done)
744 (exit-minibuffer))
745 (setq input (expand-file-name input))
746 (let ((file (file-name-nondirectory input))
747 (dir (expand-file-name (file-name-directory input))))
748 (if (string= dir ivy--directory)
749 (progn
750 (delete-minibuffer-contents)
751 (insert file))
752 (ivy--cd dir)
753 (insert file)))))))
754
755 (defun ivy--maybe-scroll-history ()
756 "If the selected history element has an index, scroll there."
757 (let ((idx (ignore-errors
758 (get-text-property
759 (minibuffer-prompt-end)
760 'ivy-index))))
761 (when idx
762 (ivy--exhibit)
763 (setq ivy--index idx))))
764
765 (defun ivy--cd (dir)
766 "When completing file names, move to directory DIR."
767 (if (null ivy--directory)
768 (error "Unexpected")
769 (setq ivy--old-cands nil)
770 (setq ivy--old-re nil)
771 (setq ivy--index 0)
772 (setq ivy--all-candidates
773 (ivy--sorted-files (setq ivy--directory dir)))
774 (setq ivy-text "")
775 (delete-minibuffer-contents)))
776
777 (defun ivy-backward-delete-char ()
778 "Forward to `backward-delete-char'.
779 On error (read-only), call `ivy-on-del-error-function'."
780 (interactive)
781 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
782 (progn
783 (ivy--cd (file-name-directory
784 (directory-file-name
785 (expand-file-name
786 ivy--directory))))
787 (ivy--exhibit))
788 (condition-case nil
789 (backward-delete-char 1)
790 (error
791 (when ivy-on-del-error-function
792 (funcall ivy-on-del-error-function))))))
793
794 (defun ivy-delete-char (arg)
795 "Forward to `delete-char' ARG."
796 (interactive "p")
797 (unless (= (point) (line-end-position))
798 (delete-char arg)))
799
800 (defun ivy-forward-char (arg)
801 "Forward to `forward-char' ARG."
802 (interactive "p")
803 (unless (= (point) (line-end-position))
804 (forward-char arg)))
805
806 (defun ivy-kill-word (arg)
807 "Forward to `kill-word' ARG."
808 (interactive "p")
809 (unless (= (point) (line-end-position))
810 (kill-word arg)))
811
812 (defun ivy-kill-line ()
813 "Forward to `kill-line'."
814 (interactive)
815 (if (eolp)
816 (kill-region (minibuffer-prompt-end) (point))
817 (kill-line)))
818
819 (defun ivy-backward-kill-word ()
820 "Forward to `backward-kill-word'."
821 (interactive)
822 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
823 (progn
824 (ivy--cd (file-name-directory
825 (directory-file-name
826 (expand-file-name
827 ivy--directory))))
828 (ivy--exhibit))
829 (ignore-errors
830 (let ((pt (point)))
831 (forward-word -1)
832 (delete-region (point) pt)))))
833
834 (defvar ivy--regexp-quote 'regexp-quote
835 "Store the regexp quoting state.")
836
837 (defun ivy-toggle-regexp-quote ()
838 "Toggle the regexp quoting."
839 (interactive)
840 (setq ivy--old-re nil)
841 (cl-rotatef ivy--regex-function ivy--regexp-quote))
842
843 (defvar avy-all-windows)
844 (defvar avy-action)
845 (defvar avy-keys)
846 (defvar avy-keys-alist)
847 (defvar avy-style)
848 (defvar avy-styles-alist)
849 (declare-function avy--process "ext:avy")
850 (declare-function avy--style-fn "ext:avy")
851
852 (eval-after-load 'avy
853 '(add-to-list 'avy-styles-alist '(ivy-avy . pre)))
854
855 (defun ivy-avy ()
856 "Jump to one of the current ivy candidates."
857 (interactive)
858 (unless (require 'avy nil 'noerror)
859 (error "Package avy isn't installed"))
860 (let* ((avy-all-windows nil)
861 (avy-keys (or (cdr (assq 'ivy-avy avy-keys-alist))
862 avy-keys))
863 (avy-style (or (cdr (assq 'ivy-avy
864 avy-styles-alist))
865 avy-style))
866 (candidate
867 (let ((candidates))
868 (save-excursion
869 (save-restriction
870 (narrow-to-region
871 (window-start)
872 (window-end))
873 (goto-char (point-min))
874 (forward-line)
875 (while (< (point) (point-max))
876 (push
877 (cons (point)
878 (selected-window))
879 candidates)
880 (forward-line))))
881 (setq avy-action #'identity)
882 (avy--process
883 (nreverse candidates)
884 (avy--style-fn avy-style)))))
885 (ivy-set-index (- (line-number-at-pos candidate) 2))
886 (ivy--exhibit)
887 (ivy-done)))
888
889 (defun ivy-sort-file-function-default (x y)
890 "Compare two files X and Y.
891 Prioritize directories."
892 (if (get-text-property 0 'dirp x)
893 (if (get-text-property 0 'dirp y)
894 (string< x y)
895 t)
896 (if (get-text-property 0 'dirp y)
897 nil
898 (string< x y))))
899
900 (defcustom ivy-sort-functions-alist
901 '((read-file-name-internal . ivy-sort-file-function-default)
902 (internal-complete-buffer . nil)
903 (counsel-git-grep-function . nil)
904 (Man-goto-section . nil)
905 (org-refile . nil)
906 (t . string-lessp))
907 "An alist of sorting functions for each collection function.
908 Interactive functions that call completion fit in here as well.
909
910 For each entry, nil means no sorting. It's very useful to turn
911 off the sorting for functions that have candidates in the natural
912 buffer order, like `org-refile' or `Man-goto-section'.
913
914 The entry associated to t is used for all fall-through cases."
915 :type
916 '(alist
917 :key-type (choice
918 (const :tag "All other functions" t)
919 (symbol :tag "Function"))
920 :value-type (choice
921 (const :tag "plain sort" string-lessp)
922 (const :tag "file sort" ivy-sort-file-function-default)
923 (const :tag "no sort" nil)))
924 :group 'ivy)
925
926 (defvar ivy-index-functions-alist
927 '((swiper . ivy-recompute-index-swiper)
928 (swiper-multi . ivy-recompute-index-swiper)
929 (counsel-git-grep . ivy-recompute-index-swiper)
930 (t . ivy-recompute-index-zero))
931 "An alist of index recomputing functions for each collection function.
932 When the input changes, calling the appropriate function will
933 return an integer - the index of the matched candidate that
934 should be selected.")
935
936 (defvar ivy-re-builders-alist
937 '((t . ivy--regex-plus))
938 "An alist of regex building functions for each collection function.
939 Each function should take a string and return a valid regex or a
940 regex sequence (see below).
941
942 The entry associated to t is used for all fall-through cases.
943 Possible choices: `ivy--regex', `regexp-quote', `ivy--regex-plus'.
944
945 In case a function returns a list, it should look like this:
946 '((\"matching-regexp\" . t) (\"non-matching-regexp\") ...).
947
948 The matches will be filtered in a sequence, you can mix the
949 regexps that should match and that should not match as you
950 like.")
951
952 (defvar ivy-initial-inputs-alist
953 '((org-refile . "^")
954 (org-agenda-refile . "^")
955 (org-capture-refile . "^")
956 (counsel-M-x . "^")
957 (counsel-describe-function . "^")
958 (counsel-describe-variable . "^")
959 (man . "^")
960 (woman . "^"))
961 "Command to initial input table.")
962
963 (defcustom ivy-sort-max-size 30000
964 "Sorting won't be done for collections larger than this."
965 :type 'integer)
966
967 (defun ivy--sorted-files (dir)
968 "Return the list of files in DIR.
969 Directories come first."
970 (let* ((default-directory dir)
971 (seq (all-completions "" 'read-file-name-internal))
972 sort-fn)
973 (if (equal dir "/")
974 seq
975 (setq seq (delete "./" (delete "../" seq)))
976 (when (eq (setq sort-fn (cdr (assoc 'read-file-name-internal
977 ivy-sort-functions-alist)))
978 #'ivy-sort-file-function-default)
979 (setq seq (mapcar (lambda (x)
980 (propertize x 'dirp (string-match-p "/\\'" x)))
981 seq)))
982 (when sort-fn
983 (setq seq (cl-sort seq sort-fn)))
984 (dolist (dir ivy-extra-directories)
985 (push dir seq))
986 seq)))
987
988 ;;** Entry Point
989 (cl-defun ivy-read (prompt collection
990 &key predicate require-match initial-input
991 history preselect keymap update-fn sort
992 action unwind re-builder matcher dynamic-collection caller)
993 "Read a string in the minibuffer, with completion.
994
995 PROMPT is a string to prompt with; normally it ends in a colon
996 and a space. When PROMPT contains %d, it will be updated with
997 the current number of matching candidates. If % appears elsewhere
998 in the PROMPT it should be quoted as %%.
999 See also `ivy-count-format'.
1000
1001 COLLECTION is a list of strings, or a function, or an alist, or a
1002 hash table.
1003
1004 If INITIAL-INPUT is non-nil, insert it in the minibuffer initially.
1005
1006 KEYMAP is composed together with `ivy-minibuffer-map'.
1007
1008 If PRESELECT is non-nil select the corresponding candidate out of
1009 the ones that match INITIAL-INPUT.
1010
1011 UPDATE-FN is called each time the current candidate(s) is changed.
1012
1013 When SORT is t, refer to `ivy-sort-functions-alist' for sorting.
1014
1015 ACTION is a lambda to call after a result was selected. It should
1016 take a single argument, usually a string.
1017
1018 UNWIND is a lambda to call before exiting.
1019
1020 RE-BUILDER is a lambda that transforms text into a regex.
1021
1022 MATCHER can completely override matching.
1023
1024 DYNAMIC-COLLECTION is a boolean that determines whether to update
1025 the list of candidates with each input by calling COLLECTION for
1026 the current input.
1027
1028 CALLER is a symbol to uniquely identify the caller to `ivy-read'.
1029 It's used in conjunction with COLLECTION to indentify which
1030 customizations should apply to the current completion session."
1031 (let ((extra-actions (plist-get ivy--actions-list this-command)))
1032 (when extra-actions
1033 (setq action
1034 (if (functionp action)
1035 `(1
1036 ("o" ,action "default")
1037 ,@extra-actions)
1038 (delete-dups (append action extra-actions))))))
1039 (let ((recursive-ivy-last (and (window-minibuffer-p) ivy-last)))
1040 (setq ivy-last
1041 (make-ivy-state
1042 :prompt prompt
1043 :collection collection
1044 :predicate predicate
1045 :require-match require-match
1046 :initial-input initial-input
1047 :history history
1048 :preselect preselect
1049 :keymap keymap
1050 :update-fn update-fn
1051 :sort sort
1052 :action action
1053 :window (selected-window)
1054 :buffer (current-buffer)
1055 :unwind unwind
1056 :re-builder re-builder
1057 :matcher matcher
1058 :dynamic-collection dynamic-collection
1059 :caller caller))
1060 (ivy--reset-state ivy-last)
1061 (prog1
1062 (unwind-protect
1063 (minibuffer-with-setup-hook
1064 #'ivy--minibuffer-setup
1065 (let* ((hist (or history 'ivy-history))
1066 (minibuffer-completion-table collection)
1067 (minibuffer-completion-predicate predicate)
1068 (resize-mini-windows (cond
1069 ((display-graphic-p) nil)
1070 ((null resize-mini-windows) 'grow-only)
1071 (t resize-mini-windows)))
1072 (res (read-from-minibuffer
1073 prompt
1074 (ivy-state-initial-input ivy-last)
1075 (make-composed-keymap keymap ivy-minibuffer-map)
1076 nil
1077 hist)))
1078 (when (eq ivy-exit 'done)
1079 (let ((item (if ivy--directory
1080 ivy--current
1081 ivy-text)))
1082 (unless (equal item "")
1083 (set hist (cons (propertize item 'ivy-index ivy--index)
1084 (delete item
1085 (cdr (symbol-value hist)))))))
1086 res)))
1087 (remove-hook 'post-command-hook #'ivy--exhibit)
1088 (when (setq unwind (ivy-state-unwind ivy-last))
1089 (funcall unwind)))
1090 (ivy-call)
1091 (when recursive-ivy-last
1092 (ivy--reset-state (setq ivy-last recursive-ivy-last))))))
1093
1094 (defun ivy--reset-state (state)
1095 "Reset the ivy to STATE.
1096 This is useful for recursive `ivy-read'."
1097 (let ((prompt (ivy-state-prompt state))
1098 (collection (ivy-state-collection state))
1099 (predicate (ivy-state-predicate state))
1100 (history (ivy-state-history state))
1101 (preselect (ivy-state-preselect state))
1102 (sort (ivy-state-sort state))
1103 (re-builder (ivy-state-re-builder state))
1104 (dynamic-collection (ivy-state-dynamic-collection state))
1105 (initial-input (ivy-state-initial-input state))
1106 (require-match (ivy-state-require-match state))
1107 (matcher (ivy-state-matcher state)))
1108 (unless initial-input
1109 (setq initial-input (cdr (assoc this-command
1110 ivy-initial-inputs-alist))))
1111 (setq ivy--directory nil)
1112 (setq ivy-case-fold-search 'auto)
1113 (setq ivy--regex-function
1114 (or re-builder
1115 (and (functionp collection)
1116 (cdr (assoc collection ivy-re-builders-alist)))
1117 (cdr (assoc t ivy-re-builders-alist))
1118 'ivy--regex))
1119 (setq ivy--subexps 0)
1120 (setq ivy--regexp-quote 'regexp-quote)
1121 (setq ivy--old-text "")
1122 (setq ivy--full-length nil)
1123 (setq ivy-text "")
1124 (setq ivy-calling nil)
1125 (let (coll sort-fn)
1126 (cond ((eq collection 'Info-read-node-name-1)
1127 (if (equal Info-current-file "dir")
1128 (setq coll
1129 (mapcar (lambda (x) (format "(%s)" x))
1130 (cl-delete-duplicates
1131 (all-completions "(" collection predicate)
1132 :test #'equal)))
1133 (setq coll (all-completions "" collection predicate))))
1134 ((eq collection 'read-file-name-internal)
1135 (setq ivy--directory default-directory)
1136 (require 'dired)
1137 (when preselect
1138 (let ((preselect-directory (file-name-directory preselect)))
1139 (unless (or (null preselect-directory)
1140 (string= preselect-directory
1141 default-directory))
1142 (setq ivy--directory preselect-directory))
1143 (setf
1144 (ivy-state-preselect state)
1145 (setq preselect (file-name-nondirectory preselect)))))
1146 (setq coll (ivy--sorted-files ivy--directory))
1147 (when initial-input
1148 (unless (or require-match
1149 (equal initial-input default-directory)
1150 (equal initial-input ""))
1151 (setq coll (cons initial-input coll)))
1152 (setq initial-input nil)))
1153 ((eq collection 'internal-complete-buffer)
1154 (setq coll (ivy--buffer-list "" ivy-use-virtual-buffers)))
1155 ((or (functionp collection)
1156 (byte-code-function-p collection)
1157 (vectorp collection)
1158 (and (consp collection) (listp (car collection)))
1159 (hash-table-p collection))
1160 (setq coll (all-completions "" collection predicate)))
1161 (t
1162 (setq coll collection)))
1163 (when sort
1164 (if (and (functionp collection)
1165 (setq sort-fn (assoc collection ivy-sort-functions-alist)))
1166 (when (and (setq sort-fn (cdr sort-fn))
1167 (not (eq collection 'read-file-name-internal)))
1168 (setq coll (cl-sort coll sort-fn)))
1169 (unless (eq history 'org-refile-history)
1170 (if (and (setq sort-fn (cdr (assoc t ivy-sort-functions-alist)))
1171 (<= (length coll) ivy-sort-max-size))
1172 (setq coll (cl-sort (copy-sequence coll) sort-fn))))))
1173 (when preselect
1174 (unless (or (and require-match
1175 (not (eq collection 'internal-complete-buffer)))
1176 (let ((re (regexp-quote preselect)))
1177 (cl-find-if (lambda (x) (string-match re x))
1178 coll)))
1179 (setq coll (cons preselect coll))))
1180 (setq ivy--index (or
1181 (and dynamic-collection
1182 ivy--index)
1183 (and preselect
1184 (ivy--preselect-index
1185 coll initial-input preselect matcher))
1186 0))
1187 (setq ivy--old-re nil)
1188 (setq ivy--old-cands nil)
1189 (setq ivy--all-candidates coll))
1190 (setq ivy-exit nil)
1191 (setq ivy--default (or
1192 (thing-at-point 'url)
1193 (thing-at-point 'symbol)
1194 ""))
1195 (setq ivy--prompt
1196 (cond ((string-match "%.*d" prompt)
1197 prompt)
1198 ((null ivy-count-format)
1199 (error
1200 "`ivy-count-format' can't be nil. Set it to an empty string instead"))
1201 ((string-match "%d.*%d" ivy-count-format)
1202 (let ((w (length (number-to-string
1203 (length ivy--all-candidates))))
1204 (s (copy-sequence ivy-count-format)))
1205 (string-match "%d" s)
1206 (match-end 0)
1207 (string-match "%d" s (match-end 0))
1208 (setq s (replace-match (format "%%-%dd" w) nil nil s))
1209 (string-match "%d" s)
1210 (concat (replace-match (format "%%%dd" w) nil nil s)
1211 prompt)))
1212 ((string-match "%.*d" ivy-count-format)
1213 (concat ivy-count-format prompt))
1214 (ivy--directory
1215 prompt)
1216 (t
1217 nil)))
1218 (setf (ivy-state-initial-input ivy-last) initial-input)))
1219
1220 ;;;###autoload
1221 (defun ivy-completing-read (prompt collection
1222 &optional predicate require-match initial-input
1223 history def _inherit-input-method)
1224 "Read a string in the minibuffer, with completion.
1225
1226 This is an interface that conforms to `completing-read', so that
1227 it can be used for `completing-read-function'.
1228
1229 PROMPT is a string to prompt with; normally it ends in a colon and a space.
1230 COLLECTION can be a list of strings, an alist, an obarray or a hash table.
1231 PREDICATE limits completion to a subset of COLLECTION.
1232 REQUIRE-MATCH is considered boolean. See `completing-read'.
1233 INITIAL-INPUT is a string that can be inserted into the minibuffer initially.
1234 _HISTORY is ignored for now.
1235 DEF is the default value.
1236 _INHERIT-INPUT-METHOD is ignored for now.
1237
1238 The history, defaults and input-method arguments are ignored for now."
1239 (ivy-read (replace-regexp-in-string "%" "%%" prompt)
1240 collection
1241 :predicate predicate
1242 :require-match require-match
1243 :initial-input (if (consp initial-input)
1244 (car initial-input)
1245 (if (and (stringp initial-input)
1246 (string-match "\\+" initial-input))
1247 (replace-regexp-in-string
1248 "\\+" "\\\\+" initial-input)
1249 initial-input))
1250 :preselect (if (listp def) (car def) def)
1251 :history history
1252 :keymap nil
1253 :sort
1254 (let ((sort (assoc this-command ivy-sort-functions-alist)))
1255 (if sort
1256 (cdr sort)
1257 t))))
1258
1259 ;;;###autoload
1260 (define-minor-mode ivy-mode
1261 "Toggle Ivy mode on or off.
1262 With ARG, turn Ivy mode on if arg is positive, off otherwise.
1263 Turning on Ivy mode will set `completing-read-function' to
1264 `ivy-completing-read'.
1265
1266 Global bindings:
1267 \\{ivy-mode-map}
1268
1269 Minibuffer bindings:
1270 \\{ivy-minibuffer-map}"
1271 :group 'ivy
1272 :global t
1273 :keymap ivy-mode-map
1274 :lighter " ivy"
1275 (if ivy-mode
1276 (setq completing-read-function 'ivy-completing-read)
1277 (setq completing-read-function 'completing-read-default)))
1278
1279 (defun ivy--preselect-index (candidates initial-input preselect matcher)
1280 "Return the index in CANDIDATES filtered by INITIAL-INPUT for PRESELECT.
1281 When MATCHER is non-nil it's used instead of `cl-remove-if-not'."
1282 (if initial-input
1283 (progn
1284 (setq initial-input (ivy--regex-plus initial-input))
1285 (setq candidates
1286 (if matcher
1287 (funcall matcher initial-input candidates)
1288 (cl-remove-if-not
1289 (lambda (x)
1290 (string-match initial-input x))
1291 candidates))))
1292 (when matcher
1293 (setq candidates (funcall matcher "" candidates))))
1294 (or (cl-position preselect candidates :test #'equal)
1295 (and (stringp preselect)
1296 (let ((re (regexp-quote preselect)))
1297 (cl-position-if
1298 (lambda (x)
1299 (string-match re x))
1300 candidates)))))
1301
1302 ;;* Implementation
1303 ;;** Regex
1304 (defvar ivy--regex-hash
1305 (make-hash-table :test #'equal)
1306 "Store pre-computed regex.")
1307
1308 (defun ivy--split (str)
1309 "Split STR into a list by single spaces.
1310 The remaining spaces stick to their left.
1311 This allows to \"quote\" N spaces by inputting N+1 spaces."
1312 (let ((len (length str))
1313 start0
1314 (start1 0)
1315 res s
1316 match-len)
1317 (while (and (string-match " +" str start1)
1318 (< start1 len))
1319 (setq match-len (- (match-end 0) (match-beginning 0)))
1320 (if (= match-len 1)
1321 (progn
1322 (when start0
1323 (setq start1 start0)
1324 (setq start0 nil))
1325 (push (substring str start1 (match-beginning 0)) res)
1326 (setq start1 (match-end 0)))
1327 (setq str (replace-match
1328 (make-string (1- match-len) ?\ )
1329 nil nil str))
1330 (setq start0 (or start0 start1))
1331 (setq start1 (1- (match-end 0)))))
1332 (if start0
1333 (push (substring str start0) res)
1334 (setq s (substring str start1))
1335 (unless (= (length s) 0)
1336 (push s res)))
1337 (nreverse res)))
1338
1339 (defun ivy--regex (str &optional greedy)
1340 "Re-build regex from STR in case it has a space.
1341 When GREEDY is non-nil, join words in a greedy way."
1342 (let ((hashed (unless greedy
1343 (gethash str ivy--regex-hash))))
1344 (if hashed
1345 (prog1 (cdr hashed)
1346 (setq ivy--subexps (car hashed)))
1347 (when (string-match "\\([^\\]\\|^\\)\\\\$" str)
1348 (setq str (substring str 0 -1)))
1349 (cdr (puthash str
1350 (let ((subs (ivy--split str)))
1351 (if (= (length subs) 1)
1352 (cons
1353 (setq ivy--subexps 0)
1354 (car subs))
1355 (cons
1356 (setq ivy--subexps (length subs))
1357 (mapconcat
1358 (lambda (x)
1359 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1360 x
1361 (format "\\(%s\\)" x)))
1362 subs
1363 (if greedy
1364 ".*"
1365 ".*?")))))
1366 ivy--regex-hash)))))
1367
1368 (defun ivy--regex-ignore-order (str)
1369 "Re-build regex from STR by splitting it on spaces.
1370 Ignore the order of each group."
1371 (let* ((subs (split-string str " +" t))
1372 (len (length subs)))
1373 (cl-case len
1374 (1
1375 (setq ivy--subexps 0)
1376 (car subs))
1377 (t
1378 (setq ivy--subexps len)
1379 (let ((all (mapconcat #'identity subs "\\|")))
1380 (mapconcat
1381 (lambda (x)
1382 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1383 x
1384 (format "\\(%s\\)" x)))
1385 (make-list len all)
1386 ".*?"))))))
1387
1388 (defun ivy--regex-plus (str)
1389 "Build a regex sequence from STR.
1390 Spaces are wild, everything before \"!\" should match.
1391 Everything after \"!\" should not match."
1392 (let ((parts (split-string str "!" t)))
1393 (cl-case (length parts)
1394 (0
1395 "")
1396 (1
1397 (ivy--regex (car parts)))
1398 (2
1399 (let ((res
1400 (mapcar #'list
1401 (split-string (cadr parts) " " t))))
1402 (cons (cons (ivy--regex (car parts)) t)
1403 res)))
1404 (t (error "Unexpected: use only one !")))))
1405
1406 (defun ivy--regex-fuzzy (str)
1407 "Build a regex sequence from STR.
1408 Insert .* between each char."
1409 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1410 (prog1
1411 (concat (match-string 1 str)
1412 (mapconcat
1413 (lambda (x)
1414 (format "\\(%c\\)" x))
1415 (string-to-list (match-string 2 str)) ".*")
1416 (match-string 3 str))
1417 (setq ivy--subexps (length (match-string 2 str))))
1418 str))
1419
1420 ;;** Rest
1421 (defun ivy--minibuffer-setup ()
1422 "Setup ivy completion in the minibuffer."
1423 (set (make-local-variable 'completion-show-inline-help) nil)
1424 (set (make-local-variable 'minibuffer-default-add-function)
1425 (lambda ()
1426 (list ivy--default)))
1427 (when (display-graphic-p)
1428 (setq truncate-lines t))
1429 (setq-local max-mini-window-height ivy-height)
1430 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1431 ;; show completions with empty input
1432 (ivy--exhibit))
1433
1434 (defun ivy--input ()
1435 "Return the current minibuffer input."
1436 ;; assume one-line minibuffer input
1437 (buffer-substring-no-properties
1438 (minibuffer-prompt-end)
1439 (line-end-position)))
1440
1441 (defun ivy--cleanup ()
1442 "Delete the displayed completion candidates."
1443 (save-excursion
1444 (goto-char (minibuffer-prompt-end))
1445 (delete-region (line-end-position) (point-max))))
1446
1447 (defun ivy--insert-prompt ()
1448 "Update the prompt according to `ivy--prompt'."
1449 (when ivy--prompt
1450 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1451 counsel-find-symbol))
1452 (setq ivy--prompt-extra ""))
1453 (let (head tail)
1454 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1455 (progn
1456 (setq head (match-string 1 ivy--prompt))
1457 (setq tail ": "))
1458 (setq head (substring ivy--prompt 0 -1))
1459 (setq tail " "))
1460 (let ((inhibit-read-only t)
1461 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1462 (n-str
1463 (concat
1464 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1465 (> (minibuffer-depth) 1))
1466 (format "[%d] " (minibuffer-depth))
1467 "")
1468 (concat
1469 (if (string-match "%d.*%d" ivy-count-format)
1470 (format head
1471 (1+ ivy--index)
1472 (or (and (ivy-state-dynamic-collection ivy-last)
1473 ivy--full-length)
1474 ivy--length))
1475 (format head
1476 (or (and (ivy-state-dynamic-collection ivy-last)
1477 ivy--full-length)
1478 ivy--length)))
1479 ivy--prompt-extra
1480 tail)))
1481 (d-str (if ivy--directory
1482 (abbreviate-file-name ivy--directory)
1483 "")))
1484 (save-excursion
1485 (goto-char (point-min))
1486 (delete-region (point-min) (minibuffer-prompt-end))
1487 (if (> (+ (mod (+ (length n-str) (length d-str)) (window-width))
1488 (length ivy-text))
1489 (window-width))
1490 (setq n-str (concat n-str "\n" d-str))
1491 (setq n-str (concat n-str d-str)))
1492 (let ((regex (format "\\([^\n]\\{%d\\}\\)[^\n]" (window-width))))
1493 (while (string-match regex n-str)
1494 (setq n-str (replace-match (concat (match-string 1 n-str) "\n") nil t n-str 1))))
1495 (set-text-properties 0 (length n-str)
1496 `(face minibuffer-prompt ,@std-props)
1497 n-str)
1498 (ivy--set-match-props n-str "confirm"
1499 `(face ivy-confirm-face ,@std-props))
1500 (ivy--set-match-props n-str "match required"
1501 `(face ivy-match-required-face ,@std-props))
1502 (insert n-str))
1503 ;; get out of the prompt area
1504 (constrain-to-field nil (point-max))))))
1505
1506 (defun ivy--set-match-props (str match props)
1507 "Set STR text proprties that match MATCH to PROPS."
1508 (when (string-match match str)
1509 (set-text-properties
1510 (match-beginning 0)
1511 (match-end 0)
1512 props
1513 str)))
1514
1515 (defvar inhibit-message)
1516
1517 (defun ivy--sort-maybe (collection)
1518 "Sort COLLECTION if needed."
1519 (let ((sort (ivy-state-sort ivy-last))
1520 entry)
1521 (if (null sort)
1522 collection
1523 (let ((sort-fn (cond ((functionp sort)
1524 sort)
1525 ((setq entry (assoc (ivy-state-collection ivy-last)
1526 ivy-sort-functions-alist))
1527 (cdr entry))
1528 (t
1529 (cdr (assoc t ivy-sort-functions-alist))))))
1530 (if (functionp sort-fn)
1531 (cl-sort (copy-sequence collection) sort-fn)
1532 collection)))))
1533
1534 (defun ivy--exhibit ()
1535 "Insert Ivy completions display.
1536 Should be run via minibuffer `post-command-hook'."
1537 (when (memq 'ivy--exhibit post-command-hook)
1538 (let ((inhibit-field-text-motion nil))
1539 (constrain-to-field nil (point-max)))
1540 (setq ivy-text (ivy--input))
1541 (if (ivy-state-dynamic-collection ivy-last)
1542 ;; while-no-input would cause annoying
1543 ;; "Waiting for process to die...done" message interruptions
1544 (let ((inhibit-message t))
1545 (unless (equal ivy--old-text ivy-text)
1546 (while-no-input
1547 (setq ivy--all-candidates
1548 (ivy--sort-maybe
1549 (funcall (ivy-state-collection ivy-last) ivy-text)))
1550 (setq ivy--old-text ivy-text)))
1551 (when ivy--all-candidates
1552 (ivy--insert-minibuffer
1553 (ivy--format ivy--all-candidates))))
1554 (cond (ivy--directory
1555 (if (string-match "/\\'" ivy-text)
1556 (if (member ivy-text ivy--all-candidates)
1557 (ivy--cd (expand-file-name ivy-text ivy--directory))
1558 (when (string-match "//\\'" ivy-text)
1559 (if (and default-directory
1560 (string-match "\\`[[:alpha:]]:/" default-directory))
1561 (ivy--cd (match-string 0 default-directory))
1562 (ivy--cd "/")))
1563 (when (string-match "[[:alpha:]]:/$" ivy-text)
1564 (let ((drive-root (match-string 0 ivy-text)))
1565 (when (file-exists-p drive-root)
1566 (ivy--cd drive-root)))))
1567 (if (string-match "\\`~\\'" ivy-text)
1568 (ivy--cd (expand-file-name "~/")))))
1569 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1570 (when (or (and (string-match "\\` " ivy-text)
1571 (not (string-match "\\` " ivy--old-text)))
1572 (and (string-match "\\` " ivy--old-text)
1573 (not (string-match "\\` " ivy-text))))
1574 (setq ivy--all-candidates
1575 (if (and (> (length ivy-text) 0)
1576 (eq (aref ivy-text 0)
1577 ?\ ))
1578 (ivy--buffer-list " ")
1579 (ivy--buffer-list "" ivy-use-virtual-buffers)))
1580 (setq ivy--old-re nil))))
1581 (ivy--insert-minibuffer
1582 (ivy--format
1583 (ivy--filter ivy-text ivy--all-candidates)))
1584 (setq ivy--old-text ivy-text))))
1585
1586 (defun ivy--insert-minibuffer (text)
1587 "Insert TEXT into minibuffer with appropriate cleanup."
1588 (let ((resize-mini-windows nil)
1589 (update-fn (ivy-state-update-fn ivy-last))
1590 deactivate-mark)
1591 (ivy--cleanup)
1592 (when update-fn
1593 (funcall update-fn))
1594 (ivy--insert-prompt)
1595 ;; Do nothing if while-no-input was aborted.
1596 (when (stringp text)
1597 (let ((buffer-undo-list t))
1598 (save-excursion
1599 (forward-line 1)
1600 (insert text))))
1601 (when (display-graphic-p)
1602 (ivy--resize-minibuffer-to-fit))))
1603
1604 (defun ivy--resize-minibuffer-to-fit ()
1605 "Resize the minibuffer window so it has enough space to display
1606 all of the text contained in the minibuffer."
1607 (with-selected-window (minibuffer-window)
1608 (if (fboundp 'window-text-pixel-size)
1609 (let ((text-height (cdr (window-text-pixel-size)))
1610 (body-height (window-body-height nil t)))
1611 (when (> text-height body-height)
1612 (window-resize nil (- text-height body-height) nil t t)))
1613 (let ((text-height (count-screen-lines))
1614 (body-height (window-body-height)))
1615 (when (> text-height body-height)
1616 (window-resize nil (- text-height body-height) nil t))))))
1617
1618 (declare-function colir-blend-face-background "ext:colir")
1619
1620 (defun ivy--add-face (str face)
1621 "Propertize STR with FACE.
1622 `font-lock-append-text-property' is used, since it's better than
1623 `propertize' or `add-face-text-property' in this case."
1624 (require 'colir)
1625 (condition-case nil
1626 (progn
1627 (colir-blend-face-background 0 (length str) face str)
1628 (let ((foreground (face-foreground face)))
1629 (when foreground
1630 (add-face-text-property
1631 0 (length str)
1632 `(:foreground ,foreground)
1633 nil
1634 str))))
1635 (error
1636 (ignore-errors
1637 (font-lock-append-text-property 0 (length str) 'face face str))))
1638 str)
1639
1640 (declare-function flx-make-string-cache "ext:flx")
1641 (declare-function flx-score "ext:flx")
1642
1643 (defvar ivy--flx-cache nil)
1644
1645 (eval-after-load 'flx
1646 '(setq ivy--flx-cache (flx-make-string-cache)))
1647
1648 (defun ivy-toggle-case-fold ()
1649 "Toggle the case folding between nil and auto.
1650 In any completion session, the case folding starts in auto:
1651
1652 - when the input is all lower case, `case-fold-search' is t
1653 - otherwise it's nil.
1654
1655 You can toggle this to make `case-fold-search' nil regardless of input."
1656 (interactive)
1657 (setq ivy-case-fold-search
1658 (if ivy-case-fold-search
1659 nil
1660 'auto))
1661 ;; reset cache so that the candidate list updates
1662 (setq ivy--old-re nil))
1663
1664 (defun ivy--filter (name candidates)
1665 "Return all items that match NAME in CANDIDATES.
1666 CANDIDATES are assumed to be static."
1667 (let ((re (funcall ivy--regex-function name)))
1668 (if (and (equal re ivy--old-re)
1669 ivy--old-cands)
1670 ;; quick caching for "C-n", "C-p" etc.
1671 ivy--old-cands
1672 (let* ((re-str (if (listp re) (caar re) re))
1673 (matcher (ivy-state-matcher ivy-last))
1674 (case-fold-search
1675 (and ivy-case-fold-search
1676 (string= name (downcase name))))
1677 (cands (cond
1678 (matcher
1679 (funcall matcher re candidates))
1680 ((and ivy--old-re
1681 (stringp re)
1682 (stringp ivy--old-re)
1683 (not (string-match "\\\\" ivy--old-re))
1684 (not (equal ivy--old-re ""))
1685 (memq (cl-search
1686 (if (string-match "\\\\)\\'" ivy--old-re)
1687 (substring ivy--old-re 0 -2)
1688 ivy--old-re)
1689 re)
1690 '(0 2)))
1691 (ignore-errors
1692 (cl-remove-if-not
1693 (lambda (x) (string-match re x))
1694 ivy--old-cands)))
1695 (t
1696 (let ((re-list (if (stringp re) (list (cons re t)) re))
1697 (res candidates))
1698 (dolist (re re-list)
1699 (setq res
1700 (ignore-errors
1701 (funcall
1702 (if (cdr re)
1703 #'cl-remove-if-not
1704 #'cl-remove-if)
1705 (let ((re-str (car re)))
1706 (lambda (x) (string-match re-str x)))
1707 res))))
1708 res)))))
1709 (ivy--recompute-index name re-str cands)
1710 (setq ivy--old-re (if cands re-str ""))
1711 (when (and (require 'flx nil 'noerror)
1712 (eq ivy--regex-function 'ivy--regex-fuzzy))
1713 (setq cands (ivy--flx-sort name cands)))
1714 (setq ivy--old-cands cands)))))
1715
1716 (defun ivy--recompute-index (name re-str cands)
1717 (let* ((caller (ivy-state-caller ivy-last))
1718 (func (or (and caller (cdr (assoc caller ivy-index-functions-alist)))
1719 (cdr (assoc t ivy-index-functions-alist))
1720 #'ivy-recompute-index-zero)))
1721 (unless (eq this-command 'ivy-resume)
1722 (setq ivy--index
1723 (or
1724 (cl-position (if (and (> (length re-str) 0)
1725 (eq ?^ (aref re-str 0)))
1726 (substring re-str 1)
1727 re-str) cands
1728 :test #'equal)
1729 (and ivy--directory
1730 (cl-position
1731 (concat re-str "/") cands
1732 :test #'equal))
1733 (and (not (string= name ""))
1734 (not (and (require 'flx nil 'noerror)
1735 (eq ivy--regex-function 'ivy--regex-fuzzy)
1736 (< (length cands) 200)))
1737
1738 (cl-position (nth ivy--index ivy--old-cands)
1739 cands))
1740 (funcall func re-str cands))))
1741 (when (and (or (string= name "")
1742 (string= name "^"))
1743 (not (equal ivy--old-re "")))
1744 (setq ivy--index
1745 (or (ivy--preselect-index
1746 cands
1747 nil
1748 (ivy-state-preselect ivy-last)
1749 nil)
1750 ivy--index)))))
1751
1752 (defun ivy-recompute-index-swiper (_re-str cands)
1753 (let ((tail (nthcdr ivy--index ivy--old-cands))
1754 idx)
1755 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
1756 (progn
1757 (while (and tail (null idx))
1758 ;; Compare with eq to handle equal duplicates in cands
1759 (setq idx (cl-position (pop tail) cands)))
1760 (or idx 0))
1761 ivy--index)))
1762
1763 (defun ivy-recompute-index-zero (_re-str _cands)
1764 0)
1765
1766 (defun ivy--flx-sort (name cands)
1767 "Sort according to closeness to string NAME the string list CANDS."
1768 (condition-case nil
1769 (if (and cands
1770 (< (length cands) 200))
1771 (let* ((flx-name (if (string-match "^\\^" name)
1772 (substring name 1)
1773 name))
1774 (cands-with-score
1775 (delq nil
1776 (mapcar
1777 (lambda (x)
1778 (let ((score (car (flx-score x flx-name ivy--flx-cache))))
1779 (and score
1780 (cons score x))))
1781 cands))))
1782 (if cands-with-score
1783 (mapcar #'cdr
1784 (sort cands-with-score
1785 (lambda (x y)
1786 (> (car x) (car y)))))
1787 cands))
1788 cands)
1789 (error
1790 cands)))
1791
1792 (defvar ivy-format-function 'ivy-format-function-default
1793 "Function to transform the list of candidates into a string.
1794 This string will be inserted into the minibuffer.")
1795
1796 (defun ivy-format-function-default (cands)
1797 "Transform CANDS into a string for minibuffer."
1798 (if (bound-and-true-p truncate-lines)
1799 (mapconcat #'identity cands "\n")
1800 (let ((ww (- (window-width)
1801 (if (and (boundp 'fringe-mode) (eq fringe-mode 0)) 1 0))))
1802 (mapconcat
1803 (if truncate-lines
1804 (lambda (s)
1805 (if (> (length s) ww)
1806 (concat (substring s 0 (- ww 3)) "...")
1807 s))
1808 #'identity)
1809 cands "\n"))))
1810
1811 (defun ivy-format-function-arrow (cands)
1812 "Transform CANDS into a string for minibuffer."
1813 (let ((i -1))
1814 (mapconcat
1815 (lambda (s)
1816 (concat (if (eq (cl-incf i) ivy--index)
1817 "> "
1818 " ")
1819 s))
1820 cands "\n")))
1821
1822 (defface ivy-minibuffer-match-face-1
1823 '((((class color) (background light))
1824 :background "#d3d3d3")
1825 (((class color) (background dark))
1826 :background "#555555"))
1827 "The background face for `ivy' minibuffer matches.")
1828
1829 (defface ivy-minibuffer-match-face-2
1830 '((((class color) (background light))
1831 :background "#e99ce8" :weight bold)
1832 (((class color) (background dark))
1833 :background "#777777" :weight bold))
1834 "Face for `ivy' minibuffer matches modulo 1.")
1835
1836 (defface ivy-minibuffer-match-face-3
1837 '((((class color) (background light))
1838 :background "#bbbbff" :weight bold)
1839 (((class color) (background dark))
1840 :background "#7777ff" :weight bold))
1841 "Face for `ivy' minibuffer matches modulo 2.")
1842
1843 (defface ivy-minibuffer-match-face-4
1844 '((((class color) (background light))
1845 :background "#ffbbff" :weight bold)
1846 (((class color) (background dark))
1847 :background "#8a498a" :weight bold))
1848 "Face for `ivy' minibuffer matches modulo 3.")
1849
1850 (defcustom ivy-minibuffer-faces
1851 '(ivy-minibuffer-match-face-1
1852 ivy-minibuffer-match-face-2
1853 ivy-minibuffer-match-face-3
1854 ivy-minibuffer-match-face-4)
1855 "List of `ivy' faces for minibuffer group matches.")
1856
1857 (defun ivy--format-minibuffer-line (str)
1858 (let ((start 0)
1859 (str (copy-sequence str)))
1860 (when (eq ivy-display-style 'fancy)
1861 (unless ivy--old-re
1862 (setq ivy--old-re (funcall ivy--regex-function ivy-text)))
1863 (while (and (string-match ivy--old-re str start)
1864 (> (- (match-end 0) (match-beginning 0)) 0))
1865 (setq start (match-end 0))
1866 (let ((i 0))
1867 (while (<= i ivy--subexps)
1868 (let ((face
1869 (cond ((zerop ivy--subexps)
1870 (cadr ivy-minibuffer-faces))
1871 ((zerop i)
1872 (car ivy-minibuffer-faces))
1873 (t
1874 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
1875 ivy-minibuffer-faces)))))
1876 (if (fboundp 'add-face-text-property)
1877 (add-face-text-property
1878 (match-beginning i)
1879 (match-end i)
1880 face
1881 nil
1882 str)
1883 (font-lock-append-text-property
1884 (match-beginning i)
1885 (match-end i)
1886 'face
1887 face
1888 str)))
1889 (cl-incf i)))))
1890 str))
1891
1892 (defun ivy--format (cands)
1893 "Return a string for CANDS suitable for display in the minibuffer.
1894 CANDS is a list of strings."
1895 (setq ivy--length (length cands))
1896 (when (>= ivy--index ivy--length)
1897 (setq ivy--index (max (1- ivy--length) 0)))
1898 (if (null cands)
1899 (setq ivy--current "")
1900 (let* ((half-height (/ ivy-height 2))
1901 (start (max 0 (- ivy--index half-height)))
1902 (end (min (+ start (1- ivy-height)) ivy--length))
1903 (start (max 0 (min start (- end (1- ivy-height)))))
1904 (cands (cl-subseq cands start end))
1905 (index (- ivy--index start)))
1906 (cond (ivy--directory
1907 (setq cands (mapcar (lambda (x)
1908 (if (string-match-p "/\\'" x)
1909 (propertize x 'face 'ivy-subdir)
1910 x))
1911 cands)))
1912 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1913 (setq cands (mapcar (lambda (x)
1914 (let ((b (get-buffer x)))
1915 (if (and b
1916 (buffer-file-name b)
1917 (buffer-modified-p b))
1918 (propertize x 'face 'ivy-modified-buffer)
1919 x)))
1920 cands))))
1921 (setq ivy--current (copy-sequence (nth index cands)))
1922 (setq cands (mapcar
1923 #'ivy--format-minibuffer-line
1924 cands))
1925 (setf (nth index cands)
1926 (ivy--add-face (nth index cands) 'ivy-current-match))
1927 (let* ((ivy--index index)
1928 (res (concat "\n" (funcall ivy-format-function cands))))
1929 (put-text-property 0 (length res) 'read-only nil res)
1930 res))))
1931
1932 (defvar ivy--virtual-buffers nil
1933 "Store the virtual buffers alist.")
1934
1935 (defvar recentf-list)
1936
1937 (defface ivy-virtual '((t :inherit font-lock-builtin-face))
1938 "Face used by Ivy for matching virtual buffer names.")
1939
1940 (defcustom ivy-virtual-abbreviate 'name
1941 "The mode of abbreviation for virtual buffer names."
1942 :type '(choice
1943 (const :tag "Only name" name)
1944 (const :tag "Full path" full)
1945 ;; eventually, uniquify
1946 ))
1947
1948 (defun ivy--virtual-buffers ()
1949 "Adapted from `ido-add-virtual-buffers-to-list'."
1950 (unless recentf-mode
1951 (recentf-mode 1))
1952 (let ((bookmarks (and (boundp 'bookmark-alist)
1953 bookmark-alist))
1954 virtual-buffers name)
1955 (dolist (head (append
1956 recentf-list
1957 (delete " - no file -"
1958 (delq nil (mapcar (lambda (bookmark)
1959 (cdr (assoc 'filename bookmark)))
1960 bookmarks)))))
1961 (setq name
1962 (if (eq ivy-virtual-abbreviate 'name)
1963 (file-name-nondirectory head)
1964 (expand-file-name head)))
1965 (when (equal name "")
1966 (setq name (file-name-nondirectory (directory-file-name head))))
1967 (when (equal name "")
1968 (setq name head))
1969 (and (not (equal name ""))
1970 (null (get-file-buffer head))
1971 (not (assoc name virtual-buffers))
1972 (push (cons name head) virtual-buffers)))
1973 (when virtual-buffers
1974 (dolist (comp virtual-buffers)
1975 (put-text-property 0 (length (car comp))
1976 'face 'ivy-virtual
1977 (car comp)))
1978 (setq ivy--virtual-buffers (nreverse virtual-buffers))
1979 (mapcar #'car ivy--virtual-buffers))))
1980
1981 (defun ivy--buffer-list (str &optional virtual)
1982 "Return the buffers that match STR.
1983 When VIRTUAL is non-nil, add virtual buffers."
1984 (delete-dups
1985 (append
1986 (mapcar
1987 (lambda (x)
1988 (if (with-current-buffer x
1989 (file-remote-p
1990 (abbreviate-file-name default-directory)))
1991 (propertize x 'face 'ivy-remote)
1992 x))
1993 (all-completions str 'internal-complete-buffer))
1994 (and virtual
1995 (ivy--virtual-buffers)))))
1996
1997 (defun ivy--switch-buffer-action (buffer)
1998 "Switch to BUFFER.
1999 BUFFER may be a string or nil."
2000 (with-ivy-window
2001 (if (zerop (length buffer))
2002 (switch-to-buffer
2003 ivy-text nil 'force-same-window)
2004 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2005 (if (and virtual
2006 (not (get-buffer buffer)))
2007 (find-file (cdr virtual))
2008 (switch-to-buffer
2009 buffer nil 'force-same-window))))))
2010
2011 (defun ivy--switch-buffer-other-window-action (buffer)
2012 "Switch to BUFFER in other window.
2013 BUFFER may be a string or nil."
2014 (if (zerop (length buffer))
2015 (switch-to-buffer-other-window ivy-text)
2016 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2017 (if (and virtual
2018 (not (get-buffer buffer)))
2019 (find-file-other-window (cdr virtual))
2020 (switch-to-buffer-other-window buffer)))))
2021
2022 (defun ivy--rename-buffer-action (buffer)
2023 "Rename BUFFER."
2024 (let ((new-name (read-string "Rename buffer (to new name): ")))
2025 (with-current-buffer buffer
2026 (rename-buffer new-name))))
2027
2028 (defvar ivy-switch-buffer-map (make-sparse-keymap))
2029
2030 (ivy-set-actions
2031 'ivy-switch-buffer
2032 '(("k"
2033 (lambda (x)
2034 (kill-buffer x)
2035 (ivy--reset-state ivy-last))
2036 "kill")
2037 ("j"
2038 ivy--switch-buffer-other-window-action
2039 "other")
2040 ("r"
2041 ivy--rename-buffer-action
2042 "rename")))
2043
2044 ;;;###autoload
2045 (defun ivy-switch-buffer ()
2046 "Switch to another buffer."
2047 (interactive)
2048 (if (not ivy-mode)
2049 (call-interactively 'switch-to-buffer)
2050 (let ((this-command 'ivy-switch-buffer))
2051 (ivy-read "Switch to buffer: " 'internal-complete-buffer
2052 :preselect (buffer-name (other-buffer (current-buffer)))
2053 :action #'ivy--switch-buffer-action
2054 :keymap ivy-switch-buffer-map))))
2055
2056 ;;;###autoload
2057 (defun ivy-recentf ()
2058 "Find a file on `recentf-list'."
2059 (interactive)
2060 (ivy-read "Recentf: " recentf-list
2061 :action
2062 (lambda (f)
2063 (with-ivy-window
2064 (find-file f)))))
2065
2066 (defun ivy-yank-word ()
2067 "Pull next word from buffer into search string."
2068 (interactive)
2069 (let (amend)
2070 (with-ivy-window
2071 (let ((pt (point))
2072 (le (line-end-position)))
2073 (forward-word 1)
2074 (if (> (point) le)
2075 (goto-char pt)
2076 (setq amend (buffer-substring-no-properties pt (point))))))
2077 (when amend
2078 (insert (replace-regexp-in-string " +" " " amend)))))
2079
2080 (defun ivy-kill-ring-save ()
2081 "Store the current candidates into the kill ring.
2082 If the region is active, forward to `kill-ring-save' instead."
2083 (interactive)
2084 (if (region-active-p)
2085 (call-interactively 'kill-ring-save)
2086 (kill-new
2087 (mapconcat
2088 #'identity
2089 ivy--old-cands
2090 "\n"))))
2091
2092 (defun ivy-insert-current ()
2093 "Make the current candidate into current input.
2094 Don't finish completion."
2095 (interactive)
2096 (delete-minibuffer-contents)
2097 (if (and ivy--directory
2098 (string-match "/$" ivy--current))
2099 (insert (substring ivy--current 0 -1))
2100 (insert ivy--current)))
2101
2102 (defun ivy-toggle-fuzzy ()
2103 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
2104 (interactive)
2105 (setq ivy--old-re nil)
2106 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
2107 (setq ivy--regex-function 'ivy--regex-plus)
2108 (setq ivy--regex-function 'ivy--regex-fuzzy)))
2109
2110 (defun ivy-reverse-i-search ()
2111 "Enter a recursive `ivy-read' session using the current history.
2112 The selected history element will be inserted into the minibufer."
2113 (interactive)
2114 (let ((enable-recursive-minibuffers t)
2115 (history (symbol-value (ivy-state-history ivy-last)))
2116 (old-last ivy-last))
2117 (ivy-read "Reverse-i-search: "
2118 history
2119 :action (lambda (x)
2120 (ivy--reset-state
2121 (setq ivy-last old-last))
2122 (delete-minibuffer-contents)
2123 (insert (substring-no-properties x))
2124 (ivy--cd-maybe)))))
2125
2126 (defun ivy-restrict-to-matches ()
2127 "Restrict candidates to current matches and erase input."
2128 (interactive)
2129 (delete-minibuffer-contents)
2130 (setq ivy--all-candidates
2131 (ivy--filter ivy-text ivy--all-candidates)))
2132
2133 ;;* Occur
2134 (defvar-local ivy-occur-last nil
2135 "Buffer-local value of `ivy-last'.
2136 Can't re-use `ivy-last' because using e.g. `swiper' in the same
2137 buffer would modify `ivy-last'.")
2138
2139 (defvar ivy-occur-mode-map
2140 (let ((map (make-sparse-keymap)))
2141 (define-key map [mouse-1] 'ivy-occur-click)
2142 (define-key map (kbd "RET") 'ivy-occur-press)
2143 (define-key map (kbd "j") 'next-line)
2144 (define-key map (kbd "k") 'previous-line)
2145 (define-key map (kbd "h") 'backward-char)
2146 (define-key map (kbd "l") 'forward-char)
2147 (define-key map (kbd "g") 'ivy-occur-press)
2148 (define-key map (kbd "a") 'ivy-occur-read-action)
2149 (define-key map (kbd "o") 'ivy-occur-dispatch)
2150 (define-key map (kbd "q") 'quit-window)
2151 map)
2152 "Keymap for Ivy Occur mode.")
2153
2154 (define-derived-mode ivy-occur-mode fundamental-mode "Ivy-Occur"
2155 "Major mode for output from \\[ivy-occur].
2156
2157 \\{ivy-occur-mode-map}")
2158
2159 (defvar ivy-occur-grep-mode-map
2160 (let ((map (copy-keymap ivy-occur-mode-map)))
2161 (define-key map (kbd "C-x C-q") 'ivy-wgrep-change-to-wgrep-mode)
2162 map)
2163 "Keymap for Ivy Occur Grep mode.")
2164
2165 (define-derived-mode ivy-occur-grep-mode grep-mode "Ivy-Occur"
2166 "Major mode for output from \\[ivy-occur].
2167
2168 \\{ivy-occur-grep-mode-map}")
2169
2170 (defun ivy-occur ()
2171 "Stop completion and put the current matches into a new buffer.
2172
2173 The new buffer will also remember the current action(s).
2174
2175 While in the *ivy-occur* buffer, selecting a cadidate with RET or
2176 a mouse click will call the appropriate action for that candidate.
2177
2178 It's possible to have an unlimited amount of *ivy-occur* buffers."
2179 (interactive)
2180 (let ((buffer
2181 (generate-new-buffer
2182 (format "*ivy-occur%s \"%s\"*"
2183 (let (caller)
2184 (if (setq caller (ivy-state-caller ivy-last))
2185 (concat " " (prin1-to-string caller))
2186 ""))
2187 ivy-text)))
2188 (do-grep (eq (ivy-state-caller ivy-last) 'counsel-git-grep)))
2189 (with-current-buffer buffer
2190 (if do-grep
2191 (progn
2192 (setq ivy--old-cands
2193 (split-string
2194 (shell-command-to-string
2195 (format counsel-git-grep-cmd ivy--old-re))
2196 "\n"
2197 t))
2198 (ivy-occur-grep-mode))
2199 (ivy-occur-mode))
2200 (setf (ivy-state-text ivy-last) ivy-text)
2201 (setq ivy-occur-last ivy-last)
2202 (setq-local ivy--directory ivy--directory)
2203 (let ((inhibit-read-only t))
2204 (erase-buffer)
2205 (when do-grep
2206 ;; Need precise number of header lines for `wgrep' to work.
2207 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
2208 default-directory)))
2209 (insert (format "%d candidates:\n" (length ivy--old-cands)))
2210 (dolist (cand ivy--old-cands)
2211 (let ((str (if do-grep
2212 (concat "./" cand)
2213 (concat " " cand))))
2214 (add-text-properties
2215 0 (length str)
2216 `(mouse-face
2217 highlight
2218 help-echo "mouse-1: call ivy-action")
2219 str)
2220 (insert str "\n")))))
2221 (ivy-exit-with-action
2222 `(lambda (_) (pop-to-buffer ,buffer)))))
2223
2224 (declare-function wgrep-change-to-wgrep-mode "ext:wgrep")
2225
2226 (defun ivy-wgrep-change-to-wgrep-mode ()
2227 "Forward to `wgrep-change-to-wgrep-mode'."
2228 (interactive)
2229 (if (require 'wgrep nil 'noerror)
2230 (wgrep-change-to-wgrep-mode)
2231 (error "Package wgrep isn't installed")))
2232
2233 (defun ivy-occur-read-action ()
2234 "Select one of the available actions as the current one."
2235 (interactive)
2236 (let ((ivy-last ivy-occur-last))
2237 (ivy-read-action)))
2238
2239 (defun ivy-occur-dispatch ()
2240 "Call one of the available actions on the current item."
2241 (interactive)
2242 (let* ((state-action (ivy-state-action ivy-occur-last))
2243 (actions (if (symbolp state-action)
2244 state-action
2245 (copy-sequence state-action))))
2246 (unwind-protect
2247 (progn
2248 (ivy-occur-read-action)
2249 (ivy-occur-press))
2250 (setf (ivy-state-action ivy-occur-last) actions))))
2251
2252 (defun ivy-occur-click (event)
2253 "Execute action for the current candidate.
2254 EVENT gives the mouse position."
2255 (interactive "e")
2256 (let ((window (posn-window (event-end event)))
2257 (pos (posn-point (event-end event))))
2258 (with-current-buffer (window-buffer window)
2259 (goto-char pos)
2260 (ivy-occur-press))))
2261
2262 (defun ivy-occur-press ()
2263 "Execute action for the current candidate."
2264 (interactive)
2265 (require 'pulse)
2266 (when (save-excursion
2267 (beginning-of-line)
2268 (looking-at "\\(?:./\\| \\)\\(.*\\)$"))
2269 (let* ((ivy-last ivy-occur-last)
2270 (ivy-text (ivy-state-text ivy-last))
2271 (str (buffer-substring
2272 (match-beginning 1)
2273 (match-end 1)))
2274 (coll (ivy-state-collection ivy-last))
2275 (action (ivy--get-action ivy-last))
2276 (ivy-exit 'done))
2277 (with-ivy-window
2278 (funcall action
2279 (if (and (consp coll)
2280 (consp (car coll)))
2281 (cdr (assoc str coll))
2282 str))
2283 (if (memq (ivy-state-caller ivy-last)
2284 '(swiper counsel-git-grep))
2285 (with-current-buffer (window-buffer (selected-window))
2286 (swiper--cleanup)
2287 (swiper--add-overlays
2288 (ivy--regex ivy-text)
2289 (line-beginning-position)
2290 (line-end-position)
2291 (selected-window))
2292 (run-at-time 0.5 nil 'swiper--cleanup))
2293 (pulse-momentary-highlight-one-line (point)))))))
2294
2295 (provide 'ivy)
2296
2297 ;;; ivy.el ends here