duat-utils 0.6.0

Basic components common in Duat, such as widgets and modes
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
use std::{io::Write, marker::PhantomData, sync::LazyLock};

use duat_core::{prelude::*, text::Searcher};

use super::IncSearcher;
use crate::{
    hooks::{SearchPerformed, SearchUpdated},
    widgets::PromptLine,
};

static PROMPT_TAGGER: LazyLock<Tagger> = LazyLock::new(Tagger::new);
static TAGGER: LazyLock<Tagger> = LazyLock::new(Tagger::new);

/// A [`Mode`] for the [`PromptLine`]
///
/// This mode abstracts over what the inner [`PromptMode`] actually
/// does, by letting them focus on just updating the [`Text`] and
/// acting on user input, instead of having to worry about which keys
/// do what, and when to update.
///
/// There are currently three [`PromptMode`]s:
///
/// - [`RunCommands`] is just your regular command runner, it can also
///   detect if your [`Parameter`]s are correct and show that in real
///   time.
/// - [`PipeSelections`] pipes each [`Selection`]'s selection in the
///   current [`File`] to an external application, replacing each
///   selection with the returned value.
/// - [`IncSearch`] has a further inner abstraction, [`IncSearcher`],
///   which lets you abstract over what the incremental search will
///   actually do. I.e. will it search for the next ocurrence, split
///   selections by matches, things of the sort.
///
/// [`Parameter`]: cmd::Parameter
/// [`Selection`]: mode::Selection
#[derive(Clone)]
pub struct Prompt<U: Ui, M: PromptMode<U> = RunCommands>(M, String, PhantomData<U>);

impl<M: PromptMode<U>, U: Ui> Prompt<U, M> {
    /// Returns a new [`Prompt`] from this [`PromptMode`]
    ///
    /// For convenience, you should make it so `new` methods in
    /// [`PromptMode`] implementors return a [`Prompt<Self, U>`],
    /// rather than the [`PromptMode`] itself.
    pub fn new(mode: M) -> Self {
        Self(mode, String::new(), PhantomData)
    }

	/// Returns a new [`Prompt`] with some initial text
    pub fn new_with(mode: M, initial: impl ToString) -> Self {
        Self(mode, initial.to_string(), PhantomData)
    }
}

impl<M: PromptMode<U>, U: Ui> mode::Mode<U> for Prompt<U, M> {
    type Widget = PromptLine<U>;

    fn send_key(&mut self, pa: &mut Pass, key: KeyEvent, handle: Handle<Self::Widget, U>) {
        let mut update = |pa: &mut Pass| {
            let text = std::mem::take(handle.write(pa).text_mut());
            let text = self.0.update(pa, text, handle.area(pa));
            *handle.write(pa).text_mut() = text;
        };

        match key {
            key!(KeyCode::Backspace) => {
                if handle.read(pa).text().is_empty() {
                    handle.write(pa).text_mut().selections_mut().clear();

                    update(pa);

                    if let Some(ret_handle) = self.0.return_handle() {
                        mode::reset_to(ret_handle);
                    } else {
                        mode::reset::<M::ExitWidget, U>();
                    }
                } else {
                    handle.edit_main(pa, |mut e| {
                        e.move_hor(-1);
                        e.set_anchor_if_needed();
                        e.replace("");
                        e.unset_anchor();
                    });
                    update(pa);
                }
            }
            key!(KeyCode::Delete) => {
                handle.edit_main(pa, |mut e| e.replace(""));
                update(pa);
            }

            key!(KeyCode::Char(char)) => {
                handle.edit_main(pa, |mut e| {
                    e.insert(char);
                    e.move_hor(1);
                });
                update(pa);
            }
            key!(KeyCode::Left) => {
                handle.edit_main(pa, |mut e| e.move_hor(-1));
                update(pa);
            }
            key!(KeyCode::Right) => {
                handle.edit_main(pa, |mut e| e.move_hor(1));
                update(pa);
            }

            key!(KeyCode::Esc) => {
                let p = handle.read(pa).text().len();
                handle.edit_main(pa, |mut e| {
                    e.move_to_start();
                    e.set_anchor();
                    e.move_to(p);
                    e.replace("");
                });
                handle.write(pa).text_mut().selections_mut().clear();
                update(pa);

                if let Some(ret_handle) = self.0.return_handle() {
                    mode::reset_to(ret_handle);
                } else {
                    mode::reset::<M::ExitWidget, U>();
                }
            }
            key!(KeyCode::Enter) => {
                handle.write(pa).text_mut().selections_mut().clear();

                update(pa);

                if let Some(ret_handle) = self.0.return_handle() {
                    mode::reset_to(ret_handle);
                } else {
                    mode::reset::<M::ExitWidget, U>();
                }
            }
            _ => {}
        }
    }

    fn on_switch(&mut self, pa: &mut Pass, handle: Handle<Self::Widget, U>) {
        let text = {
            let pl = handle.write(pa);
            *pl.text_mut() = Text::new_with_selections();
            pl.text_mut().replace_range(0..0, &self.1);
            run_once::<M, U>();

            let tag = Ghost(match pl.prompt_of::<M>() {
                Some(text) => txt!("{text}[prompt.colon]:").build(),
                None => txt!("{}[prompt.colon]:", self.0.prompt()).build(),
            });
            pl.text_mut().insert_tag(*PROMPT_TAGGER, 0, tag);

            std::mem::take(pl.text_mut())
        };

        let text = self.0.on_switch(pa, text, handle.area(pa));

        *handle.write(pa).text_mut() = text;
    }

    fn before_exit(&mut self, pa: &mut Pass, handle: Handle<Self::Widget, U>) {
        let text = std::mem::take(handle.write(pa).text_mut());
        self.0.before_exit(pa, text, handle.area(pa));
    }
}

/// A mode to control the [`Prompt`], by acting on its [`Text`] and
/// [`U::Area`]
///
/// Through the [`Pass`], one can act on the entirety of Duat's shared
/// state:
///
/// ```rust
/// use duat_core::prelude::*;
/// use duat_utils::modes::PromptMode;
///
/// #[derive(Default, Clone)]
/// struct RealTimeSwitch {
///     initial: Option<String>,
///     current: Option<String>,
///     name_was_correct: bool,
/// };
///
/// impl<U: Ui> PromptMode<U> for RealTimeSwitch {
///     fn update(&mut self, pa: &mut Pass, text: Text, area: &U::Area) -> Text {
///         let name = text.to_string();
///
///         self.name_was_correct = if name != *self.current.as_ref().unwrap() {
///             if cmd::buffer(pa, &name).is_ok() {
///                 self.current = Some(name);
///                 true
///             } else {
///                 false
///             }
///         } else {
///             true
///         };
///
///         text
///     }
///
///     fn on_switch(&mut self, pa: &mut Pass, text: Text, area: &U::Area) -> Text {
///         self.initial = Some(context::fixed_file::<U>(pa).unwrap().read(pa).name());
///         self.current = self.initial.clone();
///
///         text
///     }
///
///     fn before_exit(&mut self, pa: &mut Pass, text: Text, area: &U::Area) {
///         if !self.name_was_correct {
///             cmd::buffer(pa, self.initial.take().unwrap());
///         }
///     }
///
///     fn prompt(&self) -> Text {
///         txt!("[prompt]switch to").build()
///     }
/// }
/// ```
///
/// The [`PromptMode`] above will switch to the file with the same
/// name as the one in the [`PromptLine`], returning to the initial
/// file if the match failed.
///
/// [`U::Area`]: Ui::Area
#[allow(unused_variables)]
pub trait PromptMode<U: Ui>: Clone + Send + 'static {
    /// What [`Widget`] to exit to, upon pressing enter, esc, or
    /// backspace in an empty [`PromptLine`]
    type ExitWidget: Widget<U> = File<U>;

    /// Updates the [`PromptLine`] and [`Text`] of the [`Prompt`]
    ///
    /// This function is triggered every time the user presses a key
    /// in the [`Prompt`] mode.
    fn update(&mut self, pa: &mut Pass, text: Text, area: &U::Area) -> Text;

    /// What to do when switchin onto this [`PromptMode`]
    ///
    /// The initial [`Text`] is always empty, except for the [prompt]
    /// [`Ghost`] at the beginning of the line.
    ///
    /// [prompt]: PromptMode::prompt
    fn on_switch(&mut self, pa: &mut Pass, text: Text, area: &U::Area) -> Text {
        text
    }

    /// What to do before exiting the [`PromptMode`]
    ///
    /// This usually involves some sor of "commitment" to the result,
    /// e.g., [`RunCommands`] executes the call, [`IncSearch`]
    /// finishes the search, etc.
    fn before_exit(&mut self, pa: &mut Pass, text: Text, area: &U::Area) {}

    /// Things to do when this [`PromptMode`] is first instantiated
    fn once() {}

    /// What text should be at the beginning of the [`PromptLine`], as
    /// a [`Ghost`]
    fn prompt(&self) -> Text;

    /// An optional returning [`Handle`] for the [`ExitWidget`]
    ///
    /// [`ExitWidget`]: PromptMode::ExitWidget
    fn return_handle(&self) -> Option<Handle<Self::ExitWidget, U>> {
        None
    }
}

/// Runs Duat commands, with syntax highlighting for correct
/// [`Parameter`]s
///
/// [`Parameter`]: duat_core::cmd::Parameter
#[derive(Default, Clone)]
pub struct RunCommands;

impl RunCommands {
    /// Crates a new [`RunCommands`]
    pub fn new<U: Ui>() -> Prompt<U, Self> {
        Prompt::new(Self)
    }

    /// Opens a [`RunCommands`] with some initial text
    pub fn new_with<U: Ui>(initial: impl ToString) -> Prompt<U, Self> {
        Prompt::new_with(Self, initial)
    }
}

impl<U: Ui> PromptMode<U> for RunCommands {
    fn update(&mut self, pa: &mut Pass, mut text: Text, _: &<U as Ui>::Area) -> Text {
        text.remove_tags(*TAGGER, ..);

        let command = text.to_string();
        let caller = command.split_whitespace().next();
        if let Some(caller) = caller {
            if let Some((ok_ranges, err_range)) = cmd::check_args(pa, &command) {
                let id = form::id_of!("caller.info");
                text.insert_tag(*TAGGER, 0..caller.len(), id.to_tag(0));

                let default_id = form::id_of!("parameter.info");
                for (range, id) in ok_ranges {
                    text.insert_tag(*TAGGER, range, id.unwrap_or(default_id).to_tag(0));
                }
                if let Some((range, _)) = err_range {
                    let id = form::id_of!("parameter.error");
                    text.insert_tag(*TAGGER, range, id.to_tag(0));
                }
            } else {
                let id = form::id_of!("caller.error");
                text.insert_tag(*TAGGER, 0..caller.len(), id.to_tag(0));
            }
        }

        text
    }

    fn before_exit(&mut self, _: &mut Pass, text: Text, _: &<U as Ui>::Area) {
        let call = text.to_string();
        if !call.is_empty() {
            cmd::queue_notify(call);
        }
    }

    fn once() {
        form::set_weak("caller.info", "accent.info");
        form::set_weak("caller.error", "accent.error");
        form::set_weak("parameter.info", "default.info");
        form::set_weak("parameter.error", "default.error");
    }

    fn prompt(&self) -> Text {
        Text::default()
    }
}

/// The [`PromptMode`] that makes use of [`IncSearcher`]s
///
/// In order to make use of incremental search, you'd do something
/// like this:
///
/// ```rust
/// use duat_core::prelude::*;
/// use duat_utils::modes::{IncSearch, Regular, SearchFwd};
///
/// fn setup_generic_over_ui<U: Ui>() {
///     mode::map::<Regular, U>("<C-s>", IncSearch::new(SearchFwd));
/// }
/// ```
///
/// This function returns a [`Prompt<IncSearch<SearchFwd, U>, U>`],
#[derive(Clone)]
pub struct IncSearch<I: IncSearcher<U>, U: Ui> {
    inc: I,
    orig: Option<(mode::Selections, <U::Area as Area>::PrintInfo)>,
    ghost: PhantomData<U>,
    prev: String,
}

impl<I: IncSearcher<U>, U: Ui> IncSearch<I, U> {
    /// Returns a [`Prompt`] with [`IncSearch<I, U>`] as its
    /// [`PromptMode`]
    pub fn new(inc: I) -> Prompt<U, Self> {
        Prompt::new(Self {
            inc,
            orig: None,
            ghost: PhantomData,
            prev: String::new(),
        })
    }
}

impl<I: IncSearcher<U>, U: Ui> PromptMode<U> for IncSearch<I, U> {
    fn update(&mut self, pa: &mut Pass, mut text: Text, _: &<U as Ui>::Area) -> Text {
        let (orig_selections, orig_print_info) = self.orig.as_ref().unwrap();
        text.remove_tags(*TAGGER, ..);

        let handle = context::fixed_file::<U>(pa).unwrap();

        if text == self.prev {
            return text;
        } else {
            let prev = std::mem::replace(&mut self.prev, text.to_string());
            hook::queue(SearchUpdated((prev, self.prev.clone())));
        }

        match Searcher::new(text.to_string()) {
            Ok(searcher) => {
                let (file, area) = handle.write_with_area(pa);
                area.set_print_info(orig_print_info.clone());
                *file.selections_mut() = orig_selections.clone();

                let ast = regex_syntax::ast::parse::Parser::new()
                    .parse(&text.to_string())
                    .unwrap();

                crate::tag_from_ast(*TAGGER, &mut text, &ast);

                self.inc.search(pa, handle.attach_searcher(searcher));
            }
            Err(err) => {
                let regex_syntax::Error::Parse(err) = *err else {
                    unreachable!("As far as I can tell, regex_syntax has goofed up");
                };

                let span = err.span();
                let id = form::id_of!("regex.error");

                text.insert_tag(*TAGGER, span.start.offset..span.end.offset, id.to_tag(0));
            }
        }

        text
    }

    fn on_switch(&mut self, pa: &mut Pass, text: Text, _: &<U as Ui>::Area) -> Text {
        let handle = context::fixed_file::<U>(pa).unwrap();

        self.orig = Some((
            handle.read(pa).selections().clone(),
            handle.area(pa).print_info(),
        ));

        text
    }

    fn before_exit(&mut self, _: &mut Pass, text: Text, _: &<U as Ui>::Area) {
        if !text.is_empty() {
            if let Err(err) = Searcher::new(text.to_string()) {
                let regex_syntax::Error::Parse(err) = *err else {
                    unreachable!("As far as I can tell, regex_syntax has goofed up");
                };

                let range = err.span().start.offset..err.span().end.offset;
                let err = txt!(
                    "[a]{:?}, \"{}\"[prompt.colon]:[] {}",
                    range,
                    text.strs(range).unwrap(),
                    err.kind()
                );

                context::error!(target: self.inc.prompt().to_string(), "{err}")
            } else {
                hook::queue(SearchPerformed(text.to_string()));
            }
        }
    }

    fn once() {
        form::set_weak("regex.error", "accent.error");
        form::set_weak("regex.operator", "operator");
        form::set_weak("regex.class", "constant");
        form::set_weak("regex.bracket", "punctuation.bracket");
    }

    fn prompt(&self) -> Text {
        txt!("{}", self.inc.prompt()).build()
    }
}

/// Pipes the selections of a [`File`] through an external command
///
/// This can be useful if you, for example, don't have access to a
/// formatter, but want to format text, so you pass it to
/// [`PipeSelections`] with `fold` as the command, or things of the
/// sort.
#[derive(Clone, Copy)]
pub struct PipeSelections<U>(PhantomData<U>);

impl<U: Ui> PipeSelections<U> {
    /// Returns a [`Prompt`] with [`PipeSelections`] as its
    /// [`PromptMode`]
    pub fn new() -> Prompt<U, Self> {
        Prompt::new(Self(PhantomData))
    }
}

impl<U: Ui> PromptMode<U> for PipeSelections<U> {
    fn update(&mut self, _: &mut Pass, mut text: Text, _: &<U as Ui>::Area) -> Text {
        fn is_in_path(program: &str) -> bool {
            if let Ok(path) = std::env::var("PATH") {
                for p in path.split(":") {
                    let p_str = format!("{p}/{program}");
                    if let Ok(true) = std::fs::exists(p_str) {
                        return true;
                    }
                }
            }
            false
        }

        text.remove_tags(*TAGGER, ..);

        let command = text.to_string();
        let Some(caller) = command.split_whitespace().next() else {
            return text;
        };

        let args = cmd::args_iter(&command);

        let (caller_id, args_id) = if is_in_path(caller) {
            (form::id_of!("caller.info"), form::id_of!("parameter.indo"))
        } else {
            (
                form::id_of!("caller.error"),
                form::id_of!("parameter.error"),
            )
        };

        let c_s = command.len() - command.trim_start().len();
        text.insert_tag(*TAGGER, c_s..c_s + caller.len(), caller_id.to_tag(0));

        for (_, range) in args {
            text.insert_tag(*TAGGER, range, args_id.to_tag(0));
        }

        text
    }

    fn before_exit(&mut self, pa: &mut Pass, text: Text, _: &<U as Ui>::Area) {
        use std::process::{Command, Stdio};

        let command = text.to_string();
        let Some(caller) = command.split_whitespace().next() else {
            return;
        };

        let handle = context::fixed_file::<U>(pa).unwrap();
        handle.edit_all(pa, |mut c| {
            let Ok(mut child) = Command::new(caller)
                .args(cmd::args_iter(&command).map(|(a, _)| a))
                .stdin(Stdio::piped())
                .stdout(Stdio::piped())
                .spawn()
            else {
                return;
            };

            let input: String = c.selection().collect();
            if let Some(mut stdin) = child.stdin.take() {
                std::thread::spawn(move || {
                    stdin.write_all(input.as_bytes()).unwrap();
                });
            }
            if let Ok(out) = child.wait_with_output() {
                let out = String::from_utf8_lossy(&out.stdout);
                c.set_anchor_if_needed();
                c.replace(out);
            }
        });
    }

    fn prompt(&self) -> Text {
        txt!("[prompt]pipe").build()
    }
}

/// Runs the [`once`] function of widgets.
///
/// [`once`]: Widget::once
fn run_once<M: PromptMode<U>, U: Ui>() {
    use std::{any::TypeId, sync::Mutex};

    static LIST: LazyLock<Mutex<Vec<TypeId>>> = LazyLock::new(|| Mutex::new(Vec::new()));

    let mut list = LIST.lock().unwrap();
    if !list.contains(&TypeId::of::<M>()) {
        M::once();
        list.push(TypeId::of::<M>());
    }
}