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