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