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