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