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