1 ;;; ivy.el --- Incremental Vertical completYon -*- lexical-binding: t -*-
3 ;; Copyright (C) 2015 Free Software Foundation, Inc.
5 ;; Author: Oleh Krehel <ohwoeowho@gmail.com>
6 ;; URL: https://github.com/abo-abo/swiper
8 ;; Package-Requires: ((emacs "24.1"))
11 ;; This file is part of GNU Emacs.
13 ;; This file is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 3, or (at your option)
18 ;; This program is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; For a full copy of the GNU General Public License
24 ;; see <http://www.gnu.org/licenses/>.
28 ;; This package provides `ivy-read' as an alternative to
29 ;; `completing-read' and similar functions.
31 ;; There's no intricate code to determine the best candidate.
32 ;; Instead, the user can navigate to it with `ivy-next-line' and
33 ;; `ivy-previous-line'.
35 ;; The matching is done by splitting the input text by spaces and
36 ;; re-building it into a regex.
37 ;; So "for example" is transformed into "\\(for\\).*\\(example\\)".
42 "Incremental vertical completion."
45 (defface ivy-current-match
46 '((t (:inherit highlight)))
47 "Face used by Ivy for highlighting first match.")
49 (defcustom ivy-height 10
50 "Number of lines for the minibuffer window."
53 (defcustom ivy-count-format "%-4d "
54 "The style of showing the current candidate count for `ivy-read'.
55 Set this to nil if you don't want the count."
58 (defcustom ivy-wrap nil
59 "Whether to wrap around after the first and last candidate."
62 (defcustom ivy-on-del-error-function 'minibuffer-keyboard-quit
63 "The handler for when `ivy-backward-delete-char' throws.
64 This is usually meant as a quick exit out of the minibuffer."
67 (defcustom ivy-extra-directories '("../" "./")
68 "Add this to the front of the list when completing file names.
69 Only \"./\" and \"../\" apply here. They appear in reverse order."
75 (defvar ivy-minibuffer-map
76 (let ((map (make-sparse-keymap)))
77 (define-key map (kbd "C-m") 'ivy-done)
78 (define-key map (kbd "C-j") 'ivy-alt-done)
79 (define-key map (kbd "C-n") 'ivy-next-line)
80 (define-key map (kbd "C-p") 'ivy-previous-line)
81 (define-key map (kbd "C-s") 'ivy-next-line-or-history)
82 (define-key map (kbd "C-r") 'ivy-previous-line-or-history)
83 (define-key map (kbd "SPC") 'self-insert-command)
84 (define-key map (kbd "DEL") 'ivy-backward-delete-char)
85 (define-key map (kbd "M-<") 'ivy-beginning-of-buffer)
86 (define-key map (kbd "M->") 'ivy-end-of-buffer)
87 (define-key map (kbd "M-n") 'ivy-next-history-element)
88 (define-key map (kbd "M-p") 'ivy-previous-history-element)
89 (define-key map (kbd "C-g") 'minibuffer-keyboard-quit)
91 "Keymap used in the minibuffer.")
93 (defvar ivy-history nil
94 "History list of candidates entered in the minibuffer.
96 Maximum length of the history list is determined by the value
97 of `history-length', which see.")
99 (defvar ivy-require-match t
100 "Store require-match. See `completing-read'.")
102 (defvar ivy--directory nil
103 "Current directory when completing file names.")
107 "Exit the minibuffer with the selected candidate."
109 (delete-minibuffer-contents)
110 (if (zerop ivy--length)
111 (when (memq ivy-require-match '(nil confirm confirm-after-completion))
113 (setq ivy-exit 'done))
115 (insert (expand-file-name ivy--current ivy--directory))
116 (insert ivy--current))
117 (setq ivy-exit 'done))
120 (defun ivy-alt-done ()
121 "Exit the minibuffer with the selected candidate."
124 (cond ((and ivy--directory
126 (= 0 (length ivy-text)))
131 (setq dir (expand-file-name
132 ivy--current ivy--directory))))
139 (defun ivy-beginning-of-buffer ()
140 "Select the first completion candidate."
144 (defun ivy-end-of-buffer ()
145 "Select the last completion candidate."
147 (setq ivy--index (1- ivy--length)))
149 (defun ivy-next-line (&optional arg)
150 "Move cursor vertically down ARG candidates."
152 (setq arg (or arg 1))
153 (cl-incf ivy--index arg)
154 (when (>= ivy--index (1- ivy--length))
156 (ivy-beginning-of-buffer)
157 (setq ivy--index (1- ivy--length)))))
159 (defun ivy-next-line-or-history (&optional arg)
160 "Move cursor vertically down ARG candidates.
161 If the input is empty, select the previous history element instead."
163 (when (string= ivy-text "")
164 (ivy-previous-history-element 1))
167 (defun ivy-previous-line (&optional arg)
168 "Move cursor vertically up ARG candidates."
170 (setq arg (or arg 1))
171 (cl-decf ivy--index arg)
172 (when (< ivy--index 0)
175 (setq ivy--index 0))))
177 (defun ivy-previous-line-or-history (arg)
178 "Move cursor vertically up ARG candidates.
179 If the input is empty, select the previous history element instead."
181 (when (string= ivy-text "")
182 (ivy-previous-history-element 1))
183 (ivy-previous-line arg))
185 (defun ivy-previous-history-element (arg)
186 "Forward to `previous-history-element' with ARG."
188 (previous-history-element arg)
189 (move-end-of-line 1))
191 (defun ivy-next-history-element (arg)
192 "Forward to `next-history-element' with ARG."
194 (next-history-element arg)
195 (move-end-of-line 1))
198 "When completing file names, move to directory DIR."
199 (if (null ivy--directory)
201 (setq ivy--old-cands nil)
202 (setq ivy--all-candidates
203 (ivy--sorted-files (setq ivy--directory dir)))
205 (delete-minibuffer-contents)))
207 (defun ivy-backward-delete-char ()
208 "Forward to `backward-delete-char'.
209 On error (read-only), call `ivy-on-del-error-function'."
211 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
213 (ivy--cd (file-name-directory
214 (directory-file-name ivy--directory)))
217 (backward-delete-char 1)
219 (when ivy-on-del-error-function
220 (funcall ivy-on-del-error-function))))))
222 (defun ivy--sorted-files (dir)
223 "Return the list of files in DIR.
224 Directories come first."
225 (let* ((default-directory dir)
226 (seq (all-completions "" 'read-file-name-internal)))
230 (delete "./" (delete "../" seq))
232 (if (file-directory-p x)
233 (if (file-directory-p y)
236 (if (file-directory-p y)
239 (dolist (dir ivy-extra-directories)
244 (defun ivy-read (prompt collection
245 &optional predicate initial-input keymap preselect update-fn)
246 "Read a string in the minibuffer, with completion.
248 PROMPT is a string to prompt with; normally it ends in a colon
249 and a space. When PROMPT contains %d, it will be updated with
250 the current number of matching candidates.
251 See also `ivy-count-format'.
253 COLLECTION is a list of strings.
255 If INITIAL-INPUT is non-nil, insert it in the minibuffer initially.
257 KEYMAP is composed together with `ivy-minibuffer-map'.
259 If PRESELECT is non-nil select the corresponding candidate out of
260 the ones that match INITIAL-INPUT.
262 UPDATE-FN is called each time the current candidate(s) is changed."
263 (setq ivy--directory nil)
264 (cond ((eq collection 'Info-read-node-name-1)
265 (if (equal Info-current-file "dir")
267 (mapcar (lambda (x) (format "(%s)" x))
268 (cl-delete-duplicates
269 (all-completions "(" collection predicate)
271 (setq collection (all-completions "" collection predicate))))
272 ((eq collection 'read-file-name-internal)
273 (setq ivy--directory default-directory)
274 (setq initial-input nil)
276 (ivy--sorted-files default-directory)))
277 ((or (functionp collection)
278 (vectorp collection))
279 (setq collection (all-completions "" collection predicate)))
280 ((hash-table-p collection)
281 (error "Hash table as a collection unsupported"))
282 ((listp (car collection))
283 (setq collection (all-completions "" collection predicate))))
285 (unless (or ivy-require-match
286 (all-completions preselect collection))
287 (setq collection (cons preselect collection))))
288 (cl-case (length collection)
294 (ivy--preselect-index
295 collection initial-input preselect))
297 (setq ivy--old-re nil)
298 (setq ivy--old-cands nil)
300 (setq ivy--all-candidates collection)
301 (setq ivy--update-fn update-fn)
303 (setq ivy--default (or (thing-at-point 'symbol) ""))
305 (cond ((string-match "%.*d" prompt)
307 ((string-match "%.*d" ivy-count-format)
308 (concat ivy-count-format prompt))
313 (setq ivy--action nil)
316 (minibuffer-with-setup-hook
317 #'ivy--minibuffer-setup
318 (let ((res (read-from-minibuffer
321 (make-composed-keymap keymap ivy-minibuffer-map)
324 (when (eq ivy-exit 'done)
327 (cons ivy-text (delete ivy-text ivy-history)))
329 (remove-hook 'post-command-hook #'ivy--exhibit))
331 (funcall ivy--action))))))
333 (defun ivy-completing-read (prompt collection
334 &optional predicate require-match initial-input
335 _history def _inherit-input-method)
336 "Read a string in the minibuffer, with completion.
338 This is an interface that conforms to `completing-read', so that
339 it can be used for `completing-read-function'.
341 PROMPT is a string to prompt with; normally it ends in a colon and a space.
342 COLLECTION can be a list of strings, an alist, an obarray or a hash table.
343 PREDICATE limits completion to a subset of COLLECTION.
345 REQUIRE-MATCH is stored into `ivy-require-match'. See `completing-read'.
346 INITIAL-INPUT is a string that can be inserted into the minibuffer initially.
347 _HISTORY is ignored for now.
348 DEF is the default value.
349 _INHERIT-INPUT-METHOD is ignored for now.
351 The history, defaults and input-method arguments are ignored for now."
353 (setq def (car def)))
354 (setq ivy-require-match require-match)
355 (ivy-read prompt collection predicate initial-input nil def))
358 (define-minor-mode ivy-mode
359 "Toggle Ivy mode on or off.
360 With ARG, turn Ivy mode on if arg is positive, off otherwise.
361 Turning on Ivy mode will set `completing-read-function' to
362 `ivy-completing-read'."
367 (setq completing-read-function 'ivy-completing-read)
368 (setq completing-read-function 'completing-read-default)))
370 (defvar ivy--action nil
371 "Store a function to call at the end of `ivy--read'.")
373 (defun ivy--preselect-index (candidates initial-input preselect)
374 "Return the index in CANDIDATES filtered by INITIAL-INPUT for PRESELECT."
379 (string-match initial-input x))
383 (string-match preselect x))
387 "Stores the user's string as it is typed in.")
390 "Store 'done if the completion was successfully selected.
391 Otherwise, store nil.")
395 (defvar ivy--subexps 0
396 "Number of groups in the current `ivy--regex'.")
398 (defvar ivy--regex-hash
399 (make-hash-table :test 'equal)
400 "Store pre-computed regex.")
402 (defun ivy--regex (str)
403 "Re-build regex from STR in case it has a space."
404 (let ((hashed (gethash str ivy--regex-hash)))
407 (setq ivy--subexps (car hashed)))
409 (let ((subs (split-string str " +" t)))
410 (if (= (length subs) 1)
412 (setq ivy--subexps 0)
415 (setq ivy--subexps (length subs))
417 (lambda (x) (format "\\(%s\\)" x))
423 (defun ivy--minibuffer-setup ()
424 "Setup ivy completion in the minibuffer."
425 (set (make-local-variable 'completion-show-inline-help) nil)
426 (set (make-local-variable 'minibuffer-default-add-function)
428 (list ivy--default)))
429 (use-local-map (make-composed-keymap ivy-minibuffer-map
430 (current-local-map)))
431 (setq-local max-mini-window-height ivy-height)
432 (add-hook 'post-command-hook #'ivy--exhibit nil t)
433 ;; show completions with empty input
436 (defvar ivy--all-candidates nil
437 "Store the candidates passed to `ivy-read'.")
440 "Store the index of the current candidate.")
442 (defvar ivy--length 0
443 "Store the amount of viable candidates.")
445 (defvar ivy--current ""
446 "Current candidate.")
448 (defvar ivy--default nil
449 "Default initial input.")
451 (defvar ivy--update-fn nil
452 "Current function to call when current candidate(s) update.")
455 "Return the current minibuffer input."
456 ;; assume one-line minibuffer input
457 (buffer-substring-no-properties
458 (minibuffer-prompt-end)
459 (line-end-position)))
461 (defun ivy--cleanup ()
462 "Delete the displayed completion candidates."
464 (goto-char (minibuffer-prompt-end))
465 (delete-region (line-end-position) (point-max))))
467 (defvar ivy--prompt nil
468 "Store the format-style prompt.
469 When non-nil, it should contain one %d.")
471 (defun ivy--insert-prompt ()
472 "Update the prompt according to `ivy--prompt'."
474 (let ((inhibit-read-only t)
478 (concat ivy--prompt (abbreviate-file-name ivy--directory))
479 ivy--prompt) ivy--length)))
481 (goto-char (point-min))
482 (delete-region (point-min) (minibuffer-prompt-end))
485 '(front-sticky t rear-nonsticky t field t read-only t face minibuffer-prompt)
488 ;; get out of the prompt area
489 (constrain-to-field nil (point-max)))))
491 (defun ivy--exhibit ()
492 "Insert Ivy completions display.
493 Should be run via minibuffer `post-command-hook'."
494 (setq ivy-text (ivy--input))
497 (if (string-match "/$" ivy-text)
498 (if (member ivy-text ivy--all-candidates)
499 (ivy--cd (expand-file-name ivy-text ivy--directory))
501 (if (string-match "~$" ivy-text)
502 (ivy--cd (expand-file-name "~/")))))
503 (let ((text (ivy-completions
505 ivy--all-candidates))
509 (funcall ivy--update-fn))
511 ;; Do nothing if while-no-input was aborted.
517 (defvar ivy--old-re nil
518 "Store the old regexp.")
520 (defvar ivy--old-cands nil
521 "Store the candidates matched by `ivy--old-re'.")
523 (defun ivy--add-face (str face)
524 "Propertize STR with FACE.
525 `font-lock-append-text-property' is used, since it's better than
526 `propertize' or `add-face-text-property' in this case."
527 (font-lock-append-text-property 0 (length str) 'face face str)
530 (defun ivy-completions (name candidates)
531 "Return as text the current completions.
532 NAME is a string of words separated by spaces that is used to
534 CANDIDATES is a list of strings."
535 (let* ((re (ivy--regex name))
536 (cands (if (and (equal re ivy--old-re)
541 (lambda (x) (string-match re x))
543 (tail (nthcdr ivy--index ivy--old-cands))
546 (when (and tail ivy--old-cands)
547 (unless (and (not (equal re ivy--old-re))
548 (setq ivy--index (cl-position re cands :test 'equal)))
549 (while (and tail (null idx))
550 ;; Compare with eq to handle equal duplicates in cands
551 (setq idx (cl-position (pop tail) cands)))
552 (setq ivy--index (or idx 0))))
553 (setq ivy--old-re re)
554 (setq ivy--length (length cands))
555 (setq ivy--old-cands cands)
556 (when (>= ivy--index ivy--length)
557 (setq ivy--index (max (1- ivy--length) 0)))
560 (let* ((half-height (/ ivy-height 2))
561 (start (max 0 (- ivy--index half-height)))
562 (end (min (+ start (1- ivy-height)) ivy--length))
563 (cands (cl-subseq cands start end))
564 (index (min ivy--index half-height (1- (length cands)))))
565 (setq ivy--current (copy-sequence (nth index cands)))
566 (setf (nth index cands)
567 (ivy--add-face ivy--current 'ivy-current-match))
568 (let ((res (concat "\n" (mapconcat
570 (if (> (length s) ww)
571 (concat (substring s 0 (- ww 3)) "...")
574 (put-text-property 0 (length res) 'read-only nil res)