]> code.delx.au - gnu-emacs-elpa/blob - packages/swiper/ivy.el
Merge commit 'b128272d475ecb392f32fbc3e5832d76af33446b' from swiper
[gnu-emacs-elpa] / packages / swiper / ivy.el
1 ;;; ivy.el --- Incremental Vertical completYon -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2015 Free Software Foundation, Inc.
4
5 ;; Author: Oleh Krehel <ohwoeowho@gmail.com>
6 ;; URL: https://github.com/abo-abo/swiper
7 ;; Version: 0.2.3
8 ;; Package-Requires: ((emacs "24.1"))
9 ;; Keywords: matching
10
11 ;; This file is part of GNU Emacs.
12
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)
16 ;; any later version.
17
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.
22
23 ;; For a full copy of the GNU General Public License
24 ;; see <http://www.gnu.org/licenses/>.
25
26 ;;; Commentary:
27 ;;
28 ;; This package provides `ivy-read' as an alternative to
29 ;; `completing-read' and similar functions.
30 ;;
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'.
34 ;;
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\\)".
38
39 (require 'cl-lib)
40
41 ;;; Code:
42 ;;* Customization
43 (defgroup ivy nil
44 "Incremental vertical completion."
45 :group 'convenience)
46
47 (defface ivy-current-match
48 '((t (:inherit highlight)))
49 "Face used by Ivy for highlighting first match.")
50
51 (defcustom ivy-height 10
52 "Number of lines for the minibuffer window."
53 :type 'integer)
54
55 (defcustom ivy-count-format "%-4d "
56 "The style of showing the current candidate count for `ivy-read'.
57 Set this to nil if you don't want the count."
58 :type 'string)
59
60 (defcustom ivy-wrap nil
61 "Whether to wrap around after the first and last candidate."
62 :type 'boolean)
63
64 (defcustom ivy-on-del-error-function 'minibuffer-keyboard-quit
65 "The handler for when `ivy-backward-delete-char' throws.
66 This is usually meant as a quick exit out of the minibuffer."
67 :type 'function)
68
69 ;;* User Visible
70 ;;** Keymap
71 (require 'delsel)
72 (defvar ivy-minibuffer-map
73 (let ((map (make-sparse-keymap)))
74 (define-key map (kbd "C-m") 'ivy-done)
75 (define-key map (kbd "C-j") 'ivy-alt-done)
76 (define-key map (kbd "C-n") 'ivy-next-line)
77 (define-key map (kbd "C-p") 'ivy-previous-line)
78 (define-key map (kbd "C-s") 'ivy-next-line-or-history)
79 (define-key map (kbd "C-r") 'ivy-previous-line-or-history)
80 (define-key map (kbd "SPC") 'self-insert-command)
81 (define-key map (kbd "DEL") 'ivy-backward-delete-char)
82 (define-key map (kbd "M-<") 'ivy-beginning-of-buffer)
83 (define-key map (kbd "M->") 'ivy-end-of-buffer)
84 (define-key map (kbd "M-n") 'ivy-next-history-element)
85 (define-key map (kbd "M-p") 'ivy-previous-history-element)
86 (define-key map (kbd "C-g") 'minibuffer-keyboard-quit)
87 map)
88 "Keymap used in the minibuffer.")
89
90 (defvar ivy-history nil
91 "History list of candidates entered in the minibuffer.
92
93 Maximum length of the history list is determined by the value
94 of `history-length', which see.")
95
96 (defvar ivy-require-match t
97 "Store require-match. See `completing-read'.")
98
99 (defvar ivy--directory nil
100 "Current directory when completing file names.")
101
102 ;;** Commands
103 (defun ivy-done ()
104 "Exit the minibuffer with the selected candidate."
105 (interactive)
106 (delete-minibuffer-contents)
107 (if (zerop ivy--length)
108 (when (memq ivy-require-match '(nil confirm confirm-after-completion))
109 (insert ivy-text)
110 (setq ivy-exit 'done))
111 (if ivy--directory
112 (insert (expand-file-name ivy--current ivy--directory))
113 (insert ivy--current))
114 (setq ivy-exit 'done))
115 (exit-minibuffer))
116
117 (defun ivy-alt-done ()
118 "Exit the minibuffer with the selected candidate."
119 (interactive)
120 (if (and ivy--directory
121 (file-directory-p
122 (expand-file-name ivy--current ivy--directory)))
123 (progn
124 (delete-minibuffer-contents)
125 (setq ivy--directory
126 (expand-file-name ivy--current ivy--directory))
127 (setq ivy--old-cands nil)
128 (setq ivy--all-candidates
129 (let ((default-directory ivy--directory))
130 (all-completions "" 'read-file-name-internal)))
131
132 (ivy--exhibit))
133 (ivy-done)))
134
135 (defun ivy-beginning-of-buffer ()
136 "Select the first completion candidate."
137 (interactive)
138 (setq ivy--index 0))
139
140 (defun ivy-end-of-buffer ()
141 "Select the last completion candidate."
142 (interactive)
143 (setq ivy--index (1- ivy--length)))
144
145 (defun ivy-next-line (&optional arg)
146 "Move cursor vertically down ARG candidates."
147 (interactive "p")
148 (setq arg (or arg 1))
149 (cl-incf ivy--index arg)
150 (when (>= ivy--index (1- ivy--length))
151 (if ivy-wrap
152 (ivy-beginning-of-buffer)
153 (setq ivy--index (1- ivy--length)))))
154
155 (defun ivy-next-line-or-history (&optional arg)
156 "Move cursor vertically down ARG candidates.
157 If the input is empty, select the previous history element instead."
158 (interactive "p")
159 (when (string= ivy-text "")
160 (ivy-previous-history-element 1))
161 (ivy-next-line arg))
162
163 (defun ivy-previous-line (&optional arg)
164 "Move cursor vertically up ARG candidates."
165 (interactive "p")
166 (setq arg (or arg 1))
167 (cl-decf ivy--index arg)
168 (when (< ivy--index 0)
169 (if ivy-wrap
170 (ivy-end-of-buffer)
171 (setq ivy--index 0))))
172
173 (defun ivy-previous-line-or-history (arg)
174 "Move cursor vertically up ARG candidates.
175 If the input is empty, select the previous history element instead."
176 (interactive "p")
177 (when (string= ivy-text "")
178 (ivy-previous-history-element 1))
179 (ivy-previous-line arg))
180
181 (defun ivy-previous-history-element (arg)
182 "Forward to `previous-history-element' with ARG."
183 (interactive "p")
184 (previous-history-element arg)
185 (move-end-of-line 1))
186
187 (defun ivy-next-history-element (arg)
188 "Forward to `next-history-element' with ARG."
189 (interactive "p")
190 (next-history-element arg)
191 (move-end-of-line 1))
192
193 (defun ivy-backward-delete-char ()
194 "Forward to `backward-delete-char'.
195 On error (read-only), call `ivy-on-del-error-function'."
196 (interactive)
197 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
198 (progn
199 (setq ivy--old-cands nil)
200 (setq ivy--all-candidates
201 (let ((default-directory (setq ivy--directory
202 (file-name-directory
203 (directory-file-name ivy--directory)))))
204 (all-completions "" 'read-file-name-internal)))
205 (ivy--exhibit))
206 (condition-case nil
207 (backward-delete-char 1)
208 (error
209 (when ivy-on-del-error-function
210 (funcall ivy-on-del-error-function))))))
211
212 ;;** Entry Point
213 (defun ivy-read (prompt collection
214 &optional predicate initial-input keymap preselect update-fn)
215 "Read a string in the minibuffer, with completion.
216
217 PROMPT is a string to prompt with; normally it ends in a colon
218 and a space. When PROMPT contains %d, it will be updated with
219 the current number of matching candidates.
220 See also `ivy-count-format'.
221
222 COLLECTION is a list of strings.
223
224 If INITIAL-INPUT is non-nil, insert it in the minibuffer initially.
225
226 KEYMAP is composed together with `ivy-minibuffer-map'.
227
228 If PRESELECT is non-nil select the corresponding candidate out of
229 the ones that match INITIAL-INPUT.
230
231 UPDATE-FN is called each time the current candidate(s) is changed."
232 (setq ivy--directory nil)
233 (cond ((or (functionp collection)
234 (vectorp collection))
235 (when (eq collection 'read-file-name-internal)
236 (setq ivy--directory default-directory)
237 (setq initial-input nil))
238 (setq collection (all-completions "" collection predicate)))
239 ((hash-table-p collection)
240 (error "Hash table as a collection unsupported"))
241 ((listp (car collection))
242 (setq collection (all-completions "" collection predicate))))
243 (cl-case (length collection)
244 (0 nil)
245 (1 (car collection))
246 (t
247 (setq ivy--index (or
248 (and preselect
249 (ivy--preselect-index
250 collection initial-input preselect))
251 0))
252 (setq ivy--old-re nil)
253 (setq ivy--old-cands nil)
254 (setq ivy-text "")
255 (setq ivy--all-candidates collection)
256 (setq ivy--update-fn update-fn)
257 (setq ivy-exit nil)
258 (setq ivy--default (or (thing-at-point 'symbol) ""))
259 (setq ivy--prompt
260 (cond ((string-match "%.*d" prompt)
261 prompt)
262 ((string-match "%.*d" ivy-count-format)
263 (concat ivy-count-format prompt))
264 (ivy--directory
265 prompt)
266 (t
267 nil)))
268 (setq ivy--action nil)
269 (prog1
270 (unwind-protect
271 (minibuffer-with-setup-hook
272 #'ivy--minibuffer-setup
273 (let ((res (read-from-minibuffer
274 prompt
275 initial-input
276 (make-composed-keymap keymap ivy-minibuffer-map)
277 nil
278 'ivy-history)))
279 (when (eq ivy-exit 'done)
280 (pop ivy-history)
281 (setq ivy-history
282 (cons ivy-text (delete ivy-text ivy-history)))
283 res)))
284 (remove-hook 'post-command-hook #'ivy--exhibit))
285 (when ivy--action
286 (funcall ivy--action))))))
287
288 (defun ivy-completing-read (prompt collection
289 &optional predicate require-match initial-input
290 _history def _inherit-input-method)
291 "Read a string in the minibuffer, with completion.
292
293 This is an interface that conforms to `completing-read', so that
294 it can be used for `completing-read-function'.
295
296 PROMPT is a string to prompt with; normally it ends in a colon and a space.
297 COLLECTION can be a list of strings, an alist, an obarray or a hash table.
298 PREDICATE limits completion to a subset of COLLECTION.
299
300 REQUIRE-MATCH is stored into `ivy-require-match'. See `completing-read'.
301 INITIAL-INPUT is a string that can be inserted into the minibuffer initially.
302 _HISTORY is ignored for now.
303 DEF is the default value.
304 _INHERIT-INPUT-METHOD is ignored for now.
305
306 The history, defaults and input-method arguments are ignored for now."
307 (when (listp def)
308 (setq def (car def)))
309 (setq ivy-require-match require-match)
310 (ivy-read prompt collection predicate initial-input nil def))
311
312 ;;;###autoload
313 (define-minor-mode ivy-mode
314 "Toggle Ivy mode on or off.
315 With ARG, turn Ivy mode on if arg is positive, off otherwise.
316 Turning on Ivy mode will set `completing-read-function' to
317 `ivy-completing-read'."
318 :group 'ivy
319 :global t
320 :lighter " ivy"
321 (if ivy-mode
322 (setq completing-read-function 'ivy-completing-read)
323 (setq completing-read-function 'completing-read-default)))
324
325 (defvar ivy--action nil
326 "Store a function to call at the end of `ivy--read'.")
327
328 (defun ivy--preselect-index (candidates initial-input preselect)
329 "Return the index in CANDIDATES filtered by INITIAL-INPUT for PRESELECT."
330 (when initial-input
331 (setq candidates
332 (cl-remove-if-not
333 (lambda (x)
334 (string-match initial-input x))
335 candidates)))
336 (cl-position-if
337 (lambda (x)
338 (string-match preselect x))
339 candidates))
340
341 (defvar ivy-text ""
342 "Stores the user's string as it is typed in.")
343
344 (defvar ivy-exit nil
345 "Store 'done if the completion was successfully selected.
346 Otherwise, store nil.")
347
348 ;;* Implementation
349 ;;** Regex
350 (defvar ivy--subexps 0
351 "Number of groups in the current `ivy--regex'.")
352
353 (defvar ivy--regex-hash
354 (make-hash-table :test 'equal)
355 "Store pre-computed regex.")
356
357 (defun ivy--regex (str)
358 "Re-build regex from STR in case it has a space."
359 (let ((hashed (gethash str ivy--regex-hash)))
360 (if hashed
361 (prog1 (cdr hashed)
362 (setq ivy--subexps (car hashed)))
363 (cdr (puthash str
364 (let ((subs (split-string str " +" t)))
365 (if (= (length subs) 1)
366 (cons
367 (setq ivy--subexps 0)
368 (car subs))
369 (cons
370 (setq ivy--subexps (length subs))
371 (mapconcat
372 (lambda (x) (format "\\(%s\\)" x))
373 subs
374 ".*"))))
375 ivy--regex-hash)))))
376
377 ;;** Rest
378 (defun ivy--minibuffer-setup ()
379 "Setup ivy completion in the minibuffer."
380 (set (make-local-variable 'completion-show-inline-help) nil)
381 (set (make-local-variable 'minibuffer-default-add-function)
382 (lambda ()
383 (list ivy--default)))
384 (use-local-map (make-composed-keymap ivy-minibuffer-map
385 (current-local-map)))
386 (setq-local max-mini-window-height ivy-height)
387 (add-hook 'post-command-hook #'ivy--exhibit nil t)
388 ;; show completions with empty input
389 (ivy--exhibit))
390
391 (defvar ivy--all-candidates nil
392 "Store the candidates passed to `ivy-read'.")
393
394 (defvar ivy--index 0
395 "Store the index of the current candidate.")
396
397 (defvar ivy--length 0
398 "Store the amount of viable candidates.")
399
400 (defvar ivy--current ""
401 "Current candidate.")
402
403 (defvar ivy--default nil
404 "Default initial input.")
405
406 (defvar ivy--update-fn nil
407 "Current function to call when current candidate(s) update.")
408
409 (defun ivy--input ()
410 "Return the current minibuffer input."
411 ;; assume one-line minibuffer input
412 (buffer-substring-no-properties
413 (minibuffer-prompt-end)
414 (line-end-position)))
415
416 (defun ivy--cleanup ()
417 "Delete the displayed completion candidates."
418 (save-excursion
419 (goto-char (minibuffer-prompt-end))
420 (delete-region (line-end-position) (point-max))))
421
422 (defvar ivy--prompt nil
423 "Store the format-style prompt.
424 When non-nil, it should contain one %d.")
425
426 (defun ivy--insert-prompt ()
427 "Update the prompt according to `ivy--prompt'."
428 (when ivy--prompt
429 (let ((inhibit-read-only t)
430 (n-str
431 (format
432 (if ivy--directory
433 (concat ivy--prompt (abbreviate-file-name ivy--directory))
434 ivy--prompt) ivy--length)))
435 (save-excursion
436 (goto-char (point-min))
437 (delete-region (point-min) (minibuffer-prompt-end))
438 (set-text-properties
439 0 (length n-str)
440 '(front-sticky t rear-nonsticky t field t read-only t face minibuffer-prompt)
441 n-str)
442 (insert n-str))
443 ;; get out of the prompt area
444 (constrain-to-field nil (point-max)))))
445
446 (defun ivy--exhibit ()
447 "Insert Ivy completions display.
448 Should be run via minibuffer `post-command-hook'."
449 (setq ivy-text (ivy--input))
450 (ivy--cleanup)
451 (let ((text (ivy-completions
452 ivy-text
453 ivy--all-candidates))
454 (buffer-undo-list t)
455 deactivate-mark)
456 (when ivy--update-fn
457 (funcall ivy--update-fn))
458 (ivy--insert-prompt)
459 ;; Do nothing if while-no-input was aborted.
460 (when (stringp text)
461 (save-excursion
462 (forward-line 1)
463 (insert text)))))
464
465 (defvar ivy--old-re nil
466 "Store the old regexp.")
467
468 (defvar ivy--old-cands nil
469 "Store the candidates matched by `ivy--old-re'.")
470
471 (defun ivy--add-face (str face)
472 "Propertize STR with FACE.
473 `font-lock-append-text-property' is used, since it's better than
474 `propertize' or `add-face-text-property' in this case."
475 (font-lock-append-text-property 0 (length str) 'face face str)
476 str)
477
478 (defun ivy-completions (name candidates)
479 "Return as text the current completions.
480 NAME is a string of words separated by spaces that is used to
481 build a regex.
482 CANDIDATES is a list of strings."
483 (let* ((re (ivy--regex name))
484 (cands (if (and (equal re ivy--old-re)
485 ivy--old-cands)
486 ivy--old-cands
487 (ignore-errors
488 (cl-remove-if-not
489 (lambda (x) (string-match re x))
490 candidates))))
491 (tail (nthcdr ivy--index ivy--old-cands))
492 (ww (window-width))
493 idx)
494 (when (and tail ivy--old-cands)
495 (unless (and (not (equal re ivy--old-re))
496 (setq ivy--index (cl-position re cands :test 'equal)))
497 (while (and tail (null idx))
498 ;; Compare with eq to handle equal duplicates in cands
499 (setq idx (cl-position (pop tail) cands)))
500 (setq ivy--index (or idx 0))))
501 (setq ivy--old-re re)
502 (setq ivy--length (length cands))
503 (setq ivy--old-cands cands)
504 (when (>= ivy--index ivy--length)
505 (setq ivy--index (max (1- ivy--length) 0)))
506 (if (null cands)
507 ""
508 (let* ((half-height (/ ivy-height 2))
509 (start (max 0 (- ivy--index half-height)))
510 (end (min (+ start (1- ivy-height)) ivy--length))
511 (cands (cl-subseq cands start end))
512 (index (min ivy--index half-height (1- (length cands)))))
513 (setq ivy--current (copy-sequence (nth index cands)))
514 (setf (nth index cands)
515 (ivy--add-face ivy--current 'ivy-current-match))
516 (let ((res (concat "\n" (mapconcat
517 (lambda (s)
518 (if (> (length s) ww)
519 (concat (substring s 0 (- ww 3)) "...")
520 s))
521 cands "\n"))))
522 (put-text-property 0 (length res) 'read-only nil res)
523 res)))))
524
525 (provide 'ivy)
526
527 ;;; ivy.el ends here