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