]> code.delx.au - gnu-emacs-elpa/blob - packages/hydra/hydra.el
Merge commit '4bf7f1c9e46fb819c673e55d8a1891774e139f98' from hydra
[gnu-emacs-elpa] / packages / hydra / 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.3
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 (if (fboundp 'remove-function)
145 (remove-function input-method-function #'hydra--imf)
146 (when hydra--input-method-function
147 (setq input-method-function hydra--input-method-function)
148 (setq hydra--input-method-function nil)))
149 (dolist (frame (frame-list))
150 (with-selected-frame frame
151 (when overriding-terminal-local-map
152 (internal-pop-keymap hydra-curr-map 'overriding-terminal-local-map)
153 (unless hydra--ignore
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 (setq docstring (replace-regexp-in-string "___" "_β_" docstring))
570 (let ((rest (hydra--hint body heads))
571 (start 0)
572 varlist
573 offset)
574 (while (setq start
575 (string-match
576 "\\(?:%\\( ?-?[0-9]*s?\\)\\(`[a-z-A-Z/0-9]+\\|(\\)\\)\\|\\(?:_\\( ?-?[0-9]*?\\)\\(\\[\\|]\\|[-[:alnum:] ~.,;:/|?<>={}*+#%@!&]+?\\)_\\)"
577 docstring start))
578 (cond ((eq ?_ (aref (match-string 0 docstring) 0))
579 (let* ((key (match-string 4 docstring))
580 (key (if (equal key "β") "_" key))
581 (head (assoc key heads)))
582 (if head
583 (progn
584 (push (hydra-fontify-head head body) varlist)
585 (setq docstring
586 (replace-match
587 (or
588 hydra-key-format-spec
589 (concat "%" (match-string 3 docstring) "s"))
590 t nil docstring)))
591 (error "Unrecognized key: _%s_" key))))
592
593 (t
594 (let* ((varp (if (eq ?` (aref (match-string 2 docstring) 0)) 1 0))
595 (spec (match-string 1 docstring))
596 (lspec (length spec)))
597 (setq offset
598 (with-temp-buffer
599 (insert (substring docstring (+ 1 start varp
600 (length spec))))
601 (goto-char (point-min))
602 (push (read (current-buffer)) varlist)
603 (- (point) (point-min))))
604 (when (or (zerop lspec)
605 (/= (aref spec (1- (length spec))) ?s))
606 (setq spec (concat spec "S")))
607 (setq docstring
608 (concat
609 (substring docstring 0 start)
610 "%" spec
611 (substring docstring (+ start offset 1 lspec varp))))))))
612 (if (eq ?\n (aref docstring 0))
613 `(concat (format ,(substring docstring 1) ,@(nreverse varlist))
614 ,rest)
615 `(format ,(replace-regexp-in-string
616 " +$" ""
617 (concat docstring ": "
618 (replace-regexp-in-string
619 "\\(%\\)" "\\1\\1" rest)))))))
620
621 (defun hydra--complain (format-string &rest args)
622 "Forward to (`message' FORMAT-STRING ARGS) unless `hydra-verbose' is nil."
623 (if hydra-verbose
624 (apply #'error format-string args)
625 (apply #'message format-string args)))
626
627 (defun hydra--doc (body-key body-name heads)
628 "Generate a part of Hydra docstring.
629 BODY-KEY is the body key binding.
630 BODY-NAME is the symbol that identifies the Hydra.
631 HEADS is a list of heads."
632 (format
633 "Create a hydra with %s body and the heads:\n\n%s\n\n%s"
634 (if body-key
635 (format "a \"%s\"" body-key)
636 "no")
637 (mapconcat
638 (lambda (x)
639 (format "\"%s\": `%S'" (car x) (cadr x)))
640 heads ",\n")
641 (format "The body can be accessed via `%S'." body-name)))
642
643 (defun hydra--call-interactively (cmd name)
644 "Generate a `call-interactively' statement for CMD.
645 Set `this-command' to NAME."
646 (if (and (symbolp name)
647 (not (memq name '(nil body))))
648 `(progn
649 (setq this-command ',name)
650 (call-interactively #',cmd))
651 `(call-interactively #',cmd)))
652
653 (defun hydra--make-defun (name body doc head
654 keymap body-pre body-before-exit
655 &optional body-after-exit)
656 "Make a defun wrapper, using NAME, BODY, DOC, HEAD, and KEYMAP.
657 NAME and BODY are the arguments to `defhydra'.
658 DOC was generated with `hydra--doc'.
659 HEAD is one of the HEADS passed to `defhydra'.
660 BODY-PRE is added to the start of the wrapper.
661 BODY-BEFORE-EXIT will be called before the hydra quits.
662 BODY-AFTER-EXIT is added to the end of the wrapper."
663 (let ((cmd-name (hydra--head-name head name))
664 (cmd (when (car head)
665 (hydra--make-callable
666 (cadr head))))
667 (doc (if (car head)
668 (format "%s\n\nCall the head: `%S'." doc (cadr head))
669 doc))
670 (hint (intern (format "%S/hint" name)))
671 (body-foreign-keys (hydra--body-foreign-keys body))
672 (body-timeout (plist-get body :timeout))
673 (body-idle (plist-get body :idle)))
674 `(defun ,cmd-name ()
675 ,doc
676 (interactive)
677 (hydra-default-pre)
678 ,@(when body-pre (list body-pre))
679 ,@(if (hydra--head-property head :exit)
680 `((hydra-keyboard-quit)
681 (setq hydra-curr-body-fn ',(intern (format "%S/body" name)))
682 ,@(if body-after-exit
683 `((unwind-protect
684 ,(when cmd
685 (hydra--call-interactively cmd (cadr head)))
686 ,body-after-exit))
687 (when cmd
688 `(,(hydra--call-interactively cmd (cadr head))))))
689 (delq
690 nil
691 `((let ((hydra--ignore ,(not (eq (cadr head) 'body))))
692 (hydra-keyboard-quit)
693 (setq hydra-curr-body-fn ',(intern (format "%S/body" name))))
694 ,(when cmd
695 `(condition-case err
696 ,(hydra--call-interactively cmd (cadr head))
697 ((quit error)
698 (message "%S" err)
699 (unless hydra-lv
700 (sit-for 0.8)))))
701 ,(if (and body-idle (eq (cadr head) 'body))
702 `(hydra-idle-message ,body-idle ,hint)
703 `(when hydra-is-helpful
704 (if hydra-lv
705 (lv-message (eval ,hint))
706 (message (eval ,hint)))))
707 (hydra-set-transient-map
708 ,keymap
709 (lambda () (hydra-keyboard-quit) ,body-before-exit)
710 ,(when body-foreign-keys
711 (list 'quote body-foreign-keys)))
712 ,body-after-exit
713 ,(when body-timeout
714 `(hydra-timeout ,body-timeout))))))))
715
716 (defmacro hydra--make-funcall (sym)
717 "Transform SYM into a `funcall' to call it."
718 `(when (and ,sym (symbolp ,sym))
719 (setq ,sym `(funcall #',,sym))))
720
721 (defun hydra--head-name (h name)
722 "Return the symbol for head H of hydra with NAME."
723 (let ((str (format "%S/%s" name
724 (cond ((symbolp (cadr h))
725 (cadr h))
726 ((and (consp (cadr h))
727 (eq (cl-caadr h) 'function))
728 (cadr (cadr h)))
729 (t
730 (concat "lambda-" (car h)))))))
731 (when (and (hydra--head-property h :exit)
732 (not (memq (cadr h) '(body nil))))
733 (setq str (concat str "-and-exit")))
734 (intern str)))
735
736 (defun hydra--delete-duplicates (heads)
737 "Return HEADS without entries that have the same CMD part.
738 In duplicate HEADS, :cmd-name is modified to whatever they duplicate."
739 (let ((ali '(((hydra-repeat . nil) . hydra-repeat)))
740 res entry)
741 (dolist (h heads)
742 (if (setq entry (assoc (cons (cadr h)
743 (hydra--head-property h :exit))
744 ali))
745 (setf (cl-cdddr h) (plist-put (cl-cdddr h) :cmd-name (cdr entry)))
746 (push (cons (cons (cadr h)
747 (hydra--head-property h :exit))
748 (plist-get (cl-cdddr h) :cmd-name))
749 ali)
750 (push h res)))
751 (nreverse res)))
752
753 (defun hydra--pad (lst n)
754 "Pad LST with nil until length N."
755 (let ((len (length lst)))
756 (if (= len n)
757 lst
758 (append lst (make-list (- n len) nil)))))
759
760 (defmacro hydra-multipop (lst n)
761 "Return LST's first N elements while removing them."
762 `(if (<= (length ,lst) ,n)
763 (prog1 ,lst
764 (setq ,lst nil))
765 (prog1 ,lst
766 (setcdr
767 (nthcdr (1- ,n) (prog1 ,lst (setq ,lst (nthcdr ,n ,lst))))
768 nil))))
769
770 (defun hydra--matrix (lst rows cols)
771 "Create a matrix from elements of LST.
772 The matrix size is ROWS times COLS."
773 (let ((ls (copy-sequence lst))
774 res)
775 (dotimes (_c cols)
776 (push (hydra--pad (hydra-multipop ls rows) rows) res))
777 (nreverse res)))
778
779 (defun hydra--cell (fstr names)
780 "Format a rectangular cell based on FSTR and NAMES.
781 FSTR is a format-style string with two string inputs: one for the
782 doc and one for the symbol name.
783 NAMES is a list of variables."
784 (let ((len (cl-reduce
785 (lambda (acc it) (max (length (symbol-name it)) acc))
786 names
787 :initial-value 0)))
788 (mapconcat
789 (lambda (sym)
790 (if sym
791 (format fstr
792 (documentation-property sym 'variable-documentation)
793 (let ((name (symbol-name sym)))
794 (concat name (make-string (- len (length name)) ?^)))
795 sym)
796 ""))
797 names
798 "\n")))
799
800 (defun hydra--vconcat (strs &optional joiner)
801 "Glue STRS vertically. They must be the same height.
802 JOINER is a function similar to `concat'."
803 (setq joiner (or joiner #'concat))
804 (mapconcat
805 (lambda (s)
806 (if (string-match " +$" s)
807 (replace-match "" nil nil s)
808 s))
809 (apply #'cl-mapcar joiner
810 (mapcar
811 (lambda (s) (split-string s "\n"))
812 strs))
813 "\n"))
814
815 (defvar hydra-cell-format "% -20s %% -8`%s"
816 "The default format for docstring cells.")
817
818 (defun hydra--table (names rows cols &optional cell-formats)
819 "Format a `format'-style table from variables in NAMES.
820 The size of the table is ROWS times COLS.
821 CELL-FORMATS are `format' strings for each column.
822 If CELL-FORMATS is a string, it's used for all columns.
823 If CELL-FORMATS is nil, `hydra-cell-format' is used for all columns."
824 (setq cell-formats
825 (cond ((null cell-formats)
826 (make-list cols hydra-cell-format))
827 ((stringp cell-formats)
828 (make-list cols cell-formats))
829 (t
830 cell-formats)))
831 (hydra--vconcat
832 (cl-mapcar
833 #'hydra--cell
834 cell-formats
835 (hydra--matrix names rows cols))
836 (lambda (&rest x)
837 (mapconcat #'identity x " "))))
838
839 (defun hydra-reset-radios (names)
840 "Set varibles NAMES to their defaults.
841 NAMES should be defined by `defhydradio' or similar."
842 (dolist (n names)
843 (set n (aref (get n 'range) 0))))
844
845 (defun hydra-idle-message (secs hint)
846 "In SECS seconds display HINT."
847 (cancel-timer hydra-message-timer)
848 (setq hydra-message-timer (timer-create))
849 (timer-set-time hydra-message-timer
850 (timer-relative-time (current-time) secs))
851 (timer-set-function
852 hydra-message-timer
853 (lambda ()
854 (when hydra-is-helpful
855 (if hydra-lv
856 (lv-message (eval hint))
857 (message (eval hint))))
858 (cancel-timer hydra-message-timer)))
859 (timer-activate hydra-message-timer))
860
861 (defun hydra-timeout (secs &optional function)
862 "In SECS seconds call FUNCTION, then function `hydra-keyboard-quit'.
863 Cancel the previous `hydra-timeout'."
864 (cancel-timer hydra-timeout-timer)
865 (setq hydra-timeout-timer (timer-create))
866 (timer-set-time hydra-timeout-timer
867 (timer-relative-time (current-time) secs))
868 (timer-set-function
869 hydra-timeout-timer
870 `(lambda ()
871 ,(when function
872 `(funcall ,function))
873 (hydra-keyboard-quit)))
874 (timer-activate hydra-timeout-timer))
875
876 ;;* Macros
877 ;;;###autoload
878 (defmacro defhydra (name body &optional docstring &rest heads)
879 "Create a Hydra - a family of functions with prefix NAME.
880
881 NAME should be a symbol, it will be the prefix of all functions
882 defined here.
883
884 BODY has the format:
885
886 (BODY-MAP BODY-KEY &rest BODY-PLIST)
887
888 DOCSTRING will be displayed in the echo area to identify the
889 Hydra. When DOCSTRING starts with a newline, special Ruby-style
890 substitution will be performed by `hydra--format'.
891
892 Functions are created on basis of HEADS, each of which has the
893 format:
894
895 (KEY CMD &optional HINT &rest PLIST)
896
897 BODY-MAP is a keymap; `global-map' is used quite often. Each
898 function generated from HEADS will be bound in BODY-MAP to
899 BODY-KEY + KEY (both are strings passed to `kbd'), and will set
900 the transient map so that all following heads can be called
901 though KEY only. BODY-KEY can be an empty string.
902
903 CMD is a callable expression: either an interactive function
904 name, or an interactive lambda, or a single sexp (it will be
905 wrapped in an interactive lambda).
906
907 HINT is a short string that identifies its head. It will be
908 printed beside KEY in the echo erea if `hydra-is-helpful' is not
909 nil. If you don't even want the KEY to be printed, set HINT
910 explicitly to nil.
911
912 The heads inherit their PLIST from BODY-PLIST and are allowed to
913 override some keys. The keys recognized are :exit and :bind.
914 :exit can be:
915
916 - nil (default): this head will continue the Hydra state.
917 - t: this head will stop the Hydra state.
918
919 :bind can be:
920 - nil: this head will not be bound in BODY-MAP.
921 - a lambda taking KEY and CMD used to bind a head.
922
923 It is possible to omit both BODY-MAP and BODY-KEY if you don't
924 want to bind anything. In that case, typically you will bind the
925 generated NAME/body command. This command is also the return
926 result of `defhydra'."
927 (declare (indent defun))
928 (cond ((stringp docstring))
929 ((and (consp docstring)
930 (memq (car docstring) '(hydra--table concat format)))
931 (setq docstring (concat "\n" (eval docstring))))
932 (t
933 (setq heads (cons docstring heads))
934 (setq docstring "hydra")))
935 (when (keywordp (car body))
936 (setq body (cons nil (cons nil body))))
937 (condition-case-unless-debug err
938 (let* ((keymap (copy-keymap hydra-base-map))
939 (keymap-name (intern (format "%S/keymap" name)))
940 (body-name (intern (format "%S/body" name)))
941 (body-key (cadr body))
942 (body-plist (cddr body))
943 (body-map (or (car body)
944 (plist-get body-plist :bind)))
945 (body-pre (plist-get body-plist :pre))
946 (body-body-pre (plist-get body-plist :body-pre))
947 (body-before-exit (or (plist-get body-plist :post)
948 (plist-get body-plist :before-exit)))
949 (body-after-exit (plist-get body-plist :after-exit))
950 (body-inherit (plist-get body-plist :inherit))
951 (body-foreign-keys (hydra--body-foreign-keys body))
952 (body-exit (hydra--body-exit body)))
953 (dolist (base body-inherit)
954 (setq heads (append heads (copy-sequence (eval base)))))
955 (dolist (h heads)
956 (let ((len (length h)))
957 (cond ((< len 2)
958 (error "Each head should have at least two items: %S" h))
959 ((= len 2)
960 (setcdr (cdr h)
961 (list
962 (hydra-plist-get-default body-plist :hint "")))
963 (setcdr (nthcdr 2 h) (list :exit body-exit)))
964 (t
965 (let ((hint (cl-caddr h)))
966 (unless (or (null hint)
967 (stringp hint))
968 (setcdr (cdr h) (cons
969 (hydra-plist-get-default body-plist :hint "")
970 (cddr h)))))
971 (let ((hint-and-plist (cddr h)))
972 (if (null (cdr hint-and-plist))
973 (setcdr hint-and-plist (list :exit body-exit))
974 (let* ((plist (cl-cdddr h))
975 (h-color (plist-get plist :color)))
976 (if h-color
977 (progn
978 (plist-put plist :exit
979 (cl-case h-color
980 ((blue teal) t)
981 (t nil)))
982 (cl-remf (cl-cdddr h) :color))
983 (let ((h-exit (hydra-plist-get-default plist :exit 'default)))
984 (plist-put plist :exit
985 (if (eq h-exit 'default)
986 body-exit
987 h-exit))))))))))
988 (plist-put (cl-cdddr h) :cmd-name (hydra--head-name h name))
989 (when (null (cadr h)) (plist-put (cl-cdddr h) :exit t)))
990 (let ((doc (hydra--doc body-key body-name heads))
991 (heads-nodup (hydra--delete-duplicates heads)))
992 (mapc
993 (lambda (x)
994 (define-key keymap (kbd (car x))
995 (plist-get (cl-cdddr x) :cmd-name)))
996 heads)
997 (hydra--make-funcall body-pre)
998 (hydra--make-funcall body-body-pre)
999 (hydra--make-funcall body-before-exit)
1000 (hydra--make-funcall body-after-exit)
1001 (when (memq body-foreign-keys '(run warn))
1002 (unless (cl-some
1003 (lambda (h)
1004 (hydra--head-property h :exit))
1005 heads)
1006 (error
1007 "An %S Hydra must have at least one blue head in order to exit"
1008 body-foreign-keys)))
1009 `(progn
1010 ;; create keymap
1011 (set (defvar ,keymap-name
1012 nil
1013 ,(format "Keymap for %S." name))
1014 ',keymap)
1015 ;; declare heads
1016 (set (defvar ,(intern (format "%S/heads" name))
1017 nil
1018 ,(format "Heads for %S." name))
1019 ',(mapcar (lambda (h)
1020 (let ((j (copy-sequence h)))
1021 (cl-remf (cl-cdddr j) :cmd-name)
1022 j))
1023 heads))
1024 (set
1025 (defvar ,(intern (format "%S/hint" name)) nil
1026 ,(format "Dynamic hint for %S." name))
1027 ',(hydra--format name body docstring heads))
1028 ;; create defuns
1029 ,@(mapcar
1030 (lambda (head)
1031 (hydra--make-defun name body doc head keymap-name
1032 body-pre
1033 body-before-exit
1034 body-after-exit))
1035 heads-nodup)
1036 ;; free up keymap prefix
1037 ,@(unless (or (null body-key)
1038 (null body-map)
1039 (hydra--callablep body-map))
1040 `((unless (keymapp (lookup-key ,body-map (kbd ,body-key)))
1041 (define-key ,body-map (kbd ,body-key) nil))))
1042 ;; bind keys
1043 ,@(delq nil
1044 (mapcar
1045 (lambda (head)
1046 (let ((name (hydra--head-property head :cmd-name)))
1047 (when (and (cadr head)
1048 (or body-key body-map))
1049 (let ((bind (hydra--head-property head :bind body-map))
1050 (final-key
1051 (if body-key
1052 (vconcat (kbd body-key) (kbd (car head)))
1053 (kbd (car head)))))
1054 (cond ((null bind) nil)
1055 ((hydra--callablep bind)
1056 `(funcall ,bind ,final-key (function ,name)))
1057 ((and (symbolp bind)
1058 (if (boundp bind)
1059 (keymapp (symbol-value bind))
1060 t))
1061 `(define-key ,bind ,final-key (quote ,name)))
1062 (t
1063 (error "Invalid :bind property `%S' for head %S" bind head)))))))
1064 heads))
1065 ,(hydra--make-defun
1066 name body doc '(nil body)
1067 keymap-name
1068 (or body-body-pre body-pre) body-before-exit
1069 '(setq prefix-arg current-prefix-arg)))))
1070 (error
1071 (hydra--complain "Error in defhydra %S: %s" name (cdr err))
1072 nil)))
1073
1074 (defmacro defhydradio (name _body &rest heads)
1075 "Create radios with prefix NAME.
1076 _BODY specifies the options; there are none currently.
1077 HEADS have the format:
1078
1079 (TOGGLE-NAME &optional VALUE DOC)
1080
1081 TOGGLE-NAME will be used along with NAME to generate a variable
1082 name and a function that cycles it with the same name. VALUE
1083 should be an array. The first element of VALUE will be used to
1084 inialize the variable.
1085 VALUE defaults to [nil t].
1086 DOC defaults to TOGGLE-NAME split and capitalized."
1087 (declare (indent defun))
1088 `(progn
1089 ,@(apply #'append
1090 (mapcar (lambda (h)
1091 (hydra--radio name h))
1092 heads))
1093 (defvar ,(intern (format "%S/names" name))
1094 ',(mapcar (lambda (h) (intern (format "%S/%S" name (car h))))
1095 heads))))
1096
1097 (defun hydra--radio (parent head)
1098 "Generate a hydradio with PARENT from HEAD."
1099 (let* ((name (car head))
1100 (full-name (intern (format "%S/%S" parent name)))
1101 (doc (cadr head))
1102 (val (or (cl-caddr head) [nil t])))
1103 `((defvar ,full-name ,(hydra--quote-maybe (aref val 0)) ,doc)
1104 (put ',full-name 'range ,val)
1105 (defun ,full-name ()
1106 (hydra--cycle-radio ',full-name)))))
1107
1108 (defun hydra--quote-maybe (x)
1109 "Quote X if it's a symbol."
1110 (cond ((null x)
1111 nil)
1112 ((symbolp x)
1113 (list 'quote x))
1114 (t
1115 x)))
1116
1117 (defun hydra--cycle-radio (sym)
1118 "Set SYM to the next value in its range."
1119 (let* ((val (symbol-value sym))
1120 (range (get sym 'range))
1121 (i 0)
1122 (l (length range)))
1123 (setq i (catch 'done
1124 (while (< i l)
1125 (if (equal (aref range i) val)
1126 (throw 'done (1+ i))
1127 (cl-incf i)))
1128 (error "Val not in range for %S" sym)))
1129 (set sym
1130 (aref range
1131 (if (>= i l)
1132 0
1133 i)))))
1134
1135 (defvar hydra-pause-ring (make-ring 10)
1136 "Ring for paused hydras.")
1137
1138 (defun hydra-pause-resume ()
1139 "Quit the current hydra and save it to the stack.
1140 If there's no active hydra, pop one from the stack and call its body.
1141 If the stack is empty, call the last hydra's body."
1142 (interactive)
1143 (cond (hydra-curr-map
1144 (ring-insert hydra-pause-ring hydra-curr-body-fn)
1145 (hydra-keyboard-quit))
1146 ((zerop (ring-length hydra-pause-ring))
1147 (funcall hydra-curr-body-fn))
1148 (t
1149 (funcall (ring-remove hydra-pause-ring 0)))))
1150
1151 ;; Local Variables:
1152 ;; outline-regexp: ";;\\([;*]+ [^\s\t\n]\\|###autoload\\)\\|("
1153 ;; indent-tabs-mode: nil
1154 ;; End:
1155
1156 (provide 'hydra)
1157
1158 ;;; hydra.el ends here