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