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 (eq this-command 'handle-switch-frame)
112 (unless (eq this-command
113 (lookup-key hydra-curr-map (this-command-keys-vector)))
114 (unless (cl-case hydra-curr-foreign-keys
116 (setq this-command 'hydra-amaranth-warn))
122 (defun hydra-disable ()
123 "Disable the current Hydra."
124 (remove-hook 'pre-command-hook 'hydra--clearfun)
125 (internal-pop-keymap hydra-curr-map 'overriding-terminal-local-map)
126 (when hydra-curr-on-exit
127 (let ((on-exit hydra-curr-on-exit))
128 (setq hydra-curr-on-exit nil)
131 (unless (fboundp 'internal-push-keymap)
132 (defun internal-push-keymap (keymap symbol)
133 (let ((map (symbol-value symbol)))
134 (unless (memq keymap map)
135 (unless (memq 'add-keymap-witness (symbol-value symbol))
136 (setq map (make-composed-keymap nil (symbol-value symbol)))
137 (push 'add-keymap-witness (cdr map))
139 (push keymap (cdr map))))))
141 (unless (fboundp 'internal-pop-keymap)
142 (defun internal-pop-keymap (keymap symbol)
143 (let ((map (symbol-value symbol)))
144 (when (memq keymap map)
145 (setf (cdr map) (delq keymap (cdr map))))
146 (let ((tail (cddr map)))
147 (and (or (null tail) (keymapp tail))
148 (eq 'add-keymap-witness (nth 1 map))
149 (set symbol tail))))))
151 (defun hydra-amaranth-warn ()
153 (message "An amaranth Hydra can only exit through a blue head"))
157 "Make bindings that stick around."
161 (defcustom hydra-is-helpful t
162 "When t, display a hint with possible bindings in the echo area."
166 (defcustom hydra-keyboard-quit "
\a"
167 "This binding will quit an amaranth Hydra.
168 It's the only other way to quit it besides though a blue head.
169 It's possible to set this to nil.")
171 (defcustom hydra-lv t
172 "When non-nil, `lv-message' (not `message') will be used to display hints."
175 (defcustom hydra-verbose nil
176 "When non-nil, hydra will issue some non essential style warnings."
179 (defcustom hydra-key-format-spec "%s"
180 "Default `format'-style specifier for _a_ syntax in docstrings.
181 When nil, you can specify your own at each location like this: _ 5a_.")
183 (defface hydra-face-red
184 '((t (:foreground "#FF0000" :bold t)))
185 "Red Hydra heads will persist indefinitely."
188 (defface hydra-face-blue
189 '((t (:foreground "#0000FF" :bold t)))
190 "Blue Hydra heads will vanquish the Hydra.")
192 (defface hydra-face-amaranth
193 '((t (:foreground "#E52B50" :bold t)))
194 "Amaranth body has red heads and warns on intercepting non-heads.
195 Vanquishable only through a blue head.")
197 (defface hydra-face-pink
198 '((t (:foreground "#FF6EB4" :bold t)))
199 "Pink body has red heads and on intercepting non-heads calls them without quitting.
200 Vanquishable only through a blue head.")
202 (defface hydra-face-teal
203 '((t (:foreground "#367588" :bold t)))
204 "Teal body has blue heads an warns on intercepting non-heads.
205 Vanquishable only through a blue head.")
208 (defun hydra-add-font-lock ()
209 "Fontify `defhydra' statements."
210 (font-lock-add-keywords
212 '(("(\\(defhydra\\)\\_> +\\(.*?\\)\\_>"
213 (1 font-lock-keyword-face)
214 (2 font-lock-type-face))
215 ("(\\(defhydradio\\)\\_> +\\(.*?\\)\\_>"
216 (1 font-lock-keyword-face)
217 (2 font-lock-type-face)))))
219 ;;* Universal Argument
220 (defvar hydra-base-map
221 (let ((map (make-sparse-keymap)))
222 (define-key map [?\C-u] 'hydra--universal-argument)
223 (define-key map [?-] 'hydra--negative-argument)
224 (define-key map [?0] 'hydra--digit-argument)
225 (define-key map [?1] 'hydra--digit-argument)
226 (define-key map [?2] 'hydra--digit-argument)
227 (define-key map [?3] 'hydra--digit-argument)
228 (define-key map [?4] 'hydra--digit-argument)
229 (define-key map [?5] 'hydra--digit-argument)
230 (define-key map [?6] 'hydra--digit-argument)
231 (define-key map [?7] 'hydra--digit-argument)
232 (define-key map [?8] 'hydra--digit-argument)
233 (define-key map [?9] 'hydra--digit-argument)
234 (define-key map [kp-0] 'hydra--digit-argument)
235 (define-key map [kp-1] 'hydra--digit-argument)
236 (define-key map [kp-2] 'hydra--digit-argument)
237 (define-key map [kp-3] 'hydra--digit-argument)
238 (define-key map [kp-4] 'hydra--digit-argument)
239 (define-key map [kp-5] 'hydra--digit-argument)
240 (define-key map [kp-6] 'hydra--digit-argument)
241 (define-key map [kp-7] 'hydra--digit-argument)
242 (define-key map [kp-8] 'hydra--digit-argument)
243 (define-key map [kp-9] 'hydra--digit-argument)
244 (define-key map [kp-subtract] 'hydra--negative-argument)
246 "Keymap that all Hydras inherit. See `universal-argument-map'.")
248 (defun hydra--universal-argument (arg)
249 "Forward to (`universal-argument' ARG)."
251 (setq prefix-arg (if (consp arg)
252 (list (* 4 (car arg)))
257 (defun hydra--digit-argument (arg)
258 "Forward to (`digit-argument' ARG)."
260 (let ((universal-argument-map
261 (if (fboundp 'universal-argument--mode)
263 universal-argument-map)))
264 (digit-argument arg)))
266 (defun hydra--negative-argument (arg)
267 "Forward to (`negative-argument' ARG)."
269 (let ((universal-argument-map hydra-curr-map))
270 (negative-argument arg)))
273 (defvar hydra-repeat--prefix-arg nil
274 "Prefix arg to use with `hydra-repeat'.")
276 (defvar hydra-repeat--command nil
277 "Command to use with `hydra-repeat'.")
279 (defun hydra-repeat (&optional arg)
280 "Repeat last command with last prefix arg.
281 When ARG is non-nil, use that instead."
284 (unless (string-match "hydra-repeat$" (symbol-name last-command))
285 (setq hydra-repeat--command last-command)
286 (setq hydra-repeat--prefix-arg last-prefix-arg))
287 (setq hydra-repeat--prefix-arg arg))
288 (setq current-prefix-arg hydra-repeat--prefix-arg)
289 (funcall hydra-repeat--command))
292 (defun hydra--callablep (x)
293 "Test if X is callable."
296 (memq (car x) '(function quote)))))
298 (defun hydra--make-callable (x)
299 "Generate a callable symbol from X.
300 If X is a function symbol or a lambda, return it. Otherwise, it
301 should be a single statement. Wrap it in an interactive lambda."
302 (if (or (symbolp x) (functionp x))
308 (defun hydra-plist-get-default (plist prop default)
309 "Extract a value from a property list.
310 PLIST is a property list, which is a list of the form
311 \(PROP1 VALUE1 PROP2 VALUE2...).
313 Return the value corresponding to PROP, or DEFAULT if PROP is not
314 one of the properties on the list."
315 (if (memq prop plist)
316 (plist-get plist prop)
319 (defun hydra--head-property (h prop &optional default)
320 "Return for Hydra head H the value of property PROP.
321 Return DEFAULT if PROP is not in H."
322 (hydra-plist-get-default (cl-cdddr h) prop default))
324 (defun hydra--head-color (h body)
325 "Return the color of a Hydra head H with BODY."
326 (let* ((exit (hydra--head-property h :exit 'default))
327 (color (hydra--head-property h :color))
328 (foreign-keys (hydra--body-foreign-keys body))
330 (cond ((eq exit 'default)
336 (error "Use only :blue or :red for heads: %S" h)))))
339 (error "Don't mix :color and :exit - they are aliases: %S" h)
340 (cl-case foreign-keys
346 (error "Don't mix :color and :exit - they are aliases: %S" h)
349 (error "Unknown :exit %S" exit)))))
350 (cond ((null (cadr h))
353 "Doubly specified blue head - nil cmd is already blue: %S" h))
356 (hydra--body-color body))
359 ((eq foreign-keys 'run)
360 (if (eq head-color 'red)
363 ((eq foreign-keys 'warn)
364 (if (memq head-color '(red amaranth))
368 (error "Unexpected %S %S" h body)))))
370 (defun hydra--body-foreign-keys (body)
371 "Return what BODY does with a non-head binding."
373 (plist-get (cddr body) :foreign-keys)
374 (let ((color (plist-get (cddr body) :color)))
376 ((amaranth teal) 'warn)
379 (defun hydra--body-color (body)
380 "Return the color of BODY.
381 BODY is the second argument to `defhydra'"
382 (let ((color (plist-get (cddr body) :color))
383 (exit (plist-get (cddr body) :exit))
384 (foreign-keys (plist-get (cddr body) :foreign-keys)))
385 (cond ((eq foreign-keys 'warn)
386 (if exit 'teal 'amaranth))
387 ((eq foreign-keys 'run) 'pink)
392 (defun hydra--face (h body)
393 "Return the face for a Hydra head H with BODY."
394 (cl-case (hydra--head-color h body)
395 (blue 'hydra-face-blue)
396 (red 'hydra-face-red)
397 (amaranth 'hydra-face-amaranth)
398 (pink 'hydra-face-pink)
399 (teal 'hydra-face-teal)
400 (t (error "Unknown color for %S" h))))
402 (defvar hydra--input-method-function nil
403 "Store overridden `input-method-function' here.")
405 (defun hydra-default-pre ()
406 "Default setup that happens in each head before :pre."
407 (when (eq input-method-function 'key-chord-input-method)
408 (unless hydra--input-method-function
409 (setq hydra--input-method-function input-method-function)
410 (setq input-method-function nil))))
412 (defun hydra-keyboard-quit ()
413 "Quitting function similar to `keyboard-quit'."
416 (cancel-timer hydra-timer)
417 (when hydra--input-method-function
418 (setq input-method-function hydra--input-method-function)
419 (setq hydra--input-method-function nil))
421 (when (window-live-p lv-wnd)
422 (let ((buf (window-buffer lv-wnd)))
423 (delete-window lv-wnd)
428 (defun hydra--hint (body heads)
429 "Generate a hint for the echo area.
430 BODY, and HEADS are parameters to `defhydra'."
433 (let ((val (assoc (cadr h) alist))
434 (pstr (hydra-fontify-head h body)))
435 (unless (null (cl-caddr h))
438 (concat (cadr val) " " pstr))
441 (cons pstr (cl-caddr h)))
446 (if (> (length (cdr x)) 0)
447 (concat "[%s]: " (cdr x))
450 (nreverse (mapcar #'cdr alist))
453 (defvar hydra-fontify-head-function nil
454 "Possible replacement for `hydra-fontify-head-default'.")
456 (defun hydra-fontify-head-default (head body)
457 "Produce a pretty string from HEAD and BODY.
458 HEAD's binding is returned as a string with a colored face."
459 (propertize (car head) 'face (hydra--face head body)))
461 (defun hydra-fontify-head-greyscale (head body)
462 "Produce a pretty string from HEAD and BODY.
463 HEAD's binding is returned as a string wrapped with [] or {}."
464 (let ((color (hydra--head-color head body)))
468 "{%s}") (car head))))
470 (defun hydra-fontify-head (head body)
471 "Produce a pretty string from HEAD and BODY."
472 (funcall (or hydra-fontify-head-function 'hydra-fontify-head-default)
475 (defun hydra--format (_name body docstring heads)
476 "Generate a `format' statement from STR.
477 \"%`...\" expressions are extracted into \"%S\".
478 _NAME, BODY, DOCSTRING and HEADS are parameters of `defhydra'.
479 The expressions can be auto-expanded according to NAME."
480 (setq docstring (replace-regexp-in-string "\\^" "" docstring))
481 (let ((rest (hydra--hint body heads))
487 "\\(?:%\\( ?-?[0-9]*s?\\)\\(`[a-z-A-Z/0-9]+\\|(\\)\\)\\|\\(?:_\\( ?-?[0-9]*\\)\\([a-z-A-Z~.,;:0-9/|?<>={}*+#]+\\)_\\)"
489 (cond ((eq ?_ (aref (match-string 0 docstring) 0))
490 (let* ((key (match-string 4 docstring))
491 (head (assoc key heads)))
494 (push (hydra-fontify-head head body) varlist)
498 hydra-key-format-spec
499 (concat "%" (match-string 3 docstring) "s"))
501 (error "Unrecognized key: _%s_" key))))
504 (let* ((varp (if (eq ?` (aref (match-string 2 docstring) 0)) 1 0))
505 (spec (match-string 1 docstring))
506 (lspec (length spec)))
509 (insert (substring docstring (+ 1 start varp
511 (goto-char (point-min))
512 (push (read (current-buffer)) varlist)
513 (- (point) (point-min))))
514 (when (or (zerop lspec)
515 (/= (aref spec (1- (length spec))) ?s))
516 (setq spec (concat spec "S")))
519 (substring docstring 0 start)
521 (substring docstring (+ start offset 1 lspec varp))))))))
522 (if (eq ?\n (aref docstring 0))
523 `(concat (format ,(substring docstring 1) ,@(nreverse varlist))
525 `(format ,(concat docstring ": " rest ".")))))
527 (defun hydra--message (name body docstring heads)
528 "Generate code to display the hint in the preferred echo area.
529 Set `hydra-lv' to choose the echo area.
530 NAME, BODY, DOCSTRING, and HEADS are parameters of `defhydra'."
531 (let ((format-expr (hydra--format name body docstring heads)))
533 (lv-message ,format-expr)
534 (message ,format-expr))))
536 (defun hydra--complain (format-string &rest args)
537 "Forward to (`message' FORMAT-STRING ARGS) unless `hydra-verbose' is nil."
539 (apply #'warn format-string args)))
541 (defun hydra--doc (body-key body-name heads)
542 "Generate a part of Hydra docstring.
543 BODY-KEY is the body key binding.
544 BODY-NAME is the symbol that identifies the Hydra.
545 HEADS is a list of heads."
547 "Create a hydra with %s body and the heads:\n\n%s\n\n%s"
549 (format "a \"%s\"" body-key)
553 (format "\"%s\": `%S'" (car x) (cadr x)))
555 (format "The body can be accessed via `%S'." body-name)))
557 (defun hydra--make-defun (name body doc head
558 keymap body-pre body-post &optional other-post)
559 "Make a defun wrapper, using NAME, BODY, DOC, HEAD, and KEYMAP.
560 NAME and BODY are the arguments to `defhydra'.
561 DOC was generated with `hydra--doc'.
562 HEAD is one of the HEADS passed to `defhydra'.
563 BODY-PRE and BODY-POST are pre-processed in `defhydra'.
564 OTHER-POST is an optional extension to the :post key of BODY."
565 (let ((name (hydra--head-name head name body))
566 (cmd (when (car head)
567 (hydra--make-callable
569 (color (when (car head)
570 (hydra--head-color head body)))
572 (format "%s\n\nCall the head: `%S'." doc (cadr head))
574 (hint (intern (format "%S/hint" name)))
575 (body-color (hydra--body-color body))
576 (body-timeout (plist-get body :timeout)))
581 ,@(when body-pre (list body-pre))
582 ,@(if (memq color '(blue teal))
583 `((hydra-keyboard-quit)
584 ,(when cmd `(call-interactively #',cmd))
590 (call-interactively #',cmd)
595 (when hydra-is-helpful
597 (hydra-set-transient-map
599 (lambda () (hydra-keyboard-quit) ,body-post)
601 ((memq body-color '(amaranth teal))
603 ((eq body-color 'pink)
612 (hydra--make-callable body-post)))))))))))
614 (defmacro hydra--make-funcall (sym)
615 "Transform SYM into a `funcall' that calls it."
616 `(when (and ,sym (symbolp ,sym))
617 (setq ,sym `(funcall #',,sym))))
619 (defun hydra--head-name (h name body)
620 "Return the symbol for head H of hydra with NAME and BODY."
621 (let ((str (format "%S/%s" name
622 (if (symbolp (cadr h))
624 (concat "lambda-" (car h))))))
625 (when (and (memq (hydra--head-color h body) '(blue teal))
626 (not (memq (cadr h) '(body nil))))
627 (setq str (concat str "-and-exit")))
630 (defun hydra--delete-duplicates (heads)
631 "Return HEADS without entries that have the same CMD part.
632 In duplicate HEADS, :cmd-name is modified to whatever they duplicate."
633 (let ((ali '(((hydra-repeat . red) . hydra-repeat)))
636 (if (setq entry (assoc (cons (cadr h)
637 (hydra--head-color h '(nil nil)))
639 (setf (cl-cdddr h) (plist-put (cl-cdddr h) :cmd-name (cdr entry)))
640 (push (cons (cons (cadr h)
641 (hydra--head-color h '(nil nil)))
642 (plist-get (cl-cdddr h) :cmd-name))
647 (defun hydra--pad (lst n)
648 "Pad LST with nil until length N."
649 (let ((len (length lst)))
652 (append lst (make-list (- n len) nil)))))
654 (defun hydra--matrix (lst rows cols)
655 "Create a matrix from elements of LST.
656 The matrix size is ROWS times COLS."
657 (let ((ls (copy-sequence lst))
660 (push (hydra--pad (hydra-multipop ls rows) rows) res))
663 (defun hydra--cell (fstr names)
664 "Format a rectangular cell based on FSTR and NAMES.
665 FSTR is a format-style string with two string inputs: one for the
666 doc and one for the symbol name.
667 NAMES is a list of variables."
668 (let ((len (cl-reduce
669 (lambda (acc it) (max (length (symbol-name it)) acc))
676 (documentation-property sym 'variable-documentation)
677 (let ((name (symbol-name sym)))
678 (concat name (make-string (- len (length name)) ?^)))
684 (defun hydra--vconcat (strs &optional joiner)
685 "Glue STRS vertically. They must be the same height.
686 JOINER is a function similar to `concat'."
687 (setq joiner (or joiner #'concat))
690 (if (string-match " +$" s)
691 (replace-match "" nil nil s)
693 (apply #'cl-mapcar joiner
695 (lambda (s) (split-string s "\n"))
699 (defcustom hydra-cell-format "% -20s %% -8`%s"
700 "The default format for docstring cells."
703 (defun hydra--table (names rows cols &optional cell-formats)
704 "Format a `format'-style table from variables in NAMES.
705 The size of the table is ROWS times COLS.
706 CELL-FORMATS are `format' strings for each column.
707 If CELL-FORMATS is a string, it's used for all columns.
708 If CELL-FORMATS is nil, `hydra-cell-format' is used for all columns."
710 (cond ((null cell-formats)
711 (make-list cols hydra-cell-format))
712 ((stringp cell-formats)
713 (make-list cols cell-formats))
720 (hydra--matrix names rows cols))
722 (mapconcat #'identity x " "))))
724 (defun hydra-reset-radios (names)
725 "Set varibles NAMES to their defaults.
726 NAMES should be defined by `defhydradio' or similar."
728 (set n (aref (get n 'range) 0))))
730 (defvar hydra-timer (timer-create)
731 "Timer for `hydra-timeout'.")
733 (defun hydra-timeout (secs &optional function)
734 "In SECS seconds call FUNCTION, then function `hydra-keyboard-quit'.
735 Cancel the previous `hydra-timeout'."
736 (cancel-timer hydra-timer)
737 (setq hydra-timer (timer-create))
738 (timer-set-time hydra-timer
739 (timer-relative-time (current-time) secs))
744 `(funcall ,function))
745 (hydra-keyboard-quit)))
746 (timer-activate hydra-timer))
750 (defmacro defhydra (name body &optional docstring &rest heads)
751 "Create a Hydra - a family of functions with prefix NAME.
753 NAME should be a symbol, it will be the prefix of all functions
758 (BODY-MAP BODY-KEY &rest BODY-PLIST)
760 DOCSTRING will be displayed in the echo area to identify the
761 Hydra. When DOCSTRING starts with a newline, special Ruby-style
762 substitution will be performed by `hydra--format'.
764 Functions are created on basis of HEADS, each of which has the
767 (KEY CMD &optional HINT &rest PLIST)
769 BODY-MAP is a keymap; `global-map' is used quite often. Each
770 function generated from HEADS will be bound in BODY-MAP to
771 BODY-KEY + KEY (both are strings passed to `kbd'), and will set
772 the transient map so that all following heads can be called
773 though KEY only. BODY-KEY can be an empty string.
775 CMD is a callable expression: either an interactive function
776 name, or an interactive lambda, or a single sexp (it will be
777 wrapped in an interactive lambda).
779 HINT is a short string that identifies its head. It will be
780 printed beside KEY in the echo erea if `hydra-is-helpful' is not
781 nil. If you don't even want the KEY to be printed, set HINT
784 The heads inherit their PLIST from BODY-PLIST and are allowed to
785 override some keys. The keys recognized are :exit and :bind.
788 - nil (default): this head will continue the Hydra state.
789 - t: this head will stop the Hydra state.
792 - nil: this head will not be bound in BODY-MAP.
793 - a lambda taking KEY and CMD used to bind a head.
795 It is possible to omit both BODY-MAP and BODY-KEY if you don't
796 want to bind anything. In that case, typically you will bind the
797 generated NAME/body command. This command is also the return
798 result of `defhydra'."
799 (declare (indent defun))
800 (cond ((stringp docstring))
801 ((and (consp docstring)
802 (memq (car docstring) '(hydra--table concat format)))
803 (setq docstring (concat "\n" (eval docstring))))
805 (setq heads (cons docstring heads))
806 (setq docstring "hydra")))
807 (when (keywordp (car body))
808 (setq body (cons nil (cons nil body))))
809 (let* ((keymap (copy-keymap hydra-base-map))
810 (keymap-name (intern (format "%S/keymap" name)))
811 (body-name (intern (format "%S/body" name)))
812 (body-key (cadr body))
813 (body-plist (cddr body))
814 (body-map (or (car body)
815 (plist-get body-plist :bind)))
816 (body-pre (plist-get body-plist :pre))
817 (body-body-pre (plist-get body-plist :body-pre))
818 (body-post (plist-get body-plist :post))
819 (body-color (hydra--body-color body)))
820 (hydra--make-funcall body-post)
821 (when hydra-keyboard-quit
823 (setq heads (cons (list hydra-keyboard-quit #'hydra-keyboard-quit nil :exit t)
825 (define-key keymap hydra-keyboard-quit #'hydra-keyboard-quit)))
827 (let ((len (length h)))
829 (error "Each head should have at least two items: %S" h))
833 (hydra-plist-get-default body-plist :hint "")))
835 (list :cmd-name (hydra--head-name h name body))))
837 (let ((hint (cl-caddr h)))
838 (unless (or (null hint)
840 (setcdr (cdr h) (cons
841 (hydra-plist-get-default body-plist :hint "")
843 (let ((hint-and-plist (cddr h)))
844 (if (null (cdr hint-and-plist))
845 (setcdr hint-and-plist
847 (hydra--head-name h name body)))
848 (plist-put (cdr hint-and-plist)
850 (hydra--head-name h name body)))))))))
851 (let ((doc (hydra--doc body-key body-name heads))
852 (heads-nodup (hydra--delete-duplicates heads)))
855 (define-key keymap (kbd (car x))
856 (plist-get (cl-cdddr x) :cmd-name)))
858 (hydra--make-funcall body-pre)
859 (hydra--make-funcall body-body-pre)
860 (when (memq body-color '(amaranth pink))
863 (memq (hydra--head-color h body) '(blue teal)))
866 "An %S Hydra must have at least one blue head in order to exit"
870 (set (defvar ,keymap-name
872 ,(format "Keymap for %S." name))
877 (hydra--make-defun name body doc head keymap-name
880 ;; free up keymap prefix
881 ,@(unless (or (null body-key)
883 (hydra--callablep body-map))
884 `((unless (keymapp (lookup-key ,body-map (kbd ,body-key)))
885 (define-key ,body-map (kbd ,body-key) nil))))
890 (let ((name (hydra--head-property head :cmd-name)))
891 (when (and (cadr head)
892 (not (eq (cadr head) 'hydra-keyboard-quit))
893 (or body-key body-map))
894 (let ((bind (hydra--head-property head :bind body-map))
897 (vconcat (kbd body-key) (kbd (car head)))
899 (cond ((null bind) nil)
900 ((hydra--callablep bind)
901 `(funcall ,bind ,final-key (function ,name)))
904 (keymapp (symbol-value bind))
906 `(define-key ,bind ,final-key (function ,name)))
908 (error "Invalid :bind property `%S' for head %S" bind head)))))))
910 (defun ,(intern (format "%S/hint" name)) ()
911 ,(hydra--message name body docstring heads))
913 name body doc '(nil body)
915 (or body-body-pre body-pre) body-post
916 '(setq prefix-arg current-prefix-arg))))))
918 (defmacro defhydradio (name _body &rest heads)
919 "Create radios with prefix NAME.
920 _BODY specifies the options; there are none currently.
921 HEADS have the format:
923 (TOGGLE-NAME &optional VALUE DOC)
925 TOGGLE-NAME will be used along with NAME to generate a variable
926 name and a function that cycles it with the same name. VALUE
927 should be an array. The first element of VALUE will be used to
928 inialize the variable.
929 VALUE defaults to [nil t].
930 DOC defaults to TOGGLE-NAME split and capitalized."
931 (declare (indent defun))
935 (hydra--radio name h))
937 (defvar ,(intern (format "%S/names" name))
938 ',(mapcar (lambda (h) (intern (format "%S/%S" name (car h))))
941 (defmacro hydra-multipop (lst n)
942 "Return LST's first N elements while removing them."
943 `(if (<= (length ,lst) ,n)
948 (nthcdr (1- ,n) (prog1 ,lst (setq ,lst (nthcdr ,n ,lst))))
951 (defun hydra--radio (parent head)
952 "Generate a hydradio with PARENT from HEAD."
953 (let* ((name (car head))
954 (full-name (intern (format "%S/%S" parent name)))
956 (val (or (cl-caddr head) [nil t])))
957 `((defvar ,full-name ,(hydra--quote-maybe (aref val 0)) ,doc)
958 (put ',full-name 'range ,val)
960 (hydra--cycle-radio ',full-name)))))
962 (defun hydra--quote-maybe (x)
963 "Quote X if it's a symbol."
971 (defun hydra--cycle-radio (sym)
972 "Set SYM to the next value in its range."
973 (let* ((val (symbol-value sym))
974 (range (get sym 'range))
979 (if (equal (aref range i) val)
982 (error "Val not in range for %S" sym)))
992 ;;; outline-regexp: ";;\\*+"
995 ;;; hydra.el ends here