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