rust_widgets 2.9.2

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Built-in tokenizer and the syntax-highlighting plugin seam.
//!
//! Real grammar-aware highlighting (tree-sitter, LSP semantic tokens) belongs
//! in a plugin crate. What lives here is a dependency-free lexer good enough to
//! power keyword/string/comment/number colouring, plus the [`SyntaxHighlighter`]
//! trait that a plugin implements to replace it wholesale.

use super::types::{TokenKind, TokenSpan};
use alloc::vec::Vec;

/// Lexer state carried across a line boundary.
///
/// Real syntax highlighting is **stateful**: a block comment, a multi-line
/// string (`"""`, `r#"…"#`) or a nested-delimiter run opened on one line
/// changes how the next line must be read. A highlighter that only ever sees
/// one line cannot know whether it starts inside a string, which is why the
/// seam has to carry this value in and out of every call.
///
/// The type is intentionally a small `enum` rather than an opaque token: it has
/// to be `Copy` so the line-state cache can store one per line, and it has to be
/// comparable so an edit can stop re-lexing once the state it produces matches
/// the state that was already recorded.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub enum LineState {
    /// The line starts outside any construct; the next line does too.
    #[default]
    Clean,
    /// Inside a `/* … */` block comment.
    BlockComment,
    /// Inside a double-quoted multi-line string (`"""` for Python, `"` for
    /// a line-continued string in the C family).
    MultiLineString,
    /// Inside a single-quoted multi-line string (`'''` for Python).
    MultiLineCharString,
    /// Inside a Rust raw string, carrying the number of `#` delimiters.
    RawString {
        /// How many `#` characters delimit the raw string (`r#"` → 1).
        hashes: u8,
    },
    /// Inside a Go backtick raw string.
    RawStringTick,
    /// Inside an HTML/XML `<!-- … -->` comment.
    HtmlComment,
}

impl LineState {
    /// Returns the state a freshly opened document starts in.
    pub fn initial() -> Self {
        Self::Clean
    }

    /// Returns `true` when this state is [`Self::Clean`].
    pub fn is_clean(self) -> bool {
        matches!(self, Self::Clean)
    }

    /// Returns `true` when the state does not end at a line boundary, i.e. the
    /// next line is a continuation. Used by the renderer to keep a continuation
    /// row visually distinct from a fresh one.
    pub fn continues(self) -> bool {
        !self.is_clean()
    }
}

/// Single-line lexer interface.
///
/// Implement this to plug a real grammar into the editor:
///
/// ```
/// use rust_widgets::widget::special_widgets::code_editor::{
///     LineState, SyntaxHighlighter, TokenKind, TokenSpan,
/// };
///
/// struct EverythingIsAComment;
///
/// impl SyntaxHighlighter for EverythingIsAComment {
///     fn highlight_line(&self, line: &str, state: LineState) -> (Vec<TokenSpan>, LineState) {
///         let spans = if line.is_empty() {
///             Vec::new()
///         } else {
///             vec![TokenSpan::new(0, line.len(), TokenKind::Comment)]
///         };
///         (spans, state)
///     }
///
///     fn language_name(&self) -> &str {
///         "Comment Only"
///     }
/// }
/// ```
///
/// Implementors must be `Send + Sync` so a host may run the tokenizer on a
/// worker thread and hand the finished spans back to the UI thread. Without
/// that bound the editor can only ever re-highlight synchronously inside
/// `draw`, which is what makes a long file stutter no matter how fast the
/// lexer itself is.
pub trait SyntaxHighlighter: Send + Sync {
    /// Splits `line` into ordered, non-overlapping [`TokenSpan`]s, given the
    /// state the line starts in, and returns the state the line ends in.
    ///
    /// Spans that fall outside the line or split a UTF-8 sequence are clamped
    /// by the editor, so implementations cannot corrupt rendering by returning
    /// malformed offsets.
    fn highlight_line(&self, line: &str, state: LineState) -> (Vec<TokenSpan>, LineState);

    /// Human-readable language name used by the status bar and plugin registry.
    fn language_name(&self) -> &str {
        "Plain Text"
    }

    /// Returns `true` when `line` starts its own construct and the previous
    /// line's state can be ignored for correctness (not merely for speed).
    ///
    /// The default is the conservative `false`: a stateful highlighter always
    /// consumes the incoming state. Stateless highlighters may override this
    /// with `true` so the editor can skip re-lexing a region after an edit.
    fn resets_each_line(&self) -> bool {
        false
    }
}

/// Language families understood by the built-in lexer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum LanguageId {
    /// Rust source (`//`, `/* */`, `"`, `'`, `#[]`).
    Rust,
    /// Python source (`#`, `"""`, `'''`) — indentation-sensitive, no block comments.
    Python,
    /// JavaScript or TypeScript source.
    JavaScript,
    /// Go source, including backtick raw strings.
    Go,
    /// C-family source, including `#define` preprocessor lines.
    CLike,
    /// Java source.
    Java,
    /// C# source, including `#if` preprocessor lines.
    CSharp,
    /// C++ source.
    Cpp,
    /// Kotlin source.
    Kotlin,
    /// Swift source.
    Swift,
    /// HTML source, including `<!-- … -->` comments.
    Html,
    /// XML source, including `<!-- … -->` comments.
    Xml,
    /// JSON data (no comments; `true`/`false`/`null` are keywords).
    Json,
    /// CSS source (block comments only).
    Css,
    /// YAML source (`#` comments).
    Yaml,
    /// TOML source (`#` comments).
    Toml,
    /// Shell source (`#` comments).
    Shell,
    /// SQL source (`--` line comments, `/* */` block comments).
    Sql,
    /// Markdown-ish plain text.
    Markdown,
    /// No highlighting at all.
    #[default]
    PlainText,
}

impl LanguageId {
    /// Returns the display name.
    pub fn name(self) -> &'static str {
        match self {
            Self::Rust => "Rust",
            Self::Python => "Python",
            Self::JavaScript => "JavaScript",
            Self::Go => "Go",
            Self::CLike => "C",
            Self::Java => "Java",
            Self::CSharp => "C#",
            Self::Cpp => "C++",
            Self::Kotlin => "Kotlin",
            Self::Swift => "Swift",
            Self::Html => "HTML",
            Self::Xml => "XML",
            Self::Json => "JSON",
            Self::Css => "CSS",
            Self::Yaml => "YAML",
            Self::Toml => "TOML",
            Self::Shell => "Shell",
            Self::Sql => "SQL",
            Self::Markdown => "Markdown",
            Self::PlainText => "Plain Text",
        }
    }

    /// Returns the number of spaces a tab expands to for this language.
    pub fn default_tab_width(self) -> usize {
        match self {
            // Markup and data formats are conventionally two-space indented.
            Self::Html | Self::Xml | Self::Json | Self::Css => 2,
            _ => super::types::DEFAULT_TAB_WIDTH,
        }
    }

    /// Returns `true` when `#` starts a line comment instead of a preprocessor.
    pub fn uses_hash_comments(self) -> bool {
        matches!(self, Self::Python | Self::Shell | Self::Yaml | Self::Toml)
    }

    /// Returns `true` when `/* ... */` block comments are supported.
    pub fn supports_block_comments(self) -> bool {
        matches!(
            self,
            Self::Rust
                | Self::JavaScript
                | Self::Go
                | Self::CLike
                | Self::Java
                | Self::CSharp
                | Self::Cpp
                | Self::Kotlin
                | Self::Swift
                | Self::Css
                | Self::Sql
        )
    }

    /// Returns `true` when `#`-prefixed preprocessor lines are supported.
    pub fn supports_preprocessor(self) -> bool {
        matches!(self, Self::Rust | Self::CLike | Self::Cpp | Self::CSharp)
    }

    /// Returns `true` when `//` starts a line comment.
    pub fn supports_slash_comments(self) -> bool {
        matches!(
            self,
            Self::Rust
                | Self::JavaScript
                | Self::Go
                | Self::CLike
                | Self::Java
                | Self::CSharp
                | Self::Cpp
                | Self::Kotlin
                | Self::Swift
        )
    }

    /// Returns `true` when `--` starts a line comment.
    pub fn supports_dash_comments(self) -> bool {
        matches!(self, Self::Sql)
    }

    /// Returns `true` when `<!-- … -->` comments are supported.
    pub fn supports_html_comments(self) -> bool {
        matches!(self, Self::Html | Self::Xml)
    }

    /// Returns `true` when a single-quoted literal is a character, not a string.
    pub fn single_quote_is_char(self) -> bool {
        matches!(
            self,
            Self::Rust
                | Self::Go
                | Self::CLike
                | Self::Java
                | Self::CSharp
                | Self::Cpp
                | Self::Kotlin
                | Self::Swift
        )
    }

    /// Returns `true` when `ch` may appear inside an identifier.
    ///
    /// Also used for word-wise caret movement and whole-word search, so it is
    /// public: plugins can override the notion of "word" for their language.
    pub fn is_word_char(self, ch: char) -> bool {
        ch.is_alphanumeric() || ch == '_'
    }

    /// Returns the keyword set of the language family.
    pub fn keywords(self) -> &'static [&'static str] {
        match self {
            Self::Rust => &[
                "as", "async", "await", "break", "const", "continue", "crate", "dyn", "else",
                "enum", "extern", "false", "fn", "for", "if", "impl", "in", "let", "loop", "match",
                "mod", "move", "mut", "pub", "ref", "return", "self", "static", "struct", "super",
                "trait", "true", "type", "union", "unsafe", "use", "where", "while",
            ],
            Self::Python => &[
                "False", "None", "True", "and", "as", "assert", "async", "await", "break", "class",
                "continue", "def", "del", "elif", "else", "except", "finally", "for", "from",
                "global", "if", "import", "in", "is", "lambda", "nonlocal", "not", "or", "pass",
                "raise", "return", "try", "while", "with", "yield",
            ],
            Self::JavaScript => &[
                "async",
                "await",
                "break",
                "case",
                "catch",
                "class",
                "const",
                "continue",
                "default",
                "delete",
                "do",
                "else",
                "export",
                "extends",
                "false",
                "finally",
                "for",
                "function",
                "if",
                "import",
                "in",
                "instanceof",
                "let",
                "new",
                "null",
                "of",
                "return",
                "static",
                "super",
                "switch",
                "this",
                "throw",
                "true",
                "try",
                "typeof",
                "undefined",
                "var",
                "void",
                "while",
                "yield",
            ],
            Self::Go => &[
                "break",
                "case",
                "chan",
                "const",
                "continue",
                "default",
                "defer",
                "else",
                "fallthrough",
                "for",
                "func",
                "go",
                "goto",
                "if",
                "import",
                "interface",
                "map",
                "package",
                "range",
                "return",
                "select",
                "struct",
                "switch",
                "type",
                "var",
            ],
            Self::CLike => &[
                "auto", "break", "case", "const", "continue", "default", "do", "else", "enum",
                "extern", "for", "goto", "if", "inline", "register", "restrict", "return",
                "sizeof", "static", "struct", "switch", "typedef", "union", "volatile", "while",
            ],
            Self::Java => &[
                "abstract",
                "assert",
                "boolean",
                "break",
                "byte",
                "case",
                "catch",
                "char",
                "class",
                "const",
                "continue",
                "default",
                "do",
                "double",
                "else",
                "enum",
                "extends",
                "false",
                "final",
                "finally",
                "float",
                "for",
                "goto",
                "if",
                "implements",
                "import",
                "instanceof",
                "int",
                "interface",
                "long",
                "native",
                "new",
                "null",
                "package",
                "private",
                "protected",
                "public",
                "return",
                "short",
                "static",
                "super",
                "switch",
                "synchronized",
                "this",
                "throw",
                "throws",
                "transient",
                "true",
                "try",
                "void",
                "volatile",
                "while",
            ],
            Self::CSharp => &[
                "abstract",
                "as",
                "base",
                "bool",
                "break",
                "byte",
                "case",
                "catch",
                "char",
                "checked",
                "class",
                "const",
                "continue",
                "decimal",
                "default",
                "delegate",
                "do",
                "double",
                "else",
                "enum",
                "event",
                "explicit",
                "extern",
                "false",
                "finally",
                "fixed",
                "float",
                "for",
                "foreach",
                "goto",
                "if",
                "implicit",
                "in",
                "int",
                "interface",
                "internal",
                "is",
                "lock",
                "long",
                "namespace",
                "new",
                "null",
                "object",
                "operator",
                "out",
                "override",
                "params",
                "private",
                "protected",
                "public",
                "readonly",
                "ref",
                "return",
                "sbyte",
                "sealed",
                "short",
                "sizeof",
                "stackalloc",
                "static",
                "string",
                "struct",
                "switch",
                "this",
                "throw",
                "true",
                "try",
                "typeof",
                "uint",
                "ulong",
                "unchecked",
                "unsafe",
                "ushort",
                "using",
                "virtual",
                "void",
                "volatile",
                "while",
            ],
            Self::Cpp => &[
                "alignas",
                "alignof",
                "auto",
                "bool",
                "break",
                "case",
                "catch",
                "char",
                "class",
                "const",
                "constexpr",
                "continue",
                "decltype",
                "default",
                "delete",
                "do",
                "double",
                "else",
                "enum",
                "explicit",
                "extern",
                "false",
                "float",
                "for",
                "friend",
                "goto",
                "if",
                "inline",
                "int",
                "long",
                "mutable",
                "namespace",
                "new",
                "noexcept",
                "nullptr",
                "operator",
                "private",
                "protected",
                "public",
                "register",
                "return",
                "short",
                "signed",
                "sizeof",
                "static",
                "struct",
                "switch",
                "template",
                "this",
                "throw",
                "true",
                "try",
                "typedef",
                "typename",
                "union",
                "unsigned",
                "using",
                "virtual",
                "void",
                "volatile",
                "while",
            ],
            Self::Kotlin => &[
                "as",
                "break",
                "class",
                "continue",
                "do",
                "else",
                "false",
                "for",
                "fun",
                "if",
                "in",
                "interface",
                "is",
                "null",
                "object",
                "package",
                "return",
                "super",
                "this",
                "throw",
                "true",
                "try",
                "typealias",
                "val",
                "var",
                "when",
                "while",
            ],
            Self::Swift => &[
                "Self",
                "as",
                "associatedtype",
                "break",
                "case",
                "catch",
                "class",
                "continue",
                "default",
                "defer",
                "deinit",
                "do",
                "else",
                "enum",
                "extension",
                "fallthrough",
                "false",
                "fileprivate",
                "for",
                "func",
                "guard",
                "if",
                "import",
                "in",
                "init",
                "inout",
                "internal",
                "is",
                "let",
                "nil",
                "open",
                "operator",
                "private",
                "protocol",
                "public",
                "repeat",
                "rethrows",
                "return",
                "self",
                "static",
                "struct",
                "subscript",
                "switch",
                "throw",
                "throws",
                "true",
                "try",
                "typealias",
                "var",
                "where",
                "while",
            ],
            Self::Html | Self::Xml | Self::Css => &[],
            Self::Json => &["false", "null", "true"],
            Self::Yaml => &["false", "no", "null", "off", "on", "true", "yes"],
            Self::Toml => &["false", "true"],
            Self::Shell => &[
                "alias", "break", "case", "continue", "declare", "do", "done", "elif", "else",
                "esac", "export", "fi", "for", "function", "if", "in", "local", "readonly",
                "return", "select", "shift", "source", "then", "time", "unset", "until", "while",
            ],
            Self::Sql => &[
                "add",
                "all",
                "alter",
                "and",
                "as",
                "between",
                "by",
                "case",
                "check",
                "column",
                "create",
                "default",
                "delete",
                "distinct",
                "drop",
                "else",
                "end",
                "exists",
                "foreign",
                "from",
                "group",
                "having",
                "in",
                "index",
                "inner",
                "insert",
                "into",
                "is",
                "join",
                "key",
                "left",
                "like",
                "limit",
                "not",
                "null",
                "offset",
                "on",
                "or",
                "order",
                "outer",
                "primary",
                "references",
                "right",
                "select",
                "set",
                "table",
                "then",
                "union",
                "unique",
                "update",
                "values",
                "view",
                "when",
                "where",
            ],
            Self::Markdown | Self::PlainText => &[],
        }
    }

    /// Returns the built-in type and primitive names of the language family.
    pub fn type_names(self) -> &'static [&'static str] {
        match self {
            Self::Rust => &[
                "Arc", "Box", "Option", "Rc", "Result", "String", "Vec", "bool", "char", "f32",
                "f64", "i128", "i16", "i32", "i64", "i8", "isize", "str", "u128", "u16", "u32",
                "u64", "u8", "usize",
            ],
            Self::Python => {
                &["bool", "bytes", "dict", "float", "int", "list", "set", "str", "tuple"]
            }
            Self::JavaScript => {
                &["Array", "Boolean", "Map", "Number", "Object", "Promise", "Set", "String"]
            }
            Self::Go => {
                &["bool", "byte", "error", "float32", "float64", "int", "rune", "string", "uint"]
            }
            Self::CLike => &["char", "double", "float", "int", "long", "short", "void"],
            Self::Java => &[
                "Object", "String", "boolean", "byte", "char", "double", "float", "int", "long",
                "short", "void",
            ],
            Self::CSharp => &[
                "bool", "byte", "char", "decimal", "double", "float", "int", "long", "object",
                "sbyte", "short", "string", "uint", "ulong", "ushort", "void",
            ],
            Self::Cpp => {
                &["bool", "char", "double", "float", "int", "long", "short", "size_t", "void"]
            }
            Self::Kotlin => &[
                "Any", "Boolean", "Byte", "Char", "Double", "Float", "Int", "Long", "Short",
                "String", "Unit",
            ],
            Self::Swift => {
                &["Any", "Bool", "Character", "Double", "Float", "Int", "String", "Void"]
            }
            Self::Sql => &["boolean", "date", "int", "integer", "text", "timestamp", "varchar"],
            Self::Html
            | Self::Xml
            | Self::Json
            | Self::Css
            | Self::Yaml
            | Self::Toml
            | Self::Shell
            | Self::Markdown
            | Self::PlainText => &[],
        }
    }

    /// Returns `true` when `#` opens a line comment for this language.
    pub fn comment_prefix(self) -> &'static str {
        if self.supports_dash_comments() {
            "-- "
        } else if self.uses_hash_comments() {
            "# "
        } else {
            "// "
        }
    }

    /// Returns `true` when the language has a line-comment syntax at all.
    ///
    /// This is the `D2` predicate: a structure-aware command is *meaningless* for
    /// a language that has no such structure, and inserting `// ` into plain text
    /// or a Markdown heading is not a degraded toggle, it is corruption. Callers
    /// consult this and refuse rather than guess, so the failure is visible.
    pub fn supports_line_comments(self) -> bool {
        !matches!(
            self,
            Self::Markdown | Self::PlainText | Self::Json | Self::Html | Self::Xml | Self::Css
        )
    }

    /// Returns `true` when bracket/quote auto-pairing is meaningful.
    ///
    /// Pairing is **not** degraded by language: it is already gated by
    /// [`super::types::CodeEditorConfig::auto_close_brackets`], which is the user's
    /// explicit choice, and inserting a matching delimiter is a formatting
    /// preference rather than a claim about grammar. The one command whose
    /// incorrect guess corrupts text is [`Self::line_comment_prefix`], which is why
    /// that one *is* degraded. This predicate exists so a host can still ask the
    /// question without the editor deciding for it.
    pub fn supports_auto_pairing(self) -> bool {
        !matches!(self, Self::Markdown | Self::PlainText)
    }

    /// Returns the line-comment prefix, or `None` when there is none.
    ///
    /// The `Option` is what makes the degradation explicit at the call site: a
    /// command that needs a comment token cannot silently fall back to a wrong
    /// one.
    pub fn line_comment_prefix(self) -> Option<&'static str> {
        if self.supports_line_comments() {
            Some(self.comment_prefix())
        } else {
            None
        }
    }
}

/// Keyword/identifier-aware lexer covering the [`LanguageId`] families.
///
/// This is a lexer, not a parser: it classifies keywords, types, strings,
/// chars, numbers, comments, operators, and call-site functions. Grammar-aware
/// highlighting is a plugin concern — see the module docs.
#[derive(Debug, Clone, Copy, Default)]
pub struct BuiltinHighlighter {
    language: LanguageId,
}

impl BuiltinHighlighter {
    /// Creates a highlighter for `language`.
    pub fn new(language: LanguageId) -> Self {
        Self { language }
    }

    /// Returns the language this highlighter tokenizes.
    pub fn language(&self) -> LanguageId {
        self.language
    }

    fn word_token_kind(&self, word: &str, followed_by_call: bool) -> TokenKind {
        // Both tables are kept in byte order (a unit test pins that), so classification is a
        // binary search instead of a linear `contains` over every keyword — which ran once
        // per identifier on every painted line (J-P07).
        if self.language.keywords().binary_search(&word).is_ok() {
            TokenKind::Keyword
        } else if self.language.type_names().binary_search(&word).is_ok() {
            TokenKind::Type
        } else if followed_by_call {
            TokenKind::Function
        } else {
            TokenKind::Identifier
        }
    }
}

impl SyntaxHighlighter for BuiltinHighlighter {
    fn highlight_line(&self, line: &str, mut state: LineState) -> (Vec<TokenSpan>, LineState) {
        let len = line.len();
        let mut spans: Vec<TokenSpan> = Vec::new();
        let mut index = 0usize;

        // ── Continuation: the line starts inside a construct opened above. ──
        //
        // This is the half the old single-line signature could not express. A
        // block comment, a Python triple-quoted string and a Rust raw string are
        // all able to span any number of lines, so the first thing every line
        // must do is finish whatever the line above left open.
        if !state.is_clean() {
            match state {
                LineState::BlockComment => {
                    let end = match line.find("*/") {
                        Some(offset) => offset + 2,
                        None => {
                            // The whole line is comment body; state is unchanged
                            // and the next line continues it.
                            if len > 0 {
                                spans.push(TokenSpan::new(0, len, TokenKind::BlockComment));
                            }
                            return (spans, state);
                        }
                    };
                    spans.push(TokenSpan::new(0, end, TokenKind::BlockComment));
                    index = end;
                    state = LineState::Clean;
                }
                LineState::MultiLineString | LineState::MultiLineCharString => {
                    let quote = if state == LineState::MultiLineString { "\"\"\"" } else { "'''" };
                    let end = match line.find(quote) {
                        Some(offset) => offset + quote.len(),
                        None => {
                            if len > 0 {
                                spans.push(TokenSpan::new(0, len, TokenKind::String));
                            }
                            return (spans, state);
                        }
                    };
                    spans.push(TokenSpan::new(0, end, TokenKind::String));
                    index = end;
                    state = LineState::Clean;
                }
                LineState::RawStringTick => {
                    let end = match line.find('`') {
                        Some(offset) => offset + 1,
                        None => {
                            if len > 0 {
                                spans.push(TokenSpan::new(0, len, TokenKind::String));
                            }
                            return (spans, state);
                        }
                    };
                    spans.push(TokenSpan::new(0, end, TokenKind::String));
                    index = end;
                    state = LineState::Clean;
                }
                LineState::RawString { hashes } => {
                    // A Rust raw string closes on `"` followed by `hashes` `#`.
                    let mut close = String::with_capacity(1 + hashes as usize);
                    close.push('"');
                    for _ in 0..hashes {
                        close.push('#');
                    }
                    let end = match line.find(&close) {
                        Some(offset) => offset + close.len(),
                        None => {
                            if len > 0 {
                                spans.push(TokenSpan::new(0, len, TokenKind::String));
                            }
                            return (spans, state);
                        }
                    };
                    spans.push(TokenSpan::new(0, end, TokenKind::String));
                    index = end;
                    state = LineState::Clean;
                }
                LineState::HtmlComment => {
                    let end = match line.find("-->") {
                        Some(offset) => offset + 3,
                        None => {
                            if len > 0 {
                                spans.push(TokenSpan::new(0, len, TokenKind::BlockComment));
                            }
                            return (spans, state);
                        }
                    };
                    spans.push(TokenSpan::new(0, end, TokenKind::BlockComment));
                    index = end;
                    state = LineState::Clean;
                }
                LineState::Clean => {}
            }
        }

        while index < len {
            let rest = &line[index..];
            let ch = match rest.chars().next() {
                Some(ch) => ch,
                None => break,
            };

            // `#` starts a comment (Python) or a preprocessor line (Rust/C).
            if ch == '#' {
                if self.language.uses_hash_comments() {
                    spans.push(TokenSpan::new(index, len, TokenKind::Comment));
                    break;
                }
                if self.language.supports_preprocessor() {
                    let end = if self.language == LanguageId::Rust {
                        rest.find(']').map(|offset| index + offset + 1).unwrap_or(len)
                    } else {
                        len
                    };
                    let end = end.min(len);
                    spans.push(TokenSpan::new(index, end, TokenKind::Preprocessor));
                    index = end;
                    continue;
                }
            }
            if self.language.supports_slash_comments() && rest.starts_with("//") {
                spans.push(TokenSpan::new(index, len, TokenKind::Comment));
                break;
            }
            if self.language.supports_dash_comments() && rest.starts_with("--") {
                spans.push(TokenSpan::new(index, len, TokenKind::Comment));
                break;
            }
            if self.language.supports_html_comments() && rest.starts_with("<!--") {
                match rest.find("-->") {
                    Some(offset) => {
                        let end = (index + offset + 3).min(len);
                        spans.push(TokenSpan::new(index, end, TokenKind::BlockComment));
                        index = end;
                        continue;
                    }
                    None => {
                        spans.push(TokenSpan::new(index, len, TokenKind::BlockComment));
                        return (spans, LineState::HtmlComment);
                    }
                }
            }
            // A Rust raw string: `r"…"`, `r#"…"#`, `r##"…"##`. Colours the
            // whole literal, and only spills across lines when the closing
            // delimiter is absent — which is exactly what the old signature
            // could not represent.
            if self.language == LanguageId::Rust {
                if let Some((open_len, hashes)) = rust_raw_string_open(rest) {
                    let close = raw_string_closer(hashes);
                    let end = match rest[open_len..].find(&close) {
                        Some(offset) => index + open_len + offset + close.len(),
                        None => {
                            spans.push(TokenSpan::new(index, len, TokenKind::String));
                            return (spans, LineState::RawString { hashes });
                        }
                    };
                    spans.push(TokenSpan::new(index, end.min(len), TokenKind::String));
                    index = end.min(len);
                    continue;
                }
            }
            if self.language.supports_block_comments() && rest.starts_with("/*") {
                match rest.find("*/") {
                    Some(offset) => {
                        let end = (index + offset + 2).min(len);
                        spans.push(TokenSpan::new(index, end, TokenKind::BlockComment));
                        index = end;
                        continue;
                    }
                    None => {
                        // Unterminated: the block comment continues on the next
                        // line, and saying so is the whole point of `LineState`.
                        spans.push(TokenSpan::new(index, len, TokenKind::BlockComment));
                        return (spans, LineState::BlockComment);
                    }
                }
            }

            // String and character literals, including Python triple quotes and
            // Go raw strings.
            if ch == '"' || ch == '\'' || (self.language == LanguageId::Go && ch == '`') {
                let triple_double =
                    self.language == LanguageId::Python && rest.starts_with("\"\"\"");
                let triple_single = self.language == LanguageId::Python && rest.starts_with("'''");
                let quote = if triple_double {
                    "\"\"\""
                } else if triple_single {
                    "'''"
                } else {
                    &rest[..ch.len_utf8()]
                };
                let search_from = quote.len();
                // Backslash escapes protect the delimiter in normal strings and
                // chars. Go raw strings (backticks) and Python triple quotes are
                // scanned verbatim; so is a shell single-quoted string, where a
                // backslash is literal.
                let escape_aware = quote.len() == 1
                    && ch != '`'
                    && !(self.language == LanguageId::Shell && ch == '\'');
                let found = if escape_aware {
                    let mut cursor = search_from;
                    let mut found = None;
                    while cursor < rest.len() {
                        if rest.as_bytes()[cursor] == b'\\' {
                            // Skip the backslash **and the escaped character**, whose byte length
                            // is not 1. Advancing by a literal two bytes assumed an ASCII escape,
                            // so highlighting a line such as `"a\é"` left `cursor` inside the `é`
                            // and the `rest[cursor..]` below panicked the whole frame.
                            cursor += 1;
                            cursor +=
                                rest[cursor..].chars().next().map(|c| c.len_utf8()).unwrap_or(0);
                            continue;
                        }
                        if rest[cursor..].starts_with(quote) {
                            found = Some((index + cursor + quote.len()).min(len));
                            break;
                        }
                        cursor += rest[cursor..].chars().next().map(|c| c.len_utf8()).unwrap_or(1);
                    }
                    found
                } else {
                    rest[search_from.min(rest.len())..]
                        .find(quote)
                        .map(|offset| (index + search_from + offset + quote.len()).min(len))
                };
                let end = match found {
                    Some(end) => end,
                    None => {
                        // Unterminated. A multi-line-capable literal spills into
                        // the next line; a plain one is simply unterminated and
                        // the editor must not claim a state change it cannot undo.
                        let spill = if triple_double {
                            Some(LineState::MultiLineString)
                        } else if triple_single {
                            Some(LineState::MultiLineCharString)
                        } else if ch == '`' {
                            Some(LineState::RawStringTick)
                        } else {
                            None
                        };
                        spans.push(TokenSpan::new(index, len, TokenKind::String));
                        return (spans, spill.unwrap_or(LineState::Clean));
                    }
                };
                let kind = if quote.len() == 1 && ch == '\'' && self.language.single_quote_is_char()
                {
                    TokenKind::Character
                } else {
                    TokenKind::String
                };
                spans.push(TokenSpan::new(index, end, kind));
                index = end;
                continue;
            }

            // Numeric literals, including `_` separators and type suffixes.
            if ch.is_ascii_digit() {
                let mut end = index + ch.len_utf8();
                while end < len {
                    let next = line[end..].chars().next().unwrap_or(' ');
                    if next.is_ascii_alphanumeric() || next == '.' || next == '_' {
                        end += next.len_utf8();
                    } else {
                        break;
                    }
                }
                spans.push(TokenSpan::new(index, end, TokenKind::Number));
                index = end;
                continue;
            }

            // Identifiers, with heuristics for call sites and qualified paths.
            if ch.is_alphabetic() || ch == '_' {
                let mut end = index + ch.len_utf8();
                while end < len {
                    let next = line[end..].chars().next().unwrap_or(' ');
                    if self.language.is_word_char(next) {
                        end += next.len_utf8();
                    } else {
                        break;
                    }
                }
                let word = &line[index..end];
                let followed_by_call = line[end..].trim_start().starts_with('(');
                let after_qualifier =
                    line[..index].trim_end().ends_with('.') || line[..index].ends_with("::");
                let kind = if after_qualifier {
                    TokenKind::Identifier
                } else {
                    self.word_token_kind(word, followed_by_call)
                };
                spans.push(TokenSpan::new(index, end, kind));
                index = end;
                continue;
            }

            // Whitespace carries no style.
            if ch.is_whitespace() {
                index += ch.len_utf8();
                continue;
            }

            if is_operator_char(ch) {
                let mut end = index + ch.len_utf8();
                while end < len {
                    let next = line[end..].chars().next().unwrap_or(' ');
                    if is_operator_char(next) {
                        end += next.len_utf8();
                    } else {
                        break;
                    }
                }
                spans.push(TokenSpan::new(index, end, TokenKind::Operator));
                index = end;
                continue;
            }

            // Brackets and any remaining scalar are plain text.
            spans.push(TokenSpan::new(index, index + ch.len_utf8(), TokenKind::Plain));
            index += ch.len_utf8();
        }

        (merge_adjacent(spans), state)
    }

    fn language_name(&self) -> &str {
        self.language.name()
    }
}

/// Returns the opening length and `#` count of a Rust raw string at `text`'s start.
///
/// Recognises `r"`, `r#"`, `r##"` … An identifier that merely begins with `r`
/// (for example `return`) does not match, because the character after the `r`
/// must be `#` or the quote itself.
fn rust_raw_string_open(text: &str) -> Option<(usize, u8)> {
    let bytes = text.as_bytes();
    if bytes.first() != Some(&b'r') {
        return None;
    }
    let mut hashes = 0u8;
    let mut cursor = 1usize;
    while bytes.get(cursor) == Some(&b'#') {
        hashes = hashes.saturating_add(1);
        cursor += 1;
    }
    if bytes.get(cursor) == Some(&b'"') {
        Some((cursor + 1, hashes))
    } else {
        None
    }
}

/// Builds the closing delimiter for a Rust raw string with `hashes` `#`.
fn raw_string_closer(hashes: u8) -> String {
    let mut close = String::with_capacity(1 + hashes as usize);
    close.push('"');
    for _ in 0..hashes {
        close.push('#');
    }
    close
}

/// Returns `true` for characters that form operator runs.
fn is_operator_char(ch: char) -> bool {
    matches!(
        ch,
        '+' | '-'
            | '*'
            | '/'
            | '%'
            | '='
            | '<'
            | '>'
            | '!'
            | '&'
            | '|'
            | '^'
            | '~'
            | '?'
            | ':'
            | ';'
            | ','
            | '.'
    )
}

/// Coalesces neighbouring spans that share a token kind and are contiguous.
pub(crate) fn merge_adjacent(spans: Vec<TokenSpan>) -> Vec<TokenSpan> {
    let mut merged: Vec<TokenSpan> = Vec::with_capacity(spans.len());
    for span in spans {
        if span.is_empty() {
            continue;
        }
        match merged.last_mut() {
            Some(last) if last.kind == span.kind && last.end == span.start => last.end = span.end,
            _ => merged.push(span),
        }
    }
    merged
}

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

    fn kinds(highlighter: &BuiltinHighlighter, line: &str) -> Vec<TokenKind> {
        spans_of(highlighter, line).into_iter().map(|span| span.kind).collect()
    }

    /// Runs one line from a clean state and returns just the spans.
    ///
    /// The trait is stateful, so a test that only wants "what does this line look
    /// like on its own" must pass [`LineState::Clean`]; the multi-line tests in
    /// this module call `highlight_line` directly to thread a real state.
    fn spans_of(highlighter: &BuiltinHighlighter, line: &str) -> Vec<TokenSpan> {
        highlighter.highlight_line(line, LineState::Clean).0
    }

    #[test]
    fn rust_keywords_types_and_functions_are_distinguished() {
        let highlighter = BuiltinHighlighter::new(LanguageId::Rust);
        let line = "fn main(x: u32) { }";
        let spans = spans_of(&highlighter, line);
        let tokens: Vec<(TokenKind, &str)> =
            spans.iter().map(|span| (span.kind, &line[span.start..span.end])).collect();
        assert!(tokens.contains(&(TokenKind::Keyword, "fn")));
        assert!(tokens.contains(&(TokenKind::Function, "main")));
        assert!(tokens.contains(&(TokenKind::Type, "u32")));
    }

    #[test]
    fn rust_block_and_line_comments_do_not_leak() {
        let highlighter = BuiltinHighlighter::new(LanguageId::Rust);
        let line = "let a = 1; // fn not_keyword";
        let spans = spans_of(&highlighter, line);
        let comment = spans.last().expect("comment span");
        assert_eq!(comment.kind, TokenKind::Comment);
        assert_eq!(&line[comment.start..comment.end], "// fn not_keyword");

        let block = "/* let mut */ let b = 2;";
        let spans = spans_of(&highlighter, block);
        assert_eq!(spans[0].kind, TokenKind::BlockComment);
        assert_eq!(&block[spans[0].start..spans[0].end], "/* let mut */");
    }

    #[test]
    fn string_literals_with_escapes_and_quotes_terminate_correctly() {
        let highlighter = BuiltinHighlighter::new(LanguageId::Rust);
        let line = r#"let s = "a\"b"; let c = 'x';"#;
        let spans = spans_of(&highlighter, line);
        let strings: Vec<&str> = spans
            .iter()
            .filter(|span| span.kind == TokenKind::String)
            .map(|span| &line[span.start..span.end])
            .collect();
        assert_eq!(strings.len(), 1, "escaped quote must not end the literal early");
        let chars: Vec<&str> = spans
            .iter()
            .filter(|span| span.kind == TokenKind::Character)
            .map(|span| &line[span.start..span.end])
            .collect();
        assert_eq!(chars, vec!["'x'"]);
    }

    #[test]
    fn python_uses_hash_comments_and_triple_quoted_strings() {
        let highlighter = BuiltinHighlighter::new(LanguageId::Python);
        assert_eq!(kinds(&highlighter, "# note").first(), Some(&TokenKind::Comment));
        let line = "x = \"\"\"multi word\"\"\"";
        let spans = spans_of(&highlighter, line);
        let string = spans.iter().find(|span| span.kind == TokenKind::String).expect("string");
        assert_eq!(&line[string.start..string.end], "\"\"\"multi word\"\"\"");
    }

    #[test]
    fn go_raw_strings_and_rust_attributes_are_recognized() {
        let go = BuiltinHighlighter::new(LanguageId::Go);
        let raw = "s := `back \\ tick`";
        let spans = spans_of(&go, raw);
        let string = spans.iter().find(|span| span.kind == TokenKind::String).expect("raw string");
        assert_eq!(&raw[string.start..string.end], "`back \\ tick`");

        let rust = BuiltinHighlighter::new(LanguageId::Rust);
        let attribute = "#[derive(Debug)]";
        let spans = spans_of(&rust, attribute);
        assert_eq!(spans[0].kind, TokenKind::Preprocessor);
        assert_eq!(&attribute[spans[0].start..spans[0].end], "#[derive(Debug)]");
    }

    #[test]
    fn qualified_paths_are_not_mistaken_for_functions() {
        let highlighter = BuiltinHighlighter::new(LanguageId::Rust);
        let line = "std::mem::size_of::<u32>()";
        let spans = spans_of(&highlighter, line);
        assert!(
            !spans.iter().any(|span| span.kind == TokenKind::Function),
            "qualified path segments must stay identifiers"
        );
    }

    #[test]
    fn spans_always_cover_the_line_in_order_without_overlap() {
        let highlighter = BuiltinHighlighter::new(LanguageId::Rust);
        let line = r#"fn f() -> Vec<String> { let v = vec![1.5, 2]; } // done"#;
        let spans = spans_of(&highlighter, line);
        let mut previous_end = 0usize;
        for span in &spans {
            assert!(span.start >= previous_end, "spans must not overlap or regress");
            assert!(line.is_char_boundary(span.start));
            assert!(line.is_char_boundary(span.end));
            previous_end = span.end;
        }
        assert_eq!(spans.last().map(|span| span.end), Some(line.len()));
    }

    #[test]
    fn unicode_identifiers_do_not_split_characters() {
        let highlighter = BuiltinHighlighter::new(LanguageId::Rust);
        let line = "let 变量 = \"值\";";
        let spans = spans_of(&highlighter, line);
        for span in &spans {
            assert!(line.is_char_boundary(span.start), "span start must be a char boundary");
            assert!(line.is_char_boundary(span.end), "span end must be a char boundary");
        }
    }

    #[test]
    fn plain_text_language_produces_no_keyword_tokens() {
        let highlighter = BuiltinHighlighter::new(LanguageId::PlainText);
        let spans = spans_of(&highlighter, "fn main() {}");
        assert!(!spans.iter().any(|span| span.kind == TokenKind::Keyword));
        assert_eq!(highlighter.language_name(), "Plain Text");
    }

    #[test]
    fn empty_line_produces_no_spans() {
        let highlighter = BuiltinHighlighter::new(LanguageId::Rust);
        assert!(spans_of(&highlighter, "").is_empty());
    }

    /// A backslash escape may protect a **multi-byte** character.
    ///
    /// The string scanner advanced `cursor += 2` on a backslash, assuming a one-byte escaped
    /// character. Highlighting a line such as `"a\é"` therefore left the cursor inside the `é`
    /// and the next `rest[cursor..]` panicked — on every frame that line was visible. The skip is
    /// now the backslash's own byte plus the escaped character's real UTF-8 length.
    #[test]
    fn an_escape_may_protect_a_multibyte_character() {
        let highlighter = BuiltinHighlighter::new(LanguageId::Rust);
        for line in ["\"a\\é\"", "\"x\\世\"", "\"\\🎉\"", "'\\é'"] {
            let spans = spans_of(&highlighter, line);
            for span in &spans {
                assert!(
                    line.is_char_boundary(span.start) && line.is_char_boundary(span.end),
                    "span {span:?} must sit on character boundaries of {line:?}"
                );
            }
        }
    }

    // ── Cross-line state (the whole reason `LineState` exists) ───────────────

    /// A block comment opened on one line must keep the **next** line commented.
    ///
    /// This is the defect the state-carrying seam fixes. With the old single-line
    /// signature the second line was lexed as fresh code, so `let x = 1;` inside a
    /// comment was coloured as a keyword and an identifier — the file *looked*
    /// broken even though the text was untouched.
    #[test]
    fn a_block_comment_keeps_the_next_line_commented() {
        let highlighter = BuiltinHighlighter::new(LanguageId::Rust);
        let (first, state) = highlighter.highlight_line("/* start", LineState::Clean);
        assert_eq!(state, LineState::BlockComment, "the comment must stay open");
        assert_eq!(first[0].kind, TokenKind::BlockComment);

        let (second, state) = highlighter.highlight_line("let x = 1;", state);
        assert_eq!(state, LineState::BlockComment, "still no `*/` seen");
        assert!(
            second.iter().all(|span| span.kind == TokenKind::BlockComment),
            "every span of a comment body line is a comment, got {second:?}"
        );

        let (third, state) = highlighter.highlight_line("end */ fn main() {}", state);
        assert_eq!(state, LineState::Clean, "the comment closed here");
        let kinds: Vec<TokenKind> = third.iter().map(|span| span.kind).collect();
        assert!(kinds.contains(&TokenKind::BlockComment), "the lead-in is comment");
        assert!(kinds.contains(&TokenKind::Keyword), "code after `*/` is lexed again");
    }

    /// A Python triple-quoted string spans lines the same way.
    #[test]
    fn a_python_triple_quote_keeps_the_next_line_a_string() {
        let highlighter = BuiltinHighlighter::new(LanguageId::Python);
        let (_, state) = highlighter.highlight_line("s = \"\"\"start", LineState::Clean);
        assert_eq!(state, LineState::MultiLineString);

        let (body, state) = highlighter.highlight_line("def not_code():", state);
        assert_eq!(state, LineState::MultiLineString);
        assert!(
            body.iter().all(|span| span.kind == TokenKind::String),
            "the body is string content, not code, got {body:?}"
        );

        let (_, state) = highlighter.highlight_line("end\"\"\"", state);
        assert_eq!(state, LineState::Clean);
    }

    /// A Rust raw string spans lines, and its `#` count must be honoured.
    ///
    /// `r#"…"#` closes on `"#`, not on a bare `"`. Losing the count would make
    /// the lexer end the string a `#` too early and colour the rest as code.
    #[test]
    fn a_rust_raw_string_spans_lines_and_keeps_its_hash_count() {
        let highlighter = BuiltinHighlighter::new(LanguageId::Rust);
        let (first, state) = highlighter.highlight_line("let s = r#\"a", LineState::Clean);
        assert_eq!(state, LineState::RawString { hashes: 1 });
        assert!(first.iter().any(|span| span.kind == TokenKind::String));

        // A bare quote inside the raw string must NOT close it.
        let (body, state) = highlighter.highlight_line("let x = \" still raw", state);
        assert_eq!(state, LineState::RawString { hashes: 1 }, "a bare quote cannot close r#\"");
        assert!(body.iter().all(|span| span.kind == TokenKind::String));

        let (_, state) = highlighter.highlight_line("done\"#;", state);
        assert_eq!(state, LineState::Clean);
    }

    /// A single-quoted string in the C family does **not** spill across lines.
    ///
    /// `rust_raw_string_open` also has to not fire on an identifier that merely
    /// starts with `r`; `return` must lex as a keyword, not as the start of a raw
    /// string.
    #[test]
    fn a_bare_quote_does_not_open_a_multi_line_construct() {
        let highlighter = BuiltinHighlighter::new(LanguageId::Rust);
        let (_, state) = highlighter.highlight_line("let c = 'a", LineState::Clean);
        assert_eq!(state, LineState::Clean, "an unterminated char is not a state change");

        let kinds = kinds(&highlighter, "return value;");
        assert!(kinds.contains(&TokenKind::Keyword), "`return` is a keyword: {kinds:?}");
        assert!(!kinds.contains(&TokenKind::String), "`return` opens no raw string");
    }

    /// An empty line inside a construct must not clear the state.
    #[test]
    fn an_empty_line_inside_a_comment_keeps_it_open() {
        let highlighter = BuiltinHighlighter::new(LanguageId::Rust);
        let (_, state) = highlighter.highlight_line("/*", LineState::Clean);
        let (spans, state) = highlighter.highlight_line("", state);
        assert!(spans.is_empty());
        assert_eq!(state, LineState::BlockComment);
    }

    /// Every language the editor advertises must classify its own comments and
    /// strings, which is the defect the seven-language set had: Java/C++ fell into
    /// the C family and SQL/HTML had no rule at all.
    #[test]
    fn the_common_languages_have_their_own_comment_and_string_rules() {
        let java = BuiltinHighlighter::new(LanguageId::Java);
        let spans = kinds(&java, "int x = 1; // note");
        assert_eq!(spans.last(), Some(&TokenKind::Comment));

        let cpp = BuiltinHighlighter::new(LanguageId::Cpp);
        let spans = kinds(&cpp, "/* note */ auto x = 1;");
        assert_eq!(spans.first(), Some(&TokenKind::BlockComment));

        let sql = BuiltinHighlighter::new(LanguageId::Sql);
        let spans = kinds(&sql, "select 'x' -- note");
        assert_eq!(spans.last(), Some(&TokenKind::Comment));
        assert!(spans.contains(&TokenKind::String), "single quotes are strings in SQL");

        let yaml = BuiltinHighlighter::new(LanguageId::Yaml);
        assert_eq!(kinds(&yaml, "key: value # note").last(), Some(&TokenKind::Comment));

        let json = BuiltinHighlighter::new(LanguageId::Json);
        assert!(!kinds(&json, "{\"a\": true}").contains(&TokenKind::Comment));
    }

    /// An HTML comment spans lines and must keep the following line commented.
    #[test]
    fn an_html_comment_spans_lines() {
        let highlighter = BuiltinHighlighter::new(LanguageId::Html);
        let (_, state) = highlighter.highlight_line("<!-- start", LineState::Clean);
        assert_eq!(state, LineState::HtmlComment);
        let (spans, state) = highlighter.highlight_line("still a comment -->", state);
        assert_eq!(state, LineState::Clean);
        assert!(spans.iter().all(|span| span.kind == TokenKind::BlockComment));
    }

    /// Single quotes in JavaScript are strings, not character literals.
    #[test]
    fn javascript_single_quotes_are_strings() {
        let highlighter = BuiltinHighlighter::new(LanguageId::JavaScript);
        let spans = kinds(&highlighter, "const a = 'x';");
        assert!(spans.contains(&TokenKind::String));
        assert!(!spans.contains(&TokenKind::Character));
    }

    /// The keyword and type tables are binary-searched, so every language's list must be
    /// in byte order. This pins the invariant that makes the lookup valid — without it a
    /// new keyword appended out of order would silently stop highlighting (J-P07).
    #[test]
    fn keyword_tables_are_sorted() {
        const LANGUAGES: &[LanguageId] = &[
            LanguageId::Rust,
            LanguageId::Python,
            LanguageId::JavaScript,
            LanguageId::Go,
            LanguageId::CLike,
            LanguageId::Java,
            LanguageId::CSharp,
            LanguageId::Cpp,
            LanguageId::Kotlin,
            LanguageId::Swift,
            LanguageId::Html,
            LanguageId::Xml,
            LanguageId::Css,
            LanguageId::Json,
            LanguageId::Yaml,
            LanguageId::Toml,
            LanguageId::Shell,
            LanguageId::Sql,
            LanguageId::Markdown,
            LanguageId::PlainText,
        ];
        for language in LANGUAGES {
            let keywords = language.keywords();
            assert!(
                keywords.windows(2).all(|pair| pair[0] <= pair[1]),
                "{:?} keywords are not sorted",
                language
            );
            let types = language.type_names();
            assert!(
                types.windows(2).all(|pair| pair[0] <= pair[1]),
                "{:?} type names are not sorted",
                language
            );
        }
    }
}