sedx 1.2.0

A safe, modern replacement for GNU sed with automatic backups, preview mode, and rollback
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
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
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
use anyhow::{Result, anyhow, bail};

use crate::command::{Address, Command, SubstitutionFlags};

/// Maximum context characters to show around error position
const ERROR_CONTEXT_SIZE: usize = 30;

/// Helper function to extract context around an error position
fn extract_context(full_text: &str, pos: usize) -> String {
    let start = pos.saturating_sub(ERROR_CONTEXT_SIZE);
    let end = if pos + ERROR_CONTEXT_SIZE < full_text.len() {
        pos + ERROR_CONTEXT_SIZE
    } else {
        full_text.len()
    };

    let mut context = full_text[start..end].to_string();
    if start > 0 {
        context.insert_str(0, "...");
    }
    if end < full_text.len() {
        context.push_str("...");
    }
    context
}

/// Format an error with context and suggestions
fn format_parse_error(
    expression: &str,
    error_pos: Option<usize>,
    description: &str,
    suggestion: Option<&str>,
) -> String {
    let mut msg = format!("Parse error: {}", description);

    if let Some(pos) = error_pos {
        let context = extract_context(expression, pos);
        msg.push_str(&format!("\n  Near: \"{}\"", context));
    }

    if let Some(hint) = suggestion {
        msg.push_str(&format!("\n  Hint: {}", hint));
    }

    msg
}

/// Fold a raw sed-flag character sequence into a SubstitutionFlags value.
/// Numeric flags set `nth`; recognised letters flip their corresponding bool.
/// Unknown characters are ignored (matches GNU sed's lenience).
fn fold_substitution_flags(flags: &[char]) -> SubstitutionFlags {
    let mut out = SubstitutionFlags::default();
    for flag in flags {
        match flag {
            'g' => out.global = true,
            'p' => out.print = true,
            'i' | 'I' => out.case_insensitive = true,
            '0'..='9' => {
                // ASCII digit guaranteed by the arm's pattern; to_digit can't fail.
                out.nth = Some(flag.to_digit(10).unwrap() as usize);
            }
            _ => {} // Ignore unknown flags
        }
    }
    out
}

pub fn parse_sed_expression(expr: &str) -> Result<Vec<Command>> {
    let mut commands = Vec::new();

    // Handle multiple expressions separated by ;
    // But skip semicolons inside braces { ... }
    let mut current_expr = String::new();
    let mut in_braces = 0;
    let chars = expr.chars().peekable();

    for c in chars {
        match c {
            '{' => {
                in_braces += 1;
                current_expr.push(c);
            }
            '}' => {
                in_braces -= 1;
                current_expr.push(c);
            }
            ';' if in_braces == 0 => {
                // Semicolon at top level - command separator
                let part = current_expr.trim();
                if !part.is_empty() {
                    commands.push(parse_single_command(part)?);
                }
                current_expr.clear();
            }
            _ => {
                current_expr.push(c);
            }
        }
    }

    // Don't forget the last expression
    let part = current_expr.trim();
    if !part.is_empty() {
        commands.push(parse_single_command(part)?);
    }

    Ok(commands)
}

/// Helper function to check if a position is inside a pattern address
/// Pattern addresses are delimited by '/' or '\', e.g., /pattern/ or \pattern\
/// Returns true if the position is inside the delimiters (not at the delimiters themselves)
fn is_inside_pattern_address(cmd: &str, pos: usize) -> bool {
    let bytes = cmd.as_bytes();
    let limit = pos.min(bytes.len());

    // Phase 1: left-to-right open/close scan up to `pos`.
    // A pattern address opens with `/` (or `\X` backslash-custom-delim).
    // Once open, `\X` escapes the next char; the matching opener char closes.
    let mut i = 0;
    let mut current_opener: Option<u8> = None;
    while i < limit {
        let byte = bytes[i];
        match current_opener {
            None => {
                if byte == b'/' || byte == b'\\' {
                    current_opener = Some(byte);
                }
            }
            Some(opener) => {
                if byte == b'\\' && i + 1 < limit {
                    i += 2;
                    continue;
                }
                if byte == opener {
                    current_opener = None;
                }
            }
        }
        i += 1;
    }

    // If we are still waiting for a closer, we are inside a pattern address.
    if current_opener.is_some() {
        return true;
    }

    // Phase 2 covers the substitution replacement region (e.g. the `r` in
    // `s/foo/bar/`), where Phase 1 exits in the `None` state because the
    // pattern sub-region already closed. Discriminator: whitespace before the
    // next slash indicates a filename argument, not a paired closing delimiter.
    let has_slash_before = (0..pos)
        .rev()
        .any(|j| bytes[j] == b'/' && (j == 0 || bytes[j - 1] != b'\\'));
    if !has_slash_before {
        return false;
    }
    for &byte in bytes.iter().skip(pos + 1) {
        if byte.is_ascii_whitespace() {
            break;
        }
        if byte == b'/' {
            return true;
        }
    }

    false
}

/// Attempt to dispatch a file-I/O command (`r` / `R` / `w` / `W`). Returns
/// `Ok(Some(_))` on a successful dispatch, `Ok(None)` if the command does
/// not look like a file-I/O command (so callers fall through to other
/// dispatchers), or `Err(_)` if a file-I/O dispatch fired but the sub-parser
/// itself failed.
///
/// This helper exists so file-I/O dispatch can run BEFORE the marker-based
/// (`s/`, `i\`, `a\`, `c\`) dispatch. A filename payload like
/// `/var/folders/xx/yy/T/.tmpZZ/data.txt` legitimately contains `s/` (inside
/// the `folders/` segment), and without this ordering the whole command
/// `R /var/folders/...` gets misrouted to `parse_substitution`.
fn try_parse_file_io(cmd: &str) -> Result<Option<Command>> {
    let trimmed = cmd.trim();
    if !(trimmed.contains('r')
        || trimmed.contains('R')
        || trimmed.contains('w')
        || trimmed.contains('W'))
    {
        return Ok(None);
    }

    // Positions of each command character. Pattern-address `/.../` content
    // is filtered out because that's where `r`/`R` etc. commonly appear as
    // incidental letters rather than as command chars.
    let mut r_positions: Vec<usize> = trimmed.match_indices('r').map(|(i, _)| i).collect();
    let mut r_upper_positions: Vec<usize> = trimmed.match_indices('R').map(|(i, _)| i).collect();
    let mut w_positions: Vec<usize> = trimmed.match_indices('w').map(|(i, _)| i).collect();
    let mut w_upper_positions: Vec<usize> = trimmed.match_indices('W').map(|(i, _)| i).collect();

    r_positions.retain(|&pos| !is_inside_pattern_address(trimmed, pos));
    r_upper_positions.retain(|&pos| !is_inside_pattern_address(trimmed, pos));
    w_positions.retain(|&pos| !is_inside_pattern_address(trimmed, pos));
    w_upper_positions.retain(|&pos| !is_inside_pattern_address(trimmed, pos));

    // If an insert / append / change marker (`i\`, `a\`, `c\`) appears in
    // the command, its text payload follows the backslash and may contain
    // any characters — including `r`, `R`, `w`, `W`. Positions past the
    // earliest i/a/c marker are therefore part of the text payload, not
    // file-I/O command characters.
    let iac_pos = [
        trimmed.find("i\\"),
        trimmed.find("a\\"),
        trimmed.find("c\\"),
    ]
    .into_iter()
    .flatten()
    .min();

    let keep = |&pos: &usize| -> bool {
        match iac_pos {
            Some(iac) => pos < iac,
            None => true,
        }
    };
    let all_positions: Vec<(usize, char)> = r_positions
        .iter()
        .copied()
        .filter(keep)
        .map(|p| (p, 'r'))
        .chain(
            r_upper_positions
                .iter()
                .copied()
                .filter(keep)
                .map(|p| (p, 'R')),
        )
        .chain(w_positions.iter().copied().filter(keep).map(|p| (p, 'w')))
        .chain(
            w_upper_positions
                .iter()
                .copied()
                .filter(keep)
                .map(|p| (p, 'W')),
        )
        .collect();

    let Some(&(pos, char_at_pos)) = all_positions.iter().min_by_key(|(p, _)| p) else {
        return Ok(None);
    };

    // After the command char there must be a filename (possibly with
    // leading whitespace). An empty tail means this is just a suffix
    // character of a different command (e.g. `/pat/w` with the `w` closing
    // the pattern? — doesn't happen in practice, but be conservative).
    let rest = &trimmed[pos + 1..];
    if rest.trim().is_empty() {
        return Ok(None);
    }

    let parsed = match char_at_pos {
        'r' => parse_read_file(cmd)?,
        'R' => parse_read_line(cmd)?,
        'w' => parse_write_file(cmd)?,
        'W' => parse_write_first_line(cmd)?,
        _ => unreachable!(),
    };
    Ok(Some(parsed))
}

fn parse_single_command(cmd: &str) -> Result<Command> {
    let cmd = cmd.trim();

    // Check for command grouping with braces
    if cmd.contains('{') {
        return parse_group(cmd);
    }

    // Check for r/R/w/W (file I/O) commands FIRST, before the marker-based
    // dispatch below. File I/O commands carry a filename payload that may
    // legitimately contain any of the marker substrings — e.g. a path
    // segment like `/folders/` trips the "s/" marker and misroutes the
    // whole command to `parse_substitution`. See `try_parse_file_io` for
    // the details of how pattern-address delimiters are filtered out so
    // this does not misfire on real substitutions.
    if let Some(cmd_out) = try_parse_file_io(cmd)? {
        return Ok(cmd_out);
    }

    // Dispatch based on the EARLIEST occurrence of a command marker in the command string.
    // This correctly handles cases where a marker appears inside the text/pattern of
    // another command (e.g., `2i\s/foo/bar/g` — insert literal "s/foo/bar/g"; or
    // `s/i\foo/bar/` — substitution whose pattern contains "i\").
    type Handler = fn(&str) -> Result<Command>;
    const CANDIDATES: &[(&str, Handler)] = &[
        ("i\\", parse_insert),
        ("a\\", parse_append),
        ("c\\", parse_change),
        ("s/", parse_substitution),
        ("s#", parse_substitution),
        ("s:", parse_substitution),
        ("s|", parse_substitution),
    ];

    let earliest = CANDIDATES
        .iter()
        .filter_map(|(marker, handler)| cmd.find(marker).map(|pos| (pos, *handler)))
        .min_by_key(|(pos, _)| *pos);

    if let Some((_, handler)) = earliest {
        return handler(cmd);
    }

    // Check for hold space commands
    // These need to be checked carefully to avoid confusion with substitution patterns
    let last_char = cmd.chars().last().unwrap_or(' ');

    if last_char == 'h' || last_char == 'H' {
        // Hold command - check it's not part of a substitution
        if !cmd.starts_with('s') && cmd.chars().filter(|&c| c == 's').count() <= 1 {
            return if last_char == 'H' {
                parse_hold_append(cmd)
            } else {
                parse_hold(cmd)
            };
        }
    }

    if last_char == 'g' || last_char == 'G' {
        // Get command - check it's not part of a substitution
        if !cmd.starts_with('s') && cmd.chars().filter(|&c| c == 's').count() <= 1 {
            return if last_char == 'G' {
                parse_get_append(cmd)
            } else {
                parse_get(cmd)
            };
        }
    }

    if last_char == 'x' {
        // Exchange command - check it's not part of a substitution
        if !cmd.starts_with('s') && cmd.chars().filter(|&c| c == 's').count() <= 1 {
            return parse_exchange(cmd);
        }
    }

    // Phase 4: Multi-line pattern space commands
    if last_char == 'n' && !cmd.starts_with('s') {
        // Next command - check it's not part of a substitution
        if cmd.chars().filter(|&c| c == 's').count() <= 1 {
            return parse_next(cmd);
        }
    }

    if last_char == 'N' && !cmd.starts_with('s') {
        // Next append command
        if cmd.chars().filter(|&c| c == 's').count() <= 1 {
            return parse_next_append(cmd);
        }
    }

    if last_char == 'P' && !cmd.starts_with('s') {
        // Print first line command
        if cmd.chars().filter(|&c| c == 's').count() <= 1 {
            return parse_print_first_line(cmd);
        }
    }

    if last_char == 'D' && !cmd.starts_with('s') {
        // Delete first line command
        if cmd.chars().filter(|&c| c == 's').count() <= 1 {
            return parse_delete_first_line(cmd);
        }
    }

    // Phase 5: Check for flow control commands BEFORE other commands
    // because b/t/T may have labels after them (not at the end)
    if cmd.starts_with(':') {
        // Label definition (Phase 5)
        return parse_label(cmd);
    }

    // Check for b/t/T commands anywhere in the command
    // Examples: "b", "b label", "10b", "10b label", "/pat/b label"
    let trimmed = cmd.trim();
    if trimmed.contains('b') || trimmed.contains('t') || trimmed.contains('T') {
        // Verify it's actually a flow control command by checking the position
        // For "b", "b label", "10b", "10b label" - the b/t/T should be followed by space or end of string
        let b_pos = trimmed.find('b');
        let t_pos = trimmed.find('t');
        let t_upper_pos = trimmed.find('T');

        // Find which position comes first
        let min_pos = [b_pos, t_pos, t_upper_pos].iter().filter_map(|&p| p).min();

        if let Some(pos) = min_pos {
            let char_at_pos = trimmed
                .chars()
                .nth(pos)
                .ok_or_else(|| anyhow!("Invalid position {} in command: {}", pos, cmd))?;
            let rest = &trimmed[pos + 1..];

            // Check if after b/t/T there's only whitespace, label, or end of string
            if rest.trim().is_empty() || rest.starts_with(' ') {
                // Definitely flow control
                if char_at_pos == 'b' {
                    return parse_branch(cmd);
                } else if char_at_pos == 't' {
                    return parse_test(cmd);
                } else {
                    return parse_test_false(cmd);
                }
            }
        }
    }

    // Phase 5: Check for file I/O and additional commands
    // These commands (=, F, z, r, R, w, W) have filenames or are standalone
    // so we check for them BEFORE checking if command "ends with" certain characters
    if trimmed.contains('=') {
        // Print line number (=) - may have address before it
        // Examples: "=", "5=", "/pat/="
        // The = should be the last character (except for optional address before it)
        if let Some(eq_pos) = trimmed.find('=') {
            let rest = &trimmed[eq_pos + 1..];
            if rest.trim().is_empty() {
                // Valid = command (nothing after = except maybe whitespace)
                return parse_print_line_number(cmd);
            }
        }
    }

    if trimmed.contains('F') {
        // Print filename (F) - GNU sed extension
        // Examples: "F", "5F", "/pat/F"
        if let Some(f_pos) = trimmed.find('F') {
            let rest = &trimmed[f_pos + 1..];
            if rest.trim().is_empty() {
                // Valid F command (nothing after F except maybe whitespace)
                return parse_print_filename(cmd);
            }
        }
    }

    if trimmed.contains('z') {
        // Clear pattern space (z) - GNU sed extension
        // Examples: "z", "5z", "/pat/z"
        // Make sure it's not part of a substitution
        if !cmd.starts_with('s')
            && cmd.chars().filter(|&c| c == 's').count() <= 1
            && let Some(z_pos) = trimmed.find('z')
        {
            let rest = &trimmed[z_pos + 1..];
            if rest.trim().is_empty() {
                // Valid z command (nothing after z except maybe whitespace)
                return parse_clear_pattern_space(cmd);
            }
        }
    }

    // File-I/O dispatch has moved to the top of parse_single_command via
    // try_parse_file_io(). See the comment there.

    // Determine command type by looking at the last character or special patterns
    if cmd.ends_with('Q') && !cmd.starts_with('s') {
        // Quit without printing command (Phase 4)
        parse_quit_without_print(cmd)
    } else if cmd.ends_with('q') && !cmd.starts_with('s') {
        // Quit command
        parse_quit(cmd)
    } else if cmd.ends_with('d') {
        // Delete command
        parse_delete(cmd)
    } else if cmd.ends_with('p') && !cmd.starts_with('s') {
        // Print command (but not s/pattern/replacement/p which is a flag)
        parse_print(cmd)
    } else {
        // Try to determine by last character for other commands
        let command_char = cmd.chars().last().ok_or_else(|| anyhow!("Empty command"))?;

        match command_char {
            's' => parse_substitution(cmd),
            'Q' => parse_quit_without_print(cmd),
            'q' => parse_quit(cmd),
            'd' => parse_delete(cmd),
            'p' => parse_print(cmd),
            'h' => parse_hold(cmd),
            'H' => parse_hold_append(cmd),
            'g' => parse_get(cmd),
            'G' => parse_get_append(cmd),
            'x' => parse_exchange(cmd),
            'n' => parse_next(cmd),
            'N' => parse_next_append(cmd),
            'P' => parse_print_first_line(cmd),
            'D' => parse_delete_first_line(cmd),
            'r' => parse_read_file(cmd),
            'R' => parse_read_line(cmd),
            'w' => parse_write_file(cmd),
            'W' => parse_write_first_line(cmd),
            '=' => parse_print_line_number(cmd),
            'F' => parse_print_filename(cmd),
            'z' => parse_clear_pattern_space(cmd),
            _ => {
                let unknown_char = command_char;
                let suggestion = match unknown_char {
                    c if c.is_ascii_alphabetic() => {
                        "Did you mean:\n\
                             - Substitution: s/pattern/replacement/[flags]\n\
                             - Delete: d\n\
                             - Print: p\n\
                             - Insert (before line): 5i\\text\n\
                             - Append (after line): 5a\\text\n\
                             - Change line: 5c\\new text\n\
                             - Quit: q or Q\n\
                             See 'sedx --help' for all commands".to_string()
                    }
                    '0'..='9' => {
                        "Numbers alone are not commands. Use a command character after the line number (e.g., '5d' to delete line 5)".to_string()
                    }
                    _ => {
                        "Valid commands: s (substitute), d (delete), p (print),\n\
                             i (insert), a (append), c (change), q (quit),\n\
                             h/H (hold), g/G (get), x (exchange), n/N (next),\n\
                             b/t/T (branch), r/R (read file), w/W (write file),\n\
                             = (line number), F (filename), z (clear pattern space)".to_string()
                    }
                };

                let cmd_trimmed = cmd.trim();
                Err(anyhow!(
                    "{}",
                    format_parse_error(
                        cmd_trimmed,
                        Some(cmd_trimmed.chars().count().saturating_sub(1)),
                        &format!("unknown command '{}'", unknown_char),
                        Some(&suggestion),
                    )
                ))
            }
        }
    }
}

fn parse_substitution(cmd: &str) -> Result<Command> {
    // Find the 's' that starts the substitution command
    // It's the first 's' followed by a delimiter (/, #, :, etc.)
    let bytes = cmd.as_bytes();
    let mut s_pos = None;

    for (i, &byte) in bytes.iter().enumerate() {
        if byte == b's' && i + 1 < bytes.len() {
            let next_byte = bytes[i + 1];
            // Check if next char is a valid delimiter
            if next_byte == b'/' || next_byte == b'#' || next_byte == b':' || next_byte == b'|' {
                s_pos = Some(i);
                break;
            }
        }
    }

    let s_pos = s_pos.ok_or_else(|| anyhow!("{}", format_parse_error(
        cmd,
        None,
        "'s' command not followed by a valid delimiter",
        Some("Substitution format: s<delimiter>pattern<delimiter>replacement<delimiter>[flags]\nDelimiters: / (slash), # (hash), : (colon), | (pipe)\nExample: s/foo/bar/ or s#old#new#g"),
    )))?;

    // Everything before 's' is the address/range
    let address_part = &cmd[..s_pos];
    let rest = &cmd[s_pos + 1..]; // Skip the 's'

    // Detect delimiter
    let delimiter = rest.chars().next()
        .ok_or_else(|| anyhow!("{}", format_parse_error(
            cmd,
            Some(s_pos + 1),
            "missing delimiter after 's'",
            Some("Expected format: s<delimiter>pattern<delimiter>replacement<delimiter>[flags]\nExample: s/foo/bar/ or s#old#new#g"),
        )))?;

    // Find all delimiter positions
    let mut delimiter_positions: Vec<usize> = Vec::new();

    // Use char_indices() to get correct byte positions for UTF-8 strings
    for (byte_pos, c) in rest.char_indices() {
        if c == delimiter {
            delimiter_positions.push(byte_pos);
        }
    }

    if delimiter_positions.len() < 3 {
        // Provide specific error based on how many delimiters were found
        let (description, suggestion) = match delimiter_positions.len() {
            0 => (
                format!(
                    "no '{}' delimiter found after the opening delimiter",
                    delimiter
                ),
                Some(
                    "Make sure to close the pattern, replacement, and optionally add flags:\n  s/pattern/replacement/\n  s/pattern/replacement/g",
                ),
            ),
            1 => (
                "missing closing delimiter for replacement".to_string(),
                Some(
                    "You need to close the replacement with the delimiter:\n  s/pattern/replacement/\n                      ^ (add this)",
                ),
            ),
            2 => {
                // This is actually valid - no flags, just 2 delimiters for pattern+replacement
                // But our code expects 3 positions (including the closing delimiter)
                // Wait, delimiter_positions tracks the delimiter positions
                // So: s/pattern/replacement/ has 3 delimiters (positions of / / /)
                // If we only have 2, we're missing the final delimiter
                (
                    "missing final delimiter to close the substitution".to_string(),
                    Some(
                        "Add the final delimiter:\n  s/pattern/replacement/\n                        ^ (add this)",
                    ),
                )
            }
            _ => unreachable!(),
        };

        return Err(anyhow!(
            "{}",
            format_parse_error(cmd, None, &description, suggestion,)
        ));
    }

    let pattern = &rest[delimiter_positions[0] + 1..delimiter_positions[1]];
    // Keep the replacement raw at this layer — backreference conversion
    // (\1 → $1 etc.) is flavor-specific and happens in
    // `parser::Parser::convert_replacement` after the parse finishes. The
    // old code path converted here too, which was a layering violation:
    // sed_parser shouldn't know about regex-engine replacement syntax.
    let replacement = rest[delimiter_positions[1] + 1..delimiter_positions[2]].to_string();
    let raw_flags: Vec<char> = if delimiter_positions[2] + 1 < rest.len() {
        rest[delimiter_positions[2] + 1..].chars().collect()
    } else {
        Vec::new()
    };

    // Parse address/range if present
    let range = if address_part.contains(',') {
        // Range: start,ends/pattern/replacement/
        let parts: Vec<&str> = address_part.splitn(2, ',').collect();
        if parts.len() == 2 {
            let start = parse_address(parts[0])?;
            let end_str = parts[1].trim();

            // Chunk 8: Check if end has relative offset (+N or -N)
            if end_str.starts_with('+') || end_str.starts_with('-') {
                // Relative range: /pattern/,+5
                let offset_str = &end_str[1..]; // Skip +/-
                let offset: isize = offset_str.parse()
                    .map_err(|_| anyhow!("{}", format_parse_error(
                        cmd,
                        None,
                        &format!("invalid relative offset '{}'", end_str),
                        Some("Relative offset format: start,+N or start,-N\nExample: /pattern/,+5  - 5 lines after pattern match\n         10,-3       - 3 lines before line 10"),
                    )))?;

                let end = Address::Relative {
                    base: Box::new(start.clone()),
                    offset,
                };
                Some((start, end))
            } else {
                // Normal range
                let end = parse_address(end_str)?;
                Some((start, end))
            }
        } else {
            None
        }
    } else if !address_part.trim().is_empty() {
        // Single address: addrs/pattern/replacement/
        let addr = parse_address(address_part.trim())?;
        Some((addr.clone(), addr))
    } else {
        None
    };

    Ok(Command::Substitution {
        pattern: pattern.to_string(),
        replacement: replacement.to_string(),
        flags: fold_substitution_flags(&raw_flags),
        range,
    })
}

fn parse_delete(cmd: &str) -> Result<Command> {
    let cmd = cmd.trim();

    let addr_part = &cmd[..cmd.len() - 1]; // Remove 'd'

    // Empty address means delete all lines (1 to $)
    if addr_part.trim().is_empty() {
        return Ok(Command::Delete {
            range: (Address::LineNumber(1), Address::LastLine),
        });
    }

    // Check for range: start,endd
    if let Some(comma_pos) = addr_part.find(',') {
        let start = &addr_part[..comma_pos];
        let end = &addr_part[comma_pos + 1..];

        return Ok(Command::Delete {
            range: (parse_address(start)?, parse_address(end)?),
        });
    }

    // For simple addresses, use parse_address directly
    let addr = parse_address(addr_part)?;
    Ok(Command::Delete {
        range: (addr.clone(), addr),
    })
}

fn parse_print(cmd: &str) -> Result<Command> {
    let cmd = cmd.trim();

    let addr_part = &cmd[..cmd.len() - 1]; // Remove 'p'

    // Empty address means print all lines (1 to $)
    if addr_part.trim().is_empty() {
        return Ok(Command::Print {
            range: (Address::LineNumber(1), Address::LastLine),
        });
    }

    // Check for range: start,endp
    if let Some(comma_pos) = addr_part.find(',') {
        let start = &addr_part[..comma_pos];
        let end = &addr_part[comma_pos + 1..];

        return Ok(Command::Print {
            range: (parse_address(start)?, parse_address(end)?),
        });
    }

    // For simple addresses, use parse_address directly
    let addr = parse_address(addr_part)?;
    Ok(Command::Print {
        range: (addr.clone(), addr),
    })
}

fn parse_quit(cmd: &str) -> Result<Command> {
    let cmd = cmd.trim();
    let addr_part = &cmd[..cmd.len() - 1]; // Remove 'q'

    // Check if there's an address
    if addr_part.trim().is_empty() {
        // Just 'q' - quit immediately
        return Ok(Command::Quit { address: None });
    }

    // '10q' or '/pattern/q' - quit at that address
    let addr = parse_address(addr_part)?;
    Ok(Command::Quit {
        address: Some(addr),
    })
}

// Phase 4: Parse Q command (quit without printing)
fn parse_quit_without_print(cmd: &str) -> Result<Command> {
    let cmd = cmd.trim();
    let addr_part = &cmd[..cmd.len() - 1]; // Remove 'Q'

    // Check if there's an address
    if addr_part.trim().is_empty() {
        // Just 'Q' - quit immediately without printing
        return Ok(Command::QuitWithoutPrint { address: None });
    }

    // '10Q' or '/pattern/Q' - quit at that address without printing
    let addr = parse_address(addr_part)?;
    Ok(Command::QuitWithoutPrint {
        address: Some(addr),
    })
}

fn parse_group(cmd: &str) -> Result<Command> {
    let cmd = cmd.trim();

    // Find the opening brace
    let open_brace = cmd.find('{')
        .ok_or_else(|| anyhow!("{}", format_parse_error(
            cmd,
            None,
            "group command is missing opening '{'",
            Some("Group format: [range] { command1; command2; ... }\nExample: {s/foo/bar/; s/baz/qux/}\n         1,10{s/^/> /}"),
        )))?;

    // Extract the address/range part (before the brace)
    let addr_part = cmd[..open_brace].trim();

    // Find the matching closing brace
    let brace_start = open_brace + 1;
    let mut depth = 1;
    let mut close_brace = None;

    for (i, c) in cmd[brace_start..].chars().enumerate() {
        if c == '{' {
            depth += 1;
        } else if c == '}' {
            depth -= 1;
            if depth == 0 {
                close_brace = Some(brace_start + i);
                break;
            }
        }
    }

    let close_brace = close_brace
        .ok_or_else(|| anyhow!("{}", format_parse_error(
            cmd,
            None,
            "group command is missing closing '}'",
            Some("Every opening '{' must have a matching closing '}'.\nExample: {s/foo/bar/; p}\n                      ^ (add closing brace here)"),
        )))?;

    // Extract commands inside the braces
    let commands_str = &cmd[brace_start..close_brace].trim();

    // Parse the range if present
    let range = if addr_part.is_empty() {
        None
    } else if addr_part.contains(',') {
        // Range: start,end{...}
        let parts: Vec<&str> = addr_part.splitn(2, ',').collect();
        if parts.len() == 2 {
            Some((
                parse_address(parts[0].trim())?,
                parse_address(parts[1].trim())?,
            ))
        } else {
            None
        }
    } else {
        // Single address: addr{...}
        let addr = parse_address(addr_part)?;
        Some((addr.clone(), addr))
    };

    // Parse commands inside the group (separated by semicolons)
    let mut commands = Vec::new();
    for cmd_str in commands_str.split(';') {
        let cmd_str = cmd_str.trim();
        if !cmd_str.is_empty() {
            commands.push(parse_single_command(cmd_str)?);
        }
    }

    if commands.is_empty() {
        return Err(anyhow!(
            "{}",
            format_parse_error(
                cmd,
                None,
                "empty group: no commands inside braces",
                Some(
                    "Add commands separated by semicolons:\n  {s/foo/bar/; p}  - valid\n  {}                - invalid (empty)"
                ),
            )
        ));
    }

    Ok(Command::Group { range, commands })
}

fn parse_insert(cmd: &str) -> Result<Command> {
    // Insert: i\text or addr i\text
    let parts: Vec<&str> = cmd.splitn(2, "i\\").collect();
    if parts.len() != 2 {
        // Check if it looks like user forgot the backslash
        let suggestion = if cmd.contains('i') && !cmd.contains("i\\") {
            Some(
                "Insert command requires a backslash after 'i':\n  Format: [address]i\\text\n  Example: 5i\\INSERTED LINE\n  Example: /pattern/i\\New line before match",
            )
        } else {
            Some("Valid insert format: [address]i\\text\nExample: 5i\\INSERTED LINE")
        };
        return Err(anyhow!(
            "{}",
            format_parse_error(cmd, None, "invalid insert command syntax", suggestion,)
        ));
    }

    let address = if !parts[0].trim().is_empty() {
        parse_address(parts[0].trim())?
    } else {
        return Err(anyhow!(
            "{}",
            format_parse_error(
                cmd,
                None,
                "insert command requires an address",
                Some(
                    "Specify which line to insert before:\n  5i\\text        - insert before line 5\n  /pat/i\\text     - insert before lines matching 'pat'\n  $i\\text        - insert before last line"
                ),
            )
        ));
    };

    Ok(Command::Insert {
        text: parts[1].strip_prefix('\n').unwrap_or(parts[1]).to_string(),
        address,
    })
}

fn parse_append(cmd: &str) -> Result<Command> {
    // Append: a\text or addr a\text
    let parts: Vec<&str> = cmd.splitn(2, "a\\").collect();
    if parts.len() != 2 {
        let suggestion = if cmd.contains('a') && !cmd.contains("a\\") {
            Some(
                "Append command requires a backslash after 'a':\n  Format: [address]a\\text\n  Example: 5a\\APPENDED LINE\n  Example: /pattern/a\\New line after match",
            )
        } else {
            Some("Valid append format: [address]a\\text\nExample: 5a\\APPENDED LINE")
        };
        return Err(anyhow!(
            "{}",
            format_parse_error(cmd, None, "invalid append command syntax", suggestion,)
        ));
    }

    let address = if !parts[0].trim().is_empty() {
        parse_address(parts[0].trim())?
    } else {
        return Err(anyhow!(
            "{}",
            format_parse_error(
                cmd,
                None,
                "append command requires an address",
                Some(
                    "Specify which line to append after:\n  5a\\text        - append after line 5\n  /pat/a\\text     - append after lines matching 'pat'\n  $a\\text        - append after last line"
                ),
            )
        ));
    };

    Ok(Command::Append {
        text: parts[1].strip_prefix('\n').unwrap_or(parts[1]).to_string(),
        address,
    })
}

fn parse_change(cmd: &str) -> Result<Command> {
    let parts: Vec<&str> = cmd.splitn(2, "c\\").collect();
    if parts.len() != 2 {
        let suggestion = if cmd.contains('c') && !cmd.contains("c\\") {
            Some(
                "Change command requires a backslash after 'c':\n  Format: [address]c\\text\n  Example: 5c\\REPLACED LINE\n  Example: /pattern/c\\Replacement",
            )
        } else {
            Some("Valid change format: [address]c\\text\nExample: 5c\\REPLACED LINE")
        };
        return Err(anyhow!(
            "{}",
            format_parse_error(cmd, None, "invalid change command syntax", suggestion,)
        ));
    }

    let addr_part = parts[0].trim();
    if addr_part.is_empty() {
        return Err(anyhow!(
            "{}",
            format_parse_error(
                cmd,
                None,
                "change command requires an address",
                Some(
                    "Specify which line(s) to change:\n  5c\\text          - change line 5\n  2,3c\\text         - change lines 2-3 (collapsed)\n  /pat/c\\text       - change lines matching 'pat'\n  $c\\text          - change last line"
                ),
            )
        ));
    }

    let text = parts[1].strip_prefix('\n').unwrap_or(parts[1]).to_string();

    // Range form: start,end
    if let Some(comma_pos) = addr_part.find(',') {
        let start = parse_address(addr_part[..comma_pos].trim())?;
        let end = parse_address(addr_part[comma_pos + 1..].trim())?;
        return Ok(Command::Change {
            text,
            range: (start, end),
        });
    }

    // Single address: collapse to (addr, addr)
    let addr = parse_address(addr_part)?;
    Ok(Command::Change {
        text,
        range: (addr.clone(), addr),
    })
}

// Hold space command parsing functions

fn parse_hold(cmd: &str) -> Result<Command> {
    // h or addr h or addr1,addr2 h
    let cmd = cmd.trim();
    let addr_part = &cmd[..cmd.len() - 1]; // Remove 'h'

    let range = parse_optional_range(addr_part)?;

    Ok(Command::Hold { range })
}

fn parse_hold_append(cmd: &str) -> Result<Command> {
    // H or addr H
    let cmd = cmd.trim();
    let addr_part = &cmd[..cmd.len() - 1]; // Remove 'H'

    let range = parse_optional_range(addr_part)?;

    Ok(Command::HoldAppend { range })
}

fn parse_get(cmd: &str) -> Result<Command> {
    // g or addr g
    let cmd = cmd.trim();
    let addr_part = &cmd[..cmd.len() - 1]; // Remove 'g'

    let range = parse_optional_range(addr_part)?;

    Ok(Command::Get { range })
}

fn parse_get_append(cmd: &str) -> Result<Command> {
    // G or addr G
    let cmd = cmd.trim();
    let addr_part = &cmd[..cmd.len() - 1]; // Remove 'G'

    let range = parse_optional_range(addr_part)?;

    Ok(Command::GetAppend { range })
}

fn parse_exchange(cmd: &str) -> Result<Command> {
    // x or addr x
    let cmd = cmd.trim();
    let addr_part = &cmd[..cmd.len() - 1]; // Remove 'x'

    let range = parse_optional_range(addr_part)?;

    Ok(Command::Exchange { range })
}

// Phase 4: Multi-line pattern space command parsing functions

fn parse_next(cmd: &str) -> Result<Command> {
    // n or addr n
    let cmd = cmd.trim();
    let addr_part = &cmd[..cmd.len() - 1]; // Remove 'n'

    let range = parse_optional_range(addr_part)?;

    Ok(Command::Next { range })
}

fn parse_next_append(cmd: &str) -> Result<Command> {
    // N or addr N
    let cmd = cmd.trim();
    let addr_part = &cmd[..cmd.len() - 1]; // Remove 'N'

    let range = parse_optional_range(addr_part)?;

    Ok(Command::NextAppend { range })
}

fn parse_print_first_line(cmd: &str) -> Result<Command> {
    // P or addr P
    let cmd = cmd.trim();
    let addr_part = &cmd[..cmd.len() - 1]; // Remove 'P'

    let range = parse_optional_range(addr_part)?;

    Ok(Command::PrintFirstLine { range })
}

fn parse_delete_first_line(cmd: &str) -> Result<Command> {
    // D or addr D
    let cmd = cmd.trim();
    let addr_part = &cmd[..cmd.len() - 1]; // Remove 'D'

    let range = parse_optional_range(addr_part)?;

    Ok(Command::DeleteFirstLine { range })
}

/// Helper function to parse optional ranges for hold space commands
/// Returns None if no address (applies to all lines)
/// Returns Some((start, end)) if address or range specified
fn parse_optional_range(addr_part: &str) -> Result<Option<(Address, Address)>> {
    let addr_part = addr_part.trim();

    if addr_part.is_empty() {
        return Ok(None); // No address = applies to all lines
    }

    if let Some(comma_pos) = addr_part.find(',') {
        // Range: addr1,addr2
        let start = &addr_part[..comma_pos];
        let end = &addr_part[comma_pos + 1..];

        // Chunk 8: Check if end has relative offset (+N or -N)
        if end.starts_with('+') || end.starts_with('-') {
            // Relative range: /pattern/,+5 or 10,+3
            let start_addr = parse_address(start)?;

            // Parse the offset
            let offset_str = &end[1..]; // Skip +/-
            let offset: isize = offset_str.parse()
                .map_err(|_| anyhow!("{}", format_parse_error(
                    end,
                    None,
                    &format!("invalid relative offset '{}'", end),
                    Some("Relative offset format: start,+N or start,-N\nExample: /pattern/,+5  - 5 lines after pattern\n         10,-3       - 3 lines before line 10"),
                )))?;

            let end_addr = Address::Relative {
                base: Box::new(start_addr.clone()),
                offset,
            };

            return Ok(Some((start_addr, end_addr)));
        }

        // Normal range
        let start_addr = parse_address(start)?;
        let end_addr = parse_address(end)?;
        return Ok(Some((start_addr, end_addr)));
    }

    // Single address
    let addr = parse_address(addr_part)?;
    Ok(Some((addr.clone(), addr)))
}

fn parse_address(addr: &str) -> Result<Address> {
    let addr = addr.trim();

    // Empty address (not valid in our context)
    if addr.is_empty() {
        return Err(anyhow!("Empty address"));
    }

    // Check for negation operator (! as suffix)
    if let Some(inner_addr) = addr.strip_suffix('!') {
        let parsed = parse_address(inner_addr)?;
        return Ok(Address::Negated(Box::new(parsed)));
    }

    // Special address: 0 (for first-match substitution)
    if addr == "0" {
        return Ok(Address::FirstLine);
    }

    // Special address: $ (last line)
    if addr == "$" {
        return Ok(Address::LastLine);
    }

    // Chunk 8: Stepping address: 1~2 (every 2nd line starting from line 1)
    if let Some(tilde_pos) = addr.find('~') {
        let start_str = &addr[..tilde_pos];
        let step_str = &addr[tilde_pos + 1..];

        let start: usize = start_str.parse()
            .map_err(|_| anyhow!("{}", format_parse_error(
                addr,
                Some(tilde_pos),
                &format!("invalid step start '{}'", start_str),
                Some("Step format: start~step\nExample: 1~2  - every 2nd line starting from line 1\n         10~5 - every 5th line starting from line 10"),
            )))?;
        let step: usize = step_str.parse()
            .map_err(|_| anyhow!("{}", format_parse_error(
                addr,
                Some(tilde_pos + 1),
                &format!("invalid step value '{}'", step_str),
                Some("Step format: start~step\nThe step value must be a positive integer.\nExample: 1~2 or 10~5"),
            )))?;

        if step == 0 {
            bail!(
                "{}",
                format_parse_error(
                    addr,
                    Some(tilde_pos + 1),
                    "step value cannot be zero",
                    Some(
                        "Use a positive integer for the step value.\nExample: 1~1 (every line) or 1~2 (every other line)"
                    ),
                )
            );
        }

        return Ok(Address::Step { start, step });
    }

    // Line number
    if let Ok(num) = addr.parse::<usize>() {
        return Ok(Address::LineNumber(num));
    }

    // Pattern: /pattern/
    if addr.starts_with('/') && addr.ends_with('/') {
        let pattern = &addr[1..addr.len() - 1];
        return Ok(Address::Pattern(pattern.to_string()));
    }

    // Pattern missing closing slash
    if addr.starts_with('/') && !addr.ends_with('/') {
        return Err(anyhow!(
            "{}",
            format_parse_error(
                addr,
                Some(addr.len()),
                "pattern address is missing closing '/'",
                Some(
                    "Pattern addresses must be enclosed in slashes:\n  /pattern/\n  /^hello/\n  /goodbye$/"
                ),
            )
        ));
    }

    // Pattern missing opening slash
    if addr.ends_with('/') && !addr.starts_with('/') {
        return Err(anyhow!(
            "{}",
            format_parse_error(
                addr,
                Some(0),
                "pattern address is missing opening '/'",
                Some(
                    "Pattern addresses must be enclosed in slashes:\n  /pattern/\n  /^hello/\n  /goodbye$/"
                ),
            )
        ));
    }

    Err(anyhow!(
        "{}",
        format_parse_error(
            addr,
            None,
            &format!("invalid address '{}'", addr),
            Some(
                "Valid address formats:\n  - Line number: 5, 10, 42\n  - Last line: $\n  - Pattern: /regex/\n  - Range: 1,10 or /start/,/end/\n  - Stepping: 1~2 (every 2nd line)\n  - Relative: /pat/,+5 (5 lines after pattern match)"
            ),
        )
    ))
}

// Phase 5: Parse label definition (:label)
fn parse_label(cmd: &str) -> Result<Command> {
    let cmd = cmd.trim();

    // Remove the leading ':'
    let label_name = cmd[1..].trim();

    if label_name.is_empty() {
        return Err(anyhow!(
            "{}",
            format_parse_error(
                cmd,
                Some(1),
                "label name cannot be empty",
                Some(
                    "Label definition format: :labelname\nExample: :loop\n         :end\n         :retry\nNote: Label names are limited to 8 characters (GNU sed compatibility)"
                ),
            )
        ));
    }

    // GNU sed restricts label names to max 8 characters
    if label_name.len() > 8 {
        return Err(anyhow!(
            "{}",
            format_parse_error(
                cmd,
                None,
                &format!("label name '{}' is too long (max 8 characters)", label_name),
                Some(&format!(
                    "Shorten the label name to 8 characters or less.\nSuggestion: {} (truncated)",
                    &label_name[..8]
                )),
            )
        ));
    }

    Ok(Command::Label {
        name: label_name.to_string(),
    })
}

// Phase 5: Parse branch command (b [label])
fn parse_branch(cmd: &str) -> Result<Command> {
    let cmd = cmd.trim();

    // Find the 'b' command character
    let b_pos = cmd
        .find('b')
        .ok_or_else(|| anyhow!("Branch command missing 'b'"))?;

    // Split into: address_part (before 'b') and rest_part (after 'b' including 'b')
    let address_part = &cmd[..b_pos];
    let rest_part = &cmd[b_pos..]; // Includes the 'b'

    // Parse the optional range from address_part
    let range = parse_optional_range(address_part)?;

    // Extract label if present (after the 'b')
    let label_part = &rest_part[1..]; // Skip the 'b'
    let label = if label_part.trim().is_empty() {
        // Just 'b' - branch to end of script
        None
    } else {
        // 'b label' or '10b label'
        let label_name = label_part.trim();
        if !label_name.is_empty() {
            Some(label_name.to_string())
        } else {
            None
        }
    };

    Ok(Command::Branch { label, range })
}

// Phase 5: Parse test branch command (t [label])
fn parse_test(cmd: &str) -> Result<Command> {
    let cmd = cmd.trim();

    // Find the 't' command character
    let t_pos = cmd
        .find('t')
        .ok_or_else(|| anyhow!("Test command missing 't'"))?;

    // Split into: address_part (before 't') and rest_part (after 't' including 't')
    let address_part = &cmd[..t_pos];
    let rest_part = &cmd[t_pos..]; // Includes the 't'

    // Parse the optional range from address_part
    let range = parse_optional_range(address_part)?;

    // Extract label if present (after the 't')
    let label_part = &rest_part[1..]; // Skip the 't'
    let label = if label_part.trim().is_empty() {
        None
    } else {
        let label_name = label_part.trim();
        if !label_name.is_empty() {
            Some(label_name.to_string())
        } else {
            None
        }
    };

    Ok(Command::Test { label, range })
}

// Phase 5: Parse test false branch command (T [label])
fn parse_test_false(cmd: &str) -> Result<Command> {
    let cmd = cmd.trim();

    // Find the 'T' command character
    let t_pos = cmd
        .find('T')
        .ok_or_else(|| anyhow!("Test false command missing 'T'"))?;

    // Split into: address_part (before 'T') and rest_part (after 'T' including 'T')
    let address_part = &cmd[..t_pos];
    let rest_part = &cmd[t_pos..]; // Includes the 'T'

    // Parse the optional range from address_part
    let range = parse_optional_range(address_part)?;

    // Extract label if present (after the 'T')
    let label_part = &rest_part[1..]; // Skip the 'T'
    let label = if label_part.trim().is_empty() {
        None
    } else {
        let label_name = label_part.trim();
        if !label_name.is_empty() {
            Some(label_name.to_string())
        } else {
            None
        }
    };

    Ok(Command::TestFalse { label, range })
}

// Phase 5: Parse read file command (r filename)
fn parse_read_file(cmd: &str) -> Result<Command> {
    let cmd = cmd.trim();

    // Find the 'r' command character — skip any 'r' that is inside a pattern
    // address (e.g. `/err/r filename` must not match the 'r' in "err").
    let r_pos = cmd
        .char_indices()
        .find(|&(pos, ch)| ch == 'r' && !is_inside_pattern_address(cmd, pos))
        .map(|(pos, _)| pos)
        .ok_or_else(|| anyhow!("Read file command missing 'r'"))?;

    // Split into: address_part (before 'r') and rest_part (after 'r' including 'r')
    let address_part = &cmd[..r_pos];
    let rest_part = &cmd[r_pos..]; // Includes the 'r'

    // Parse the optional address from address_part
    let range = if address_part.trim().is_empty() {
        None
    } else {
        Some(parse_address(address_part.trim())?)
    };

    // Extract filename (after the 'r')
    let filename_part = &rest_part[1..]; // Skip the 'r'
    let filename = filename_part.trim();
    if filename.is_empty() {
        bail!(
            "{}",
            format_parse_error(
                cmd,
                None,
                "read file command requires a filename",
                Some(
                    "Read file format: [address]r filename\nExample: 5r header.txt    - insert contents of header.txt after line 5\n         /pat/r data.txt  - insert contents after lines matching 'pat'"
                ),
            )
        );
    }

    Ok(Command::ReadFile {
        filename: filename.to_string(),
        range,
    })
}

// Phase 5: Parse write file command (w filename)
fn parse_write_file(cmd: &str) -> Result<Command> {
    let cmd = cmd.trim();

    // Find the 'w' command character — skip any 'w' that is inside a pattern
    // address (e.g. `/wrong/w filename` must not match the 'w' in "wrong").
    let w_pos = cmd
        .char_indices()
        .find(|&(pos, ch)| ch == 'w' && !is_inside_pattern_address(cmd, pos))
        .map(|(pos, _)| pos)
        .ok_or_else(|| anyhow!("Write file command missing 'w'"))?;

    // Split into: address_part (before 'w') and rest_part (after 'w' including 'w')
    let address_part = &cmd[..w_pos];
    let rest_part = &cmd[w_pos..]; // Includes the 'w'

    // Parse the optional address from address_part
    let range = if address_part.trim().is_empty() {
        None
    } else {
        Some(parse_address(address_part.trim())?)
    };

    // Extract filename (after the 'w')
    let filename_part = &rest_part[1..]; // Skip the 'w'
    let filename = filename_part.trim();
    if filename.is_empty() {
        bail!(
            "{}",
            format_parse_error(
                cmd,
                None,
                "write file command requires a filename",
                Some(
                    "Write file format: [address]w filename\nExample: 5w output.txt    - write line 5 to output.txt\n         /pat/w log.txt    - write matching lines to log.txt"
                ),
            )
        );
    }

    Ok(Command::WriteFile {
        filename: filename.to_string(),
        range,
    })
}

// Phase 5: Parse read line command (R filename)
fn parse_read_line(cmd: &str) -> Result<Command> {
    let cmd = cmd.trim();

    // Find the 'R' command character — skip any 'R' that is inside a pattern
    // address (e.g. `/wRong/R filename` must not match the 'R' in "wRong").
    let r_pos = cmd
        .char_indices()
        .find(|&(pos, ch)| ch == 'R' && !is_inside_pattern_address(cmd, pos))
        .map(|(pos, _)| pos)
        .ok_or_else(|| anyhow!("Read line command missing 'R'"))?;

    // Split into: address_part (before 'R') and rest_part (after 'R' including 'R')
    let address_part = &cmd[..r_pos];
    let rest_part = &cmd[r_pos..]; // Includes the 'R'

    // Parse the optional address from address_part
    let range = if address_part.trim().is_empty() {
        None
    } else {
        Some(parse_address(address_part.trim())?)
    };

    // Extract filename (after the 'R')
    let filename_part = &rest_part[1..]; // Skip the 'R'
    let filename = filename_part.trim();
    if filename.is_empty() {
        bail!(
            "{}",
            format_parse_error(
                cmd,
                None,
                "read line command requires a filename",
                Some(
                    "Read line format: [address]R filename\nExample: 5R data.txt       - append one line from data.txt after line 5\n         /pat/R input.txt  - append one line after matching lines"
                ),
            )
        );
    }

    Ok(Command::ReadLine {
        filename: filename.to_string(),
        range,
    })
}

// Phase 5: Parse write first line command (W filename)
fn parse_write_first_line(cmd: &str) -> Result<Command> {
    let cmd = cmd.trim();

    // Find the 'W' command character — skip any 'W' that is inside a pattern
    // address (e.g. `/Wrong/W filename` must not match the 'W' in "Wrong").
    let w_pos = cmd
        .char_indices()
        .find(|&(pos, ch)| ch == 'W' && !is_inside_pattern_address(cmd, pos))
        .map(|(pos, _)| pos)
        .ok_or_else(|| anyhow!("Write first line command missing 'W'"))?;

    // Split into: address_part (before 'W') and rest_part (after 'W' including 'W')
    let address_part = &cmd[..w_pos];
    let rest_part = &cmd[w_pos..]; // Includes the 'W'

    // Parse the optional address from address_part
    let range = if address_part.trim().is_empty() {
        None
    } else {
        Some(parse_address(address_part.trim())?)
    };

    // Extract filename (after the 'W')
    let filename_part = &rest_part[1..]; // Skip the 'W'
    let filename = filename_part.trim();
    if filename.is_empty() {
        bail!(
            "{}",
            format_parse_error(
                cmd,
                None,
                "write first line command requires a filename",
                Some(
                    "Write first line format: [address]W filename\nExample: 5W output.txt    - write first line of pattern space to output.txt\n         /pat/W log.txt   - write first line to log.txt for matches"
                ),
            )
        );
    }

    Ok(Command::WriteFirstLine {
        filename: filename.to_string(),
        range,
    })
}

// Phase 5: Parse print line number command (=)
fn parse_print_line_number(cmd: &str) -> Result<Command> {
    let cmd = cmd.trim();

    // Find the '=' command character
    let eq_pos = cmd
        .find('=')
        .ok_or_else(|| anyhow!("Print line number command missing '='"))?;

    // Split into: address_part (before '=') and the rest
    let address_part = &cmd[..eq_pos];

    // Parse the optional address from address_part
    let range = if address_part.trim().is_empty() {
        None
    } else {
        Some(parse_address(address_part.trim())?)
    };

    Ok(Command::PrintLineNumber { range })
}

// Phase 5: Parse print filename command (F)
fn parse_print_filename(cmd: &str) -> Result<Command> {
    let cmd = cmd.trim();

    // Find the 'F' command character
    let f_pos = cmd
        .find('F')
        .ok_or_else(|| anyhow!("Print filename command missing 'F'"))?;

    // Split into: address_part (before 'F') and the rest
    let address_part = &cmd[..f_pos];

    // Parse the optional address from address_part
    let range = if address_part.trim().is_empty() {
        None
    } else {
        Some(parse_address(address_part.trim())?)
    };

    Ok(Command::PrintFilename { range })
}

// Phase 5: Parse clear pattern space command (z)
fn parse_clear_pattern_space(cmd: &str) -> Result<Command> {
    let cmd = cmd.trim();

    // Find the 'z' command character
    let z_pos = cmd
        .find('z')
        .ok_or_else(|| anyhow!("Clear pattern space command missing 'z'"))?;

    // Split into: address_part (before 'z') and the rest
    let address_part = &cmd[..z_pos];

    // Parse the optional address from address_part
    let range = if address_part.trim().is_empty() {
        None
    } else {
        Some(parse_address(address_part.trim())?)
    };

    Ok(Command::ClearPatternSpace { range })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::command::{Address, Command};

    #[test]
    fn test_parse_simple_substitution() {
        let cmd = parse_single_command("s/foo/bar/g").unwrap();
        match cmd {
            Command::Substitution {
                pattern,
                replacement,
                flags,
                range,
            } => {
                assert_eq!(pattern, "foo");
                assert_eq!(replacement, "bar");
                assert!(flags.global);
                assert!(range.is_none());
            }
            other => panic!("expected Substitution, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_line_substitution() {
        let cmd = parse_single_command("10s/foo/bar/").unwrap();
        match cmd {
            Command::Substitution {
                pattern,
                replacement,
                flags,
                range,
            } => {
                assert_eq!(pattern, "foo");
                assert_eq!(replacement, "bar");
                assert!(!flags.global);
                assert_eq!(
                    range,
                    Some((Address::LineNumber(10), Address::LineNumber(10)))
                );
            }
            other => panic!("expected Substitution, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_range_substitution() {
        let cmd = parse_single_command("1,10s/foo/bar/").unwrap();
        match cmd {
            Command::Substitution {
                pattern,
                replacement,
                flags,
                range,
            } => {
                assert_eq!(pattern, "foo");
                assert_eq!(replacement, "bar");
                assert!(!flags.global);
                assert_eq!(
                    range,
                    Some((Address::LineNumber(1), Address::LineNumber(10)))
                );
            }
            other => panic!("expected Substitution, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_delete_line() {
        let cmd = parse_single_command("10d").unwrap();
        assert_eq!(
            cmd,
            Command::Delete {
                range: (Address::LineNumber(10), Address::LineNumber(10)),
            }
        );
    }

    #[test]
    fn test_parse_delete_range() {
        let cmd = parse_single_command("1,10d").unwrap();
        assert_eq!(
            cmd,
            Command::Delete {
                range: (Address::LineNumber(1), Address::LineNumber(10)),
            }
        );
    }

    #[test]
    fn test_parse_delete_pattern() {
        let cmd = parse_single_command("/foo/d").unwrap();
        assert_eq!(
            cmd,
            Command::Delete {
                range: (
                    Address::Pattern("foo".to_string()),
                    Address::Pattern("foo".to_string())
                ),
            }
        );
    }

    #[test]
    fn test_parse_print_line() {
        let cmd = parse_single_command("10p").unwrap();
        assert_eq!(
            cmd,
            Command::Print {
                range: (Address::LineNumber(10), Address::LineNumber(10)),
            }
        );
    }

    #[test]
    fn test_parse_print_range() {
        let cmd = parse_single_command("1,10p").unwrap();
        assert_eq!(
            cmd,
            Command::Print {
                range: (Address::LineNumber(1), Address::LineNumber(10)),
            }
        );
    }

    // Backreference conversion tests were moved to `bre_converter::tests`
    // (the canonical home of the \N → $N conversion logic). See also
    // `parser::tests` for end-to-end coverage via `Parser::convert_replacement`.

    // Bug 2: Command grouping tests
    #[test]
    fn test_parse_simple_group() {
        let cmd = parse_single_command("{s/foo/bar/}").unwrap();
        match cmd {
            Command::Group { range, commands } => {
                assert_eq!(range, None);
                assert_eq!(commands.len(), 1);
            }
            _ => panic!("Expected Group command"),
        }
    }

    #[test]
    fn test_parse_group_with_semicolons() {
        let cmd = parse_single_command("{s/foo/bar/; s/baz/qux/}").unwrap();
        match cmd {
            Command::Group { range, commands } => {
                assert_eq!(range, None);
                assert_eq!(commands.len(), 2);
            }
            _ => panic!("Expected Group command"),
        }
    }

    // Hold space command tests
    #[test]
    fn test_parse_hold_simple() {
        let cmd = parse_single_command("h").unwrap();
        assert_eq!(cmd, Command::Hold { range: None });
    }

    #[test]
    fn test_parse_hold_with_address() {
        let cmd = parse_single_command("5h").unwrap();
        assert_eq!(
            cmd,
            Command::Hold {
                range: Some((Address::LineNumber(5), Address::LineNumber(5)))
            }
        );
    }

    #[test]
    fn test_parse_hold_append_with_range() {
        let cmd = parse_single_command("1,5H").unwrap();
        assert_eq!(
            cmd,
            Command::HoldAppend {
                range: Some((Address::LineNumber(1), Address::LineNumber(5)))
            }
        );
    }

    #[test]
    fn test_parse_get_append() {
        let cmd = parse_single_command("$G").unwrap();
        assert_eq!(
            cmd,
            Command::GetAppend {
                range: Some((Address::LastLine, Address::LastLine))
            }
        );
    }

    #[test]
    fn test_parse_exchange_with_pattern() {
        let cmd = parse_single_command("/pattern/x").unwrap();
        match cmd {
            Command::Exchange {
                range: Some((Address::Pattern(p), _)),
            } => {
                assert_eq!(p, "pattern");
            }
            _ => panic!("Expected Exchange command with pattern"),
        }
    }

    #[test]
    fn test_parse_get_with_negation() {
        let cmd = parse_single_command("/foo/!g").unwrap();
        match cmd {
            Command::Get {
                range: Some((Address::Negated(_), _)),
            } => {
                // Success
            }
            _ => panic!("Expected Get command with negation"),
        }
    }

    #[test]
    fn test_parse_hold_range_with_patterns() {
        let cmd = parse_single_command("/start/,/end/H").unwrap();
        match cmd {
            Command::HoldAppend {
                range: Some((Address::Pattern(s), Address::Pattern(e))),
            } => {
                assert_eq!(s, "start");
                assert_eq!(e, "end");
            }
            _ => panic!("Expected HoldAppend with pattern range"),
        }
    }

    #[test]
    fn test_parse_get_simple() {
        let cmd = parse_single_command("g").unwrap();
        assert_eq!(cmd, Command::Get { range: None });
    }

    #[test]
    fn test_parse_exchange_simple() {
        let cmd = parse_single_command("x").unwrap();
        assert_eq!(cmd, Command::Exchange { range: None });
    }

    #[test]
    fn test_parse_insert_with_text_ending_in_command_char() {
        // Regression: text ending in 'D' must not be dispatched as DeleteFirstLine
        let result = parse_sed_expression("2i\\INSERTED").expect("should parse");
        assert_eq!(result.len(), 1);
        match &result[0] {
            Command::Insert { text, address } => {
                assert_eq!(text, "INSERTED");
                assert!(matches!(address, Address::LineNumber(2)));
            }
            other => panic!("expected Insert, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_append_with_text_ending_in_command_char() {
        let result = parse_sed_expression("5a\\PATCHED").expect("should parse");
        assert_eq!(result.len(), 1);
        match &result[0] {
            Command::Append { text, address } => {
                assert_eq!(text, "PATCHED");
                assert!(matches!(address, Address::LineNumber(5)));
            }
            other => panic!("expected Append, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_change_pattern_addr_text_ending_h() {
        // 'H' would otherwise trigger HoldAppend dispatch
        let result = parse_sed_expression("/foo/c\\BAH").expect("should parse");
        assert_eq!(result.len(), 1);
        match &result[0] {
            Command::Change { text, .. } => assert_eq!(text, "BAH"),
            other => panic!("expected Change, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_insert_with_text_containing_substitution_lookalike() {
        // Regression: text "s/foo/bar/g" must produce Insert, not route to parse_substitution
        let result = parse_sed_expression("2i\\s/foo/bar/g").expect("should parse");
        assert_eq!(result.len(), 1);
        match &result[0] {
            Command::Insert { text, address } => {
                assert_eq!(text, "s/foo/bar/g");
                assert!(matches!(address, Address::LineNumber(2)));
            }
            other => panic!("expected Insert, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_read_file_with_path_containing_s_slash_segment() {
        // Regression: a path like /var/folders/.../data.txt contains the
        // substring "s/" inside "folders/". The marker-based dispatch used
        // to pick that up as a substitution command and misroute the whole
        // invocation. File-I/O must be dispatched first.
        let result =
            parse_sed_expression("R /var/folders/tb/abc/T/.tmpXYZ/data.txt").expect("should parse");
        assert_eq!(result.len(), 1);
        match &result[0] {
            Command::ReadLine { filename, range } => {
                assert_eq!(filename, "/var/folders/tb/abc/T/.tmpXYZ/data.txt");
                assert!(range.is_none());
            }
            other => panic!("expected ReadLine, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_read_file_with_line_address_and_s_slash_in_path() {
        let result = parse_sed_expression("2r /var/folders/xx/yy/extra.txt").expect("should parse");
        match &result[0] {
            Command::ReadFile { filename, range } => {
                assert_eq!(filename, "/var/folders/xx/yy/extra.txt");
                assert!(matches!(range, Some(Address::LineNumber(2))));
            }
            other => panic!("expected ReadFile, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_write_file_with_s_slash_in_path_no_address() {
        // Same fix as read_file: W with a path that contains `folders/`
        // must not be misrouted through the substitution marker dispatch.
        let result = parse_sed_expression("W /var/folders/xx/yy/out.txt").expect("should parse");
        match &result[0] {
            Command::WriteFirstLine { filename, range } => {
                assert_eq!(filename, "/var/folders/xx/yy/out.txt");
                assert!(range.is_none());
            }
            other => panic!("expected WriteFirstLine, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_change_with_text_containing_substitution_lookalike() {
        let result = parse_sed_expression("2c\\s/foo/bar/g").expect("should parse");
        match &result[0] {
            Command::Change { text, .. } => assert_eq!(text, "s/foo/bar/g"),
            other => panic!("expected Change, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_substitution_with_pattern_containing_iac_marker() {
        // Substitution pattern contains "i\" — must route to substitution, not insert
        let result = parse_sed_expression("s/i\\foo/bar/").expect("should parse");
        assert_eq!(result.len(), 1);
        match &result[0] {
            Command::Substitution {
                pattern,
                replacement,
                ..
            } => {
                assert_eq!(pattern, "i\\foo");
                assert_eq!(replacement, "bar");
            }
            other => panic!("expected Substitution, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_substitution_with_pattern_containing_c_marker() {
        let result = parse_sed_expression("s/c\\d+/NUM/").expect("should parse");
        match &result[0] {
            Command::Substitution { pattern, .. } => {
                assert_eq!(pattern, "c\\d+");
            }
            other => panic!("expected Substitution, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_substitution_with_address_and_iac_in_pattern() {
        let result = parse_sed_expression("5s/a\\b/X/").expect("should parse");
        match &result[0] {
            Command::Substitution { pattern, range, .. } => {
                assert_eq!(pattern, "a\\b");
                assert!(matches!(range, Some((Address::LineNumber(5), _))));
            }
            other => panic!("expected Substitution, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_insert_strips_leading_newline() {
        // Multi-line form: i\<NL>TEXT — the newline is syntax, not part of the text
        let result = parse_sed_expression("2i\\\nINSERTED").expect("should parse");
        match &result[0] {
            Command::Insert { text, .. } => assert_eq!(text, "INSERTED"),
            other => panic!("expected Insert, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_append_strips_leading_newline() {
        let result = parse_sed_expression("3a\\\nPATCHED").expect("should parse");
        match &result[0] {
            Command::Append { text, .. } => assert_eq!(text, "PATCHED"),
            other => panic!("expected Append, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_change_strips_leading_newline() {
        let result = parse_sed_expression("4c\\\nREPLACED").expect("should parse");
        match &result[0] {
            Command::Change { text, .. } => assert_eq!(text, "REPLACED"),
            other => panic!("expected Change, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_insert_inline_form_unchanged() {
        // Inline form (no newline) — text must not be mangled
        let result = parse_sed_expression("2i\\INSERTED").expect("should parse");
        match &result[0] {
            Command::Insert { text, .. } => assert_eq!(text, "INSERTED"),
            other => panic!("expected Insert, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_insert_empty_text_after_multiline_separator() {
        // i\<NL> with no text inserts a blank line (empty string text)
        let result = parse_sed_expression("2i\\\n").expect("should parse");
        match &result[0] {
            Command::Insert { text, .. } => assert_eq!(text, ""),
            other => panic!("expected Insert, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_change_with_range() {
        let result = parse_sed_expression("2,3c\\REPLACED").expect("should parse");
        assert_eq!(result.len(), 1);
        match &result[0] {
            Command::Change { text, range } => {
                assert_eq!(text, "REPLACED");
                assert!(matches!(range.0, Address::LineNumber(2)));
                assert!(matches!(range.1, Address::LineNumber(3)));
            }
            other => panic!("expected Change with range, got {:?}", other),
        }
    }

    #[test]
    fn test_parse_change_single_address_uses_same_addr_for_both() {
        let result = parse_sed_expression("5c\\REPLACED").expect("should parse");
        match &result[0] {
            Command::Change { range, .. } => {
                assert!(matches!(range.0, Address::LineNumber(5)));
                assert!(matches!(range.1, Address::LineNumber(5)));
            }
            other => panic!("expected Change, got {:?}", other),
        }
    }

    #[test]
    fn parse_pattern_addr_r_with_absolute_path() {
        // /err/r /etc/hosts — the `/etc/hosts` argument must not be re-interpreted
        // as a new pattern delimiter. The r command's filename should be `/etc/hosts`.
        let commands = parse_sed_expression("/err/r /etc/hosts").unwrap();
        assert_eq!(commands.len(), 1);
        match &commands[0] {
            Command::ReadFile { filename, range } => {
                assert_eq!(filename, "/etc/hosts");
                assert!(range.is_some());
            }
            other => panic!("expected ReadFile, got {:?}", other),
        }
    }

    #[test]
    fn parse_pattern_addr_w_with_absolute_path() {
        let commands = parse_sed_expression("/err/w /tmp/out.log").unwrap();
        assert_eq!(commands.len(), 1);
        match &commands[0] {
            Command::WriteFile { filename, range } => {
                assert_eq!(filename, "/tmp/out.log");
                assert!(range.is_some());
            }
            other => panic!("expected WriteFile, got {:?}", other),
        }
    }

    #[test]
    fn parse_pattern_addr_capital_w_with_absolute_path() {
        let commands = parse_sed_expression("/err/W /var/log/first.log").unwrap();
        assert_eq!(commands.len(), 1);
        match &commands[0] {
            Command::WriteFirstLine { filename, range } => {
                assert_eq!(filename, "/var/log/first.log");
                assert!(range.is_some());
            }
            other => panic!("expected WriteFirstLine, got {:?}", other),
        }
    }

    #[test]
    fn parse_pattern_addr_with_w_in_pattern() {
        // `/wrong/w /tmp/out` — the `w` inside `/wrong/` must be skipped.
        let commands = parse_sed_expression("/wrong/w /tmp/out.log").unwrap();
        assert_eq!(commands.len(), 1);
        match &commands[0] {
            Command::WriteFile { filename, range } => {
                assert_eq!(filename, "/tmp/out.log");
                assert!(range.is_some());
            }
            other => panic!("expected WriteFile, got {:?}", other),
        }
    }

    #[test]
    fn parse_pattern_addr_with_capital_r_in_pattern() {
        // `/wRong/R data.txt` — the `R` inside `/wRong/` must be skipped.
        let commands = parse_sed_expression("/wRong/R data.txt").unwrap();
        assert_eq!(commands.len(), 1);
        match &commands[0] {
            Command::ReadLine { filename, range } => {
                assert_eq!(filename, "data.txt");
                assert!(range.is_some());
            }
            other => panic!("expected ReadLine, got {:?}", other),
        }
    }

    #[test]
    fn parse_pattern_addr_with_capital_w_in_pattern() {
        // `/Wrong/W /var/log/first.log` — the `W` inside `/Wrong/` must be skipped.
        let commands = parse_sed_expression("/Wrong/W /var/log/first.log").unwrap();
        assert_eq!(commands.len(), 1);
        match &commands[0] {
            Command::WriteFirstLine { filename, range } => {
                assert_eq!(filename, "/var/log/first.log");
                assert!(range.is_some());
            }
            other => panic!("expected WriteFirstLine, got {:?}", other),
        }
    }

    #[test]
    fn parse_pattern_addr_with_escaped_slash_in_pattern() {
        // Escaped `/` inside the pattern must not close the pattern address.
        let commands = parse_sed_expression("/foo\\/bar/r /tmp/out.txt").unwrap();
        assert_eq!(commands.len(), 1);
        match &commands[0] {
            Command::ReadFile { filename, range } => {
                assert_eq!(filename, "/tmp/out.txt");
                assert!(range.is_some());
            }
            other => panic!("expected ReadFile, got {:?}", other),
        }
    }
}