hande 1.0.0

HANDE, Let's Go!, is a powerful bookmark manager to keep track of your favorites both on the filesystem and the web.
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
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
//! `hande`'s interactive shell: run with no arguments to get a `hlg>` prompt
//! where you can open one bookmark after another without the process exiting
//! in between.
//!
//! Commands to the shell itself are prefixed with a colon, vim-style
//! (`:quit`/`:q`, `:list`/`:l`, ...). Anything else is treated as a target for
//! hande itself: a single word is a bookmark name (so a bare `.` behaves
//! exactly like `hande .` on the direct command line), and more than one word
//! is a search phrase -- there's no bookmark name with a space in it, so this
//! is unambiguous.
//!
//! The shell keeps one piece of session state: a "working category," set
//! with `:to`/`:switch`, that every subsequently-typed plain bookmark name
//! (and every command that implicitly means "the category," like
//! `:new-bookmark` or `:delete`) resolves against instead of the configured
//! default -- until the next `:to`.
//!
//! Every shell command re-invokes the `hande` binary itself as a subprocess,
//! rather than calling `hande-api` in-process: opening a bookmark, listing
//! one, adding a category, or editing the bookmarks file can all end the
//! process outright (a bad lookup, a malformed category file, a handler that
//! replaces the process image to launch a browser). Running each one as a
//! subprocess means none of that can ever take the shell itself down --
//! worst case, a command prints an error and the shell hands you back the
//! prompt. `:new-bookmark` goes one step further: it validates the new line
//! against a throwaway sandbox copy of the whole database before ever
//! touching the real file, so a typo can't corrupt a category. Line editing,
//! history and tab completion (also built by shelling out, once, to refresh
//! a cached candidate list, rather than on every keystroke) follow the same
//! principle.

use hande_api::{Api, Configurations};
use rustyline::completion::{Completer, Pair};
use rustyline::error::ReadlineError;
use rustyline::highlight::Highlighter;
use rustyline::hint::Hinter;
use rustyline::validate::Validator;
use rustyline::{Cmd, Config, Context, Editor, Helper, KeyEvent, Modifiers};
use std::cell::Cell;
use std::fs;
use std::io::{self, Write};
use std::path::Path;
use std::process::Command;

const LICENSE: &str = r#"MIT License

Copyright (c) 2026 Ishe Chinyoka, the Textsmith

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE."#;

/// Bookmark names, shortcut keys, and category names, cached for tab
/// completion. Rebuilt at startup, after anything that could change the
/// database (`:add`, `:new-bookmark`, `:delete`, `:delete-global`, `:edit`),
/// and after `:to`/`:switch` changes the working category.
struct Completions {
    local_names: Vec<String>,
    global_names: Vec<String>,
    keys: Vec<(char, String)>,
    category_names: Vec<String>,
    /// Direct child subcategories of the current working category/
    /// subcategory, as ".child" strings ready to offer alongside
    /// `category_names` for `:to`/`:to?` -- deliberately only one level
    /// deep, not grandchildren.
    subcategory_children: Vec<String>,
}

impl Completions {
    fn refresh(category: &str) -> Self {
        let mut local_names = fetch_names(&["--category", category, "--list"]);
        local_names.retain(|n| n != "(no bookmarks)");
        let mut global_names = fetch_names(&["--list-global"]);
        global_names.retain(|n| n != "(no bookmarks)");

        let mut keys = parse_keys(&fetch_lines(&[
            "--category",
            category,
            "--list-category-keys",
        ]));
        keys.extend(parse_keys(&fetch_lines(&["--list-global-keys"])));

        let category_names = Api::categories();

        let (top, parent_path) = split_top(category);
        let subcategory_children = Api::subcategory_children(top, &parent_path)
            .into_iter()
            .map(|name| format!(".{name}"))
            .collect();

        Self {
            local_names,
            global_names,
            keys,
            category_names,
            subcategory_children,
        }
    }

    /// Candidates for `:to`/`:to?`: every top-level category, plus one
    /// level of the current working category's own subcategories
    /// (prefixed with '.', matching the relative-descend syntax).
    fn to_candidates(&self, prefix: &str) -> Vec<String> {
        let mut names = Self::name_candidates(&self.category_names, prefix);
        names.extend(Self::name_candidates(&self.subcategory_children, prefix));
        names
    }

    /// Candidates for opening a bookmark directly: shortcut matches first
    /// (per hande's convention that a single typed letter may itself be a
    /// shortcut key), then any name starting with the typed prefix.
    fn open_candidates(&self, prefix: &str) -> Vec<String> {
        let mut out: Vec<String> = Vec::new();
        if prefix.chars().count() == 1 {
            let c = prefix.chars().next().unwrap();
            for (key, name) in &self.keys {
                if *key == c && !out.contains(name) {
                    out.push(name.clone());
                }
            }
        }
        for name in self.local_names.iter().chain(self.global_names.iter()) {
            if name.starts_with(prefix) && !out.contains(name) {
                out.push(name.clone());
            }
        }
        out
    }

    fn name_candidates(names: &[String], prefix: &str) -> Vec<String> {
        names
            .iter()
            .filter(|n| n.starts_with(prefix))
            .cloned()
            .collect()
    }
}

/// Parse the human-readable `key:\tName` lines the `-k`/`-K` key listing
/// prints (its header/footer lines simply don't match and are skipped).
fn parse_keys(lines: &[String]) -> Vec<(char, String)> {
    lines
        .iter()
        .filter_map(|line| {
            let (key, name) = line.split_once(':')?;
            let key = key.trim();
            let name = name.trim();
            if name.is_empty() {
                return None;
            }
            let mut chars = key.chars();
            let only_char = chars.next()?;
            if chars.next().is_some() {
                return None;
            }
            Some((only_char, name.to_string()))
        })
        .collect()
}

/// Run `hande` with `args` and collect its stdout as lines. Used only for
/// read-only enumeration (building completion candidates) -- never for
/// anything that opens a bookmark or touches the database.
fn fetch_lines(args: &[&str]) -> Vec<String> {
    let Ok(exe) = std::env::current_exe() else {
        return Vec::new();
    };
    match Command::new(exe).args(args).output() {
        Ok(output) => String::from_utf8_lossy(&output.stdout)
            .lines()
            .map(str::to_string)
            .collect(),
        Err(_) => Vec::new(),
    }
}

/// Like `fetch_lines`, but for a bookmark listing specifically: each line
/// may have a `\t`-separated comment column, which isn't part of the name.
fn fetch_names(args: &[&str]) -> Vec<String> {
    fetch_lines(args)
        .into_iter()
        .map(|line| line.split('\t').next().unwrap_or(&line).to_string())
        .collect()
}

/// If `line` (up to the cursor) starts with any of `prefixes` (each already
/// including its trailing space), return the partial word typed after it.
fn strip_any<'a>(line: &'a str, prefixes: &[&str]) -> Option<&'a str> {
    prefixes.iter().find_map(|p| line.strip_prefix(p))
}

/// Qualify a bookmark reference the way plain shell input does: "." alone,
/// or "." followed by a name, a bare lowercase/digit-led name, or a `/`
/// alias lookup, all resolve in the working category by rewriting to
/// "category.name" (an alias search still has to know which category to
/// search); anything else (already "category.name", global/capitalized, a
/// search) is left exactly as given.
fn qualify(current_category: &str, reference: &str) -> String {
    if let Some(rest) = reference.strip_prefix('.') {
        format!("{current_category}.{rest}")
    } else if reference.starts_with('/') {
        format!("{current_category}.{reference}")
    } else if !reference.contains('.')
        && reference
            .chars()
            .next()
            .map(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
            .unwrap_or(false)
    {
        format!("{current_category}.{reference}")
    } else {
        reference.to_string()
    }
}

/// Split an already-qualified reference ("category.name") into its
/// category hint and bare name. A reference with no dot (a bare global,
/// capitalized name) has no hint -- the caller searches every category.
fn split_reference(qualified: &str) -> (Option<String>, String) {
    match qualified.find('.') {
        Some(pos) => {
            let (category, name) = qualified.split_at(pos);
            (Some(category.to_string()), name[1..].to_string())
        }
        None => (None, qualified.to_string()),
    }
}

/// Remove the first line matching `target` from `content` exactly, keeping
/// everything else (including blank lines and comments) untouched.
fn remove_line(content: &str, target: &str) -> String {
    let mut removed = false;
    let kept: Vec<&str> = content
        .lines()
        .filter(|line| {
            if removed || *line != target {
                true
            } else {
                removed = true;
                false
            }
        })
        .collect();
    format!("{}\n", kept.join("\n"))
}

/// Replace the first line matching `old_line` with `new_line`, in place --
/// unlike a remove-then-append, this keeps the line's original position in
/// the file, so anything that preceded it there (like a comment) still
/// applies to the right line afterward.
fn replace_line_in_place(content: &str, old_line: &str, new_line: &str) -> String {
    let mut replaced = false;
    let result: Vec<String> = content
        .lines()
        .map(|line| {
            if !replaced && line == old_line {
                replaced = true;
                new_line.to_string()
            } else {
                line.to_string()
            }
        })
        .collect();
    format!("{}\n", result.join("\n"))
}

struct HandeHelper {
    completions: Completions,
    /// Set while a `:to?`/`:switch?` sub-prompt is reading its answer, so
    /// completion offers category names instead of bookmark names.
    picking_category: Cell<bool>,
    /// Set while an `:update`/`:add-*` command's "which bookmark?" prompt
    /// is reading its answer, so completion offers bookmark names.
    picking_bookmark: Cell<bool>,
}

impl Completer for HandeHelper {
    type Candidate = Pair;

    fn complete(
        &self,
        line: &str,
        pos: usize,
        _ctx: &Context<'_>,
    ) -> rustyline::Result<(usize, Vec<Pair>)> {
        let typed = &line[..pos];
        let as_pairs = |names: Vec<String>| -> Vec<Pair> {
            names
                .into_iter()
                .map(|name| Pair {
                    display: name.clone(),
                    replacement: name,
                })
                .collect()
        };

        if self.picking_category.get() {
            let names = self.completions.to_candidates(typed);
            return Ok((0, as_pairs(names)));
        }
        if self.picking_bookmark.get() {
            let mut names = Completions::name_candidates(&self.completions.local_names, typed);
            names.extend(Completions::name_candidates(
                &self.completions.global_names,
                typed,
            ));
            return Ok((0, as_pairs(names)));
        }

        if let Some(rest) = strip_any(typed, &[":d ", ":delete ", ":delete-bookmark "]) {
            let start = pos - rest.len();
            let names = Completions::name_candidates(&self.completions.local_names, rest);
            return Ok((start, as_pairs(names)));
        }
        if let Some(rest) = strip_any(
            typed,
            &[":D ", ":delete-global ", ":delete-global-bookmark "],
        ) {
            let start = pos - rest.len();
            let names = Completions::name_candidates(&self.completions.global_names, rest);
            return Ok((start, as_pairs(names)));
        }
        if let Some(rest) = strip_any(typed, &[":to ", ":switch "]) {
            let start = pos - rest.len();
            let names = self.completions.to_candidates(rest);
            return Ok((start, as_pairs(names)));
        }
        if let Some(rest) = strip_any(typed, &[":m ", ":move ", ":y ", ":copy "]) {
            // First argument: the bookmark being moved/copied (local or
            // global name). Second argument (after a space): the
            // destination category.
            return Ok(match rest.rsplit_once(' ') {
                None => {
                    let start = pos - rest.len();
                    let mut names = Completions::name_candidates(&self.completions.local_names, rest);
                    names.extend(Completions::name_candidates(
                        &self.completions.global_names,
                        rest,
                    ));
                    (start, as_pairs(names))
                }
                Some((_, second)) => {
                    let start = pos - second.len();
                    let mut names =
                        Completions::name_candidates(&self.completions.category_names, second);
                    if "_".starts_with(second) {
                        names.push("_".to_string());
                    }
                    (start, as_pairs(names))
                }
            });
        }
        if typed.starts_with(':') {
            // No completion for the shell commands themselves yet.
            return Ok((0, Vec::new()));
        }

        // Plain input: completion only makes sense for the single word
        // being typed -- once there's a space, the line is a search
        // phrase, not a bookmark name.
        if typed.is_empty() || typed.contains(char::is_whitespace) {
            return Ok((0, Vec::new()));
        }
        Ok((0, as_pairs(self.completions.open_candidates(typed))))
    }
}

impl Hinter for HandeHelper {
    type Hint = String;
}

impl Highlighter for HandeHelper {}

impl Validator for HandeHelper {}

impl Helper for HandeHelper {}

fn history_path() -> String {
    format!("{}/history", Configurations::get_app_home())
}

pub fn run() {
    Api::ensure_initialized();
    println!("Hande, Let's Go! version 1.0 (2026-10-01) -- \"Your Digital Treasures\"");
    println!("Copyright (C) 2026 Ishe Chinyoka, the Textsmith (hande@thetextsmith.com) under the MIT license.");
    println!();
    println!("Type :help for help, :license for license.");

    // Emacs mode (rustyline's default, used here) waits indefinitely by
    // default after seeing an Escape byte, to correctly recognize a
    // following key as a meta-combination or an arrow-key/function-key
    // sequence -- so a bare Escape on its own would otherwise never
    // resolve at all until more input happened to arrive. A short,
    // deliberate timeout here lets it resolve quickly instead, which is
    // what actually makes the Escape-to-cancel binding below usable.
    let config = Config::builder()
        .auto_add_history(true)
        .keyseq_timeout(Some(50))
        .max_history_size(Api::history_size())
        .map(|builder| builder.build())
        .unwrap_or_default();
    let mut editor: Editor<HandeHelper, _> = match Editor::with_config(config) {
        Ok(editor) => editor,
        Err(err) => {
            eprintln!("Could not start the shell's line editor: {err}");
            return;
        }
    };
    // Both Escape and Ctrl-G are bound by rustyline's own emacs-mode
    // defaults to Cmd::Abort -- but that command only actually does
    // anything in the middle of Tab-completion cycling or an incremental
    // history search; anywhere else (an ordinary prompt, including every
    // `:to?`/"Which bookmark?"/etc. sub-prompt this shell uses) it's
    // silently ignored, so pressing either key there did nothing at all.
    // Rebinding both to Cmd::Interrupt instead makes them actually cancel
    // the current prompt, the same way Ctrl-C already does everywhere in
    // this shell (readline returns Err, and every prompt here already
    // treats that as "cancelled").
    editor.bind_sequence(KeyEvent::ctrl('g'), Cmd::Interrupt);
    editor.bind_sequence(KeyEvent::new('\x1b', Modifiers::NONE), Cmd::Interrupt);
    let mut current_category = Api::default_category();
    editor.set_helper(Some(HandeHelper {
        completions: Completions::refresh(&current_category),
        picking_category: Cell::new(false),
        picking_bookmark: Cell::new(false),
    }));
    let history_file = history_path();
    let _ = editor.load_history(&history_file);

    loop {
        let default_category = Api::default_category();
        let prompt = if current_category == default_category {
            "hlg> ".to_string()
        } else {
            format!("hlg ({current_category})> ")
        };
        let line = match editor.readline(&prompt) {
            Ok(line) => line,
            Err(ReadlineError::Interrupted) => continue, // Ctrl-C: cancel this line, stay in the shell
            Err(ReadlineError::Eof) => break,             // Ctrl-D: leave, like :quit
            Err(err) => {
                eprintln!("Readline error: {err}");
                break;
            }
        };
        let line = line.trim();
        if line.is_empty() {
            continue;
        }

        if let Some(command) = line.strip_prefix(':') {
            if !handle_command(command.trim(), &mut editor, &mut current_category) {
                break;
            }
            continue;
        }

        // A single word is a bookmark name (or shortcut, alias, the `.`
        // category-home symbol, etc); more than one word is a search
        // phrase. A plain word (lowercase, digit, or `.`) resolves in the
        // working category; anything else (a global capitalized name, an
        // `@` category shortcut, a search) is scope-complete on its own.
        // `@_<chain>` is the one exception that still needs the working
        // category: it's an `@` shortcut chain that starts from here
        // instead of a top-level category key, so it has to be resolved
        // with `current_category` in hand before anything is launched.
        let words: Vec<&str> = line.split_whitespace().collect();
        if words.len() == 1 {
            if let Some(chain) = words[0].strip_prefix("@_") {
                match Api::resolve_underscore_target(&current_category, chain) {
                    Ok((category, key)) => run_hande(&["--category", &category, &key]),
                    Err(msg) => eprintln!("{msg}"),
                }
            } else {
                let qualified = qualify(&current_category, words[0]);
                run_hande(&[&qualified]);
            }
        } else {
            run_hande(&words);
        }
    }

    // Ensure the config directory exists before the final save -- on a
    // truly fresh install nothing may have created it yet.
    let _ = fs::create_dir_all(Configurations::get_app_home());
    let _ = editor.save_history(&history_file);
}

/// Handle a `:command`, optionally followed by an argument (`:d slint`).
/// Returns false when the shell should exit.
fn handle_command(
    command: &str,
    editor: &mut Editor<HandeHelper, impl rustyline::history::History>,
    current_category: &mut String,
) -> bool {
    let (head, rest) = match command.split_once(' ') {
        Some((h, r)) => (h, r.trim()),
        None => (command, ""),
    };
    match head {
        "quit" | "q" => return false,
        "help" | "h" | "?" => print_help(),
        "license" => println!("{LICENSE}"),
        "list" | "l" => {
            run_hande(&["--category", current_category, "--list"]);
            run_hande(&["--list-global"]);
        }
        "category-list" | "c" => run_hande(&["--category", current_category, "--list"]),
        "global-list" | "g" => run_hande(&["--list-global"]),
        "to" | "switch" => {
            if rest.is_empty() {
                *current_category = Api::default_category();
                println!("Switched to the '{current_category}' category.");
                refresh_completions(editor, current_category);
            } else if let Some(key_str) = rest.strip_prefix('@') {
                match key_str.chars().next().filter(|_| key_str.chars().count() == 1) {
                    Some(key) => match Api::category_by_key(key) {
                        Some(name) => {
                            *current_category = name.clone();
                            println!("Switched to the '{name}' category.");
                            refresh_completions(editor, current_category);
                        }
                        None => eprintln!("No category found for shortcut '@{key}'."),
                    },
                    None => eprintln!("A category shortcut is a single character, like '@b'."),
                }
            } else if switch_to(current_category, rest) {
                refresh_completions(editor, current_category);
            }
        }
        "to?" | "switch?" => {
            if let Some(name) = prompt_for_category(current_category, editor) {
                *current_category = name.clone();
                println!("Switched to the '{name}' category.");
                refresh_completions(editor, current_category);
            } else {
                println!("Cancelled.");
            }
        }
        "add-category" | "n" => {
            add_category();
            refresh_completions(editor, current_category);
        }
        "add-bookmark" | "a" | "ab" => {
            add_bookmark(current_category);
            refresh_completions(editor, current_category);
        }
        "update" | "u" => {
            update_bookmark(current_category, editor);
            refresh_completions(editor, current_category);
        }
        "add-key" | "ak" => {
            add_key(current_category, editor);
            refresh_completions(editor, current_category);
        }
        "add-handler" | "ah" => {
            add_handler(current_category, editor);
        }
        "add-comment" | "ac" => {
            add_comment(current_category, editor);
        }
        "add-alias" | "add-tag" | "aa" | "at" => {
            add_alias(current_category, editor);
        }
        "delete" | "d" | "delete-bookmark" => {
            if rest.is_empty() {
                println!("Usage: :d <name>  (or just :d and Tab to see candidates)");
            } else {
                run_hande(&["--category", current_category, "--delete-bookmark", rest]);
                refresh_completions(editor, current_category);
            }
        }
        "delete-global" | "D" | "delete-global-bookmark" => {
            if rest.is_empty() {
                println!("Usage: :D <name>  (or just :D and Tab to see candidates)");
            } else {
                run_hande(&["--delete-global-bookmark", rest]);
                refresh_completions(editor, current_category);
            }
        }
        "move" | "m" => {
            move_or_copy_bookmark(current_category, rest, true);
            refresh_completions(editor, current_category);
        }
        "copy" | "y" => {
            move_or_copy_bookmark(current_category, rest, false);
            refresh_completions(editor, current_category);
        }
        "edit" | "e" => {
            let (top, subpath) = split_top(current_category);
            if subpath.is_empty() {
                run_hande(&["--category", top, "--edit-bookmarks"]);
            } else {
                edit_subcategory(top, &subpath);
            }
            refresh_completions(editor, current_category);
        }
        "man" => run_hande(&["$manual$"]),
        "config" | "cfg" => run_hande(&["--edit-configuration"]),
        "import" | "i" => {
            import_bookmarks(current_category, editor);
        }
        "export" | "x" => {
            export_bookmarks(current_category, editor);
        }
        "" => {}
        "@" => {
            *current_category = Api::default_category();
            println!("Switched to the '{current_category}' category.");
            refresh_completions(editor, current_category);
        }
        other if other.starts_with('@') && other.len() > 1 => {
            let chain = &other[1..];
            match Api::resolve_shortcut_chain(chain, current_category) {
                Ok(resolved) => {
                    *current_category = resolved.clone();
                    println!("Switched to the '{resolved}' category.");
                    refresh_completions(editor, current_category);
                }
                Err(msg) => eprintln!("{msg}"),
            }
        }
        other => {
            eprintln!("Unrecognized shell command ':{other}'. Type :help for a list.");
        }
    }
    true
}

/// Switch to `target` if it's a real category, reporting either way.
/// Returns whether the switch happened.
/// Split a (possibly subcategory-nested) working-category string into its
/// real top-level category and the subcategory path within it, if any --
/// e.g. "searches/wikis/linux" -> ("searches", "wikis/linux").
fn split_top(scope: &str) -> (&str, String) {
    match scope.split_once('/') {
        Some((top, rest)) => (top, rest.to_string()),
        None => (scope, String::new()),
    }
}

/// Resolve a `:to` navigation target against the current working
/// category/subcategory, returning the new (possibly slash-joined,
/// subcategory-nested) category string to switch to. Three forms:
/// `.name` descends into a child subcategory of wherever you are now;
/// `..` goes up one level; a dotted path like "searches.wikis.linux" is
/// absolute and works from anywhere; anything else is a bare top-level
/// category name, exactly as `:to` has always worked.
fn resolve_to_target(current: &str, target: &str) -> Result<String, String> {
    if target == ".." {
        return match current.rfind('/') {
            Some(pos) => Ok(current[..pos].to_string()),
            None => Err(format!(
                "'{current}' has no parent subcategory; you're already at the top."
            )),
        };
    }
    if let Some(name) = target.strip_prefix('.') {
        if name.is_empty() || name.contains('.') {
            return Err(
                "A relative subcategory name looks like '.name', with no further dots.".to_string(),
            );
        }
        let candidate = format!("{current}/{name}");
        let (top, path) = split_top(&candidate);
        if !Api::categories().iter().any(|c| c == top) {
            return Err(format!("No category named '{top}'."));
        }
        if !Api::subcategory_exists(top, &path) {
            return Err(format!("No subcategory named '{name}' here."));
        }
        Ok(candidate)
    } else if target.contains('.') {
        let segments: Vec<&str> = target.split('.').collect();
        let top = segments[0];
        if !Api::categories().iter().any(|c| c == top) {
            return Err(format!("No category named '{top}'."));
        }
        let path = segments[1..].join("/");
        if !path.is_empty() && !Api::subcategory_exists(top, &path) {
            return Err(format!(
                "No subcategory named '{}' in '{top}'.",
                segments[1..].join(".")
            ));
        }
        Ok(if path.is_empty() {
            top.to_string()
        } else {
            format!("{top}/{path}")
        })
    } else if Api::categories().iter().any(|c| c == target) {
        Ok(target.to_string())
    } else {
        Err(format!(
            "No category named '{target}'. Type :to? to see the list."
        ))
    }
}

fn switch_to(current_category: &mut String, target: &str) -> bool {
    match resolve_to_target(current_category, target) {
        Ok(resolved) => {
            *current_category = resolved.clone();
            println!("Switched to the '{resolved}' category.");
            true
        }
        Err(msg) => {
            eprintln!("{msg}");
            false
        }
    }
}

/// Ask which category to switch to, with Tab completion over category
/// names (and one level of the working category's own subcategories), and
/// resolve the answer exactly the way a plain `:to <answer>` would --
/// relative (".name", "..") and absolute ("category.sub") forms included,
/// not just a bare top-level name. Returns the resolved name, or `None`
/// if cancelled or invalid.
fn prompt_for_category(
    current_category: &str,
    editor: &mut Editor<HandeHelper, impl rustyline::history::History>,
) -> Option<String> {
    if let Some(helper) = editor.helper() {
        helper.picking_category.set(true);
    }
    let result = editor.readline("Switch to which category: ");
    if let Some(helper) = editor.helper() {
        helper.picking_category.set(false);
    }
    let name = match result {
        Ok(line) => line.trim().to_string(),
        Err(_) => return None,
    };
    if name.is_empty() {
        return None;
    }
    match resolve_to_target(current_category, &name) {
        Ok(resolved) => Some(resolved),
        Err(msg) => {
            eprintln!("{msg}");
            None
        }
    }
}

/// Prompt "Which bookmark?" with Tab completion over bookmark names (local
/// and global), then resolve it. Returns the category it lives in, its
/// parsed name, its raw line, and its preceding comment/tags line if any.
fn pick_bookmark(
    current_category: &str,
    editor: &mut Editor<HandeHelper, impl rustyline::history::History>,
) -> Option<(String, String, String, Option<String>)> {
    if let Some(helper) = editor.helper() {
        helper.picking_bookmark.set(true);
    }
    let result = editor.readline("Which bookmark? ");
    if let Some(helper) = editor.helper() {
        helper.picking_bookmark.set(false);
    }
    let reference = match result {
        Ok(line) => line.trim().to_string(),
        Err(_) => return None,
    };
    if reference.is_empty() {
        return None;
    }
    let qualified = qualify(current_category, &reference);
    let (hint, name) = split_reference(&qualified);
    match Api::locate_bookmark_context(hint.as_deref(), &name) {
        Some((category, line, comment)) => Some((category, name, line, comment)),
        None => {
            // The typed text might be an unambiguous prefix rather than
            // the full name -- e.g. cut short because a long imported
            // name was hard to hear in full before pressing Enter. Fall
            // back to a prefix match against what's already cached for
            // completion, and only use it if it's unambiguous.
            if let Some(full_name) = resolve_unambiguous_prefix(editor, &name) {
                if let Some((category, line, comment)) =
                    Api::locate_bookmark_context(hint.as_deref(), &full_name)
                {
                    return Some((category, full_name, line, comment));
                }
            }
            eprintln!("No bookmark named '{name}' was found.");
            None
        }
    }
}

/// If `prefix` matches the start of exactly one cached bookmark name
/// (local or global), return that full name; otherwise `None` -- used to
/// forgive a typed reference that's an unambiguous but incomplete prefix.
fn resolve_unambiguous_prefix(
    editor: &Editor<HandeHelper, impl rustyline::history::History>,
    prefix: &str,
) -> Option<String> {
    let helper = editor.helper()?;
    let mut matches: Vec<&String> = helper
        .completions
        .local_names
        .iter()
        .chain(helper.completions.global_names.iter())
        .filter(|n| n.starts_with(prefix))
        .collect();
    matches.dedup();
    if matches.len() == 1 {
        Some(matches[0].clone())
    } else {
        None
    }
}

/// A plain yes/no prompt; anything but "y"/"yes" (case-insensitive) is no.
fn confirm(prompt: &str) -> bool {
    print!("{prompt}");
    let _ = io::stdout().flush();
    let mut input = String::new();
    if io::stdin().read_line(&mut input).unwrap_or(0) == 0 {
        return false;
    }
    matches!(input.trim().to_lowercase().as_str(), "y" | "yes")
}

/// Read one line of free text from stdin (not the rustyline editor -- these
/// prompts are plain values, not commands, so no history or completion is
/// wanted), trimmed. `None` on EOF.
fn read_value(prompt: &str) -> Option<String> {
    print!("{prompt}");
    let _ = io::stdout().flush();
    let mut input = String::new();
    if io::stdin().read_line(&mut input).unwrap_or(0) == 0 {
        return None;
    }
    Some(input.trim().to_string())
}

/// Validate `candidate` as `category`'s new content in a sandbox before
/// ever touching the real file -- the same safety net `:new-bookmark` and
/// `:move`/`:copy` use, applied to any single-category edit.
/// The bare name from a subcategory-open line's trimmed text (before its
/// trailing '{'), stripping the ':' that marks it as a subcategory opener
/// -- the shell's own mirror of the parser's own subcategory-name
/// extraction, since that one is private to the api crate.
fn bare_subcategory_name(raw: &str) -> String {
    let raw = raw.trim();
    raw.strip_suffix(':').unwrap_or(raw).trim().to_string()
}

/// Find the (open-brace-line-index, close-brace-line-index) of a
/// subcategory's own block within a category file's lines, by its full
/// path (e.g. "education" or "education/books").
fn find_subcategory_block(lines: &[&str], path: &str) -> Option<(usize, usize)> {
    let segments: Vec<String> = path.split('/').map(str::to_string).collect();
    let mut stack: Vec<String> = Vec::new();
    for (i, line) in lines.iter().enumerate() {
        let trimmed = line.trim();
        if let Some(name) = trimmed.strip_suffix('{') {
            stack.push(bare_subcategory_name(name));
            if stack == segments {
                let mut depth = 1;
                for (j, later) in lines.iter().enumerate().skip(i + 1) {
                    let t = later.trim();
                    if t.ends_with('{') {
                        depth += 1;
                    } else if t == "}" {
                        depth -= 1;
                        if depth == 0 {
                            return Some((i, j));
                        }
                    }
                }
                return None;
            }
        } else if trimmed == "}" {
            stack.pop();
        }
    }
    None
}

/// Edit just a subcategory's own content (everything inside its braces,
/// nested sub-blocks included) in $EDITOR, rather than opening the whole
/// category file -- much easier to work with in a large, imported file,
/// and avoids having every other bookmark in the file read out along the
/// way to the one you actually want. Validated in the same sandbox before
/// the real file is ever touched.
fn edit_subcategory(top: &str, subpath: &str) {
    let app_home = Configurations::get_app_home();
    let category_file = format!("{app_home}/bookmarks/{top}");
    let Ok(original) = fs::read_to_string(&category_file) else {
        eprintln!("Could not read the '{top}' category file.");
        return;
    };
    let lines: Vec<&str> = original.lines().collect();
    let Some((open_idx, close_idx)) = find_subcategory_block(&lines, subpath) else {
        eprintln!("Could not find the '{subpath}' subcategory in '{top}'.");
        return;
    };
    let inner = format!("{}\n", lines[open_idx + 1..close_idx].join("\n"));

    let temp_path =
        std::env::temp_dir().join(format!("hande-subcat-edit-{}.txt", std::process::id()));
    if fs::write(&temp_path, &inner).is_err() {
        eprintln!("Could not create a temporary file to edit.");
        return;
    }

    let editor_program = std::env::var("EDITOR").unwrap_or_else(|_| "vi".to_string());
    let status = Command::new(&editor_program).arg(&temp_path).status();
    if !matches!(status, Ok(s) if s.success()) {
        eprintln!("Editor exited without success -- nothing was changed.");
        let _ = fs::remove_file(&temp_path);
        return;
    }
    let Ok(edited) = fs::read_to_string(&temp_path) else {
        eprintln!("Could not read back the edited content.");
        let _ = fs::remove_file(&temp_path);
        return;
    };
    let _ = fs::remove_file(&temp_path);

    let mut new_lines: Vec<String> = lines[..=open_idx].iter().map(|s| s.to_string()).collect();
    new_lines.extend(edited.lines().map(str::to_string));
    new_lines.extend(lines[close_idx..].iter().map(|s| s.to_string()));
    let candidate = format!("{}\n", new_lines.join("\n"));

    commit_with_validation(
        &app_home,
        top,
        &candidate,
        &format!("Updated the '{subpath}' subcategory."),
        "changed",
    );
}

/// Run one sandbox validation check, returning whether it passed. Uses
/// `output()` rather than `status()` so a *successful* check's own
/// listing doesn't get printed to the terminal at all -- with `status()`
/// (which inherits stdout), every other bookmark in the category or
/// database would otherwise be printed, and read aloud in full by a
/// screen reader, on every single validated change. A failing check's
/// stderr (hande's own error message) is still shown, since that's the
/// one thing the person actually needs to see.
fn run_validation_check(exe: &std::path::Path, sandbox: &std::path::Path, args: &[&str]) -> bool {
    match Command::new(exe).env("HANDE_HOME", sandbox).args(args).output() {
        Ok(output) => {
            if !output.status.success() {
                let _ = io::stderr().write_all(&output.stderr);
            }
            output.status.success()
        }
        Err(_) => false,
    }
}

fn commit_with_validation(app_home: &str, category: &str, candidate: &str, success: &str, verb: &str) {
    let overrides = [(category.to_string(), candidate.to_string())];
    let sandbox = std::env::temp_dir().join(format!("hande-validate-{}", std::process::id()));
    if let Err(err) = build_sandbox(app_home, &sandbox, &overrides) {
        eprintln!("Could not prepare a sandbox to check this: {err}");
        let _ = fs::remove_dir_all(&sandbox);
        return;
    }
    let exe = match std::env::current_exe() {
        Ok(path) => path,
        Err(err) => {
            eprintln!("Could not locate the hande binary: {err}");
            let _ = fs::remove_dir_all(&sandbox);
            return;
        }
    };
    let destination_ok = run_validation_check(&exe, &sandbox, &["--category", category, "--list"]);
    let global_ok = run_validation_check(&exe, &sandbox, &["--list-global"]);
    if destination_ok && global_ok {
        match fs::write(format!("{app_home}/bookmarks/{category}"), candidate) {
            Ok(_) => println!("{success}"),
            Err(err) => eprintln!("It checked out fine, but could not be saved: {err}"),
        }
    } else {
        println!("Not {verb} -- see the error above, fix it, and try again.");
    }
    let _ = fs::remove_dir_all(&sandbox);
}

/// Pick a bookmark and let you retype its whole raw line freely, pre-filled
/// with what's there now (like editing a git commit message) -- covers
/// renaming, along with any other change, since there's no separate
/// `:rename`. Validated in a sandbox before anything real is touched.
fn update_bookmark(
    current_category: &str,
    editor: &mut Editor<HandeHelper, impl rustyline::history::History>,
) {
    let Some((category, _name, line, _comment)) = pick_bookmark(current_category, editor) else {
        return;
    };
    let new_line = match editor.readline_with_initial("New line: ", (&line, "")) {
        Ok(l) => l.trim().to_string(),
        Err(_) => {
            println!("Cancelled.");
            return;
        }
    };
    if new_line.is_empty() {
        println!("Cancelled: an empty line would delete the bookmark -- use :delete for that.");
        return;
    }
    if new_line == line {
        println!("No change.");
        return;
    }
    let (top, _) = split_top(&category);
    let app_home = Configurations::get_app_home();
    let original = fs::read_to_string(format!("{app_home}/bookmarks/{top}")).unwrap_or_default();
    let candidate = replace_line_in_place(&original, &line, &new_line);
    commit_with_validation(
        &app_home,
        top,
        &candidate,
        &format!("Updated the bookmark in the '{category}' category."),
        "updated",
    );
}

/// The name field's current shortcut key, if it has one, from either an
/// auto-derived `_name` prefix or an explicit `(key)` block.
fn extract_key(line: &str) -> Option<char> {
    let field = line.find('<').map(|p| line[..p].trim()).unwrap_or("");
    if let Some(rest) = field.strip_prefix('_') {
        rest.chars().next()
    } else if let (Some(open), Some(close)) = (field.find('('), field.find(')')) {
        if close > open + 1 {
            field[open + 1..close].chars().next()
        } else {
            None
        }
    } else {
        None
    }
}

/// Replace whatever shortcut-key decoration a name field has (if any) with
/// an explicit `(key)` block for `key`.
fn set_key_field(field: &str, key: char) -> String {
    let base = if let Some(rest) = field.strip_prefix('_') {
        rest.to_string()
    } else if let Some(open) = field.find('(') {
        field[..open].to_string()
    } else {
        field.to_string()
    };
    format!("{base}({key})")
}

/// Pick a bookmark and give it a shortcut key, warning first if it already
/// has one. The key's case has to agree with the bookmark's scope (see
/// `:move`'s scope rules) -- global needs uppercase, local needs lowercase.
fn add_key(
    current_category: &str,
    editor: &mut Editor<HandeHelper, impl rustyline::history::History>,
) {
    let Some((category, name, line, _comment)) = pick_bookmark(current_category, editor) else {
        return;
    };
    if let Some(existing) = extract_key(&line) {
        if !confirm(&format!(
            "'{name}' already has the shortcut key '{existing}'. Overwrite? [y/N] "
        )) {
            println!("Cancelled.");
            return;
        }
    }
    let Some(input) = read_value(&format!("New shortcut key for '{name}': ")) else {
        return;
    };
    let mut chars = input.chars();
    let (Some(key), None) = (chars.next(), chars.next()) else {
        println!("Cancelled: a shortcut key must be a single character.");
        return;
    };
    let is_global = name
        .chars()
        .next()
        .map(|c| c.is_uppercase())
        .unwrap_or(false);
    if is_global && !key.is_ascii_uppercase() {
        eprintln!(
            "Error: '{name}' is global, so its shortcut key must be uppercase -- try '{}'.",
            key.to_ascii_uppercase()
        );
        return;
    }
    if !is_global && key.is_ascii_uppercase() {
        eprintln!(
            "Error: '{name}' is local, so its shortcut key can't be uppercase -- try '{}'.",
            key.to_ascii_lowercase()
        );
        return;
    }
    let field = line.find('<').map(|p| line[..p].trim()).unwrap_or("");
    let new_field = set_key_field(field, key);
    let new_line = replace_name_field(&line, &new_field);
    let (top, _) = split_top(&category);
    let app_home = Configurations::get_app_home();
    let original = fs::read_to_string(format!("{app_home}/bookmarks/{top}")).unwrap_or_default();
    let candidate = replace_line_in_place(&original, &line, &new_line);
    commit_with_validation(
        &app_home,
        top,
        &candidate,
        &format!("'{name}' now has the shortcut key '{key}'."),
        "changed",
    );
}

/// The handler token after a bookmark's `<location>`, if it has one.
fn extract_handler(line: &str) -> Option<String> {
    let after = line.rfind('>').map(|p| line[p + 1..].trim())?;
    if after.is_empty() {
        None
    } else {
        Some(after.to_string())
    }
}

/// Pick a bookmark and give it a handler (the program used to open it),
/// warning first if it already has one.
fn add_handler(
    current_category: &str,
    editor: &mut Editor<HandeHelper, impl rustyline::history::History>,
) {
    let Some((category, name, line, _comment)) = pick_bookmark(current_category, editor) else {
        return;
    };
    if let Some(existing) = extract_handler(&line) {
        if !confirm(&format!(
            "'{name}' already has the handler '{existing}'. Overwrite? [y/N] "
        )) {
            println!("Cancelled.");
            return;
        }
    }
    let Some(handler) = read_value(&format!("New handler for '{name}' (e.g. chrome): ")) else {
        return;
    };
    if handler.is_empty() {
        println!("Cancelled: no handler given.");
        return;
    }
    let handler = handler.strip_prefix(':').unwrap_or(&handler);
    let Some(pos) = line.rfind('>') else {
        eprintln!("'{name}' has no location field to attach a handler after.");
        return;
    };
    let new_line = format!("{} :{handler}", &line[..=pos]);
    let (top, _) = split_top(&category);
    let app_home = Configurations::get_app_home();
    let original = fs::read_to_string(format!("{app_home}/bookmarks/{top}")).unwrap_or_default();
    let candidate = replace_line_in_place(&original, &line, &new_line);
    commit_with_validation(
        &app_home,
        top,
        &candidate,
        &format!("'{name}' now uses the '{handler}' handler."),
        "changed",
    );
}

/// Split a comment line's body into its plain description and its
/// `[bracketed tags]`, mirroring the engine's own `# description [tags]`
/// parsing (either half may be absent).
fn parse_comment_line(line: &str) -> (String, Vec<String>) {
    let body = line.trim_start_matches('#').trim();
    if let Some(pos) = body.find('[') {
        let (desc, bracket) = body.split_at(pos);
        let tags: Vec<String> = bracket
            .trim_start_matches('[')
            .trim_end_matches(']')
            .split_whitespace()
            .map(str::to_lowercase)
            .collect();
        (desc.trim().to_string(), tags)
    } else {
        (body.trim().to_string(), Vec::new())
    }
}

/// Build a `# description [tags]` comment line, omitting whichever half is
/// empty (matching every shape the engine itself accepts).
fn build_comment_line(description: &str, tags: &[String]) -> String {
    if tags.is_empty() {
        format!("# {description}")
    } else if description.is_empty() {
        format!("# [{}]", tags.join(" "))
    } else {
        format!("# {description} [{}]", tags.join(" "))
    }
}

/// Insert or replace the comment/tags line directly above `bookmark_line`,
/// then validate and commit -- shared by `:add-comment` and `:add-alias`,
/// which only ever touch this one line, never the bookmark's own.
fn apply_comment_change(
    category: &str,
    bookmark_line: &str,
    old_comment: Option<&str>,
    new_comment_line: &str,
    success: &str,
) {
    let (top, _) = split_top(category);
    let app_home = Configurations::get_app_home();
    let original = fs::read_to_string(format!("{app_home}/bookmarks/{top}")).unwrap_or_default();
    let mut updated: Vec<String> = Vec::new();
    for line in original.lines() {
        let trimmed = line.trim();
        if let Some(old) = old_comment {
            if trimmed == old {
                continue;
            }
        }
        if trimmed == bookmark_line {
            updated.push(new_comment_line.to_string());
        }
        updated.push(line.to_string());
    }
    let candidate = format!("{}\n", updated.join("\n"));
    commit_with_validation(&app_home, top, &candidate, success, "changed");
}

/// Pick a bookmark and give it (or replace) its description, warning first
/// if it already has one. Any existing tags are kept as they are.
fn add_comment(
    current_category: &str,
    editor: &mut Editor<HandeHelper, impl rustyline::history::History>,
) {
    let Some((category, name, line, comment)) = pick_bookmark(current_category, editor) else {
        return;
    };
    let (existing_desc, existing_tags) = comment
        .as_deref()
        .map(parse_comment_line)
        .unwrap_or_default();
    if !existing_desc.is_empty()
        && !confirm(&format!(
            "'{name}' already has the comment \"{existing_desc}\". Overwrite? [y/N] "
        ))
    {
        println!("Cancelled.");
        return;
    }
    let Some(new_desc) = read_value(&format!("New comment for '{name}': ")) else {
        return;
    };
    if new_desc.is_empty() {
        println!("Cancelled: no comment given.");
        return;
    }
    let new_comment_line = build_comment_line(&new_desc, &existing_tags);
    apply_comment_change(
        &category,
        &line,
        comment.as_deref(),
        &new_comment_line,
        &format!("'{name}' now has that comment."),
    );
}

/// Pick a bookmark and give it (or replace) its tags/aliases, warning first
/// if it already has some. Any existing description is kept as it is.
fn add_alias(
    current_category: &str,
    editor: &mut Editor<HandeHelper, impl rustyline::history::History>,
) {
    let Some((category, name, line, comment)) = pick_bookmark(current_category, editor) else {
        return;
    };
    let (existing_desc, existing_tags) = comment
        .as_deref()
        .map(parse_comment_line)
        .unwrap_or_default();
    if !existing_tags.is_empty()
        && !confirm(&format!(
            "'{name}' already has the tags [{}]. Overwrite? [y/N] ",
            existing_tags.join(" ")
        ))
    {
        println!("Cancelled.");
        return;
    }
    let Some(input) = read_value(&format!("New tags for '{name}' (space-separated): ")) else {
        return;
    };
    let new_tags: Vec<String> = input.split_whitespace().map(str::to_lowercase).collect();
    if new_tags.is_empty() {
        println!("Cancelled: no tags given.");
        return;
    }
    let new_comment_line = build_comment_line(&existing_desc, &new_tags);
    apply_comment_change(
        &category,
        &line,
        comment.as_deref(),
        &new_comment_line,
        &format!("'{name}' now has those tags."),
    );
}

fn refresh_completions(
    editor: &mut Editor<HandeHelper, impl rustyline::history::History>,
    category: &str,
) {
    if let Some(helper) = editor.helper_mut() {
        helper.completions = Completions::refresh(category);
    }
}

fn print_help() {
    println!("Shell commands (all prefixed with ':'; short letter in brackets):");
    println!("  :quit           [:q]  leave the shell");
    println!("  :list           [:l]  list every bookmark, working category and global");
    println!("  :category-list  [:c]  list bookmarks in the working category only");
    println!("  :global-list    [:g]  list bookmarks in the global scope only");
    println!("  :to <name>      [:switch]  switch the working category");
    println!("  :to             [:switch]  switch back to the default category");
    println!("  :to @<key>                 switch by a category's shortcut key");
    println!("  :to?            [:switch?] prompt for a category, with Tab completion");
    println!("  :@<keys>        jump straight to a category/subcategory by its shortcut key");
    println!("                    chain (e.g. :@we) -- every character is a category or");
    println!("                    subcategory key, unlike a bookmark's own '@' shortcut, whose");
    println!("                    last character always picks a bookmark instead; :@ alone");
    println!("                    resets to the default category, like :to alone does. Start");
    println!("                    the chain with '_' (e.g. :@_e, @_ec) to walk from the working");
    println!("                    category instead of a top-level one -- handy for a nearby");
    println!("                    subcategory you'd otherwise need its whole key chain to reach");
    println!("  :add-category   [:n]  add a new category");
    println!("  :add-bookmark   [:a, :ab]  add a bookmark to the working category");
    println!("  :update         [:u]  pick a bookmark and retype its whole line freely");
    println!("                    (pre-filled with what's there now -- also how you rename)");
    println!("  :add-key        [:ak]  pick a bookmark and give it a shortcut key");
    println!("  :add-handler    [:ah]  pick a bookmark and give it a handler (e.g. chrome)");
    println!("  :add-comment    [:ac]  pick a bookmark and give it a description");
    println!("  :add-alias      [:aa, :at, :add-tag]  pick a bookmark and give it tags");
    println!("                    each add-* warns and asks before overwriting an existing");
    println!("                    key/handler/comment/tags");
    println!("  :delete <name>  [:d]  delete a bookmark from the working category");
    println!("  :delete-global <name>  [:D]  delete a global bookmark");
    println!("  :move <bookmark> <category>  [:m]  move a bookmark into another category");
    println!("  :copy <bookmark> <category>  [:y]  copy a local bookmark into another category");
    println!("                    a :move destination can also be '_' (working category,");
    println!("                    lowercasing the name if needed), ':' (global scope, keeping");
    println!("                    the name but capitalizing it), or a capitalized new name");
    println!("                    (global scope, renamed) -- relocating a bookmark's file");
    println!("                    never changes its scope on its own, since that's decided");
    println!("                    purely by the name's case, so these forms rename it to match");
    println!("  :edit           [:e]  edit the working category's bookmarks in $EDITOR");
    println!("  :help           [:h]  show this message");
    println!("  :license              show the MIT license");
    println!("  :man                   open the full manual (a quick-start is under '?')");
    println!("  :config         [:cfg]  edit the configuration file in $EDITOR");
    println!("  :import         [:i]  import bookmarks from a browser's exported HTML file");
    println!("  :export         [:x]  export bookmarks as an HTML file a browser can import");
    println!();
    println!("Anything else opens hande itself: a single word opens that bookmark,");
    println!("shortcut, or alias in the working category (just like `hande --category");
    println!("<name> <word>`); more than one word runs a search. Tab-complete bookmark");
    println!("names, shortcuts, and the arguments to :delete/:delete-global/:to/:move/:copy;");
    println!("use the up/down arrows for command history. A bookmark reference for :move");
    println!("or :copy can be a bare name (working category), '.name', 'category.name',");
    println!("or a bare capitalized (global) name.");
}

/// Import bookmarks from a browser's exported HTML file (the format
/// Firefox, Chrome, Safari and Edge all use) into a chosen category.
/// Prompt for a file path, pre-filled with "bookmarks.html" -- what most
/// browsers name their own export, and what most people never bother
/// changing -- editable or just acceptable as-is with Enter, the same way
/// `:update` pre-fills a bookmark's line.
fn prompt_for_path(
    editor: &mut Editor<HandeHelper, impl rustyline::history::History>,
    prompt: &str,
) -> Option<String> {
    match editor.readline_with_initial(prompt, ("bookmarks.html", "")) {
        Ok(line) => {
            let path = line.trim().to_string();
            if path.is_empty() {
                None
            } else {
                Some(path)
            }
        }
        Err(_) => None,
    }
}

fn import_bookmarks(
    current_category: &str,
    editor: &mut Editor<HandeHelper, impl rustyline::history::History>,
) {
    let Some(path) = prompt_for_path(editor, "Path to the browser bookmarks HTML file: ") else {
        println!("Cancelled: no file given.");
        return;
    };
    let prompt = format!("Import into which category? [{current_category}]: ");
    let Some(category) = read_value(&prompt) else {
        return;
    };
    let category = if category.is_empty() {
        current_category.to_string()
    } else {
        category
    };
    if confirm(
        "Preserve folder structure as nested subcategories, rather than importing flat? [y/N] ",
    ) {
        run_hande(&[
            "--import-bookmarks",
            path.as_str(),
            "--category",
            category.as_str(),
            "--preserve-folders",
        ]);
    } else {
        run_hande(&["--import-bookmarks", path.as_str(), "--category", category.as_str()]);
    }
    refresh_completions(editor, current_category);
}

/// Export bookmarks as a browser-importable HTML file.
fn export_bookmarks(
    current_category: &str,
    editor: &mut Editor<HandeHelper, impl rustyline::history::History>,
) {
    let Some(path) = prompt_for_path(editor, "Path to write the exported HTML file: ") else {
        println!("Cancelled: no file given.");
        return;
    };
    if confirm(&format!(
        "Export only the '{current_category}' category, rather than everything? [y/N] "
    )) {
        run_hande(&["--export-bookmarks", path.as_str(), "--category", current_category]);
    } else {
        run_hande(&["--export-bookmarks", path.as_str()]);
    }
}

/// Create a new category, then optionally replace its default header (the
/// one that points back at hande's own site) with a custom one -- a real
/// web URL, and optionally a shortcut key and description, in the same
/// `*key <location> description` shape a hand-edited header would use.
/// Validated in the same sandbox-then-commit pattern as any other
/// category-file edit, since a malformed header would break the whole
/// category.
fn add_category() {
    print!("New category name: ");
    let _ = io::stdout().flush();
    let mut name = String::new();
    if io::stdin().read_line(&mut name).unwrap_or(0) == 0 {
        return;
    }
    let name = name.trim().to_string();
    if name.is_empty() {
        println!("Cancelled: no category name given.");
        return;
    }
    run_hande(&["--new-category", &name]);

    if !confirm(&format!(
        "Set up a custom header for '{name}' instead of the default one? [y/N] "
    )) {
        return;
    }
    let Some(url) = read_value(
        "Web address for this category's header (a plain domain, or a full http(s):// address): ",
    ) else {
        return;
    };
    if url.is_empty() {
        println!("Cancelled: no address given, keeping the default header.");
        return;
    }
    let key = read_value("Optional shortcut key for this category (Enter to skip): ")
        .unwrap_or_default();
    let description = read_value("Optional description for this category (Enter to skip): ")
        .unwrap_or_default();

    let location = if url.starts_with("http://") || url.starts_with("https://") || url.starts_with('@')
    {
        url
    } else {
        format!("@{url}")
    };
    let key_part = key.chars().next().map(|c| c.to_string()).unwrap_or_default();
    let new_header = if description.is_empty() {
        format!("*{key_part} <{location}>")
    } else {
        format!("*{key_part} <{location}> {description}")
    };

    let app_home = Configurations::get_app_home();
    let category_file = format!("{app_home}/bookmarks/{name}");
    let original = fs::read_to_string(&category_file).unwrap_or_default();
    let mut lines: Vec<String> = original.lines().map(str::to_string).collect();
    if lines.is_empty() {
        eprintln!("Could not read the new category file back to give it a header.");
        return;
    }
    lines[0] = new_header;
    let candidate = format!("{}\n", lines.join("\n"));
    commit_with_validation(
        &app_home,
        &name,
        &candidate,
        &format!("'{name}' now has its own header."),
        "changed",
    );
}

/// Prompt for a raw bookmark line and append it to `category`'s file --
/// but only after validating it in a throwaway sandbox copy of the whole
/// database, so a typo can never corrupt the real file. The sandbox is a
/// full copy (config plus every category) because a bad reference in the
/// new line could otherwise only surface later, when something else tries
/// to use it.
fn add_bookmark(category: &str) {
    print!("New bookmark for the '{category}' category, e.g. `guardian <@guardian.co.uk> :chrome`: ");
    let _ = io::stdout().flush();
    let mut line = String::new();
    if io::stdin().read_line(&mut line).unwrap_or(0) == 0 {
        return;
    }
    let line = line.trim();
    if line.is_empty() {
        println!("Cancelled: no bookmark entered.");
        return;
    }
    if !line.contains('<') || !line.contains('>') {
        println!("A bookmark needs a location in angle brackets, like `name <location>`.");
        return;
    }

    let (top, subpath) = split_top(category);
    let app_home = Configurations::get_app_home();
    let category_file = format!("{app_home}/bookmarks/{top}");
    let original = fs::read_to_string(&category_file).unwrap_or_default();
    // A bare append to the end of the file is only correct for the
    // top-level category itself -- inside a subcategory, the new line
    // has to land inside that subcategory's own block, right before its
    // closing brace, or it would silently end up as a top-level entry
    // instead of where the person is actually working.
    let candidate = if subpath.is_empty() {
        format!("{}\n{line}\n", original.trim_end())
    } else {
        let file_lines: Vec<&str> = original.lines().collect();
        match find_subcategory_block(&file_lines, &subpath) {
            Some((_, close_idx)) => {
                let mut new_lines: Vec<String> =
                    file_lines[..close_idx].iter().map(|s| s.to_string()).collect();
                new_lines.push(line.to_string());
                new_lines.extend(file_lines[close_idx..].iter().map(|s| s.to_string()));
                format!("{}\n", new_lines.join("\n"))
            }
            None => {
                eprintln!("Could not find the '{subpath}' subcategory in '{top}'.");
                return;
            }
        }
    };

    let sandbox = std::env::temp_dir().join(format!("hande-validate-{}", std::process::id()));
    let overrides = [(top.to_string(), candidate.clone())];
    if let Err(err) = build_sandbox(&app_home, &sandbox, &overrides) {
        eprintln!("Could not prepare a sandbox to check this bookmark: {err}");
        let _ = fs::remove_dir_all(&sandbox);
        return;
    }

    let exe = match std::env::current_exe() {
        Ok(path) => path,
        Err(err) => {
            eprintln!("Could not locate the hande binary: {err}");
            let _ = fs::remove_dir_all(&sandbox);
            return;
        }
    };
    let status = run_validation_check(&exe, &sandbox, &["--category", top, "--list"]);

    if status {
        match fs::write(&category_file, &candidate) {
            Ok(_) => println!("Added to the '{category}' category."),
            Err(err) => eprintln!("It checked out fine, but could not be saved: {err}"),
        }
    } else {
        println!("Not added -- see the error above, fix it, and try again.");
    }
    let _ = fs::remove_dir_all(&sandbox);
}

/// Move (or, with `is_move: false`, copy) a bookmark into `destination`.
/// The reference can be a bare name (working category), "." or ".name"
/// (also the working category), "category.name" (explicit), or a bare
/// capitalized name (global -- searched for across every category).
///
/// Copying a global bookmark is refused outright: it's already reachable
/// from everywhere, and leaving a second copy behind would create two
/// bookmarks with the same name, which hande's global-uniqueness rule
/// won't allow -- that's exactly the kind of self-inflicted database
/// corruption the sandbox check below exists to catch, so it's better to
/// explain the problem than let the user hit it as a cryptic parse error.
///
/// Like `:new-bookmark`, nothing real is touched until a full sandbox copy
/// of the database -- with the move or copy already applied -- has been
/// checked out clean, so a collision (a duplicate name in the destination,
/// or a duplicate global name anywhere) can never corrupt a real file.
/// A move or copy's destination: either a local category (by name), or the
/// global scope (keeping the current base name, or with an explicit new
/// one).
enum Destination {
    Local(String),
    Global(Option<String>),
}

/// Parse a `:move`/`:copy` destination argument:
/// - `_` -- the working category, keeping the bookmark's base name (its
///   case is adjusted to fit, same as any other local destination).
/// - `<category>` or `<category>._` -- that explicit category, same as `_`.
/// - `:` -- the global scope, capitalizing the current base name if needed.
/// - `<Name>` (capitalized) -- the global scope, under this new name
///   instead of the current one.
fn parse_destination(current_category: &str, dest: &str) -> Result<Destination, String> {
    if dest == ":" {
        return Ok(Destination::Global(None));
    }
    if dest == "_" {
        return Ok(Destination::Local(current_category.to_string()));
    }
    if let Some(category) = dest.strip_suffix("._") {
        if category.is_empty() {
            return Err(format!("'{dest}' needs a category name before the dot."));
        }
        return Ok(Destination::Local(category.to_string()));
    }
    if dest.contains('.') {
        return Err(format!(
            "'{dest}' isn't a supported destination -- use '_', ':', a category name, or 'category._'."
        ));
    }
    if dest.chars().next().map(|c| c.is_uppercase()).unwrap_or(false) {
        return Ok(Destination::Global(Some(dest.to_string())));
    }
    Ok(Destination::Local(dest.to_string()))
}

fn lowercase_first(name: &str) -> String {
    let mut chars = name.chars();
    match chars.next() {
        Some(c) => c.to_lowercase().collect::<String>() + chars.as_str(),
        None => String::new(),
    }
}

fn uppercase_first(name: &str) -> String {
    let mut chars = name.chars();
    match chars.next() {
        Some(c) => c.to_uppercase().collect::<String>() + chars.as_str(),
        None => String::new(),
    }
}

/// Flip the case of a bookmark line's name field (the part before its
/// `<location>`) to match a new scope, keeping the same base name.
///
/// An auto-derived `_name` shortcut updates itself for free, since its key
/// is just the name's own first letter; an explicit `(key)` block has its
/// key's case flipped too, since a shortcut key always has to agree with
/// its bookmark's scope. Trailing flags (`*`, `/`, `-`) are never touched
/// -- they're never part of the name field's leading characters. (An
/// explicit rename to a brand-new name is handled separately by the
/// caller, which drops any decoration entirely rather than calling this.)
fn rename_field(name_field: &str, is_now_global: bool) -> String {
    let mut chars: Vec<char> = name_field.chars().collect();
    if chars.is_empty() {
        return name_field.to_string();
    }
    if chars[0] == '_' {
        if chars.len() > 1 {
            chars[1] = if is_now_global {
                chars[1].to_ascii_uppercase()
            } else {
                chars[1].to_ascii_lowercase()
            };
        }
    } else {
        chars[0] = if is_now_global {
            chars[0].to_ascii_uppercase()
        } else {
            chars[0].to_ascii_lowercase()
        };
        if let (Some(open), Some(close)) = (
            chars.iter().position(|&c| c == '('),
            chars.iter().position(|&c| c == ')'),
        ) {
            if close > open + 1 {
                for c in chars.iter_mut().take(close).skip(open + 1) {
                    *c = if is_now_global {
                        c.to_ascii_uppercase()
                    } else {
                        c.to_ascii_lowercase()
                    };
                }
            }
        }
    }
    chars.into_iter().collect()
}

/// Replace a bookmark line's name field (everything before its first `<`)
/// with `new_name_field`, preserving the exact original spacing before `<`.
fn replace_name_field(line: &str, new_name_field: &str) -> String {
    let Some(pos) = line.find('<') else {
        return line.to_string();
    };
    let before = &line[..pos];
    let trimmed = before.trim_end();
    let gap = &before[trimmed.len()..];
    format!("{new_name_field}{gap}{}", &line[pos..])
}

/// Move (or, with `is_move: false`, copy) a bookmark into `destination`.
/// The reference can be a bare name (working category), "." or ".name"
/// (also the working category), "category.name" (explicit), or a bare
/// capitalized name (global -- searched for across every category).
///
/// The destination can change scope, not just location: `_` (or an
/// explicit local category) lowercases the bookmark's first letter if it
/// isn't already local, `:` capitalizes it to make it global, and an
/// explicit capitalized destination renames it outright as it goes global.
/// Relocating a bookmark's *file* never by itself changes its scope --
/// that's decided purely by the name's own case -- so a scope-changing
/// move always rewrites the name to match, never just the file it lives in.
///
/// Copying stays a strictly local-to-local operation: copying an
/// already-global bookmark, or copying into the global scope, would both
/// either create or resemble a duplicate name, which hande doesn't allow --
/// both are refused with an explanation rather than a cryptic failure.
///
/// Like `:new-bookmark`, nothing real is touched until a full sandbox copy
/// of the database -- with the change already applied -- has been checked
/// out clean, so a collision can never corrupt a real file. When the move
/// stays within a single category (already true for a scope flip that
/// doesn't relocate anything, and possible if a global bookmark already
/// happens to live in the target file), it's an in-place rename rather
/// than a delete-and-re-append, so the line's position in the file doesn't
/// needlessly jump to the end.
fn move_or_copy_bookmark(current_category: &str, args: &str, is_move: bool) {
    let mut parts = args.split_whitespace();
    let (Some(reference), Some(dest_arg), None) = (parts.next(), parts.next(), parts.next())
    else {
        let example = if is_move {
            ":m <bookmark> <category|_|:|Name>"
        } else {
            ":y <bookmark> <category|_>"
        };
        println!("Usage: {example}");
        return;
    };

    let qualified = qualify(current_category, reference);
    let (category_hint, target_name) = split_reference(&qualified);

    let Some((source_category, line)) = Api::locate_bookmark(category_hint.as_deref(), &target_name)
    else {
        eprintln!("No bookmark named '{target_name}' was found.");
        return;
    };

    let source_is_global = target_name
        .chars()
        .next()
        .map(|c| c.is_uppercase())
        .unwrap_or(false);

    if !is_move && source_is_global {
        eprintln!(
            "Error: '{target_name}' is a global bookmark, so it's already reachable from every category."
        );
        eprintln!(
            "Copying it would leave two bookmarks with the same name, which hande won't allow. Did you mean :move?"
        );
        return;
    }

    let destination = match parse_destination(current_category, dest_arg) {
        Ok(d) => d,
        Err(msg) => {
            eprintln!("Error: {msg}");
            return;
        }
    };

    if !is_move {
        if let Destination::Global(_) = destination {
            eprintln!("Error: :copy only duplicates a bookmark within local categories.");
            eprintln!(
                "A global copy would give it a second identity outside any one category -- that isn't really a copy. Add it directly if you want a new global bookmark, or use :move if you mean to relocate this one."
            );
            return;
        }
    }

    let (destination_category, new_name, name_field) = match &destination {
        Destination::Local(category) => {
            if !Api::categories().iter().any(|c| c == category) {
                eprintln!("No category named '{category}'.");
                return;
            }
            let new_name = lowercase_first(&target_name);
            let position = line.find('<').map(|p| line[..p].trim()).unwrap_or("");
            let field = rename_field(position, false);
            (category.clone(), new_name, field)
        }
        Destination::Global(None) => {
            let new_name = uppercase_first(&target_name);
            let position = line.find('<').map(|p| line[..p].trim()).unwrap_or("");
            let field = rename_field(position, true);
            (source_category.clone(), new_name, field)
        }
        Destination::Global(Some(explicit)) => {
            (source_category.clone(), explicit.clone(), explicit.clone())
        }
    };

    if source_category == destination_category && new_name == target_name {
        println!("'{target_name}' is already in the '{destination_category}' category.");
        return;
    }

    let new_line = replace_name_field(&line, &name_field);

    let app_home = Configurations::get_app_home();
    let mut affected: std::collections::HashMap<String, String> = std::collections::HashMap::new();
    for category in [&source_category, &destination_category] {
        affected.entry(category.clone()).or_insert_with(|| {
            fs::read_to_string(format!("{app_home}/bookmarks/{category}")).unwrap_or_default()
        });
    }
    if source_category == destination_category {
        // Same file: a true in-place substitution at the line's original
        // position, rather than remove-then-append -- otherwise a comment
        // that precedes this line in the file would end up in front of
        // whatever line originally followed it instead.
        let content = affected.get_mut(&source_category).unwrap();
        *content = replace_line_in_place(content, &line, &new_line);
    } else {
        if is_move {
            let content = affected.get_mut(&source_category).unwrap();
            *content = remove_line(content, &line);
        }
        let content = affected.get_mut(&destination_category).unwrap();
        *content = format!("{}\n{new_line}\n", content.trim_end());
    }

    let overrides: Vec<(String, String)> = affected.into_iter().collect();
    let sandbox = std::env::temp_dir().join(format!("hande-validate-{}", std::process::id()));
    if let Err(err) = build_sandbox(&app_home, &sandbox, &overrides) {
        eprintln!("Could not prepare a sandbox to check this: {err}");
        let _ = fs::remove_dir_all(&sandbox);
        return;
    }

    let exe = match std::env::current_exe() {
        Ok(path) => path,
        Err(err) => {
            eprintln!("Could not locate the hande binary: {err}");
            let _ = fs::remove_dir_all(&sandbox);
            return;
        }
    };
    // Two checks cover both collision shapes: a duplicate name within the
    // destination category, and a duplicate global name anywhere at all.
    let destination_ok =
        run_validation_check(&exe, &sandbox, &["--category", &destination_category, "--list"]);
    let global_ok = run_validation_check(&exe, &sandbox, &["--list-global"]);

    if destination_ok && global_ok {
        let mut ok = true;
        for (category, content) in &overrides {
            ok &= fs::write(format!("{app_home}/bookmarks/{category}"), content).is_ok();
        }
        if ok {
            let verb = if is_move { "Moved" } else { "Copied" };
            let rename_note = if new_name != target_name {
                format!(" as '{new_name}'")
            } else {
                String::new()
            };
            if source_category == destination_category {
                println!(
                    "{verb} '{target_name}'{rename_note} within the '{source_category}' category."
                );
            } else {
                println!(
                    "{verb} '{target_name}'{rename_note} from '{source_category}' to '{destination_category}'."
                );
            }
        } else {
            eprintln!("It checked out fine, but could not be saved.");
        }
    } else {
        let verb = if is_move { "moved" } else { "copied" };
        println!("Not {verb} -- see the error above, fix it, and try again.");
    }
    let _ = fs::remove_dir_all(&sandbox);
}

/// Build an isolated copy of the app's config and every category file under
/// `sandbox`, with each `(category, content)` pair in `overrides` replacing
/// that category's real content -- enough for `hande` to validate a change
/// exactly as the real engine would, without ever touching the real
/// database. Supports overriding more than one file at once (a move
/// touches both its source and destination).
fn build_sandbox(app_home: &str, sandbox: &Path, overrides: &[(String, String)]) -> io::Result<()> {
    fs::create_dir_all(sandbox.join("bookmarks"))?;
    let config_src = format!("{app_home}/config.toml");
    if Path::new(&config_src).exists() {
        fs::copy(&config_src, sandbox.join("config.toml"))?;
    }
    let bookmarks_src = format!("{app_home}/bookmarks");
    if let Ok(entries) = fs::read_dir(&bookmarks_src) {
        for entry in entries.flatten() {
            if entry.path().is_file() {
                fs::copy(entry.path(), sandbox.join("bookmarks").join(entry.file_name()))?;
            }
        }
    }
    for (category, content) in overrides {
        fs::write(sandbox.join("bookmarks").join(category), content)?;
    }
    Ok(())
}

/// Re-invoke the `hande` binary itself with `args`, waiting for it to finish.
/// This is how the shell performs anything that can touch the bookmarks
/// database -- all of the risk (process exit, exec-based launches) then
/// only ever affects the subprocess, never the shell.
fn run_hande(args: &[&str]) {
    let exe = match std::env::current_exe() {
        Ok(path) => path,
        Err(err) => {
            eprintln!("Could not locate the hande binary: {err}");
            return;
        }
    };
    // A command-location bookmark (a script or one-liner, like a `ping`
    // used to check for a connection) ends up exec()'d in place of this
    // subprocess -- and since we never gave it its own process group, it
    // shares our terminal's foreground process group, exactly as if you'd
    // typed the command yourself. That's what lets it be interrupted with
    // Ctrl-C at all. But Ctrl-C's SIGINT goes to that *whole* process
    // group, us included: left alone, hande's own shell would be killed
    // right along with the hung command it was only waiting on, dropping
    // you straight back out to your terminal instead of to the `hlg>`
    // prompt. So we ignore SIGINT here for exactly as long as we're
    // waiting -- the command still gets it and can still be interrupted
    // normally -- and restore normal handling the moment we're back.
    unsafe {
        libc::signal(libc::SIGINT, libc::SIG_IGN);
    }
    let result = Command::new(exe).args(args).status();
    unsafe {
        libc::signal(libc::SIGINT, libc::SIG_DFL);
    }
    match result {
        Ok(_) => {}
        Err(err) => eprintln!("Could not run hande: {err}"),
    }
}