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