duat 0.10.2

A modern, very customizable text editor, configured in rust.
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
//! General options for Duat.
//!
//! This struct is sent as an argument to duat's setup function, are
//! applied _globally_, and mostly serve as convenience methods to
//! modify Duat's behavior. If you wish to apply them on a case by
//! case basis, you should reach out for [hooks].
//!
//! [hooks]: crate::hook
use std::any::TypeId;

use duat_base::widgets::{LineNumbersOpts, LogBookOpts, StatusLineFmt};
#[allow(unused_imports)]
pub use duat_core::opts::*;
use duat_core::{
    data::Pass,
    mode::{Description, KeyCode, KeyEvent, KeyMod, Mode},
    text::Text,
    ui::Orientation,
};
pub use duatmode::TabMode;
use duatmode::opts::DuatModeOpts;

use crate::widgets::NotificationsOpts;

/// General options to set when starting Duat.
pub struct Opts {
    /// Highlights the current line.
    ///
    /// The default is `true`
    ///
    /// This makes use of the `current_line` [`Form`]
    ///
    /// [`Form`]: crate::form::Form
    pub highlight_current_line: bool,
    /// Enables wrapping of lines.
    ///
    /// The default is `true`
    pub wrap_lines: bool,
    /// Wrap on word boundaries, rather than on any character.
    ///
    /// The default is `false`.
    pub wrap_on_word: bool,
    /// Where to start wrapping.
    ///
    /// The default is `None`
    ///
    /// If this value is `None` and `opts.wrap_lines == false`, then
    /// wrapping will take place at the right edge of the screen.
    ///
    /// Otherwise, if it is `Some({cap})`, then wrapping will take
    /// place `{cap}` cells from the left edge. This value may or may
    /// not be greater than the width of the area. If it is greater
    /// than it, then wrapping will take place slightly outside the
    /// screen as a concequence.
    pub wrapping_cap: Option<u32>,
    /// Whether to indent wrapped lines or not.
    ///
    /// In [`Buffer`]s, the default is `true`.
    ///
    /// This turns this:
    ///
    /// ```text
    ///     This is a very long line of text, so long that it
    /// wraps around
    /// ```
    ///
    /// Into this:
    ///
    /// ```text
    ///     This is a very long line of text, so long that it
    ///     wraps around
    /// ```
    ///
    /// [`Buffer`]: crate::buffer::Buffer
    pub indent_wraps: bool,
    /// How long tabs should be on screen.
    ///
    /// In [`Buffer`]s, the default is `4`
    ///
    /// This also affect other things, like if your tabs are converted
    /// into spaces, this will also set how many spaces should be
    /// added.
    ///
    /// [`Buffer`]: crate::buffer::Buffer
    pub tabstop: u8,
    /// How much space to keep between the cursor and edges.
    ///
    /// In [`Buffer`]s, the default is `ScrollOff { x: 3, y: 3 }`
    ///
    /// [`Buffer`]: crate::buffer::Buffer
    pub scrolloff: ScrollOff,
    /// Whether to limit scrolloff at the end of lines.
    ///
    /// In [`Buffer`]s, the default is `false`
    ///
    /// This makes it so, as you reach the end of a long line of text,
    /// the cursor line will continue scrolling to the left,
    /// maintaining the `scrolloff.x`'s gap.
    ///
    /// [`Buffer`]: crate::buffer::Buffer
    pub force_scrolloff: bool,
    /// Extra characters to be considered part of a word.
    ///
    /// The default is `&[]`.
    ///
    /// Normally, word characters include all of those in the [`\w`]
    /// character set, which most importantly includes `[0-9A-Za-z_]`.
    ///
    /// You can use this setting to add more characters to that list,
    /// usually something like `-`, `$` or `@`, which are useful to
    /// consider as word characters in some circumstances.
    ///
    /// [`\w`]: https://www.unicode.org/reports/tr18/#word
    pub extra_word_chars: &'static [char],
    /// Indent string.
    ///
    /// The default is `Some("│")`.
    ///
    /// The indent lines will be printed with the `replace.indent`
    /// [`Form`].
    ///
    /// A string to replace the indentation at the start of the line.
    /// This string will repeat on every `opts.tabstop` initial spaces
    /// or on every `\t` character, replacing that many characters of
    /// the tab stop with those of the string.
    ///
    /// For example, if `tabstop == 2 && indent_str == Some("│")`,
    /// this:
    ///
    /// ```txt
    /// int (int var1, int var2) {
    ///   if (var1 > 2)
    ///     return 42;
    ///   else
    ///     if (var1 <= 50)
    ///       return 20;
    ///     else
    ///       return 10;
    /// }
    /// ```
    ///
    /// Would be displayed like this:
    ///
    /// ```txt
    /// int (int var1, int var2) {
    /// │ if (var1 > 2)
    /// │ │ return 42;
    /// │ else
    /// │ │ if (var1 <= 50)
    /// │ │ │ return 20;
    /// │ │ else
    /// │ │ │ return 10;
    /// }
    /// ```
    ///
    /// That is, it will take `tabstop` characters and print them.
    /// Where the `tabstop == 4`, it would use all 4 characters.
    ///
    /// [`Form`]: crate::form::Form
    pub indent_str: Option<&'static str>,
    /// Wether to copy the indentation string of `opts.indent_str` on
    /// empty lines.
    ///
    /// The default is `true`
    ///
    /// This will always copy whichever line has the smallest ammount
    /// of indentation.
    pub indent_str_on_empty: bool,
    /// An indent string, just like `opts.indent_str`, but only for
    /// `\t`s.
    ///
    /// The default is `None`
    ///
    /// This is useful for languages like python, where the mixup of
    /// tabs and spaces on indentation can cause problems.
    ///
    /// If it is `Some`, the `str` will be shown with the
    /// `replace.indent.tab` form. If this is `None`, then
    /// `opts.indent_str` will be used instead.
    pub indent_tab_str: Option<&'static str>,
    /// A character to be printed in place of the space.
    ///
    /// The default is `None`
    ///
    /// The char will be printed with the `replace.space` [`Form`].
    ///
    /// This character will replace only the space characters that are
    /// not part of the indentation.
    ///
    /// [`Form`]: crate::form::Form
    pub space_char: Option<char>,
    /// Which `char` should be printed in new lines.
    ///
    /// The default is `' '` (space character)
    ///
    /// This character will be printed with the `replace.newline`
    /// [`Form`].
    ///
    /// [`Buffer`]: crate::buffer::Buffer
    /// [`Form`]: crate::form::Form
    pub newline: char,
    /// A character to be printed on the new line on empty strings.
    ///
    /// The default is `None`
    ///
    /// This character will be printed with the
    /// `replace.newline.empty` [`Form`].
    ///
    /// If it is `None`, it will be the same as `opts.newline`.
    ///
    /// [`Form`]: crate::form::Form
    pub newline_on_empty: Option<char>,
    /// A character to be printed on trailing new lines.
    ///
    /// The default is `None`
    ///
    /// This character will be printed with the
    /// `replace.newline.trailing` [`Form`].
    ///
    /// [`Form`]: crate::form::Form
    pub newline_trailing: Option<char>,
    /// Options concerning the [`duatmode`] [`Mode`]s.
    ///
    /// `duatmode` is the default key arrangement of Duat. These
    /// options tweak the behavior of this arrangement.
    ///
    /// Note that you can have other arrangements for `mode`s, (e.g. a
    /// vim one, or a helix one), and these options may not apply to
    /// those.
    pub duatmode: DuatModeOpts,
    /// Makes the [`FooterWidgets`] take up one line instead of two.
    ///
    /// Normally, the [`StatusLine`] is placed in one line and the
    /// [`PromptLine`] and [`Notifications`] are placed on another.
    /// With this option set to `true`, they will all occupy one
    /// line, the same way Kakoune does it.
    ///
    /// If you don't call [`Opts::fmt_status`], this will also
    /// reformat the [`StatusLine`] to this:
    ///
    /// ```rust
    /// # use duat::prelude::*;
    /// let mode = mode_txt();
    /// let new_status = status!("{Spacer}{name_txt} {mode} {sels_txt} {main_txt}");
    /// ```
    ///
    /// This will firmly put all the information on the right side,
    /// like Kakoune does.
    ///
    /// [`FooterWidgets`]: crate::widgets::FooterWidgets
    /// [`StatusLine`]: crate::widgets::StatusLine
    /// [`PromptLine`]: crate::widgets::PromptLine
    /// [`Notifications`]: crate::widgets::Notifications
    /// [`Widget`]: crate::widgets::Widget
    /// [`Opts::fmt_status`]: Opts::fmt_status
    pub one_line_footer: bool,
    /// Place the [`FooterWidgets`]s on top of the screen.
    ///
    /// Normally, the [`StatusLine`], [`PromptLine`] and
    /// [`Notifications`] [`Widget`]s are placed at the bottom of
    /// the screen, you can use this option to change that.
    ///
    /// [`FooterWidgets`]: crate::widgets::FooterWidgets
    /// [`StatusLine`]: crate::widgets::StatusLine
    /// [`PromptLine`]: crate::widgets::PromptLine
    /// [`Notifications`]: crate::widgets::Notifications
    /// [`Widget`]: crate::ui::Widget
    pub footer_on_top: bool,
    /// A [`KeyEvent`] to show the [`WhichKey`] widget.
    ///
    /// If [`None`] is given, the help key functionality will be
    /// disabled entirely, though the `WhichKey` widget will
    /// continue to show up automatically when appropriate. You
    /// can disable that functionality by [removing] the
    /// `"WhichKey"` hook.
    ///
    /// [`WhichKey`]: crate::widgets::WhichKey
    /// [removing]: crate::hook::remove
    pub help_key: Option<KeyEvent>,
    /// Options for the [`LineNumbers`]s widget.
    ///
    /// Do note that, at the moment, these options only apply to newly
    /// opened `LineNumbers`s, not to those that already exist.
    ///
    /// [`LineNumbers`]: crate::widgets::LineNumbers
    pub line_numbers: LineNumbersOpts,
    /// Options for the [`Notifications`] widget.
    ///
    /// The main purpose of these options is to modify how messages
    /// get displayed in the `Widget`, here's how you can do that:
    ///
    /// ```rust
    /// setup_duat!(setup);
    /// use context::Level::*;
    /// use duat::prelude::*;
    ///
    /// fn setup(opts: &mut Opts) {
    ///     opts.notifications.fmt(|rec| {
    ///         let mut builder = Text::builder();
    ///
    ///         match rec.level() {
    ///             Error => builder.push(txt!("[log_book.error]  ")),
    ///             Warn => builder.push(txt!("[log_book.warn]  ")),
    ///             Info => builder.push(txt!("[log_book.info]  ")),
    ///             Debug => builder.push(txt!("[log_book.debug]  ")),
    ///             Trace => unreachable!(""),
    ///         };
    ///
    ///         builder.push(rec.text().clone());
    ///
    ///         builder.build()
    ///     });
    ///
    ///     opts.notifications
    ///         .set_allowed_levels([Error, Warn, Info, Debug]);
    /// }
    /// ```
    ///
    /// In the snippet above, I'm reformatting the notifications, so
    /// they show a symbol for identification. I'm also making use
    /// of the `log_book.{}` forms, since those are already set by
    /// the [`LogBook`].
    ///
    /// Do note that, at the moment, these options only apply to newly
    /// opened `Notifications`s, not to those that already exist.
    ///
    /// [`Notifications`]: crate::widgets::Notifications
    /// [`LogBook`]: crate::widgets::LogBook
    pub notifications: NotificationsOpts,
    /// Changes the [`WhichKey`] widget.
    ///
    /// This is the [`Widget`] that shows available bindings, as well
    /// as any possible remappings to those bindings, whenever you
    /// type a multi key sequence (and on other circumstances too).
    ///
    /// [`WhichKey`]: crate::widgets::WhichKey
    /// [`Widget`]: crate::widgets::Widget
    pub whichkey: WhichKeyOpts,
    /// Options for the [`LogBook`] widget.
    ///
    /// You can open the `LogBook` by calling the `"logs"` command,
    /// which will also focus on the `Widget`.
    ///
    /// By default, the `LogBook` will be shown at the bottom of the
    /// screen, and it shows the full log of notifications sent do
    /// Duat, unlike the [`Notifications`] `Widget`, which shows
    /// only the last one.
    ///
    /// You can change how the logs are displayed, here's how:
    ///
    /// ```rust
    /// setup_duat!(setup);
    /// use duat::prelude::*;
    ///
    /// fn setup(opts: &mut Opts) {
    ///     let logs = &mut opts.logs;
    ///
    ///     logs.fmt(|rec| match rec.level() {
    ///         context::Level::Error => Some(txt!("[log_book.error]  {}", rec.text())),
    ///         _ => None,
    ///     });
    ///
    ///     logs.hidden = false;
    ///     logs.close_on_unfocus = false;
    ///     logs.side = ui::Side::Right;
    ///     logs.width = 75.0;
    /// }
    /// ```
    ///
    /// Here, I'm reformatting the notifications. Note that the
    /// closure return [`Some`] only when the notification is of
    /// type [`Level::Error`]. This filters out other types of
    /// notifications, which could be useful for heavy debugging
    /// sessions.
    ///
    /// Also helpful for debugging are the other options set. For
    /// example, if you're debugging a Duat [`Plugin`], it would
    /// be useful to show the [`LogBook`] right as Duat is
    /// reloaded, so you can see diagnostics immediately.
    ///
    /// Do note that, at the moment, these options only apply to newly
    /// opened `LogBook`s, not to those that already exist.
    ///
    /// [`Notifications`]: crate::widgets::Notifications
    /// [`Level::Error`]: crate::context::Level::Error
    /// [`Plugin`]: crate::Plugin
    /// [`LogBook`]: crate::widgets::LogBook
    pub logs: LogBookOpts,
    /// Which default hooks should be enabled.
    ///
    /// This can optionally let you turn off various parts of Duat,
    /// either because you don't want that funcionality or because you
    /// wish to add your own replacement for it.
    pub enabled_hooks: EnabledHooks,
    pub(crate) status_fmt_fn: Option<StatusLineFn>,
}

/// A struct that lets you optionally disable some of Duat's default
/// hooks.
///
/// This lets you turn off a bunch of functionality in order to either
/// not have it, or replace it with your own version.
///
/// Every item here is set to `true` by default, and by setting it to
/// `false`, you will disable that functionality.
pub struct EnabledHooks {
    /// Enables the default [`BufferOpts`] parser.
    ///
    /// This parser is responsible for dynamically adding things like
    /// indent lines, trailing newlines and other replacement
    /// characters.
    ///
    /// You can disable this if you wish to replace it with your own
    /// version.
    ///
    /// [`BufferOpts`]: crate::buffer::BufferOpts
    pub default_opts_parser: bool,
    /// Automatically reloads the configuration whenever you save a
    /// file in the config crate.
    ///
    /// Instead of calling `:write` followed by a call to `:reload`,
    /// by having this enabled, just by calling `:write` (or `:w` or
    /// `wa`), you will automatically trigger a reload.
    pub reload_on_save: bool,
    /// Automatically reloads [`Buffer`]s whenever an external change
    /// is detected.
    ///
    /// This feature is completely automatic, that is, there's no
    /// prompt asking you if you want to do it. You may want to
    /// disable this feature if you either don't want auto reloads, or
    /// you don't want them to be completely automatic.
    ///
    /// [`Buffer`]: crate::widgets::Buffer
    pub auto_reload_buffers: bool,
    /// Automatically shows the [`WhichKey`] widget.
    ///
    /// The `WhichKey` widget tells you which keys are mapped in your
    /// current situation. If you type a mapped sequence like `jk` or
    /// `'w`, this widget will helpfully show you which keys you can
    /// type next, and what each of them will do.
    ///
    /// If you want to configure the `WhichKey`, you can check out
    /// [`opts.whichkey`].
    ///
    /// You can disable this if you don't like this functionality, or
    /// if you want to replace it with your own version.
    ///
    /// [`WhichKey`]: crate::widgets::WhichKey
    /// [`opts.whichkey`]: Opts::whichkey
    pub show_whichkey: bool,
    /// Adds the default buffer widgets to every [`Buffer`]
    ///
    /// These include mainly the [`LineNumbers`] and [`Gutter`], which
    /// most people using a text editor would want to make use of.
    ///
    /// One reason you might want to disable this hook is if you want
    /// to change their order, like this:
    ///
    /// ```rust
    /// setup_duat!(setup);
    /// use duat::prelude::*;
    /// use widgets::*;
    ///
    /// fn setup(opts: &mut Opts) {
    ///     opts.enabled_hooks.default_buffer_widgets = false;
    ///
    ///     let line_numbers = opts.line_numbers;
    ///     hook::add::<BufferOpened>(move |pa, buffer| {
    ///         VertRule::builder().push_on(pa, buffer);
    ///         Gutter::builder().push_on(pa, buffer);
    ///         VertRule::builder().push_on(pa, buffer);
    ///         line_numbers.push_on(pa, buffer);
    ///     });
    /// }
    /// ```
    ///
    /// Normally, the `Gutter` is to the left of the `LineNumbers`,
    /// but with the snipped above, that will be the other way around.
    /// The [`VertRule`]s in there only serve the purpose of adding
    /// spacing to the widgets.
    ///
    /// [`Buffer`]: crate::widgets::Buffer
    /// [`LineNumbers`]: crate::widgets::LineNumbers
    /// [`Gutter`]: crate::widgets::Gutter
    /// [`VertRule`]: crate::widgets::VertRule
    pub default_buffer_widgets: bool,
    /// Adds the default [`FooterWidgets`] to each window.
    ///
    /// This is a bundle of widgets that are necessary for some basic
    /// Duat functionality. It includes:
    ///
    /// - The [`StatusLine`], which shows information about Duat and
    ///   the current [`Buffer`]. It can be altered by calling
    ///   [`opts.fmt_status`].
    /// - The [`PromptLine`], which is where you type things like
    ///   [commands] and search queries.
    /// - [`Notifications`], which shows messages when things happen.
    ///
    /// By disabling this hook, you will remove all three widgets. One
    /// reason you might want to do this is to customize one of these
    /// three widgets, maybe make them floating or things like that.
    ///
    /// Do keep in mind however, that by disabling the
    /// `FooterWidgets`, unless you add another [`PromptLine`], you
    /// will _lose the ability to run commands_, which includes things
    /// like quitting duat.
    ///
    /// [`FooterWidgets`]: crate::widgets::FooterWidgets
    /// [`Buffer`]: crate::widgets::Buffer
    /// [`StatusLine`]: crate::widgets::StatusLine
    /// [`opts.fmt_status`]: Opts::fmt_status
    /// [`PromptLine`]: crate::widgets::PromptLine
    /// [commands]: crate::cmd
    /// [`Notifications`]: crate::widgets::Notifications
    pub default_footer_widgets: bool,
    /// Save cursor positions when closing [`Buffer`]s.
    ///
    /// By having this enabled, whenever you close a `Buffer` and
    /// reopen it in the future, your cursor position will be the same
    /// as when you closed.
    ///
    /// [`Buffer`]: crate::widgets::Buffer
    pub cache_cursor_position: bool,
}

impl Opts {
    /// Reformat the [`StatusLine`] using the [`status!`] macro.
    ///
    /// The `status!` macro is very convenient for showing information
    /// about Duat, but most importantly to show information about
    /// [`Buffer`]s.
    ///
    /// The `status!` macro follows the same syntax as the [`txt!`]
    /// macro, although inlined arguments tend to be functions,
    /// rather than just variables. Here's the default
    /// [`StatusLine`]:
    ///
    /// ```rust
    /// # use duat::prelude::*;
    /// let mode = mode_txt();
    /// status!("{mode}{Spacer}{name_txt} {sels_txt} {main_txt}");
    /// ```
    ///
    /// The `mode` has to be explicitely returned, because
    /// [`mode_txt`] isn't a `StatusLine` part, but a function
    /// that returns a [`DataMap<&str, Text>`], which can be used
    /// as a `StatusLine` part.
    ///
    /// The [`Spacer`] here serves to do just that, separate the text
    /// into two parts, each on one part of the screen. You can
    /// place as many of these as you want, for example, this
    /// function will place the `Buffer`'s name in between the two
    /// side parts:
    ///
    /// ```rust
    /// # use duat::prelude::*;
    /// let mode = mode_txt();
    /// status!("{mode}{Spacer}{name_txt}{Spacer}{sels_txt} {main_txt}");
    /// ```
    ///
    /// # Configuration
    ///
    /// Duat provides a bunch of built-in functions to modify the
    /// `StatusLine`:
    ///
    /// - [`name_txt`]: `Text` with the `Buffer`'s name.
    /// - [`path_txt`]: `Text` with the `Buffer`'s full path.
    /// - [`mode_name`]: Unformatted mode (e.g. `"Prompt"`,
    ///   `"Normal"`).
    /// - [`mode_txt`]: Formatted mode as `Text` (e.g. "normal").
    /// - [`main_byte`]: byte index of the main cursor, 1 indexed.
    /// - [`main_char`]: character index of the main cursor, 1
    ///   indexed.
    /// - [`main_line`]: line index of the main cursor, 1 indexed.
    /// - [`main_col`]: column of the main cursor, 1 indexed.
    /// - [`main_txt`]: `Text` showing main cursor and line count
    ///   info.
    /// - [`sels_txt`]: `Text` showing the number of cursors.
    /// - [`mapped_txt`]: `Text` showing the keys being mapped.
    /// - [`last_key`]: The last typed key.
    ///
    /// A rule of thumb is that every argument suffixed with `_txt` is
    /// a function that returns a [`Text`], usually by making use
    /// of the [`txt!`] macro. The [`Spacer`] in there is just one
    /// of the many [`Tag`]s that can be placed on `Text`.
    ///
    /// The other functions could return anything that implements the
    /// [`Display`] or [`Debug`] traits.
    ///
    /// It is rather easy to make a function that can be slotted into
    /// the [`StatusLine`]:
    ///
    /// ```rust
    /// # use duat::prelude::*;
    /// fn zero_main_txt(buffer: &Buffer, area: &Area) -> Text {
    ///     txt!(
    ///         "[coord]{}[separator]|[coord]{}[separator]/[coord]{}",
    ///         main_col(buffer, area) - 1,
    ///         main_line(buffer) - 1,
    ///         buffer.text().end_point().line()
    ///     )
    /// }
    ///
    /// let mode = mode_txt();
    /// status!("{mode}{Spacer}{name_txt} {sels_txt} {zero_main_txt}");
    /// ```
    ///
    /// This is just the main cursor ([`Selection`]), but 0 indexed,
    /// as opposed to 1 indexed. The `[coord]` and `[spearator]`
    /// bits apply the `"coord"` and `"separator"` [`Form`]s,
    /// which you can change by calling [`form::set`].
    ///
    /// Of course, you could do this inline as well:
    ///
    /// ```rust
    /// # fn test() {
    /// # use duat::prelude::*;
    /// let mode = mode_txt();
    /// status!(
    ///     "{mode}{Spacer}{name_txt} {sels_txt} [coord]{}[separator]|[coord]{}[separator]/[coord]{}",
    ///     |buf: &Buffer, area: &Area| main_col(buf, area) - 1,
    ///     |buf: &Buffer| main_line(buf) - 1,
    ///     |buf: &Buffer| buf.text().end_point().line()
    /// );
    /// # }
    /// ```
    ///
    /// A full list of which types can be used as `StatusLine` parts
    /// can be found in the documentation for the [`status!`]
    /// macro.
    ///
    /// # Where to place
    ///
    /// Normally, the [`StatusLine`] is included in the
    /// [`FooterWidgets`], which is a "bundle" of [`Widget`]s,
    /// including the [`PromptLine`] and [`Notifications`]. This
    /// means that it will follow them around, so you have a few
    /// options for customization of this group, all in the
    /// [`Opts`] struct:
    ///
    /// - [`Opts::footer_on_top`]: Will place the `StatusLine`,
    ///   `PromptLine`, and `Notifications` `Widget`s on top of the
    ///   window, rather than at the bottom.
    ///
    /// - [`Opts::one_line_footer`]: These widgets will occupy one
    ///   line rather than two, Kakoune style.
    ///
    /// # Which [`Buffer`]?
    ///
    /// As you could see above, the [`status!`] macro can take
    /// functions that take `Buffer`s. But if there are multiple
    /// open `Buffer`s, which one is used as an argument?
    ///
    /// Basically, the [`Buffer`] in question is the "most relevant
    /// `Buffer`", which is determined as follows, on a `StatusLine`
    /// by `StatusLine` basis:
    ///
    /// - If the `StatusLine` was [pushed onto a `Buffer`], then that
    ///   `Buffer` is the argument.
    /// - If it was [pushed around the window], the [active `Buffer`]
    ///   is the argument. This is where the [`FooterWidgets`] are
    ///   placed by default.
    ///
    /// This means that, with multiple `StatusLine`s, you could create
    /// custom statuses that show global information, as well as
    /// information about each [`Buffer`]:
    ///
    /// ```rust
    /// setup_duat!(setup);
    /// use duat::prelude::*;
    ///
    /// fn buf_percent(text: &Text, main: &Selection) -> Text {
    ///     // The caret is the part of the cursor that moves, as opposed to the anchor.
    ///     let caret = main.caret();
    ///     txt!("[coord]{}%", (100 * caret.line()) / text.end_point().line())
    /// }
    ///
    /// fn setup(opts: &mut Opts) {
    ///     hook::add::<BufferOpened>(|pa, handle| {
    ///         status!("{name_txt}{Spacer}{buf_percent}")
    ///             .above()
    ///             .push_on(pa, handle);
    ///     });
    /// }
    /// ```
    ///
    /// With the snipped above, not only will there be the global
    /// [`StatusLine`] at the bottom, but each [`Buffer`] will also
    /// have a `StatusLine` above, showing the `Buffer`'s name and
    /// the line percentage covered by the main cursor.
    ///
    /// [`StatusLine`]: crate::widgets::StatusLine
    /// [`status!`]: crate::widgets::status
    /// [`Buffer`]: crate::widgets::Buffer
    /// [`txt!`]: crate::text::txt
    /// [`Text`]: crate::text::Text
    /// [`Spacer`]: crate::text::Spacer
    /// [`Tag`]: crate::text::Tag
    /// [`name_txt`]: crate::state::name_txt
    /// [`path_txt`]: crate::state::path_txt
    /// [`mode_name`]: crate::state::mode_name
    /// [`mode_txt`]: crate::state::mode_txt
    /// [`main_byte`]: crate::state::main_byte
    /// [`main_char`]: crate::state::main_char
    /// [`main_line`]: crate::state::main_line
    /// [`main_col`]: crate::state::main_col
    /// [`main_txt`]: crate::state::main_txt
    /// [`sels_txt`]: crate::state::sels_txt
    /// [`mapped_txt`]: crate::state::mapped_txt
    /// [`last_key`]: crate::state::last_key
    /// [`Display`]: std::fmt::Display
    /// [`Debug`]: std::fmt::Debug
    /// [`Selection`]: crate::mode::Selection
    /// [`Form`]: crate::form::Form
    /// [`form::set`]: crate::form::set
    /// [`DataMap<&str, Text>`]: crate::data::DataMap
    /// [pushed onto a `Buffer`]: crate::context::Handle::push_outer_widget
    /// [pushed around the window]: crate::ui::Window::push_outer
    /// [active `Buffer`]: crate::context::dynamic_buffer
    /// [`Widget`]: crate::ui::Widget
    /// [`PromptLine`]: crate::widgets::PromptLine
    /// [`Notifications`]: crate::widgets::Notifications
    /// [`FooterWidgets`]: crate::widgets::FooterWidgets
    pub fn fmt_status(&mut self, fmt: impl FnMut(&mut Pass) -> StatusLineFmt + Send + 'static) {
        self.status_fmt_fn = Some(Box::new(fmt));
    }
}

impl Default for Opts {
    fn default() -> Self {
        Self {
            highlight_current_line: true,
            wrap_lines: true,
            wrap_on_word: false,
            wrapping_cap: None,
            indent_wraps: true,
            tabstop: 4,
            scrolloff: ScrollOff { x: 3, y: 3 },
            force_scrolloff: false,
            extra_word_chars: &[],
            indent_str: Some(""),
            indent_str_on_empty: true,
            indent_tab_str: None,
            space_char: None,
            newline: ' ',
            newline_on_empty: None,
            newline_trailing: Some(''),
            duatmode: DuatModeOpts::default(),
            one_line_footer: false,
            footer_on_top: false,
            help_key: Some(KeyEvent::new(KeyCode::Char('h'), KeyMod::CONTROL)),
            line_numbers: LineNumbersOpts::default(),
            notifications: NotificationsOpts::default(),
            whichkey: WhichKeyOpts::default(),
            logs: LogBookOpts::default(),
            status_fmt_fn: None,
            enabled_hooks: EnabledHooks {
                default_opts_parser: true,
                reload_on_save: true,
                auto_reload_buffers: true,
                show_whichkey: true,
                default_buffer_widgets: true,
                default_footer_widgets: true,
                cache_cursor_position: true,
            },
        }
    }
}

/// Options for the [`WhichKey`] widget.
///
/// These options concern the formatting and on which [`Mode`]s the
/// help should show up:
///
/// - [`disable_for`]: Disables the automatic showing of `WhichKey` on
///   a `Mode`. It'll still show up with the [help key]. If you want
///   to disable for all `Mode`s, [remove] the `"WhichKey"` hook
///   group.
///
/// [`WhichKey`]: crate::widgets::WhichKey
/// [`disable_for`]: WhichKeyOpts::disable_for
/// [help key]: Opts::help_key
/// [remove]: crate::hook::remove
pub struct WhichKeyOpts {
    pub(crate) fmt_getter: Option<Box<dyn Fn() -> DescriptionFn + Send + 'static>>,
    pub(crate) disabled_modes: Vec<TypeId>,
    pub(crate) always_shown_modes: Vec<TypeId>,
    /// Where to place the [`Widget`].
    ///
    /// Normally, this is [`Orientation::VerRightBelow`]. Since it's
    /// placed "inside" of the parent `Widget`, this normally places
    /// the widget on the bottom right corner, inside of the active
    /// [`Buffer`].
    ///
    /// [`Widget`]: crate::widgets::Widget
    /// [`Buffer`]: crate::widgets::Buffer
    pub orientation: Orientation,
}

impl Default for WhichKeyOpts {
    fn default() -> Self {
        Self {
            fmt_getter: None,
            disabled_modes: vec![TypeId::of::<duatmode::Insert>()],
            always_shown_modes: vec![TypeId::of::<crate::mode::User>()],
            orientation: Orientation::VerRightBelow,
        }
    }
}

impl WhichKeyOpts {
    /// How to format the `WhichKey` widget.
    ///
    /// This function returns an [`Option<(Text, Text)>`]. The first
    /// [`Text`] is used for the keys, the second `Text` is used for
    /// the description of said keys.
    ///
    /// If it returns [`None`], then that specific entry won't show up
    /// on the list of bindings. This is useful for, for example,
    /// hiding entries that have no description `Text`, which is done
    /// by default.
    pub fn fmt(
        &mut self,
        fmt: impl FnMut(Description) -> Option<(Text, Text)> + Send + Clone + 'static,
    ) {
        self.fmt_getter = Some(Box::new(move || Box::new(fmt.clone())))
    }

    /// Disable hints for the given [`Mode`].
    ///
    /// The hints will still show up if you press the [help key]. By
    /// default, `WhichKey` is disabled for `duatmode`'s [`Insert`]
    /// mode.
    ///
    /// Calling this function will also remove said `Mode` from the
    /// [always shown list].
    ///
    /// [`Mode`]: crate::mode::Mode
    /// [help key]: Opts::help_key
    /// [`Insert`]: crate::mode::Insert
    /// [always shown list]: Self::always_show
    pub fn disable_for<M: Mode>(&mut self) {
        self.always_shown_modes
            .retain(|ty| *ty != TypeId::of::<M>());
        self.disabled_modes.push(TypeId::of::<M>());
    }

    /// Makes the [`WhichKey`] permanently visible on this [`Mode`].
    ///
    /// This is useful for `Mode`s where the keys don't form
    /// sequences, but you'd still want them shown to the user. By
    /// default, this is enabled for the [`User`] mode.
    ///
    /// Calling this function will also remove said `Mode` from the
    /// [disabled list].
    ///
    /// [`WhichKey`]: crate::widgets::WhichKey
    /// [`User`]: crate::mode::User
    /// [disabled list]: Self::disable_for
    pub fn always_show<M: Mode>(&mut self) {
        self.disabled_modes.retain(|ty| *ty != TypeId::of::<M>());
        self.always_shown_modes.push(TypeId::of::<M>());
    }

    /// Makes the [`WhichKey`] show up normally on this [`Mode`].
    ///
    /// This function just removes this `Mode` from the [disabled] and
    /// [always shown] lists. By calling it, the [`WhichKey`]s widget
    /// will be displayed when you begin typing a sequence of bound or
    /// mapped keys.
    ///
    /// [`WhichKey`]: crate::widgets::WhichKey
    /// [disabled]: Self::disable_for
    /// [always shown]: Self::always_show
    pub fn show_normally<M: Mode>(&mut self) {
        self.disabled_modes.retain(|ty| *ty != TypeId::of::<M>());
        self.always_shown_modes
            .retain(|ty| *ty != TypeId::of::<M>());
    }
}

type StatusLineFn = Box<dyn FnMut(&mut Pass) -> StatusLineFmt + Send + 'static>;
type DescriptionFn = Box<dyn FnMut(Description<'_>) -> Option<(Text, Text)> + 'static>;