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