]> code.delx.au - gnu-emacs-elpa/blob - ivy.el
ivy.el (ffap): Move require
[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 (defface ivy-current-match
48 '((((class color) (background light))
49 :background "#1a4b77" :foreground "white")
50 (((class color) (background dark))
51 :background "#65a7e2" :foreground "black"))
52 "Face used by Ivy for highlighting first match.")
53
54 (defface ivy-confirm-face
55 '((t :foreground "ForestGreen" :inherit minibuffer-prompt))
56 "Face used by Ivy to issue a confirmation prompt.")
57
58 (defface ivy-match-required-face
59 '((t :foreground "red" :inherit minibuffer-prompt))
60 "Face used by Ivy to issue a match required prompt.")
61
62 (defface ivy-subdir
63 '((t (:inherit 'dired-directory)))
64 "Face used by Ivy for highlighting subdirs in the alternatives.")
65
66 (defface ivy-remote
67 '((t (:foreground "#110099")))
68 "Face used by Ivy for highlighting remotes in the alternatives.")
69
70 (defcustom ivy-height 10
71 "Number of lines for the minibuffer window."
72 :type 'integer)
73
74 (defcustom ivy-count-format "%-4d "
75 "The style of showing the current candidate count for `ivy-read'.
76 Set this to \"\" if you don't want the count. You can also set
77 it to e.g. \"(%d/%d) \" if you want to see both the candidate
78 index and the candidate count."
79 :type '(choice
80 (const :tag "Count disabled" "")
81 (const :tag "Count matches" "%-4d ")
82 (const :tag "Count matches and show current match" "(%d/%d) ")
83 string))
84
85 (defcustom ivy-wrap nil
86 "Whether to wrap around after the first and last candidate."
87 :type 'boolean)
88
89 (defcustom ivy-display-style (unless (version< emacs-version "24.5") 'fancy)
90 "The style for formatting the minibuffer.
91
92 By default, the matched strings will be copied as they are.
93
94 With the fancy method, the matching parts of the regexp will be
95 additionally highlighted, just like `swiper' does it.
96
97 This setting depends on `add-face-text-property' - a C function
98 available as of 24.5. It will behave poorly in earlier Emacs
99 versions."
100 :type '(choice
101 (const :tag "Plain" nil)
102 (const :tag "Fancy" fancy)))
103
104 (defcustom ivy-on-del-error-function 'minibuffer-keyboard-quit
105 "The handler for when `ivy-backward-delete-char' throws.
106 This is usually meant as a quick exit out of the minibuffer."
107 :type 'function)
108
109 (defcustom ivy-extra-directories '("../" "./")
110 "Add this to the front of the list when completing file names.
111 Only \"./\" and \"../\" apply here. They appear in reverse order."
112 :type '(repeat :tag "Dirs"
113 (choice
114 (const :tag "Parent Directory" "../")
115 (const :tag "Current Directory" "./"))))
116
117 (defcustom ivy-use-virtual-buffers nil
118 "When non-nil, add `recentf-mode' and bookmarks to `ivy-switch-buffer'."
119 :type 'boolean)
120
121 (defvar ivy--actions-list nil
122 "A list of extra actions per command.")
123
124 (defun ivy-set-actions (cmd actions)
125 "Set CMD extra exit points to ACTIONS."
126 (setq ivy--actions-list
127 (plist-put ivy--actions-list cmd actions)))
128
129 ;;* Keymap
130 (require 'delsel)
131 (defvar ivy-minibuffer-map
132 (let ((map (make-sparse-keymap)))
133 (define-key map (kbd "C-m") 'ivy-done)
134 (define-key map (kbd "C-M-m") 'ivy-call)
135 (define-key map (kbd "C-j") 'ivy-alt-done)
136 (define-key map (kbd "C-M-j") 'ivy-immediate-done)
137 (define-key map (kbd "TAB") 'ivy-partial-or-done)
138 (define-key map (kbd "C-n") 'ivy-next-line)
139 (define-key map (kbd "C-p") 'ivy-previous-line)
140 (define-key map (kbd "<down>") 'ivy-next-line)
141 (define-key map (kbd "<up>") 'ivy-previous-line)
142 (define-key map (kbd "C-s") 'ivy-next-line-or-history)
143 (define-key map (kbd "C-r") 'ivy-reverse-i-search)
144 (define-key map (kbd "SPC") 'self-insert-command)
145 (define-key map (kbd "DEL") 'ivy-backward-delete-char)
146 (define-key map (kbd "M-DEL") 'ivy-backward-kill-word)
147 (define-key map (kbd "C-d") 'ivy-delete-char)
148 (define-key map (kbd "C-f") 'ivy-forward-char)
149 (define-key map (kbd "M-d") 'ivy-kill-word)
150 (define-key map (kbd "M-<") 'ivy-beginning-of-buffer)
151 (define-key map (kbd "M->") 'ivy-end-of-buffer)
152 (define-key map (kbd "M-n") 'ivy-next-history-element)
153 (define-key map (kbd "M-p") 'ivy-previous-history-element)
154 (define-key map (kbd "C-g") 'minibuffer-keyboard-quit)
155 (define-key map (kbd "C-v") 'ivy-scroll-up-command)
156 (define-key map (kbd "M-v") 'ivy-scroll-down-command)
157 (define-key map (kbd "C-M-n") 'ivy-next-line-and-call)
158 (define-key map (kbd "C-M-p") 'ivy-previous-line-and-call)
159 (define-key map (kbd "M-q") 'ivy-toggle-regexp-quote)
160 (define-key map (kbd "M-j") 'ivy-yank-word)
161 (define-key map (kbd "M-i") 'ivy-insert-current)
162 (define-key map (kbd "C-o") 'hydra-ivy/body)
163 (define-key map (kbd "M-o") 'ivy-dispatching-done)
164 (define-key map (kbd "C-M-o") 'ivy-dispatching-call)
165 (define-key map (kbd "C-k") 'ivy-kill-line)
166 (define-key map (kbd "S-SPC") 'ivy-restrict-to-matches)
167 (define-key map (kbd "M-w") 'ivy-kill-ring-save)
168 (define-key map (kbd "C-'") 'ivy-avy)
169 map)
170 "Keymap used in the minibuffer.")
171 (autoload 'hydra-ivy/body "ivy-hydra" "" t)
172
173 (defvar ivy-mode-map
174 (let ((map (make-sparse-keymap)))
175 (define-key map [remap switch-to-buffer] 'ivy-switch-buffer)
176 map)
177 "Keymap for `ivy-mode'.")
178
179 ;;* Globals
180 (cl-defstruct ivy-state
181 prompt collection
182 predicate require-match initial-input
183 history preselect keymap update-fn sort
184 ;; The window in which `ivy-read' was called
185 window
186 action
187 unwind
188 re-builder
189 matcher
190 ;; When this is non-nil, call it for each input change to get new candidates
191 dynamic-collection
192 caller)
193
194 (defvar ivy-last nil
195 "The last parameters passed to `ivy-read'.
196
197 This should eventually become a stack so that you could use
198 `ivy-read' recursively.")
199
200 (defsubst ivy-set-action (action)
201 (setf (ivy-state-action ivy-last) action))
202
203 (defvar ivy-history nil
204 "History list of candidates entered in the minibuffer.
205
206 Maximum length of the history list is determined by the value
207 of `history-length', which see.")
208
209 (defvar ivy--directory nil
210 "Current directory when completing file names.")
211
212 (defvar ivy--length 0
213 "Store the amount of viable candidates.")
214
215 (defvar ivy-text ""
216 "Store the user's string as it is typed in.")
217
218 (defvar ivy--current ""
219 "Current candidate.")
220
221 (defvar ivy--index 0
222 "Store the index of the current candidate.")
223
224 (defvar ivy-exit nil
225 "Store 'done if the completion was successfully selected.
226 Otherwise, store nil.")
227
228 (defvar ivy--all-candidates nil
229 "Store the candidates passed to `ivy-read'.")
230
231 (defvar ivy--default nil
232 "Default initial input.")
233
234 (defvar ivy--prompt nil
235 "Store the format-style prompt.
236 When non-nil, it should contain one %d.")
237
238 (defvar ivy--prompt-extra ""
239 "Temporary modifications to the prompt.")
240
241 (defvar ivy--old-re nil
242 "Store the old regexp.")
243
244 (defvar ivy--old-cands nil
245 "Store the candidates matched by `ivy--old-re'.")
246
247 (defvar ivy--regex-function 'ivy--regex
248 "Current function for building a regex.")
249
250 (defvar ivy--subexps 0
251 "Number of groups in the current `ivy--regex'.")
252
253 (defvar ivy--full-length nil
254 "When :dynamic-collection is non-nil, this can be the total amount of candidates.")
255
256 (defvar ivy--old-text ""
257 "Store old `ivy-text' for dynamic completion.")
258
259 (defvar ivy-case-fold-search 'auto
260 "Store the current overriding `case-fold-search'.")
261
262 (defvar Info-current-file)
263
264 (defmacro ivy-quit-and-run (&rest body)
265 "Quit the minibuffer and run BODY afterwards."
266 `(progn
267 (put 'quit 'error-message "")
268 (run-at-time nil nil
269 (lambda ()
270 (put 'quit 'error-message "Quit")
271 ,@body))
272 (minibuffer-keyboard-quit)))
273
274 (defmacro with-ivy-window (&rest body)
275 "Execute BODY in the window from which `ivy-read' was called."
276 (declare (indent 0)
277 (debug t))
278 `(with-selected-window (ivy-state-window ivy-last)
279 ,@body))
280
281 (defun ivy--done (text)
282 "Insert TEXT and exit minibuffer."
283 (if (and ivy--directory
284 (not (eq (ivy-state-history ivy-last) 'grep-files-history)))
285 (insert (setq ivy--current (expand-file-name
286 text ivy--directory)))
287 (insert (setq ivy--current text)))
288 (setq ivy-exit 'done)
289 (exit-minibuffer))
290
291 ;;* Commands
292 (defun ivy-done ()
293 "Exit the minibuffer with the selected candidate."
294 (interactive)
295 (delete-minibuffer-contents)
296 (cond ((> ivy--length 0)
297 (ivy--done ivy--current))
298 ((memq (ivy-state-collection ivy-last)
299 '(read-file-name-internal internal-complete-buffer))
300 (if (or (not (eq confirm-nonexistent-file-or-buffer t))
301 (equal " (confirm)" ivy--prompt-extra))
302 (ivy--done ivy-text)
303 (setq ivy--prompt-extra " (confirm)")
304 (insert ivy-text)
305 (ivy--exhibit)))
306 ((memq (ivy-state-require-match ivy-last)
307 '(nil confirm confirm-after-completion))
308 (ivy--done ivy-text))
309 (t
310 (setq ivy--prompt-extra " (match required)")
311 (insert ivy-text)
312 (ivy--exhibit))))
313
314 (defun ivy-read-action ()
315 "Change the action to one of the available ones."
316 (interactive)
317 (let ((actions (ivy-state-action ivy-last)))
318 (unless (null (ivy--actionp actions))
319 (let* ((hint (concat ivy--current
320 "\n"
321 (mapconcat
322 (lambda (x)
323 (format "%s: %s"
324 (propertize
325 (car x)
326 'face 'font-lock-builtin-face)
327 (nth 2 x)))
328 (cdr actions)
329 "\n")
330 "\n"))
331 (key (string (read-key hint)))
332 (action-idx (cl-position-if
333 (lambda (x) (equal (car x) key))
334 (cdr actions))))
335 (cond ((string= key "\a"))
336 ((null action-idx)
337 (error "%s is not bound" key))
338 (t
339 (message "")
340 (setcar actions (1+ action-idx))
341 (ivy-set-action actions)))))))
342
343 (defun ivy-dispatching-done ()
344 "Select one of the available actions and call `ivy-done'."
345 (interactive)
346 (ivy-read-action)
347 (ivy-done))
348
349 (defun ivy-dispatching-call ()
350 "Select one of the available actions and call `ivy-call'."
351 (interactive)
352 (let ((actions (copy-sequence (ivy-state-action ivy-last))))
353 (ivy-read-action)
354 (ivy-call)
355 (ivy-set-action actions)))
356
357 (defun ivy-build-tramp-name (x)
358 "Reconstruct X into a path.
359 Is is a cons cell, related to `tramp-get-completion-function'."
360 (let ((user (car x))
361 (domain (cadr x)))
362 (if user
363 (concat user "@" domain)
364 domain)))
365
366 (declare-function tramp-get-completion-function "tramp")
367 (declare-function Info-find-node "info")
368
369 (defun ivy-alt-done (&optional arg)
370 "Exit the minibuffer with the selected candidate.
371 When ARG is t, exit with current text, ignoring the candidates."
372 (interactive "P")
373 (let (dir)
374 (cond (arg
375 (ivy-immediate-done))
376 ((and ivy--directory
377 (or
378 (and
379 (not (equal ivy-text ""))
380 (file-directory-p ivy-text)
381 (setq dir (expand-file-name
382 ivy-text ivy--directory)))
383 (and
384 (not (string= ivy--current "./"))
385 (cl-plusp ivy--length)
386 (file-directory-p
387 (setq dir (expand-file-name
388 ivy--current ivy--directory))))))
389 (ivy--cd dir)
390 (ivy--exhibit))
391 ((eq (ivy-state-collection ivy-last) 'Info-read-node-name-1)
392 (if (or (equal ivy--current "(./)")
393 (equal ivy--current "(../)"))
394 (ivy-quit-and-run
395 (ivy-read "Go to file: " 'read-file-name-internal
396 :action (lambda (x)
397 (Info-find-node
398 (expand-file-name x ivy--directory)
399 "Top"))))
400 (ivy-done)))
401 ((and ivy--directory
402 (string-match "\\`/[^/]+:.*:.*\\'" ivy-text))
403 (ivy-done))
404 ((and ivy--directory
405 (string-match
406 "\\`/\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
407 ivy-text))
408 (let ((method (match-string 1 ivy-text))
409 (user (match-string 2 ivy-text))
410 (rest (match-string 3 ivy-text))
411 res)
412 (require 'tramp)
413 (dolist (x (tramp-get-completion-function method))
414 (setq res (append res (funcall (car x) (cadr x)))))
415 (setq res (delq nil res))
416 (when user
417 (dolist (x res)
418 (setcar x user)))
419 (setq res (cl-delete-duplicates res :test #'equal))
420 (let* ((old-ivy-last ivy-last)
421 (enable-recursive-minibuffers t)
422 (host (ivy-read "Find File: "
423 (mapcar #'ivy-build-tramp-name res)
424 :initial-input rest)))
425 (setq ivy-last old-ivy-last)
426 (when host
427 (setq ivy--directory "/")
428 (ivy--cd (concat "/" method ":" host ":"))))))
429 (t
430 (ivy-done)))))
431
432 (defcustom ivy-tab-space nil
433 "When non-nil, `ivy-partial-or-done' should insert a space."
434 :type 'boolean)
435
436 (defun ivy-partial-or-done ()
437 "Complete the minibuffer text as much as possible.
438 If the text hasn't changed as a result, forward to `ivy-alt-done'."
439 (interactive)
440 (if (and (eq (ivy-state-collection ivy-last) #'read-file-name-internal)
441 (string-match "\\`/" ivy-text))
442 (let ((default-directory ivy--directory))
443 (minibuffer-complete)
444 (setq ivy-text (ivy--input))
445 (when (and (file-directory-p ivy-text)
446 (= ivy--length 1))
447 (ivy--cd (expand-file-name ivy-text))))
448 (or (ivy-partial)
449 (when (or (eq this-command last-command)
450 (eq ivy--length 1))
451 (ivy-alt-done)))))
452
453 (defun ivy-partial ()
454 "Complete the minibuffer text as much as possible."
455 (interactive)
456 (let* ((parts (or (split-string ivy-text " " t) (list "")))
457 (postfix (car (last parts)))
458 (completion-ignore-case t)
459 (startp (string-match "^\\^" postfix))
460 (new (try-completion (if startp
461 (substring postfix 1)
462 postfix)
463 (mapcar (lambda (str)
464 (let ((i (string-match postfix str)))
465 (when i
466 (substring str i))))
467 ivy--old-cands))))
468 (cond ((eq new t) nil)
469 ((string= new ivy-text) nil)
470 (new
471 (delete-region (minibuffer-prompt-end) (point-max))
472 (setcar (last parts)
473 (if startp
474 (concat "^" new)
475 new))
476 (insert (mapconcat #'identity parts " ")
477 (if ivy-tab-space " " ""))
478 t))))
479
480 (defun ivy-immediate-done ()
481 "Exit the minibuffer with the current input."
482 (interactive)
483 (delete-minibuffer-contents)
484 (insert (setq ivy--current
485 (if ivy--directory
486 (expand-file-name ivy-text ivy--directory)
487 ivy-text)))
488 (setq ivy-exit 'done)
489 (exit-minibuffer))
490
491 ;;;###autoload
492 (defun ivy-resume ()
493 "Resume the last completion session."
494 (interactive)
495 (ivy-read
496 (ivy-state-prompt ivy-last)
497 (ivy-state-collection ivy-last)
498 :predicate (ivy-state-predicate ivy-last)
499 :require-match (ivy-state-require-match ivy-last)
500 :initial-input ivy-text
501 :history (ivy-state-history ivy-last)
502 :preselect (unless (eq (ivy-state-collection ivy-last)
503 'read-file-name-internal)
504 ivy--current)
505 :keymap (ivy-state-keymap ivy-last)
506 :update-fn (ivy-state-update-fn ivy-last)
507 :sort (ivy-state-sort ivy-last)
508 :action (ivy-state-action ivy-last)
509 :unwind (ivy-state-unwind ivy-last)
510 :re-builder (ivy-state-re-builder ivy-last)
511 :matcher (ivy-state-matcher ivy-last)
512 :dynamic-collection (ivy-state-dynamic-collection ivy-last)
513 :caller (ivy-state-caller ivy-last)))
514
515 (defvar ivy-calling nil
516 "When non-nil, call the current action when `ivy--index' changes.")
517
518 (defun ivy-set-index (index)
519 "Set `ivy--index' to INDEX."
520 (setq ivy--index index)
521 (when ivy-calling
522 (ivy--exhibit)
523 (ivy-call)))
524
525 (defun ivy-beginning-of-buffer ()
526 "Select the first completion candidate."
527 (interactive)
528 (ivy-set-index 0))
529
530 (defun ivy-end-of-buffer ()
531 "Select the last completion candidate."
532 (interactive)
533 (ivy-set-index (1- ivy--length)))
534
535 (defun ivy-scroll-up-command ()
536 "Scroll the candidates upward by the minibuffer height."
537 (interactive)
538 (ivy-set-index (min (+ ivy--index ivy-height)
539 (1- ivy--length))))
540
541 (defun ivy-scroll-down-command ()
542 "Scroll the candidates downward by the minibuffer height."
543 (interactive)
544 (ivy-set-index (max (- ivy--index ivy-height)
545 0)))
546
547 (defun ivy-minibuffer-grow ()
548 "Grow the minibuffer window by 1 line."
549 (interactive)
550 (setq-local max-mini-window-height
551 (cl-incf ivy-height)))
552
553 (defun ivy-minibuffer-shrink ()
554 "Shrink the minibuffer window by 1 line."
555 (interactive)
556 (unless (<= ivy-height 2)
557 (setq-local max-mini-window-height
558 (cl-decf ivy-height))
559 (window-resize (selected-window) -1)))
560
561 (defun ivy-next-line (&optional arg)
562 "Move cursor vertically down ARG candidates."
563 (interactive "p")
564 (setq arg (or arg 1))
565 (let ((index (+ ivy--index arg)))
566 (if (> index (1- ivy--length))
567 (if ivy-wrap
568 (ivy-beginning-of-buffer)
569 (ivy-set-index (1- ivy--length)))
570 (ivy-set-index index))))
571
572 (defun ivy-next-line-or-history (&optional arg)
573 "Move cursor vertically down ARG candidates.
574 If the input is empty, select the previous history element instead."
575 (interactive "p")
576 (when (string= ivy-text "")
577 (ivy-previous-history-element 1))
578 (ivy-next-line arg))
579
580 (defun ivy-previous-line (&optional arg)
581 "Move cursor vertically up ARG candidates."
582 (interactive "p")
583 (setq arg (or arg 1))
584 (let ((index (- ivy--index arg)))
585 (if (< index 0)
586 (if ivy-wrap
587 (ivy-end-of-buffer)
588 (ivy-set-index 0))
589 (ivy-set-index index))))
590
591 (defun ivy-previous-line-or-history (arg)
592 "Move cursor vertically up ARG candidates.
593 If the input is empty, select the previous history element instead."
594 (interactive "p")
595 (when (string= ivy-text "")
596 (ivy-previous-history-element 1))
597 (ivy-previous-line arg))
598
599 (defun ivy-toggle-calling ()
600 "Flip `ivy-calling'."
601 (interactive)
602 (when (setq ivy-calling (not ivy-calling))
603 (ivy-call)))
604
605 (defun ivy--get-action (state)
606 "Get the action function from STATE."
607 (let ((action (ivy-state-action state)))
608 (when action
609 (if (functionp action)
610 action
611 (cadr (nth (car action) action))))))
612
613 (defun ivy--actionp (x)
614 "Return non-nil when X is a list of actions."
615 (and x (listp x) (not (eq (car x) 'closure))))
616
617 (defun ivy-next-action ()
618 "When the current action is a list, scroll it forwards."
619 (interactive)
620 (let ((action (ivy-state-action ivy-last)))
621 (when (ivy--actionp action)
622 (unless (>= (car action) (1- (length action)))
623 (cl-incf (car action))))))
624
625 (defun ivy-prev-action ()
626 "When the current action is a list, scroll it backwards."
627 (interactive)
628 (let ((action (ivy-state-action ivy-last)))
629 (when (ivy--actionp action)
630 (unless (<= (car action) 1)
631 (cl-decf (car action))))))
632
633 (defun ivy-action-name ()
634 "Return the name associated with the current action."
635 (let ((action (ivy-state-action ivy-last)))
636 (if (ivy--actionp action)
637 (format "[%d/%d] %s"
638 (car action)
639 (1- (length action))
640 (nth 2 (nth (car action) action)))
641 "[1/1] default")))
642
643 (defun ivy-call ()
644 "Call the current action without exiting completion."
645 (interactive)
646 (let ((action (ivy--get-action ivy-last)))
647 (when action
648 (let* ((collection (ivy-state-collection ivy-last))
649 (x (if (and (consp collection)
650 (consp (car collection)))
651 (cdr (assoc ivy--current collection))
652 (if (equal ivy--current "")
653 ivy-text
654 ivy--current))))
655 (prog1 (funcall action x)
656 (unless (or (eq ivy-exit 'done)
657 (equal (selected-window)
658 (active-minibuffer-window))
659 (null (active-minibuffer-window)))
660 (select-window (active-minibuffer-window))))))))
661
662 (defun ivy-next-line-and-call (&optional arg)
663 "Move cursor vertically down ARG candidates.
664 Call the permanent action if possible."
665 (interactive "p")
666 (ivy-next-line arg)
667 (ivy--exhibit)
668 (ivy-call))
669
670 (defun ivy-previous-line-and-call (&optional arg)
671 "Move cursor vertically down ARG candidates.
672 Call the permanent action if possible."
673 (interactive "p")
674 (ivy-previous-line arg)
675 (ivy--exhibit)
676 (ivy-call))
677
678 (defun ivy-previous-history-element (arg)
679 "Forward to `previous-history-element' with ARG."
680 (interactive "p")
681 (previous-history-element arg)
682 (ivy--cd-maybe)
683 (move-end-of-line 1)
684 (ivy--maybe-scroll-history))
685
686 (defun ivy-next-history-element (arg)
687 "Forward to `next-history-element' with ARG."
688 (interactive "p")
689 (next-history-element arg)
690 (ivy--cd-maybe)
691 (move-end-of-line 1)
692 (ivy--maybe-scroll-history))
693
694 (defun ivy--cd-maybe ()
695 "Check if the current input points to a different directory.
696 If so, move to that directory, while keeping only the file name."
697 (when ivy--directory
698 (let ((input (ivy--input))
699 url)
700 (if (setq url (ffap-url-p input))
701 (progn
702 (ivy-set-action
703 (lambda (_)
704 (funcall ffap-url-fetcher url)))
705 (setq ivy-exit 'done)
706 (exit-minibuffer))
707 (setq input (expand-file-name input))
708 (let ((file (file-name-nondirectory input))
709 (dir (expand-file-name (file-name-directory input))))
710 (if (string= dir ivy--directory)
711 (progn
712 (delete-minibuffer-contents)
713 (insert file))
714 (ivy--cd dir)
715 (insert file)))))))
716
717 (defun ivy--maybe-scroll-history ()
718 "If the selected history element has an index, scroll there."
719 (let ((idx (ignore-errors
720 (get-text-property
721 (minibuffer-prompt-end)
722 'ivy-index))))
723 (when idx
724 (ivy--exhibit)
725 (setq ivy--index idx))))
726
727 (defun ivy--cd (dir)
728 "When completing file names, move to directory DIR."
729 (if (null ivy--directory)
730 (error "Unexpected")
731 (setq ivy--old-cands nil)
732 (setq ivy--old-re nil)
733 (setq ivy--index 0)
734 (setq ivy--all-candidates
735 (ivy--sorted-files (setq ivy--directory dir)))
736 (setq ivy-text "")
737 (delete-minibuffer-contents)))
738
739 (defun ivy-backward-delete-char ()
740 "Forward to `backward-delete-char'.
741 On error (read-only), call `ivy-on-del-error-function'."
742 (interactive)
743 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
744 (progn
745 (ivy--cd (file-name-directory
746 (directory-file-name
747 (expand-file-name
748 ivy--directory))))
749 (ivy--exhibit))
750 (condition-case nil
751 (backward-delete-char 1)
752 (error
753 (when ivy-on-del-error-function
754 (funcall ivy-on-del-error-function))))))
755
756 (defun ivy-delete-char (arg)
757 "Forward to `delete-char' ARG."
758 (interactive "p")
759 (unless (= (point) (line-end-position))
760 (delete-char arg)))
761
762 (defun ivy-forward-char (arg)
763 "Forward to `forward-char' ARG."
764 (interactive "p")
765 (unless (= (point) (line-end-position))
766 (forward-char arg)))
767
768 (defun ivy-kill-word (arg)
769 "Forward to `kill-word' ARG."
770 (interactive "p")
771 (unless (= (point) (line-end-position))
772 (kill-word arg)))
773
774 (defun ivy-kill-line ()
775 "Forward to `kill-line'."
776 (interactive)
777 (if (eolp)
778 (kill-region (minibuffer-prompt-end) (point))
779 (kill-line)))
780
781 (defun ivy-backward-kill-word ()
782 "Forward to `backward-kill-word'."
783 (interactive)
784 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
785 (progn
786 (ivy--cd (file-name-directory
787 (directory-file-name
788 (expand-file-name
789 ivy--directory))))
790 (ivy--exhibit))
791 (ignore-errors
792 (let ((pt (point)))
793 (forward-word -1)
794 (delete-region (point) pt)))))
795
796 (defvar ivy--regexp-quote 'regexp-quote
797 "Store the regexp quoting state.")
798
799 (defun ivy-toggle-regexp-quote ()
800 "Toggle the regexp quoting."
801 (interactive)
802 (setq ivy--old-re nil)
803 (cl-rotatef ivy--regex-function ivy--regexp-quote))
804
805 (defvar avy-all-windows)
806 (defvar avy-action)
807 (defvar avy-keys)
808 (defvar avy-keys-alist)
809 (defvar avy-style)
810 (defvar avy-styles-alist)
811 (declare-function avy--process "ext:avy")
812 (declare-function avy--style-fn "ext:avy")
813
814 (eval-after-load 'avy
815 '(add-to-list 'avy-styles-alist '(ivy-avy . pre)))
816
817 (defun ivy-avy ()
818 "Jump to one of the current ivy candidates."
819 (interactive)
820 (unless (require 'avy nil 'noerror)
821 (error "Package avy isn't installed"))
822 (let* ((avy-all-windows nil)
823 (avy-keys (or (cdr (assq 'ivy-avy avy-keys-alist))
824 avy-keys))
825 (avy-style (or (cdr (assq 'ivy-avy
826 avy-styles-alist))
827 avy-style))
828 (candidate
829 (let ((candidates))
830 (save-excursion
831 (save-restriction
832 (narrow-to-region
833 (window-start)
834 (window-end))
835 (goto-char (point-min))
836 (forward-line)
837 (while (< (point) (point-max))
838 (push
839 (cons (point)
840 (selected-window))
841 candidates)
842 (forward-line))))
843 (setq avy-action #'identity)
844 (avy--process
845 (nreverse candidates)
846 (avy--style-fn avy-style)))))
847 (ivy-set-index (- (line-number-at-pos candidate) 2))
848 (ivy--exhibit)
849 (ivy-done)))
850
851 (defun ivy-sort-file-function-default (x y)
852 "Compare two files X and Y.
853 Prioritize directories."
854 (if (get-text-property 0 'dirp x)
855 (if (get-text-property 0 'dirp y)
856 (string< x y)
857 t)
858 (if (get-text-property 0 'dirp y)
859 nil
860 (string< x y))))
861
862 (defcustom ivy-sort-functions-alist
863 '((read-file-name-internal . ivy-sort-file-function-default)
864 (internal-complete-buffer . nil)
865 (counsel-git-grep-function . nil)
866 (Man-goto-section . nil)
867 (org-refile . nil)
868 (t . string-lessp))
869 "An alist of sorting functions for each collection function.
870 Interactive functions that call completion fit in here as well.
871
872 For each entry, nil means no sorting. It's very useful to turn
873 off the sorting for functions that have candidates in the natural
874 buffer order, like `org-refile' or `Man-goto-section'.
875
876 The entry associated to t is used for all fall-through cases."
877 :type
878 '(alist
879 :key-type (choice
880 (const :tag "All other functions" t)
881 (symbol :tag "Function"))
882 :value-type (choice
883 (const :tag "plain sort" string-lessp)
884 (const :tag "file sort" ivy-sort-file-function-default)
885 (const :tag "no sort" nil)))
886 :group 'ivy)
887
888 (defvar ivy-index-functions-alist
889 '((swiper . ivy-recompute-index-swiper)
890 (swiper-multi . ivy-recompute-index-swiper)
891 (counsel-git-grep . ivy-recompute-index-swiper)
892 (t . ivy-recompute-index-zero))
893 "An alist of index recomputing functions for each collection function.
894 When the input changes, calling the appropriate function will
895 return an integer - the index of the matched candidate that
896 should be selected.")
897
898 (defvar ivy-re-builders-alist
899 '((t . ivy--regex-plus))
900 "An alist of regex building functions for each collection function.
901 Each function should take a string and return a valid regex or a
902 regex sequence (see below).
903
904 The entry associated to t is used for all fall-through cases.
905 Possible choices: `ivy--regex', `regexp-quote', `ivy--regex-plus'.
906
907 In case a function returns a list, it should look like this:
908 '((\"matching-regexp\" . t) (\"non-matching-regexp\") ...).
909
910 The matches will be filtered in a sequence, you can mix the
911 regexps that should match and that should not match as you
912 like.")
913
914 (defvar ivy-initial-inputs-alist
915 '((org-refile . "^")
916 (org-agenda-refile . "^")
917 (org-capture-refile . "^")
918 (counsel-M-x . "^")
919 (counsel-describe-function . "^")
920 (counsel-describe-variable . "^")
921 (man . "^")
922 (woman . "^"))
923 "Command to initial input table.")
924
925 (defcustom ivy-sort-max-size 30000
926 "Sorting won't be done for collections larger than this."
927 :type 'integer)
928
929 (defun ivy--sorted-files (dir)
930 "Return the list of files in DIR.
931 Directories come first."
932 (let* ((default-directory dir)
933 (seq (all-completions "" 'read-file-name-internal))
934 sort-fn)
935 (if (equal dir "/")
936 seq
937 (setq seq (delete "./" (delete "../" seq)))
938 (when (eq (setq sort-fn (cdr (assoc 'read-file-name-internal
939 ivy-sort-functions-alist)))
940 #'ivy-sort-file-function-default)
941 (setq seq (mapcar (lambda (x)
942 (propertize x 'dirp (string-match-p "/\\'" x)))
943 seq)))
944 (when sort-fn
945 (setq seq (cl-sort seq sort-fn)))
946 (dolist (dir ivy-extra-directories)
947 (push dir seq))
948 seq)))
949
950 ;;** Entry Point
951 (cl-defun ivy-read (prompt collection
952 &key predicate require-match initial-input
953 history preselect keymap update-fn sort
954 action unwind re-builder matcher dynamic-collection caller)
955 "Read a string in the minibuffer, with completion.
956
957 PROMPT is a string to prompt with; normally it ends in a colon
958 and a space. When PROMPT contains %d, it will be updated with
959 the current number of matching candidates. If % appears elsewhere
960 in the PROMPT it should be quoted as %%.
961 See also `ivy-count-format'.
962
963 COLLECTION is a list of strings, or a function, or an alist, or a
964 hash table.
965
966 If INITIAL-INPUT is non-nil, insert it in the minibuffer initially.
967
968 KEYMAP is composed together with `ivy-minibuffer-map'.
969
970 If PRESELECT is non-nil select the corresponding candidate out of
971 the ones that match INITIAL-INPUT.
972
973 UPDATE-FN is called each time the current candidate(s) is changed.
974
975 When SORT is t, refer to `ivy-sort-functions-alist' for sorting.
976
977 ACTION is a lambda to call after a result was selected. It should
978 take a single argument, usually a string.
979
980 UNWIND is a lambda to call before exiting.
981
982 RE-BUILDER is a lambda that transforms text into a regex.
983
984 MATCHER can completely override matching.
985
986 DYNAMIC-COLLECTION is a function to call to update the list of
987 candidates with each input.
988
989 CALLER is a symbol to uniquely identify the caller to `ivy-read'.
990 It's used in conjunction with COLLECTION to indentify which
991 customizations should apply to the current completion session."
992 (let ((extra-actions (plist-get ivy--actions-list this-command)))
993 (when extra-actions
994 (setq action
995 (if (functionp action)
996 `(1
997 ("o" ,action "default")
998 ,@extra-actions)
999 (delete-dups (append action extra-actions))))))
1000 (setq ivy-last
1001 (make-ivy-state
1002 :prompt prompt
1003 :collection collection
1004 :predicate predicate
1005 :require-match require-match
1006 :initial-input initial-input
1007 :history history
1008 :preselect preselect
1009 :keymap keymap
1010 :update-fn update-fn
1011 :sort sort
1012 :action action
1013 :window (selected-window)
1014 :unwind unwind
1015 :re-builder re-builder
1016 :matcher matcher
1017 :dynamic-collection dynamic-collection
1018 :caller caller))
1019 (ivy--reset-state ivy-last)
1020 (prog1
1021 (unwind-protect
1022 (minibuffer-with-setup-hook
1023 #'ivy--minibuffer-setup
1024 (let* ((hist (or history 'ivy-history))
1025 (minibuffer-completion-table collection)
1026 (minibuffer-completion-predicate predicate)
1027 (resize-mini-windows (cond
1028 ((display-graphic-p) nil)
1029 ((null resize-mini-windows) 'grow-only)
1030 (t resize-mini-windows)))
1031 (res (read-from-minibuffer
1032 prompt
1033 (ivy-state-initial-input ivy-last)
1034 (make-composed-keymap keymap ivy-minibuffer-map)
1035 nil
1036 hist)))
1037 (when (eq ivy-exit 'done)
1038 (let ((item (if ivy--directory
1039 ivy--current
1040 ivy-text)))
1041 (unless (equal item "")
1042 (set hist (cons (propertize item 'ivy-index ivy--index)
1043 (delete item
1044 (cdr (symbol-value hist)))))))
1045 res)))
1046 (remove-hook 'post-command-hook #'ivy--exhibit)
1047 (when (setq unwind (ivy-state-unwind ivy-last))
1048 (funcall unwind)))
1049 (ivy-call)))
1050
1051 (defun ivy--reset-state (state)
1052 "Reset the ivy to STATE.
1053 This is useful for recursive `ivy-read'."
1054 (let ((prompt (ivy-state-prompt state))
1055 (collection (ivy-state-collection state))
1056 (predicate (ivy-state-predicate state))
1057 (history (ivy-state-history state))
1058 (preselect (ivy-state-preselect state))
1059 (sort (ivy-state-sort state))
1060 (re-builder (ivy-state-re-builder state))
1061 (dynamic-collection (ivy-state-dynamic-collection state))
1062 (initial-input (ivy-state-initial-input state))
1063 (require-match (ivy-state-require-match state))
1064 (matcher (ivy-state-matcher state)))
1065 (unless initial-input
1066 (setq initial-input (cdr (assoc this-command
1067 ivy-initial-inputs-alist))))
1068 (setq ivy--directory nil)
1069 (setq ivy-case-fold-search 'auto)
1070 (setq ivy--regex-function
1071 (or re-builder
1072 (and (functionp collection)
1073 (cdr (assoc collection ivy-re-builders-alist)))
1074 (cdr (assoc t ivy-re-builders-alist))
1075 'ivy--regex))
1076 (setq ivy--subexps 0)
1077 (setq ivy--regexp-quote 'regexp-quote)
1078 (setq ivy--old-text "")
1079 (setq ivy--full-length nil)
1080 (setq ivy-text "")
1081 (setq ivy-calling nil)
1082 (let (coll sort-fn)
1083 (cond ((eq collection 'Info-read-node-name-1)
1084 (if (equal Info-current-file "dir")
1085 (setq coll
1086 (mapcar (lambda (x) (format "(%s)" x))
1087 (cl-delete-duplicates
1088 (all-completions "(" collection predicate)
1089 :test #'equal)))
1090 (setq coll (all-completions "" collection predicate))))
1091 ((eq collection 'read-file-name-internal)
1092 (setq ivy--directory default-directory)
1093 (require 'dired)
1094 (when preselect
1095 (let ((preselect-directory (file-name-directory preselect)))
1096 (unless (or (null preselect-directory)
1097 (string= preselect-directory
1098 default-directory))
1099 (setq ivy--directory preselect-directory))
1100 (setf
1101 (ivy-state-preselect state)
1102 (setq preselect (file-name-nondirectory preselect)))))
1103 (setq coll (ivy--sorted-files ivy--directory))
1104 (when initial-input
1105 (unless (or require-match
1106 (equal initial-input default-directory)
1107 (equal initial-input ""))
1108 (setq coll (cons initial-input coll)))
1109 (setq initial-input nil)))
1110 ((eq collection 'internal-complete-buffer)
1111 (setq coll (ivy--buffer-list "" ivy-use-virtual-buffers)))
1112 ((or (functionp collection)
1113 (byte-code-function-p collection)
1114 (vectorp collection)
1115 (and (consp collection) (listp (car collection)))
1116 (hash-table-p collection))
1117 (setq coll (all-completions "" collection predicate)))
1118 (t
1119 (setq coll collection)))
1120 (when sort
1121 (if (and (functionp collection)
1122 (setq sort-fn (assoc collection ivy-sort-functions-alist)))
1123 (when (and (setq sort-fn (cdr sort-fn))
1124 (not (eq collection 'read-file-name-internal)))
1125 (setq coll (cl-sort coll sort-fn)))
1126 (unless (eq history 'org-refile-history)
1127 (if (and (setq sort-fn (cdr (assoc t ivy-sort-functions-alist)))
1128 (<= (length coll) ivy-sort-max-size))
1129 (setq coll (cl-sort (copy-sequence coll) sort-fn))))))
1130 (when preselect
1131 (unless (or (and require-match
1132 (not (eq collection 'internal-complete-buffer)))
1133 (let ((re (regexp-quote preselect)))
1134 (cl-find-if (lambda (x) (string-match re x))
1135 coll)))
1136 (setq coll (cons preselect coll))))
1137 (setq ivy--index (or
1138 (and dynamic-collection
1139 ivy--index)
1140 (and preselect
1141 (ivy--preselect-index
1142 coll initial-input preselect matcher))
1143 0))
1144 (setq ivy--old-re nil)
1145 (setq ivy--old-cands nil)
1146 (setq ivy--all-candidates coll))
1147 (setq ivy-exit nil)
1148 (setq ivy--default (or
1149 (thing-at-point 'url)
1150 (thing-at-point 'symbol)
1151 ""))
1152 (setq ivy--prompt
1153 (cond ((string-match "%.*d" prompt)
1154 prompt)
1155 ((null ivy-count-format)
1156 (error
1157 "`ivy-count-format' can't be nil. Set it to an empty string instead"))
1158 ((string-match "%d.*%d" ivy-count-format)
1159 (let ((w (length (number-to-string
1160 (length ivy--all-candidates))))
1161 (s (copy-sequence ivy-count-format)))
1162 (string-match "%d" s)
1163 (match-end 0)
1164 (string-match "%d" s (match-end 0))
1165 (setq s (replace-match (format "%%-%dd" w) nil nil s))
1166 (string-match "%d" s)
1167 (concat (replace-match (format "%%%dd" w) nil nil s)
1168 prompt)))
1169 ((string-match "%.*d" ivy-count-format)
1170 (concat ivy-count-format prompt))
1171 (ivy--directory
1172 prompt)
1173 (t
1174 nil)))
1175 (setf (ivy-state-initial-input ivy-last) initial-input)))
1176
1177 ;;;###autoload
1178 (defun ivy-completing-read (prompt collection
1179 &optional predicate require-match initial-input
1180 history def _inherit-input-method)
1181 "Read a string in the minibuffer, with completion.
1182
1183 This is an interface that conforms to `completing-read', so that
1184 it can be used for `completing-read-function'.
1185
1186 PROMPT is a string to prompt with; normally it ends in a colon and a space.
1187 COLLECTION can be a list of strings, an alist, an obarray or a hash table.
1188 PREDICATE limits completion to a subset of COLLECTION.
1189 REQUIRE-MATCH is considered boolean. See `completing-read'.
1190 INITIAL-INPUT is a string that can be inserted into the minibuffer initially.
1191 _HISTORY is ignored for now.
1192 DEF is the default value.
1193 _INHERIT-INPUT-METHOD is ignored for now.
1194
1195 The history, defaults and input-method arguments are ignored for now."
1196 (ivy-read (replace-regexp-in-string "%" "%%" prompt)
1197 collection
1198 :predicate predicate
1199 :require-match require-match
1200 :initial-input (if (consp initial-input)
1201 (car initial-input)
1202 (if (and (stringp initial-input)
1203 (string-match "\\+" initial-input))
1204 (replace-regexp-in-string
1205 "\\+" "\\\\+" initial-input)
1206 initial-input))
1207 :preselect (if (listp def) (car def) def)
1208 :history history
1209 :keymap nil
1210 :sort
1211 (let ((sort (assoc this-command ivy-sort-functions-alist)))
1212 (if sort
1213 (cdr sort)
1214 t))))
1215
1216 ;;;###autoload
1217 (define-minor-mode ivy-mode
1218 "Toggle Ivy mode on or off.
1219 With ARG, turn Ivy mode on if arg is positive, off otherwise.
1220 Turning on Ivy mode will set `completing-read-function' to
1221 `ivy-completing-read'.
1222
1223 Global bindings:
1224 \\{ivy-mode-map}
1225
1226 Minibuffer bindings:
1227 \\{ivy-minibuffer-map}"
1228 :group 'ivy
1229 :global t
1230 :keymap ivy-mode-map
1231 :lighter " ivy"
1232 (if ivy-mode
1233 (setq completing-read-function 'ivy-completing-read)
1234 (setq completing-read-function 'completing-read-default)))
1235
1236 (defun ivy--preselect-index (candidates initial-input preselect matcher)
1237 "Return the index in CANDIDATES filtered by INITIAL-INPUT for PRESELECT.
1238 When MATCHER is non-nil it's used instead of `cl-remove-if-not'."
1239 (if initial-input
1240 (progn
1241 (setq initial-input (ivy--regex-plus initial-input))
1242 (setq candidates
1243 (if matcher
1244 (funcall matcher initial-input candidates)
1245 (cl-remove-if-not
1246 (lambda (x)
1247 (string-match initial-input x))
1248 candidates))))
1249 (when matcher
1250 (setq candidates (funcall matcher "" candidates))))
1251 (or (cl-position preselect candidates :test #'equal)
1252 (and (stringp preselect)
1253 (let ((re (regexp-quote preselect)))
1254 (cl-position-if
1255 (lambda (x)
1256 (string-match re x))
1257 candidates)))))
1258
1259 ;;* Implementation
1260 ;;** Regex
1261 (defvar ivy--regex-hash
1262 (make-hash-table :test #'equal)
1263 "Store pre-computed regex.")
1264
1265 (defun ivy--split (str)
1266 "Split STR into a list by single spaces.
1267 The remaining spaces stick to their left.
1268 This allows to \"quote\" N spaces by inputting N+1 spaces."
1269 (let ((len (length str))
1270 start0
1271 (start1 0)
1272 res s
1273 match-len)
1274 (while (and (string-match " +" str start1)
1275 (< start1 len))
1276 (setq match-len (- (match-end 0) (match-beginning 0)))
1277 (if (= match-len 1)
1278 (progn
1279 (when start0
1280 (setq start1 start0)
1281 (setq start0 nil))
1282 (push (substring str start1 (match-beginning 0)) res)
1283 (setq start1 (match-end 0)))
1284 (setq str (replace-match
1285 (make-string (1- match-len) ?\ )
1286 nil nil str))
1287 (setq start0 (or start0 start1))
1288 (setq start1 (1- (match-end 0)))))
1289 (if start0
1290 (push (substring str start0) res)
1291 (setq s (substring str start1))
1292 (unless (= (length s) 0)
1293 (push s res)))
1294 (nreverse res)))
1295
1296 (defun ivy--regex (str &optional greedy)
1297 "Re-build regex from STR in case it has a space.
1298 When GREEDY is non-nil, join words in a greedy way."
1299 (let ((hashed (unless greedy
1300 (gethash str ivy--regex-hash))))
1301 (if hashed
1302 (prog1 (cdr hashed)
1303 (setq ivy--subexps (car hashed)))
1304 (when (string-match "\\([^\\]\\|^\\)\\\\$" str)
1305 (setq str (substring str 0 -1)))
1306 (cdr (puthash str
1307 (let ((subs (ivy--split str)))
1308 (if (= (length subs) 1)
1309 (cons
1310 (setq ivy--subexps 0)
1311 (car subs))
1312 (cons
1313 (setq ivy--subexps (length subs))
1314 (mapconcat
1315 (lambda (x)
1316 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1317 x
1318 (format "\\(%s\\)" x)))
1319 subs
1320 (if greedy
1321 ".*"
1322 ".*?")))))
1323 ivy--regex-hash)))))
1324
1325 (defun ivy--regex-ignore-order (str)
1326 "Re-build regex from STR by splitting it on spaces.
1327 Ignore the order of each group."
1328 (let* ((subs (split-string str " +" t))
1329 (len (length subs)))
1330 (cl-case len
1331 (1
1332 (setq ivy--subexps 0)
1333 (car subs))
1334 (t
1335 (setq ivy--subexps len)
1336 (let ((all (mapconcat #'identity subs "\\|")))
1337 (mapconcat
1338 (lambda (x)
1339 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1340 x
1341 (format "\\(%s\\)" x)))
1342 (make-list len all)
1343 ".*?"))))))
1344
1345 (defun ivy--regex-plus (str)
1346 "Build a regex sequence from STR.
1347 Spaces are wild, everything before \"!\" should match.
1348 Everything after \"!\" should not match."
1349 (let ((parts (split-string str "!" t)))
1350 (cl-case (length parts)
1351 (0
1352 "")
1353 (1
1354 (ivy--regex (car parts)))
1355 (2
1356 (let ((res
1357 (mapcar #'list
1358 (split-string (cadr parts) " " t))))
1359 (cons (cons (ivy--regex (car parts)) t)
1360 res)))
1361 (t (error "Unexpected: use only one !")))))
1362
1363 (defun ivy--regex-fuzzy (str)
1364 "Build a regex sequence from STR.
1365 Insert .* between each char."
1366 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1367 (prog1
1368 (concat (match-string 1 str)
1369 (mapconcat
1370 (lambda (x)
1371 (format "\\(%c\\)" x))
1372 (string-to-list (match-string 2 str)) ".*")
1373 (match-string 3 str))
1374 (setq ivy--subexps (length (match-string 2 str))))
1375 str))
1376
1377 ;;** Rest
1378 (defun ivy--minibuffer-setup ()
1379 "Setup ivy completion in the minibuffer."
1380 (set (make-local-variable 'completion-show-inline-help) nil)
1381 (set (make-local-variable 'minibuffer-default-add-function)
1382 (lambda ()
1383 (list ivy--default)))
1384 (when (display-graphic-p)
1385 (setq truncate-lines t))
1386 (setq-local max-mini-window-height ivy-height)
1387 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1388 ;; show completions with empty input
1389 (ivy--exhibit))
1390
1391 (defun ivy--input ()
1392 "Return the current minibuffer input."
1393 ;; assume one-line minibuffer input
1394 (buffer-substring-no-properties
1395 (minibuffer-prompt-end)
1396 (line-end-position)))
1397
1398 (defun ivy--cleanup ()
1399 "Delete the displayed completion candidates."
1400 (save-excursion
1401 (goto-char (minibuffer-prompt-end))
1402 (delete-region (line-end-position) (point-max))))
1403
1404 (defun ivy--insert-prompt ()
1405 "Update the prompt according to `ivy--prompt'."
1406 (when ivy--prompt
1407 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1408 counsel-find-symbol))
1409 (setq ivy--prompt-extra ""))
1410 (let (head tail)
1411 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1412 (progn
1413 (setq head (match-string 1 ivy--prompt))
1414 (setq tail ": "))
1415 (setq head (substring ivy--prompt 0 -1))
1416 (setq tail " "))
1417 (let ((inhibit-read-only t)
1418 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1419 (n-str
1420 (concat
1421 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1422 (> (minibuffer-depth) 1))
1423 (format "[%d] " (minibuffer-depth))
1424 "")
1425 (concat
1426 (if (string-match "%d.*%d" ivy-count-format)
1427 (format head
1428 (1+ ivy--index)
1429 (or (and (ivy-state-dynamic-collection ivy-last)
1430 ivy--full-length)
1431 ivy--length))
1432 (format head
1433 (or (and (ivy-state-dynamic-collection ivy-last)
1434 ivy--full-length)
1435 ivy--length)))
1436 ivy--prompt-extra
1437 tail)))
1438 (d-str (if ivy--directory
1439 (abbreviate-file-name ivy--directory)
1440 "")))
1441 (save-excursion
1442 (goto-char (point-min))
1443 (delete-region (point-min) (minibuffer-prompt-end))
1444 (if (> (+ (mod (+ (length n-str) (length d-str)) (window-width))
1445 (length ivy-text))
1446 (window-width))
1447 (setq n-str (concat n-str "\n" d-str))
1448 (setq n-str (concat n-str d-str)))
1449 (let ((regex (format "\\([^\n]\\{%d\\}\\)[^\n]" (window-width))))
1450 (while (string-match regex n-str)
1451 (setq n-str (replace-match (concat (match-string 1 n-str) "\n") nil t n-str 1))))
1452 (set-text-properties 0 (length n-str)
1453 `(face minibuffer-prompt ,@std-props)
1454 n-str)
1455 (ivy--set-match-props n-str "confirm"
1456 `(face ivy-confirm-face ,@std-props))
1457 (ivy--set-match-props n-str "match required"
1458 `(face ivy-match-required-face ,@std-props))
1459 (insert n-str))
1460 ;; get out of the prompt area
1461 (constrain-to-field nil (point-max))))))
1462
1463 (defun ivy--set-match-props (str match props)
1464 "Set STR text proprties that match MATCH to PROPS."
1465 (when (string-match match str)
1466 (set-text-properties
1467 (match-beginning 0)
1468 (match-end 0)
1469 props
1470 str)))
1471
1472 (defvar inhibit-message)
1473
1474 (defun ivy--sort-maybe (collection)
1475 "Sort COLLECTION if needed."
1476 (let ((sort (ivy-state-sort ivy-last))
1477 entry)
1478 (if (null sort)
1479 collection
1480 (let ((sort-fn (cond ((functionp sort)
1481 sort)
1482 ((setq entry (assoc (ivy-state-collection ivy-last)
1483 ivy-sort-functions-alist))
1484 (cdr entry))
1485 (t
1486 (cdr (assoc t ivy-sort-functions-alist))))))
1487 (if (functionp sort-fn)
1488 (cl-sort (copy-sequence collection) sort-fn)
1489 collection)))))
1490
1491 (defun ivy--exhibit ()
1492 "Insert Ivy completions display.
1493 Should be run via minibuffer `post-command-hook'."
1494 (when (memq 'ivy--exhibit post-command-hook)
1495 (let ((inhibit-field-text-motion nil))
1496 (constrain-to-field nil (point-max)))
1497 (setq ivy-text (ivy--input))
1498 (if (ivy-state-dynamic-collection ivy-last)
1499 ;; while-no-input would cause annoying
1500 ;; "Waiting for process to die...done" message interruptions
1501 (let ((inhibit-message t))
1502 (unless (equal ivy--old-text ivy-text)
1503 (while-no-input
1504 (setq ivy--all-candidates
1505 (ivy--sort-maybe
1506 (funcall (ivy-state-collection ivy-last) ivy-text)))
1507 (setq ivy--old-text ivy-text)))
1508 (when ivy--all-candidates
1509 (ivy--insert-minibuffer
1510 (ivy--format ivy--all-candidates))))
1511 (cond (ivy--directory
1512 (if (string-match "/\\'" ivy-text)
1513 (if (member ivy-text ivy--all-candidates)
1514 (ivy--cd (expand-file-name ivy-text ivy--directory))
1515 (when (string-match "//\\'" ivy-text)
1516 (if (and default-directory
1517 (string-match "\\`[[:alpha:]]:/" default-directory))
1518 (ivy--cd (match-string 0 default-directory))
1519 (ivy--cd "/")))
1520 (when (string-match "[[:alpha:]]:/$" ivy-text)
1521 (let ((drive-root (match-string 0 ivy-text)))
1522 (when (file-exists-p drive-root)
1523 (ivy--cd drive-root)))))
1524 (if (string-match "\\`~\\'" ivy-text)
1525 (ivy--cd (expand-file-name "~/")))))
1526 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1527 (when (or (and (string-match "\\` " ivy-text)
1528 (not (string-match "\\` " ivy--old-text)))
1529 (and (string-match "\\` " ivy--old-text)
1530 (not (string-match "\\` " ivy-text))))
1531 (setq ivy--all-candidates
1532 (if (and (> (length ivy-text) 0)
1533 (eq (aref ivy-text 0)
1534 ?\ ))
1535 (ivy--buffer-list " ")
1536 (ivy--buffer-list "" ivy-use-virtual-buffers)))
1537 (setq ivy--old-re nil))))
1538 (ivy--insert-minibuffer
1539 (ivy--format
1540 (ivy--filter ivy-text ivy--all-candidates)))
1541 (setq ivy--old-text ivy-text))))
1542
1543 (defun ivy--insert-minibuffer (text)
1544 "Insert TEXT into minibuffer with appropriate cleanup."
1545 (let ((resize-mini-windows nil)
1546 (update-fn (ivy-state-update-fn ivy-last))
1547 deactivate-mark)
1548 (ivy--cleanup)
1549 (when update-fn
1550 (funcall update-fn))
1551 (ivy--insert-prompt)
1552 ;; Do nothing if while-no-input was aborted.
1553 (when (stringp text)
1554 (let ((buffer-undo-list t))
1555 (save-excursion
1556 (forward-line 1)
1557 (insert text))))
1558 (when (display-graphic-p)
1559 (ivy--resize-minibuffer-to-fit))))
1560
1561 (defun ivy--resize-minibuffer-to-fit ()
1562 "Resize the minibuffer window so it has enough space to display
1563 all of the text contained in the minibuffer."
1564 (with-selected-window (minibuffer-window)
1565 (if (fboundp 'window-text-pixel-size)
1566 (let ((text-height (cdr (window-text-pixel-size)))
1567 (body-height (window-body-height nil t)))
1568 (when (> text-height body-height)
1569 (window-resize nil (- text-height body-height) nil t t)))
1570 (let ((text-height (count-screen-lines))
1571 (body-height (window-body-height)))
1572 (when (> text-height body-height)
1573 (window-resize nil (- text-height body-height) nil t))))))
1574
1575 (declare-function colir-blend-face-background "ext:colir")
1576
1577 (defun ivy--add-face (str face)
1578 "Propertize STR with FACE.
1579 `font-lock-append-text-property' is used, since it's better than
1580 `propertize' or `add-face-text-property' in this case."
1581 (require 'colir)
1582 (condition-case nil
1583 (progn
1584 (colir-blend-face-background 0 (length str) face str)
1585 (let ((foreground (face-foreground face)))
1586 (when foreground
1587 (add-face-text-property
1588 0 (length str)
1589 `(:foreground ,foreground)
1590 nil
1591 str))))
1592 (error
1593 (ignore-errors
1594 (font-lock-append-text-property 0 (length str) 'face face str))))
1595 str)
1596
1597 (declare-function flx-make-string-cache "ext:flx")
1598 (declare-function flx-score "ext:flx")
1599
1600 (defvar ivy--flx-cache nil)
1601
1602 (eval-after-load 'flx
1603 '(setq ivy--flx-cache (flx-make-string-cache)))
1604
1605 (defun ivy-toggle-case-fold ()
1606 "Toggle the case folding between nil and auto.
1607 In any completion session, the case folding starts in auto:
1608
1609 - when the input is all lower case, `case-fold-search' is t
1610 - otherwise it's nil.
1611
1612 You can toggle this to make `case-fold-search' nil regardless of input."
1613 (interactive)
1614 (setq ivy-case-fold-search
1615 (if ivy-case-fold-search
1616 nil
1617 'auto))
1618 ;; reset cache so that the candidate list updates
1619 (setq ivy--old-re nil))
1620
1621 (defun ivy--filter (name candidates)
1622 "Return all items that match NAME in CANDIDATES.
1623 CANDIDATES are assumed to be static."
1624 (let ((re (funcall ivy--regex-function name)))
1625 (if (and (equal re ivy--old-re)
1626 ivy--old-cands)
1627 ;; quick caching for "C-n", "C-p" etc.
1628 ivy--old-cands
1629 (let* ((re-str (if (listp re) (caar re) re))
1630 (matcher (ivy-state-matcher ivy-last))
1631 (case-fold-search
1632 (and ivy-case-fold-search
1633 (string= name (downcase name))))
1634 (cands (cond
1635 (matcher
1636 (funcall matcher re candidates))
1637 ((and ivy--old-re
1638 (stringp re)
1639 (stringp ivy--old-re)
1640 (not (string-match "\\\\" ivy--old-re))
1641 (not (equal ivy--old-re ""))
1642 (memq (cl-search
1643 (if (string-match "\\\\)\\'" ivy--old-re)
1644 (substring ivy--old-re 0 -2)
1645 ivy--old-re)
1646 re)
1647 '(0 2)))
1648 (ignore-errors
1649 (cl-remove-if-not
1650 (lambda (x) (string-match re x))
1651 ivy--old-cands)))
1652 (t
1653 (let ((re-list (if (stringp re) (list (cons re t)) re))
1654 (res candidates))
1655 (dolist (re re-list)
1656 (setq res
1657 (ignore-errors
1658 (funcall
1659 (if (cdr re)
1660 #'cl-remove-if-not
1661 #'cl-remove-if)
1662 (let ((re-str (car re)))
1663 (lambda (x) (string-match re-str x)))
1664 res))))
1665 res)))))
1666 (ivy--recompute-index name re-str cands)
1667 (setq ivy--old-re (if cands re-str ""))
1668 (when (and (require 'flx nil 'noerror)
1669 (eq ivy--regex-function 'ivy--regex-fuzzy))
1670 (setq cands (ivy--flx-sort name cands)))
1671 (setq ivy--old-cands cands)))))
1672
1673 (defun ivy--recompute-index (name re-str cands)
1674 (let* ((caller (ivy-state-caller ivy-last))
1675 (func (or (and caller (cdr (assoc caller ivy-index-functions-alist)))
1676 (cdr (assoc t ivy-index-functions-alist))
1677 #'ivy-recompute-index-zero)))
1678 (unless (eq this-command 'ivy-resume)
1679 (setq ivy--index
1680 (or
1681 (cl-position (if (and (> (length re-str) 0)
1682 (eq ?^ (aref re-str 0)))
1683 (substring re-str 1)
1684 re-str) cands
1685 :test #'equal)
1686 (and ivy--directory
1687 (cl-position
1688 (concat re-str "/") cands
1689 :test #'equal))
1690 (and (not (string= name ""))
1691 (not (and (require 'flx nil 'noerror)
1692 (eq ivy--regex-function 'ivy--regex-fuzzy)
1693 (< (length cands) 200)))
1694
1695 (cl-position (nth ivy--index ivy--old-cands)
1696 cands))
1697 (funcall func re-str cands))))
1698 (when (and (or (string= name "")
1699 (string= name "^"))
1700 (not (equal ivy--old-re "")))
1701 (setq ivy--index
1702 (or (ivy--preselect-index
1703 cands
1704 nil
1705 (ivy-state-preselect ivy-last)
1706 nil)
1707 ivy--index)))))
1708
1709 (defun ivy-recompute-index-swiper (_re-str cands)
1710 (let ((tail (nthcdr ivy--index ivy--old-cands))
1711 idx)
1712 (if (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
1713 (progn
1714 (while (and tail (null idx))
1715 ;; Compare with eq to handle equal duplicates in cands
1716 (setq idx (cl-position (pop tail) cands)))
1717 (or idx 0))
1718 ivy--index)))
1719
1720 (defun ivy-recompute-index-zero (_re-str _cands)
1721 0)
1722
1723 (defun ivy--flx-sort (name cands)
1724 "Sort according to closeness to string NAME the string list CANDS."
1725 (condition-case nil
1726 (if (and cands
1727 (< (length cands) 200))
1728 (let* ((flx-name (if (string-match "^\\^" name)
1729 (substring name 1)
1730 name))
1731 (cands-with-score
1732 (delq nil
1733 (mapcar
1734 (lambda (x)
1735 (let ((score (car (flx-score x flx-name ivy--flx-cache))))
1736 (and score
1737 (cons score x))))
1738 cands))))
1739 (if cands-with-score
1740 (mapcar #'cdr
1741 (sort cands-with-score
1742 (lambda (x y)
1743 (> (car x) (car y)))))
1744 cands))
1745 cands)
1746 (error
1747 cands)))
1748
1749 (defvar ivy-format-function 'ivy-format-function-default
1750 "Function to transform the list of candidates into a string.
1751 This string will be inserted into the minibuffer.")
1752
1753 (defun ivy-format-function-default (cands)
1754 "Transform CANDS into a string for minibuffer."
1755 (if (bound-and-true-p truncate-lines)
1756 (mapconcat #'identity cands "\n")
1757 (let ((ww (- (window-width)
1758 (if (and (boundp 'fringe-mode) (eq fringe-mode 0)) 1 0))))
1759 (mapconcat
1760 (if truncate-lines
1761 (lambda (s)
1762 (if (> (length s) ww)
1763 (concat (substring s 0 (- ww 3)) "...")
1764 s))
1765 #'identity)
1766 cands "\n"))))
1767
1768 (defun ivy-format-function-arrow (cands)
1769 "Transform CANDS into a string for minibuffer."
1770 (let ((i -1))
1771 (mapconcat
1772 (lambda (s)
1773 (concat (if (eq (cl-incf i) ivy--index)
1774 "> "
1775 " ")
1776 s))
1777 cands "\n")))
1778
1779 (defface ivy-minibuffer-match-face-1
1780 '((((class color) (background light))
1781 :background "#d3d3d3")
1782 (((class color) (background dark))
1783 :background "#555555"))
1784 "The background face for `ivy' minibuffer matches.")
1785
1786 (defface ivy-minibuffer-match-face-2
1787 '((((class color) (background light))
1788 :background "#e99ce8" :weight bold)
1789 (((class color) (background dark))
1790 :background "#777777" :weight bold))
1791 "Face for `ivy' minibuffer matches modulo 1.")
1792
1793 (defface ivy-minibuffer-match-face-3
1794 '((((class color) (background light))
1795 :background "#bbbbff" :weight bold)
1796 (((class color) (background dark))
1797 :background "#7777ff" :weight bold))
1798 "Face for `ivy' minibuffer matches modulo 2.")
1799
1800 (defface ivy-minibuffer-match-face-4
1801 '((((class color) (background light))
1802 :background "#ffbbff" :weight bold)
1803 (((class color) (background dark))
1804 :background "#8a498a" :weight bold))
1805 "Face for `ivy' minibuffer matches modulo 3.")
1806
1807 (defcustom ivy-minibuffer-faces
1808 '(ivy-minibuffer-match-face-1
1809 ivy-minibuffer-match-face-2
1810 ivy-minibuffer-match-face-3
1811 ivy-minibuffer-match-face-4)
1812 "List of `ivy' faces for minibuffer group matches.")
1813
1814 (defun ivy--format-minibuffer-line (str)
1815 (let ((start 0)
1816 (str (copy-sequence str)))
1817 (when (eq ivy-display-style 'fancy)
1818 (unless ivy--old-re
1819 (setq ivy--old-re (funcall ivy--regex-function ivy-text)))
1820 (while (and (string-match ivy--old-re str start)
1821 (> (- (match-end 0) (match-beginning 0)) 0))
1822 (setq start (match-end 0))
1823 (let ((i 0))
1824 (while (<= i ivy--subexps)
1825 (let ((face
1826 (cond ((zerop ivy--subexps)
1827 (cadr ivy-minibuffer-faces))
1828 ((zerop i)
1829 (car ivy-minibuffer-faces))
1830 (t
1831 (nth (1+ (mod (+ i 2) (1- (length ivy-minibuffer-faces))))
1832 ivy-minibuffer-faces)))))
1833 (if (fboundp 'add-face-text-property)
1834 (add-face-text-property
1835 (match-beginning i)
1836 (match-end i)
1837 face
1838 nil
1839 str)
1840 (font-lock-append-text-property
1841 (match-beginning i)
1842 (match-end i)
1843 'face
1844 face
1845 str)))
1846 (cl-incf i)))))
1847 str))
1848
1849 (defun ivy--format (cands)
1850 "Return a string for CANDS suitable for display in the minibuffer.
1851 CANDS is a list of strings."
1852 (setq ivy--length (length cands))
1853 (when (>= ivy--index ivy--length)
1854 (setq ivy--index (max (1- ivy--length) 0)))
1855 (if (null cands)
1856 (setq ivy--current "")
1857 (let* ((half-height (/ ivy-height 2))
1858 (start (max 0 (- ivy--index half-height)))
1859 (end (min (+ start (1- ivy-height)) ivy--length))
1860 (start (max 0 (min start (- end (1- ivy-height)))))
1861 (cands (cl-subseq cands start end))
1862 (index (- ivy--index start)))
1863 (when ivy--directory
1864 (setq cands (mapcar (lambda (x)
1865 (if (string-match-p "/\\'" x)
1866 (propertize x 'face 'ivy-subdir)
1867 x))
1868 cands)))
1869 (setq ivy--current (copy-sequence (nth index cands)))
1870 (setq cands (mapcar
1871 #'ivy--format-minibuffer-line
1872 cands))
1873 (setf (nth index cands)
1874 (ivy--add-face (nth index cands) 'ivy-current-match))
1875 (let* ((ivy--index index)
1876 (res (concat "\n" (funcall ivy-format-function cands))))
1877 (put-text-property 0 (length res) 'read-only nil res)
1878 res))))
1879
1880 (defvar ivy--virtual-buffers nil
1881 "Store the virtual buffers alist.")
1882
1883 (defvar recentf-list)
1884
1885 (defface ivy-virtual '((t :inherit font-lock-builtin-face))
1886 "Face used by Ivy for matching virtual buffer names.")
1887
1888 (defcustom ivy-virtual-abbreviate 'name
1889 "The mode of abbreviation for virtual buffer names."
1890 :type '(choice
1891 (const :tag "Only name" name)
1892 (const :tag "Full path" full)
1893 ;; eventually, uniquify
1894 ))
1895
1896 (defun ivy--virtual-buffers ()
1897 "Adapted from `ido-add-virtual-buffers-to-list'."
1898 (unless recentf-mode
1899 (recentf-mode 1))
1900 (let ((bookmarks (and (boundp 'bookmark-alist)
1901 bookmark-alist))
1902 virtual-buffers name)
1903 (dolist (head (append
1904 recentf-list
1905 (delete " - no file -"
1906 (delq nil (mapcar (lambda (bookmark)
1907 (cdr (assoc 'filename bookmark)))
1908 bookmarks)))))
1909 (setq name
1910 (if (eq ivy-virtual-abbreviate 'name)
1911 (file-name-nondirectory head)
1912 (expand-file-name head)))
1913 (when (equal name "")
1914 (setq name (file-name-nondirectory (directory-file-name head))))
1915 (when (equal name "")
1916 (setq name head))
1917 (and (not (equal name ""))
1918 (null (get-file-buffer head))
1919 (not (assoc name virtual-buffers))
1920 (push (cons name head) virtual-buffers)))
1921 (when virtual-buffers
1922 (dolist (comp virtual-buffers)
1923 (put-text-property 0 (length (car comp))
1924 'face 'ivy-virtual
1925 (car comp)))
1926 (setq ivy--virtual-buffers (nreverse virtual-buffers))
1927 (mapcar #'car ivy--virtual-buffers))))
1928
1929 (defun ivy--buffer-list (str &optional virtual)
1930 "Return the buffers that match STR.
1931 When VIRTUAL is non-nil, add virtual buffers."
1932 (delete-dups
1933 (append
1934 (mapcar
1935 (lambda (x)
1936 (if (with-current-buffer x
1937 (file-remote-p
1938 (abbreviate-file-name default-directory)))
1939 (propertize x 'face 'ivy-remote)
1940 x))
1941 (all-completions str 'internal-complete-buffer))
1942 (and virtual
1943 (ivy--virtual-buffers)))))
1944
1945 (defun ivy--switch-buffer-action (buffer)
1946 "Switch to BUFFER.
1947 BUFFER may be a string or nil."
1948 (with-ivy-window
1949 (if (zerop (length buffer))
1950 (switch-to-buffer
1951 ivy-text nil 'force-same-window)
1952 (let ((virtual (assoc buffer ivy--virtual-buffers)))
1953 (if (and virtual
1954 (not (get-buffer buffer)))
1955 (find-file (cdr virtual))
1956 (switch-to-buffer
1957 buffer nil 'force-same-window))))))
1958
1959 (defun ivy--switch-buffer-other-window-action (buffer)
1960 "Switch to BUFFER in other window.
1961 BUFFER may be a string or nil."
1962 (if (zerop (length buffer))
1963 (switch-to-buffer-other-window ivy-text)
1964 (let ((virtual (assoc buffer ivy--virtual-buffers)))
1965 (if (and virtual
1966 (not (get-buffer buffer)))
1967 (find-file-other-window (cdr virtual))
1968 (switch-to-buffer-other-window buffer)))))
1969
1970 (defun ivy--rename-buffer-action (buffer)
1971 "Rename BUFFER."
1972 (let ((new-name (read-string "Rename buffer (to new name): ")))
1973 (with-current-buffer buffer
1974 (rename-buffer new-name))))
1975
1976 (defvar ivy-switch-buffer-map (make-sparse-keymap))
1977
1978 (ivy-set-actions
1979 'ivy-switch-buffer
1980 '(("k"
1981 (lambda (x)
1982 (kill-buffer x)
1983 (ivy--reset-state ivy-last))
1984 "kill")
1985 ("j"
1986 ivy--switch-buffer-other-window-action
1987 "other")
1988 ("r"
1989 ivy--rename-buffer-action
1990 "rename")))
1991
1992 ;;;###autoload
1993 (defun ivy-switch-buffer ()
1994 "Switch to another buffer."
1995 (interactive)
1996 (if (not ivy-mode)
1997 (call-interactively 'switch-to-buffer)
1998 (let ((this-command 'ivy-switch-buffer))
1999 (ivy-read "Switch to buffer: " 'internal-complete-buffer
2000 :preselect (buffer-name (other-buffer (current-buffer)))
2001 :action #'ivy--switch-buffer-action
2002 :keymap ivy-switch-buffer-map))))
2003
2004 ;;;###autoload
2005 (defun ivy-recentf ()
2006 "Find a file on `recentf-list'."
2007 (interactive)
2008 (ivy-read "Recentf: " recentf-list
2009 :action
2010 (lambda (f)
2011 (with-ivy-window
2012 (find-file f)))))
2013
2014 (defun ivy-yank-word ()
2015 "Pull next word from buffer into search string."
2016 (interactive)
2017 (let (amend)
2018 (with-ivy-window
2019 (let ((pt (point))
2020 (le (line-end-position)))
2021 (forward-word 1)
2022 (if (> (point) le)
2023 (goto-char pt)
2024 (setq amend (buffer-substring-no-properties pt (point))))))
2025 (when amend
2026 (insert (replace-regexp-in-string " +" " " amend)))))
2027
2028 (defun ivy-kill-ring-save ()
2029 "Store the current candidates into the kill ring.
2030 If the region is active, forward to `kill-ring-save' instead."
2031 (interactive)
2032 (if (region-active-p)
2033 (call-interactively 'kill-ring-save)
2034 (kill-new
2035 (mapconcat
2036 #'identity
2037 ivy--old-cands
2038 "\n"))))
2039
2040 (defun ivy-insert-current ()
2041 "Make the current candidate into current input.
2042 Don't finish completion."
2043 (interactive)
2044 (delete-minibuffer-contents)
2045 (if (and ivy--directory
2046 (string-match "/$" ivy--current))
2047 (insert (substring ivy--current 0 -1))
2048 (insert ivy--current)))
2049
2050 (defun ivy-toggle-fuzzy ()
2051 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
2052 (interactive)
2053 (setq ivy--old-re nil)
2054 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
2055 (setq ivy--regex-function 'ivy--regex-plus)
2056 (setq ivy--regex-function 'ivy--regex-fuzzy)))
2057
2058 (defun ivy-reverse-i-search ()
2059 "Enter a recursive `ivy-read' session using the current history.
2060 The selected history element will be inserted into the minibufer."
2061 (interactive)
2062 (let ((enable-recursive-minibuffers t)
2063 (history (symbol-value (ivy-state-history ivy-last)))
2064 (old-last ivy-last))
2065 (ivy-read "Reverse-i-search: "
2066 history
2067 :action (lambda (x)
2068 (ivy--reset-state
2069 (setq ivy-last old-last))
2070 (delete-minibuffer-contents)
2071 (insert (substring-no-properties x))
2072 (ivy--cd-maybe)))))
2073
2074 (defun ivy-restrict-to-matches ()
2075 "Restrict candidates to current matches and erase input."
2076 (interactive)
2077 (delete-minibuffer-contents)
2078 (setq ivy--all-candidates
2079 (ivy--filter ivy-text ivy--all-candidates)))
2080
2081 (provide 'ivy)
2082
2083 ;;; ivy.el ends here