]> code.delx.au - gnu-emacs-elpa/blob - packages/swiper/ivy.el
Merge commit 'efa18eca10e5a0e05043f872cf9945842bb3a034' 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 (defface ivy-subdir
52 '((t (:weight bold)))
53 "Face used by Ivy for highlighting subdirs in the alternatives.")
54
55 (defcustom ivy-height 10
56 "Number of lines for the minibuffer window."
57 :type 'integer)
58
59 (defcustom ivy-count-format "%-4d "
60 "The style of showing the current candidate count for `ivy-read'.
61 Set this to nil if you don't want the count."
62 :type 'string)
63
64 (defcustom ivy-wrap nil
65 "Whether to wrap around after the first and last candidate."
66 :type 'boolean)
67
68 (defcustom ivy-on-del-error-function 'minibuffer-keyboard-quit
69 "The handler for when `ivy-backward-delete-char' throws.
70 This is usually meant as a quick exit out of the minibuffer."
71 :type 'function)
72
73 (defcustom ivy-extra-directories '("../" "./")
74 "Add this to the front of the list when completing file names.
75 Only \"./\" and \"../\" apply here. They appear in reverse order."
76 :type 'list)
77
78 ;;* User Visible
79 ;;** Keymap
80 (require 'delsel)
81 (defvar ivy-minibuffer-map
82 (let ((map (make-sparse-keymap)))
83 (define-key map (kbd "C-m") 'ivy-done)
84 (define-key map (kbd "C-j") 'ivy-alt-done)
85 (define-key map (kbd "C-n") 'ivy-next-line)
86 (define-key map (kbd "C-p") 'ivy-previous-line)
87 (define-key map (kbd "C-s") 'ivy-next-line-or-history)
88 (define-key map (kbd "C-r") 'ivy-previous-line-or-history)
89 (define-key map (kbd "SPC") 'self-insert-command)
90 (define-key map (kbd "DEL") 'ivy-backward-delete-char)
91 (define-key map (kbd "M-<") 'ivy-beginning-of-buffer)
92 (define-key map (kbd "M->") 'ivy-end-of-buffer)
93 (define-key map (kbd "M-n") 'ivy-next-history-element)
94 (define-key map (kbd "M-p") 'ivy-previous-history-element)
95 (define-key map (kbd "C-g") 'minibuffer-keyboard-quit)
96 (define-key map (kbd "C-v") 'ivy-scroll-up-command)
97 (define-key map (kbd "M-v") 'ivy-scroll-down-command)
98 map)
99 "Keymap used in the minibuffer.")
100
101 (defvar ivy-history nil
102 "History list of candidates entered in the minibuffer.
103
104 Maximum length of the history list is determined by the value
105 of `history-length', which see.")
106
107 (defvar ivy-require-match t
108 "Store require-match. See `completing-read'.")
109
110 (defvar ivy--directory nil
111 "Current directory when completing file names.")
112
113 (defvar ivy--length 0
114 "Store the amount of viable candidates.")
115
116 (defvar ivy-text ""
117 "Store the user's string as it is typed in.")
118
119 (defvar ivy--current ""
120 "Current candidate.")
121
122 (defvar ivy--index 0
123 "Store the index of the current candidate.")
124
125 (defvar ivy-exit nil
126 "Store 'done if the completion was successfully selected.
127 Otherwise, store nil.")
128
129 (defvar ivy--action nil
130 "Store a function to call at the end of `ivy--read'.")
131
132 (defvar ivy--all-candidates nil
133 "Store the candidates passed to `ivy-read'.")
134
135 (defvar ivy--default nil
136 "Default initial input.")
137
138 (defvar ivy--update-fn nil
139 "Current function to call when current candidate(s) update.")
140
141 (defvar ivy--prompt nil
142 "Store the format-style prompt.
143 When non-nil, it should contain one %d.")
144
145 (defvar ivy--old-re nil
146 "Store the old regexp.")
147
148 (defvar ivy--old-cands nil
149 "Store the candidates matched by `ivy--old-re'.")
150
151 ;;** Commands
152 (defun ivy-done ()
153 "Exit the minibuffer with the selected candidate."
154 (interactive)
155 (delete-minibuffer-contents)
156 (cond (ivy--directory
157 (insert
158 (cond ((string= ivy-text "")
159 (if (equal ivy--current "./")
160 ivy--directory
161 ivy--current))
162 ((zerop ivy--length)
163 (expand-file-name ivy-text ivy--directory))
164 (t
165 (expand-file-name ivy--current ivy--directory))))
166 (setq ivy-exit 'done))
167 ((zerop ivy--length)
168 (when (memq ivy-require-match
169 '(nil confirm confirm-after-completion))
170 (insert ivy-text)
171 (setq ivy-exit 'done)))
172 (t
173 (insert ivy--current)
174 (setq ivy-exit 'done)))
175 (exit-minibuffer))
176
177 (defun ivy-alt-done ()
178 "Exit the minibuffer with the selected candidate."
179 (interactive)
180 (let (dir)
181 (cond ((and ivy--directory
182 (= 0 ivy--index)
183 (= 0 (length ivy-text)))
184 (ivy-done))
185
186 ((and ivy--directory
187 (plusp ivy--length)
188 (file-directory-p
189 (setq dir (expand-file-name
190 ivy--current ivy--directory))))
191 (ivy--cd dir)
192 (ivy--exhibit))
193
194 (t
195 (ivy-done)))))
196
197 (defun ivy-beginning-of-buffer ()
198 "Select the first completion candidate."
199 (interactive)
200 (setq ivy--index 0))
201
202 (defun ivy-end-of-buffer ()
203 "Select the last completion candidate."
204 (interactive)
205 (setq ivy--index (1- ivy--length)))
206
207 (defun ivy-scroll-up-command ()
208 "Scroll the candidates upward by the minibuffer height."
209 (interactive)
210 (setq ivy--index (min (+ ivy--index ivy-height)
211 (1- ivy--length))))
212
213 (defun ivy-scroll-down-command ()
214 "Scroll the candidates downward by the minibuffer height."
215 (interactive)
216 (setq ivy--index (max (- ivy--index ivy-height)
217 0)))
218
219 (defun ivy-next-line (&optional arg)
220 "Move cursor vertically down ARG candidates."
221 (interactive "p")
222 (setq arg (or arg 1))
223 (cl-incf ivy--index arg)
224 (when (>= ivy--index (1- ivy--length))
225 (if ivy-wrap
226 (ivy-beginning-of-buffer)
227 (setq ivy--index (1- ivy--length)))))
228
229 (defun ivy-next-line-or-history (&optional arg)
230 "Move cursor vertically down ARG candidates.
231 If the input is empty, select the previous history element instead."
232 (interactive "p")
233 (when (string= ivy-text "")
234 (ivy-previous-history-element 1))
235 (ivy-next-line arg))
236
237 (defun ivy-previous-line (&optional arg)
238 "Move cursor vertically up ARG candidates."
239 (interactive "p")
240 (setq arg (or arg 1))
241 (cl-decf ivy--index arg)
242 (when (< ivy--index 0)
243 (if ivy-wrap
244 (ivy-end-of-buffer)
245 (setq ivy--index 0))))
246
247 (defun ivy-previous-line-or-history (arg)
248 "Move cursor vertically up ARG candidates.
249 If the input is empty, select the previous history element instead."
250 (interactive "p")
251 (when (string= ivy-text "")
252 (ivy-previous-history-element 1))
253 (ivy-previous-line arg))
254
255 (defun ivy-previous-history-element (arg)
256 "Forward to `previous-history-element' with ARG."
257 (interactive "p")
258 (previous-history-element arg)
259 (move-end-of-line 1))
260
261 (defun ivy-next-history-element (arg)
262 "Forward to `next-history-element' with ARG."
263 (interactive "p")
264 (next-history-element arg)
265 (move-end-of-line 1))
266
267 (defun ivy--cd (dir)
268 "When completing file names, move to directory DIR."
269 (if (null ivy--directory)
270 (error "Unexpected")
271 (setq ivy--old-cands nil)
272 (setq ivy--all-candidates
273 (ivy--sorted-files (setq ivy--directory dir)))
274 (setq ivy-text "")
275 (delete-minibuffer-contents)))
276
277 (defun ivy-backward-delete-char ()
278 "Forward to `backward-delete-char'.
279 On error (read-only), call `ivy-on-del-error-function'."
280 (interactive)
281 (if (and ivy--directory (= (minibuffer-prompt-end) (point)))
282 (progn
283 (ivy--cd (file-name-directory
284 (directory-file-name ivy--directory)))
285 (ivy--exhibit))
286 (condition-case nil
287 (backward-delete-char 1)
288 (error
289 (when ivy-on-del-error-function
290 (funcall ivy-on-del-error-function))))))
291
292 (defun ivy-sort-file-function-default (x y)
293 "Compare two files X and Y.
294 Prioritize directories."
295 (if (get-text-property 0 'dirp x)
296 (if (get-text-property 0 'dirp y)
297 (string< x y)
298 t)
299 (if (get-text-property 0 'dirp y)
300 nil
301 (string< x y))))
302
303 (defvar ivy-sort-file-function 'ivy-sort-file-function-default
304 "The function that compares file names.
305 It should take two string arguments and return nil and non-nil.")
306
307 (defun ivy--sorted-files (dir)
308 "Return the list of files in DIR.
309 Directories come first."
310 (let* ((default-directory dir)
311 (seq (all-completions "" 'read-file-name-internal)))
312 (if (equal dir "/")
313 seq
314 (setq seq (delete "./" (delete "../" seq)))
315 (when (eq ivy-sort-file-function 'ivy-sort-file-function-default)
316 (setq seq (mapcar (lambda (x)
317 (propertize x 'dirp (string-match-p "/$" x)))
318 (delete "./" (delete "../" seq)))))
319 (setq seq (cl-sort seq ivy-sort-file-function))
320 (dolist (dir ivy-extra-directories)
321 (push dir seq))
322 seq)))
323
324 ;;** Entry Point
325 (defun ivy-read (prompt collection
326 &optional predicate initial-input keymap preselect update-fn)
327 "Read a string in the minibuffer, with completion.
328
329 PROMPT is a string to prompt with; normally it ends in a colon
330 and a space. When PROMPT contains %d, it will be updated with
331 the current number of matching candidates.
332 See also `ivy-count-format'.
333
334 COLLECTION is a list of strings.
335
336 If INITIAL-INPUT is non-nil, insert it in the minibuffer initially.
337
338 KEYMAP is composed together with `ivy-minibuffer-map'.
339
340 If PRESELECT is non-nil select the corresponding candidate out of
341 the ones that match INITIAL-INPUT.
342
343 UPDATE-FN is called each time the current candidate(s) is changed."
344 (setq ivy--directory nil)
345 (cond ((eq collection 'Info-read-node-name-1)
346 (if (equal Info-current-file "dir")
347 (setq collection
348 (mapcar (lambda (x) (format "(%s)" x))
349 (cl-delete-duplicates
350 (all-completions "(" collection predicate)
351 :test 'equal)))
352 (setq collection (all-completions "" collection predicate))))
353 ((eq collection 'read-file-name-internal)
354 (setq ivy--directory default-directory)
355 (setq initial-input nil)
356 (setq collection
357 (ivy--sorted-files default-directory)))
358 ((or (functionp collection)
359 (vectorp collection))
360 (setq collection (all-completions "" collection predicate)))
361 ((hash-table-p collection)
362 (error "Hash table as a collection unsupported"))
363 ((listp (car collection))
364 (setq collection (all-completions "" collection predicate))))
365 (when preselect
366 (unless (or ivy-require-match
367 (all-completions preselect collection))
368 (setq collection (cons preselect collection))))
369 (cl-case (length collection)
370 (0 nil)
371 (1 (car collection))
372 (t
373 (setq ivy--index (or
374 (and preselect
375 (ivy--preselect-index
376 collection initial-input preselect))
377 0))
378 (setq ivy--old-re nil)
379 (setq ivy--old-cands nil)
380 (setq ivy-text "")
381 (setq ivy--all-candidates collection)
382 (setq ivy--update-fn update-fn)
383 (setq ivy-exit nil)
384 (setq ivy--default (or (thing-at-point 'symbol) ""))
385 (setq ivy--prompt
386 (cond ((string-match "%.*d" prompt)
387 prompt)
388 ((string-match "%.*d" ivy-count-format)
389 (concat ivy-count-format prompt))
390 (ivy--directory
391 prompt)
392 (t
393 nil)))
394 (setq ivy--action nil)
395 (prog1
396 (unwind-protect
397 (minibuffer-with-setup-hook
398 #'ivy--minibuffer-setup
399 (let ((res (read-from-minibuffer
400 prompt
401 initial-input
402 (make-composed-keymap keymap ivy-minibuffer-map)
403 nil
404 'ivy-history)))
405 (when (eq ivy-exit 'done)
406 (pop ivy-history)
407 (setq ivy-history
408 (cons ivy-text (delete ivy-text ivy-history)))
409 res)))
410 (remove-hook 'post-command-hook #'ivy--exhibit))
411 (when ivy--action
412 (funcall ivy--action))))))
413
414 (defun ivy-completing-read (prompt collection
415 &optional predicate require-match initial-input
416 _history def _inherit-input-method)
417 "Read a string in the minibuffer, with completion.
418
419 This is an interface that conforms to `completing-read', so that
420 it can be used for `completing-read-function'.
421
422 PROMPT is a string to prompt with; normally it ends in a colon and a space.
423 COLLECTION can be a list of strings, an alist, an obarray or a hash table.
424 PREDICATE limits completion to a subset of COLLECTION.
425
426 REQUIRE-MATCH is stored into `ivy-require-match'. See `completing-read'.
427 INITIAL-INPUT is a string that can be inserted into the minibuffer initially.
428 _HISTORY is ignored for now.
429 DEF is the default value.
430 _INHERIT-INPUT-METHOD is ignored for now.
431
432 The history, defaults and input-method arguments are ignored for now."
433 (when (listp def)
434 (setq def (car def)))
435 (setq ivy-require-match require-match)
436 (ivy-read prompt collection predicate initial-input nil def))
437
438 ;;;###autoload
439 (define-minor-mode ivy-mode
440 "Toggle Ivy mode on or off.
441 With ARG, turn Ivy mode on if arg is positive, off otherwise.
442 Turning on Ivy mode will set `completing-read-function' to
443 `ivy-completing-read'.
444
445 \\{ivy-minibuffer-map}"
446 :group 'ivy
447 :global t
448 :lighter " ivy"
449 (if ivy-mode
450 (setq completing-read-function 'ivy-completing-read)
451 (setq completing-read-function 'completing-read-default)))
452
453 (defun ivy--preselect-index (candidates initial-input preselect)
454 "Return the index in CANDIDATES filtered by INITIAL-INPUT for PRESELECT."
455 (when initial-input
456 (setq candidates
457 (cl-remove-if-not
458 (lambda (x)
459 (string-match initial-input x))
460 candidates)))
461 (or (cl-position preselect candidates :test 'equal)
462 (cl-position-if
463 (lambda (x)
464 (string-match preselect x))
465 candidates)))
466
467 ;;* Implementation
468 ;;** Regex
469 (defvar ivy--subexps 0
470 "Number of groups in the current `ivy--regex'.")
471
472 (defvar ivy--regex-hash
473 (make-hash-table :test 'equal)
474 "Store pre-computed regex.")
475
476 (defun ivy--regex (str)
477 "Re-build regex from STR in case it has a space."
478 (let ((hashed (gethash str ivy--regex-hash)))
479 (if hashed
480 (prog1 (cdr hashed)
481 (setq ivy--subexps (car hashed)))
482 (cdr (puthash str
483 (let ((subs (split-string str " +" t)))
484 (if (= (length subs) 1)
485 (cons
486 (setq ivy--subexps 0)
487 (car subs))
488 (cons
489 (setq ivy--subexps (length subs))
490 (mapconcat
491 (lambda (x) (format "\\(%s\\)" x))
492 subs
493 ".*"))))
494 ivy--regex-hash)))))
495
496 ;;** Rest
497 (defun ivy--minibuffer-setup ()
498 "Setup ivy completion in the minibuffer."
499 (set (make-local-variable 'completion-show-inline-help) nil)
500 (set (make-local-variable 'minibuffer-default-add-function)
501 (lambda ()
502 (list ivy--default)))
503 (use-local-map (make-composed-keymap ivy-minibuffer-map
504 (current-local-map)))
505 (setq-local max-mini-window-height ivy-height)
506 (add-hook 'post-command-hook #'ivy--exhibit nil t)
507 ;; show completions with empty input
508 (ivy--exhibit))
509
510 (defun ivy--input ()
511 "Return the current minibuffer input."
512 ;; assume one-line minibuffer input
513 (buffer-substring-no-properties
514 (minibuffer-prompt-end)
515 (line-end-position)))
516
517 (defun ivy--cleanup ()
518 "Delete the displayed completion candidates."
519 (save-excursion
520 (goto-char (minibuffer-prompt-end))
521 (delete-region (line-end-position) (point-max))))
522
523 (defun ivy--insert-prompt ()
524 "Update the prompt according to `ivy--prompt'."
525 (when ivy--prompt
526 (let ((inhibit-read-only t)
527 (n-str
528 (format
529 (if ivy--directory
530 (concat ivy--prompt (abbreviate-file-name ivy--directory))
531 ivy--prompt) ivy--length)))
532 (save-excursion
533 (goto-char (point-min))
534 (delete-region (point-min) (minibuffer-prompt-end))
535 (set-text-properties
536 0 (length n-str)
537 '(front-sticky t rear-nonsticky t field t read-only t face minibuffer-prompt)
538 n-str)
539 (insert n-str))
540 ;; get out of the prompt area
541 (constrain-to-field nil (point-max)))))
542
543 (defun ivy--exhibit ()
544 "Insert Ivy completions display.
545 Should be run via minibuffer `post-command-hook'."
546 (setq ivy-text (ivy--input))
547 (ivy--cleanup)
548 (when ivy--directory
549 (if (string-match "/$" ivy-text)
550 (if (member ivy-text ivy--all-candidates)
551 (ivy--cd (expand-file-name ivy-text ivy--directory))
552 (ivy--cd "/"))
553 (if (string-match "~$" ivy-text)
554 (ivy--cd (expand-file-name "~/")))))
555 (let ((text (ivy-completions
556 ivy-text
557 ivy--all-candidates))
558 (buffer-undo-list t)
559 deactivate-mark)
560 (when ivy--update-fn
561 (funcall ivy--update-fn))
562 (ivy--insert-prompt)
563 ;; Do nothing if while-no-input was aborted.
564 (when (stringp text)
565 (save-excursion
566 (forward-line 1)
567 (insert text)))))
568
569 (defun ivy--add-face (str face)
570 "Propertize STR with FACE.
571 `font-lock-append-text-property' is used, since it's better than
572 `propertize' or `add-face-text-property' in this case."
573 (font-lock-append-text-property 0 (length str) 'face face str)
574 str)
575
576 (defun ivy-completions (name candidates)
577 "Return as text the current completions.
578 NAME is a string of words separated by spaces that is used to
579 build a regex.
580 CANDIDATES is a list of strings."
581 (let* ((re (ivy--regex name))
582 (cands (cond ((and (equal re ivy--old-re)
583 ivy--old-cands)
584 ivy--old-cands)
585 ((and ivy--old-re
586 (not (equal ivy--old-re ""))
587 (eq 0 (cl-search ivy--old-re re)))
588 (ignore-errors
589 (cl-remove-if-not
590 (lambda (x) (string-match re x))
591 ivy--old-cands)))
592 (t
593 (ignore-errors
594 (cl-remove-if-not
595 (lambda (x) (string-match re x))
596 candidates)))))
597 (tail (nthcdr ivy--index ivy--old-cands))
598 (ww (window-width))
599 idx)
600 (when (and tail ivy--old-cands)
601 (unless (and (not (equal re ivy--old-re))
602 (setq ivy--index (cl-position re cands :test 'equal)))
603 (while (and tail (null idx))
604 ;; Compare with eq to handle equal duplicates in cands
605 (setq idx (cl-position (pop tail) cands)))
606 (setq ivy--index (or idx 0))))
607 (setq ivy--old-re re)
608 (setq ivy--length (length cands))
609 (setq ivy--old-cands cands)
610 (when (>= ivy--index ivy--length)
611 (setq ivy--index (max (1- ivy--length) 0)))
612 (if (null cands)
613 ""
614 (let* ((half-height (/ ivy-height 2))
615 (start (max 0 (- ivy--index half-height)))
616 (end (min (+ start (1- ivy-height)) ivy--length))
617 (cands (cl-subseq cands start end))
618 (index (min ivy--index half-height (1- (length cands)))))
619 (when ivy--directory
620 (setq cands (mapcar (lambda (x)
621 (if (string-match-p "/$" x)
622 (propertize x 'face 'ivy-subdir)
623 x))
624 cands)))
625 (setq ivy--current (copy-sequence (nth index cands)))
626 (setf (nth index cands)
627 (ivy--add-face ivy--current 'ivy-current-match))
628 (let ((res (concat "\n" (mapconcat
629 (lambda (s)
630 (if (> (length s) ww)
631 (concat (substring s 0 (- ww 3)) "...")
632 s))
633 cands "\n"))))
634 (put-text-property 0 (length res) 'read-only nil res)
635 res)))))
636
637 (provide 'ivy)
638
639 ;;; ivy.el ends here