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 (defvar hydra-deactivate nil
92 "If a Hydra head sets this to t, exit the Hydra even if the
93 head wasn't designated for exiting.")
95 (defun hydra-set-transient-map (keymap on-exit &optional foreign-keys)
96 "Set KEYMAP to the highest priority.
98 Call ON-EXIT when the KEYMAP is deactivated.
100 FOREIGN-KEYS determines the deactivation behavior, when a command
101 that isn't in KEYMAP is called:
103 nil: deactivate KEYMAP and run the command.
104 run: keep KEYMAP and run the command.
105 warn: keep KEYMAP and issue a warning instead of running the command."
107 (hydra-keyboard-quit)
108 (setq hydra-curr-map keymap)
109 (setq hydra-curr-on-exit on-exit)
110 (setq hydra-curr-foreign-keys foreign-keys)
111 (add-hook 'pre-command-hook 'hydra--clearfun)
112 (internal-push-keymap keymap 'overriding-terminal-local-map)))
114 (defun hydra--clearfun ()
115 "Disable the current Hydra unless `this-command' is a head."
117 (memq this-command '(handle-switch-frame keyboard-quit))
118 (null overriding-terminal-local-map)
119 (not (or (eq this-command
120 (lookup-key hydra-curr-map (this-single-command-keys)))
121 (cl-case hydra-curr-foreign-keys
123 (setq this-command 'hydra-amaranth-warn))
129 (defvar hydra--ignore nil
130 "When non-nil, don't call `hydra-curr-on-exit'")
132 (defvar hydra--input-method-function nil
133 "Store overridden `input-method-function' here.")
135 (defun hydra-disable ()
136 "Disable the current Hydra."
137 (setq hydra-deactivate nil)
138 (remove-hook 'pre-command-hook 'hydra--clearfun)
139 (dolist (frame (frame-list))
140 (with-selected-frame frame
141 (when overriding-terminal-local-map
142 (internal-pop-keymap hydra-curr-map 'overriding-terminal-local-map)
143 (unless hydra--ignore
144 (when hydra--input-method-function
145 (setq input-method-function hydra--input-method-function)
146 (setq hydra--input-method-function nil))
147 (when hydra-curr-on-exit
148 (let ((on-exit hydra-curr-on-exit))
149 (setq hydra-curr-on-exit nil)
150 (funcall on-exit))))))))
152 (unless (fboundp 'internal-push-keymap)
153 (defun internal-push-keymap (keymap symbol)
154 (let ((map (symbol-value symbol)))
155 (unless (memq keymap map)
156 (unless (memq 'add-keymap-witness (symbol-value symbol))
157 (setq map (make-composed-keymap nil (symbol-value symbol)))
158 (push 'add-keymap-witness (cdr map))
160 (push keymap (cdr map))))))
162 (unless (fboundp 'internal-pop-keymap)
163 (defun internal-pop-keymap (keymap symbol)
164 (let ((map (symbol-value symbol)))
165 (when (memq keymap map)
166 (setf (cdr map) (delq keymap (cdr map))))
167 (let ((tail (cddr map)))
168 (and (or (null tail) (keymapp tail))
169 (eq 'add-keymap-witness (nth 1 map))
170 (set symbol tail))))))
172 (defun hydra-amaranth-warn ()
174 (message "An amaranth Hydra can only exit through a blue head"))
178 "Make bindings that stick around."
182 (defcustom hydra-is-helpful t
183 "When t, display a hint with possible bindings in the echo area."
187 (defcustom hydra-lv t
188 "When non-nil, `lv-message' (not `message') will be used to display hints."
191 (defcustom hydra-verbose nil
192 "When non-nil, hydra will issue some non essential style warnings."
195 (defcustom hydra-key-format-spec "%s"
196 "Default `format'-style specifier for _a_ syntax in docstrings.
197 When nil, you can specify your own at each location like this: _ 5a_.")
199 (defface hydra-face-red
200 '((t (:foreground "#FF0000" :bold t)))
201 "Red Hydra heads don't exit the Hydra.
202 Every other command exits the Hydra."
205 (defface hydra-face-blue
206 '((t (:foreground "#0000FF" :bold t)))
207 "Blue Hydra heads exit the Hydra.
208 Every other command exits as well.")
210 (defface hydra-face-amaranth
211 '((t (:foreground "#E52B50" :bold t)))
212 "Amaranth body has red heads and warns on intercepting non-heads.
213 Exitable only through a blue head.")
215 (defface hydra-face-pink
216 '((t (:foreground "#FF6EB4" :bold t)))
217 "Pink body has red heads and runs intercepted non-heads.
218 Exitable only through a blue head.")
220 (defface hydra-face-teal
221 '((t (:foreground "#367588" :bold t)))
222 "Teal body has blue heads and warns on intercepting non-heads.
223 Exitable only through a blue head.")
226 (defun hydra-add-font-lock ()
227 "Fontify `defhydra' statements."
228 (font-lock-add-keywords
230 '(("(\\(defhydra\\)\\_> +\\(.*?\\)\\_>"
231 (1 font-lock-keyword-face)
232 (2 font-lock-type-face))
233 ("(\\(defhydradio\\)\\_> +\\(.*?\\)\\_>"
234 (1 font-lock-keyword-face)
235 (2 font-lock-type-face)))))
237 ;;* Universal Argument
238 (defvar hydra-base-map
239 (let ((map (make-sparse-keymap)))
240 (define-key map [?\C-u] 'hydra--universal-argument)
241 (define-key map [?-] 'hydra--negative-argument)
242 (define-key map [?0] 'hydra--digit-argument)
243 (define-key map [?1] 'hydra--digit-argument)
244 (define-key map [?2] 'hydra--digit-argument)
245 (define-key map [?3] 'hydra--digit-argument)
246 (define-key map [?4] 'hydra--digit-argument)
247 (define-key map [?5] 'hydra--digit-argument)
248 (define-key map [?6] 'hydra--digit-argument)
249 (define-key map [?7] 'hydra--digit-argument)
250 (define-key map [?8] 'hydra--digit-argument)
251 (define-key map [?9] 'hydra--digit-argument)
252 (define-key map [kp-0] 'hydra--digit-argument)
253 (define-key map [kp-1] 'hydra--digit-argument)
254 (define-key map [kp-2] 'hydra--digit-argument)
255 (define-key map [kp-3] 'hydra--digit-argument)
256 (define-key map [kp-4] 'hydra--digit-argument)
257 (define-key map [kp-5] 'hydra--digit-argument)
258 (define-key map [kp-6] 'hydra--digit-argument)
259 (define-key map [kp-7] 'hydra--digit-argument)
260 (define-key map [kp-8] 'hydra--digit-argument)
261 (define-key map [kp-9] 'hydra--digit-argument)
262 (define-key map [kp-subtract] 'hydra--negative-argument)
264 "Keymap that all Hydras inherit. See `universal-argument-map'.")
266 (defun hydra--universal-argument (arg)
267 "Forward to (`universal-argument' ARG)."
269 (setq prefix-arg (if (consp arg)
270 (list (* 4 (car arg)))
275 (defun hydra--digit-argument (arg)
276 "Forward to (`digit-argument' ARG)."
278 (let* ((char (if (integerp last-command-event)
280 (get last-command-event 'ascii-character)))
281 (digit (- (logand char ?\177) ?0)))
282 (setq prefix-arg (cond ((integerp arg)
294 (defun hydra--negative-argument (arg)
295 "Forward to (`negative-argument' ARG)."
297 (setq prefix-arg (cond ((integerp arg) (- arg))
302 (defvar hydra-repeat--prefix-arg nil
303 "Prefix arg to use with `hydra-repeat'.")
305 (defvar hydra-repeat--command nil
306 "Command to use with `hydra-repeat'.")
308 (defun hydra-repeat (&optional arg)
309 "Repeat last command with last prefix arg.
310 When ARG is non-nil, use that instead."
313 (unless (string-match "hydra-repeat$" (symbol-name last-command))
314 (setq hydra-repeat--command last-command)
315 (setq hydra-repeat--prefix-arg last-prefix-arg))
316 (setq hydra-repeat--prefix-arg arg))
317 (setq current-prefix-arg hydra-repeat--prefix-arg)
318 (funcall hydra-repeat--command))
321 (defun hydra--callablep (x)
322 "Test if X is callable."
325 (memq (car x) '(function quote)))))
327 (defun hydra--make-callable (x)
328 "Generate a callable symbol from X.
329 If X is a function symbol or a lambda, return it. Otherwise, it
330 should be a single statement. Wrap it in an interactive lambda."
331 (if (or (symbolp x) (functionp x))
337 (defun hydra-plist-get-default (plist prop default)
338 "Extract a value from a property list.
339 PLIST is a property list, which is a list of the form
340 \(PROP1 VALUE1 PROP2 VALUE2...).
342 Return the value corresponding to PROP, or DEFAULT if PROP is not
343 one of the properties on the list."
344 (if (memq prop plist)
345 (plist-get plist prop)
348 (defun hydra--head-property (h prop &optional default)
349 "Return for Hydra head H the value of property PROP.
350 Return DEFAULT if PROP is not in H."
351 (hydra-plist-get-default (cl-cdddr h) prop default))
353 (defun hydra--body-foreign-keys (body)
354 "Return what BODY does with a non-head binding."
356 (plist-get (cddr body) :foreign-keys)
357 (let ((color (plist-get (cddr body) :color)))
359 ((amaranth teal) 'warn)
362 (defun hydra--body-exit (body)
363 "Return the exit behavior of BODY."
365 (plist-get (cddr body) :exit)
366 (let ((color (plist-get (cddr body) :color)))
371 (defun hydra-default-pre ()
372 "Default setup that happens in each head before :pre."
373 (when (eq input-method-function 'key-chord-input-method)
374 (unless hydra--input-method-function
375 (setq hydra--input-method-function input-method-function)
376 (setq input-method-function nil))))
378 (defvar hydra-timeout-timer (timer-create)
379 "Timer for `hydra-timeout'.")
381 (defvar hydra-message-timer (timer-create)
382 "Timer for the hint.")
384 (defvar hydra--work-around-dedicated t
385 "When non-nil, assume there's no bug in `pop-to-buffer'
386 selecting a dedicated window.")
388 (defun hydra-keyboard-quit ()
389 "Quitting function similar to `keyboard-quit'."
392 (cancel-timer hydra-timeout-timer)
393 (cancel-timer hydra-message-timer)
394 (unless (and hydra--ignore
395 (null hydra--work-around-dedicated))
401 (defun hydra--hint (body heads)
402 "Generate a hint for the echo area.
403 BODY, and HEADS are parameters to `defhydra'."
406 (let ((val (assoc (cadr h) alist))
407 (pstr (hydra-fontify-head h body)))
408 (unless (null (cl-caddr h))
411 (concat (cadr val) " " pstr))
414 (cons pstr (cl-caddr h)))
419 (if (> (length (cdr x)) 0)
420 (concat "[%s]: " (cdr x))
423 (nreverse (mapcar #'cdr alist))
426 (defvar hydra-fontify-head-function nil
427 "Possible replacement for `hydra-fontify-head-default'.")
429 (defun hydra-fontify-head-default (head body)
430 "Produce a pretty string from HEAD and BODY.
431 HEAD's binding is returned as a string with a colored face."
432 (let* ((foreign-keys (hydra--body-foreign-keys body))
433 (head-exit (hydra--head-property head :exit))
436 (if (eq foreign-keys 'warn)
439 (cl-case foreign-keys
443 (when (and (null (cadr head))
444 (not (eq head-color 'blue)))
445 (hydra--complain "nil cmd can only be blue"))
446 (propertize (car head) 'face
448 (blue 'hydra-face-blue)
449 (red 'hydra-face-red)
450 (amaranth 'hydra-face-amaranth)
451 (pink 'hydra-face-pink)
452 (teal 'hydra-face-teal)
453 (t (error "Unknown color for %S" head))))))
455 (defun hydra-fontify-head-greyscale (head _body)
456 "Produce a pretty string from HEAD and BODY.
457 HEAD's binding is returned as a string wrapped with [] or {}."
459 (if (hydra--head-property head :exit)
463 (defun hydra-fontify-head (head body)
464 "Produce a pretty string from HEAD and BODY."
465 (funcall (or hydra-fontify-head-function 'hydra-fontify-head-default)
468 (defun hydra--format (_name body docstring heads)
469 "Generate a `format' statement from STR.
470 \"%`...\" expressions are extracted into \"%S\".
471 _NAME, BODY, DOCSTRING and HEADS are parameters of `defhydra'.
472 The expressions can be auto-expanded according to NAME."
473 (setq docstring (replace-regexp-in-string "\\^" "" docstring))
474 (let ((rest (hydra--hint body heads))
480 "\\(?:%\\( ?-?[0-9]*s?\\)\\(`[a-z-A-Z/0-9]+\\|(\\)\\)\\|\\(?:_\\( ?-?[0-9]*?\\)\\([-[:alnum:] ~.,;:/|?<>={}*+#]+?\\)_\\)"
482 (cond ((eq ?_ (aref (match-string 0 docstring) 0))
483 (let* ((key (match-string 4 docstring))
484 (head (assoc key heads)))
487 (push (hydra-fontify-head head body) varlist)
491 hydra-key-format-spec
492 (concat "%" (match-string 3 docstring) "s"))
494 (error "Unrecognized key: _%s_" key))))
497 (let* ((varp (if (eq ?` (aref (match-string 2 docstring) 0)) 1 0))
498 (spec (match-string 1 docstring))
499 (lspec (length spec)))
502 (insert (substring docstring (+ 1 start varp
504 (goto-char (point-min))
505 (push (read (current-buffer)) varlist)
506 (- (point) (point-min))))
507 (when (or (zerop lspec)
508 (/= (aref spec (1- (length spec))) ?s))
509 (setq spec (concat spec "S")))
512 (substring docstring 0 start)
514 (substring docstring (+ start offset 1 lspec varp))))))))
515 (if (eq ?\n (aref docstring 0))
516 `(concat (format ,(substring docstring 1) ,@(nreverse varlist))
518 `(format ,(concat docstring ": " rest ".")))))
520 (defun hydra--complain (format-string &rest args)
521 "Forward to (`message' FORMAT-STRING ARGS) unless `hydra-verbose' is nil."
523 (apply #'warn format-string args)))
525 (defun hydra--doc (body-key body-name heads)
526 "Generate a part of Hydra docstring.
527 BODY-KEY is the body key binding.
528 BODY-NAME is the symbol that identifies the Hydra.
529 HEADS is a list of heads."
531 "Create a hydra with %s body and the heads:\n\n%s\n\n%s"
533 (format "a \"%s\"" body-key)
537 (format "\"%s\": `%S'" (car x) (cadr x)))
539 (format "The body can be accessed via `%S'." body-name)))
541 (defun hydra--call-interactively (cmd name)
542 "Generate a `call-interactively' statement for CMD.
543 Set `this-command' to NAME."
544 (if (and (symbolp name)
545 (not (memq name '(nil body))))
547 (setq this-command ',name)
548 (call-interactively #',cmd))
549 `(call-interactively #',cmd)))
551 (defun hydra--make-defun (name body doc head
552 keymap body-pre body-before-exit
553 &optional body-after-exit)
554 "Make a defun wrapper, using NAME, BODY, DOC, HEAD, and KEYMAP.
555 NAME and BODY are the arguments to `defhydra'.
556 DOC was generated with `hydra--doc'.
557 HEAD is one of the HEADS passed to `defhydra'.
558 BODY-PRE is added to the start of the wrapper.
559 BODY-BEFORE-EXIT will be called before the hydra quits.
560 BODY-AFTER-EXIT is added to the end of the wrapper."
561 (let ((name (hydra--head-name head name))
562 (cmd (when (car head)
563 (hydra--make-callable
566 (format "%s\n\nCall the head: `%S'." doc (cadr head))
568 (hint (intern (format "%S/hint" name)))
569 (body-foreign-keys (hydra--body-foreign-keys body))
570 (body-timeout (plist-get body :timeout))
571 (body-idle (plist-get body :idle)))
576 ,@(when body-pre (list body-pre))
577 ,@(if (hydra--head-property head :exit)
578 `((hydra-keyboard-quit)
579 ,@(if body-after-exit
582 (hydra--call-interactively cmd (cadr head)))
585 `(,(hydra--call-interactively cmd (cadr head))))))
588 `((let ((hydra--ignore ,(not (eq (cadr head) 'body))))
589 (hydra-keyboard-quit))
592 ,(hydra--call-interactively cmd (cadr head))
597 ,(if (and body-idle (eq (cadr head) 'body))
598 `(hydra-idle-message ,body-idle ,hint)
599 `(when hydra-is-helpful
601 (lv-message (eval ,hint))
602 (message (eval ,hint)))))
603 (hydra-set-transient-map
605 (lambda () (hydra-keyboard-quit) ,body-before-exit)
606 ,(when body-foreign-keys
607 (list 'quote body-foreign-keys)))
610 `(hydra-timeout ,body-timeout))))))))
612 (defmacro hydra--make-funcall (sym)
613 "Transform SYM into a `funcall' to call it."
614 `(when (and ,sym (symbolp ,sym))
615 (setq ,sym `(funcall #',,sym))))
617 (defun hydra--head-name (h name)
618 "Return the symbol for head H of hydra with NAME."
619 (let ((str (format "%S/%s" name
620 (if (symbolp (cadr h))
622 (concat "lambda-" (car h))))))
623 (when (and (hydra--head-property h :exit)
624 (not (memq (cadr h) '(body nil))))
625 (setq str (concat str "-and-exit")))
628 (defun hydra--delete-duplicates (heads)
629 "Return HEADS without entries that have the same CMD part.
630 In duplicate HEADS, :cmd-name is modified to whatever they duplicate."
631 (let ((ali '(((hydra-repeat . nil) . hydra-repeat)))
634 (if (setq entry (assoc (cons (cadr h)
635 (hydra--head-property h :exit))
637 (setf (cl-cdddr h) (plist-put (cl-cdddr h) :cmd-name (cdr entry)))
638 (push (cons (cons (cadr h)
639 (hydra--head-property h :exit))
640 (plist-get (cl-cdddr h) :cmd-name))
645 (defun hydra--pad (lst n)
646 "Pad LST with nil until length N."
647 (let ((len (length lst)))
650 (append lst (make-list (- n len) nil)))))
652 (defmacro hydra-multipop (lst n)
653 "Return LST's first N elements while removing them."
654 `(if (<= (length ,lst) ,n)
659 (nthcdr (1- ,n) (prog1 ,lst (setq ,lst (nthcdr ,n ,lst))))
662 (defun hydra--matrix (lst rows cols)
663 "Create a matrix from elements of LST.
664 The matrix size is ROWS times COLS."
665 (let ((ls (copy-sequence lst))
668 (push (hydra--pad (hydra-multipop ls rows) rows) res))
671 (defun hydra--cell (fstr names)
672 "Format a rectangular cell based on FSTR and NAMES.
673 FSTR is a format-style string with two string inputs: one for the
674 doc and one for the symbol name.
675 NAMES is a list of variables."
676 (let ((len (cl-reduce
677 (lambda (acc it) (max (length (symbol-name it)) acc))
684 (documentation-property sym 'variable-documentation)
685 (let ((name (symbol-name sym)))
686 (concat name (make-string (- len (length name)) ?^)))
692 (defun hydra--vconcat (strs &optional joiner)
693 "Glue STRS vertically. They must be the same height.
694 JOINER is a function similar to `concat'."
695 (setq joiner (or joiner #'concat))
698 (if (string-match " +$" s)
699 (replace-match "" nil nil s)
701 (apply #'cl-mapcar joiner
703 (lambda (s) (split-string s "\n"))
707 (defcustom hydra-cell-format "% -20s %% -8`%s"
708 "The default format for docstring cells."
711 (defun hydra--table (names rows cols &optional cell-formats)
712 "Format a `format'-style table from variables in NAMES.
713 The size of the table is ROWS times COLS.
714 CELL-FORMATS are `format' strings for each column.
715 If CELL-FORMATS is a string, it's used for all columns.
716 If CELL-FORMATS is nil, `hydra-cell-format' is used for all columns."
718 (cond ((null cell-formats)
719 (make-list cols hydra-cell-format))
720 ((stringp cell-formats)
721 (make-list cols cell-formats))
728 (hydra--matrix names rows cols))
730 (mapconcat #'identity x " "))))
732 (defun hydra-reset-radios (names)
733 "Set varibles NAMES to their defaults.
734 NAMES should be defined by `defhydradio' or similar."
736 (set n (aref (get n 'range) 0))))
738 (defun hydra-idle-message (secs hint)
739 "In SECS seconds display HINT."
740 (cancel-timer hydra-message-timer)
741 (setq hydra-message-timer (timer-create))
742 (timer-set-time hydra-message-timer
743 (timer-relative-time (current-time) secs))
747 (when hydra-is-helpful
749 (lv-message (eval hint))
750 (message (eval hint))))
751 (cancel-timer hydra-message-timer)))
752 (timer-activate hydra-message-timer))
754 (defun hydra-timeout (secs &optional function)
755 "In SECS seconds call FUNCTION, then function `hydra-keyboard-quit'.
756 Cancel the previous `hydra-timeout'."
757 (cancel-timer hydra-timeout-timer)
758 (setq hydra-timeout-timer (timer-create))
759 (timer-set-time hydra-timeout-timer
760 (timer-relative-time (current-time) secs))
765 `(funcall ,function))
766 (hydra-keyboard-quit)))
767 (timer-activate hydra-timeout-timer))
771 (defmacro defhydra (name body &optional docstring &rest heads)
772 "Create a Hydra - a family of functions with prefix NAME.
774 NAME should be a symbol, it will be the prefix of all functions
779 (BODY-MAP BODY-KEY &rest BODY-PLIST)
781 DOCSTRING will be displayed in the echo area to identify the
782 Hydra. When DOCSTRING starts with a newline, special Ruby-style
783 substitution will be performed by `hydra--format'.
785 Functions are created on basis of HEADS, each of which has the
788 (KEY CMD &optional HINT &rest PLIST)
790 BODY-MAP is a keymap; `global-map' is used quite often. Each
791 function generated from HEADS will be bound in BODY-MAP to
792 BODY-KEY + KEY (both are strings passed to `kbd'), and will set
793 the transient map so that all following heads can be called
794 though KEY only. BODY-KEY can be an empty string.
796 CMD is a callable expression: either an interactive function
797 name, or an interactive lambda, or a single sexp (it will be
798 wrapped in an interactive lambda).
800 HINT is a short string that identifies its head. It will be
801 printed beside KEY in the echo erea if `hydra-is-helpful' is not
802 nil. If you don't even want the KEY to be printed, set HINT
805 The heads inherit their PLIST from BODY-PLIST and are allowed to
806 override some keys. The keys recognized are :exit and :bind.
809 - nil (default): this head will continue the Hydra state.
810 - t: this head will stop the Hydra state.
813 - nil: this head will not be bound in BODY-MAP.
814 - a lambda taking KEY and CMD used to bind a head.
816 It is possible to omit both BODY-MAP and BODY-KEY if you don't
817 want to bind anything. In that case, typically you will bind the
818 generated NAME/body command. This command is also the return
819 result of `defhydra'."
820 (declare (indent defun))
821 (cond ((stringp docstring))
822 ((and (consp docstring)
823 (memq (car docstring) '(hydra--table concat format)))
824 (setq docstring (concat "\n" (eval docstring))))
826 (setq heads (cons docstring heads))
827 (setq docstring "hydra")))
828 (when (keywordp (car body))
829 (setq body (cons nil (cons nil body))))
830 (condition-case-unless-debug err
831 (let* ((keymap (copy-keymap hydra-base-map))
832 (keymap-name (intern (format "%S/keymap" name)))
833 (body-name (intern (format "%S/body" name)))
834 (body-key (cadr body))
835 (body-plist (cddr body))
836 (body-map (or (car body)
837 (plist-get body-plist :bind)))
838 (body-pre (plist-get body-plist :pre))
839 (body-body-pre (plist-get body-plist :body-pre))
840 (body-before-exit (or (plist-get body-plist :post)
841 (plist-get body-plist :before-exit)))
842 (body-after-exit (plist-get body-plist :after-exit))
843 (body-inherit (plist-get body-plist :inherit))
844 (body-foreign-keys (hydra--body-foreign-keys body))
845 (body-exit (hydra--body-exit body)))
846 (dolist (base body-inherit)
847 (setq heads (append heads (copy-sequence (eval base)))))
849 (let ((len (length h)))
851 (error "Each head should have at least two items: %S" h))
855 (hydra-plist-get-default body-plist :hint "")))
856 (setcdr (nthcdr 2 h) (list :exit body-exit)))
858 (let ((hint (cl-caddr h)))
859 (unless (or (null hint)
861 (setcdr (cdr h) (cons
862 (hydra-plist-get-default body-plist :hint "")
864 (let ((hint-and-plist (cddr h)))
865 (if (null (cdr hint-and-plist))
866 (setcdr hint-and-plist (list :exit body-exit))
867 (let* ((plist (cl-cdddr h))
868 (h-color (plist-get plist :color)))
871 (plist-put plist :exit
875 (cl-remf (cl-cdddr h) :color))
876 (let ((h-exit (hydra-plist-get-default plist :exit 'default)))
877 (plist-put plist :exit
878 (if (eq h-exit 'default)
881 (plist-put (cl-cdddr h) :cmd-name (hydra--head-name h name))
882 (when (null (cadr h)) (plist-put (cl-cdddr h) :exit t)))
883 (let ((doc (hydra--doc body-key body-name heads))
884 (heads-nodup (hydra--delete-duplicates heads)))
887 (define-key keymap (kbd (car x))
888 (plist-get (cl-cdddr x) :cmd-name)))
890 (hydra--make-funcall body-pre)
891 (hydra--make-funcall body-body-pre)
892 (hydra--make-funcall body-before-exit)
893 (hydra--make-funcall body-after-exit)
894 (when (memq body-foreign-keys '(run warn))
897 (hydra--head-property h :exit))
900 "An %S Hydra must have at least one blue head in order to exit"
904 (set (defvar ,keymap-name
906 ,(format "Keymap for %S." name))
909 (set (defvar ,(intern (format "%S/heads" name))
911 ,(format "Heads for %S." name))
912 ',(mapcar (lambda (h)
913 (let ((j (copy-sequence h)))
914 (cl-remf (cl-cdddr j) :cmd-name)
918 (defvar ,(intern (format "%S/hint" name)) nil
919 ,(format "Dynamic hint for %S." name))
920 ',(hydra--format name body docstring heads))
924 (hydra--make-defun name body doc head keymap-name
929 ;; free up keymap prefix
930 ,@(unless (or (null body-key)
932 (hydra--callablep body-map))
933 `((unless (keymapp (lookup-key ,body-map (kbd ,body-key)))
934 (define-key ,body-map (kbd ,body-key) nil))))
939 (let ((name (hydra--head-property head :cmd-name)))
940 (when (and (cadr head)
941 (or body-key body-map))
942 (let ((bind (hydra--head-property head :bind body-map))
945 (vconcat (kbd body-key) (kbd (car head)))
947 (cond ((null bind) nil)
948 ((hydra--callablep bind)
949 `(funcall ,bind ,final-key (function ,name)))
952 (keymapp (symbol-value bind))
954 `(define-key ,bind ,final-key (function ,name)))
956 (error "Invalid :bind property `%S' for head %S" bind head)))))))
959 name body doc '(nil body)
961 (or body-body-pre body-pre) body-before-exit
962 '(setq prefix-arg current-prefix-arg)))))
964 (message "Error in defhydra %S: %s" name (cdr err))
967 (defmacro defhydradio (name _body &rest heads)
968 "Create radios with prefix NAME.
969 _BODY specifies the options; there are none currently.
970 HEADS have the format:
972 (TOGGLE-NAME &optional VALUE DOC)
974 TOGGLE-NAME will be used along with NAME to generate a variable
975 name and a function that cycles it with the same name. VALUE
976 should be an array. The first element of VALUE will be used to
977 inialize the variable.
978 VALUE defaults to [nil t].
979 DOC defaults to TOGGLE-NAME split and capitalized."
980 (declare (indent defun))
984 (hydra--radio name h))
986 (defvar ,(intern (format "%S/names" name))
987 ',(mapcar (lambda (h) (intern (format "%S/%S" name (car h))))
990 (defun hydra--radio (parent head)
991 "Generate a hydradio with PARENT from HEAD."
992 (let* ((name (car head))
993 (full-name (intern (format "%S/%S" parent name)))
995 (val (or (cl-caddr head) [nil t])))
996 `((defvar ,full-name ,(hydra--quote-maybe (aref val 0)) ,doc)
997 (put ',full-name 'range ,val)
999 (hydra--cycle-radio ',full-name)))))
1001 (defun hydra--quote-maybe (x)
1002 "Quote X if it's a symbol."
1010 (defun hydra--cycle-radio (sym)
1011 "Set SYM to the next value in its range."
1012 (let* ((val (symbol-value sym))
1013 (range (get sym 'range))
1016 (setq i (catch 'done
1018 (if (equal (aref range i) val)
1019 (throw 'done (1+ i))
1021 (error "Val not in range for %S" sym)))
1031 ;; outline-regexp: ";;\\([;*]+ [^\s\t\n]\\|###autoload\\)\\|("
1032 ;; indent-tabs-mode: nil
1035 ;;; hydra.el ends here