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