]> code.delx.au - gnu-emacs-elpa/blob - hydra.el
Quit Hydra for `handle-switch-frame'
[gnu-emacs-elpa] / hydra.el
1 ;;; hydra.el --- Make bindings that stick around. -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2015 Free Software Foundation, Inc.
4
5 ;; Author: Oleh Krehel <ohwoeowho@gmail.com>
6 ;; Maintainer: Oleh Krehel <ohwoeowho@gmail.com>
7 ;; URL: https://github.com/abo-abo/hydra
8 ;; Version: 0.12.1
9 ;; Keywords: bindings
10 ;; Package-Requires: ((cl-lib "0.5"))
11
12 ;; This file is part of GNU Emacs.
13
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.
18
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.
23
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/>.
26
27 ;;; Commentary:
28 ;;
29 ;; This package can be used to tie related commands into a family of
30 ;; short bindings with a common prefix - a Hydra.
31 ;;
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.
39 ;;
40 ;; Here's an example Hydra, bound in the global map (you can use any
41 ;; keymap in place of `global-map'):
42 ;;
43 ;; (defhydra hydra-zoom (global-map "<f2>")
44 ;; "zoom"
45 ;; ("g" text-scale-increase "in")
46 ;; ("l" text-scale-decrease "out"))
47 ;;
48 ;; It allows to start a command chain either like this:
49 ;; "<f2> gg4ll5g", or "<f2> lgllg".
50 ;;
51 ;; Here's another approach, when you just want a "callable keymap":
52 ;;
53 ;; (defhydra hydra-toggle (:color blue)
54 ;; "toggle"
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"))
61 ;;
62 ;; This binds nothing so far, but if you follow up with:
63 ;;
64 ;; (global-set-key (kbd "C-c C-v") 'hydra-toggle/body)
65 ;;
66 ;; you will have bound "C-c C-v a", "C-c C-v d" etc.
67 ;;
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.
71 ;;
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.
76
77 ;;; Code:
78 ;;* Requires
79 (require 'cl-lib)
80 (require 'lv)
81
82 (defvar hydra-curr-map nil
83 "The keymap of the current Hydra called.")
84
85 (defvar hydra-curr-on-exit nil
86 "The on-exit predicate for the current Hydra.")
87
88 (defvar hydra-curr-foreign-keys nil
89 "The current :foreign-keys behavior.")
90
91 (defun hydra-set-transient-map (keymap on-exit &optional foreign-keys)
92 "Set KEYMAP to the highest priority.
93
94 Call ON-EXIT when the KEYMAP is deactivated.
95
96 FOREIGN-KEYS determines the deactivation behavior, when a command
97 that isn't in KEYMAP is called:
98
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))
107
108 (defun hydra--clearfun ()
109 "Disable the current Hydra unless `this-command' is a head."
110 (if (eq this-command 'handle-switch-frame)
111 (hydra-disable)
112 (unless (eq this-command
113 (lookup-key hydra-curr-map (this-command-keys-vector)))
114 (unless (cl-case hydra-curr-foreign-keys
115 (warn
116 (setq this-command 'hydra-amaranth-warn))
117 (run
118 t)
119 (t nil))
120 (hydra-disable)))))
121
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)
129 (funcall on-exit))))
130
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))
138 (set symbol map))
139 (push keymap (cdr map))))))
140
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))))))
150
151 (defun hydra-amaranth-warn ()
152 (interactive)
153 (message "An amaranth Hydra can only exit through a blue head"))
154
155 ;;* Customize
156 (defgroup hydra nil
157 "Make bindings that stick around."
158 :group 'bindings
159 :prefix "hydra-")
160
161 (defcustom hydra-is-helpful t
162 "When t, display a hint with possible bindings in the echo area."
163 :type 'boolean
164 :group 'hydra)
165
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.")
170
171 (defcustom hydra-lv t
172 "When non-nil, `lv-message' (not `message') will be used to display hints."
173 :type 'boolean)
174
175 (defcustom hydra-verbose nil
176 "When non-nil, hydra will issue some non essential style warnings."
177 :type 'boolean)
178
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_.")
182
183 (defface hydra-face-red
184 '((t (:foreground "#FF0000" :bold t)))
185 "Red Hydra heads will persist indefinitely."
186 :group 'hydra)
187
188 (defface hydra-face-blue
189 '((t (:foreground "#0000FF" :bold t)))
190 "Blue Hydra heads will vanquish the Hydra.")
191
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.")
196
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.")
201
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.")
206
207 ;;* Fontification
208 (defun hydra-add-font-lock ()
209 "Fontify `defhydra' statements."
210 (font-lock-add-keywords
211 'emacs-lisp-mode
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)))))
218
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)
245 map)
246 "Keymap that all Hydras inherit. See `universal-argument-map'.")
247
248 (defun hydra--universal-argument (arg)
249 "Forward to (`universal-argument' ARG)."
250 (interactive "P")
251 (setq prefix-arg (if (consp arg)
252 (list (* 4 (car arg)))
253 (if (eq arg '-)
254 (list -4)
255 '(4)))))
256
257 (defun hydra--digit-argument (arg)
258 "Forward to (`digit-argument' ARG)."
259 (interactive "P")
260 (let ((universal-argument-map
261 (if (fboundp 'universal-argument--mode)
262 hydra-curr-map
263 universal-argument-map)))
264 (digit-argument arg)))
265
266 (defun hydra--negative-argument (arg)
267 "Forward to (`negative-argument' ARG)."
268 (interactive "P")
269 (let ((universal-argument-map hydra-curr-map))
270 (negative-argument arg)))
271
272 ;;* Repeat
273 (defvar hydra-repeat--prefix-arg nil
274 "Prefix arg to use with `hydra-repeat'.")
275
276 (defvar hydra-repeat--command nil
277 "Command to use with `hydra-repeat'.")
278
279 (defun hydra-repeat (&optional arg)
280 "Repeat last command with last prefix arg.
281 When ARG is non-nil, use that instead."
282 (interactive "p")
283 (if (eq arg 1)
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))
290
291 ;;* Misc internals
292 (defun hydra--callablep (x)
293 "Test if X is callable."
294 (or (functionp x)
295 (and (consp x)
296 (memq (car x) '(function quote)))))
297
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))
303 x
304 `(lambda ()
305 (interactive)
306 ,x)))
307
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...).
312
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)
317 default))
318
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))
323
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))
329 (head-color
330 (cond ((eq exit 'default)
331 (cl-case color
332 (blue 'blue)
333 (red 'red)
334 (t
335 (unless (null color)
336 (error "Use only :blue or :red for heads: %S" h)))))
337 ((null exit)
338 (if color
339 (error "Don't mix :color and :exit - they are aliases: %S" h)
340 (cl-case foreign-keys
341 (run 'pink)
342 (warn 'amaranth)
343 (t 'red))))
344 ((eq exit t)
345 (if color
346 (error "Don't mix :color and :exit - they are aliases: %S" h)
347 'blue))
348 (t
349 (error "Unknown :exit %S" exit)))))
350 (cond ((null (cadr h))
351 (when head-color
352 (hydra--complain
353 "Doubly specified blue head - nil cmd is already blue: %S" h))
354 'blue)
355 ((null head-color)
356 (hydra--body-color body))
357 ((null foreign-keys)
358 head-color)
359 ((eq foreign-keys 'run)
360 (if (eq head-color 'red)
361 'pink
362 'blue))
363 ((eq foreign-keys 'warn)
364 (if (memq head-color '(red amaranth))
365 'amaranth
366 'teal))
367 (t
368 (error "Unexpected %S %S" h body)))))
369
370 (defun hydra--body-foreign-keys (body)
371 "Return what BODY does with a non-head binding."
372 (or
373 (plist-get (cddr body) :foreign-keys)
374 (let ((color (plist-get (cddr body) :color)))
375 (cl-case color
376 ((amaranth teal) 'warn)
377 (pink 'run)))))
378
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)
388 (exit 'blue)
389 (color color)
390 (t 'red))))
391
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))))
401
402 (defvar hydra--input-method-function nil
403 "Store overridden `input-method-function' here.")
404
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))))
411
412 (defun hydra-keyboard-quit ()
413 "Quitting function similar to `keyboard-quit'."
414 (interactive)
415 (hydra-disable)
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))
420 (if hydra-lv
421 (when (window-live-p lv-wnd)
422 (let ((buf (window-buffer lv-wnd)))
423 (delete-window lv-wnd)
424 (kill-buffer buf)))
425 (message ""))
426 nil)
427
428 (defun hydra--hint (body heads)
429 "Generate a hint for the echo area.
430 BODY, and HEADS are parameters to `defhydra'."
431 (let (alist)
432 (dolist (h heads)
433 (let ((val (assoc (cadr h) alist))
434 (pstr (hydra-fontify-head h body)))
435 (unless (null (cl-caddr h))
436 (if val
437 (setf (cadr val)
438 (concat (cadr val) " " pstr))
439 (push
440 (cons (cadr h)
441 (cons pstr (cl-caddr h)))
442 alist)))))
443 (mapconcat
444 (lambda (x)
445 (format
446 (if (> (length (cdr x)) 0)
447 (concat "[%s]: " (cdr x))
448 "%s")
449 (car x)))
450 (nreverse (mapcar #'cdr alist))
451 ", ")))
452
453 (defvar hydra-fontify-head-function nil
454 "Possible replacement for `hydra-fontify-head-default'.")
455
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)))
460
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)))
465 (format
466 (if (eq color 'blue)
467 "[%s]"
468 "{%s}") (car head))))
469
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)
473 head body))
474
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))
482 (start 0)
483 varlist
484 offset)
485 (while (setq start
486 (string-match
487 "\\(?:%\\( ?-?[0-9]*s?\\)\\(`[a-z-A-Z/0-9]+\\|(\\)\\)\\|\\(?:_\\( ?-?[0-9]*\\)\\([a-z-A-Z~.,;:0-9/|?<>={}*+#]+\\)_\\)"
488 docstring start))
489 (cond ((eq ?_ (aref (match-string 0 docstring) 0))
490 (let* ((key (match-string 4 docstring))
491 (head (assoc key heads)))
492 (if head
493 (progn
494 (push (hydra-fontify-head head body) varlist)
495 (setq docstring
496 (replace-match
497 (or
498 hydra-key-format-spec
499 (concat "%" (match-string 3 docstring) "s"))
500 t nil docstring)))
501 (error "Unrecognized key: _%s_" key))))
502
503 (t
504 (let* ((varp (if (eq ?` (aref (match-string 2 docstring) 0)) 1 0))
505 (spec (match-string 1 docstring))
506 (lspec (length spec)))
507 (setq offset
508 (with-temp-buffer
509 (insert (substring docstring (+ 1 start varp
510 (length spec))))
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")))
517 (setq docstring
518 (concat
519 (substring docstring 0 start)
520 "%" spec
521 (substring docstring (+ start offset 1 lspec varp))))))))
522 (if (eq ?\n (aref docstring 0))
523 `(concat (format ,(substring docstring 1) ,@(nreverse varlist))
524 ,rest)
525 `(format ,(concat docstring ": " rest ".")))))
526
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)))
532 `(if hydra-lv
533 (lv-message ,format-expr)
534 (message ,format-expr))))
535
536 (defun hydra--complain (format-string &rest args)
537 "Forward to (`message' FORMAT-STRING ARGS) unless `hydra-verbose' is nil."
538 (when hydra-verbose
539 (apply #'warn format-string args)))
540
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."
546 (format
547 "Create a hydra with %s body and the heads:\n\n%s\n\n%s"
548 (if body-key
549 (format "a \"%s\"" body-key)
550 "no")
551 (mapconcat
552 (lambda (x)
553 (format "\"%s\": `%S'" (car x) (cadr x)))
554 heads ",\n")
555 (format "The body can be accessed via `%S'." body-name)))
556
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
568 (cadr head))))
569 (color (when (car head)
570 (hydra--head-color head body)))
571 (doc (if (car head)
572 (format "%s\n\nCall the head: `%S'." doc (cadr head))
573 doc))
574 (hint (intern (format "%S/hint" name)))
575 (body-color (hydra--body-color body))
576 (body-timeout (plist-get body :timeout)))
577 `(defun ,name ()
578 ,doc
579 (interactive)
580 (hydra-default-pre)
581 ,@(when body-pre (list body-pre))
582 ,@(if (memq color '(blue teal))
583 `((hydra-keyboard-quit)
584 ,(when cmd `(call-interactively #',cmd))
585 ,body-post)
586 (delq
587 nil
588 `(,(when cmd
589 `(condition-case err
590 (call-interactively #',cmd)
591 ((quit error)
592 (message "%S" err)
593 (unless hydra-lv
594 (sit-for 0.8)))))
595 (when hydra-is-helpful
596 (,hint))
597 (hydra-set-transient-map
598 ,keymap
599 (lambda () (hydra-keyboard-quit) ,body-post)
600 ,(cond
601 ((memq body-color '(amaranth teal))
602 ''warn)
603 ((eq body-color 'pink)
604 ''run)
605 (t
606 nil)))
607 ,(or other-post
608 (when body-timeout
609 `(hydra-timeout
610 ,body-timeout
611 ,(when body-post
612 (hydra--make-callable body-post)))))))))))
613
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))))
618
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))
623 (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")))
628 (intern str)))
629
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)))
634 res entry)
635 (dolist (h heads)
636 (if (setq entry (assoc (cons (cadr h)
637 (hydra--head-color h '(nil nil)))
638 ali))
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))
643 ali)
644 (push h res)))
645 (nreverse res)))
646
647 (defun hydra--pad (lst n)
648 "Pad LST with nil until length N."
649 (let ((len (length lst)))
650 (if (= len n)
651 lst
652 (append lst (make-list (- n len) nil)))))
653
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))
658 res)
659 (dotimes (_c cols)
660 (push (hydra--pad (hydra-multipop ls rows) rows) res))
661 (nreverse res)))
662
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))
670 names
671 :initial-value 0)))
672 (mapconcat
673 (lambda (sym)
674 (if sym
675 (format fstr
676 (documentation-property sym 'variable-documentation)
677 (let ((name (symbol-name sym)))
678 (concat name (make-string (- len (length name)) ?^)))
679 sym)
680 ""))
681 names
682 "\n")))
683
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))
688 (mapconcat
689 (lambda (s)
690 (if (string-match " +$" s)
691 (replace-match "" nil nil s)
692 s))
693 (apply #'cl-mapcar joiner
694 (mapcar
695 (lambda (s) (split-string s "\n"))
696 strs))
697 "\n"))
698
699 (defcustom hydra-cell-format "% -20s %% -8`%s"
700 "The default format for docstring cells."
701 :type 'string)
702
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."
709 (setq cell-formats
710 (cond ((null cell-formats)
711 (make-list cols hydra-cell-format))
712 ((stringp cell-formats)
713 (make-list cols cell-formats))
714 (t
715 cell-formats)))
716 (hydra--vconcat
717 (cl-mapcar
718 #'hydra--cell
719 cell-formats
720 (hydra--matrix names rows cols))
721 (lambda (&rest x)
722 (mapconcat #'identity x " "))))
723
724 (defun hydra-reset-radios (names)
725 "Set varibles NAMES to their defaults.
726 NAMES should be defined by `defhydradio' or similar."
727 (dolist (n names)
728 (set n (aref (get n 'range) 0))))
729
730 (defvar hydra-timer (timer-create)
731 "Timer for `hydra-timeout'.")
732
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))
740 (timer-set-function
741 hydra-timer
742 `(lambda ()
743 ,(when function
744 `(funcall ,function))
745 (hydra-keyboard-quit)))
746 (timer-activate hydra-timer))
747
748 ;;* Macros
749 ;;;###autoload
750 (defmacro defhydra (name body &optional docstring &rest heads)
751 "Create a Hydra - a family of functions with prefix NAME.
752
753 NAME should be a symbol, it will be the prefix of all functions
754 defined here.
755
756 BODY has the format:
757
758 (BODY-MAP BODY-KEY &rest BODY-PLIST)
759
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'.
763
764 Functions are created on basis of HEADS, each of which has the
765 format:
766
767 (KEY CMD &optional HINT &rest PLIST)
768
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.
774
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).
778
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
782 explicitly to nil.
783
784 The heads inherit their PLIST from BODY-PLIST and are allowed to
785 override some keys. The keys recognized are :exit and :bind.
786 :exit can be:
787
788 - nil (default): this head will continue the Hydra state.
789 - t: this head will stop the Hydra state.
790
791 :bind can be:
792 - nil: this head will not be bound in BODY-MAP.
793 - a lambda taking KEY and CMD used to bind a head.
794
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))))
804 (t
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
822 (if body-post
823 (setq heads (cons (list hydra-keyboard-quit #'hydra-keyboard-quit nil :exit t)
824 heads))
825 (define-key keymap hydra-keyboard-quit #'hydra-keyboard-quit)))
826 (dolist (h heads)
827 (let ((len (length h)))
828 (cond ((< len 2)
829 (error "Each head should have at least two items: %S" h))
830 ((= len 2)
831 (setcdr (cdr h)
832 (list
833 (hydra-plist-get-default body-plist :hint "")))
834 (setcdr (nthcdr 2 h)
835 (list :cmd-name (hydra--head-name h name body))))
836 (t
837 (let ((hint (cl-caddr h)))
838 (unless (or (null hint)
839 (stringp hint))
840 (setcdr (cdr h) (cons
841 (hydra-plist-get-default body-plist :hint "")
842 (cddr h))))
843 (let ((hint-and-plist (cddr h)))
844 (if (null (cdr hint-and-plist))
845 (setcdr hint-and-plist
846 (list :cmd-name
847 (hydra--head-name h name body)))
848 (plist-put (cdr hint-and-plist)
849 :cmd-name
850 (hydra--head-name h name body)))))))))
851 (let ((doc (hydra--doc body-key body-name heads))
852 (heads-nodup (hydra--delete-duplicates heads)))
853 (mapc
854 (lambda (x)
855 (define-key keymap (kbd (car x))
856 (plist-get (cl-cdddr x) :cmd-name)))
857 heads)
858 (hydra--make-funcall body-pre)
859 (hydra--make-funcall body-body-pre)
860 (when (memq body-color '(amaranth pink))
861 (unless (cl-some
862 (lambda (h)
863 (memq (hydra--head-color h body) '(blue teal)))
864 heads)
865 (error
866 "An %S Hydra must have at least one blue head in order to exit"
867 body-color)))
868 `(progn
869 ;; create keymap
870 (set (defvar ,keymap-name
871 nil
872 ,(format "Keymap for %S." name))
873 ',keymap)
874 ;; create defuns
875 ,@(mapcar
876 (lambda (head)
877 (hydra--make-defun name body doc head keymap-name
878 body-pre body-post))
879 heads-nodup)
880 ;; free up keymap prefix
881 ,@(unless (or (null body-key)
882 (null body-map)
883 (hydra--callablep body-map))
884 `((unless (keymapp (lookup-key ,body-map (kbd ,body-key)))
885 (define-key ,body-map (kbd ,body-key) nil))))
886 ;; bind keys
887 ,@(delq nil
888 (mapcar
889 (lambda (head)
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))
895 (final-key
896 (if body-key
897 (vconcat (kbd body-key) (kbd (car head)))
898 (kbd (car head)))))
899 (cond ((null bind) nil)
900 ((hydra--callablep bind)
901 `(funcall ,bind ,final-key (function ,name)))
902 ((and (symbolp bind)
903 (if (boundp bind)
904 (keymapp (symbol-value bind))
905 t))
906 `(define-key ,bind ,final-key (function ,name)))
907 (t
908 (error "Invalid :bind property `%S' for head %S" bind head)))))))
909 heads))
910 (defun ,(intern (format "%S/hint" name)) ()
911 ,(hydra--message name body docstring heads))
912 ,(hydra--make-defun
913 name body doc '(nil body)
914 keymap-name
915 (or body-body-pre body-pre) body-post
916 '(setq prefix-arg current-prefix-arg))))))
917
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:
922
923 (TOGGLE-NAME &optional VALUE DOC)
924
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))
932 `(progn
933 ,@(apply #'append
934 (mapcar (lambda (h)
935 (hydra--radio name h))
936 heads))
937 (defvar ,(intern (format "%S/names" name))
938 ',(mapcar (lambda (h) (intern (format "%S/%S" name (car h))))
939 heads))))
940
941 (defmacro hydra-multipop (lst n)
942 "Return LST's first N elements while removing them."
943 `(if (<= (length ,lst) ,n)
944 (prog1 ,lst
945 (setq ,lst nil))
946 (prog1 ,lst
947 (setcdr
948 (nthcdr (1- ,n) (prog1 ,lst (setq ,lst (nthcdr ,n ,lst))))
949 nil))))
950
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)))
955 (doc (cadr head))
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)
959 (defun ,full-name ()
960 (hydra--cycle-radio ',full-name)))))
961
962 (defun hydra--quote-maybe (x)
963 "Quote X if it's a symbol."
964 (cond ((null x)
965 nil)
966 ((symbolp x)
967 (list 'quote x))
968 (t
969 x)))
970
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))
975 (i 0)
976 (l (length range)))
977 (setq i (catch 'done
978 (while (< i l)
979 (if (equal (aref range i) val)
980 (throw 'done (1+ i))
981 (cl-incf i)))
982 (error "Val not in range for %S" sym)))
983 (set sym
984 (aref range
985 (if (>= i l)
986 0
987 i)))))
988
989 (provide 'hydra)
990
991 ;;; Local Variables:
992 ;;; outline-regexp: ";;\\*+"
993 ;;; End:
994
995 ;;; hydra.el ends here