fresh-editor 0.3.10

A lightweight, fast terminal-based text editor with LSP support and TypeScript plugins
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
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
//! Unified highlighting engine over syntect (TextMate grammars) and
//! tree-sitter. Syntect is the default; tree-sitter `Language` is still
//! detected for non-highlighting features (indentation, semantic highlighting).
//!
//! # TextMate cache design
//!
//! Syntect's parser is a sequential state machine — it must process bytes
//! in order from a known parse state to track multi-line constructs and
//! embedded language transitions. To make scrolling cheap, the engine keeps
//! a span cache, a `(ParseState, ScopeStack)` snapshot at the cache tail,
//! and periodic checkpoint anchors to support resume-from-anywhere.
//!
//! Three render-time paths, gated by what the cache covers:
//!
//! - **Cache hit** — cache fully covers the parse range and there's no
//!   pending edit; filter cached spans for the viewport. Zero parse work.
//! - **Forward extension** — cache covers the start of the parse range but
//!   not its end; resume from `tail_state` and parse only the uncovered
//!   tail bytes. Steady-state scroll path.
//! - **Partial update** — there's a pending edit; resume from the nearest
//!   checkpoint before the dirty point and parse forward looking for
//!   convergence (state matches an existing checkpoint), bounded by a
//!   per-pass byte budget so pathological edits can't degenerate into
//!   whole-file reparses.
//! - **Cold start / fallback** — no cache, or none of the above applies;
//!   parse the appropriate range from a fresh state or nearest checkpoint.
//!
//! For files at or below `MAX_PARSE_BYTES` the parse range is the whole
//! file, so the cache is whole-file after the first parse and scrolling
//! becomes filter-only. Larger files use a viewport-centred window of
//! `±context_bytes` and rely on the forward-extension path to keep
//! scroll-cost bounded.
//!
//! Edits go through `notify_insert` / `notify_delete`, which shift cached
//! span byte offsets in place, set `dirty_from`, and invalidate `tail_state`
//! when the edit lies inside the cached range.

use crate::model::buffer::Buffer;
use crate::model::marker::{MarkerId, MarkerList};
use crate::primitives::grammar::GrammarRegistry;
use crate::primitives::highlighter::{
    highlight_bg, highlight_color, HighlightCategory, HighlightSpan, Highlighter, Language,
};
use crate::view::theme::Theme;
use std::collections::HashMap;
use std::ops::Range;
use std::path::Path;
use std::sync::Arc;
use syntect::parsing::SyntaxSet;

/// Map TextMate scope to highlight category
fn scope_to_category(scope: &str) -> Option<HighlightCategory> {
    let scope_lower = scope.to_lowercase();

    // Comments - highest priority
    if scope_lower.starts_with("comment") {
        return Some(HighlightCategory::Comment);
    }

    // Strings
    if scope_lower.starts_with("string") {
        return Some(HighlightCategory::String);
    }

    // Markdown/markup scopes - handle before generic keyword/punctuation checks
    // See: https://macromates.com/manual/en/language_grammars (TextMate scope naming)
    // Headings: markup.heading and entity.name.section (used by syntect's markdown grammar)
    if scope_lower.starts_with("markup.heading") || scope_lower.starts_with("entity.name.section") {
        return Some(HighlightCategory::Keyword); // Headers styled like keywords (bold, prominent)
    }
    // Bold: markup.bold
    if scope_lower.starts_with("markup.bold") {
        return Some(HighlightCategory::Constant); // Bold styled like constants (bright)
    }
    // Italic: markup.italic
    if scope_lower.starts_with("markup.italic") {
        return Some(HighlightCategory::Variable); // Italic styled like variables
    }
    // Inline code and code blocks: markup.raw, markup.inline.raw
    if scope_lower.starts_with("markup.raw") || scope_lower.starts_with("markup.inline.raw") {
        return Some(HighlightCategory::String); // Code styled like strings
    }
    // Links: markup.underline.link
    if scope_lower.starts_with("markup.underline.link") {
        return Some(HighlightCategory::Function); // Links styled like functions (distinct color)
    }
    // Generic underline (often links)
    if scope_lower.starts_with("markup.underline") {
        return Some(HighlightCategory::Function);
    }
    // Block quotes: markup.quote
    if scope_lower.starts_with("markup.quote") {
        return Some(HighlightCategory::Comment); // Quotes styled like comments (subdued)
    }
    // Lists: markup.list
    if scope_lower.starts_with("markup.list") {
        return Some(HighlightCategory::Operator); // List markers styled like operators
    }
    // Strikethrough: markup.strikethrough
    if scope_lower.starts_with("markup.strikethrough") {
        return Some(HighlightCategory::Comment); // Strikethrough styled subdued
    }

    // Diff scopes (syntect's bundled `Diff` grammar). These scope the
    // entire row, not just the leading +/-/@@ marker, so the renderer
    // can paint a whole-line background by reading the span's bg.
    //
    //   markup.inserted.diff      — `+` line
    //   markup.deleted.diff       — `-` line
    //   meta.diff.range.unified   — `@@ ... @@` hunk header
    //   markup.changed.*          — generic "changed" marker (rare)
    //   meta.diff.header.*        — `diff --git`, `index ...`, file
    //                               headers; render like Type so they
    //                               stand out without a bg wash.
    if scope_lower.starts_with("markup.inserted") {
        return Some(HighlightCategory::Inserted);
    }
    if scope_lower.starts_with("markup.deleted") {
        return Some(HighlightCategory::Deleted);
    }
    if scope_lower.starts_with("markup.changed") || scope_lower.starts_with("meta.diff.range") {
        return Some(HighlightCategory::Changed);
    }
    if scope_lower.starts_with("meta.diff.header") {
        return Some(HighlightCategory::Type);
    }

    // Keywords
    if scope_lower.starts_with("keyword.control")
        || scope_lower.starts_with("keyword.other")
        || scope_lower.starts_with("keyword.declaration")
        || scope_lower.starts_with("keyword")
    {
        // keyword.operator should map to Operator, not Keyword
        if !scope_lower.starts_with("keyword.operator") {
            return Some(HighlightCategory::Keyword);
        }
    }

    // Punctuation that belongs to a parent construct (comment/string delimiters)
    // These must be checked before the generic punctuation rule below.
    // TextMate grammars assign e.g. `punctuation.definition.comment` to # // /* etc.
    if scope_lower.starts_with("punctuation.definition.comment") {
        return Some(HighlightCategory::Comment);
    }
    if scope_lower.starts_with("punctuation.definition.string") {
        return Some(HighlightCategory::String);
    }

    // Operators (keyword.operator only)
    if scope_lower.starts_with("keyword.operator") {
        return Some(HighlightCategory::Operator);
    }

    // Punctuation brackets ({, }, (, ), [, ], <, >)
    // Covers punctuation.section.*, punctuation.bracket.*,
    // and punctuation.definition.{array,block,brackets,group,inline-table,section,table,tag}
    if scope_lower.starts_with("punctuation.section")
        || scope_lower.starts_with("punctuation.bracket")
        || scope_lower.starts_with("punctuation.definition.array")
        || scope_lower.starts_with("punctuation.definition.block")
        || scope_lower.starts_with("punctuation.definition.brackets")
        || scope_lower.starts_with("punctuation.definition.group")
        || scope_lower.starts_with("punctuation.definition.inline-table")
        || scope_lower.starts_with("punctuation.definition.section")
        || scope_lower.starts_with("punctuation.definition.table")
        || scope_lower.starts_with("punctuation.definition.tag")
    {
        return Some(HighlightCategory::PunctuationBracket);
    }

    // Punctuation delimiters (;, ,, .)
    if scope_lower.starts_with("punctuation.separator")
        || scope_lower.starts_with("punctuation.terminator")
        || scope_lower.starts_with("punctuation.accessor")
    {
        return Some(HighlightCategory::PunctuationDelimiter);
    }

    // Functions
    if scope_lower.starts_with("entity.name.function")
        || scope_lower.starts_with("support.function")
        || scope_lower.starts_with("meta.function-call")
        || scope_lower.starts_with("variable.function")
    {
        return Some(HighlightCategory::Function);
    }

    // Types
    if scope_lower.starts_with("entity.name.type")
        || scope_lower.starts_with("entity.name.class")
        || scope_lower.starts_with("entity.name.struct")
        || scope_lower.starts_with("entity.name.enum")
        || scope_lower.starts_with("entity.name.interface")
        || scope_lower.starts_with("entity.name.trait")
        || scope_lower.starts_with("support.type")
        || scope_lower.starts_with("support.class")
        || scope_lower.starts_with("storage.type")
    {
        return Some(HighlightCategory::Type);
    }

    // Storage modifiers (pub, static, const as keywords)
    if scope_lower.starts_with("storage.modifier") {
        return Some(HighlightCategory::Keyword);
    }

    // Constants and numbers
    if scope_lower.starts_with("constant.numeric")
        || scope_lower.starts_with("constant.language.boolean")
    {
        return Some(HighlightCategory::Number);
    }
    if scope_lower.starts_with("constant") {
        return Some(HighlightCategory::Constant);
    }

    // Variables
    if scope_lower.starts_with("variable.parameter")
        || scope_lower.starts_with("variable.other")
        || scope_lower.starts_with("variable.language")
    {
        return Some(HighlightCategory::Variable);
    }

    // Properties / object keys
    if scope_lower.starts_with("entity.name.tag")
        || scope_lower.starts_with("support.other.property")
        || scope_lower.starts_with("meta.object-literal.key")
        || scope_lower.starts_with("variable.other.property")
        || scope_lower.starts_with("variable.other.object.property")
    {
        return Some(HighlightCategory::Property);
    }

    // Attributes (decorators, annotations)
    if scope_lower.starts_with("entity.other.attribute")
        || scope_lower.starts_with("meta.attribute")
        || scope_lower.starts_with("entity.name.decorator")
    {
        return Some(HighlightCategory::Attribute);
    }

    // Generic variable fallback
    if scope_lower.starts_with("variable") {
        return Some(HighlightCategory::Variable);
    }

    None
}

/// Unified highlighting engine supporting multiple backends
#[derive(Default)]
pub enum HighlightEngine {
    /// Tree-sitter based highlighting (built-in languages)
    TreeSitter(Box<Highlighter>),
    /// TextMate grammar based highlighting
    TextMate(Box<TextMateEngine>),
    /// No highlighting available
    #[default]
    None,
}

/// TextMate highlighting engine. See module docs for the cache design.
pub struct TextMateEngine {
    syntax_set: Arc<SyntaxSet>,
    syntax_index: usize,
    checkpoint_markers: MarkerList,
    checkpoint_states:
        HashMap<MarkerId, (syntect::parsing::ParseState, syntect::parsing::ScopeStack)>,
    dirty_from: Option<usize>,
    cache: Option<TextMateCache>,
    last_buffer_len: usize,
    ts_language: Option<Language>,
    stats: HighlightStats,
    // Scope→Category memo. Syntect Scope atoms are append-only-interned
    // globally, so entries never need invalidation.
    scope_category_cache: HashMap<syntect::parsing::Scope, Option<HighlightCategory>>,
}

/// Counters for monitoring highlighting performance in tests.
#[derive(Debug, Default, Clone)]
pub struct HighlightStats {
    /// Number of bytes parsed by syntect (total across all highlight_viewport calls).
    pub bytes_parsed: usize,
    /// Number of highlight_viewport calls that hit the span cache.
    pub cache_hits: usize,
    /// Number of highlight_viewport calls that missed the cache and re-parsed.
    pub cache_misses: usize,
    /// Number of checkpoint states updated during convergence.
    pub checkpoints_updated: usize,
    /// Number of times convergence was detected (state matched existing checkpoint).
    pub convergences: usize,
}

#[derive(Debug, Clone)]
struct TextMateCache {
    range: Range<usize>,
    spans: Vec<CachedSpan>,
    // Parse state at `range.end`; powers forward extension. None when the
    // last mutation didn't end at `range.end`.
    tail_state: Option<(syntect::parsing::ParseState, syntect::parsing::ScopeStack)>,
}

#[derive(Debug, Clone)]
struct CachedSpan {
    range: Range<usize>,
    category: crate::primitives::highlighter::HighlightCategory,
}

/// Small/large file threshold (whole-file cache vs viewport window).
const MAX_PARSE_BYTES: usize = 1024 * 1024;

/// Distance between checkpoint anchors. Smaller = faster convergence on edit.
const CHECKPOINT_INTERVAL: usize = 256;

/// Per-pass cap on partial-update parsing past `dirty_pos`. Bounds work for
/// pathological edits whose effect doesn't converge.
const CONVERGENCE_BUDGET: usize = 64 * 1024;

/// Byte position one past the end of the line that starts at `pos`.
/// Accepts `\n` and `\r\n` terminators; returns `content_bytes.len()`
/// when the buffer ends without a terminator (the streaming tail).
fn find_line_end(content_bytes: &[u8], pos: usize) -> usize {
    let mut line_end = pos;
    while line_end < content_bytes.len() {
        if content_bytes[line_end] == b'\n' {
            line_end += 1;
            break;
        } else if content_bytes[line_end] == b'\r' {
            if line_end + 1 < content_bytes.len() && content_bytes[line_end + 1] == b'\n' {
                line_end += 2;
            } else {
                line_end += 1;
            }
            break;
        }
        line_end += 1;
    }
    line_end
}

/// UTF-8-decoded line ready to feed `state.parse_line`.
struct PreparedLine {
    /// What `parse_line` sees: line content always terminated by `\n`,
    /// EXCEPT for the buffer's final partial line where no `\n` has
    /// arrived yet (caller must not commit cache state past such a
    /// line — see `extend_cache_forward`).
    line_for_syntect: String,
    /// Byte length of the line excluding `\r` / `\n` terminator.
    line_content_len: usize,
    /// Whether the original line ended with `\n` (true for every line
    /// except the streaming tail).
    ends_with_newline: bool,
}

/// Slice the line starting at `pos` from `content_bytes` and prepare
/// it for `parse_line`. Returns `(line_end, line_byte_len, prepared)`:
/// callers always advance by `line_byte_len` to `line_end`; `prepared`
/// is `None` only when the line wasn't valid UTF-8 (skip & continue).
fn prepare_line_at(content_bytes: &[u8], pos: usize) -> (usize, usize, Option<PreparedLine>) {
    let line_end = find_line_end(content_bytes, pos);
    let line_bytes = &content_bytes[pos..line_end];
    let line_byte_len = line_bytes.len();
    let prepared = std::str::from_utf8(line_bytes).ok().map(|line_str| {
        let line_content = line_str.trim_end_matches(&['\r', '\n'][..]);
        let ends_with_newline = line_str.ends_with('\n');
        let is_streaming_tail = line_end == content_bytes.len() && !ends_with_newline;
        let line_for_syntect = if is_streaming_tail {
            line_content.to_string()
        } else {
            format!("{}\n", line_content)
        };
        PreparedLine {
            line_for_syntect,
            line_content_len: line_content.len(),
            ends_with_newline,
        }
    });
    (line_end, line_byte_len, prepared)
}

impl TextMateEngine {
    /// Create a new TextMate engine for the given syntax
    pub fn new(syntax_set: Arc<SyntaxSet>, syntax_index: usize) -> Self {
        Self {
            syntax_set,
            syntax_index,
            checkpoint_markers: MarkerList::new(),
            checkpoint_states: HashMap::new(),
            dirty_from: None,
            cache: None,
            last_buffer_len: 0,
            ts_language: None,
            stats: HighlightStats::default(),
            scope_category_cache: HashMap::new(),
        }
    }

    /// Create a new TextMate engine with a tree-sitter language for non-highlighting features
    pub fn with_language(
        syntax_set: Arc<SyntaxSet>,
        syntax_index: usize,
        ts_language: Option<Language>,
    ) -> Self {
        Self {
            syntax_set,
            syntax_index,
            checkpoint_markers: MarkerList::new(),
            checkpoint_states: HashMap::new(),
            dirty_from: None,
            cache: None,
            last_buffer_len: 0,
            ts_language,
            stats: HighlightStats::default(),
            scope_category_cache: HashMap::new(),
        }
    }

    /// Get performance stats for testing and diagnostics.
    pub fn stats(&self) -> &HighlightStats {
        &self.stats
    }

    /// Reset performance counters.
    pub fn reset_stats(&mut self) {
        self.stats = HighlightStats::default();
    }

    /// Get the tree-sitter language (for indentation, semantic highlighting, etc.)
    pub fn language(&self) -> Option<&Language> {
        self.ts_language.as_ref()
    }

    /// Buffer-insert notification. Shifts span offsets in place and marks
    /// the cache dirty so the partial-update path runs on next render.
    pub fn notify_insert(&mut self, position: usize, length: usize) {
        self.checkpoint_markers.adjust_for_insert(position, length);
        self.dirty_from = Some(self.dirty_from.map_or(position, |d| d.min(position)));
        if let Some(cache) = &mut self.cache {
            for span in &mut cache.spans {
                if span.range.start >= position {
                    span.range.start += length;
                    span.range.end += length;
                } else if span.range.end > position {
                    span.range.end += length;
                }
            }
            if cache.range.end >= position {
                cache.range.end += length;
                if position < cache.range.end {
                    cache.tail_state = None;
                }
            }
        }
    }

    /// Buffer-delete notification. Mirror of `notify_insert`.
    pub fn notify_delete(&mut self, position: usize, length: usize) {
        self.checkpoint_markers.adjust_for_delete(position, length);
        self.dirty_from = Some(self.dirty_from.map_or(position, |d| d.min(position)));
        if let Some(cache) = &mut self.cache {
            let delete_end = position + length;
            cache.spans.retain_mut(|span| {
                if span.range.start >= delete_end {
                    span.range.start -= length;
                    span.range.end -= length;
                    true
                } else if span.range.end <= position {
                    true
                } else if span.range.start >= position && span.range.end <= delete_end {
                    false
                } else {
                    if span.range.start < position {
                        span.range.end = position.min(span.range.end);
                    } else {
                        span.range.start = position;
                        span.range.end = position + span.range.end.saturating_sub(delete_end);
                    }
                    span.range.start < span.range.end
                }
            });
            if cache.range.end > delete_end {
                cache.range.end -= length;
            } else if cache.range.end > position {
                cache.range.end = position;
            }
            if position < cache.range.end {
                cache.tail_state = None;
            }
        }
    }

    /// Create a checkpoint at `current_offset` carrying the supplied
    /// parse state, unless one already exists within half an interval
    /// (which would shadow it). Callers gate on
    /// `bytes_since_checkpoint >= CHECKPOINT_INTERVAL` to control
    /// spacing.
    fn maybe_create_checkpoint(
        &mut self,
        current_offset: usize,
        state: &syntect::parsing::ParseState,
        current_scopes: &syntect::parsing::ScopeStack,
    ) {
        let nearby = self.checkpoint_markers.query_range(
            current_offset.saturating_sub(CHECKPOINT_INTERVAL / 2),
            current_offset + CHECKPOINT_INTERVAL / 2,
        );
        if nearby.is_empty() {
            let marker_id = self.checkpoint_markers.create(current_offset, true);
            self.checkpoint_states
                .insert(marker_id, (state.clone(), current_scopes.clone()));
        }
    }

    /// Drive `state.parse_line(prepared.line_for_syntect)` and emit one
    /// span per category-carrying byte range via `on_span(start, end,
    /// category)`. Returns `false` when `parse_line` errored — caller
    /// should advance past the line and continue (state may have been
    /// mutated mid-parse but is left as-is, matching prior behaviour).
    ///
    /// Span emission is in two passes: the op iterator emits the
    /// segment between consecutive ops with the scope-stack-active
    /// category, and a trailing segment covers `[syntect_offset,
    /// line_content_len)` when the final op didn't reach end-of-line.
    fn parse_line_into_spans(
        &mut self,
        state: &mut syntect::parsing::ParseState,
        current_scopes: &mut syntect::parsing::ScopeStack,
        prepared: &PreparedLine,
        current_offset: usize,
        mut on_span: impl FnMut(usize, usize, HighlightCategory),
    ) -> bool {
        let ops = match state.parse_line(&prepared.line_for_syntect, &self.syntax_set) {
            Ok(ops) => ops,
            Err(_) => return false,
        };

        let line_content_len = prepared.line_content_len;
        let mut syntect_offset = 0;

        for (op_offset, op) in ops {
            let clamped_op_offset = op_offset.min(line_content_len);
            if clamped_op_offset > syntect_offset {
                if let Some(category) = self.scope_stack_to_category(current_scopes) {
                    on_span(
                        current_offset + syntect_offset,
                        current_offset + clamped_op_offset,
                        category,
                    );
                }
            }
            syntect_offset = clamped_op_offset;
            #[allow(clippy::let_underscore_must_use)]
            let _ = current_scopes.apply(&op);
        }

        if syntect_offset < line_content_len {
            if let Some(category) = self.scope_stack_to_category(current_scopes) {
                on_span(
                    current_offset + syntect_offset,
                    current_offset + line_content_len,
                    category,
                );
            }
        }
        true
    }

    /// Highlight the visible viewport. Path selection is documented in the
    /// module-level docs ("TextMate cache design").
    /// Test-only: inspect the cache commit point (range.end) and
    /// whether tail_state is populated. The cache must commit at a
    /// newline boundary — anything past that risks streaming
    /// forward-extension picking up where partial-line state poisoned
    /// the parser, see `test_partial_trailing_line_not_committed_to_cache`.
    #[cfg(test)]
    pub fn cache_commit_for_test(&self) -> (usize, bool) {
        match &self.cache {
            Some(c) => (c.range.end, c.tail_state.is_some()),
            None => (0, false),
        }
    }

    pub fn highlight_viewport(
        &mut self,
        buffer: &Buffer,
        viewport_start: usize,
        viewport_end: usize,
        theme: &Theme,
        context_bytes: usize,
    ) -> Vec<HighlightSpan> {
        let buf_len = buffer.len();
        let (desired_parse_start, parse_end) = if buf_len <= MAX_PARSE_BYTES {
            (0, buf_len)
        } else {
            let s = viewport_start.saturating_sub(context_bytes);
            let e = (viewport_end + context_bytes).min(buf_len);
            (s, e)
        };

        let dirty = self.dirty_from.take();
        let cache_covers_viewport = self.cache.as_ref().is_some_and(|c| {
            c.range.start <= desired_parse_start && c.range.end >= desired_parse_start
        });
        let exact_cache_hit = cache_covers_viewport
            && dirty.is_none()
            && self.last_buffer_len == buffer.len()
            && self
                .cache
                .as_ref()
                .is_some_and(|c| c.range.end >= parse_end);

        // Cache hit.
        if exact_cache_hit {
            self.stats.cache_hits += 1;
            return self.filter_cached_spans(viewport_start, viewport_end, theme);
        }

        // Forward extension.
        if dirty.is_none()
            && cache_covers_viewport
            && self.last_buffer_len == buffer.len()
            && self
                .cache
                .as_ref()
                .is_some_and(|c| c.range.end < parse_end && c.tail_state.is_some())
        {
            return self.extend_cache_forward(
                buffer,
                parse_end,
                viewport_start,
                viewport_end,
                theme,
            );
        }

        // Partial update.
        if cache_covers_viewport && dirty.is_some() {
            if let Some(dirty_pos) = dirty {
                if dirty_pos < parse_end {
                    if let Some(result) = self.try_partial_update(
                        buffer,
                        dirty_pos,
                        desired_parse_start,
                        parse_end,
                        viewport_start,
                        viewport_end,
                        theme,
                    ) {
                        return result;
                    }
                } else {
                    // Dirty region past viewport: cached spans are still valid.
                    self.dirty_from = Some(dirty_pos);
                    self.stats.cache_hits += 1;
                    return self.filter_cached_spans(viewport_start, viewport_end, theme);
                }
            }
        } else if let Some(d) = dirty {
            self.dirty_from = Some(d);
        }

        // Cold start / fallback.
        self.full_parse(
            buffer,
            desired_parse_start,
            parse_end,
            viewport_start,
            viewport_end,
            theme,
            context_bytes,
        )
    }

    /// Filter cached spans for the viewport and resolve colors.
    fn filter_cached_spans(
        &self,
        viewport_start: usize,
        viewport_end: usize,
        theme: &Theme,
    ) -> Vec<HighlightSpan> {
        let cache = self.cache.as_ref().unwrap();
        cache
            .spans
            .iter()
            .filter(|span| span.range.start < viewport_end && span.range.end > viewport_start)
            .map(|span| HighlightSpan {
                range: span.range.clone(),
                color: highlight_color(span.category, theme),
                bg: highlight_bg(span.category, theme),
                category: Some(span.category),
            })
            .collect()
    }

    /// Partial update path. Returns `Some` whenever an anchor was available,
    /// even on budget hit or EOF (see post-loop classification). `None` only
    /// when no checkpoint anchor reaches the dirty point.
    #[allow(clippy::too_many_arguments)]
    fn try_partial_update(
        &mut self,
        buffer: &Buffer,
        dirty_pos: usize,
        desired_parse_start: usize,
        parse_end: usize,
        viewport_start: usize,
        viewport_end: usize,
        theme: &Theme,
    ) -> Option<Vec<HighlightSpan>> {
        let syntax = &self.syntax_set.syntaxes()[self.syntax_index];

        // Find checkpoint before the dirty point (bounded search)
        let (actual_start, mut state, mut current_scopes) = {
            let search_start = dirty_pos.saturating_sub(MAX_PARSE_BYTES);
            let markers = self.checkpoint_markers.query_range(search_start, dirty_pos);
            let nearest = markers.into_iter().max_by_key(|(_, start, _)| *start);
            if let Some((id, cp_pos, _)) = nearest {
                if let Some((s, sc)) = self.checkpoint_states.get(&id) {
                    (cp_pos, s.clone(), sc.clone())
                } else {
                    return None; // orphan, fall back
                }
            } else if parse_end <= MAX_PARSE_BYTES {
                (
                    0,
                    syntect::parsing::ParseState::new(syntax),
                    syntect::parsing::ScopeStack::new(),
                )
            } else {
                return None; // large file, no nearby checkpoint, fall back
            }
        };

        // Get markers from dirty point forward for convergence checking
        let mut markers_ahead: Vec<(MarkerId, usize)> = self
            .checkpoint_markers
            .query_range(dirty_pos, parse_end)
            .into_iter()
            .map(|(id, start, _)| (id, start))
            .collect();
        markers_ahead.sort_by_key(|(_, pos)| *pos);
        let mut marker_idx = 0;

        // Parse from actual_start to parse_end, looking for convergence
        let content_end = parse_end.min(buffer.len());
        if actual_start >= content_end {
            return None;
        }
        let content = buffer.slice_bytes(actual_start..content_end);
        let content_str = match std::str::from_utf8(&content) {
            Ok(s) => s,
            Err(_) => return None,
        };

        let mut new_spans = Vec::new();
        let content_bytes = content_str.as_bytes();
        let mut pos = 0;
        let mut current_offset = actual_start;
        let mut converged_at: Option<usize> = None;
        let mut budget_hit_at: Option<usize> = None;
        let mut bytes_since_checkpoint: usize = 0;

        while pos < content_bytes.len() {
            // Create checkpoints in new territory
            if bytes_since_checkpoint >= CHECKPOINT_INTERVAL {
                self.maybe_create_checkpoint(current_offset, &state, &current_scopes);
                bytes_since_checkpoint = 0;
            }

            let (line_end, line_byte_len, prepared) = prepare_line_at(content_bytes, pos);
            // Collect spans for the dirty region
            let collect_spans =
                current_offset + line_byte_len > desired_parse_start.max(actual_start);
            if let Some(prepared) = prepared {
                let _ = self.parse_line_into_spans(
                    &mut state,
                    &mut current_scopes,
                    &prepared,
                    current_offset,
                    |byte_start, byte_end, category| {
                        if !collect_spans {
                            return;
                        }
                        let clamped_start = byte_start.max(actual_start);
                        if clamped_start < byte_end {
                            new_spans.push(CachedSpan {
                                range: clamped_start..byte_end,
                                category,
                            });
                        }
                    },
                );
            }

            pos = line_end;
            current_offset += line_byte_len;
            bytes_since_checkpoint += line_byte_len;

            // Check convergence at checkpoint markers
            while marker_idx < markers_ahead.len() && markers_ahead[marker_idx].1 <= current_offset
            {
                let (marker_id, _) = markers_ahead[marker_idx];
                marker_idx += 1;
                if let Some(stored) = self.checkpoint_states.get(&marker_id) {
                    if *stored == (state.clone(), current_scopes.clone()) {
                        self.stats.convergences += 1;
                        converged_at = Some(current_offset);
                        break;
                    }
                }
                self.stats.checkpoints_updated += 1;
                self.checkpoint_states
                    .insert(marker_id, (state.clone(), current_scopes.clone()));
            }

            if converged_at.is_some() {
                break;
            }

            // Bound work per pass: pathological edits (e.g. unclosed `/*`
            // re-scoping the rest of the file) can never converge. Stop here
            // and resume from `current_offset` on the next render.
            if current_offset.saturating_sub(dirty_pos) >= CONVERGENCE_BUDGET {
                budget_hit_at = Some(current_offset);
                break;
            }
        }

        self.stats.bytes_parsed += current_offset.saturating_sub(actual_start);

        // Splice classification: converged → clear dirty; budget hit → keep
        // dirty for next pass; EOF → clear dirty.
        let (splice_end, dirty_after) = if let Some(c) = converged_at {
            (c, None)
        } else if let Some(b) = budget_hit_at {
            (b, Some(b))
        } else {
            (current_offset, None)
        };

        self.stats.cache_misses += 1; // partial update counts as a miss

        Self::merge_adjacent_spans(&mut new_spans);

        if let Some(cache) = &mut self.cache {
            let splice_start = actual_start;
            cache
                .spans
                .retain(|span| span.range.end <= splice_start || span.range.start >= splice_end);
            cache.spans.extend(new_spans);
            cache.spans.sort_by_key(|s| s.range.start);
            Self::merge_adjacent_spans(&mut cache.spans);
            if splice_end > cache.range.end {
                cache.range.end = splice_end;
            }
            cache.tail_state = None;
        }

        self.last_buffer_len = buffer.len();
        self.dirty_from = dirty_after;

        Some(self.filter_cached_spans(viewport_start, viewport_end, theme))
    }

    /// Forward extension path (see module docs). Caller checks the cache
    /// exists, has a `tail_state`, has no dirty edits, and `cache.range.end
    /// < parse_end`.
    fn extend_cache_forward(
        &mut self,
        buffer: &Buffer,
        parse_end: usize,
        viewport_start: usize,
        viewport_end: usize,
        theme: &Theme,
    ) -> Vec<HighlightSpan> {
        self.stats.cache_misses += 1;
        let buf_len = buffer.len();
        let parse_end = parse_end.min(buf_len);

        let (extension_start, mut state, mut current_scopes) = {
            let cache = self
                .cache
                .as_ref()
                .expect("extend_cache_forward: cache must exist");
            let (s, sc) = cache
                .tail_state
                .as_ref()
                .expect("extend_cache_forward: tail_state must exist")
                .clone();
            (cache.range.end, s, sc)
        };

        if parse_end <= extension_start {
            return self.filter_cached_spans(viewport_start, viewport_end, theme);
        }

        let content = buffer.slice_bytes(extension_start..parse_end);
        let content_str = match std::str::from_utf8(&content) {
            Ok(s) => s,
            Err(_) => return self.filter_cached_spans(viewport_start, viewport_end, theme),
        };

        let mut new_spans = Vec::new();
        let content_bytes = content_str.as_bytes();
        let mut pos = 0;
        let mut current_offset = extension_start;
        let mut bytes_since_checkpoint: usize = 0;
        // Snapshot of the last newline-aligned cache commit point. We never
        // commit parse state for a partial trailing line: with a streaming
        // grammar like syntect's `Diff` (line-anchored `^\+.*` etc.) the
        // state at end-of-input has already popped `markup.inserted`, so
        // resuming from there parses the rest of the same line in
        // `source.diff` with no scope — bytes of the line streamed in
        // later get default editor bg, producing the dark-bar artifact
        // inside `+` lines. Re-parsing the trailing partial line on every
        // refresh costs at most one extra `parse_line` and is correct.
        let mut safe_offset = extension_start;
        let mut safe_state = state.clone();
        let mut safe_scopes = current_scopes.clone();

        while pos < content_bytes.len() {
            if bytes_since_checkpoint >= CHECKPOINT_INTERVAL {
                self.maybe_create_checkpoint(current_offset, &state, &current_scopes);
                bytes_since_checkpoint = 0;
            }

            let (line_end, line_byte_len, prepared) = prepare_line_at(content_bytes, pos);
            let mut newline_terminated = false;
            if let Some(prepared) = prepared {
                let parse_ok = self.parse_line_into_spans(
                    &mut state,
                    &mut current_scopes,
                    &prepared,
                    current_offset,
                    |byte_start, byte_end, category| {
                        new_spans.push(CachedSpan {
                            range: byte_start..byte_end,
                            category,
                        });
                    },
                );
                if parse_ok {
                    newline_terminated = prepared.ends_with_newline;
                }
            }

            pos = line_end;
            current_offset += line_byte_len;
            bytes_since_checkpoint += line_byte_len;

            if newline_terminated {
                safe_offset = current_offset;
                safe_state = state.clone();
                safe_scopes = current_scopes.clone();
            }
        }

        self.stats.bytes_parsed += parse_end - extension_start;

        Self::merge_adjacent_spans(&mut new_spans);

        // Split spans into safe (fully before the trailing partial line,
        // cacheable) and unsafe (overlap the partial line, render-only).
        // Unsafe spans are returned in this pass so the partial line is
        // still highlighted, but won't be cached — they'll be recomputed
        // on the next refresh once more bytes (and a newline) stream in.
        let (safe_spans, unsafe_spans): (Vec<_>, Vec<_>) = new_spans
            .into_iter()
            .partition(|s| s.range.end <= safe_offset);

        let cache = self
            .cache
            .as_mut()
            .expect("extend_cache_forward: cache must still exist");
        cache.spans.extend(safe_spans);
        Self::merge_adjacent_spans(&mut cache.spans);
        cache.range.end = safe_offset;
        cache.tail_state = Some((safe_state, safe_scopes));
        self.last_buffer_len = buf_len;

        let mut result = self.filter_cached_spans(viewport_start, viewport_end, theme);
        result.extend(
            unsafe_spans
                .into_iter()
                .filter(|s| s.range.start < viewport_end && s.range.end > viewport_start)
                .map(|s| HighlightSpan {
                    range: s.range,
                    color: highlight_color(s.category, theme),
                    bg: highlight_bg(s.category, theme),
                    category: Some(s.category),
                }),
        );
        result
    }

    /// Full re-parse from desired_parse_start to parse_end. Used on cold start
    /// or when partial update fails (no convergence).
    #[allow(clippy::too_many_arguments)]
    fn full_parse(
        &mut self,
        buffer: &Buffer,
        desired_parse_start: usize,
        parse_end: usize,
        viewport_start: usize,
        viewport_end: usize,
        theme: &Theme,
        _context_bytes: usize,
    ) -> Vec<HighlightSpan> {
        self.stats.cache_misses += 1;
        self.dirty_from = None; // consumed

        if parse_end <= desired_parse_start {
            return Vec::new();
        }

        let syntax = &self.syntax_set.syntaxes()[self.syntax_index];
        let (actual_start, mut state, mut current_scopes, create_checkpoints) =
            self.find_parse_resume_point(desired_parse_start, parse_end, syntax);

        let content = buffer.slice_bytes(actual_start..parse_end);
        let content_str = match std::str::from_utf8(&content) {
            Ok(s) => s,
            Err(_) => return Vec::new(),
        };

        let mut spans = Vec::new();
        let content_bytes = content_str.as_bytes();
        let mut pos = 0;
        let mut current_offset = actual_start;
        let mut bytes_since_checkpoint: usize = 0;
        // See `extend_cache_forward` for rationale: never commit cache
        // state past the last newline. `safe_offset` ends up == parse_end
        // for buffers that end on `\n` (no behaviour change), and at the
        // start of the trailing partial line otherwise so the next
        // refresh re-parses it from scratch.
        let mut safe_offset = actual_start;
        let mut safe_state = state.clone();
        let mut safe_scopes = current_scopes.clone();

        while pos < content_bytes.len() {
            if create_checkpoints && bytes_since_checkpoint >= CHECKPOINT_INTERVAL {
                self.maybe_create_checkpoint(current_offset, &state, &current_scopes);
                bytes_since_checkpoint = 0;
            }

            let (line_end, line_byte_len, prepared) = prepare_line_at(content_bytes, pos);
            // Skip span collection for lines that ended before the viewport's
            // desired_parse_start — we still need to drive `parse_line` for
            // state continuity, but their spans wouldn't be returned anyway.
            let collect_spans = current_offset + line_byte_len > desired_parse_start;
            let mut newline_terminated = false;
            if let Some(prepared) = prepared {
                let parse_ok = self.parse_line_into_spans(
                    &mut state,
                    &mut current_scopes,
                    &prepared,
                    current_offset,
                    |byte_start, byte_end, category| {
                        if !collect_spans {
                            return;
                        }
                        let clamped_start = byte_start.max(desired_parse_start);
                        if clamped_start < byte_end {
                            spans.push(CachedSpan {
                                range: clamped_start..byte_end,
                                category,
                            });
                        }
                    },
                );
                if parse_ok {
                    newline_terminated = prepared.ends_with_newline;
                }
            }

            pos = line_end;
            current_offset += line_byte_len;
            bytes_since_checkpoint += line_byte_len;

            if newline_terminated {
                safe_offset = current_offset;
                safe_state = state.clone();
                safe_scopes = current_scopes.clone();
            }

            // Update checkpoint states as we pass them. Done after the
            // line is parsed (state now reflects end-of-line) so a
            // checkpoint placed at the line's start position carries
            // the state at that position, ready to feed the next line.
            let markers_here: Vec<(MarkerId, usize)> = self
                .checkpoint_markers
                .query_range(current_offset.saturating_sub(line_byte_len), current_offset)
                .into_iter()
                .map(|(id, start, _)| (id, start))
                .collect();
            for (marker_id, _) in markers_here {
                self.checkpoint_states
                    .insert(marker_id, (state.clone(), current_scopes.clone()));
            }
        }

        self.stats.bytes_parsed += parse_end.saturating_sub(actual_start);

        Self::merge_adjacent_spans(&mut spans);

        // Cache only the prefix up to the last newline. Spans straddling
        // or past the trailing partial line are returned for THIS render
        // pass (so the partial line is highlighted now), but excluded
        // from the cache — the next refresh re-parses them from
        // `safe_state` once more bytes have streamed in.
        let cache_range_end = safe_offset.max(desired_parse_start);
        let cached_spans: Vec<CachedSpan> = spans
            .iter()
            .filter(|s| s.range.end <= cache_range_end)
            .cloned()
            .collect();

        self.cache = Some(TextMateCache {
            range: desired_parse_start..cache_range_end,
            spans: cached_spans,
            tail_state: Some((safe_state, safe_scopes)),
        });
        self.last_buffer_len = buffer.len();

        spans
            .into_iter()
            .filter(|span| span.range.start < viewport_end && span.range.end > viewport_start)
            .map(|span| {
                let cat = span.category;
                HighlightSpan {
                    range: span.range,
                    color: highlight_color(cat, theme),
                    bg: highlight_bg(cat, theme),
                    category: Some(cat),
                }
            })
            .collect()
    }

    /// Find the best point to resume parsing from for the viewport.
    fn find_parse_resume_point(
        &self,
        desired_start: usize,
        parse_end: usize,
        syntax: &syntect::parsing::SyntaxReference,
    ) -> (
        usize,
        syntect::parsing::ParseState,
        syntect::parsing::ScopeStack,
        bool,
    ) {
        use syntect::parsing::{ParseState, ScopeStack};

        // Look for a checkpoint near the desired start. For large files, only
        // consider checkpoints that are within MAX_PARSE_BYTES of desired_start
        // to avoid parsing hundreds of MB from a distant checkpoint.
        let search_start = desired_start.saturating_sub(MAX_PARSE_BYTES);
        let markers = self
            .checkpoint_markers
            .query_range(search_start, desired_start + 1);
        let nearest = markers.into_iter().max_by_key(|(_, start, _)| *start);

        if let Some((id, cp_pos, _)) = nearest {
            if let Some((s, sc)) = self.checkpoint_states.get(&id) {
                return (cp_pos, s.clone(), sc.clone(), true);
            }
        }

        if parse_end <= MAX_PARSE_BYTES {
            // File is small enough to parse from byte 0
            (0, ParseState::new(syntax), ScopeStack::new(), true)
        } else {
            // Large file, no nearby checkpoint — start fresh from desired_start.
            // Still create checkpoints so future visits to this region can resume.
            (
                desired_start,
                ParseState::new(syntax),
                ScopeStack::new(),
                true,
            )
        }
    }

    /// Map scope stack to highlight category, memoising per-scope lookups.
    /// `scope.build_string()` is the costly step; the cache hides it after
    /// each scope atom has been seen once.
    fn scope_stack_to_category(
        &mut self,
        scopes: &syntect::parsing::ScopeStack,
    ) -> Option<HighlightCategory> {
        for scope in scopes.as_slice().iter().rev() {
            let cat = match self.scope_category_cache.get(scope) {
                Some(c) => *c,
                None => {
                    let computed = scope_to_category(&scope.build_string());
                    self.scope_category_cache.insert(*scope, computed);
                    computed
                }
            };
            if let Some(c) = cat {
                return Some(c);
            }
        }
        None
    }

    /// Merge adjacent spans with same category
    fn merge_adjacent_spans(spans: &mut Vec<CachedSpan>) {
        if spans.len() < 2 {
            return;
        }

        let mut write_idx = 0;
        for read_idx in 1..spans.len() {
            if spans[write_idx].category == spans[read_idx].category
                && spans[write_idx].range.end == spans[read_idx].range.start
            {
                spans[write_idx].range.end = spans[read_idx].range.end;
            } else {
                write_idx += 1;
                if write_idx != read_idx {
                    spans[write_idx] = spans[read_idx].clone();
                }
            }
        }
        spans.truncate(write_idx + 1);
    }

    /// Invalidate span cache for an edited range.
    /// Checkpoint positions are handled by notify_insert/notify_delete.
    /// The span cache is NOT cleared here — it will be patched (partial update)
    /// during the next highlight_viewport call using convergence. Only dirty_from
    /// (set by notify_insert/notify_delete) controls re-parsing scope.
    pub fn invalidate_range(&mut self, _edit_range: Range<usize>) {
        // Intentionally does NOT clear self.cache.
        // The cache will be partially updated in highlight_viewport when
        // dirty_from is set. This avoids full re-parses for small edits.
    }

    /// Invalidate all cache and checkpoints (file reload, language change, etc.)
    pub fn invalidate_all(&mut self) {
        self.cache = None;
        let ids: Vec<MarkerId> = self.checkpoint_states.keys().copied().collect();
        for id in ids {
            self.checkpoint_markers.delete(id);
        }
        self.checkpoint_states.clear();
        self.dirty_from = None;
    }

    /// Get the highlight category at a byte position from the cache.
    ///
    /// Returns the category if the position falls within a cached highlight span.
    /// The position must be within the last highlighted viewport range for a result.
    pub fn category_at_position(&self, position: usize) -> Option<HighlightCategory> {
        let cache = self.cache.as_ref()?;
        cache
            .spans
            .iter()
            .find(|span| span.range.start <= position && position < span.range.end)
            .map(|span| span.category)
    }

    /// Get syntax name
    pub fn syntax_name(&self) -> &str {
        &self.syntax_set.syntaxes()[self.syntax_index].name
    }
}

impl HighlightEngine {
    /// Build a highlighting engine for a catalog entry.
    ///
    /// Single chokepoint for the "prefer syntect, fall back to tree-sitter"
    /// logic. Callers that start from a path or a syntax name should resolve
    /// the entry through `GrammarRegistry::find_by_path` / `find_by_name` and
    /// then call this.
    pub fn from_entry(
        entry: &crate::primitives::grammar::GrammarEntry,
        registry: &GrammarRegistry,
    ) -> Self {
        let syntax_set = registry.syntax_set_arc();
        if let Some(index) = entry.engines.syntect {
            return Self::TextMate(Box::new(TextMateEngine::with_language(
                syntax_set,
                index,
                entry.engines.tree_sitter,
            )));
        }
        if let Some(lang) = entry.engines.tree_sitter {
            if let Ok(highlighter) = Highlighter::new(lang) {
                return Self::TreeSitter(Box::new(highlighter));
            }
        }
        Self::None
    }

    /// Create a highlighting engine for a file.
    ///
    /// Thin wrapper around `from_entry` that resolves the path via the catalog.
    /// User-config-declared filename/extension mappings are honoured as long as
    /// `GrammarRegistry::apply_language_config` has been called on the registry.
    /// `first_line` is used for shebang / first-line regex fallback — pass
    /// `None` when no content is available.
    pub fn for_file(path: &Path, first_line: Option<&str>, registry: &GrammarRegistry) -> Self {
        if let Some(entry) = registry.find_by_path(path, first_line) {
            return Self::from_entry(entry, registry);
        }
        Self::None
    }

    /// Create a highlighting engine for a syntax by name.
    ///
    /// Thin wrapper around `from_entry` that performs the lookup via
    /// `find_by_name`. The catalog entry already knows which tree-sitter
    /// `Language` (if any) serves it, so no separate hint is needed.
    pub fn for_syntax_name(name: &str, registry: &GrammarRegistry) -> Self {
        if let Some(entry) = registry.find_by_name(name) {
            return Self::from_entry(entry, registry);
        }
        Self::None
    }

    /// Highlight the visible viewport
    ///
    /// `context_bytes` controls how far before/after the viewport to parse for accurate
    /// highlighting of multi-line constructs (strings, comments, nested blocks).
    pub fn highlight_viewport(
        &mut self,
        buffer: &Buffer,
        viewport_start: usize,
        viewport_end: usize,
        theme: &Theme,
        context_bytes: usize,
    ) -> Vec<HighlightSpan> {
        match self {
            Self::TreeSitter(h) => {
                h.highlight_viewport(buffer, viewport_start, viewport_end, theme, context_bytes)
            }
            Self::TextMate(h) => {
                h.highlight_viewport(buffer, viewport_start, viewport_end, theme, context_bytes)
            }
            Self::None => Vec::new(),
        }
    }

    /// Notify the highlighting engine of a buffer insert (for checkpoint position tracking).
    pub fn notify_insert(&mut self, position: usize, length: usize) {
        if let Self::TextMate(h) = self {
            h.notify_insert(position, length);
        }
    }

    /// Notify the highlighting engine of a buffer delete (for checkpoint position tracking).
    pub fn notify_delete(&mut self, position: usize, length: usize) {
        if let Self::TextMate(h) = self {
            h.notify_delete(position, length);
        }
    }

    /// Invalidate cache for an edited range
    pub fn invalidate_range(&mut self, edit_range: Range<usize>) {
        match self {
            Self::TreeSitter(h) => h.invalidate_range(edit_range),
            Self::TextMate(h) => h.invalidate_range(edit_range),
            Self::None => {}
        }
    }

    /// Invalidate entire cache
    pub fn invalidate_all(&mut self) {
        match self {
            Self::TreeSitter(h) => h.invalidate_all(),
            Self::TextMate(h) => h.invalidate_all(),
            Self::None => {}
        }
    }

    /// Track a sequence of bulk edits in the cache.
    ///
    /// Each edit is `(pos, del_len, ins_len)`. The slice must be sorted in
    /// descending position order — the same order `apply_bulk_edits` uses to
    /// mutate the buffer — so positions remain valid as the buffer changes.
    ///
    /// This mirrors the `notify_*` + `invalidate_range` pattern used by
    /// single-edit paths. It preserves the TextMate engine's checkpoints and
    /// dirty-from anchor (so the next render uses the partial-update path
    /// rather than a cold reparse from byte zero) and drops the tree-sitter
    /// viewport cache only when an edit overlaps it.
    pub fn notify_edits(&mut self, edits: &[(usize, usize, usize)]) {
        for &(pos, del_len, ins_len) in edits {
            if del_len > 0 {
                self.notify_delete(pos, del_len);
            }
            if ins_len > 0 {
                self.notify_insert(pos, ins_len);
            }
            let edit_end = pos + del_len.max(ins_len);
            self.invalidate_range(pos..edit_end);
        }
    }

    /// Check if this engine has highlighting available
    pub fn has_highlighting(&self) -> bool {
        !matches!(self, Self::None)
    }

    /// Get a description of the active backend
    pub fn backend_name(&self) -> &str {
        match self {
            Self::TreeSitter(_) => "tree-sitter",
            Self::TextMate(_) => "textmate",
            Self::None => "none",
        }
    }

    /// Get performance stats (TextMate engine only).
    pub fn highlight_stats(&self) -> Option<&HighlightStats> {
        if let Self::TextMate(h) = self {
            Some(h.stats())
        } else {
            None
        }
    }

    /// Reset performance counters.
    pub fn reset_highlight_stats(&mut self) {
        if let Self::TextMate(h) = self {
            h.reset_stats();
        }
    }

    /// Get the language/syntax name if available
    pub fn syntax_name(&self) -> Option<&str> {
        match self {
            Self::TreeSitter(_) => None, // Tree-sitter doesn't expose name easily
            Self::TextMate(h) => Some(h.syntax_name()),
            Self::None => None,
        }
    }

    /// Get the highlight category at a byte position from the cache.
    ///
    /// Returns the category if the position falls within a cached highlight span.
    /// Useful for detecting whether the cursor is inside a string, comment, etc.
    pub fn category_at_position(&self, position: usize) -> Option<HighlightCategory> {
        match self {
            Self::TreeSitter(h) => h.category_at_position(position),
            Self::TextMate(h) => h.category_at_position(position),
            Self::None => None,
        }
    }

    /// Get the tree-sitter Language for non-highlighting features
    /// Returns the language even when using TextMate for highlighting
    pub fn language(&self) -> Option<&Language> {
        match self {
            Self::TreeSitter(h) => Some(h.language()),
            Self::TextMate(h) => h.language(),
            Self::None => None,
        }
    }
}

/// Highlight a code string using syntect (for markdown code blocks, hover popups, etc.)
/// Returns spans with byte ranges relative to the input string.
///
/// This uses TextMate grammars via syntect which provides broader language coverage
/// than tree-sitter (~150+ languages vs ~17).
pub fn highlight_string(
    code: &str,
    lang_hint: &str,
    registry: &GrammarRegistry,
    theme: &Theme,
) -> Vec<HighlightSpan> {
    use syntect::parsing::{ParseState, ScopeStack};

    // Find syntax by language token (handles aliases like "py" -> Python)
    let syntax = match registry.syntax_set().find_syntax_by_token(lang_hint) {
        Some(s) => s,
        None => return Vec::new(),
    };

    let syntax_set = registry.syntax_set();
    let mut state = ParseState::new(syntax);
    let mut spans = Vec::new();
    let mut current_scopes = ScopeStack::new();
    let mut current_offset = 0;

    // Parse line by line
    for line in code.split_inclusive('\n') {
        let line_start = current_offset;
        let line_len = line.len();

        // Remove trailing newline for syntect, then add it back
        let line_content = line.trim_end_matches(&['\r', '\n'][..]);
        let line_for_syntect = if line.ends_with('\n') {
            format!("{}\n", line_content)
        } else {
            line_content.to_string()
        };

        let ops = match state.parse_line(&line_for_syntect, syntax_set) {
            Ok(ops) => ops,
            Err(_) => {
                current_offset += line_len;
                continue;
            }
        };

        let mut syntect_offset = 0;
        let line_content_len = line_content.len();

        for (op_offset, op) in ops {
            let clamped_op_offset = op_offset.min(line_content_len);
            if clamped_op_offset > syntect_offset {
                if let Some(category) = scope_stack_to_category(&current_scopes) {
                    let byte_start = line_start + syntect_offset;
                    let byte_end = line_start + clamped_op_offset;
                    if byte_start < byte_end {
                        spans.push(HighlightSpan {
                            range: byte_start..byte_end,
                            color: highlight_color(category, theme),
                            bg: highlight_bg(category, theme),
                            category: Some(category),
                        });
                    }
                }
            }
            syntect_offset = clamped_op_offset;
            // Scope stack errors are non-fatal for highlighting
            #[allow(clippy::let_underscore_must_use)]
            let _ = current_scopes.apply(&op);
        }

        // Handle remaining text on line
        if syntect_offset < line_content_len {
            if let Some(category) = scope_stack_to_category(&current_scopes) {
                let byte_start = line_start + syntect_offset;
                let byte_end = line_start + line_content_len;
                if byte_start < byte_end {
                    spans.push(HighlightSpan {
                        range: byte_start..byte_end,
                        color: highlight_color(category, theme),
                        bg: highlight_bg(category, theme),
                        category: Some(category),
                    });
                }
            }
        }

        current_offset += line_len;
    }

    // Merge adjacent spans with same color
    merge_adjacent_highlight_spans(&mut spans);

    spans
}

/// Map scope stack to highlight category (for highlight_string)
fn scope_stack_to_category(scopes: &syntect::parsing::ScopeStack) -> Option<HighlightCategory> {
    for scope in scopes.as_slice().iter().rev() {
        let scope_str = scope.build_string();
        if let Some(cat) = scope_to_category(&scope_str) {
            return Some(cat);
        }
    }
    None
}

/// Merge adjacent spans with same color
fn merge_adjacent_highlight_spans(spans: &mut Vec<HighlightSpan>) {
    if spans.len() < 2 {
        return;
    }

    let mut write_idx = 0;
    for read_idx in 1..spans.len() {
        if spans[write_idx].color == spans[read_idx].color
            && spans[write_idx].range.end == spans[read_idx].range.start
        {
            spans[write_idx].range.end = spans[read_idx].range.end;
        } else {
            write_idx += 1;
            if write_idx != read_idx {
                spans[write_idx] = spans[read_idx].clone();
            }
        }
    }
    spans.truncate(write_idx + 1);
}

#[cfg(test)]
mod tests {
    use crate::model::filesystem::StdFileSystem;
    use std::sync::Arc;

    fn test_fs() -> Arc<dyn crate::model::filesystem::FileSystem + Send + Sync> {
        Arc::new(StdFileSystem)
    }
    use super::*;
    use crate::view::theme;

    #[test]
    fn test_highlight_engine_default() {
        let engine = HighlightEngine::default();
        assert!(!engine.has_highlighting());
        assert_eq!(engine.backend_name(), "none");
    }

    #[test]
    fn test_textmate_backend_selection() {
        let registry =
            GrammarRegistry::load(&crate::primitives::grammar::LocalGrammarLoader::embedded_only());

        // Languages with TextMate grammars use TextMate for highlighting
        let engine = HighlightEngine::for_file(Path::new("test.rs"), None, &registry);
        assert_eq!(engine.backend_name(), "textmate");
        // Tree-sitter language should still be detected for other features
        assert!(engine.language().is_some());

        let engine = HighlightEngine::for_file(Path::new("test.py"), None, &registry);
        assert_eq!(engine.backend_name(), "textmate");
        assert!(engine.language().is_some());

        // JavaScript is routed to tree-sitter (issue #899: syntect's JS
        // grammar bleeds template-literal string state past the closing
        // backtick).
        let engine = HighlightEngine::for_file(Path::new("test.js"), None, &registry);
        assert_eq!(engine.backend_name(), "tree-sitter");
        assert!(engine.language().is_some());

        // TypeScript falls back to tree-sitter (syntect doesn't include TS by default)
        let engine = HighlightEngine::for_file(Path::new("test.ts"), None, &registry);
        assert_eq!(engine.backend_name(), "tree-sitter");
        assert!(engine.language().is_some());

        let engine = HighlightEngine::for_file(Path::new("test.tsx"), None, &registry);
        assert_eq!(engine.backend_name(), "tree-sitter");
        assert!(engine.language().is_some());
    }

    #[test]
    fn test_tree_sitter_direct() {
        // Verify tree-sitter highlighter can be created directly for Rust
        let highlighter = Highlighter::new(Language::Rust);
        assert!(highlighter.is_ok());
    }

    #[test]
    fn test_unknown_extension() {
        let registry =
            GrammarRegistry::load(&crate::primitives::grammar::LocalGrammarLoader::embedded_only());

        // Unknown extension
        let engine = HighlightEngine::for_file(Path::new("test.unknown_xyz_123"), None, &registry);
        // Might be none or might find something via syntect
        // Just verify it doesn't panic
        let _ = engine.backend_name();
    }

    #[test]
    fn test_highlight_viewport_empty_buffer_no_panic() {
        // Regression test: calling highlight_viewport with an empty buffer
        // and non-zero viewport range previously caused subtraction overflow panic.
        //
        // The bug occurred when:
        // - buffer is empty (len = 0)
        // - viewport_start > context_bytes (so parse_start > 0 after saturating_sub)
        // - parse_end = min(viewport_end + context_bytes, buffer.len()) = 0
        // - parse_end - parse_start would underflow (0 - positive = overflow)
        let registry =
            GrammarRegistry::load(&crate::primitives::grammar::LocalGrammarLoader::embedded_only());

        let mut engine = HighlightEngine::for_file(Path::new("test.rs"), None, &registry);

        // Create empty buffer
        let buffer = Buffer::from_str("", 0, test_fs());
        let theme = Theme::load_builtin(theme::THEME_LIGHT).unwrap();

        // Test the specific case that triggered the overflow:
        // viewport_start=100, context_bytes=10 => parse_start=90, parse_end=0
        // 0 - 90 = overflow!
        if let HighlightEngine::TextMate(ref mut tm) = engine {
            // Small context_bytes so parse_start remains > 0
            let spans = tm.highlight_viewport(&buffer, 100, 200, &theme, 10);
            assert!(spans.is_empty());
        }
    }

    /// Test that TextMateEngine produces correct byte offsets for CRLF content.
    /// This is a regression test for a bug where using str::lines() caused 1-byte
    /// offset drift per line because it strips line terminators.
    #[test]
    fn test_textmate_engine_crlf_byte_offsets() {
        let registry =
            GrammarRegistry::load(&crate::primitives::grammar::LocalGrammarLoader::embedded_only());

        let mut engine = HighlightEngine::for_file(Path::new("test.java"), None, &registry);

        // Create CRLF content with keywords on each line
        // Each "public" keyword should be highlighted at byte positions:
        // Line 1: "public" at bytes 0-5
        // Line 2: "public" at bytes 8-13 (after "public\r\n" = 8 bytes)
        // Line 3: "public" at bytes 16-21 (after two "public\r\n" = 16 bytes)
        let content = b"public\r\npublic\r\npublic\r\n";
        let buffer = Buffer::from_bytes(content.to_vec(), test_fs());
        let theme = Theme::load_builtin(theme::THEME_LIGHT).unwrap();

        if let HighlightEngine::TextMate(ref mut tm) = engine {
            // Highlight the entire content
            let spans = tm.highlight_viewport(&buffer, 0, content.len(), &theme, 0);

            // Find spans that cover keyword positions
            // The keyword "public" should have spans at these byte ranges:
            // Line 1: 0..6
            // Line 2: 8..14 (NOT 7..13 which would be the buggy offset)
            // Line 3: 16..22 (NOT 14..20 which would be the buggy offset)

            eprintln!(
                "Spans: {:?}",
                spans.iter().map(|s| &s.range).collect::<Vec<_>>()
            );

            // Check that we have spans covering the correct positions
            let has_span_at = |start: usize, end: usize| -> bool {
                spans
                    .iter()
                    .any(|s| s.range.start <= start && s.range.end >= end)
            };

            // Line 1: "public" at bytes 0-6
            assert!(
                has_span_at(0, 6),
                "Should have span covering bytes 0-6 (line 1 'public'). Spans: {:?}",
                spans.iter().map(|s| &s.range).collect::<Vec<_>>()
            );

            // Line 2: "public" at bytes 8-14 (after "public\r\n")
            // If buggy, would be at 7-13
            assert!(
                has_span_at(8, 14),
                "Should have span covering bytes 8-14 (line 2 'public'). \
                 If this fails, CRLF offset drift is occurring. Spans: {:?}",
                spans.iter().map(|s| &s.range).collect::<Vec<_>>()
            );

            // Line 3: "public" at bytes 16-22 (after two "public\r\n")
            // If buggy, would be at 14-20
            assert!(
                has_span_at(16, 22),
                "Should have span covering bytes 16-22 (line 3 'public'). \
                 If this fails, CRLF offset drift is occurring. Spans: {:?}",
                spans.iter().map(|s| &s.range).collect::<Vec<_>>()
            );
        } else {
            panic!("Expected TextMate engine for .java file");
        }
    }

    /// When a buffer is parsed with no trailing newline (the streaming
    /// case for `git show` output between writes), the engine must not
    /// commit cache tail state at the end of the partial trailing line.
    /// With syntect's `Diff` grammar (line-anchored `^\+.*` etc.), the
    /// state at end-of-input has popped `markup.inserted`, so any
    /// follow-up parse from there would see the rest of the line as a
    /// new line in `source.diff` and emit no scope — losing the bg
    /// inside otherwise-green `+` lines.
    ///
    /// This test pins the boundary the cache commits at: after parsing
    /// a buffer ending mid-line, `cache.range.end` must be the last
    /// newline (or `desired_parse_start` if no newline was seen), not
    /// the end of the partial line.
    #[test]
    fn test_partial_trailing_line_not_committed_to_cache() {
        let registry =
            GrammarRegistry::load(&crate::primitives::grammar::LocalGrammarLoader::embedded_only());
        let mut engine = HighlightEngine::for_file(Path::new("commit.diff"), None, &registry);
        let theme = Theme::load_builtin(theme::THEME_DARK).unwrap();

        // A complete `+` line followed by a partial `+` line (no \n).
        let content = "+complete\n+partial";
        let buffer = Buffer::from_str(content, 0, test_fs());

        if let HighlightEngine::TextMate(ref mut tm) = engine {
            let _ = tm.highlight_viewport(&buffer, 0, content.len(), &theme, 0);
            let (cache_end, has_tail) = tm.cache_commit_for_test();
            assert_eq!(
                cache_end,
                "+complete\n".len(),
                "cache should commit at the last newline, not into the partial \
                 trailing line — committing past the newline causes streaming \
                 forward-extension to parse the line's continuation in the wrong \
                 grammar context, losing the diff bg."
            );
            assert!(has_tail, "tail state should be saved at the safe boundary");
        }
    }

    /// Reproduce: artifacts inside `+` lines whose content contains
    /// JS template literals — `\`...\`` with `${}` interpolation.
    /// The whole `+` line should be one contiguous Inserted span
    /// carrying `theme.diff_add_bg`, with no bg-less holes mid-line.
    #[test]
    fn test_diff_inserted_line_is_fully_covered() {
        let registry =
            GrammarRegistry::load(&crate::primitives::grammar::LocalGrammarLoader::embedded_only());
        let mut engine = HighlightEngine::for_file(Path::new("commit.diff"), None, &registry);
        let theme = Theme::load_builtin(theme::THEME_DARK).unwrap();

        let content =
            "diff --git a/file.ts b/file.ts\n\
             index aaa..bbb 100644\n\
             --- a/file.ts\n\
             +++ b/file.ts\n\
             @@ -1,3 +1,5 @@\n\
             +${seen[g.subtree] > 1 ? `**Seen ${seen[g.subtree]}× — likely cross-subtree type seam.**` : \"\"}\n\
             +              const k = `${b.fn}::${(b.what || \"\").slice(0, 80)}`;\n";
        let buffer = Buffer::from_str(content, 0, test_fs());

        if let HighlightEngine::TextMate(ref mut tm) = engine {
            let spans = tm.highlight_viewport(&buffer, 0, content.len(), &theme, 0);

            let bytes = content.as_bytes();
            let mut line_start = 0;
            while line_start < bytes.len() {
                let mut line_end = line_start;
                while line_end < bytes.len() && bytes[line_end] != b'\n' {
                    line_end += 1;
                }
                if bytes[line_start] == b'+' && !content[line_start..line_end].starts_with("+++") {
                    for byte_pos in line_start..line_end {
                        let span = spans
                            .iter()
                            .find(|s| s.range.start <= byte_pos && s.range.end > byte_pos);
                        let bg = span.and_then(|s| s.bg);
                        assert_eq!(
                            bg,
                            Some(theme.diff_add_bg),
                            "byte {} (`{}`) of `+` line starting at {} should carry diff_add_bg; \
                             got span={:?}",
                            byte_pos,
                            content[byte_pos..byte_pos + 1].escape_debug(),
                            line_start,
                            span,
                        );
                    }
                }
                line_start = line_end + 1;
            }
        } else {
            panic!("Expected TextMate engine for .diff file");
        }
    }

    #[test]
    fn test_git_rebase_todo_highlighting() {
        let registry =
            GrammarRegistry::load(&crate::primitives::grammar::LocalGrammarLoader::embedded_only());

        // git-rebase-todo files should use the Git Rebase Todo grammar
        let engine = HighlightEngine::for_file(Path::new("git-rebase-todo"), None, &registry);
        assert_eq!(engine.backend_name(), "textmate");
        assert!(engine.has_highlighting());
    }

    #[test]
    fn test_git_commit_message_highlighting() {
        let registry =
            GrammarRegistry::load(&crate::primitives::grammar::LocalGrammarLoader::embedded_only());

        // COMMIT_EDITMSG should use the Git Commit Message grammar
        let engine = HighlightEngine::for_file(Path::new("COMMIT_EDITMSG"), None, &registry);
        assert_eq!(engine.backend_name(), "textmate");
        assert!(engine.has_highlighting());

        // MERGE_MSG should also work
        let engine = HighlightEngine::for_file(Path::new("MERGE_MSG"), None, &registry);
        assert_eq!(engine.backend_name(), "textmate");
        assert!(engine.has_highlighting());
    }

    #[test]
    fn test_gitignore_highlighting() {
        let registry =
            GrammarRegistry::load(&crate::primitives::grammar::LocalGrammarLoader::embedded_only());

        // .gitignore should use the Gitignore grammar
        let engine = HighlightEngine::for_file(Path::new(".gitignore"), None, &registry);
        assert_eq!(engine.backend_name(), "textmate");
        assert!(engine.has_highlighting());

        // .dockerignore should also work
        let engine = HighlightEngine::for_file(Path::new(".dockerignore"), None, &registry);
        assert_eq!(engine.backend_name(), "textmate");
        assert!(engine.has_highlighting());
    }

    #[test]
    fn test_gitconfig_highlighting() {
        let registry =
            GrammarRegistry::load(&crate::primitives::grammar::LocalGrammarLoader::embedded_only());

        // .gitconfig should use the Git Config grammar
        let engine = HighlightEngine::for_file(Path::new(".gitconfig"), None, &registry);
        assert_eq!(engine.backend_name(), "textmate");
        assert!(engine.has_highlighting());

        // .gitmodules should also work
        let engine = HighlightEngine::for_file(Path::new(".gitmodules"), None, &registry);
        assert_eq!(engine.backend_name(), "textmate");
        assert!(engine.has_highlighting());
    }

    #[test]
    fn test_gitattributes_highlighting() {
        let registry =
            GrammarRegistry::load(&crate::primitives::grammar::LocalGrammarLoader::embedded_only());

        // .gitattributes should use the Git Attributes grammar
        let engine = HighlightEngine::for_file(Path::new(".gitattributes"), None, &registry);
        assert_eq!(engine.backend_name(), "textmate");
        assert!(engine.has_highlighting());
    }

    #[test]
    fn test_comment_delimiter_uses_comment_color() {
        // Comment delimiters (#, //, /*) should use comment color, not operator
        assert_eq!(
            scope_to_category("punctuation.definition.comment"),
            Some(HighlightCategory::Comment)
        );
        assert_eq!(
            scope_to_category("punctuation.definition.comment.python"),
            Some(HighlightCategory::Comment)
        );
        assert_eq!(
            scope_to_category("punctuation.definition.comment.begin"),
            Some(HighlightCategory::Comment)
        );
    }

    #[test]
    fn test_string_delimiter_uses_string_color() {
        // String delimiters (", ', `) should use string color, not operator
        assert_eq!(
            scope_to_category("punctuation.definition.string.begin"),
            Some(HighlightCategory::String)
        );
        assert_eq!(
            scope_to_category("punctuation.definition.string.end"),
            Some(HighlightCategory::String)
        );
    }

    #[test]
    fn test_punctuation_bracket() {
        // punctuation.section (TextMate standard for block delimiters)
        assert_eq!(
            scope_to_category("punctuation.section"),
            Some(HighlightCategory::PunctuationBracket)
        );
        assert_eq!(
            scope_to_category("punctuation.section.block.begin.c"),
            Some(HighlightCategory::PunctuationBracket)
        );
        assert_eq!(
            scope_to_category("punctuation.bracket"),
            Some(HighlightCategory::PunctuationBracket)
        );
        // punctuation.definition.* bracket-like scopes from sublime-syntax grammars
        assert_eq!(
            scope_to_category("punctuation.definition.array.begin.toml"),
            Some(HighlightCategory::PunctuationBracket)
        );
        assert_eq!(
            scope_to_category("punctuation.definition.block.code.typst"),
            Some(HighlightCategory::PunctuationBracket)
        );
        assert_eq!(
            scope_to_category("punctuation.definition.group.typst"),
            Some(HighlightCategory::PunctuationBracket)
        );
        assert_eq!(
            scope_to_category("punctuation.definition.inline-table.begin.toml"),
            Some(HighlightCategory::PunctuationBracket)
        );
        assert_eq!(
            scope_to_category("punctuation.definition.tag.end.svelte"),
            Some(HighlightCategory::PunctuationBracket)
        );
    }

    #[test]
    fn test_punctuation_delimiter() {
        assert_eq!(
            scope_to_category("punctuation.separator"),
            Some(HighlightCategory::PunctuationDelimiter)
        );
        assert_eq!(
            scope_to_category("punctuation.terminator.statement.c"),
            Some(HighlightCategory::PunctuationDelimiter)
        );
        assert_eq!(
            scope_to_category("punctuation.accessor"),
            Some(HighlightCategory::PunctuationDelimiter)
        );
    }

    /// First parse of a small file populates a whole-file cache; subsequent
    /// scrolls anywhere in the file are exact cache hits with no extra parse
    /// work.
    #[test]
    fn test_small_file_scroll_is_cache_hit() {
        let registry =
            GrammarRegistry::load(&crate::primitives::grammar::LocalGrammarLoader::embedded_only());
        let mut engine = HighlightEngine::for_file(Path::new("test.rs"), None, &registry);

        let mut content = String::new();
        for i in 0..200 {
            content.push_str(&format!("fn f_{i}() {{ let x = {i}; }}\n"));
        }
        let buffer = Buffer::from_str(&content, 0, test_fs());
        let theme = Theme::load_builtin(theme::THEME_LIGHT).unwrap();

        let HighlightEngine::TextMate(ref mut tm) = engine else {
            panic!("expected TextMate engine for .rs");
        };

        // First call: cold start, full parse.
        let _ = tm.highlight_viewport(&buffer, 0, 200, &theme, 10_000);
        let stats_after_first = tm.stats().clone();
        assert_eq!(
            stats_after_first.cache_hits, 0,
            "first call cannot hit cache"
        );
        assert_eq!(
            stats_after_first.cache_misses, 1,
            "first call must be a miss"
        );

        // Scroll anywhere — top, middle, end. All must be cache hits.
        let mid = buffer.len() / 2;
        let near_end = buffer.len().saturating_sub(200);
        let probes = [(0, 200), (mid, mid + 200), (near_end, buffer.len())];
        for (vs, ve) in probes {
            let _ = tm.highlight_viewport(&buffer, vs, ve, &theme, 10_000);
        }

        let stats_after_scroll = tm.stats().clone();
        assert_eq!(
            stats_after_scroll.cache_misses,
            1,
            "scrolling must not add cache misses (got extra: {})",
            stats_after_scroll.cache_misses - 1
        );
        assert_eq!(
            stats_after_scroll.cache_hits, 3,
            "all three scroll probes must hit the cache"
        );
        assert_eq!(
            stats_after_scroll.bytes_parsed, stats_after_first.bytes_parsed,
            "scrolling must not parse any new bytes"
        );
    }

    /// After a small edit, the next render takes the partial-update path
    /// (convergence) and continues to serve cache hits afterwards. Crucially:
    /// the partial update parses far fewer bytes than the file is long.
    #[test]
    fn test_small_file_edit_uses_partial_update() {
        let registry =
            GrammarRegistry::load(&crate::primitives::grammar::LocalGrammarLoader::embedded_only());
        let mut engine = HighlightEngine::for_file(Path::new("test.rs"), None, &registry);

        let mut content = String::new();
        for i in 0..200 {
            content.push_str(&format!("fn f_{i}() {{ let x = {i}; }}\n"));
        }
        let buffer = Buffer::from_str(&content, 0, test_fs());
        let theme = Theme::load_builtin(theme::THEME_LIGHT).unwrap();

        let HighlightEngine::TextMate(ref mut tm) = engine else {
            panic!("expected TextMate engine for .rs");
        };

        // Warm cache.
        let _ = tm.highlight_viewport(&buffer, 0, 100, &theme, 10_000);
        let bytes_before_edit = tm.stats().bytes_parsed;
        let buf_len = buffer.len();
        assert!(
            buf_len > 4000,
            "test needs a buffer larger than the partial-update region"
        );

        // Simulate an edit deep in the file.
        let edit_pos = buf_len / 2;
        tm.notify_insert(edit_pos, 1);
        // The buffer itself doesn't change here (we test the engine in isolation),
        // but notify_insert sets dirty_from and shifts spans, which is what the
        // partial-update path consumes.

        let _ = tm.highlight_viewport(&buffer, 0, 100, &theme, 10_000);
        let bytes_after_edit = tm.stats().bytes_parsed;
        let parsed = bytes_after_edit - bytes_before_edit;

        assert!(
            parsed < buf_len,
            "edit must not trigger a whole-file reparse (parsed {parsed}, file {buf_len})"
        );
    }

    /// Bulk edits (multi-cursor typing, "select word + type letter" replace,
    /// search-replace, etc.) must take the same partial-update path as single
    /// edits. Regression for #1958: the previous code called `invalidate_all()`
    /// after a bulk edit, wiping every checkpoint and forcing a cold reparse
    /// from byte zero on the next keystroke.
    #[test]
    fn test_bulk_edit_uses_partial_update() {
        let registry =
            GrammarRegistry::load(&crate::primitives::grammar::LocalGrammarLoader::embedded_only());
        let mut engine = HighlightEngine::for_file(Path::new("test.rs"), None, &registry);

        let mut content = String::new();
        for i in 0..200 {
            content.push_str(&format!("fn f_{i}() {{ let x = {i}; }}\n"));
        }
        let buffer = Buffer::from_str(&content, 0, test_fs());
        let theme = Theme::load_builtin(theme::THEME_LIGHT).unwrap();

        // Warm cache.
        let _ = engine.highlight_viewport(&buffer, 0, 100, &theme, 10_000);
        let bytes_before_edit = match &engine {
            HighlightEngine::TextMate(h) => h.stats().bytes_parsed,
            _ => panic!("expected TextMate engine for .rs"),
        };
        let buf_len = buffer.len();
        assert!(
            buf_len > 4000,
            "test needs a buffer larger than the partial-update region"
        );

        // Simulate "select a word, type a letter" deep in the file: a single
        // bulk edit that deletes 8 bytes and inserts 1 byte at the same
        // position. This is exactly the user-facing scenario in #1958.
        let edit_pos = buf_len / 2;
        let edits = vec![(edit_pos, 8usize, 1usize)];
        engine.notify_edits(&edits);

        let _ = engine.highlight_viewport(&buffer, 0, 100, &theme, 10_000);
        let bytes_after_edit = match &engine {
            HighlightEngine::TextMate(h) => h.stats().bytes_parsed,
            _ => unreachable!(),
        };
        let parsed = bytes_after_edit - bytes_before_edit;

        assert!(
            parsed < buf_len,
            "bulk edit must not trigger a whole-file reparse \
             (parsed {parsed}, file {buf_len})"
        );
    }

    /// Bulk edits whose positions are all outside the cached viewport must
    /// not invalidate the cache at all on the tree-sitter / `Highlighter`
    /// path. (TextMate has a richer convergence model, but for both engines
    /// the regression to guard against is: "any bulk edit, even a tiny one,
    /// destroys the cache and forces a full reparse.")
    #[test]
    fn test_bulk_edit_outside_cache_keeps_textmate_partial_update() {
        let registry =
            GrammarRegistry::load(&crate::primitives::grammar::LocalGrammarLoader::embedded_only());
        let mut engine = HighlightEngine::for_file(Path::new("test.rs"), None, &registry);

        let mut content = String::new();
        for i in 0..400 {
            content.push_str(&format!("fn f_{i}() {{ let x = {i}; }}\n"));
        }
        let buffer = Buffer::from_str(&content, 0, test_fs());
        let theme = Theme::load_builtin(theme::THEME_LIGHT).unwrap();

        // Warm a viewport near the start.
        let _ = engine.highlight_viewport(&buffer, 0, 200, &theme, 1_000);
        let bytes_before = match &engine {
            HighlightEngine::TextMate(h) => h.stats().bytes_parsed,
            _ => panic!("expected TextMate engine for .rs"),
        };

        // Apply a bulk edit far past the warmed viewport.
        let far_pos = buffer.len() - 100;
        engine.notify_edits(&[(far_pos, 3, 1)]);

        // Re-render the original viewport. The partial-update path must keep
        // parsed bytes well below a whole-file reparse.
        let _ = engine.highlight_viewport(&buffer, 0, 200, &theme, 1_000);
        let bytes_after = match &engine {
            HighlightEngine::TextMate(h) => h.stats().bytes_parsed,
            _ => unreachable!(),
        };
        let parsed = bytes_after - bytes_before;
        let buf_len = buffer.len();
        assert!(
            parsed < buf_len,
            "bulk edit outside the viewport must not force a whole-file \
             reparse (parsed {parsed}, file {buf_len})"
        );
    }

    /// Convergence budget caps per-pass work even when the parse state never
    /// agrees with any existing checkpoint. Without the cap, a non-converging
    /// edit would parse the rest of the file on every keystroke.
    #[test]
    fn test_partial_update_budget_caps_work() {
        let registry =
            GrammarRegistry::load(&crate::primitives::grammar::LocalGrammarLoader::embedded_only());
        let mut engine = HighlightEngine::for_file(Path::new("test.rs"), None, &registry);

        // Build a buffer comfortably larger than CONVERGENCE_BUDGET.
        let mut content = String::new();
        while content.len() < (CONVERGENCE_BUDGET * 4) {
            content.push_str("fn name() { let mut v = 0; v += 1; }\n");
        }
        let buffer = Buffer::from_str(&content, 0, test_fs());
        let theme = Theme::load_builtin(theme::THEME_LIGHT).unwrap();

        let HighlightEngine::TextMate(ref mut tm) = engine else {
            panic!("expected TextMate engine for .rs");
        };

        // Warm cache (whole-file parse).
        let _ = tm.highlight_viewport(&buffer, 0, 200, &theme, 10_000);
        // Simulate an edit and force every checkpoint to disagree by clearing
        // their stored states. The convergence loop will look at each marker,
        // find the slot empty, and never converge.
        tm.notify_insert(100, 0);
        tm.checkpoint_states.clear();

        let bytes_before = tm.stats().bytes_parsed;
        let _ = tm.highlight_viewport(&buffer, 0, 200, &theme, 10_000);
        let parsed = tm.stats().bytes_parsed - bytes_before;

        // Budget bounds the work to roughly CONVERGENCE_BUDGET past the dirty
        // point (plus the prefix back to the resume checkpoint). Allow a small
        // overshoot for the line that crossed the budget threshold.
        assert!(
            parsed <= CONVERGENCE_BUDGET + 4096,
            "partial update parsed {parsed}, expected <= {} \
             (budget {CONVERGENCE_BUDGET} + slack)",
            CONVERGENCE_BUDGET + 4096
        );

        // Budget hit must leave dirty_from set for follow-up passes.
        assert!(
            tm.dirty_from.is_some(),
            "budget exit must keep dirty_from set"
        );
    }

    /// Large files (above MAX_PARSE_BYTES) keep the existing windowed
    /// behaviour: parse range is bounded by ±context_bytes around the
    /// viewport, not the whole file.
    ///
    /// The viewport is placed past `MAX_PARSE_BYTES` so we exercise the
    /// "large file, no nearby checkpoint" branch in `find_parse_resume_point`
    /// — the symmetric branch that fires when `parse_end <= MAX_PARSE_BYTES`
    /// still parses from byte 0 even on big files (pre-existing behaviour,
    /// addressed in a later phase).
    #[test]
    fn test_large_file_uses_windowed_parse() {
        let registry =
            GrammarRegistry::load(&crate::primitives::grammar::LocalGrammarLoader::embedded_only());
        let mut engine = HighlightEngine::for_file(Path::new("test.rs"), None, &registry);

        // Build content well past MAX_PARSE_BYTES so we can put the viewport
        // beyond it.
        let line = "fn long_name_for_padding() { let v = 1; v + 1; }\n";
        let bytes_needed = MAX_PARSE_BYTES * 2;
        let lines_needed = bytes_needed / line.len() + 100;
        let mut content = String::with_capacity(lines_needed * line.len());
        for _ in 0..lines_needed {
            content.push_str(line);
        }
        assert!(content.len() > MAX_PARSE_BYTES * 2);
        let buffer = Buffer::from_str(&content, 0, test_fs());
        let theme = Theme::load_builtin(theme::THEME_LIGHT).unwrap();

        let HighlightEngine::TextMate(ref mut tm) = engine else {
            panic!("expected TextMate engine for .rs");
        };

        // Viewport past MAX_PARSE_BYTES: parse_end > MAX_PARSE_BYTES, so the
        // resume-from-byte-0 fallback in find_parse_resume_point doesn't fire.
        let context_bytes = 10_000usize;
        let viewport_start = MAX_PARSE_BYTES + 200_000;
        let viewport_end = viewport_start + 1000;
        let _ = tm.highlight_viewport(&buffer, viewport_start, viewport_end, &theme, context_bytes);
        let parsed = tm.stats().bytes_parsed;

        // Windowed parse covers viewport ± context_bytes plus a tiny prefix
        // for the resume anchor. Allow generous slack (4×) but reject
        // anything close to whole-file.
        let window = (viewport_end - viewport_start) + 2 * context_bytes;
        assert!(
            parsed <= window * 4,
            "large file windowed parse should be ~{window} bytes, got {parsed} \
             (file {})",
            buffer.len()
        );
    }

    /// Regression for issue #899: a class field initialised with an arrow
    /// function that returns a template literal must not bleed string
    /// highlighting onto the rest of the class body. The user-reported
    /// repro pinned the syntect JavaScript grammar to a string state from
    /// the trailing `;` until EOF; the constructor keyword, comments, and
    /// the closing `}` were all painted as a string.
    #[test]
    fn test_javascript_template_literal_does_not_bleed() {
        let registry =
            GrammarRegistry::load(&crate::primitives::grammar::LocalGrammarLoader::embedded_only());
        let mut engine = HighlightEngine::for_file(Path::new("repro.js"), None, &registry);

        // Reproduction code from issue #899.
        let source = "class ExampleClass {\n\
                      \texampleFunction = exampleArg => `${exampleArg}`;\n\
                      \n\
                      \tconstructor() {\n\
                      \t\t// constructor body\n\
                      \t}\n\
                      \n\
                      \t/* multiline comment */\n\
                      }\n";
        let buffer = Buffer::from_str(source, 0, test_fs());
        let theme = Theme::load_builtin(theme::THEME_LIGHT).unwrap();

        let _ = engine.highlight_viewport(&buffer, 0, source.len(), &theme, 0);

        // The `constructor` keyword sits well after the template literal.
        // If string state bleeds, this position is reported as String.
        let ctor_pos = source.find("constructor").expect("locate constructor");
        let ctor_cat = engine.category_at_position(ctor_pos);
        assert_ne!(
            ctor_cat,
            Some(HighlightCategory::String),
            "constructor keyword must not inherit string state from earlier \
             template literal (got {:?})",
            ctor_cat,
        );

        // The closing brace of the class — the very last non-whitespace char
        // — also lives outside any string in correct JS.
        let last_brace = source.rfind('}').expect("locate closing brace");
        let brace_cat = engine.category_at_position(last_brace);
        assert_ne!(
            brace_cat,
            Some(HighlightCategory::String),
            "closing class brace must not be highlighted as string \
             (got {:?})",
            brace_cat,
        );
    }

    /// The closing `}` of a `${…}` template substitution and the closing
    /// backtick of the surrounding template literal must keep template
    /// string colouring — not inherit the `@variable` highlight from the
    /// substitution's expression. Tree-sitter-highlight emits one
    /// HighlightEnd event per started highlight; if the editor's
    /// span-flattening logic doesn't pop the inner `@variable` correctly
    /// when the substitution closes, the variable colour bleeds across
    /// `}` and the trailing `\`` until the next sibling capture (here,
    /// the `;` operator).
    #[test]
    fn test_javascript_template_substitution_closing_tokens_are_string() {
        let registry =
            GrammarRegistry::load(&crate::primitives::grammar::LocalGrammarLoader::embedded_only());
        let mut engine = HighlightEngine::for_file(Path::new("tmpl.js"), None, &registry);

        // Minimal template literal: `${name}` — wrapped in a statement so
        // the parser sees a complete program.
        let source = "const x = `${name}`;\n";
        let buffer = Buffer::from_str(source, 0, test_fs());
        let theme = Theme::load_builtin(theme::THEME_LIGHT).unwrap();

        let _ = engine.highlight_viewport(&buffer, 0, source.len(), &theme, 0);

        // Locate the closing `}` of the substitution and the closing
        // backtick of the template literal.
        let close_brace = source
            .find("}`")
            .expect("locate substitution closing brace");
        let close_backtick = close_brace + 1;

        // Sanity: the inner identifier `name` is correctly tagged as a
        // variable (this guards us against an unrelated regression where
        // the entire template gets typed wrong).
        let name_pos = source.find("name").expect("locate identifier");
        let name_cat = engine.category_at_position(name_pos);
        assert_eq!(
            name_cat,
            Some(HighlightCategory::Variable),
            "substitution identifier should be Variable (got {:?})",
            name_cat,
        );

        // The closing `}` and `` ` `` live inside the surrounding
        // `template_string` node, so tree-sitter assigns them the
        // `@string` capture. They must surface as String here — not
        // as Variable (the previous symptom of the bleed) and not as
        // None (which would make the editor render them with the
        // default foreground colour, equally wrong).
        let brace_cat = engine.category_at_position(close_brace);
        assert_eq!(
            brace_cat,
            Some(HighlightCategory::String),
            "closing }} of ${{…}} must be String (got {:?})",
            brace_cat,
        );
        let backtick_cat = engine.category_at_position(close_backtick);
        assert_eq!(
            backtick_cat,
            Some(HighlightCategory::String),
            "closing backtick of template literal must be String \
             (got {:?})",
            backtick_cat,
        );
    }
}