thag_rs 0.2.0

A versatile cross-platform playground 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
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
use crate::{
    code_utils::write_source,
    file_dialog::{DialogMode, FileDialog, Status},
    key,
    stdin::edit_history,
    KeyCombination, ThagError, ThagResult,
};
// use crokey::key;
// use crokey::crossterm::event::KeyEvent;
use crossterm::event::{
    self, DisableMouseCapture, EnableBracketedPaste, EnableMouseCapture,
    Event::{self, Paste},
    KeyEvent, KeyEventKind,
};
use mockall::automock;
use ratatui::crossterm::terminal::{
    disable_raw_mode, enable_raw_mode, is_raw_mode_enabled, EnterAlternateScreen,
    LeaveAlternateScreen,
};
use ratatui::layout::{Constraint, Direction, Layout, Margin};
use ratatui::prelude::{CrosstermBackend, Rect};
pub use ratatui::style::Style as RataStyle;
use ratatui::style::{Color, Modifier, Styled, Stylize};
use ratatui::text::Line;
use ratatui::widgets::{block::Block, Borders, Clear, Paragraph};
use ratatui::{CompletedFrame, Frame, Terminal};
use regex::Regex;
use scopeguard::{guard, ScopeGuard};
use serde::{Deserialize, Serialize};
use std::{
    self,
    collections::VecDeque,
    convert::Into,
    env::var,
    fmt::{Debug, Display, Write as _},
    fs::{self, OpenOptions},
    io::Write,
    path::PathBuf,
    time::Duration,
};
use thag_common::{debug_log, re};
use thag_styling::{Role, ThemedStyle};
// import without risk of name clashing
use thag_profiler::profiled;
use tui_textarea::{CursorMove, Input, TextArea};

/// Title displayed at the top of the key bindings popup
pub const TITLE_TOP: &str = "Key bindings - subject to your terminal settings";
/// Title displayed at the bottom of the key bindings popup
pub const TITLE_BOTTOM: &str = "Ctrl+l to hide";

/// Type alias for the crossterm backend with stdout lock
pub type BackEnd<'a> = CrosstermBackend<std::io::StdoutLock<'a>>;
/// Type alias for a terminal with the backend
pub type Term<'a> = Terminal<BackEnd<'a>>;
/// Type alias for a closure that resets the terminal
pub type ResetTermClosure<'a> = Box<dyn FnOnce(Term<'a>)>;
/// Type alias for a scope guard that manages terminal cleanup
pub type TermScopeGuard<'a> = ScopeGuard<Term<'a>, ResetTermClosure<'a>>;
/// A trait to allow mocking of the event reader for testing purposes.
#[automock]
pub trait EventReader {
    /// Read a terminal event.
    ///
    /// # Errors
    ///
    /// This function will bubble up any i/o, `ratatui` or `crossterm` errors encountered.
    fn read_event(&self) -> ThagResult<Event>;
    /// Poll for a terminal event.
    ///
    /// # Errors
    ///
    /// This function will bubble up any i/o, `ratatui` or `crossterm` errors encountered.
    fn poll(&self, timeout: Duration) -> ThagResult<bool>;
}

/// A struct to implement real-world use of the event reader, as opposed to use in testing.
#[derive(Debug)]
pub struct CrosstermEventReader;

impl EventReader for CrosstermEventReader {
    #[profiled]
    fn read_event(&self) -> ThagResult<Event> {
        crossterm::event::read().map_err(Into::<ThagError>::into)
    }

    #[profiled]
    fn poll(&self, timeout: Duration) -> ThagResult<bool> {
        crossterm::event::poll(timeout).map_err(Into::<ThagError>::into)
    }
}

/// A wrapper around a terminal with scope guard for automatic cleanup.
///
/// This struct manages a terminal instance and ensures proper cleanup
/// when the terminal goes out of scope, regardless of how the program exits.
pub struct ManagedTerminal<'a> {
    terminal: TermScopeGuard<'a>,
}

impl ManagedTerminal<'_> {
    /// Draw to the terminal.
    ///
    /// # Errors
    ///
    /// This function will return an error if there is an issue drawing to the terminal.
    #[profiled]
    pub fn draw<F>(&mut self, f: F) -> std::io::Result<CompletedFrame<'_>>
    where
        F: FnOnce(&mut Frame<'_>),
    {
        self.terminal.draw(f)
    }
}

/// Determine whether a terminal is in use (as opposed to testing or headless CI), and
/// if so, wrap it in a scopeguard in order to reset it regardless of success or failure.
///
/// # Panics
///
/// Panics if a `crossterm` error is encountered resetting the terminal inside a
/// `scopeguard::guard` closure.
///
/// # Errors
///
#[profiled]
pub fn resolve_term<'a>() -> ThagResult<Option<ManagedTerminal<'a>>> {
    if var("TEST_ENV").is_ok() {
        return Ok(None);
    }

    let mut stdout = std::io::stdout().lock();
    enable_raw_mode()?;

    ratatui::crossterm::execute!(
        stdout,
        EnterAlternateScreen,
        EnableMouseCapture,
        EnableBracketedPaste
    )?;

    let backend = CrosstermBackend::new(stdout);
    let terminal = Terminal::new(backend)?;

    Ok(Some(ManagedTerminal {
        terminal: guard(
            terminal,
            Box::new(|term| {
                reset_term(term).expect("Error resetting terminal");
            }),
        ),
    }))
}

#[derive(Clone, Debug, Serialize, Deserialize)]
/// Represents a single entry in the edit history.
///
/// An entry contains both an index for ordering and the actual text content
/// stored as individual lines. This structure is used to maintain a history
/// of text edits that can be navigated and restored.
pub struct Entry {
    /// The index of this entry in the history collection
    pub index: usize, // Holds the entry's index
    /// The text content of this entry, stored as separate lines
    pub lines: Vec<String>, // Holds editor content as lines
}

impl Display for Entry {
    #[profiled]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}: {}", self.index, self.lines.join("\n"))
    }
}

impl Entry {
    /// Creates a new Entry with the given index and content.
    ///
    /// The content string is split into individual lines and stored in the `lines` field.
    ///
    /// # Arguments
    ///
    /// * `index` - The index of this entry in the history collection
    /// * `content` - The text content to store, which will be split into lines
    #[profiled]
    pub fn new(index: usize, content: &str) -> Self {
        Self {
            index,
            lines: content.lines().map(String::from).collect(),
        }
    }

    /// Extracts string contents of entry for use in the editor.
    ///
    /// Joins all lines in the entry with newline characters to reconstruct
    /// the original text content.
    ///
    /// # Returns
    ///
    /// A String containing the full text content with lines joined by newlines
    #[must_use]
    #[profiled]
    pub fn contents(&self) -> String {
        self.lines.join("\n")
    }
}

/// Represents the edit history for a text editor.
///
/// This struct maintains a collection of text entries that can be navigated
/// through, similar to command history in a shell. It tracks the current
/// position within the history and provides methods for adding, updating,
/// and navigating through entries.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct History {
    /// The index of the currently selected entry in the history.
    /// `None` indicates no current selection or an empty history.
    pub current_index: Option<usize>,
    /// A double-ended queue containing all history entries.
    /// Entries are stored as `Entry` objects which contain both
    /// an index and the text content as lines.
    pub entries: VecDeque<Entry>, // Now a VecDeque of Entries
}

impl History {
    /// Creates a new empty History instance.
    #[must_use]
    #[profiled]
    pub fn new() -> Self {
        Self {
            current_index: None,
            entries: VecDeque::with_capacity(20),
        }
    }

    /// Loads a History instance from a file.
    ///
    /// # Arguments
    ///
    /// * `path` - The path to the file to load from
    ///
    /// # Returns
    ///
    /// A History instance loaded from the file, or a new empty instance if loading fails
    #[must_use]
    #[profiled]
    pub fn load_from_file(path: &PathBuf) -> Self {
        let mut history = fs::read_to_string(path).map_or_else(
            |_| Self::default(),
            |data| serde_json::from_str(&data).unwrap_or_else(|_| Self::new()),
        );
        debug_log!("Loaded history={history:?}");
        // Remove any blanks - TODO they shouldn't be saved in the first place
        history.entries.retain(|e| !e.contents().trim().is_empty());

        // Reassign indices
        history.reassign_indices();

        // Set current_index to the index of the front entry (most recent one)
        if history.entries.is_empty() {
            history.current_index = None;
        } else {
            history.current_index = Some(history.entries.len() - 1);
        }
        debug_log!("history={history:?}");
        debug_log!(
            "load_from_file({path:?}); current index={:?}",
            history.current_index
        );
        history
    }

    /// Returns true if the current position is at the start of the history.
    #[allow(clippy::unnecessary_map_or)]
    #[must_use]
    #[profiled]
    pub fn at_start(&self) -> bool {
        debug_log!("at_start ...");
        self.current_index
            .map_or(true, |current_index| current_index == 0)
    }

    /// Returns true if the current position is at the end of the history.
    #[allow(clippy::unnecessary_map_or)]
    #[must_use]
    #[profiled]
    pub fn at_end(&self) -> bool {
        debug_log!("at_end ...");
        self.current_index.map_or(true, |current_index| {
            current_index == self.entries.len() - 1
        })
    }

    /// Adds a new entry to the history.
    ///
    /// # Arguments
    ///
    /// * `text` - The text content to add to the history
    #[profiled]
    pub fn add_entry(&mut self, text: &str) {
        let new_index = self.entries.len(); // Assign the next index based on current length
        let new_entry = Entry::new(new_index, text);

        // Remove prior duplicates
        self.entries
            .retain(|f| f.contents().trim() != new_entry.contents().trim());
        self.entries.push_back(new_entry);

        // // Reassign indices after pushing the new entry
        // self.reassign_indices();

        // Update current_index to point to the most recent entry (the front)
        self.current_index = Some(self.entries.len() - 1);
        debug_log!("add_entry({text}); current index={:?}", self.current_index);
        debug_log!("history={self:?}");
    }

    /// Updates an existing entry in the history or adds a new one if it doesn't exist.
    ///
    /// # Arguments
    ///
    /// * `index` - The index of the entry to update
    /// * `text` - The new text content for the entry
    #[profiled]
    pub fn update_entry(&mut self, index: usize, text: &str) {
        debug_log!("update_entry for index {index}...");
        // Get a mutable reference to the entry at the specified index
        let current_index = self.current_index;
        if let Some(entry) = self.get_mut(index) {
            // Update the lines if the entry exists
            entry.lines = text.lines().map(String::from).collect::<Vec<String>>();
            debug_log!("... update_entry({entry:?}); current index={current_index:?}");
        } else {
            // If the entry doesn't exist, add it
            self.add_entry(text);
        }
    }

    /// Deletes an entry from the history by index.
    ///
    /// # Arguments
    ///
    /// * `index` - The index of the entry to delete
    #[profiled]
    pub fn delete_entry(&mut self, index: usize) {
        self.entries.retain(|entry| entry.index != index);

        // Reassign indices after deletion
        self.reassign_indices();

        // Update current_index after deletion, set to most recent entry (the front)
        if self.entries.is_empty() {
            self.current_index = None;
        } else {
            self.current_index = Some(self.entries.len() - 1);
        }
    }

    /// Save history to a file.
    ///
    /// # Errors
    ///
    /// This function will bubble up any i/o errors encountered writing the file.
    #[profiled]
    pub fn save_to_file(&mut self, path: &PathBuf) -> ThagResult<()> {
        self.reassign_indices();
        if let Ok(data) = serde_json::to_string(&self) {
            debug_log!("About to write data=({data}");
            if let Ok(metadata) = std::fs::metadata(path) {
                debug_log!("File permissions: {:?}", metadata.permissions());
            }

            // fs::write(path, data)?;
            // fs::write(path, "\n")?;
            let mut file = OpenOptions::new()
                .write(true)
                .create(true)
                .truncate(true) // This will clear the file before writing
                .open(path)?;

            // Write the data
            file.write_all((data + "\n").into_bytes().as_ref())?;

            // Flush the write to disk
            // Beware of exiting "too early" for writes actually to be flushed despite sync.
            // file.sync_all()?;
            file.sync_data()?;
        } else {
            debug_log!("Could not serialise history: {self:?}");
        }
        debug_log!("save_to_file({path:?}");
        Ok(())
    }

    /// Gets the currently selected entry from the history.
    ///
    /// # Returns
    ///
    /// An optional reference to the current entry, or None if the history is empty
    #[profiled]
    pub fn get_current(&mut self) -> Option<&Entry> {
        if self.entries.is_empty() {
            return None;
        }

        if let Some(index) = self.current_index {
            debug_log!("get_current(); current index={:?}", self.current_index);

            self.get(index)
        } else {
            debug_log!("None");
            None
        }
    }

    /// Gets an entry at the specified index and sets it as the current entry.
    ///
    /// # Arguments
    ///
    /// * `index` - The index of the entry to retrieve
    ///
    /// # Returns
    ///
    /// An optional reference to the entry at the specified index
    #[profiled]
    pub fn get(&mut self, index: usize) -> Option<&Entry> {
        debug_log!("get({index})...");
        if !(0..self.entries.len()).contains(&index) {
            return None;
        }
        self.current_index = Some(index);
        debug_log!(
            "...get({:?}); current index={:?}",
            self.entries.get(index),
            self.current_index
        );

        let entry = self.entries.get(index);
        debug_log!("... returning {entry:?}");
        entry
    }

    /// Gets a mutable reference to an entry at the specified index and sets it as the current entry.
    ///
    /// # Arguments
    ///
    /// * `index` - The index of the entry to retrieve
    ///
    /// # Returns
    ///
    /// An optional mutable reference to the entry at the specified index
    #[profiled]
    pub fn get_mut(&mut self, index: usize) -> Option<&mut Entry> {
        debug_log!("get_mut({index})...");

        if !(0..self.entries.len()).contains(&index) {
            return None;
        }

        self.current_index = Some(index);
        debug_log!(
            "...get_mut({:?}); current index={:?}",
            self.entries.get(index),
            self.current_index
        );

        let entry = self.entries.get_mut(index);
        debug_log!("... returning {entry:?}");

        entry
    }

    /// Returns the previous entry in this [`History`] collection.
    ///
    /// # Panics
    ///
    /// Panics if a logic error is detected, likely when reaching the oldest History entry.
    #[profiled]
    pub fn get_previous(&mut self) -> Option<&Entry> {
        // let this = &mut *self;
        debug_log!("get_previous...");
        if self.entries.is_empty() {
            return None;
        }
        let new_index = self.current_index.map(|index| {
            if index > 0 {
                index - 1
            } else {
                // TODO crossterm terminal beep if and when implemented (issue #806 pull request)
                0
            }
        });
        debug_log!(
            "...old index={:#?};new_index={new_index:?}",
            self.current_index
        );

        self.current_index = new_index;

        self.current_index.map_or_else(
            || {
                panic!(
                    "Logic error: current_index should never be None if there are History records"
                );
            },
            |index| {
                let entry = self.get(index);
                debug_log!("get_previous; new current index={index:?}, entry={entry:?}");
                entry
            },
        )
    }

    /// Returns the next entry in this [`History`] collection.
    ///
    /// # Panics
    ///
    /// Panics if a logic error is detected, likely when reaching the newest History entry.
    #[profiled]
    pub fn get_next(&mut self) -> Option<&Entry> {
        debug_log!("get_next...");
        let this = &mut *self;
        if this.entries.is_empty() {
            return None;
        }
        let new_index = self.current_index.map(|index| {
            let max_index = self.entries.len() - 1;
            if index < max_index {
                index + 1
            } else {
                // crossterm terminal beep if and when implemented (issue #806 pull request)
                max_index
            }
        });
        debug_log!(
            "...old index={:#?};new_index={new_index:?}",
            self.current_index
        );

        self.current_index = new_index;

        self.current_index.map_or_else(
            || {
                panic!(
                    "Logic error: current_index should never be None if there are History records"
                );
            },
            |index| {
                let entry = self.get(index);
                debug_log!("get_next(); current index={index:?}, entry={entry:?}");
                entry
            },
        )
    }

    /// Gets the last (most recent) entry in the history.
    ///
    /// # Returns
    ///
    /// An optional reference to the last entry, or None if the history is empty
    #[profiled]
    pub fn get_last(&mut self) -> Option<&Entry> {
        if self.entries.is_empty() {
            return None;
        }

        self.entries.back()
    }

    /// Reassigns indices so that the newest entry has index 0, and the oldest has len - 1.
    #[profiled]
    fn reassign_indices(&mut self) {
        // let len = self.entries.len();
        for (i, entry) in self.entries.iter_mut().enumerate() {
            entry.index = i;
        }
    }
}

#[allow(dead_code)]
#[derive(Debug, Default)]
/// Struct to hold data-related parameters for the TUI editor
pub struct EditData<'a> {
    /// Whether to return the edited text as part of the result
    pub return_text: bool,
    /// The initial content to display in the editor
    pub initial_content: &'a str,
    /// Optional path where the edited content should be saved
    pub save_path: Option<PathBuf>,
    /// Optional path to the history file for storing edit history
    pub history_path: Option<&'a PathBuf>,
    /// Optional history object for managing edit history
    pub history: Option<History>,
}

/// Struct to hold display-related parameters for the TUI editor
#[derive(Debug)]
pub struct KeyDisplay<'a> {
    /// The title to display at the top of the editor
    pub title: &'a str,
    /// The style to apply to the title text
    pub title_style: RataStyle,
    /// Keys to remove from the default key mappings display
    pub remove_keys: &'a [&'a str],
    /// Additional key mappings to add to the display
    pub add_keys: &'a [KeyDisplayLine],
}

/// Tracks the scroll state of the popup help display
#[derive(Debug, Default)]
pub struct PopupScrollState {
    /// Current scroll offset (number of rows scrolled down)
    pub scroll_offset: usize,
}

/// Represents the different actions that can be taken in response to user input in the TUI editor.
///
/// This enum is used to communicate between key handlers and the main editor loop,
/// indicating what action should be taken based on the user's key press.
#[derive(Debug)]
pub enum KeyAction {
    /// Abandon any unsaved changes and exit without saving
    AbandonChanges,
    /// Continue with normal editor operation - no special action needed
    Continue, // For other inputs that don't need specific handling
    /// Quit the editor, with a boolean indicating whether changes have been saved
    Quit(bool),
    /// Save the current content to file
    Save,
    /// Save the current content and then exit the editor
    SaveAndExit,
    /// Show the help screen with key bindings
    ShowHelp,
    /// Save the current content and submit it (e.g., for REPL execution)
    SaveAndSubmit,
    /// Submit the current content without necessarily saving to file
    Submit,
    /// Toggle the syntax highlighting colors
    ToggleHighlight,
    /// Toggle the visibility of the popup help screen
    TogglePopup,
}

/// Edit content with a TUI
///
/// # Panics
///
/// Panics if a `crossterm` error is encountered resetting the terminal inside a
/// `scopeguard::guard` closure in the call to `resolve_term`.
///
/// # Errors
///
/// This function will bubble up any i/o, `ratatui` or `crossterm` errors encountered.
#[allow(clippy::cognitive_complexity, clippy::too_many_lines)]
#[profiled]
pub fn tui_edit<R, F>(
    event_reader: &R,
    edit_data: &mut EditData,
    display: &KeyDisplay,
    key_handler: F, // closure or function for key handling
) -> ThagResult<(KeyAction, Option<Vec<String>>)>
where
    R: EventReader + Debug,
    F: Fn(
        ratatui::crossterm::event::KeyEvent,
        Option<&mut ManagedTerminal>,
        &mut TextArea,
        &mut EditData,
        &mut bool,
        &mut bool,
        &mut String,
    ) -> ThagResult<KeyAction>,
{
    // Initialize state variables
    let mut popup = false;
    let mut tui_highlight_fg: Role = Role::Emphasis;
    let mut saved = false;
    let mut status_message: String = String::default(); // Add status message variable

    let mut maybe_term = resolve_term()?;

    // Create the `TextArea` from initial content
    let mut textarea = TextArea::from(edit_data.initial_content.lines());
    textarea.set_hard_tab_indent(true);
    // eprintln!("textarea.tab_length()={}", textarea.tab_length());

    // Set up the display parameters for the `TextArea`
    textarea.set_block(
        Block::default()
            .borders(Borders::ALL)
            .title(display.title)
            .title_style(display.title_style),
    );

    textarea.set_line_number_style(RataStyle::themed(Role::Hint));
    textarea.move_cursor(CursorMove::Bottom);
    // New line with cursor at EOF for usability
    textarea.move_cursor(CursorMove::End);
    if !textarea.is_empty() {
        textarea.insert_newline();
    }

    // Apply initial highlights
    highlight_selection(&mut textarea, tui_highlight_fg);

    let remove = display.remove_keys;
    let add = display.add_keys;
    // Track popup scroll state
    let mut popup_scroll = PopupScrollState::default();

    // Can't make these OnceLock values, since their configuration depends on the `remove`
    // and `add` values passed in by the caller.
    let mut adjusted_mappings: Vec<KeyDisplayLine> = MAPPINGS
        .iter()
        .filter(|&row| !remove.contains(&row.keys))
        .chain(add.iter())
        .cloned()
        .collect();
    adjusted_mappings.sort();
    let (max_key_len, max_desc_len) =
        adjusted_mappings
            .iter()
            .fold((0_u16, 0_u16), |(max_key, max_desc), row| {
                let key_len = row.keys.len().try_into().unwrap();
                let desc_len = row.desc.len().try_into().unwrap();
                (max_key.max(key_len), max_desc.max(desc_len))
            });

    // Event loop for handling key events
    loop {
        maybe_enable_raw_mode()?;
        let test_env = &var("TEST_ENV");
        let event = if test_env.is_ok() {
            // Testing or CI
            event_reader.read_event()?
        } else {
            // Real-world interaction
            maybe_term.as_mut().map_or_else(
                || Err("Logic issue unwrapping term we wrapped ourselves".into()),
                |term| {
                    term.draw(|f| {
                        // Get the size of the available terminal area
                        let area = f.area();

                        // Ensure there's enough height for both the `TextArea` and the status line
                        if area.height > 1 {
                            let chunks = Layout::default()
                                .direction(Direction::Vertical)
                                .constraints::<&[Constraint]>(&[
                                    Constraint::Min(area.height - 3), // Editor area takes up the rest
                                    Constraint::Length(3),            // Status line gets 1 line
                                ])
                                .split(area);

                            // Render the `TextArea` in the first chunk
                            f.render_widget(&textarea, chunks[0]);

                            // Render the status line in the second chunk
                            let status_block = Block::default()
                                .borders(Borders::ALL)
                                .title("Status")
                                .style(RataStyle::themed(Role::Success))
                                .title_style(display.title_style)
                                .padding(ratatui::widgets::Padding::horizontal(1));

                            let status_text = Paragraph::new::<&str>(status_message.as_ref())
                                .block(status_block)
                                .style(RataStyle::themed(Role::Info));

                            f.render_widget(status_text, chunks[1]);

                            if popup {
                                display_popup(
                                    &adjusted_mappings,
                                    TITLE_TOP,
                                    TITLE_BOTTOM,
                                    max_key_len,
                                    max_desc_len,
                                    &mut popup_scroll,
                                    f,
                                );
                            }
                            highlight_selection(&mut textarea, tui_highlight_fg);
                            // status_message = String::new();
                        }
                    })
                    .map_err(|e| {
                        eprintln!("Error drawing terminal: {e:?}");
                        e
                    })?;

                    // NB: leave in raw mode until end of session to avoid random appearance of OSC codes on screen
                    event_reader.read_event()
                },
            )?
        };

        if let Paste(ref data) = event {
            textarea.insert_str(normalize_newlines(data));
        } else if let Event::Mouse(mouse_event) = event {
            // Handle mouse scrolling in popup
            if popup {
                use ratatui::crossterm::event::MouseEventKind;
                match mouse_event.kind {
                    MouseEventKind::ScrollDown => {
                        if popup_scroll.scroll_offset + 1 < adjusted_mappings.len() {
                            popup_scroll.scroll_offset += 1;
                        }
                    }
                    MouseEventKind::ScrollUp => {
                        popup_scroll.scroll_offset = popup_scroll.scroll_offset.saturating_sub(1);
                    }
                    _ => {}
                }
            }
        } else if let Event::Key(key_event) = event {
            // Ignore key release, which creates an unwanted second event in Windows
            if !matches!(key_event.kind, KeyEventKind::Press) {
                continue;
            }
            //
            // log::debug_log!("key_event={key_event:#?}");
            let key_combination = KeyCombination::from(key_event); // Derive KeyCombination

            // Handle scrolling in popup before normal editor keys
            if popup {
                let max_scroll = adjusted_mappings.len().saturating_sub(10);

                match key_combination {
                    key!(up) => {
                        popup_scroll.scroll_offset = popup_scroll.scroll_offset.saturating_sub(1);
                        continue;
                    }
                    key!(down) => {
                        if popup_scroll.scroll_offset < max_scroll {
                            popup_scroll.scroll_offset += 1;
                        }
                        continue;
                    }
                    _ => {} // Let other keys fall through to toggle popup
                }
            }

            // If using iterm2, ensure Settings | Profiles | Keys | Left Option key is set to Esc+.
            #[allow(clippy::unnested_or_patterns)]
            match key_combination {
                key!(ctrl - h) | key!(backspace) => {
                    textarea.delete_char();
                }
                // Not how this works. Intercepting tab and Ctrl-i is counter-productive.
                // key!(ctrl - i) | key!(tab) => {
                //     textarea.indent();
                // }
                key!(ctrl - m) | key!(enter) => {
                    textarea.insert_newline();
                }
                key!(ctrl - k) => {
                    textarea.delete_line_by_end();
                }
                key!(ctrl - j) => {
                    textarea.delete_line_by_head();
                }
                key!(ctrl - w) | key!(alt - backspace) => {
                    textarea.delete_word();
                }
                key!(alt - d) => {
                    textarea.delete_next_word();
                }
                key!(ctrl - u) => {
                    textarea.undo();
                }
                key!(ctrl - r) => {
                    textarea.redo();
                }
                key!(ctrl - c) => {
                    textarea.copy();
                }
                key!(ctrl - x) => {
                    textarea.cut();
                }
                key!(ctrl - y) => {
                    textarea.paste();
                }
                key!(ctrl - f) | key!(right) => {
                    if textarea.is_selecting() {
                        textarea.cancel_selection();
                    }
                    textarea.move_cursor(CursorMove::Forward);
                }
                key!(ctrl - b) | key!(left) => {
                    if textarea.is_selecting() {
                        textarea.cancel_selection();
                    }
                    textarea.move_cursor(CursorMove::Back);
                }
                key!(ctrl - p) | key!(up) => {
                    if textarea.is_selecting() {
                        textarea.cancel_selection();
                    }
                    textarea.move_cursor(CursorMove::Up);
                }
                key!(ctrl - n) | key!(down) => {
                    if textarea.is_selecting() {
                        textarea.cancel_selection();
                    }
                    textarea.move_cursor(CursorMove::Down);
                }
                key!(alt - f) => {
                    if textarea.is_selecting() {
                        textarea.cancel_selection();
                    }
                    textarea.move_cursor(CursorMove::WordForward);
                }
                key!(alt - shift - f) => {
                    textarea.move_cursor(CursorMove::WordEnd);
                }
                key!(alt - b) => {
                    if textarea.is_selecting() {
                        textarea.cancel_selection();
                    }
                    textarea.move_cursor(CursorMove::WordBack);
                }
                key!(alt - p) | key!(alt - ')') | key!(f1) => {
                    if textarea.is_selecting() {
                        textarea.cancel_selection();
                    }
                    textarea.move_cursor(CursorMove::ParagraphBack);
                }
                key!(alt - n) | key!(alt - '(') | key!(f2) => {
                    textarea.move_cursor(CursorMove::ParagraphForward);
                }
                key!(ctrl - e) | key!(end) | key!(ctrl - alt - f) => {
                    textarea.move_cursor(CursorMove::End);
                }
                key!(ctrl - a) | key!(home) | key!(ctrl - alt - b) => {
                    textarea.move_cursor(CursorMove::Head);
                }
                key!(f9) => {
                    ratatui::crossterm::execute!(std::io::stdout().lock(), DisableMouseCapture,)?;
                    textarea.remove_line_number();
                    textarea.set_block(
                        Block::default()
                            .borders(Borders::NONE)
                            .title(display.title)
                            .title_style(display.title_style),
                    );
                }
                key!(f10) => {
                    // eprintln!("key_combination={key_combination:?}");
                    ratatui::crossterm::execute!(std::io::stdout().lock(), EnableMouseCapture,)?;
                    textarea.set_line_number_style(RataStyle::themed(Role::Hint));
                    textarea.set_block(
                        Block::default()
                            .borders(Borders::ALL)
                            .title(display.title)
                            .title_style(display.title_style),
                    );
                }
                key!(alt - '<') | key!(ctrl - alt - p) => {
                    textarea.move_cursor(CursorMove::Top);
                }
                key!(alt - '>') | key!(ctrl - alt - n) => {
                    textarea.move_cursor(CursorMove::Bottom);
                }
                key!(alt - c) => {
                    if textarea.is_selecting() {
                        textarea.cancel_selection();
                    } else {
                        textarea.start_selection();
                    }
                }
                key!(alt - shift - 'h') => {
                    if !textarea.is_selecting() {
                        textarea.start_selection();
                    }
                    textarea.move_cursor(CursorMove::WordBack);
                }
                key!(alt - shift - 'j') => {
                    if !textarea.is_selecting() {
                        textarea.start_selection();
                    }
                    textarea.move_cursor(CursorMove::Down);
                }
                key!(alt - shift - 'k') => {
                    if !textarea.is_selecting() {
                        textarea.start_selection();
                    }
                    textarea.move_cursor(CursorMove::Up);
                }
                key!(alt - shift - 'l') => {
                    if !textarea.is_selecting() {
                        textarea.start_selection();
                    }
                    textarea.move_cursor(CursorMove::WordEnd);
                }
                key!(alt - shift - 'p') => {
                    if !textarea.is_selecting() {
                        textarea.start_selection();
                    }
                    textarea.move_cursor(CursorMove::ParagraphBack);
                }
                key!(alt - shift - 'n') => {
                    if !textarea.is_selecting() {
                        textarea.start_selection();
                    }
                    textarea.move_cursor(CursorMove::ParagraphForward);
                }
                // key!(alt - shift - c) => {
                //     textarea.start_selection();
                // }
                key!(alt - shift - a) => {
                    textarea.select_all();
                }
                key!(ctrl - t) => {
                    // Toggle highlighting colours
                    tui_highlight_fg = match tui_highlight_fg {
                        Role::Emphasis => Role::Info,
                        Role::Info => Role::Error,
                        Role::Error => Role::Warning,
                        Role::Warning => Role::Heading1,
                        Role::Heading1 => Role::Heading2,
                        Role::Heading2 => Role::Heading3,
                        _ => Role::Emphasis,
                    };
                    if var("TEST_ENV").is_err() {
                        #[allow(clippy::option_if_let_else)]
                        if let Some(ref mut term) = maybe_term {
                            term.draw(|_| {
                                highlight_selection(&mut textarea, tui_highlight_fg);
                            })?;
                        }
                    }
                }
                _ => {
                    // Call the key_handler closure to process events
                    let key_action = key_handler(
                        key_event,
                        maybe_term.as_mut(),
                        &mut textarea,
                        edit_data,
                        &mut popup,
                        &mut saved,
                        &mut status_message,
                    )?;
                    // eprintln!("key_action={key_action:?}");
                    match key_action {
                        KeyAction::AbandonChanges => break Ok((key_action, None::<Vec<String>>)),
                        KeyAction::Quit(_)
                        | KeyAction::SaveAndExit
                        | KeyAction::SaveAndSubmit
                        | KeyAction::Submit => {
                            let maybe_text = if edit_data.return_text {
                                Some(textarea.lines().to_vec())
                            } else {
                                None::<Vec<String>>
                            };
                            break Ok((key_action, maybe_text));
                        }
                        KeyAction::Continue | KeyAction::Save | KeyAction::ToggleHighlight => (),
                        KeyAction::TogglePopup => {
                            // Reset scroll position when popup is opened
                            if popup {
                                popup_scroll.scroll_offset = 0;
                            }
                        }
                        KeyAction::ShowHelp => todo!(),
                    }
                }
            }
        } else {
            // println!("You typed {key_combination:?} which represents nothing yet"/*, key.blue()*/);
            let input = tui_textarea::Input::from(event);
            textarea.input(input);
        }
    }
}

/// Highlight the selected text in the `TextArea` with the specified color role.
///
/// This function applies styling to the selected text in the `TextArea`, setting
/// the foreground color based on the provided `Role` and making it bold.
///
/// # Arguments
///
/// * `textarea` - A mutable reference to the `TextArea` to apply highlighting to
/// * `tui_highlight_fg` - The `Role` that determines the foreground color for highlighting
#[profiled]
pub fn highlight_selection(textarea: &mut TextArea<'_>, tui_highlight_fg: Role) {
    textarea.set_selection_style(RataStyle::themed(tui_highlight_fg).bold());
}

/// 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.
#[allow(clippy::too_many_lines, clippy::missing_panics_doc)]
#[profiled]
pub fn script_key_handler(
    key_event: KeyEvent,
    maybe_term: Option<&mut ManagedTerminal>,
    textarea: &mut TextArea,
    edit_data: &mut EditData,
    popup: &mut bool,
    saved: &mut bool, // TODO decide if we need this
    status_message: &mut String,
) -> ThagResult<KeyAction> {
    // let mut owned_path: PathBuf;
    if !matches!(key_event.kind, event::KeyEventKind::Press) {
        return Ok(KeyAction::Continue);
    }

    let key_combination = KeyCombination::from(key_event); // Derive KeyCombination
                                                           // eprintln!("key_combination={key_combination:?}");

    let history_path = edit_data.history_path.cloned();

    #[allow(clippy::unnested_or_patterns)]
    match key_combination {
        key!(esc) | key!(ctrl - q) => Ok(KeyAction::Quit(*saved)),
        key!(ctrl - d) => save_and_submit(history_path.as_ref(), edit_data, textarea),
        key!(ctrl - s) | key!(ctrl - alt - s) | key!(f12) => {
            if matches!(key_combination, key!(ctrl - s)) && edit_data.save_path.is_some() {
                // eprintln!("key_combination matches ctrl-s");
                save(
                    edit_data,
                    history_path.as_ref(),
                    textarea,
                    saved,
                    status_message,
                )
            } else {
                let key_action = save_as(edit_data, maybe_term, textarea, saved, status_message)?;
                Ok(key_action)
            }
        }
        key!(ctrl - l) => {
            // Toggle popup
            *popup = !*popup;
            Ok(KeyAction::TogglePopup)
        }
        key!(f3) => {
            // Ask to revert
            Ok(KeyAction::AbandonChanges)
        }
        key!(f4) => {
            // Clear textarea
            textarea.select_all();
            textarea.cut();
            Ok(KeyAction::Continue)
        }
        key!(f5) => {
            // Clear textarea and wipe from history
            if textarea.is_empty() {
                return Ok(KeyAction::Continue);
            }
            wipe_textarea(edit_data, textarea, history_path.as_ref())?;
            Ok(KeyAction::Continue)
        }
        key!(f6) => {
            // Edit history
            edit_history()?;
            Ok(KeyAction::Continue)
        }
        key!(f7) => {
            // Scroll up in history
            prev_hist(edit_data, textarea, history_path.as_ref())?;
            Ok(KeyAction::Continue)
        }
        key!(f8) => {
            // Scroll down in history
            next_hist(edit_data, textarea);
            Ok(KeyAction::Continue)
        }
        _ => {
            // Update the `TextArea` with the input from the key event
            textarea.input(Input::from(key_event)); // Input derived from Event
            Ok(KeyAction::Continue)
        }
    }
}

#[profiled]
fn next_hist(edit_data: &mut EditData<'_>, textarea: &mut TextArea<'_>) {
    if let Some(ref mut hist) = edit_data.history {
        // save_if_changed(hist, textarea, &history_path)?;
        if let Some(entry) = hist.get_next() {
            debug_log!("F8 found entry {entry:?}");
            paste_to_textarea(textarea, entry);
        }
    }
}

#[profiled]
fn prev_hist(
    edit_data: &mut EditData<'_>,
    textarea: &mut TextArea<'_>,
    history_path: Option<&PathBuf>,
) -> ThagResult<()> {
    if let Some(ref mut hist) = edit_data.history {
        if hist.at_end() && textarea.is_empty() {
            if let Some(entry) = &hist.get_last() {
                debug_log!("F7 (1) found entry {entry:?}");
                paste_to_textarea(textarea, entry);
            }
        } else {
            save_if_changed(hist, textarea, history_path)?;
            if let Some(entry) = &hist.get_previous() {
                debug_log!("F7 (2) found entry {entry:?}");
                paste_to_textarea(textarea, entry);
            }
        }
    }
    Ok(())
}

#[profiled]
fn wipe_textarea(
    edit_data: &mut EditData<'_>,
    textarea: &mut TextArea<'_>,
    history_path: Option<&PathBuf>,
) -> ThagResult<()> {
    if let Some(ref mut hist) = edit_data.history {
        let _in_hist = !&hist.at_end();
        let textarea_contents = textarea.lines().to_vec().join("\n");
        textarea.select_all();
        textarea.cut();
        let yank_text = textarea.yank_text();
        assert_eq!(yank_text, textarea_contents);
        if let Some(current_hist_entry) = &hist.get_current() {
            assert_eq!(yank_text, current_hist_entry.contents());
            let index = current_hist_entry.index;
            hist.delete_entry(index);
            hist.entries
                .retain(|f| f.contents().trim() != textarea_contents);
        }
        if let Some(hist_path) = history_path {
            hist.save_to_file(hist_path)?;
        }
    }
    Ok(())
}

#[profiled]
fn save_as(
    edit_data: &mut EditData<'_>,
    maybe_term: Option<&mut ManagedTerminal<'_>>,
    textarea: &mut TextArea<'_>,
    saved: &mut bool,
    status_message: &mut String,
) -> ThagResult<KeyAction> {
    if let Some(term) = maybe_term {
        let mut save_dialog: FileDialog<'_> = FileDialog::new(60, 20, DialogMode::Save)?;
        save_dialog.open();
        let mut status = Status::Incomplete;
        while matches!(status, Status::Incomplete) && save_dialog.selected_file.is_none() {
            term.draw(|f| save_dialog.draw(f))?;
            if let Event::Key(key) = event::read()? {
                status = save_dialog.handle_input(key)?;
            }
        }

        status_message.clear();
        if let Some(ref to_rs_path) = save_dialog.selected_file {
            save_source_file(to_rs_path, textarea, saved)?;
            let _ = write!(status_message, "Saved to {}", to_rs_path.display());
            edit_data.save_path = Some(to_rs_path.clone());
            Ok(KeyAction::Save)
        } else {
            let _ = write!(status_message, "Failed to save file");
            Ok(KeyAction::Continue)
        }
    } else {
        let _ = write!(status_message, "No terminal to display file save dialog");
        Ok(KeyAction::Continue)
    }
}

#[profiled]
fn save(
    edit_data: &mut EditData<'_>,
    history_path: Option<&PathBuf>,
    textarea: &mut TextArea<'_>,
    saved: &mut bool,
    status_message: &mut String,
) -> ThagResult<KeyAction> {
    if let Some(ref save_path) = edit_data.save_path {
        if let Some(hist_path) = history_path {
            let history = &mut edit_data.history;
            if let Some(hist) = history {
                preserve(textarea, hist, hist_path)?;
            }
        }
        let result = save_source_file(save_path, textarea, saved);
        // eprintln!("result={result:?}");
        match result {
            Ok(()) => {
                status_message.clear();
                let _ = write!(status_message, "Saved to {}", save_path.display());
                Ok(KeyAction::Save)
            }
            Err(e) => Err(e),
        }
    } else {
        status_message.clear();
        let _ = write!(
            status_message,
            "No save path: edit_data.save_path={:?}",
            edit_data.save_path
        );
        Ok(KeyAction::Continue)
    }
}

#[profiled]
fn save_and_submit(
    history_path: Option<&PathBuf>,
    edit_data: &mut EditData<'_>,
    textarea: &mut TextArea<'_>,
) -> ThagResult<KeyAction> {
    if let Some(hist_path) = history_path {
        let history = &mut edit_data.history;
        if let Some(hist) = history {
            preserve(textarea, hist, hist_path)?;
        }
    }
    Ok(KeyAction::Submit)
}

/// Enable raw mode, but not if in test mode, because that will cause the dreaded rightward drift
/// in log output due to carriage returns being ignored.
///
/// # Errors
///
/// This function will bubble up any i/o errors encountered by `crossterm::enable_raw_mode`.
#[profiled]
pub fn maybe_enable_raw_mode() -> ThagResult<()> {
    let test_env = &var("TEST_ENV");
    debug_log!("test_env={test_env:?}");
    if !test_env.is_ok() && !is_raw_mode_enabled()? {
        // Check if stdout is a terminal before enabling raw mode
        if std::io::IsTerminal::is_terminal(&std::io::stdout()) {
            debug_log!("Enabling raw mode");
            enable_raw_mode()?;
        } else {
            debug_log!("Skipping raw mode - not a terminal");
        }
    }
    Ok(())
}

/// Display a popup with key mappings and descriptions.
///
/// This function renders a centered popup window containing a list of key bindings
/// and their descriptions. The popup is styled with borders and titles, and each
/// key mapping is displayed in a two-column layout.
///
/// # Arguments
///
/// * `mappings` - A slice of `KeyDisplayLine` structs containing the key mappings to display
/// * `title_top` - The title text to display at the top of the popup
/// * `title_bottom` - The title text to display at the bottom of the popup
/// * `max_key_len` - The maximum length of key strings for column width calculation
/// * `max_desc_len` - The maximum length of description strings for column width calculation
/// * `f` - A mutable reference to the ratatui Frame for rendering
#[profiled]
#[allow(clippy::cast_possible_truncation)]
pub fn display_popup(
    mappings: &[KeyDisplayLine],
    title_top: &str,
    title_bottom: &str,
    max_key_len: u16,
    max_desc_len: u16,
    scroll_state: &mut PopupScrollState,
    f: &mut ratatui::prelude::Frame<'_>,
) {
    let total_rows = mappings.len();

    // Calculate available height for content
    let max_height = f.area().height.saturating_sub(6); // Reserve space for borders and titles
    let content_height = max_height.min(total_rows as u16);

    let block = Block::default()
        .borders(Borders::ALL)
        .title_top(Line::from(title_top).centered())
        .title_bottom(Line::from(format!("{title_bottom} (scroll with mouse wheel)")).centered())
        .add_modifier(Modifier::BOLD)
        .fg(Color::themed(Role::HD1));

    #[allow(clippy::cast_possible_truncation)]
    let area = centered_rect(max_key_len + max_desc_len + 5, content_height + 5, f.area());

    let inner = area.inner(Margin {
        vertical: 2,
        horizontal: 2,
    });

    // Clear background and render block
    f.render_widget(Clear, area);
    f.render_widget(block, area);

    // Calculate visible range based on scroll offset
    let visible_rows = inner.height as usize;
    let max_scroll = total_rows.saturating_sub(visible_rows);
    scroll_state.scroll_offset = scroll_state.scroll_offset.min(max_scroll);

    let start_idx = scroll_state.scroll_offset;
    let end_idx = (start_idx + visible_rows).min(total_rows);
    let visible_mappings = &mappings[start_idx..end_idx];

    // Create layout for visible rows
    #[allow(clippy::cast_possible_truncation)]
    let row_layout = Layout::default()
        .direction(Direction::Vertical)
        .constraints(std::iter::repeat_n(
            Constraint::Length(1),
            visible_mappings.len(),
        ));
    let rows = row_layout.split(inner);

    for (i, row) in rows.iter().enumerate() {
        let actual_idx = start_idx + i;
        let col_layout = Layout::default()
            .direction(Direction::Horizontal)
            .constraints::<&[Constraint]>(&[
                Constraint::Length(max_key_len + 1),
                Constraint::Length(max_desc_len),
            ]);
        let cells = col_layout.split(*row);

        let mut widget = Paragraph::new(visible_mappings[i].keys);
        if actual_idx == 0 {
            widget = widget
                .add_modifier(Modifier::BOLD)
                .fg(Color::themed(Role::EMPH));
        } else {
            widget = widget.fg(Color::themed(Role::HD2)).not_bold();
        }
        f.render_widget(widget, cells[0]);

        let mut widget = Paragraph::new(visible_mappings[i].desc);
        if actual_idx == 0 {
            widget = widget
                .add_modifier(Modifier::BOLD)
                .fg(Color::themed(Role::EMPH));
        } else {
            widget = widget
                .remove_modifier(Modifier::BOLD)
                .set_style(RataStyle::themed(Role::INFO).not_bold());
        }
        f.render_widget(widget, cells[1]);
    }
}

#[must_use]
/// Creates a centered rectangle within the given area with the specified maximum dimensions.
///
/// This function creates a popup-style rectangle that is centered both horizontally
/// and vertically within the provided area, constrained by the given maximum width
/// and height.
///
/// # Arguments
///
/// * `max_width` - The maximum width of the centered rectangle
/// * `max_height` - The maximum height of the centered rectangle
/// * `r` - The area within which to center the rectangle
///
/// # Returns
///
/// A `Rect` representing the centered rectangle
#[profiled]
pub fn centered_rect(max_width: u16, max_height: u16, r: Rect) -> Rect {
    let popup_layout = Layout::vertical([
        Constraint::Fill(1),
        Constraint::Max(max_height),
        Constraint::Fill(1),
    ])
    .split(r);

    Layout::horizontal([
        Constraint::Fill(1),
        Constraint::Max(max_width),
        Constraint::Fill(1),
    ])
    .split(popup_layout[1])[1]
}

/// Convert the different newline sequences for Windows and other platforms into the common
/// standard sequence of `"\n"` (backslash + 'n', as opposed to the '\n' (0xa) character for which
/// it stands).
#[must_use]
#[profiled]
pub fn normalize_newlines(input: &str) -> String {
    let re: &Regex = re!(r"\r\n?");

    re.replace_all(input, "\n").to_string()
}

/// Reset the terminal.
///
/// # Errors
///
/// This function will bubble up any `ratatui` or `crossterm` errors encountered.
// TODO: move to shared or tui_editor?
#[profiled]
pub fn reset_term(mut term: Terminal<CrosstermBackend<std::io::StdoutLock<'_>>>) -> ThagResult<()> {
    disable_raw_mode()?;
    ratatui::crossterm::execute!(
        term.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture
    )?;
    term.show_cursor()?;
    Ok(())
}

/// Save a `TextArea` to history if it has changed.
///
/// # Errors
///
/// This function will bubble up any i/o errors encuntered.
#[profiled]
pub fn save_if_changed(
    hist: &mut History,
    textarea: &mut TextArea<'_>,
    history_path: Option<&PathBuf>,
) -> ThagResult<()> {
    debug_log!("save_if_changed...");
    if textarea.is_empty() {
        debug_log!("nothing to save(1)...");
        return Ok(());
    }
    if let Some(entry) = &hist.get_current() {
        let index = entry.index;
        let copy_text = copy_text(textarea);
        // In case they entered blanks
        if copy_text.trim().is_empty() {
            debug_log!("nothing to save(2)...");
            return Ok(());
        }
        if entry.contents() != copy_text {
            hist.update_entry(index, &copy_text);
            if let Some(hist_path) = history_path {
                hist.save_to_file(hist_path)?;
            }
        }
    }
    Ok(())
}

// Save a `TextArea` to history if it has changed.
//
// # Errors
//
// This function will bubble up any i/o errors encuntered.
// pub fn remove_current_from_history(
//     hist: &mut History,
//     textarea: &mut TextArea<'_>,
//     history_path: &Option<PathBuf>,
// ) -> ThagResult<()> {
//     debug_log!("save_if_changed...");
//     if textarea.is_empty() {
//         debug_log!("nothing to save(1)...");
//         return Ok(());
//     }
//     if let Some(entry) = &hist.get_current() {
//         let index = entry.index;
//         let copy_text = copy_text(textarea);
//         // In case they entered blanks
//         if copy_text.trim().is_empty() {
//             debug_log!("nothing to save(2)...");
//             return Ok(());
//         }
//         if entry.contents() != copy_text {
//             hist.update_entry(index, &copy_text);
//             if let Some(ref hist_path) = history_path {
//                 hist.save_to_file(hist_path)?;
//             }
//         }
//     }
//     Ok(())
// }

/// Paste the contents of a history entry into a text area.
///
/// This function clears the current content of the `TextArea` by selecting all
/// and cutting it, then inserts the content from the provided history entry.
///
/// # Arguments
///
/// * `textarea` - A mutable reference to the `TextArea` to paste into
/// * `entry` - The history entry containing the content to paste
#[profiled]
pub fn paste_to_textarea(textarea: &mut TextArea<'_>, entry: &Entry) {
    textarea.select_all();
    textarea.cut();
    // 6
    textarea.insert_str(entry.contents());
}

/// Save a `TextArea` to history and the history to the backing file.
///
/// # Errors
///
/// This function will bubble up any i/o errors encuntered.
#[profiled]
pub fn preserve(
    textarea: &mut TextArea<'_>,
    hist: &mut History,
    history_path: &PathBuf,
) -> ThagResult<()> {
    debug_log!("preserve...");
    save_if_not_empty(textarea, hist);
    save_history(Some(&mut hist.clone()), Some(history_path))?;
    Ok(())
}

/// Save content from textarea to history if it's not empty.
///
/// This function copies the text content from the `TextArea` and adds it to the history
/// collection if the content is not empty (after trimming whitespace).
///
/// # Arguments
///
/// * `textarea` - A mutable reference to the `TextArea` to copy from
/// * `hist` - A mutable reference to the History to add the entry to
#[profiled]
pub fn save_if_not_empty(textarea: &mut TextArea<'_>, hist: &mut History) {
    debug_log!("save_if_not_empty...");

    let text = copy_text(textarea);
    if !text.trim().is_empty() {
        hist.add_entry(&text);
        debug_log!("... added entry");
    }
}

/// Copy the entire text content from a `TextArea`.
///
/// This function selects all text in the `TextArea`, copies it, and returns
/// the content as a single string with newlines preserved.
///
/// # Arguments
///
/// * `textarea` - A mutable reference to the `TextArea` to copy from
///
/// # Returns
///
/// A String containing the entire text content of the `TextArea`
#[profiled]
pub fn copy_text(textarea: &mut TextArea<'_>) -> String {
    textarea.select_all();
    textarea.copy();
    let text = textarea.yank_text().lines().collect::<Vec<_>>().join("\n");
    text
}

/// Save the history to the backing file.
///
/// # Errors
///
/// This function will bubble up any i/o errors encuntered.
#[profiled]
pub fn save_history(
    history: Option<&mut History>,
    history_path: Option<&PathBuf>,
) -> ThagResult<()> {
    debug_log!("save_history...{history:?}");
    if let Some(hist) = history {
        if let Some(hist_path) = history_path {
            hist.save_to_file(hist_path)?;
            debug_log!("... saved to file");
        }
    }
    Ok(())
}

/// Save Rust source code to a source file.
///
/// # Errors
///
/// This function will bubble up any i/o errors encuntered.
#[profiled]
pub fn save_source_file(
    to_rs_path: &PathBuf,
    textarea: &mut TextArea<'_>,
    saved: &mut bool,
) -> ThagResult<()> {
    // Ensure newline at end
    textarea.move_cursor(CursorMove::Bottom);
    textarea.move_cursor(CursorMove::End);
    if textarea.cursor().1 != 0 {
        textarea.insert_newline();
    }
    let _write_source = write_source(to_rs_path, textarea.lines().join("\n").as_str())?;
    *saved = true;
    Ok(())
}

/// Key mappings for display purposes via (Ctrl-l) in TUI editor and file dialog.
///
#[macro_export]
macro_rules! key_mappings {
    (
        $(($seq:expr, $keys:expr, $desc:expr)),* $(,)?
    ) => {
        &[
            $(
                KeyDisplayLine {
                    seq: $seq,
                    keys: $keys,
                    desc: $desc,
                }
            ),*
        ]
    };
}

/// Key mappings for display purposes via (Ctrl-l) in TUI editor and file dialog.
pub const MAPPINGS: &[KeyDisplayLine] = key_mappings![
    (10, "Key bindings", "Description"),
    (
        20,
        "Shift+arrow keys",
        "Select/deselect chars (←→) or lines (↑↓)"
    ),
    (
        30,
        "Alt+shift+ h/j/k/l",
        "Select/deselect words (←h l→) or lines (↑k j↓)"
    ),
    (35, "Alt+shift+ p/n", "Select/deselect paras (↑p n↓)"),
    (40, "Alt+Shift+a", "Select all"),
    (50, "Alt+c", "Cancel selection"),
    (60, "Ctrl+d", "Submit"),
    (70, "Ctrl+q", "Cancel and quit"),
    (80, "Ctrl+h, Backspace", "Delete character before cursor"),
    (90, "Ctrl+i, Tab", "Indent"),
    (100, "Ctrl+m, Enter", "Insert newline"),
    (110, "Ctrl+k", "Delete from cursor to end of line"),
    (120, "Ctrl+j", "Delete from cursor to start of line"),
    (
        130,
        "Ctrl+w, Alt+Backspace",
        "Delete one word before cursor"
    ),
    (140, "Alt+d, Delete", "Delete one word from cursor position"),
    (150, "Ctrl+u", "Undo"),
    (160, "Ctrl+r", "Redo"),
    (170, "Ctrl+c", "Copy (yank) selected text"),
    (180, "Ctrl+x", "Cut (yank) selected text"),
    (190, "Ctrl+y", "Paste yanked text"),
    (
        200,
        "Ctrl+v, Shift+Ins, Cmd+v",
        "Paste from system clipboard according to platform"
    ),
    (210, "Ctrl+f, →", "Move cursor forward one character"),
    (220, "Ctrl+b, ←", "Move cursor backward one character"),
    (230, "Ctrl+p, ↑", "Move cursor up one line"),
    (240, "Ctrl+n, ↓", "Move cursor down one line"),
    (250, "Alt+f", "Move cursor forward one word"),
    (260, "Alt+Shift+f", "Move cursor to next word end"),
    (270, "Atl+b", "Move cursor backward one word"),
    (280, "Alt+p", "Move cursor up one paragraph"),
    (290, "Alt+n", "Move cursor down one paragraph"),
    (300, "Ctrl+e, End, Ctrl+Alt+f", "Move cursor to end of line"),
    (
        310,
        "Ctrl+a, Home, Ctrl+Alt+b",
        "Move cursor to start of line"
    ),
    (320, "Alt+<, Ctrl+Alt+p", "Move cursor to top of file"),
    (330, "Alt+>, Ctrl+Alt+n", "Move cursor to bottom of file"),
    (340, "Ctrl+l", "Toggle keys display (this screen)"),
    (350, "Ctrl+t", "Toggle selection highlight colours"),
    (360, "Alt+v, PageUp, F1", "Page up"),
    (370, "PageDown, F2", "Page down"),
    (380, "F4", "Clear text buffer (Ctrl+y or Ctrl+u to restore)"),
    (
        390,
        "F5",
        "Clear and wipe from history (Ctrl+y or Ctrl+u to restore text buffer)"
    ),
    (400, "F6", "Edit history"),
    (410, "F7", "Previous in history"),
    (420, "F8", "Next in history"),
    (
        430,
        "F9",
        "Enter `copy to system clipboard` mode with mouse selection and OS keys"
    ),
    (440, "F10", "Exit `copy to system clipboard` mode"),
    (450, "F12", "Save as..."),
];

#[derive(Clone, Debug, PartialEq, Eq)]
/// A struct representing a line in the key display help screen.
/// Contains information about key bindings and their descriptions.
pub struct KeyDisplayLine {
    /// Sequence number for ordering the display lines
    pub seq: usize,
    /// The key combination string to display
    pub keys: &'static str, // Or String if you plan to modify the keys later
    /// The description of what the key combination does
    pub desc: &'static str, // Or String for modifiability
}

impl PartialOrd for KeyDisplayLine {
    #[profiled]
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        // profile_method!("partial_cmp");
        Some(self.cmp(other))
    }
}

impl Ord for KeyDisplayLine {
    #[profiled]
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // profile_method!("cmp");
        usize::cmp(&self.seq, &other.seq)
    }
}

impl KeyDisplayLine {
    /// Creates a new `KeyDisplayLine` with the specified sequence number, key combination, and description.
    ///
    /// # Arguments
    ///
    /// * `seq` - The sequence number for ordering the display lines
    /// * `keys` - The key combination string to display
    /// * `desc` - The description of what the key combination does
    #[must_use]
    pub const fn new(seq: usize, keys: &'static str, desc: &'static str) -> Self {
        Self { seq, keys, desc }
    }
}