dioxus-code 0.1.0

Syntax-highlighted code blocks for Dioxus.
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
//! Advanced building blocks for custom syntax-highlighted renderers.
//!
//! Most users should use [`Code()`](crate::Code()). This module exposes the
//! lower-level source, span, segment, and theme helpers used by companion
//! components such as `dioxus-code-editor`.
//!
//! ```rust
//! use dioxus_code::Language;
//! use dioxus_code::advanced::{HighlightSpan, HighlightedSource};
//! static SPANS: &[HighlightSpan] = &[HighlightSpan::new(0..2, "k")];
//! let src = HighlightedSource::from_static_parts("fn main() {}", Language::Rust, SPANS);
//! assert_eq!(src.spans().len(), 1);
//! ```

use super::*;
use std::{borrow::Cow, fmt, ops::Range};

/// A typed error produced while preparing runtime syntax highlighting.
///
/// These errors are recoverable for renderers: callers can surface the error
/// and render the original source as plaintext.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum HighlightError {
    /// The tree-sitter parser rejected the selected grammar.
    GrammarLoad {
        /// The language whose grammar failed to load.
        language: Language,
        /// The parser's diagnostic message.
        message: String,
    },
    /// The tree-sitter highlights query failed to compile.
    Query {
        /// The language whose query failed.
        language: Language,
        /// Zero-based query row where the error was reported.
        row: usize,
        /// Zero-based query column where the error was reported.
        column: usize,
        /// Byte offset where the error was reported.
        offset: usize,
        /// The query error kind.
        kind: HighlightQueryErrorKind,
        /// The query compiler's diagnostic message.
        message: String,
    },
    /// Tree-sitter failed to parse the source.
    Parse {
        /// The language being parsed.
        language: Language,
    },
    /// [`Buffer::edit`] received offsets that are out of bounds or not on
    /// UTF-8 character boundaries.
    ///
    /// The buffer's state is unchanged when this error is returned.
    InvalidEdit {
        /// First byte the caller said changed.
        start_byte: usize,
        /// One past the last byte of the replaced region in the previous source.
        old_end_byte: usize,
        /// One past the last byte of the inserted region in the new source.
        new_end_byte: usize,
        /// Length of the previous source, for context.
        old_len: usize,
        /// Length of the new source, for context.
        new_len: usize,
    },
}

impl HighlightError {
    #[cfg(feature = "runtime")]
    fn grammar_load(language: Language, error: arborium_tree_sitter::LanguageError) -> Self {
        Self::GrammarLoad {
            language,
            message: error.to_string(),
        }
    }

    #[cfg(feature = "runtime")]
    fn query(language: Language, error: arborium_tree_sitter::QueryError) -> Self {
        Self::Query {
            language,
            row: error.row,
            column: error.column,
            offset: error.offset,
            kind: error.kind.into(),
            message: error.message,
        }
    }
}

impl fmt::Display for HighlightError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::GrammarLoad { language, message } => {
                write!(
                    f,
                    "failed to load grammar for {}: {}",
                    language.slug(),
                    message
                )
            }
            Self::Query {
                language,
                row,
                column,
                kind,
                message,
                ..
            } => {
                write!(
                    f,
                    "query error for {} at {}:{} ({}): {}",
                    language.slug(),
                    row + 1,
                    column + 1,
                    kind,
                    message
                )
            }
            Self::Parse { language } => {
                write!(f, "tree-sitter parse failed for {}", language.slug())
            }
            Self::InvalidEdit {
                start_byte,
                old_end_byte,
                new_end_byte,
                old_len,
                new_len,
            } => {
                write!(
                    f,
                    "invalid edit: start_byte {start_byte}, old_end_byte {old_end_byte}, \
                     new_end_byte {new_end_byte} (old_len {old_len}, new_len {new_len})"
                )
            }
        }
    }
}

impl std::error::Error for HighlightError {}

/// The category of a tree-sitter highlights query compilation error.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum HighlightQueryErrorKind {
    /// Invalid query syntax.
    Syntax,
    /// Invalid node type.
    NodeType,
    /// Invalid field name.
    Field,
    /// Invalid capture name.
    Capture,
    /// Invalid predicate.
    Predicate,
    /// Impossible query pattern structure.
    Structure,
    /// Query and grammar language mismatch.
    Language,
}

impl fmt::Display for HighlightQueryErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let kind = match self {
            Self::Syntax => "syntax",
            Self::NodeType => "node type",
            Self::Field => "field",
            Self::Capture => "capture",
            Self::Predicate => "predicate",
            Self::Structure => "structure",
            Self::Language => "language",
        };
        f.write_str(kind)
    }
}

#[cfg(feature = "runtime")]
impl From<arborium_tree_sitter::QueryErrorKind> for HighlightQueryErrorKind {
    fn from(kind: arborium_tree_sitter::QueryErrorKind) -> Self {
        match kind {
            arborium_tree_sitter::QueryErrorKind::Syntax => Self::Syntax,
            arborium_tree_sitter::QueryErrorKind::NodeType => Self::NodeType,
            arborium_tree_sitter::QueryErrorKind::Field => Self::Field,
            arborium_tree_sitter::QueryErrorKind::Capture => Self::Capture,
            arborium_tree_sitter::QueryErrorKind::Predicate => Self::Predicate,
            arborium_tree_sitter::QueryErrorKind::Structure => Self::Structure,
            arborium_tree_sitter::QueryErrorKind::Language => Self::Language,
        }
    }
}

/// A highlighted source string with metadata and token spans.
///
/// ```rust
/// use dioxus_code::Language;
/// use dioxus_code::advanced::HighlightedSource;
/// let src = HighlightedSource::from_static_parts("let x = 1;", Language::Rust, &[]);
/// assert_eq!(src.source(), "let x = 1;");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HighlightedSource {
    source: Cow<'static, str>,
    language: Language,
    spans: Cow<'static, [HighlightSpan]>,
}

impl HighlightedSource {
    #[cfg(feature = "runtime")]
    pub(crate) fn from_owned_parts(
        source: String,
        language: Language,
        spans: Vec<HighlightSpan>,
    ) -> Self {
        Self {
            source: Cow::Owned(source),
            language,
            spans: Cow::Owned(spans),
        }
    }

    /// Build highlighted source from static text and spans.
    ///
    /// This is mainly useful for compile-time highlighters and macro output.
    ///
    /// ```rust
    /// use dioxus_code::Language;
    /// use dioxus_code::advanced::HighlightedSource;
    /// let src = HighlightedSource::from_static_parts("let x = 1;", Language::Rust, &[]);
    /// assert_eq!(src.language(), Language::Rust);
    /// ```
    pub const fn from_static_parts(
        source: &'static str,
        language: Language,
        spans: &'static [HighlightSpan],
    ) -> Self {
        Self {
            source: Cow::Borrowed(source),
            language,
            spans: Cow::Borrowed(spans),
        }
    }

    #[cfg(feature = "runtime")]
    pub(crate) fn plaintext(source: impl Into<Cow<'static, str>>, language: Language) -> Self {
        Self {
            source: source.into(),
            language,
            spans: Cow::Borrowed(&[]),
        }
    }

    /// The raw source text.
    ///
    /// ```rust
    /// use dioxus_code::Language;
    /// use dioxus_code::advanced::HighlightedSource;
    /// let src = HighlightedSource::from_static_parts("hello", Language::Rust, &[]);
    /// assert_eq!(src.source(), "hello");
    /// ```
    pub fn source(&self) -> &str {
        self.source.as_ref()
    }

    /// The detected or explicitly set language, if any.
    ///
    /// ```rust
    /// use dioxus_code::Language;
    /// use dioxus_code::advanced::HighlightedSource;
    /// let src = HighlightedSource::from_static_parts("", Language::Rust, &[]);
    /// assert_eq!(src.language(), Language::Rust);
    /// ```
    pub const fn language(&self) -> Language {
        self.language
    }

    /// The highlight spans covering the source.
    ///
    /// ```rust
    /// use dioxus_code::Language;
    /// use dioxus_code::advanced::HighlightedSource;
    /// let src = HighlightedSource::from_static_parts("", Language::Rust, &[]);
    /// assert!(src.spans().is_empty());
    /// ```
    pub fn spans(&self) -> &[HighlightSpan] {
        self.spans.as_ref()
    }

    /// Split the source into renderable highlighted segments.
    ///
    /// ```rust
    /// use dioxus_code::Language;
    /// use dioxus_code::advanced::HighlightedSource;
    /// let src = HighlightedSource::from_static_parts("hello", Language::Rust, &[]);
    /// assert_eq!(src.segments().len(), 1);
    /// ```
    pub fn segments(&self) -> Vec<HighlightSegment<'_>> {
        highlighted_segments(self.source(), self.spans())
    }

    pub(crate) fn trimmed_segments(&self) -> Vec<HighlightSegment<'_>> {
        highlighted_segments(self.source().trim_end_matches('\n'), self.spans())
    }

    /// Split the source into highlighted lines.
    ///
    /// Trailing empty lines are preserved so editor renderers can keep line
    /// numbers and input rows aligned with the original source text.
    ///
    /// ```rust
    /// use dioxus_code::Language;
    /// use dioxus_code::advanced::HighlightedSource;
    /// let src = HighlightedSource::from_static_parts("a\nb", Language::Rust, &[]);
    /// assert_eq!(src.lines().len(), 2);
    /// ```
    pub fn lines(&self) -> Vec<Vec<HighlightSegment<'_>>> {
        highlighted_lines(self.source(), self.spans())
    }
}

/// A highlight span attached to a byte range of source text.
///
/// ```rust
/// use dioxus_code::advanced::HighlightSpan;
/// let span = HighlightSpan::new(0..2, "k");
/// assert_eq!(span.tag(), "k");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HighlightSpan {
    start: u32,
    end: u32,
    tag: &'static str,
}

impl HighlightSpan {
    /// Create a highlight span.
    ///
    /// ```rust
    /// use dioxus_code::advanced::HighlightSpan;
    /// let span = HighlightSpan::new(0..2, "k");
    /// assert_eq!(span.range(), 0..2);
    /// ```
    pub const fn new(range: Range<u32>, tag: &'static str) -> Self {
        Self {
            start: range.start,
            end: range.end,
            tag,
        }
    }

    /// Create a highlight span from explicit byte offsets.
    ///
    /// ```rust
    /// use dioxus_code::advanced::HighlightSpan;
    /// let span = HighlightSpan::from_offsets(0, 2, "k");
    /// assert_eq!(span.start(), 0);
    /// ```
    pub const fn from_offsets(start: u32, end: u32, tag: &'static str) -> Self {
        Self { start, end, tag }
    }

    /// Byte offset, inclusive, of the span's start in the source.
    ///
    /// ```rust
    /// use dioxus_code::advanced::HighlightSpan;
    /// assert_eq!(HighlightSpan::new(3..5, "k").start(), 3);
    /// ```
    pub const fn start(self) -> u32 {
        self.start
    }

    /// Byte offset, exclusive, of the span's end in the source.
    ///
    /// ```rust
    /// use dioxus_code::advanced::HighlightSpan;
    /// assert_eq!(HighlightSpan::new(3..5, "k").end(), 5);
    /// ```
    pub const fn end(self) -> u32 {
        self.end
    }

    /// Byte range covered by this span.
    ///
    /// ```rust
    /// use dioxus_code::advanced::HighlightSpan;
    /// assert_eq!(HighlightSpan::new(3..5, "k").range(), 3..5);
    /// ```
    pub const fn range(self) -> Range<u32> {
        self.start..self.end
    }

    /// Highlight tag class suffix, for example `"k"` for keywords.
    ///
    /// ```rust
    /// use dioxus_code::advanced::HighlightSpan;
    /// assert_eq!(HighlightSpan::new(0..2, "k").tag(), "k");
    /// ```
    pub const fn tag(self) -> &'static str {
        self.tag
    }

    #[cfg(feature = "runtime")]
    pub(crate) fn set_end(&mut self, end: u32) {
        self.end = end;
    }
}

/// A borrowed render segment with an optional highlight tag.
///
/// ```rust
/// use dioxus_code::advanced::HighlightSegment;
/// let segment = HighlightSegment::new("fn", Some("k"));
/// assert_eq!(segment.text(), "fn");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HighlightSegment<'a> {
    text: &'a str,
    tag: Option<&'static str>,
}

impl<'a> HighlightSegment<'a> {
    /// Create a highlighted segment.
    ///
    /// ```rust
    /// use dioxus_code::advanced::HighlightSegment;
    /// let _segment = HighlightSegment::new("fn", Some("k"));
    /// ```
    pub const fn new(text: &'a str, tag: Option<&'static str>) -> Self {
        Self { text, tag }
    }

    /// The source text for this segment.
    ///
    /// ```rust
    /// use dioxus_code::advanced::HighlightSegment;
    /// assert_eq!(HighlightSegment::new("fn", Some("k")).text(), "fn");
    /// ```
    pub const fn text(self) -> &'a str {
        self.text
    }

    /// Highlight tag class suffix, when this segment is highlighted.
    ///
    /// ```rust
    /// use dioxus_code::advanced::HighlightSegment;
    /// assert_eq!(HighlightSegment::new("fn", Some("k")).tag(), Some("k"));
    /// ```
    pub const fn tag(self) -> Option<&'static str> {
        self.tag
    }
}

fn highlighted_segments<'a>(source: &'a str, spans: &[HighlightSpan]) -> Vec<HighlightSegment<'a>> {
    if spans.is_empty() {
        return vec![HighlightSegment::new(source, None)];
    }

    let mut spans = spans.to_vec();
    spans.sort_by(|a, b| a.start.cmp(&b.start).then_with(|| b.end.cmp(&a.end)));

    let mut events = Vec::with_capacity(spans.len() * 2);
    for (index, span) in spans.iter().enumerate() {
        events.push((span.start, true, index));
        events.push((span.end, false, index));
    }
    events.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));

    let mut segments = Vec::new();
    let mut last_pos = 0;
    let mut stack: Vec<usize> = Vec::new();

    for (pos, is_start, span_index) in events {
        let pos = pos as usize;
        if pos > last_pos && pos <= source.len() {
            segments.push(HighlightSegment::new(
                &source[last_pos..pos],
                stack.last().map(|&i| spans[i].tag),
            ));
            last_pos = pos;
        }

        if is_start {
            stack.push(span_index);
        } else if let Some(index) = stack.iter().rposition(|&i| i == span_index) {
            stack.remove(index);
        }
    }

    if last_pos < source.len() {
        segments.push(HighlightSegment::new(
            &source[last_pos..],
            stack.last().map(|&i| spans[i].tag),
        ));
    }

    segments
}

fn highlighted_lines<'a>(
    source: &'a str,
    spans: &[HighlightSpan],
) -> Vec<Vec<HighlightSegment<'a>>> {
    let mut lines = vec![Vec::new()];

    for segment in highlighted_segments(source, spans) {
        push_line_segments(&mut lines, segment);
    }

    lines
}

fn push_line_segments<'a>(
    lines: &mut Vec<Vec<HighlightSegment<'a>>>,
    segment: HighlightSegment<'a>,
) {
    let mut text = segment.text;

    loop {
        if let Some(newline) = text.find('\n') {
            let before_newline = &text[..newline];
            if !before_newline.is_empty() {
                lines
                    .last_mut()
                    .unwrap()
                    .push(HighlightSegment::new(before_newline, segment.tag));
            }
            lines.push(Vec::new());
            text = &text[newline + 1..];
        } else {
            if !text.is_empty() {
                lines
                    .last_mut()
                    .unwrap()
                    .push(HighlightSegment::new(text, segment.tag));
            }
            break;
        }
    }
}

/// Props for [`TokenSpan`].
///
/// ```rust
/// use dioxus_code::advanced::TokenSpanProps;
/// let _props = TokenSpanProps { text: "fn".to_string(), tag: "k" };
/// ```
#[derive(Props, Clone, PartialEq)]
pub struct TokenSpanProps {
    /// The literal text rendered inside the span.
    #[props(into)]
    pub text: String,
    /// Highlight tag class suffix used to derive the span's class name.
    pub tag: &'static str,
}

/// Render one highlighted token as `<span class="a-{tag}">{text}</span>`.
///
/// ```rust
/// use dioxus::prelude::*;
/// use dioxus_code::advanced::TokenSpan;
///
/// fn _example() -> Element {
///     rsx! { TokenSpan { text: "fn", tag: "k" } }
/// }
/// ```
#[component]
pub fn TokenSpan(props: TokenSpanProps) -> Element {
    let class = format!("a-{}", props.tag);
    rsx! {
        span {
            class,
            "{props.text}"
        }
    }
}

/// A live `(text, grammar)` pair you can edit, reparse, and snapshot.
///
/// `Buffer` owns the source string, the parse tree, and the highlight spans as
/// a single coherent unit. [`edit`](Self::edit) applies an incremental edit
/// (reusing the cached parse tree); [`replace`](Self::replace) swaps the source
/// wholesale; [`set_language`](Self::set_language) switches grammars and
/// reparses. After any successful mutation, [`source`](Self::source),
/// [`spans`](Self::spans), and [`lines`](Self::lines) reflect the new state.
///
/// Available with the `runtime` feature. Hold one per editor instance (e.g.
/// inside `use_hook`). Highlighting operations return [`HighlightError`] when
/// grammar setup or parsing fails.
///
/// ```rust
/// use dioxus_code::Language;
/// use dioxus_code::advanced::Buffer;
/// let buffer = Buffer::new(Language::Rust, "fn main() {}").expect("rust grammar loads");
/// assert_eq!(buffer.language(), Language::Rust);
/// assert!(!buffer.spans().is_empty());
/// ```
#[cfg(feature = "runtime")]
#[cfg_attr(docsrs, doc(cfg(feature = "runtime")))]
pub struct Buffer {
    parser: arborium_tree_sitter::Parser,
    cursor: arborium_tree_sitter::QueryCursor,
    language: Language,
    incremental: IncrementalGrammar,
    tree: arborium_tree_sitter::Tree,
    source: String,
    spans: Vec<HighlightSpan>,
}

#[cfg(feature = "runtime")]
struct IncrementalGrammar {
    query: arborium_tree_sitter::Query,
}

#[cfg(feature = "runtime")]
#[cfg_attr(docsrs, doc(cfg(feature = "runtime")))]
impl Buffer {
    /// Create a buffer for `language`, parse `source`, and collect spans.
    ///
    /// ```rust
    /// use dioxus_code::Language;
    /// use dioxus_code::advanced::Buffer;
    /// let buffer = Buffer::new(Language::Rust, "fn main() {}").expect("rust grammar loads");
    /// assert_eq!(buffer.source(), "fn main() {}");
    /// ```
    pub fn new(language: Language, source: impl ToString) -> Result<Self, HighlightError> {
        let source = source.to_string();
        let (mut parser, incremental) = Self::parser_for(language)?;
        let mut cursor = arborium_tree_sitter::QueryCursor::new();
        let (tree, spans) = Self::parse_source(
            language,
            &mut parser,
            &incremental.query,
            &mut cursor,
            &source,
            None,
        )?;

        Ok(Self {
            parser,
            cursor,
            language,
            incremental,
            tree,
            source,
            spans,
        })
    }

    /// Replace the source wholesale and reparse from scratch.
    ///
    /// Use this when the new text is unrelated to the old (e.g. loading a
    /// different file). For keystroke-level edits, prefer [`edit`](Self::edit)
    /// — it reuses the cached parse tree.
    ///
    /// ```rust
    /// use dioxus_code::Language;
    /// use dioxus_code::advanced::Buffer;
    /// let mut buffer = Buffer::new(Language::Rust, "fn old() {}").expect("rust grammar loads");
    /// buffer.replace("fn new() {}").expect("rust parses");
    /// assert_eq!(buffer.source(), "fn new() {}");
    /// ```
    pub fn replace(&mut self, source: impl ToString) -> Result<(), HighlightError> {
        let source = source.to_string();
        let (tree, spans) = Self::parse_source(
            self.language,
            &mut self.parser,
            &self.incremental.query,
            &mut self.cursor,
            &source,
            None,
        )?;

        self.source = source;
        self.tree = tree;
        self.spans = spans;
        Ok(())
    }

    /// Apply an incremental edit and reparse, reusing the cached parse tree.
    ///
    /// `new_source` must be the full text *after* the edit. `edit` describes
    /// the byte range that changed — its `start_byte` / `old_end_byte` index
    /// into the buffer's previous source, and `new_end_byte` indexes into
    /// `new_source`. If the edit is malformed, [`HighlightError::InvalidEdit`]
    /// is returned and the buffer is left unchanged. Validation is limited to
    /// bounds and UTF-8 character boundaries; callers are responsible for
    /// passing an edit range that matches the unchanged prefix and suffix.
    ///
    /// ```rust
    /// use dioxus_code::Language;
    /// use dioxus_code::advanced::{Buffer, SourceEdit};
    /// let mut buffer = Buffer::new(Language::Rust, "fn main() { 1 }").expect("rust grammar loads");
    /// buffer.edit(
    ///     SourceEdit { start_byte: 12, old_end_byte: 13, new_end_byte: 14 },
    ///     "fn main() { 22 }",
    /// ).expect("rust parses");
    /// assert_eq!(buffer.source(), "fn main() { 22 }");
    /// ```
    pub fn edit(
        &mut self,
        edit: SourceEdit,
        new_source: impl ToString,
    ) -> Result<(), HighlightError> {
        let new_source: String = new_source.to_string();
        let input_edit = edit.into_input_edit(&self.source, &new_source)?;

        let mut old_tree = self.tree.clone();
        old_tree.edit(&input_edit);
        let (tree, spans) = Self::parse_source(
            self.language,
            &mut self.parser,
            &self.incremental.query,
            &mut self.cursor,
            &new_source,
            Some(&old_tree),
        )?;

        self.source = new_source;
        self.tree = tree;
        self.spans = spans;
        Ok(())
    }

    /// Switch grammars and reparse the current source.
    ///
    /// No-op when the new language matches the current one.
    ///
    /// ```rust
    /// use dioxus_code::Language;
    /// use dioxus_code::advanced::Buffer;
    /// let mut buffer = Buffer::new(Language::Rust, "fn main() {}").expect("rust grammar loads");
    /// buffer.set_language(Language::Rust).expect("rust grammar loads");
    /// assert_eq!(buffer.language(), Language::Rust);
    /// ```
    pub fn set_language(&mut self, language: Language) -> Result<(), HighlightError> {
        if self.language == language {
            return Ok(());
        }
        let (mut parser, incremental) = Self::parser_for(language)?;
        let (tree, spans) = Self::parse_source(
            language,
            &mut parser,
            &incremental.query,
            &mut self.cursor,
            &self.source,
            None,
        )?;

        self.parser = parser;
        self.incremental = incremental;
        self.language = language;
        self.tree = tree;
        self.spans = spans;
        Ok(())
    }

    /// The current source text.
    pub fn source(&self) -> &str {
        &self.source
    }

    /// The grammar this buffer is parsing with.
    pub const fn language(&self) -> Language {
        self.language
    }

    /// Highlight spans covering the current source.
    pub fn spans(&self) -> &[HighlightSpan] {
        &self.spans
    }

    /// Split the source into renderable highlighted segments.
    pub fn segments(&self) -> Vec<HighlightSegment<'_>> {
        highlighted_segments(&self.source, &self.spans)
    }

    /// Split the source into highlighted lines, preserving trailing empty lines.
    pub fn lines(&self) -> Vec<Vec<HighlightSegment<'_>>> {
        highlighted_lines(&self.source, &self.spans)
    }

    /// Snapshot the buffer as an immutable [`HighlightedSource`].
    ///
    /// Useful for handing off to [`Code()`](crate::Code()) or any consumer
    /// that takes the frozen snapshot type.
    pub fn highlighted(&self) -> HighlightedSource {
        HighlightedSource::from_owned_parts(self.source.clone(), self.language, self.spans.clone())
    }

    fn parser_for(
        language: Language,
    ) -> Result<(arborium_tree_sitter::Parser, IncrementalGrammar), HighlightError> {
        let mut parser = arborium_tree_sitter::Parser::new();
        let (language_fn, highlights_query) = grammar_for(language);
        let ts_language: arborium_tree_sitter::Language = language_fn.into();
        if let Err(error) = parser.set_language(&ts_language) {
            return Err(HighlightError::grammar_load(language, error));
        }

        match arborium_tree_sitter::Query::new(&ts_language, highlights_query) {
            Ok(query) => Ok((parser, IncrementalGrammar { query })),
            Err(error) => Err(HighlightError::query(language, error)),
        }
    }

    fn parse_source(
        language: Language,
        parser: &mut arborium_tree_sitter::Parser,
        query: &arborium_tree_sitter::Query,
        cursor: &mut arborium_tree_sitter::QueryCursor,
        source: &str,
        old_tree: Option<&arborium_tree_sitter::Tree>,
    ) -> Result<(arborium_tree_sitter::Tree, Vec<HighlightSpan>), HighlightError> {
        match parser.parse(source, old_tree) {
            Some(tree) => {
                let spans = collect_spans(query, cursor, &tree, source);
                Ok((tree, spans))
            }
            None => Err(HighlightError::Parse { language }),
        }
    }
}

#[cfg(feature = "runtime")]
fn collect_spans(
    query: &arborium_tree_sitter::Query,
    cursor: &mut arborium_tree_sitter::QueryCursor,
    tree: &arborium_tree_sitter::Tree,
    source: &str,
) -> Vec<HighlightSpan> {
    use arborium_tree_sitter::StreamingIterator;

    let bytes = source.as_bytes();
    let capture_names = query.capture_names();
    let mut raw: Vec<RawHighlightSpan> = Vec::new();

    let mut matches = cursor.matches(query, tree.root_node(), bytes);
    while let Some(m) = matches.next() {
        for capture in m.captures {
            let name = capture_names[capture.index as usize];
            if name.starts_with('_') || name.starts_with("injection.") {
                continue;
            }
            raw.push(RawHighlightSpan {
                start: capture.node.start_byte() as u32,
                end: capture.node.end_byte() as u32,
                tag: arborium_theme::tag_for_capture(name),
                pattern_index: m.pattern_index as u32,
            });
        }
    }

    normalize_spans(raw)
}

#[cfg(feature = "runtime")]
fn grammar_for(language: Language) -> (arborium_tree_sitter::LanguageFn, &'static str) {
    // Rust is bundled with the `runtime` feature; everything else is opt-in via
    // its `lang-*` cargo feature (or the `all-languages` umbrella).
    match language {
        Language::Rust => (
            arborium::lang_rust::language(),
            arborium::lang_rust::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-ada")]
        Language::Ada => (
            arborium::lang_ada::language(),
            arborium::lang_ada::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-agda")]
        Language::Agda => (
            arborium::lang_agda::language(),
            arborium::lang_agda::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-asciidoc")]
        Language::Asciidoc => (
            arborium::lang_asciidoc::language(),
            arborium::lang_asciidoc::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-asm")]
        Language::Asm => (
            arborium::lang_asm::language(),
            arborium::lang_asm::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-awk")]
        Language::Awk => (
            arborium::lang_awk::language(),
            arborium::lang_awk::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-bash")]
        Language::Bash => (
            arborium::lang_bash::language(),
            arborium::lang_bash::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-batch")]
        Language::Batch => (
            arborium::lang_batch::language(),
            arborium::lang_batch::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-c")]
        Language::C => (
            arborium::lang_c::language(),
            arborium::lang_c::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-c-sharp")]
        Language::CSharp => (
            arborium::lang_c_sharp::language(),
            arborium::lang_c_sharp::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-caddy")]
        Language::Caddy => (
            arborium::lang_caddy::language(),
            arborium::lang_caddy::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-capnp")]
        Language::Capnp => (
            arborium::lang_capnp::language(),
            arborium::lang_capnp::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-cedar")]
        Language::Cedar => (
            arborium::lang_cedar::language(),
            arborium::lang_cedar::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-cedarschema")]
        Language::CedarSchema => (
            arborium::lang_cedarschema::language(),
            arborium::lang_cedarschema::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-clojure")]
        Language::Clojure => (
            arborium::lang_clojure::language(),
            arborium::lang_clojure::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-cmake")]
        Language::CMake => (
            arborium::lang_cmake::language(),
            arborium::lang_cmake::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-cobol")]
        Language::Cobol => (
            arborium::lang_cobol::language(),
            arborium::lang_cobol::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-commonlisp")]
        Language::CommonLisp => (
            arborium::lang_commonlisp::language(),
            arborium::lang_commonlisp::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-cpp")]
        Language::Cpp => (
            arborium::lang_cpp::language(),
            &arborium::lang_cpp::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-css")]
        Language::Css => (
            arborium::lang_css::language(),
            arborium::lang_css::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-d")]
        Language::D => (
            arborium::lang_d::language(),
            arborium::lang_d::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-dart")]
        Language::Dart => (
            arborium::lang_dart::language(),
            arborium::lang_dart::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-devicetree")]
        Language::DeviceTree => (
            arborium::lang_devicetree::language(),
            arborium::lang_devicetree::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-diff")]
        Language::Diff => (
            arborium::lang_diff::language(),
            arborium::lang_diff::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-dockerfile")]
        Language::Dockerfile => (
            arborium::lang_dockerfile::language(),
            arborium::lang_dockerfile::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-dot")]
        Language::Dot => (
            arborium::lang_dot::language(),
            arborium::lang_dot::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-elisp")]
        Language::Elisp => (
            arborium::lang_elisp::language(),
            arborium::lang_elisp::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-elixir")]
        Language::Elixir => (
            arborium::lang_elixir::language(),
            arborium::lang_elixir::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-elm")]
        Language::Elm => (
            arborium::lang_elm::language(),
            arborium::lang_elm::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-erlang")]
        Language::Erlang => (
            arborium::lang_erlang::language(),
            arborium::lang_erlang::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-fish")]
        Language::Fish => (
            arborium::lang_fish::language(),
            arborium::lang_fish::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-fsharp")]
        Language::FSharp => (
            arborium::lang_fsharp::language(),
            arborium::lang_fsharp::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-gleam")]
        Language::Gleam => (
            arborium::lang_gleam::language(),
            arborium::lang_gleam::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-glsl")]
        Language::Glsl => (
            arborium::lang_glsl::language(),
            &arborium::lang_glsl::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-go")]
        Language::Go => (
            arborium::lang_go::language(),
            arborium::lang_go::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-graphql")]
        Language::GraphQL => (
            arborium::lang_graphql::language(),
            arborium::lang_graphql::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-groovy")]
        Language::Groovy => (
            arborium::lang_groovy::language(),
            arborium::lang_groovy::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-haskell")]
        Language::Haskell => (
            arborium::lang_haskell::language(),
            arborium::lang_haskell::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-hcl")]
        Language::Hcl => (
            arborium::lang_hcl::language(),
            arborium::lang_hcl::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-hlsl")]
        Language::Hlsl => (
            arborium::lang_hlsl::language(),
            &arborium::lang_hlsl::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-html")]
        Language::Html => (
            arborium::lang_html::language(),
            arborium::lang_html::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-idris")]
        Language::Idris => (
            arborium::lang_idris::language(),
            arborium::lang_idris::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-ini")]
        Language::Ini => (
            arborium::lang_ini::language(),
            arborium::lang_ini::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-java")]
        Language::Java => (
            arborium::lang_java::language(),
            arborium::lang_java::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-javascript")]
        Language::JavaScript => (
            arborium::lang_javascript::language(),
            arborium::lang_javascript::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-jinja2")]
        Language::Jinja2 => (
            arborium::lang_jinja2::language(),
            arborium::lang_jinja2::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-jq")]
        Language::Jq => (
            arborium::lang_jq::language(),
            arborium::lang_jq::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-json")]
        Language::Json => (
            arborium::lang_json::language(),
            arborium::lang_json::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-julia")]
        Language::Julia => (
            arborium::lang_julia::language(),
            arborium::lang_julia::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-kotlin")]
        Language::Kotlin => (
            arborium::lang_kotlin::language(),
            arborium::lang_kotlin::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-lean")]
        Language::Lean => (
            arborium::lang_lean::language(),
            arborium::lang_lean::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-lua")]
        Language::Lua => (
            arborium::lang_lua::language(),
            arborium::lang_lua::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-markdown")]
        Language::Markdown => (
            arborium::lang_markdown::language(),
            arborium::lang_markdown::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-matlab")]
        Language::Matlab => (
            arborium::lang_matlab::language(),
            arborium::lang_matlab::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-meson")]
        Language::Meson => (
            arborium::lang_meson::language(),
            arborium::lang_meson::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-nginx")]
        Language::Nginx => (
            arborium::lang_nginx::language(),
            arborium::lang_nginx::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-ninja")]
        Language::Ninja => (
            arborium::lang_ninja::language(),
            arborium::lang_ninja::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-nix")]
        Language::Nix => (
            arborium::lang_nix::language(),
            arborium::lang_nix::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-objc")]
        Language::ObjectiveC => (
            arborium::lang_objc::language(),
            &arborium::lang_objc::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-ocaml")]
        Language::OCaml => (
            arborium::lang_ocaml::language(),
            arborium::lang_ocaml::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-perl")]
        Language::Perl => (
            arborium::lang_perl::language(),
            arborium::lang_perl::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-php")]
        Language::Php => (
            arborium::lang_php::language(),
            arborium::lang_php::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-postscript")]
        Language::PostScript => (
            arborium::lang_postscript::language(),
            arborium::lang_postscript::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-powershell")]
        Language::PowerShell => (
            arborium::lang_powershell::language(),
            arborium::lang_powershell::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-prolog")]
        Language::Prolog => (
            arborium::lang_prolog::language(),
            arborium::lang_prolog::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-python")]
        Language::Python => (
            arborium::lang_python::language(),
            arborium::lang_python::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-query")]
        Language::Query => (
            arborium::lang_query::language(),
            arborium::lang_query::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-r")]
        Language::R => (
            arborium::lang_r::language(),
            arborium::lang_r::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-rego")]
        Language::Rego => (
            arborium::lang_rego::language(),
            arborium::lang_rego::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-rescript")]
        Language::Rescript => (
            arborium::lang_rescript::language(),
            arborium::lang_rescript::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-ron")]
        Language::Ron => (
            arborium::lang_ron::language(),
            arborium::lang_ron::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-ruby")]
        Language::Ruby => (
            arborium::lang_ruby::language(),
            arborium::lang_ruby::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-scala")]
        Language::Scala => (
            arborium::lang_scala::language(),
            arborium::lang_scala::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-scheme")]
        Language::Scheme => (
            arborium::lang_scheme::language(),
            arborium::lang_scheme::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-scss")]
        Language::Scss => (
            arborium::lang_scss::language(),
            &arborium::lang_scss::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-solidity")]
        Language::Solidity => (
            arborium::lang_solidity::language(),
            arborium::lang_solidity::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-sparql")]
        Language::Sparql => (
            arborium::lang_sparql::language(),
            arborium::lang_sparql::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-sql")]
        Language::Sql => (
            arborium::lang_sql::language(),
            arborium::lang_sql::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-ssh-config")]
        Language::SshConfig => (
            arborium::lang_ssh_config::language(),
            arborium::lang_ssh_config::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-starlark")]
        Language::Starlark => (
            arborium::lang_starlark::language(),
            arborium::lang_starlark::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-styx")]
        Language::Styx => (
            arborium::lang_styx::language(),
            arborium::lang_styx::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-svelte")]
        Language::Svelte => (
            arborium::lang_svelte::language(),
            &arborium::lang_svelte::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-swift")]
        Language::Swift => (
            arborium::lang_swift::language(),
            arborium::lang_swift::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-textproto")]
        Language::Textproto => (
            arborium::lang_textproto::language(),
            arborium::lang_textproto::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-thrift")]
        Language::Thrift => (
            arborium::lang_thrift::language(),
            arborium::lang_thrift::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-tlaplus")]
        Language::TlaPlus => (
            arborium::lang_tlaplus::language(),
            arborium::lang_tlaplus::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-toml")]
        Language::Toml => (
            arborium::lang_toml::language(),
            arborium::lang_toml::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-tsx")]
        Language::Tsx => (
            arborium::lang_tsx::language(),
            &arborium::lang_tsx::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-typescript")]
        Language::TypeScript => (
            arborium::lang_typescript::language(),
            &arborium::lang_typescript::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-typst")]
        Language::Typst => (
            arborium::lang_typst::language(),
            arborium::lang_typst::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-uiua")]
        Language::Uiua => (
            arborium::lang_uiua::language(),
            arborium::lang_uiua::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-vb")]
        Language::VisualBasic => (
            arborium::lang_vb::language(),
            arborium::lang_vb::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-verilog")]
        Language::Verilog => (
            arborium::lang_verilog::language(),
            arborium::lang_verilog::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-vhdl")]
        Language::Vhdl => (
            arborium::lang_vhdl::language(),
            arborium::lang_vhdl::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-vim")]
        Language::Vim => (
            arborium::lang_vim::language(),
            arborium::lang_vim::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-vue")]
        Language::Vue => (
            arborium::lang_vue::language(),
            &arborium::lang_vue::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-wit")]
        Language::Wit => (
            arborium::lang_wit::language(),
            arborium::lang_wit::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-x86asm")]
        Language::X86Asm => (
            arborium::lang_x86asm::language(),
            arborium::lang_x86asm::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-xml")]
        Language::Xml => (
            arborium::lang_xml::language(),
            arborium::lang_xml::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-yaml")]
        Language::Yaml => (
            arborium::lang_yaml::language(),
            arborium::lang_yaml::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-yuri")]
        Language::Yuri => (
            arborium::lang_yuri::language(),
            arborium::lang_yuri::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-zig")]
        Language::Zig => (
            arborium::lang_zig::language(),
            arborium::lang_zig::HIGHLIGHTS_QUERY,
        ),
        #[cfg(feature = "lang-zsh")]
        Language::Zsh => (
            arborium::lang_zsh::language(),
            arborium::lang_zsh::HIGHLIGHTS_QUERY,
        ),
    }
}

/// A byte-range edit description used to drive incremental highlighting.
///
/// Build one from a real edit signal (for example a textarea `beforeinput`
/// event) and pass it to [`Buffer::edit`]. `start_byte` and
/// `old_end_byte` index into the buffer's previous source, while
/// `new_end_byte` indexes into the new source supplied alongside the edit.
///
/// ```rust
/// use dioxus_code::advanced::SourceEdit;
/// // Insertion of one byte at offset 0.
/// let _edit = SourceEdit { start_byte: 0, old_end_byte: 0, new_end_byte: 1 };
/// ```
#[cfg(feature = "runtime")]
#[cfg_attr(docsrs, doc(cfg(feature = "runtime")))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SourceEdit {
    /// First byte that changed.
    pub start_byte: usize,
    /// One past the last byte of the replaced region in the previous source.
    pub old_end_byte: usize,
    /// One past the last byte of the inserted region in the new source.
    pub new_end_byte: usize,
}

#[cfg(feature = "runtime")]
impl SourceEdit {
    fn into_input_edit(
        self,
        old_source: &str,
        new_source: &str,
    ) -> Result<arborium_tree_sitter::InputEdit, HighlightError> {
        if self.start_byte > self.old_end_byte
            || self.start_byte > self.new_end_byte
            || self.old_end_byte > old_source.len()
            || self.new_end_byte > new_source.len()
            || !old_source.is_char_boundary(self.start_byte)
            || !old_source.is_char_boundary(self.old_end_byte)
            || !new_source.is_char_boundary(self.start_byte)
            || !new_source.is_char_boundary(self.new_end_byte)
        {
            return Err(HighlightError::InvalidEdit {
                start_byte: self.start_byte,
                old_end_byte: self.old_end_byte,
                new_end_byte: self.new_end_byte,
                old_len: old_source.len(),
                new_len: new_source.len(),
            });
        }

        Ok(arborium_tree_sitter::InputEdit {
            start_byte: self.start_byte,
            old_end_byte: self.old_end_byte,
            new_end_byte: self.new_end_byte,
            start_position: byte_to_point(old_source, self.start_byte),
            old_end_position: byte_to_point(old_source, self.old_end_byte),
            new_end_position: byte_to_point(new_source, self.new_end_byte),
        })
    }
}

#[cfg(feature = "runtime")]
fn byte_to_point(text: &str, byte: usize) -> arborium_tree_sitter::Point {
    let prefix = &text.as_bytes()[..byte];
    let last_newline = prefix.iter().rposition(|&b| b == b'\n');
    let row = prefix.iter().filter(|&&b| b == b'\n').count();
    let column = match last_newline {
        Some(pos) => byte - pos - 1,
        None => byte,
    };
    arborium_tree_sitter::Point { row, column }
}

/// Inject the shared syntax theme stylesheet and selected theme stylesheet.
///
/// ```rust
/// use dioxus::prelude::*;
/// use dioxus_code::{CodeTheme, Theme};
/// use dioxus_code::advanced::CodeThemeStyles;
///
/// fn _example() -> Element {
///     rsx! { CodeThemeStyles { theme: CodeTheme::fixed(Theme::TOKYO_NIGHT) } }
/// }
/// ```
#[component]
pub fn CodeThemeStyles(theme: CodeTheme) -> Element {
    let shared_theme_css = Theme::THEME_CSS;

    match theme.stylesheets() {
        CodeThemeStylesheets::Fixed(stylesheet) => {
            let theme_asset = stylesheet.asset;
            let theme_key = stylesheet.class;

            rsx! {
                document::Stylesheet { href: shared_theme_css }
                {rsx!{document::Stylesheet { key: "{theme_key}", href: theme_asset }}}
            }
        }
        CodeThemeStylesheets::System { light, dark } => {
            let light_asset = light.asset;
            let dark_asset = dark.asset;
            let light_key = light.class;
            let dark_key = dark.class;

            rsx! {
                document::Stylesheet { href: shared_theme_css }
                {rsx!{document::Stylesheet { key: "{light_key}", href: light_asset }}}
                {rsx!{document::Stylesheet { key: "{dark_key}", href: dark_asset }}}
            }
        }
    }
}

#[cfg(all(test, feature = "runtime"))]
mod buffer_tests {
    use super::*;

    fn span_ranges(spans: &[HighlightSpan]) -> Vec<(u32, u32, &'static str)> {
        spans
            .iter()
            .map(|s| (s.start(), s.end(), s.tag()))
            .collect()
    }

    fn batch_spans(source: &str, language: Language) -> Vec<HighlightSpan> {
        let snapshot: HighlightedSource = SourceCode::new(language, source.to_owned()).into();
        snapshot.spans().to_vec()
    }

    #[test]
    fn new_matches_batch_path() {
        let source = "fn main() { let x = 1; }";
        let buffer = Buffer::new(Language::Rust, source).unwrap();

        assert_eq!(buffer.language(), Language::Rust);
        assert_eq!(
            span_ranges(buffer.spans()),
            span_ranges(&batch_spans(source, Language::Rust)),
        );
    }

    #[test]
    fn edit_with_explicit_source_edit() {
        let mut buffer = Buffer::new(Language::Rust, "fn main() { let x = 1; }").unwrap();
        let updated = "fn main() { let x = 12; }";
        buffer
            .edit(
                SourceEdit {
                    start_byte: 21,
                    old_end_byte: 21,
                    new_end_byte: 22,
                },
                updated,
            )
            .unwrap();

        assert_eq!(buffer.source(), updated);
        assert_eq!(
            span_ranges(buffer.spans()),
            span_ranges(&batch_spans(updated, Language::Rust)),
        );
    }

    #[test]
    fn malformed_edit_returns_typed_error_and_leaves_state_unchanged() {
        let mut buffer = Buffer::new(Language::Rust, "fn main() { let x = 1; }").unwrap();
        let previous_spans = buffer.spans().to_vec();
        let updated = "fn main() { let x = 12; }";

        assert_eq!(
            buffer.edit(
                // old_end_byte beyond the previous source — must not panic.
                SourceEdit {
                    start_byte: 21,
                    old_end_byte: 999,
                    new_end_byte: 22,
                },
                updated,
            ),
            Err(HighlightError::InvalidEdit {
                start_byte: 21,
                old_end_byte: 999,
                new_end_byte: 22,
                old_len: "fn main() { let x = 1; }".len(),
                new_len: updated.len(),
            }),
        );
        assert_eq!(buffer.source(), "fn main() { let x = 1; }");
        assert_eq!(buffer.spans(), previous_spans.as_slice());
    }

    #[test]
    fn semantic_edit_mismatch_is_not_validated() {
        let mut buffer = Buffer::new(Language::Rust, "fn main() { let x = 1; }").unwrap();
        let updated = "fn main() { let y = 1; }";

        buffer
            .edit(
                // The unchanged suffix does not match this edit; validation
                // intentionally stays O(1) and trusts callers on semantics.
                SourceEdit {
                    start_byte: 21,
                    old_end_byte: 21,
                    new_end_byte: 22,
                },
                updated,
            )
            .unwrap();

        assert_eq!(buffer.source(), updated);
    }

    #[test]
    fn replace_drops_cached_tree() {
        let mut buffer = Buffer::new(Language::Rust, "fn main() { 1 }").unwrap();
        let updated = "fn main() { 2 }";
        buffer.replace(updated).unwrap();

        assert_eq!(buffer.source(), updated);
        assert_eq!(
            span_ranges(buffer.spans()),
            span_ranges(&batch_spans(updated, Language::Rust)),
        );
    }

    #[test]
    fn set_language_reparses() {
        let mut buffer = Buffer::new(Language::Rust, "fn main() {}").unwrap();
        let rust_spans = buffer.spans().to_vec();

        // Re-set to the same language is a no-op but should still produce
        // the same output.
        buffer.set_language(Language::Rust).unwrap();
        assert_eq!(buffer.spans(), rust_spans.as_slice());
    }

    #[test]
    fn byte_to_point_counts_rows_and_columns() {
        use arborium_tree_sitter::Point;
        assert_eq!(byte_to_point("abc", 2), Point { row: 0, column: 2 });
        assert_eq!(byte_to_point("ab\ncd\nef", 6), Point { row: 2, column: 0 });
        assert_eq!(byte_to_point("ab\ncd\nef", 8), Point { row: 2, column: 2 });
    }
}