arblang 0.1.24

Visualize and modify Unix pipelines: pipe a stream in, arb spawns a dynamic TUI
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
//! fzf option compatibility: everything `arb --fzf` needs to paint the picker the
//! `fzf` binary would paint for the same environment.
//!
//! Two halves:
//!
//! 1. **Config ingestion** — `$FZF_DEFAULT_OPTS_FILE` and `$FZF_DEFAULT_OPTS`.
//!    A drop-in (`ZPWR_FZF='arb --fzf'`) inherits the user's fzf configuration
//!    exactly like the real binary does, so the prompt string, layout, border,
//!    colors and key bindings come out identical without touching the call site.
//! 2. **Look parsing** — the presentation flags (`--layout`, `--border`,
//!    `--info`, `--pointer`, `--marker`, `--color`, `--bind`, `--cycle`) that
//!    used to be dropped as "cosmetic". They are the look, so they are honored.
//!
//! The default palettes are not invented: they were read off fzf 0.74.2's own
//! output by running it under a pty and decoding the SGR sequences it emitted
//! (`dark`, `light` and `base16` each captured separately). Each constant below
//! is the color index fzf actually wrote for that slot.

use ratatui::style::{Color, Modifier, Style};
use ratatui::widgets::{BorderType, Borders};

/// Split a shell-style option string into words, honoring `'…'`, `"…"` and `\`.
/// `$FZF_DEFAULT_OPTS` is written as a shell fragment — e.g.
/// `--prompt='<<)ZPWR(>> ' --reverse` — so splitting on whitespace alone would
/// tear the prompt in half and lose its trailing space.
pub fn shell_split(s: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut cur = String::new();
    let mut started = false; // `--prompt=''` is an empty word, not no word
    let mut quote: Option<char> = None;
    let mut chars = s.chars();
    while let Some(c) = chars.next() {
        match quote {
            // Inside single quotes everything is literal (shell rules).
            Some('\'') if c == '\'' => quote = None,
            Some('\'') => cur.push(c),
            Some('"') if c == '"' => quote = None,
            Some('"') if c == '\\' => match chars.next() {
                // In double quotes a backslash only escapes these four.
                Some(n @ ('"' | '\\' | '$' | '`')) => cur.push(n),
                Some(n) => {
                    cur.push('\\');
                    cur.push(n);
                }
                None => cur.push('\\'),
            },
            Some('"') => cur.push(c),
            Some(_) => unreachable!("quote is only ever ' or \""),
            None => match c {
                '\'' | '"' => {
                    started = true;
                    quote = Some(c);
                }
                '\\' => {
                    started = true;
                    if let Some(n) = chars.next() {
                        cur.push(n);
                    }
                }
                c if c.is_whitespace() => {
                    if started {
                        out.push(std::mem::take(&mut cur));
                        started = false;
                    }
                }
                _ => {
                    started = true;
                    cur.push(c);
                }
            },
        }
    }
    if started {
        out.push(cur);
    }
    out
}

/// The user's fzf configuration as argv words: `$FZF_DEFAULT_OPTS_FILE` first,
/// then `$FZF_DEFAULT_OPTS` — fzf's own precedence, with the command line
/// (spliced after these by the caller) winning over both.
pub fn env_args() -> Vec<String> {
    let mut out = Vec::new();
    if let Ok(path) = std::env::var("FZF_DEFAULT_OPTS_FILE") {
        let path = match (path.strip_prefix("~/"), std::env::var("HOME")) {
            (Some(rest), Ok(home)) => format!("{home}/{rest}"),
            _ => path,
        };
        if let Ok(body) = std::fs::read_to_string(path) {
            out.extend(shell_split(&body));
        }
    }
    if let Ok(opts) = std::env::var("FZF_DEFAULT_OPTS") {
        out.extend(shell_split(&opts));
    }
    out
}

/// One `--color` slot: an optional color (None = the terminal's default) plus
/// text attributes, e.g. fzf's `hl+:151:bold`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Ent {
    pub color: Option<Color>,
    pub attrs: Modifier,
}

impl Ent {
    /// A plain colored slot.
    fn c(idx: u8) -> Self {
        Ent {
            color: Some(Color::Indexed(idx)),
            attrs: Modifier::empty(),
        }
    }
    /// A bold colored slot (fzf bolds the pointer, the current line and hl+).
    fn b(idx: u8) -> Self {
        Ent {
            color: Some(Color::Indexed(idx)),
            attrs: Modifier::BOLD,
        }
    }
    /// Attributes only — the terminal's default color (fzf's `-1`).
    fn attr(attrs: Modifier) -> Self {
        Ent { color: None, attrs }
    }
    /// As a foreground style.
    pub fn fg(self) -> Style {
        let s = Style::default().add_modifier(self.attrs);
        match self.color {
            Some(c) => s.fg(c),
            None => s,
        }
    }
    /// As a background style (used for `bg`/`bg+`, where attrs don't apply).
    pub fn bg(self) -> Style {
        match self.color {
            Some(c) => Style::default().bg(c),
            None => Style::default(),
        }
    }
}

/// fzf's color slots. Field names track fzf's option names (`fg+` → `fg_plus`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Colors {
    pub fg: Ent,
    pub bg: Ent,
    pub hl: Ent,
    pub fg_plus: Ent,
    pub bg_plus: Ent,
    pub hl_plus: Ent,
    pub gutter: Ent,
    pub pointer: Ent,
    pub marker: Ent,
    pub prompt: Ent,
    pub query: Ent,
    pub info: Ent,
    pub spinner: Ent,
    pub header: Ent,
    pub border: Ent,
    pub separator: Ent,
    pub scrollbar: Ent,
}

impl Default for Colors {
    fn default() -> Self {
        Colors::dark()
    }
}

impl Colors {
    /// fzf's `dark` scheme (its default on a 256-color terminal), as measured
    /// from fzf 0.74.2's SGR output.
    pub fn dark() -> Self {
        Colors {
            fg: Ent::default(),
            bg: Ent::default(),
            hl: Ent::c(108),
            fg_plus: Ent::b(254),
            bg_plus: Ent::c(236),
            hl_plus: Ent::b(151),
            gutter: Ent::c(236),
            pointer: Ent::b(161),
            marker: Ent::c(168),
            prompt: Ent::b(110),
            query: Ent::attr(Modifier::BOLD),
            info: Ent::c(144),
            spinner: Ent::b(148),
            header: Ent::c(109),
            border: Ent::c(59),
            separator: Ent::c(59),
            scrollbar: Ent::c(59),
        }
    }

    /// fzf's `light` scheme.
    pub fn light() -> Self {
        Colors {
            hl: Ent::c(66),
            fg_plus: Ent::b(237),
            bg_plus: Ent::c(251),
            hl_plus: Ent::b(23),
            gutter: Ent::c(251),
            pointer: Ent::b(161),
            marker: Ent::c(168),
            prompt: Ent::b(25),
            info: Ent::c(101),
            border: Ent::c(145),
            separator: Ent::c(145),
            scrollbar: Ent::c(145),
            ..Colors::dark()
        }
    }

    /// fzf's `base16`/`16` scheme — the basic ANSI palette instead of 256 colors.
    pub fn base16() -> Self {
        Colors {
            hl: Ent {
                color: Some(Color::Green),
                attrs: Modifier::empty(),
            },
            fg_plus: Ent {
                color: Some(Color::White),
                attrs: Modifier::BOLD,
            },
            bg_plus: Ent {
                color: Some(Color::DarkGray),
                attrs: Modifier::empty(),
            },
            hl_plus: Ent {
                color: Some(Color::LightGreen),
                attrs: Modifier::BOLD,
            },
            gutter: Ent {
                color: Some(Color::DarkGray),
                attrs: Modifier::empty(),
            },
            pointer: Ent {
                color: Some(Color::Red),
                attrs: Modifier::BOLD,
            },
            marker: Ent {
                color: Some(Color::Magenta),
                attrs: Modifier::empty(),
            },
            prompt: Ent {
                color: Some(Color::Blue),
                attrs: Modifier::BOLD,
            },
            info: Ent {
                color: Some(Color::Yellow),
                attrs: Modifier::empty(),
            },
            border: Ent::attr(Modifier::DIM),
            separator: Ent::attr(Modifier::DIM),
            scrollbar: Ent::attr(Modifier::DIM),
            ..Colors::dark()
        }
    }

    /// fzf's `bw` scheme (`--no-color`, or `$NO_COLOR` set): attributes only.
    pub fn bw() -> Self {
        Colors {
            fg: Ent::default(),
            bg: Ent::default(),
            hl: Ent::attr(Modifier::UNDERLINED),
            fg_plus: Ent::attr(Modifier::BOLD),
            bg_plus: Ent::default(),
            hl_plus: Ent::attr(Modifier::BOLD | Modifier::UNDERLINED),
            gutter: Ent::default(),
            pointer: Ent::attr(Modifier::BOLD),
            marker: Ent::attr(Modifier::BOLD),
            prompt: Ent::default(),
            query: Ent::attr(Modifier::BOLD),
            info: Ent::default(),
            spinner: Ent::default(),
            header: Ent::default(),
            border: Ent::default(),
            separator: Ent::default(),
            scrollbar: Ent::default(),
        }
    }

    /// Look up a base scheme by fzf's name.
    fn scheme(name: &str) -> Option<Self> {
        match name {
            "dark" => Some(Colors::dark()),
            "light" => Some(Colors::light()),
            "16" | "base16" => Some(Colors::base16()),
            "bw" | "no" => Some(Colors::bw()),
            _ => None,
        }
    }

    /// Assign one slot by its fzf name (aliases included). Unknown names — the
    /// preview/label/scrollbar family arb has no analog for — are ignored, so a
    /// rich `--color` line from a themed setup still applies the slots that do
    /// map instead of failing the whole spec.
    fn set(&mut self, name: &str, ent: Ent) {
        match name {
            "fg" | "list-fg" => self.fg = ent,
            "bg" | "list-bg" => self.bg = ent,
            "hl" => self.hl = ent,
            "fg+" | "current-fg" | "selected-fg" => self.fg_plus = ent,
            "bg+" | "current-bg" | "selected-bg" => self.bg_plus = ent,
            "hl+" | "current-hl" | "selected-hl" => self.hl_plus = ent,
            "gutter" => self.gutter = ent,
            "pointer" => self.pointer = ent,
            "marker" => self.marker = ent,
            "prompt" => self.prompt = ent,
            "query" | "input-fg" => self.query = ent,
            "info" => self.info = ent,
            "spinner" => self.spinner = ent,
            "header" => self.header = ent,
            "border" => {
                self.border = ent;
                self.separator = ent;
            }
            "separator" => self.separator = ent,
            _ => {}
        }
    }
}

/// Parse one fzf color token: an index (`161`), `-1` for the terminal default,
/// `#rrggbb`, or an ANSI color name.
fn parse_color(tok: &str) -> Option<Option<Color>> {
    if tok == "-1" || tok == "default" {
        return Some(None);
    }
    if let Some(hex) = tok.strip_prefix('#') {
        if hex.len() == 6 {
            let n = u32::from_str_radix(hex, 16).ok()?;
            return Some(Some(Color::Rgb((n >> 16) as u8, (n >> 8) as u8, n as u8)));
        }
        return None;
    }
    if let Ok(idx) = tok.parse::<u8>() {
        return Some(Some(Color::Indexed(idx)));
    }
    let named = match tok {
        "black" => Color::Black,
        "red" => Color::Red,
        "green" => Color::Green,
        "yellow" => Color::Yellow,
        "blue" => Color::Blue,
        "magenta" => Color::Magenta,
        "cyan" => Color::Cyan,
        "white" => Color::Gray,
        "bright-black" | "gray" | "grey" => Color::DarkGray,
        "bright-red" => Color::LightRed,
        "bright-green" => Color::LightGreen,
        "bright-yellow" => Color::LightYellow,
        "bright-blue" => Color::LightBlue,
        "bright-magenta" => Color::LightMagenta,
        "bright-cyan" => Color::LightCyan,
        "bright-white" => Color::White,
        _ => return None,
    };
    Some(Some(named))
}

/// Parse one fzf attribute token.
fn parse_attr(tok: &str) -> Option<Modifier> {
    match tok {
        "bold" => Some(Modifier::BOLD),
        "dim" => Some(Modifier::DIM),
        "italic" => Some(Modifier::ITALIC),
        "underline" => Some(Modifier::UNDERLINED),
        "blink" => Some(Modifier::SLOW_BLINK),
        "reverse" => Some(Modifier::REVERSED),
        "strikethrough" => Some(Modifier::CROSSED_OUT),
        "regular" => Some(Modifier::empty()),
        _ => None,
    }
}

/// Apply one `--color=…` value: an optional leading base scheme followed by
/// `name:color[:attr…]` entries, separated by commas and/or whitespace.
fn apply_color_spec(colors: &mut Colors, spec: &str) {
    for entry in spec.split([',', ' ', '\t']).filter(|e| !e.is_empty()) {
        let mut parts = entry.split(':');
        let Some(name) = parts.next() else { continue };
        if let Some(scheme) = Colors::scheme(name) {
            // A base scheme resets every slot; later entries customize it.
            *colors = scheme;
            continue;
        }
        let mut ent = Ent::default();
        let mut saw = false;
        for tok in parts {
            if let Some(c) = parse_color(tok) {
                ent.color = c;
                saw = true;
            } else if let Some(a) = parse_attr(tok) {
                ent.attrs |= a;
                saw = true;
            }
        }
        if saw {
            colors.set(name, ent);
        }
    }
}

/// One `--nth`/`--with-nth` field range. `1` is the first field, `-1` the last,
/// and [`Nth::ELLIPSIS`] is the open end of `2..` / `..3` / `..`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Nth {
    pub begin: i32,
    pub end: i32,
}

impl Nth {
    pub const ELLIPSIS: i32 = i32::MIN;

    /// Parse one range in fzf's syntax (`ParseRange` in tokenizer.go).
    pub fn parse(s: &str) -> Option<Nth> {
        let n = |v: &str| v.parse::<i32>().ok().filter(|n| *n != 0);
        if s == ".." {
            return Some(Nth {
                begin: Nth::ELLIPSIS,
                end: Nth::ELLIPSIS,
            });
        }
        if let Some(rest) = s.strip_prefix("..") {
            return n(rest).map(|end| Nth {
                begin: Nth::ELLIPSIS,
                end,
            });
        }
        if let Some(rest) = s.strip_suffix("..") {
            return n(rest).map(|begin| Nth {
                begin,
                end: Nth::ELLIPSIS,
            });
        }
        if let Some((a, b)) = s.split_once("..") {
            let (begin, end) = (n(a)?, n(b)?);
            // fzf rejects a negative start paired with a positive end.
            return (!(begin < 0 && end > 0)).then_some(Nth { begin, end });
        }
        n(s).map(|v| Nth { begin: v, end: v })
    }

    /// Parse a comma-separated list (`--nth 1,3..`). Any bad entry drops the
    /// whole list, as fzf treats it as an option error.
    pub fn parse_list(s: &str) -> Vec<Nth> {
        let mut out = Vec::new();
        for part in s.split(',').filter(|p| !p.is_empty()) {
            match Nth::parse(part) {
                Some(r) => out.push(r),
                None => return Vec::new(),
            }
        }
        out
    }
}

/// Split a line into fields the way fzf's `Tokenize` does: with no
/// `--delimiter`, AWK-style — each token is a run of non-space plus the
/// whitespace that follows it, and leading whitespace belongs to no token. With
/// a delimiter, each token keeps its trailing delimiter so ranges rejoin
/// exactly as they appeared.
pub fn tokenize<'a>(text: &'a str, delimiter: Option<&str>) -> Vec<&'a str> {
    let Some(d) = delimiter else {
        let mut out = Vec::new();
        let bytes = text.as_bytes();
        let (mut start, mut i) = (0usize, 0usize);
        // Skip the leading whitespace — fzf counts it as a prefix, not a token.
        while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
            i += 1;
        }
        start = start.max(i);
        while i < bytes.len() {
            // A token runs to the end of the whitespace that follows it.
            while i < bytes.len() && bytes[i] != b' ' && bytes[i] != b'\t' {
                i += 1;
            }
            while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
                i += 1;
            }
            out.push(&text[start..i]);
            start = i;
        }
        return out;
    };
    if d.is_empty() {
        return vec![text];
    }
    let mut out = Vec::new();
    let mut rest = text;
    while let Some(pos) = rest.find(d) {
        let (head, tail) = rest.split_at(pos + d.len());
        out.push(head);
        rest = tail;
    }
    if !rest.is_empty() {
        out.push(rest);
    }
    out
}

/// The text a `--nth`/`--with-nth` range selects: the chosen tokens rejoined.
/// With an explicit delimiter the trailing one is dropped (`--nth 1` on
/// `a:b:c` matches `a`, not `a:`, while `--nth 1..2` matches `a:b`); AWK-style
/// tokens keep their trailing whitespace.
pub fn transform(tokens: &[&str], ranges: &[Nth], delimiter: Option<&str>) -> String {
    if ranges.is_empty() {
        return tokens.concat();
    }
    let mut out = String::new();
    for r in ranges {
        let part = transform_join(tokens, std::slice::from_ref(r));
        match delimiter {
            Some(d) => out.push_str(part.strip_suffix(d).unwrap_or(&part)),
            None => out.push_str(&part),
        }
    }
    out
}

/// fzf's `JoinTokens(Transform(...))`: the selected tokens concatenated as they
/// were, delimiters and all. A token carries the separator that followed it, so
/// joining fields 2 and 3 of `a:b:c` gives `b:c` — [`transform`] instead trims
/// each range, which is what `--nth` matching wants and what `--accept-nth`
/// printing must not do (fzf strips only the very last delimiter, once).
pub fn transform_join(tokens: &[&str], ranges: &[Nth]) -> String {
    if ranges.is_empty() {
        return tokens.concat();
    }
    let n = tokens.len() as i32;
    let resolve = |v: i32| if v < 0 { v + n + 1 } else { v };
    let mut out = String::new();
    for r in ranges {
        let (begin, end) = match (r.begin, r.end) {
            (Nth::ELLIPSIS, Nth::ELLIPSIS) => (1, n),
            (Nth::ELLIPSIS, e) => (1, resolve(e)),
            (b, Nth::ELLIPSIS) => (resolve(b), n),
            (b, e) => (resolve(b), resolve(e)),
        };
        for idx in begin.max(1)..=end.min(n) {
            out.push_str(tokens[(idx - 1) as usize]);
        }
    }
    out
}

/// Strip SGR escape sequences, leaving the text `--ansi` should match against.
pub fn strip_ansi(s: &str) -> String {
    if !s.contains('\u{1b}') {
        return s.to_string();
    }
    let mut out = String::with_capacity(s.len());
    let mut chars = s.chars();
    while let Some(c) = chars.next() {
        if c != '\u{1b}' {
            out.push(c);
            continue;
        }
        // `ESC [ … <final>` — drop the whole sequence.
        if chars.next() != Some('[') {
            continue;
        }
        for t in chars.by_ref() {
            if t.is_ascii_alphabetic() {
                break;
            }
        }
    }
    out
}

/// Where the prompt sits relative to the list (fzf `--layout`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Layout {
    /// fzf's default: prompt at the bottom, list growing upward from it.
    Default,
    /// `--reverse` / `--layout=reverse`: prompt at the top, list below.
    Reverse,
    /// `--layout=reverse-list`: prompt at the bottom, list top-down.
    ReverseList,
}

/// Where the match counter goes (fzf `--info`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Info {
    /// Own line, on the left of a horizontal separator (fzf's default).
    Default,
    /// Own line, on the right of the separator.
    Right,
    /// No counter at all (`--info=hidden` / `--no-info`).
    Hidden,
    /// After the query, with the given prefix (default ` < `).
    Inline(String),
    /// At the right end of the prompt line.
    InlineRight(String),
}

/// Where `--preview-window` puts the preview box relative to the list.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PreviewPos {
    Up,
    Down,
    Left,
    /// fzf's default.
    Right,
}

/// How much room the preview box takes: a share of the body, or a fixed number
/// of columns (`left`/`right`) or rows (`up`/`down`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PreviewSize {
    Percent(u16),
    Cells(u16),
}

/// What `+SCROLL` of `--preview-window` takes as its base line: a number, or a
/// field index expression (`{2}`) read from the cursor line.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ScrollBase {
    Line(i64),
    Field(Vec<Nth>),
}

/// `--preview-window=+SCROLL[OFFSETS][/DENOM]`: the line the preview starts at
/// for each new cursor line. `+{2}+3/2` is field 2, plus 3, placed half a
/// window down.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PreviewScroll {
    pub base: ScrollBase,
    /// Sum of the signed `+N`/`-N` adjustments.
    pub offset: i64,
    /// `/DENOM`: the line sits `rows / denom` below the top; 0 = at the top.
    pub denom: usize,
}

impl PreviewScroll {
    /// Parse the part after the leading `+` (`{2}-5`, `10/2`, `{1}+3/2`).
    fn parse(spec: &str) -> Option<PreviewScroll> {
        let (spec, denom) = match spec.split_once('/') {
            Some((s, d)) => (s, d.parse::<usize>().ok()?),
            None => (spec, 0),
        };
        let (base, mut rest) = match spec.strip_prefix('{') {
            Some(r) => {
                let (inner, tail) = r.split_once('}')?;
                (ScrollBase::Field(Nth::parse_list(inner)), tail)
            }
            None => {
                let end = spec
                    .find(|c: char| !c.is_ascii_digit())
                    .unwrap_or(spec.len());
                (ScrollBase::Line(spec[..end].parse().ok()?), &spec[end..])
            }
        };
        if matches!(&base, ScrollBase::Field(n) if n.is_empty()) {
            return None;
        }
        let mut offset = 0i64;
        while !rest.is_empty() {
            let sign = match rest.as_bytes()[0] {
                b'+' => 1,
                b'-' => -1,
                _ => return None,
            };
            let end = rest[1..]
                .find(|c: char| !c.is_ascii_digit())
                .map_or(rest.len(), |i| i + 1);
            offset += sign * rest[1..end].parse::<i64>().ok()?;
            rest = &rest[end..];
        }
        Some(PreviewScroll {
            base,
            offset,
            denom,
        })
    }

    /// The one-based line this spec points at for `line`, or `None` when the
    /// field is not a number.
    pub fn target(&self, line: &str, delimiter: Option<&str>) -> Option<i64> {
        let base = match &self.base {
            ScrollBase::Line(n) => *n,
            ScrollBase::Field(nth) => {
                let tokens = tokenize(line, delimiter);
                let field = strip_last_delimiter(&transform_join(&tokens, nth), delimiter);
                field.trim().parse::<i64>().ok()?
            }
        };
        Some(base + self.offset)
    }

    /// First preview line (zero-based) to show for a pane of `rows` rows.
    pub fn top(&self, target: i64, rows: usize) -> usize {
        let above = rows.checked_div(self.denom).unwrap_or(0) as i64;
        (target - 1 - above).max(0) as usize
    }
}

/// `--preview-window=[POSITION][,SIZE[%]][,[no]wrap][,[no]hidden][,+SCROLL][,…]`.
///
/// The flags arb can act on are modeled; the rest of fzf's grammar
/// (`border-STYLE`, `follow`, `cycle`, `info`, `~HEADER_LINES`, `default`,
/// `<THRESHOLD(ALT)`) parses without error and is ignored, so a spec written
/// for fzf never fails here — it just may not be honored in full.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PreviewWindow {
    pub pos: PreviewPos,
    pub size: PreviewSize,
    /// `hidden`: the box is not drawn (the command still runs, as in fzf).
    pub hidden: bool,
    /// `wrap`: long preview lines wrap instead of being truncated.
    pub wrap: bool,
    /// `+SCROLL…`: where each cursor line's preview starts.
    pub scroll: Option<PreviewScroll>,
}

impl Default for PreviewWindow {
    fn default() -> Self {
        // fzf(1): "POSITION: (default: right)", and its default size is half the
        // window.
        Self {
            pos: PreviewPos::Right,
            size: PreviewSize::Percent(50),
            hidden: false,
            wrap: false,
            scroll: None,
        }
    }
}

impl PreviewWindow {
    /// Parse one `--preview-window` spec. fzf accepts the parts in any order,
    /// separated by `,`; the older `:` form (`right:55%`) is still widely
    /// written, so both separators are taken.
    pub fn parse(spec: &str) -> PreviewWindow {
        let mut w = PreviewWindow::default();
        w.apply(spec);
        w
    }

    /// Apply a spec on top of the current settings: fzf folds repeated
    /// `--preview-window` options into one, so `--preview-window right:50%
    /// --preview-window +{2}` keeps the position and size.
    pub fn apply(&mut self, spec: &str) {
        let w = self;
        for part in spec.split([',', ':']).map(str::trim) {
            match part {
                "" => {}
                "up" | "top" => w.pos = PreviewPos::Up,
                "down" | "bottom" => w.pos = PreviewPos::Down,
                "left" => w.pos = PreviewPos::Left,
                // `next` places the preview on the list side of the input. arb
                // draws the input at the top in every fzf layout it models, so
                // that is the same side as `down`.
                "right" | "next" => w.pos = PreviewPos::Right,
                "hidden" => w.hidden = true,
                "nohidden" => w.hidden = false,
                "wrap" | "wrap-word" => w.wrap = true,
                "nowrap" => w.wrap = false,
                _ if part.starts_with('+') => w.scroll = PreviewScroll::parse(&part[1..]),
                _ => {
                    if let Some(n) = part.strip_suffix('%') {
                        if let Ok(pct) = n.parse::<u16>() {
                            w.size = PreviewSize::Percent(pct.min(100));
                        }
                    } else if let Ok(cells) = part.parse::<u16>() {
                        w.size = PreviewSize::Cells(cells);
                    }
                    // Anything else is a part of fzf's grammar arb does not act
                    // on (border-*, follow, cycle, info, ~N, default,
                    // <THRESHOLD(ALT)). Ignored rather than rejected.
                }
            }
        }
    }

    /// Split `body` into (list, preview) rectangles. `None` means the preview is
    /// not drawn — `hidden`, or a size of zero, which fzf documents as "preview
    /// window will not be visible, but fzf will still execute the command".
    pub fn split(
        &self,
        body: ratatui::layout::Rect,
    ) -> (ratatui::layout::Rect, Option<ratatui::layout::Rect>) {
        use ratatui::layout::{Constraint, Layout};
        if self.hidden {
            return (body, None);
        }
        let vertical = matches!(self.pos, PreviewPos::Up | PreviewPos::Down);
        let total = match vertical {
            true => body.height,
            false => body.width,
        };
        let want = match self.size {
            PreviewSize::Percent(p) => (u32::from(total) * u32::from(p) / 100) as u16,
            PreviewSize::Cells(c) => c,
        };
        // Leave at least one cell for the list itself, or there is nothing to
        // pick from.
        let want = want.min(total.saturating_sub(1));
        if want == 0 {
            return (body, None);
        }
        let rest = total - want;
        let constraints = match self.pos {
            PreviewPos::Up | PreviewPos::Left => {
                [Constraint::Length(want), Constraint::Length(rest)]
            }
            PreviewPos::Down | PreviewPos::Right => {
                [Constraint::Length(rest), Constraint::Length(want)]
            }
        };
        let chunks = match vertical {
            true => Layout::vertical(constraints).split(body),
            false => Layout::horizontal(constraints).split(body),
        };
        match self.pos {
            PreviewPos::Up | PreviewPos::Left => (chunks[1], Some(chunks[0])),
            PreviewPos::Down | PreviewPos::Right => (chunks[0], Some(chunks[1])),
        }
    }
}

/// How the query's case is read. fzf's default is smart-case — a query typed
/// in lowercase matches either case, and one uppercase character anywhere makes
/// the whole query case-sensitive. `-i`/`--ignore-case` and `+i`/
/// `--no-ignore-case` pin it either way; `--smart-case` restores the default.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Case {
    #[default]
    Smart,
    Ignore,
    Respect,
}

/// The resolved presentation of the picker: everything the renderer and the key
/// handler need in order to match fzf.
#[derive(Clone, Debug)]
pub struct Look {
    pub layout: Layout,
    pub info: Info,
    /// `None` = borderless (fzf's default). `Some((type, sides))` maps straight
    /// onto ratatui's `Block`.
    pub border: Option<(BorderType, Borders)>,
    pub pointer: String,
    pub marker: String,
    /// `--ellipsis`: what a truncated row ends with (fzf's default is `··`).
    pub ellipsis: String,
    pub colors: Colors,
    /// `--cycle`: moving past either end wraps around.
    pub cycle: bool,
    /// `--tac`: present the list in reverse input order.
    pub tac: bool,
    /// `--ansi`: the input carries SGR colour codes — render them, and match
    /// against the text with the codes removed.
    pub ansi: bool,
    /// `--delimiter`: what splits a line into fields. `None` = fzf's AWK-style
    /// splitting (a run of non-space plus the whitespace after it).
    pub delimiter: Option<String>,
    /// `--nth`: which fields the query matches against (the row still shows,
    /// and Enter still emits, the whole line).
    pub nth: Vec<Nth>,
    /// `--with-nth`: which fields the row SHOWS (and, absent `--nth`, matches).
    pub with_nth: Vec<Nth>,
    /// `--header-lines`: the first N input lines are a header, not candidates.
    pub header_lines: usize,
    /// `--with-shell`: how child processes (a `--preview` command, an `execute`
    /// binding) are started. fzf defaults to `$SHELL -c`, NOT `sh -c` — a
    /// preview written against the user's shell (zsh's `print`, a function from
    /// their rc) fails outright under `sh`.
    pub with_shell: Option<String>,
    /// `--print-query`: the query is written before the selection.
    pub print_query: bool,
    /// `--expect=KEYS`: these keys also accept, and the one that did is written
    /// before the selection (an empty line when plain Enter accepted). This is
    /// how fzf-tab drives continuous completion.
    pub expect: Vec<(Key, String)>,
    /// `--min-height=N[+]`: the floor for a percentage `--height`. fzf's default
    /// is `10+` — ten LIST rows, with the chrome added on top (the `+`).
    pub min_height: u16,
    pub min_height_plus: bool,
    /// `--no-scrollbar`: give the list its last column back.
    pub scrollbar: bool,
    /// `--scroll-off`: screen lines kept above/below the cursor while scrolling
    /// (fzf's default is 3, which is why its list starts sliding well before the
    /// cursor reaches the edge).
    pub scroll_off: usize,
    /// `--tiebreak`: the ranking criteria after score, in order, with the
    /// item's input index as the implicit last one. Defaults to what the
    /// `--scheme` implies (`length` for `default`).
    pub tiebreak: Vec<crate::pattern::Criterion>,
    /// `--preview-window`: where the preview box goes and how big it is.
    pub preview_window: PreviewWindow,
    /// `--bind` bindings, in declaration order (later wins for the same key).
    pub binds: Vec<(Key, Vec<Action>)>,
    /// `-i`/`--ignore-case`, `+i`/`--no-ignore-case`, `--smart-case`.
    pub case: Case,
    /// `--algo=v1|v2`: which fuzzy matcher runs. `v2` (the default) is the
    /// score-matrix one; `v1` is fzf's older greedy scan, kept because it finds
    /// a different alignment and so ranks differently.
    pub algo_v1: bool,
    /// `--scheme=default|path|history`: which characters count as boundaries
    /// and what a match just after one is worth (fzf's `Init`, algo.go:176).
    /// `path` also changes the default tiebreak order.
    pub scheme: crate::algo::Scheme,
    /// `--tail=N`: keep only the last N candidates. fzf applies this to the
    /// candidate list, so the dropped lines are not matched, not merely hidden.
    pub tail: Option<usize>,
    /// `--read0`: input records are separated by NUL rather than newline —
    /// what `fd -0` and `find -print0` produce.
    pub read0: bool,
    /// `--print0`: output records are terminated by NUL rather than newline —
    /// what `xargs -0` expects.
    pub print0: bool,
    /// `--accept-nth=EXPR`: print only these fields of the accepted line
    /// instead of the whole line.
    pub accept_nth: Option<AcceptNth>,
    /// `-x`/`--extended` (fzf's DEFAULT) vs `+x`/`--no-extended`. Extended makes
    /// the query a term list — space-separated terms are AND'd, `|` ORs them,
    /// and `'exact` / `^prefix` / `suffix$` / `!inverse` change how a term
    /// matches. `+x` makes the whole query one literal fuzzy term.
    pub extended: bool,
}

impl Default for Look {
    fn default() -> Self {
        Look {
            layout: Layout::Default,
            info: Info::Default,
            border: None,
            // fzf 0.74's default pointer/marker glyphs.
            pointer: "\u{258c}".to_string(),
            marker: "\u{2503}".to_string(),
            ellipsis: "\u{b7}\u{b7}".to_string(),
            colors: Colors::dark(),
            cycle: false,
            tac: false,
            ansi: false,
            delimiter: None,
            nth: Vec::new(),
            with_nth: Vec::new(),
            header_lines: 0,
            with_shell: None,
            print_query: false,
            expect: Vec::new(),
            min_height: 10,
            min_height_plus: true,
            scrollbar: true,
            scroll_off: 3,
            tiebreak: vec![
                crate::pattern::Criterion::Score,
                crate::pattern::Criterion::Length,
            ],
            preview_window: PreviewWindow::default(),
            binds: Vec::new(),
            case: Case::Smart,
            algo_v1: false,
            scheme: crate::algo::Scheme::DEFAULT,
            tail: None,
            read0: false,
            print0: false,
            accept_nth: None,
            extended: true,
        }
    }
}

/// Expand a `--preview` command template for `line`: `{}` is the whole line,
/// `{2}` / `{1,3}` / `{-1}` are fields (the `--nth` grammar). Each value goes
/// through `quote`, so the shell sees it as one word. Any other brace text is
/// left as written.
pub fn expand_preview(
    template: &str,
    line: &str,
    delimiter: Option<&str>,
    quote: impl Fn(&str) -> String,
) -> String {
    let tokens = tokenize(line, delimiter);
    let mut out = String::new();
    let mut rest = template;
    while let Some(open) = rest.find('{') {
        out.push_str(&rest[..open]);
        let tail = &rest[open..];
        let Some(close) = tail.find('}') else { break };
        let inner = &tail[1..close];
        let is_fields = !inner.is_empty()
            && inner
                .chars()
                .all(|c| c.is_ascii_digit() || matches!(c, ',' | '-' | '.'));
        if inner.is_empty() {
            out.push_str(&quote(line));
        } else if is_fields {
            let nth = Nth::parse_list(inner);
            out.push_str(&quote(&strip_last_delimiter(
                &transform_join(&tokens, &nth),
                delimiter,
            )));
        } else {
            out.push_str(&tail[..=close]);
        }
        rest = &tail[close + 1..];
    }
    out.push_str(rest);
    out
}

/// `--accept-nth=EXPR` — what an accepted line prints instead of itself
/// (fzf's `nthTransformer`, options.go:1265). Two forms: a bare field list, or
/// a template of literal text with `{FIELDS}` and `{n}` placeholders.
#[derive(Clone, Debug, PartialEq)]
pub enum AcceptNth {
    /// `--accept-nth=2,4..`: the joined fields, nothing else.
    Fields(Vec<Nth>),
    /// `--accept-nth='[{n}] {2}'`: literal text with placeholders spliced in.
    Template(Vec<AcceptPart>),
}

/// One piece of an `--accept-nth` template.
#[derive(Clone, Debug, PartialEq)]
pub enum AcceptPart {
    Literal(String),
    Fields(Vec<Nth>),
    /// `{n}` — the line's zero-based input index.
    Index,
}

impl AcceptNth {
    /// fzf's `nthTransformer`: a spec of only digits, `,`, `-` and `.` is a
    /// field list; anything else is a template and must hold a placeholder.
    pub fn parse(spec: &str) -> Option<AcceptNth> {
        if !spec.is_empty()
            && spec
                .chars()
                .all(|c| c.is_ascii_digit() || matches!(c, ',' | '-' | '.'))
        {
            let nth = Nth::parse_list(spec);
            if !nth.is_empty() {
                return Some(AcceptNth::Fields(nth));
            }
        }
        let mut parts = Vec::new();
        let mut rest = spec;
        let mut saw_placeholder = false;
        while let Some(open) = rest.find('{') {
            let Some(close) = rest[open..].find('}').map(|i| open + i) else {
                break;
            };
            let inner = &rest[open + 1..close];
            let ok = inner == "n"
                || (!inner.is_empty()
                    && inner
                        .chars()
                        .all(|c| c.is_ascii_digit() || matches!(c, ',' | '-' | '.')));
            if !ok {
                // Not a placeholder — keep scanning past this brace.
                let (lit, tail) = rest.split_at(close + 1);
                parts.push(AcceptPart::Literal(lit.to_string()));
                rest = tail;
                continue;
            }
            if open > 0 {
                parts.push(AcceptPart::Literal(rest[..open].to_string()));
            }
            parts.push(match inner {
                "n" => AcceptPart::Index,
                f => AcceptPart::Fields(Nth::parse_list(f)),
            });
            saw_placeholder = true;
            rest = &rest[close + 1..];
        }
        if !saw_placeholder {
            return None;
        }
        if !rest.is_empty() {
            parts.push(AcceptPart::Literal(rest.to_string()));
        }
        Some(AcceptNth::Template(parts))
    }

    /// Render one line through the spec. `index` backs `{n}`.
    pub fn render(&self, line: &str, delimiter: Option<&str>, index: usize) -> String {
        let tokens = tokenize(line, delimiter);
        match self {
            AcceptNth::Fields(nth) => {
                strip_last_delimiter(&transform_join(&tokens, nth), delimiter)
            }
            AcceptNth::Template(parts) => parts
                .iter()
                .map(|p| match p {
                    AcceptPart::Literal(s) => s.clone(),
                    AcceptPart::Index => index.to_string(),
                    AcceptPart::Fields(nth) => {
                        strip_last_delimiter(&transform_join(&tokens, nth), delimiter)
                    }
                })
                .collect(),
        }
    }
}

/// fzf's `StripLastDelimiter` (tokenizer.go): a field slice keeps the delimiter
/// that followed its last token, and that trailing separator is dropped before
/// the line is printed.
pub fn strip_last_delimiter(s: &str, delimiter: Option<&str>) -> String {
    match delimiter {
        Some(d) => s.strip_suffix(d).unwrap_or(s).to_string(),
        None => s.trim_end().to_string(),
    }
}

/// Map an fzf `--border` style name onto ratatui's border type + sides.
fn parse_border(style: &str) -> Option<(BorderType, Borders)> {
    let all = Borders::ALL;
    match style {
        "rounded" | "" => Some((BorderType::Rounded, all)),
        "sharp" | "block" | "thinblock" => Some((BorderType::Plain, all)),
        "bold" | "double" => Some((BorderType::Double, all)),
        "horizontal" => Some((BorderType::Plain, Borders::TOP | Borders::BOTTOM)),
        "vertical" => Some((BorderType::Plain, Borders::LEFT | Borders::RIGHT)),
        "top" | "up" => Some((BorderType::Plain, Borders::TOP)),
        "bottom" | "down" => Some((BorderType::Plain, Borders::BOTTOM)),
        "left" => Some((BorderType::Plain, Borders::LEFT)),
        "right" => Some((BorderType::Plain, Borders::RIGHT)),
        "none" => None,
        _ => Some((BorderType::Rounded, all)),
    }
}

/// A key an fzf `--bind` can name. Only keys arb's `/dev/tty` reader can
/// actually deliver are modeled; anything else parses to `None` and its binding
/// is dropped rather than silently mis-firing on a different key.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Key {
    /// `ctrl-x` — the letter, lowercased.
    Ctrl(char),
    /// `alt-x` — the character after Esc.
    Alt(char),
    Tab,
    BTab,
    Enter,
    Esc,
    Up,
    Down,
    Left,
    Right,
    PageUp,
    PageDown,
    Home,
    End,
    Backspace,
    Delete,
    Space,
    /// `shift-up`: fzf's default for scrolling the preview up.
    ShiftUp,
    /// `shift-down`: fzf's default for scrolling the preview down.
    ShiftDown,
    /// A plain printable key (`--bind=?:toggle-preview`).
    Char(char),
}

/// The fzf actions arb can carry out. fzf has many more (`execute`,
/// `reload`, `toggle-preview` …); a binding naming one of those is dropped whole
/// so the key keeps its built-in behavior instead of half-working.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Action {
    Up,
    Down,
    PageUp,
    PageDown,
    HalfPageUp,
    HalfPageDown,
    First,
    Last,
    Toggle,
    ToggleAll,
    Accept,
    Abort,
    ClearQuery,
    BackwardDeleteChar,
    PreviewUp,
    PreviewDown,
    PreviewPageUp,
    PreviewPageDown,
    PreviewHalfPageUp,
    PreviewHalfPageDown,
    PreviewTop,
    PreviewBottom,
    Ignore,
}

/// Parse an fzf key name.
fn parse_key(name: &str) -> Option<Key> {
    let n = name.trim().to_ascii_lowercase();
    if let Some(rest) = n.strip_prefix("ctrl-") {
        let mut ch = rest.chars();
        let c = ch.next()?;
        return ch.next().is_none().then_some(Key::Ctrl(c));
    }
    if let Some(rest) = n.strip_prefix("alt-") {
        let mut ch = rest.chars();
        let c = ch.next()?;
        return ch.next().is_none().then_some(Key::Alt(c));
    }
    Some(match n.as_str() {
        "tab" => Key::Tab,
        "btab" | "shift-tab" => Key::BTab,
        "enter" | "return" => Key::Enter,
        "esc" => Key::Esc,
        "up" => Key::Up,
        "down" => Key::Down,
        "left" => Key::Left,
        "right" => Key::Right,
        "pgup" | "page-up" => Key::PageUp,
        "pgdn" | "page-down" => Key::PageDown,
        "home" => Key::Home,
        "end" => Key::End,
        "bspace" | "bs" | "backspace" => Key::Backspace,
        "del" | "delete" => Key::Delete,
        "shift-up" => Key::ShiftUp,
        "shift-down" => Key::ShiftDown,
        "space" => Key::Space,
        s if s.chars().count() == 1 => Key::Char(s.chars().next()?),
        _ => return None,
    })
}

/// Parse an fzf action name. `None` = arb has no equivalent.
fn parse_action(name: &str) -> Option<Action> {
    Some(match name.trim() {
        "up" | "prev-history" => Action::Up,
        "down" | "next-history" => Action::Down,
        "page-up" => Action::PageUp,
        "page-down" => Action::PageDown,
        "half-page-up" => Action::HalfPageUp,
        "half-page-down" => Action::HalfPageDown,
        "first" | "top" | "beginning-of-line" => Action::First,
        "last" => Action::Last,
        "toggle" | "toggle+up" => Action::Toggle,
        "toggle-all" | "select-all" | "deselect-all" => Action::ToggleAll,
        "accept" | "accept-non-empty" => Action::Accept,
        "abort" | "cancel" => Action::Abort,
        "clear-query" | "unix-line-discard" | "kill-line" => Action::ClearQuery,
        "backward-delete-char" => Action::BackwardDeleteChar,
        "preview-up" => Action::PreviewUp,
        "preview-down" => Action::PreviewDown,
        "preview-page-up" => Action::PreviewPageUp,
        "preview-page-down" => Action::PreviewPageDown,
        "preview-half-page-up" => Action::PreviewHalfPageUp,
        "preview-half-page-down" => Action::PreviewHalfPageDown,
        "preview-top" => Action::PreviewTop,
        "preview-bottom" => Action::PreviewBottom,
        "ignore" => Action::Ignore,
        _ => return None,
    })
}

/// Split on `sep`, ignoring separators inside `(…)` — fzf action arguments
/// (`execute(grep -r {} .)`) routinely contain commas and plus signs.
fn split_top(s: &str, sep: char) -> Vec<String> {
    let mut out = Vec::new();
    let mut cur = String::new();
    let mut depth = 0i32;
    for c in s.chars() {
        match c {
            '(' => {
                depth += 1;
                cur.push(c);
            }
            ')' => {
                depth -= 1;
                cur.push(c);
            }
            c if c == sep && depth <= 0 => out.push(std::mem::take(&mut cur)),
            _ => cur.push(c),
        }
    }
    out.push(cur);
    out
}

/// Parse one `--bind` value (`tab:toggle+down,ctrl-n:page-down`) into bindings.
/// A binding whose key or any action arb doesn't implement is skipped entirely.
fn parse_bind_spec(spec: &str) -> Vec<(Key, Vec<Action>)> {
    let mut out = Vec::new();
    for one in split_top(spec, ',') {
        let one = one.trim();
        if one.is_empty() {
            continue;
        }
        let Some((keyname, actions)) = one.split_once(':') else {
            continue;
        };
        let Some(key) = parse_key(keyname) else {
            continue;
        };
        let acts: Option<Vec<Action>> = split_top(actions, '+')
            .iter()
            .map(|a| parse_action(a))
            .collect();
        if let Some(acts) = acts {
            out.push((key, acts));
        }
    }
    out
}

/// The value of `--flag VALUE` / `--flag=VALUE`, consuming the next argv word
/// when the value is separate.
fn flag_value(arg: &str, next: Option<&String>) -> (Option<String>, bool) {
    match arg.split_once('=') {
        Some((_, v)) => (Some(v.to_string()), false),
        None => (next.cloned(), true),
    }
}

impl Look {
    /// Resolve the picker's look from a full argv (env options first, command
    /// line after — later wins, exactly like fzf).
    pub fn parse(args: &[String]) -> Look {
        let mut look = Look::default();
        // fzf honors $NO_COLOR by starting from the `bw` scheme.
        if std::env::var_os("NO_COLOR").is_some() {
            look.colors = Colors::bw();
        }
        let mut i = 0;
        while i < args.len() {
            let a = args[i].as_str();
            // fzf's short flags take an attached value (`-d:`, `-n3..`), so the
            // key is just the flag itself and the rest is the value.
            let key = match a.as_bytes() {
                [b'-', b'd', rest @ ..] if !rest.is_empty() => "-d",
                [b'-', b'n', rest @ ..] if !rest.is_empty() && rest[0] != b'o' => "-n",
                _ => a.split('=').next().unwrap_or(a),
            };
            let attached = match key {
                "-d" | "-n" if a.len() > 2 => Some(a[2..].to_string()),
                _ => None,
            };
            let next = args.get(i + 1);
            match key {
                "--reverse" => look.layout = Layout::Reverse,
                "--no-reverse" => look.layout = Layout::Default,
                "--layout" => {
                    let (v, sep) = flag_value(a, next);
                    look.layout = match v.as_deref() {
                        Some("reverse") => Layout::Reverse,
                        Some("reverse-list") => Layout::ReverseList,
                        _ => Layout::Default,
                    };
                    i += usize::from(sep);
                }
                "--preview-window" => {
                    let (v, sep) = flag_value(a, next);
                    if let Some(spec) = v {
                        look.preview_window.apply(&spec);
                    }
                    i += usize::from(sep);
                }
                "--border" => {
                    // `--border` alone is fzf's rounded box; `--border=STYLE` picks.
                    let style = a.split_once('=').map(|(_, v)| v.to_string());
                    look.border = parse_border(style.as_deref().unwrap_or("rounded"));
                }
                "--no-border" => look.border = None,
                "--info" => {
                    let (v, sep) = flag_value(a, next);
                    look.info = match v.as_deref() {
                        Some("hidden") => Info::Hidden,
                        Some("right") => Info::Right,
                        Some("inline") => Info::Inline(" < ".to_string()),
                        Some("inline-right") => Info::InlineRight(String::new()),
                        Some(s) if s.starts_with("inline-right:") => {
                            Info::InlineRight(s["inline-right:".len()..].to_string())
                        }
                        Some(s) if s.starts_with("inline:") => {
                            Info::Inline(s["inline:".len()..].to_string())
                        }
                        _ => Info::Default,
                    };
                    i += usize::from(sep);
                }
                "--no-info" => look.info = Info::Hidden,
                "--inline-info" => look.info = Info::Inline(" < ".to_string()),
                "--no-inline-info" => look.info = Info::Default,
                "--pointer" => {
                    let (v, sep) = flag_value(a, next);
                    if let Some(v) = v {
                        look.pointer = v;
                    }
                    i += usize::from(sep);
                }
                "--marker" => {
                    let (v, sep) = flag_value(a, next);
                    if let Some(v) = v {
                        look.marker = v;
                    }
                    i += usize::from(sep);
                }
                "--ellipsis" => {
                    let (v, sep) = flag_value(a, next);
                    if let Some(v) = v {
                        look.ellipsis = v;
                    }
                    i += usize::from(sep);
                }
                "--color" => {
                    let (v, sep) = flag_value(a, next);
                    if let Some(v) = v {
                        apply_color_spec(&mut look.colors, &v);
                    }
                    i += usize::from(sep);
                }
                "--no-color" => look.colors = Colors::bw(),
                "--tiebreak" => {
                    let (v, sep) = flag_value(a, next);
                    // A spec fzf would reject leaves the current criteria alone.
                    if let Some(c) = v.as_deref().and_then(crate::pattern::parse_tiebreak) {
                        look.tiebreak = c;
                    }
                    i += usize::from(sep);
                }
                "--scroll-off" => {
                    let (v, sep) = flag_value(a, next);
                    if let Some(n) = v.and_then(|v| v.parse::<usize>().ok()) {
                        look.scroll_off = n;
                    }
                    i += usize::from(sep);
                }
                "--cycle" => look.cycle = true,
                "--no-cycle" => look.cycle = false,
                "--tac" => look.tac = true,
                "--no-tac" => look.tac = false,
                "--ansi" => look.ansi = true,
                "--print-query" => look.print_query = true,
                "--no-print-query" => look.print_query = false,
                // fzf's case flags. The default is smart-case, so `--smart-case`
                // after an `-i` from `$FZF_DEFAULT_OPTS` puts it back.
                "-i" | "--ignore-case" => look.case = Case::Ignore,
                "+i" | "--no-ignore-case" => look.case = Case::Respect,
                "--smart-case" => look.case = Case::Smart,
                // fzf's query language. Extended is the DEFAULT — `+x` is what
                // turns the query back into a single literal fuzzy term.
                "-x" | "--extended" => look.extended = true,
                "+x" | "--no-extended" => look.extended = false,
                // fzf's `--extended-exact` is `-x -e` in one flag (and has no
                // negation of its own). The exact half is applied in `cli.rs`.
                "--extended-exact" => look.extended = true,
                "--algo" => {
                    let (v, sep) = flag_value(a, next);
                    match v.as_deref() {
                        Some("v1") => look.algo_v1 = true,
                        Some("v2") => look.algo_v1 = false,
                        // An unknown algo keeps the default, as fzf rejects it.
                        _ => {}
                    }
                    i += usize::from(sep);
                }
                "--scheme" => {
                    let (v, sep) = flag_value(a, next);
                    // An unrecognized scheme keeps the default, the way fzf
                    // rejects it rather than scoring with something else.
                    if let Some(s) = v.as_deref().and_then(crate::algo::Scheme::by_name) {
                        look.scheme = s;
                        // A scheme carries its own tiebreak order, and fzf lets
                        // whichever of `--scheme`/`--tiebreak` comes last win.
                        look.tiebreak = crate::pattern::scheme_criteria(&s);
                    }
                    i += usize::from(sep);
                }
                // Record framing: NUL in, NUL out.
                "--read0" => look.read0 = true,
                "--no-read0" => look.read0 = false,
                "--print0" => look.print0 = true,
                "--no-print0" => look.print0 = false,
                "--tail" => {
                    let (v, sep) = flag_value(a, next);
                    look.tail = v.and_then(|v| v.parse::<usize>().ok()).filter(|n| *n > 0);
                    i += usize::from(sep);
                }
                "--no-tail" => look.tail = None,
                "--accept-nth" => {
                    let (v, sep) = flag_value(a, next);
                    look.accept_nth = v.as_deref().and_then(AcceptNth::parse);
                    i += usize::from(sep);
                }
                "--with-shell" => {
                    let (v, sep) = flag_value(a, next);
                    look.with_shell = v.filter(|v| !v.is_empty());
                    i += usize::from(sep);
                }
                "--expect" => {
                    let (v, sep) = flag_value(a, next);
                    if let Some(v) = v {
                        look.expect = v
                            .split(',')
                            .filter(|k| !k.is_empty())
                            .filter_map(|k| parse_key(k).map(|p| (p, k.to_string())))
                            .collect();
                    }
                    i += usize::from(sep);
                }
                "--no-ansi" => look.ansi = false,
                "--no-expect" => look.expect.clear(),
                "--no-header-lines" => look.header_lines = 0,
                // `--scrollbar[=CHARS]` puts the bar back after a `--no-scrollbar`.
                // arb draws fzf's default glyph, so only the on/off state is read.
                "--scrollbar" => look.scrollbar = true,
                "--delimiter" | "-d" => {
                    let (v, sep) = match attached {
                        Some(v) => (Some(v), false),
                        None => flag_value(a, next),
                    };
                    look.delimiter = v.filter(|v| !v.is_empty());
                    i += usize::from(sep);
                }
                "--nth" | "-n" => {
                    let (v, sep) = match attached {
                        Some(v) => (Some(v), false),
                        None => flag_value(a, next),
                    };
                    if let Some(v) = v {
                        look.nth = Nth::parse_list(&v);
                    }
                    i += usize::from(sep);
                }
                "--with-nth" => {
                    let (v, sep) = flag_value(a, next);
                    if let Some(v) = v {
                        look.with_nth = Nth::parse_list(&v);
                    }
                    i += usize::from(sep);
                }
                "--header-lines" => {
                    let (v, sep) = flag_value(a, next);
                    if let Some(n) = v.and_then(|v| v.parse::<usize>().ok()) {
                        look.header_lines = n;
                    }
                    i += usize::from(sep);
                }
                "--min-height" => {
                    let (v, sep) = flag_value(a, next);
                    if let Some(v) = v {
                        let plus = v.ends_with('+');
                        if let Ok(n) = v.trim_end_matches('+').parse::<u16>() {
                            look.min_height = n;
                            look.min_height_plus = plus;
                        }
                    }
                    i += usize::from(sep);
                }
                "--no-scrollbar" => look.scrollbar = false,
                "--bind" => {
                    let (v, sep) = flag_value(a, next);
                    if let Some(v) = v {
                        look.binds.extend(parse_bind_spec(&v));
                    }
                    i += usize::from(sep);
                }
                _ => {}
            }
            i += 1;
        }
        look
    }

    /// The command and flags a child process starts with: `--with-shell` if
    /// given, else `$SHELL -c`, else `sh -c` — fzf's rule, so a preview that
    /// works under `fzf` works here.
    pub fn shell(&self) -> Vec<String> {
        if let Some(w) = &self.with_shell {
            let words = shell_split(w);
            if !words.is_empty() {
                return words;
            }
        }
        match std::env::var("SHELL") {
            Ok(sh) if !sh.is_empty() => vec![sh, "-c".to_string()],
            _ => vec!["sh".to_string(), "-c".to_string()],
        }
    }

    /// The actions bound to `key`, if any. Later bindings win, so the command
    /// line overrides `$FZF_DEFAULT_OPTS` for the same key.
    pub fn bound(&self, key: Key) -> Option<&[Action]> {
        self.binds
            .iter()
            .rev()
            .find(|(k, _)| *k == key)
            .map(|(_, a)| a.as_slice())
    }

    /// The actions `key` runs: the user's binding, else fzf's built-in preview
    /// scrolling (`shift-up`/`shift-down`).
    pub fn bound_or_default(&self, key: Key) -> Option<Vec<Action>> {
        self.bound(key).map(<[_]>::to_vec).or(match key {
            Key::ShiftUp => Some(vec![Action::PreviewUp]),
            Key::ShiftDown => Some(vec![Action::PreviewDown]),
            _ => None,
        })
    }
}

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

    #[test]
    fn shell_split_keeps_quoted_prompt_intact() {
        // The real $FZF_DEFAULT_OPTS from a themed zsh setup: the prompt has a
        // trailing space and parentheses, so quoting must survive the split.
        let v = shell_split("--prompt='<<)ZPWR(>> ' --reverse --height 100%");
        assert_eq!(
            v,
            vec!["--prompt=<<)ZPWR(>> ", "--reverse", "--height", "100%"]
        );
    }

    #[test]
    fn shell_split_handles_double_quotes_and_escapes() {
        let v = shell_split(r#"--prompt="a b" --header=c\ d"#);
        assert_eq!(v, vec!["--prompt=a b", "--header=c d"]);
        // An empty quoted value is a word, not nothing.
        assert_eq!(shell_split("--prompt=''"), vec!["--prompt="]);
    }

    #[test]
    fn later_options_win() {
        // env options are spliced first, so a command-line flag must override.
        let args: Vec<String> = ["--layout=reverse", "--layout=default"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        assert_eq!(Look::parse(&args).layout, Layout::Default);
    }

    #[test]
    fn parses_layout_border_info_pointer() {
        let args: Vec<String> = [
            "--reverse",
            "--border",
            "--info=inline",
            "--pointer",
            ">",
            "--marker",
            "*",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();
        let look = Look::parse(&args);
        assert_eq!(look.layout, Layout::Reverse);
        assert_eq!(look.border, Some((BorderType::Rounded, Borders::ALL)));
        assert_eq!(look.info, Info::Inline(" < ".to_string()));
        assert_eq!(look.pointer, ">");
        assert_eq!(look.marker, "*");
    }

    #[test]
    fn color_spec_overrides_scheme_slots() {
        let args: Vec<String> = ["--color=light,hl:#ff0000,fg+:2:bold:underline"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        let c = Look::parse(&args).colors;
        // The base scheme applied…
        assert_eq!(c.prompt, Ent::b(25));
        // …then the per-slot overrides on top of it.
        assert_eq!(c.hl.color, Some(Color::Rgb(0xff, 0, 0)));
        // `2` is a palette index, not a name — fzf writes it as `38;5;2`.
        assert_eq!(c.fg_plus.color, Some(Color::Indexed(2)));
        assert!(c.fg_plus.attrs.contains(Modifier::BOLD));
        assert!(c.fg_plus.attrs.contains(Modifier::UNDERLINED));
    }

    #[test]
    fn binds_map_fzf_actions() {
        let args: Vec<String> =
            ["--bind=ctrl-n:page-down,ctrl-p:page-up,tab:toggle+down,ctrl-j:down,ctrl-k:up"]
                .iter()
                .map(|s| s.to_string())
                .collect();
        let look = Look::parse(&args);
        assert_eq!(look.bound(Key::Ctrl('n')), Some(&[Action::PageDown][..]));
        assert_eq!(look.bound(Key::Ctrl('p')), Some(&[Action::PageUp][..]));
        assert_eq!(
            look.bound(Key::Tab),
            Some(&[Action::Toggle, Action::Down][..])
        );
        assert_eq!(look.bound(Key::Ctrl('j')), Some(&[Action::Down][..]));
        assert_eq!(look.bound(Key::Ctrl('k')), Some(&[Action::Up][..]));
    }

    #[test]
    fn unsupported_action_drops_only_that_binding() {
        // `execute(...)` has no arb analog: that key keeps its built-in meaning,
        // while the other binding in the same spec still applies.
        let args: Vec<String> = ["--bind=ctrl-o:execute(vim {}),ctrl-k:up"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        let look = Look::parse(&args);
        assert_eq!(look.bound(Key::Ctrl('o')), None);
        assert_eq!(look.bound(Key::Ctrl('k')), Some(&[Action::Up][..]));
    }

    #[test]
    fn preview_scroll_actions_parse_and_shift_arrows_default_to_them() {
        let args: Vec<String> = ["--bind=ctrl-d:preview-half-page-down,ctrl-b:preview-page-up,alt-t:preview-top+preview-down"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        let look = Look::parse(&args);
        assert_eq!(
            look.bound(Key::Ctrl('d')),
            Some(&[Action::PreviewHalfPageDown][..])
        );
        assert_eq!(
            look.bound(Key::Ctrl('b')),
            Some(&[Action::PreviewPageUp][..])
        );
        assert_eq!(
            look.bound(Key::Alt('t')),
            Some(&[Action::PreviewTop, Action::PreviewDown][..])
        );
        // fzf's built-in shift-up/shift-down, overridable by a binding.
        let plain = Look::default();
        assert_eq!(
            plain.bound_or_default(Key::ShiftUp),
            Some(vec![Action::PreviewUp])
        );
        assert_eq!(
            plain.bound_or_default(Key::ShiftDown),
            Some(vec![Action::PreviewDown])
        );
        assert_eq!(plain.bound_or_default(Key::Char('x')), None);
        let own = Look::parse(&["--bind=shift-up:up".to_string()]);
        assert_eq!(own.bound_or_default(Key::ShiftUp), Some(vec![Action::Up]));
    }

    #[test]
    fn preview_scroll_spec_parses_base_offsets_and_denominator() {
        let w = PreviewWindow::parse("right,60%,+{2}+3/2");
        assert_eq!(w.size, PreviewSize::Percent(60));
        let sc = w.scroll.expect("scroll");
        assert_eq!(sc.base, ScrollBase::Field(Nth::parse_list("2")));
        assert_eq!((sc.offset, sc.denom), (3, 2));
        let n = PreviewWindow::parse("+10-4").scroll.expect("scroll");
        assert_eq!((n.base, n.offset, n.denom), (ScrollBase::Line(10), -4, 0));
        assert_eq!(PreviewWindow::parse("+{x}").scroll, None);
        assert_eq!(PreviewWindow::parse("+{2}*").scroll, None);
    }

    #[test]
    fn preview_scroll_targets_the_field_line_and_centres_it() {
        let sc = PreviewWindow::parse("+{2}-5").scroll.unwrap();
        assert_eq!(sc.target("main.rs:120:fn x", Some(":")), Some(115));
        assert_eq!(sc.target("main.rs:abc:fn x", Some(":")), None);
        // One-based line 115 is index 114 at the top …
        assert_eq!(sc.top(115, 20), 114);
        // … or half a window lower with `/2`, clamped at the first line.
        let mid = PreviewWindow::parse("+{2}/2").scroll.unwrap();
        assert_eq!(mid.top(120, 20), 109);
        assert_eq!(mid.top(3, 20), 0);
    }

    #[test]
    fn preview_template_expands_whole_line_and_fields() {
        let q = |s: &str| format!("<{s}>");
        assert_eq!(
            expand_preview("bat {1} --highlight-line {2}", "a.rs:7:x", Some(":"), q),
            "bat <a.rs> --highlight-line <7>"
        );
        assert_eq!(expand_preview("echo {}", "a b", None, q), "echo <a b>");
        assert_eq!(
            expand_preview("awk '{print $1}' {}", "z", None, q),
            "awk '{print $1}' <z>"
        );
    }

    #[test]
    fn repeated_preview_window_options_fold_together() {
        let look = Look::parse(
            &[
                "--preview-window=down:40%:wrap",
                "--preview-window",
                "+{2}+3/3",
            ]
            .map(String::from),
        );
        let w = look.preview_window;
        assert_eq!(
            (w.pos, w.size, w.wrap),
            (PreviewPos::Down, PreviewSize::Percent(40), true)
        );
        assert!(w.scroll.is_some());
    }

    #[test]
    fn preview_window_defaults_are_fzfs() {
        // fzf(1): "POSITION: (default: right)", half the window.
        let w = PreviewWindow::default();
        assert_eq!(w.pos, PreviewPos::Right);
        assert_eq!(w.size, PreviewSize::Percent(50));
        assert!(!w.hidden && !w.wrap);
    }

    #[test]
    fn preview_window_takes_both_separators_in_any_order() {
        // The modern comma form and the older colon form are both in the wild.
        let a = PreviewWindow::parse("down,30%,wrap");
        assert_eq!(a.pos, PreviewPos::Down);
        assert_eq!(a.size, PreviewSize::Percent(30));
        assert!(a.wrap);
        let b = PreviewWindow::parse("right:55%");
        assert_eq!(b.pos, PreviewPos::Right);
        assert_eq!(b.size, PreviewSize::Percent(55));
        // Order does not matter to fzf, so it must not matter here.
        assert_eq!(PreviewWindow::parse("20,up"), PreviewWindow::parse("up,20"));
        assert_eq!(PreviewWindow::parse("up,20").size, PreviewSize::Cells(20));
    }

    #[test]
    fn unmodeled_parts_of_the_spec_are_ignored_not_rejected() {
        // A spec written for fzf must never fail here just because arb does not
        // act on every part of the grammar.
        let w = PreviewWindow::parse("left,40%,border-sharp,follow,cycle,+3/2,~2,noinfo");
        assert_eq!(w.pos, PreviewPos::Left);
        assert_eq!(w.size, PreviewSize::Percent(40));
    }

    #[test]
    fn hidden_and_zero_size_draw_no_pane() {
        use ratatui::layout::Rect;
        let body = Rect {
            x: 0,
            y: 0,
            width: 100,
            height: 30,
        };
        let (list, pane) = PreviewWindow::parse("hidden").split(body);
        assert!(pane.is_none(), "hidden draws nothing");
        assert_eq!(list, body, "and the list takes the whole body");
        // fzf(1): "If size is given as 0, preview window will not be visible,
        // but fzf will still execute the command in the background."
        assert!(PreviewWindow::parse("right,0").split(body).1.is_none());
        assert!(PreviewWindow::parse("right,0%").split(body).1.is_none());
    }

    #[test]
    fn the_split_places_and_sizes_the_pane() {
        use ratatui::layout::Rect;
        let body = Rect {
            x: 0,
            y: 0,
            width: 100,
            height: 30,
        };

        let (list, pane) = PreviewWindow::parse("right,60%").split(body);
        let pane = pane.expect("drawn");
        assert_eq!((list.width, pane.width), (40, 60));
        assert_eq!(pane.x, 40, "right means after the list");

        let (list, pane) = PreviewWindow::parse("left,25").split(body);
        let pane = pane.expect("drawn");
        assert_eq!((pane.width, list.width), (25, 75));
        assert_eq!(pane.x, 0, "left means before the list");

        let (list, pane) = PreviewWindow::parse("up,10").split(body);
        let pane = pane.expect("drawn");
        assert_eq!((pane.height, list.height), (10, 20));
        assert_eq!(pane.y, 0);

        let (list, pane) = PreviewWindow::parse("down,3").split(body);
        let pane = pane.expect("drawn");
        assert_eq!((list.height, pane.height), (27, 3));
        assert_eq!(pane.y, 27);
    }

    #[test]
    fn the_list_always_keeps_a_cell() {
        use ratatui::layout::Rect;
        let body = Rect {
            x: 0,
            y: 0,
            width: 10,
            height: 4,
        };
        // An oversized request must not leave zero columns to pick from.
        let (list, pane) = PreviewWindow::parse("right,100%").split(body);
        assert_eq!(list.width, 1);
        assert_eq!(pane.expect("drawn").width, 9);
    }

    #[test]
    fn look_parses_the_flag_in_both_spellings() {
        let attached = Look::parse(&["arb".into(), "--fzf".into(), "--preview-window=up,7".into()]);
        assert_eq!(attached.preview_window.pos, PreviewPos::Up);
        assert_eq!(attached.preview_window.size, PreviewSize::Cells(7));
        let separate = Look::parse(&[
            "arb".into(),
            "--fzf".into(),
            "--preview-window".into(),
            "down,20%".into(),
        ]);
        assert_eq!(separate.preview_window.pos, PreviewPos::Down);
        assert_eq!(separate.preview_window.size, PreviewSize::Percent(20));
    }
}