]> code.delx.au - gnu-emacs-elpa/blob - packages/swiper/ivy.el
Add 'packages/tiny/' from commit '159c3f74e75970808b83fe4b732f180cb76872a3'
[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.1.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 &optional initial-input update-fn preselect)
169 "Read a string in the minibuffer, with completion.
170
171 PROMPT is a string to prompt with; normally it ends in a colon
172 and a space. When PROMPT contains %d, it will be updated with
173 the current number of matching candidates.
174
175 COLLECTION is a list of strings.
176
177 If INITIAL-INPUT is non-nil, insert it in the minibuffer initially.
178
179 UPDATE-FN is called each time the current candidate(s) is changed.
180
181 If PRESELECT is non-nil select the corresponding candidate out of
182 the ones that match INITIAL-INPUT."
183 (cl-case (length collection)
184 (0 nil)
185 (1 (car collection))
186 (t
187 (setq ivy--index (or
188 (and preselect
189 (ivy--preselect-index
190 collection initial-input preselect))
191 0))
192 (setq ivy--old-re nil)
193 (setq ivy--old-cands nil)
194 (setq ivy-text "")
195 (setq ivy--all-candidates collection)
196 (setq ivy--update-fn update-fn)
197 (setq ivy-exit nil)
198 (setq ivy--default (or (thing-at-point 'symbol) ""))
199 (setq ivy--prompt
200 (cond ((string-match "%.*d" prompt)
201 prompt)
202 ((string-match "%.*d" ivy-count-format)
203 (concat ivy-count-format prompt))
204 (t
205 nil)))
206 (unwind-protect
207 (minibuffer-with-setup-hook
208 #'ivy--minibuffer-setup
209 (let ((res (read-from-minibuffer
210 prompt
211 initial-input
212 ivy-minibuffer-map
213 nil
214 'ivy-history)))
215 (when (eq ivy-exit 'done)
216 (pop ivy-history)
217 (setq ivy-history
218 (cons ivy-text (delete ivy-text ivy-history)))
219 res)))
220 (remove-hook 'post-command-hook #'ivy--exhibit)))))
221
222 (defun ivy--preselect-index (candidates initial-input preselect)
223 "Return the index in CANDIDATES filtered by INITIAL-INPUT for PRESELECT."
224 (when initial-input
225 (setq candidates
226 (cl-remove-if-not
227 (lambda (x)
228 (string-match initial-input x))
229 candidates)))
230 (cl-position-if
231 (lambda (x)
232 (string-match preselect x))
233 candidates))
234
235 (defvar ivy-text ""
236 "Stores the user's string as it is typed in.")
237
238 (defvar ivy-exit nil
239 "Store 'done if the completion was successfully selected.
240 Otherwise, store nil.")
241
242 ;;* Implementation
243 ;;** Regex
244 (defvar ivy--subexps 0
245 "Number of groups in the current `ivy--regex'.")
246
247 (defvar ivy--regex-hash
248 (make-hash-table :test 'equal)
249 "Store pre-computed regex.")
250
251 (defun ivy--regex (str)
252 "Re-build regex from STR in case it has a space."
253 (let ((hashed (gethash str ivy--regex-hash)))
254 (if hashed
255 (prog1 (cdr hashed)
256 (setq ivy--subexps (car hashed)))
257 (cdr (puthash str
258 (let ((subs (split-string str " +" t)))
259 (if (= (length subs) 1)
260 (cons
261 (setq ivy--subexps 0)
262 (car subs))
263 (cons
264 (setq ivy--subexps (length subs))
265 (mapconcat
266 (lambda (x) (format "\\(%s\\)" x))
267 subs
268 ".*"))))
269 ivy--regex-hash)))))
270
271 ;;** Rest
272 (defun ivy--minibuffer-setup ()
273 "Setup ivy completion in the minibuffer."
274 (set (make-local-variable 'completion-show-inline-help) nil)
275 (set (make-local-variable 'minibuffer-default-add-function)
276 (lambda ()
277 (list ivy--default)))
278 (use-local-map (make-composed-keymap ivy-minibuffer-map
279 (current-local-map)))
280 (setq-local max-mini-window-height ivy-height)
281 (add-hook 'post-command-hook #'ivy--exhibit nil t)
282 ;; show completions with empty input
283 (ivy--exhibit))
284
285 (defvar ivy--all-candidates nil
286 "Store the candidates passed to `ivy-read'.")
287
288 (defvar ivy--index 0
289 "Store the index of the current candidate.")
290
291 (defvar ivy--length 0
292 "Store the amount of viable candidates.")
293
294 (defvar ivy--current ""
295 "Current candidate.")
296
297 (defvar ivy--default nil
298 "Default initial input.")
299
300 (defvar ivy--update-fn nil
301 "Current function to call when current candidate(s) update.")
302
303 (defun ivy--input ()
304 "Return the current minibuffer input."
305 ;; assume one-line minibuffer input
306 (buffer-substring-no-properties
307 (minibuffer-prompt-end)
308 (line-end-position)))
309
310 (defun ivy--cleanup ()
311 "Delete the displayed completion candidates."
312 (save-excursion
313 (goto-char (minibuffer-prompt-end))
314 (delete-region (line-end-position) (point-max))))
315
316 (defvar ivy--prompt nil
317 "Store the format-style prompt.
318 When non-nil, it should contain one %d.")
319
320 (defun ivy--insert-prompt ()
321 "Update the prompt according to `ivy--prompt'."
322 (when ivy--prompt
323 (let ((inhibit-read-only t)
324 (n-str (format ivy--prompt ivy--length)))
325 (save-excursion
326 (goto-char (point-min))
327 (delete-region (point-min) (minibuffer-prompt-end))
328 (set-text-properties
329 0 (length n-str)
330 '(front-sticky t rear-nonsticky t field t read-only t face minibuffer-prompt)
331 n-str)
332 (insert n-str))
333 ;; get out of the prompt area
334 (constrain-to-field nil (point-max)))))
335
336 (defun ivy--exhibit ()
337 "Insert Ivy completions display.
338 Should be run via minibuffer `post-command-hook'."
339 (setq ivy-text (ivy--input))
340 (ivy--cleanup)
341 (let ((text (ivy-completions
342 ivy-text
343 ivy--all-candidates))
344 (buffer-undo-list t)
345 deactivate-mark)
346 (when ivy--update-fn
347 (funcall ivy--update-fn))
348 (ivy--insert-prompt)
349 ;; Do nothing if while-no-input was aborted.
350 (when (stringp text)
351 (save-excursion
352 (forward-line 1)
353 (insert text)))))
354
355 (defvar ivy--old-re nil
356 "Store the old regexp.")
357
358 (defvar ivy--old-cands nil
359 "Store the candidates matched by `ivy--old-re'.")
360
361 (defun ivy--add-face (str face)
362 "Propertize STR with FACE.
363 `font-lock-append-text-property' is used, since it's better than
364 `propertize' or `add-face-text-property' in this case."
365 (font-lock-append-text-property 0 (length str) 'face face str)
366 str)
367
368 (defun ivy-completions (name candidates)
369 "Return as text the current completions.
370 NAME is a string of words separated by spaces that is used to
371 build a regex.
372 CANDIDATES is a list of strings."
373 (let* ((re (ivy--regex name))
374 (cands (if (and (equal re ivy--old-re)
375 ivy--old-cands)
376 ivy--old-cands
377 (setq ivy--old-re re)
378 (ignore-errors
379 (cl-remove-if-not
380 (lambda (x) (string-match re x))
381 candidates))))
382 (tail (nthcdr ivy--index ivy--old-cands))
383 (ww (window-width))
384 idx)
385 (setq ivy--length (length cands))
386 (when (and tail ivy--old-cands)
387 (while (and tail
388 (null (setq idx (cl-position (pop tail) cands
389 :test #'equal)))))
390 (setq ivy--index (or idx 0)))
391 (setq ivy--old-cands cands)
392 (when (>= ivy--index ivy--length)
393 (setq ivy--index (max (1- ivy--length) 0)))
394 (if (null cands)
395 ""
396 (let* ((half-height (/ ivy-height 2))
397 (start (max 0 (- ivy--index half-height)))
398 (end (min (+ start (1- ivy-height)) ivy--length))
399 (cands (cl-subseq cands start end))
400 (index (min ivy--index half-height (1- (length cands)))))
401 (setq ivy--current (copy-sequence (nth index cands)))
402 (setf (nth index cands)
403 (ivy--add-face ivy--current 'ivy-current-match))
404 (concat "\n" (mapconcat
405 (lambda (s)
406 (if (> (length s) ww)
407 (concat (substring s 0 (- ww 3)) "...")
408 s))
409 cands "\n"))))))
410
411 (provide 'ivy)
412
413 ;;; ivy.el ends here