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