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