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."
111 (memq this-command '(handle-switch-frame keyboard-quit))
112 (null overriding-terminal-local-map)
113 (not (or (eq this-command
114 (lookup-key hydra-curr-map (this-single-command-keys)))
115 (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 (dolist (frame (frame-list))
127 (with-selected-frame frame
128 (when overriding-terminal-local-map
129 (internal-pop-keymap hydra-curr-map 'overriding-terminal-local-map)
130 (when hydra-curr-on-exit
131 (let ((on-exit hydra-curr-on-exit))
132 (setq hydra-curr-on-exit nil)
133 (funcall on-exit)))))))
135 (unless (fboundp 'internal-push-keymap)
136 (defun internal-push-keymap (keymap symbol)
137 (let ((map (symbol-value symbol)))
138 (unless (memq keymap map)
139 (unless (memq 'add-keymap-witness (symbol-value symbol))
140 (setq map (make-composed-keymap nil (symbol-value symbol)))
141 (push 'add-keymap-witness (cdr map))
143 (push keymap (cdr map))))))
145 (unless (fboundp 'internal-pop-keymap)
146 (defun internal-pop-keymap (keymap symbol)
147 (let ((map (symbol-value symbol)))
148 (when (memq keymap map)
149 (setf (cdr map) (delq keymap (cdr map))))
150 (let ((tail (cddr map)))
151 (and (or (null tail) (keymapp tail))
152 (eq 'add-keymap-witness (nth 1 map))
153 (set symbol tail))))))
155 (defun hydra-amaranth-warn ()
157 (message "An amaranth Hydra can only exit through a blue head"))
161 "Make bindings that stick around."
165 (defcustom hydra-is-helpful t
166 "When t, display a hint with possible bindings in the echo area."
170 (defcustom hydra-lv t
171 "When non-nil, `lv-message' (not `message') will be used to display hints."
174 (defcustom hydra-verbose nil
175 "When non-nil, hydra will issue some non essential style warnings."
178 (defcustom hydra-key-format-spec "%s"
179 "Default `format'-style specifier for _a_ syntax in docstrings.
180 When nil, you can specify your own at each location like this: _ 5a_.")
182 (defface hydra-face-red
183 '((t (:foreground "#FF0000" :bold t)))
184 "Red Hydra heads don't exit the Hydra.
185 Every other command exits the Hydra."
188 (defface hydra-face-blue
189 '((t (:foreground "#0000FF" :bold t)))
190 "Blue Hydra heads exit the Hydra.
191 Every other command exits as well.")
193 (defface hydra-face-amaranth
194 '((t (:foreground "#E52B50" :bold t)))
195 "Amaranth body has red heads and warns on intercepting non-heads.
196 Exitable only through a blue head.")
198 (defface hydra-face-pink
199 '((t (:foreground "#FF6EB4" :bold t)))
200 "Pink body has red heads and runs intercepted non-heads.
201 Exitable only through a blue head.")
203 (defface hydra-face-teal
204 '((t (:foreground "#367588" :bold t)))
205 "Teal body has blue heads an warns on intercepting non-heads.
206 Exitable only through a blue head.")
209 (defun hydra-add-font-lock ()
210 "Fontify `defhydra' statements."
211 (font-lock-add-keywords
213 '(("(\\(defhydra\\)\\_> +\\(.*?\\)\\_>"
214 (1 font-lock-keyword-face)
215 (2 font-lock-type-face))
216 ("(\\(defhydradio\\)\\_> +\\(.*?\\)\\_>"
217 (1 font-lock-keyword-face)
218 (2 font-lock-type-face)))))
220 ;;* Universal Argument
221 (defvar hydra-base-map
222 (let ((map (make-sparse-keymap)))
223 (define-key map [?\C-u] 'hydra--universal-argument)
224 (define-key map [?-] 'hydra--negative-argument)
225 (define-key map [?0] 'hydra--digit-argument)
226 (define-key map [?1] 'hydra--digit-argument)
227 (define-key map [?2] 'hydra--digit-argument)
228 (define-key map [?3] 'hydra--digit-argument)
229 (define-key map [?4] 'hydra--digit-argument)
230 (define-key map [?5] 'hydra--digit-argument)
231 (define-key map [?6] 'hydra--digit-argument)
232 (define-key map [?7] 'hydra--digit-argument)
233 (define-key map [?8] 'hydra--digit-argument)
234 (define-key map [?9] 'hydra--digit-argument)
235 (define-key map [kp-0] 'hydra--digit-argument)
236 (define-key map [kp-1] 'hydra--digit-argument)
237 (define-key map [kp-2] 'hydra--digit-argument)
238 (define-key map [kp-3] 'hydra--digit-argument)
239 (define-key map [kp-4] 'hydra--digit-argument)
240 (define-key map [kp-5] 'hydra--digit-argument)
241 (define-key map [kp-6] 'hydra--digit-argument)
242 (define-key map [kp-7] 'hydra--digit-argument)
243 (define-key map [kp-8] 'hydra--digit-argument)
244 (define-key map [kp-9] 'hydra--digit-argument)
245 (define-key map [kp-subtract] 'hydra--negative-argument)
247 "Keymap that all Hydras inherit. See `universal-argument-map'.")
249 (defun hydra--universal-argument (arg)
250 "Forward to (`universal-argument' ARG)."
252 (setq prefix-arg (if (consp arg)
253 (list (* 4 (car arg)))
258 (defun hydra--digit-argument (arg)
259 "Forward to (`digit-argument' ARG)."
261 (let* ((char (if (integerp last-command-event)
263 (get last-command-event 'ascii-character)))
264 (digit (- (logand char ?\177) ?0)))
265 (setq prefix-arg (cond ((integerp arg)
277 (defun hydra--negative-argument (arg)
278 "Forward to (`negative-argument' ARG)."
280 (setq prefix-arg (cond ((integerp arg) (- arg))
285 (defvar hydra-repeat--prefix-arg nil
286 "Prefix arg to use with `hydra-repeat'.")
288 (defvar hydra-repeat--command nil
289 "Command to use with `hydra-repeat'.")
291 (defun hydra-repeat (&optional arg)
292 "Repeat last command with last prefix arg.
293 When ARG is non-nil, use that instead."
296 (unless (string-match "hydra-repeat$" (symbol-name last-command))
297 (setq hydra-repeat--command last-command)
298 (setq hydra-repeat--prefix-arg last-prefix-arg))
299 (setq hydra-repeat--prefix-arg arg))
300 (setq current-prefix-arg hydra-repeat--prefix-arg)
301 (funcall hydra-repeat--command))
304 (defun hydra--callablep (x)
305 "Test if X is callable."
308 (memq (car x) '(function quote)))))
310 (defun hydra--make-callable (x)
311 "Generate a callable symbol from X.
312 If X is a function symbol or a lambda, return it. Otherwise, it
313 should be a single statement. Wrap it in an interactive lambda."
314 (if (or (symbolp x) (functionp x))
320 (defun hydra-plist-get-default (plist prop default)
321 "Extract a value from a property list.
322 PLIST is a property list, which is a list of the form
323 \(PROP1 VALUE1 PROP2 VALUE2...).
325 Return the value corresponding to PROP, or DEFAULT if PROP is not
326 one of the properties on the list."
327 (if (memq prop plist)
328 (plist-get plist prop)
331 (defun hydra--head-property (h prop &optional default)
332 "Return for Hydra head H the value of property PROP.
333 Return DEFAULT if PROP is not in H."
334 (hydra-plist-get-default (cl-cdddr h) prop default))
336 (defun hydra--body-foreign-keys (body)
337 "Return what BODY does with a non-head binding."
339 (plist-get (cddr body) :foreign-keys)
340 (let ((color (plist-get (cddr body) :color)))
342 ((amaranth teal) 'warn)
345 (defun hydra--body-exit (body)
346 "Return the exit behavior of BODY."
348 (plist-get (cddr body) :exit)
349 (let ((color (plist-get (cddr body) :color)))
354 (defvar hydra--input-method-function nil
355 "Store overridden `input-method-function' here.")
357 (defun hydra-default-pre ()
358 "Default setup that happens in each head before :pre."
359 (when (eq input-method-function 'key-chord-input-method)
360 (unless hydra--input-method-function
361 (setq hydra--input-method-function input-method-function)
362 (setq input-method-function nil))))
364 (defun hydra-keyboard-quit ()
365 "Quitting function similar to `keyboard-quit'."
368 (cancel-timer hydra-timer)
369 (when hydra--input-method-function
370 (setq input-method-function hydra--input-method-function)
371 (setq hydra--input-method-function nil))
373 (when (window-live-p lv-wnd)
374 (let ((buf (window-buffer lv-wnd)))
375 (delete-window lv-wnd)
380 (defun hydra--hint (body heads)
381 "Generate a hint for the echo area.
382 BODY, and HEADS are parameters to `defhydra'."
385 (let ((val (assoc (cadr h) alist))
386 (pstr (hydra-fontify-head h body)))
387 (unless (null (cl-caddr h))
390 (concat (cadr val) " " pstr))
393 (cons pstr (cl-caddr h)))
398 (if (> (length (cdr x)) 0)
399 (concat "[%s]: " (cdr x))
402 (nreverse (mapcar #'cdr alist))
405 (defvar hydra-fontify-head-function nil
406 "Possible replacement for `hydra-fontify-head-default'.")
408 (defun hydra-fontify-head-default (head body)
409 "Produce a pretty string from HEAD and BODY.
410 HEAD's binding is returned as a string with a colored face."
411 (let* ((foreign-keys (hydra--body-foreign-keys body))
412 (head-exit (hydra--head-property head :exit))
415 (if (eq foreign-keys 'warn)
418 (cl-case foreign-keys
422 (when (and (null (cadr head))
423 (not (eq head-color 'blue)))
424 (hydra--complain "nil cmd can only be blue"))
425 (propertize (car head) 'face
427 (blue 'hydra-face-blue)
428 (red 'hydra-face-red)
429 (amaranth 'hydra-face-amaranth)
430 (pink 'hydra-face-pink)
431 (teal 'hydra-face-teal)
432 (t (error "Unknown color for %S" head))))))
434 (defun hydra-fontify-head-greyscale (head body)
435 "Produce a pretty string from HEAD and BODY.
436 HEAD's binding is returned as a string wrapped with [] or {}."
438 (if (hydra--head-property head :exit)
442 (defun hydra-fontify-head (head body)
443 "Produce a pretty string from HEAD and BODY."
444 (funcall (or hydra-fontify-head-function 'hydra-fontify-head-default)
447 (defun hydra--format (_name body docstring heads)
448 "Generate a `format' statement from STR.
449 \"%`...\" expressions are extracted into \"%S\".
450 _NAME, BODY, DOCSTRING and HEADS are parameters of `defhydra'.
451 The expressions can be auto-expanded according to NAME."
452 (setq docstring (replace-regexp-in-string "\\^" "" docstring))
453 (let ((rest (hydra--hint body heads))
459 "\\(?:%\\( ?-?[0-9]*s?\\)\\(`[a-z-A-Z/0-9]+\\|(\\)\\)\\|\\(?:_\\( ?-?[0-9]*\\)\\([[:alnum:]~.,;:/|?<>={}*+#]+\\)_\\)"
461 (cond ((eq ?_ (aref (match-string 0 docstring) 0))
462 (let* ((key (match-string 4 docstring))
463 (head (assoc key heads)))
466 (push (hydra-fontify-head head body) varlist)
470 hydra-key-format-spec
471 (concat "%" (match-string 3 docstring) "s"))
473 (error "Unrecognized key: _%s_" key))))
476 (let* ((varp (if (eq ?` (aref (match-string 2 docstring) 0)) 1 0))
477 (spec (match-string 1 docstring))
478 (lspec (length spec)))
481 (insert (substring docstring (+ 1 start varp
483 (goto-char (point-min))
484 (push (read (current-buffer)) varlist)
485 (- (point) (point-min))))
486 (when (or (zerop lspec)
487 (/= (aref spec (1- (length spec))) ?s))
488 (setq spec (concat spec "S")))
491 (substring docstring 0 start)
493 (substring docstring (+ start offset 1 lspec varp))))))))
494 (if (eq ?\n (aref docstring 0))
495 `(concat (format ,(substring docstring 1) ,@(nreverse varlist))
497 `(format ,(concat docstring ": " rest ".")))))
499 (defun hydra--complain (format-string &rest args)
500 "Forward to (`message' FORMAT-STRING ARGS) unless `hydra-verbose' is nil."
502 (apply #'warn format-string args)))
504 (defun hydra--doc (body-key body-name heads)
505 "Generate a part of Hydra docstring.
506 BODY-KEY is the body key binding.
507 BODY-NAME is the symbol that identifies the Hydra.
508 HEADS is a list of heads."
510 "Create a hydra with %s body and the heads:\n\n%s\n\n%s"
512 (format "a \"%s\"" body-key)
516 (format "\"%s\": `%S'" (car x) (cadr x)))
518 (format "The body can be accessed via `%S'." body-name)))
520 (defun hydra--call-interactively (cmd name)
521 "Generate a `call-interactively' statement for CMD.
522 Set `this-command' to NAME."
523 (if (and (symbolp name)
524 (not (memq name '(nil body))))
526 (setq this-command ',name)
527 (call-interactively #',cmd))
528 `(call-interactively #',cmd)))
530 (defun hydra--make-defun (name body doc head
531 keymap body-pre body-before-exit
532 &optional body-after-exit)
533 "Make a defun wrapper, using NAME, BODY, DOC, HEAD, and KEYMAP.
534 NAME and BODY are the arguments to `defhydra'.
535 DOC was generated with `hydra--doc'.
536 HEAD is one of the HEADS passed to `defhydra'.
537 BODY-PRE is added to the start of the wrapper.
538 BODY-BEFORE-EXIT will be called before the hydra quits.
539 BODY-AFTER-EXIT is added to the end of the wrapper."
540 (let ((name (hydra--head-name head name body))
541 (cmd (when (car head)
542 (hydra--make-callable
545 (format "%s\n\nCall the head: `%S'." doc (cadr head))
547 (hint (intern (format "%S/hint" name)))
548 (body-foreign-keys (hydra--body-foreign-keys body))
549 (body-timeout (plist-get body :timeout)))
554 ,@(when body-pre (list body-pre))
555 ,@(if (hydra--head-property head :exit)
556 `((hydra-keyboard-quit)
557 ,@(if body-after-exit
560 (hydra--call-interactively cmd (cadr head)))
563 `(,(hydra--call-interactively cmd (cadr head))))))
568 ,(hydra--call-interactively cmd (cadr head))
573 (when hydra-is-helpful
575 (lv-message (eval ,hint))
576 (message (eval ,hint))))
577 (hydra-set-transient-map
579 (lambda () (hydra-keyboard-quit) ,body-before-exit)
580 ,(when body-foreign-keys
581 (list 'quote body-foreign-keys)))
584 `(hydra-timeout ,body-timeout))))))))
586 (defmacro hydra--make-funcall (sym)
587 "Transform SYM into a `funcall' to call it."
588 `(when (and ,sym (symbolp ,sym))
589 (setq ,sym `(funcall #',,sym))))
591 (defun hydra--head-name (h name body)
592 "Return the symbol for head H of hydra with NAME and BODY."
593 (let ((str (format "%S/%s" name
594 (if (symbolp (cadr h))
596 (concat "lambda-" (car h))))))
597 (when (and (hydra--head-property h :exit)
598 (not (memq (cadr h) '(body nil))))
599 (setq str (concat str "-and-exit")))
602 (defun hydra--delete-duplicates (heads)
603 "Return HEADS without entries that have the same CMD part.
604 In duplicate HEADS, :cmd-name is modified to whatever they duplicate."
605 (let ((ali '(((hydra-repeat . nil) . hydra-repeat)))
608 (if (setq entry (assoc (cons (cadr h)
609 (hydra--head-property h :exit))
611 (setf (cl-cdddr h) (plist-put (cl-cdddr h) :cmd-name (cdr entry)))
612 (push (cons (cons (cadr h)
613 (hydra--head-property h :exit))
614 (plist-get (cl-cdddr h) :cmd-name))
619 (defun hydra--pad (lst n)
620 "Pad LST with nil until length N."
621 (let ((len (length lst)))
624 (append lst (make-list (- n len) nil)))))
626 (defun hydra--matrix (lst rows cols)
627 "Create a matrix from elements of LST.
628 The matrix size is ROWS times COLS."
629 (let ((ls (copy-sequence lst))
632 (push (hydra--pad (hydra-multipop ls rows) rows) res))
635 (defun hydra--cell (fstr names)
636 "Format a rectangular cell based on FSTR and NAMES.
637 FSTR is a format-style string with two string inputs: one for the
638 doc and one for the symbol name.
639 NAMES is a list of variables."
640 (let ((len (cl-reduce
641 (lambda (acc it) (max (length (symbol-name it)) acc))
648 (documentation-property sym 'variable-documentation)
649 (let ((name (symbol-name sym)))
650 (concat name (make-string (- len (length name)) ?^)))
656 (defun hydra--vconcat (strs &optional joiner)
657 "Glue STRS vertically. They must be the same height.
658 JOINER is a function similar to `concat'."
659 (setq joiner (or joiner #'concat))
662 (if (string-match " +$" s)
663 (replace-match "" nil nil s)
665 (apply #'cl-mapcar joiner
667 (lambda (s) (split-string s "\n"))
671 (defcustom hydra-cell-format "% -20s %% -8`%s"
672 "The default format for docstring cells."
675 (defun hydra--table (names rows cols &optional cell-formats)
676 "Format a `format'-style table from variables in NAMES.
677 The size of the table is ROWS times COLS.
678 CELL-FORMATS are `format' strings for each column.
679 If CELL-FORMATS is a string, it's used for all columns.
680 If CELL-FORMATS is nil, `hydra-cell-format' is used for all columns."
682 (cond ((null cell-formats)
683 (make-list cols hydra-cell-format))
684 ((stringp cell-formats)
685 (make-list cols cell-formats))
692 (hydra--matrix names rows cols))
694 (mapconcat #'identity x " "))))
696 (defun hydra-reset-radios (names)
697 "Set varibles NAMES to their defaults.
698 NAMES should be defined by `defhydradio' or similar."
700 (set n (aref (get n 'range) 0))))
702 (defvar hydra-timer (timer-create)
703 "Timer for `hydra-timeout'.")
705 (defun hydra-timeout (secs &optional function)
706 "In SECS seconds call FUNCTION, then function `hydra-keyboard-quit'.
707 Cancel the previous `hydra-timeout'."
708 (cancel-timer hydra-timer)
709 (setq hydra-timer (timer-create))
710 (timer-set-time hydra-timer
711 (timer-relative-time (current-time) secs))
716 `(funcall ,function))
717 (hydra-keyboard-quit)))
718 (timer-activate hydra-timer))
722 (defmacro defhydra (name body &optional docstring &rest heads)
723 "Create a Hydra - a family of functions with prefix NAME.
725 NAME should be a symbol, it will be the prefix of all functions
730 (BODY-MAP BODY-KEY &rest BODY-PLIST)
732 DOCSTRING will be displayed in the echo area to identify the
733 Hydra. When DOCSTRING starts with a newline, special Ruby-style
734 substitution will be performed by `hydra--format'.
736 Functions are created on basis of HEADS, each of which has the
739 (KEY CMD &optional HINT &rest PLIST)
741 BODY-MAP is a keymap; `global-map' is used quite often. Each
742 function generated from HEADS will be bound in BODY-MAP to
743 BODY-KEY + KEY (both are strings passed to `kbd'), and will set
744 the transient map so that all following heads can be called
745 though KEY only. BODY-KEY can be an empty string.
747 CMD is a callable expression: either an interactive function
748 name, or an interactive lambda, or a single sexp (it will be
749 wrapped in an interactive lambda).
751 HINT is a short string that identifies its head. It will be
752 printed beside KEY in the echo erea if `hydra-is-helpful' is not
753 nil. If you don't even want the KEY to be printed, set HINT
756 The heads inherit their PLIST from BODY-PLIST and are allowed to
757 override some keys. The keys recognized are :exit and :bind.
760 - nil (default): this head will continue the Hydra state.
761 - t: this head will stop the Hydra state.
764 - nil: this head will not be bound in BODY-MAP.
765 - a lambda taking KEY and CMD used to bind a head.
767 It is possible to omit both BODY-MAP and BODY-KEY if you don't
768 want to bind anything. In that case, typically you will bind the
769 generated NAME/body command. This command is also the return
770 result of `defhydra'."
771 (declare (indent defun))
772 (cond ((stringp docstring))
773 ((and (consp docstring)
774 (memq (car docstring) '(hydra--table concat format)))
775 (setq docstring (concat "\n" (eval docstring))))
777 (setq heads (cons docstring heads))
778 (setq docstring "hydra")))
779 (when (keywordp (car body))
780 (setq body (cons nil (cons nil body))))
782 (let* ((keymap (copy-keymap hydra-base-map))
783 (keymap-name (intern (format "%S/keymap" name)))
784 (body-name (intern (format "%S/body" name)))
785 (body-key (cadr body))
786 (body-plist (cddr body))
787 (body-map (or (car body)
788 (plist-get body-plist :bind)))
789 (body-pre (plist-get body-plist :pre))
790 (body-body-pre (plist-get body-plist :body-pre))
791 (body-before-exit (or (plist-get body-plist :post)
792 (plist-get body-plist :before-exit)))
793 (body-after-exit (plist-get body-plist :after-exit))
794 (body-inherit (plist-get body-plist :inherit))
795 (body-foreign-keys (hydra--body-foreign-keys body))
796 (body-exit (hydra--body-exit body)))
797 (dolist (base body-inherit)
798 (setq heads (append heads (copy-sequence (eval base)))))
800 (let ((len (length h)))
802 (error "Each head should have at least two items: %S" h))
806 (hydra-plist-get-default body-plist :hint "")))
807 (setcdr (nthcdr 2 h) (list :exit body-exit)))
809 (let ((hint (cl-caddr h)))
810 (unless (or (null hint)
812 (setcdr (cdr h) (cons
813 (hydra-plist-get-default body-plist :hint "")
815 (let ((hint-and-plist (cddr h)))
816 (if (null (cdr hint-and-plist))
817 (setcdr hint-and-plist (list :exit body-exit))
818 (let* ((plist (cl-cdddr h))
819 (h-color (plist-get plist :color)))
822 (plist-put plist :exit
826 (cl-remf (cl-cdddr h) :color))
827 (let ((h-exit (hydra-plist-get-default plist :exit 'default)))
828 (plist-put plist :exit
829 (if (eq h-exit 'default)
832 (plist-put (cl-cdddr h) :cmd-name (hydra--head-name h name body))
833 (when (null (cadr h)) (plist-put (cl-cdddr h) :exit t)))
834 (let ((doc (hydra--doc body-key body-name heads))
835 (heads-nodup (hydra--delete-duplicates heads)))
838 (define-key keymap (kbd (car x))
839 (plist-get (cl-cdddr x) :cmd-name)))
841 (hydra--make-funcall body-pre)
842 (hydra--make-funcall body-body-pre)
843 (hydra--make-funcall body-before-exit)
844 (hydra--make-funcall body-after-exit)
845 (when (memq body-foreign-keys '(run warn))
848 (hydra--head-property h :exit))
851 "An %S Hydra must have at least one blue head in order to exit"
855 (set (defvar ,keymap-name
857 ,(format "Keymap for %S." name))
860 (set (defvar ,(intern (format "%S/heads" name))
862 ,(format "Heads for %S." name))
863 ',(mapcar (lambda (h)
864 (let ((j (copy-sequence h)))
865 (cl-remf (cl-cdddr j) :cmd-name)
871 (hydra--make-defun name body doc head keymap-name
876 ;; free up keymap prefix
877 ,@(unless (or (null body-key)
879 (hydra--callablep body-map))
880 `((unless (keymapp (lookup-key ,body-map (kbd ,body-key)))
881 (define-key ,body-map (kbd ,body-key) nil))))
886 (let ((name (hydra--head-property head :cmd-name)))
887 (when (and (cadr head)
888 (or body-key body-map))
889 (let ((bind (hydra--head-property head :bind body-map))
892 (vconcat (kbd body-key) (kbd (car head)))
894 (cond ((null bind) nil)
895 ((hydra--callablep bind)
896 `(funcall ,bind ,final-key (function ,name)))
899 (keymapp (symbol-value bind))
901 `(define-key ,bind ,final-key (function ,name)))
903 (error "Invalid :bind property `%S' for head %S" bind head)))))))
906 (defvar ,(intern (format "%S/hint" name)) nil
907 ,(format "Dynamic hint for %S." name))
908 ',(hydra--format name body docstring heads))
910 name body doc '(nil body)
912 (or body-body-pre body-pre) body-before-exit
913 '(setq prefix-arg current-prefix-arg)))))
915 (message "Error in defhydra %S: %s" name (cdr err))
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