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