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