1 ;;; hydra.el --- Make bindings that stick around. -*- lexical-binding: t -*-
3 ;; Copyright (C) 2015 Free Software Foundation, Inc.
5 ;; Author: Oleh Krehel <ohwoeowho@gmail.com>
6 ;; Maintainer: Oleh Krehel <ohwoeowho@gmail.com>
7 ;; URL: https://github.com/abo-abo/hydra
10 ;; Package-Requires: ((cl-lib "0.5"))
12 ;; This file is part of GNU Emacs.
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.
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.
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/>.
29 ;; This package can be used to tie related commands into a family of
30 ;; short bindings with a common prefix - a Hydra.
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.
40 ;; Here's an example Hydra, bound in the global map (you can use any
41 ;; keymap in place of `global-map'):
43 ;; (defhydra hydra-zoom (global-map "<f2>")
45 ;; ("g" text-scale-increase "in")
46 ;; ("l" text-scale-decrease "out"))
48 ;; It allows to start a command chain either like this:
49 ;; "<f2> gg4ll5g", or "<f2> lgllg".
51 ;; Here's another approach, when you just want a "callable keymap":
53 ;; (defhydra hydra-toggle (:color blue)
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"))
62 ;; This binds nothing so far, but if you follow up with:
64 ;; (global-set-key (kbd "C-c C-v") 'hydra-toggle/body)
66 ;; you will have bound "C-c C-v a", "C-c C-v d" etc.
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.
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.
82 (defvar hydra-curr-map nil
83 "The keymap of the current Hydra called.")
85 (defvar hydra-curr-on-exit nil
86 "The on-exit predicate for the current Hydra.")
88 (defvar hydra-curr-foreign-keys nil
89 "The current :foreign-keys behavior.")
91 (defun hydra-set-transient-map (keymap on-exit &optional foreign-keys)
92 "Set KEYMAP to the highest priority.
94 Call ON-EXIT when the KEYMAP is deactivated.
96 FOREIGN-KEYS determines the deactivation behavior, when a command
97 that isn't in KEYMAP is called:
99 nil: deactivate KEYMAP and run the command.
100 run: keep KEYMAP and run the command.
101 warn: keep KEYMAP and issue a warning instead of running the command."
102 (setq hydra-curr-map keymap)
103 (setq hydra-curr-on-exit on-exit)
104 (setq hydra-curr-foreign-keys foreign-keys)
105 (add-hook 'pre-command-hook 'hydra--clearfun)
106 (internal-push-keymap keymap 'overriding-terminal-local-map))
108 (defun hydra--clearfun ()
109 "Disable the current Hydra unless `this-command' is a head."
110 (if (memq this-command '(handle-switch-frame
113 (unless (eq this-command
114 (lookup-key hydra-curr-map (this-command-keys-vector)))
115 (unless (cl-case hydra-curr-foreign-keys
117 (setq this-command 'hydra-amaranth-warn))
123 (defun hydra-disable ()
124 "Disable the current Hydra."
125 (remove-hook 'pre-command-hook 'hydra--clearfun)
126 (internal-pop-keymap hydra-curr-map 'overriding-terminal-local-map)
127 (when hydra-curr-on-exit
128 (let ((on-exit hydra-curr-on-exit))
129 (setq hydra-curr-on-exit nil)
132 (unless (fboundp 'internal-push-keymap)
133 (defun internal-push-keymap (keymap symbol)
134 (let ((map (symbol-value symbol)))
135 (unless (memq keymap map)
136 (unless (memq 'add-keymap-witness (symbol-value symbol))
137 (setq map (make-composed-keymap nil (symbol-value symbol)))
138 (push 'add-keymap-witness (cdr map))
140 (push keymap (cdr map))))))
142 (unless (fboundp 'internal-pop-keymap)
143 (defun internal-pop-keymap (keymap symbol)
144 (let ((map (symbol-value symbol)))
145 (when (memq keymap map)
146 (setf (cdr map) (delq keymap (cdr map))))
147 (let ((tail (cddr map)))
148 (and (or (null tail) (keymapp tail))
149 (eq 'add-keymap-witness (nth 1 map))
150 (set symbol tail))))))
152 (defun hydra-amaranth-warn ()
154 (message "An amaranth Hydra can only exit through a blue head"))
158 "Make bindings that stick around."
162 (defcustom hydra-is-helpful t
163 "When t, display a hint with possible bindings in the echo area."
167 (defcustom hydra-lv t
168 "When non-nil, `lv-message' (not `message') will be used to display hints."
171 (defcustom hydra-verbose nil
172 "When non-nil, hydra will issue some non essential style warnings."
175 (defcustom hydra-key-format-spec "%s"
176 "Default `format'-style specifier for _a_ syntax in docstrings.
177 When nil, you can specify your own at each location like this: _ 5a_.")
179 (defface hydra-face-red
180 '((t (:foreground "#FF0000" :bold t)))
181 "Red Hydra heads will persist indefinitely."
184 (defface hydra-face-blue
185 '((t (:foreground "#0000FF" :bold t)))
186 "Blue Hydra heads will vanquish the Hydra.")
188 (defface hydra-face-amaranth
189 '((t (:foreground "#E52B50" :bold t)))
190 "Amaranth body has red heads and warns on intercepting non-heads.
191 Vanquishable only through a blue head.")
193 (defface hydra-face-pink
194 '((t (:foreground "#FF6EB4" :bold t)))
195 "Pink body has red heads and on intercepting non-heads calls them without quitting.
196 Vanquishable only through a blue head.")
198 (defface hydra-face-teal
199 '((t (:foreground "#367588" :bold t)))
200 "Teal body has blue heads an warns on intercepting non-heads.
201 Vanquishable only through a blue head.")
204 (defun hydra-add-font-lock ()
205 "Fontify `defhydra' statements."
206 (font-lock-add-keywords
208 '(("(\\(defhydra\\)\\_> +\\(.*?\\)\\_>"
209 (1 font-lock-keyword-face)
210 (2 font-lock-type-face))
211 ("(\\(defhydradio\\)\\_> +\\(.*?\\)\\_>"
212 (1 font-lock-keyword-face)
213 (2 font-lock-type-face)))))
215 ;;* Universal Argument
216 (defvar hydra-base-map
217 (let ((map (make-sparse-keymap)))
218 (define-key map [?\C-u] 'hydra--universal-argument)
219 (define-key map [?-] 'hydra--negative-argument)
220 (define-key map [?0] 'hydra--digit-argument)
221 (define-key map [?1] 'hydra--digit-argument)
222 (define-key map [?2] 'hydra--digit-argument)
223 (define-key map [?3] 'hydra--digit-argument)
224 (define-key map [?4] 'hydra--digit-argument)
225 (define-key map [?5] 'hydra--digit-argument)
226 (define-key map [?6] 'hydra--digit-argument)
227 (define-key map [?7] 'hydra--digit-argument)
228 (define-key map [?8] 'hydra--digit-argument)
229 (define-key map [?9] 'hydra--digit-argument)
230 (define-key map [kp-0] 'hydra--digit-argument)
231 (define-key map [kp-1] 'hydra--digit-argument)
232 (define-key map [kp-2] 'hydra--digit-argument)
233 (define-key map [kp-3] 'hydra--digit-argument)
234 (define-key map [kp-4] 'hydra--digit-argument)
235 (define-key map [kp-5] 'hydra--digit-argument)
236 (define-key map [kp-6] 'hydra--digit-argument)
237 (define-key map [kp-7] 'hydra--digit-argument)
238 (define-key map [kp-8] 'hydra--digit-argument)
239 (define-key map [kp-9] 'hydra--digit-argument)
240 (define-key map [kp-subtract] 'hydra--negative-argument)
242 "Keymap that all Hydras inherit. See `universal-argument-map'.")
244 (defun hydra--universal-argument (arg)
245 "Forward to (`universal-argument' ARG)."
247 (setq prefix-arg (if (consp arg)
248 (list (* 4 (car arg)))
253 (defun hydra--digit-argument (arg)
254 "Forward to (`digit-argument' ARG)."
256 (let ((universal-argument-map
257 (if (fboundp 'universal-argument--mode)
259 universal-argument-map)))
260 (digit-argument arg)))
262 (defun hydra--negative-argument (arg)
263 "Forward to (`negative-argument' ARG)."
265 (let ((universal-argument-map hydra-curr-map))
266 (negative-argument arg)))
269 (defvar hydra-repeat--prefix-arg nil
270 "Prefix arg to use with `hydra-repeat'.")
272 (defvar hydra-repeat--command nil
273 "Command to use with `hydra-repeat'.")
275 (defun hydra-repeat (&optional arg)
276 "Repeat last command with last prefix arg.
277 When ARG is non-nil, use that instead."
280 (unless (string-match "hydra-repeat$" (symbol-name last-command))
281 (setq hydra-repeat--command last-command)
282 (setq hydra-repeat--prefix-arg last-prefix-arg))
283 (setq hydra-repeat--prefix-arg arg))
284 (setq current-prefix-arg hydra-repeat--prefix-arg)
285 (funcall hydra-repeat--command))
288 (defun hydra--callablep (x)
289 "Test if X is callable."
292 (memq (car x) '(function quote)))))
294 (defun hydra--make-callable (x)
295 "Generate a callable symbol from X.
296 If X is a function symbol or a lambda, return it. Otherwise, it
297 should be a single statement. Wrap it in an interactive lambda."
298 (if (or (symbolp x) (functionp x))
304 (defun hydra-plist-get-default (plist prop default)
305 "Extract a value from a property list.
306 PLIST is a property list, which is a list of the form
307 \(PROP1 VALUE1 PROP2 VALUE2...).
309 Return the value corresponding to PROP, or DEFAULT if PROP is not
310 one of the properties on the list."
311 (if (memq prop plist)
312 (plist-get plist prop)
315 (defun hydra--head-property (h prop &optional default)
316 "Return for Hydra head H the value of property PROP.
317 Return DEFAULT if PROP is not in H."
318 (hydra-plist-get-default (cl-cdddr h) prop default))
320 (defun hydra--head-color (h body)
321 "Return the color of a Hydra head H with BODY."
322 (let* ((head-exit (hydra--head-property h :exit 'default))
323 (foreign-keys (hydra--body-foreign-keys body))
324 (head-color (hydra--head-property h :color))
326 (cond ((eq head-exit 'default)
331 (unless (null head-color)
332 (error "Use only :blue or :red for heads: %S" h)))))
335 (error "Don't mix :color and :exit - they are aliases: %S" h)
336 (cl-case foreign-keys
342 (error "Don't mix :color and :exit - they are aliases: %S" h)
345 (error "Unknown :exit %S" head-exit)))))
346 (cond ((null (cadr h))
349 "Doubly specified blue head - nil cmd is already blue: %S" h))
352 (let ((color (plist-get (cddr body) :color))
353 (exit (plist-get (cddr body) :exit))
354 (foreign-keys (plist-get (cddr body) :foreign-keys)))
355 (cond ((eq foreign-keys 'warn)
356 (if exit 'teal 'amaranth))
357 ((eq foreign-keys 'run) 'pink)
363 ((eq foreign-keys 'run)
364 (if (eq head-color 'red)
367 ((eq foreign-keys 'warn)
368 (if (memq head-color '(red amaranth))
372 (error "Unexpected %S %S" h body)))))
374 (defun hydra--body-foreign-keys (body)
375 "Return what BODY does with a non-head binding."
377 (plist-get (cddr body) :foreign-keys)
378 (let ((color (plist-get (cddr body) :color)))
380 ((amaranth teal) 'warn)
383 (defvar hydra--input-method-function nil
384 "Store overridden `input-method-function' here.")
386 (defun hydra-default-pre ()
387 "Default setup that happens in each head before :pre."
388 (when (eq input-method-function 'key-chord-input-method)
389 (unless hydra--input-method-function
390 (setq hydra--input-method-function input-method-function)
391 (setq input-method-function nil))))
393 (defun hydra-keyboard-quit ()
394 "Quitting function similar to `keyboard-quit'."
397 (cancel-timer hydra-timer)
398 (when hydra--input-method-function
399 (setq input-method-function hydra--input-method-function)
400 (setq hydra--input-method-function nil))
402 (when (window-live-p lv-wnd)
403 (let ((buf (window-buffer lv-wnd)))
404 (delete-window lv-wnd)
409 (defun hydra--hint (body heads)
410 "Generate a hint for the echo area.
411 BODY, and HEADS are parameters to `defhydra'."
414 (let ((val (assoc (cadr h) alist))
415 (pstr (hydra-fontify-head h body)))
416 (unless (null (cl-caddr h))
419 (concat (cadr val) " " pstr))
422 (cons pstr (cl-caddr h)))
427 (if (> (length (cdr x)) 0)
428 (concat "[%s]: " (cdr x))
431 (nreverse (mapcar #'cdr alist))
434 (defvar hydra-fontify-head-function nil
435 "Possible replacement for `hydra-fontify-head-default'.")
437 (defun hydra-fontify-head-default (head body)
438 "Produce a pretty string from HEAD and BODY.
439 HEAD's binding is returned as a string with a colored face."
440 (propertize (car head) 'face
441 (cl-case (hydra--head-color head body)
442 (blue 'hydra-face-blue)
443 (red 'hydra-face-red)
444 (amaranth 'hydra-face-amaranth)
445 (pink 'hydra-face-pink)
446 (teal 'hydra-face-teal)
447 (t (error "Unknown color for %S" head)))))
449 (defun hydra-fontify-head-greyscale (head body)
450 "Produce a pretty string from HEAD and BODY.
451 HEAD's binding is returned as a string wrapped with [] or {}."
452 (let ((color (hydra--head-color head body)))
456 "{%s}") (car head))))
458 (defun hydra-fontify-head (head body)
459 "Produce a pretty string from HEAD and BODY."
460 (funcall (or hydra-fontify-head-function 'hydra-fontify-head-default)
463 (defun hydra--format (_name body docstring heads)
464 "Generate a `format' statement from STR.
465 \"%`...\" expressions are extracted into \"%S\".
466 _NAME, BODY, DOCSTRING and HEADS are parameters of `defhydra'.
467 The expressions can be auto-expanded according to NAME."
468 (setq docstring (replace-regexp-in-string "\\^" "" docstring))
469 (let ((rest (hydra--hint body heads))
475 "\\(?:%\\( ?-?[0-9]*s?\\)\\(`[a-z-A-Z/0-9]+\\|(\\)\\)\\|\\(?:_\\( ?-?[0-9]*\\)\\([a-z-A-Z~.,;:0-9/|?<>={}*+#]+\\)_\\)"
477 (cond ((eq ?_ (aref (match-string 0 docstring) 0))
478 (let* ((key (match-string 4 docstring))
479 (head (assoc key heads)))
482 (push (hydra-fontify-head head body) varlist)
486 hydra-key-format-spec
487 (concat "%" (match-string 3 docstring) "s"))
489 (error "Unrecognized key: _%s_" key))))
492 (let* ((varp (if (eq ?` (aref (match-string 2 docstring) 0)) 1 0))
493 (spec (match-string 1 docstring))
494 (lspec (length spec)))
497 (insert (substring docstring (+ 1 start varp
499 (goto-char (point-min))
500 (push (read (current-buffer)) varlist)
501 (- (point) (point-min))))
502 (when (or (zerop lspec)
503 (/= (aref spec (1- (length spec))) ?s))
504 (setq spec (concat spec "S")))
507 (substring docstring 0 start)
509 (substring docstring (+ start offset 1 lspec varp))))))))
510 (if (eq ?\n (aref docstring 0))
511 `(concat (format ,(substring docstring 1) ,@(nreverse varlist))
513 `(format ,(concat docstring ": " rest ".")))))
515 (defun hydra--complain (format-string &rest args)
516 "Forward to (`message' FORMAT-STRING ARGS) unless `hydra-verbose' is nil."
518 (apply #'warn format-string args)))
520 (defun hydra--doc (body-key body-name heads)
521 "Generate a part of Hydra docstring.
522 BODY-KEY is the body key binding.
523 BODY-NAME is the symbol that identifies the Hydra.
524 HEADS is a list of heads."
526 "Create a hydra with %s body and the heads:\n\n%s\n\n%s"
528 (format "a \"%s\"" body-key)
532 (format "\"%s\": `%S'" (car x) (cadr x)))
534 (format "The body can be accessed via `%S'." body-name)))
536 (defun hydra--make-defun (name body doc head
537 keymap body-pre body-before-exit
538 &optional body-after-exit)
539 "Make a defun wrapper, using NAME, BODY, DOC, HEAD, and KEYMAP.
540 NAME and BODY are the arguments to `defhydra'.
541 DOC was generated with `hydra--doc'.
542 HEAD is one of the HEADS passed to `defhydra'.
543 BODY-PRE is added to the start of the wrapper.
544 BODY-BEFORE-EXIT will be called before the hydra quits.
545 BODY-AFTER-EXIT is added to the end of the wrapper."
546 (let ((name (hydra--head-name head name body))
547 (cmd (when (car head)
548 (hydra--make-callable
550 (color (when (car head)
551 (hydra--head-color head body)))
553 (format "%s\n\nCall the head: `%S'." doc (cadr head))
555 (hint (intern (format "%S/hint" name)))
556 (body-foreign-keys (hydra--body-foreign-keys body))
557 (body-timeout (plist-get body :timeout)))
562 ,@(when body-pre (list body-pre))
563 ,@(if (memq color '(blue teal))
564 `((hydra-keyboard-quit)
567 ,(when cmd `(call-interactively #',cmd))
569 (when cmd `(call-interactively #',cmd))))
574 (call-interactively #',cmd)
579 (when hydra-is-helpful
581 (lv-message (eval ,hint))
582 (message (eval ,hint))))
583 (hydra-set-transient-map
585 (lambda () (hydra-keyboard-quit) ,body-before-exit)
586 ,(when body-foreign-keys
587 (list 'quote body-foreign-keys)))
590 `(hydra-timeout ,body-timeout))))))))
592 (defmacro hydra--make-funcall (sym)
593 "Transform SYM into a `funcall' to call it."
594 `(when (and ,sym (symbolp ,sym))
595 (setq ,sym `(funcall #',,sym))))
597 (defun hydra--head-name (h name body)
598 "Return the symbol for head H of hydra with NAME and BODY."
599 (let ((str (format "%S/%s" name
600 (if (symbolp (cadr h))
602 (concat "lambda-" (car h))))))
603 (when (and (memq (hydra--head-color h body) '(blue teal))
604 (not (memq (cadr h) '(body nil))))
605 (setq str (concat str "-and-exit")))
608 (defun hydra--delete-duplicates (heads)
609 "Return HEADS without entries that have the same CMD part.
610 In duplicate HEADS, :cmd-name is modified to whatever they duplicate."
611 (let ((ali '(((hydra-repeat . red) . hydra-repeat)))
614 (if (setq entry (assoc (cons (cadr h)
615 (hydra--head-color h '(nil nil)))
617 (setf (cl-cdddr h) (plist-put (cl-cdddr h) :cmd-name (cdr entry)))
618 (push (cons (cons (cadr h)
619 (hydra--head-color h '(nil nil)))
620 (plist-get (cl-cdddr h) :cmd-name))
625 (defun hydra--pad (lst n)
626 "Pad LST with nil until length N."
627 (let ((len (length lst)))
630 (append lst (make-list (- n len) nil)))))
632 (defun hydra--matrix (lst rows cols)
633 "Create a matrix from elements of LST.
634 The matrix size is ROWS times COLS."
635 (let ((ls (copy-sequence lst))
638 (push (hydra--pad (hydra-multipop ls rows) rows) res))
641 (defun hydra--cell (fstr names)
642 "Format a rectangular cell based on FSTR and NAMES.
643 FSTR is a format-style string with two string inputs: one for the
644 doc and one for the symbol name.
645 NAMES is a list of variables."
646 (let ((len (cl-reduce
647 (lambda (acc it) (max (length (symbol-name it)) acc))
654 (documentation-property sym 'variable-documentation)
655 (let ((name (symbol-name sym)))
656 (concat name (make-string (- len (length name)) ?^)))
662 (defun hydra--vconcat (strs &optional joiner)
663 "Glue STRS vertically. They must be the same height.
664 JOINER is a function similar to `concat'."
665 (setq joiner (or joiner #'concat))
668 (if (string-match " +$" s)
669 (replace-match "" nil nil s)
671 (apply #'cl-mapcar joiner
673 (lambda (s) (split-string s "\n"))
677 (defcustom hydra-cell-format "% -20s %% -8`%s"
678 "The default format for docstring cells."
681 (defun hydra--table (names rows cols &optional cell-formats)
682 "Format a `format'-style table from variables in NAMES.
683 The size of the table is ROWS times COLS.
684 CELL-FORMATS are `format' strings for each column.
685 If CELL-FORMATS is a string, it's used for all columns.
686 If CELL-FORMATS is nil, `hydra-cell-format' is used for all columns."
688 (cond ((null cell-formats)
689 (make-list cols hydra-cell-format))
690 ((stringp cell-formats)
691 (make-list cols cell-formats))
698 (hydra--matrix names rows cols))
700 (mapconcat #'identity x " "))))
702 (defun hydra-reset-radios (names)
703 "Set varibles NAMES to their defaults.
704 NAMES should be defined by `defhydradio' or similar."
706 (set n (aref (get n 'range) 0))))
708 (defvar hydra-timer (timer-create)
709 "Timer for `hydra-timeout'.")
711 (defun hydra-timeout (secs &optional function)
712 "In SECS seconds call FUNCTION, then function `hydra-keyboard-quit'.
713 Cancel the previous `hydra-timeout'."
714 (cancel-timer hydra-timer)
715 (setq hydra-timer (timer-create))
716 (timer-set-time hydra-timer
717 (timer-relative-time (current-time) secs))
722 `(funcall ,function))
723 (hydra-keyboard-quit)))
724 (timer-activate hydra-timer))
728 (defmacro defhydra (name body &optional docstring &rest heads)
729 "Create a Hydra - a family of functions with prefix NAME.
731 NAME should be a symbol, it will be the prefix of all functions
736 (BODY-MAP BODY-KEY &rest BODY-PLIST)
738 DOCSTRING will be displayed in the echo area to identify the
739 Hydra. When DOCSTRING starts with a newline, special Ruby-style
740 substitution will be performed by `hydra--format'.
742 Functions are created on basis of HEADS, each of which has the
745 (KEY CMD &optional HINT &rest PLIST)
747 BODY-MAP is a keymap; `global-map' is used quite often. Each
748 function generated from HEADS will be bound in BODY-MAP to
749 BODY-KEY + KEY (both are strings passed to `kbd'), and will set
750 the transient map so that all following heads can be called
751 though KEY only. BODY-KEY can be an empty string.
753 CMD is a callable expression: either an interactive function
754 name, or an interactive lambda, or a single sexp (it will be
755 wrapped in an interactive lambda).
757 HINT is a short string that identifies its head. It will be
758 printed beside KEY in the echo erea if `hydra-is-helpful' is not
759 nil. If you don't even want the KEY to be printed, set HINT
762 The heads inherit their PLIST from BODY-PLIST and are allowed to
763 override some keys. The keys recognized are :exit and :bind.
766 - nil (default): this head will continue the Hydra state.
767 - t: this head will stop the Hydra state.
770 - nil: this head will not be bound in BODY-MAP.
771 - a lambda taking KEY and CMD used to bind a head.
773 It is possible to omit both BODY-MAP and BODY-KEY if you don't
774 want to bind anything. In that case, typically you will bind the
775 generated NAME/body command. This command is also the return
776 result of `defhydra'."
777 (declare (indent defun))
778 (cond ((stringp docstring))
779 ((and (consp docstring)
780 (memq (car docstring) '(hydra--table concat format)))
781 (setq docstring (concat "\n" (eval docstring))))
783 (setq heads (cons docstring heads))
784 (setq docstring "hydra")))
785 (when (keywordp (car body))
786 (setq body (cons nil (cons nil body))))
788 (let* ((keymap (copy-keymap hydra-base-map))
789 (keymap-name (intern (format "%S/keymap" name)))
790 (body-name (intern (format "%S/body" name)))
791 (body-key (cadr body))
792 (body-plist (cddr body))
793 (body-map (or (car body)
794 (plist-get body-plist :bind)))
795 (body-pre (plist-get body-plist :pre))
796 (body-body-pre (plist-get body-plist :body-pre))
797 (body-before-exit (or (plist-get body-plist :post)
798 (plist-get body-plist :before-exit)))
799 (body-after-exit (plist-get body-plist :after-exit))
800 (body-inherit (plist-get body-plist :inherit))
801 (body-foreign-keys (hydra--body-foreign-keys body)))
802 (hydra--make-funcall body-before-exit)
803 (hydra--make-funcall body-after-exit)
804 (dolist (base body-inherit)
805 (setq heads (append heads (eval base))))
807 (let ((len (length h)))
809 (error "Each head should have at least two items: %S" h))
813 (hydra-plist-get-default body-plist :hint "")))
815 (list :cmd-name (hydra--head-name h name body))))
817 (let ((hint (cl-caddr h)))
818 (unless (or (null hint)
820 (setcdr (cdr h) (cons
821 (hydra-plist-get-default body-plist :hint "")
823 (let ((hint-and-plist (cddr h)))
824 (if (null (cdr hint-and-plist))
825 (setcdr hint-and-plist
827 (hydra--head-name h name body)))
828 (plist-put (cdr hint-and-plist)
830 (hydra--head-name h name body)))))))))
831 (let ((doc (hydra--doc body-key body-name heads))
832 (heads-nodup (hydra--delete-duplicates heads)))
835 (define-key keymap (kbd (car x))
836 (plist-get (cl-cdddr x) :cmd-name)))
838 (hydra--make-funcall body-pre)
839 (hydra--make-funcall body-body-pre)
840 (when (memq body-foreign-keys '(run warn))
843 (memq (hydra--head-color h body) '(blue teal)))
846 "An %S Hydra must have at least one blue head in order to exit"
850 (set (defvar ,keymap-name
852 ,(format "Keymap for %S." name))
855 ;; (set (defvar ,(intern (format "%S/heads" name))
857 ;; ,(format "Heads for %S." name))
858 ;; ',(mapcar (lambda (h)
859 ;; (let ((j (copy-sequence h)))
860 ;; (cl-remf (cl-cdddr j) :cmd-name)
866 (hydra--make-defun name body doc head keymap-name
871 ;; free up keymap prefix
872 ,@(unless (or (null body-key)
874 (hydra--callablep body-map))
875 `((unless (keymapp (lookup-key ,body-map (kbd ,body-key)))
876 (define-key ,body-map (kbd ,body-key) nil))))
881 (let ((name (hydra--head-property head :cmd-name)))
882 (when (and (cadr head)
883 (or body-key body-map))
884 (let ((bind (hydra--head-property head :bind body-map))
887 (vconcat (kbd body-key) (kbd (car head)))
889 (cond ((null bind) nil)
890 ((hydra--callablep bind)
891 `(funcall ,bind ,final-key (function ,name)))
894 (keymapp (symbol-value bind))
896 `(define-key ,bind ,final-key (function ,name)))
898 (error "Invalid :bind property `%S' for head %S" bind head)))))))
901 (defvar ,(intern (format "%S/hint" name)) nil
902 ,(format "Dynamic hint for %S." name))
903 ',(hydra--format name body docstring heads))
905 name body doc '(nil body)
907 (or body-body-pre body-pre) body-before-exit
908 '(setq prefix-arg current-prefix-arg)))))
910 (message "Error in defhydra %S: %s" name (cdr err))
913 (defmacro defhydradio (name _body &rest heads)
914 "Create radios with prefix NAME.
915 _BODY specifies the options; there are none currently.
916 HEADS have the format:
918 (TOGGLE-NAME &optional VALUE DOC)
920 TOGGLE-NAME will be used along with NAME to generate a variable
921 name and a function that cycles it with the same name. VALUE
922 should be an array. The first element of VALUE will be used to
923 inialize the variable.
924 VALUE defaults to [nil t].
925 DOC defaults to TOGGLE-NAME split and capitalized."
926 (declare (indent defun))
930 (hydra--radio name h))
932 (defvar ,(intern (format "%S/names" name))
933 ',(mapcar (lambda (h) (intern (format "%S/%S" name (car h))))
936 (defmacro hydra-multipop (lst n)
937 "Return LST's first N elements while removing them."
938 `(if (<= (length ,lst) ,n)
943 (nthcdr (1- ,n) (prog1 ,lst (setq ,lst (nthcdr ,n ,lst))))
946 (defun hydra--radio (parent head)
947 "Generate a hydradio with PARENT from HEAD."
948 (let* ((name (car head))
949 (full-name (intern (format "%S/%S" parent name)))
951 (val (or (cl-caddr head) [nil t])))
952 `((defvar ,full-name ,(hydra--quote-maybe (aref val 0)) ,doc)
953 (put ',full-name 'range ,val)
955 (hydra--cycle-radio ',full-name)))))
957 (defun hydra--quote-maybe (x)
958 "Quote X if it's a symbol."
966 (defun hydra--cycle-radio (sym)
967 "Set SYM to the next value in its range."
968 (let* ((val (symbol-value sym))
969 (range (get sym 'range))
974 (if (equal (aref range i) val)
977 (error "Val not in range for %S" sym)))
987 ;;; outline-regexp: ";;\\*+"
990 ;;; hydra.el ends here