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