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 (defvar hydra--ignore nil
124 "When non-nil, don't call `hydra-curr-on-exit'")
126 (defun hydra-disable ()
127 "Disable the current Hydra."
128 (remove-hook 'pre-command-hook 'hydra--clearfun)
129 (dolist (frame (frame-list))
130 (with-selected-frame frame
131 (when overriding-terminal-local-map
132 (internal-pop-keymap hydra-curr-map 'overriding-terminal-local-map)
133 (unless hydra--ignore
134 (when hydra--input-method-function
135 (setq input-method-function hydra--input-method-function)
136 (setq hydra--input-method-function nil))
137 (when hydra-curr-on-exit
138 (let ((on-exit hydra-curr-on-exit))
139 (setq hydra-curr-on-exit nil)
140 (funcall on-exit))))))))
142 (unless (fboundp 'internal-push-keymap)
143 (defun internal-push-keymap (keymap symbol)
144 (let ((map (symbol-value symbol)))
145 (unless (memq keymap map)
146 (unless (memq 'add-keymap-witness (symbol-value symbol))
147 (setq map (make-composed-keymap nil (symbol-value symbol)))
148 (push 'add-keymap-witness (cdr map))
150 (push keymap (cdr map))))))
152 (unless (fboundp 'internal-pop-keymap)
153 (defun internal-pop-keymap (keymap symbol)
154 (let ((map (symbol-value symbol)))
155 (when (memq keymap map)
156 (setf (cdr map) (delq keymap (cdr map))))
157 (let ((tail (cddr map)))
158 (and (or (null tail) (keymapp tail))
159 (eq 'add-keymap-witness (nth 1 map))
160 (set symbol tail))))))
162 (defun hydra-amaranth-warn ()
164 (message "An amaranth Hydra can only exit through a blue head"))
168 "Make bindings that stick around."
172 (defcustom hydra-is-helpful t
173 "When t, display a hint with possible bindings in the echo area."
177 (defcustom hydra-lv t
178 "When non-nil, `lv-message' (not `message') will be used to display hints."
181 (defcustom hydra-verbose nil
182 "When non-nil, hydra will issue some non essential style warnings."
185 (defcustom hydra-key-format-spec "%s"
186 "Default `format'-style specifier for _a_ syntax in docstrings.
187 When nil, you can specify your own at each location like this: _ 5a_.")
189 (defface hydra-face-red
190 '((t (:foreground "#FF0000" :bold t)))
191 "Red Hydra heads don't exit the Hydra.
192 Every other command exits the Hydra."
195 (defface hydra-face-blue
196 '((t (:foreground "#0000FF" :bold t)))
197 "Blue Hydra heads exit the Hydra.
198 Every other command exits as well.")
200 (defface hydra-face-amaranth
201 '((t (:foreground "#E52B50" :bold t)))
202 "Amaranth body has red heads and warns on intercepting non-heads.
203 Exitable only through a blue head.")
205 (defface hydra-face-pink
206 '((t (:foreground "#FF6EB4" :bold t)))
207 "Pink body has red heads and runs intercepted non-heads.
208 Exitable only through a blue head.")
210 (defface hydra-face-teal
211 '((t (:foreground "#367588" :bold t)))
212 "Teal body has blue heads an warns on intercepting non-heads.
213 Exitable only through a blue head.")
216 (defun hydra-add-font-lock ()
217 "Fontify `defhydra' statements."
218 (font-lock-add-keywords
220 '(("(\\(defhydra\\)\\_> +\\(.*?\\)\\_>"
221 (1 font-lock-keyword-face)
222 (2 font-lock-type-face))
223 ("(\\(defhydradio\\)\\_> +\\(.*?\\)\\_>"
224 (1 font-lock-keyword-face)
225 (2 font-lock-type-face)))))
227 ;;* Universal Argument
228 (defvar hydra-base-map
229 (let ((map (make-sparse-keymap)))
230 (define-key map [?\C-u] 'hydra--universal-argument)
231 (define-key map [?-] 'hydra--negative-argument)
232 (define-key map [?0] 'hydra--digit-argument)
233 (define-key map [?1] 'hydra--digit-argument)
234 (define-key map [?2] 'hydra--digit-argument)
235 (define-key map [?3] 'hydra--digit-argument)
236 (define-key map [?4] 'hydra--digit-argument)
237 (define-key map [?5] 'hydra--digit-argument)
238 (define-key map [?6] 'hydra--digit-argument)
239 (define-key map [?7] 'hydra--digit-argument)
240 (define-key map [?8] 'hydra--digit-argument)
241 (define-key map [?9] 'hydra--digit-argument)
242 (define-key map [kp-0] 'hydra--digit-argument)
243 (define-key map [kp-1] 'hydra--digit-argument)
244 (define-key map [kp-2] 'hydra--digit-argument)
245 (define-key map [kp-3] 'hydra--digit-argument)
246 (define-key map [kp-4] 'hydra--digit-argument)
247 (define-key map [kp-5] 'hydra--digit-argument)
248 (define-key map [kp-6] 'hydra--digit-argument)
249 (define-key map [kp-7] 'hydra--digit-argument)
250 (define-key map [kp-8] 'hydra--digit-argument)
251 (define-key map [kp-9] 'hydra--digit-argument)
252 (define-key map [kp-subtract] 'hydra--negative-argument)
254 "Keymap that all Hydras inherit. See `universal-argument-map'.")
256 (defun hydra--universal-argument (arg)
257 "Forward to (`universal-argument' ARG)."
259 (setq prefix-arg (if (consp arg)
260 (list (* 4 (car arg)))
265 (defun hydra--digit-argument (arg)
266 "Forward to (`digit-argument' ARG)."
268 (let* ((char (if (integerp last-command-event)
270 (get last-command-event 'ascii-character)))
271 (digit (- (logand char ?\177) ?0)))
272 (setq prefix-arg (cond ((integerp arg)
284 (defun hydra--negative-argument (arg)
285 "Forward to (`negative-argument' ARG)."
287 (setq prefix-arg (cond ((integerp arg) (- arg))
292 (defvar hydra-repeat--prefix-arg nil
293 "Prefix arg to use with `hydra-repeat'.")
295 (defvar hydra-repeat--command nil
296 "Command to use with `hydra-repeat'.")
298 (defun hydra-repeat (&optional arg)
299 "Repeat last command with last prefix arg.
300 When ARG is non-nil, use that instead."
303 (unless (string-match "hydra-repeat$" (symbol-name last-command))
304 (setq hydra-repeat--command last-command)
305 (setq hydra-repeat--prefix-arg last-prefix-arg))
306 (setq hydra-repeat--prefix-arg arg))
307 (setq current-prefix-arg hydra-repeat--prefix-arg)
308 (funcall hydra-repeat--command))
311 (defun hydra--callablep (x)
312 "Test if X is callable."
315 (memq (car x) '(function quote)))))
317 (defun hydra--make-callable (x)
318 "Generate a callable symbol from X.
319 If X is a function symbol or a lambda, return it. Otherwise, it
320 should be a single statement. Wrap it in an interactive lambda."
321 (if (or (symbolp x) (functionp x))
327 (defun hydra-plist-get-default (plist prop default)
328 "Extract a value from a property list.
329 PLIST is a property list, which is a list of the form
330 \(PROP1 VALUE1 PROP2 VALUE2...).
332 Return the value corresponding to PROP, or DEFAULT if PROP is not
333 one of the properties on the list."
334 (if (memq prop plist)
335 (plist-get plist prop)
338 (defun hydra--head-property (h prop &optional default)
339 "Return for Hydra head H the value of property PROP.
340 Return DEFAULT if PROP is not in H."
341 (hydra-plist-get-default (cl-cdddr h) prop default))
343 (defun hydra--body-foreign-keys (body)
344 "Return what BODY does with a non-head binding."
346 (plist-get (cddr body) :foreign-keys)
347 (let ((color (plist-get (cddr body) :color)))
349 ((amaranth teal) 'warn)
352 (defun hydra--body-exit (body)
353 "Return the exit behavior of BODY."
355 (plist-get (cddr body) :exit)
356 (let ((color (plist-get (cddr body) :color)))
361 (defvar hydra--input-method-function nil
362 "Store overridden `input-method-function' here.")
364 (defun hydra-default-pre ()
365 "Default setup that happens in each head before :pre."
366 (when (eq input-method-function 'key-chord-input-method)
367 (unless hydra--input-method-function
368 (setq hydra--input-method-function input-method-function)
369 (setq input-method-function nil))))
371 (defun hydra-keyboard-quit ()
372 "Quitting function similar to `keyboard-quit'."
375 (cancel-timer hydra-timeout-timer)
376 (cancel-timer hydra-message-timer)
378 (when (window-live-p lv-wnd)
379 (let ((buf (window-buffer lv-wnd)))
380 (delete-window lv-wnd)
385 (defun hydra--hint (body heads)
386 "Generate a hint for the echo area.
387 BODY, and HEADS are parameters to `defhydra'."
390 (let ((val (assoc (cadr h) alist))
391 (pstr (hydra-fontify-head h body)))
392 (unless (null (cl-caddr h))
395 (concat (cadr val) " " pstr))
398 (cons pstr (cl-caddr h)))
403 (if (> (length (cdr x)) 0)
404 (concat "[%s]: " (cdr x))
407 (nreverse (mapcar #'cdr alist))
410 (defvar hydra-fontify-head-function nil
411 "Possible replacement for `hydra-fontify-head-default'.")
413 (defun hydra-fontify-head-default (head body)
414 "Produce a pretty string from HEAD and BODY.
415 HEAD's binding is returned as a string with a colored face."
416 (let* ((foreign-keys (hydra--body-foreign-keys body))
417 (head-exit (hydra--head-property head :exit))
420 (if (eq foreign-keys 'warn)
423 (cl-case foreign-keys
427 (when (and (null (cadr head))
428 (not (eq head-color 'blue)))
429 (hydra--complain "nil cmd can only be blue"))
430 (propertize (car head) 'face
432 (blue 'hydra-face-blue)
433 (red 'hydra-face-red)
434 (amaranth 'hydra-face-amaranth)
435 (pink 'hydra-face-pink)
436 (teal 'hydra-face-teal)
437 (t (error "Unknown color for %S" head))))))
439 (defun hydra-fontify-head-greyscale (head body)
440 "Produce a pretty string from HEAD and BODY.
441 HEAD's binding is returned as a string wrapped with [] or {}."
443 (if (hydra--head-property head :exit)
447 (defun hydra-fontify-head (head body)
448 "Produce a pretty string from HEAD and BODY."
449 (funcall (or hydra-fontify-head-function 'hydra-fontify-head-default)
452 (defun hydra--format (_name body docstring heads)
453 "Generate a `format' statement from STR.
454 \"%`...\" expressions are extracted into \"%S\".
455 _NAME, BODY, DOCSTRING and HEADS are parameters of `defhydra'.
456 The expressions can be auto-expanded according to NAME."
457 (setq docstring (replace-regexp-in-string "\\^" "" docstring))
458 (let ((rest (hydra--hint body heads))
464 "\\(?:%\\( ?-?[0-9]*s?\\)\\(`[a-z-A-Z/0-9]+\\|(\\)\\)\\|\\(?:_\\( ?-?[0-9]*\\)\\([[:alnum:]-~.,;:/|?<>={}*+#]+\\)_\\)"
466 (cond ((eq ?_ (aref (match-string 0 docstring) 0))
467 (let* ((key (match-string 4 docstring))
468 (head (assoc key heads)))
471 (push (hydra-fontify-head head body) varlist)
475 hydra-key-format-spec
476 (concat "%" (match-string 3 docstring) "s"))
478 (error "Unrecognized key: _%s_" key))))
481 (let* ((varp (if (eq ?` (aref (match-string 2 docstring) 0)) 1 0))
482 (spec (match-string 1 docstring))
483 (lspec (length spec)))
486 (insert (substring docstring (+ 1 start varp
488 (goto-char (point-min))
489 (push (read (current-buffer)) varlist)
490 (- (point) (point-min))))
491 (when (or (zerop lspec)
492 (/= (aref spec (1- (length spec))) ?s))
493 (setq spec (concat spec "S")))
496 (substring docstring 0 start)
498 (substring docstring (+ start offset 1 lspec varp))))))))
499 (if (eq ?\n (aref docstring 0))
500 `(concat (format ,(substring docstring 1) ,@(nreverse varlist))
502 `(format ,(concat docstring ": " rest ".")))))
504 (defun hydra--complain (format-string &rest args)
505 "Forward to (`message' FORMAT-STRING ARGS) unless `hydra-verbose' is nil."
507 (apply #'warn format-string args)))
509 (defun hydra--doc (body-key body-name heads)
510 "Generate a part of Hydra docstring.
511 BODY-KEY is the body key binding.
512 BODY-NAME is the symbol that identifies the Hydra.
513 HEADS is a list of heads."
515 "Create a hydra with %s body and the heads:\n\n%s\n\n%s"
517 (format "a \"%s\"" body-key)
521 (format "\"%s\": `%S'" (car x) (cadr x)))
523 (format "The body can be accessed via `%S'." body-name)))
525 (defun hydra--call-interactively (cmd name)
526 "Generate a `call-interactively' statement for CMD.
527 Set `this-command' to NAME."
528 (if (and (symbolp name)
529 (not (memq name '(nil body))))
531 (setq this-command ',name)
532 (call-interactively #',cmd))
533 `(call-interactively #',cmd)))
535 (defun hydra--make-defun (name body doc head
536 keymap body-pre body-before-exit
537 &optional body-after-exit)
538 "Make a defun wrapper, using NAME, BODY, DOC, HEAD, and KEYMAP.
539 NAME and BODY are the arguments to `defhydra'.
540 DOC was generated with `hydra--doc'.
541 HEAD is one of the HEADS passed to `defhydra'.
542 BODY-PRE is added to the start of the wrapper.
543 BODY-BEFORE-EXIT will be called before the hydra quits.
544 BODY-AFTER-EXIT is added to the end of the wrapper."
545 (let ((name (hydra--head-name head name body))
546 (cmd (when (car head)
547 (hydra--make-callable
550 (format "%s\n\nCall the head: `%S'." doc (cadr head))
552 (hint (intern (format "%S/hint" name)))
553 (body-foreign-keys (hydra--body-foreign-keys body))
554 (body-timeout (plist-get body :timeout))
555 (body-idle (plist-get body :idle)))
560 ,@(when body-pre (list body-pre))
561 ,@(if (hydra--head-property head :exit)
562 `((hydra-keyboard-quit)
563 ,@(if body-after-exit
566 (hydra--call-interactively cmd (cadr head)))
569 `(,(hydra--call-interactively cmd (cadr head))))))
572 `((let ((hydra--ignore ,(not (eq (cadr head) 'body))))
573 (hydra-keyboard-quit))
576 ,(hydra--call-interactively cmd (cadr head))
581 ,(if (and body-idle (eq (cadr head) 'body))
582 `(hydra-idle-message ,body-idle ,hint)
583 `(when hydra-is-helpful
585 (lv-message (eval ,hint))
586 (message (eval ,hint)))))
587 (hydra-set-transient-map
589 (lambda () (hydra-keyboard-quit) ,body-before-exit)
590 ,(when body-foreign-keys
591 (list 'quote body-foreign-keys)))
594 `(hydra-timeout ,body-timeout))))))))
596 (defmacro hydra--make-funcall (sym)
597 "Transform SYM into a `funcall' to call it."
598 `(when (and ,sym (symbolp ,sym))
599 (setq ,sym `(funcall #',,sym))))
601 (defun hydra--head-name (h name body)
602 "Return the symbol for head H of hydra with NAME and BODY."
603 (let ((str (format "%S/%s" name
604 (if (symbolp (cadr h))
606 (concat "lambda-" (car h))))))
607 (when (and (hydra--head-property h :exit)
608 (not (memq (cadr h) '(body nil))))
609 (setq str (concat str "-and-exit")))
612 (defun hydra--delete-duplicates (heads)
613 "Return HEADS without entries that have the same CMD part.
614 In duplicate HEADS, :cmd-name is modified to whatever they duplicate."
615 (let ((ali '(((hydra-repeat . nil) . hydra-repeat)))
618 (if (setq entry (assoc (cons (cadr h)
619 (hydra--head-property h :exit))
621 (setf (cl-cdddr h) (plist-put (cl-cdddr h) :cmd-name (cdr entry)))
622 (push (cons (cons (cadr h)
623 (hydra--head-property h :exit))
624 (plist-get (cl-cdddr h) :cmd-name))
629 (defun hydra--pad (lst n)
630 "Pad LST with nil until length N."
631 (let ((len (length lst)))
634 (append lst (make-list (- n len) nil)))))
636 (defun hydra--matrix (lst rows cols)
637 "Create a matrix from elements of LST.
638 The matrix size is ROWS times COLS."
639 (let ((ls (copy-sequence lst))
642 (push (hydra--pad (hydra-multipop ls rows) rows) res))
645 (defun hydra--cell (fstr names)
646 "Format a rectangular cell based on FSTR and NAMES.
647 FSTR is a format-style string with two string inputs: one for the
648 doc and one for the symbol name.
649 NAMES is a list of variables."
650 (let ((len (cl-reduce
651 (lambda (acc it) (max (length (symbol-name it)) acc))
658 (documentation-property sym 'variable-documentation)
659 (let ((name (symbol-name sym)))
660 (concat name (make-string (- len (length name)) ?^)))
666 (defun hydra--vconcat (strs &optional joiner)
667 "Glue STRS vertically. They must be the same height.
668 JOINER is a function similar to `concat'."
669 (setq joiner (or joiner #'concat))
672 (if (string-match " +$" s)
673 (replace-match "" nil nil s)
675 (apply #'cl-mapcar joiner
677 (lambda (s) (split-string s "\n"))
681 (defcustom hydra-cell-format "% -20s %% -8`%s"
682 "The default format for docstring cells."
685 (defun hydra--table (names rows cols &optional cell-formats)
686 "Format a `format'-style table from variables in NAMES.
687 The size of the table is ROWS times COLS.
688 CELL-FORMATS are `format' strings for each column.
689 If CELL-FORMATS is a string, it's used for all columns.
690 If CELL-FORMATS is nil, `hydra-cell-format' is used for all columns."
692 (cond ((null cell-formats)
693 (make-list cols hydra-cell-format))
694 ((stringp cell-formats)
695 (make-list cols cell-formats))
702 (hydra--matrix names rows cols))
704 (mapconcat #'identity x " "))))
706 (defun hydra-reset-radios (names)
707 "Set varibles NAMES to their defaults.
708 NAMES should be defined by `defhydradio' or similar."
710 (set n (aref (get n 'range) 0))))
712 (defvar hydra-timeout-timer (timer-create)
713 "Timer for `hydra-timeout'.")
715 (defvar hydra-message-timer (timer-create)
716 "Timer for the hint.")
718 (defun hydra-idle-message (secs hint)
719 "In SECS seconds display HINT."
720 (cancel-timer hydra-message-timer)
721 (setq hydra-message-timer (timer-create))
722 (timer-set-time hydra-message-timer
723 (timer-relative-time (current-time) secs))
727 (when hydra-is-helpful
729 (lv-message (eval hint))
730 (message (eval hint))))
731 (cancel-timer hydra-message-timer)))
732 (timer-activate hydra-message-timer))
734 (defun hydra-timeout (secs &optional function)
735 "In SECS seconds call FUNCTION, then function `hydra-keyboard-quit'.
736 Cancel the previous `hydra-timeout'."
737 (cancel-timer hydra-timeout-timer)
738 (setq hydra-timeout-timer (timer-create))
739 (timer-set-time hydra-timeout-timer
740 (timer-relative-time (current-time) secs))
745 `(funcall ,function))
746 (hydra-keyboard-quit)))
747 (timer-activate hydra-timeout-timer))
751 (defmacro defhydra (name body &optional docstring &rest heads)
752 "Create a Hydra - a family of functions with prefix NAME.
754 NAME should be a symbol, it will be the prefix of all functions
759 (BODY-MAP BODY-KEY &rest BODY-PLIST)
761 DOCSTRING will be displayed in the echo area to identify the
762 Hydra. When DOCSTRING starts with a newline, special Ruby-style
763 substitution will be performed by `hydra--format'.
765 Functions are created on basis of HEADS, each of which has the
768 (KEY CMD &optional HINT &rest PLIST)
770 BODY-MAP is a keymap; `global-map' is used quite often. Each
771 function generated from HEADS will be bound in BODY-MAP to
772 BODY-KEY + KEY (both are strings passed to `kbd'), and will set
773 the transient map so that all following heads can be called
774 though KEY only. BODY-KEY can be an empty string.
776 CMD is a callable expression: either an interactive function
777 name, or an interactive lambda, or a single sexp (it will be
778 wrapped in an interactive lambda).
780 HINT is a short string that identifies its head. It will be
781 printed beside KEY in the echo erea if `hydra-is-helpful' is not
782 nil. If you don't even want the KEY to be printed, set HINT
785 The heads inherit their PLIST from BODY-PLIST and are allowed to
786 override some keys. The keys recognized are :exit and :bind.
789 - nil (default): this head will continue the Hydra state.
790 - t: this head will stop the Hydra state.
793 - nil: this head will not be bound in BODY-MAP.
794 - a lambda taking KEY and CMD used to bind a head.
796 It is possible to omit both BODY-MAP and BODY-KEY if you don't
797 want to bind anything. In that case, typically you will bind the
798 generated NAME/body command. This command is also the return
799 result of `defhydra'."
800 (declare (indent defun))
801 (cond ((stringp docstring))
802 ((and (consp docstring)
803 (memq (car docstring) '(hydra--table concat format)))
804 (setq docstring (concat "\n" (eval docstring))))
806 (setq heads (cons docstring heads))
807 (setq docstring "hydra")))
808 (when (keywordp (car body))
809 (setq body (cons nil (cons nil body))))
811 (let* ((keymap (copy-keymap hydra-base-map))
812 (keymap-name (intern (format "%S/keymap" name)))
813 (body-name (intern (format "%S/body" name)))
814 (body-key (cadr body))
815 (body-plist (cddr body))
816 (body-map (or (car body)
817 (plist-get body-plist :bind)))
818 (body-pre (plist-get body-plist :pre))
819 (body-body-pre (plist-get body-plist :body-pre))
820 (body-before-exit (or (plist-get body-plist :post)
821 (plist-get body-plist :before-exit)))
822 (body-after-exit (plist-get body-plist :after-exit))
823 (body-inherit (plist-get body-plist :inherit))
824 (body-foreign-keys (hydra--body-foreign-keys body))
825 (body-exit (hydra--body-exit body)))
826 (dolist (base body-inherit)
827 (setq heads (append heads (copy-sequence (eval base)))))
829 (let ((len (length h)))
831 (error "Each head should have at least two items: %S" h))
835 (hydra-plist-get-default body-plist :hint "")))
836 (setcdr (nthcdr 2 h) (list :exit body-exit)))
838 (let ((hint (cl-caddr h)))
839 (unless (or (null hint)
841 (setcdr (cdr h) (cons
842 (hydra-plist-get-default body-plist :hint "")
844 (let ((hint-and-plist (cddr h)))
845 (if (null (cdr hint-and-plist))
846 (setcdr hint-and-plist (list :exit body-exit))
847 (let* ((plist (cl-cdddr h))
848 (h-color (plist-get plist :color)))
851 (plist-put plist :exit
855 (cl-remf (cl-cdddr h) :color))
856 (let ((h-exit (hydra-plist-get-default plist :exit 'default)))
857 (plist-put plist :exit
858 (if (eq h-exit 'default)
861 (plist-put (cl-cdddr h) :cmd-name (hydra--head-name h name body))
862 (when (null (cadr h)) (plist-put (cl-cdddr h) :exit t)))
863 (let ((doc (hydra--doc body-key body-name heads))
864 (heads-nodup (hydra--delete-duplicates heads)))
867 (define-key keymap (kbd (car x))
868 (plist-get (cl-cdddr x) :cmd-name)))
870 (hydra--make-funcall body-pre)
871 (hydra--make-funcall body-body-pre)
872 (hydra--make-funcall body-before-exit)
873 (hydra--make-funcall body-after-exit)
874 (when (memq body-foreign-keys '(run warn))
877 (hydra--head-property h :exit))
880 "An %S Hydra must have at least one blue head in order to exit"
884 (set (defvar ,keymap-name
886 ,(format "Keymap for %S." name))
889 (set (defvar ,(intern (format "%S/heads" name))
891 ,(format "Heads for %S." name))
892 ',(mapcar (lambda (h)
893 (let ((j (copy-sequence h)))
894 (cl-remf (cl-cdddr j) :cmd-name)
900 (hydra--make-defun name body doc head keymap-name
905 ;; free up keymap prefix
906 ,@(unless (or (null body-key)
908 (hydra--callablep body-map))
909 `((unless (keymapp (lookup-key ,body-map (kbd ,body-key)))
910 (define-key ,body-map (kbd ,body-key) nil))))
915 (let ((name (hydra--head-property head :cmd-name)))
916 (when (and (cadr head)
917 (or body-key body-map))
918 (let ((bind (hydra--head-property head :bind body-map))
921 (vconcat (kbd body-key) (kbd (car head)))
923 (cond ((null bind) nil)
924 ((hydra--callablep bind)
925 `(funcall ,bind ,final-key (function ,name)))
928 (keymapp (symbol-value bind))
930 `(define-key ,bind ,final-key (function ,name)))
932 (error "Invalid :bind property `%S' for head %S" bind head)))))))
935 (defvar ,(intern (format "%S/hint" name)) nil
936 ,(format "Dynamic hint for %S." name))
937 ',(hydra--format name body docstring heads))
939 name body doc '(nil body)
941 (or body-body-pre body-pre) body-before-exit
942 '(setq prefix-arg current-prefix-arg)))))
945 (signal (car err) (cdr err))
946 (message "Error in defhydra %S: %s" name (cdr err)))
949 (defmacro defhydradio (name _body &rest heads)
950 "Create radios with prefix NAME.
951 _BODY specifies the options; there are none currently.
952 HEADS have the format:
954 (TOGGLE-NAME &optional VALUE DOC)
956 TOGGLE-NAME will be used along with NAME to generate a variable
957 name and a function that cycles it with the same name. VALUE
958 should be an array. The first element of VALUE will be used to
959 inialize the variable.
960 VALUE defaults to [nil t].
961 DOC defaults to TOGGLE-NAME split and capitalized."
962 (declare (indent defun))
966 (hydra--radio name h))
968 (defvar ,(intern (format "%S/names" name))
969 ',(mapcar (lambda (h) (intern (format "%S/%S" name (car h))))
972 (defmacro hydra-multipop (lst n)
973 "Return LST's first N elements while removing them."
974 `(if (<= (length ,lst) ,n)
979 (nthcdr (1- ,n) (prog1 ,lst (setq ,lst (nthcdr ,n ,lst))))
982 (defun hydra--radio (parent head)
983 "Generate a hydradio with PARENT from HEAD."
984 (let* ((name (car head))
985 (full-name (intern (format "%S/%S" parent name)))
987 (val (or (cl-caddr head) [nil t])))
988 `((defvar ,full-name ,(hydra--quote-maybe (aref val 0)) ,doc)
989 (put ',full-name 'range ,val)
991 (hydra--cycle-radio ',full-name)))))
993 (defun hydra--quote-maybe (x)
994 "Quote X if it's a symbol."
1002 (defun hydra--cycle-radio (sym)
1003 "Set SYM to the next value in its range."
1004 (let* ((val (symbol-value sym))
1005 (range (get sym 'range))
1008 (setq i (catch 'done
1010 (if (equal (aref range i) val)
1011 (throw 'done (1+ i))
1013 (error "Val not in range for %S" sym)))
1022 ;;; Local Variables:
1023 ;;; outline-regexp: ";;\\*+"
1026 ;;; hydra.el ends here