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
//! General utility functions for Duat.
//!
//! This module contains a bunch of functions which are mostly useful
//! within Duat, but I have found use for them in some of my plugins,
//! so I'm making them public for other to use as well.
//!
//! An example of these functions are those that deal with ranges of
//! "shifted parts".
//!
//! Internally (and externally), these functions work with structs
//! that have a "shift" component. The shifting component indicates at
//! which point in the list there is a shift. Elements before that
//! point are considered to be correctly shifted, while elements
//! after that point are considered to be incorrectly shifted by the
//! exact size of the shift.
//!
//! This essentially lets me have a sorted list (for binary search and
//! fast insertion via [`GapBuffer`]s) while still letting me shift
//! elements (usually by a [`Change`] in the [`Text`]) without
//! updating every element after the `Change`. I just have to shift
//! elements between where the `Change` was inserted and where the
//! shift starts.
//!
//! This mirrors how text editing works in the real world. A user
//! doesn't just type randomly on the text buffer, the changes are
//! usually localized. Given that, this model of keeping a shifting
//! point results in a very low number of updates that need to be
//! made.
//!
//! One other (more common) way to prevent a bazillion changes to the
//! text is to divide said text in lines. So a change in some place
//! will only affect other elements on the same line. However, the
//! biggest problem with this approach is that you are purposefully
//! dividing your text in lines, which makes a lot of other things
//! more complicated than simply having a buffer of bytes. For
//! example, a change spanning multiple lines is much more complex to
//! implement in this kind of system. And this complexity trickles
//! down through your whole text editor, even down to printing text,
//! which I also find really simple with my system.
//!
//! [`GapBuffer`]: gap_buf::GapBuffer
//! [`Change`]: crate::buffer::Change
use std::{
    any::TypeId,
    collections::HashMap,
    ops::Range,
    path::{Path, PathBuf},
    sync::{LazyLock, Mutex, OnceLock, RwLock},
};

pub use shellexpand::full as expand_path;

use crate::text::{Text, txt};

/// A struct for lazy memoization, meant to be kept as a `static`.
pub struct Memoized<K: std::hash::Hash + std::cmp::Eq, V>(LazyLock<Mutex<HashMap<K, V>>>);

impl<K: std::hash::Hash + std::cmp::Eq, V: Clone + 'static> Memoized<K, V> {
    /// Returns a new `Memoized`, for quick memoization
    pub const fn new() -> Self {
        Self(LazyLock::new(Mutex::default))
    }

    /// Gets a key, or inserts a new one with a given function
    pub fn get_or_insert_with<Q>(&self, key: &Q, f: impl FnOnce() -> V) -> V
    where
        K: std::borrow::Borrow<Q>,
        Q: std::hash::Hash + Eq + Clone + Into<K>,
    {
        let mut map = self.0.lock().unwrap_or_else(|err| err.into_inner());
        match map.get(key) {
            Some(value) => value.clone(),
            None => map.entry(key.clone().into()).or_insert(f()).clone(),
        }
    }
}

impl<K: std::hash::Hash + std::cmp::Eq, V: Clone + 'static> Default for Memoized<K, V> {
    fn default() -> Self {
        Self::new()
    }
}

/// Takes a type and generates an appropriate name for it.
///
/// Use this function if you need a name of a type to be
/// referrable by string, such as by commands or by the
/// user.
pub fn duat_name<T: ?Sized + 'static>() -> &'static str {
    fn duat_name_inner(type_id: TypeId, type_name: &str) -> &'static str {
        static NAMES: LazyLock<RwLock<HashMap<TypeId, &'static str>>> =
            LazyLock::new(RwLock::default);
        let mut names = NAMES.write().unwrap();

        if let Some(name) = names.get(&type_id) {
            name
        } else {
            let mut name = String::new();

            for path in type_name.split_inclusive(['<', '>', ',', ' ']) {
                for segment in path.split("::") {
                    let is_type = segment.chars().any(|c| c.is_uppercase());
                    let is_punct = segment.chars().all(|c| !c.is_alphanumeric());
                    let is_dyn = segment.starts_with("dyn");
                    if is_type || is_punct || is_dyn {
                        name.push_str(segment);
                    }
                }
            }

            names.insert(type_id, name.leak());
            names.get(&type_id).unwrap()
        }
    }

    duat_name_inner(TypeId::of::<T>(), std::any::type_name::<T>())
}

/// Returns the source crate of a given type.
pub fn src_crate<T: ?Sized + 'static>() -> &'static str {
    fn src_crate_inner(type_id: TypeId, type_name: &'static str) -> &'static str {
        static CRATES: LazyLock<RwLock<HashMap<TypeId, &'static str>>> =
            LazyLock::new(|| RwLock::new(HashMap::new()));
        let mut crates = CRATES.write().unwrap();

        if let Some(src_crate) = crates.get(&type_id) {
            src_crate
        } else {
            let src_crate = type_name.split([' ', ':']).find(|w| *w != "dyn").unwrap();

            crates.insert(type_id, src_crate);
            crates.get(&type_id).unwrap()
        }
    }

    src_crate_inner(TypeId::of::<T>(), std::any::type_name::<T>())
}

/// The path for the crate that was loaded.
static CRATE_DIR: OnceLock<Option<&Path>> = OnceLock::new();
/// The profile that was loaded.
static PROFILE: OnceLock<&str> = OnceLock::new();

/// Sets the crate directory.
///
/// **FOR USE BY THE DUAT EXECUTABLE ONLY**
#[doc(hidden)]
#[track_caller]
pub(crate) fn set_crate_profile_and_dir(profile: String, dir: Option<String>) {
    CRATE_DIR
        .set(dir.map(|dir| Path::new(dir.leak())))
        .expect("Crate directory set multiple times.");
    PROFILE
        .set(profile.leak())
        .expect("Profile set multiple times.");
}

/// The path for the config crate of Duat.
#[track_caller]
pub fn crate_dir() -> Result<&'static Path, Text> {
    CRATE_DIR
        .get()
        .expect("Config not set yet")
        .ok_or_else(|| txt!("Config directory is [a]undefined"))
}

/// The Profile that is currently loaded.
///
/// This is only valid inside of the loaded configuration's `run`
/// function, not in the metastatic Ui.
pub fn profile() -> &'static str {
    PROFILE.get().expect("Profile not set yet")
}

/// The path for a plugin's auxiliary buffers.
///
/// If you want to store something in a more permanent basis, and also
/// possibly allow for the user to modify some buffers (e.g. a TOML
/// buffer with definitions for various LSPs), you should place it in
/// here.
///
/// This function will also create said directory, if it doesn't
/// already exist, only returning [`Some`], if it managed to verify
/// its existance.
pub fn plugin_dir(plugin: &str) -> Result<PathBuf, Text> {
    assert_ne!(plugin, "", "Can't have an empty plugin name");

    static PLUGIN_DIR: LazyLock<Option<&Path>> = LazyLock::new(|| {
        dirs_next::data_local_dir().map(|local_dir| {
            let path: &'static str = local_dir
                .join("duat")
                .join("plugins")
                .to_string_lossy()
                .to_string()
                .leak();

            Path::new(path)
        })
    });

    let plugin_dir = (*PLUGIN_DIR)
        .ok_or_else(|| txt!("Local directory is [a]undefined"))?
        .join(plugin);
    std::fs::create_dir_all(&plugin_dir)?;

    Ok(plugin_dir)
}

/// Convenience function for the bounds of a range.
///
/// Non panicking version of [`get_range`].
pub fn try_get_range(range: impl std::ops::RangeBounds<usize>, max: usize) -> Option<Range<usize>> {
    let start = match range.start_bound() {
        std::ops::Bound::Included(start) => *start,
        std::ops::Bound::Excluded(start) => *start + 1,
        std::ops::Bound::Unbounded => 0,
    };
    let end = match range.end_bound() {
        std::ops::Bound::Included(end) => *end + 1,
        std::ops::Bound::Excluded(end) => *end,
        std::ops::Bound::Unbounded => max,
    };

    if start > max || end > max || start > end {
        None
    } else {
        Some(start..end)
    }
}

/// Convenience function for the bounds of a range.
///
/// Panicking version of [`try_get_range`].
#[track_caller]
pub fn get_range(range: impl std::ops::RangeBounds<usize>, max: usize) -> Range<usize> {
    let start = match range.start_bound() {
        std::ops::Bound::Included(start) => *start,
        std::ops::Bound::Excluded(start) => *start + 1,
        std::ops::Bound::Unbounded => 0,
    };
    let end = match range.end_bound() {
        std::ops::Bound::Included(end) => *end + 1,
        std::ops::Bound::Excluded(end) => *end,
        std::ops::Bound::Unbounded => max,
    };

    crate::ranges::assert_range(&(start..end));

    assert!(
        start <= max,
        "start out of bounds: the len is {max}, but the index is {start}",
    );
    assert!(
        end <= max,
        "end out of bounds: the len is {max}, but the index is {end}",
    );

    start..end
}

/// Adds two shifts together.
pub fn add_shifts(lhs: [i32; 3], rhs: [i32; 3]) -> [i32; 3] {
    let b = lhs[0] + rhs[0];
    let c = lhs[1] + rhs[1];
    let l = lhs[2] + rhs[2];
    [b, c, l]
}

/// Allows binary searching with an initial guess and displaced
/// entries.
///
/// This function essentially looks at a list of entries and with a
/// starting shift position, shifts them by an amount, before
/// comparing inside of the binary search.
#[track_caller]
pub fn merging_range_by_guess_and_lazy_shift<T, U: Copy + Ord + std::fmt::Debug, V: Copy>(
    (container, len): (&impl std::ops::Index<usize, Output = T>, usize),
    (guess_i, [start, end]): (usize, [U; 2]),
    (shift_from, shift, zero_shift, shift_fn): (usize, V, V, fn(U, V) -> U),
    (start_fn, end_fn): (fn(&T) -> U, fn(&T) -> U),
) -> Range<usize> {
    let sh = |n: usize| if n >= shift_from { shift } else { zero_shift };
    let start_of = |i: usize| shift_fn(start_fn(&container[i]), sh(i));
    let end_of = |i: usize| shift_fn(end_fn(&container[i]), sh(i));
    let search = |n: usize, t: &T| shift_fn(start_fn(t), sh(n));

    let mut m_range = if let Some(prev_i) = guess_i.checked_sub(1)
        && (prev_i < len && start_of(prev_i) <= start && start <= end_of(prev_i))
    {
        prev_i..guess_i
    } else {
        match binary_search_by_key_and_index(container, len, start, search) {
            Ok(i) => i..i + 1,
            Err(i) => {
                if let Some(prev_i) = i.checked_sub(1)
                    && start <= end_of(prev_i)
                {
                    prev_i..i
                } else {
                    i..i
                }
            }
        }
    };

    // On Cursors, the Cursors can intersect, so we need to check
    while m_range.start > 0 && start <= end_of(m_range.start - 1) {
        m_range.start -= 1;
    }

    // This block determines how far ahead this cursor will merge
    if m_range.end < len && end >= start_of(m_range.end) {
        m_range.end = match binary_search_by_key_and_index(container, len, end, search) {
            Ok(i) => i + 1,
            Err(i) => i,
        }
    }

    while m_range.end + 1 < len && end >= start_of(m_range.end + 1) {
        m_range.end += 1;
    }

    m_range
}

/// A binary search that takes into account the index of the element
/// in order to extract the key.
///
/// In Duat, this is used for searching in ordered lists where the
/// elements after a certain index are shifted by some amount, while
/// those behind that point aren't shifted at all.
#[inline(always)]
pub fn binary_search_by_key_and_index<T, K>(
    container: &(impl std::ops::Index<usize, Output = T> + ?Sized),
    len: usize,
    key: K,
    f: impl Fn(usize, &T) -> K,
) -> std::result::Result<usize, usize>
where
    K: PartialEq + Eq + PartialOrd + Ord,
{
    let mut size = len;
    let mut left = 0;
    let mut right = size;

    while left < right {
        let mid = left + size / 2;

        let k = f(mid, &container[mid]);

        match k.cmp(&key) {
            std::cmp::Ordering::Less => left = mid + 1,
            std::cmp::Ordering::Equal => return Ok(mid),
            std::cmp::Ordering::Greater => right = mid,
        }

        size = right - left;
    }

    Err(left)
}

/// A function to catch panics.
///
/// Used in duat-core in order to prevent sudden panics from just
/// crashing the program, which would be bad for the end user I think.
///
/// You shouldn't use this function unless you are doing a trait based
/// API, where the implementation of traits by users might cause
/// panics.
pub fn catch_panic<R>(f: impl FnOnce() -> R) -> Option<R> {
    std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).ok()
}

/// Log something to a log file, when things are panicking in a way
/// that exits Duat.
#[macro_export]
macro_rules! log_to_file {
    ($($tokens:tt)*) => {{
        use std::io::Write;
        let mut log = std::fs::OpenOptions::new()
            .append(true)
            .create(true)
            .open("log")
            .unwrap();

        writeln!(log, $($tokens)*).unwrap();
    }};
}

/// Macro used internally for doc tests in duat-core.
#[doc(hidden)]
#[rustfmt::skip]
#[macro_export]
macro_rules! doc_duat {
    ($duat:ident) => {
        #[allow(unused, missing_docs)]
        mod $duat {
            pub use $crate::{clipboard, notify, process};
            
            pub struct Opts {
                pub wrap_lines: bool,
                pub wrap_on_word: bool,
                pub wrapping_cap: Option<u32>,
                pub indent_wraps: bool,
                pub tabstop: u8,
                pub print_new_line: bool,
                pub scrolloff: $crate::opts::ScrollOff,
                pub force_scrolloff: bool,
                pub extra_word_chars: &'static [char],
                pub show_ghosts: bool,
                pub allow_overscroll: bool,
                pub one_line_footer: bool,
                pub footer_on_top: bool,
            }

            pub mod hook {
                pub use $crate::hook::*;
            }
            
            pub mod text {
                pub use $crate::text::*;
            }
            
            pub mod cursor {
                pub use $crate::form::{
                    extra_cursor as get_extra, id_of, main_cursor as get_main,
                    set_extra_cursor as set_extra, set_main_cursor as set_main,
                    unset_cursors as unset, unset_extra_cursor as unset_extra,
                    unset_main_cursor as unset_main,
                };
            }

            pub mod opts {
                use super::prelude::*;
                pub use $crate::opts::{self, PrintOpts};
                pub fn set(set: impl FnOnce(&mut super::Opts)) {}
                pub fn fmt_status<T>(set: impl FnMut(&mut Pass) -> T) {}
            }

            pub mod data {
                pub use $crate::data::*;
            }

            pub mod state {
                use super::prelude::*;
                pub fn name_txt(buffer: &Buffer) -> Text { Text::default() }
                pub fn path_txt(buffer: &Buffer) -> Text { Text::default() }
                pub fn mode_name() -> data::DataMap<&'static str, &'static str> { todo!() }
                pub fn mode_txt() -> data::DataMap<&'static str, Text> { todo!() }
                pub fn main_byte(buffer: &Buffer) -> usize { 0 }
                pub fn main_char(buffer: &Buffer) -> usize { 0 }
                pub fn main_line(buffer: &Buffer) -> usize { 0 }
                pub fn main_col(buffer: &Buffer, area: &ui::Area) -> usize { 0 }
                pub fn main_txt(buffer: &Buffer, area: &ui::Area) -> Text { Text::default() }
                pub fn selections(buffer: &Buffer) -> usize { 0 }
                pub fn sels_txt(buffer: &Buffer) -> Text { Text::default() }
                pub fn cur_map_txt() -> data::DataMap<(Vec<KeyEvent>, bool), Text> { todo!() }
                pub fn last_key() -> data::RwData<String> { todo!() }
            }

            pub mod mode {
                pub use $crate::mode::*;
                pub use super::modes::*;
            }
                
            pub mod prelude {
                pub use std::ops::Range;
                pub use $crate::try_or_log_err;
                
                pub use $crate::{
                    Ns, buffer::Buffer, cmd,
                    context::{self, Handle},
                    data::{self, Pass},
                    form::{self, CursorShape, Form},
                    hook::{
                        self, BufferOpened, BufferSaved, BufferUpdated, ColorschemeSet,
                        ConfigLoaded, ConfigUnloaded, FocusChanged, FocusedOn, FocusedOnDuat,
                        FormSet, Hookable, KeySent, ModeSwitched, UnfocusedFrom, UnfocusedFromDuat,
                        WidgetOpened, WindowOpened,
                    },
                    text::{
                        self, Builder, Conceal, Inlay, Spacer, Spawn, Strs, Text, txt, Point, Mask,
                        TextMut
                    },
                    ui::{self, Area, Widget},
                };
                
                pub use super::{
                    cursor::*,
                    mode::{
                        self, KeyCode, KeyEvent, Mode, Prompt, Pager, User, alias, alt, ctrl, event,
                        map, shift,
                    },
                    state::*, widgets::*, PassFileType, FileType, opts, Opts
                };

                #[macro_export]
                macro_rules! setup_duat{ ($setup:ident) => {} }
            }

            pub mod widgets {
                use std::fmt::Alignment;
                
                pub struct LineNumbers {
                    buffer: Handle,
                    text: Text,
                    pub relative: bool,
                    pub align: Alignment,
                    pub main_align: Alignment,
                    pub show_wraps: bool,
                }
                impl LineNumbers {
                    pub fn builder() -> LineNumbersOpts { LineNumbersOpts {
                        relative: false,
                        align: Alignment::Right,
                        main_align: Alignment::Right,
                        show_wraps: false,
                        on_the_right: false
                    }}
                }
                impl Widget for LineNumbers {
                    fn text(&self) -> &Text { &self.text }
                    fn text_mut(&mut self) -> TextMut<'_> { self.text.as_mut() }
                }
                #[derive(Clone, Copy, Debug)]
                pub struct LineNumbersOpts {
                    pub relative: bool,
                    pub align: Alignment,
                    pub main_align: Alignment,
                    pub show_wraps: bool,
                    pub on_the_right: bool,
                }
                impl LineNumbersOpts {
                    pub fn push_on(self, _: &mut Pass, _: &Handle) {}
                }
                
                #[macro_export]
                macro_rules! status{ ($str: literal) => { $duat::widgets::StatusLine } }
                pub struct StatusLine;
                impl StatusLine {
                    pub fn above(self) -> Self { Self }
                    pub fn push_on(self, _: &mut Pass, _: &impl $crate::ui::PushTarget) {}
                }

                pub struct LogBook;
                impl LogBook {
                    pub fn builder() -> LogBookOpts { LogBookOpts::default() }
                    pub fn push_on(self, _: &mut Pass, _: &impl $crate::ui::PushTarget) {}
                }
                #[derive(Default, Clone, Copy, Debug)]
                pub struct LogBookOpts {
                    pub close_on_unfocus: bool,
                    pub hidden: bool,
                    pub side: $crate::ui::Side,
                    pub height: f32,
                    pub width: f32,
                }
                impl LogBookOpts {
                    pub fn push_on(self, _: &mut Pass, _: &impl $crate::ui::PushTarget) {}
                }
                
                use super::prelude::*;
                pub struct VertRule;
                impl VertRule {
                    pub fn builder() -> VertRuleBuilder { VertRuleBuilder }
                }
                pub struct VertRuleBuilder;
                impl VertRuleBuilder {
                    pub fn push_on(self, _: &mut Pass, _: &impl $crate::ui::PushTarget) {}
                    pub fn on_the_right(self) -> Self { self }
                }
            }

            pub mod modes {
                use super::prelude::*;
                #[derive(Clone)]
                pub struct Pager;
                impl $crate::mode::Mode for Pager {
                    type Widget = $crate::buffer::Buffer;
                    fn send_key(
                        &mut self,
                        _: &mut Pass,
                        _: $crate::mode::KeyEvent,
                        _: Handle<Self::Widget>,
                    ) {
                    }
                }
                
                #[derive(Clone)]
                pub struct Prompt;
                impl $crate::mode::Mode for Prompt {
                    type Widget = $crate::buffer::Buffer;
                    fn send_key(
                        &mut self,
                        _: &mut Pass,
                        _: $crate::mode::KeyEvent,
                        _: Handle<Self::Widget>,
                    ) {
                    }
                }

                #[derive(Clone)]
                pub struct RunCommands;
                impl RunCommands {
                    pub fn new() -> Prompt {
                        Prompt
                    }
                    pub fn new_with(initial: &str) -> Prompt {
                        Prompt
                    }
                }
            }

            pub trait FileType {
                fn filetype(&self) -> Option<&'static str> { None }
            }

            impl FileType for prelude::Buffer {}
            impl FileType for String {}
            impl FileType for &'_ str {}
            impl FileType for std::path::PathBuf {}
            impl FileType for &'_ std::path::Path {}

            pub trait PassFileType {
                fn filetype(&self, _: &prelude::Pass) -> Option<&'static str> { None }
            }
            impl PassFileType for prelude::data::RwData<prelude::Buffer> {}
            impl PassFileType for prelude::Handle {}

            
        }
    }
}