]> code.delx.au - gnu-emacs-elpa/blob - packages/swiper/ivy.el
Merge commit 'e9530990914c1d81889269b4a8365b8003625557' from swiper
[gnu-emacs-elpa] / packages / swiper / 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
41 ;;* Customization
42 (defgroup ivy nil
43 "Incremental vertical completion."
44 :group 'convenience)
45
46 (defface ivy-current-match
47 '((t (:inherit highlight)))
48 "Face used by Ivy for highlighting first match.")
49
50 (defface ivy-confirm-face
51 '((t :foreground "ForestGreen" :inherit minibuffer-prompt))
52 "Face used by Ivy to issue a confirmation prompt.")
53
54 (defface ivy-match-required-face
55 '((t :foreground "red" :inherit minibuffer-prompt))
56 "Face used by Ivy to issue a match required prompt.")
57
58 (defface ivy-subdir
59 '((t (:inherit 'dired-directory)))
60 "Face used by Ivy for highlighting subdirs in the alternatives.")
61
62 (defface ivy-remote
63 '((t (:foreground "#110099")))
64 "Face used by Ivy for highlighting remotes in the alternatives.")
65
66 (defcustom ivy-height 10
67 "Number of lines for the minibuffer window."
68 :type 'integer)
69
70 (defcustom ivy-count-format "%-4d "
71 "The style of showing the current candidate count for `ivy-read'.
72 Set this to nil if you don't want the count."
73 :type 'string)
74
75 (defcustom ivy-wrap nil
76 "Whether to wrap around after the first and last candidate."
77 :type 'boolean)
78
79 (defcustom ivy-on-del-error-function 'minibuffer-keyboard-quit
80 "The handler for when `ivy-backward-delete-char' throws.
81 This is usually meant as a quick exit out of the minibuffer."
82 :type 'function)
83
84 (defcustom ivy-extra-directories '("../" "./")
85 "Add this to the front of the list when completing file names.
86 Only \"./\" and \"../\" apply here. They appear in reverse order."
87 :type 'list)
88
89 (defcustom ivy-use-virtual-buffers nil
90 "When non-nil, add `recentf-mode' and bookmarks to the list of buffers."
91 :type 'boolean)
92
93 ;;* Keymap
94 (require 'delsel)
95 (defvar ivy-minibuffer-map
96 (let ((map (make-sparse-keymap)))
97 (define-key map (kbd "C-m") 'ivy-done)
98 (define-key map (kbd "C-j") 'ivy-alt-done)
99 (define-key map (kbd "TAB") 'ivy-partial-or-done)
100 (define-key map (kbd "C-n") 'ivy-next-line)
101 (define-key map (kbd "C-p") 'ivy-previous-line)
102 (define-key map (kbd "<down>") 'ivy-next-line)
103 (define-key map (kbd "<up>") 'ivy-previous-line)
104 (define-key map (kbd "C-s") 'ivy-next-line-or-history)
105 (define-key map (kbd "C-r") 'ivy-reverse-i-search)
106 (define-key map (kbd "SPC") 'self-insert-command)
107 (define-key map (kbd "DEL") 'ivy-backward-delete-char)
108 (define-key map (kbd "M-DEL") 'ivy-backward-kill-word)
109 (define-key map (kbd "C-d") 'ivy-delete-char)
110 (define-key map (kbd "C-f") 'ivy-forward-char)
111 (define-key map (kbd "M-d") 'ivy-kill-word)
112 (define-key map (kbd "M-<") 'ivy-beginning-of-buffer)
113 (define-key map (kbd "M->") 'ivy-end-of-buffer)
114 (define-key map (kbd "<left>") 'ivy-beginning-of-buffer)
115 (define-key map (kbd "<right>") 'ivy-end-of-buffer)
116 (define-key map (kbd "M-n") 'ivy-next-history-element)
117 (define-key map (kbd "M-p") 'ivy-previous-history-element)
118 (define-key map (kbd "C-g") 'minibuffer-keyboard-quit)
119 (define-key map (kbd "C-v") 'ivy-scroll-up-command)
120 (define-key map (kbd "M-v") 'ivy-scroll-down-command)
121 (define-key map (kbd "C-M-n") 'ivy-next-line-and-call)
122 (define-key map (kbd "C-M-p") 'ivy-previous-line-and-call)
123 (define-key map (kbd "M-q") 'ivy-toggle-regexp-quote)
124 (define-key map (kbd "M-j") 'ivy-yank-word)
125 (define-key map (kbd "M-i") 'ivy-insert-current)
126 (define-key map (kbd "C-o") 'hydra-ivy/body)
127 (define-key map (kbd "C-k") 'ivy-kill-line)
128 map)
129 "Keymap used in the minibuffer.")
130 (autoload 'hydra-ivy/body "ivy-hydra" "" t)
131
132 (defvar ivy-mode-map
133 (let ((map (make-sparse-keymap)))
134 (define-key map [remap switch-to-buffer] 'ivy-switch-buffer)
135 map)
136 "Keymap for `ivy-mode'.")
137
138 ;;* Globals
139 (cl-defstruct ivy-state
140 prompt collection
141 predicate require-match initial-input
142 history preselect keymap update-fn sort
143 ;; The window in which `ivy-read' was called
144 window
145 action
146 unwind
147 re-builder
148 matcher
149 ;; When this is non-nil, call it for each input change to get new candidates
150 dynamic-collection)
151
152 (defvar ivy-last nil
153 "The last parameters passed to `ivy-read'.")
154
155 (defsubst ivy-set-action (action)
156 (setf (ivy-state-action ivy-last) action))
157
158 (defvar ivy-history nil
159 "History list of candidates entered in the minibuffer.
160
161 Maximum length of the history list is determined by the value
162 of `history-length', which see.")
163
164 (defvar ivy--directory nil
165 "Current directory when completing file names.")
166
167 (defvar ivy--length 0
168 "Store the amount of viable candidates.")
169
170 (defvar ivy-text ""
171 "Store the user's string as it is typed in.")
172
173 (defvar ivy--current ""
174 "Current candidate.")
175
176 (defvar ivy--index 0
177 "Store the index of the current candidate.")
178
179 (defvar ivy-exit nil
180 "Store 'done if the completion was successfully selected.
181 Otherwise, store nil.")
182
183 (defvar ivy--all-candidates nil
184 "Store the candidates passed to `ivy-read'.")
185
186 (defvar ivy--default nil
187 "Default initial input.")
188
189 (defvar ivy--prompt nil
190 "Store the format-style prompt.
191 When non-nil, it should contain one %d.")
192
193 (defvar ivy--prompt-extra ""
194 "Temporary modifications to the prompt.")
195
196 (defvar ivy--old-re nil
197 "Store the old regexp.")
198
199 (defvar ivy--old-cands nil
200 "Store the candidates matched by `ivy--old-re'.")
201
202 (defvar ivy--regex-function 'ivy--regex
203 "Current function for building a regex.")
204
205 (defvar ivy--subexps 0
206 "Number of groups in the current `ivy--regex'.")
207
208 (defvar ivy--full-length nil
209 "When :dynamic-collection is non-nil, this can be the total amount of candidates.")
210
211 (defvar ivy--old-text ""
212 "Store old `ivy-text' for dynamic completion.")
213
214 (defvar Info-current-file)
215
216 (defmacro ivy-quit-and-run (&rest body)
217 "Quit the minibuffer and run BODY afterwards."
218 `(progn
219 (put 'quit 'error-message "")
220 (run-at-time nil nil
221 (lambda ()
222 (put 'quit 'error-message "Quit")
223 ,@body))
224 (minibuffer-keyboard-quit)))
225
226 (defun ivy--done (text)
227 "Insert TEXT and exit minibuffer."
228 (if (and ivy--directory
229 (not (eq (ivy-state-history ivy-last) 'grep-files-history)))
230 (insert (setq ivy--current (expand-file-name
231 text ivy--directory)))
232 (insert (setq ivy--current text)))
233 (setq ivy-exit 'done)
234 (exit-minibuffer))
235
236 ;;* Commands
237 (defun ivy-done ()
238 "Exit the minibuffer with the selected candidate."
239 (interactive)
240 (delete-minibuffer-contents)
241 (cond ((> ivy--length 0)
242 (ivy--done ivy--current))
243 ((memq (ivy-state-collection ivy-last)
244 '(read-file-name-internal internal-complete-buffer))
245 (if (or (not (eq confirm-nonexistent-file-or-buffer t))
246 (equal " (confirm)" ivy--prompt-extra))
247 (ivy--done ivy-text)
248 (setq ivy--prompt-extra " (confirm)")
249 (insert ivy-text)
250 (ivy--exhibit)))
251 ((memq (ivy-state-require-match ivy-last)
252 '(nil confirm confirm-after-completion))
253 (ivy--done ivy-text))
254 (t
255 (setq ivy--prompt-extra " (match required)")
256 (insert ivy-text)
257 (ivy--exhibit))))
258
259 (defun ivy-build-tramp-name (x)
260 "Reconstruct X into a path.
261 Is is a cons cell, related to `tramp-get-completion-function'."
262 (let ((user (car x))
263 (domain (cadr x)))
264 (if user
265 (concat user "@" domain)
266 domain)))
267
268 (declare-function tramp-get-completion-function "tramp")
269 (declare-function Info-find-node "info")
270
271 (defun ivy-alt-done (&optional arg)
272 "Exit the minibuffer with the selected candidate.
273 When ARG is t, exit with current text, ignoring the candidates."
274 (interactive "P")
275 (let (dir)
276 (cond (arg
277 (ivy-immediate-done))
278 ((and ivy--directory
279 (or
280 (and
281 (not (string= ivy--current "./"))
282 (cl-plusp ivy--length)
283 (file-directory-p
284 (setq dir (expand-file-name
285 ivy--current ivy--directory))))))
286 (ivy--cd dir)
287 (ivy--exhibit))
288 ((eq (ivy-state-collection ivy-last) 'Info-read-node-name-1)
289 (if (or (equal ivy--current "(./)")
290 (equal ivy--current "(../)"))
291 (ivy-quit-and-run
292 (ivy-read "Go to file: " 'read-file-name-internal
293 :action (lambda (x)
294 (Info-find-node
295 (expand-file-name x ivy--directory)
296 "Top"))))
297 (ivy-done)))
298 ((and ivy--directory
299 (string-match "\\`/[^/]+:.*:.*\\'" ivy-text))
300 (ivy-done))
301 ((and ivy--directory
302 (string-match
303 "\\`/\\([^/]+?\\):\\(?:\\(.*\\)@\\)?\\(.*\\)\\'"
304 ivy-text))
305 (let ((method (match-string 1 ivy-text))
306 (user (match-string 2 ivy-text))
307 (rest (match-string 3 ivy-text))
308 res)
309 (require 'tramp)
310 (dolist (x (tramp-get-completion-function method))
311 (setq res (append res (funcall (car x) (cadr x)))))
312 (setq res (delq nil res))
313 (when user
314 (dolist (x res)
315 (setcar x user)))
316 (setq res (cl-delete-duplicates res :test #'equal))
317 (let* ((old-ivy-last ivy-last)
318 (enable-recursive-minibuffers t)
319 (host (ivy-read "Find File: "
320 (mapcar #'ivy-build-tramp-name res)
321 :initial-input rest)))
322 (setq ivy-last old-ivy-last)
323 (when host
324 (setq ivy--directory "/")
325 (ivy--cd (concat "/" method ":" host ":"))))))
326 (t
327 (ivy-done)))))
328
329 (defcustom ivy-tab-space nil
330 "When non-nil, `ivy-partial-or-done' should insert a space."
331 :type 'boolean)
332
333 (defun ivy-partial-or-done ()
334 "Complete the minibuffer text as much as possible.
335 If the text hasn't changed as a result, forward to `ivy-alt-done'."
336 (interactive)
337 (if (and (eq (ivy-state-collection ivy-last) #'read-file-name-internal)
338 (string-match "\\`/" ivy-text))
339 (let ((default-directory ivy--directory))
340 (minibuffer-complete)
341 (setq ivy-text (ivy--input))
342 (when (and (file-directory-p ivy-text)
343 (= ivy--length 1))
344 (ivy--cd (expand-file-name ivy-text))))
345 (or (ivy-partial)
346 (when (or (eq this-command last-command)
347 (eq ivy--length 1))
348 (ivy-alt-done)))))
349
350 (defun ivy-partial ()
351 "Complete the minibuffer text as much as possible."
352 (interactive)
353 (let* ((parts (or (split-string ivy-text " " t) (list "")))
354 (postfix (car (last parts)))
355 (completion-ignore-case t)
356 (startp (string-match "^\\^" postfix))
357 (new (try-completion (if startp
358 (substring postfix 1)
359 postfix)
360 (mapcar (lambda (str) (substring str (string-match postfix str)))
361 ivy--old-cands))))
362 (cond ((eq new t) nil)
363 ((string= new ivy-text) nil)
364 (new
365 (delete-region (minibuffer-prompt-end) (point-max))
366 (setcar (last parts)
367 (if startp
368 (concat "^" new)
369 new))
370 (insert (mapconcat #'identity parts " ")
371 (if ivy-tab-space " " ""))
372 t))))
373
374 (defun ivy-immediate-done ()
375 "Exit the minibuffer with the current input."
376 (interactive)
377 (delete-minibuffer-contents)
378 (insert (setq ivy--current ivy-text))
379 (setq ivy-exit 'done)
380 (exit-minibuffer))
381
382 (defun ivy-resume ()
383 "Resume the last completion session."
384 (interactive)
385 (ivy-read
386 (ivy-state-prompt ivy-last)
387 (ivy-state-collection ivy-last)
388 :predicate (ivy-state-predicate ivy-last)
389 :require-match (ivy-state-require-match ivy-last)
390 :initial-input ivy-text
391 :history (ivy-state-history ivy-last)
392 :preselect (unless (eq (ivy-state-collection ivy-last)
393 'read-file-name-internal)
394 (regexp-quote ivy--current))
395 :keymap (ivy-state-keymap ivy-last)
396 :update-fn (ivy-state-update-fn ivy-last)
397 :sort (ivy-state-sort ivy-last)
398 :action (ivy-state-action ivy-last)
399 :unwind (ivy-state-unwind ivy-last)
400 :re-builder (ivy-state-re-builder ivy-last)
401 :matcher (ivy-state-matcher ivy-last)
402 :dynamic-collection (ivy-state-dynamic-collection ivy-last)))
403
404 (defvar ivy-calling nil
405 "When non-nil, call the current action when `ivy--index' changes.")
406
407 (defun ivy-set-index (index)
408 "Set `ivy--index' to INDEX."
409 (setq ivy--index index)
410 (when ivy-calling
411 (ivy--exhibit)
412 (ivy-call)))
413
414 (defun ivy-beginning-of-buffer ()
415 "Select the first completion candidate."
416 (interactive)
417 (ivy-set-index 0))
418
419 (defun ivy-end-of-buffer ()
420 "Select the last completion candidate."
421 (interactive)
422 (ivy-set-index (1- ivy--length)))
423
424 (defun ivy-scroll-up-command ()
425 "Scroll the candidates upward by the minibuffer height."
426 (interactive)
427 (ivy-set-index (min (+ ivy--index ivy-height)
428 (1- ivy--length))))
429
430 (defun ivy-scroll-down-command ()
431 "Scroll the candidates downward by the minibuffer height."
432 (interactive)
433 (ivy-set-index (max (- ivy--index ivy-height)
434 0)))
435 (defun ivy-minibuffer-grow ()
436 "Grow the minibuffer window by 1 line"
437 (interactive)
438 (setq-local max-mini-window-height
439 (cl-incf ivy-height)))
440
441 (defun ivy-minibuffer-shrink ()
442 "Shrink the minibuffer window by 1 line."
443 (interactive)
444 (unless (<= ivy-height 2)
445 (setq-local max-mini-window-height
446 (cl-decf ivy-height))
447 (window-resize (selected-window) -1)))
448
449 (defun ivy-next-line (&optional arg)
450 "Move cursor vertically down ARG candidates."
451 (interactive "p")
452 (setq arg (or arg 1))
453 (let ((index (+ ivy--index arg)))
454 (if (> index (1- ivy--length))
455 (if ivy-wrap
456 (ivy-beginning-of-buffer)
457 (ivy-set-index (1- ivy--length)))
458 (ivy-set-index index))))
459
460 (defun ivy-next-line-or-history (&optional arg)
461 "Move cursor vertically down ARG candidates.
462 If the input is empty, select the previous history element instead."
463 (interactive "p")
464 (when (string= ivy-text "")
465 (ivy-previous-history-element 1))
466 (ivy-next-line arg))
467
468 (defun ivy-previous-line (&optional arg)
469 "Move cursor vertically up ARG candidates."
470 (interactive "p")
471 (setq arg (or arg 1))
472 (let ((index (- ivy--index arg)))
473 (if (< index 0)
474 (if ivy-wrap
475 (ivy-end-of-buffer)
476 (ivy-set-index 0))
477 (ivy-set-index index))))
478
479 (defun ivy-previous-line-or-history (arg)
480 "Move cursor vertically up ARG candidates.
481 If the input is empty, select the previous history element instead."
482 (interactive "p")
483 (when (string= ivy-text "")
484 (ivy-previous-history-element 1))
485 (ivy-previous-line arg))
486
487 (defun ivy-toggle-calling ()
488 "Flip `ivy-calling'"
489 (interactive)
490 (when (setq ivy-calling (not ivy-calling))
491 (ivy-call)))
492
493 (defun ivy-call ()
494 "Call the current action without exiting completion."
495 (when (ivy-state-action ivy-last)
496 (with-selected-window (ivy-state-window ivy-last)
497 (funcall (ivy-state-action ivy-last) ivy--current))))
498
499 (defun ivy-next-line-and-call (&optional arg)
500 "Move cursor vertically down ARG candidates.
501 Call the permanent action if possible."
502 (interactive "p")
503 (ivy-next-line arg)
504 (ivy--exhibit)
505 (ivy-call))
506
507 (defun ivy-previous-line-and-call (&optional arg)
508 "Move cursor vertically down ARG candidates.
509 Call the permanent action if possible."
510 (interactive "p")
511 (ivy-previous-line arg)
512 (ivy--exhibit)
513 (ivy-call))
514
515 (defun ivy-previous-history-element (arg)
516 "Forward to `previous-history-element' with ARG."
517 (interactive "p")
518 (previous-history-element arg)
519 (ivy--cd-maybe)
520 (move-end-of-line 1)
521 (ivy--maybe-scroll-history))
522
523 (defun ivy-next-history-element (arg)
524 "Forward to `next-history-element' with ARG."
525 (interactive "p")
526 (next-history-element arg)
527 (ivy--cd-maybe)
528 (move-end-of-line 1)
529 (ivy--maybe-scroll-history))
530
531 (defun ivy--cd-maybe ()
532 "Check if the current input points to a different directory.
533 If so, move to that directory, while keeping only the file name."
534 (when ivy--directory
535 (let* ((input (expand-file-name (ivy--input)))
536 (file (file-name-nondirectory input))
537 (dir (expand-file-name (file-name-directory input))))
538 (if (string= dir ivy--directory)
539 (progn
540 (delete-minibuffer-contents)
541 (insert file))
542 (ivy--cd dir)
543 (insert file)))))
544
545 (defun ivy--maybe-scroll-history ()
546 "If the selected history element has an index, scroll there."
547 (let ((idx (ignore-errors
548 (get-text-property
549 (minibuffer-prompt-end)
550 'ivy-index))))
551 (when idx
552 (ivy--exhibit)
553 (setq ivy--index idx))))
554
555 (defun ivy--cd (dir)
556 "When completing file names, move to directory DIR."
557 (if (null ivy--directory)
558 (error "Unexpected")
559 (setq ivy--old-cands nil)
560 (setq ivy--old-re nil)
561 (setq ivy--index 0)
562 (setq ivy--all-candidates
563 (ivy--sorted-files (setq ivy--directory dir)))
564 (setq ivy-text "")
565 (delete-minibuffer-contents)))
566
567 (defun ivy-backward-delete-char ()
568 "Forward to `backward-delete-char'.
569 On error (read-only), call `ivy-on-del-error-function'."
570 (interactive)
571 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
572 (progn
573 (ivy--cd (file-name-directory
574 (directory-file-name
575 (expand-file-name
576 ivy--directory))))
577 (ivy--exhibit))
578 (condition-case nil
579 (backward-delete-char 1)
580 (error
581 (when ivy-on-del-error-function
582 (funcall ivy-on-del-error-function))))))
583
584 (defun ivy-delete-char (arg)
585 "Forward to `delete-char' ARG."
586 (interactive "p")
587 (unless (= (point) (line-end-position))
588 (delete-char arg)))
589
590 (defun ivy-forward-char (arg)
591 "Forward to `forward-char' ARG."
592 (interactive "p")
593 (unless (= (point) (line-end-position))
594 (forward-char arg)))
595
596 (defun ivy-kill-word (arg)
597 "Forward to `kill-word' ARG."
598 (interactive "p")
599 (unless (= (point) (line-end-position))
600 (kill-word arg)))
601
602 (defun ivy-kill-line ()
603 "Forward to `kill-line'."
604 (interactive)
605 (if (eolp)
606 (kill-region (minibuffer-prompt-end) (point))
607 (kill-line)))
608
609 (defun ivy-backward-kill-word ()
610 "Forward to `backward-kill-word'."
611 (interactive)
612 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
613 (progn
614 (ivy--cd (file-name-directory
615 (directory-file-name
616 (expand-file-name
617 ivy--directory))))
618 (ivy--exhibit))
619 (ignore-errors
620 (backward-kill-word 1))))
621
622 (defvar ivy--regexp-quote 'regexp-quote
623 "Store the regexp quoting state.")
624
625 (defun ivy-toggle-regexp-quote ()
626 "Toggle the regexp quoting."
627 (interactive)
628 (setq ivy--old-re nil)
629 (cl-rotatef ivy--regex-function ivy--regexp-quote))
630
631 (defun ivy-sort-file-function-default (x y)
632 "Compare two files X and Y.
633 Prioritize directories."
634 (if (get-text-property 0 'dirp x)
635 (if (get-text-property 0 'dirp y)
636 (string< x y)
637 t)
638 (if (get-text-property 0 'dirp y)
639 nil
640 (string< x y))))
641
642 (defvar ivy-sort-functions-alist
643 '((read-file-name-internal . ivy-sort-file-function-default)
644 (internal-complete-buffer . nil)
645 (counsel-git-grep-function . nil)
646 (Man-goto-section . nil)
647 (org-refile . nil)
648 (t . string-lessp))
649 "An alist of sorting functions for each collection function.
650 Interactive functions that call completion fit in here as well.
651
652 For each entry, nil means no sorting. It's very useful to turn
653 off the sorting for functions that have candidates in the natural
654 buffer order, like `org-refile' or `Man-goto-section'.
655
656 The entry associated to t is used for all fall-through cases.")
657
658 (defvar ivy-re-builders-alist
659 '((t . ivy--regex-plus))
660 "An alist of regex building functions for each collection function.
661 Each function should take a string and return a valid regex or a
662 regex sequence (see below).
663
664 The entry associated to t is used for all fall-through cases.
665 Possible choices: `ivy--regex', `regexp-quote', `ivy--regex-plus'.
666
667 In case a function returns a list, it should look like this:
668 '((\"matching-regexp\" . t) (\"non-matching-regexp\") ...).
669
670 The matches will be filtered in a sequence, you can mix the
671 regexps that should match and that should not match as you
672 like.")
673
674 (defvar ivy-initial-inputs-alist
675 '((org-refile . "^")
676 (org-agenda-refile . "^")
677 (org-capture-refile . "^")
678 (counsel-M-x . "^")
679 (counsel-describe-function . "^")
680 (counsel-describe-variable . "^")
681 (man . "^")
682 (woman . "^"))
683 "Command to initial input table.")
684
685 (defcustom ivy-sort-max-size 30000
686 "Sorting won't be done for collections larger than this."
687 :type 'integer)
688
689 (defun ivy--sorted-files (dir)
690 "Return the list of files in DIR.
691 Directories come first."
692 (let* ((default-directory dir)
693 (seq (all-completions "" 'read-file-name-internal))
694 sort-fn)
695 (if (equal dir "/")
696 seq
697 (setq seq (delete "./" (delete "../" seq)))
698 (when (eq (setq sort-fn (cdr (assoc 'read-file-name-internal
699 ivy-sort-functions-alist)))
700 #'ivy-sort-file-function-default)
701 (setq seq (mapcar (lambda (x)
702 (propertize x 'dirp (string-match-p "/\\'" x)))
703 seq)))
704 (when sort-fn
705 (setq seq (cl-sort seq sort-fn)))
706 (dolist (dir ivy-extra-directories)
707 (push dir seq))
708 seq)))
709
710 ;;** Entry Point
711 (cl-defun ivy-read (prompt collection
712 &key predicate require-match initial-input
713 history preselect keymap update-fn sort
714 action unwind re-builder matcher dynamic-collection)
715 "Read a string in the minibuffer, with completion.
716
717 PROMPT is a string to prompt with; normally it ends in a colon
718 and a space. When PROMPT contains %d, it will be updated with
719 the current number of matching candidates.
720 See also `ivy-count-format'.
721
722 COLLECTION is a list of strings.
723
724 If INITIAL-INPUT is non-nil, insert it in the minibuffer initially.
725
726 KEYMAP is composed together with `ivy-minibuffer-map'.
727
728 If PRESELECT is non-nil select the corresponding candidate out of
729 the ones that match INITIAL-INPUT.
730
731 UPDATE-FN is called each time the current candidate(s) is changed.
732
733 When SORT is t, refer to `ivy-sort-functions-alist' for sorting.
734
735 ACTION is a lambda to call after a result was selected. It should
736 take a single argument, usually a string.
737
738 UNWIND is a lambda to call before exiting.
739
740 RE-BUILDER is a lambda that transforms text into a regex.
741
742 MATCHER can completely override matching.
743
744 DYNAMIC-COLLECTION is a function to call to update the list of
745 candidates with each input."
746 (setq ivy-last
747 (make-ivy-state
748 :prompt prompt
749 :collection collection
750 :predicate predicate
751 :require-match require-match
752 :initial-input initial-input
753 :history history
754 :preselect preselect
755 :keymap keymap
756 :update-fn update-fn
757 :sort sort
758 :action action
759 :window (selected-window)
760 :unwind unwind
761 :re-builder re-builder
762 :matcher matcher
763 :dynamic-collection dynamic-collection))
764 (ivy--reset-state ivy-last)
765 (prog1
766 (unwind-protect
767 (minibuffer-with-setup-hook
768 #'ivy--minibuffer-setup
769 (let* ((hist (or history 'ivy-history))
770 (minibuffer-completion-table collection)
771 (minibuffer-completion-predicate predicate)
772 (res (read-from-minibuffer
773 prompt
774 (ivy-state-initial-input ivy-last)
775 (make-composed-keymap keymap ivy-minibuffer-map)
776 nil
777 hist)))
778 (when (eq ivy-exit 'done)
779 (let ((item (if ivy--directory
780 ivy--current
781 ivy-text)))
782 (set hist (cons (propertize item 'ivy-index ivy--index)
783 (delete item
784 (cdr (symbol-value hist))))))
785 res)))
786 (remove-hook 'post-command-hook #'ivy--exhibit)
787 (when (setq unwind (ivy-state-unwind ivy-last))
788 (funcall unwind)))
789 (when (setq action (ivy-state-action ivy-last))
790 (funcall action ivy--current))))
791
792 (defun ivy--reset-state (state)
793 "Reset the ivy to STATE.
794 This is useful for recursive `ivy-read'."
795 (let ((prompt (ivy-state-prompt state))
796 (collection (ivy-state-collection state))
797 (predicate (ivy-state-predicate state))
798 (history (ivy-state-history state))
799 (preselect (ivy-state-preselect state))
800 (sort (ivy-state-sort state))
801 (re-builder (ivy-state-re-builder state))
802 (dynamic-collection (ivy-state-dynamic-collection state))
803 (initial-input (ivy-state-initial-input state))
804 (require-match (ivy-state-require-match state)))
805 (unless initial-input
806 (setq initial-input (cdr (assoc this-command
807 ivy-initial-inputs-alist))))
808 (setq ivy--directory nil)
809 (setq ivy--regex-function
810 (or re-builder
811 (and (functionp collection)
812 (cdr (assoc collection ivy-re-builders-alist)))
813 (cdr (assoc t ivy-re-builders-alist))
814 'ivy--regex))
815 (setq ivy--subexps 0)
816 (setq ivy--regexp-quote 'regexp-quote)
817 (setq ivy--old-text "")
818 (setq ivy--full-length nil)
819 (setq ivy-text "")
820 (setq ivy-calling nil)
821 (let (coll sort-fn)
822 (cond ((eq collection 'Info-read-node-name-1)
823 (if (equal Info-current-file "dir")
824 (setq coll
825 (mapcar (lambda (x) (format "(%s)" x))
826 (cl-delete-duplicates
827 (all-completions "(" collection predicate)
828 :test #'equal)))
829 (setq coll (all-completions "" collection predicate))))
830 ((eq collection 'read-file-name-internal)
831 (setq ivy--directory default-directory)
832 (require 'dired)
833 (setq coll
834 (ivy--sorted-files default-directory))
835 (when initial-input
836 (unless (or require-match
837 (equal initial-input default-directory)
838 (equal initial-input ""))
839 (setq coll (cons initial-input coll)))
840 (setq initial-input nil)))
841 ((eq collection 'internal-complete-buffer)
842 (setq coll (ivy--buffer-list "" ivy-use-virtual-buffers)))
843 ((or (functionp collection)
844 (vectorp collection)
845 (listp (car collection)))
846 (setq coll (all-completions "" collection predicate)))
847 ((hash-table-p collection)
848 (error "Hash table as a collection unsupported"))
849 (t
850 (setq coll collection)))
851 (when sort
852 (if (and (functionp collection)
853 (setq sort-fn (assoc collection ivy-sort-functions-alist)))
854 (when (and (setq sort-fn (cdr sort-fn))
855 (not (eq collection 'read-file-name-internal)))
856 (setq coll (cl-sort coll sort-fn)))
857 (unless (eq history 'org-refile-history)
858 (if (and (setq sort-fn (cdr (assoc t ivy-sort-functions-alist)))
859 (<= (length coll) ivy-sort-max-size))
860 (setq coll (cl-sort (copy-sequence coll) sort-fn))))))
861 (when preselect
862 (unless (or (and require-match
863 (not (eq collection 'internal-complete-buffer)))
864 (let ((re (format "\\`%s" (regexp-quote preselect))))
865 (cl-find-if (lambda (x) (string-match re x))
866 coll)))
867 (setq coll (cons preselect coll))))
868 (setq ivy--index (or
869 (and dynamic-collection
870 ivy--index)
871 (and preselect
872 (ivy--preselect-index
873 coll initial-input preselect))
874 0))
875 (setq ivy--old-re nil)
876 (setq ivy--old-cands nil)
877 (setq ivy--all-candidates coll))
878 (setq ivy-exit nil)
879 (setq ivy--default (or (thing-at-point 'symbol) ""))
880 (setq ivy--prompt
881 (cond ((string-match "%.*d" prompt)
882 prompt)
883 ((string-match "%.*d" ivy-count-format)
884 (concat ivy-count-format prompt))
885 (ivy--directory
886 prompt)
887 (t
888 nil)))
889 (setf (ivy-state-initial-input ivy-last) initial-input)))
890
891 (defun ivy-completing-read (prompt collection
892 &optional predicate require-match initial-input
893 history def _inherit-input-method)
894 "Read a string in the minibuffer, with completion.
895
896 This is an interface that conforms to `completing-read', so that
897 it can be used for `completing-read-function'.
898
899 PROMPT is a string to prompt with; normally it ends in a colon and a space.
900 COLLECTION can be a list of strings, an alist, an obarray or a hash table.
901 PREDICATE limits completion to a subset of COLLECTION.
902 REQUIRE-MATCH is considered boolean. See `completing-read'.
903 INITIAL-INPUT is a string that can be inserted into the minibuffer initially.
904 _HISTORY is ignored for now.
905 DEF is the default value.
906 _INHERIT-INPUT-METHOD is ignored for now.
907
908 The history, defaults and input-method arguments are ignored for now."
909 (ivy-read prompt collection
910 :predicate predicate
911 :require-match require-match
912 :initial-input (if (consp initial-input)
913 (car initial-input)
914 initial-input)
915 :preselect (if (listp def) (car def) def)
916 :history history
917 :keymap nil
918 :sort
919 (let ((sort (assoc this-command ivy-sort-functions-alist)))
920 (if sort
921 (cdr sort)
922 t))))
923
924 ;;;###autoload
925 (define-minor-mode ivy-mode
926 "Toggle Ivy mode on or off.
927 With ARG, turn Ivy mode on if arg is positive, off otherwise.
928 Turning on Ivy mode will set `completing-read-function' to
929 `ivy-completing-read'.
930
931 Global bindings:
932 \\{ivy-mode-map}
933
934 Minibuffer bindings:
935 \\{ivy-minibuffer-map}"
936 :group 'ivy
937 :global t
938 :keymap ivy-mode-map
939 :lighter " ivy"
940 (if ivy-mode
941 (setq completing-read-function 'ivy-completing-read)
942 (setq completing-read-function 'completing-read-default)))
943
944 (defun ivy--preselect-index (candidates initial-input preselect)
945 "Return the index in CANDIDATES filtered by INITIAL-INPUT for PRESELECT."
946 (when initial-input
947 (setq initial-input (ivy--regex-plus initial-input))
948 (setq candidates
949 (cl-remove-if-not
950 (lambda (x)
951 (string-match initial-input x))
952 candidates)))
953 (or (cl-position preselect candidates :test #'equal)
954 (cl-position-if
955 (lambda (x)
956 (string-match (regexp-quote preselect) x))
957 candidates)))
958
959 ;;* Implementation
960 ;;** Regex
961 (defvar ivy--regex-hash
962 (make-hash-table :test #'equal)
963 "Store pre-computed regex.")
964
965 (defun ivy--split (str)
966 "Split STR into a list by single spaces.
967 The remaining spaces stick to their left.
968 This allows to \"quote\" N spaces by inputting N+1 spaces."
969 (let ((len (length str))
970 start0
971 (start1 0)
972 res s
973 match-len)
974 (while (and (string-match " +" str start1)
975 (< start1 len))
976 (setq match-len (- (match-end 0) (match-beginning 0)))
977 (if (= match-len 1)
978 (progn
979 (when start0
980 (setq start1 start0)
981 (setq start0 nil))
982 (push (substring str start1 (match-beginning 0)) res)
983 (setq start1 (match-end 0)))
984 (setq str (replace-match
985 (make-string (1- match-len) ?\ )
986 nil nil str))
987 (setq start0 (or start0 start1))
988 (setq start1 (1- (match-end 0)))))
989 (if start0
990 (push (substring str start0) res)
991 (setq s (substring str start1))
992 (unless (= (length s) 0)
993 (push s res)))
994 (nreverse res)))
995
996 (defun ivy--regex (str &optional greedy)
997 "Re-build regex from STR in case it has a space.
998 When GREEDY is non-nil, join words in a greedy way."
999 (let ((hashed (unless greedy
1000 (gethash str ivy--regex-hash))))
1001 (if hashed
1002 (prog1 (cdr hashed)
1003 (setq ivy--subexps (car hashed)))
1004 (cdr (puthash str
1005 (let ((subs (ivy--split str)))
1006 (if (= (length subs) 1)
1007 (cons
1008 (setq ivy--subexps 0)
1009 (car subs))
1010 (cons
1011 (setq ivy--subexps (length subs))
1012 (mapconcat
1013 (lambda (x)
1014 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1015 x
1016 (format "\\(%s\\)" x)))
1017 subs
1018 (if greedy
1019 ".*"
1020 ".*?")))))
1021 ivy--regex-hash)))))
1022
1023 (defun ivy--regex-ignore-order (str)
1024 "Re-build regex from STR by splitting it on spaces.
1025 Ignore the order of each group."
1026 (let* ((subs (split-string str " +" t))
1027 (len (length subs)))
1028 (cl-case len
1029 (1
1030 (setq ivy--subexps 0)
1031 (car subs))
1032 (t
1033 (setq ivy--subexps len)
1034 (let ((all (mapconcat #'identity subs "\\|")))
1035 (mapconcat
1036 (lambda (x)
1037 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1038 x
1039 (format "\\(%s\\)" x)))
1040 (make-list len all)
1041 ".*?"))))))
1042
1043 (defun ivy--regex-plus (str)
1044 "Build a regex sequence from STR.
1045 Spaces are wild, everything before \"!\" should match.
1046 Everything after \"!\" should not match."
1047 (let ((parts (split-string str "!" t)))
1048 (cl-case (length parts)
1049 (0
1050 "")
1051 (1
1052 (ivy--regex (car parts)))
1053 (2
1054 (let ((res
1055 (mapcar #'list
1056 (split-string (cadr parts) " " t))))
1057 (cons (cons (ivy--regex (car parts)) t)
1058 res)))
1059 (t (error "Unexpected: use only one !")))))
1060
1061 (defun ivy--regex-fuzzy (str)
1062 "Build a regex sequence from STR.
1063 Insert .* between each char."
1064 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1065 (concat (match-string 1 str)
1066 (mapconcat #'string (string-to-list (match-string 2 str)) ".*")
1067 (match-string 3 str))
1068 str))
1069
1070 ;;** Rest
1071 (defun ivy--minibuffer-setup ()
1072 "Setup ivy completion in the minibuffer."
1073 (set (make-local-variable 'completion-show-inline-help) nil)
1074 (set (make-local-variable 'minibuffer-default-add-function)
1075 (lambda ()
1076 (list ivy--default)))
1077 (setq-local max-mini-window-height ivy-height)
1078 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1079 ;; show completions with empty input
1080 (ivy--exhibit))
1081
1082 (defun ivy--input ()
1083 "Return the current minibuffer input."
1084 ;; assume one-line minibuffer input
1085 (buffer-substring-no-properties
1086 (minibuffer-prompt-end)
1087 (line-end-position)))
1088
1089 (defun ivy--cleanup ()
1090 "Delete the displayed completion candidates."
1091 (save-excursion
1092 (goto-char (minibuffer-prompt-end))
1093 (delete-region (line-end-position) (point-max))))
1094
1095 (defun ivy--insert-prompt ()
1096 "Update the prompt according to `ivy--prompt'."
1097 (when ivy--prompt
1098 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1099 counsel-find-symbol))
1100 (setq ivy--prompt-extra ""))
1101 (let (head tail)
1102 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1103 (progn
1104 (setq head (match-string 1 ivy--prompt))
1105 (setq tail ": "))
1106 (setq head (substring ivy--prompt 0 -1))
1107 (setq tail " "))
1108 (let ((inhibit-read-only t)
1109 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1110 (n-str
1111 (format
1112 (concat
1113 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1114 (> (minibuffer-depth) 1))
1115 (format "[%d] " (minibuffer-depth))
1116 "")
1117 head
1118 ivy--prompt-extra
1119 tail
1120 (if ivy--directory
1121 (abbreviate-file-name ivy--directory)
1122 ""))
1123 (or (and (ivy-state-dynamic-collection ivy-last)
1124 ivy--full-length)
1125 ivy--length))))
1126 (save-excursion
1127 (goto-char (point-min))
1128 (delete-region (point-min) (minibuffer-prompt-end))
1129 (set-text-properties 0 (length n-str)
1130 `(face minibuffer-prompt ,@std-props)
1131 n-str)
1132 (ivy--set-match-props n-str "confirm"
1133 `(face ivy-confirm-face ,@std-props))
1134 (ivy--set-match-props n-str "match required"
1135 `(face ivy-match-required-face ,@std-props))
1136 (insert n-str))
1137 ;; get out of the prompt area
1138 (constrain-to-field nil (point-max))))))
1139
1140 (defun ivy--set-match-props (str match props)
1141 "Set STR text proprties that match MATCH to PROPS."
1142 (when (string-match match str)
1143 (set-text-properties
1144 (match-beginning 0)
1145 (match-end 0)
1146 props
1147 str)))
1148
1149 (defvar inhibit-message)
1150
1151 (defun ivy--exhibit ()
1152 "Insert Ivy completions display.
1153 Should be run via minibuffer `post-command-hook'."
1154 (setq ivy-text (ivy--input))
1155 (if (ivy-state-dynamic-collection ivy-last)
1156 ;; while-no-input would cause annoying
1157 ;; "Waiting for process to die...done" message interruptions
1158 (let ((inhibit-message t))
1159 (unless (equal ivy--old-text ivy-text)
1160 (while-no-input
1161 ;; dynamic collection should take care of everything
1162 (funcall (ivy-state-dynamic-collection ivy-last) ivy-text)
1163 (setq ivy--old-text ivy-text)))
1164 (unless (eq ivy--full-length -1)
1165 (ivy--insert-minibuffer
1166 (ivy--format ivy--all-candidates))))
1167 (cond (ivy--directory
1168 (if (string-match "/\\'" ivy-text)
1169 (if (member ivy-text ivy--all-candidates)
1170 (ivy--cd (expand-file-name ivy-text ivy--directory))
1171 (when (string-match "//\\'" ivy-text)
1172 (if (and default-directory
1173 (string-match "\\`[[:alpha:]]:/" default-directory))
1174 (ivy--cd (match-string 0 default-directory))
1175 (ivy--cd "/")))
1176 (when (string-match "[[:alpha:]]:/" ivy-text)
1177 (let ((drive-root (match-string 0 ivy-text)))
1178 (when (file-exists-p drive-root)
1179 (ivy--cd drive-root)))))
1180 (if (string-match "\\`~\\'" ivy-text)
1181 (ivy--cd (expand-file-name "~/")))))
1182 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1183 (when (or (and (string-match "\\` " ivy-text)
1184 (not (string-match "\\` " ivy--old-text)))
1185 (and (string-match "\\` " ivy--old-text)
1186 (not (string-match "\\` " ivy-text))))
1187 (setq ivy--all-candidates
1188 (if (and (> (length ivy-text) 0)
1189 (eq (aref ivy-text 0)
1190 ?\ ))
1191 (ivy--buffer-list " ")
1192 (ivy--buffer-list "" ivy-use-virtual-buffers)))
1193 (setq ivy--old-re nil))))
1194 (ivy--insert-minibuffer
1195 (ivy--format
1196 (ivy--filter ivy-text ivy--all-candidates)))
1197 (setq ivy--old-text ivy-text)))
1198
1199 (defun ivy--insert-minibuffer (text)
1200 "Insert TEXT into minibuffer with appropriate cleanup."
1201 (let ((resize-mini-windows nil)
1202 (update-fn (ivy-state-update-fn ivy-last))
1203 deactivate-mark)
1204 (ivy--cleanup)
1205 (when update-fn
1206 (funcall update-fn))
1207 (ivy--insert-prompt)
1208 ;; Do nothing if while-no-input was aborted.
1209 (when (stringp text)
1210 (let ((buffer-undo-list t))
1211 (save-excursion
1212 (forward-line 1)
1213 (insert text))))))
1214
1215 (declare-function colir-blend-face-background "ext:colir")
1216
1217 (defun ivy--add-face (str face)
1218 "Propertize STR with FACE.
1219 `font-lock-append-text-property' is used, since it's better than
1220 `propertize' or `add-face-text-property' in this case."
1221 (require 'colir)
1222 (condition-case nil
1223 (colir-blend-face-background 0 (length str) face str)
1224 (error
1225 (ignore-errors
1226 (font-lock-append-text-property 0 (length str) 'face face str))))
1227 str)
1228
1229 (defun ivy--filter (name candidates)
1230 "Return all items that match NAME in CANDIDATES.
1231 CANDIDATES are assumed to be static."
1232 (let* ((re (funcall ivy--regex-function name))
1233 (matcher (ivy-state-matcher ivy-last))
1234 (cands (cond
1235 (matcher
1236 (funcall matcher re candidates))
1237 ((and (equal re ivy--old-re)
1238 ivy--old-cands)
1239 ivy--old-cands)
1240 ((and ivy--old-re
1241 (stringp re)
1242 (stringp ivy--old-re)
1243 (not (string-match "\\\\" ivy--old-re))
1244 (not (equal ivy--old-re ""))
1245 (memq (cl-search
1246 (if (string-match "\\\\)\\'" ivy--old-re)
1247 (substring ivy--old-re 0 -2)
1248 ivy--old-re)
1249 re)
1250 '(0 2)))
1251 (ignore-errors
1252 (cl-remove-if-not
1253 (lambda (x) (string-match re x))
1254 ivy--old-cands)))
1255 (t
1256 (let ((re-list (if (stringp re) (list (cons re t)) re))
1257 (res candidates))
1258 (dolist (re re-list)
1259 (setq res
1260 (ignore-errors
1261 (funcall
1262 (if (cdr re)
1263 #'cl-remove-if-not
1264 #'cl-remove-if)
1265 (let ((re (car re)))
1266 (lambda (x) (string-match re x)))
1267 res))))
1268 res))))
1269 (tail (nthcdr ivy--index ivy--old-cands))
1270 idx)
1271 (when (and tail ivy--old-cands (not (equal "^" ivy--old-re)))
1272 (unless (and (not (equal re ivy--old-re))
1273 (or (setq ivy--index
1274 (or
1275 (cl-position re cands
1276 :test #'equal)
1277 (and ivy--directory
1278 (cl-position
1279 (concat re "/") cands
1280 :test #'equal))))))
1281 (while (and tail (null idx))
1282 ;; Compare with eq to handle equal duplicates in cands
1283 (setq idx (cl-position (pop tail) cands)))
1284 (setq ivy--index (or idx 0))))
1285 (when (and (string= name "") (not (equal ivy--old-re "")))
1286 (setq ivy--index
1287 (or (cl-position (ivy-state-preselect ivy-last)
1288 cands :test #'equal)
1289 ivy--index)))
1290 (setq ivy--old-re (if cands re ""))
1291 (setq ivy--old-cands cands)))
1292
1293 (defvar ivy-format-function 'ivy-format-function-default
1294 "Function to transform the list of candidates into a string.
1295 This string will be inserted into the minibuffer.")
1296
1297 (defun ivy-format-function-default (cands)
1298 "Transform CANDS into a string for minibuffer."
1299 (let ((ww (window-width)))
1300 (mapconcat
1301 (lambda (s)
1302 (if (> (length s) ww)
1303 (concat (substring s 0 (- ww 3)) "...")
1304 s))
1305 cands "\n")))
1306
1307 (defun ivy-format-function-arrow (cands)
1308 "Transform CANDS into a string for minibuffer."
1309 (let ((i -1))
1310 (mapconcat
1311 (lambda (s)
1312 (concat (if (eq (cl-incf i) ivy--index)
1313 "> "
1314 " ")
1315 s))
1316 cands "\n")))
1317
1318 (defun ivy--format (cands)
1319 "Return a string for CANDS suitable for display in the minibuffer.
1320 CANDS is a list of strings."
1321 (setq ivy--length (length cands))
1322 (when (>= ivy--index ivy--length)
1323 (setq ivy--index (max (1- ivy--length) 0)))
1324 (if (null cands)
1325 (setq ivy--current "")
1326 (let* ((half-height (/ ivy-height 2))
1327 (start (max 0 (- ivy--index half-height)))
1328 (end (min (+ start (1- ivy-height)) ivy--length))
1329 (start (max 0 (min start (- end (1- ivy-height)))))
1330 (cands (cl-subseq cands start end))
1331 (index (- ivy--index start)))
1332 (when ivy--directory
1333 (setq cands (mapcar (lambda (x)
1334 (if (string-match-p "/\\'" x)
1335 (propertize x 'face 'ivy-subdir)
1336 x))
1337 cands)))
1338 (setq ivy--current (copy-sequence (nth index cands)))
1339 (setf (nth index cands)
1340 (ivy--add-face ivy--current 'ivy-current-match))
1341 (setq cands (mapcar
1342 (lambda (s)
1343 (let ((s (copy-sequence s)))
1344 (when (fboundp 'add-face-text-property)
1345 (add-face-text-property
1346 0 (length s)
1347 `(:height ,(face-attribute 'default :height)
1348 :overline nil) nil s))
1349 s))
1350 cands))
1351 (let* ((ivy--index index)
1352 (res (concat "\n" (funcall ivy-format-function cands))))
1353 (put-text-property 0 (length res) 'read-only nil res)
1354 res))))
1355
1356 (defvar ivy--virtual-buffers nil
1357 "Store the virtual buffers alist.")
1358
1359 (defvar recentf-list)
1360
1361 (defface ivy-virtual '((t :inherit font-lock-builtin-face))
1362 "Face used by Ivy for matching virtual buffer names.")
1363
1364 (defun ivy--virtual-buffers ()
1365 "Adapted from `ido-add-virtual-buffers-to-list'."
1366 (unless recentf-mode
1367 (recentf-mode 1))
1368 (let ((bookmarks (and (boundp 'bookmark-alist)
1369 bookmark-alist))
1370 virtual-buffers name)
1371 (dolist (head (append
1372 recentf-list
1373 (delete " - no file -"
1374 (delq nil (mapcar (lambda (bookmark)
1375 (cdr (assoc 'filename bookmark)))
1376 bookmarks)))))
1377 (setq name (file-name-nondirectory head))
1378 (when (equal name "")
1379 (setq name (file-name-nondirectory (directory-file-name head))))
1380 (when (equal name "")
1381 (setq name head))
1382 (and (not (equal name ""))
1383 (null (get-file-buffer head))
1384 (not (assoc name virtual-buffers))
1385 (push (cons name head) virtual-buffers)))
1386 (when virtual-buffers
1387 (dolist (comp virtual-buffers)
1388 (put-text-property 0 (length (car comp))
1389 'face 'ivy-virtual
1390 (car comp)))
1391 (setq ivy--virtual-buffers (nreverse virtual-buffers))
1392 (mapcar #'car ivy--virtual-buffers))))
1393
1394 (defun ivy--buffer-list (str &optional virtual)
1395 "Return the buffers that match STR.
1396 When VIRTUAL is non-nil, add virtual buffers."
1397 (delete-dups
1398 (append
1399 (mapcar
1400 (lambda (x)
1401 (if (with-current-buffer x
1402 (file-remote-p
1403 (abbreviate-file-name default-directory)))
1404 (propertize x 'face 'ivy-remote)
1405 x))
1406 (all-completions str 'internal-complete-buffer))
1407 (and virtual
1408 (ivy--virtual-buffers)))))
1409
1410 (defun ivy--switch-buffer-action (buffer)
1411 "Switch to BUFFER.
1412 BUFFER may be a string or nil."
1413 (if (zerop (length buffer))
1414 (switch-to-buffer
1415 ivy-text nil 'force-same-window)
1416 (let ((virtual (assoc buffer ivy--virtual-buffers)))
1417 (if (and virtual
1418 (not (get-buffer buffer)))
1419 (find-file (cdr virtual))
1420 (switch-to-buffer
1421 buffer nil 'force-same-window)))))
1422
1423 (defun ivy-switch-buffer ()
1424 "Switch to another buffer."
1425 (interactive)
1426 (if (not ivy-mode)
1427 (call-interactively 'switch-to-buffer)
1428 (ivy-read "Switch to buffer: " 'internal-complete-buffer
1429 :preselect (buffer-name (other-buffer (current-buffer)))
1430 :action #'ivy--switch-buffer-action)))
1431
1432 (defun ivy-recentf ()
1433 "Find a file on `recentf-list'."
1434 (interactive)
1435 (ivy-read "Recentf: " recentf-list
1436 :action #'find-file))
1437
1438 (defun ivy-yank-word ()
1439 "Pull next word from buffer into search string."
1440 (interactive)
1441 (let (amend)
1442 (with-selected-window (ivy-state-window ivy-last)
1443 (let ((pt (point))
1444 (le (line-end-position)))
1445 (forward-word 1)
1446 (if (> (point) le)
1447 (goto-char pt)
1448 (setq amend (buffer-substring-no-properties pt (point))))))
1449 (when amend
1450 (insert amend))))
1451
1452 (defun ivy-insert-current ()
1453 "Make the current candidate into current input.
1454 Don't finish completion."
1455 (interactive)
1456 (delete-minibuffer-contents)
1457 (if (and ivy--directory
1458 (string-match "/$" ivy--current))
1459 (insert (substring ivy--current 0 -1))
1460 (insert ivy--current)))
1461
1462 (defun ivy-toggle-fuzzy ()
1463 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
1464 (interactive)
1465 (setq ivy--old-re nil)
1466 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
1467 (setq ivy--regex-function 'ivy--regex-plus)
1468 (setq ivy--regex-function 'ivy--regex-fuzzy)))
1469
1470 (defun ivy-reverse-i-search ()
1471 "Enter a recursive `ivy-read' session using the current history.
1472 The selected history element will be inserted into the minibufer."
1473 (interactive)
1474 (let ((enable-recursive-minibuffers t)
1475 (history (symbol-value (ivy-state-history ivy-last)))
1476 (old-last ivy-last))
1477 (ivy-read "Reverse-i-search: "
1478 history
1479 :action (lambda (x)
1480 (ivy--reset-state
1481 (setq ivy-last old-last))
1482 (delete-minibuffer-contents)
1483 (insert (substring-no-properties x))
1484 (ivy--cd-maybe)))))
1485
1486 (provide 'ivy)
1487
1488 ;;; ivy.el ends here