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