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