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