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