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