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