]> code.delx.au - gnu-emacs-elpa/blob - hydra.el
Allow for the "%s`foo" spec.
[gnu-emacs-elpa] / hydra.el
1 ;;; hydra.el --- Make bindings that stick around. -*- lexical-binding: t -*-
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.12.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 (define-key map [switch-frame] 'hydra--handle-switch-frame)
192 map)
193 "Keymap that all Hydras inherit. See `universal-argument-map'.")
194
195 (defvar hydra-curr-map
196 (make-sparse-keymap)
197 "Keymap of the current Hydra called.")
198
199 (defun hydra--handle-switch-frame (evt)
200 "Quit hydra and call old switch-frame event handler."
201 (interactive "e")
202 (hydra-keyboard-quit)
203 (funcall (lookup-key (current-global-map) [switch-frame]) evt))
204
205 (defun hydra--universal-argument (arg)
206 "Forward to (`universal-argument' ARG)."
207 (interactive "P")
208 (setq prefix-arg (if (consp arg)
209 (list (* 4 (car arg)))
210 (if (eq arg '-)
211 (list -4)
212 '(4))))
213 (hydra-set-transient-map hydra-curr-map t))
214
215 (defun hydra--digit-argument (arg)
216 "Forward to (`digit-argument' ARG)."
217 (interactive "P")
218 (let ((universal-argument-map hydra-curr-map))
219 (digit-argument arg)))
220
221 (defun hydra--negative-argument (arg)
222 "Forward to (`negative-argument' ARG)."
223 (interactive "P")
224 (let ((universal-argument-map hydra-curr-map))
225 (negative-argument arg)))
226 ;;* Repeat
227 (defvar hydra-repeat--prefix-arg nil
228 "Prefix arg to use with `hydra-repeat'.")
229
230 (defvar hydra-repeat--command nil
231 "Command to use with `hydra-repeat'.")
232
233 (defun hydra-repeat ()
234 "Repeat last command with last prefix arg."
235 (interactive)
236 (unless (string-match "hydra-repeat$" (symbol-name last-command))
237 (setq hydra-repeat--command last-command)
238 (setq hydra-repeat--prefix-arg (or last-prefix-arg 1)))
239 (setq current-prefix-arg hydra-repeat--prefix-arg)
240 (funcall hydra-repeat--command))
241
242 ;;* Misc internals
243 (defvar hydra-last nil
244 "The result of the last `hydra-set-transient-map' call.")
245
246 (defun hydra--callablep (x)
247 "Test if X is callable."
248 (or (functionp x)
249 (and (consp x)
250 (memq (car x) '(function quote)))))
251
252 (defun hydra--make-callable (x)
253 "Generate a callable symbol from X.
254 If X is a function symbol or a lambda, return it. Otherwise, it
255 should be a single statement. Wrap it in an interactive lambda."
256 (if (or (symbolp x) (functionp x))
257 x
258 `(lambda ()
259 (interactive)
260 ,x)))
261
262 (defun hydra-plist-get-default (plist prop default)
263 "Extract a value from a property list.
264 PLIST is a property list, which is a list of the form
265 \(PROP1 VALUE1 PROP2 VALUE2...).
266
267 Return the value corresponding to PROP, or DEFAULT if PROP is not
268 one of the properties on the list."
269 (if (memq prop plist)
270 (plist-get plist prop)
271 default))
272
273 (defun hydra--head-property (h prop &optional default)
274 "Return for Hydra head H the value of property PROP.
275 Return DEFAULT if PROP is not in H."
276 (hydra-plist-get-default (cl-cdddr h) prop default))
277
278 (defun hydra--aggregate-color (head-color body-color)
279 "Return the resulting head color for HEAD-COLOR and BODY-COLOR."
280 (cond ((eq head-color 'red)
281 (cl-case body-color
282 (red 'red)
283 (blue 'red)
284 (amaranth 'amaranth)
285 (pink 'pink)
286 (cyan 'amaranth)))
287 ((eq head-color 'blue)
288 (cl-case body-color
289 (red 'blue)
290 (blue 'blue)
291 (amaranth 'teal)
292 (pink 'blue)
293 (cyan 'teal)))
294 (t
295 (error "Can't aggregate head %S to body %S"
296 head-color body-color))))
297
298 (defun hydra--head-color (h body)
299 "Return the color of a Hydra head H with BODY."
300 (let* ((exit (hydra--head-property h :exit 'default))
301 (color (hydra--head-property h :color))
302 (foreign-keys (hydra--body-foreign-keys body))
303 (head-color
304 (cond ((eq exit 'default)
305 (cl-case color
306 (blue 'blue)
307 (red 'red)
308 (t
309 (unless (null color)
310 (error "Use only :blue or :red for heads: %S" h)))))
311 ((null exit)
312 (if color
313 (error "Don't mix :color and :exit - they are aliases: %S" h)
314 (cl-case foreign-keys
315 (run 'pink)
316 (warn 'amaranth)
317 (t 'red))))
318 ((eq exit t)
319 (if color
320 (error "Don't mix :color and :exit - they are aliases: %S" h)
321 'blue))
322 (t
323 (error "Unknown :exit %S" exit)))))
324 (cond ((null (cadr h))
325 (when head-color
326 (hydra--complain
327 "Doubly specified blue head - nil cmd is already blue: %S" h))
328 'blue)
329 ((null head-color)
330 (hydra--body-color body))
331 ((null foreign-keys)
332 head-color)
333 ((eq foreign-keys 'run)
334 (if (eq head-color 'red)
335 'pink
336 'blue))
337 ((eq foreign-keys 'warn)
338 (if (memq head-color '(red amaranth))
339 'amaranth
340 'teal))
341 (t
342 (error "Unexpected %S %S" h body)))))
343
344 (defun hydra--body-foreign-keys (body)
345 "Return what BODY does with a non-head binding."
346 (or
347 (plist-get (cddr body) :foreign-keys)
348 (let ((color (plist-get (cddr body) :color)))
349 (cl-case color
350 ((amaranth teal) 'warn)
351 (pink 'run)))))
352
353 (defun hydra--body-color (body)
354 "Return the color of BODY.
355 BODY is the second argument to `defhydra'"
356 (let ((color (plist-get (cddr body) :color))
357 (exit (plist-get (cddr body) :exit))
358 (foreign-keys (plist-get (cddr body) :foreign-keys)))
359 (cond ((eq foreign-keys 'warn)
360 (if exit 'teal 'amaranth))
361 ((eq foreign-keys 'run) 'pink)
362 (exit 'blue)
363 (color color)
364 (t 'red))))
365
366 (defun hydra--face (h body)
367 "Return the face for a Hydra head H with BODY."
368 (cl-case (hydra--head-color h body)
369 (blue 'hydra-face-blue)
370 (red 'hydra-face-red)
371 (amaranth 'hydra-face-amaranth)
372 (pink 'hydra-face-pink)
373 (teal 'hydra-face-teal)
374 (t (error "Unknown color for %S" h))))
375
376 (defun hydra-cleanup ()
377 "Clean up after a Hydra."
378 (when (window-live-p lv-wnd)
379 (let ((buf (window-buffer lv-wnd)))
380 (delete-window lv-wnd)
381 (kill-buffer buf))))
382
383 (defun hydra-keyboard-quit ()
384 "Quitting function similar to `keyboard-quit'."
385 (interactive)
386 (hydra-disable)
387 (hydra-cleanup)
388 (cancel-timer hydra-timer)
389 (unless hydra-lv
390 (message ""))
391 nil)
392
393 (defun hydra-disable ()
394 "Disable the current Hydra."
395 (cond
396 ;; Emacs 25
397 ((functionp hydra-last)
398 (funcall hydra-last))
399
400 ;; Emacs 24.3 or older
401 ((< emacs-minor-version 4)
402 (setq emulation-mode-map-alists
403 (cl-remove-if
404 (lambda (x)
405 (and (consp x)
406 (consp (car x))
407 (equal (cdar x) hydra-curr-map)))
408 emulation-mode-map-alists)))
409
410 ;; Emacs 24.4.1
411 (t
412 (setq overriding-terminal-local-map nil))))
413
414 (defun hydra--unalias-var (str prefix)
415 "Return the symbol named STR if it's bound as a variable.
416 Otherwise, add PREFIX to the symbol name."
417 (let ((sym (intern-soft str)))
418 (if (boundp sym)
419 sym
420 (intern (concat prefix "/" str)))))
421
422 (defun hydra--hint (body heads)
423 "Generate a hint for the echo area.
424 BODY, and HEADS are parameters to `defhydra'."
425 (let (alist)
426 (dolist (h heads)
427 (let ((val (assoc (cadr h) alist))
428 (pstr (hydra-fontify-head h body)))
429 (unless (null (cl-caddr h))
430 (if val
431 (setf (cadr val)
432 (concat (cadr val) " " pstr))
433 (push
434 (cons (cadr h)
435 (cons pstr (cl-caddr h)))
436 alist)))))
437 (mapconcat
438 (lambda (x)
439 (format
440 (if (> (length (cdr x)) 0)
441 (concat "[%s]: " (cdr x))
442 "%s")
443 (car x)))
444 (nreverse (mapcar #'cdr alist))
445 ", ")))
446
447 (defvar hydra-fontify-head-function nil
448 "Possible replacement for `hydra-fontify-head-default'.")
449
450 (defun hydra-fontify-head-default (head body)
451 "Produce a pretty string from HEAD and BODY.
452 HEAD's binding is returned as a string with a colored face."
453 (propertize (car head) 'face (hydra--face head body)))
454
455 (defun hydra-fontify-head-greyscale (head body)
456 "Produce a pretty string from HEAD and BODY.
457 HEAD's binding is returned as a string wrapped with [] or {}."
458 (let ((color (hydra--head-color head body)))
459 (format
460 (if (eq color 'blue)
461 "[%s]"
462 "{%s}") (car head))))
463
464 (defun hydra-fontify-head (head body)
465 "Produce a pretty string from HEAD and BODY."
466 (funcall (or hydra-fontify-head-function 'hydra-fontify-head-default)
467 head body))
468
469 (defun hydra--format (_name body docstring heads)
470 "Generate a `format' statement from STR.
471 \"%`...\" expressions are extracted into \"%S\".
472 NAME, BODY, DOCSTRING and HEADS are parameters of `defhydra'.
473 The expressions can be auto-expanded according to NAME."
474 (setq docstring (replace-regexp-in-string "\\^" "" docstring))
475 (let ((rest (hydra--hint body heads))
476 (start 0)
477 varlist
478 offset)
479 (while (setq start
480 (string-match
481 "\\(?:%\\( ?-?[0-9]*s?\\)\\(`[a-z-A-Z/0-9]+\\|(\\)\\)\\|\\(?:_\\( ?-?[0-9]*\\)\\([a-z-~A-Z;:0-9/|?<>={}]+\\)_\\)"
482 docstring start))
483 (cond ((eq ?_ (aref (match-string 0 docstring) 0))
484 (let* ((key (match-string 4 docstring))
485 (head (assoc key heads)))
486 (if head
487 (progn
488 (push (hydra-fontify-head head body) varlist)
489 (setq docstring
490 (replace-match
491 (or
492 hydra-key-format-spec
493 (concat "%" (match-string 3 docstring) "s"))
494 nil nil docstring)))
495 (error "Unrecognized key: _%s_" key))))
496
497 (t
498 (let* ((varp (if (eq ?` (aref (match-string 2 docstring) 0)) 1 0))
499 (spec (match-string 1 docstring))
500 (lspec (length spec)))
501 (setq offset
502 (with-temp-buffer
503 (insert (substring docstring (+ 1 start varp
504 (length spec))))
505 (goto-char (point-min))
506 (push (read (current-buffer)) varlist)
507 (- (point) (point-min))))
508 (when (or (zerop lspec)
509 (/= (aref spec (1- (length spec))) ?s))
510 (setq spec (concat spec "S")))
511 (setq docstring
512 (concat
513 (substring docstring 0 start)
514 "%" spec
515 (substring docstring (+ start offset 1 lspec varp))))))))
516 (if (eq ?\n (aref docstring 0))
517 `(concat (format ,(substring docstring 1) ,@(nreverse varlist))
518 ,rest)
519 `(format ,(concat docstring ": " rest ".")))))
520
521 (defun hydra--message (name body docstring heads)
522 "Generate code to display the hint in the preferred echo area.
523 Set `hydra-lv' to choose the echo area.
524 NAME, BODY, DOCSTRING, and HEADS are parameters of `defhydra'."
525 (let ((format-expr (hydra--format name body docstring heads)))
526 `(if hydra-lv
527 (lv-message ,format-expr)
528 (message ,format-expr))))
529
530 (defun hydra--complain (format-string &rest args)
531 "Forward to (`message' FORMAT-STRING ARGS) unless `hydra-verbose' is nil."
532 (when hydra-verbose
533 (apply #'warn format-string args)))
534
535 (defun hydra--doc (body-key body-name heads)
536 "Generate a part of Hydra docstring.
537 BODY-KEY is the body key binding.
538 BODY-NAME is the symbol that identifies the Hydra.
539 HEADS is a list of heads."
540 (format
541 "Create a hydra with %s body and the heads:\n\n%s\n\n%s"
542 (if body-key
543 (format "a \"%s\"" body-key)
544 "no")
545 (mapconcat
546 (lambda (x)
547 (format "\"%s\": `%S'" (car x) (cadr x)))
548 heads ",\n")
549 (format "The body can be accessed via `%S'." body-name)))
550
551 (defun hydra--make-defun (name body doc head
552 keymap body-pre body-post &optional other-post)
553 "Make a defun wrapper, using NAME, BODY, DOC, HEAD, and KEYMAP.
554 NAME and BODY are the arguments to `defhydra'.
555 DOC was generated with `hydra--doc'.
556 HEAD is one of the HEADS passed to `defhydra'.
557 BODY-PRE and BODY-POST are pre-processed in `defhydra'.
558 OTHER-POST is an optional extension to the :post key of BODY."
559 (let ((name (hydra--head-name head name))
560 (cmd (when (car head)
561 (hydra--make-callable
562 (cadr head))))
563 (color (when (car head)
564 (hydra--head-color head body)))
565 (doc (if (car head)
566 (format "%s\n\nCall the head: `%S'." doc (cadr head))
567 doc))
568 (hint (intern (format "%S/hint" name)))
569 (body-color (hydra--body-color body))
570 (body-timeout (plist-get body :timeout)))
571 `(defun ,name ()
572 ,doc
573 (interactive)
574 ,@(when body-pre (list body-pre))
575 (hydra-disable)
576 ,@(when (memq color '(blue teal)) '((hydra-cleanup)))
577 (catch 'hydra-disable
578 ,@(delq nil
579 (if (memq color '(blue teal))
580 `(,(when cmd `(call-interactively #',cmd))
581 ,body-post)
582 `(,(when cmd
583 `(condition-case err
584 (prog1 t
585 (call-interactively #',cmd))
586 ((quit error)
587 (message "%S" err)
588 (unless hydra-lv
589 (sit-for 0.8))
590 nil)))
591 (when hydra-is-helpful
592 (,hint))
593 (setq hydra-last
594 (hydra-set-transient-map
595 (setq hydra-curr-map ',keymap)
596 t
597 ,(if (and
598 (not (memq body-color
599 '(amaranth pink teal)))
600 body-post)
601 `(lambda () (hydra-cleanup) ,body-post)
602 `(lambda () (hydra-cleanup)))))
603 ,(or other-post
604 (when body-timeout
605 (list 'hydra-timeout
606 body-timeout
607 (when body-post
608 (hydra--make-callable body-post))))))))))))
609
610 (defun hydra-pink-fallback ()
611 "On intercepting a non-head, try to run it."
612 (let ((keys (this-command-keys))
613 kb)
614 (when (equal keys [backspace])
615 (setq keys "\7f"))
616 (setq kb (key-binding keys))
617 (if kb
618 (if (commandp kb)
619 (condition-case err
620 (call-interactively kb)
621 ((quit error)
622 (message "%S" err)
623 (unless hydra-lv
624 (sit-for 0.8))))
625 (message "Pink Hydra can't currently handle prefixes, continuing"))
626 (message "Pink Hydra could not resolve: %S" keys))))
627
628 (defun hydra--modify-keymap (keymap def)
629 "In KEYMAP, add DEF to each sub-keymap."
630 (cl-labels
631 ((recur (map)
632 (if (atom map)
633 map
634 (if (eq (car map) 'keymap)
635 (cons 'keymap
636 (cons
637 def
638 (recur (cdr map))))
639 (cons
640 (recur (car map))
641 (recur (cdr map)))))))
642 (recur keymap)))
643
644 (defun hydra--handle-nonhead (keymap name body heads)
645 "Setup KEYMAP for intercepting non-head bindings.
646 NAME, BODY and HEADS are parameters to `defhydra'."
647 (let ((body-color (hydra--body-color body))
648 (body-post (plist-get (cddr body) :post)))
649 (if body-post
650 (when (symbolp body-post)
651 (setq body-post `(funcall #',body-post)))
652 (when hydra-keyboard-quit
653 (define-key keymap hydra-keyboard-quit #'hydra-keyboard-quit)))
654 (when (memq body-color '(amaranth pink teal))
655 (if (cl-some (lambda (h)
656 (memq (hydra--head-color h body) '(blue teal)))
657 heads)
658 (progn
659 (setcdr
660 keymap
661 (cdr
662 (hydra--modify-keymap
663 keymap
664 (cons t
665 `(lambda ()
666 (interactive)
667 ,(cond
668 ((memq body-color '(amaranth teal))
669 '(message "An amaranth Hydra can only exit through a blue head"))
670 (t
671 '(hydra-pink-fallback)))
672 (hydra-set-transient-map hydra-curr-map t)
673 (when hydra-is-helpful
674 (unless hydra-lv
675 (sit-for 0.8))
676 (,(intern (format "%S/hint" name))))))))))
677 (unless (eq body-color 'teal)
678 (error
679 "An %S Hydra must have at least one blue head in order to exit"
680 body-color))))))
681
682 (defun hydra--head-name (h body-name)
683 "Return the symbol for head H of body BODY-NAME."
684 (intern (format "%S/%s" body-name
685 (if (symbolp (cadr h))
686 (cadr h)
687 (concat "lambda-" (car h))))))
688
689 (defun hydra--delete-duplicates (heads)
690 "Return HEADS without entries that have the same CMD part.
691 In duplicate HEADS, :cmd-name is modified to whatever they duplicate."
692 (let ((ali '(((hydra-repeat . red) . hydra-repeat)))
693 res entry)
694 (dolist (h heads)
695 (if (setq entry (assoc (cons (cadr h)
696 (hydra--head-color h '(nil nil)))
697 ali))
698 (setf (cl-cdddr h) (plist-put (cl-cdddr h) :cmd-name (cdr entry)))
699 (push (cons (cons (cadr h)
700 (hydra--head-color h '(nil nil)))
701 (plist-get (cl-cdddr h) :cmd-name))
702 ali)
703 (push h res)))
704 (nreverse res)))
705
706 (defun hydra--pad (lst n)
707 "Pad LST with nil until length N."
708 (let ((len (length lst)))
709 (if (= len n)
710 lst
711 (append lst (make-list (- n len) nil)))))
712
713 (defun hydra--matrix (lst rows cols)
714 "Create a matrix from elements of LST.
715 The matrix size is ROWS times COLS."
716 (let ((ls (copy-sequence lst))
717 res)
718 (dotimes (_c cols)
719 (push (hydra--pad (hydra-multipop ls rows) rows) res))
720 (nreverse res)))
721
722 (defun hydra--cell (fstr names)
723 "Format a rectangular cell based on FSTR and NAMES.
724 FSTR is a format-style string with two string inputs: one for the
725 doc and one for the symbol name.
726 NAMES is a list of variables."
727 (let ((len (cl-reduce
728 (lambda (acc it) (max (length (symbol-name it)) acc))
729 names
730 :initial-value 0)))
731 (mapconcat
732 (lambda (sym)
733 (if sym
734 (format fstr
735 (documentation-property sym 'variable-documentation)
736 (let ((name (symbol-name sym)))
737 (concat name (make-string (- len (length name)) ?^)))
738 sym)
739 ""))
740 names
741 "\n")))
742
743 (defun hydra--vconcat (strs &optional joiner)
744 "Glue STRS vertically. They must be the same height.
745 JOINER is a function similar to `concat'."
746 (setq joiner (or joiner #'concat))
747 (mapconcat
748 (lambda (s)
749 (if (string-match " +$" s)
750 (replace-match "" nil nil s)
751 s))
752 (apply #'cl-mapcar joiner
753 (mapcar
754 (lambda (s) (split-string s "\n"))
755 strs))
756 "\n"))
757
758 (defcustom hydra-cell-format "% -20s %% -8`%s"
759 "The default format for docstring cells."
760 :type 'string)
761
762 (defun hydra--table (names rows cols &optional cell-formats)
763 "Format a `format'-style table from variables in NAMES.
764 The size of the table is ROWS times COLS.
765 CELL-FORMATS are `format' strings for each column.
766 If CELL-FORMATS is a string, it's used for all columns.
767 If CELL-FORMATS is nil, `hydra-cell-format' is used for all columns."
768 (setq cell-formats
769 (cond ((null cell-formats)
770 (make-list cols hydra-cell-format))
771 ((stringp cell-formats)
772 (make-list cols cell-formats))
773 (t
774 cell-formats)))
775 (hydra--vconcat
776 (cl-mapcar
777 #'hydra--cell
778 cell-formats
779 (hydra--matrix names rows cols))
780 (lambda (&rest x)
781 (mapconcat #'identity x " "))))
782
783 (defun hydra-reset-radios (names)
784 "Set varibles NAMES to their defaults.
785 NAMES should be defined by `defhydradio' or similar."
786 (dolist (n names)
787 (set n (aref (get n 'range) 0))))
788
789 (defvar hydra-timer (timer-create)
790 "Timer for `hydra-timeout'.")
791
792 (defun hydra-timeout (secs &optional function)
793 "In SECS seconds call FUNCTION, then `hydra-keyboard-quit'.
794 Cancel the previous `hydra-timeout'."
795 (cancel-timer hydra-timer)
796 (setq hydra-timer (timer-create))
797 (timer-set-time hydra-timer
798 (timer-relative-time (current-time) secs))
799 (timer-set-function
800 hydra-timer
801 `(lambda ()
802 ,(when function
803 `(funcall ,function))
804 (hydra-keyboard-quit)))
805 (timer-activate hydra-timer))
806
807 ;;* Macros
808 ;;** defhydra
809 ;;;###autoload
810 (defmacro defhydra (name body &optional docstring &rest heads)
811 "Create a Hydra - a family of functions with prefix NAME.
812
813 NAME should be a symbol, it will be the prefix of all functions
814 defined here.
815
816 BODY has the format:
817
818 (BODY-MAP BODY-KEY &rest PLIST)
819
820 DOCSTRING will be displayed in the echo area to identify the
821 Hydra.
822
823 Functions are created on basis of HEADS, each of which has the
824 format:
825
826 (KEY CMD &optional HINT &rest PLIST)
827
828 BODY-MAP is a keymap; `global-map' is used quite often. Each
829 function generated from HEADS will be bound in BODY-MAP to
830 BODY-KEY + KEY (both are strings passed to `kbd'), and will set
831 the transient map so that all following heads can be called
832 though KEY only.
833
834 CMD is a callable expression: either an interactive function
835 name, or an interactive lambda, or a single sexp (it will be
836 wrapped in an interactive lambda).
837
838 HINT is a short string that identifies its head. It will be
839 printed beside KEY in the echo erea if `hydra-is-helpful' is not
840 nil. If you don't even want the KEY to be printed, set HINT
841 explicitly to nil.
842
843 The heads inherit their PLIST from the body and are allowed to
844 override each key. The keys recognized are :color and :bind.
845 :color can be:
846
847 - red (default): this head will continue the Hydra state.
848 - blue: this head will stop the Hydra state.
849 - amaranth (applies to body only): similar to red, but no binding
850 except a blue head can stop the Hydra state.
851
852 :bind can be:
853 - nil: this head will not be bound in BODY-MAP.
854 - a lambda taking KEY and CMD used to bind a head
855
856 It is possible to omit both BODY-MAP and BODY-KEY if you don't
857 want to bind anything. In that case, typically you will bind the
858 generated NAME/body command. This command is also the return
859 result of `defhydra'."
860 (declare (indent defun))
861 (cond ((stringp docstring))
862 ((and (consp docstring)
863 (memq (car docstring) '(hydra--table concat format)))
864 (setq docstring (concat "\n" (eval docstring))))
865 (t
866 (setq heads (cons docstring heads))
867 (setq docstring "hydra")))
868 (when (keywordp (car body))
869 (setq body (cons nil (cons nil body))))
870 (let ((keymap (copy-keymap hydra-base-map))
871 (body-name (intern (format "%S/body" name)))
872 (body-key (cadr body))
873 (body-pre (plist-get (cddr body) :pre))
874 (body-body-pre (plist-get (cddr body) :body-pre))
875 (body-post (plist-get (cddr body) :post))
876 (method (or (plist-get body :bind)
877 (car body))))
878 (when body-post
879 (when (symbolp body-post)
880 (setq body-post `(funcall #',body-post)))
881 (setq heads (cons (list hydra-keyboard-quit #'hydra-keyboard-quit nil :exit t)
882 heads)))
883 (dolist (h heads)
884 (let ((len (length h))
885 (cmd-name (hydra--head-name h name)))
886 (cond ((< len 2)
887 (error "Each head should have at least two items: %S" h))
888 ((= len 2)
889 (setcdr (cdr h)
890 (list
891 (hydra-plist-get-default (cddr body) :hint "")
892 :cmd-name cmd-name)))
893 (t
894 (let ((hint (cl-caddr h)))
895 (unless (or (null hint)
896 (stringp hint))
897 (setcdr (cdr h) (cons
898 (hydra-plist-get-default (cddr body) :hint "")
899 (cddr h))))
900 (setcdr (cddr h) `(:cmd-name ,cmd-name ,@(cl-cdddr h))))))))
901 (let ((doc (hydra--doc body-key body-name heads))
902 (heads-nodup (hydra--delete-duplicates heads)))
903 (mapc
904 (lambda (x)
905 (define-key keymap (kbd (car x))
906 (plist-get (cl-cdddr x) :cmd-name)))
907 heads)
908 (when (and body-pre (symbolp body-pre))
909 (setq body-pre `(funcall #',body-pre)))
910 (when (and body-body-pre (symbolp body-body-pre))
911 (setq body-body-pre `(funcall #',body-body-pre)))
912 (hydra--handle-nonhead keymap name body heads)
913 `(progn
914 ,@(mapcar
915 (lambda (head)
916 (hydra--make-defun name body doc head keymap
917 body-pre body-post))
918 heads-nodup)
919 ,@(unless (or (null body-key)
920 (null method)
921 (hydra--callablep method))
922 `((unless (keymapp (lookup-key ,method (kbd ,body-key)))
923 (define-key ,method (kbd ,body-key) nil))))
924 ,@(delq nil
925 (cl-mapcar
926 (lambda (head)
927 (let ((name (hydra--head-property head :cmd-name)))
928 (when (and (cadr head)
929 (not (eq (cadr head) 'hydra-keyboard-quit))
930 (or body-key method))
931 (let ((bind (hydra--head-property head :bind 'default))
932 (final-key
933 (if body-key
934 (vconcat (kbd body-key) (kbd (car head)))
935 (kbd (car head)))))
936 (cond ((null bind) nil)
937
938 ((eq bind 'default)
939 (list
940 (if (hydra--callablep method)
941 'funcall
942 'define-key)
943 method
944 final-key
945 (list 'function name)))
946
947 ((hydra--callablep bind)
948 `(funcall (function ,bind)
949 ,final-key
950 (function ,name)))
951
952 (t
953 (error "Invalid :bind property %S" head)))))))
954 heads))
955 (defun ,(intern (format "%S/hint" name)) ()
956 ,(hydra--message name body docstring heads))
957 ,(hydra--make-defun
958 name body doc '(nil body)
959 keymap
960 (or body-body-pre body-pre) body-post
961 '(setq prefix-arg current-prefix-arg))))))
962
963 (defmacro defhydradio (name _body &rest heads)
964 "Create radios with prefix NAME.
965 BODY specifies the options; there are none currently.
966 HEADS have the format:
967
968 (TOGGLE-NAME &optional VALUE DOC)
969
970 TOGGLE-NAME will be used along with NAME to generate a variable
971 name and a function that cycles it with the same name. VALUE
972 should be an array. The first element of VALUE will be used to
973 inialize the variable.
974 VALUE defaults to [nil t].
975 DOC defaults to TOGGLE-NAME split and capitalized."
976 (declare (indent defun))
977 `(progn
978 ,@(apply #'append
979 (mapcar (lambda (h)
980 (hydra--radio name h))
981 heads))
982 (defvar ,(intern (format "%S/names" name))
983 ',(mapcar (lambda (h) (intern (format "%S/%S" name (car h))))
984 heads))))
985
986 (defmacro hydra-multipop (lst n)
987 "Return LST's first N elements while removing them."
988 `(if (<= (length ,lst) ,n)
989 (prog1 ,lst
990 (setq ,lst nil))
991 (prog1 ,lst
992 (setcdr
993 (nthcdr (1- ,n) (prog1 ,lst (setq ,lst (nthcdr ,n ,lst))))
994 nil))))
995
996 (defun hydra--radio (parent head)
997 "Generate a hydradio with PARENT from HEAD."
998 (let* ((name (car head))
999 (full-name (intern (format "%S/%S" parent name)))
1000 (doc (cadr head))
1001 (val (or (cl-caddr head) [nil t])))
1002 `((defvar ,full-name ,(hydra--quote-maybe (aref val 0)) ,doc)
1003 (put ',full-name 'range ,val)
1004 (defun ,full-name ()
1005 (hydra--cycle-radio ',full-name)))))
1006
1007 (defun hydra--quote-maybe (x)
1008 "Quote X if it's a symbol."
1009 (cond ((null x)
1010 nil)
1011 ((symbolp x)
1012 (list 'quote x))
1013 (t
1014 x)))
1015
1016 (defun hydra--cycle-radio (sym)
1017 "Set SYM to the next value in its range."
1018 (let* ((val (symbol-value sym))
1019 (range (get sym 'range))
1020 (i 0)
1021 (l (length range)))
1022 (setq i (catch 'done
1023 (while (< i l)
1024 (if (equal (aref range i) val)
1025 (throw 'done (1+ i))
1026 (cl-incf i)))
1027 (error "Val not in range for %S" sym)))
1028 (set sym
1029 (aref range
1030 (if (>= i l)
1031 0
1032 i)))))
1033
1034 (provide 'hydra)
1035
1036 ;;; Local Variables:
1037 ;;; outline-regexp: ";;\\*+"
1038 ;;; End:
1039
1040 ;;; hydra.el ends here