]> code.delx.au - gnu-emacs-elpa/blob - hydra.el
Don't double-call :post
[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 (delq
586 nil
587 `(,(when cmd
588 `(condition-case err
589 (call-interactively #',cmd)
590 ((quit error)
591 (message "%S" err)
592 (unless hydra-lv
593 (sit-for 0.8)))))
594 (when hydra-is-helpful
595 (,hint))
596 (hydra-set-transient-map
597 ,keymap
598 (lambda () (hydra-keyboard-quit) ,body-post)
599 ,(cond
600 ((memq body-color '(amaranth teal))
601 ''warn)
602 ((eq body-color 'pink)
603 ''run)
604 (t
605 nil)))
606 ,(or other-post
607 (when body-timeout
608 `(hydra-timeout ,body-timeout)))))))))
609
610 (defmacro hydra--make-funcall (sym)
611 "Transform SYM into a `funcall' that calls it."
612 `(when (and ,sym (symbolp ,sym))
613 (setq ,sym `(funcall #',,sym))))
614
615 (defun hydra--head-name (h name body)
616 "Return the symbol for head H of hydra with NAME and BODY."
617 (let ((str (format "%S/%s" name
618 (if (symbolp (cadr h))
619 (cadr h)
620 (concat "lambda-" (car h))))))
621 (when (and (memq (hydra--head-color h body) '(blue teal))
622 (not (memq (cadr h) '(body nil))))
623 (setq str (concat str "-and-exit")))
624 (intern str)))
625
626 (defun hydra--delete-duplicates (heads)
627 "Return HEADS without entries that have the same CMD part.
628 In duplicate HEADS, :cmd-name is modified to whatever they duplicate."
629 (let ((ali '(((hydra-repeat . red) . hydra-repeat)))
630 res entry)
631 (dolist (h heads)
632 (if (setq entry (assoc (cons (cadr h)
633 (hydra--head-color h '(nil nil)))
634 ali))
635 (setf (cl-cdddr h) (plist-put (cl-cdddr h) :cmd-name (cdr entry)))
636 (push (cons (cons (cadr h)
637 (hydra--head-color h '(nil nil)))
638 (plist-get (cl-cdddr h) :cmd-name))
639 ali)
640 (push h res)))
641 (nreverse res)))
642
643 (defun hydra--pad (lst n)
644 "Pad LST with nil until length N."
645 (let ((len (length lst)))
646 (if (= len n)
647 lst
648 (append lst (make-list (- n len) nil)))))
649
650 (defun hydra--matrix (lst rows cols)
651 "Create a matrix from elements of LST.
652 The matrix size is ROWS times COLS."
653 (let ((ls (copy-sequence lst))
654 res)
655 (dotimes (_c cols)
656 (push (hydra--pad (hydra-multipop ls rows) rows) res))
657 (nreverse res)))
658
659 (defun hydra--cell (fstr names)
660 "Format a rectangular cell based on FSTR and NAMES.
661 FSTR is a format-style string with two string inputs: one for the
662 doc and one for the symbol name.
663 NAMES is a list of variables."
664 (let ((len (cl-reduce
665 (lambda (acc it) (max (length (symbol-name it)) acc))
666 names
667 :initial-value 0)))
668 (mapconcat
669 (lambda (sym)
670 (if sym
671 (format fstr
672 (documentation-property sym 'variable-documentation)
673 (let ((name (symbol-name sym)))
674 (concat name (make-string (- len (length name)) ?^)))
675 sym)
676 ""))
677 names
678 "\n")))
679
680 (defun hydra--vconcat (strs &optional joiner)
681 "Glue STRS vertically. They must be the same height.
682 JOINER is a function similar to `concat'."
683 (setq joiner (or joiner #'concat))
684 (mapconcat
685 (lambda (s)
686 (if (string-match " +$" s)
687 (replace-match "" nil nil s)
688 s))
689 (apply #'cl-mapcar joiner
690 (mapcar
691 (lambda (s) (split-string s "\n"))
692 strs))
693 "\n"))
694
695 (defcustom hydra-cell-format "% -20s %% -8`%s"
696 "The default format for docstring cells."
697 :type 'string)
698
699 (defun hydra--table (names rows cols &optional cell-formats)
700 "Format a `format'-style table from variables in NAMES.
701 The size of the table is ROWS times COLS.
702 CELL-FORMATS are `format' strings for each column.
703 If CELL-FORMATS is a string, it's used for all columns.
704 If CELL-FORMATS is nil, `hydra-cell-format' is used for all columns."
705 (setq cell-formats
706 (cond ((null cell-formats)
707 (make-list cols hydra-cell-format))
708 ((stringp cell-formats)
709 (make-list cols cell-formats))
710 (t
711 cell-formats)))
712 (hydra--vconcat
713 (cl-mapcar
714 #'hydra--cell
715 cell-formats
716 (hydra--matrix names rows cols))
717 (lambda (&rest x)
718 (mapconcat #'identity x " "))))
719
720 (defun hydra-reset-radios (names)
721 "Set varibles NAMES to their defaults.
722 NAMES should be defined by `defhydradio' or similar."
723 (dolist (n names)
724 (set n (aref (get n 'range) 0))))
725
726 (defvar hydra-timer (timer-create)
727 "Timer for `hydra-timeout'.")
728
729 (defun hydra-timeout (secs &optional function)
730 "In SECS seconds call FUNCTION, then function `hydra-keyboard-quit'.
731 Cancel the previous `hydra-timeout'."
732 (cancel-timer hydra-timer)
733 (setq hydra-timer (timer-create))
734 (timer-set-time hydra-timer
735 (timer-relative-time (current-time) secs))
736 (timer-set-function
737 hydra-timer
738 `(lambda ()
739 ,(when function
740 `(funcall ,function))
741 (hydra-keyboard-quit)))
742 (timer-activate hydra-timer))
743
744 ;;* Macros
745 ;;;###autoload
746 (defmacro defhydra (name body &optional docstring &rest heads)
747 "Create a Hydra - a family of functions with prefix NAME.
748
749 NAME should be a symbol, it will be the prefix of all functions
750 defined here.
751
752 BODY has the format:
753
754 (BODY-MAP BODY-KEY &rest BODY-PLIST)
755
756 DOCSTRING will be displayed in the echo area to identify the
757 Hydra. When DOCSTRING starts with a newline, special Ruby-style
758 substitution will be performed by `hydra--format'.
759
760 Functions are created on basis of HEADS, each of which has the
761 format:
762
763 (KEY CMD &optional HINT &rest PLIST)
764
765 BODY-MAP is a keymap; `global-map' is used quite often. Each
766 function generated from HEADS will be bound in BODY-MAP to
767 BODY-KEY + KEY (both are strings passed to `kbd'), and will set
768 the transient map so that all following heads can be called
769 though KEY only. BODY-KEY can be an empty string.
770
771 CMD is a callable expression: either an interactive function
772 name, or an interactive lambda, or a single sexp (it will be
773 wrapped in an interactive lambda).
774
775 HINT is a short string that identifies its head. It will be
776 printed beside KEY in the echo erea if `hydra-is-helpful' is not
777 nil. If you don't even want the KEY to be printed, set HINT
778 explicitly to nil.
779
780 The heads inherit their PLIST from BODY-PLIST and are allowed to
781 override some keys. The keys recognized are :exit and :bind.
782 :exit can be:
783
784 - nil (default): this head will continue the Hydra state.
785 - t: this head will stop the Hydra state.
786
787 :bind can be:
788 - nil: this head will not be bound in BODY-MAP.
789 - a lambda taking KEY and CMD used to bind a head.
790
791 It is possible to omit both BODY-MAP and BODY-KEY if you don't
792 want to bind anything. In that case, typically you will bind the
793 generated NAME/body command. This command is also the return
794 result of `defhydra'."
795 (declare (indent defun))
796 (cond ((stringp docstring))
797 ((and (consp docstring)
798 (memq (car docstring) '(hydra--table concat format)))
799 (setq docstring (concat "\n" (eval docstring))))
800 (t
801 (setq heads (cons docstring heads))
802 (setq docstring "hydra")))
803 (when (keywordp (car body))
804 (setq body (cons nil (cons nil body))))
805 (let* ((keymap (copy-keymap hydra-base-map))
806 (keymap-name (intern (format "%S/keymap" name)))
807 (body-name (intern (format "%S/body" name)))
808 (body-key (cadr body))
809 (body-plist (cddr body))
810 (body-map (or (car body)
811 (plist-get body-plist :bind)))
812 (body-pre (plist-get body-plist :pre))
813 (body-body-pre (plist-get body-plist :body-pre))
814 (body-post (plist-get body-plist :post))
815 (body-color (hydra--body-color body)))
816 (hydra--make-funcall body-post)
817 (when hydra-keyboard-quit
818 (if body-post
819 (setq heads (cons (list hydra-keyboard-quit #'hydra-keyboard-quit nil :exit t)
820 heads))
821 (define-key keymap hydra-keyboard-quit #'hydra-keyboard-quit)))
822 (dolist (h heads)
823 (let ((len (length h)))
824 (cond ((< len 2)
825 (error "Each head should have at least two items: %S" h))
826 ((= len 2)
827 (setcdr (cdr h)
828 (list
829 (hydra-plist-get-default body-plist :hint "")))
830 (setcdr (nthcdr 2 h)
831 (list :cmd-name (hydra--head-name h name body))))
832 (t
833 (let ((hint (cl-caddr h)))
834 (unless (or (null hint)
835 (stringp hint))
836 (setcdr (cdr h) (cons
837 (hydra-plist-get-default body-plist :hint "")
838 (cddr h))))
839 (let ((hint-and-plist (cddr h)))
840 (if (null (cdr hint-and-plist))
841 (setcdr hint-and-plist
842 (list :cmd-name
843 (hydra--head-name h name body)))
844 (plist-put (cdr hint-and-plist)
845 :cmd-name
846 (hydra--head-name h name body)))))))))
847 (let ((doc (hydra--doc body-key body-name heads))
848 (heads-nodup (hydra--delete-duplicates heads)))
849 (mapc
850 (lambda (x)
851 (define-key keymap (kbd (car x))
852 (plist-get (cl-cdddr x) :cmd-name)))
853 heads)
854 (hydra--make-funcall body-pre)
855 (hydra--make-funcall body-body-pre)
856 (when (memq body-color '(amaranth pink))
857 (unless (cl-some
858 (lambda (h)
859 (memq (hydra--head-color h body) '(blue teal)))
860 heads)
861 (error
862 "An %S Hydra must have at least one blue head in order to exit"
863 body-color)))
864 `(progn
865 ;; create keymap
866 (set (defvar ,keymap-name
867 nil
868 ,(format "Keymap for %S." name))
869 ',keymap)
870 ;; create defuns
871 ,@(mapcar
872 (lambda (head)
873 (hydra--make-defun name body doc head keymap-name
874 body-pre body-post))
875 heads-nodup)
876 ;; free up keymap prefix
877 ,@(unless (or (null body-key)
878 (null body-map)
879 (hydra--callablep body-map))
880 `((unless (keymapp (lookup-key ,body-map (kbd ,body-key)))
881 (define-key ,body-map (kbd ,body-key) nil))))
882 ;; bind keys
883 ,@(delq nil
884 (mapcar
885 (lambda (head)
886 (let ((name (hydra--head-property head :cmd-name)))
887 (when (and (cadr head)
888 (not (eq (cadr head) 'hydra-keyboard-quit))
889 (or body-key body-map))
890 (let ((bind (hydra--head-property head :bind body-map))
891 (final-key
892 (if body-key
893 (vconcat (kbd body-key) (kbd (car head)))
894 (kbd (car head)))))
895 (cond ((null bind) nil)
896 ((hydra--callablep bind)
897 `(funcall ,bind ,final-key (function ,name)))
898 ((and (symbolp bind)
899 (if (boundp bind)
900 (keymapp (symbol-value bind))
901 t))
902 `(define-key ,bind ,final-key (function ,name)))
903 (t
904 (error "Invalid :bind property `%S' for head %S" bind head)))))))
905 heads))
906 (defun ,(intern (format "%S/hint" name)) ()
907 ,(hydra--message name body docstring heads))
908 ,(hydra--make-defun
909 name body doc '(nil body)
910 keymap-name
911 (or body-body-pre body-pre) body-post
912 '(setq prefix-arg current-prefix-arg))))))
913
914 (defmacro defhydradio (name _body &rest heads)
915 "Create radios with prefix NAME.
916 _BODY specifies the options; there are none currently.
917 HEADS have the format:
918
919 (TOGGLE-NAME &optional VALUE DOC)
920
921 TOGGLE-NAME will be used along with NAME to generate a variable
922 name and a function that cycles it with the same name. VALUE
923 should be an array. The first element of VALUE will be used to
924 inialize the variable.
925 VALUE defaults to [nil t].
926 DOC defaults to TOGGLE-NAME split and capitalized."
927 (declare (indent defun))
928 `(progn
929 ,@(apply #'append
930 (mapcar (lambda (h)
931 (hydra--radio name h))
932 heads))
933 (defvar ,(intern (format "%S/names" name))
934 ',(mapcar (lambda (h) (intern (format "%S/%S" name (car h))))
935 heads))))
936
937 (defmacro hydra-multipop (lst n)
938 "Return LST's first N elements while removing them."
939 `(if (<= (length ,lst) ,n)
940 (prog1 ,lst
941 (setq ,lst nil))
942 (prog1 ,lst
943 (setcdr
944 (nthcdr (1- ,n) (prog1 ,lst (setq ,lst (nthcdr ,n ,lst))))
945 nil))))
946
947 (defun hydra--radio (parent head)
948 "Generate a hydradio with PARENT from HEAD."
949 (let* ((name (car head))
950 (full-name (intern (format "%S/%S" parent name)))
951 (doc (cadr head))
952 (val (or (cl-caddr head) [nil t])))
953 `((defvar ,full-name ,(hydra--quote-maybe (aref val 0)) ,doc)
954 (put ',full-name 'range ,val)
955 (defun ,full-name ()
956 (hydra--cycle-radio ',full-name)))))
957
958 (defun hydra--quote-maybe (x)
959 "Quote X if it's a symbol."
960 (cond ((null x)
961 nil)
962 ((symbolp x)
963 (list 'quote x))
964 (t
965 x)))
966
967 (defun hydra--cycle-radio (sym)
968 "Set SYM to the next value in its range."
969 (let* ((val (symbol-value sym))
970 (range (get sym 'range))
971 (i 0)
972 (l (length range)))
973 (setq i (catch 'done
974 (while (< i l)
975 (if (equal (aref range i) val)
976 (throw 'done (1+ i))
977 (cl-incf i)))
978 (error "Val not in range for %S" sym)))
979 (set sym
980 (aref range
981 (if (>= i l)
982 0
983 i)))))
984
985 (provide 'hydra)
986
987 ;;; Local Variables:
988 ;;; outline-regexp: ";;\\*+"
989 ;;; End:
990
991 ;;; hydra.el ends here