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