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