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