duat-core 0.10.0

The core of Duat, a highly customizable text editor.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
//! Utilities for hooks in Duat.
//!
//! In Duat, hooks are handled through the [`Hookable`] trait. This
//! trait contains the [`Hookable::Input`] associated type, which is
//! what should be passed to hooks on the specific [`Hookable`]. By
//! implementing this trait, you allow an end user to hook executions
//! whenever said [`Hookable`] is triggered:
//!
//! ```rust
//! # duat_core::doc_duat!(duat);
//! setup_duat!(setup);
//! use duat::prelude::*;
//!
//! fn setup() {
//!     hook::add::<BufferOpened>(|pa: &mut Pass, handle: &Handle| {
//!         let buffer = handle.write(pa);
//!         if let Some("lisp") = buffer.filetype() {
//!             buffer.opts.wrap_lines = true;
//!         }
//!     });
//! }
//! ```
//!
//! The hook above is triggered whenever a [`Buffer`] widget is
//! opened. Like every other hook, it gives you access to the global
//! state via the [`Pass`]. Additionally, like most hooks, it gives
//! you a relevant argument, in this case, a [`Handle<Buffer>`], which
//! you can modify to your liking.
//!
//! This is just one of many built-in [`Hookable`]s. Currently, these
//! are the existing hooks in `duat-core`, but you can also make your
//! own:
//!
//! - [`BufferOpened`] is an alias for [`WidgetOpened<Buffer>`].
//! - [`BufferSaved`] triggers after the [`Buffer`] is written.
//! - [`BufferClosed`] triggers on every buffer upon closing Duat.
//! - [`BufferUnloaded`] triggers on every buffer upon reloading Duat.
//! - [`BufferUpdated`] triggers whenever a buffer changes.
//! - [`BufferPrinted`] triggers after a buffer has been printed.
//! - [`BufferSwitched`] triggers when switching the active buffer.
//! - [`ConfigLoaded`] triggers after loading the config crate.
//! - [`ConfigUnloaded`] triggers after unloading the config crate.
//! - [`FocusedOnDuat`] triggers when Duat gains focus.
//! - [`UnfocusedFromDuat`] triggers when Duat loses focus.
//! - [`WidgetOpened`] triggers when a [`Widget`] is opened.
//! - [`WindowOpened`] triggers when a [`Window`] is created.
//! - [`FocusedOn`] triggers when a [widget] is focused.
//! - [`UnfocusedFrom`] triggers when a [widget] is unfocused.
//! - [`FocusChanged`] is like [`FocusedOn`], but on [dyn `Widget`]s.
//! - [`ModeSwitched`] triggers when you change [`Mode`].
//! - [`KeySent`] triggers when a keys are sent.
//! - [`KeyTyped`] triggers when keys are _typed_, not _sent_.
//! - [`OnMouseEvent`] triggers with mouse events.
//! - [`FormSet`] triggers whenever a [`Form`] is added/altered.
//! - [`ColorschemeSet`] triggers whenever a [colorscheme is set].
//! - [`MsgLogged`] triggers after logginng macros like [`debug!`].
//!
//! # Basic makeout
//!
//! When a hook is added, it can take arguments
//!
//! ```rust
//! # duat_core::doc_duat!(duat);
//! use duat::prelude::*;
//!
//! struct CustomHook(usize);
//! impl Hookable for CustomHook {
//!     type Input<'h> = usize;
//!
//!     fn get_input<'h>(&'h mut self, pa: &mut Pass) -> Self::Input<'h> {
//!         self.0
//!     }
//! }
//!
//! fn runtime_function_that_triggers_hook(pa: &mut Pass) {
//!     let arg = 42;
//!     hook::trigger(pa, CustomHook(arg));
//! }
//! ```
//!
//! The above example ilustrates how hooks are implemented in Duat.
//! You essentially pass a struct wich will hold the arguments that
//! will be passed as input to the hooks. The [`Hookable::Input`]
//! argument makes it so you can have more convenient parameters for
//! hooks, like `(usize, &'h str)`, for example.
//!
//! Sometimes, you may need to trigger hooks "remotely", that is, in a
//! place wher you don't have acces to a [`Pass`] (due to not being on
//! the main thread or for some other reason), you can make use of
//! [`context::queue`] in order to queue the hook to be executed on
//! the main thread:
//!
//! ```rust
//! # duat_core::doc_duat!(duat);
//! # use duat::prelude::*;
//! # struct CustomHook(usize);
//! # impl Hookable for CustomHook {
//! #     type Input<'h> = usize;
//! #     fn get_input<'h>(&'h mut self, pa: &mut Pass) -> Self::Input<'h> { self.0 }
//! # }
//! fn on_a_thread_far_far_away() {
//!     let arg = 42;
//!     context::queue(move |pa| _ = hook::trigger(pa, CustomHook(arg)));
//! }
//! ```
//!
//! The main difference (apart from the asynchronous execution) is
//! that [`hook::trigger`] _returns_ the hook to you, so you can
//! retrieve its internal values. This can be useful if, for example,
//! you wish to create a hook for configuring things:
//!
//! ```rust
//! # duat_core::doc_duat!(duat);
//! use duat::prelude::*;
//!
//! #[derive(Default)]
//! struct MyConfig {
//!     pub value_1: usize,
//!     pub value_2: Option<f32>,
//! }
//!
//! struct MyConfigCreated(MyConfig);
//!
//! impl Hookable for MyConfigCreated {
//!     type Input<'h> = &'h mut MyConfig;
//!
//!     fn get_input<'h>(&'h mut self, pa: &mut Pass) -> Self::Input<'h> {
//!         &mut self.0
//!     }
//! }
//!
//! fn create_my_config(pa: &mut Pass) -> MyConfig {
//!     let my_config = MyConfig::default();
//!     let MyConfigCreated(my_config) = hook::trigger(pa, MyConfigCreated(my_config));
//!     my_config
//! }
//! ```
//!
//! This way, the user can configure `MyConfig` by calling
//! [`hook::add`]:
//!
//! ```rust
//! # duat_core::doc_duat!(duat);
//! # #[derive(Default)]
//! # struct MyConfig {
//! #     pub value_1: usize,
//! #     pub value_2: Option<f32>,
//! # }
//! # struct MyConfigCreated(MyConfig);
//! # impl Hookable for MyConfigCreated {
//! #     type Input<'h> = &'h mut MyConfig;
//! #     fn get_input<'h>(&'h mut self, pa: &mut Pass) -> Self::Input<'h> { &mut self.0 }
//! # }
//! use duat::prelude::*;
//! setup_duat!(setup);
//!
//! fn setup() {
//!     hook::add::<MyConfigCreated>(|pa, my_config| my_config.value_1 = 3);
//! }
//! ```
//!
//! [`Buffer`]: crate::buffer::Buffer
//! [`LineNumbers`]: https://docs.rs/duat/latest/duat/widgets/struct.LineNumbers.html
//! [widget]: Widget
//! [dyn `Widget`]: Widget
//! [key]: KeyEvent
//! [deadlocks]: https://en.wikipedia.org/wiki/Deadlock_(computer_science)
//! [commands]: crate::cmd
//! [`Mode`]: crate::mode::Mode
//! [`&mut Widget`]: Widget
//! [`context::queue`]: crate::context::queue
//! [`hook::trigger`]: trigger
//! [`hook::add`]: add
//! [`SearchPerformed`]: https://docs.rs/duat/latest/duat/hooks/struct.SearchPerformed.html
//! [`SearchUpdated`]: https://docs.rs/duat/latest/duat/hooks/struct.SearchUpdated.html
//! [`debug!`]: crate::context::debug
//! [colorscheme is set]: crate::form::set_colorscheme
use std::{
    any::{Any, TypeId},
    cell::RefCell,
    collections::HashMap,
    sync::Mutex,
};

use crossterm::event::MouseEventKind;

pub use self::global::*;
use crate::{
    Ns,
    buffer::Buffer,
    context::Handle,
    data::Pass,
    form::{Form, FormId},
    mode::{KeyEvent, KeyMod, MouseEvent, TwoPointsPlace},
    ui::{Coord, Widget, Window},
    utils::catch_panic,
};

/// Hook functions.
mod global {
    use std::sync::LazyLock;

    use super::{Hookable, InnerHooks};
    use crate::{Ns, data::Pass, hook::Callback};

    static HOOKS: LazyLock<InnerHooks> = LazyLock::new(InnerHooks::default);

    /// A struct used in order to specify more options for [hook]s.
    ///
    /// You can set three options currently:
    ///
    /// - [`HookBuilder::grouped`]: Groups this hook with others,
    ///   allowing them to all be [removed] at once.
    /// - [`HookBuilder::filter`]: Filters when this hook should be
    ///   called, by giving a struct for which  `H` implements
    ///   [`PartialEq`]. An example is the [`FocusedOn`] hook, which
    ///   accepts [`Handle`]s and [`Handle`] pairs.
    ///
    /// [hook]: crate::hook
    /// [`FocusedOn`]: super::FocusedOn
    /// [`Handle`]: crate::context::Handle
    /// [removed]: remove
    pub struct HookBuilder<H: Hookable> {
        callback: Option<Callback<H>>,
        ns: Option<Ns>,
        filter: Option<Box<dyn Fn(&H) -> bool + Send>>,
        lateness: usize,
    }

    impl<H: Hookable> HookBuilder<H> {
        /// Groups this hook with a [namespace].
        ///
        /// By adding a namespace to this group, you are then able to
        /// remove a group of hooks by calling [`hook::remove`].
        ///
        /// [namespace]: Ns
        /// [`hook::remove`]: remove
        pub fn grouped(mut self, ns: Ns) -> Self {
            self.ns = Some(ns);
            self
        }

        /// Filter when this hook will be called.
        ///
        /// This is mostly for convenience's sake, since you _could_
        /// just add a check inside of the callback itself.
        ///
        /// This is useful if for example, you want to trigger a hook
        /// on only some specific [`Handle`], or some [`Buffer`],
        /// things of the sort.
        ///
        /// [`Handle`]: crate::context::Handle
        /// [`Buffer`]: crate::buffer::Buffer
        pub fn filter<T: Send + 'static>(mut self, filter: T) -> Self
        where
            H: PartialEq<T>,
        {
            self.filter = Some(Box::new(move |hookable| *hookable == filter));
            self
        }

        /// Set the "lateness" of this [`hook`].
        ///
        /// The lateness determines how "late" a `hook` should be
        /// applied. For example, if a hook has a lateness of `0` and
        /// another has a lateness of [`usize::MAX`], the latter one
        /// will be triggered after the first one.
        ///
        /// An example of where this is useful is with hooks that need
        /// to know which lines were printed. For example, if I print
        /// the line numbers, and then in a later hook in the same
        /// [`BufferUpdated`] trigger, an edit is made, the printed
        /// line numbers may now be wrong.
        ///
        /// The general wisdom is that, in order to not break things,
        /// if your hook relies on meta `Tag`s ([`Inlay`], [`Conceal`]
        /// or [`Spacer`]) or [edits the `Text`] of the [`Buffer`],
        /// you should make use of a lower lateness.
        ///
        /// If it only makes use of "light" `Tag`s (like [`FormTag`])
        /// or relies on no future changes on the same `BufferUpdated`
        /// trigger (by e.g. getting the [printed lines]), then it
        /// should have a higher lateness.
        ///
        /// By default, every hook has a lateness of 100.
        ///
        /// [`hook`]: super
        /// [`Tag`]: crate::text::Tag
        /// [`BufferUpdated`]: super::BufferUpdated
        /// [`Inlay`]: crate::text::Inlay
        /// [`Conceal`]: crate::text::Conceal
        /// [`Spacer`]: crate::text::Spacer
        /// [`FormTag`]: crate::text::FormTag
        /// [edits the `Text`]: crate::text::Text::replace_range
        /// [printed lines]: crate::context::Handle::printed_lines
        /// [`Buffer`]: crate::buffer::Buffer
        pub fn lateness(mut self, lateness: usize) -> Self {
            self.lateness = lateness;
            self
        }
    }

    impl<H: Hookable> Drop for HookBuilder<H> {
        fn drop(&mut self) {
            HOOKS.add(
                self.callback.take().unwrap(),
                self.ns,
                self.filter.take(),
                self.lateness,
            )
        }
    }

    /// Adds a hook, which will be called whenever the [`Hookable`] is
    /// triggered.
    ///
    /// [`hook::add`] will return a [`HookBuilder`], which is a struct
    /// that can be used to further modify the behaviour of the hook,
    /// and will add said hook when [`Drop`]ped.
    ///
    /// You can call [`HookBuilder::grouped`], which will group this
    /// hook with others of the same group, allowing for
    /// [`hook::remove`] to remove many hooks a once.
    ///
    /// You can also call [`HookBuilder::filter`], which lets you
    /// filter when your function is actually called, based on the
    /// input arguments of `H`.
    ///
    /// If you want to call a function only once, check out
    /// [`hook::add_once`], which takes an [`FnOnce`] as input, rather
    /// than an [`FnMut`].
    ///
    /// [`hook::add`]: add
    /// [`hook::add_once`]: add_once
    /// [`hook::remove`]: remove
    #[inline(never)]
    pub fn add<H: Hookable>(
        f: impl FnMut(&mut Pass, H::Input<'_>) + Send + 'static,
    ) -> HookBuilder<H> {
        HookBuilder {
            callback: Some(Callback::FnMut(Box::new(f))),
            ns: None,
            filter: None,
            lateness: 100,
        }
    }

    /// Adds a hook, which will be called once when the [`Hookable`]
    /// is triggered.
    ///
    /// This is in contrast to [`hook::add`], whose function is called
    /// every time the `Hookable` is triggered, the function passed to
    /// `add_once` will only be triggered one time.
    ///
    /// [`hook::add`] will return a [`HookBuilder`], which is a struct
    /// that can be used to further modify the behaviour of the hook,
    /// and will add said hook when [`Drop`]ped.
    ///
    /// You can call [`HookBuilder::grouped`], which will group this
    /// hook with others of the same group, allowing for
    /// [`hook::remove`] to remove many hooks a once.
    ///
    /// You can also call [`HookBuilder::filter`], which lets you
    /// filter when your function is actually called, based on the
    /// input arguments of `H`. This is especially useful with
    /// `add_once`, since it prevents the function from being called
    /// once with the wrong arguments (e.g., it was meant for a
    /// specific [`Buffer`], but the trigger happened first on
    /// another).
    ///
    /// [`hook::add`]: add
    /// [`hook::remove`]: remove
    /// [`Buffer`]: crate::buffer::Buffer
    #[inline(never)]
    pub fn add_once<H: Hookable>(
        f: impl FnOnce(&mut Pass, H::Input<'_>) + Send + 'static,
    ) -> HookBuilder<H> {
        HookBuilder {
            callback: Some(Callback::FnOnce(Some(Box::new(f)))),
            ns: None,
            filter: None,
            lateness: 100,
        }
    }

    /// Removes all [hooks] grouped with a [namespace]
    ///
    /// Any hook that was previously added with
    /// [`HookBuilder::grouped`] with the same `Ns` will be removed.
    /// This also includes hooks added via [`hook::add_once`]
    ///
    /// [hooks]: super
    /// [`Ns`]: crate::Ns
    /// [namespace]: Ns
    /// [`hook::add_once`]: add_once
    pub fn remove(ns: Ns) {
        HOOKS.remove(ns);
    }

    /// Triggers a hooks for a [`Hookable`] struct.
    pub fn trigger<H: Hookable>(pa: &mut Pass, hookable: H) -> H {
        HOOKS.trigger(pa, hookable)
    }

    /// Checks if a give group exists.
    ///
    /// The hook can either be a string type, or a [`GroupId`].
    ///
    /// Returns `true` if said group was added via
    /// [`HookBuilder::grouped`], and no [`hook::remove`]
    /// followed these additions
    ///
    /// [`hook::remove`]: remove
    pub fn group_exists(ns: Ns) -> bool {
        HOOKS.group_exists(ns)
    }
}

/// [`Hookable`]: Triggers when a [`Widget`] is created.
///
/// # Arguments
///
/// - The [`Handle<W>`] of said `Widget`.
///
/// # Aliases
///
/// Since every `Widget` implements the `HookAlias` trait, instead
/// of writing this in the config crate:
///
/// ```rust
/// # duat_core::doc_duat!(duat);
/// setup_duat!(setup);
/// use duat::prelude::*;
///
/// fn setup() {
///     hook::add::<WidgetOpened<LineNumbers>>(|pa, ln| ln.write(pa).relative = true);
/// }
/// ```
///
/// You can just write this:
///
/// ```rust
/// # duat_core::doc_duat!(duat);
/// setup_duat!(setup);
/// use duat::prelude::*;
///
/// fn setup() {
///     hook::add::<WidgetOpened<LineNumbers>>(|pa, ln| ln.write(pa).relative = true);
/// }
/// ```
///
/// # Changing the layout
///
/// Assuming you are using `duat-term`, you could make it so every
/// [`LineNumbers`] comes with a [`VertRule`] on the right, like this:
///
/// ```rust
/// # duat_core::doc_duat!(duat);
/// setup_duat!(setup);
/// use duat::prelude::*;
///
/// fn setup() {
///     hook::add::<WidgetOpened<LineNumbers>>(|pa, handle| {
///         VertRule::builder().on_the_right().push_on(pa, handle);
///     });
/// }
/// ```
///
/// Now, every time a [`LineNumbers`]s `Widget` is inserted in Duat,
/// a [`VertRule`] will be pushed on the right of it. You could even
/// further add a [hook] on `VertRule`, that would push further
/// `Widget`s if you wanted to.
///
/// [hook]: self
/// [direction]: crate::ui::PushSpecs
/// [`LineNumbers`]: https://docs.rs/duat/latest/duat/widgets/struct.LineNumbers.html
/// [`VertRule`]: https://docs.rs/duat_term/latest/duat-term/struct.VertRule.html
pub struct WidgetOpened<W>(pub(crate) Handle<W>);

impl<W: 'static> Hookable for WidgetOpened<W> {
    type Input<'h> = &'h Handle<W>;

    fn get_input<'h>(&'h mut self, _: &mut Pass) -> Self::Input<'h> {
        &self.0
    }
}

/// An alias for [`WidgetOpened<Buffer>`].
pub type BufferOpened = WidgetOpened<Buffer>;

/// [`Hookable`]: Triggers after [`Handle::save`] or [`Handle::save_to`].
///
/// Only triggers if the buffer was actually updated.
///
/// # Arguments
///
/// - The [`Handle`] of said [`Buffer`]
/// - Wether the `Buffer` will be closed (happens when calling the
///   `wq` or `waq` commands)
pub struct BufferSaved(pub(crate) (Handle, bool));

impl Hookable for BufferSaved {
    type Input<'h> = (&'h Handle, bool);

    fn get_input<'h>(&'h mut self, _: &mut Pass) -> Self::Input<'h> {
        (&self.0.0, self.0.1)
    }
}

/// [`Hookable`]: Triggers when a new window is opened.
///
/// # Arguments
///
/// - The [`Window`] that was created
///
/// One of the main reasons to use this [hook] is to push new
/// [`Widget`]s to a `Window`. That is, you can push [outer
/// `Widget`s] or [inner `Widget`s], just like with
/// [`Handle`]s.
///
/// Here's how that works: `Window`s are divided into two main
/// regions, the inner "[`Buffer`] region", and the outer "master
/// region". This means that, on every `Window`, you'll have a
/// collection of `Buffer`s in the middle, with their satellite
/// `Widget`s, and various `Widget`s on the outer rims of the
/// `Window`, not necessarily associated with any single `Buffer`.
///
/// As an example, this is how the default layout of Duat is layed
/// out:
///
/// ```text
/// ╭┄┄┬┄┄┄┄┄┄┄┄┬┄┄┬┄┄┄┄┄┄┄┄┬───────╮
/// ┊  │        │  │        ┊       │
/// ┊LN│        │LN│        ┊       │
/// ┊  │ Buffer │  │ Buffer ┊       │
/// ┊VR│        │VR│        ┊LogBook│
/// ┊  │        │  │        ┊       │
/// ├┄┄┴┄┄┄┄┄┄┄┄┴┄┄┴┄┄┄┄┄┄┄┄┤       │
/// │     FooterWidgets     │       │
/// ╰───────────────────────┴───────╯
/// ```
///
/// In this configuration, you can see the delineation between the
/// "`Buffer` region" (surrounded by dotted lines) and the "master
/// region", where:
///
/// - For each [`Buffer`], we are adding a [`LineNumbers`] (LN) and a
///   [`VertRule`] (VR) `Widget`s. Each of these is related to a
///   specific `Buffer`, and if that `Buffer` moves around, they will
///   follow.
///
/// - On the outer edges, we have a [`FooterWidgets`], which includes
///   a [`StatusLine`], [`PromptLine`] and [`Notifications`], as well
///   as a [`LogBook`] on the side, which is hidden by default. These
///   [`Widget`]s are not related to any `Buffer`, and will not move
///   around or be removed, unless directly.
///
/// So the distinction here is that, if you call
/// [`Window::push_inner`], you will be pushing [`Widget`]s _around_
/// the "`Buffer` region", but _not_ within it. If you want to push to
/// specific [`Buffer`]s, you should look at
/// [`Handle::push_inner_widget`] and [`Handle::push_outer_widget`].
///
/// On the other hand, by calling [`Window::push_outer`], you will be
/// pushing [`Widget`]s around the "master region", so they will go on
/// the edges of the screen.
///
/// [hook]: self
/// [outer `Widget`s]: Window::push_outer
/// [inner `Widget`s]: Window::push_inner
/// [`LineNumbers`]: https://docs.rs/duat/duat/latest/widgets/struct.LineNumbers.html
/// [`VertRule`]: https://docs.rs/duat/duat/latest/widgets/struct.VertRule.html
/// [`FooterWidgets`]: https://docs.rs/duat/duat/latest/widgets/struct.FooterWidgets.html
/// [`StatusLine`]: https://docs.rs/duat/duat/latest/widgets/struct.StatusLine.html
/// [`PromptLine`]: https://docs.rs/duat/duat/latest/widgets/struct.PromptLine.html
/// [`Notifications`]: https://docs.rs/duat/duat/latest/widgets/struct.Notifications.html
/// [`LogBook`]: https://docs.rs/duat/duat/latest/widgets/struct.LogBook.html
pub struct WindowOpened(pub(crate) Window);

impl Hookable for WindowOpened {
    type Input<'h> = &'h mut Window;

    fn get_input<'h>(&'h mut self, _: &mut Pass) -> Self::Input<'h> {
        &mut self.0
    }
}

/// [`Hookable`]: Triggers before closing a [`Buffer`].
///
/// # Arguments
///
/// - The [`Buffer`]'s [`Handle`].
///
/// This will be triggered whenever a `Buffer` is closed. Note that
/// this does not count when a `Buffer` is closed in order to be
/// reopened in a reloaded config.
///
/// If you want to handle that scenario, check out [`BufferUnloaded`].
pub struct BufferClosed(pub(crate) Handle);

impl Hookable for BufferClosed {
    type Input<'h> = &'h Handle;

    fn get_input<'h>(&'h mut self, _: &mut Pass) -> Self::Input<'h> {
        &self.0
    }
}

impl PartialEq<Handle> for BufferClosed {
    fn eq(&self, other: &Handle) -> bool {
        self.0 == *other
    }
}

/// [`Hookable`]: Triggers before unloading a [`Buffer`].
///
/// # Arguments
///
/// - The `Buffer`'s [`Handle`].
///
/// This will happen before reloading Duat, on every `Buffer` that is
/// open at that point.
///
/// If you want to handle the closure of buffers, see the hook for
/// [`BufferClosed`].
pub struct BufferUnloaded(pub(crate) Handle);

impl Hookable for BufferUnloaded {
    type Input<'h> = &'h Handle;

    fn get_input<'h>(&'h mut self, _: &mut Pass) -> Self::Input<'h> {
        &self.0
    }
}

impl PartialEq<Handle> for BufferUnloaded {
    fn eq(&self, other: &Handle) -> bool {
        self.0 == *other
    }
}

/// [`Hookable`]: Triggers when a [`Buffer`] updates.
///
/// This is triggered after a batch of writing calls to the `Buffer`,
/// once per frame. This can happen after typing a key, calling a
/// command, triggering hooks, or any other action with access to a
/// [`Pass`], which could be used to write to the `Buffer`.
///
/// Think of this is as a "last pass" on the `Buffer`, right before
/// printing, where it can be adjusted given the modifications to it,
/// like [`Change`]s and such.
///
/// As an example, here's a hook that will highlight every non ascii
/// character:
///
/// ```rust
/// # duat_core::doc_duat!(duat);
/// use duat::{
///     prelude::*,
///     text::{Strs, Tags},
/// };
///
/// fn setup() {
///     let ns = Ns::new();
///     let tag = form::id_of!("non_ascii_char").to_tag(50);
///
///     let hl_non_ascii = move |tags: &mut Tags, strs: &Strs, range: Range<Point>| {
///         for (b, char) in strs[range.clone()].char_indices() {
///             let b = b + range.start.byte();
///             if !char.is_ascii() {
///                 tags.insert(ns, b..b + char.len_utf8(), tag);
///             }
///         }
///     };
///
///     hook::add::<BufferOpened>(move |pa, buffer| {
///         let _ = buffer.read(pa).moment_for(ns);
///
///         let mut parts = buffer.text_parts(pa);
///         let range = Point::default()..parts.strs.end_point();
///         hl_non_ascii(&mut parts.tags, parts.strs, range);
///     });
///
///     hook::add::<BufferUpdated>(move |pa, buffer| {
///         let moment = buffer.read(pa).moment_for(ns);
///
///         let mut parts = buffer.text_parts(pa);
///         for change in moment.iter() {
///             parts.tags.remove(ns, change.added_range());
///             hl_non_ascii(&mut parts.tags, parts.strs, change.added_range())
///         }
///     });
/// }
/// ```
///
/// You can see here that I called [`Buffer::moment_for`]. This
/// function will give, for a given [namespace], a list of all
/// [`Change`]s that have taken place since the last call of that
/// function with the same namespace. This is very useful for tracking
/// alterations to the `Buffer` and acting on them accordingly.
///
/// In this case, I'm just taking the added range of changes and
/// adding tags to every non ascii character in them.
///
/// Note that the `moment_for` function will work anywhere (that you
/// have a [`Pass`], this is just a common situation where you'd use
/// it.
///
/// # Arguments
///
/// - The [`Buffer`]'s [`Handle`]
///
/// [`Area`]: crate::ui::Area
/// [`Buffer`]: crate::buffer::Buffer
/// [`PrintOpts`]: crate::opts::PrintOpts
/// [`Change`]: crate::buffer::Change
/// [`Cursor`]: crate::mode::Cursor
/// [`Tag`]: crate::text::Tag
/// [`Strs`]: crate::text::Strs
/// [`Tags`]: crate::text::Tags
/// [`Selections`]: crate::mode::Selections
/// [`Text`]: crate::text::Text
/// [`Text::parts`]: crate::text::Text::parts
/// [`Text::replace_range`]: crate::text::Text::replace_range
/// [namespace]: crate::Ns
pub struct BufferUpdated(pub(crate) Handle);

impl Hookable for BufferUpdated {
    type Input<'h> = &'h Handle;

    fn get_input<'h>(&'h mut self, _: &mut Pass) -> Self::Input<'h> {
        &self.0
    }
}

impl PartialEq<Handle> for BufferUpdated {
    fn eq(&self, other: &Handle) -> bool {
        self.0 == *other
    }
}

/// [`Hookable`]: Triggers after a [`Buffer`] is printed.
///
/// The primary purpose of this `Widget` is to do cleanup on temporary
/// changes made during a `BufferUpdated` triggering.
///
/// One example of this is with the default `BufferOpts`, which allow
/// you to hightlight the current cursor line. Since this makes use of
/// disruptive `Tag`s, it is best to do this only during the printing
/// process, then get rid of said tags.
///
/// # Warning
///
/// Any changes done to the [`Buffer`] or [`Area`] from this hook will
/// _not_ be checked in order for a reprint. This is to avoid
/// repeatedly printing over and over again.
///
/// [`Area`]: crate::ui::Area
pub struct BufferPrinted(pub(crate) Handle);

impl Hookable for BufferPrinted {
    type Input<'h> = &'h Handle;

    fn get_input<'h>(&'h mut self, _: &mut Pass) -> Self::Input<'h> {
        &self.0
    }
}

/// [`Hookable`]: Triggers whenever the active [`Buffer`] changes.
///
/// # Arguments
///
/// - The former `Buffer`'s [`Handle`]
/// - The current `Buffer`'s [`Handle`]
///
/// [`Buffer`]: crate::buffer::Buffer
pub struct BufferSwitched(pub(crate) (Handle, Handle));

impl Hookable for BufferSwitched {
    type Input<'h> = (&'h Handle, &'h Handle);

    fn get_input<'h>(&'h mut self, _: &mut Pass) -> Self::Input<'h> {
        (&self.0.0, &self.0.1)
    }
}

/// [`Hookable`]: Triggers when Duat opens or reloads.
///
/// This trigger will also happen after a few other initial setups of
/// Duat. Notably, it takes place after all [`Buffer`]s are
/// registered, and their [`BufferOpened`] hooks are triggered.
///
/// # Arguments
///
/// - Wether duat has just opened.
pub struct ConfigLoaded(pub(crate) bool);

impl Hookable for ConfigLoaded {
    type Input<'h> = bool;

    fn get_input<'h>(&'h mut self, _: &mut Pass) -> Self::Input<'h> {
        self.0
    }
}

/// [`Hookable`]: Triggers when Duat closes or has to reload.
///
/// # Arguments
///
/// - Wether duat is in the process of quitting.
pub struct ConfigUnloaded(pub(crate) bool);

impl Hookable for ConfigUnloaded {
    type Input<'h> = bool;

    fn get_input<'h>(&'h mut self, _: &mut Pass) -> Self::Input<'h> {
        self.0
    }
}

/// [`Hookable`]: Triggers when Duat is refocused.
///
/// # Arguments
///
/// There are no arguments
pub struct FocusedOnDuat(pub(crate) ());

impl Hookable for FocusedOnDuat {
    type Input<'h> = ();

    fn get_input<'h>(&'h mut self, _: &mut Pass) -> Self::Input<'h> {}
}

/// [`Hookable`]: Triggers when Duat is unfocused.
///
/// # Arguments
///
/// There are no arguments
pub struct UnfocusedFromDuat(pub(crate) ());

impl Hookable for UnfocusedFromDuat {
    type Input<'h> = ();

    fn get_input<'h>(&'h mut self, _: &mut Pass) -> Self::Input<'h> {}
}

/// [`Hookable`]: Triggers when the [`Widget`] is focused.
///
/// # Arguments
///
/// - The [`Handle<dyn Widget>`] for the unfocused `Widget`.
/// - The [`Handle<W>`] for the newly focused `Widget`.
///
/// # Filters
///
/// This `Hookable` can be filtered in two ways
///
/// - By a focused [`Handle<_>`].
/// - By a `(Handle<_>, Handle<_>)` pair.
pub struct FocusedOn<W>(pub(crate) (Handle<dyn Widget>, Handle<W>));

impl<W: 'static> Hookable for FocusedOn<W> {
    type Input<'h> = &'h (Handle<dyn Widget>, Handle<W>);

    fn get_input<'h>(&'h mut self, _: &mut Pass) -> Self::Input<'h> {
        &self.0
    }
}

impl<W1, W2: ?Sized> PartialEq<Handle<W2>> for FocusedOn<W1> {
    fn eq(&self, other: &Handle<W2>) -> bool {
        self.0.1 == *other
    }
}

impl<W1: Widget, W2: Widget + ?Sized, W3: Widget + ?Sized> PartialEq<(Handle<W2>, Handle<W3>)>
    for FocusedOn<W1>
{
    fn eq(&self, other: &(Handle<W2>, Handle<W3>)) -> bool {
        self.0.0 == other.0 && self.0.1 == other.1
    }
}

/// [`Hookable`]: Triggers when the [`Widget`] is unfocused.
///
/// # Arguments
///
/// - The [`Handle<W>`] for the unfocused `Widget`
/// - The [`Handle<dyn Widget>`] for the newly focused `Widget`
pub struct UnfocusedFrom<W: Widget>(pub(crate) (Handle<W>, Handle<dyn Widget>));

impl<W: Widget> Hookable for UnfocusedFrom<W> {
    type Input<'h> = &'h (Handle<W>, Handle<dyn Widget>);

    fn get_input<'h>(&'h mut self, _: &mut Pass) -> Self::Input<'h> {
        &self.0
    }
}

impl<W1: Widget, W2: Widget + ?Sized> PartialEq<Handle<W2>> for UnfocusedFrom<W1> {
    fn eq(&self, other: &Handle<W2>) -> bool {
        self.0.0 == *other
    }
}

impl<W1: Widget, W2: Widget + ?Sized, W3: Widget + ?Sized> PartialEq<(Handle<W2>, Handle<W3>)>
    for UnfocusedFrom<W1>
{
    fn eq(&self, other: &(Handle<W2>, Handle<W3>)) -> bool {
        self.0.0 == other.0 && self.0.1 == other.1
    }
}

/// [`Hookable`]: Triggers when focus changes between two [`Widget`]s.
///
/// # Arguments
///
/// - The [`Handle<dyn Widget>`] for the unfocused `Widget`
/// - The [`Handle<dyn Widget>`] for the newly focused `Widget`
///
/// This `Hookable` is triggered _before_ [`FocusedOn`] and
/// [`UnfocusedFrom`] are triggered.
pub struct FocusChanged(pub(crate) (Handle<dyn Widget>, Handle<dyn Widget>));

impl Hookable for FocusChanged {
    type Input<'h> = &'h (Handle<dyn Widget>, Handle<dyn Widget>);

    fn get_input<'h>(&'h mut self, _: &mut Pass) -> Self::Input<'h> {
        &self.0
    }
}

/// [`Hookable`]: Triggers when the [`Mode`] is changed.
///
/// # Arguments
///
/// - The previous mode.
/// - The current mode.
///
/// [`Mode`]: crate::mode::Mode
pub struct ModeSwitched {
    pub(crate) old: (&'static str, Box<dyn Any + Send>),
    pub(crate) new: (&'static str, Box<dyn Any + Send>),
}

impl Hookable for ModeSwitched {
    type Input<'h> = ModeSwitch<'h>;

    fn get_input<'h>(&'h mut self, _: &mut Pass) -> Self::Input<'h> {
        ModeSwitch {
            old: ModeParts {
                name: self.old.0,
                mode: self.old.1.as_mut(),
            },
            new: ModeParts {
                name: self.new.0,
                mode: self.new.1.as_mut(),
            },
        }
    }
}

/// An event representing a [`Mode`] switch, is the argument for the
/// [`ModeSwitched`] [`hook`].
///
/// [`hook`]: self
/// [`Mode`]: crate::mode::Mode
pub struct ModeSwitch<'h> {
    /// The name of the previous [`Mode`].
    ///
    /// [`Mode`]: crate::mode::Mode
    pub old: ModeParts<'h>,
    /// The name of the current [`Mode`].
    ///
    /// [`Mode`]: crate::mode::Mode
    pub new: ModeParts<'h>,
}

/// Parts of a [`Mode`], used on the [`ModeSwitched`] [`hook`].
///
/// [`hook`]: self
/// [`Mode`]: crate::mode::Mode
pub struct ModeParts<'h> {
    /// The name of this [`Mode`].
    ///
    /// [`Mode`]: crate::mode::Mode
    pub name: &'static str,
    pub(crate) mode: &'h mut dyn Any,
}

impl ModeParts<'_> {
    /// Try to downcast the [`Mode`].
    ///
    /// Returns [`Some`] if the mode is of the correct type.
    ///
    /// [`Mode`]: crate::mode::Mode
    pub fn get_as<M: 'static>(&mut self) -> Option<&mut M> {
        self.mode.downcast_mut()
    }

    /// Check if the [`Mode`] is of a given type.
    pub fn is<M: 'static>(&self) -> bool {
        self.mode.is::<M>()
    }
}

/// [`Hookable`]: Triggers whenever a [key] is sent.
///
/// [`KeyEvent`]s are "sent" when you type [unmapped] keys _or_ with
/// the keys that were mapped, this is in contrast with [`KeyTyped`],
/// which triggers when you type or when calling [`mode::type_keys`].
/// For example, if `jk` is mapped to `<Esc>`, [`KeyTyped`] will
/// trigger once for `j` and once for `k`, while [`KeySent`] will
/// trigger once for `<Esc>`.
///
/// # Arguments
///
/// - The sent [key].
///
/// [key]: KeyEvent
/// [unmapped]: crate::mode::map
/// [`mode::type_keys`]: crate::mode::type_keys
pub struct KeySent(pub(crate) KeyEvent);

impl Hookable for KeySent {
    type Input<'h> = KeyEvent;

    fn get_input<'h>(&'h mut self, _: &mut Pass) -> Self::Input<'h> {
        self.0
    }
}

/// [`Hookable`]: Triggers whenever a [key] is typed.
///
/// [`KeyEvent`]s are "typed" when typing keys _or_ when calling the
/// [`mode::type_keys`] function, this is in contrast with
/// [`KeySent`], which triggers when you type [unmapped] keys or with
/// the remapped keys. For example, if `jk` is mapped to `<Esc>`,
/// [`KeyTyped`] will trigger once for `j` and once for `k`, while
/// [`KeySent`] will trigger once for `<Esc>`.
///
/// # Arguments
///
/// - The typed [key].
///
/// [key]: KeyEvent
/// [unmapped]: crate::mode::map
/// [`mode::type_keys`]: crate::mode::type_keys
pub struct KeyTyped(pub(crate) KeyEvent);

impl Hookable for KeyTyped {
    type Input<'h> = KeyEvent;

    fn get_input<'h>(&'h mut self, _: &mut Pass) -> Self::Input<'h> {
        self.0
    }
}

impl PartialEq<KeyEvent> for KeyTyped {
    fn eq(&self, other: &KeyEvent) -> bool {
        self.0 == *other
    }
}

/// [`Hookable`]: Triggers on every [`MouseEvent`].
///
/// # Arguments
///
/// - The [`Handle<W>`] under the mouse.
/// - The [`MouseEvent`] itself.
pub struct OnMouseEvent<W: ?Sized = dyn Widget> {
    pub(crate) handle: Handle<W>,
    pub(crate) points: Option<TwoPointsPlace>,
    pub(crate) coord: Coord,
    pub(crate) kind: MouseEventKind,
    pub(crate) modifiers: KeyMod,
}

impl<W: 'static + ?Sized> Hookable for OnMouseEvent<W> {
    type Input<'h> = MouseEvent<'h, W>;

    fn get_input<'h>(&'h mut self, _: &mut Pass) -> Self::Input<'h> {
        MouseEvent {
            handle: &self.handle,
            points: self.points,
            coord: self.coord,
            kind: self.kind,
            modifiers: self.modifiers,
        }
    }
}

impl<W: 'static + ?Sized> PartialEq<MouseEvent<'_, W>> for OnMouseEvent<W> {
    fn eq(&self, other: &MouseEvent<W>) -> bool {
        self.points == other.points
            && self.coord == other.coord
            && self.kind == other.kind
            && self.modifiers == other.modifiers
    }
}

impl<W: 'static + ?Sized> PartialEq<MouseEventKind> for OnMouseEvent<W> {
    fn eq(&self, other: &MouseEventKind) -> bool {
        self.kind == *other
    }
}

impl<W: 'static + ?Sized> PartialEq<Handle<W>> for OnMouseEvent<W> {
    fn eq(&self, other: &Handle<W>) -> bool {
        self.handle.ptr_eq(other.widget())
    }
}

/// [`Hookable`]: Triggers whenever a [`Form`] is set.
///
/// This can be a creation or alteration of a `Form`.
/// If the `Form` is a reference to another, the reference's
/// `Form` will be returned instead.
///
/// # Arguments
///
/// - The `Form`'s name.
/// - Its [`FormId`].
/// - Its new value.
pub struct FormSet(pub(crate) (&'static str, FormId, Form));

impl Hookable for FormSet {
    type Input<'h> = (&'static str, FormId, Form);

    fn get_input<'h>(&'h mut self, _: &mut Pass) -> Self::Input<'h> {
        (self.0.0, self.0.1, self.0.2)
    }
}

/// [`Hookable`]: Triggers when a colorscheme is set.
///
/// # Arguments
///
/// - The name of the `ColorScheme`.
/// - The list of form name/form value pairs.
pub struct ColorschemeSet(pub(crate) (String, Vec<(String, Form)>));

impl Hookable for ColorschemeSet {
    type Input<'h> = (&'h str, &'h [(String, Form)]);

    fn get_input<'h>(&'h mut self, _: &mut Pass) -> Self::Input<'h> {
        (&self.0.0, &self.0.1)
    }
}

/// [`Hookable`]: Triggers when messages are logged (e.g. via [`warn!`].
///
/// # Arguments
///
/// - The [`Record`] that was logged.
///
/// [`warn!`]: crate::context::warn
/// [`Record`]: crate::context::Record
pub struct MsgLogged(pub(crate) crate::context::Record);

impl Hookable for MsgLogged {
    type Input<'h> = crate::context::Record;

    fn get_input<'h>(&'h mut self, _: &mut Pass) -> Self::Input<'h> {
        self.0.clone()
    }
}

/// A hookable struct, for hooks taking [`Hookable::Input`].
///
/// Through this trait, Duat allows for custom hookable structs. With
/// these structs, plugin creators can create their own custom hooks,
/// and trigger them via [`hook::trigger`].
///
/// This further empowers an end user to customize the behaviour of
/// Duat in the configuration crate.
///
/// [`hook::trigger`]: trigger
pub trait Hookable: Sized + 'static {
    /// The arguments that are passed to each hook.
    type Input<'h>;
    /// How to get the arguments from the [`Hookable`].
    ///
    /// This function is triggered once on every call that was added
    /// via [`hook::add`]. So if three hooks were added to
    /// [`BufferSaved`], for example, [`BufferSaved::get_input`]
    /// will be called three times, once before each hook.
    ///
    /// The vast majority of the time, this function is just a
    /// "getter", as it should take a copy, clone, or reference to the
    /// input type, which should be owned by the `Hookable`. For
    /// example, here's the definition of the [`KeyTyped`] hook:
    ///
    /// ```rust
    /// # duat_core::doc_duat!(duat);
    /// use duat::{hook::Hookable, mode::KeyEvent, prelude::*};
    ///
    /// struct KeyTyped(pub(crate) KeyEvent);
    ///
    /// impl Hookable for KeyTyped {
    ///     type Input<'h> = KeyEvent;
    ///
    ///     fn get_input<'h>(&'h mut self, pa: &mut Pass) -> Self::Input<'h> {
    ///         self.0
    ///     }
    /// }
    /// ```
    ///
    /// However, given the `&mut self` and `&mut Pass`, you can also
    /// do "inter hook mutations", in order to prepare for future hook
    /// calls. An example of this is on [`BufferUpdated`].
    ///
    /// Note that the [`Pass`] here is purely for internal use, you
    /// are not allowed to return something that borrows from it, as
    /// the borrow checker will prevent you.
    ///
    /// [`hook::add`]: add
    fn get_input<'h>(&'h mut self, pa: &mut Pass) -> Self::Input<'h>;
}

/// Where all hooks of Duat are stored.
#[derive(Clone, Copy)]
struct InnerHooks {
    types: &'static Mutex<HashMap<TypeId, Box<dyn HookHolder>>>,
    namespaces: &'static Mutex<Vec<Ns>>,
}

impl InnerHooks {
    /// Adds a hook for a [`Hookable`]
    fn add<H: Hookable>(
        &self,
        callback: Callback<H>,
        ns: Option<Ns>,
        filter: Option<Box<dyn Fn(&H) -> bool + Send + 'static>>,
        lateness: usize,
    ) {
        let mut map = self.types.lock().unwrap();

        if let Some(ns) = ns {
            let mut namespaces = self.namespaces.lock().unwrap();
            if !namespaces.contains(&ns) {
                namespaces.push(ns)
            }
        }

        let new_hook = Hook { callback, ns, filter, lateness };

        if let Some(holder) = map.get(&TypeId::of::<H>()) {
            let hooks_of = unsafe {
                let ptr = (&**holder as *const dyn HookHolder).cast::<HooksOf<H>>();
                ptr.as_ref().unwrap()
            };

            let mut hooks = hooks_of.0.borrow_mut();
            if let Some(i) = hooks.iter().position(|hook| hook.lateness >= lateness) {
                hooks.insert(i, new_hook);
            } else {
                hooks.push(new_hook)
            }
        } else {
            map.insert(
                TypeId::of::<H>(),
                Box::new(HooksOf::<H>(RefCell::new(vec![new_hook]))),
            );
        }
    }

    /// Removes hooks with said group.
    fn remove(&self, ns: Ns) {
        self.namespaces.lock().unwrap().retain(|g| *g != ns);
        let map = self.types.lock().unwrap();
        for holder in map.iter() {
            holder.1.remove(ns)
        }
    }

    /// Triggers hooks with args of the [`Hookable`].
    fn trigger<H: Hookable>(&self, pa: &mut Pass, mut hookable: H) -> H {
        let holder = self.types.lock().unwrap().remove(&TypeId::of::<H>());

        let Some(holder) = holder else {
            return hookable;
        };

        // SAFETY: HooksOf<H> is the only type that this HookHolder could be.
        let hooks_of = unsafe {
            let ptr = Box::into_raw(holder) as *mut HooksOf<H>;
            Box::from_raw(ptr)
        };

        hooks_of.0.borrow_mut().retain_mut(|hook| {
            let has_been_removed = || matches!(hook.ns, Some(ns) if !self.group_exists(ns));

            if has_been_removed() {
                return false;
            }

            if let Some(filter) = hook.filter.as_ref()
                && !filter(&hookable)
            {
                return true;
            }

            let input = hookable.get_input(pa);

            match &mut hook.callback {
                Callback::FnMut(fn_mut) => {
                    catch_panic(|| fn_mut(pa, input));
                    !has_been_removed()
                }
                Callback::FnOnce(fn_once) => {
                    catch_panic(|| fn_once.take().unwrap()(pa, input));
                    false
                }
            }
        });

        let mut types = self.types.lock().unwrap();
        if let Some(new_holder) = types.remove(&TypeId::of::<H>()) {
            let new_hooks_of = unsafe {
                let ptr = Box::into_raw(new_holder) as *mut HooksOf<H>;
                Box::from_raw(ptr)
            };

            hooks_of
                .0
                .borrow_mut()
                .extend(new_hooks_of.0.borrow_mut().drain(..));

            types.insert(TypeId::of::<H>(), unsafe {
                Box::from_raw(Box::into_raw(hooks_of) as *mut dyn HookHolder)
            });
        } else {
            types.insert(TypeId::of::<H>(), unsafe {
                Box::from_raw(Box::into_raw(hooks_of) as *mut dyn HookHolder)
            });
        }

        hookable
    }

    /// Checks if a hook group exists.
    fn group_exists(&self, ns: Ns) -> bool {
        self.namespaces.lock().unwrap().contains(&ns)
    }
}

impl Default for InnerHooks {
    fn default() -> Self {
        Self {
            types: Box::leak(Box::default()),
            namespaces: Box::leak(Box::default()),
        }
    }
}

unsafe impl Send for InnerHooks {}
unsafe impl Sync for InnerHooks {}

/// An intermediary trait, meant for group removal.
trait HookHolder {
    /// Remove the given group from hooks of this holder
    fn remove(&self, ns: Ns);
}

/// An intermediary struct, meant to hold the hooks of a [`Hookable`].
struct HooksOf<H: Hookable>(RefCell<Vec<Hook<H>>>);

impl<H: Hookable> HookHolder for HooksOf<H> {
    fn remove(&self, ns: Ns) {
        let mut hooks = self.0.borrow_mut();
        hooks.retain(|hook| hook.ns.is_none_or(|other| other != ns));
    }
}

struct Hook<H: Hookable> {
    callback: Callback<H>,
    ns: Option<Ns>,
    filter: Option<Box<dyn Fn(&H) -> bool + Send + 'static>>,
    lateness: usize,
}

enum Callback<H: Hookable> {
    FnMut(Box<dyn FnMut(&mut Pass, <H as Hookable>::Input<'_>)>),
    FnOnce(Option<Box<dyn FnOnce(&mut Pass, <H as Hookable>::Input<'_>)>>),
}