trail-fm 1.11.2

A terminal-first workspace for navigating, inspecting and acting on the filesystem
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
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
//! Command Mode grammar: parsing, history, completion, and validation.
//!
//! Handles the `:` and `!`-prefixed command grammar including `:mkdir`,
//! `:touch`, `:rename`, `:mv`, `:cp`, `:git`, `:set`, `:term`, and `!<shell>`.
//!
//! # Grammar
//!
//! ```text
//! command ::= ":" verb (" " arg)*
//!           | "!" shell_string
//!
//! verb    ::= "mkdir" | "touch" | "rename" | "mv" | "cp" | "git" | "set"
//!           | "sort" | "bookmark" | "jump" | "unmark" | "config" | "plugin"
//!           | "term"
//! ```
//!
//! Parsing only validates shape; what a command does is `actions::mod`'s
//! business. `:git` runs `git` through the configured shell, and `:set` goes
//! through `TrailConfig::set_value`.

use std::fs;
use std::path::{Path, PathBuf};

use thiserror::Error;

// ── Parsed command ─────────────────────────────────────────────────────────────

/// A successfully parsed, validated Command Mode input.
///
/// Each variant carries exactly the arguments it needs; the parser rejects
/// inputs that don't match the expected arity or content constraints.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParsedCommand {
    /// Create a directory with the given name inside the current directory.
    Mkdir(String),
    /// Create an empty file with the given name inside the current directory.
    Touch(String),
    /// Rename the currently selected entry to `new_name`.
    Rename(String),
    /// Move the selected entry to `dest` (relative or absolute path).
    Mv(String),
    /// Copy the selected entry to `dest` (relative or absolute path).
    Cp(String),
    /// Move every entry of `cwd` matching `pattern` into the directory `dest`.
    MvMatching {
        /// A name with `*` or `?` in it, matched against the current directory.
        pattern: String,
        /// Destination, which has to be an existing directory: several files
        /// cannot be moved onto one path.
        dest: String,
    },
    /// Copy every entry of `cwd` matching `pattern` into the directory `dest`.
    CpMatching {
        /// A name with `*` or `?` in it, matched against the current directory.
        pattern: String,
        /// Destination, which has to be an existing directory.
        dest: String,
    },
    /// Run a git subcommand string (e.g. `"init"`, `"status --short"`) as
    /// `git <subcommand>` through `[general] shell`, holding the screen
    /// afterwards per `[general] shell_pause`.
    Git(String),
    /// Set a runtime config key to a value, through `TrailConfig::set_value`.
    Set { key: String, value: String },
    /// Re-order the active tab's listing: `:sort [key] [reverse]`.
    ///
    /// `by` is `None` when the command named only `reverse`, which flips the
    /// order already in use rather than choosing a new one.
    Sort {
        /// The key to order by, or `None` to keep the current one.
        by: Option<crate::app::sort::SortBy>,
        /// Whether to flip the resulting order.
        reverse: bool,
    },
    /// Execute an arbitrary shell command string.
    Shell(String),
    /// Add a bookmark: `:bookmark <name>` saves `cwd` under `name`.
    /// If `name` is empty the current directory base-name is used.
    Bookmark(String),
    /// Jump to a previously saved bookmark: `:jump <name>`.
    Jump(String),
    /// Run a custom plugin action: `:plugin <name> [arg]`.
    Plugin { name: String, arg: String },
    /// Drive the terminal panel: `:term`, `:term new [profile]`,
    /// `:term close`, `:term <n>`, `:term max`.
    Term(crate::terminal::TermCommand),
    /// Unmark every marked entry: `:unmark`.
    Unmark,
    /// Save this session's `:set` changes into the config file:
    /// `:config write`.
    ConfigWrite,
}

// ── Parse error ────────────────────────────────────────────────────────────────

/// Validation errors produced during command parsing.
#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum ParseError {
    /// An unrecognised command verb was entered.
    #[error("unknown command '{0}' — try :mkdir, :touch, :rename, :mv, :cp, :git, :set, :sort, :bookmark, :jump, :unmark, :config, :plugin, :term")]
    UnknownVerb(String),
    /// A required argument was not provided.
    #[error("{0} requires an argument")]
    MissingArgument(String),
    /// The argument failed a content constraint (e.g. `/` in a rename).
    #[error("{0}")]
    InvalidArgument(String),
    /// The command buffer is empty.
    #[error("empty command")]
    Empty,
}

// ── Parser ────────────────────────────────────────────────────────────────────

/// Parse `buffer` (the text typed after `:` or `!`) into a [`ParsedCommand`].
///
/// The buffer should **not** include the leading `:` or `!` sentinel — the
/// caller strips it before calling here. The `!` prefix is preserved as a
/// flag argument to distinguish shell execution from `:` commands.
///
/// # Errors
///
/// Returns [`ParseError`] if the buffer is empty, contains an unknown verb,
/// is missing a required argument, or fails content validation.
pub fn parse(buffer: &str, is_shell: bool) -> Result<ParsedCommand, ParseError> {
    if is_shell {
        let cmd = buffer.trim();
        if cmd.is_empty() {
            return Err(ParseError::MissingArgument("!".to_owned()));
        }
        return Ok(ParsedCommand::Shell(cmd.to_owned()));
    }

    let trimmed = buffer.trim();
    if trimmed.is_empty() {
        return Err(ParseError::Empty);
    }

    // Split into verb + rest. The rest after the first word is the argument(s).
    let (verb, rest) = match trimmed.split_once(' ') {
        Some((v, r)) => (v, r.trim()),
        None => (trimmed, ""),
    };

    match verb {
        "mkdir" => {
            if rest.is_empty() {
                return Err(ParseError::MissingArgument("mkdir".to_owned()));
            }
            // Directory names cannot be empty; reject embedded path separators
            // to prevent accidental deep creation.
            let name = rest.to_owned();
            if name.contains('/') || name.contains('\\') {
                return Err(ParseError::InvalidArgument(
                    "mkdir: name must not contain path separators".to_owned(),
                ));
            }
            Ok(ParsedCommand::Mkdir(name))
        }

        "touch" => {
            if rest.is_empty() {
                return Err(ParseError::MissingArgument("touch".to_owned()));
            }
            let name = rest.to_owned();
            if name.contains('/') || name.contains('\\') {
                return Err(ParseError::InvalidArgument(
                    "touch: name must not contain path separators".to_owned(),
                ));
            }
            Ok(ParsedCommand::Touch(name))
        }

        "rename" | "ren" => {
            if rest.is_empty() {
                return Err(ParseError::MissingArgument("rename".to_owned()));
            }
            let new_name = rest.to_owned();
            if new_name.contains('/') || new_name.contains('\\') {
                return Err(ParseError::InvalidArgument(
                    "rename: new name must not contain path separators".to_owned(),
                ));
            }
            Ok(ParsedCommand::Rename(new_name))
        }

        "mv" => {
            if rest.is_empty() {
                return Err(ParseError::MissingArgument("mv".to_owned()));
            }
            match split_pattern_and_dest("mv", rest)? {
                Some((pattern, dest)) => Ok(ParsedCommand::MvMatching { pattern, dest }),
                None => Ok(ParsedCommand::Mv(rest.to_owned())),
            }
        }

        "cp" => {
            if rest.is_empty() {
                return Err(ParseError::MissingArgument("cp".to_owned()));
            }
            match split_pattern_and_dest("cp", rest)? {
                Some((pattern, dest)) => Ok(ParsedCommand::CpMatching { pattern, dest }),
                None => Ok(ParsedCommand::Cp(rest.to_owned())),
            }
        }

        "git" => {
            if rest.is_empty() {
                return Err(ParseError::MissingArgument("git".to_owned()));
            }
            Ok(ParsedCommand::Git(rest.to_owned()))
        }

        "set" => {
            // Expect: set <key> <value>
            let (key, value) = match rest.split_once(' ') {
                Some((k, v)) => (k.trim(), v.trim()),
                None => {
                    return Err(ParseError::MissingArgument(
                        "set requires <key> <value>".to_owned(),
                    ));
                }
            };
            if key.is_empty() {
                return Err(ParseError::MissingArgument("set: key is empty".to_owned()));
            }
            if value.is_empty() {
                return Err(ParseError::MissingArgument(
                    "set: value is empty".to_owned(),
                ));
            }
            Ok(ParsedCommand::Set {
                key: key.to_owned(),
                value: value.to_owned(),
            })
        }

        "sort" => {
            // `:sort`, `:sort <key>`, `:sort reverse`, `:sort <key> reverse` —
            // in any order, because "sort reverse size" is the same request as
            // "sort size reverse" and refusing it teaches nothing.
            let mut by = None;
            let mut reverse = false;
            for word in rest.split_whitespace() {
                if word.eq_ignore_ascii_case("reverse") || word.eq_ignore_ascii_case("rev") {
                    reverse = true;
                } else if let Some(key) = crate::app::sort::SortBy::parse(word) {
                    by = Some(key);
                } else {
                    return Err(ParseError::InvalidArgument(format!(
                        "sort: '{word}' is not a sort key ({})",
                        crate::app::sort::SORT_BY_REASON
                    )));
                }
            }
            if by.is_none() && !reverse {
                return Err(ParseError::MissingArgument(
                    "sort requires a key (name, size, modified, extension) or 'reverse'".to_owned(),
                ));
            }
            Ok(ParsedCommand::Sort { by, reverse })
        }

        "bookmark" | "bm" => {
            // :bookmark [name] — name is optional; empty string means
            // "use the cwd base-name" (resolved at execution time).
            let name = rest.trim().to_owned();
            if name.contains('/') || name.contains('\\') {
                return Err(ParseError::InvalidArgument(
                    "bookmark: name must not contain path separators".to_owned(),
                ));
            }
            Ok(ParsedCommand::Bookmark(name))
        }

        "jump" | "j" => {
            // :jump <name> — name is required.
            let name = rest.trim();
            if name.is_empty() {
                return Err(ParseError::MissingArgument("jump".to_owned()));
            }
            Ok(ParsedCommand::Jump(name.to_owned()))
        }

        "plugin" => {
            // :plugin <action_name> [arg] — action name is required.
            let rest_trimmed = rest.trim();
            if rest_trimmed.is_empty() {
                return Err(ParseError::MissingArgument("plugin".to_owned()));
            }
            let (name, arg) = match rest_trimmed.split_once(' ') {
                Some((n, a)) => (n.trim(), a.trim()),
                None => (rest_trimmed, ""),
            };
            if name.is_empty() {
                return Err(ParseError::MissingArgument("plugin".to_owned()));
            }
            Ok(ParsedCommand::Plugin {
                name: name.to_owned(),
                arg: arg.to_owned(),
            })
        }

        "term" => parse_term(rest),

        "config" => match rest {
            "write" => Ok(ParsedCommand::ConfigWrite),
            "" => Err(ParseError::MissingArgument(
                "config needs a subcommand: write".to_owned(),
            )),
            other => Err(ParseError::InvalidArgument(format!(
                "config: '{other}' is not a subcommand (write)"
            ))),
        },

        "unmark" => {
            if !rest.is_empty() {
                return Err(ParseError::InvalidArgument(
                    "unmark takes no argument".to_owned(),
                ));
            }
            Ok(ParsedCommand::Unmark)
        }

        other => Err(ParseError::UnknownVerb(other.to_owned())),
    }
}

/// Parses the arguments of `:term`.
fn parse_term(rest: &str) -> Result<ParsedCommand, ParseError> {
    use crate::terminal::TermCommand;

    let mut words = rest.split_whitespace();
    let command = match words.next() {
        None => TermCommand::Toggle,
        Some("new") => TermCommand::New(words.next().map(str::to_owned)),
        Some("close") => TermCommand::Close,
        Some("max") => TermCommand::Max,
        Some(word) => match word.parse::<usize>() {
            Ok(n) if n > 0 => TermCommand::Select(n),
            _ => {
                return Err(ParseError::InvalidArgument(format!(
                    "term: '{word}' is not new, close, max or a shell number"
                )))
            }
        },
    };
    if let Some(extra) = words.next() {
        return Err(ParseError::InvalidArgument(format!(
            "term: unexpected '{extra}'"
        )));
    }
    Ok(ParsedCommand::Term(command))
}

/// Splits the argument of `:mv`/`:cp` into a wildcard pattern and a destination,
/// or `None` when it is an ordinary one-argument destination.
///
/// The first whitespace-separated token decides: a `*` or a `?` in it means the
/// user is naming several files, and everything after it is the destination.
/// Nothing else is treated as two arguments, which is what keeps a destination
/// containing a space (`:mv my folder`) working exactly as before -- `*` and `?`
/// cannot appear in a Windows filename at all.
///
/// # Errors
///
/// Returns [`ParseError::MissingArgument`] for a pattern with no destination
/// after it: there is no sensible default, and guessing `cwd` would move files
/// onto themselves.
fn split_pattern_and_dest(verb: &str, rest: &str) -> Result<Option<(String, String)>, ParseError> {
    let (first, remainder) = match rest.split_once(char::is_whitespace) {
        Some((first, remainder)) => (first, remainder.trim()),
        None => (rest, ""),
    };

    if !crate::actions::fs_ops::is_pattern(first) {
        return Ok(None);
    }
    if remainder.is_empty() {
        return Err(ParseError::MissingArgument(format!(
            "{verb} {first} needs a destination directory"
        )));
    }
    Ok(Some((first.to_owned(), remainder.to_owned())))
}

// ── Completion ────────────────────────────────────────────────────────────────

/// Returns a list of completion candidates for the current command `buffer`.
///
/// Completions are provided for:
/// - **Verb completion**: when the buffer is a prefix of a known verb (no
///   space typed yet), return the full verb with a trailing space.
/// - **Path completion**: for `:mv` and `:cp`, complete the destination
///   argument against filesystem entries. A destination that is a whole route
///   (`nested\`, `..\dst\re`, `C:\Users\me\Desk`) is completed against the
///   directory the route names, not against `cwd`. Directory candidates carry
///   a trailing separator, so a route can be walked one `Tab` at a time.
///
/// The returned `Vec` is empty when no completions apply. The caller should
/// cycle through candidates on repeated `Tab` presses.
///
/// `is_shell`: whether the buffer came from a `!`-prefixed input (no verb
/// completion applies — the shell handles its own completion).
#[allow(dead_code)]
pub fn completions(buffer: &str, cwd: &Path, is_shell: bool) -> Vec<String> {
    completions_with_sources(buffer, cwd, is_shell, &CompletionSources::default())
}

/// What completion can offer beyond verbs and the filesystem: names that live
/// in Trail's own state rather than on disk.
#[derive(Debug, Default, Clone, Copy)]
pub struct CompletionSources<'a> {
    /// Registered plugin action names, for `:plugin`.
    pub plugin_actions: &'a [&'a str],
    /// Bookmarks as `(name, path)`, for an `@name` destination of `:mv`/`:cp`.
    pub bookmarks: &'a [(String, PathBuf)],
}

/// Same as [`completions`], but with plugin action names and bookmarks to
/// offer as well.
pub fn completions_with_sources(
    buffer: &str,
    cwd: &Path,
    is_shell: bool,
    sources: &CompletionSources<'_>,
) -> Vec<String> {
    if is_shell {
        return Vec::new(); // shell completion not handled here
    }

    let trimmed = buffer.trim_start();

    // If there's no space yet, complete the verb.
    if !trimmed.contains(' ') {
        let prefix = trimmed;
        let verbs = [
            "mkdir", "touch", "rename", "mv", "cp", "git", "set", "sort", "bookmark", "jump",
            "unmark", "config", "plugin", "term",
        ];
        return verbs
            .iter()
            .filter(|v| v.starts_with(prefix))
            .map(|v| format!("{v} "))
            .collect();
    }

    // Verb is typed — check sub-completions.
    let (verb, partial) = match trimmed.split_once(' ') {
        Some((v, p)) => (v, p),
        None => return Vec::new(),
    };

    if verb == "plugin" {
        let mut candidates: Vec<String> = sources
            .plugin_actions
            .iter()
            .filter(|a| partial.is_empty() || a.starts_with(partial))
            .map(|a| a.to_string())
            .collect();
        candidates.sort();
        return candidates;
    }

    if !matches!(verb, "mv" | "cp") {
        return Vec::new();
    }

    if let Some(after_at) = partial.strip_prefix('@') {
        return bookmark_completions(after_at, sources.bookmarks);
    }

    // Complete `partial` against entries in cwd.
    path_completions(partial, cwd)
}

/// Completes an `@name` destination: the bookmark names first, then — once a
/// separator follows the name — the route inside the bookmarked directory.
///
/// `after_at` is what follows the `@`. Candidates are whole tokens, `@` and
/// all, because [`apply_completion`] replaces the whole token.
fn bookmark_completions(after_at: &str, bookmarks: &[(String, PathBuf)]) -> Vec<String> {
    match after_at.find(std::path::is_separator) {
        None => {
            let mut names: Vec<String> = bookmarks
                .iter()
                .filter(|(name, _)| name.starts_with(after_at))
                .map(|(name, _)| format!("@{name}{}", std::path::MAIN_SEPARATOR))
                .collect();
            names.sort();
            names
        }
        Some(split) => {
            let (name, route) = after_at.split_at(split);
            let Some((_, base)) = bookmarks.iter().find(|(n, _)| n == name) else {
                return Vec::new();
            };
            // `route` still starts with its separator, which is what the
            // bookmark name is joined back on with.
            let (sep, inner) = route.split_at(1);
            // With no route of its own, `path_completions` ends a directory
            // with the platform separator; the one typed after the name is
            // the one to keep, as it is everywhere else.
            let respell = !inner.contains(std::path::is_separator);
            path_completions(inner, base)
                .into_iter()
                .map(
                    |candidate| match candidate.strip_suffix(std::path::MAIN_SEPARATOR) {
                        Some(dir) if respell => format!("@{name}{sep}{dir}{sep}"),
                        _ => format!("@{name}{sep}{candidate}"),
                    },
                )
                .collect()
        }
    }
}

/// Returns filesystem-based completion candidates matching `partial`.
///
/// `partial` is the destination typed so far. It may be a bare name (`no`), a
/// route into a subdirectory (`nested\re`, `..\dst\`) or an absolute path
/// (`C:\Users\me\Desk`). Everything up to the last separator names the
/// directory to list; what follows is the prefix to match against its entries
/// (case-sensitive). A route that names no directory is completed against
/// `cwd`, as before.
///
/// Each candidate is the whole token to put back on the command line, route
/// included, because [`apply_completion`] replaces the entire space-delimited
/// token. Directories carry a trailing separator so a route can be walked one
/// `Tab` at a time, and the separator the user already typed is the one used —
/// a route typed with `\` stays spelled with `\`.
fn path_completions(partial: &str, cwd: &Path) -> Vec<String> {
    // `std::path::is_separator` is the platform's own answer: `/` and `\` on
    // Windows, `/` alone on Unix, where a backslash is an ordinary character in
    // a file name and must not split a route.
    let split_at = partial.rfind(std::path::is_separator).map_or(0, |i| i + 1);
    let (route, name_prefix) = partial.split_at(split_at);

    let search_dir = if route.is_empty() {
        cwd.to_owned()
    } else {
        // `join` is correct for every shape a route can take here, including a
        // Windows path that is rooted but has no drive (`\Users`), which
        // replaces everything but `cwd`'s drive letter.
        cwd.join(route)
    };

    let read = match fs::read_dir(&search_dir) {
        Ok(r) => r,
        Err(_) => return Vec::new(),
    };

    let separator = route
        .chars()
        .next_back()
        .filter(|c| std::path::is_separator(*c))
        .unwrap_or(std::path::MAIN_SEPARATOR);

    let mut candidates: Vec<String> = read
        .filter_map(|e| e.ok())
        .filter_map(|entry| {
            let name = entry.file_name().into_string().ok()?;
            if !name.starts_with(name_prefix) {
                return None;
            }
            let is_dir = entry.file_type().map(|t| t.is_dir()).unwrap_or(false);
            if is_dir {
                Some(format!("{route}{name}{separator}"))
            } else {
                Some(format!("{route}{name}"))
            }
        })
        .collect();

    candidates.sort();
    candidates
}

// ── Command history ───────────────────────────────────────────────────────────

/// Maximum number of entries kept in the command history ring buffer.
const HISTORY_CAPACITY: usize = 100;

/// A ring buffer of past commands, persisted to a small cache file.
///
/// The buffer stores the most recent `HISTORY_CAPACITY` unique commands.
/// Duplicate consecutive entries are deduplicated. History is persisted in a
/// newline-delimited text file: one command per line, most-recent last.
#[derive(Debug, Default)]
pub struct CommandHistory {
    /// Entries, oldest first, most-recent last.
    entries: Vec<String>,
    /// Path to the persistence file; `None` means in-memory only.
    path: Option<PathBuf>,
}

impl CommandHistory {
    /// Creates a new, in-memory-only history buffer.
    pub fn new() -> Self {
        CommandHistory {
            entries: Vec::new(),
            path: None,
        }
    }

    /// Creates a history buffer backed by `path`.
    ///
    /// Existing entries are loaded immediately. If the file does not exist yet
    /// the history starts empty (it will be created on the first `push`). If
    /// the file exists but cannot be read, the history starts empty and will
    /// overwrite the file on the next `push`.
    // clippy: dead_code — called from command_parser_tests.rs and will be
    // wired into AppState::new() once the config dir path is resolved (Phase 7).
    #[allow(dead_code)]
    pub fn with_path(path: PathBuf) -> Self {
        let entries = load_history(&path).unwrap_or_default();
        CommandHistory {
            entries,
            path: Some(path),
        }
    }

    /// Appends `command` to the history, deduplicating consecutive identical
    /// entries and evicting the oldest entry when the ring buffer is full.
    ///
    /// Persists to disk if a path was provided. Errors are silently logged at
    /// `debug` level — history persistence is best-effort, not load-bearing.
    pub fn push(&mut self, command: String) {
        if command.is_empty() {
            return;
        }
        // Deduplicate consecutive identical entries.
        if self.entries.last().map(|s| s.as_str()) == Some(command.as_str()) {
            return;
        }
        // Evict oldest if at capacity.
        if self.entries.len() >= HISTORY_CAPACITY {
            self.entries.remove(0);
        }
        self.entries.push(command);

        if let Some(ref path) = self.path {
            if let Err(e) = save_history(path, &self.entries) {
                tracing::debug!("failed to save command history to {path:?}: {e}");
            }
        }
    }

    /// Returns the number of history entries.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns `true` if there are no history entries.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Returns the entry at position `index` (0 = oldest, len-1 = newest).
    ///
    /// Returns `None` if `index` is out of range.
    pub fn get(&self, index: usize) -> Option<&str> {
        self.entries.get(index).map(String::as_str)
    }

    /// Returns the entry at `offset` positions from the most-recent end.
    ///
    /// `prev(0)` → most-recent; `prev(1)` → second-most-recent; etc.
    /// Returns `None` when `offset` exceeds the number of entries.
    // clippy: dead_code — used in command_parser_tests.rs integration tests.
    #[allow(dead_code)]
    pub fn prev(&self, offset: usize) -> Option<&str> {
        let n = self.entries.len();
        n.checked_sub(offset + 1).and_then(|i| self.get(i))
    }
}

/// Reads a history file. Each non-empty line is one entry.
// clippy: dead_code — called by with_path which is used in tests and
// will be wired into AppState::new() in Phase 7.
#[allow(dead_code)]
fn load_history(path: &Path) -> Option<Vec<String>> {
    let content = fs::read_to_string(path).ok()?;
    let entries: Vec<String> = content
        .lines()
        .filter(|l| !l.is_empty())
        .map(|l| l.to_owned())
        .collect();
    // Trim to capacity in case the file was hand-edited.
    let start = entries.len().saturating_sub(HISTORY_CAPACITY);
    Some(entries[start..].to_vec())
}

/// Writes all history entries to `path`, one per line.
fn save_history(path: &Path, entries: &[String]) -> std::io::Result<()> {
    // Ensure the parent directory exists.
    if let Some(parent) = path.parent() {
        if !parent.exists() {
            fs::create_dir_all(parent)?;
        }
    }
    let content = entries.join("\n");
    fs::write(path, content.as_bytes())?;
    Ok(())
}

// ── Command mode feed (key-level entry point) ─────────────────────────────────

/// The result of feeding one keystroke to Command Mode.
///
/// The caller in `input/mod.rs` dispatches on this to decide which `Action`
/// to queue, if any.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FeedResult {
    /// The buffer was updated but no action should fire yet.
    Updated,
    /// The user pressed `Enter`; `buffer` is the completed input.
    Submit(String),
    /// The user pressed `Esc`; exit Command Mode without executing.
    Cancel,
    /// The user pressed `Tab`; `candidates` is the list of completions and
    /// `index` is which one was cycled to this press.
    Completion {
        candidates: Vec<String>,
        index: usize,
    },
}

/// Feeds a single keystroke into Command Mode state.
///
/// `buffer`: the current typed text (after `:` or `!`).
/// `cursor`: byte offset of the insertion point.
/// `history_index`: current history scroll position (`None` = live buffer).
/// `tab_state`: tracks the current completion cycle.
/// `history`: the command history.
/// `cwd`: current directory, used for path completions.
/// `is_shell`: whether the leading sentinel was `!` (not `:`).
///
/// Mutates `buffer`, `cursor`, and `history_index` in-place. Returns a
/// [`FeedResult`] describing what the caller should do next.
#[allow(dead_code)]
#[allow(clippy::too_many_arguments)]
pub fn feed(
    key: crossterm::event::KeyEvent,
    buffer: &mut String,
    cursor: &mut usize,
    history_index: &mut Option<usize>,
    tab_state: &mut TabState,
    history: &CommandHistory,
    cwd: &Path,
    is_shell: bool,
) -> FeedResult {
    feed_with_sources(
        key,
        buffer,
        cursor,
        history_index,
        tab_state,
        history,
        cwd,
        is_shell,
        &CompletionSources::default(),
    )
}

/// Same as [`feed`], but completion also offers plugin action names and
/// bookmarks.
#[allow(clippy::too_many_arguments)]
pub fn feed_with_sources(
    key: crossterm::event::KeyEvent,
    buffer: &mut String,
    cursor: &mut usize,
    history_index: &mut Option<usize>,
    tab_state: &mut TabState,
    history: &CommandHistory,
    cwd: &Path,
    is_shell: bool,
    sources: &CompletionSources<'_>,
) -> FeedResult {
    use crossterm::event::{KeyCode, KeyModifiers};

    match key.code {
        KeyCode::Esc => FeedResult::Cancel,

        KeyCode::Enter => {
            // Collect the buffer before returning.
            FeedResult::Submit(buffer.clone())
        }

        KeyCode::Backspace => {
            // Delete the character immediately before the cursor.
            if *cursor > 0 {
                // Walk back one UTF-8 character boundary.
                let new_cursor = prev_char_boundary(buffer, *cursor);
                buffer.drain(new_cursor..*cursor);
                *cursor = new_cursor;
                tab_state.reset();
            }
            FeedResult::Updated
        }

        KeyCode::Char('h') if key.modifiers.contains(KeyModifiers::CONTROL) => {
            // Delete the character immediately before the cursor.
            if *cursor > 0 {
                // Walk back one UTF-8 character boundary.
                let new_cursor = prev_char_boundary(buffer, *cursor);
                buffer.drain(new_cursor..*cursor);
                *cursor = new_cursor;
                tab_state.reset();
            }
            FeedResult::Updated
        }

        KeyCode::Delete => {
            // Delete the character at the cursor (forward delete).
            if *cursor < buffer.len() {
                let next = next_char_boundary(buffer, *cursor);
                buffer.drain(*cursor..next);
                tab_state.reset();
            }
            FeedResult::Updated
        }

        KeyCode::Left => {
            if *cursor > 0 {
                *cursor = prev_char_boundary(buffer, *cursor);
            }
            // Moving the cursor abandons the completion cycle: the next `Tab`
            // should complete where the cursor is now, not where it started.
            tab_state.reset();
            FeedResult::Updated
        }

        KeyCode::Right => {
            if *cursor < buffer.len() {
                *cursor = next_char_boundary(buffer, *cursor);
            }
            tab_state.reset();
            FeedResult::Updated
        }

        KeyCode::Up => {
            // Scroll back through history.
            let next_idx = match *history_index {
                None => {
                    if history.is_empty() {
                        return FeedResult::Updated;
                    }
                    history.len() - 1
                }
                Some(i) => i.saturating_sub(1),
            };
            if let Some(entry) = history.get(next_idx) {
                *buffer = entry.to_owned();
                *cursor = buffer.len();
                *history_index = Some(next_idx);
            }
            tab_state.reset();
            FeedResult::Updated
        }

        KeyCode::Down => {
            // Scroll forward through history.
            match *history_index {
                None => FeedResult::Updated,
                Some(i) => {
                    if i + 1 < history.len() {
                        let next_idx = i + 1;
                        if let Some(entry) = history.get(next_idx) {
                            *buffer = entry.to_owned();
                            *cursor = buffer.len();
                            *history_index = Some(next_idx);
                        }
                    } else {
                        // Past the end of history — restore blank buffer.
                        buffer.clear();
                        *cursor = 0;
                        *history_index = None;
                    }
                    tab_state.reset();
                    FeedResult::Updated
                }
            }
        }

        KeyCode::Tab => {
            // Candidates come from the text that opened the cycle, not from the
            // buffer — the previous `Tab` has already overwritten that with a
            // candidate, and completing a completion is how the cycle used to
            // get stuck on its first answer.
            let prefix = tab_state.cycle_prefix(buffer);
            let candidates = completions_with_sources(&prefix, cwd, is_shell, sources);
            if candidates.is_empty() {
                return FeedResult::Updated;
            }
            // Cycle to the next candidate.
            let idx = tab_state.advance(candidates.len());
            // Apply the completion: replace the completed token with the candidate.
            apply_completion(buffer, cursor, &prefix, &candidates[idx], is_shell);
            FeedResult::Completion {
                candidates,
                index: idx,
            }
        }

        KeyCode::Home => {
            *cursor = 0;
            tab_state.reset();
            FeedResult::Updated
        }

        KeyCode::End => {
            *cursor = buffer.len();
            tab_state.reset();
            FeedResult::Updated
        }

        // Only a bare Ctrl is a chord here. AltGr arrives as Ctrl+Alt on
        // Windows and is how `\` is typed (and pasted) on many layouts.
        KeyCode::Char(ch)
            if crate::input::is_text_modifiers(key.modifiers)
                || key.modifiers.contains(KeyModifiers::ALT) =>
        {
            // Insert the character at the cursor position.
            buffer.insert(*cursor, ch);
            *cursor += ch.len_utf8();
            *history_index = None;
            tab_state.reset();
            FeedResult::Updated
        }

        _ => FeedResult::Updated,
    }
}

/// Tracks the current tab-completion cycle.
///
/// Resets when the buffer changes (any non-Tab keystroke).
#[derive(Debug, Default)]
pub struct TabState {
    /// Current position in the candidate list (cycling).
    index: Option<usize>,
    /// The buffer text the cycle is completing, captured on the first `Tab`.
    ///
    /// Applying a completion overwrites the buffer, so the text the user
    /// actually typed is gone by the second `Tab`. Without it, candidates were
    /// recomputed from the completed buffer: `:m` + `Tab` gives `mkdir `, which
    /// contains a space, so the next `Tab` took the path-completion branch,
    /// found `mkdir` is not `mv`/`cp`, and returned nothing — `mv` could never
    /// be reached.
    prefix: Option<String>,
}

impl TabState {
    /// Creates a new, idle `TabState`.
    pub fn new() -> Self {
        TabState {
            index: None,
            prefix: None,
        }
    }

    /// Resets the completion cycle (called on any non-Tab keystroke).
    pub fn reset(&mut self) {
        self.index = None;
        self.prefix = None;
    }

    /// Returns the text this cycle completes, starting a cycle at `buffer` when
    /// none is running.
    ///
    /// Every `Tab` in the same cycle therefore sees the same candidate list, in
    /// the same order, which is what makes [`TabState::advance`] step through it
    /// rather than re-deciding it.
    pub fn cycle_prefix(&mut self, buffer: &str) -> String {
        self.prefix.get_or_insert_with(|| buffer.to_owned()).clone()
    }

    /// Advances to the next completion and returns the new index.
    ///
    /// Wraps around when `len` is exceeded.
    pub fn advance(&mut self, len: usize) -> usize {
        let next = match self.index {
            None => 0,
            Some(i) => (i + 1) % len,
        };
        self.index = Some(next);
        next
    }
}

/// Rewrites `buffer` as `prefix` with its last token replaced by `candidate`.
///
/// `prefix` is what the user typed before the cycle started, not the current
/// buffer: the buffer already holds the previous candidate, and replacing that
/// one's last token would compound completions instead of offering the next.
///
/// For verb completion (no space in `prefix`) the candidate is the whole line.
/// For path completion everything up to the last space is kept.
fn apply_completion(
    buffer: &mut String,
    cursor: &mut usize,
    prefix: &str,
    candidate: &str,
    is_shell: bool,
) {
    if is_shell {
        return; // Shell completions not handled here.
    }
    *buffer = match prefix.rfind(' ') {
        Some(last_space) => format!("{}{candidate}", &prefix[..=last_space]),
        None => candidate.to_owned(),
    };
    *cursor = buffer.len();
}

// ── UTF-8 cursor helpers ─────────────────────────────────────────────────────

/// Returns the byte offset of the start of the character immediately before
/// `cursor` in `s`. Panics if `cursor == 0`; callers must guard.
fn prev_char_boundary(s: &str, cursor: usize) -> usize {
    let mut pos = cursor.saturating_sub(1);
    while pos > 0 && !s.is_char_boundary(pos) {
        pos -= 1;
    }
    pos
}

/// Returns the byte offset of the start of the next character after `cursor`.
fn next_char_boundary(s: &str, cursor: usize) -> usize {
    let mut pos = cursor + 1;
    while pos < s.len() && !s.is_char_boundary(pos) {
        pos += 1;
    }
    pos
}

// ── Unit tests ────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    // ── parse ──────────────────────────────────────────────────────────────────

    #[test]
    fn parse_mkdir_valid() {
        let cmd = parse("mkdir foo", false).unwrap();
        assert_eq!(cmd, ParsedCommand::Mkdir("foo".to_owned()));
    }

    #[test]
    fn parse_mkdir_empty_arg_is_error() {
        let err = parse("mkdir", false).unwrap_err();
        assert!(matches!(err, ParseError::MissingArgument(_)));
    }

    #[test]
    fn parse_mkdir_with_separator_is_error() {
        let err = parse("mkdir foo/bar", false).unwrap_err();
        assert!(matches!(err, ParseError::InvalidArgument(_)));
    }

    #[test]
    fn parse_touch_valid() {
        let cmd = parse("touch new_file.txt", false).unwrap();
        assert_eq!(cmd, ParsedCommand::Touch("new_file.txt".to_owned()));
    }

    #[test]
    fn parse_rename_valid() {
        let cmd = parse("rename new_name", false).unwrap();
        assert_eq!(cmd, ParsedCommand::Rename("new_name".to_owned()));
    }

    #[test]
    fn parse_rename_alias_ren() {
        let cmd = parse("ren new_name", false).unwrap();
        assert_eq!(cmd, ParsedCommand::Rename("new_name".to_owned()));
    }

    #[test]
    fn parse_rename_with_slash_is_error() {
        let err = parse("rename foo/bar", false).unwrap_err();
        assert!(matches!(err, ParseError::InvalidArgument(_)));
    }

    #[test]
    fn parse_mv_valid() {
        let cmd = parse("mv ../somewhere", false).unwrap();
        assert_eq!(cmd, ParsedCommand::Mv("../somewhere".to_owned()));
    }

    #[test]
    fn parse_cp_valid() {
        let cmd = parse("cp backup.txt", false).unwrap();
        assert_eq!(cmd, ParsedCommand::Cp("backup.txt".to_owned()));
    }

    #[test]
    fn parse_git_valid() {
        let cmd = parse("git status --short", false).unwrap();
        assert_eq!(cmd, ParsedCommand::Git("status --short".to_owned()));
    }

    #[test]
    fn parse_git_no_subcommand_is_error() {
        let err = parse("git", false).unwrap_err();
        assert!(matches!(err, ParseError::MissingArgument(_)));
    }

    #[test]
    fn parse_set_valid() {
        let cmd = parse("set git_status_enabled true", false).unwrap();
        assert_eq!(
            cmd,
            ParsedCommand::Set {
                key: "git_status_enabled".to_owned(),
                value: "true".to_owned(),
            }
        );
    }

    #[test]
    fn parse_set_no_value_is_error() {
        let err = parse("set key_only", false).unwrap_err();
        assert!(matches!(err, ParseError::MissingArgument(_)));
    }

    #[test]
    fn parse_sort_key_only() {
        use crate::app::sort::SortBy;
        assert_eq!(
            parse("sort size", false).unwrap(),
            ParsedCommand::Sort {
                by: Some(SortBy::Size),
                reverse: false
            }
        );
    }

    #[test]
    fn parse_sort_key_and_reverse_in_either_word_order() {
        use crate::app::sort::SortBy;
        let expected = ParsedCommand::Sort {
            by: Some(SortBy::Modified),
            reverse: true,
        };
        assert_eq!(parse("sort modified reverse", false).unwrap(), expected);
        assert_eq!(parse("sort reverse modified", false).unwrap(), expected);
    }

    #[test]
    fn parse_sort_reverse_alone_keeps_the_current_key() {
        assert_eq!(
            parse("sort reverse", false).unwrap(),
            ParsedCommand::Sort {
                by: None,
                reverse: true
            }
        );
    }

    #[test]
    fn parse_sort_with_no_argument_is_error() {
        let err = parse("sort", false).unwrap_err();
        assert!(matches!(err, ParseError::MissingArgument(_)));
    }

    #[test]
    fn parse_sort_with_an_unknown_key_is_error() {
        // `created` is the one a user is most likely to reach for; it is not a
        // key because the platform will not reliably report a creation time.
        let err = parse("sort created", false).unwrap_err();
        assert!(matches!(err, ParseError::InvalidArgument(_)), "{err:?}");
    }

    #[test]
    fn parse_empty_is_error() {
        let err = parse("", false).unwrap_err();
        assert!(matches!(err, ParseError::Empty));
    }

    #[test]
    fn parse_unknown_verb_is_error() {
        let err = parse("zap foo", false).unwrap_err();
        assert!(matches!(err, ParseError::UnknownVerb(_)));
    }

    #[test]
    fn parse_plugin_valid() {
        let cmd = parse("plugin my_action", false).unwrap();
        assert_eq!(
            cmd,
            ParsedCommand::Plugin {
                name: "my_action".to_owned(),
                arg: "".to_owned(),
            }
        );
    }

    #[test]
    fn parse_plugin_with_args() {
        let cmd = parse("plugin log_note hello world", false).unwrap();
        assert_eq!(
            cmd,
            ParsedCommand::Plugin {
                name: "log_note".to_owned(),
                arg: "hello world".to_owned(),
            }
        );
    }

    #[test]
    fn parse_plugin_no_action_is_error() {
        let err = parse("plugin", false).unwrap_err();
        assert!(matches!(err, ParseError::MissingArgument(_)));
    }

    #[test]
    fn parse_shell_command() {
        let cmd = parse("ls -la", true).unwrap();
        assert_eq!(cmd, ParsedCommand::Shell("ls -la".to_owned()));
    }

    #[test]
    fn parse_shell_empty_is_error() {
        let err = parse("", true).unwrap_err();
        assert!(matches!(err, ParseError::MissingArgument(_)));
    }

    // ── completions ────────────────────────────────────────────────────────────

    #[test]
    fn verb_completion_prefix_mk() {
        let dir = tempfile::tempdir().unwrap();
        let candidates = completions("mk", dir.path(), false);
        assert!(
            candidates.contains(&"mkdir ".to_owned()),
            "expected 'mkdir ' in candidates: {candidates:?}"
        );
    }

    #[test]
    fn verb_completion_empty_returns_all_verbs() {
        let dir = tempfile::tempdir().unwrap();
        let candidates = completions("", dir.path(), false);
        // A count alone says nothing about *which* verb went missing, so the
        // set is asserted: a verb added to the parser and forgotten here is the
        // failure this catches.
        let mut got: Vec<String> = candidates.iter().map(|c| c.trim().to_owned()).collect();
        got.sort();
        assert_eq!(
            got,
            vec![
                "bookmark", "config", "cp", "git", "jump", "mkdir", "mv", "plugin", "rename",
                "set", "sort", "term", "touch", "unmark",
            ]
        );
    }

    #[test]
    fn plugin_action_completion() {
        let dir = tempfile::tempdir().unwrap();
        let candidates = completions_with_sources(
            "plugin ",
            dir.path(),
            false,
            &CompletionSources {
                plugin_actions: &["log_note", "bookmark_add"],
                bookmarks: &[],
            },
        );
        assert_eq!(candidates, vec!["bookmark_add", "log_note"]);
    }

    #[test]
    fn verb_completion_no_match_returns_empty() {
        let dir = tempfile::tempdir().unwrap();
        let candidates = completions("zzz", dir.path(), false);
        assert!(candidates.is_empty());
    }

    #[test]
    fn path_completion_for_mv() {
        use std::fs;
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("alpha.txt"), b"").unwrap();
        fs::write(dir.path().join("beta.txt"), b"").unwrap();

        let candidates = completions("mv al", dir.path(), false);
        assert!(
            candidates.contains(&"alpha.txt".to_owned()),
            "expected 'alpha.txt' in candidates: {candidates:?}"
        );
        assert!(
            !candidates.contains(&"beta.txt".to_owned()),
            "beta.txt should not match prefix 'al'"
        );
    }

    #[test]
    fn no_path_completion_for_mkdir() {
        let dir = tempfile::tempdir().unwrap();
        let candidates = completions("mkdir so", dir.path(), false);
        assert!(
            candidates.is_empty(),
            "path completion should not apply to mkdir"
        );
    }

    // ── CommandHistory ─────────────────────────────────────────────────────────

    #[test]
    fn history_push_and_retrieve() {
        let mut h = CommandHistory::new();
        h.push("mkdir foo".to_owned());
        h.push("touch bar".to_owned());
        assert_eq!(h.len(), 2);
        assert_eq!(h.prev(0), Some("touch bar"));
        assert_eq!(h.prev(1), Some("mkdir foo"));
    }

    #[test]
    fn history_deduplicates_consecutive_identical() {
        let mut h = CommandHistory::new();
        h.push("mkdir foo".to_owned());
        h.push("mkdir foo".to_owned());
        assert_eq!(h.len(), 1);
    }

    #[test]
    fn history_allows_non_consecutive_duplicate() {
        let mut h = CommandHistory::new();
        h.push("mkdir foo".to_owned());
        h.push("touch bar".to_owned());
        h.push("mkdir foo".to_owned());
        assert_eq!(h.len(), 3);
    }

    #[test]
    fn history_evicts_oldest_at_capacity() {
        let mut h = CommandHistory::new();
        for i in 0..HISTORY_CAPACITY + 5 {
            h.push(format!("cmd{i}"));
        }
        assert_eq!(h.len(), HISTORY_CAPACITY);
        // The oldest entries should be gone; the most recent should survive.
        assert_eq!(
            h.prev(0),
            Some(format!("cmd{}", HISTORY_CAPACITY + 4).as_str())
        );
    }

    #[test]
    fn history_persist_and_reload() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("history.txt");

        let mut h = CommandHistory::with_path(path.clone());
        h.push("mkdir foo".to_owned());
        h.push("touch bar".to_owned());

        // Reload from the same path.
        let h2 = CommandHistory::with_path(path);
        assert_eq!(h2.len(), 2);
        assert_eq!(h2.prev(0), Some("touch bar"));
    }

    // ── feed (tab completion) ──────────────────────────────────────────────────

    /// Presses `Tab` `times` times against `buffer` and returns what the buffer
    /// became, driving the same `TabState` throughout as a real session does.
    fn tab_cycle(buffer: &str, cwd: &Path, times: usize) -> Vec<String> {
        use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers};
        let mut buf = buffer.to_owned();
        let mut cursor = buf.len();
        let mut hist_idx = None;
        let mut tab = TabState::new();
        let h = CommandHistory::new();
        let key = KeyEvent {
            code: KeyCode::Tab,
            modifiers: KeyModifiers::NONE,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        };

        (0..times)
            .map(|_| {
                feed(
                    key,
                    &mut buf,
                    &mut cursor,
                    &mut hist_idx,
                    &mut tab,
                    &h,
                    cwd,
                    false,
                );
                buf.clone()
            })
            .collect()
    }

    /// The bug this guards: applying a completion overwrote the buffer, and the
    /// next `Tab` recomputed candidates from *that*. `:m` completed to `mkdir `,
    /// which contains a space, so the second `Tab` looked for path completions
    /// for a verb that takes none and found nothing — `mv` was unreachable.
    #[test]
    fn tab_cycles_through_verb_completions_and_wraps() {
        let dir = tempfile::tempdir().unwrap();
        assert_eq!(
            tab_cycle("m", dir.path(), 3),
            vec!["mkdir ", "mv ", "mkdir "],
            "Tab must step through every verb sharing the prefix, then wrap"
        );
    }

    #[test]
    fn tab_cycles_through_path_completions() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("alpha.txt"), b"").unwrap();
        fs::write(dir.path().join("alpine.txt"), b"").unwrap();

        assert_eq!(
            tab_cycle("mv al", dir.path(), 3),
            vec!["mv alpha.txt", "mv alpine.txt", "mv alpha.txt"],
            "a destination with two matches must offer both"
        );
    }

    /// Typing anything ends the cycle, so the next `Tab` completes what is on
    /// the line now rather than continuing an abandoned list.
    #[test]
    fn editing_restarts_the_completion_cycle() {
        use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers};
        let dir = tempfile::tempdir().unwrap();
        let mut buf = "m".to_owned();
        let mut cursor = buf.len();
        let mut hist_idx = None;
        let mut tab = TabState::new();
        let h = CommandHistory::new();
        let press = |code| KeyEvent {
            code,
            modifiers: KeyModifiers::NONE,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        };

        let mut send = |code, buf: &mut String, cursor: &mut usize| {
            feed(
                press(code),
                buf,
                cursor,
                &mut hist_idx,
                &mut tab,
                &h,
                dir.path(),
                false,
            );
        };

        send(KeyCode::Tab, &mut buf, &mut cursor);
        assert_eq!(buf, "mkdir ");
        // Backspace leaves "mkdir", which is a complete verb on its own.
        send(KeyCode::Backspace, &mut buf, &mut cursor);
        send(KeyCode::Tab, &mut buf, &mut cursor);
        assert_eq!(
            buf, "mkdir ",
            "the new cycle completes the edited text, not the old prefix"
        );
    }

    // ── feed (cursor movement) ─────────────────────────────────────────────────

    #[test]
    fn feed_char_appends_to_buffer() {
        use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers};
        let dir = tempfile::tempdir().unwrap();
        let mut buf = String::new();
        let mut cursor = 0usize;
        let mut hist_idx = None;
        let mut tab = TabState::new();
        let h = CommandHistory::new();

        let key = KeyEvent {
            code: KeyCode::Char('m'),
            modifiers: KeyModifiers::NONE,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        };
        let result = feed(
            key,
            &mut buf,
            &mut cursor,
            &mut hist_idx,
            &mut tab,
            &h,
            dir.path(),
            false,
        );
        assert_eq!(result, FeedResult::Updated);
        assert_eq!(buf, "m");
        assert_eq!(cursor, 1);
    }

    /// A pasted Windows path arrives one key at a time, and on layouts where
    /// `\` needs AltGr each backslash carries Ctrl+Alt. None may be dropped.
    #[test]
    fn feed_keeps_altgr_backslashes_of_a_pasted_path() {
        use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers};
        let dir = tempfile::tempdir().unwrap();
        let mut buf = String::new();
        let mut cursor = 0usize;
        let mut hist_idx = None;
        let mut tab = TabState::new();
        let h = CommandHistory::new();

        let pasted = r"C:\Users\me\file.txt";
        for ch in pasted.chars() {
            let modifiers = match ch {
                '\\' => KeyModifiers::CONTROL | KeyModifiers::ALT,
                ':' | 'C' | 'U' => KeyModifiers::SHIFT,
                _ => KeyModifiers::NONE,
            };
            let key = KeyEvent {
                code: KeyCode::Char(ch),
                modifiers,
                kind: KeyEventKind::Press,
                state: KeyEventState::NONE,
            };
            feed(
                key,
                &mut buf,
                &mut cursor,
                &mut hist_idx,
                &mut tab,
                &h,
                dir.path(),
                false,
            );
        }
        assert_eq!(buf, pasted);
        assert_eq!(cursor, pasted.len());
    }

    #[test]
    fn feed_bare_ctrl_char_is_not_text() {
        use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers};
        let dir = tempfile::tempdir().unwrap();
        let mut buf = String::new();
        let mut cursor = 0usize;
        let mut hist_idx = None;
        let mut tab = TabState::new();
        let h = CommandHistory::new();

        let key = KeyEvent {
            code: KeyCode::Char('x'),
            modifiers: KeyModifiers::CONTROL,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        };
        feed(
            key,
            &mut buf,
            &mut cursor,
            &mut hist_idx,
            &mut tab,
            &h,
            dir.path(),
            false,
        );
        assert!(buf.is_empty());
    }

    #[test]
    fn feed_enter_submits_buffer() {
        use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers};
        let dir = tempfile::tempdir().unwrap();
        let mut buf = "mkdir foo".to_owned();
        let mut cursor = buf.len();
        let mut hist_idx = None;
        let mut tab = TabState::new();
        let h = CommandHistory::new();

        let key = KeyEvent {
            code: KeyCode::Enter,
            modifiers: KeyModifiers::NONE,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        };
        let result = feed(
            key,
            &mut buf,
            &mut cursor,
            &mut hist_idx,
            &mut tab,
            &h,
            dir.path(),
            false,
        );
        assert_eq!(result, FeedResult::Submit("mkdir foo".to_owned()));
    }

    #[test]
    fn feed_esc_cancels() {
        use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers};
        let dir = tempfile::tempdir().unwrap();
        let mut buf = "mkdir foo".to_owned();
        let mut cursor = buf.len();
        let mut hist_idx = None;
        let mut tab = TabState::new();
        let h = CommandHistory::new();

        let key = KeyEvent {
            code: KeyCode::Esc,
            modifiers: KeyModifiers::NONE,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        };
        let result = feed(
            key,
            &mut buf,
            &mut cursor,
            &mut hist_idx,
            &mut tab,
            &h,
            dir.path(),
            false,
        );
        assert_eq!(result, FeedResult::Cancel);
    }

    #[test]
    fn feed_backspace_removes_last_char() {
        use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers};
        let dir = tempfile::tempdir().unwrap();
        let mut buf = "abc".to_owned();
        let mut cursor = 3usize;
        let mut hist_idx = None;
        let mut tab = TabState::new();
        let h = CommandHistory::new();

        let key = KeyEvent {
            code: KeyCode::Backspace,
            modifiers: KeyModifiers::NONE,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        };
        feed(
            key,
            &mut buf,
            &mut cursor,
            &mut hist_idx,
            &mut tab,
            &h,
            dir.path(),
            false,
        );
        assert_eq!(buf, "ab");
        assert_eq!(cursor, 2);
    }
}