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