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