]> code.delx.au - gnu-emacs-elpa/blob - packages/hydra/hydra.el
Merge commit 'a7b4e52766977b58c6b9899305e962a2b5235bda'
[gnu-emacs-elpa] / packages / hydra / hydra.el
1 ;;; hydra.el --- Make bindings that stick around
2
3 ;; Copyright (C) 2015 Free Software Foundation, Inc.
4
5 ;; Author: Oleh Krehel <ohwoeowho@gmail.com>
6 ;; Maintainer: Oleh Krehel <ohwoeowho@gmail.com>
7 ;; URL: https://github.com/abo-abo/hydra
8 ;; Version: 0.11.0
9 ;; Keywords: bindings
10 ;; Package-Requires: ((cl-lib "0.5"))
11
12 ;; This file is part of GNU Emacs.
13
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
18
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26
27 ;;; Commentary:
28 ;;
29 ;; This package can be used to tie related commands into a family of
30 ;; short bindings with a common prefix - a Hydra.
31 ;;
32 ;; Once you summon the Hydra (through the prefixed binding), all the
33 ;; heads can be called in succession with only a short extension.
34 ;; The Hydra is vanquished once Hercules, any binding that isn't the
35 ;; Hydra's head, arrives. Note that Hercules, besides vanquishing the
36 ;; Hydra, will still serve his orignal purpose, calling his proper
37 ;; command. This makes the Hydra very seamless, it's like a minor
38 ;; mode that disables itself automagically.
39 ;;
40 ;; Here's an example Hydra, bound in the global map (you can use any
41 ;; keymap in place of `global-map'):
42 ;;
43 ;; (defhydra hydra-zoom (global-map "<f2>")
44 ;; "zoom"
45 ;; ("g" text-scale-increase "in")
46 ;; ("l" text-scale-decrease "out"))
47 ;;
48 ;; It allows to start a command chain either like this:
49 ;; "<f2> gg4ll5g", or "<f2> lgllg".
50 ;;
51 ;; Here's another approach, when you just want a "callable keymap":
52 ;;
53 ;; (defhydra hydra-toggle (:color blue)
54 ;; "toggle"
55 ;; ("a" abbrev-mode "abbrev")
56 ;; ("d" toggle-debug-on-error "debug")
57 ;; ("f" auto-fill-mode "fill")
58 ;; ("t" toggle-truncate-lines "truncate")
59 ;; ("w" whitespace-mode "whitespace")
60 ;; ("q" nil "cancel"))
61 ;;
62 ;; This binds nothing so far, but if you follow up with:
63 ;;
64 ;; (global-set-key (kbd "C-c C-v") 'hydra-toggle/body)
65 ;;
66 ;; you will have bound "C-c C-v a", "C-c C-v d" etc.
67 ;;
68 ;; Knowing that `defhydra' defines e.g. `hydra-toggle/body' command,
69 ;; you can nest Hydras if you wish, with `hydra-toggle/body' possibly
70 ;; becoming a blue head of another Hydra.
71 ;;
72 ;; Initially, Hydra shipped with a simplified `hydra-create' macro, to
73 ;; which you could hook up the examples from hydra-examples.el. It's
74 ;; better to take the examples simply as templates and use `defhydra'
75 ;; instead of `hydra-create', since it's more flexible.
76
77 ;;; Code:
78 ;;* Requires
79 (require 'cl-lib)
80 (require 'lv)
81
82 (defalias 'hydra-set-transient-map
83 (if (fboundp 'set-transient-map)
84 'set-transient-map
85 (lambda (map keep-pred &optional on-exit)
86 (with-no-warnings
87 (set-temporary-overlay-map map (hydra--pred on-exit))))))
88
89 (defun hydra--pred (on-exit)
90 "Generate a predicate on whether to continue the Hydra state.
91 Call ON-EXIT for clean-up.
92 This is a compatibility code for Emacs older than 24.4."
93 `(lambda ()
94 (if (lookup-key hydra-curr-map (this-command-keys-vector))
95 t
96 (hydra-cleanup)
97 ,(when on-exit
98 `(funcall ,(hydra--make-callable on-exit)))
99 nil)))
100
101 ;;* Customize
102 (defgroup hydra nil
103 "Make bindings that stick around."
104 :group 'bindings
105 :prefix "hydra-")
106
107 (defcustom hydra-is-helpful t
108 "When t, display a hint with possible bindings in the echo area."
109 :type 'boolean
110 :group 'hydra)
111
112 (defcustom hydra-keyboard-quit "\a"
113 "This binding will quit an amaranth Hydra.
114 It's the only other way to quit it besides though a blue head.
115 It's possible to set this to nil.")
116
117 (defcustom hydra-lv t
118 "When non-nil, `lv-message' (not `message') will be used to display hints."
119 :type 'boolean)
120
121 (defcustom hydra-verbose nil
122 "When non-nil, hydra will issue some non essential style warnings."
123 :type 'boolean)
124
125 (defcustom hydra-key-format-spec "%s"
126 "Default `format'-style specifier for _a_ syntax in docstrings.
127 When nil, you can specify your own at each location like this: _ 5a_.")
128
129 (defface hydra-face-red
130 '((t (:foreground "#FF0000" :bold t)))
131 "Red Hydra heads will persist indefinitely."
132 :group 'hydra)
133
134 (defface hydra-face-blue
135 '((t (:foreground "#0000FF" :bold t)))
136 "Blue Hydra heads will vanquish the Hydra.")
137
138 (defface hydra-face-amaranth
139 '((t (:foreground "#E52B50" :bold t)))
140 "Amaranth body has red heads and warns on intercepting non-heads.
141 Vanquishable only through a blue head.")
142
143 (defface hydra-face-pink
144 '((t (:foreground "#FF6EB4" :bold t)))
145 "Pink body has red heads and on intercepting non-heads calls them without quitting.
146 Vanquishable only through a blue head.")
147
148 (defface hydra-face-teal
149 '((t (:foreground "#367588" :bold t)))
150 "Teal body has blue heads an warns on intercepting non-heads.
151 Vanquishable only through a blue head.")
152
153 ;;* Fontification
154 (defun hydra-add-font-lock ()
155 "Fontify `defhydra' statements."
156 (font-lock-add-keywords
157 'emacs-lisp-mode
158 '(("(\\(defhydra\\)\\_> +\\(.*?\\)\\_>"
159 (1 font-lock-keyword-face)
160 (2 font-lock-type-face))
161 ("(\\(defhydradio\\)\\_> +\\(.*?\\)\\_>"
162 (1 font-lock-keyword-face)
163 (2 font-lock-type-face)))))
164
165 ;;* Universal Argument
166 (defvar hydra-base-map
167 (let ((map (make-sparse-keymap)))
168 (define-key map [?\C-u] 'hydra--universal-argument)
169 (define-key map [?-] 'hydra--negative-argument)
170 (define-key map [?0] 'hydra--digit-argument)
171 (define-key map [?1] 'hydra--digit-argument)
172 (define-key map [?2] 'hydra--digit-argument)
173 (define-key map [?3] 'hydra--digit-argument)
174 (define-key map [?4] 'hydra--digit-argument)
175 (define-key map [?5] 'hydra--digit-argument)
176 (define-key map [?6] 'hydra--digit-argument)
177 (define-key map [?7] 'hydra--digit-argument)
178 (define-key map [?8] 'hydra--digit-argument)
179 (define-key map [?9] 'hydra--digit-argument)
180 (define-key map [kp-0] 'hydra--digit-argument)
181 (define-key map [kp-1] 'hydra--digit-argument)
182 (define-key map [kp-2] 'hydra--digit-argument)
183 (define-key map [kp-3] 'hydra--digit-argument)
184 (define-key map [kp-4] 'hydra--digit-argument)
185 (define-key map [kp-5] 'hydra--digit-argument)
186 (define-key map [kp-6] 'hydra--digit-argument)
187 (define-key map [kp-7] 'hydra--digit-argument)
188 (define-key map [kp-8] 'hydra--digit-argument)
189 (define-key map [kp-9] 'hydra--digit-argument)
190 (define-key map [kp-subtract] 'hydra--negative-argument)
191 map)
192 "Keymap that all Hydras inherit. See `universal-argument-map'.")
193
194 (defvar hydra-curr-map
195 (make-sparse-keymap)
196 "Keymap of the current Hydra called.")
197
198 (defun hydra--universal-argument (arg)
199 "Forward to (`universal-argument' ARG)."
200 (interactive "P")
201 (setq prefix-arg (if (consp arg)
202 (list (* 4 (car arg)))
203 (if (eq arg '-)
204 (list -4)
205 '(4))))
206 (hydra-set-transient-map hydra-curr-map t))
207
208 (defun hydra--digit-argument (arg)
209 "Forward to (`digit-argument' ARG)."
210 (interactive "P")
211 (let ((universal-argument-map hydra-curr-map))
212 (digit-argument arg)))
213
214 (defun hydra--negative-argument (arg)
215 "Forward to (`negative-argument' ARG)."
216 (interactive "P")
217 (let ((universal-argument-map hydra-curr-map))
218 (negative-argument arg)))
219 ;;* Repeat
220 (defvar hydra-repeat--prefix-arg nil
221 "Prefix arg to use with `hydra-repeat'.")
222
223 (defvar hydra-repeat--command nil
224 "Command to use with `hydra-repeat'.")
225
226 (defun hydra-repeat ()
227 "Repeat last command with last prefix arg."
228 (interactive)
229 (unless (string-match "hydra-repeat$" (symbol-name last-command))
230 (setq hydra-repeat--command last-command)
231 (setq hydra-repeat--prefix-arg (or last-prefix-arg 1)))
232 (setq current-prefix-arg hydra-repeat--prefix-arg)
233 (funcall hydra-repeat--command))
234
235 ;;* Misc internals
236 (defvar hydra-last nil
237 "The result of the last `hydra-set-transient-map' call.")
238
239 (defun hydra--callablep (x)
240 "Test if X is callable."
241 (or (functionp x)
242 (and (consp x)
243 (memq (car x) '(function quote)))))
244
245 (defun hydra--make-callable (x)
246 "Generate a callable symbol from X.
247 If X is a function symbol or a lambda, return it. Otherwise, it
248 should be a single statement. Wrap it in an interactive lambda."
249 (if (or (symbolp x) (functionp x))
250 x
251 `(lambda ()
252 (interactive)
253 ,x)))
254
255 (defun hydra--head-property (h prop &optional default)
256 "Return for Hydra head H the value of property PROP.
257 Return DEFAULT if PROP is not in H."
258 (let ((plist (cl-cdddr h)))
259 (if (memq prop h)
260 (plist-get plist prop)
261 default)))
262
263 (defun hydra--aggregate-color (head-color body-color)
264 "Return the resulting head color for HEAD-COLOR and BODY-COLOR."
265 (cond ((eq head-color 'red)
266 (cl-case body-color
267 (red 'red)
268 (blue 'red)
269 (amaranth 'amaranth)
270 (pink 'pink)
271 (cyan 'amaranth)))
272 ((eq head-color 'blue)
273 (cl-case body-color
274 (red 'blue)
275 (blue 'blue)
276 (amaranth 'teal)
277 (pink 'blue)
278 (cyan 'teal)))
279 (t
280 (error "Can't aggregate head %S to body %S"
281 head-color body-color))))
282
283 (defun hydra--head-color (h body)
284 "Return the color of a Hydra head H with BODY."
285 (let* ((exit (hydra--head-property h :exit 'default))
286 (color (hydra--head-property h :color))
287 (foreign-keys (hydra--body-foreign-keys body))
288 (head-color
289 (cond ((eq exit 'default)
290 (cl-case color
291 (blue 'blue)
292 (red 'red)
293 (t
294 (unless (null color)
295 (error "Use only :blue or :red for heads: %S" h)))))
296 ((null exit)
297 (if color
298 (error "Don't mix :color and :exit - they are aliases: %S" h)
299 (cl-case foreign-keys
300 (run 'pink)
301 (warn 'amaranth)
302 (t 'red))))
303 ((eq exit t)
304 (if color
305 (error "Don't mix :color and :exit - they are aliases: %S" h)
306 'blue))
307 (t
308 (error "Unknown :exit %S" exit)))))
309 (let ((body-exit (plist-get (cddr body) :exit)))
310 (cond ((null (cadr h))
311 (when head-color
312 (hydra--complain
313 "Doubly specified blue head - nil cmd is already blue: %S" h))
314 'blue)
315 ((null head-color)
316 (hydra--body-color body))
317 ((null foreign-keys)
318 head-color)
319 ((eq foreign-keys 'run)
320 (if (eq head-color 'red)
321 'pink
322 'blue))
323 ((eq foreign-keys 'warn)
324 (if (memq head-color '(red amaranth))
325 'amaranth
326 'teal))
327 (t
328 (error "Unexpected %S %S" h body))))))
329
330 (defun hydra--body-foreign-keys (body)
331 "Return what BODY does with a non-head binding."
332 (or
333 (plist-get (cddr body) :foreign-keys)
334 (let ((color (plist-get (cddr body) :color)))
335 (cl-case color
336 ((amaranth teal) 'warn)
337 (pink 'run)))))
338
339 (defun hydra--body-color (body)
340 "Return the color of BODY.
341 BODY is the second argument to `defhydra'"
342 (let ((color (plist-get (cddr body) :color))
343 (exit (plist-get (cddr body) :exit))
344 (foreign-keys (plist-get (cddr body) :foreign-keys)))
345 (cond ((eq foreign-keys 'warn)
346 (if exit 'teal 'amaranth))
347 ((eq foreign-keys 'run) 'pink)
348 (exit 'blue)
349 (color color)
350 (t 'red))))
351
352 (defun hydra--face (h body)
353 "Return the face for a Hydra head H with BODY."
354 (cl-case (hydra--head-color h body)
355 (blue 'hydra-face-blue)
356 (red 'hydra-face-red)
357 (amaranth 'hydra-face-amaranth)
358 (pink 'hydra-face-pink)
359 (teal 'hydra-face-teal)
360 (t (error "Unknown color for %S" h))))
361
362 (defun hydra-cleanup ()
363 "Clean up after a Hydra."
364 (when (window-live-p lv-wnd)
365 (let ((buf (window-buffer lv-wnd)))
366 (delete-window lv-wnd)
367 (kill-buffer buf))))
368
369 (defun hydra-keyboard-quit ()
370 "Quitting function similar to `keyboard-quit'."
371 (interactive)
372 (hydra-disable)
373 (hydra-cleanup)
374 (cancel-timer hydra-timer)
375 nil)
376
377 (defun hydra-disable ()
378 "Disable the current Hydra."
379 (cond
380 ;; Emacs 25
381 ((functionp hydra-last)
382 (funcall hydra-last))
383
384 ;; Emacs 24.3 or older
385 ((< emacs-minor-version 4)
386 (setq emulation-mode-map-alists
387 (cl-remove-if
388 (lambda (x)
389 (and (consp x)
390 (consp (car x))
391 (equal (cdar x) hydra-curr-map)))
392 emulation-mode-map-alists)))
393
394 ;; Emacs 24.4.1
395 (t
396 (setq overriding-terminal-local-map nil))))
397
398 (defun hydra--unalias-var (str prefix)
399 "Return the symbol named STR if it's bound as a variable.
400 Otherwise, add PREFIX to the symbol name."
401 (let ((sym (intern-soft str)))
402 (if (boundp sym)
403 sym
404 (intern (concat prefix "/" str)))))
405
406 (defun hydra--hint (name body docstring heads)
407 "Generate a hint for the echo area.
408 NAME, BODY, DOCSTRING and HEADS are parameters to `defhydra'."
409 (let (alist)
410 (dolist (h heads)
411 (let ((val (assoc (cadr h) alist))
412 (pstr (hydra-fontify-head h body)))
413 (unless (null (cl-caddr h))
414 (if val
415 (setf (cadr val)
416 (concat (cadr val) " " pstr))
417 (push
418 (cons (cadr h)
419 (cons pstr (cl-caddr h)))
420 alist)))))
421 (mapconcat
422 (lambda (x)
423 (format
424 (if (> (length (cdr x)) 0)
425 (concat "[%s]: " (cdr x))
426 "%s")
427 (car x)))
428 (nreverse (mapcar #'cdr alist))
429 ", ")))
430
431 (defvar hydra-fontify-head-function nil
432 "Possible replacement for `hydra-fontify-head-default'.")
433
434 (defun hydra-fontify-head-default (head body)
435 "Produce a pretty string from HEAD and BODY.
436 HEAD's binding is returned as a string with a colored face."
437 (propertize (car head) 'face (hydra--face head body)))
438
439 (defun hydra-fontify-head-greyscale (head body)
440 "Produce a pretty string from HEAD and BODY.
441 HEAD's binding is returned as a string wrapped with [] or {}."
442 (let ((color (hydra--head-color head body)))
443 (format
444 (if (eq color 'blue)
445 "[%s]"
446 "{%s}") (car head))))
447
448 (defun hydra-fontify-head (head body)
449 "Produce a pretty string from HEAD and BODY."
450 (funcall (or hydra-fontify-head-function 'hydra-fontify-head-default)
451 head body))
452
453 (defun hydra--format (name body docstring heads)
454 "Generate a `format' statement from STR.
455 \"%`...\" expressions are extracted into \"%S\".
456 NAME, BODY, DOCSTRING and HEADS are parameters of `defhydra'.
457 The expressions can be auto-expanded according to NAME."
458 (setq docstring (replace-regexp-in-string "\\^" "" docstring))
459 (let ((rest (hydra--hint name body docstring heads))
460 (body-color (hydra--body-color body))
461 (prefix (symbol-name name))
462 (start 0)
463 varlist
464 offset)
465 (while (setq start
466 (string-match
467 "\\(?:%\\( ?-?[0-9]*s?\\)\\(`[a-z-A-Z/0-9]+\\|(\\)\\)\\|\\(?:_\\( ?-?[0-9]*\\)\\([a-z-~A-Z0-9/|?<>={}]+\\)_\\)"
468 docstring start))
469 (cond ((eq ?_ (aref (match-string 0 docstring) 0))
470 (let* ((key (match-string 4 docstring))
471 (head (assoc key heads)))
472 (if head
473 (progn
474 (push (hydra-fontify-head head body) varlist)
475 (setq docstring
476 (replace-match
477 (or
478 hydra-key-format-spec
479 (concat "%" (match-string 3 docstring) "s"))
480 nil nil docstring)))
481 (error "Unrecognized key: _%s_" key))))
482
483 ((eq ?` (aref (match-string 2 docstring) 0))
484 (push (hydra--unalias-var
485 (substring (match-string 2 docstring) 1) prefix) varlist)
486 (setq docstring
487 (replace-match
488 (concat "%" (match-string 1 docstring) "S")
489 nil nil docstring 0)))
490
491 (t
492 (let* ((spec (match-string 1 docstring))
493 (lspec (length spec)))
494 (setq offset
495 (with-temp-buffer
496 (insert (substring docstring (+ 1 start (length spec))))
497 (goto-char (point-min))
498 (push (read (current-buffer)) varlist)
499 (point)))
500 (when (or (zerop lspec)
501 (/= (aref spec (1- (length spec))) ?s))
502 (setq spec (concat spec "S")))
503 (setq docstring
504 (concat
505 (substring docstring 0 start)
506 "%" spec
507 (substring docstring
508 (+ (match-end 2) offset -2))))))))
509 (if (eq ?\n (aref docstring 0))
510 `(concat (format ,(substring docstring 1) ,@(nreverse varlist))
511 ,rest)
512 `(format ,(concat docstring ": " rest ".")))))
513
514 (defun hydra--message (name body docstring heads)
515 "Generate code to display the hint in the preferred echo area.
516 Set `hydra-lv' to choose the echo area.
517 NAME, BODY, DOCSTRING, and HEADS are parameters of `defhydra'."
518 (let ((format-expr (hydra--format name body docstring heads)))
519 `(if hydra-lv
520 (lv-message ,format-expr)
521 (message ,format-expr))))
522
523 (defun hydra--complain (format-string &rest args)
524 "Forward to (`message' FORMAT-STRING ARGS) unless `hydra-verbose' is nil."
525 (when hydra-verbose
526 (apply #'warn format-string args)))
527
528 (defun hydra--doc (body-key body-name heads)
529 "Generate a part of Hydra docstring.
530 BODY-KEY is the body key binding.
531 BODY-NAME is the symbol that identifies the Hydra.
532 HEADS is a list of heads."
533 (format
534 "Create a hydra with %s body and the heads:\n\n%s\n\n%s"
535 (if body-key
536 (format "a \"%s\"" body-key)
537 "no")
538 (mapconcat
539 (lambda (x)
540 (format "\"%s\": `%S'" (car x) (cadr x)))
541 heads ",\n")
542 (format "The body can be accessed via `%S'." body-name)))
543
544 (defun hydra--make-defun (name body doc head
545 keymap body-pre body-post &optional other-post)
546 "Make a defun wrapper, using NAME, BODY, DOC, HEAD, and KEYMAP.
547 NAME and BODY are the arguments to `defhydra'.
548 DOC was generated with `hydra--doc'.
549 HEAD is one of the HEADS passed to `defhydra'.
550 BODY-PRE and BODY-POST are pre-processed in `defhydra'.
551 OTHER-POST is an optional extension to the :post key of BODY."
552 (let ((name (hydra--head-name head name))
553 (cmd (when (car head)
554 (hydra--make-callable
555 (cadr head))))
556 (color (when (car head)
557 (hydra--head-color head body)))
558 (doc (if (car head)
559 (format "%s\n\nCall the head: `%S'." doc (cadr head))
560 doc))
561 (hint (intern (format "%S/hint" name)))
562 (body-color (hydra--body-color body))
563 (body-timeout (plist-get body :timeout)))
564 `(defun ,name ()
565 ,doc
566 (interactive)
567 ,@(when body-pre (list body-pre))
568 (hydra-disable)
569 ,@(when (memq color '(blue teal)) '((hydra-cleanup)))
570 (catch 'hydra-disable
571 ,@(delq nil
572 (if (memq color '(blue teal))
573 `(,(when cmd `(call-interactively #',cmd))
574 ,body-post)
575 `(,(when cmd
576 `(condition-case err
577 (prog1 t
578 (call-interactively #',cmd))
579 ((quit error)
580 (message "%S" err)
581 (unless hydra-lv
582 (sit-for 0.8))
583 nil)))
584 (when hydra-is-helpful
585 (,hint))
586 (setq hydra-last
587 (hydra-set-transient-map
588 (setq hydra-curr-map ',keymap)
589 t
590 ,(if (and
591 (not (memq body-color
592 '(amaranth pink teal)))
593 body-post)
594 `(lambda () (hydra-cleanup) ,body-post)
595 `(lambda () (hydra-cleanup)))))
596 ,(or other-post
597 (when body-timeout
598 `(hydra-timeout ,body-timeout))))))))))
599
600 (defun hydra-pink-fallback ()
601 "On intercepting a non-head, try to run it."
602 (let ((keys (this-command-keys))
603 kb)
604 (when (equal keys [backspace])
605 (setq keys "\7f"))
606 (setq kb (key-binding keys))
607 (if kb
608 (if (commandp kb)
609 (condition-case err
610 (call-interactively kb)
611 ((quit error)
612 (message "%S" err)
613 (unless hydra-lv
614 (sit-for 0.8))))
615 (message "Pink Hydra can't currently handle prefixes, continuing"))
616 (message "Pink Hydra could not resolve: %S" keys))))
617
618 (defun hydra--handle-nonhead (keymap name body heads)
619 "Setup KEYMAP for intercepting non-head bindings.
620 NAME, BODY and HEADS are parameters to `defhydra'."
621 (let ((body-color (hydra--body-color body))
622 (body-post (plist-get (cddr body) :post)))
623 (when (and body-post (symbolp body-post))
624 (setq body-post `(funcall #',body-post)))
625 (when hydra-keyboard-quit
626 (define-key keymap hydra-keyboard-quit #'hydra-keyboard-quit))
627 (when (memq body-color '(amaranth pink teal))
628 (if (cl-some `(lambda (h)
629 (memq (hydra--head-color h body) '(blue teal)))
630 heads)
631 (progn
632 (define-key keymap [t]
633 `(lambda ()
634 (interactive)
635 ,(cond
636 ((memq body-color '(amaranth teal))
637 '(message "An amaranth Hydra can only exit through a blue head"))
638 (t
639 '(hydra-pink-fallback)))
640 (hydra-set-transient-map hydra-curr-map t)
641 (when hydra-is-helpful
642 (unless hydra-lv
643 (sit-for 0.8))
644 (,(intern (format "%S/hint" name)))))))
645 (unless (eq body-color 'teal)
646 (error
647 "An %S Hydra must have at least one blue head in order to exit"
648 body-color))))))
649
650 (defun hydra--head-name (h body-name)
651 "Return the symbol for head H of body BODY-NAME."
652 (intern (format "%S/%s" body-name
653 (if (symbolp (cadr h))
654 (cadr h)
655 (concat "lambda-" (car h))))))
656
657 (defun hydra--delete-duplicates (heads)
658 "Return HEADS without entries that have the same CMD part.
659 In duplicate HEADS, :cmd-name is modified to whatever they duplicate."
660 (let ((ali '(((hydra-repeat . red) . hydra-repeat)))
661 res entry)
662 (dolist (h heads)
663 (if (setq entry (assoc (cons (cadr h)
664 (hydra--head-color h '(nil nil)))
665 ali))
666 (setf (cl-cdddr h) (plist-put (cl-cdddr h) :cmd-name (cdr entry)))
667 (push (cons (cons (cadr h)
668 (hydra--head-color h '(nil nil)))
669 (plist-get (cl-cdddr h) :cmd-name))
670 ali)
671 (push h res)))
672 (nreverse res)))
673
674 (defun hydra--pad (lst n)
675 "Pad LST with nil until length N."
676 (let ((len (length lst)))
677 (if (= len n)
678 lst
679 (append lst (make-list (- n len) nil)))))
680
681 (defun hydra--matrix (lst rows cols)
682 "Create a matrix from elements of LST.
683 The matrix size is ROWS times COLS."
684 (let ((ls (copy-sequence lst))
685 res)
686 (dotimes (c cols)
687 (push (hydra--pad (hydra-multipop ls rows) rows) res))
688 (nreverse res)))
689
690 (defun hydra--cell (fstr names)
691 "Format a rectangular cell based on FSTR and NAMES.
692 FSTR is a format-style string with two string inputs: one for the
693 doc and one for the symbol name.
694 NAMES is a list of variables."
695 (let ((len (cl-reduce
696 (lambda (acc it) (max (length (symbol-name it)) acc))
697 names
698 :initial-value 0)))
699 (mapconcat
700 (lambda (sym)
701 (if sym
702 (format fstr
703 (documentation-property sym 'variable-documentation)
704 (let ((name (symbol-name sym)))
705 (concat name (make-string (- len (length name)) ?^)))
706 sym)
707 ""))
708 names
709 "\n")))
710
711 (defun hydra--vconcat (strs &optional joiner)
712 "Glue STRS vertically. They must be the same height.
713 JOINER is a function similar to `concat'."
714 (setq joiner (or joiner #'concat))
715 (mapconcat
716 (lambda (s)
717 (if (string-match " +$" s)
718 (replace-match "" nil nil s)
719 s))
720 (apply #'cl-mapcar joiner
721 (mapcar
722 (lambda (s) (split-string s "\n"))
723 strs))
724 "\n"))
725
726 (defcustom hydra-cell-format "% -20s %% -8`%s"
727 "The default format for docstring cells."
728 :type 'string)
729
730 (defun hydra--table (names rows cols &optional cell-formats)
731 "Format a `format'-style table from variables in NAMES.
732 The size of the table is ROWS times COLS.
733 CELL-FORMATS are `format' strings for each column.
734 If CELL-FORMATS is a string, it's used for all columns.
735 If CELL-FORMATS is nil, `hydra-cell-format' is used for all columns."
736 (setq cell-formats
737 (cond ((null cell-formats)
738 (make-list cols hydra-cell-format))
739 ((stringp cell-formats)
740 (make-list cols cell-formats))
741 (t
742 cell-formats)))
743 (hydra--vconcat
744 (cl-mapcar
745 #'hydra--cell
746 cell-formats
747 (hydra--matrix names rows cols))
748 (lambda (&rest x)
749 (mapconcat #'identity x " "))))
750
751 (defun hydra-reset-radios (names)
752 "Set varibles NAMES to their defaults.
753 NAMES should be defined by `defhydradio' or similar."
754 (dolist (n names)
755 (set n (aref (get n 'range) 0))))
756
757 (defvar hydra-timer (timer-create)
758 "Timer for `hydra-timeout'.")
759
760 (defun hydra-timeout (secs &optional function)
761 "In SECS seconds call FUNCTION.
762 FUNCTION defaults to `hydra-disable'.
763 Cancel the previous `hydra-timeout'."
764 (cancel-timer hydra-timer)
765 (setq hydra-timer (timer-create))
766 (timer-set-time hydra-timer
767 (timer-relative-time nil secs))
768 (timer-set-function
769 hydra-timer
770 (or function #'hydra-keyboard-quit))
771 (timer-activate hydra-timer))
772
773 ;;* Macros
774 ;;** defhydra
775 ;;;###autoload
776 (defmacro defhydra (name body &optional docstring &rest heads)
777 "Create a Hydra - a family of functions with prefix NAME.
778
779 NAME should be a symbol, it will be the prefix of all functions
780 defined here.
781
782 BODY has the format:
783
784 (BODY-MAP BODY-KEY &rest PLIST)
785
786 DOCSTRING will be displayed in the echo area to identify the
787 Hydra.
788
789 Functions are created on basis of HEADS, each of which has the
790 format:
791
792 (KEY CMD &optional HINT &rest PLIST)
793
794 BODY-MAP is a keymap; `global-map' is used quite often. Each
795 function generated from HEADS will be bound in BODY-MAP to
796 BODY-KEY + KEY (both are strings passed to `kbd'), and will set
797 the transient map so that all following heads can be called
798 though KEY only.
799
800 CMD is a callable expression: either an interactive function
801 name, or an interactive lambda, or a single sexp (it will be
802 wrapped in an interactive lambda).
803
804 HINT is a short string that identifies its head. It will be
805 printed beside KEY in the echo erea if `hydra-is-helpful' is not
806 nil. If you don't even want the KEY to be printed, set HINT
807 explicitly to nil.
808
809 The heads inherit their PLIST from the body and are allowed to
810 override each key. The keys recognized are :color and :bind.
811 :color can be:
812
813 - red (default): this head will continue the Hydra state.
814 - blue: this head will stop the Hydra state.
815 - amaranth (applies to body only): similar to red, but no binding
816 except a blue head can stop the Hydra state.
817
818 :bind can be:
819 - nil: this head will not be bound in BODY-MAP.
820 - a lambda taking KEY and CMD used to bind a head
821
822 It is possible to omit both BODY-MAP and BODY-KEY if you don't
823 want to bind anything. In that case, typically you will bind the
824 generated NAME/body command. This command is also the return
825 result of `defhydra'."
826 (declare (indent defun))
827 (cond ((stringp docstring))
828 ((and (consp docstring)
829 (memq (car docstring) '(hydra--table concat format)))
830 (setq docstring (concat "\n" (eval docstring))))
831 (t
832 (setq heads (cons docstring heads))
833 (setq docstring "hydra")))
834 (when (keywordp (car body))
835 (setq body (cons nil (cons nil body))))
836 (dolist (h heads)
837 (let ((len (length h))
838 (cmd-name (hydra--head-name h name)))
839 (cond ((< len 2)
840 (error "Each head should have at least two items: %S" h))
841 ((= len 2)
842 (setcdr (cdr h) `("" :cmd-name ,cmd-name)))
843 (t
844 (let ((hint (cl-caddr h)))
845 (unless (or (null hint)
846 (stringp hint))
847 (setcdr (cdr h) (cons "" (cddr h))))
848 (setcdr (cddr h) `(:cmd-name ,cmd-name ,@(cl-cdddr h))))))))
849 (let* ((keymap (copy-keymap hydra-base-map))
850 (body-name (intern (format "%S/body" name)))
851 (body-key (unless (hydra--callablep body)
852 (cadr body)))
853 (body-color (hydra--body-color body))
854 (body-pre (plist-get (cddr body) :pre))
855 (body-body-pre (plist-get (cddr body) :body-pre))
856 (body-post (plist-get (cddr body) :post))
857 (method (or (plist-get body :bind)
858 (car body)))
859 (doc (hydra--doc body-key body-name heads))
860 (heads-nodup (hydra--delete-duplicates heads)))
861 (mapc
862 (lambda (x)
863 (define-key keymap (kbd (car x))
864 (plist-get (cl-cdddr x) :cmd-name)))
865 heads)
866 (when (and body-pre (symbolp body-pre))
867 (setq body-pre `(funcall #',body-pre)))
868 (when (and body-body-pre (symbolp body-body-pre))
869 (setq body-body-pre `(funcall #',body-body-pre)))
870 (when (and body-post (symbolp body-post))
871 (setq body-post `(funcall #',body-post)))
872 (hydra--handle-nonhead keymap name body heads)
873 `(progn
874 ,@(mapcar
875 (lambda (head)
876 (hydra--make-defun name body doc head keymap
877 body-pre body-post))
878 heads-nodup)
879 ,@(unless (or (null body-key)
880 (null method)
881 (hydra--callablep method))
882 `((unless (keymapp (lookup-key ,method (kbd ,body-key)))
883 (define-key ,method (kbd ,body-key) nil))))
884 ,@(delq nil
885 (cl-mapcar
886 (lambda (head)
887 (let ((name (hydra--head-property head :cmd-name)))
888 (when (cadr head)
889 (when (or body-key method)
890 (let ((bind (hydra--head-property head :bind 'default))
891 (final-key
892 (if body-key
893 (vconcat (kbd body-key) (kbd (car head)))
894 (kbd (car head)))))
895 (cond ((null bind) nil)
896
897 ((eq bind 'default)
898 (list
899 (if (hydra--callablep method)
900 'funcall
901 'define-key)
902 method
903 final-key
904 (list 'function name)))
905
906 ((hydra--callablep bind)
907 `(funcall (function ,bind)
908 ,final-key
909 (function ,name)))
910
911 (t
912 (error "Invalid :bind property %S" head))))))))
913 heads))
914 (defun ,(intern (format "%S/hint" name)) ()
915 ,(hydra--message name body docstring heads))
916 ,(hydra--make-defun
917 name body doc '(nil body)
918 keymap
919 (or body-body-pre body-pre) body-post
920 '(setq prefix-arg current-prefix-arg)))))
921
922 (defmacro defhydradio (name body &rest heads)
923 "Create radios with prefix NAME.
924 BODY specifies the options; there are none currently.
925 HEADS have the format:
926
927 (TOGGLE-NAME &optional VALUE DOC)
928
929 TOGGLE-NAME will be used along with NAME to generate a variable
930 name and a function that cycles it with the same name. VALUE
931 should be an array. The first element of VALUE will be used to
932 inialize the variable.
933 VALUE defaults to [nil t].
934 DOC defaults to TOGGLE-NAME split and capitalized."
935 (declare (indent defun))
936 `(progn
937 ,@(apply #'append
938 (mapcar (lambda (h)
939 (hydra--radio name h))
940 heads))
941 (defvar ,(intern (format "%S/names" name))
942 ',(mapcar (lambda (h) (intern (format "%S/%S" name (car h))))
943 heads))))
944
945 (defmacro hydra-multipop (lst n)
946 "Return LST's first N elements while removing them."
947 `(if (<= (length ,lst) ,n)
948 (prog1 ,lst
949 (setq ,lst nil))
950 (prog1 ,lst
951 (setcdr
952 (nthcdr (1- ,n) (prog1 ,lst (setq ,lst (nthcdr ,n ,lst))))
953 nil))))
954
955 (defun hydra--radio (parent head)
956 "Generate a hydradio with PARENT from HEAD."
957 (let* ((name (car head))
958 (full-name (intern (format "%S/%S" parent name)))
959 (doc (cadr head))
960 (val (or (cl-caddr head) [nil t])))
961 `((defvar ,full-name ,(hydra--quote-maybe (aref val 0)) ,doc)
962 (put ',full-name 'range ,val)
963 (defun ,full-name ()
964 (hydra--cycle-radio ',full-name)))))
965
966 (defun hydra--quote-maybe (x)
967 "Quote X if it's a symbol."
968 (cond ((null x)
969 nil)
970 ((symbolp x)
971 (list 'quote x))
972 (t
973 x)))
974
975 (defun hydra--cycle-radio (sym)
976 "Set SYM to the next value in its range."
977 (let* ((val (symbol-value sym))
978 (range (get sym 'range))
979 (i 0)
980 (l (length range)))
981 (setq i (catch 'done
982 (while (< i l)
983 (if (equal (aref range i) val)
984 (throw 'done (1+ i))
985 (incf i)))
986 (error "Val not in range for %S" sym)))
987 (set sym
988 (aref range
989 (if (>= i l)
990 0
991 i)))))
992
993 (provide 'hydra)
994
995 ;;; Local Variables:
996 ;;; outline-regexp: ";;\\*+"
997 ;;; End:
998
999 ;;; hydra.el ends here