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