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