]> code.delx.au - gnu-emacs-elpa/blob - avy.el
avy.el (avy-goto-line-above): Work in a single window
[gnu-emacs-elpa] / avy.el
1 ;;; avy.el --- set-based completion -*- 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/avy
7 ;; Version: 0.3.0
8 ;; Package-Requires: ((emacs "24.1") (cl-lib "0.5"))
9 ;; Keywords: point, location
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 a generic completion method based on building
29 ;; a balanced decision tree with each candidate being a leaf. To
30 ;; traverse the tree from the root to a desired leaf, typically a
31 ;; sequence of `read-key' can be used.
32 ;;
33 ;; In order for `read-key' to make sense, the tree needs to be
34 ;; visualized appropriately, with a character at each branch node. So
35 ;; this completion method works only for things that you can see on
36 ;; your screen, all at once:
37 ;;
38 ;; * character positions
39 ;; * word or subword start positions
40 ;; * line beginning positions
41 ;; * link positions
42 ;; * window positions
43 ;;
44 ;; If you're familiar with the popular `ace-jump-mode' package, this
45 ;; package does all that and more, without the implementation
46 ;; headache.
47
48 ;;; Code:
49 (require 'cl-lib)
50 (require 'ring)
51
52 ;;* Customization
53 (defgroup avy nil
54 "Jump to things tree-style."
55 :group 'convenience
56 :prefix "avy-")
57
58 (defcustom avy-keys '(?a ?s ?d ?f ?g ?h ?j ?k ?l)
59 "Default keys for jumping.
60 Any key is either a character representing a self-inserting
61 key (letters, digits, punctuation, etc.) or a symbol denoting a
62 non-printing key like an arrow key (left, right, up, down). For
63 non-printing keys, a corresponding entry in
64 `avy-key-to-char-alist' must exist in order to visualize the key
65 in the avy overlays."
66 :type '(repeat :tag "Keys" (choice (character :tag "char")
67 (symbol :tag "non-printing key"))))
68
69 (defcustom avy-keys-alist nil
70 "Alist of avy-jump commands to `avy-keys' overriding the default `avy-keys'."
71 :type '(alist
72 :key-type (choice :tag "Command"
73 (const avy-goto-char)
74 (const avy-goto-char-2)
75 (const avy-isearch)
76 (const avy-goto-line)
77 (const avy-goto-subword-0)
78 (const avy-goto-subword-1)
79 (const avy-goto-word-0)
80 (const avy-goto-word-1)
81 (const avy-copy-line)
82 (const avy-copy-region)
83 (const avy-move-line))
84 :value-type (repeat :tag "Keys" character)))
85
86 (defcustom avy-style 'at-full
87 "The default method of displaying the overlays.
88 Use `avy-styles-alist' to customize this per-command."
89 :type '(choice
90 (const :tag "Pre" pre)
91 (const :tag "At" at)
92 (const :tag "At Full" at-full)
93 (const :tag "Post" post)
94 (const :tag "De Bruijn" de-bruijn)))
95
96 (defcustom avy-styles-alist nil
97 "Alist of avy-jump commands to the style for each command.
98 If the commands isn't on the list, `avy-style' is used."
99 :type '(alist
100 :key-type (choice :tag "Command"
101 (const avy-goto-char)
102 (const avy-goto-char-2)
103 (const avy-isearch)
104 (const avy-goto-line)
105 (const avy-goto-subword-0)
106 (const avy-goto-subword-1)
107 (const avy-goto-word-0)
108 (const avy-goto-word-1)
109 (const avy-copy-line)
110 (const avy-copy-region)
111 (const avy-move-line))
112 :value-type (choice
113 (const :tag "Pre" pre)
114 (const :tag "At" at)
115 (const :tag "At Full" at-full)
116 (const :tag "Post" post)
117 (const :tag "De Bruijn" de-bruijn))))
118
119 (defcustom avy-dispatch-alist
120 '((?x . avy-action-kill)
121 (?m . avy-action-mark)
122 (?n . avy-action-copy))
123 "List of actions for `avy-handler-default'.
124
125 Each item is (KEY . ACTION). When KEY not on `avy-keys' is
126 pressed during the dispatch, ACTION is set to replace the default
127 `avy-action-goto' once a candidate is finally selected."
128 :type
129 '(alist
130 :key-type (choice (character :tag "Char"))
131 :value-type (choice
132 (const :tag "Mark" avy-action-mark)
133 (const :tag "Copy" avy-action-copy)
134 (const :tag "Kill" avy-action-kill))))
135
136 (defcustom avy-background nil
137 "When non-nil, a gray background will be added during the selection."
138 :type 'boolean)
139
140 (defcustom avy-all-windows t
141 "Determine the list of windows to consider in search of candidates."
142 :type
143 '(choice
144 (const :tag "All Frames" all-frames)
145 (const :tag "This Frame" t)
146 (const :tag "This Window" nil)))
147
148 (defcustom avy-case-fold-search t
149 "Non-nil if searches should ignore case."
150 :type 'boolean)
151
152 (defcustom avy-word-punc-regexp "[!-/:-@[-`{-~]"
153 "Regexp of punctuation chars that count as word starts for `avy-goto-word-1.
154 When nil, punctuation chars will not be matched.
155
156 \"[!-/:-@[-`{-~]\" will match all printable punctuation chars."
157 :type 'regexp)
158
159 (defcustom avy-ignored-modes '(image-mode doc-view-mode pdf-view-mode)
160 "List of modes to ignore when searching for candidates.
161 Typically, these modes don't use the text representation.")
162
163 (defvar avy-translate-char-function #'identity
164 "Function to translate user input key into another key.
165 For example, to make SPC do the same as ?a, use
166 \(lambda (c) (if (= c 32) ?a c)).")
167
168 (defface avy-lead-face-0
169 '((t (:foreground "white" :background "#4f57f9")))
170 "Face used for first non-terminating leading chars.")
171
172 (defface avy-lead-face-1
173 '((t (:foreground "white" :background "gray")))
174 "Face used for matched leading chars.")
175
176 (defface avy-lead-face-2
177 '((t (:foreground "white" :background "#f86bf3")))
178 "Face used for leading chars.")
179
180 (defface avy-lead-face
181 '((t (:foreground "white" :background "#e52b50")))
182 "Face used for the leading chars.")
183
184 (defface avy-background-face
185 '((t (:foreground "gray40")))
186 "Face for whole window background during selection.")
187
188 (defface avy-goto-char-timer-face
189 '((t (:inherit highlight)))
190 "Face for matches during reading chars using `avy-goto-char-timer'.")
191
192 (defconst avy-lead-faces '(avy-lead-face
193 avy-lead-face-0
194 avy-lead-face-2
195 avy-lead-face
196 avy-lead-face-0
197 avy-lead-face-2)
198 "Face sequence for `avy--overlay-at-full'.")
199
200 (defvar avy-key-to-char-alist '((left . ?◀)
201 (right . ?▶)
202 (up . ?▲)
203 (down . ?▼)
204 (prior . ?△)
205 (next . ?▽))
206 "An alist from non-character keys to printable chars used in avy overlays.
207 This alist must contain all keys used in `avy-keys' which are not
208 self-inserting keys and thus aren't read as characters.")
209
210 ;;* Internals
211 ;;** Tree
212 (defmacro avy-multipop (lst n)
213 "Remove LST's first N elements and return them."
214 `(if (<= (length ,lst) ,n)
215 (prog1 ,lst
216 (setq ,lst nil))
217 (prog1 ,lst
218 (setcdr
219 (nthcdr (1- ,n) (prog1 ,lst (setq ,lst (nthcdr ,n ,lst))))
220 nil))))
221
222 (defun avy--de-bruijn (keys n)
223 "De Bruijn sequence for alphabet KEYS and subsequences of length N."
224 (let* ((k (length keys))
225 (a (make-list (* n k) 0))
226 sequence)
227 (cl-labels ((db (T p)
228 (if (> T n)
229 (if (eq (% n p) 0)
230 (setq sequence
231 (append sequence
232 (cl-subseq a 1 (1+ p)))))
233 (setf (nth T a) (nth (- T p) a))
234 (db (1+ T) p)
235 (cl-loop for j from (1+ (nth (- T p) a)) to (1- k) do
236 (setf (nth T a) j)
237 (db (1+ T) T)))))
238 (db 1 1)
239 (mapcar (lambda (n)
240 (nth n keys))
241 sequence))))
242
243 (defun avy--path-alist-1 (lst seq-len keys)
244 "Build a De Bruin sequence from LST.
245 SEQ-LEN is how many elements of KEYS it takes to identify a match."
246 (let ((db-seq (avy--de-bruijn keys seq-len))
247 prev-pos prev-seq prev-win path-alist)
248 ;; The De Bruijn seq is cyclic, so append the seq-len - 1 first chars to
249 ;; the end.
250 (setq db-seq (nconc db-seq (cl-subseq db-seq 0 (1- seq-len))))
251 (cl-labels ((subseq-and-pop ()
252 (when (nth (1- seq-len) db-seq)
253 (prog1 (cl-subseq db-seq 0 seq-len)
254 (pop db-seq)))))
255 (while lst
256 (let* ((cur (car lst))
257 (pos (cond
258 ;; ace-window has matches of the form (pos . wnd)
259 ((integerp (car cur)) (car cur))
260 ;; avy-jump have form ((start . end) . wnd)
261 ((consp (car cur)) (caar cur))
262 (t (error "Unexpected match representation: %s" cur))))
263 (win (cdr cur))
264 (path (if prev-pos
265 (let ((diff (if (eq win prev-win)
266 (- pos prev-pos)
267 0)))
268 (when (and (> diff 0) (< diff seq-len))
269 (while (and (nth (1- seq-len) db-seq)
270 (not
271 (eq 0 (cl-search
272 (cl-subseq prev-seq diff)
273 (cl-subseq db-seq 0 seq-len)))))
274 (pop db-seq)))
275 (subseq-and-pop))
276 (subseq-and-pop))))
277 (if (not path)
278 (setq lst nil
279 path-alist nil)
280 (push (cons path (car lst)) path-alist)
281 (setq prev-pos pos
282 prev-seq path
283 prev-win win
284 lst (cdr lst))))))
285 (nreverse path-alist)))
286
287 (defun avy-tree (lst keys)
288 "Coerce LST into a balanced tree.
289 The degree of the tree is the length of KEYS.
290 KEYS are placed appropriately on internal nodes."
291 (let ((len (length keys)))
292 (cl-labels
293 ((rd (ls)
294 (let ((ln (length ls)))
295 (if (< ln len)
296 (cl-pairlis keys
297 (mapcar (lambda (x) (cons 'leaf x)) ls))
298 (let ((ks (copy-sequence keys))
299 res)
300 (dolist (s (avy-subdiv ln len))
301 (push (cons (pop ks)
302 (if (eq s 1)
303 (cons 'leaf (pop ls))
304 (rd (avy-multipop ls s))))
305 res))
306 (nreverse res))))))
307 (rd lst))))
308
309 (defun avy-subdiv (n b)
310 "Distribute N in B terms in a balanced way."
311 (let* ((p (1- (floor (+ (log n b) 1e-6))))
312 (x1 (expt b p))
313 (x2 (* b x1))
314 (delta (- n x2))
315 (n2 (/ delta (- x2 x1)))
316 (n1 (- b n2 1)))
317 (append
318 (make-list n1 x1)
319 (list
320 (- n (* n1 x1) (* n2 x2)))
321 (make-list n2 x2))))
322
323 (defun avy-traverse (tree walker &optional recur-key)
324 "Traverse TREE generated by `avy-tree'.
325 WALKER is a function that takes KEYS and LEAF.
326
327 RECUR-KEY is used in recursion.
328
329 LEAF is a member of LST argument of `avy-tree'.
330
331 KEYS is the path from the root of `avy-tree' to LEAF."
332 (dolist (br tree)
333 (let ((key (cons (car br) recur-key)))
334 (if (eq (cadr br) 'leaf)
335 (funcall walker key (cddr br))
336 (avy-traverse (cdr br) walker key)))))
337
338 (defvar avy-action nil
339 "Function to call at the end of select.")
340
341 (defun avy-handler-default (char)
342 "The default handler for a bad CHAR."
343 (let (dispatch)
344 (if (setq dispatch (assoc char avy-dispatch-alist))
345 (progn
346 (setq avy-action (cdr dispatch))
347 (throw 'done 'restart))
348 (signal 'user-error (list "No such candidate" char))
349 (throw 'done nil))))
350
351 (defvar avy-handler-function 'avy-handler-default
352 "A function to call for a bad `read-key' in `avy-read'.")
353
354 (defvar avy-current-path ""
355 "Store the current incomplete path during `avy-read'.")
356
357 (defun avy-read (tree display-fn cleanup-fn)
358 "Select a leaf from TREE using consecutive `read-char'.
359
360 DISPLAY-FN should take CHAR and LEAF and signify that LEAFs
361 associated with CHAR will be selected if CHAR is pressed. This is
362 commonly done by adding a CHAR overlay at LEAF position.
363
364 CLEANUP-FN should take no arguments and remove the effects of
365 multiple DISPLAY-FN invokations."
366 (catch 'done
367 (setq avy-current-path "")
368 (while tree
369 (let ((avy--leafs nil))
370 (avy-traverse tree
371 (lambda (path leaf)
372 (push (cons path leaf) avy--leafs)))
373 (dolist (x avy--leafs)
374 (funcall display-fn (car x) (cdr x))))
375 (let ((char (funcall avy-translate-char-function (read-key)))
376 branch)
377 (funcall cleanup-fn)
378 (if (setq branch (assoc char tree))
379 (if (eq (car (setq tree (cdr branch))) 'leaf)
380 (throw 'done (cdr tree))
381 (setq avy-current-path
382 (concat avy-current-path (string (avy--key-to-char char)))))
383 (funcall avy-handler-function char))))))
384
385 (defun avy-read-de-bruijn (lst keys)
386 "Select from LST dispatching on KEYS."
387 ;; In theory, the De Bruijn sequence B(k,n) has k^n subsequences of length n
388 ;; (the path length) usable as paths, thus that's the lower bound. Due to
389 ;; partially overlapping matches, not all subsequences may be usable, so it's
390 ;; possible that the path-len must be incremented, e.g., if we're matching
391 ;; for x and a buffer contains xaxbxcx only every second subsequence is
392 ;; usable for the four matches.
393 (catch 'done
394 (let* ((path-len (ceiling (log (length lst) (length keys))))
395 (alist (avy--path-alist-1 lst path-len keys)))
396 (while (not alist)
397 (cl-incf path-len)
398 (setq alist (avy--path-alist-1 lst path-len keys)))
399 (let* ((len (length (caar alist)))
400 (i 0))
401 (setq avy-current-path "")
402 (while (< i len)
403 (dolist (x (reverse alist))
404 (avy--overlay-at-full (reverse (car x)) (cdr x)))
405 (let ((char (funcall avy-translate-char-function (read-key))))
406 (avy--remove-leading-chars)
407 (setq alist
408 (delq nil
409 (mapcar (lambda (x)
410 (when (eq (caar x) char)
411 (cons (cdr (car x)) (cdr x))))
412 alist)))
413 (setq avy-current-path
414 (concat avy-current-path (string (avy--key-to-char char))))
415 (cl-incf i)
416 (unless alist
417 (funcall avy-handler-function char))))
418 (cdar alist)))))
419
420 ;;** Rest
421 (defun avy-window-list ()
422 "Return a list of windows depending on `avy-all-windows'."
423 (cond ((eq avy-all-windows 'all-frames)
424 (cl-mapcan #'window-list (frame-list)))
425
426 ((eq avy-all-windows t)
427 (window-list))
428
429 ((null avy-all-windows)
430 (list (selected-window)))
431
432 (t
433 (error "Unrecognized option: %S" avy-all-windows))))
434
435 (defmacro avy-dowindows (flip &rest body)
436 "Depending on FLIP and `avy-all-windows' run BODY in each or selected window."
437 (declare (indent 1)
438 (debug (form body)))
439 `(let ((avy-all-windows (if ,flip
440 (not avy-all-windows)
441 avy-all-windows)))
442 (dolist (wnd (avy-window-list))
443 (with-selected-window wnd
444 (unless (memq major-mode avy-ignored-modes)
445 ,@body)))))
446
447 (defmacro avy-with (command &rest body)
448 "Set `avy-keys' according to COMMAND and execute BODY.
449 Set `avy-style' according to COMMMAND as well."
450 (declare (indent 1)
451 (debug (form body)))
452 `(let ((avy-keys (or (cdr (assq ',command avy-keys-alist))
453 avy-keys))
454 (avy-style (or (cdr (assq ',command avy-styles-alist))
455 avy-style)))
456 (setq avy-action nil)
457 ,@body))
458
459 (defun avy-action-goto (pt)
460 "Goto PT."
461 (goto-char pt))
462
463 (defun avy-action-mark (pt)
464 "Mark sexp at PT."
465 (goto-char pt)
466 (set-mark (point))
467 (forward-sexp))
468
469 (defun avy-action-copy (pt)
470 "Copy sexp starting on PT."
471 (save-excursion
472 (let (str)
473 (goto-char pt)
474 (forward-sexp)
475 (setq str (buffer-substring pt (point)))
476 (kill-new str)
477 (message "Copied: %s" str))))
478
479 (defun avy-action-kill (pt)
480 "Kill sexp at PT."
481 (goto-char pt)
482 (forward-sexp)
483 (kill-region pt (point))
484 (message "Killed: %s" (current-kill 0)))
485
486 (defun avy--process (candidates overlay-fn)
487 "Select one of CANDIDATES using `avy-read'.
488 Use OVERLAY-FN to visualize the decision overlay."
489 (unless (and (consp (car candidates))
490 (windowp (cdar candidates)))
491 (setq candidates
492 (mapcar (lambda (x) (cons x (selected-window)))
493 candidates)))
494 (let ((len (length candidates))
495 (cands (copy-sequence candidates))
496 res)
497 (if (= len 0)
498 (message "zero candidates")
499 (if (= len 1)
500 (setq res (car candidates))
501 (unwind-protect
502 (progn
503 (avy--make-backgrounds
504 (avy-window-list))
505 (setq res (if (eq avy-style 'de-bruijn)
506 (avy-read-de-bruijn
507 candidates avy-keys)
508 (avy-read (avy-tree candidates avy-keys)
509 overlay-fn
510 #'avy--remove-leading-chars))))
511 (avy--done)))
512 (cond ((eq res 'restart)
513 (avy--process cands overlay-fn))
514 ;; ignore exit from `avy-handler-function'
515 ((eq res 'exit))
516 (t
517 (avy-push-mark)
518 (when (and (consp res)
519 (windowp (cdr res)))
520 (let* ((window (cdr res))
521 (frame (window-frame window)))
522 (unless (equal frame (selected-frame))
523 (select-frame-set-input-focus frame))
524 (select-window window))
525 (setq res (car res)))
526
527 (funcall (or avy-action 'avy-action-goto)
528 (if (consp res)
529 (car res)
530 res)))))))
531
532 (defvar avy--overlays-back nil
533 "Hold overlays for when `avy-background' is t.")
534
535 (defun avy--make-backgrounds (wnd-list)
536 "Create a dim background overlay for each window on WND-LIST."
537 (when avy-background
538 (setq avy--overlays-back
539 (mapcar (lambda (w)
540 (let ((ol (make-overlay
541 (window-start w)
542 (window-end w)
543 (window-buffer w))))
544 (overlay-put ol 'face 'avy-background-face)
545 (overlay-put ol 'window w)
546 ol))
547 wnd-list))))
548
549 (defun avy--done ()
550 "Clean up overlays."
551 (mapc #'delete-overlay avy--overlays-back)
552 (setq avy--overlays-back nil)
553 (avy--remove-leading-chars))
554
555 (defun avy--next-visible-point ()
556 "Return the next closest point without 'invisible property."
557 (let ((s (point)))
558 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
559 (get-char-property s 'invisible)))
560 s))
561
562 (defun avy--next-invisible-point ()
563 "Return the next closest point with 'invisible property."
564 (let ((s (point)))
565 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
566 (not (get-char-property s 'invisible))))
567 s))
568
569 (defun avy--find-visible-regions (rbeg rend)
570 "Return a list of all visible regions between RBEG and REND."
571 (setq rbeg (max rbeg (point-min)))
572 (setq rend (min rend (point-max)))
573 (when (< rbeg rend)
574 (let (visibles beg)
575 (save-excursion
576 (save-restriction
577 (narrow-to-region rbeg rend)
578 (setq beg (goto-char (point-min)))
579 (while (not (= (point) (point-max)))
580 (goto-char (avy--next-invisible-point))
581 (push (cons beg (point)) visibles)
582 (setq beg (goto-char (avy--next-visible-point))))
583 (nreverse visibles))))))
584
585 (defun avy--regex-candidates (regex &optional beg end pred group)
586 "Return all elements that match REGEX.
587 Each element of the list is ((BEG . END) . WND)
588 When PRED is non-nil, it's a filter for matching point positions.
589 When GROUP is non-nil, (BEG . END) should delimit that regex group."
590 (setq group (or group 0))
591 (let ((case-fold-search (or avy-case-fold-search
592 (not (string= regex (upcase regex)))))
593 candidates)
594 (avy-dowindows nil
595 (dolist (pair (avy--find-visible-regions
596 (or beg (window-start))
597 (or end (window-end (selected-window) t))))
598 (save-excursion
599 (goto-char (car pair))
600 (while (re-search-forward regex (cdr pair) t)
601 (unless (get-char-property (1- (point)) 'invisible)
602 (when (or (null pred)
603 (funcall pred))
604 (push (cons (cons (match-beginning group)
605 (match-end group))
606 wnd) candidates)))))))
607 (nreverse candidates)))
608
609 (defvar avy--overlay-offset 0
610 "The offset to apply in `avy--overlay'.")
611
612 (defvar avy--overlays-lead nil
613 "Hold overlays for leading chars.")
614
615 (defun avy--remove-leading-chars ()
616 "Remove leading char overlays."
617 (mapc #'delete-overlay avy--overlays-lead)
618 (setq avy--overlays-lead nil))
619
620 (defun avy--old-str (pt wnd)
621 "Return a one-char string at PT in WND."
622 (let ((old-str (with-selected-window wnd
623 (buffer-substring pt (1+ pt)))))
624 (if avy-background
625 (propertize old-str 'face 'avy-background-face)
626 old-str)))
627
628 (defun avy--overlay (str beg end wnd &optional compose-fn)
629 "Create an overlay with STR from BEG to END in WND.
630 COMPOSE-FN is a lambda that concatenates the old string at BEG with STR."
631 (when (<= (1+ beg) (with-selected-window wnd (point-max)))
632 (let* ((beg (+ beg avy--overlay-offset))
633 (ol (make-overlay beg (or end (1+ beg)) (window-buffer wnd)))
634 (old-str (avy--old-str beg wnd))
635 (os-line-prefix (get-text-property 0 'line-prefix old-str))
636 (os-wrap-prefix (get-text-property 0 'wrap-prefix old-str)))
637 (when os-line-prefix
638 (add-text-properties 0 1 `(line-prefix ,os-line-prefix) str))
639 (when os-wrap-prefix
640 (add-text-properties 0 1 `(wrap-prefix ,os-wrap-prefix) str))
641 (overlay-put ol 'window wnd)
642 (overlay-put ol 'category 'avy)
643 (overlay-put ol 'display (funcall
644 (or compose-fn #'concat)
645 str old-str))
646 (push ol avy--overlays-lead))))
647
648 (defcustom avy-highlight-first nil
649 "When non-nil highlight the first decision char with `avy-lead-face-0'.
650 Do this even when the char is terminating."
651 :type 'boolean)
652
653 (defun avy--key-to-char (c)
654 "If C is no character, translate it using `avy-key-to-char-alist'."
655 (if (characterp c)
656 c
657 (or (cdr (assoc c avy-key-to-char-alist))
658 (error "Unknown key %s" c))))
659
660 (defun avy-candidate-beg (leaf)
661 "Return the start position for LEAF."
662 (cond ((numberp leaf)
663 leaf)
664 ((consp (car leaf))
665 (caar leaf))
666 (t
667 (car leaf))))
668
669 (defun avy-candidate-end (leaf)
670 "Return the end position for LEAF."
671 (cond ((numberp leaf)
672 leaf)
673 ((consp (car leaf))
674 (cdar leaf))
675 (t
676 (car leaf))))
677
678 (defun avy-candidate-wnd (leaf)
679 "Return the window for LEAF."
680 (if (consp leaf)
681 (cdr leaf)
682 (selected-window)))
683
684 (defun avy--overlay-pre (path leaf)
685 "Create an overlay with PATH at LEAF.
686 PATH is a list of keys from tree root to LEAF.
687 LEAF is normally ((BEG . END) . WND)."
688 (let* ((path (mapcar #'avy--key-to-char path))
689 (str (propertize (apply #'string (reverse path))
690 'face 'avy-lead-face)))
691 (when (or avy-highlight-first (> (length str) 1))
692 (set-text-properties 0 1 '(face avy-lead-face-0) str))
693 (setq str (concat
694 (propertize avy-current-path
695 'face 'avy-lead-face-1)
696 str))
697 (avy--overlay
698 str
699 (avy-candidate-beg leaf) nil
700 (avy-candidate-wnd leaf))))
701
702 (defun avy--overlay-at (path leaf)
703 "Create an overlay with PATH at LEAF.
704 PATH is a list of keys from tree root to LEAF.
705 LEAF is normally ((BEG . END) . WND)."
706 (let* ((path (mapcar #'avy--key-to-char path))
707 (str (propertize
708 (string (car (last path)))
709 'face 'avy-lead-face)))
710 (avy--overlay
711 str
712 (avy-candidate-beg leaf) nil
713 (avy-candidate-wnd leaf)
714 (lambda (str old-str)
715 (cond ((string= old-str "\n")
716 (concat str "\n"))
717 ;; add padding for wide-width character
718 ((eq (string-width old-str) 2)
719 (concat str " "))
720 (t
721 str))))))
722
723 (defun avy--overlay-at-full (path leaf)
724 "Create an overlay with PATH at LEAF.
725 PATH is a list of keys from tree root to LEAF.
726 LEAF is normally ((BEG . END) . WND)."
727 (let* ((path (mapcar #'avy--key-to-char path))
728 (str (propertize
729 (apply #'string (reverse path))
730 'face 'avy-lead-face))
731 (len (length path))
732 (beg (avy-candidate-beg leaf))
733 (wnd (cdr leaf))
734 end)
735 (dotimes (i len)
736 (set-text-properties (- len i 1) (- len i)
737 `(face ,(nth i avy-lead-faces))
738 str))
739 (when (eq avy-style 'de-bruijn)
740 (setq str (concat
741 (propertize avy-current-path
742 'face 'avy-lead-face-1)
743 str))
744 (setq len (length str)))
745 (with-selected-window wnd
746 (save-excursion
747 (goto-char beg)
748 (let* ((lep (if (bound-and-true-p visual-line-mode)
749 (save-excursion
750 (end-of-visual-line)
751 (point))
752 (line-end-position)))
753 (len-and-str (avy--update-offset-and-str len str lep)))
754 (setq len (car len-and-str))
755 (setq str (cdr len-and-str))
756 (setq end (if (= beg lep)
757 (1+ beg)
758 (min (+ beg
759 (if (eq (char-after) ?\t)
760 1
761 len))
762 lep)))
763 (when (and (bound-and-true-p visual-line-mode)
764 (> len (- end beg)))
765 (setq len (- end beg))
766 (let ((old-str (apply #'string (reverse path))))
767 (setq str
768 (substring
769 (propertize
770 old-str
771 'face
772 (if (= (length old-str) 1)
773 'avy-lead-face
774 'avy-lead-face-0))
775 0 len)))))))
776 (avy--overlay
777 str beg end wnd
778 (lambda (str old-str)
779 (cond ((string= old-str "\n")
780 (concat str "\n"))
781 ((string= old-str "\t")
782 (concat str (make-string (max (- tab-width len) 0) ?\ )))
783 (t
784 ;; add padding for wide-width character
785 (if (eq (string-width old-str) 2)
786 (concat str " ")
787 str)))))))
788
789 (defun avy--overlay-post (path leaf)
790 "Create an overlay with PATH at LEAF.
791 PATH is a list of keys from tree root to LEAF.
792 LEAF is normally ((BEG . END) . WND)."
793 (let* ((path (mapcar #'avy--key-to-char path))
794 (str (propertize (apply #'string (reverse path))
795 'face 'avy-lead-face)))
796 (when (or avy-highlight-first (> (length str) 1))
797 (set-text-properties 0 1 '(face avy-lead-face-0) str))
798 (setq str (concat
799 (propertize avy-current-path
800 'face 'avy-lead-face-1)
801 str))
802 (avy--overlay
803 str
804 (avy-candidate-end leaf) nil
805 (avy-candidate-wnd leaf))))
806
807 (defun avy--update-offset-and-str (offset str lep)
808 "Recalculate the length of the new overlay at point.
809
810 OFFSET is the previous overlay length.
811 STR is the overlay string that we wish to add.
812 LEP is the line end position.
813
814 We want to add an overlay between point and END=point+OFFSET.
815 When other overlays already exist between point and END, set
816 OFFSET to be the difference between the start of the first
817 overlay and point. This is equivalent to truncating our new
818 overlay, so that it doesn't intersect with overlays that already
819 exist."
820 (let* ((wnd (selected-window))
821 (beg (point))
822 (oov (delq nil
823 (mapcar
824 (lambda (o)
825 (and (eq (overlay-get o 'category) 'avy)
826 (eq (overlay-get o 'window) wnd)
827 (overlay-start o)))
828 (overlays-in beg (min (+ beg offset) lep))))))
829 (when oov
830 (setq offset (- (apply #'min oov) beg))
831 (setq str (substring str 0 offset)))
832 (let ((other-ov (cl-find-if
833 (lambda (o)
834 (and (eq (overlay-get o 'category) 'avy)
835 (eq (overlay-start o) beg)
836 (not (eq (overlay-get o 'window) wnd))))
837 (overlays-in (point) (min (+ (point) offset) lep)))))
838 (when (and other-ov
839 (> (overlay-end other-ov)
840 (+ beg offset)))
841 (setq str (concat str (buffer-substring
842 (+ beg offset)
843 (overlay-end other-ov))))
844 (setq offset (- (overlay-end other-ov)
845 beg))))
846 (cons offset str)))
847
848 (defun avy--style-fn (style)
849 "Transform STYLE symbol to a style function."
850 (cl-case style
851 (pre #'avy--overlay-pre)
852 (at #'avy--overlay-at)
853 (at-full 'avy--overlay-at-full)
854 (post #'avy--overlay-post)
855 (de-bruijn #'avy--overlay-at-full)
856 (t (error "Unexpected style %S" style))))
857
858 (defun avy--generic-jump (regex window-flip style &optional beg end)
859 "Jump to REGEX.
860 When WINDOW-FLIP is non-nil, do the opposite of `avy-all-windows'.
861 STYLE determines the leading char overlay style.
862 BEG and END delimit the area where candidates are searched."
863 (let ((avy-all-windows
864 (if window-flip
865 (not avy-all-windows)
866 avy-all-windows)))
867 (avy--process
868 (avy--regex-candidates regex beg end)
869 (avy--style-fn style))))
870
871 ;;* Commands
872 ;;;###autoload
873 (defun avy-goto-char (char &optional arg)
874 "Jump to the currently visible CHAR.
875 The window scope is determined by `avy-all-windows' (ARG negates it)."
876 (interactive (list (read-char "char: " t)
877 current-prefix-arg))
878 (avy-with avy-goto-char
879 (avy--generic-jump
880 (if (= 13 char)
881 "\n"
882 (regexp-quote (string char)))
883 arg
884 avy-style)))
885
886 ;;;###autoload
887 (defun avy-goto-char-in-line (char)
888 "Jump to the currently visible CHAR in the current line."
889 (interactive (list (read-char "char: " t)))
890 (avy-with avy-goto-char
891 (avy--generic-jump
892 (regexp-quote (string char))
893 avy-all-windows
894 avy-style
895 (line-beginning-position)
896 (line-end-position))))
897
898 ;;;###autoload
899 (defun avy-goto-char-2 (char1 char2 &optional arg)
900 "Jump to the currently visible CHAR1 followed by CHAR2.
901 The window scope is determined by `avy-all-windows' (ARG negates it)."
902 (interactive (list (read-char "char 1: " t)
903 (read-char "char 2: " t)
904 current-prefix-arg))
905 (avy-with avy-goto-char-2
906 (avy--generic-jump
907 (regexp-quote (string char1 char2))
908 arg
909 avy-style)))
910
911 ;;;###autoload
912 (defun avy-isearch ()
913 "Jump to one of the current isearch candidates."
914 (interactive)
915 (avy-with avy-isearch
916 (let ((avy-background nil))
917 (avy--process
918 (avy--regex-candidates isearch-string)
919 (avy--style-fn avy-style))
920 (isearch-done))))
921
922 ;;;###autoload
923 (defun avy-goto-word-0 (arg)
924 "Jump to a word start.
925 The window scope is determined by `avy-all-windows' (ARG negates it)."
926 (interactive "P")
927 (avy-with avy-goto-word-0
928 (avy--generic-jump "\\b\\sw" arg avy-style)))
929
930 ;;;###autoload
931 (defun avy-goto-word-1 (char &optional arg)
932 "Jump to the currently visible CHAR at a word start.
933 The window scope is determined by `avy-all-windows' (ARG negates it)."
934 (interactive (list (read-char "char: " t)
935 current-prefix-arg))
936 (avy-with avy-goto-word-1
937 (let* ((str (string char))
938 (regex (cond ((string= str ".")
939 "\\.")
940 ((and avy-word-punc-regexp
941 (string-match avy-word-punc-regexp str))
942 (regexp-quote str))
943 (t
944 (concat
945 "\\b"
946 str)))))
947 (avy--generic-jump regex arg avy-style))))
948
949 (declare-function subword-backward "subword")
950 (defvar subword-backward-regexp)
951
952 ;;;###autoload
953 (defun avy-goto-subword-0 (&optional arg predicate)
954 "Jump to a word or subword start.
955
956 The window scope is determined by `avy-all-windows' (ARG negates it).
957
958 When PREDICATE is non-nil it's a function of zero parameters that
959 should return true."
960 (interactive "P")
961 (require 'subword)
962 (avy-with avy-goto-subword-0
963 (let ((case-fold-search nil)
964 (subword-backward-regexp
965 "\\(\\(\\W\\|[[:lower:][:digit:]]\\)\\([!-/:@`~[:upper:]]+\\W*\\)\\|\\W\\w+\\)")
966 candidates)
967 (avy-dowindows arg
968 (let ((ws (window-start))
969 window-cands)
970 (save-excursion
971 (goto-char (window-end (selected-window) t))
972 (subword-backward)
973 (while (> (point) ws)
974 (when (or (null predicate)
975 (and predicate (funcall predicate)))
976 (unless (get-char-property (point) 'invisible)
977 (push (cons (point) (selected-window)) window-cands)))
978 (subword-backward)))
979 (setq candidates (nconc candidates window-cands))))
980 (avy--process candidates (avy--style-fn avy-style)))))
981
982 ;;;###autoload
983 (defun avy-goto-subword-1 (char &optional arg)
984 "Jump to the currently visible CHAR at a subword start.
985 The window scope is determined by `avy-all-windows' (ARG negates it).
986 The case of CHAR is ignored."
987 (interactive (list (read-char "char: " t)
988 current-prefix-arg))
989 (avy-with avy-goto-subword-1
990 (let ((char (downcase char)))
991 (avy-goto-subword-0
992 arg (lambda () (eq (downcase (char-after)) char))))))
993
994 ;;;###autoload
995 (defun avy-goto-word-or-subword-1 ()
996 "Forward to `avy-goto-subword-1' or `avy-goto-word-1'.
997 Which one depends on variable `subword-mode'."
998 (interactive)
999 (if (bound-and-true-p subword-mode)
1000 (call-interactively #'avy-goto-subword-1)
1001 (call-interactively #'avy-goto-word-1)))
1002
1003 (defvar visual-line-mode)
1004
1005 (defun avy--line (&optional arg beg end)
1006 "Select a line.
1007 The window scope is determined by `avy-all-windows' (ARG negates it).
1008 Narrow the scope to BEG END."
1009 (let (candidates)
1010 (avy-dowindows arg
1011 (let ((ws (or beg (window-start))))
1012 (save-excursion
1013 (save-restriction
1014 (narrow-to-region ws (or end (window-end (selected-window) t)))
1015 (goto-char (point-min))
1016 (while (< (point) (point-max))
1017 (unless (get-char-property
1018 (max (1- (point)) ws) 'invisible)
1019 (push (cons
1020 (if (eq avy-style 'post)
1021 (line-end-position)
1022 (point))
1023 (selected-window)) candidates))
1024 (if visual-line-mode
1025 (progn
1026 (setq temporary-goal-column 0)
1027 (line-move-visual 1 t))
1028 (forward-line 1)))))))
1029 (setq avy-action #'identity)
1030 (avy--process (nreverse candidates) (avy--style-fn avy-style))))
1031
1032 ;;;###autoload
1033 (defun avy-goto-line (&optional arg)
1034 "Jump to a line start in current buffer.
1035
1036 When ARG is 1, jump to lines currently visible, with the option
1037 to cancel to `goto-line' by entering a number.
1038
1039 When ARG is 4, negate the window scope determined by
1040 `avy-all-windows'.
1041
1042 Otherwise, forward to `goto-line' with ARG."
1043 (interactive "p")
1044 (if (not (memq arg '(1 4)))
1045 (progn
1046 (goto-char (point-min))
1047 (forward-line (1- arg)))
1048 (avy-with avy-goto-line
1049 (let* ((avy-handler-function
1050 (lambda (char)
1051 (if (or (< char ?0)
1052 (> char ?9))
1053 (avy-handler-default char)
1054 (let ((line (read-from-minibuffer
1055 "Goto line: " (string char))))
1056 (when line
1057 (avy-push-mark)
1058 (goto-char (point-min))
1059 (forward-line (1- (string-to-number line)))
1060 (throw 'done 'exit))))))
1061 (r (avy--line (eq arg 4))))
1062 (unless (eq r t)
1063 (avy-action-goto r))))))
1064
1065 ;;;###autoload
1066 (defun avy-goto-line-above ()
1067 "Goto visible line above the cursor."
1068 (interactive)
1069 (let* ((avy-all-windows nil)
1070 (r (avy--line nil (window-start) (point))))
1071 (unless (eq r t)
1072 (avy-action-goto r))))
1073
1074 ;;;###autoload
1075 (defun avy-goto-line-below ()
1076 "Goto visible line below the cursor."
1077 (interactive)
1078 (let* ((avy-all-windows nil)
1079 (r (avy--line
1080 nil (point)
1081 (window-end (selected-window) t))))
1082 (unless (eq r t)
1083 (avy-action-goto r))))
1084
1085 (defcustom avy-line-insert-style 'above
1086 "How to insert the newly copied/cut line."
1087 :type '(choice
1088 (const :tag "Above" above)
1089 (const :tag "Below" below)))
1090
1091 ;;;###autoload
1092 (defun avy-copy-line (arg)
1093 "Copy a selected line above the current line.
1094 ARG lines can be used."
1095 (interactive "p")
1096 (avy-with avy-copy-line
1097 (let* ((start (avy--line))
1098 (str (buffer-substring-no-properties
1099 start
1100 (save-excursion
1101 (goto-char start)
1102 (move-end-of-line arg)
1103 (point)))))
1104 (cond ((eq avy-line-insert-style 'above)
1105 (beginning-of-line)
1106 (save-excursion
1107 (insert str "\n")))
1108 ((eq avy-line-insert-style 'below)
1109 (end-of-line)
1110 (insert "\n" str)
1111 (beginning-of-line))
1112 (t
1113 (user-error "Unexpected `avy-line-insert-style'"))))))
1114
1115 ;;;###autoload
1116 (defun avy-move-line (arg)
1117 "Move a selected line above the current line.
1118 ARG lines can be used."
1119 (interactive "p")
1120 (avy-with avy-move-line
1121 (let ((start (avy--line)))
1122 (save-excursion
1123 (goto-char start)
1124 (kill-whole-line arg))
1125 (cond ((eq avy-line-insert-style 'above)
1126 (beginning-of-line)
1127 (save-excursion
1128 (insert
1129 (current-kill 0))))
1130 ((eq avy-line-insert-style 'below)
1131 (end-of-line)
1132 (newline)
1133 (save-excursion
1134 (insert (substring (current-kill 0) 0 -1))))
1135 (t
1136 (user-error "Unexpected `avy-line-insert-style'"))))))
1137
1138 ;;;###autoload
1139 (defun avy-copy-region ()
1140 "Select two lines and copy the text between them here."
1141 (interactive)
1142 (avy-with avy-copy-region
1143 (let* ((beg (avy--line))
1144 (end (avy--line))
1145 (str (buffer-substring-no-properties
1146 beg
1147 (save-excursion
1148 (goto-char end)
1149 (line-end-position)))))
1150 (cond ((eq avy-line-insert-style 'above)
1151 (beginning-of-line)
1152 (save-excursion
1153 (insert str "\n")))
1154 ((eq avy-line-insert-style 'below)
1155 (end-of-line)
1156 (newline)
1157 (save-excursion
1158 (insert str)))
1159 (t
1160 (user-error "Unexpected `avy-line-insert-style'"))))))
1161
1162 ;;;###autoload
1163 (defun avy-setup-default ()
1164 "Setup the default shortcuts."
1165 (eval-after-load "isearch"
1166 '(define-key isearch-mode-map (kbd "C-'") 'avy-isearch)))
1167
1168 (defcustom avy-timeout-seconds 0.5
1169 "How many seconds to wait for the second char.")
1170
1171 (defun avy--read-candidates ()
1172 "Read as many chars as possible and return their occurences.
1173 At least one char must be read, and then repeatedly one next char
1174 may be read if it is entered before `avy-timeout-seconds'. `DEL'
1175 deletes the last char entered, and `RET' exits with the currently
1176 read string immediately instead of waiting for another char for
1177 `avy-timeout-seconds'.
1178 The format of the result is the same as that of `avy--regex-candidates'.
1179 This function obeys `avy-all-windows' setting."
1180 (let ((str "") char break overlays regex)
1181 (unwind-protect
1182 (progn
1183 (while (and (not break)
1184 (setq char
1185 (read-char (format "char%s: "
1186 (if (string= str "")
1187 str
1188 (format " (%s)" str)))
1189 t
1190 (and (not (string= str ""))
1191 avy-timeout-seconds))))
1192 ;; Unhighlight
1193 (dolist (ov overlays)
1194 (delete-overlay ov))
1195 (setq overlays nil)
1196 (cond
1197 ;; Handle RET
1198 ((= char 13)
1199 (setq break t))
1200 ;; Handle DEL
1201 ((= char 127)
1202 (let ((l (length str)))
1203 (when (>= l 1)
1204 (setq str (substring str 0 (1- l))))))
1205 (t
1206 (setq str (concat str (list char)))))
1207 ;; Highlight
1208 (when (>= (length str) 1)
1209 (let (found)
1210 (avy-dowindows nil
1211 (dolist (pair (avy--find-visible-regions
1212 (window-start)
1213 (window-end (selected-window) t)))
1214 (save-excursion
1215 (goto-char (car pair))
1216 (setq regex (regexp-quote str))
1217 (while (re-search-forward regex (cdr pair) t)
1218 (unless (get-char-property (1- (point)) 'invisible)
1219 (let ((ov (make-overlay
1220 (match-beginning 0)
1221 (match-end 0))))
1222 (setq found t)
1223 (push ov overlays)
1224 (overlay-put ov 'window (selected-window))
1225 (overlay-put ov 'face 'avy-goto-char-timer-face)))))))
1226 ;; No matches at all, so there's surely a typo in the input.
1227 (unless found (beep)))))
1228 (nreverse (mapcar (lambda (ov)
1229 (cons (cons (overlay-start ov)
1230 (overlay-end ov))
1231 (overlay-get ov 'window)))
1232 overlays)))
1233 (dolist (ov overlays)
1234 (delete-overlay ov)))))
1235
1236 ;;;###autoload
1237 (defun avy-goto-char-timer (&optional arg)
1238 "Read one or many consecutive chars and jump to the first one.
1239 The window scope is determined by `avy-all-windows' (ARG negates it)."
1240 (interactive "P")
1241 (let ((avy-all-windows (if arg
1242 (not avy-all-windows)
1243 avy-all-windows)))
1244 (avy-with avy-goto-char-timer
1245 (avy--process
1246 (avy--read-candidates)
1247 (avy--style-fn avy-style)))))
1248
1249 (defvar avy-ring (make-ring 20)
1250 "Hold the window and point history.")
1251
1252 (defun avy-push-mark ()
1253 "Store the current point and window."
1254 (ring-insert avy-ring
1255 (cons (point) (selected-window)))
1256 (unless (region-active-p)
1257 (push-mark)))
1258
1259 (defun avy-pop-mark ()
1260 "Jump back to the last location of `avy-push-mark'."
1261 (interactive)
1262 (let (res)
1263 (condition-case nil
1264 (progn
1265 (while (not (window-live-p
1266 (cdr (setq res (ring-remove avy-ring 0))))))
1267 (let* ((window (cdr res))
1268 (frame (window-frame window)))
1269 (when (and (frame-live-p frame)
1270 (not (eq frame (selected-frame))))
1271 (select-frame-set-input-focus frame))
1272 (select-window window)
1273 (goto-char (car res))))
1274 (error
1275 (set-mark-command 4)))))
1276
1277 (define-obsolete-function-alias
1278 'avy--goto 'identity "0.3.0"
1279 "Don't use this function any more.
1280 `avy--process' will do the jump all by itself.")
1281
1282 (define-obsolete-function-alias 'avy--with-avy-keys 'avy-with "0.3.0")
1283
1284 (provide 'avy)
1285
1286 ;;; avy.el ends here