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