]> code.delx.au - gnu-emacs-elpa/blob - ivy.el
ivy.el (ivy--recompute-index): Update cl-position logic
[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 (if (string= str (car comps))
1410 (message "Sole match")
1411 (setf (ivy-state-window ivy-last) (selected-window))
1412 (ivy-completion-in-region-action
1413 (substring-no-properties
1414 (car comps))))
1415 (let* ((w (1+ (floor (log (length comps) 10))))
1416 (ivy-count-format (if (string= ivy-count-format "")
1417 ivy-count-format
1418 (format "%%-%dd " w)))
1419 (prompt (format "(%s): " str)))
1420 (and
1421 (ivy-read (if (string= ivy-count-format "")
1422 prompt
1423 (replace-regexp-in-string "%" "%%" prompt))
1424 ;; remove 'completions-first-difference face
1425 (mapcar #'substring-no-properties comps)
1426 :predicate predicate
1427 :action #'ivy-completion-in-region-action
1428 :require-match t)
1429 t))))))
1430
1431 ;;;###autoload
1432 (define-minor-mode ivy-mode
1433 "Toggle Ivy mode on or off.
1434 Turn Ivy mode on if ARG is positive, off otherwise.
1435 Turning on Ivy mode sets `completing-read-function' to
1436 `ivy-completing-read'.
1437
1438 Global bindings:
1439 \\{ivy-mode-map}
1440
1441 Minibuffer bindings:
1442 \\{ivy-minibuffer-map}"
1443 :group 'ivy
1444 :global t
1445 :keymap ivy-mode-map
1446 :lighter " ivy"
1447 (if ivy-mode
1448 (progn
1449 (setq completing-read-function 'ivy-completing-read)
1450 (setq completion-in-region-function 'ivy-completion-in-region))
1451 (setq completing-read-function 'completing-read-default)
1452 (setq completion-in-region-function 'completion--in-region)))
1453
1454 (defun ivy--preselect-index (preselect candidates)
1455 "Return the index of PRESELECT in CANDIDATES."
1456 (cond ((integerp preselect)
1457 preselect)
1458 ((cl-position preselect candidates :test #'equal))
1459 ((stringp preselect)
1460 (let ((re (regexp-quote preselect)))
1461 (cl-position-if
1462 (lambda (x)
1463 (string-match re x))
1464 candidates)))))
1465
1466 ;;* Implementation
1467 ;;** Regex
1468 (defvar ivy--regex-hash
1469 (make-hash-table :test #'equal)
1470 "Store pre-computed regex.")
1471
1472 (defun ivy--split (str)
1473 "Split STR into a list by single spaces.
1474 The remaining spaces stick to their left.
1475 This allows to \"quote\" N spaces by inputting N+1 spaces."
1476 (let ((len (length str))
1477 start0
1478 (start1 0)
1479 res s
1480 match-len)
1481 (while (and (string-match " +" str start1)
1482 (< start1 len))
1483 (setq match-len (- (match-end 0) (match-beginning 0)))
1484 (if (= match-len 1)
1485 (progn
1486 (when start0
1487 (setq start1 start0)
1488 (setq start0 nil))
1489 (push (substring str start1 (match-beginning 0)) res)
1490 (setq start1 (match-end 0)))
1491 (setq str (replace-match
1492 (make-string (1- match-len) ?\ )
1493 nil nil str))
1494 (setq start0 (or start0 start1))
1495 (setq start1 (1- (match-end 0)))))
1496 (if start0
1497 (push (substring str start0) res)
1498 (setq s (substring str start1))
1499 (unless (= (length s) 0)
1500 (push s res)))
1501 (nreverse res)))
1502
1503 (defun ivy--regex (str &optional greedy)
1504 "Re-build regex pattern from STR in case it has a space.
1505 When GREEDY is non-nil, join words in a greedy way."
1506 (let ((hashed (unless greedy
1507 (gethash str ivy--regex-hash))))
1508 (if hashed
1509 (prog1 (cdr hashed)
1510 (setq ivy--subexps (car hashed)))
1511 (when (string-match "\\([^\\]\\|^\\)\\\\$" str)
1512 (setq str (substring str 0 -1)))
1513 (cdr (puthash str
1514 (let ((subs (ivy--split str)))
1515 (if (= (length subs) 1)
1516 (cons
1517 (setq ivy--subexps 0)
1518 (car subs))
1519 (cons
1520 (setq ivy--subexps (length subs))
1521 (mapconcat
1522 (lambda (x)
1523 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1524 x
1525 (format "\\(%s\\)" x)))
1526 subs
1527 (if greedy
1528 ".*"
1529 ".*?")))))
1530 ivy--regex-hash)))))
1531
1532 (defun ivy--regex-ignore-order--part (str &optional discard)
1533 "Re-build regex from STR by splitting at spaces.
1534 Ignore the order of each group."
1535 (let* ((subs (split-string str " +" t))
1536 (len (length subs)))
1537 (cl-case len
1538 (0
1539 "")
1540 (t
1541 (mapcar (lambda (x) (cons x (not discard)))
1542 subs)))))
1543
1544 (defun ivy--regex-ignore-order (str)
1545 "Re-build regex from STR by splitting at spaces.
1546 Ignore the order of each group. Everything before \"!\" should
1547 match. Everything after \"!\" should not match."
1548 (let ((parts (split-string str "!" t)))
1549 (cl-case (length parts)
1550 (0
1551 "")
1552 (1
1553 (if (string= (substring str 0 1) "!")
1554 (list (cons "" t)
1555 (ivy--regex-ignore-order--part (car parts) t))
1556 (ivy--regex-ignore-order--part (car parts))))
1557 (2
1558 (append
1559 (ivy--regex-ignore-order--part (car parts))
1560 (ivy--regex-ignore-order--part (cadr parts) t)))
1561 (t (error "Unexpected: use only one !")))))
1562
1563 (defun ivy--regex-plus (str)
1564 "Build a regex sequence from STR.
1565 Spaces are wild card characters, everything before \"!\" should
1566 match. Everything after \"!\" should not match."
1567 (let ((parts (split-string str "!" t)))
1568 (cl-case (length parts)
1569 (0
1570 "")
1571 (1
1572 (if (string= (substring str 0 1) "!")
1573 (list (cons "" t)
1574 (list (ivy--regex (car parts))))
1575 (ivy--regex (car parts))))
1576 (2
1577 (cons
1578 (cons (ivy--regex (car parts)) t)
1579 (mapcar #'list (split-string (cadr parts) " " t))))
1580 (t (error "Unexpected: use only one !")))))
1581
1582 (defun ivy--regex-fuzzy (str)
1583 "Build a regex sequence from STR.
1584 Insert .* between each char."
1585 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1586 (prog1
1587 (concat (match-string 1 str)
1588 (mapconcat
1589 (lambda (x)
1590 (format "\\(%c\\)" x))
1591 (string-to-list (match-string 2 str)) ".*")
1592 (match-string 3 str))
1593 (setq ivy--subexps (length (match-string 2 str))))
1594 str))
1595
1596 ;;** Rest
1597 (defun ivy--minibuffer-setup ()
1598 "Setup ivy completion in the minibuffer."
1599 (set (make-local-variable 'completion-show-inline-help) nil)
1600 (set (make-local-variable 'minibuffer-default-add-function)
1601 (lambda ()
1602 (list ivy--default)))
1603 (when (display-graphic-p)
1604 (setq truncate-lines t))
1605 (setq-local max-mini-window-height ivy-height)
1606 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1607 ;; show completions with empty input
1608 (ivy--exhibit))
1609
1610 (defun ivy--input ()
1611 "Return the current minibuffer input."
1612 ;; assume one-line minibuffer input
1613 (buffer-substring-no-properties
1614 (minibuffer-prompt-end)
1615 (line-end-position)))
1616
1617 (defun ivy--cleanup ()
1618 "Delete the displayed completion candidates."
1619 (save-excursion
1620 (goto-char (minibuffer-prompt-end))
1621 (delete-region (line-end-position) (point-max))))
1622
1623 (defun ivy--insert-prompt ()
1624 "Update the prompt according to `ivy--prompt'."
1625 (when ivy--prompt
1626 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1627 counsel-find-symbol))
1628 (setq ivy--prompt-extra ""))
1629 (let (head tail)
1630 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1631 (progn
1632 (setq head (match-string 1 ivy--prompt))
1633 (setq tail ": "))
1634 (setq head (substring ivy--prompt 0 -1))
1635 (setq tail " "))
1636 (let ((inhibit-read-only t)
1637 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1638 (n-str
1639 (concat
1640 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1641 (> (minibuffer-depth) 1))
1642 (format "[%d] " (minibuffer-depth))
1643 "")
1644 (concat
1645 (if (string-match "%d.*%d" ivy-count-format)
1646 (format head
1647 (1+ ivy--index)
1648 (or (and (ivy-state-dynamic-collection ivy-last)
1649 ivy--full-length)
1650 ivy--length))
1651 (format head
1652 (or (and (ivy-state-dynamic-collection ivy-last)
1653 ivy--full-length)
1654 ivy--length)))
1655 ivy--prompt-extra
1656 tail)))
1657 (d-str (if ivy--directory
1658 (abbreviate-file-name ivy--directory)
1659 "")))
1660 (save-excursion
1661 (goto-char (point-min))
1662 (delete-region (point-min) (minibuffer-prompt-end))
1663 (if (> (+ (mod (+ (length n-str) (length d-str)) (window-width))
1664 (length ivy-text))
1665 (window-width))
1666 (setq n-str (concat n-str "\n" d-str))
1667 (setq n-str (concat n-str d-str)))
1668 (let ((regex (format "\\([^\n]\\{%d\\}\\)[^\n]" (window-width))))
1669 (while (string-match regex n-str)
1670 (setq n-str (replace-match (concat (match-string 1 n-str) "\n") nil t n-str 1))))
1671 (set-text-properties 0 (length n-str)
1672 `(face minibuffer-prompt ,@std-props)
1673 n-str)
1674 (ivy--set-match-props n-str "confirm"
1675 `(face ivy-confirm-face ,@std-props))
1676 (ivy--set-match-props n-str "match required"
1677 `(face ivy-match-required-face ,@std-props))
1678 (insert n-str))
1679 ;; get out of the prompt area
1680 (constrain-to-field nil (point-max))))))
1681
1682 (defun ivy--set-match-props (str match props)
1683 "Set STR text properties that match MATCH to PROPS."
1684 (when (string-match match str)
1685 (set-text-properties
1686 (match-beginning 0)
1687 (match-end 0)
1688 props
1689 str)))
1690
1691 (defvar inhibit-message)
1692
1693 (defun ivy--sort-maybe (collection)
1694 "Sort COLLECTION if needed."
1695 (let ((sort (ivy-state-sort ivy-last))
1696 entry)
1697 (if (null sort)
1698 collection
1699 (let ((sort-fn (cond ((functionp sort)
1700 sort)
1701 ((setq entry (assoc (ivy-state-collection ivy-last)
1702 ivy-sort-functions-alist))
1703 (cdr entry))
1704 (t
1705 (cdr (assoc t ivy-sort-functions-alist))))))
1706 (if (functionp sort-fn)
1707 (cl-sort (copy-sequence collection) sort-fn)
1708 collection)))))
1709
1710 (defun ivy--exhibit ()
1711 "Insert Ivy completions display.
1712 Should be run via minibuffer `post-command-hook'."
1713 (when (memq 'ivy--exhibit post-command-hook)
1714 (let ((inhibit-field-text-motion nil))
1715 (constrain-to-field nil (point-max)))
1716 (setq ivy-text (ivy--input))
1717 (if (ivy-state-dynamic-collection ivy-last)
1718 ;; while-no-input would cause annoying
1719 ;; "Waiting for process to die...done" message interruptions
1720 (let ((inhibit-message t))
1721 (unless (equal ivy--old-text ivy-text)
1722 (while-no-input
1723 (setq ivy--all-candidates
1724 (ivy--sort-maybe
1725 (funcall (ivy-state-collection ivy-last) ivy-text)))
1726 (setq ivy--old-text ivy-text)))
1727 (when ivy--all-candidates
1728 (ivy--insert-minibuffer
1729 (ivy--format ivy--all-candidates))))
1730 (cond (ivy--directory
1731 (if (string-match "/\\'" ivy-text)
1732 (if (member ivy-text ivy--all-candidates)
1733 (ivy--cd (expand-file-name ivy-text ivy--directory))
1734 (when (string-match "//\\'" ivy-text)
1735 (if (and default-directory
1736 (string-match "\\`[[:alpha:]]:/" default-directory))
1737 (ivy--cd (match-string 0 default-directory))
1738 (ivy--cd "/")))
1739 (when (string-match "[[:alpha:]]:/$" ivy-text)
1740 (let ((drive-root (match-string 0 ivy-text)))
1741 (when (file-exists-p drive-root)
1742 (ivy--cd drive-root)))))
1743 (if (string-match "\\`~\\'" ivy-text)
1744 (ivy--cd (expand-file-name "~/")))))
1745 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1746 (when (or (and (string-match "\\` " ivy-text)
1747 (not (string-match "\\` " ivy--old-text)))
1748 (and (string-match "\\` " ivy--old-text)
1749 (not (string-match "\\` " ivy-text))))
1750 (setq ivy--all-candidates
1751 (if (and (> (length ivy-text) 0)
1752 (eq (aref ivy-text 0)
1753 ?\ ))
1754 (ivy--buffer-list " ")
1755 (ivy--buffer-list "" ivy-use-virtual-buffers)))
1756 (setq ivy--old-re nil))))
1757 (ivy--insert-minibuffer
1758 (with-current-buffer (ivy-state-buffer ivy-last)
1759 (ivy--format
1760 (ivy--filter ivy-text ivy--all-candidates))))
1761 (setq ivy--old-text ivy-text))))
1762
1763 (defun ivy--insert-minibuffer (text)
1764 "Insert TEXT into minibuffer with appropriate cleanup."
1765 (let ((resize-mini-windows nil)
1766 (update-fn (ivy-state-update-fn ivy-last))
1767 deactivate-mark)
1768 (ivy--cleanup)
1769 (when update-fn
1770 (funcall update-fn))
1771 (ivy--insert-prompt)
1772 ;; Do nothing if while-no-input was aborted.
1773 (when (stringp text)
1774 (let ((buffer-undo-list t))
1775 (save-excursion
1776 (forward-line 1)
1777 (insert text))))
1778 (when (display-graphic-p)
1779 (ivy--resize-minibuffer-to-fit))))
1780
1781 (defun ivy--resize-minibuffer-to-fit ()
1782 "Resize the minibuffer window size to fit the text in the minibuffer."
1783 (with-selected-window (minibuffer-window)
1784 (if (fboundp 'window-text-pixel-size)
1785 (let ((text-height (cdr (window-text-pixel-size)))
1786 (body-height (window-body-height nil t)))
1787 (when (> text-height body-height)
1788 ;; Note: the size increment needs to be at least frame-char-height,
1789 ;; otherwise resizing won't do anything.
1790 (let ((delta (max (- text-height body-height) (frame-char-height))))
1791 (window-resize nil delta nil t t))))
1792 (let ((text-height (count-screen-lines))
1793 (body-height (window-body-height)))
1794 (when (> text-height body-height)
1795 (window-resize nil (- text-height body-height) nil t))))))
1796
1797 (declare-function colir-blend-face-background "ext:colir")
1798
1799 (defun ivy--add-face (str face)
1800 "Propertize STR with FACE.
1801 `font-lock-append-text-property' is used, since it's better than
1802 `propertize' or `add-face-text-property' in this case."
1803 (require 'colir)
1804 (condition-case nil
1805 (progn
1806 (colir-blend-face-background 0 (length str) face str)
1807 (let ((foreground (face-foreground face)))
1808 (when foreground
1809 (add-face-text-property
1810 0 (length str)
1811 `(:foreground ,foreground)
1812 nil
1813 str))))
1814 (error
1815 (ignore-errors
1816 (font-lock-append-text-property 0 (length str) 'face face str))))
1817 str)
1818
1819 (declare-function flx-make-string-cache "ext:flx")
1820 (declare-function flx-score "ext:flx")
1821
1822 (defvar ivy--flx-cache nil)
1823
1824 (eval-after-load 'flx
1825 '(setq ivy--flx-cache (flx-make-string-cache)))
1826
1827 (defun ivy-toggle-case-fold ()
1828 "Toggle the case folding between nil and auto.
1829 In any completion session, the case folding starts in auto:
1830
1831 - when the input is all lower case, `case-fold-search' is t
1832 - otherwise nil.
1833
1834 You can toggle this to make `case-fold-search' nil regardless of input."
1835 (interactive)
1836 (setq ivy-case-fold-search
1837 (if ivy-case-fold-search
1838 nil
1839 'auto))
1840 ;; reset cache so that the candidate list updates
1841 (setq ivy--old-re nil))
1842
1843 (defun ivy--re-filter (re candidates)
1844 "Return all RE matching CANDIDATES.
1845 RE is a list of cons cells, with a regexp car and a boolean cdr.
1846 When the cdr is t, the car must match.
1847 Otherwise, the car must not match."
1848 (let ((re-list (if (stringp re) (list (cons re t)) re))
1849 (res candidates))
1850 (dolist (re re-list)
1851 (setq res
1852 (ignore-errors
1853 (funcall
1854 (if (cdr re)
1855 #'cl-remove-if-not
1856 #'cl-remove-if)
1857 (let ((re-str (car re)))
1858 (lambda (x) (string-match re-str x)))
1859 res))))
1860 res))
1861
1862 (defun ivy--filter (name candidates)
1863 "Return all items that match NAME in CANDIDATES.
1864 CANDIDATES are assumed to be static."
1865 (let ((re (funcall ivy--regex-function name)))
1866 (if (and (equal re ivy--old-re)
1867 ivy--old-cands)
1868 ;; quick caching for "C-n", "C-p" etc.
1869 ivy--old-cands
1870 (let* ((re-str (if (listp re) (caar re) re))
1871 (matcher (ivy-state-matcher ivy-last))
1872 (case-fold-search
1873 (and ivy-case-fold-search
1874 (string= name (downcase name))))
1875 (cands (cond
1876 (matcher
1877 (funcall matcher re candidates))
1878 ((and ivy--old-re
1879 (stringp re)
1880 (stringp ivy--old-re)
1881 (not (string-match "\\\\" ivy--old-re))
1882 (not (equal ivy--old-re ""))
1883 (memq (cl-search
1884 (if (string-match "\\\\)\\'" ivy--old-re)
1885 (substring ivy--old-re 0 -2)
1886 ivy--old-re)
1887 re)
1888 '(0 2)))
1889 (ignore-errors
1890 (cl-remove-if-not
1891 (lambda (x) (string-match re x))
1892 ivy--old-cands)))
1893 (t
1894 (ivy--re-filter re candidates)))))
1895 (ivy--recompute-index name re-str cands)
1896 (setq ivy--old-re
1897 (if (eq ivy--regex-function 'ivy--regex-ignore-order)
1898 re
1899 (if cands
1900 re-str
1901 "")))
1902 (setq ivy--old-cands (ivy--sort name cands))))))
1903
1904 (defcustom ivy-sort-matches-functions-alist '((t . nil))
1905 "An alist of functions used to sort the matching candidates.
1906
1907 This is different from `ivy-sort-functions-alist', which is used
1908 to sort the whole collection only once. The functions taken from
1909 here are instead used on each input change, but they are used
1910 only on already matching candidates, not on all of them.
1911
1912 The alist KEY is a collection function or t to match previously
1913 not matched collection functions.
1914
1915 The alist VAL is a sorting function with the signature of
1916 `ivy--prefix-sort'.")
1917
1918 (defun ivy--sort-files-by-date (_name candidates)
1919 "Re-soft CANDIDATES according to file modification date."
1920 (let ((default-directory ivy--directory))
1921 (cl-sort (copy-sequence candidates)
1922 (lambda (f1 f2)
1923 (time-less-p
1924 (nth 5 (file-attributes f2))
1925 (nth 5 (file-attributes f1)))))))
1926
1927 (defun ivy--sort (name candidates)
1928 "Re-sort CANDIDATES by NAME.
1929 All CANDIDATES are assumed to match NAME."
1930 (let ((key (or (ivy-state-caller ivy-last)
1931 (when (functionp (ivy-state-collection ivy-last))
1932 (ivy-state-collection ivy-last))))
1933 fun)
1934 (cond ((and (require 'flx nil 'noerror)
1935 (eq ivy--regex-function 'ivy--regex-fuzzy))
1936 (ivy--flx-sort name candidates))
1937 ((setq fun (cdr (or (assoc key ivy-sort-matches-functions-alist)
1938 (assoc t ivy-sort-matches-functions-alist))))
1939 (funcall fun name candidates))
1940 (t
1941 candidates))))
1942
1943 (defun ivy--prefix-sort (name candidates)
1944 "Re-sort CANDIDATES.
1945 Prefix matches to NAME are put ahead of the list."
1946 (if (or (string-match "^\\^" name) (string= name ""))
1947 candidates
1948 (let ((re-prefix (concat "^" (funcall ivy--regex-function name)))
1949 res-prefix
1950 res-noprefix)
1951 (dolist (s candidates)
1952 (if (string-match re-prefix s)
1953 (push s res-prefix)
1954 (push s res-noprefix)))
1955 (nconc
1956 (nreverse res-prefix)
1957 (nreverse res-noprefix)))))
1958
1959 (defun ivy--recompute-index (name re-str cands)
1960 (let* ((caller (ivy-state-caller ivy-last))
1961 (func (or (and caller (cdr (assoc caller ivy-index-functions-alist)))
1962 (cdr (assoc t ivy-index-functions-alist))
1963 #'ivy-recompute-index-zero)))
1964 (unless (eq this-command 'ivy-resume)
1965 (setq ivy--index
1966 (or
1967 (cl-position (if (and (> (length name) 0)
1968 (eq ?^ (aref name 0)))
1969 (substring name 1)
1970 name) cands
1971 :test #'equal)
1972 (and ivy--directory
1973 (cl-position
1974 (concat re-str "/") cands
1975 :test #'equal))
1976 (and (not (string= name ""))
1977 (not (and (require 'flx nil 'noerror)
1978 (eq ivy--regex-function 'ivy--regex-fuzzy)
1979 (< (length cands) 200)))
1980
1981 (cl-position (nth ivy--index ivy--old-cands)
1982 cands))
1983 (funcall func re-str cands))))
1984 (when (and (or (string= name "")
1985 (string= name "^"))
1986 (not (equal ivy--old-re "")))
1987 (setq ivy--index
1988 (or (ivy--preselect-index
1989 (ivy-state-preselect ivy-last)
1990 cands)
1991 ivy--index)))))
1992
1993 (defun ivy-recompute-index-swiper (_re-str cands)
1994 (let ((tail (nthcdr ivy--index ivy--old-cands))
1995 idx)
1996 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
1997 (progn
1998 (while (and tail (null idx))
1999 ;; Compare with eq to handle equal duplicates in cands
2000 (setq idx (cl-position (pop tail) cands)))
2001 (or idx 0))
2002 (if ivy--old-cands
2003 ivy--index
2004 ;; already in ivy-state-buffer
2005 (let ((n (line-number-at-pos))
2006 (res 0)
2007 (i 0))
2008 (dolist (c cands)
2009 (when (eq n (read (get-text-property 0 'display c)))
2010 (setq res i))
2011 (cl-incf i))
2012 res)))))
2013
2014 (defun ivy-recompute-index-swiper-async (_re-str cands)
2015 (let ((tail (nthcdr ivy--index ivy--old-cands))
2016 idx)
2017 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
2018 (progn
2019 (while (and tail (null idx))
2020 ;; Compare with `equal', since the collection is re-created
2021 ;; each time with `split-string'
2022 (setq idx (cl-position (pop tail) cands :test #'equal)))
2023 (or idx 0))
2024 ivy--index)))
2025
2026 (defun ivy-recompute-index-zero (_re-str _cands)
2027 0)
2028
2029 (defcustom ivy-minibuffer-faces
2030 '(ivy-minibuffer-match-face-1
2031 ivy-minibuffer-match-face-2
2032 ivy-minibuffer-match-face-3
2033 ivy-minibuffer-match-face-4)
2034 "List of `ivy' faces for minibuffer group matches.")
2035
2036 (defun ivy--flx-sort (name cands)
2037 "Sort according to closeness to string NAME the string list CANDS."
2038 (condition-case nil
2039 (if (and cands
2040 (< (length cands) 200))
2041 (let* ((flx-name (if (string-match "^\\^" name)
2042 (substring name 1)
2043 name))
2044 (cands-with-score
2045 (delq nil
2046 (mapcar
2047 (lambda (x)
2048 (let ((score (flx-score x flx-name ivy--flx-cache)))
2049 (and score
2050 (cons score x))))
2051 cands))))
2052 (if cands-with-score
2053 (mapcar (lambda (x)
2054 (let ((str (copy-sequence (cdr x)))
2055 (i 0)
2056 (last-j -2))
2057 (dolist (j (cdar x))
2058 (unless (eq j (1+ last-j))
2059 (cl-incf i))
2060 (setq last-j j)
2061 (ivy-add-face-text-property
2062 j (1+ j)
2063 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2064 ivy-minibuffer-faces)
2065 str))
2066 str))
2067 (sort cands-with-score
2068 (lambda (x y)
2069 (> (caar x) (caar y)))))
2070 cands))
2071 cands)
2072 (error
2073 cands)))
2074
2075 (defcustom ivy-format-function 'ivy-format-function-default
2076 "Function to transform the list of candidates into a string.
2077 This string is inserted into the minibuffer."
2078 :type '(choice
2079 (const :tag "Default" ivy-format-function-default)
2080 (const :tag "Arrow prefix" ivy-format-function-arrow)
2081 (const :tag "Full line" ivy-format-function-line)))
2082
2083 (defun ivy--truncate-string (str width)
2084 "Truncate STR to WIDTH."
2085 (if (> (string-width str) width)
2086 (concat (substring str 0 (min (- width 3)
2087 (- (length str) 3))) "...")
2088 str))
2089
2090 (defun ivy--format-function-generic (selected-fn other-fn cand-pairs separator)
2091 "Transform CAND-PAIRS into a string for minibuffer.
2092 SELECTED-FN and OTHER-FN each take two string arguments.
2093 SEPARATOR is used to join the candidates."
2094 (let ((i -1))
2095 (mapconcat
2096 (lambda (pair)
2097 (let ((str (car pair))
2098 (extra (cdr pair))
2099 (curr (eq (cl-incf i) ivy--index)))
2100 (if curr
2101 (funcall selected-fn str extra)
2102 (funcall other-fn str extra))))
2103 cand-pairs
2104 separator)))
2105
2106 (defun ivy-format-function-default (cand-pairs)
2107 "Transform CAND-PAIRS into a string for minibuffer."
2108 (ivy--format-function-generic
2109 (lambda (str extra)
2110 (concat (ivy--add-face str 'ivy-current-match) extra))
2111 #'concat
2112 cand-pairs
2113 "\n"))
2114
2115 (defun ivy-format-function-arrow (cand-pairs)
2116 "Transform CAND-PAIRS into a string for minibuffer."
2117 (ivy--format-function-generic
2118 (lambda (str extra)
2119 (concat "> " (ivy--add-face str 'ivy-current-match) extra))
2120 (lambda (str extra)
2121 (concat " " str extra))
2122 cand-pairs
2123 "\n"))
2124
2125 (defun ivy-format-function-line (cand-pairs)
2126 "Transform CAND-PAIRS into a string for minibuffer."
2127 (ivy--format-function-generic
2128 (lambda (str extra)
2129 (ivy--add-face (concat str extra "\n") 'ivy-current-match))
2130 (lambda (str extra)
2131 (concat str extra "\n"))
2132 cand-pairs
2133 ""))
2134
2135 (defun ivy-add-face-text-property (start end face str)
2136 (if (fboundp 'add-face-text-property)
2137 (add-face-text-property
2138 start end face nil str)
2139 (font-lock-append-text-property
2140 start end 'face face str)))
2141
2142 (defun ivy--format-minibuffer-line (str)
2143 (let ((start 0)
2144 (str (copy-sequence str)))
2145 (cond ((eq ivy--regex-function 'ivy--regex-ignore-order)
2146 (when (consp ivy--old-re)
2147 (let ((i 1))
2148 (dolist (re ivy--old-re)
2149 (when (string-match (car re) str)
2150 (ivy-add-face-text-property
2151 (match-beginning 0) (match-end 0)
2152 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2153 ivy-minibuffer-faces)
2154 str))
2155 (cl-incf i)))))
2156 ((and (eq ivy-display-style 'fancy)
2157 (not (eq ivy--regex-function 'ivy--regex-fuzzy)))
2158 (unless ivy--old-re
2159 (setq ivy--old-re (funcall ivy--regex-function ivy-text)))
2160 (while (and (string-match ivy--old-re str start)
2161 (> (- (match-end 0) (match-beginning 0)) 0))
2162 (setq start (match-end 0))
2163 (let ((i 0))
2164 (while (<= i ivy--subexps)
2165 (let ((face
2166 (cond ((zerop ivy--subexps)
2167 (cadr ivy-minibuffer-faces))
2168 ((zerop i)
2169 (car ivy-minibuffer-faces))
2170 (t
2171 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
2172 ivy-minibuffer-faces)))))
2173 (ivy-add-face-text-property
2174 (match-beginning i) (match-end i)
2175 face str))
2176 (cl-incf i))))))
2177 str))
2178
2179 (defun ivy--format (cands)
2180 "Return a string for CANDS suitable for display in the minibuffer.
2181 CANDS is a list of strings."
2182 (setq ivy--length (length cands))
2183 (when (>= ivy--index ivy--length)
2184 (setq ivy--index (max (1- ivy--length) 0)))
2185 (if (null cands)
2186 (setq ivy--current "")
2187 (let* ((half-height (/ ivy-height 2))
2188 (start (max 0 (- ivy--index half-height)))
2189 (end (min (+ start (1- ivy-height)) ivy--length))
2190 (start (max 0 (min start (- end (1- ivy-height)))))
2191 (cands (cl-subseq cands start end))
2192 (index (- ivy--index start)))
2193 (cond (ivy--directory
2194 (setq cands (mapcar (lambda (x)
2195 (if (string-match-p "/\\'" x)
2196 (propertize x 'face 'ivy-subdir)
2197 x))
2198 cands)))
2199 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
2200 (setq cands (mapcar (lambda (x)
2201 (let ((b (get-buffer x)))
2202 (if (and b
2203 (buffer-file-name b)
2204 (buffer-modified-p b))
2205 (propertize x 'face 'ivy-modified-buffer)
2206 x)))
2207 cands))))
2208 (setq ivy--current (copy-sequence (nth index cands)))
2209 (let* ((ivy--index index)
2210 (cand-pairs (mapcar
2211 (lambda (cand)
2212 (cons (ivy--format-minibuffer-line cand) nil)) cands))
2213 (res (concat "\n" (funcall ivy-format-function cand-pairs))))
2214 (put-text-property 0 (length res) 'read-only nil res)
2215 res))))
2216
2217 (defvar ivy--virtual-buffers nil
2218 "Store the virtual buffers alist.")
2219
2220 (defvar recentf-list)
2221
2222 (defcustom ivy-virtual-abbreviate 'name
2223 "The mode of abbreviation for virtual buffer names."
2224 :type '(choice
2225 (const :tag "Only name" name)
2226 (const :tag "Full path" full)
2227 ;; eventually, uniquify
2228 ))
2229
2230 (defun ivy--virtual-buffers ()
2231 "Adapted from `ido-add-virtual-buffers-to-list'."
2232 (unless recentf-mode
2233 (recentf-mode 1))
2234 (let ((bookmarks (and (boundp 'bookmark-alist)
2235 bookmark-alist))
2236 virtual-buffers name)
2237 (dolist (head (append
2238 recentf-list
2239 (delete " - no file -"
2240 (delq nil (mapcar (lambda (bookmark)
2241 (cdr (assoc 'filename bookmark)))
2242 bookmarks)))))
2243 (setq name
2244 (if (eq ivy-virtual-abbreviate 'name)
2245 (file-name-nondirectory head)
2246 (expand-file-name head)))
2247 (when (equal name "")
2248 (setq name (file-name-nondirectory (directory-file-name head))))
2249 (when (equal name "")
2250 (setq name head))
2251 (and (not (equal name ""))
2252 (null (get-file-buffer head))
2253 (not (assoc name virtual-buffers))
2254 (push (cons name head) virtual-buffers)))
2255 (when virtual-buffers
2256 (dolist (comp virtual-buffers)
2257 (put-text-property 0 (length (car comp))
2258 'face 'ivy-virtual
2259 (car comp)))
2260 (setq ivy--virtual-buffers (nreverse virtual-buffers))
2261 (mapcar #'car ivy--virtual-buffers))))
2262
2263 (defun ivy--buffer-list (str &optional virtual)
2264 "Return the buffers that match STR.
2265 When VIRTUAL is non-nil, add virtual buffers."
2266 (delete-dups
2267 (append
2268 (mapcar
2269 (lambda (x)
2270 (if (with-current-buffer x
2271 (file-remote-p
2272 (abbreviate-file-name default-directory)))
2273 (propertize x 'face 'ivy-remote)
2274 x))
2275 (all-completions str 'internal-complete-buffer))
2276 (and virtual
2277 (ivy--virtual-buffers)))))
2278
2279 (defun ivy--switch-buffer-action (buffer)
2280 "Switch to BUFFER.
2281 BUFFER may be a string or nil."
2282 (with-ivy-window
2283 (if (zerop (length buffer))
2284 (switch-to-buffer
2285 ivy-text nil 'force-same-window)
2286 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2287 (if (and virtual
2288 (not (get-buffer buffer)))
2289 (find-file (cdr virtual))
2290 (switch-to-buffer
2291 buffer nil 'force-same-window))))))
2292
2293 (defun ivy--switch-buffer-other-window-action (buffer)
2294 "Switch to BUFFER in other window.
2295 BUFFER may be a string or nil."
2296 (if (zerop (length buffer))
2297 (switch-to-buffer-other-window ivy-text)
2298 (let ((virtual (assoc buffer ivy--virtual-buffers)))
2299 (if (and virtual
2300 (not (get-buffer buffer)))
2301 (find-file-other-window (cdr virtual))
2302 (switch-to-buffer-other-window buffer)))))
2303
2304 (defun ivy--rename-buffer-action (buffer)
2305 "Rename BUFFER."
2306 (let ((new-name (read-string "Rename buffer (to new name): ")))
2307 (with-current-buffer buffer
2308 (rename-buffer new-name))))
2309
2310 (defvar ivy-switch-buffer-map (make-sparse-keymap))
2311
2312 (ivy-set-actions
2313 'ivy-switch-buffer
2314 '(("k"
2315 (lambda (x)
2316 (kill-buffer x)
2317 (ivy--reset-state ivy-last))
2318 "kill")
2319 ("j"
2320 ivy--switch-buffer-other-window-action
2321 "other")
2322 ("r"
2323 ivy--rename-buffer-action
2324 "rename")))
2325
2326 ;;;###autoload
2327 (defun ivy-switch-buffer ()
2328 "Switch to another buffer."
2329 (interactive)
2330 (if (not ivy-mode)
2331 (call-interactively 'switch-to-buffer)
2332 (let ((this-command 'ivy-switch-buffer))
2333 (ivy-read "Switch to buffer: " 'internal-complete-buffer
2334 :preselect (buffer-name (other-buffer (current-buffer)))
2335 :action #'ivy--switch-buffer-action
2336 :keymap ivy-switch-buffer-map))))
2337
2338 ;;;###autoload
2339 (defun ivy-recentf ()
2340 "Find a file on `recentf-list'."
2341 (interactive)
2342 (ivy-read "Recentf: " recentf-list
2343 :action
2344 (lambda (f)
2345 (with-ivy-window
2346 (find-file f)))))
2347
2348 (defun ivy-yank-word ()
2349 "Pull next word from buffer into search string."
2350 (interactive)
2351 (let (amend)
2352 (with-ivy-window
2353 (let ((pt (point))
2354 (le (line-end-position)))
2355 (forward-word 1)
2356 (if (> (point) le)
2357 (goto-char pt)
2358 (setq amend (buffer-substring-no-properties pt (point))))))
2359 (when amend
2360 (insert (replace-regexp-in-string " +" " " amend)))))
2361
2362 (defun ivy-kill-ring-save ()
2363 "Store the current candidates into the kill ring.
2364 If the region is active, forward to `kill-ring-save' instead."
2365 (interactive)
2366 (if (region-active-p)
2367 (call-interactively 'kill-ring-save)
2368 (kill-new
2369 (mapconcat
2370 #'identity
2371 ivy--old-cands
2372 "\n"))))
2373
2374 (defun ivy-insert-current ()
2375 "Make the current candidate into current input.
2376 Don't finish completion."
2377 (interactive)
2378 (delete-minibuffer-contents)
2379 (if (and ivy--directory
2380 (string-match "/$" ivy--current))
2381 (insert (substring ivy--current 0 -1))
2382 (insert ivy--current)))
2383
2384 (defun ivy-toggle-fuzzy ()
2385 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
2386 (interactive)
2387 (setq ivy--old-re nil)
2388 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
2389 (setq ivy--regex-function 'ivy--regex-plus)
2390 (setq ivy--regex-function 'ivy--regex-fuzzy)))
2391
2392 (defun ivy-reverse-i-search ()
2393 "Enter a recursive `ivy-read' session using the current history.
2394 The selected history element will be inserted into the minibuffer."
2395 (interactive)
2396 (let ((enable-recursive-minibuffers t)
2397 (history (symbol-value (ivy-state-history ivy-last)))
2398 (old-last ivy-last)
2399 (ivy-recursive-restore nil))
2400 (ivy-read "Reverse-i-search: "
2401 history
2402 :action (lambda (x)
2403 (ivy--reset-state
2404 (setq ivy-last old-last))
2405 (delete-minibuffer-contents)
2406 (insert (substring-no-properties x))
2407 (ivy--cd-maybe)))))
2408
2409 (defun ivy-restrict-to-matches ()
2410 "Restrict candidates to current matches and erase input."
2411 (interactive)
2412 (delete-minibuffer-contents)
2413 (setq ivy--all-candidates
2414 (ivy--filter ivy-text ivy--all-candidates)))
2415
2416 ;;* Occur
2417 (defvar-local ivy-occur-last nil
2418 "Buffer-local value of `ivy-last'.
2419 Can't re-use `ivy-last' because using e.g. `swiper' in the same
2420 buffer would modify `ivy-last'.")
2421
2422 (defvar ivy-occur-mode-map
2423 (let ((map (make-sparse-keymap)))
2424 (define-key map [mouse-1] 'ivy-occur-click)
2425 (define-key map (kbd "RET") 'ivy-occur-press)
2426 (define-key map (kbd "j") 'next-line)
2427 (define-key map (kbd "k") 'previous-line)
2428 (define-key map (kbd "h") 'backward-char)
2429 (define-key map (kbd "l") 'forward-char)
2430 (define-key map (kbd "g") 'ivy-occur-press)
2431 (define-key map (kbd "a") 'ivy-occur-read-action)
2432 (define-key map (kbd "o") 'ivy-occur-dispatch)
2433 (define-key map (kbd "q") 'quit-window)
2434 map)
2435 "Keymap for Ivy Occur mode.")
2436
2437 (define-derived-mode ivy-occur-mode fundamental-mode "Ivy-Occur"
2438 "Major mode for output from \\[ivy-occur].
2439
2440 \\{ivy-occur-mode-map}")
2441
2442 (defvar ivy-occur-grep-mode-map
2443 (let ((map (copy-keymap ivy-occur-mode-map)))
2444 (define-key map (kbd "C-x C-q") 'ivy-wgrep-change-to-wgrep-mode)
2445 map)
2446 "Keymap for Ivy Occur Grep mode.")
2447
2448 (define-derived-mode ivy-occur-grep-mode grep-mode "Ivy-Occur"
2449 "Major mode for output from \\[ivy-occur].
2450
2451 \\{ivy-occur-grep-mode-map}")
2452
2453 (defvar counsel-git-grep-cmd)
2454
2455 (defun ivy-occur ()
2456 "Stop completion and put the current matches into a new buffer.
2457
2458 The new buffer remembers current action(s).
2459
2460 While in the *ivy-occur* buffer, selecting a candidate with RET or
2461 a mouse click will call the appropriate action for that candidate.
2462
2463 There is no limit on the number of *ivy-occur* buffers."
2464 (interactive)
2465 (let ((buffer
2466 (generate-new-buffer
2467 (format "*ivy-occur%s \"%s\"*"
2468 (let (caller)
2469 (if (setq caller (ivy-state-caller ivy-last))
2470 (concat " " (prin1-to-string caller))
2471 ""))
2472 ivy-text)))
2473 (do-grep (eq (ivy-state-caller ivy-last) 'counsel-git-grep)))
2474 (with-current-buffer buffer
2475 (if do-grep
2476 (progn
2477 (setq ivy--old-cands
2478 (split-string
2479 (shell-command-to-string
2480 (format counsel-git-grep-cmd
2481 (if (stringp ivy--old-re)
2482 ivy--old-re
2483 (caar ivy--old-re))))
2484 "\n"
2485 t))
2486 (ivy-occur-grep-mode))
2487 (ivy-occur-mode))
2488 (setf (ivy-state-text ivy-last) ivy-text)
2489 (setq ivy-occur-last ivy-last)
2490 (setq-local ivy--directory ivy--directory)
2491 (let ((inhibit-read-only t))
2492 (erase-buffer)
2493 (when do-grep
2494 ;; Need precise number of header lines for `wgrep' to work.
2495 (insert (format "-*- mode:grep; default-directory: %S -*-\n\n\n"
2496 default-directory)))
2497 (insert (format "%d candidates:\n" (length ivy--old-cands)))
2498 (dolist (cand ivy--old-cands)
2499 (let ((str (if do-grep
2500 (concat "./" cand)
2501 (concat " " cand))))
2502 (add-text-properties
2503 0 (length str)
2504 `(mouse-face
2505 highlight
2506 help-echo "mouse-1: call ivy-action")
2507 str)
2508 (insert str "\n")))))
2509 (ivy-exit-with-action
2510 `(lambda (_) (pop-to-buffer ,buffer)))))
2511
2512 (declare-function wgrep-change-to-wgrep-mode "ext:wgrep")
2513
2514 (defun ivy-wgrep-change-to-wgrep-mode ()
2515 "Forward to `wgrep-change-to-wgrep-mode'."
2516 (interactive)
2517 (if (require 'wgrep nil 'noerror)
2518 (wgrep-change-to-wgrep-mode)
2519 (error "Package wgrep isn't installed")))
2520
2521 (defun ivy-occur-read-action ()
2522 "Select one of the available actions as the current one."
2523 (interactive)
2524 (let ((ivy-last ivy-occur-last))
2525 (ivy-read-action)))
2526
2527 (defun ivy-occur-dispatch ()
2528 "Call one of the available actions on the current item."
2529 (interactive)
2530 (let* ((state-action (ivy-state-action ivy-occur-last))
2531 (actions (if (symbolp state-action)
2532 state-action
2533 (copy-sequence state-action))))
2534 (unwind-protect
2535 (progn
2536 (ivy-occur-read-action)
2537 (ivy-occur-press))
2538 (setf (ivy-state-action ivy-occur-last) actions))))
2539
2540 (defun ivy-occur-click (event)
2541 "Execute action for the current candidate.
2542 EVENT gives the mouse position."
2543 (interactive "e")
2544 (let ((window (posn-window (event-end event)))
2545 (pos (posn-point (event-end event))))
2546 (with-current-buffer (window-buffer window)
2547 (goto-char pos)
2548 (ivy-occur-press))))
2549
2550 (declare-function swiper--cleanup "swiper")
2551 (declare-function swiper--add-overlays "swiper")
2552
2553 (defun ivy-occur-press ()
2554 "Execute action for the current candidate."
2555 (interactive)
2556 (require 'pulse)
2557 (when (save-excursion
2558 (beginning-of-line)
2559 (looking-at "\\(?:./\\| \\)\\(.*\\)$"))
2560 (let* ((ivy-last ivy-occur-last)
2561 (ivy-text (ivy-state-text ivy-last))
2562 (str (buffer-substring
2563 (match-beginning 1)
2564 (match-end 1)))
2565 (coll (ivy-state-collection ivy-last))
2566 (action (ivy--get-action ivy-last))
2567 (ivy-exit 'done))
2568 (with-ivy-window
2569 (funcall action
2570 (if (and (consp coll)
2571 (consp (car coll)))
2572 (cdr (assoc str coll))
2573 str))
2574 (if (memq (ivy-state-caller ivy-last)
2575 '(swiper counsel-git-grep))
2576 (with-current-buffer (window-buffer (selected-window))
2577 (swiper--cleanup)
2578 (swiper--add-overlays
2579 (ivy--regex ivy-text)
2580 (line-beginning-position)
2581 (line-end-position)
2582 (selected-window))
2583 (run-at-time 0.5 nil 'swiper--cleanup))
2584 (pulse-momentary-highlight-one-line (point)))))))
2585
2586 (provide 'ivy)
2587
2588 ;;; ivy.el ends here