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