-
Notifications
You must be signed in to change notification settings - Fork 0
/
deianira.el
1471 lines (1310 loc) · 59.5 KB
/
deianira.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; deianira.el --- Hydra-ize every key sequence -*- lexical-binding: t; -*-
;; (read-symbol-shorthands . '("dei-" . "deianira-"))
;; Copyright (C) 2018-2023 Martin Edström
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;; This file is not part of GNU Emacs.
;; Author: <[email protected]>
;; Created: 2018-08-03
;; Version: 0.2.9-pre
;; Keywords: abbrev convenience
;; Homepage: https://github.com/meedstrom/deianira
;; Package-Requires: ((emacs "28") (asyncloop "0.5.1") (massmapper "0.1.4") (compat "29.1.4.4") (hydra "0.15.0") (named-timer "0.1") (dash "2.19.1"))
;;; Commentary:
;; See the README.org. You may find it by visiting:
;; https://github.com/meedstrom/deianira
;;
;; or by evalling (but your package manager probably left out the README):
;; (find-file (file-name-directory (find-library-name "deianira")))
;;
;; or with Straight:
;; M-x straight-visit-package RET deianira RET
;;; Code:
(defgroup deianira nil
"Hydra everywhere."
;; :link '(info-link "(deianira)")
:group 'keyboard)
;; builtin dependencies
(require 'subr-x)
(require 'cl-lib)
;; external dependencies
(require 'dash)
(require 'hydra)
(require 'compat)
(require 'asyncloop) ;; was part of this package
(require 'massmapper-lib) ;; was part of this package
;; muffle the compiler
(declare-function #'dei-A/body "deianira" nil t)
(declare-function #'dei-C/body "deianira" nil t)
(declare-function #'dei-H/body "deianira" nil t)
(declare-function #'dei-M/body "deianira" nil t)
(declare-function #'dei-s/body "deianira" nil t)
;; obsolete
(defun dei-homogenize-all-keymaps ()
(display-warning 'massmapper "Deprecated function dei-homogenize-all-keymaps, use massmapper-homogenize"))
;;;; User settings
(defcustom dei-hydra-keys
"1234567890qwertyuiopasdfghjkl;zxcvbnm,./"
"Keys to show in hydra hint\; default reflects an US QWERTY keyboard.
Length should be divisible by `dei-columns'. In other words, if
you have 10 columns this can be 30 or 40 characters, if you
want 11 columns this can be 33 or 44 characters, and so on.
The order matters\; it determines the order in which the keys are
displayed.
Unfortunately I have no advice if you want to show more oddly
located (on QWERTY) keys such as ` or =, but these would waste
columns on an already cramped grid."
:type 'string
:group 'deianira)
(defcustom dei-all-shifted-symbols
"~!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:\"ZXCVBNM<>?"
"Characters that imply Shift pressed\; default reflects an US keyboard.
You can add or remove any characters, in any order. You can even
merge two or more regional layouts' sets of shift-symbols,
because inclusion in this list mostly means that Deianira will do
less with them.
Note also that even if you usually use a non-US layout, you do
not need to modify this variable if you never bind non-US keys to
commands anyway."
:type 'string
:group 'deianira)
(defcustom dei-columns 10
"Amount of columns to display in the hydra hint.
When customizing, please also customize `dei-hydra-keys'."
:type 'number
:group 'deianira)
(defcustom dei-debug nil
"Whether to enable debugging checks."
:type 'boolean
:group 'deianira)
(defcustom dei-quasiquitter-keys
'("C-c c"
"C-x l" ;; for testing
)
"Keys that send you to the root hydra.
Note that if you use Massmapper (see manual), the hydras are
generated afterwards, consulting this list then. So it is safe
to only refer to e.g. \"C-c c\" even if it's going to be a clone
of \"C-c C-c\". In fact, only \"C-c c\" will have an effect,
probably."
:type '(repeat key)
:group 'deianira
:set (lambda (var new)
(set-default var (--map (massmapper--normalize
(key-description (key-parse it))) new))))
(defcustom dei-quasiquitter-commands
'(set-mark-command
rectangle-mark-mode)
"Commands that send you to the root hydra."
:type '(repeat symbol)
:group 'deianira)
(defcustom dei-inserting-quitters
'("SPC"
"RET")
"Keys guaranteed to slay the hydra as well as self-insert.
Note that you do not need to specify shift symbols, as
`dei-all-shifted-symbols' is basically added to this."
:type '(repeat key)
:group 'deianira
:set (lambda (var new)
(set-default var (--map (massmapper--normalize
(key-description (key-parse it))) new))))
(defcustom dei-stemless-quitters
'("<menu>"
"C-g")
"Keys guaranteed to behave like themselves, instead of the key plus a prefix.
Also guaranteed to slay the hydra.
This can be used to ensure that when you're in any hydra, let's
say the hydra for the \"C-x a\" keymap, typing C-g will not send
to Emacs \"C-x a C-g\", but simply C-g."
:type '(repeat key)
:group 'deianira
:set (lambda (var new)
(set-default var (--map (massmapper--normalize
(key-description (key-parse it))) new))))
(defcustom dei-quitter-keys
'()
"Key sequences guaranteed to slay the hydra.
Note that if you use Massmapper (see manual), the hydras are
generated afterwards, consulting this list then. So it is safe
to only refer to e.g. \"C-c c\" even if it's going to be a clone
of \"C-c C-c\". In fact, only \"C-c c\" will have an effect,
probably."
:type '(repeat key)
:group 'deianira
:set (lambda (var new)
(set-default var (--map (massmapper--normalize
(key-description (key-parse it))) new))))
(defcustom dei-quitter-commands
'(keyboard-quit
keyboard-escape-quit
minibuffer-keyboard-quit
abort-recursive-edit
dei--call-and-return-to-root
dei--call-and-return-to-parent
isearch-forward
isearch-forward-regexp
isearch-backward
isearch-backward-regexp
query-replace
query-replace-regexp
doom/escape
doom/restart
doom/restart-and-restore
magit-status
dired
dired-jump
re-builder
;; ffap-other-frame
;; make-frame-command
;; other-frame
kill-emacs
save-buffers-kill-emacs
save-buffers-kill-terminal
+lookup/online
+doom-dashboard/open
org-noter
org-agenda
org-roam-capture
org-capture)
"Commands guaranteed to slay the hydra.
Note that you usually don't need to add commands that focus the
minibuffer, as Deianira tries to slay the hydra automatically
when that happens."
:type '(repeat symbol)
:group 'deianira)
(defcustom dei-extra-heads
'()
"Heads to add to every hydra. See `defhydra' for the format."
:type '(repeat sexp)
:group 'deianira)
(defcustom dei-ignore
nil
"Regexp for key sequences to avoid making hydras for.
To ignore all C- sequences, write C-."
:group 'deianira
:type 'string)
;; FIXME: broken in the Custom interface
(defcustom dei-invisible-leafs
(append
(split-string
"`-=[]\\'"
"" t)
(split-string
(concat
" <left> <right> <up> <down> SPC"
" <print> <insert> <next> <prior> <home> <end> <menu>"
" TAB <tab> <iso-lefttab> <backtab>")))
"Keys that should not behave as foreign keys.
By default, typing a key not in `dei-hydra-keys' nor this list
will result in calling that key's normal binding, as if there was
no active hydra (in Hydra jargon, it behaves as a foreign key).
Inclusion in this list means that key will be prepended with a
prefix, even though you can't see the key in the hint.
Example:
If TAB is not a member of this list, typing the three keystrokes
<Ctrl> x TAB calls the binding of TAB.
If TAB is a member of this list, it's taken as a leaf grafted
onto the hydra's corresponding stem. So typing the three
keystrokes <Ctrl> x TAB calls the binding of C-x TAB."
:type '(repeat key)
:group 'deianira
:set (lambda (var new)
(set-default var (--map (massmapper--normalize
(key-description (key-parse it))) new))))
;;;; Background facts
(defun dei--all-shifted-symbols-list-recalc ()
"Make new value for `dei--all-shifted-symbols-list'."
(split-string dei-all-shifted-symbols "" t))
(defvar dei--all-shifted-symbols-list (dei--all-shifted-symbols-list-recalc)
"Cache variable, not to be modified directly.
Customize `dei-all-shifted-symbols' instead.")
(defun dei--hydra-keys-list-recalc ()
"Make new value for `dei--hydra-keys-list'."
(split-string dei-hydra-keys "" t))
(defvar dei--hydra-keys-list (dei--hydra-keys-list-recalc)
"Cache variable, not to be modified directly.
Customize `dei-hydra-keys' instead.")
(defun dei--colwidth-recalc (width)
"Recalculate `dei--colwidth' based on frame width WIDTH."
;; Minus four because of the legend (there's space reserved around a,b,c in
;; "a: COMMAND b: COMMAND c: COMMAND ...".
(max 1 (- (floor width dei-columns) 4)))
(defvar dei--colwidth (dei--colwidth-recalc (frame-width))
"Cache variable, not to be modified directly.")
(defun dei--filler-recalc (colwidth)
"Recalculate `dei--filler' based on COLWIDTH.
See `dei--colwidth-recalc'."
(make-string colwidth (string-to-char " ")))
(defvar dei--filler (dei--filler-recalc dei--colwidth)
"Cache variable, not to be modified directly.")
;;;; Library of random stuff
(defun dei--hydra-active-p ()
"Return t if a hydra is active and awaiting input."
(not (null hydra-curr-map)))
(defun dei--slay (&rest args)
"Slay active hydra and return ARGS."
(when (dei--hydra-active-p)
(setq hydra-deactivate t)
(call-interactively #'hydra-keyboard-quit))
args)
(defun dei--dub-hydra-from-key (keydesc)
"Example: if KEYDESC is \"C-x C-a\", return \"dei-Cxa\"."
(declare (pure t) (side-effect-free t))
(if (string-empty-p keydesc)
nil
(let* ((steps (split-string keydesc " "))
(first-is-long (> (length (car steps)) 1)))
(and dei-debug
first-is-long
;; Never try to represent chords beyond the first. This restriction
;; allows compact notation with dashes and spaces stripped. Else
;; there would be ambiguity due to confusing chords and keys for
;; each other (even banning upcase keys leaves s-).
(cl-assert (not (string-match-p massmapper--modifier-safe-re
(substring keydesc 2)))))
(concat "dei-"
;; root modifier
(and first-is-long
(string-match-p massmapper--modifier-safe-re
(substring keydesc 0 2))
(substring keydesc 0 1))
;; the rest
(string-join
(cl-loop
for step in steps
as leaf = (massmapper--get-leaf step)
collect
;; TODO: Before transitioning to this, ensure <tab> and TAB
;; don't generate diff hydras
;; (cond (;; Eliminate ambiguity by downcasing capitals
;; (and (= 1 (length leaf))
;; (seq-contains-p dei-all-shifted-symbols
;; (string-to-char leaf)))
;; (concat "S" (downcase leaf)))
;; ;; Make function keys compact (and stay unambiguous
;; ;; by upcasing them instead)
;; ((string-match-p "<.*?>" leaf)
;; (upcase (string-replace "-" "" (substring 1 -1 leaf))))
;; (t
;; leaf))
;; Wrap RET SPC DEL etc in <>, to distinguish from
;; (extremely unusual) all-caps seqs such as T A B
(if (member leaf '("NUL" "RET" "TAB" "LFD" "ESC" "SPC" "DEL"))
(concat "<" leaf ">")
leaf)))))))
(defun dei--dub-hydra-from-stem (stem)
"Example: if STEM is \"C-x C-\", return \"dei-Cx\"."
(declare (pure t) (side-effect-free t))
(if (string-empty-p stem)
nil
(if (= 2 (length stem))
(concat "dei-" (substring stem 0 1)) ;; stem is just C- or M- etc
(dei--dub-hydra-from-key (string-join (butlast (split-string stem " "))
" ")))))
(defun dei--dub-hydra-from-key-or-stem (keydesc-or-stem)
(if (key-valid-p keydesc-or-stem)
(dei--dub-hydra-from-key keydesc-or-stem)
(dei--dub-hydra-from-stem keydesc-or-stem)))
;; This is used by `dei--head-arg-cmd'
(defun dei--corresponding-hydra (keydesc-or-stem &optional leaf)
"Return the hydra body that corresponds to a key.
If only one argument is given, KEYDESC-OR-STEM, it should be a
valid key description. If supplying LEAF, then KEYDESC-OR-STEM
should be a dangling stem, as they will be concatenated to make a
valid key description."
(let ((keydesc (concat keydesc-or-stem leaf)))
(if (string-empty-p keydesc)
nil
(intern (concat
(dei--dub-hydra-from-key-or-stem keydesc)
"/body")))))
;; REVIEW: write test for it with a key-simulator
(defun dei-universal-argument (arg)
"Enter a nonum hydra and activate the universal argument."
(interactive "p")
(prefix-command-preserve-state)
(call-interactively
(intern (concat
(substring (symbol-name hydra-curr-body-fn) 0 -5) ;; chop "/body"
"-nonum/body")))
(hydra--universal-argument arg))
(defun dei-negative-argument (arg)
"Enter a nonum hydra and activate the negative argument."
(interactive "p")
(prefix-command-preserve-state)
(call-interactively
(intern (concat
(substring (symbol-name hydra-curr-body-fn) 0 -5) ;; chop "/body"
"-nonum/body")))
(hydra--negative-argument arg))
;; quasiquit
;; unused
(defun dei--call-and-return-to-root (keydesc)
"For use in a hydra: call the key binding of KEYDESC.
Then return to the root hydra.
Nice in some cases, like C-c C-c for which it's often desirable
to end up in the Control root hydra rather than exit altogether.
Say you want to call it for each item in a list of Org headings,
and `next-line' is bound to the standard C-n, then you want to be
able to type nccnccnccncc."
(interactive)
(call-interactively (key-binding (key-parse keydesc)))
(let ((init (substring keydesc 0 2)))
;; REVIEW: is it better to use call-interactively?
(cond ((string-search "C-" init) (dei-C/body))
((string-search "M-" init) (dei-M/body))
((string-search "s-" init) (dei-s/body))
((string-search "H-" init) (dei-H/body))
((string-search "A-" init) (dei-A/body)))))
;; unused; another sense of quasiquit
;; TODO: come up with a good name and implement a defcustom
(defun dei--call-and-return-to-parent (keydesc)
"For use in a hydra: call the key binding of KEYDESC.
Then return to the parent hydra."
(interactive)
(call-interactively (key-binding (key-parse keydesc)))
(if-let ((parent (dei--corresponding-hydra
(massmapper--parent-stem
(massmapper--drop-leaf keydesc)))))
(call-interactively parent)
(hydra-keyboard-quit)))
;;;; Main
(defvar dei--old-hydra-cell-format nil
"Backup for `hydra-cell-format'.")
(defvar dei--old-hydra-C-u nil
"Backup for key binding of \"C-u\" in `hydra-base-map'.")
(declare-function #'ido-read-internal "ido")
(declare-function #'ivy-read "ivy")
(declare-function #'helm "helm-core")
(defvar dei--interrupts-counter 0
"How many times the hydra maker was interrupted recently.")
(defun dei--interrupts-decrement ()
"Decrement `dei--interrupts-counter' unless already zero."
(unless (zerop dei--interrupts-counter)
(cl-decf dei--interrupts-counter)))
(defun dei--on-which-keys (command &optional keymap)
"Find to which keys COMMAND is bound.
Optional argument KEYMAP means look only in that keymap."
(->> (where-is-internal command (when keymap (list keymap)))
(-map #'key-description)
(--remove (string-match-p dei--ignore-regexp-merged it))))
(defvar dei--give-up nil)
;;;###autoload
(define-minor-mode deianira-mode
"Set up hooks to forge hydras, and in the darkness bind them."
:global t
:lighter " dei"
:group 'deianira
:keymap (make-sparse-keymap)
(if deianira-mode
(progn
(setq dei--interrupts-counter 0)
(setq dei--ctr-decay-timer
(run-with-timer 60 60 #'dei--interrupts-decrement))
(setq dei--old-hydra-cell-format hydra-cell-format)
(setq dei--old-hydra-C-u (keymap-lookup hydra-base-map "C-u"))
(setq hydra-cell-format "% -20s %% -11`%s")
(setq dei--give-up nil)
(keymap-unset hydra-base-map "C-u" t)
;; REVIEW: I may prefer to just instruct the user to set this stuff
;; themselves, so they get familiar with the variables
(cl-loop for key in (dei--on-which-keys #'hydra--universal-argument hydra-base-map)
do
(cl-pushnew `( ,key dei-universal-argument nil :exit t) dei-extra-heads)
(setq dei-invisible-leafs (remove key dei-invisible-leafs)))
(cl-loop for key in (dei--on-which-keys #'hydra--negative-argument hydra-base-map)
do
(cl-pushnew `( ,key dei-negative-argument nil :exit t) dei-extra-heads)
(setq dei-invisible-leafs (remove key dei-invisible-leafs)))
;; REVIEW: Still necessary?
(cl-loop for key in (dei--on-which-keys #'hydra-repeat hydra-base-map)
do (cl-pushnew `( ,key hydra-repeat nil) dei-extra-heads))
(add-hook 'before-make-frame-hook #'dei--slay)
(add-hook 'minibuffer-setup-hook #'dei--slay)
(advice-add #'completing-read :before #'dei--slay)
(advice-add #'read-key :before #'dei--slay)
(advice-add #'read-char :before #'dei--slay)
(advice-add #'read-event :before #'dei--slay)
(advice-add #'ido-read-internal :before #'dei--slay)
(advice-add #'ivy-read :before #'dei--slay)
(advice-add #'helm :before #'dei--slay)
(add-hook 'window-buffer-change-functions #'dei-make-hydras-maybe 56)
(add-hook 'window-selection-change-functions #'dei-make-hydras-maybe)
;; Unfortunately this is triggered every time hydra calls a command.
;; Maybe upstream would consider it a bug:
;; (add-hook 'after-change-major-mode-hook #'dei-make-hydras-maybe)
;; With auto-save-visited-mode, this watcher is triggered every 5
;; seconds. No big deal but clutters the log buffer:
;; (add-variable-watcher 'local-minor-modes #'dei-make-hydras-maybe)
(when (and dei-warn-hydra-is-helpful
(not hydra-is-helpful))
(message "hydra-is-helpful is nil! If intended, disable `%S'"
'dei-warn-hydra-is-helpful))
(when (or (bound-and-true-p dei-keymap-found-hook)
(bound-and-true-p dei-homogenizing-winners))
(deianira-mode 0)
(user-error "%s%s%s"
"Deianira has split into two packages,"
" you'll want to add the massmapper package:"
" https://github.com/meedstrom/massmapper"))
(when (null massmapper-homogenizing-winners)
(deianira-mode 0)
(user-error "Disabling Deianira, please customize massmapper-homogenizing-winners")))
(when dei--loop (asyncloop-cancel dei--loop))
(when (timerp dei--ctr-decay-timer) (cancel-timer dei--ctr-decay-timer))
(setq hydra-cell-format (or dei--old-hydra-cell-format "% -20s %% -8`%s"))
(keymap-set hydra-base-map "C-u" dei--old-hydra-C-u)
(remove-hook 'window-buffer-change-functions #'dei-make-hydras-maybe)
(remove-hook 'window-selection-change-functions #'dei-make-hydras-maybe)
(remove-hook 'before-make-frame-hook #'dei--slay)
(remove-hook 'minibuffer-setup-hook #'dei--slay)
(advice-remove #'completing-read #'dei--slay)
(advice-remove #'read-key #'dei--slay)
(advice-remove #'read-event #'dei--slay)
(advice-remove #'read-char #'dei--slay)
(advice-remove #'ido-read-internal #'dei--slay)
(advice-remove #'ivy-read #'dei--slay)
(advice-remove #'helm #'dei--slay)))
(defcustom dei-warn-hydra-is-helpful t
"Whether to warn that `hydra-is-helpful' is nil.")
(defvar dei--ctr-decay-timer nil)
(defvar dei--loop nil)
(defconst dei--ersatz-keys-alist
'((dei-ersatz-alt . dei-A/body)
(dei-ersatz-control . dei-C/body)
(dei-ersatz-hyper . dei-H/body)
(dei-ersatz-meta . dei-M/body)
(dei-ersatz-super . dei-s/body))
"Table associating the ersatz keys with root hydras.
Never expected to change. Customize `dei-ersatz-alt' & co
instead.")
(defvar dei--hidden-obarray (obarray-make)
"Place to store the huge variable named \"flocks\".
Reason not to store it in the global obarray as simply just
another variable \"dei--flocks\" is that when the user reads the
source code and happens to place point on \"dei--flocks\", eldoc
chokes Emacs for minutes.")
(defun dei--set-ersatz-key (sym newkey)
"Bind SYM to NEWKEY, and help other code cope with the change."
;; Reset all hydras because value gets hardcoded by
;; `dei--specify-extra-heads'
(obarray-remove dei--hidden-obarray "flocks")
;; Unbind last key in case it was different
(when (boundp sym)
(keymap-unset deianira-mode-map (symbol-value sym) t))
;; Bind new key
(keymap-set deianira-mode-map newkey (alist-get sym dei--ersatz-keys-alist))
(set-default sym newkey))
;; FIXME: these options are broken in the Custom interface
(defcustom dei-ersatz-alt "<hiragana-katakana>"
"Key that represents Alt."
:type 'key
:group 'deianira
:set #'dei--set-ersatz-key)
(defcustom dei-ersatz-control "<katakana>"
"Key that represents Control."
:type 'key
:group 'deianira
:set #'dei--set-ersatz-key)
(defcustom dei-ersatz-hyper "<hiragana>"
"Key that represents Hyper."
:type 'key
:group 'deianira
:set #'dei--set-ersatz-key)
(defcustom dei-ersatz-meta "<muhenkan>"
"Key that represents Meta."
:type 'key
:group 'deianira
:set #'dei--set-ersatz-key)
(defcustom dei-ersatz-super "<henkan>"
"Key that represents Super."
:type 'key
:group 'deianira
:set #'dei--set-ersatz-key)
;;;; Hydra blueprinting
(defvar dei--hydrable-prefixes-with-ancestors nil
"List of keys that may turn into hydras.")
;; Head arguments
(defun dei--head-arg-cmd (stem leaf)
"See `dei--head'."
(let ((key (concat stem leaf)))
(cond
;; Sub-hydra
((member key dei--hydrable-prefixes-with-ancestors)
(dei--corresponding-hydra key))
;; Quasi-quitter, meaning call key and return to root hydra
;; Only works if root hydra is a modifier, not if it's <f1> or other keys!
((and (massmapper--key-starts-with-modifier key)
(or (member (key-binding (key-parse key)) dei-quasiquitter-commands)
(member key dei-quasiquitter-keys)))
`(lambda ()
(interactive)
(call-interactively (key-binding ,(key-parse key)))
;; the root hydra /body
(,(dei--corresponding-hydra (substring key 0 2)))))
;; Regular key
(t
`(call-interactively (key-binding ,(key-parse key)))))))
(defun dei--head-arg-cmd-leads-to-subhydra-p (stem leaf)
(let ((binding (dei--head-arg-cmd stem leaf)))
(when (symbolp binding)
(string-suffix-p "/body" (symbol-name binding)))))
(defun dei--head-arg-hint (stem leaf)
"See `dei--head'."
(let* ((sym (if (member (concat stem leaf)
dei--hydrable-prefixes-with-ancestors)
(dei--corresponding-hydra stem leaf)
(key-binding (key-parse (concat stem leaf)))))
;; REVIEW: when is sym ever not a symbol?
(name (if (symbolp sym)
(symbol-name sym)
(concat stem leaf))))
(if (null sym)
dei--filler
(if (> (length name) dei--colwidth)
(substring name 0 dei--colwidth)
name))))
(defun dei--head-arg-exit (stem leaf)
"See `dei--head'."
(let ((key (concat stem leaf)))
(when (or (member (key-binding (key-parse key)) dei-quasiquitter-commands)
(member (key-binding (key-parse key)) dei-quitter-commands)
(member key dei-quasiquitter-keys)
(member key dei-quitter-keys)
(member key dei--hydrable-prefixes-with-ancestors)
;; Extra safety measure which could be upstreamed to Hydra
(dei--head-arg-cmd-leads-to-subhydra-p stem leaf))
'(:exit t))))
;; Different types of full heads
(defun dei--head (stem leaf)
"Return a hydra head specification (a list), see `defhydra'.
Strings STEM and LEAF concatenate to form a key description
satisfying `key-valid-p' (Emacs 29 function), and string LEAF is
a single unchorded key, typically one character but can also be a
named function key such as <return>."
`( ,leaf
,(dei--head-arg-cmd stem leaf)
,(dei--head-arg-hint stem leaf)
,@(dei--head-arg-exit stem leaf)))
(defun dei--head-invisible (stem leaf)
`( ,leaf
,(dei--head-arg-cmd stem leaf)
,@(dei--head-arg-exit stem leaf)))
(defun dei--head-invisible-self-inserting-stemless (_stem leaf)
`( ,leaf
self-insert-command
:exit t))
(defun dei--head-invisible-exiting-stemless (_stem leaf)
`( ,leaf
,(dei--head-arg-cmd "" leaf)
:exit t))
(defun dei--head-invisible-stemless (_stem leaf)
`( ,leaf
,(dei--head-arg-cmd "" leaf)))
;; Lists of full heads
(defun dei--specify-visible-heads (stem &optional verboten-leafs)
"Return a list of heads that will be shown in the hydra hint.
These are for the hydra imaged by STEM, which is combined with
various leafs, see function body.
Optional argument VERBOTEN-LEAFS, a list of strings such as
'(\"1\" \"z\"), prevents including heads for these leafs."
(let ((leaf-list (-difference dei--hydra-keys-list verboten-leafs)))
(cl-loop for leaf in leaf-list
collect `(,leaf
,(dei--head-arg-cmd stem leaf)
,(dei--head-arg-hint stem leaf)
,@(dei--head-arg-exit stem leaf)))))
(defun dei--specify-invisible-heads (stem &optional verboten-leafs)
"Return a list of heads not to be shown in the hydra hint.
These are for the hydra imaged by STEM, which is combined with
various leafs, see function body.
Optional argument VERBOTEN-LEAFS, a list of strings such as
'(\"1\" \"z\"), prevents including heads for these leafs."
(let ((x (append
(cl-loop for leaf in dei-invisible-leafs
collect (dei--head-invisible stem leaf))
;; For these keys, we want the hydra to exit, so we need to add
;; heads so that we can set :exit t. (We design hydras with default
;; :exit nil for foreign keys, because otherwise we'd need a lot
;; more heads in order to set :exit nil for them.) As for the
;; command within these heads, the naive approach is bind to nil,
;; but we prefer to self-insert at the same time otherwise user has
;; to press twice. So we bind directly to self-insert-command. An
;; alternative, our usual head-arg-cmd, is not necessary if we've
;; anyway decided to self-insert --- although if all shiftsyms were
;; unbound in all keymaps, it'd work the same.
(cl-loop for leaf in (append dei--all-shifted-symbols-list
dei-inserting-quitters)
collect (dei--head-invisible-self-inserting-stemless stem leaf))
;; NOTE: This doesn't overlap with dei-quitter-keys; have to be stemless
(cl-loop for leaf in dei-stemless-quitters
collect (dei--head-invisible-exiting-stemless stem leaf)))))
(-remove (lambda (head)
(member (car head) verboten-leafs))
x)))
(defun dei--convert-head-for-nonum (head)
"Ensure that hydra head HEAD suits a nonum hydra.
Basically, if HEAD binds `dei-universal-argument', return a
different head that instead binds `hydra--universal-argument' and
drops any :exit keyword. Same for `dei-negative-argument'.
This is necessary for the nonum hydras to stay active, as the
wrapper `dei-universal-argument' exists to spawn the nonum hydra to
start with, and should only be called once."
(cond ((eq (cadr head) 'dei-universal-argument)
(list (car head) 'hydra--universal-argument))
((eq (cadr head) 'dei-negative-argument)
(list (car head) 'hydra--negative-argument))
(t
head)))
(defun dei--specify-extra-heads (stem &optional nonum-p)
"For a hydra imaged by STEM, return some bonus heads for it.
These are mostly the kinds of heads shared by all of Deianira's
hydras. With NONUM-P non-nil, return a different set of extra
heads suited for a nonum hydra, see `dei--convert-head-for-nonum'."
(let ((self-poppers
(cond ((equal "C-" stem) (list dei-ersatz-control
(concat "C-" dei-ersatz-control)))
((equal "M-" stem) (list dei-ersatz-meta
(concat "M-" dei-ersatz-meta)))
((equal "s-" stem) (list dei-ersatz-super
(concat "s-" dei-ersatz-super)))
((equal "H-" stem) (list dei-ersatz-hyper
(concat "H-" dei-ersatz-hyper)))
((equal "A-" stem) (list dei-ersatz-alt
(concat "A-" dei-ersatz-alt)))))
(extras (if nonum-p
(mapcar #'dei--convert-head-for-nonum dei-extra-heads)
dei-extra-heads)))
(-non-nil
`(,(if nonum-p
`("<backspace>" ,(dei--corresponding-hydra stem) :exit t)
`("<backspace>" ,(dei--corresponding-hydra
(massmapper--parent-stem stem)) :exit t))
,@(when self-poppers
(cl-loop for key in self-poppers
collect `(,key nil :exit t)))
,@extras))))
;; Grand merged list of heads
(defun dei--specify-hydra (stem name &optional nonum-p)
"Return a list of hydra heads, with NAME as first element.
You can pass the output to `dei--try-birth-hydra'.
String STEM is a stem on which the resulting list of heads will
be based.
Boolean NONUM-P determines if this should be a numberless hydra,
i.e. one where the numeric keys do numeric prefix arguments
instead of anything else they may have been bound to."
(let* ((extra-heads (dei--specify-extra-heads stem nonum-p))
(verboten-leafs (append (mapcar #'car extra-heads)
(when nonum-p
(split-string "1234567890" "" t))))
(heads (append
extra-heads
(dei--specify-visible-heads stem verboten-leafs)
(dei--specify-invisible-heads stem verboten-leafs))))
(cons name heads)))
;; NOTE: Further improving performance is not a priority, but here's where the
;; package spends over 50% of CPU time, sometimes 90%. I guess defhydra was
;; not meant to be used in a performance-intensive way, especially when quoted.
;; Approaches:
;;
;; 1. Dodge the need to `eval' a quoted macro, so the byte-compiler can help.
;; I don't really see a way without rewriting defhydra as a defun that suits
;; our purposes (even if it would be limited for other purposes). I doubt
;; I'm capable of doing so without abo-abo's advice since the perf is not an
;; itch for me anymore.
;;
;; 2. Reduce workload by giving up on the self-inserting quitters (principally
;; capital keys) since there are many of those heads, or giving up on nonum
;; hydras.
;;
;; 3. C-s cream on top RET
;;
;; 4. It seems that every time this function runs, it gets slower, in a way
;; that doesn't have to do with point #3. On emacs start, it takes 0.01s,
;; but after many flocks, it takes 0.30s per invocation! (And because of
;; this, the stopgap measure described in point #2 would compound to a huge
;; difference)
(defun dei--try-birth-hydra (recipe)
"Birth a hydra out of RECIPE formed by `dei--specify-hydra'.
You can view that function as a dry-run and this one as the step
that finally wets it, altering Emacs state in a way the user can
see."
(let ((name (car recipe))
(list-of-heads (cdr recipe)))
(if (eq hydra-curr-body-fn (intern name))
;; REVIEW: An old safety measure, not sure it's needed
(error "This hydra active, skipped redefining: %s" name)
(eval `(defhydra ,(intern name)
(:columns ,dei-columns
:exit nil
:hint nil
:foreign-keys run)
,name
,@list-of-heads)
t))))
;;;; Keymap scanner
;; Since (rx (or ...)) calls the slow `regexp-opt', cache the regexp.
(defconst dei--shift-chord-regexp (rx (or bol "-" " ") "S-")
"Match explicit \"S-\" chords in key descriptions.
Do not match capital letters.")
;; (will probably export to massmapper.el)
(defun dei--key-is-illegal (keydesc)
"Non-nil if KEYDESC would be unbound in a purist scheme.
This means a scheme of homogenizing, no shift, no multi-chords,
and no mixed modifiers."
(let ((case-fold-search nil))
(or
(string-match-p dei--shift-chord-regexp keydesc)
(massmapper--key-contains dei--all-shifted-symbols-list keydesc)
(massmapper--key-contains-multi-chord keydesc)
(massmapper--key-mixes-modifiers keydesc)
;; Drop bastard sequences.
(and (massmapper--key-has-more-than-one-chord keydesc)
(not (massmapper--permachord-p keydesc)))
;; Drop e.g. <f1> C-f.
(and (not (massmapper--key-starts-with-modifier keydesc))
(string-match-p massmapper--modifier-safe-re keydesc)))))
(defconst dei--ignore-regexp-merged
(regexp-opt
(append '("DEL" "backspace")
;; declutter a bit (unlikely someone wants)
'("help" "kp-" "iso-" "wheel" "menu" "redo" "undo" "again" "XF86")
massmapper--ignore-keys-irrelevant
massmapper--ignore-keys-control-chars)))
;; REVIEW: Test <ctl> x 8 with Deianira active.
(defvar dei--avoid-prefixes
(cons "C-x 8"
(mapcar #'key-description
(where-is-internal #'iso-transl-ctl-x-8-map)))
"List of prefixes to avoid looking up.")
(defvar dei--cache (make-hash-table :size 2000 :test #'equal))
(defun dei--seq-to-key-if-legal (seq)
(let ((cached-value (gethash seq dei--cache 'not-found)))
(if (eq 'not-found cached-value)
(puthash seq
(let* ((key (key-description seq))
(normkey (and
;; Ignore menu-bar/tool-bar/tab-bar
(not (string-search "-bar>" key))
;; Sometimes (key-description seq) evalutes
;; to a key called "C-x (..*", a key called
;; "ESC 3..9", etc. Even stranger, `seq' for
;; every one of them is just [switch-frame].
;; And all are bound to self-insert-command.
;; I don't get it. But it's ok to filter out
;; self-insert-command.
(not (string-search ".." key))
;; Finally the input can be assumed valid.
(massmapper--normalize key))))
(and
normkey
;; (not (-any-p #'dei--not-on-keyboard (split-string normkey " ")))
(not (string-match-p dei--ignore-regexp-merged normkey))
(not (massmapper--key-has-more-than-one-chord normkey))
(not (dei--key-is-illegal normkey))
(cl-loop for prefix in dei--avoid-prefixes
never (string-prefix-p prefix normkey))
normkey))
dei--cache)
cached-value)))
;;(dei--relevant-buffer-bindings)
(defun dei--relevant-buffer-bindings ()
"List the current bindings appropriate for hydra-making.
The result is an alist of \(KEYDESC . COMMAND\), where each
KEYDESC is normalized to satisfy `key-valid-p'. COMMAND is
expected to be either a command, a lambda or a closure.
Perhaps obvious but: this is not the bindings from any single
keymap such as `global-map', but from the composite of currently
active keymaps, many of which occlude parts of `global-map'."
;; You know that the same key can be found several times in multiple
;; keymaps. Fortunately we can know which binding is correct for the
;; current buffer, as `current-active-maps' seems to return maps in the
;; order in which Emacs selects them. So what comes earlier in the list
;; is what would in fact be used. The rest is history.
(cl-loop
with case-fold-search = nil
for keymap in (current-active-maps)
append (cl-loop
for seq being the key-seqs of keymap
using (key-bindings cmd)
as key = (dei--seq-to-key-if-legal seq)
when key
when cmd
;; Rule out menu-items and other "weird" bindings
when (if (listp cmd)
(member (car cmd) '(closure lambda))
t)
;; Only consider the first instance of a given key (a keymap can
;; list the same key twice, and it can be in several keymaps)
unless (assoc key bindings)
unless (assoc key merged)
;; Check if we already found an ancestor to or descendant of this
;; key sequence... (the things I put up with...) The reason why is
;; that every key that's already gotten into `merged' at this point
;; has prio over the key now looked at, so if for example there
;; exists a bound key C-x s d, it would be wrong to assume that
;; either C-x s OR C-x s d f are now bound to a command in practice,
;; just because we found it in this late keymap (C-x s would
;; technically still be bound, but to a keymap value, not a command,
;; which still overshadows the C-x s we now find, and the earlier
;; `assoc' won't catch it because `cl-loop' skips keys bound to
;; keymap values).
when (cl-loop for (priokey . _) in merged
never (string-prefix-p key priokey)
never (string-prefix-p priokey key))
;; May look like amateur `cl-loop' code, but necessary
collect (cons key cmd) into bindings
finally return bindings)
;; Separating `bindings' and `merged', instead of collecting each key into
;; `merged' from the start, halves the total execution time
into merged
finally return merged))
(defun dei--connection-exists (parent-stem child-stem)
(when (and parent-stem
child-stem)
(let* ((parent-hydra-name (dei--dub-hydra-from-stem parent-stem))
(child-hydra-name (dei--dub-hydra-from-stem child-stem)))
(and (fboundp (intern (concat parent-hydra-name "/body")))
(cl-find-if
(lambda (head)
(eq (nth 1 head)
(intern (concat child-hydra-name "/body"))))
(symbol-value (intern (concat parent-hydra-name "/heads"))))))))