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