]> code.delx.au - gnu-emacs-elpa/blob - ivy.el
ivy.el (ivy-alt-done): Find file if given a full tramp path
[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
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-previous-line-or-history)
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 (host (ivy-read "Find File: "
319 (mapcar #'ivy-build-tramp-name res)
320 :initial-input rest)))
321 (setq ivy-last old-ivy-last)
322 (when host
323 (setq ivy--directory "/")
324 (ivy--cd (concat "/" method ":" host ":"))))))
325 (t
326 (ivy-done)))))
327
328 (defcustom ivy-tab-space nil
329 "When non-nil, `ivy-partial-or-done' should insert a space."
330 :type 'boolean)
331
332 (defun ivy-partial-or-done ()
333 "Complete the minibuffer text as much as possible.
334 If the text hasn't changed as a result, forward to `ivy-alt-done'."
335 (interactive)
336 (if (and (eq (ivy-state-collection ivy-last) #'read-file-name-internal)
337 (string-match "\\`/" ivy-text))
338 (let ((default-directory ivy--directory))
339 (minibuffer-complete)
340 (setq ivy-text (ivy--input))
341 (when (and (file-directory-p ivy-text)
342 (= ivy--length 1))
343 (ivy--cd (expand-file-name ivy-text))))
344 (or (ivy-partial)
345 (when (or (eq this-command last-command)
346 (eq ivy--length 1))
347 (ivy-alt-done)))))
348
349 (defun ivy-partial ()
350 "Complete the minibuffer text as much as possible."
351 (interactive)
352 (let* ((parts (or (split-string ivy-text " " t) (list "")))
353 (postfix (car (last parts)))
354 (completion-ignore-case t)
355 (startp (string-match "^\\^" postfix))
356 (new (try-completion (if startp
357 (substring postfix 1)
358 postfix)
359 (mapcar (lambda (str) (substring str (string-match postfix str)))
360 ivy--old-cands))))
361 (cond ((eq new t) nil)
362 ((string= new ivy-text) nil)
363 (new
364 (delete-region (minibuffer-prompt-end) (point-max))
365 (setcar (last parts)
366 (if startp
367 (concat "^" new)
368 new))
369 (insert (mapconcat #'identity parts " ")
370 (if ivy-tab-space " " ""))
371 t))))
372
373 (defun ivy-immediate-done ()
374 "Exit the minibuffer with the current input."
375 (interactive)
376 (delete-minibuffer-contents)
377 (insert (setq ivy--current ivy-text))
378 (setq ivy-exit 'done)
379 (exit-minibuffer))
380
381 (defun ivy-resume ()
382 "Resume the last completion session."
383 (interactive)
384 (ivy-read
385 (ivy-state-prompt ivy-last)
386 (ivy-state-collection ivy-last)
387 :predicate (ivy-state-predicate ivy-last)
388 :require-match (ivy-state-require-match ivy-last)
389 :initial-input ivy-text
390 :history (ivy-state-history ivy-last)
391 :preselect (unless (eq (ivy-state-collection ivy-last)
392 'read-file-name-internal)
393 (regexp-quote ivy--current))
394 :keymap (ivy-state-keymap ivy-last)
395 :update-fn (ivy-state-update-fn ivy-last)
396 :sort (ivy-state-sort ivy-last)
397 :action (ivy-state-action ivy-last)
398 :unwind (ivy-state-unwind ivy-last)
399 :re-builder (ivy-state-re-builder ivy-last)
400 :matcher (ivy-state-matcher ivy-last)
401 :dynamic-collection (ivy-state-dynamic-collection ivy-last)))
402
403 (defvar ivy-calling nil
404 "When non-nil, call the current action when `ivy--index' changes.")
405
406 (defun ivy-set-index (index)
407 "Set `ivy--index' to INDEX."
408 (setq ivy--index index)
409 (when ivy-calling
410 (ivy--exhibit)
411 (ivy-call)))
412
413 (defun ivy-beginning-of-buffer ()
414 "Select the first completion candidate."
415 (interactive)
416 (ivy-set-index 0))
417
418 (defun ivy-end-of-buffer ()
419 "Select the last completion candidate."
420 (interactive)
421 (ivy-set-index (1- ivy--length)))
422
423 (defun ivy-scroll-up-command ()
424 "Scroll the candidates upward by the minibuffer height."
425 (interactive)
426 (ivy-set-index (min (+ ivy--index ivy-height)
427 (1- ivy--length))))
428
429 (defun ivy-scroll-down-command ()
430 "Scroll the candidates downward by the minibuffer height."
431 (interactive)
432 (ivy-set-index (max (- ivy--index ivy-height)
433 0)))
434 (defun ivy-minibuffer-grow ()
435 "Grow the minibuffer window by 1 line"
436 (interactive)
437 (setq-local max-mini-window-height
438 (cl-incf ivy-height)))
439
440 (defun ivy-minibuffer-shrink ()
441 "Shrink the minibuffer window by 1 line."
442 (interactive)
443 (unless (<= ivy-height 2)
444 (setq-local max-mini-window-height
445 (cl-decf ivy-height))
446 (window-resize (selected-window) -1)))
447
448 (defun ivy-next-line (&optional arg)
449 "Move cursor vertically down ARG candidates."
450 (interactive "p")
451 (setq arg (or arg 1))
452 (let ((index (+ ivy--index arg)))
453 (if (> index (1- ivy--length))
454 (if ivy-wrap
455 (ivy-beginning-of-buffer)
456 (ivy-set-index (1- ivy--length)))
457 (ivy-set-index index))))
458
459 (defun ivy-next-line-or-history (&optional arg)
460 "Move cursor vertically down ARG candidates.
461 If the input is empty, select the previous history element instead."
462 (interactive "p")
463 (when (string= ivy-text "")
464 (ivy-previous-history-element 1))
465 (ivy-next-line arg))
466
467 (defun ivy-previous-line (&optional arg)
468 "Move cursor vertically up ARG candidates."
469 (interactive "p")
470 (setq arg (or arg 1))
471 (let ((index (- ivy--index arg)))
472 (if (< index 0)
473 (if ivy-wrap
474 (ivy-end-of-buffer)
475 (ivy-set-index 0))
476 (ivy-set-index index))))
477
478 (defun ivy-previous-line-or-history (arg)
479 "Move cursor vertically up ARG candidates.
480 If the input is empty, select the previous history element instead."
481 (interactive "p")
482 (when (string= ivy-text "")
483 (ivy-previous-history-element 1))
484 (ivy-previous-line arg))
485
486 (defun ivy-toggle-calling ()
487 "Flip `ivy-calling'"
488 (interactive)
489 (when (setq ivy-calling (not ivy-calling))
490 (ivy-call)))
491
492 (defun ivy-call ()
493 "Call the current action without exiting completion."
494 (when (ivy-state-action ivy-last)
495 (with-selected-window (ivy-state-window ivy-last)
496 (funcall (ivy-state-action ivy-last) ivy--current))))
497
498 (defun ivy-next-line-and-call (&optional arg)
499 "Move cursor vertically down ARG candidates.
500 Call the permanent action if possible."
501 (interactive "p")
502 (ivy-next-line arg)
503 (ivy--exhibit)
504 (ivy-call))
505
506 (defun ivy-previous-line-and-call (&optional arg)
507 "Move cursor vertically down ARG candidates.
508 Call the permanent action if possible."
509 (interactive "p")
510 (ivy-previous-line arg)
511 (ivy--exhibit)
512 (ivy-call))
513
514 (defun ivy-previous-history-element (arg)
515 "Forward to `previous-history-element' with ARG."
516 (interactive "p")
517 (previous-history-element arg)
518 (ivy--cd-maybe)
519 (move-end-of-line 1)
520 (ivy--maybe-scroll-history))
521
522 (defun ivy-next-history-element (arg)
523 "Forward to `next-history-element' with ARG."
524 (interactive "p")
525 (next-history-element arg)
526 (ivy--cd-maybe)
527 (move-end-of-line 1)
528 (ivy--maybe-scroll-history))
529
530 (defun ivy--cd-maybe ()
531 "Check if the current input points to a different directory.
532 If so, move to that directory, while keeping only the file name."
533 (when ivy--directory
534 (let* ((input (expand-file-name (ivy--input)))
535 (file (file-name-nondirectory input))
536 (dir (expand-file-name (file-name-directory input))))
537 (if (string= dir ivy--directory)
538 (progn
539 (delete-minibuffer-contents)
540 (insert file))
541 (ivy--cd dir)
542 (insert file)))))
543
544 (defun ivy--maybe-scroll-history ()
545 "If the selected history element has an index, scroll there."
546 (let ((idx (ignore-errors
547 (get-text-property
548 (minibuffer-prompt-end)
549 'ivy-index))))
550 (when idx
551 (ivy--exhibit)
552 (setq ivy--index idx))))
553
554 (defun ivy--cd (dir)
555 "When completing file names, move to directory DIR."
556 (if (null ivy--directory)
557 (error "Unexpected")
558 (setq ivy--old-cands nil)
559 (setq ivy--old-re nil)
560 (setq ivy--index 0)
561 (setq ivy--all-candidates
562 (ivy--sorted-files (setq ivy--directory dir)))
563 (setq ivy-text "")
564 (delete-minibuffer-contents)))
565
566 (defun ivy-backward-delete-char ()
567 "Forward to `backward-delete-char'.
568 On error (read-only), call `ivy-on-del-error-function'."
569 (interactive)
570 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
571 (progn
572 (ivy--cd (file-name-directory
573 (directory-file-name
574 (expand-file-name
575 ivy--directory))))
576 (ivy--exhibit))
577 (condition-case nil
578 (backward-delete-char 1)
579 (error
580 (when ivy-on-del-error-function
581 (funcall ivy-on-del-error-function))))))
582
583 (defun ivy-delete-char (arg)
584 "Forward to `delete-char' ARG."
585 (interactive "p")
586 (unless (= (point) (line-end-position))
587 (delete-char arg)))
588
589 (defun ivy-forward-char (arg)
590 "Forward to `forward-char' ARG."
591 (interactive "p")
592 (unless (= (point) (line-end-position))
593 (forward-char arg)))
594
595 (defun ivy-kill-word (arg)
596 "Forward to `kill-word' ARG."
597 (interactive "p")
598 (unless (= (point) (line-end-position))
599 (kill-word arg)))
600
601 (defun ivy-kill-line ()
602 "Forward to `kill-line'."
603 (interactive)
604 (if (eolp)
605 (kill-region (minibuffer-prompt-end) (point))
606 (kill-line)))
607
608 (defun ivy-backward-kill-word ()
609 "Forward to `backward-kill-word'."
610 (interactive)
611 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
612 (progn
613 (ivy--cd (file-name-directory
614 (directory-file-name
615 (expand-file-name
616 ivy--directory))))
617 (ivy--exhibit))
618 (ignore-errors
619 (backward-kill-word 1))))
620
621 (defvar ivy--regexp-quote 'regexp-quote
622 "Store the regexp quoting state.")
623
624 (defun ivy-toggle-regexp-quote ()
625 "Toggle the regexp quoting."
626 (interactive)
627 (setq ivy--old-re nil)
628 (cl-rotatef ivy--regex-function ivy--regexp-quote))
629
630 (defun ivy-sort-file-function-default (x y)
631 "Compare two files X and Y.
632 Prioritize directories."
633 (if (get-text-property 0 'dirp x)
634 (if (get-text-property 0 'dirp y)
635 (string< x y)
636 t)
637 (if (get-text-property 0 'dirp y)
638 nil
639 (string< x y))))
640
641 (defvar ivy-sort-functions-alist
642 '((read-file-name-internal . ivy-sort-file-function-default)
643 (internal-complete-buffer . nil)
644 (counsel-git-grep-function . nil)
645 (Man-goto-section . nil)
646 (org-refile . nil)
647 (t . string-lessp))
648 "An alist of sorting functions for each collection function.
649 Interactive functions that call completion fit in here as well.
650
651 For each entry, nil means no sorting. It's very useful to turn
652 off the sorting for functions that have candidates in the natural
653 buffer order, like `org-refile' or `Man-goto-section'.
654
655 The entry associated to t is used for all fall-through cases.")
656
657 (defvar ivy-re-builders-alist
658 '((t . ivy--regex-plus))
659 "An alist of regex building functions for each collection function.
660 Each function should take a string and return a valid regex or a
661 regex sequence (see below).
662
663 The entry associated to t is used for all fall-through cases.
664 Possible choices: `ivy--regex', `regexp-quote', `ivy--regex-plus'.
665
666 In case a function returns a list, it should look like this:
667 '((\"matching-regexp\" . t) (\"non-matching-regexp\") ...).
668
669 The matches will be filtered in a sequence, you can mix the
670 regexps that should match and that should not match as you
671 like.")
672
673 (defvar ivy-initial-inputs-alist
674 '((org-refile . "^")
675 (counsel-M-x . "^")
676 (counsel-describe-function . "^")
677 (counsel-describe-variable . "^")
678 (man . "^")
679 (woman . "^"))
680 "Command to initial input table.")
681
682 (defcustom ivy-sort-max-size 30000
683 "Sorting won't be done for collections larger than this."
684 :type 'integer)
685
686 (defun ivy--sorted-files (dir)
687 "Return the list of files in DIR.
688 Directories come first."
689 (let* ((default-directory dir)
690 (seq (all-completions "" 'read-file-name-internal))
691 sort-fn)
692 (if (equal dir "/")
693 seq
694 (setq seq (delete "./" (delete "../" seq)))
695 (when (eq (setq sort-fn (cdr (assoc 'read-file-name-internal
696 ivy-sort-functions-alist)))
697 #'ivy-sort-file-function-default)
698 (setq seq (mapcar (lambda (x)
699 (propertize x 'dirp (string-match-p "/\\'" x)))
700 seq)))
701 (when sort-fn
702 (setq seq (cl-sort seq sort-fn)))
703 (dolist (dir ivy-extra-directories)
704 (push dir seq))
705 seq)))
706
707 ;;** Entry Point
708 (cl-defun ivy-read (prompt collection
709 &key predicate require-match initial-input
710 history preselect keymap update-fn sort
711 action unwind re-builder matcher dynamic-collection)
712 "Read a string in the minibuffer, with completion.
713
714 PROMPT is a string to prompt with; normally it ends in a colon
715 and a space. When PROMPT contains %d, it will be updated with
716 the current number of matching candidates.
717 See also `ivy-count-format'.
718
719 COLLECTION is a list of strings.
720
721 If INITIAL-INPUT is non-nil, insert it in the minibuffer initially.
722
723 KEYMAP is composed together with `ivy-minibuffer-map'.
724
725 If PRESELECT is non-nil select the corresponding candidate out of
726 the ones that match INITIAL-INPUT.
727
728 UPDATE-FN is called each time the current candidate(s) is changed.
729
730 When SORT is t, refer to `ivy-sort-functions-alist' for sorting.
731
732 ACTION is a lambda to call after a result was selected. It should
733 take a single argument, usually a string.
734
735 UNWIND is a lambda to call before exiting.
736
737 RE-BUILDER is a lambda that transforms text into a regex.
738
739 MATCHER can completely override matching.
740
741 DYNAMIC-COLLECTION is a function to call to update the list of
742 candidates with each input."
743 (unless initial-input
744 (setq initial-input (cdr (assoc this-command
745 ivy-initial-inputs-alist))))
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 (setq ivy--directory nil)
765 (setq ivy--regex-function
766 (or re-builder
767 (and (functionp collection)
768 (cdr (assoc collection ivy-re-builders-alist)))
769 (cdr (assoc t ivy-re-builders-alist))
770 'ivy--regex))
771 (setq ivy--subexps 0)
772 (setq ivy--regexp-quote 'regexp-quote)
773 (setq ivy--old-text "")
774 (setq ivy-text "")
775 (setq ivy-calling nil)
776 (let (coll sort-fn)
777 (cond ((eq collection 'Info-read-node-name-1)
778 (if (equal Info-current-file "dir")
779 (setq coll
780 (mapcar (lambda (x) (format "(%s)" x))
781 (cl-delete-duplicates
782 (all-completions "(" collection predicate)
783 :test #'equal)))
784 (setq coll (all-completions "" collection predicate))))
785 ((eq collection 'read-file-name-internal)
786 (setq ivy--directory default-directory)
787 (require 'dired)
788 (setq coll
789 (ivy--sorted-files default-directory))
790 (when initial-input
791 (unless (or require-match
792 (equal initial-input default-directory)
793 (equal initial-input ""))
794 (setq coll (cons initial-input coll)))
795 (setq initial-input nil)))
796 ((eq collection 'internal-complete-buffer)
797 (setq coll (ivy--buffer-list "" ivy-use-virtual-buffers)))
798 ((or (functionp collection)
799 (vectorp collection)
800 (listp (car collection)))
801 (setq coll (all-completions "" collection predicate)))
802 ((hash-table-p collection)
803 (error "Hash table as a collection unsupported"))
804 (t
805 (setq coll collection)))
806 (when sort
807 (if (and (functionp collection)
808 (setq sort-fn (assoc collection ivy-sort-functions-alist)))
809 (when (and (setq sort-fn (cdr sort-fn))
810 (not (eq collection 'read-file-name-internal)))
811 (setq coll (cl-sort coll sort-fn)))
812 (unless (eq history 'org-refile-history)
813 (if (and (setq sort-fn (cdr (assoc t ivy-sort-functions-alist)))
814 (<= (length coll) ivy-sort-max-size))
815 (setq coll (cl-sort (copy-sequence coll) sort-fn))))))
816 (when preselect
817 (unless (or (and require-match
818 (not (eq collection 'internal-complete-buffer)))
819 (let ((re (format "\\`%s" (regexp-quote preselect))))
820 (cl-find-if (lambda (x) (string-match re x))
821 coll)))
822 (setq coll (cons preselect coll))))
823 (setq ivy--index (or
824 (and dynamic-collection
825 ivy--index)
826 (and preselect
827 (ivy--preselect-index
828 coll initial-input preselect))
829 0))
830 (setq ivy--old-re nil)
831 (setq ivy--old-cands nil)
832 (setq ivy--all-candidates coll)
833 (setq ivy-exit nil)
834 (setq ivy--default (or (thing-at-point 'symbol) ""))
835 (setq ivy--prompt
836 (cond ((string-match "%.*d" prompt)
837 prompt)
838 ((string-match "%.*d" ivy-count-format)
839 (concat ivy-count-format prompt))
840 (ivy--directory
841 prompt)
842 (t
843 nil)))
844 (prog1
845 (unwind-protect
846 (minibuffer-with-setup-hook
847 #'ivy--minibuffer-setup
848 (let* ((hist (or history 'ivy-history))
849 (minibuffer-completion-table collection)
850 (minibuffer-completion-predicate predicate)
851 (res (read-from-minibuffer
852 prompt
853 initial-input
854 (make-composed-keymap keymap ivy-minibuffer-map)
855 nil
856 hist)))
857 (when (eq ivy-exit 'done)
858 (let ((item (if ivy--directory
859 ivy--current
860 ivy-text)))
861 (set hist (cons (propertize item 'ivy-index ivy--index)
862 (delete item
863 (cdr (symbol-value hist))))))
864 res)))
865 (remove-hook 'post-command-hook #'ivy--exhibit)
866 (when (setq unwind (ivy-state-unwind ivy-last))
867 (funcall unwind)))
868 (when (setq action (ivy-state-action ivy-last))
869 (funcall action ivy--current)))))
870
871 (defun ivy-completing-read (prompt collection
872 &optional predicate require-match initial-input
873 history def _inherit-input-method)
874 "Read a string in the minibuffer, with completion.
875
876 This is an interface that conforms to `completing-read', so that
877 it can be used for `completing-read-function'.
878
879 PROMPT is a string to prompt with; normally it ends in a colon and a space.
880 COLLECTION can be a list of strings, an alist, an obarray or a hash table.
881 PREDICATE limits completion to a subset of COLLECTION.
882 REQUIRE-MATCH is considered boolean. See `completing-read'.
883 INITIAL-INPUT is a string that can be inserted into the minibuffer initially.
884 _HISTORY is ignored for now.
885 DEF is the default value.
886 _INHERIT-INPUT-METHOD is ignored for now.
887
888 The history, defaults and input-method arguments are ignored for now."
889 (ivy-read prompt collection
890 :predicate predicate
891 :require-match require-match
892 :initial-input (if (consp initial-input)
893 (car initial-input)
894 initial-input)
895 :preselect (if (listp def) (car def) def)
896 :history history
897 :keymap nil
898 :sort
899 (let ((sort (assoc this-command ivy-sort-functions-alist)))
900 (if sort
901 (cdr sort)
902 t))))
903
904 ;;;###autoload
905 (define-minor-mode ivy-mode
906 "Toggle Ivy mode on or off.
907 With ARG, turn Ivy mode on if arg is positive, off otherwise.
908 Turning on Ivy mode will set `completing-read-function' to
909 `ivy-completing-read'.
910
911 Global bindings:
912 \\{ivy-mode-map}
913
914 Minibuffer bindings:
915 \\{ivy-minibuffer-map}"
916 :group 'ivy
917 :global t
918 :keymap ivy-mode-map
919 :lighter " ivy"
920 (if ivy-mode
921 (setq completing-read-function 'ivy-completing-read)
922 (setq completing-read-function 'completing-read-default)))
923
924 (defun ivy--preselect-index (candidates initial-input preselect)
925 "Return the index in CANDIDATES filtered by INITIAL-INPUT for PRESELECT."
926 (when initial-input
927 (setq initial-input (ivy--regex-plus initial-input))
928 (setq candidates
929 (cl-remove-if-not
930 (lambda (x)
931 (string-match initial-input x))
932 candidates)))
933 (or (cl-position preselect candidates :test #'equal)
934 (cl-position-if
935 (lambda (x)
936 (string-match (regexp-quote preselect) x))
937 candidates)))
938
939 ;;* Implementation
940 ;;** Regex
941 (defvar ivy--regex-hash
942 (make-hash-table :test #'equal)
943 "Store pre-computed regex.")
944
945 (defun ivy--split (str)
946 "Split STR into a list by single spaces.
947 The remaining spaces stick to their left.
948 This allows to \"quote\" N spaces by inputting N+1 spaces."
949 (let ((len (length str))
950 start0
951 (start1 0)
952 res s
953 match-len)
954 (while (and (string-match " +" str start1)
955 (< start1 len))
956 (setq match-len (- (match-end 0) (match-beginning 0)))
957 (if (= match-len 1)
958 (progn
959 (when start0
960 (setq start1 start0)
961 (setq start0 nil))
962 (push (substring str start1 (match-beginning 0)) res)
963 (setq start1 (match-end 0)))
964 (setq str (replace-match
965 (make-string (1- match-len) ?\ )
966 nil nil str))
967 (setq start0 (or start0 start1))
968 (setq start1 (1- (match-end 0)))))
969 (if start0
970 (push (substring str start0) res)
971 (setq s (substring str start1))
972 (unless (= (length s) 0)
973 (push s res)))
974 (nreverse res)))
975
976 (defun ivy--regex (str &optional greedy)
977 "Re-build regex from STR in case it has a space.
978 When GREEDY is non-nil, join words in a greedy way."
979 (let ((hashed (unless greedy
980 (gethash str ivy--regex-hash))))
981 (if hashed
982 (prog1 (cdr hashed)
983 (setq ivy--subexps (car hashed)))
984 (cdr (puthash str
985 (let ((subs (ivy--split str)))
986 (if (= (length subs) 1)
987 (cons
988 (setq ivy--subexps 0)
989 (car subs))
990 (cons
991 (setq ivy--subexps (length subs))
992 (mapconcat
993 (lambda (x)
994 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
995 x
996 (format "\\(%s\\)" x)))
997 subs
998 (if greedy
999 ".*"
1000 ".*?")))))
1001 ivy--regex-hash)))))
1002
1003 (defun ivy--regex-ignore-order (str)
1004 "Re-build regex from STR by splitting it on spaces.
1005 Ignore the order of each group."
1006 (let* ((subs (split-string str " +" t))
1007 (len (length subs)))
1008 (cl-case len
1009 (1
1010 (setq ivy--subexps 0)
1011 (car subs))
1012 (t
1013 (setq ivy--subexps len)
1014 (let ((all (mapconcat #'identity subs "\\|")))
1015 (mapconcat
1016 (lambda (x)
1017 (if (string-match "\\`\\\\(.*\\\\)\\'" x)
1018 x
1019 (format "\\(%s\\)" x)))
1020 (make-list len all)
1021 ".*?"))))))
1022
1023 (defun ivy--regex-plus (str)
1024 "Build a regex sequence from STR.
1025 Spaces are wild, everything before \"!\" should match.
1026 Everything after \"!\" should not match."
1027 (let ((parts (split-string str "!" t)))
1028 (cl-case (length parts)
1029 (0
1030 "")
1031 (1
1032 (ivy--regex (car parts)))
1033 (2
1034 (let ((res
1035 (mapcar #'list
1036 (split-string (cadr parts) " " t))))
1037 (cons (cons (ivy--regex (car parts)) t)
1038 res)))
1039 (t (error "Unexpected: use only one !")))))
1040
1041 (defun ivy--regex-fuzzy (str)
1042 "Build a regex sequence from STR.
1043 Insert .* between each char."
1044 (if (string-match "\\`\\(\\^?\\)\\(.*?\\)\\(\\$?\\)\\'" str)
1045 (concat (match-string 1 str)
1046 (mapconcat #'string (string-to-list (match-string 2 str)) ".*")
1047 (match-string 3 str))
1048 str))
1049
1050 ;;** Rest
1051 (defun ivy--minibuffer-setup ()
1052 "Setup ivy completion in the minibuffer."
1053 (set (make-local-variable 'completion-show-inline-help) nil)
1054 (set (make-local-variable 'minibuffer-default-add-function)
1055 (lambda ()
1056 (list ivy--default)))
1057 (setq-local max-mini-window-height ivy-height)
1058 (add-hook 'post-command-hook #'ivy--exhibit nil t)
1059 ;; show completions with empty input
1060 (ivy--exhibit))
1061
1062 (defun ivy--input ()
1063 "Return the current minibuffer input."
1064 ;; assume one-line minibuffer input
1065 (buffer-substring-no-properties
1066 (minibuffer-prompt-end)
1067 (line-end-position)))
1068
1069 (defun ivy--cleanup ()
1070 "Delete the displayed completion candidates."
1071 (save-excursion
1072 (goto-char (minibuffer-prompt-end))
1073 (delete-region (line-end-position) (point-max))))
1074
1075 (defun ivy--insert-prompt ()
1076 "Update the prompt according to `ivy--prompt'."
1077 (when ivy--prompt
1078 (unless (memq this-command '(ivy-done ivy-alt-done ivy-partial-or-done
1079 counsel-find-symbol))
1080 (setq ivy--prompt-extra ""))
1081 (let (head tail)
1082 (if (string-match "\\(.*\\): \\'" ivy--prompt)
1083 (progn
1084 (setq head (match-string 1 ivy--prompt))
1085 (setq tail ": "))
1086 (setq head (substring ivy--prompt 0 -1))
1087 (setq tail " "))
1088 (let ((inhibit-read-only t)
1089 (std-props '(front-sticky t rear-nonsticky t field t read-only t))
1090 (n-str
1091 (format
1092 (concat
1093 (if (and (bound-and-true-p minibuffer-depth-indicate-mode)
1094 (> (minibuffer-depth) 1))
1095 (format "[%d] " (minibuffer-depth))
1096 "")
1097 head
1098 ivy--prompt-extra
1099 tail
1100 (if ivy--directory
1101 (abbreviate-file-name ivy--directory)
1102 ""))
1103 (or (and (ivy-state-dynamic-collection ivy-last)
1104 ivy--full-length)
1105 ivy--length))))
1106 (save-excursion
1107 (goto-char (point-min))
1108 (delete-region (point-min) (minibuffer-prompt-end))
1109 (set-text-properties 0 (length n-str)
1110 `(face minibuffer-prompt ,@std-props)
1111 n-str)
1112 (ivy--set-match-props n-str "confirm"
1113 `(face ivy-confirm-face ,@std-props))
1114 (ivy--set-match-props n-str "match required"
1115 `(face ivy-match-required-face ,@std-props))
1116 (insert n-str))
1117 ;; get out of the prompt area
1118 (constrain-to-field nil (point-max))))))
1119
1120 (defun ivy--set-match-props (str match props)
1121 "Set STR text proprties that match MATCH to PROPS."
1122 (when (string-match match str)
1123 (set-text-properties
1124 (match-beginning 0)
1125 (match-end 0)
1126 props
1127 str)))
1128
1129 (defvar inhibit-message)
1130
1131 (defun ivy--exhibit ()
1132 "Insert Ivy completions display.
1133 Should be run via minibuffer `post-command-hook'."
1134 (setq ivy-text (ivy--input))
1135 (if (ivy-state-dynamic-collection ivy-last)
1136 ;; while-no-input would cause annoying
1137 ;; "Waiting for process to die...done" message interruptions
1138 (let ((inhibit-message t))
1139 (unless (equal ivy--old-text ivy-text)
1140 (while-no-input
1141 ;; dynamic collection should take care of everything
1142 (funcall (ivy-state-dynamic-collection ivy-last) ivy-text)
1143 (setq ivy--old-text ivy-text)))
1144 (unless (eq ivy--full-length -1)
1145 (ivy--insert-minibuffer
1146 (ivy--format ivy--all-candidates))))
1147 (cond (ivy--directory
1148 (if (string-match "/\\'" ivy-text)
1149 (if (member ivy-text ivy--all-candidates)
1150 (ivy--cd (expand-file-name ivy-text ivy--directory))
1151 (when (string-match "//\\'" ivy-text)
1152 (ivy--cd "/")))
1153 (if (string-match "~\\'" ivy-text)
1154 (ivy--cd (expand-file-name "~/")))))
1155 ((eq (ivy-state-collection ivy-last) 'internal-complete-buffer)
1156 (when (or (and (string-match "\\` " ivy-text)
1157 (not (string-match "\\` " ivy--old-text)))
1158 (and (string-match "\\` " ivy--old-text)
1159 (not (string-match "\\` " ivy-text))))
1160 (setq ivy--all-candidates
1161 (if (and (> (length ivy-text) 0)
1162 (eq (aref ivy-text 0)
1163 ?\ ))
1164 (ivy--buffer-list " ")
1165 (ivy--buffer-list "" ivy-use-virtual-buffers)))
1166 (setq ivy--old-re nil))))
1167 (ivy--insert-minibuffer
1168 (ivy--format
1169 (ivy--filter ivy-text ivy--all-candidates)))
1170 (setq ivy--old-text ivy-text)))
1171
1172 (defun ivy--insert-minibuffer (text)
1173 "Insert TEXT into minibuffer with appropriate cleanup."
1174 (let ((resize-mini-windows nil)
1175 (update-fn (ivy-state-update-fn ivy-last))
1176 deactivate-mark)
1177 (ivy--cleanup)
1178 (when update-fn
1179 (funcall update-fn))
1180 (ivy--insert-prompt)
1181 ;; Do nothing if while-no-input was aborted.
1182 (when (stringp text)
1183 (let ((buffer-undo-list t))
1184 (save-excursion
1185 (forward-line 1)
1186 (insert text))))))
1187
1188 (declare-function colir-blend-face-background "ext:colir")
1189
1190 (defun ivy--add-face (str face)
1191 "Propertize STR with FACE.
1192 `font-lock-append-text-property' is used, since it's better than
1193 `propertize' or `add-face-text-property' in this case."
1194 (require 'colir)
1195 (condition-case nil
1196 (colir-blend-face-background 0 (length str) face str)
1197 (error
1198 (ignore-errors
1199 (font-lock-append-text-property 0 (length str) 'face face str))))
1200 str)
1201
1202 (defun ivy--filter (name candidates)
1203 "Return all items that match NAME in CANDIDATES.
1204 CANDIDATES are assumed to be static."
1205 (let* ((re (funcall ivy--regex-function name))
1206 (matcher (ivy-state-matcher ivy-last))
1207 (cands (cond
1208 (matcher
1209 (funcall matcher re candidates))
1210 ((and (equal re ivy--old-re)
1211 ivy--old-cands)
1212 ivy--old-cands)
1213 ((and ivy--old-re
1214 (stringp re)
1215 (stringp ivy--old-re)
1216 (not (string-match "\\\\" ivy--old-re))
1217 (not (equal ivy--old-re ""))
1218 (memq (cl-search
1219 (if (string-match "\\\\)\\'" ivy--old-re)
1220 (substring ivy--old-re 0 -2)
1221 ivy--old-re)
1222 re)
1223 '(0 2)))
1224 (ignore-errors
1225 (cl-remove-if-not
1226 (lambda (x) (string-match re x))
1227 ivy--old-cands)))
1228 (t
1229 (let ((re-list (if (stringp re) (list (cons re t)) re))
1230 (res candidates))
1231 (dolist (re re-list)
1232 (setq res
1233 (ignore-errors
1234 (funcall
1235 (if (cdr re)
1236 #'cl-remove-if-not
1237 #'cl-remove-if)
1238 (let ((re (car re)))
1239 (lambda (x) (string-match re x)))
1240 res))))
1241 res))))
1242 (tail (nthcdr ivy--index ivy--old-cands))
1243 idx)
1244 (when (and tail ivy--old-cands)
1245 (unless (and (not (equal re ivy--old-re))
1246 (or (setq ivy--index
1247 (or
1248 (cl-position re cands
1249 :test #'equal)
1250 (and ivy--directory
1251 (cl-position
1252 (concat re "/") cands
1253 :test #'equal))))))
1254 (while (and tail (null idx))
1255 ;; Compare with eq to handle equal duplicates in cands
1256 (setq idx (cl-position (pop tail) cands)))
1257 (setq ivy--index (or idx 0))))
1258 (when (and (string= name "") (not (equal ivy--old-re "")))
1259 (setq ivy--index
1260 (or (cl-position (ivy-state-preselect ivy-last)
1261 cands :test #'equal)
1262 ivy--index)))
1263 (setq ivy--old-re (if cands re ""))
1264 (setq ivy--old-cands cands)))
1265
1266 (defvar ivy-format-function 'ivy-format-function-default
1267 "Function to transform the list of candidates into a string.
1268 This string will be inserted into the minibuffer.")
1269
1270 (defun ivy-format-function-default (cands)
1271 "Transform CANDS into a string for minibuffer."
1272 (let ((ww (window-width)))
1273 (mapconcat
1274 (lambda (s)
1275 (if (> (length s) ww)
1276 (concat (substring s 0 (- ww 3)) "...")
1277 s))
1278 cands "\n")))
1279
1280 (defun ivy-format-function-arrow (cands)
1281 "Transform CANDS into a string for minibuffer."
1282 (let ((i -1))
1283 (mapconcat
1284 (lambda (s)
1285 (concat (if (eq (cl-incf i) ivy--index)
1286 "> "
1287 " ")
1288 s))
1289 cands "\n")))
1290
1291 (defun ivy--format (cands)
1292 "Return a string for CANDS suitable for display in the minibuffer.
1293 CANDS is a list of strings."
1294 (setq ivy--length (length cands))
1295 (when (>= ivy--index ivy--length)
1296 (setq ivy--index (max (1- ivy--length) 0)))
1297 (if (null cands)
1298 (setq ivy--current "")
1299 (let* ((half-height (/ ivy-height 2))
1300 (start (max 0 (- ivy--index half-height)))
1301 (end (min (+ start (1- ivy-height)) ivy--length))
1302 (start (max 0 (min start (- end (1- ivy-height)))))
1303 (cands (cl-subseq cands start end))
1304 (index (- ivy--index start)))
1305 (when ivy--directory
1306 (setq cands (mapcar (lambda (x)
1307 (if (string-match-p "/\\'" x)
1308 (propertize x 'face 'ivy-subdir)
1309 x))
1310 cands)))
1311 (setq ivy--current (copy-sequence (nth index cands)))
1312 (setf (nth index cands)
1313 (ivy--add-face ivy--current 'ivy-current-match))
1314 (let* ((ivy--index index)
1315 (res (concat "\n" (funcall ivy-format-function cands))))
1316 (put-text-property 0 (length res) 'read-only nil res)
1317 res))))
1318
1319 (defvar ivy--virtual-buffers nil
1320 "Store the virtual buffers alist.")
1321
1322 (defvar recentf-list)
1323
1324 (defface ivy-virtual '((t :inherit font-lock-builtin-face))
1325 "Face used by Ivy for matching virtual buffer names.")
1326
1327 (defun ivy--virtual-buffers ()
1328 "Adapted from `ido-add-virtual-buffers-to-list'."
1329 (unless recentf-mode
1330 (recentf-mode 1))
1331 (let ((bookmarks (and (boundp 'bookmark-alist)
1332 bookmark-alist))
1333 virtual-buffers name)
1334 (dolist (head (append
1335 recentf-list
1336 (delete " - no file -"
1337 (delq nil (mapcar (lambda (bookmark)
1338 (cdr (assoc 'filename bookmark)))
1339 bookmarks)))))
1340 (setq name (file-name-nondirectory head))
1341 (when (equal name "")
1342 (setq name (file-name-nondirectory (directory-file-name head))))
1343 (when (equal name "")
1344 (setq name head))
1345 (and (not (equal name ""))
1346 (null (get-file-buffer head))
1347 (not (assoc name virtual-buffers))
1348 (push (cons name head) virtual-buffers)))
1349 (when virtual-buffers
1350 (dolist (comp virtual-buffers)
1351 (put-text-property 0 (length (car comp))
1352 'face 'ivy-virtual
1353 (car comp)))
1354 (setq ivy--virtual-buffers (nreverse virtual-buffers))
1355 (mapcar #'car ivy--virtual-buffers))))
1356
1357 (defun ivy--buffer-list (str &optional virtual)
1358 "Return the buffers that match STR.
1359 When VIRTUAL is non-nil, add virtual buffers."
1360 (delete-dups
1361 (append
1362 (mapcar
1363 (lambda (x)
1364 (if (with-current-buffer x
1365 (file-remote-p
1366 (abbreviate-file-name default-directory)))
1367 (propertize x 'face 'ivy-remote)
1368 x))
1369 (all-completions str 'internal-complete-buffer))
1370 (and virtual
1371 (ivy--virtual-buffers)))))
1372
1373 (defun ivy--switch-buffer-action (buffer)
1374 "Switch to BUFFER.
1375 BUFFER may be a string or nil."
1376 (if (zerop (length buffer))
1377 (switch-to-buffer
1378 ivy-text nil 'force-same-window)
1379 (let ((virtual (assoc buffer ivy--virtual-buffers)))
1380 (if (and virtual
1381 (not (get-buffer buffer)))
1382 (find-file (cdr virtual))
1383 (switch-to-buffer
1384 buffer nil 'force-same-window)))))
1385
1386 (defun ivy-switch-buffer ()
1387 "Switch to another buffer."
1388 (interactive)
1389 (if (not ivy-mode)
1390 (call-interactively 'switch-to-buffer)
1391 (ivy-read "Switch to buffer: " 'internal-complete-buffer
1392 :preselect (buffer-name (other-buffer (current-buffer)))
1393 :action #'ivy--switch-buffer-action)))
1394
1395 (defun ivy-recentf ()
1396 "Find a file on `recentf-list'."
1397 (interactive)
1398 (ivy-read "Recentf: " recentf-list
1399 :action #'find-file))
1400
1401 (defun ivy-yank-word ()
1402 "Pull next word from buffer into search string."
1403 (interactive)
1404 (let (amend)
1405 (with-selected-window (ivy-state-window ivy-last)
1406 (let ((pt (point))
1407 (le (line-end-position)))
1408 (forward-word 1)
1409 (if (> (point) le)
1410 (goto-char pt)
1411 (setq amend (buffer-substring-no-properties pt (point))))))
1412 (when amend
1413 (insert amend))))
1414
1415 (defun ivy-insert-current ()
1416 "Make the current candidate into current input.
1417 Don't finish completion."
1418 (interactive)
1419 (delete-minibuffer-contents)
1420 (if (and ivy--directory
1421 (string-match "/$" ivy--current))
1422 (insert (substring ivy--current 0 -1))
1423 (insert ivy--current)))
1424
1425 (defun ivy-toggle-fuzzy ()
1426 "Toggle the re builder between `ivy--regex-fuzzy' and `ivy--regex-plus'."
1427 (interactive)
1428 (setq ivy--old-re nil)
1429 (if (eq ivy--regex-function 'ivy--regex-fuzzy)
1430 (setq ivy--regex-function 'ivy--regex-plus)
1431 (setq ivy--regex-function 'ivy--regex-fuzzy)))
1432
1433 (provide 'ivy)
1434
1435 ;;; ivy.el ends here