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