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