]> code.delx.au - gnu-emacs-elpa/blob - hydra.el
hydra.el (hydra--format): Amend regex
[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.0
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 (defalias 'hydra-set-transient-map
83 (if (fboundp 'set-transient-map)
84 'set-transient-map
85 (lambda (map _keep-pred &optional on-exit)
86 (with-no-warnings
87 (set-temporary-overlay-map map (hydra--pred on-exit))))))
88
89 (defun hydra--pred (on-exit)
90 "Generate a predicate on whether to continue the Hydra state.
91 Call ON-EXIT for clean-up.
92 This is a compatibility code for Emacs older than 24.4."
93 `(lambda ()
94 (if (lookup-key hydra-curr-map (this-command-keys-vector))
95 t
96 (hydra-cleanup)
97 ,(when on-exit
98 `(funcall ,(hydra--make-callable on-exit)))
99 nil)))
100
101 ;;* Customize
102 (defgroup hydra nil
103 "Make bindings that stick around."
104 :group 'bindings
105 :prefix "hydra-")
106
107 (defcustom hydra-is-helpful t
108 "When t, display a hint with possible bindings in the echo area."
109 :type 'boolean
110 :group 'hydra)
111
112 (defcustom hydra-keyboard-quit "\a"
113 "This binding will quit an amaranth Hydra.
114 It's the only other way to quit it besides though a blue head.
115 It's possible to set this to nil.")
116
117 (defcustom hydra-lv t
118 "When non-nil, `lv-message' (not `message') will be used to display hints."
119 :type 'boolean)
120
121 (defcustom hydra-verbose nil
122 "When non-nil, hydra will issue some non essential style warnings."
123 :type 'boolean)
124
125 (defcustom hydra-key-format-spec "%s"
126 "Default `format'-style specifier for _a_ syntax in docstrings.
127 When nil, you can specify your own at each location like this: _ 5a_.")
128
129 (defface hydra-face-red
130 '((t (:foreground "#FF0000" :bold t)))
131 "Red Hydra heads will persist indefinitely."
132 :group 'hydra)
133
134 (defface hydra-face-blue
135 '((t (:foreground "#0000FF" :bold t)))
136 "Blue Hydra heads will vanquish the Hydra.")
137
138 (defface hydra-face-amaranth
139 '((t (:foreground "#E52B50" :bold t)))
140 "Amaranth body has red heads and warns on intercepting non-heads.
141 Vanquishable only through a blue head.")
142
143 (defface hydra-face-pink
144 '((t (:foreground "#FF6EB4" :bold t)))
145 "Pink body has red heads and on intercepting non-heads calls them without quitting.
146 Vanquishable only through a blue head.")
147
148 (defface hydra-face-teal
149 '((t (:foreground "#367588" :bold t)))
150 "Teal body has blue heads an warns on intercepting non-heads.
151 Vanquishable only through a blue head.")
152
153 ;;* Fontification
154 (defun hydra-add-font-lock ()
155 "Fontify `defhydra' statements."
156 (font-lock-add-keywords
157 'emacs-lisp-mode
158 '(("(\\(defhydra\\)\\_> +\\(.*?\\)\\_>"
159 (1 font-lock-keyword-face)
160 (2 font-lock-type-face))
161 ("(\\(defhydradio\\)\\_> +\\(.*?\\)\\_>"
162 (1 font-lock-keyword-face)
163 (2 font-lock-type-face)))))
164
165 ;;* Universal Argument
166 (defvar hydra-base-map
167 (let ((map (make-sparse-keymap)))
168 (define-key map [?\C-u] 'hydra--universal-argument)
169 (define-key map [?-] 'hydra--negative-argument)
170 (define-key map [?0] 'hydra--digit-argument)
171 (define-key map [?1] 'hydra--digit-argument)
172 (define-key map [?2] 'hydra--digit-argument)
173 (define-key map [?3] 'hydra--digit-argument)
174 (define-key map [?4] 'hydra--digit-argument)
175 (define-key map [?5] 'hydra--digit-argument)
176 (define-key map [?6] 'hydra--digit-argument)
177 (define-key map [?7] 'hydra--digit-argument)
178 (define-key map [?8] 'hydra--digit-argument)
179 (define-key map [?9] 'hydra--digit-argument)
180 (define-key map [kp-0] 'hydra--digit-argument)
181 (define-key map [kp-1] 'hydra--digit-argument)
182 (define-key map [kp-2] 'hydra--digit-argument)
183 (define-key map [kp-3] 'hydra--digit-argument)
184 (define-key map [kp-4] 'hydra--digit-argument)
185 (define-key map [kp-5] 'hydra--digit-argument)
186 (define-key map [kp-6] 'hydra--digit-argument)
187 (define-key map [kp-7] 'hydra--digit-argument)
188 (define-key map [kp-8] 'hydra--digit-argument)
189 (define-key map [kp-9] 'hydra--digit-argument)
190 (define-key map [kp-subtract] 'hydra--negative-argument)
191 (define-key map [switch-frame] 'hydra--handle-switch-frame)
192 map)
193 "Keymap that all Hydras inherit. See `universal-argument-map'.")
194
195 (defvar hydra-curr-map
196 (make-sparse-keymap)
197 "Keymap of the current Hydra called.")
198
199 (defun hydra--handle-switch-frame (evt)
200 "Quit hydra and call old switch-frame event handler for EVT."
201 (interactive "e")
202 (hydra-keyboard-quit)
203 (funcall (lookup-key (current-global-map) [switch-frame]) evt))
204
205 (defun hydra--universal-argument (arg)
206 "Forward to (`universal-argument' ARG)."
207 (interactive "P")
208 (setq prefix-arg (if (consp arg)
209 (list (* 4 (car arg)))
210 (if (eq arg '-)
211 (list -4)
212 '(4))))
213 (hydra-set-transient-map hydra-curr-map t))
214
215 (defun hydra--digit-argument (arg)
216 "Forward to (`digit-argument' ARG)."
217 (interactive "P")
218 (let ((universal-argument-map hydra-curr-map))
219 (digit-argument arg)))
220
221 (defun hydra--negative-argument (arg)
222 "Forward to (`negative-argument' ARG)."
223 (interactive "P")
224 (let ((universal-argument-map hydra-curr-map))
225 (negative-argument arg)))
226 ;;* Repeat
227 (defvar hydra-repeat--prefix-arg nil
228 "Prefix arg to use with `hydra-repeat'.")
229
230 (defvar hydra-repeat--command nil
231 "Command to use with `hydra-repeat'.")
232
233 (defun hydra-repeat (&optional arg)
234 "Repeat last command with last prefix arg.
235 When ARG is non-nil, use that instead."
236 (interactive "p")
237 (if (eq arg 1)
238 (unless (string-match "hydra-repeat$" (symbol-name last-command))
239 (setq hydra-repeat--command last-command)
240 (setq hydra-repeat--prefix-arg last-prefix-arg))
241 (setq hydra-repeat--prefix-arg arg))
242 (setq current-prefix-arg hydra-repeat--prefix-arg)
243 (funcall hydra-repeat--command))
244
245 ;;* Misc internals
246 (defvar hydra-last nil
247 "The result of the last `hydra-set-transient-map' call.")
248
249 (defun hydra--callablep (x)
250 "Test if X is callable."
251 (or (functionp x)
252 (and (consp x)
253 (memq (car x) '(function quote)))))
254
255 (defun hydra--make-callable (x)
256 "Generate a callable symbol from X.
257 If X is a function symbol or a lambda, return it. Otherwise, it
258 should be a single statement. Wrap it in an interactive lambda."
259 (if (or (symbolp x) (functionp x))
260 x
261 `(lambda ()
262 (interactive)
263 ,x)))
264
265 (defun hydra-plist-get-default (plist prop default)
266 "Extract a value from a property list.
267 PLIST is a property list, which is a list of the form
268 \(PROP1 VALUE1 PROP2 VALUE2...).
269
270 Return the value corresponding to PROP, or DEFAULT if PROP is not
271 one of the properties on the list."
272 (if (memq prop plist)
273 (plist-get plist prop)
274 default))
275
276 (defun hydra--head-property (h prop &optional default)
277 "Return for Hydra head H the value of property PROP.
278 Return DEFAULT if PROP is not in H."
279 (hydra-plist-get-default (cl-cdddr h) prop default))
280
281 (defun hydra--aggregate-color (head-color body-color)
282 "Return the resulting head color for HEAD-COLOR and BODY-COLOR."
283 (cond ((eq head-color 'red)
284 (cl-case body-color
285 (red 'red)
286 (blue 'red)
287 (amaranth 'amaranth)
288 (pink 'pink)
289 (cyan 'amaranth)))
290 ((eq head-color 'blue)
291 (cl-case body-color
292 (red 'blue)
293 (blue 'blue)
294 (amaranth 'teal)
295 (pink 'blue)
296 (cyan 'teal)))
297 (t
298 (error "Can't aggregate head %S to body %S"
299 head-color body-color))))
300
301 (defun hydra--head-color (h body)
302 "Return the color of a Hydra head H with BODY."
303 (let* ((exit (hydra--head-property h :exit 'default))
304 (color (hydra--head-property h :color))
305 (foreign-keys (hydra--body-foreign-keys body))
306 (head-color
307 (cond ((eq exit 'default)
308 (cl-case color
309 (blue 'blue)
310 (red 'red)
311 (t
312 (unless (null color)
313 (error "Use only :blue or :red for heads: %S" h)))))
314 ((null exit)
315 (if color
316 (error "Don't mix :color and :exit - they are aliases: %S" h)
317 (cl-case foreign-keys
318 (run 'pink)
319 (warn 'amaranth)
320 (t 'red))))
321 ((eq exit t)
322 (if color
323 (error "Don't mix :color and :exit - they are aliases: %S" h)
324 'blue))
325 (t
326 (error "Unknown :exit %S" exit)))))
327 (cond ((null (cadr h))
328 (when head-color
329 (hydra--complain
330 "Doubly specified blue head - nil cmd is already blue: %S" h))
331 'blue)
332 ((null head-color)
333 (hydra--body-color body))
334 ((null foreign-keys)
335 head-color)
336 ((eq foreign-keys 'run)
337 (if (eq head-color 'red)
338 'pink
339 'blue))
340 ((eq foreign-keys 'warn)
341 (if (memq head-color '(red amaranth))
342 'amaranth
343 'teal))
344 (t
345 (error "Unexpected %S %S" h body)))))
346
347 (defun hydra--body-foreign-keys (body)
348 "Return what BODY does with a non-head binding."
349 (or
350 (plist-get (cddr body) :foreign-keys)
351 (let ((color (plist-get (cddr body) :color)))
352 (cl-case color
353 ((amaranth teal) 'warn)
354 (pink 'run)))))
355
356 (defun hydra--body-color (body)
357 "Return the color of BODY.
358 BODY is the second argument to `defhydra'"
359 (let ((color (plist-get (cddr body) :color))
360 (exit (plist-get (cddr body) :exit))
361 (foreign-keys (plist-get (cddr body) :foreign-keys)))
362 (cond ((eq foreign-keys 'warn)
363 (if exit 'teal 'amaranth))
364 ((eq foreign-keys 'run) 'pink)
365 (exit 'blue)
366 (color color)
367 (t 'red))))
368
369 (defun hydra--face (h body)
370 "Return the face for a Hydra head H with BODY."
371 (cl-case (hydra--head-color h body)
372 (blue 'hydra-face-blue)
373 (red 'hydra-face-red)
374 (amaranth 'hydra-face-amaranth)
375 (pink 'hydra-face-pink)
376 (teal 'hydra-face-teal)
377 (t (error "Unknown color for %S" h))))
378
379 (defun hydra-cleanup ()
380 "Clean up after a Hydra."
381 (when (window-live-p lv-wnd)
382 (let ((buf (window-buffer lv-wnd)))
383 (delete-window lv-wnd)
384 (kill-buffer buf))))
385
386 (defun hydra-keyboard-quit ()
387 "Quitting function similar to `keyboard-quit'."
388 (interactive)
389 (hydra-disable)
390 (hydra-cleanup)
391 (cancel-timer hydra-timer)
392 (unless hydra-lv
393 (message ""))
394 nil)
395
396 (defun hydra-disable ()
397 "Disable the current Hydra."
398 (cond
399 ;; Emacs 25
400 ((functionp hydra-last)
401 (funcall hydra-last))
402
403 ;; Emacs 24.3 or older
404 ((< emacs-minor-version 4)
405 (setq emulation-mode-map-alists
406 (cl-remove-if
407 (lambda (x)
408 (and (consp x)
409 (consp (car x))
410 (equal (cdar x) hydra-curr-map)))
411 emulation-mode-map-alists)))
412
413 ;; Emacs 24.4.1
414 (t
415 (setq overriding-terminal-local-map nil))))
416
417 (defun hydra--unalias-var (str prefix)
418 "Return the symbol named STR if it's bound as a variable.
419 Otherwise, add PREFIX to the symbol name."
420 (let ((sym (intern-soft str)))
421 (if (boundp sym)
422 sym
423 (intern (concat prefix "/" str)))))
424
425 (defun hydra--hint (body heads)
426 "Generate a hint for the echo area.
427 BODY, and HEADS are parameters to `defhydra'."
428 (let (alist)
429 (dolist (h heads)
430 (let ((val (assoc (cadr h) alist))
431 (pstr (hydra-fontify-head h body)))
432 (unless (null (cl-caddr h))
433 (if val
434 (setf (cadr val)
435 (concat (cadr val) " " pstr))
436 (push
437 (cons (cadr h)
438 (cons pstr (cl-caddr h)))
439 alist)))))
440 (mapconcat
441 (lambda (x)
442 (format
443 (if (> (length (cdr x)) 0)
444 (concat "[%s]: " (cdr x))
445 "%s")
446 (car x)))
447 (nreverse (mapcar #'cdr alist))
448 ", ")))
449
450 (defvar hydra-fontify-head-function nil
451 "Possible replacement for `hydra-fontify-head-default'.")
452
453 (defun hydra-fontify-head-default (head body)
454 "Produce a pretty string from HEAD and BODY.
455 HEAD's binding is returned as a string with a colored face."
456 (propertize (car head) 'face (hydra--face head body)))
457
458 (defun hydra-fontify-head-greyscale (head body)
459 "Produce a pretty string from HEAD and BODY.
460 HEAD's binding is returned as a string wrapped with [] or {}."
461 (let ((color (hydra--head-color head body)))
462 (format
463 (if (eq color 'blue)
464 "[%s]"
465 "{%s}") (car head))))
466
467 (defun hydra-fontify-head (head body)
468 "Produce a pretty string from HEAD and BODY."
469 (funcall (or hydra-fontify-head-function 'hydra-fontify-head-default)
470 head body))
471
472 (defun hydra--format (_name body docstring heads)
473 "Generate a `format' statement from STR.
474 \"%`...\" expressions are extracted into \"%S\".
475 _NAME, BODY, DOCSTRING and HEADS are parameters of `defhydra'.
476 The expressions can be auto-expanded according to NAME."
477 (setq docstring (replace-regexp-in-string "\\^" "" docstring))
478 (let ((rest (hydra--hint body heads))
479 (start 0)
480 varlist
481 offset)
482 (while (setq start
483 (string-match
484 "\\(?:%\\( ?-?[0-9]*s?\\)\\(`[a-z-A-Z/0-9]+\\|(\\)\\)\\|\\(?:_\\( ?-?[0-9]*\\)\\([a-z.,-~A-Z;:0-9/|?<>={}]+\\)_\\)"
485 docstring start))
486 (cond ((eq ?_ (aref (match-string 0 docstring) 0))
487 (let* ((key (match-string 4 docstring))
488 (head (assoc key heads)))
489 (if head
490 (progn
491 (push (hydra-fontify-head head body) varlist)
492 (setq docstring
493 (replace-match
494 (or
495 hydra-key-format-spec
496 (concat "%" (match-string 3 docstring) "s"))
497 t nil docstring)))
498 (error "Unrecognized key: _%s_" key))))
499
500 (t
501 (let* ((varp (if (eq ?` (aref (match-string 2 docstring) 0)) 1 0))
502 (spec (match-string 1 docstring))
503 (lspec (length spec)))
504 (setq offset
505 (with-temp-buffer
506 (insert (substring docstring (+ 1 start varp
507 (length spec))))
508 (goto-char (point-min))
509 (push (read (current-buffer)) varlist)
510 (- (point) (point-min))))
511 (when (or (zerop lspec)
512 (/= (aref spec (1- (length spec))) ?s))
513 (setq spec (concat spec "S")))
514 (setq docstring
515 (concat
516 (substring docstring 0 start)
517 "%" spec
518 (substring docstring (+ start offset 1 lspec varp))))))))
519 (if (eq ?\n (aref docstring 0))
520 `(concat (format ,(substring docstring 1) ,@(nreverse varlist))
521 ,rest)
522 `(format ,(concat docstring ": " rest ".")))))
523
524 (defun hydra--message (name body docstring heads)
525 "Generate code to display the hint in the preferred echo area.
526 Set `hydra-lv' to choose the echo area.
527 NAME, BODY, DOCSTRING, and HEADS are parameters of `defhydra'."
528 (let ((format-expr (hydra--format name body docstring heads)))
529 `(if hydra-lv
530 (lv-message ,format-expr)
531 (message ,format-expr))))
532
533 (defun hydra--complain (format-string &rest args)
534 "Forward to (`message' FORMAT-STRING ARGS) unless `hydra-verbose' is nil."
535 (when hydra-verbose
536 (apply #'warn format-string args)))
537
538 (defun hydra--doc (body-key body-name heads)
539 "Generate a part of Hydra docstring.
540 BODY-KEY is the body key binding.
541 BODY-NAME is the symbol that identifies the Hydra.
542 HEADS is a list of heads."
543 (format
544 "Create a hydra with %s body and the heads:\n\n%s\n\n%s"
545 (if body-key
546 (format "a \"%s\"" body-key)
547 "no")
548 (mapconcat
549 (lambda (x)
550 (format "\"%s\": `%S'" (car x) (cadr x)))
551 heads ",\n")
552 (format "The body can be accessed via `%S'." body-name)))
553
554 (defun hydra--make-defun (name body doc head
555 keymap body-pre body-post &optional other-post)
556 "Make a defun wrapper, using NAME, BODY, DOC, HEAD, and KEYMAP.
557 NAME and BODY are the arguments to `defhydra'.
558 DOC was generated with `hydra--doc'.
559 HEAD is one of the HEADS passed to `defhydra'.
560 BODY-PRE and BODY-POST are pre-processed in `defhydra'.
561 OTHER-POST is an optional extension to the :post key of BODY."
562 (let ((name (hydra--head-name head name body))
563 (cmd (when (car head)
564 (hydra--make-callable
565 (cadr head))))
566 (color (when (car head)
567 (hydra--head-color head body)))
568 (doc (if (car head)
569 (format "%s\n\nCall the head: `%S'." doc (cadr head))
570 doc))
571 (hint (intern (format "%S/hint" name)))
572 (body-color (hydra--body-color body))
573 (body-timeout (plist-get body :timeout)))
574 `(defun ,name ()
575 ,doc
576 (interactive)
577 ,@(when body-pre (list body-pre))
578 (hydra-disable)
579 ,@(when (memq color '(blue teal)) '((hydra-cleanup)))
580 (catch 'hydra-disable
581 ,@(delq nil
582 (if (memq color '(blue teal))
583 `(,(when cmd `(call-interactively #',cmd))
584 ,body-post)
585 `(,(when cmd
586 `(condition-case err
587 (prog1 t
588 (call-interactively #',cmd))
589 ((quit error)
590 (message "%S" err)
591 (unless hydra-lv
592 (sit-for 0.8))
593 nil)))
594 (when hydra-is-helpful
595 (,hint))
596 (setq hydra-last
597 (hydra-set-transient-map
598 (setq hydra-curr-map ',keymap)
599 t
600 ,(if (and
601 (not (memq body-color
602 '(amaranth pink teal)))
603 body-post)
604 `(lambda () (hydra-cleanup) ,body-post)
605 `(lambda () (hydra-cleanup)))))
606 ,(or other-post
607 (when body-timeout
608 (list 'hydra-timeout
609 body-timeout
610 (when body-post
611 (hydra--make-callable body-post))))))))))))
612
613 (defun hydra-pink-fallback ()
614 "On intercepting a non-head, try to run it."
615 (let ((keys (this-command-keys))
616 kb)
617 (when (equal keys [backspace])
618 (setq keys "\7f"))
619 (setq kb (key-binding keys))
620 (if kb
621 (if (commandp kb)
622 (condition-case err
623 (call-interactively kb)
624 ((quit error)
625 (message "%S" err)
626 (unless hydra-lv
627 (sit-for 0.8))))
628 (message "Pink Hydra can't currently handle prefixes, continuing"))
629 (message "Pink Hydra could not resolve: %S" keys))))
630
631 (defun hydra--modify-keymap (keymap def)
632 "In KEYMAP, add DEF to each sub-keymap."
633 (cl-labels
634 ((recur (map)
635 (if (atom map)
636 map
637 (if (eq (car map) 'keymap)
638 (cons 'keymap
639 (cons
640 def
641 (recur (cdr map))))
642 (cons
643 (recur (car map))
644 (recur (cdr map)))))))
645 (recur keymap)))
646
647 (defun hydra--handle-nonhead (keymap name body heads)
648 "Setup KEYMAP for intercepting non-head bindings.
649 NAME, BODY and HEADS are parameters to `defhydra'."
650 (let ((body-color (hydra--body-color body))
651 (body-post (plist-get (cddr body) :post)))
652 (if body-post
653 (when (symbolp body-post)
654 (setq body-post `(funcall #',body-post)))
655 (when hydra-keyboard-quit
656 (define-key keymap hydra-keyboard-quit #'hydra-keyboard-quit)))
657 (when (memq body-color '(amaranth pink teal))
658 (if (cl-some (lambda (h)
659 (memq (hydra--head-color h body) '(blue teal)))
660 heads)
661 (progn
662 (setcdr
663 keymap
664 (cdr
665 (hydra--modify-keymap
666 keymap
667 (cons t
668 `(lambda ()
669 (interactive)
670 ,(cond
671 ((memq body-color '(amaranth teal))
672 '(message "An amaranth Hydra can only exit through a blue head"))
673 (t
674 '(hydra-pink-fallback)))
675 (hydra-set-transient-map hydra-curr-map t)
676 (when hydra-is-helpful
677 (unless hydra-lv
678 (sit-for 0.8))
679 (,(intern (format "%S/hint" name))))))))))
680 (unless (eq body-color 'teal)
681 (error
682 "An %S Hydra must have at least one blue head in order to exit"
683 body-color))))))
684
685 (defun hydra--head-name (h name body)
686 "Return the symbol for head H of hydra with NAME and BODY."
687 (let ((str (format "%S/%s" name
688 (if (symbolp (cadr h))
689 (cadr h)
690 (concat "lambda-" (car h))))))
691 (when (and (memq (hydra--head-color h body) '(blue teal))
692 (not (memq (cadr h) '(body nil))))
693 (setq str (concat str "-and-exit")))
694 (intern str)))
695
696 (defun hydra--delete-duplicates (heads)
697 "Return HEADS without entries that have the same CMD part.
698 In duplicate HEADS, :cmd-name is modified to whatever they duplicate."
699 (let ((ali '(((hydra-repeat . red) . hydra-repeat)))
700 res entry)
701 (dolist (h heads)
702 (if (setq entry (assoc (cons (cadr h)
703 (hydra--head-color h '(nil nil)))
704 ali))
705 (setf (cl-cdddr h) (plist-put (cl-cdddr h) :cmd-name (cdr entry)))
706 (push (cons (cons (cadr h)
707 (hydra--head-color h '(nil nil)))
708 (plist-get (cl-cdddr h) :cmd-name))
709 ali)
710 (push h res)))
711 (nreverse res)))
712
713 (defun hydra--pad (lst n)
714 "Pad LST with nil until length N."
715 (let ((len (length lst)))
716 (if (= len n)
717 lst
718 (append lst (make-list (- n len) nil)))))
719
720 (defun hydra--matrix (lst rows cols)
721 "Create a matrix from elements of LST.
722 The matrix size is ROWS times COLS."
723 (let ((ls (copy-sequence lst))
724 res)
725 (dotimes (_c cols)
726 (push (hydra--pad (hydra-multipop ls rows) rows) res))
727 (nreverse res)))
728
729 (defun hydra--cell (fstr names)
730 "Format a rectangular cell based on FSTR and NAMES.
731 FSTR is a format-style string with two string inputs: one for the
732 doc and one for the symbol name.
733 NAMES is a list of variables."
734 (let ((len (cl-reduce
735 (lambda (acc it) (max (length (symbol-name it)) acc))
736 names
737 :initial-value 0)))
738 (mapconcat
739 (lambda (sym)
740 (if sym
741 (format fstr
742 (documentation-property sym 'variable-documentation)
743 (let ((name (symbol-name sym)))
744 (concat name (make-string (- len (length name)) ?^)))
745 sym)
746 ""))
747 names
748 "\n")))
749
750 (defun hydra--vconcat (strs &optional joiner)
751 "Glue STRS vertically. They must be the same height.
752 JOINER is a function similar to `concat'."
753 (setq joiner (or joiner #'concat))
754 (mapconcat
755 (lambda (s)
756 (if (string-match " +$" s)
757 (replace-match "" nil nil s)
758 s))
759 (apply #'cl-mapcar joiner
760 (mapcar
761 (lambda (s) (split-string s "\n"))
762 strs))
763 "\n"))
764
765 (defcustom hydra-cell-format "% -20s %% -8`%s"
766 "The default format for docstring cells."
767 :type 'string)
768
769 (defun hydra--table (names rows cols &optional cell-formats)
770 "Format a `format'-style table from variables in NAMES.
771 The size of the table is ROWS times COLS.
772 CELL-FORMATS are `format' strings for each column.
773 If CELL-FORMATS is a string, it's used for all columns.
774 If CELL-FORMATS is nil, `hydra-cell-format' is used for all columns."
775 (setq cell-formats
776 (cond ((null cell-formats)
777 (make-list cols hydra-cell-format))
778 ((stringp cell-formats)
779 (make-list cols cell-formats))
780 (t
781 cell-formats)))
782 (hydra--vconcat
783 (cl-mapcar
784 #'hydra--cell
785 cell-formats
786 (hydra--matrix names rows cols))
787 (lambda (&rest x)
788 (mapconcat #'identity x " "))))
789
790 (defun hydra-reset-radios (names)
791 "Set varibles NAMES to their defaults.
792 NAMES should be defined by `defhydradio' or similar."
793 (dolist (n names)
794 (set n (aref (get n 'range) 0))))
795
796 (defvar hydra-timer (timer-create)
797 "Timer for `hydra-timeout'.")
798
799 (defun hydra-timeout (secs &optional function)
800 "In SECS seconds call FUNCTION, then function `hydra-keyboard-quit'.
801 Cancel the previous `hydra-timeout'."
802 (cancel-timer hydra-timer)
803 (setq hydra-timer (timer-create))
804 (timer-set-time hydra-timer
805 (timer-relative-time (current-time) secs))
806 (timer-set-function
807 hydra-timer
808 `(lambda ()
809 ,(when function
810 `(funcall ,function))
811 (hydra-keyboard-quit)))
812 (timer-activate hydra-timer))
813
814 ;;* Macros
815 ;;** defhydra
816 ;;;###autoload
817 (defmacro defhydra (name body &optional docstring &rest heads)
818 "Create a Hydra - a family of functions with prefix NAME.
819
820 NAME should be a symbol, it will be the prefix of all functions
821 defined here.
822
823 BODY has the format:
824
825 (BODY-MAP BODY-KEY &rest PLIST)
826
827 DOCSTRING will be displayed in the echo area to identify the
828 Hydra. When DOCSTRING starts with a newline, special Ruby-style
829 substitution will be performed by `hydra--format'.
830
831 Functions are created on basis of HEADS, each of which has the
832 format:
833
834 (KEY CMD &optional HINT &rest PLIST)
835
836 BODY-MAP is a keymap; `global-map' is used quite often. Each
837 function generated from HEADS will be bound in BODY-MAP to
838 BODY-KEY + KEY (both are strings passed to `kbd'), and will set
839 the transient map so that all following heads can be called
840 though KEY only.
841
842 CMD is a callable expression: either an interactive function
843 name, or an interactive lambda, or a single sexp (it will be
844 wrapped in an interactive lambda).
845
846 HINT is a short string that identifies its head. It will be
847 printed beside KEY in the echo erea if `hydra-is-helpful' is not
848 nil. If you don't even want the KEY to be printed, set HINT
849 explicitly to nil.
850
851 The heads inherit their PLIST from the body and are allowed to
852 override each key. The keys recognized are :color and :bind.
853 :color can be:
854
855 - red (default): this head will continue the Hydra state.
856 - blue: this head will stop the Hydra state.
857 - amaranth (applies to body only): similar to red, but no binding
858 except a blue head can stop the Hydra state.
859
860 :bind can be:
861 - nil: this head will not be bound in BODY-MAP.
862 - a lambda taking KEY and CMD used to bind a head
863
864 It is possible to omit both BODY-MAP and BODY-KEY if you don't
865 want to bind anything. In that case, typically you will bind the
866 generated NAME/body command. This command is also the return
867 result of `defhydra'."
868 (declare (indent defun))
869 (cond ((stringp docstring))
870 ((and (consp docstring)
871 (memq (car docstring) '(hydra--table concat format)))
872 (setq docstring (concat "\n" (eval docstring))))
873 (t
874 (setq heads (cons docstring heads))
875 (setq docstring "hydra")))
876 (when (keywordp (car body))
877 (setq body (cons nil (cons nil body))))
878 (let ((keymap (copy-keymap hydra-base-map))
879 (body-name (intern (format "%S/body" name)))
880 (body-key (cadr body))
881 (body-pre (plist-get (cddr body) :pre))
882 (body-body-pre (plist-get (cddr body) :body-pre))
883 (body-post (plist-get (cddr body) :post))
884 (method (or (plist-get body :bind)
885 (car body))))
886 (when body-post
887 (when (symbolp body-post)
888 (setq body-post `(funcall #',body-post)))
889 (setq heads (cons (list hydra-keyboard-quit #'hydra-keyboard-quit nil :exit t)
890 heads)))
891 (dolist (h heads)
892 (let ((len (length h)))
893 (cond ((< len 2)
894 (error "Each head should have at least two items: %S" h))
895 ((= len 2)
896 (setcdr (cdr h)
897 (list
898 (hydra-plist-get-default (cddr body) :hint "")))
899 (setcdr (nthcdr 2 h)
900 (list :cmd-name (hydra--head-name h name body))))
901 (t
902 (let ((hint (cl-caddr h)))
903 (unless (or (null hint)
904 (stringp hint))
905 (setcdr (cdr h) (cons
906 (hydra-plist-get-default (cddr body) :hint "")
907 (cddr h))))
908 (setcdr (cddr h)
909 `(:cmd-name
910 ,(hydra--head-name h name body)
911 ,@(cl-cdddr h))))))))
912 (let ((doc (hydra--doc body-key body-name heads))
913 (heads-nodup (hydra--delete-duplicates heads)))
914 (mapc
915 (lambda (x)
916 (define-key keymap (kbd (car x))
917 (plist-get (cl-cdddr x) :cmd-name)))
918 heads)
919 (when (and body-pre (symbolp body-pre))
920 (setq body-pre `(funcall #',body-pre)))
921 (when (and body-body-pre (symbolp body-body-pre))
922 (setq body-body-pre `(funcall #',body-body-pre)))
923 (hydra--handle-nonhead keymap name body heads)
924 `(progn
925 ,@(mapcar
926 (lambda (head)
927 (hydra--make-defun name body doc head keymap
928 body-pre body-post))
929 heads-nodup)
930 ,@(unless (or (null body-key)
931 (null method)
932 (hydra--callablep method))
933 `((unless (keymapp (lookup-key ,method (kbd ,body-key)))
934 (define-key ,method (kbd ,body-key) nil))))
935 ,@(delq nil
936 (cl-mapcar
937 (lambda (head)
938 (let ((name (hydra--head-property head :cmd-name)))
939 (when (and (cadr head)
940 (not (eq (cadr head) 'hydra-keyboard-quit))
941 (or body-key method))
942 (let ((bind (hydra--head-property head :bind 'default))
943 (final-key
944 (if body-key
945 (vconcat (kbd body-key) (kbd (car head)))
946 (kbd (car head)))))
947 (cond ((null bind) nil)
948
949 ((eq bind 'default)
950 (list
951 (if (hydra--callablep method)
952 'funcall
953 'define-key)
954 method
955 final-key
956 (list 'function name)))
957
958 ((hydra--callablep bind)
959 `(funcall (function ,bind)
960 ,final-key
961 (function ,name)))
962
963 (t
964 (error "Invalid :bind property %S" head)))))))
965 heads))
966 (defun ,(intern (format "%S/hint" name)) ()
967 ,(hydra--message name body docstring heads))
968 ,(hydra--make-defun
969 name body doc '(nil body)
970 keymap
971 (or body-body-pre body-pre) body-post
972 '(setq prefix-arg current-prefix-arg))))))
973
974 (defmacro defhydradio (name _body &rest heads)
975 "Create radios with prefix NAME.
976 _BODY specifies the options; there are none currently.
977 HEADS have the format:
978
979 (TOGGLE-NAME &optional VALUE DOC)
980
981 TOGGLE-NAME will be used along with NAME to generate a variable
982 name and a function that cycles it with the same name. VALUE
983 should be an array. The first element of VALUE will be used to
984 inialize the variable.
985 VALUE defaults to [nil t].
986 DOC defaults to TOGGLE-NAME split and capitalized."
987 (declare (indent defun))
988 `(progn
989 ,@(apply #'append
990 (mapcar (lambda (h)
991 (hydra--radio name h))
992 heads))
993 (defvar ,(intern (format "%S/names" name))
994 ',(mapcar (lambda (h) (intern (format "%S/%S" name (car h))))
995 heads))))
996
997 (defmacro hydra-multipop (lst n)
998 "Return LST's first N elements while removing them."
999 `(if (<= (length ,lst) ,n)
1000 (prog1 ,lst
1001 (setq ,lst nil))
1002 (prog1 ,lst
1003 (setcdr
1004 (nthcdr (1- ,n) (prog1 ,lst (setq ,lst (nthcdr ,n ,lst))))
1005 nil))))
1006
1007 (defun hydra--radio (parent head)
1008 "Generate a hydradio with PARENT from HEAD."
1009 (let* ((name (car head))
1010 (full-name (intern (format "%S/%S" parent name)))
1011 (doc (cadr head))
1012 (val (or (cl-caddr head) [nil t])))
1013 `((defvar ,full-name ,(hydra--quote-maybe (aref val 0)) ,doc)
1014 (put ',full-name 'range ,val)
1015 (defun ,full-name ()
1016 (hydra--cycle-radio ',full-name)))))
1017
1018 (defun hydra--quote-maybe (x)
1019 "Quote X if it's a symbol."
1020 (cond ((null x)
1021 nil)
1022 ((symbolp x)
1023 (list 'quote x))
1024 (t
1025 x)))
1026
1027 (defun hydra--cycle-radio (sym)
1028 "Set SYM to the next value in its range."
1029 (let* ((val (symbol-value sym))
1030 (range (get sym 'range))
1031 (i 0)
1032 (l (length range)))
1033 (setq i (catch 'done
1034 (while (< i l)
1035 (if (equal (aref range i) val)
1036 (throw 'done (1+ i))
1037 (cl-incf i)))
1038 (error "Val not in range for %S" sym)))
1039 (set sym
1040 (aref range
1041 (if (>= i l)
1042 0
1043 i)))))
1044
1045 (provide 'hydra)
1046
1047 ;;; Local Variables:
1048 ;;; outline-regexp: ";;\\*+"
1049 ;;; End:
1050
1051 ;;; hydra.el ends here