]> code.delx.au - gnu-emacs-elpa/blob - ivy.el
ff7b2b213200a192621d10ac7c60f15177b43c7f
[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 (window-minibuffer-p) 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 (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 initial-input
1203 ;; Needed for anchor to work
1204 (setq ivy--old-cands coll)
1205 (setq ivy--old-cands (ivy--filter initial-input coll)))
1206 (setq ivy--all-candidates coll)
1207 (setq ivy--index (or
1208 (and dynamic-collection
1209 ivy--index)
1210 (and preselect
1211 (ivy--preselect-index
1212 preselect
1213 (if initial-input
1214 ivy--old-cands
1215 coll)))
1216 0)))
1217 (setq ivy-exit nil)
1218 (setq ivy--default (or
1219 (thing-at-point 'url)
1220 (thing-at-point 'symbol)
1221 ""))
1222 (setq ivy--prompt
1223 (cond ((string-match "%.*d" prompt)
1224 prompt)
1225 ((null ivy-count-format)
1226 (error
1227 "`ivy-count-format' can't be nil. Set it to an empty string instead"))
1228 ((string-match "%d.*%d" ivy-count-format)
1229 (let ((w (length (number-to-string
1230 (length ivy--all-candidates))))
1231 (s (copy-sequence ivy-count-format)))
1232 (string-match "%d" s)
1233 (match-end 0)
1234 (string-match "%d" s (match-end 0))
1235 (setq s (replace-match (format "%%-%dd" w) nil nil s))
1236 (string-match "%d" s)
1237 (concat (replace-match (format "%%%dd" w) nil nil s)
1238 prompt)))
1239 ((string-match "%.*d" ivy-count-format)
1240 (concat ivy-count-format prompt))
1241 (ivy--directory
1242 prompt)
1243 (t
1244 nil)))
1245 (setf (ivy-state-initial-input ivy-last) initial-input)))
1246
1247 ;;;###autoload
1248 (defun ivy-completing-read (prompt collection
1249 &optional predicate require-match initial-input
1250 history def _inherit-input-method)
1251 "Read a string in the minibuffer, with completion.
1252
1253 This interface conforms to `completing-read' and can be used for
1254 `completing-read-function'.
1255
1256 PROMPT is a string to prompt with; normally it ends in a colon and a space.
1257 COLLECTION can be a list of strings, an alist, an obarray or a hash table.
1258 PREDICATE limits completion to a subset of COLLECTION.
1259 REQUIRE-MATCH is specified with a boolean value. See `completing-read'.
1260 INITIAL-INPUT is a string that can be inserted into the minibuffer initially.
1261 HISTORY is a list of previously selected inputs.
1262 DEF is the default value.
1263 _INHERIT-INPUT-METHOD is currently ignored."
1264
1265 ;; See the doc of `completing-read'.
1266 (when (consp history)
1267 (when (numberp (cdr history))
1268 (setq initial-input (nth (1- (cdr history))
1269 (symbol-value (car history)))))
1270 (setq history (car history)))
1271 (ivy-read (replace-regexp-in-string "%" "%%" prompt)
1272 collection
1273 :predicate predicate
1274 :require-match require-match
1275 :initial-input (if (consp initial-input)
1276 (car initial-input)
1277 (if (and (stringp initial-input)
1278 (string-match "\\+" initial-input))
1279 (replace-regexp-in-string
1280 "\\+" "\\\\+" initial-input)
1281 initial-input))
1282 :preselect (if (listp def) (car def) def)
1283 :history history
1284 :keymap nil
1285 :sort
1286 (let ((sort (assoc this-command ivy-sort-functions-alist)))
1287 (if sort
1288 (cdr sort)
1289 t))))
1290
1291 ;;;###autoload
1292 (define-minor-mode ivy-mode
1293 "Toggle Ivy mode on or off.
1294 Turn Ivy mode on if ARG is positive, off otherwise.
1295 Turning on Ivy mode sets `completing-read-function' to
1296 `ivy-completing-read'.
1297
1298 Global bindings:
1299 \\{ivy-mode-map}
1300
1301 Minibuffer bindings:
1302 \\{ivy-minibuffer-map}"
1303 :group 'ivy
1304 :global t
1305 :keymap ivy-mode-map
1306 :lighter " ivy"
1307 (if ivy-mode
1308 (setq completing-read-function 'ivy-completing-read)
1309 (setq completing-read-function 'completing-read-default)))
1310
1311 (defun ivy--preselect-index (preselect candidates)
1312 "Return the index of PRESELECT in CANDIDATES."
1313 (cond ((integerp preselect)
1314 preselect)
1315 ((cl-position preselect candidates :test #'equal))
1316 ((stringp preselect)
1317 (let ((re (regexp-quote preselect)))
1318 (cl-position-if
1319 (lambda (x)
1320 (string-match re x))
1321 candidates)))))
1322
1323 ;;* Implementation
1324 ;;** Regex
1325 (defvar ivy--regex-hash
1326 (make-hash-table :test #'equal)
1327 "Store pre-computed regex.")
1328
1329 (defun ivy--split (str)
1330 "Split STR into a list by single spaces.
1331 The remaining spaces stick to their left.
1332 This allows to \"quote\" N spaces by inputting N+1 spaces."
1333 (let ((len (length str))
1334 start0
1335 (start1 0)
1336 res s
1337 match-len)
1338 (while (and (string-match " +" str start1)
1339 (< start1 len))
1340 (setq match-len (- (match-end 0) (match-beginning 0)))
1341 (if (= match-len 1)
1342 (progn
1343 (when start0
1344 (setq start1 start0)
1345 (setq start0 nil))
1346 (push (substring str start1 (match-beginning 0)) res)
1347 (setq start1 (match-end 0)))
1348 (setq str (replace-match
1349 (make-string (1- match-len) ?\ )
1350 nil nil str))
1351 (setq start0 (or start0 start1))
1352 (setq start1 (1- (match-end 0)))))
1353 (if start0
1354 (push (substring str start0) res)
1355 (setq s (substring str start1))
1356 (unless (= (length s) 0)
1357 (push s res)))
1358 (nreverse res)))
1359
1360 (defun ivy--regex (str &optional greedy)
1361 "Re-build regex pattern from STR in case it has a space.
1362 When GREEDY is non-nil, join words in a greedy way."
1363 (let ((hashed (unless greedy
1364 (gethash str ivy--regex-hash))))
1365 (if hashed
1366 (prog1 (cdr hashed)
1367 (setq ivy--subexps (car hashed)))
1368 (when (string-match "\\([^\\]\\|^\\)\\\\$" str)
1369 (setq str (substring str 0 -1)))
1370 (cdr (puthash str
1371 (let ((subs (ivy--split str)))
1372 (if (= (length subs) 1)
1373 (cons
1374 (setq ivy--subexps 0)
1375 (car subs))
1376 (cons
1377 (setq ivy--subexps (length subs))
1378 (mapconcat
1379 (lambda (x)
1380 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1381 x
1382 (format "\\(%s\\)" x)))
1383 subs
1384 (if greedy
1385 ".*"
1386 ".*?")))))
1387 ivy--regex-hash)))))
1388
1389 (defun ivy--regex-ignore-order (str)
1390 "Re-build regex from STR by splitting at spaces.
1391 Ignore the order of each group.
1392
1393 ATTENTION: This is just a proof of concept and may not work as
1394 expected. Besides ignoring the order of the tokens where 'foo'
1395 and 'bar', 'bar' and 'foo' are matched, it also matches multiple
1396 occurrences of 'foo' and 'bar'. To ignore the sort order and avoid
1397 multiple matches, use `ivy-restrict-to-matches' instead.
1398 "
1399 (let* ((subs (split-string str " +" t))
1400 (len (length subs)))
1401 (cl-case len
1402 (1
1403 (setq ivy--subexps 0)
1404 (car subs))
1405 (t
1406 (setq ivy--subexps len)
1407 (let ((all (mapconcat #'identity subs "\\|")))
1408 (mapconcat
1409 (lambda (x)
1410 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1411 x
1412 (format "\\(%s\\)" x)))
1413 (make-list len all)
1414 ".*?"))))))
1415
1416 (defun ivy--regex-plus (str)
1417 "Build a regex sequence from STR.
1418 Spaces are wild card characters, everything before \"!\" should
1419 match. Everything after \"!\" should not match."
1420 (let ((parts (split-string str "!" t)))
1421 (cl-case (length parts)
1422 (0
1423 "")
1424 (1
1425 (ivy--regex (car parts)))
1426 (2
1427 (let ((res
1428 (mapcar #'list
1429 (split-string (cadr parts) " " t))))
1430 (cons (cons (ivy--regex (car parts)) t)
1431 res)))
1432 (t (error "Unexpected: use only one !")))))
1433
1434 (defun ivy--regex-fuzzy (str)
1435 "Build a regex sequence from STR.
1436 Insert .* between each char."
1437 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1438 (prog1
1439 (concat (match-string 1 str)
1440 (mapconcat
1441 (lambda (x)
1442 (format "\\(%c\\)" x))
1443 (string-to-list (match-string 2 str)) ".*")
1444 (match-string 3 str))
1445 (setq ivy--subexps (length (match-string 2 str))))
1446 str))
1447
1448 ;;** Rest
1449 (defun ivy--minibuffer-setup ()
1450 "Setup ivy completion in the minibuffer."
1451 (set (make-local-variable 'completion-show-inline-help) nil)
1452 (set (make-local-variable 'minibuffer-default-add-function)
1453 (lambda ()
1454 (list ivy--default)))
1455 (when (display-graphic-p)
1456 (setq truncate-lines t))
1457 (setq-local max-mini-window-height ivy-height)
1458 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1459 ;; show completions with empty input
1460 (ivy--exhibit))
1461
1462 (defun ivy--input ()
1463 "Return the current minibuffer input."
1464 ;; assume one-line minibuffer input
1465 (buffer-substring-no-properties
1466 (minibuffer-prompt-end)
1467 (line-end-position)))
1468
1469 (defun ivy--cleanup ()
1470 "Delete the displayed completion candidates."
1471 (save-excursion
1472 (goto-char (minibuffer-prompt-end))
1473 (delete-region (line-end-position) (point-max))))
1474
1475 (defun ivy--insert-prompt ()
1476 "Update the prompt according to `ivy--prompt'."
1477 (when ivy--prompt
1478 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1479 counsel-find-symbol))
1480 (setq ivy--prompt-extra ""))
1481 (let (head tail)
1482 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1483 (progn
1484 (setq head (match-string 1 ivy--prompt))
1485 (setq tail ": "))
1486 (setq head (substring ivy--prompt 0 -1))
1487 (setq tail " "))
1488 (let ((inhibit-read-only t)
1489 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1490 (n-str
1491 (concat
1492 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1493 (> (minibuffer-depth) 1))
1494 (format "[%d] " (minibuffer-depth))
1495 "")
1496 (concat
1497 (if (string-match "%d.*%d" ivy-count-format)
1498 (format head
1499 (1+ ivy--index)
1500 (or (and (ivy-state-dynamic-collection ivy-last)
1501 ivy--full-length)
1502 ivy--length))
1503 (format head
1504 (or (and (ivy-state-dynamic-collection ivy-last)
1505 ivy--full-length)
1506 ivy--length)))
1507 ivy--prompt-extra
1508 tail)))
1509 (d-str (if ivy--directory
1510 (abbreviate-file-name ivy--directory)
1511 "")))
1512 (save-excursion
1513 (goto-char (point-min))
1514 (delete-region (point-min) (minibuffer-prompt-end))
1515 (if (> (+ (mod (+ (length n-str) (length d-str)) (window-width))
1516 (length ivy-text))
1517 (window-width))
1518 (setq n-str (concat n-str "\n" d-str))
1519 (setq n-str (concat n-str d-str)))
1520 (let ((regex (format "\\([^\n]\\{%d\\}\\)[^\n]" (window-width))))
1521 (while (string-match regex n-str)
1522 (setq n-str (replace-match (concat (match-string 1 n-str) "\n") nil t n-str 1))))
1523 (set-text-properties 0 (length n-str)
1524 `(face minibuffer-prompt ,@std-props)
1525 n-str)
1526 (ivy--set-match-props n-str "confirm"
1527 `(face ivy-confirm-face ,@std-props))
1528 (ivy--set-match-props n-str "match required"
1529 `(face ivy-match-required-face ,@std-props))
1530 (insert n-str))
1531 ;; get out of the prompt area
1532 (constrain-to-field nil (point-max))))))
1533
1534 (defun ivy--set-match-props (str match props)
1535 "Set STR text properties that match MATCH to PROPS."
1536 (when (string-match match str)
1537 (set-text-properties
1538 (match-beginning 0)
1539 (match-end 0)
1540 props
1541 str)))
1542
1543 (defvar inhibit-message)
1544
1545 (defun ivy--sort-maybe (collection)
1546 "Sort COLLECTION if needed."
1547 (let ((sort (ivy-state-sort ivy-last))
1548 entry)
1549 (if (null sort)
1550 collection
1551 (let ((sort-fn (cond ((functionp sort)
1552 sort)
1553 ((setq entry (assoc (ivy-state-collection ivy-last)
1554 ivy-sort-functions-alist))
1555 (cdr entry))
1556 (t
1557 (cdr (assoc t ivy-sort-functions-alist))))))
1558 (if (functionp sort-fn)
1559 (cl-sort (copy-sequence collection) sort-fn)
1560 collection)))))
1561
1562 (defun ivy--exhibit ()
1563 "Insert Ivy completions display.
1564 Should be run via minibuffer `post-command-hook'."
1565 (when (memq 'ivy--exhibit post-command-hook)
1566 (let ((inhibit-field-text-motion nil))
1567 (constrain-to-field nil (point-max)))
1568 (setq ivy-text (ivy--input))
1569 (if (ivy-state-dynamic-collection ivy-last)
1570 ;; while-no-input would cause annoying
1571 ;; "Waiting for process to die...done" message interruptions
1572 (let ((inhibit-message t))
1573 (unless (equal ivy--old-text ivy-text)
1574 (while-no-input
1575 (setq ivy--all-candidates
1576 (ivy--sort-maybe
1577 (funcall (ivy-state-collection ivy-last) ivy-text)))
1578 (setq ivy--old-text ivy-text)))
1579 (when ivy--all-candidates
1580 (ivy--insert-minibuffer
1581 (ivy--format ivy--all-candidates))))
1582 (cond (ivy--directory
1583 (if (string-match "/\\'" ivy-text)
1584 (if (member ivy-text ivy--all-candidates)
1585 (ivy--cd (expand-file-name ivy-text ivy--directory))
1586 (when (string-match "//\\'" ivy-text)
1587 (if (and default-directory
1588 (string-match "\\`[[:alpha:]]:/" default-directory))
1589 (ivy--cd (match-string 0 default-directory))
1590 (ivy--cd "/")))
1591 (when (string-match "[[:alpha:]]:/$" ivy-text)
1592 (let ((drive-root (match-string 0 ivy-text)))
1593 (when (file-exists-p drive-root)
1594 (ivy--cd drive-root)))))
1595 (if (string-match "\\`~\\'" ivy-text)
1596 (ivy--cd (expand-file-name "~/")))))
1597 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1598 (when (or (and (string-match "\\` " ivy-text)
1599 (not (string-match "\\` " ivy--old-text)))
1600 (and (string-match "\\` " ivy--old-text)
1601 (not (string-match "\\` " ivy-text))))
1602 (setq ivy--all-candidates
1603 (if (and (> (length ivy-text) 0)
1604 (eq (aref ivy-text 0)
1605 ?\ ))
1606 (ivy--buffer-list " ")
1607 (ivy--buffer-list "" ivy-use-virtual-buffers)))
1608 (setq ivy--old-re nil))))
1609 (ivy--insert-minibuffer
1610 (with-current-buffer (ivy-state-buffer ivy-last)
1611 (ivy--format
1612 (ivy--filter ivy-text ivy--all-candidates))))
1613 (setq ivy--old-text ivy-text))))
1614
1615 (defun ivy--insert-minibuffer (text)
1616 "Insert TEXT into minibuffer with appropriate cleanup."
1617 (let ((resize-mini-windows nil)
1618 (update-fn (ivy-state-update-fn ivy-last))
1619 deactivate-mark)
1620 (ivy--cleanup)
1621 (when update-fn
1622 (funcall update-fn))
1623 (ivy--insert-prompt)
1624 ;; Do nothing if while-no-input was aborted.
1625 (when (stringp text)
1626 (let ((buffer-undo-list t))
1627 (save-excursion
1628 (forward-line 1)
1629 (insert text))))
1630 (when (display-graphic-p)
1631 (ivy--resize-minibuffer-to-fit))))
1632
1633 (defun ivy--resize-minibuffer-to-fit ()
1634 "Resize the minibuffer window size to fit the text in the minibuffer."
1635 (with-selected-window (minibuffer-window)
1636 (if (fboundp 'window-text-pixel-size)
1637 (let ((text-height (cdr (window-text-pixel-size)))
1638 (body-height (window-body-height nil t)))
1639 (when (> text-height body-height)
1640 (window-resize nil (- text-height body-height) nil t t)))
1641 (let ((text-height (count-screen-lines))
1642 (body-height (window-body-height)))
1643 (when (> text-height body-height)
1644 (window-resize nil (- text-height body-height) nil t))))))
1645
1646 (declare-function colir-blend-face-background "ext:colir")
1647
1648 (defun ivy--add-face (str face)
1649 "Propertize STR with FACE.
1650 `font-lock-append-text-property' is used, since it's better than
1651 `propertize' or `add-face-text-property' in this case."
1652 (require 'colir)
1653 (condition-case nil
1654 (progn
1655 (colir-blend-face-background 0 (length str) face str)
1656 (let ((foreground (face-foreground face)))
1657 (when foreground
1658 (add-face-text-property
1659 0 (length str)
1660 `(:foreground ,foreground)
1661 nil
1662 str))))
1663 (error
1664 (ignore-errors
1665 (font-lock-append-text-property 0 (length str) 'face face str))))
1666 str)
1667
1668 (declare-function flx-make-string-cache "ext:flx")
1669 (declare-function flx-score "ext:flx")
1670
1671 (defvar ivy--flx-cache nil)
1672
1673 (eval-after-load 'flx
1674 '(setq ivy--flx-cache (flx-make-string-cache)))
1675
1676 (defun ivy-toggle-case-fold ()
1677 "Toggle the case folding between nil and auto.
1678 In any completion session, the case folding starts in auto:
1679
1680 - when the input is all lower case, `case-fold-search' is t
1681 - otherwise nil.
1682
1683 You can toggle this to make `case-fold-search' nil regardless of input."
1684 (interactive)
1685 (setq ivy-case-fold-search
1686 (if ivy-case-fold-search
1687 nil
1688 'auto))
1689 ;; reset cache so that the candidate list updates
1690 (setq ivy--old-re nil))
1691
1692 (defun ivy--filter (name candidates)
1693 "Return all items that match NAME in CANDIDATES.
1694 CANDIDATES are assumed to be static."
1695 (let ((re (funcall ivy--regex-function name)))
1696 (if (and (equal re ivy--old-re)
1697 ivy--old-cands)
1698 ;; quick caching for "C-n", "C-p" etc.
1699 ivy--old-cands
1700 (let* ((re-str (if (listp re) (caar re) re))
1701 (matcher (ivy-state-matcher ivy-last))
1702 (case-fold-search
1703 (and ivy-case-fold-search
1704 (string= name (downcase name))))
1705 (cands (cond
1706 (matcher
1707 (funcall matcher re candidates))
1708 ((and ivy--old-re
1709 (stringp re)
1710 (stringp ivy--old-re)
1711 (not (string-match "\\\\" ivy--old-re))
1712 (not (equal ivy--old-re ""))
1713 (memq (cl-search
1714 (if (string-match "\\\\)\\'" ivy--old-re)
1715 (substring ivy--old-re 0 -2)
1716 ivy--old-re)
1717 re)
1718 '(0 2)))
1719 (ignore-errors
1720 (cl-remove-if-not
1721 (lambda (x) (string-match re x))
1722 ivy--old-cands)))
1723 (t
1724 (let ((re-list (if (stringp re) (list (cons re t)) re))
1725 (res candidates))
1726 (dolist (re re-list)
1727 (setq res
1728 (ignore-errors
1729 (funcall
1730 (if (cdr re)
1731 #'cl-remove-if-not
1732 #'cl-remove-if)
1733 (let ((re-str (car re)))
1734 (lambda (x) (string-match re-str x)))
1735 res))))
1736 res)))))
1737 (ivy--recompute-index name re-str cands)
1738 (setq ivy--old-re (if cands re-str ""))
1739 (setq ivy--old-cands (ivy--sort name cands))))))
1740
1741 (defcustom ivy-sort-matches-functions-alist '((t . nil))
1742 "An alist of functions used to sort the matching candidates.
1743
1744 This is different from `ivy-sort-functions-alist', which is used
1745 to sort the whole collection only once. The functions taken from
1746 here are instead used on each input change, but they are used
1747 only on already matching candidates, not on all of them.
1748
1749 The alist KEY is a collection function or t to match previously
1750 not matched collection functions.
1751
1752 The alist VAL is a sorting function with the signature of
1753 `ivy--prefix-sort'.")
1754
1755 (defun ivy--sort-files-by-date (_name candidates)
1756 "Re-soft CANDIDATES according to file modification date."
1757 (let ((default-directory ivy--directory))
1758 (cl-sort (copy-sequence candidates)
1759 (lambda (f1 f2)
1760 (time-less-p
1761 (nth 5 (file-attributes f2))
1762 (nth 5 (file-attributes f1)))))))
1763
1764 (defun ivy--sort (name candidates)
1765 "Re-sort CANDIDATES by NAME.
1766 All CANDIDATES are assumed to match NAME."
1767 (let ((key (or (ivy-state-caller ivy-last)
1768 (when (functionp (ivy-state-collection ivy-last))
1769 (ivy-state-collection ivy-last))))
1770 fun)
1771 (cond ((and (require 'flx nil 'noerror)
1772 (eq ivy--regex-function 'ivy--regex-fuzzy))
1773 (ivy--flx-sort name candidates))
1774 ((setq fun (cdr (or (assoc key ivy-sort-matches-functions-alist)
1775 (assoc t ivy-sort-matches-functions-alist))))
1776 (funcall fun name candidates))
1777 (t
1778 candidates))))
1779
1780 (defun ivy--prefix-sort (name candidates)
1781 "Re-sort CANDIDATES.
1782 Prefix matches to NAME are put ahead of the list."
1783 (if (or (string-match "^\\^" name) (string= name ""))
1784 candidates
1785 (let ((re-prefix (concat "^" (funcall ivy--regex-function name)))
1786 res-prefix
1787 res-noprefix)
1788 (dolist (s candidates)
1789 (if (string-match re-prefix s)
1790 (push s res-prefix)
1791 (push s res-noprefix)))
1792 (nconc
1793 (nreverse res-prefix)
1794 (nreverse res-noprefix)))))
1795
1796 (defun ivy--recompute-index (name re-str cands)
1797 (let* ((caller (ivy-state-caller ivy-last))
1798 (func (or (and caller (cdr (assoc caller ivy-index-functions-alist)))
1799 (cdr (assoc t ivy-index-functions-alist))
1800 #'ivy-recompute-index-zero)))
1801 (unless (eq this-command 'ivy-resume)
1802 (setq ivy--index
1803 (or
1804 (cl-position (if (and (> (length re-str) 0)
1805 (eq ?^ (aref re-str 0)))
1806 (substring re-str 1)
1807 re-str) cands
1808 :test #'equal)
1809 (and ivy--directory
1810 (cl-position
1811 (concat re-str "/") cands
1812 :test #'equal))
1813 (and (not (string= name ""))
1814 (not (and (require 'flx nil 'noerror)
1815 (eq ivy--regex-function 'ivy--regex-fuzzy)
1816 (< (length cands) 200)))
1817
1818 (cl-position (nth ivy--index ivy--old-cands)
1819 cands))
1820 (funcall func re-str cands))))
1821 (when (and (or (string= name "")
1822 (string= name "^"))
1823 (not (equal ivy--old-re "")))
1824 (setq ivy--index
1825 (or (ivy--preselect-index
1826 (ivy-state-preselect ivy-last)
1827 cands)
1828 ivy--index)))))
1829
1830 (defun ivy-recompute-index-swiper (_re-str cands)
1831 (let ((tail (nthcdr ivy--index ivy--old-cands))
1832 idx)
1833 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
1834 (progn
1835 (while (and tail (null idx))
1836 ;; Compare with eq to handle equal duplicates in cands
1837 (setq idx (cl-position (pop tail) cands)))
1838 (or idx 0))
1839 (if ivy--old-cands
1840 ivy--index
1841 ;; already in ivy-state-buffer
1842 (let ((n (line-number-at-pos))
1843 (res 0)
1844 (i 0))
1845 (dolist (c cands)
1846 (when (eq n (read (get-text-property 0 'display c)))
1847 (setq res i))
1848 (cl-incf i))
1849 res)))))
1850
1851 (defun ivy-recompute-index-swiper-async (_re-str cands)
1852 (let ((tail (nthcdr ivy--index ivy--old-cands))
1853 idx)
1854 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
1855 (progn
1856 (while (and tail (null idx))
1857 ;; Compare with `equal', since the collection is re-created
1858 ;; each time with `split-string'
1859 (setq idx (cl-position (pop tail) cands :test #'equal)))
1860 (or idx 0))
1861 ivy--index)))
1862
1863 (defun ivy-recompute-index-zero (_re-str _cands)
1864 0)
1865
1866 (defun ivy--flx-sort (name cands)
1867 "Sort according to closeness to string NAME the string list CANDS."
1868 (condition-case nil
1869 (if (and cands
1870 (< (length cands) 200))
1871 (let* ((flx-name (if (string-match "^\\^" name)
1872 (substring name 1)
1873 name))
1874 (cands-with-score
1875 (delq nil
1876 (mapcar
1877 (lambda (x)
1878 (let ((score (car (flx-score x flx-name ivy--flx-cache))))
1879 (and score
1880 (cons score x))))
1881 cands))))
1882 (if cands-with-score
1883 (mapcar #'cdr
1884 (sort cands-with-score
1885 (lambda (x y)
1886 (> (car x) (car y)))))
1887 cands))
1888 cands)
1889 (error
1890 cands)))
1891
1892 (defcustom ivy-format-function 'ivy-format-function-default
1893 "Function to transform the list of candidates into a string.
1894 This string is inserted into the minibuffer."
1895 :type '(choice
1896 (const :tag "Default" ivy-format-function-default)
1897 (const :tag "Arrow prefix" ivy-format-function-arrow)
1898 (const :tag "Full line" ivy-format-function-line)))
1899
1900 (defun ivy--truncate-string (str width)
1901 "Truncate STR to WIDTH."
1902 (if (> (string-width str) width)
1903 (concat (substring str 0 (min (- width 3)
1904 (- (length str) 3))) "...")
1905 str))
1906
1907 (defun ivy--format-function-generic (selected-fn other-fn cand-pairs separator)
1908 "Transform CAND-PAIRS into a string for minibuffer.
1909 SELECTED-FN and OTHER-FN each take two string arguments.
1910 SEPARATOR is used to join the candidates."
1911 (let ((i -1))
1912 (mapconcat
1913 (lambda (pair)
1914 (let ((str (car pair))
1915 (extra (cdr pair))
1916 (curr (eq (cl-incf i) ivy--index)))
1917 (if curr
1918 (funcall selected-fn str extra)
1919 (funcall other-fn str extra))))
1920 cand-pairs
1921 separator)))
1922
1923 (defun ivy-format-function-default (cand-pairs)
1924 "Transform CAND-PAIRS into a string for minibuffer."
1925 (ivy--format-function-generic
1926 (lambda (str extra)
1927 (concat (ivy--add-face str 'ivy-current-match) extra))
1928 #'concat
1929 cand-pairs
1930 "\n"))
1931
1932 (defun ivy-format-function-arrow (cand-pairs)
1933 "Transform CAND-PAIRS into a string for minibuffer."
1934 (ivy--format-function-generic
1935 (lambda (str extra)
1936 (concat "> " (ivy--add-face str 'ivy-current-match) extra))
1937 (lambda (str extra)
1938 (concat " " str extra))
1939 cand-pairs
1940 "\n"))
1941
1942 (defun ivy-format-function-line (cand-pairs)
1943 "Transform CAND-PAIRS into a string for minibuffer."
1944 (ivy--format-function-generic
1945 (lambda (str extra)
1946 (ivy--add-face (concat str extra "\n") 'ivy-current-match))
1947 (lambda (str extra)
1948 (concat str extra "\n"))
1949 cand-pairs
1950 ""))
1951
1952 (defface ivy-minibuffer-match-face-1
1953 '((((class color) (background light))
1954 :background "#d3d3d3")
1955 (((class color) (background dark))
1956 :background "#555555"))
1957 "The background face for `ivy' minibuffer matches.")
1958
1959 (defface ivy-minibuffer-match-face-2
1960 '((((class color) (background light))
1961 :background "#e99ce8" :weight bold)
1962 (((class color) (background dark))
1963 :background "#777777" :weight bold))
1964 "Face for `ivy' minibuffer matches modulo 1.")
1965
1966 (defface ivy-minibuffer-match-face-3
1967 '((((class color) (background light))
1968 :background "#bbbbff" :weight bold)
1969 (((class color) (background dark))
1970 :background "#7777ff" :weight bold))
1971 "Face for `ivy' minibuffer matches modulo 2.")
1972
1973 (defface ivy-minibuffer-match-face-4
1974 '((((class color) (background light))
1975 :background "#ffbbff" :weight bold)
1976 (((class color) (background dark))
1977 :background "#8a498a" :weight bold))
1978 "Face for `ivy' minibuffer matches modulo 3.")
1979
1980 (defcustom ivy-minibuffer-faces
1981 '(ivy-minibuffer-match-face-1
1982 ivy-minibuffer-match-face-2
1983 ivy-minibuffer-match-face-3
1984 ivy-minibuffer-match-face-4)
1985 "List of `ivy' faces for minibuffer group matches.")
1986
1987 (defun ivy--format-minibuffer-line (str)
1988 (let ((start 0)
1989 (str (copy-sequence str)))
1990 (when (eq ivy-display-style 'fancy)
1991 (unless ivy--old-re
1992 (setq ivy--old-re (funcall ivy--regex-function ivy-text)))
1993 (while (and (string-match ivy--old-re str start)
1994 (> (- (match-end 0) (match-beginning 0)) 0))
1995 (setq start (match-end 0))
1996 (let ((i 0))
1997 (while (<= i ivy--subexps)
1998 (let ((face
1999 (cond ((zerop ivy--subexps)
2000 (cadr ivy-minibuffer-faces))
2001 ((zerop i)
2002 (car ivy-minibuffer-faces))
2003 (t
2004 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2005 ivy-minibuffer-faces)))))
2006 (if (fboundp 'add-face-text-property)
2007 (add-face-text-property
2008 (match-beginning i)
2009 (match-end i)
2010 face
2011 nil
2012 str)
2013 (font-lock-append-text-property
2014 (match-beginning i)
2015 (match-end i)
2016 'face
2017 face
2018 str)))
2019 (cl-incf i)))))
2020 str))
2021
2022 (defun ivy--format (cands)
2023 "Return a string for CANDS suitable for display in the minibuffer.
2024 CANDS is a list of strings."
2025 (setq ivy--length (length cands))
2026 (when (>= ivy--index ivy--length)
2027 (setq ivy--index (max (1- ivy--length) 0)))
2028 (if (null cands)
2029 (setq ivy--current "")
2030 (let* ((half-height (/ ivy-height 2))
2031 (start (max 0 (- ivy--index half-height)))
2032 (end (min (+ start (1- ivy-height)) ivy--length))
2033 (start (max 0 (min start (- end (1- ivy-height)))))
2034 (cands (cl-subseq cands start end))
2035 (index (- ivy--index start)))
2036 (cond (ivy--directory
2037 (setq cands (mapcar (lambda (x)
2038 (if (string-match-p "/\\'" x)
2039 (propertize x 'face 'ivy-subdir)
2040 x))
2041 cands)))
2042 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
2043 (setq cands (mapcar (lambda (x)
2044 (let ((b (get-buffer x)))
2045 (if (and b
2046 (buffer-file-name b)
2047 (buffer-modified-p b))
2048 (propertize x 'face 'ivy-modified-buffer)
2049 x)))
2050 cands))))
2051 (setq ivy--current (copy-sequence (nth index cands)))
2052 (let* ((ivy--index index)
2053 (cand-pairs (mapcar
2054 (lambda (cand)
2055 (cons (ivy--format-minibuffer-line cand) nil)) cands))
2056 (res (concat "\n" (funcall ivy-format-function cand-pairs))))
2057 (put-text-property 0 (length res) 'read-only nil res)
2058 res))))
2059
2060 (defvar ivy--virtual-buffers nil
2061 "Store the virtual buffers alist.")
2062
2063 (defvar recentf-list)
2064
2065 (defface ivy-virtual '((t :inherit font-lock-builtin-face))
2066 "Face used by Ivy for matching virtual buffer names.")
2067
2068 (defcustom ivy-virtual-abbreviate 'name
2069 "The mode of abbreviation for virtual buffer names."
2070 :type '(choice
2071 (const :tag "Only name" name)
2072 (const :tag "Full path" full)
2073 ;; eventually, uniquify
2074 ))
2075
2076 (defun ivy--virtual-buffers ()
2077 "Adapted from `ido-add-virtual-buffers-to-list'."
2078 (unless recentf-mode
2079 (recentf-mode 1))
2080 (let ((bookmarks (and (boundp 'bookmark-alist)
2081 bookmark-alist))
2082 virtual-buffers name)
2083 (dolist (head (append
2084 recentf-list
2085 (delete " - no file -"
2086 (delq nil (mapcar (lambda (bookmark)
2087 (cdr (assoc 'filename bookmark)))
2088 bookmarks)))))
2089 (setq name
2090 (if (eq ivy-virtual-abbreviate 'name)
2091 (file-name-nondirectory head)
2092 (expand-file-name head)))
2093 (when (equal name "")
2094 (setq name (file-name-nondirectory (directory-file-name head))))
2095 (when (equal name "")
2096 (setq name head))
2097 (and (not (equal name ""))
2098 (null (get-file-buffer head))
2099 (not (assoc name virtual-buffers))
2100 (push (cons name head) virtual-buffers)))
2101 (when virtual-buffers
2102 (dolist (comp virtual-buffers)
2103 (put-text-property 0 (length (car comp))
2104 'face 'ivy-virtual
2105 (car comp)))
2106 (setq ivy--virtual-buffers (nreverse virtual-buffers))
2107 (mapcar #'car ivy--virtual-buffers))))
2108
2109 (defun ivy--buffer-list (str &optional virtual)
2110 "Return the buffers that match STR.
2111 When VIRTUAL is non-nil, add virtual buffers."
2112 (delete-dups
2113 (append
2114 (mapcar
2115 (lambda (x)
2116 (if (with-current-buffer x
2117 (file-remote-p
2118 (abbreviate-file-name default-directory)))
2119 (propertize x 'face 'ivy-remote)
2120 x))
2121 (all-completions str 'internal-complete-buffer))
2122 (and virtual
2123 (ivy--virtual-buffers)))))
2124
2125 (defun ivy--switch-buffer-action (buffer)
2126 "Switch to BUFFER.
2127 BUFFER may be a string or nil."
2128 (with-ivy-window
2129 (if (zerop (length buffer))
2130 (switch-to-buffer
2131 ivy-text nil 'force-same-window)
2132 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2133 (if (and virtual
2134 (not (get-buffer buffer)))
2135 (find-file (cdr virtual))
2136 (switch-to-buffer
2137 buffer nil 'force-same-window))))))
2138
2139 (defun ivy--switch-buffer-other-window-action (buffer)
2140 "Switch to BUFFER in other window.
2141 BUFFER may be a string or nil."
2142 (if (zerop (length buffer))
2143 (switch-to-buffer-other-window ivy-text)
2144 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2145 (if (and virtual
2146 (not (get-buffer buffer)))
2147 (find-file-other-window (cdr virtual))
2148 (switch-to-buffer-other-window buffer)))))
2149
2150 (defun ivy--rename-buffer-action (buffer)
2151 "Rename BUFFER."
2152 (let ((new-name (read-string "Rename buffer (to new name): ")))
2153 (with-current-buffer buffer
2154 (rename-buffer new-name))))
2155
2156 (defvar ivy-switch-buffer-map (make-sparse-keymap))
2157
2158 (ivy-set-actions
2159 'ivy-switch-buffer
2160 '(("k"
2161 (lambda (x)
2162 (kill-buffer x)
2163 (ivy--reset-state ivy-last))
2164 "kill")
2165 ("j"
2166 ivy--switch-buffer-other-window-action
2167 "other")
2168 ("r"
2169 ivy--rename-buffer-action
2170 "rename")))
2171
2172 ;;;###autoload
2173 (defun ivy-switch-buffer ()
2174 "Switch to another buffer."
2175 (interactive)
2176 (if (not ivy-mode)
2177 (call-interactively 'switch-to-buffer)
2178 (let ((this-command 'ivy-switch-buffer))
2179 (ivy-read "Switch to buffer: " 'internal-complete-buffer
2180 :preselect (buffer-name (other-buffer (current-buffer)))
2181 :action #'ivy--switch-buffer-action
2182 :keymap ivy-switch-buffer-map))))
2183
2184 ;;;###autoload
2185 (defun ivy-recentf ()
2186 "Find a file on `recentf-list'."
2187 (interactive)
2188 (ivy-read "Recentf: " recentf-list
2189 :action
2190 (lambda (f)
2191 (with-ivy-window
2192 (find-file f)))))
2193
2194 (defun ivy-yank-word ()
2195 "Pull next word from buffer into search string."
2196 (interactive)
2197 (let (amend)
2198 (with-ivy-window
2199 (let ((pt (point))
2200 (le (line-end-position)))
2201 (forward-word 1)
2202 (if (> (point) le)
2203 (goto-char pt)
2204 (setq amend (buffer-substring-no-properties pt (point))))))
2205 (when amend
2206 (insert (replace-regexp-in-string " +" " " amend)))))
2207
2208 (defun ivy-kill-ring-save ()
2209 "Store the current candidates into the kill ring.
2210 If the region is active, forward to `kill-ring-save' instead."
2211 (interactive)
2212 (if (region-active-p)
2213 (call-interactively 'kill-ring-save)
2214 (kill-new
2215 (mapconcat
2216 #'identity
2217 ivy--old-cands
2218 "\n"))))
2219
2220 (defun ivy-insert-current ()
2221 "Make the current candidate into current input.
2222 Don't finish completion."
2223 (interactive)
2224 (delete-minibuffer-contents)
2225 (if (and ivy--directory
2226 (string-match "/$" ivy--current))
2227 (insert (substring ivy--current 0 -1))
2228 (insert ivy--current)))
2229
2230 (defun ivy-toggle-fuzzy ()
2231 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
2232 (interactive)
2233 (setq ivy--old-re nil)
2234 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
2235 (setq ivy--regex-function 'ivy--regex-plus)
2236 (setq ivy--regex-function 'ivy--regex-fuzzy)))
2237
2238 (defun ivy-reverse-i-search ()
2239 "Enter a recursive `ivy-read' session using the current history.
2240 The selected history element will be inserted into the minibuffer."
2241 (interactive)
2242 (let ((enable-recursive-minibuffers t)
2243 (history (symbol-value (ivy-state-history ivy-last)))
2244 (old-last ivy-last))
2245 (ivy-read "Reverse-i-search: "
2246 history
2247 :action (lambda (x)
2248 (ivy--reset-state
2249 (setq ivy-last old-last))
2250 (delete-minibuffer-contents)
2251 (insert (substring-no-properties x))
2252 (ivy--cd-maybe)))))
2253
2254 (defun ivy-restrict-to-matches ()
2255 "Restrict candidates to current matches and erase input."
2256 (interactive)
2257 (delete-minibuffer-contents)
2258 (setq ivy--all-candidates
2259 (ivy--filter ivy-text ivy--all-candidates)))
2260
2261 ;;* Occur
2262 (defvar-local ivy-occur-last nil
2263 "Buffer-local value of `ivy-last'.
2264 Can't re-use `ivy-last' because using e.g. `swiper' in the same
2265 buffer would modify `ivy-last'.")
2266
2267 (defvar ivy-occur-mode-map
2268 (let ((map (make-sparse-keymap)))
2269 (define-key map [mouse-1] 'ivy-occur-click)
2270 (define-key map (kbd "RET") 'ivy-occur-press)
2271 (define-key map (kbd "j") 'next-line)
2272 (define-key map (kbd "k") 'previous-line)
2273 (define-key map (kbd "h") 'backward-char)
2274 (define-key map (kbd "l") 'forward-char)
2275 (define-key map (kbd "g") 'ivy-occur-press)
2276 (define-key map (kbd "a") 'ivy-occur-read-action)
2277 (define-key map (kbd "o") 'ivy-occur-dispatch)
2278 (define-key map (kbd "q") 'quit-window)
2279 map)
2280 "Keymap for Ivy Occur mode.")
2281
2282 (define-derived-mode ivy-occur-mode fundamental-mode "Ivy-Occur"
2283 "Major mode for output from \\[ivy-occur].
2284
2285 \\{ivy-occur-mode-map}")
2286
2287 (defvar ivy-occur-grep-mode-map
2288 (let ((map (copy-keymap ivy-occur-mode-map)))
2289 (define-key map (kbd "C-x C-q") 'ivy-wgrep-change-to-wgrep-mode)
2290 map)
2291 "Keymap for Ivy Occur Grep mode.")
2292
2293 (define-derived-mode ivy-occur-grep-mode grep-mode "Ivy-Occur"
2294 "Major mode for output from \\[ivy-occur].
2295
2296 \\{ivy-occur-grep-mode-map}")
2297
2298 (defvar counsel-git-grep-cmd)
2299
2300 (defun ivy-occur ()
2301 "Stop completion and put the current matches into a new buffer.
2302
2303 The new buffer remembers current action(s).
2304
2305 While in the *ivy-occur* buffer, selecting a candidate with RET or
2306 a mouse click will call the appropriate action for that candidate.
2307
2308 There is no limit on the number of *ivy-occur* buffers."
2309 (interactive)
2310 (let ((buffer
2311 (generate-new-buffer
2312 (format "*ivy-occur%s \"%s\"*"
2313 (let (caller)
2314 (if (setq caller (ivy-state-caller ivy-last))
2315 (concat " " (prin1-to-string caller))
2316 ""))
2317 ivy-text)))
2318 (do-grep (eq (ivy-state-caller ivy-last) 'counsel-git-grep)))
2319 (with-current-buffer buffer
2320 (if do-grep
2321 (progn
2322 (setq ivy--old-cands
2323 (split-string
2324 (shell-command-to-string
2325 (format counsel-git-grep-cmd ivy--old-re))
2326 "\n"
2327 t))
2328 (ivy-occur-grep-mode))
2329 (ivy-occur-mode))
2330 (setf (ivy-state-text ivy-last) ivy-text)
2331 (setq ivy-occur-last ivy-last)
2332 (setq-local ivy--directory ivy--directory)
2333 (let ((inhibit-read-only t))
2334 (erase-buffer)
2335 (when do-grep
2336 ;; Need precise number of header lines for `wgrep' to work.
2337 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
2338 default-directory)))
2339 (insert (format "%d candidates:\n" (length ivy--old-cands)))
2340 (dolist (cand ivy--old-cands)
2341 (let ((str (if do-grep
2342 (concat "./" cand)
2343 (concat " " cand))))
2344 (add-text-properties
2345 0 (length str)
2346 `(mouse-face
2347 highlight
2348 help-echo "mouse-1: call ivy-action")
2349 str)
2350 (insert str "\n")))))
2351 (ivy-exit-with-action
2352 `(lambda (_) (pop-to-buffer ,buffer)))))
2353
2354 (declare-function wgrep-change-to-wgrep-mode "ext:wgrep")
2355
2356 (defun ivy-wgrep-change-to-wgrep-mode ()
2357 "Forward to `wgrep-change-to-wgrep-mode'."
2358 (interactive)
2359 (if (require 'wgrep nil 'noerror)
2360 (wgrep-change-to-wgrep-mode)
2361 (error "Package wgrep isn't installed")))
2362
2363 (defun ivy-occur-read-action ()
2364 "Select one of the available actions as the current one."
2365 (interactive)
2366 (let ((ivy-last ivy-occur-last))
2367 (ivy-read-action)))
2368
2369 (defun ivy-occur-dispatch ()
2370 "Call one of the available actions on the current item."
2371 (interactive)
2372 (let* ((state-action (ivy-state-action ivy-occur-last))
2373 (actions (if (symbolp state-action)
2374 state-action
2375 (copy-sequence state-action))))
2376 (unwind-protect
2377 (progn
2378 (ivy-occur-read-action)
2379 (ivy-occur-press))
2380 (setf (ivy-state-action ivy-occur-last) actions))))
2381
2382 (defun ivy-occur-click (event)
2383 "Execute action for the current candidate.
2384 EVENT gives the mouse position."
2385 (interactive "e")
2386 (let ((window (posn-window (event-end event)))
2387 (pos (posn-point (event-end event))))
2388 (with-current-buffer (window-buffer window)
2389 (goto-char pos)
2390 (ivy-occur-press))))
2391
2392 (defun ivy-occur-press ()
2393 "Execute action for the current candidate."
2394 (interactive)
2395 (require 'pulse)
2396 (when (save-excursion
2397 (beginning-of-line)
2398 (looking-at "\\(?:./\\| \\)\\(.*\\)$"))
2399 (let* ((ivy-last ivy-occur-last)
2400 (ivy-text (ivy-state-text ivy-last))
2401 (str (buffer-substring
2402 (match-beginning 1)
2403 (match-end 1)))
2404 (coll (ivy-state-collection ivy-last))
2405 (action (ivy--get-action ivy-last))
2406 (ivy-exit 'done))
2407 (with-ivy-window
2408 (funcall action
2409 (if (and (consp coll)
2410 (consp (car coll)))
2411 (cdr (assoc str coll))
2412 str))
2413 (if (memq (ivy-state-caller ivy-last)
2414 '(swiper counsel-git-grep))
2415 (with-current-buffer (window-buffer (selected-window))
2416 (swiper--cleanup)
2417 (swiper--add-overlays
2418 (ivy--regex ivy-text)
2419 (line-beginning-position)
2420 (line-end-position)
2421 (selected-window))
2422 (run-at-time 0.5 nil 'swiper--cleanup))
2423 (pulse-momentary-highlight-one-line (point)))))))
2424
2425 (provide 'ivy)
2426
2427 ;;; ivy.el ends here