thag_rs 0.1.8

A versatile cross-platform script runner and REPL for Rust snippets, expressions and programs. Accepts a script file or dynamic options.
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
#![allow(clippy::uninlined_format_args)]
use crate::builder::process_expr;
use crate::code_utils::{self, clean_up, display_dir_contents, extract_ast_expr, extract_manifest};
use crate::tui_editor::{
    script_key_handler, tui_edit, EditData, Entry, History, KeyAction, KeyDisplay, ManagedTerminal,
};
use crate::{
    cprtln, cvprtln, get_verbosity, key, lazy_static_var, regex, vlog, BuildState, Cli,
    CrosstermEventReader, EventReader, KeyCombination, KeyDisplayLine, Lvl, ProcFlags, ThagError,
    ThagResult, V,
};
use clap::{CommandFactory, Parser};
use crossterm::event::{KeyEvent, KeyEventKind};
use edit::edit_file;
use firestorm::{profile_fn, profile_method};
use nu_ansi_term::{Color, Style as NuStyle};
use ratatui::style::{Style as RataStyle, Stylize};
use reedline::{
    default_emacs_keybindings, ColumnarMenu, DefaultCompleter, DefaultHinter, DefaultValidator,
    EditCommand, Emacs, ExampleHighlighter, FileBackedHistory, HistoryItem, KeyCode, KeyModifiers,
    Keybindings, MenuBuilder, Prompt, PromptEditMode, PromptHistorySearch,
    PromptHistorySearchStatus, Reedline, ReedlineEvent, ReedlineMenu, Signal,
};
use regex::Regex;
use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt::Debug;
use std::fs::{self, read_to_string, OpenOptions};
use std::io::{BufWriter, Write};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::time::Instant;
use strum::{EnumIter, EnumString, IntoEnumIterator, IntoStaticStr};
use tui_textarea::{Input, TextArea};

pub const HISTORY_FILE: &str = "thag_repl_hist.txt";
pub static DEFAULT_MULTILINE_INDICATOR: &str = "";

const EVENT_DESCS: &[[&str; 2]; 33] = &[
    [
        "HistoryHintComplete",
        "Complete history hint (default in full)",
    ],
    [
        "HistoryHintWordComplete",
        "Complete a single token/word of the history hint",
    ],
    ["CtrlD", "Handle EndOfLine event"],
    ["CtrlC", "Handle SIGTERM key input"],
    [
        "ClearScreen",
        "Clears the screen and sets prompt to first line",
    ],
    [
        "ClearScrollback",
        "Clears the screen and the scrollback buffer, sets the prompt back to the first line",
    ],
    ["Enter", "Handle enter event"],
    ["Submit", "Handle unconditional submit event"],
    [
        "SubmitOrNewline",
        "Submit at the end of the *complete* text, otherwise newline",
    ],
    ["Esc", "Esc event"],
    ["Mouse", "Mouse"],
    ["Resize(u16, u16)", "trigger terminal resize"],
    [
        "Edit(Vec<EditCommand>)",
        "Run §these commands in the editor",
    ],
    ["Repaint", "Trigger full repaint"],
    [
        "PreviousHistory",
        "Navigate to the previous historic buffer",
    ],
    [
        "Up",
        "Move up to the previous line, if multiline, or up into the historic buffers",
    ],
    [
        "Down",
        "Move down to the next line, if multiline, or down through the historic buffers",
    ],
    [
        "Right",
        "Move right to the next column, completion entry, or complete hint",
    ],
    ["Left", "Move left to the next column, or completion entry"],
    ["NextHistory", "Navigate to the next historic buffer"],
    ["SearchHistory", "Search the history for a string"],
    ["Multiple(Vec<ReedlineEvent>)", "Multiple chained (Vi)"],
    ["UntilFound(Vec<ReedlineEvent>)", "Test"],
    [
        "Menu(String)",
        "Trigger a menu event. It activates a menu with the event name",
    ],
    ["MenuNext", "Next element in the menu"],
    ["MenuPrevious", "Previous element in the menu"],
    ["MenuUp", "Moves up in the menu"],
    ["MenuDown", "Moves down in the menu"],
    ["MenuLeft", "Moves left in the menu"],
    ["MenuRight", "Moves right in the menu"],
    ["MenuPageNext", "Move to the next history page"],
    ["MenuPagePrevious", "Move to the previous history page"],
    ["OpenEditor", "Open text editor"],
];

const CMD_DESCS: &[[&str; 2]; 59] = &[
    ["MoveToStart", "Move to the start of the buffer"],
    ["MoveToLineStart", "Move to the start of the current line"],
    ["MoveToEnd", "Move to the end of the buffer"],
    ["MoveToLineEnd", "Move to the end of the current line"],
    ["MoveLeft", "Move one character to the left"],
    ["MoveRight", "Move one character to the right"],
    ["MoveWordLeft", "Move one word to the left"],
    ["MoveBigWordLeft", "Move one WORD to the left"],
    ["MoveWordRight", "Move one word to the right"],
    ["MoveWordRightStart", "Move one word to the right, stop at start of word"],
    ["MoveBigWordRightStart", "Move one WORD to the right, stop at start of WORD"],
    ["MoveWordRightEnd", "Move one word to the right, stop at end of word"],
    ["MoveBigWordRightEnd", "Move one WORD to the right, stop at end of WORD"],
    ["MoveToPosition", "Move to position"],
    ["InsertChar", "Insert a character at the current insertion point"],
    ["InsertString", "Insert a string at the current insertion point"],
    ["InsertNewline", "Insert the system specific new line character"],
    ["ReplaceChars", "Replace characters with string"],
    ["Backspace", "Backspace delete from the current insertion point"],
    ["Delete", "Delete in-place from the current insertion point"],
    ["CutChar", "Cut the grapheme right from the current insertion point"],
    ["BackspaceWord", "Backspace delete a word from the current insertion point"],
    ["DeleteWord", "Delete in-place a word from the current insertion point"],
    ["Clear", "Clear the current buffer"],
    ["ClearToLineEnd", "Clear to the end of the current line"],
    ["Complete", "Insert completion: entire completion if there is only one possibility, or else up to shared prefix."],
    ["CutCurrentLine", "Cut the current line"],
    ["CutFromStart", "Cut from the start of the buffer to the insertion point"],
    ["CutFromLineStart", "Cut from the start of the current line to the insertion point"],
    ["CutToEnd", "Cut from the insertion point to the end of the buffer"],
    ["CutToLineEnd", "Cut from the insertion point to the end of the current line"],
    ["CutWordLeft", "Cut the word left of the insertion point"],
    ["CutBigWordLeft", "Cut the WORD left of the insertion point"],
    ["CutWordRight", "Cut the word right of the insertion point"],
    ["CutBigWordRight", "Cut the WORD right of the insertion point"],
    ["CutWordRightToNext", "Cut the word right of the insertion point and any following space"],
    ["CutBigWordRightToNext", "Cut the WORD right of the insertion point and any following space"],
    ["PasteCutBufferBefore", "Paste the cut buffer in front of the insertion point (Emacs, vi P)"],
    ["PasteCutBufferAfter", "Paste the cut buffer in front of the insertion point (vi p)"],
    ["UppercaseWord", "Upper case the current word"],
    ["LowercaseWord", "Lower case the current word"],
    ["CapitalizeChar", "Capitalize the current character"],
    ["SwitchcaseChar", "Switch the case of the current character"],
    ["SwapWords", "Swap the current word with the word to the right"],
    ["SwapGraphemes", "Swap the current grapheme/character with the one to the right"],
    ["Undo", "Undo the previous edit command"],
    ["Redo", "Redo an edit command from the undo history"],
    ["CutRightUntil", "CutUntil right until char"],
    ["CutRightBefore", "CutUntil right before char"],
    ["MoveRightUntil", "MoveUntil right until char"],
    ["MoveRightBefore", "MoveUntil right before char"],
    ["CutLeftUntil", "CutUntil left until char"],
    ["CutLeftBefore", "CutUntil left before char"],
    ["MoveLeftUntil", "MoveUntil left until char"],
    ["MoveLeftBefore", "MoveUntil left before char"],
    ["SelectAll", "Select whole input buffer"],
    ["CutSelection", "Cut selection to local buffer"],
    ["CopySelection", "Copy selection to local buffer"],
    ["Paste", "Paste content from local buffer at the current cursor position"],
];

/// REPL mode lets you type or paste a Rust expression to be evaluated.
///
/// Start by choosing the eval option and entering your expression. Expressions between matching braces,
/// brackets, parens or quotes may span multiple lines.
/// If valid, the expression will be converted into a Rust program, and built and run using Cargo.
/// Dependencies will be inferred from imports if possible using a Cargo search, but the overhead
/// of doing so can be avoided by placing them in Cargo.toml format at the top of the expression in a
/// comment block of the form
/// ``` rust
/// /*[toml]
/// [dependencies]
/// ...
/// */
/// ```
/// From here they will be extracted to a dedicated Cargo.toml file.
/// In this case the whole expression must be enclosed in curly braces to include the TOML in the expression.
/// At any stage before exiting the REPL, or at least as long as your TMPDIR is not cleared, you can
/// go back and edit your expression or its generated Cargo.toml file and copy or save them from the
/// editor or directly from their temporary disk locations.
/// The tab key will show command selections and complete partial matching selections."
#[derive(Debug, Parser, EnumIter, EnumString, IntoStaticStr)]
#[command(
    name = "",
    disable_help_flag = true,
    disable_help_subcommand = true,
    verbatim_doc_comment
)] // Disable automatic help subcommand and flag
#[strum(serialize_all = "snake_case")]
#[allow(clippy::module_name_repetitions)]
pub enum ReplCommand {
    /// Show the REPL banner
    Banner,
    /// Promote the Rust expression to the TUI (Terminal user interface) repl, which can handle any script. This is a one-way process but the original expression will be saved in history.
    Tui,
    /// Edit the Rust expression. Edit+run can also be used as an alternative to eval for longer snippets and programs.
    Edit,
    /// Edit the generated Cargo.toml
    Toml,
    /// Attempt to build and run the Rust expression
    Run,
    /// Delete all temporary files for this eval (see list)
    Delete,
    /// List temporary files for this eval
    List,
    /// Edit history
    History,
    /// Show help information
    Help,
    /// Show key bindings
    Keys,
    /// Exit the REPL
    Quit,
}

impl ReplCommand {
    fn print_help() {
        profile_method!(print_help);
        let mut command = Self::command();
        // let mut buf = Vec::new();
        // command.write_help(&mut buf).unwrap();
        // let help_message = String::from_utf8(buf).unwrap();
        println!("{}", command.render_long_help());
    }
}

/// A struct to implement the Prompt trait.
#[allow(clippy::module_name_repetitions)]
pub struct ReplPrompt(pub &'static str);
impl Prompt for ReplPrompt {
    fn render_prompt_left(&self) -> Cow<str> {
        profile_method!(render_prompt_left);
        Cow::Owned(self.0.to_string())
    }

    fn render_prompt_right(&self) -> Cow<str> {
        profile_method!(render_prompt_right);
        Cow::Owned(String::new())
    }

    fn render_prompt_indicator(&self, _edit_mode: PromptEditMode) -> Cow<str> {
        profile_method!(render_prompt_indicator);
        Cow::Owned("> ".to_string())
    }

    fn render_prompt_multiline_indicator(&self) -> Cow<str> {
        profile_method!(render_prompt_multiline_indicator);
        Cow::Borrowed(DEFAULT_MULTILINE_INDICATOR)
    }

    fn render_prompt_history_search_indicator(
        &self,
        history_search: PromptHistorySearch,
    ) -> Cow<str> {
        profile_method!(render_prompt_history_search_indicator);
        let prefix = match history_search.status {
            PromptHistorySearchStatus::Passing => "",
            PromptHistorySearchStatus::Failing => "failing ",
        };

        Cow::Owned(format!(
            "({}reverse-search: {}) ",
            prefix, history_search.term
        ))
    }
}

fn get_heading_style() -> &'static NuStyle {
    profile_fn!(get_heading_style);
    lazy_static_var!(NuStyle, NuStyle::from(&Lvl::HEAD))
}

fn get_subhead_style() -> &'static NuStyle {
    profile_fn!(get_subhead_style);
    lazy_static_var!(NuStyle, NuStyle::from(&Lvl::SUBH))
}

pub fn add_menu_keybindings(keybindings: &mut Keybindings) {
    profile_fn!(add_menu_keybindings);
    keybindings.add_binding(
        KeyModifiers::NONE,
        KeyCode::Tab,
        ReedlineEvent::UntilFound(vec![
            ReedlineEvent::Menu("completion_menu".to_string()),
            ReedlineEvent::MenuNext,
        ]),
    );
    keybindings.add_binding(
        KeyModifiers::ALT,
        KeyCode::Enter,
        ReedlineEvent::Edit(vec![EditCommand::InsertNewline]),
    );
    keybindings.add_binding(
        KeyModifiers::NONE,
        KeyCode::F(7),
        ReedlineEvent::PreviousHistory,
    );
    keybindings.add_binding(
        KeyModifiers::NONE,
        KeyCode::F(8),
        ReedlineEvent::NextHistory,
    );
}

/// Run the REPL.
/// # Errors
/// Will return `Err` if there is any error in running the REPL.
/// # Panics
/// Will panic if there is a problem configuring the `reedline` history file.
#[allow(clippy::module_name_repetitions)]
#[allow(clippy::too_many_lines)]
pub fn run_repl(
    args: &Cli,
    proc_flags: &ProcFlags,
    build_state: &mut BuildState,
    start: Instant,
) -> ThagResult<()> {
    #[allow(unused_variables)]
    let history_path = build_state.cargo_home.join(HISTORY_FILE);
    let hist_staging_path: PathBuf = build_state.cargo_home.join("hist_staging.txt");
    let hist_backup_path: PathBuf = build_state.cargo_home.join("hist_backup.txt");
    let history = Box::new(FileBackedHistory::with_file(25, history_path.clone())?);

    let cmd_vec = ReplCommand::iter()
        .map(<ReplCommand as Into<&'static str>>::into)
        .map(String::from)
        .collect::<Vec<String>>();

    let completer = Box::new(DefaultCompleter::new_with_wordlen(cmd_vec.clone(), 2));

    // Use the interactive menu to select options from the completer
    let columnar_menu = ColumnarMenu::default()
        .with_name("completion_menu")
        .with_columns(4)
        .with_column_width(None)
        .with_column_padding(2);

    let completion_menu = Box::new(columnar_menu);

    let mut keybindings = default_emacs_keybindings();
    add_menu_keybindings(&mut keybindings);
    // println!("{:#?}", keybindings.get_keybindings());

    let edit_mode = Box::new(Emacs::new(keybindings.clone()));
    let mut highlighter = Box::new(ExampleHighlighter::new(cmd_vec.clone()));
    highlighter.change_colors(
        Color::from(&Lvl::HEAD),
        Color::from(&Lvl::EMPH),
        Color::from(&Lvl::NORM),
    );
    let mut line_editor = Reedline::create()
        .with_validator(Box::new(DefaultValidator))
        .with_hinter(Box::new(
            DefaultHinter::default().with_style(NuStyle::from(&Lvl::Ghost).italic()),
        ))
        .with_history(history)
        .with_history_exclusion_prefix(Some("q".into()))
        .with_highlighter(highlighter)
        .with_completer(completer)
        .with_menu(ReedlineMenu::EngineCompleter(completion_menu))
        .with_edit_mode(edit_mode);

    let bindings = keybindings.get_keybindings();
    let reedline_events = bindings.values().cloned().collect::<Vec<ReedlineEvent>>();
    let max_cmd_len = get_max_cmd_len(&reedline_events);

    let prompt = ReplPrompt("repl");
    let cmd_list = &cmd_vec.join(", ");
    disp_repl_banner(cmd_list);

    // Collect and format key bindings while user is taking in the display banner
    // NB: Can't extract this to a method either, because reedline does not expose KeyCombination.
    let named_reedline_events = bindings
        .iter()
        .map(|(key_combination, reedline_event)| {
            let key_modifiers = key_combination.modifier;
            let key_code = key_combination.key_code;
            let modifier = format_key_modifier(key_modifiers);
            let key = format_key_code(key_code);
            let key_desc = format!("{modifier}{key}");
            (key_desc, reedline_event)
        })
        // .cloned()
        .collect::<Vec<(String, &ReedlineEvent)>>();
    let formatted_bindings = format_bindings(&named_reedline_events, max_cmd_len);

    // Determine the length of the longest key description for padding
    let max_key_len = lazy_static_var!(usize, get_max_key_len(formatted_bindings), deref);
    // eprintln!("max_key_len={max_key_len}");

    loop {
        let sig = line_editor.read_line(&prompt)?;
        let input: &str = match sig {
            Signal::Success(ref buffer) => buffer,
            Signal::CtrlD | Signal::CtrlC => {
                break;
            }
        };

        // Process user input (line)

        let rs_source = input.trim();
        if rs_source.is_empty() {
            continue;
        }

        let (first_word, _rest) = parse_line(rs_source);
        let maybe_cmd = {
            let mut matches = 0;
            let mut cmd = String::new();
            for key in &cmd_vec {
                if key.starts_with(&first_word) {
                    matches += 1;
                    // Selects last match
                    if matches == 1 {
                        cmd = key.to_string();
                    }
                    // eprintln!("key={key}, split[0]={}", split[0]);
                }
            }
            if matches == 1 {
                Some(cmd)
            } else {
                // println!("No single matching key found");
                None
            }
        };

        if let Some(cmd) = maybe_cmd {
            if let Ok(repl_command) = ReplCommand::from_str(&cmd) {
                match repl_command {
                    ReplCommand::Banner => disp_repl_banner(cmd_list),
                    ReplCommand::Help => {
                        ReplCommand::print_help();
                    }
                    ReplCommand::Quit => {
                        break;
                    }
                    ReplCommand::Tui => {
                        let source_path = &build_state.source_path;
                        let mut save_path: PathBuf =
                            build_state.cargo_home.join("repl_tui_save.rs");
                        // let backup_path: PathBuf =
                        //     &build_state.cargo_home.join("repl_tui_backup.rs");

                        let rs_source = read_to_string(source_path)?;
                        tui(
                            rs_source.as_str(),
                            &mut save_path,
                            build_state,
                            args,
                            proc_flags,
                        )?;
                    }
                    ReplCommand::Edit => {
                        edit(&build_state.source_path)?;
                    }
                    ReplCommand::Toml => {
                        toml(build_state)?;
                    }
                    ReplCommand::Run => {
                        let rs_source = code_utils::read_file_contents(&build_state.source_path)?;
                        process_source(&rs_source, build_state, args, proc_flags, start)?;
                    }
                    ReplCommand::Delete => {
                        delete(build_state)?;
                    }
                    ReplCommand::List => {
                        list(build_state)?;
                    }
                    ReplCommand::History => {
                        review_history(
                            &mut line_editor,
                            &history_path,
                            &hist_backup_path,
                            &hist_staging_path,
                        )?;
                    }
                    ReplCommand::Keys => {
                        show_key_bindings(formatted_bindings, max_key_len);
                    }
                }
                continue;
            }
        }

        process_source(rs_source, build_state, args, proc_flags, start)?;
    }
    Ok(())
}

/// Process a source string through to completion according to the arguments passed in.
///
/// # Errors
///
/// This function will bubble up any error encountered in processing.
pub fn process_source(
    rs_source: &str,
    build_state: &mut BuildState,
    args: &Cli,
    proc_flags: &ProcFlags,
    start: Instant,
) -> ThagResult<()> {
    profile_fn!(process_source);
    let rs_manifest = extract_manifest(rs_source, Instant::now())?;
    build_state.rs_manifest = Some(rs_manifest);
    let maybe_ast = extract_ast_expr(rs_source);
    if let Ok(expr_ast) = maybe_ast {
        build_state.ast = Some(crate::Ast::Expr(expr_ast));
        process_expr(build_state, rs_source, args, proc_flags, &start)?;
    } else {
        cprtln!(&(&Lvl::ERR).into(), "Error parsing code: {maybe_ast:#?}");
    };
    Ok(())
}

fn tui(
    initial_content: &str,
    save_path: &mut PathBuf,
    build_state: &mut BuildState,
    args: &Cli,
    proc_flags: &ProcFlags,
) -> ThagResult<()> {
    let cargo_home = std::env::var("CARGO_HOME").unwrap_or_else(|_| ".".into());
    let history_path = PathBuf::from(cargo_home).join("rs_stdin_history.json");
    let mut history = History::load_from_file(&history_path);
    let initial_content = if initial_content.trim().is_empty() {
        history.get_last().map_or_else(String::new, Entry::contents)
    } else {
        history.add_entry(initial_content);
        history.save_to_file(&history_path)?;
        initial_content.to_string()
    };

    let event_reader = CrosstermEventReader;
    let mut edit_data = EditData {
        return_text: true,
        initial_content: &initial_content,
        save_path: Some(save_path),
        history_path: Some(&history_path),
        history: Some(history),
    };
    let add_keys = [
        KeyDisplayLine::new(371, "Ctrl+Alt+s", "Save a copy"),
        KeyDisplayLine::new(372, "F3", "Discard saved and unsaved changes, and exit"),
        // KeyDisplayLine::new(373, "F4", "Clear text buffer (Ctrl+y or Ctrl+u to restore)"),
    ];

    let display = KeyDisplay {
        title: "Edit TUI script.  ^d: submit  ^q: quit  ^s: save  F3: abandon  ^l: keys  ^t: toggle highlighting",
        title_style: RataStyle::from(&Lvl::SUBH).bold(),
        remove_keys: &[""; 0],
        add_keys: &add_keys,
    };
    let (key_action, maybe_text) = tui_edit(
        &event_reader,
        &mut edit_data,
        &display,
        |key_event,
         maybe_term,
         /*maybe_save_file,*/ textarea,
         edit_data,
         popup,
         saved,
         status_message| {
            script_key_handler(
                key_event,
                maybe_term, // maybe_save_file,
                textarea,
                edit_data,
                popup,
                saved,
                status_message,
            )
        },
    )?;
    let _ = match key_action {
        // KeyAction::Quit(_saved) => false,
        KeyAction::Save
        | KeyAction::ShowHelp
        | KeyAction::ToggleHighlight
        | KeyAction::TogglePopup => {
            return Err(
                format!("Logic error: {key_action:?} should not return from tui_edit").into(),
            )
        }
        // KeyAction::SaveAndExit => false,
        KeyAction::Submit => {
            return maybe_text.map_or(Err(ThagError::Cancelled), |v| {
                let rs_source = v.join("\n");
                process_source(&rs_source, build_state, args, proc_flags, Instant::now())
            });
        }
        _ => false,
    };
    Ok(())
}

fn review_history(
    line_editor: &mut Reedline,
    history_path: &PathBuf,
    backup_path: &PathBuf,
    staging_path: &PathBuf,
) -> ThagResult<()> {
    let event_reader = CrosstermEventReader;
    line_editor.sync_history()?;
    fs::copy(history_path, backup_path)?;
    let history_string = read_to_string(history_path)?;
    let confirm = edit_history(&history_string, staging_path, &event_reader)?;
    if confirm {
        let history_mut = line_editor.history_mut();
        let saved_history = fs::read_to_string(staging_path)?;
        eprintln!("staging_path={staging_path:?}");
        eprintln!("saved_history={saved_history}");
        history_mut.clear()?;
        for line in saved_history.lines() {
            let entry = decode(line);
            // eprintln!("saving entry={entry}");
            let _ = history_mut.save(HistoryItem::from_command_line(entry))?;
        }
        history_mut.sync()?;
    }
    Ok(())
}

/// Convert the `reedline` file-backed history newline sequence <\n> into the '\n' (0xa) character for which it stands.
#[must_use]
#[allow(clippy::missing_panics_doc)]
pub fn decode(input: &str) -> String {
    profile_fn!(decode);
    let re = regex!(r"(<\\n>)");
    let lf = std::str::from_utf8(&[10_u8]).unwrap();
    re.replace_all(input, lf).to_string()
}

/// Edit the history.
///
/// # Errors
///
/// This function will bubble up any i/o, `ratatui` or `crossterm` errors encountered.
pub fn edit_history<R: EventReader + Debug>(
    initial_content: &str,
    staging_path: &Path,
    event_reader: &R,
) -> ThagResult<bool> {
    let mut staging_path_buf = staging_path.to_path_buf();
    let mut edit_data = EditData {
        return_text: false,
        initial_content,
        save_path: Some(&mut staging_path_buf),
        history_path: None,
        history: None::<History>,
    };
    let binding = [
        KeyDisplayLine::new(372, "F3", "Discard saved and unsaved changes, and exit"),
        // KeyDisplayLine::new(373, "F4", "Clear text buffer (Ctrl+y or Ctrl+u to restore)"),
    ];
    let display = KeyDisplay {
        title: "Enter / paste / edit REPL history.  ^d: save & exit  ^q: quit  ^s: save  F3: abandon  ^l: keys  ^t: toggle highlighting",
        title_style: RataStyle::from(&Lvl::HEAD).bold(),
        remove_keys: &["F7", "F8"],
        add_keys: &binding,
    };
    let (key_action, _maybe_text) = tui_edit(
        event_reader,
        &mut edit_data,
        &display,
        |key_event, maybe_term, textarea, edit_data, popup, saved, status_message| {
            history_key_handler(
                key_event,
                maybe_term, // maybe_save_file,
                textarea,
                edit_data,
                popup,
                saved,
                status_message,
            )
        },
    )?;
    Ok(match key_action {
        KeyAction::Quit(saved) => saved,
        KeyAction::Save
        | KeyAction::ShowHelp
        | KeyAction::ToggleHighlight
        | KeyAction::TogglePopup => {
            return Err(format!("Logic error: {key_action:?} should not return from tui_edit").into())
        }
        KeyAction::SaveAndSubmit => {
            return Err(format!("Logic error: {key_action:?} should not be implemented in tui_edit or history_key_handler").into()
            )
        }
        KeyAction::SaveAndExit => true,
        _ => false,
    })
}

/// Key handler function to be passed into `tui_edit` for editing REPL history.
///
/// # Errors
///
/// This function will bubble up any i/o, `ratatui` or `crossterm` errors encountered.
pub fn history_key_handler(
    key_event: KeyEvent,
    _maybe_term: Option<&mut ManagedTerminal>,
    // maybe_save_path: &mut Option<&mut PathBuf>,
    textarea: &mut TextArea,
    edit_data: &mut EditData,
    popup: &mut bool,
    saved: &mut bool,
    status_message: &mut String,
) -> ThagResult<KeyAction> {
    profile_fn!(history_key_handler);
    // Make sure for Windows
    if !matches!(key_event.kind, KeyEventKind::Press) {
        return Ok(KeyAction::Continue);
    }
    let maybe_save_path = &mut edit_data.save_path;
    let key_combination = KeyCombination::from(key_event); // Derive KeyCombination

    match key_combination {
        #[allow(clippy::unnested_or_patterns)]
        key!(esc) | key!(ctrl - c) | key!(ctrl - q) => Ok(KeyAction::Quit(*saved)),
        key!(ctrl - d) => {
            // Save logic
            save_file(maybe_save_path, textarea)?;
            // println!("Saved");
            Ok(KeyAction::SaveAndExit)
        }
        key!(ctrl - s) => {
            // Save logic
            let save_file = save_file(maybe_save_path, textarea)?;
            // eprintln!("Saved {:?} to {save_file:?}", textarea.lines());
            *saved = true;
            status_message.clear();
            status_message.push_str(&format!("Saved to {save_file}"));
            Ok(KeyAction::Save)
        }
        key!(ctrl - l) => {
            // Toggle popup
            *popup = !*popup;
            Ok(KeyAction::TogglePopup)
        }
        key!(f3) => {
            // Ask to revert
            Ok(KeyAction::AbandonChanges)
        }
        _ => {
            // Update the textarea with the input from the key event
            textarea.input(Input::from(key_event)); // Input derived from Event
            Ok(KeyAction::Continue)
        }
    }
}

fn save_file(
    maybe_save_path: &Option<&mut PathBuf>,
    textarea: &TextArea<'_>,
) -> ThagResult<String> {
    profile_fn!(save_file);
    let staging_path = maybe_save_path.as_ref().ok_or("Missing save_path")?;
    let staging_file = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(true)
        .open(staging_path)?;
    let mut f = BufWriter::new(&staging_file);
    for line in textarea.lines() {
        Write::write_all(&mut f, line.as_bytes())?;
        Write::write_all(&mut f, b"\n")?;
    }
    Ok(staging_path.display().to_string())
}

/// Return the maximum length of the key descriptor for a set of styled and
/// formatted key / description bindings to be displayed on screen.
fn get_max_key_len(formatted_bindings: &[(String, String)]) -> usize {
    profile_fn!(get_max_key_len);
    let style: NuStyle = *get_heading_style();
    formatted_bindings
        .iter()
        .map(|(key_desc, _)| {
            let key_desc = style.paint(key_desc);
            let key_desc = format!("{key_desc}");
            key_desc.len()
        })
        .max()
        .unwrap_or(0)
}

fn format_bindings(
    named_reedline_events: &[(String, &ReedlineEvent)],
    max_cmd_len: usize,
) -> &'static Vec<(String, String)> {
    profile_fn!(format_bindings);
    lazy_static_var!(Vec<(String, String)>, {
        let mut formatted_bindings = named_reedline_events
            .iter()
            .filter_map(|(key_desc, reedline_event)| {
                if let ReedlineEvent::Edit(edit_cmds) = reedline_event {
                    let cmd_desc = format_edit_commands(edit_cmds, max_cmd_len);
                    Some((key_desc.clone(), cmd_desc))
                } else {
                    let event_name = format!("{reedline_event:?}");
                    if event_name.starts_with("UntilFound") {
                        None
                    } else {
                        let event_desc = format_non_edit_events(&event_name, max_cmd_len);
                        Some((key_desc.clone(), event_desc))
                    }
                }
            })
            .collect::<Vec<(String, String)>>();
        // Sort the formatted bindings alphabetically by key combination description
        formatted_bindings.sort_by(|a, b| a.0.cmp(&b.0));
        formatted_bindings
    })
}

fn get_max_cmd_len(reedline_events: &[ReedlineEvent]) -> usize {
    profile_fn!(get_max_cmd_len);
    // Calculate max command len for padding
    lazy_static_var!(
        usize,
        {
            // Determine the length of the longest command for padding
            // NB: Can't extract this to a method because for some reason reedline does not expose KeyCombination.
            let style = get_subhead_style();
            let max_cmd_len = reedline_events
                .iter()
                .map(|reedline_event| {
                    if let ReedlineEvent::Edit(edit_cmds) = reedline_event {
                        edit_cmds
                            .iter()
                            .map(|cmd| {
                                let key_desc = style.paint(format!("{cmd:?}"));
                                let key_desc = format!("{key_desc}");
                                key_desc.len()
                            })
                            .max()
                            .unwrap_or(0)
                    } else if !format!("{reedline_event}").starts_with("UntilFound") {
                        let event_desc = style.paint(format!("{reedline_event:?}"));
                        let event_desc = format!("{event_desc}");
                        event_desc.len()
                    } else {
                        0
                    }
                })
                .max()
                .unwrap_or(0);
            // Add 2 bytes of padding
            max_cmd_len + 2
        },
        deref
    )
}

pub fn show_key_bindings(formatted_bindings: &[(String, String)], max_key_len: usize) {
    profile_fn!(show_key_bindings);
    println!();
    cprtln!(
        &(&Lvl::EMPH).into(),
        "Key bindings - subject to your terminal settings"
    );

    // Print the formatted and sorted key bindings
    let style = get_heading_style();
    for (key_desc, cmd_desc) in formatted_bindings {
        let key_desc = style.paint(key_desc);
        let key_desc = format!("{key_desc}");
        println!("{key_desc:<width$}    {cmd_desc}", width = max_key_len);
    }
    println!();
}

// Helper function to convert KeyModifiers to string
#[must_use]
pub fn format_key_modifier(modifier: KeyModifiers) -> String {
    profile_fn!(format_key_modifier);
    let mut modifiers = Vec::new();
    if modifier.contains(KeyModifiers::CONTROL) {
        modifiers.push("CONTROL");
    }
    if modifier.contains(KeyModifiers::SHIFT) {
        modifiers.push("SHIFT");
    }
    if modifier.contains(KeyModifiers::ALT) {
        modifiers.push("ALT");
    }
    let mods_str = modifiers.join("+");
    if modifiers.is_empty() {
        mods_str
    } else {
        mods_str + "-"
    }
}

// Helper function to convert KeyCode to string
#[must_use]
pub fn format_key_code(key_code: KeyCode) -> String {
    profile_fn!(format_key_code);
    match key_code {
        KeyCode::Backspace => "Backspace".to_string(),
        KeyCode::Enter => "Enter".to_string(),
        KeyCode::Left => "Left".to_string(),
        KeyCode::Right => "Right".to_string(),
        KeyCode::Up => "Up".to_string(),
        KeyCode::Down => "Down".to_string(),
        KeyCode::Home => "Home".to_string(),
        KeyCode::End => "End".to_string(),
        KeyCode::PageUp => "PageUp".to_string(),
        KeyCode::PageDown => "PageDown".to_string(),
        KeyCode::Tab => "Tab".to_string(),
        KeyCode::BackTab => "BackTab".to_string(),
        KeyCode::Delete => "Delete".to_string(),
        KeyCode::Insert => "Insert".to_string(),
        KeyCode::F(num) => format!("F{}", num),
        KeyCode::Char(c) => format!("{}", c.to_uppercase()),
        KeyCode::Null => "Null".to_string(),
        KeyCode::Esc => "Esc".to_string(),
        KeyCode::CapsLock => "CapsLock".to_string(),
        KeyCode::ScrollLock => "ScrollLock".to_string(),
        KeyCode::NumLock => "NumLock".to_string(),
        KeyCode::PrintScreen => "PrintScreen".to_string(),
        KeyCode::Pause => "Pause".to_string(),
        KeyCode::Menu => "Menu".to_string(),
        KeyCode::KeypadBegin => "KeypadBegin".to_string(),
        KeyCode::Media(media) => format!("Media({:?})", media),
        KeyCode::Modifier(modifier) => format!("Modifier({:?})", modifier),
    }
}

// Helper function to format ReedlineEvents other than Edit, and their doc comments
/// # Panics
/// Will panic if it fails to split a `EVENT_DESC_MAP` entry, indicating a problem with the `EVENT_DESC_MAP`.
#[allow(clippy::too_many_lines)]
#[must_use]
pub fn format_non_edit_events(event_name: &str, max_cmd_len: usize) -> String {
    profile_fn!(format_non_edit_events);
    let event_desc_map = lazy_static_var!(HashMap<&'static str, &'static str>, {
        EVENT_DESCS
            .iter()
            .map(|[k, d]| (*k, *d))
            .collect::<HashMap<&'static str, &'static str>>()
    });

    let event_highlight = get_subhead_style().paint(event_name);
    let event_highlight = format!("{event_highlight}");
    let event_desc = format!(
        "{:<max_cmd_len$} {}",
        event_highlight,
        event_desc_map.get(event_name).unwrap_or(&"")
    );
    event_desc
}

/// Helper function to format `EditCommand` and include its doc comments
/// # Panics
/// Will panic if it fails to split a `CMD_DESC_MAP` entry, indicating a problem with the `CMD_DESC_MAP`.
#[must_use]
pub fn format_edit_commands(edit_cmds: &[EditCommand], max_cmd_len: usize) -> String {
    profile_fn!(format_edit_commands);
    let cmd_desc_map: &HashMap<&str, &str> =
        lazy_static_var!(HashMap<&'static str, &'static str>, {
            CMD_DESCS
                .iter()
                .map(|[k, d]| (*k, *d))
                .collect::<HashMap<&'static str, &'static str>>()
        });
    let cmd_descriptions = edit_cmds
        .iter()
        .map(|cmd| format_cmd_desc(cmd, cmd_desc_map, max_cmd_len))
        .collect::<Vec<String>>();

    cmd_descriptions.join(", ")
}

#[allow(clippy::too_many_lines)]
fn format_cmd_desc(
    cmd: &EditCommand,
    cmd_desc_map: &HashMap<&str, &str>,
    max_cmd_len: usize,
) -> String {
    profile_fn!(format_cmd_desc);
    let style = get_subhead_style();

    let cmd_highlight = style.paint(format!("{cmd:?}"));
    let cmd_highlight = format!("{cmd_highlight}");
    match cmd {
        EditCommand::MoveToStart { select }
        | EditCommand::MoveToLineStart { select }
        | EditCommand::MoveToEnd { select }
        | EditCommand::MoveToLineEnd { select }
        | EditCommand::MoveLeft { select }
        | EditCommand::MoveRight { select }
        | EditCommand::MoveWordLeft { select }
        | EditCommand::MoveBigWordLeft { select }
        | EditCommand::MoveWordRight { select }
        | EditCommand::MoveWordRightStart { select }
        | EditCommand::MoveBigWordRightStart { select }
        | EditCommand::MoveWordRightEnd { select }
        | EditCommand::MoveBigWordRightEnd { select } => format!(
            "{:<max_cmd_len$} {}{}",
            cmd_highlight,
            cmd_desc_map
                .get(format!("{cmd:?}").split_once(' ').unwrap().0)
                .unwrap_or(&""),
            if *select {
                ". Select the text between the current cursor position and destination"
            } else {
                ", without selecting"
            }
        ),
        EditCommand::InsertString(_)
        | EditCommand::InsertNewline
        | EditCommand::ReplaceChar(_)
        | EditCommand::ReplaceChars(_, _)
        | EditCommand::Backspace
        | EditCommand::Delete
        | EditCommand::CutChar
        | EditCommand::BackspaceWord
        | EditCommand::DeleteWord
        | EditCommand::Clear
        | EditCommand::ClearToLineEnd
        | EditCommand::Complete
        | EditCommand::CutCurrentLine
        | EditCommand::CutFromStart
        | EditCommand::CutFromLineStart
        | EditCommand::CutToEnd
        | EditCommand::CutToLineEnd
        | EditCommand::CutWordLeft
        | EditCommand::CutBigWordLeft
        | EditCommand::CutWordRight
        | EditCommand::CutBigWordRight
        | EditCommand::CutWordRightToNext
        | EditCommand::CutBigWordRightToNext
        | EditCommand::PasteCutBufferBefore
        | EditCommand::PasteCutBufferAfter
        | EditCommand::UppercaseWord
        | EditCommand::InsertChar(_)
        | EditCommand::CapitalizeChar
        | EditCommand::SwitchcaseChar
        | EditCommand::SwapWords
        | EditCommand::SwapGraphemes
        | EditCommand::Undo
        | EditCommand::Redo
        | EditCommand::CutRightUntil(_)
        | EditCommand::CutRightBefore(_)
        | EditCommand::CutLeftUntil(_)
        | EditCommand::CutLeftBefore(_)
        | EditCommand::CutSelection
        | EditCommand::CopySelection
        | EditCommand::Paste
        | EditCommand::SelectAll
        | EditCommand::LowercaseWord => format!(
            "{:<max_cmd_len$} {}",
            cmd_highlight,
            cmd_desc_map.get(format!("{cmd:?}").as_str()).unwrap_or(&"")
        ),
        EditCommand::MoveRightUntil { c: _, select }
        | EditCommand::MoveRightBefore { c: _, select }
        | EditCommand::MoveLeftUntil { c: _, select }
        | EditCommand::MoveLeftBefore { c: _, select } => format!(
            "{:<max_cmd_len$} {}. {}",
            cmd_highlight,
            cmd_desc_map
                .get(format!("{cmd:?}").split_once(' ').unwrap().0)
                .unwrap_or(&""),
            if *select {
                "Select the text between the current cursor position and destination"
            } else {
                "without selecting"
            }
        ),
        EditCommand::MoveToPosition { position, select } => format!(
            "{:<max_cmd_len$} {} {} {}",
            cmd_highlight,
            cmd_desc_map
                .get(format!("{cmd:?}").split_once(' ').unwrap().0)
                .unwrap_or(&""),
            position,
            if *select {
                "Select the text between the current cursor position and destination"
            } else {
                "without selecting"
            }
        ),
        // Add other EditCommand variants and their descriptions here
        _ => format!("{:<width$}", cmd_highlight, width = max_cmd_len + 2),
    }
}

/// Delete the temporary files used by the current REPL instance.
/// # Errors
/// Currently will not return any errors.
#[allow(clippy::unnecessary_wraps)]
pub fn delete(build_state: &BuildState) -> ThagResult<Option<String>> {
    profile_fn!(delete);
    // let build_state = &context.build_state;
    let clean_up = clean_up(&build_state.source_path, &build_state.target_dir_path);
    if clean_up.is_ok()
        || (!&build_state.source_path.exists() && !&build_state.target_dir_path.exists())
    {
        vlog!(V::QQ, "Deleted");
    } else {
        vlog!(
            V::QQ,
            "Failed to delete all files - enter l(ist) to list remaining files"
        );
    }
    Ok(Some(String::from("End of delete")))
}

/// Open the generated destination Rust source code file in an editor.
/// # Errors
/// Will return `Err` if there is an error editing the file.
#[allow(clippy::unnecessary_wraps)]
pub fn edit(source_path: &PathBuf) -> ThagResult<Option<String>> {
    edit_file(source_path)?;

    Ok(Some(String::from("End of source edit")))
}

/// Open the generated Cargo.toml file in an editor.
/// # Errors
/// Will return `Err` if there is an error editing the file.
#[allow(clippy::unnecessary_wraps)]
pub fn toml(build_state: &BuildState) -> ThagResult<Option<String>> {
    let cargo_toml_file = &build_state.cargo_toml_path;
    if cargo_toml_file.exists() {
        edit_file(cargo_toml_file)?;
    } else {
        vlog!(V::QQ, "No Cargo.toml file found - have you run anything?");
    }
    Ok(Some(String::from("End of Cargo.toml edit")))
}

/// Parse the current line. Borrowed from clap-repl crate.
#[must_use]
pub fn parse_line(line: &str) -> (String, Vec<String>) {
    profile_fn!(parse_line);
    let re: &Regex = regex!(r#"("[^"\n]+"|[\S]+)"#);

    let mut args = re
        .captures_iter(line)
        .map(|a| a[0].to_string().replace('\"', ""))
        .collect::<Vec<String>>();
    let command: String = args.drain(..1).collect();
    (command, args)
}

/// Display the REPL banner.
pub fn disp_repl_banner(cmd_list: &str) {
    profile_fn!(disp_repl_banner);
    cvprtln!(
        Lvl::HEAD,
        get_verbosity(),
        r#"Enter a Rust expression (e.g., 2 + 3 or "Hi!"), or one of: {cmd_list}."#
    );

    println!();

    cvprtln!(
        Lvl::SUBH,
        get_verbosity(),
        r"Expressions in matching braces, brackets or quotes may span multiple lines."
    );

    cvprtln!(
        Lvl::SUBH,
        get_verbosity(),
        r"Use F7 & F8 to navigate prev/next history, →  to select current. Ctrl-U: clear. Ctrl-K: delete to end."
    );
}

/// Display a list of the temporary files used by the current REPL instance.
/// # Errors
/// This function will return an error in the following situations, but is not limited to just these cases:
/// The provided path doesn't exist.
/// The process lacks permissions to view the contents.
/// The path points at a non-directory file.
#[allow(clippy::unnecessary_wraps)]
pub fn list(build_state: &BuildState) -> ThagResult<Option<String>> {
    profile_fn!(list);
    let source_path = &build_state.source_path;
    if source_path.exists() {
        vlog!(V::QQ, "File: {source_path:?}");
    }

    // Display directory contents
    display_dir_contents(&build_state.target_dir_path)?;

    // Check if neither file nor directory exist
    if !&source_path.exists() && !&build_state.target_dir_path.exists() {
        vlog!(V::QQ, "No temporary files found");
    }
    Ok(Some(String::from("End of list")))
}