svg-format 0.1.0

Structural formatter for SVG documents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
//! Deterministic structural formatting for SVG documents.
//!
//! # Examples
//!
//! ```rust
//! let input = r#"<svg><rect x="0"  y="0" /></svg>"#;
//! let formatted = svg_format::format(input);
//! assert!(formatted.contains("<rect"));
//! ```

mod tag_parse;
mod text_content;

use tag_parse::{
    ParsedAttribute, ParsedAttributeValue, ParsedTag, canonical_group_key, parse_tag,
    reorder_attributes,
};
use text_content::{
    collapse_whitespace, decode_xml_entities, dedent_block_with_offset, encode_xml_entities,
    is_text_content_element, normalize_text_content_with_entities, strip_cdata_wrapper,
};
use tree_sitter::{Node, Parser};

/// Attribute ordering mode.
///
/// # Examples
///
/// ```rust
/// let mut options = svg_format::FormatOptions::default();
/// options.attribute_sort = svg_format::AttributeSort::Alphabetical;
/// let formatted = svg_format::format_with_options(r#"<svg y="2" x="1"/>"#, options);
/// assert!(formatted.contains(r#"x="1" y="2""#));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
#[cfg_attr(feature = "cli", value(rename_all = "kebab-case"))]
pub enum AttributeSort {
    /// Keep original source order.
    None,
    /// SVG-aware canonical grouping/order.
    #[default]
    Canonical,
    /// Sort attributes alphabetically by name.
    Alphabetical,
}

/// Attribute wrapping mode.
///
/// # Examples
///
/// ```rust
/// let mut options = svg_format::FormatOptions::default();
/// options.attribute_layout = svg_format::AttributeLayout::MultiLine;
/// let formatted = svg_format::format_with_options(r#"<svg><rect x="1" y="2"/></svg>"#, options);
/// assert!(formatted.contains('\n'));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
#[cfg_attr(feature = "cli", value(rename_all = "kebab-case"))]
pub enum AttributeLayout {
    /// Wrap only when inline width exceeds threshold (or source was already multiline).
    #[default]
    Auto,
    /// Always keep attributes in one line.
    SingleLine,
    /// Always wrap attributes into multiple lines (if any attributes exist).
    MultiLine,
}

/// Quoting strategy for attribute values.
///
/// # Examples
///
/// ```rust
/// let mut options = svg_format::FormatOptions::default();
/// options.quote_style = svg_format::QuoteStyle::Single;
/// let formatted = svg_format::format_with_options(r#"<svg><rect x="1"/></svg>"#, options);
/// assert!(formatted.contains("x='1'"));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
#[cfg_attr(feature = "cli", value(rename_all = "kebab-case"))]
pub enum QuoteStyle {
    /// Preserve original quote style where present.
    #[default]
    Preserve,
    /// Normalize quoted values to double quotes.
    Double,
    /// Normalize quoted values to single quotes.
    Single,
}

/// Indentation strategy for wrapped attributes.
///
/// # Examples
///
/// ```rust
/// let mut options = svg_format::FormatOptions::default();
/// options.attribute_layout = svg_format::AttributeLayout::MultiLine;
/// options.wrapped_attribute_indent = svg_format::WrappedAttributeIndent::OneLevel;
/// let formatted = svg_format::format_with_options(r#"<svg><rect x="1" y="2"/></svg>"#, options);
/// assert!(formatted.contains("\n    x="));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
#[cfg_attr(feature = "cli", value(rename_all = "kebab-case"))]
pub enum WrappedAttributeIndent {
    /// Add one normal indentation unit.
    OneLevel,
    /// Align to the column after `<tag ` so wrapped attributes line up visually.
    #[default]
    AlignToTagName,
}

/// How blank lines between sibling elements are handled.
///
/// # Examples
///
/// ```rust
/// let mut options = svg_format::FormatOptions::default();
/// options.blank_lines = svg_format::BlankLines::Remove;
/// let formatted = svg_format::format_with_options("<svg><g/>\n\n<g/></svg>", options);
/// assert!(!formatted.contains("\n\n"));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
#[cfg_attr(feature = "cli", value(rename_all = "kebab-case"))]
pub enum BlankLines {
    /// Strip all blank lines between siblings.
    Remove,
    /// Keep blank lines from source verbatim.
    Preserve,
    /// Collapse 2+ blank lines to exactly 1.
    #[default]
    Truncate,
    /// Force exactly 1 blank line between every sibling.
    Insert,
}

/// How the formatter handles whitespace in text nodes.
///
/// # Examples
///
/// ```rust
/// let mut options = svg_format::FormatOptions::default();
/// options.text_content = svg_format::TextContentMode::Collapse;
/// let formatted = svg_format::format_with_options("<svg><text>a   b</text></svg>", options);
/// assert!(formatted.contains("a b"));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
#[cfg_attr(feature = "cli", value(rename_all = "kebab-case"))]
pub enum TextContentMode {
    /// Collapse runs of whitespace into single spaces, trim lines, skip blanks.
    Collapse,
    /// Preserve content structure; dedent then re-indent to SVG depth.
    #[default]
    Maintain,
    /// Trim each line, remove blank lines, re-indent to SVG depth.
    Prettify,
}

/// The language of embedded content found within an SVG element.
///
/// # Examples
///
/// ```rust
/// let language = svg_format::EmbeddedLanguage::Css;
/// assert_eq!(language, svg_format::EmbeddedLanguage::Css);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EmbeddedLanguage {
    /// CSS inside `<style>`.
    Css,
    /// JavaScript inside `<script>`.
    JavaScript,
    /// HTML/XHTML inside `<foreignObject>`.
    Html,
}

const fn is_script_or_style_language(language: EmbeddedLanguage) -> bool {
    matches!(
        language,
        EmbeddedLanguage::Css | EmbeddedLanguage::JavaScript
    )
}

/// A request to format embedded content within an SVG document.
///
/// # Examples
///
/// ```rust
/// let embedded = svg_format::EmbeddedContent {
///     language: svg_format::EmbeddedLanguage::Css,
///     content: ".icon{fill:red}",
///     indent_depth: 1,
///     file_byte_offset: 12,
/// };
/// assert_eq!(embedded.language, svg_format::EmbeddedLanguage::Css);
/// ```
pub struct EmbeddedContent<'a> {
    /// The language of the embedded content.
    pub language: EmbeddedLanguage,
    /// The raw content text (common indent removed).
    pub content: &'a str,
    /// The nesting depth in the SVG tree where this content lives.
    pub indent_depth: usize,
    /// Byte offset in the original SVG source where the embedded payload
    /// begins: the first non-whitespace content byte, past any `<![CDATA[`
    /// prefix and the common leading indentation.
    ///
    /// This is a *block anchor*, not a byte-for-byte map. `content` is a
    /// transformed view of the source — common indentation is stripped per
    /// line, CRLF is normalized to LF, and (outside CDATA) XML entities are
    /// decoded — so it is generally not byte-identical to
    /// `&source[file_byte_offset..]`. A host callback can use this to locate
    /// where the embedded region starts, but interior `(line, col)` positions
    /// within `content` cannot be recovered by counting bytes from this
    /// offset; that would require a full source map.
    pub file_byte_offset: usize,
}

/// Formatter configuration for SVG pretty-printing.
///
/// # Examples
///
/// ```rust
/// let options = svg_format::FormatOptions::default();
/// assert_eq!(options.indent_width, 2);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FormatOptions {
    /// Number of spaces per indentation level when `insert_spaces` is true.
    pub indent_width: usize,
    /// Whether indentation should use spaces (true) or tabs (false).
    pub insert_spaces: bool,
    /// Maximum inline tag width before switching to multi-line attributes.
    pub max_inline_tag_width: usize,
    /// Attribute ordering mode.
    pub attribute_sort: AttributeSort,
    /// Attribute wrapping mode.
    pub attribute_layout: AttributeLayout,
    /// Maximum number of attributes emitted per wrapped line.
    pub attributes_per_line: usize,
    /// Emit a space before `/>` in self-closing tags.
    pub space_before_self_close: bool,
    /// Preferred quote style for attribute values.
    pub quote_style: QuoteStyle,
    /// Indentation style for wrapped attributes.
    pub wrapped_attribute_indent: WrappedAttributeIndent,
    /// How text-node whitespace is handled.
    pub text_content: TextContentMode,
    /// How blank lines between sibling elements are handled.
    pub blank_lines: BlankLines,
    /// Comment prefixes that trigger ignore directives.
    ///
    /// For each prefix `p`, the formatter recognizes:
    /// - `<!-- p-ignore -->` — skip formatting the next sibling
    /// - `<!-- p-ignore-file -->` — skip the entire file (detected anywhere)
    /// - `<!-- p-ignore-start -->` / `<!-- p-ignore-end -->` — skip a range
    ///
    /// Defaults to `["svg-format"]`.
    pub ignore_prefixes: Vec<String>,
}

impl Default for FormatOptions {
    fn default() -> Self {
        Self {
            indent_width: 2,
            insert_spaces: true,
            max_inline_tag_width: 100,
            attribute_sort: AttributeSort::Canonical,
            attribute_layout: AttributeLayout::Auto,
            attributes_per_line: 1,
            space_before_self_close: true,
            quote_style: QuoteStyle::Preserve,
            wrapped_attribute_indent: WrappedAttributeIndent::AlignToTagName,
            text_content: TextContentMode::Maintain,
            blank_lines: BlankLines::Truncate,
            ignore_prefixes: vec!["svg-format".to_string()],
        }
    }
}

/// Format an SVG source string with default options.
///
/// # Examples
///
/// ```rust
/// let formatted = svg_format::format(r#"<svg><rect x="1"/></svg>"#);
/// assert!(formatted.contains("<rect"));
/// ```
#[must_use]
pub fn format(source: &str) -> String {
    format_with_options(source, FormatOptions::default())
}

/// Format an SVG source string with explicit options.
///
/// # Examples
///
/// ```rust
/// let mut options = svg_format::FormatOptions::default();
/// options.space_before_self_close = false;
/// let formatted = svg_format::format_with_options("<svg />", options);
/// assert!(formatted.contains("<svg/>"));
/// ```
#[must_use]
pub fn format_with_options(source: &str, options: FormatOptions) -> String {
    format_with_host(source, options, &mut |_| None)
}

/// Format an SVG source string, delegating embedded content to a callback.
///
/// The callback receives [`EmbeddedContent`] for `<style>`, `<script>`, and
/// `<foreignObject>` blocks. Return `Some(formatted)` to use the formatted
/// result, or `None` to fall back to the default text-handling behavior.
///
/// # Examples
///
/// ```rust
/// let mut seen_css = false;
/// let formatted = svg_format::format_with_host(
///     "<svg><style>.icon{fill:red}</style></svg>",
///     svg_format::FormatOptions::default(),
///     &mut |embedded| {
///         seen_css = embedded.language == svg_format::EmbeddedLanguage::Css;
///         Some(".icon { fill: red; }".to_owned())
///     },
/// );
/// assert!(seen_css);
/// assert!(formatted.contains(".icon { fill: red; }"));
/// ```
#[must_use]
pub fn format_with_host(
    source: &str,
    options: FormatOptions,
    format_embedded: &mut dyn FnMut(EmbeddedContent<'_>) -> Option<String>,
) -> String {
    let mut parser = Parser::new();
    if parser
        .set_language(&tree_sitter_svg::LANGUAGE.into())
        .is_err()
    {
        return normalize_line_endings(source);
    }

    let Some(tree) = parser.parse(source.as_bytes(), None) else {
        return normalize_line_endings(source);
    };

    if tree.root_node().has_error() {
        return normalize_line_endings(source);
    }

    // Check for ignore-file directive in actual comment nodes only.
    if has_ignore_file_comment(
        tree.root_node(),
        source.as_bytes(),
        &options.ignore_prefixes,
    ) {
        return normalize_line_endings(source);
    }

    let mut formatter = Formatter::new(source.as_bytes(), options);
    formatter.format_node(tree.root_node(), 0, format_embedded);
    formatter.finish(source)
}

/// Normalize CRLF and bare CR to LF.
///
/// [`format_with_host`] guarantees pure-LF output so callers can safely
/// translate line endings with a blanket `replace('\n', target)` without
/// double-counting CRs that the source happened to contain.
fn normalize_line_endings(source: &str) -> String {
    if !source.contains('\r') {
        return source.to_owned();
    }
    source.replace("\r\n", "\n").replace('\r', "\n")
}

/// Walk the AST looking for `<!-- {prefix}-ignore-file -->` in comment nodes.
fn has_ignore_file_comment(node: Node<'_>, source: &[u8], prefixes: &[String]) -> bool {
    if node.kind() == "comment" {
        let inner = node
            .child_by_field_name("text")
            .and_then(|t| std::str::from_utf8(&source[t.byte_range()]).ok())
            .map_or("", str::trim);
        if prefixes.iter().any(|p| inner == format!("{p}-ignore-file")) {
            return true;
        }
    }
    let mut cursor = node.walk();
    node.named_children(&mut cursor)
        .any(|child| has_ignore_file_comment(child, source, prefixes))
}

/// Greedily pack SVG path-data segments (or `points` coordinate pairs)
/// onto wrapped lines separated by `\n`, breaking at segment or pair
/// boundaries so the value fits within `budget` characters per line
/// when possible. Returns `Some(value)` with embedded newlines for the
/// caller to re-emit under continuation alignment, or `None` if the
/// value fits as-is, is empty, or can't be parsed.
///
/// The formatter never reformats minified path-data on its own merit;
/// `wrap_path_data` is only invoked when the tag would otherwise
/// overflow `max_inline_tag_width` and we're choosing to break at
/// semantic boundaries instead of leaving a 12kB single-line blob.
fn wrap_path_data(name: &str, raw: &str, budget: usize) -> Option<String> {
    if budget == 0 || raw.chars().count() <= budget {
        return None;
    }
    if raw.trim().is_empty() {
        return None;
    }
    if raw.contains('\n') {
        // Source-preserved embedded newlines take the existing
        // continuation path — don't re-wrap.
        return None;
    }
    match name {
        "d" => wrap_d_value(raw, budget),
        "points" => wrap_points_value(raw, budget),
        _ => None,
    }
}

fn wrap_d_value(raw: &str, budget: usize) -> Option<String> {
    // Path data lives in the injected `svg_path` grammar — the host grammar
    // now exposes the `d`/`path` value as one opaque `path_data_payload`
    // token. Parse the raw attribute value directly with `svg_path` to
    // recover structured segments (`source_file` → `path_data` → segments).
    // Empty/whitespace path data is valid; a parse error means we leave the
    // value untouched.
    let mut parser = Parser::new();
    parser
        .set_language(&tree_sitter_svg_path::LANGUAGE.into())
        .ok()?;
    let tree = parser.parse(raw.as_bytes(), None)?;
    if tree.root_node().has_error() {
        return None;
    }

    let mut segments: Vec<(usize, usize, &str)> = Vec::new();
    collect_path_segments(tree.root_node(), raw.as_bytes(), &mut segments);
    if segments.is_empty() {
        return None;
    }

    let segment_strs: Vec<&str> = segments
        .iter()
        .map(|&(start, end, _kind)| &raw[start..end])
        .collect();
    let segment_kinds: Vec<&str> = segments.iter().map(|&(_, _, kind)| kind).collect();

    pack_segments(&segment_strs, &segment_kinds, budget, true)
}

fn wrap_points_value(raw: &str, budget: usize) -> Option<String> {
    // `<polyline/polygon points="…">` has no grammar children for the
    // coordinate pairs — split on whitespace into pairs manually. A pair
    // is an `x,y` (comma-separated) or two whitespace-separated numbers;
    // this implementation preserves the inter-pair separator style the
    // source uses by splitting only on runs of whitespace between pairs.
    let tokens: Vec<&str> = raw.split_ascii_whitespace().collect();
    if tokens.is_empty() {
        return None;
    }
    // Re-group tokens into pairs. If a token already contains a comma
    // (e.g. `10,20`) it's a full pair; otherwise two consecutive tokens
    // form a pair.
    let mut pairs: Vec<String> = Vec::new();
    let mut i = 0;
    while i < tokens.len() {
        let t = tokens[i];
        if t.contains(',') {
            pairs.push(t.to_string());
            i += 1;
        } else if i + 1 < tokens.len() {
            pairs.push(format!("{t},{}", tokens[i + 1]));
            i += 2;
        } else {
            pairs.push(t.to_string());
            i += 1;
        }
    }
    if pairs.len() <= 1 {
        return None;
    }
    let pair_refs: Vec<&str> = pairs.iter().map(String::as_str).collect();
    let kinds = vec!["pair"; pair_refs.len()];
    pack_segments(&pair_refs, &kinds, budget, false)
}

/// Greedy packer: emit segments separated by single spaces, wrapping
/// to a new line at `\n` when adding the next segment would exceed
/// `budget`. When `prefer_subpath_breaks` is set, a `moveto_segment`
/// forces a new line if the current line is already half full — this
/// keeps `M...` subpath starts from dangling at the end of a line.
fn pack_segments(
    segments: &[&str],
    kinds: &[&str],
    budget: usize,
    prefer_subpath_breaks: bool,
) -> Option<String> {
    if segments.is_empty() {
        return None;
    }
    let mut out = String::with_capacity(segments.iter().map(|s| s.len() + 1).sum::<usize>());
    let mut line_width = 0usize;
    let half_budget = budget / 2;
    for (i, seg) in segments.iter().enumerate() {
        let w = seg.chars().count();
        let is_moveto_split = prefer_subpath_breaks
            && i > 0
            && kinds[i] == "moveto_segment"
            && line_width >= half_budget;
        if line_width == 0 {
            out.push_str(seg);
            line_width = w;
        } else if !is_moveto_split && line_width + 1 + w <= budget {
            out.push(' ');
            out.push_str(seg);
            line_width += 1 + w;
        } else {
            out.push('\n');
            out.push_str(seg);
            line_width = w;
        }
    }
    if out.contains('\n') { Some(out) } else { None }
}

fn collect_path_segments(
    node: Node<'_>,
    source: &[u8],
    segments: &mut Vec<(usize, usize, &'static str)>,
) {
    const SEGMENT_KINDS: &[&str] = &[
        "moveto_segment",
        "lineto_segment",
        "closepath_segment",
        "curveto_segment",
        "smooth_curveto_segment",
        "quadratic_bezier_curveto_segment",
        "smooth_quadratic_bezier_curveto_segment",
        "elliptical_arc_segment",
        "horizontal_lineto_segment",
        "vertical_lineto_segment",
        "implicit_lineto_segment",
    ];
    let kind = node.kind();
    if let Some(&matched) = SEGMENT_KINDS.iter().find(|k| **k == kind) {
        let range = node.byte_range();
        // Use the raw slice to drop any trailing whitespace captured
        // inside the segment — keeps packed output compact.
        let text = std::str::from_utf8(&source[range.clone()])
            .unwrap_or("")
            .trim_end();
        let end = range.start + text.len();
        segments.push((range.start, end, matched));
        return;
    }
    let mut cursor = node.walk();
    for child in node.named_children(&mut cursor) {
        collect_path_segments(child, source, segments);
    }
}

/// Partition attributes into contiguous runs sharing the same canonical
/// group key. Returned as lists of indices into the input slice so the
/// caller can emit them without reallocating attribute data.
fn partition_by_canonical_group(attributes: &[ParsedAttribute]) -> Vec<Vec<usize>> {
    if attributes.is_empty() {
        return Vec::new();
    }
    let mut groups: Vec<Vec<usize>> = Vec::new();
    let mut current: Vec<usize> = vec![0];
    let mut current_key = canonical_group_key(&attributes[0].name);
    for (i, attr) in attributes.iter().enumerate().skip(1) {
        let key = canonical_group_key(&attr.name);
        if key == current_key {
            current.push(i);
        } else {
            groups.push(std::mem::take(&mut current));
            current.push(i);
            current_key = key;
        }
    }
    if !current.is_empty() {
        groups.push(current);
    }
    groups
}

/// If a group's rendered width on a single wrapped line would exceed
/// `budget`, fall back to one attribute per line within that group.
/// Otherwise emit the group as a single chunk.
///
/// Rendered width here uses the raw `<name>=<quoted-value>` form with a
/// single space separator. This is an approximation of the final
/// `render_attribute_aligned` output for single-line values — exact
/// enough to decide overflow since quote style doesn't change column
/// width.
fn split_group_if_overflow(
    attributes: &[ParsedAttribute],
    group: Vec<usize>,
    budget: usize,
) -> Vec<Vec<usize>> {
    let width: usize = group
        .iter()
        .map(|&i| approximate_attribute_width(&attributes[i]))
        .sum::<usize>()
        + group.len().saturating_sub(1);
    if width <= budget || group.len() <= 1 {
        vec![group]
    } else {
        group.into_iter().map(|i| vec![i]).collect()
    }
}

/// Rough column width of `name=(quote)value(quote)`. `value` and quotes
/// contribute their literal `chars().count()`; a bare attribute has
/// just the name width.
fn approximate_attribute_width(attribute: &ParsedAttribute) -> usize {
    let name_width = attribute.name.chars().count();
    attribute.value.as_ref().map_or(name_width, |v| {
        let quote_width = if v.original_quote.is_some() { 2 } else { 0 };
        name_width + 1 + quote_width + v.raw.chars().count()
    })
}

/// Decide which attributes ride the tag line and which become the head
/// of the wrapped remainder. Pops trailing attributes off the first
/// chunk until it fits within `line_budget`, with a hard minimum of one
/// attribute on the tag line (per W3 sample style).
///
/// `tag_line_prefix_width` is the column count consumed by `<tagname `
/// plus leading indent — i.e. everything before the first attribute.
/// Returns `(first_chunk_indices, rest_chunks)` where `rest_chunks`
/// contains any popped attrs as a new chunk prepended to the remaining
/// wrapped lines.
fn split_first_chunk_for_tag_line(
    attributes: &[ParsedAttribute],
    chunks: &mut Vec<Vec<usize>>,
    tag_line_prefix_width: usize,
    line_budget: usize,
    mut render: impl FnMut(&ParsedAttribute) -> String,
) -> (Vec<usize>, Vec<Vec<usize>>) {
    if chunks.is_empty() {
        return (Vec::new(), Vec::new());
    }
    let first = chunks.remove(0);
    let mut kept: Vec<usize> = Vec::with_capacity(first.len());
    let mut popped: Vec<usize> = Vec::new();
    for &idx in &first {
        let candidate = render(&attributes[idx]);
        let tentative = if kept.is_empty() {
            tag_line_prefix_width + candidate.chars().count()
        } else {
            // existing width + space separator + new attr
            let existing: usize = tag_line_prefix_width
                + kept
                    .iter()
                    .map(|&i| render(&attributes[i]).chars().count() + 1)
                    .sum::<usize>()
                - 1;
            existing + 1 + candidate.chars().count()
        };
        if !kept.is_empty() && tentative > line_budget {
            popped.push(idx);
        } else {
            kept.push(idx);
        }
    }
    // Once we start popping, any later attrs in this group also get
    // pushed into the remainder — preserve source order by appending.
    for &idx in &first {
        if !kept.contains(&idx) && !popped.contains(&idx) {
            popped.push(idx);
        }
    }
    let rest: Vec<Vec<usize>> = if popped.is_empty() {
        std::mem::take(chunks)
    } else {
        std::iter::once(popped)
            .chain(std::mem::take(chunks))
            .collect()
    };
    (kept, rest)
}

struct Formatter<'a> {
    source: &'a [u8],
    options: FormatOptions,
    out: String,
}

impl<'a> Formatter<'a> {
    const fn new(source: &'a [u8], options: FormatOptions) -> Self {
        Self {
            source,
            options,
            out: String::new(),
        }
    }

    fn finish(mut self, original: &str) -> String {
        while self.out.ends_with('\n') {
            self.out.pop();
        }
        if original.ends_with('\n') {
            self.out.push('\n');
        }
        self.out
    }

    fn format_node(
        &mut self,
        node: Node<'_>,
        depth: usize,
        fmt: &mut dyn FnMut(EmbeddedContent<'_>) -> Option<String>,
    ) {
        match node.kind() {
            "svg_root_element" | "element" => self.format_element_like(node, depth, fmt),
            "start_tag" => self.write_tag_node(node, depth, false),
            "self_closing_tag" => self.write_tag_node(node, depth, true),
            "style_text_double" | "style_text_single" | "script_text_double"
            | "script_text_single" => {
                self.write_preserved_block_text(node, depth);
            }
            "text" | "raw_text" => {
                self.write_text_node(node, depth);
            }
            "end_tag"
            | "comment"
            | "cdata_section"
            | "doctype"
            | "processing_instruction"
            | "xml_declaration"
            | "entity_reference"
            | "erroneous_end_tag" => {
                let text = self.node_text(node).trim().to_string();
                self.write_line(depth, &text);
            }
            _ => self.format_children(node, depth, fmt),
        }
    }

    fn format_children(
        &mut self,
        node: Node<'_>,
        depth: usize,
        fmt: &mut dyn FnMut(EmbeddedContent<'_>) -> Option<String>,
    ) {
        let mut cursor = node.walk();
        let mut prev_end: Option<usize> = None;
        let mut prev_was_comment = false;
        let mut ignore_next = false;
        let mut in_ignore_range = false;
        for child in node.named_children(&mut cursor) {
            if self.handle_ignore(
                child,
                &mut in_ignore_range,
                &mut ignore_next,
                &mut prev_was_comment,
                &mut prev_end,
            ) {
                continue;
            }

            if let Some(end) = prev_end {
                self.emit_gap(end, child.start_byte(), prev_was_comment);
            }
            self.format_node(child, depth, fmt);
            prev_was_comment = child.kind() == "comment";
            prev_end = Some(child.end_byte());
        }
    }

    fn format_element_like(
        &mut self,
        node: Node<'_>,
        depth: usize,
        fmt: &mut dyn FnMut(EmbeddedContent<'_>) -> Option<String>,
    ) {
        let mut cursor = node.walk();
        let children: Vec<Node<'_>> = node.named_children(&mut cursor).collect();
        if children.is_empty() {
            return;
        }

        if children.len() == 1 && children[0].kind() == "self_closing_tag" {
            self.format_node(children[0], depth, fmt);
            return;
        }

        let tag_name: String = children
            .iter()
            .find(|c| c.kind() == "start_tag")
            .and_then(|tag| {
                let text = self.node_text(*tag).trim();
                text.strip_prefix('<')
                    .and_then(|s| s.split(|c: char| c.is_whitespace() || c == '>').next())
                    .map(str::to_string)
            })
            .unwrap_or_default();

        let embedded_lang = match tag_name.as_str() {
            "style" => Some(EmbeddedLanguage::Css),
            "script" => Some(EmbeddedLanguage::JavaScript),
            "foreignObject" => Some(EmbeddedLanguage::Html),
            _ => None,
        };

        if embedded_lang == Some(EmbeddedLanguage::Html)
            && self
                .try_format_foreign_object(&children, depth, fmt)
                .is_some()
        {
            return;
        }

        if let Some((start, end)) = text_content_entity_bounds(&children, &tag_name) {
            self.format_text_content_element(start, end, depth);
            return;
        }

        self.format_element_children(&children, embedded_lang, depth, fmt);
    }

    fn format_element_children(
        &mut self,
        children: &[Node<'_>],
        embedded_lang: Option<EmbeddedLanguage>,
        depth: usize,
        fmt: &mut dyn FnMut(EmbeddedContent<'_>) -> Option<String>,
    ) {
        let mut prev_end: Option<usize> = None;
        let mut prev_was_comment = false;
        let mut ignore_next = false;
        let mut in_ignore_range = false;
        for &child in children {
            if self.handle_ignore(
                child,
                &mut in_ignore_range,
                &mut ignore_next,
                &mut prev_was_comment,
                &mut prev_end,
            ) {
                continue;
            }

            match child.kind() {
                "start_tag" | "end_tag" => {
                    self.format_node(child, depth, fmt);
                }
                "style_text_double" | "style_text_single" | "script_text_double"
                | "script_text_single" => {
                    if !self.node_text(child).trim().is_empty() {
                        self.write_preserved_block_text(child, depth + 1);
                    }
                    prev_was_comment = false;
                    prev_end = Some(child.end_byte());
                }
                "cdata_section" if embedded_lang.is_some_and(is_script_or_style_language) => {
                    let Some(lang) = embedded_lang else { continue };
                    self.format_embedded_child(
                        child,
                        lang,
                        depth + 1,
                        fmt,
                        (&mut prev_end, &mut prev_was_comment),
                        true,
                    );
                }
                "text" | "raw_text" => {
                    if let Some(lang) = embedded_lang
                        && lang != EmbeddedLanguage::Html
                    {
                        self.format_embedded_child(
                            child,
                            lang,
                            depth + 1,
                            fmt,
                            (&mut prev_end, &mut prev_was_comment),
                            false,
                        );
                        continue;
                    }
                    self.format_plain_text_child(
                        child,
                        depth + 1,
                        &mut prev_end,
                        &mut prev_was_comment,
                    );
                }
                _ => {
                    if let Some(end) = prev_end {
                        self.emit_gap(end, child.start_byte(), prev_was_comment);
                    }
                    self.format_node(child, depth + 1, fmt);
                    prev_was_comment = child.kind() == "comment";
                    prev_end = Some(child.end_byte());
                }
            }
        }
    }

    fn format_plain_text_child(
        &mut self,
        child: Node<'_>,
        depth: usize,
        prev_end: &mut Option<usize>,
        prev_was_comment: &mut bool,
    ) {
        if self.node_text(child).trim().is_empty() {
            return;
        }
        if let Some(end) = *prev_end {
            self.emit_gap(end, child.start_byte(), *prev_was_comment);
        }
        self.write_text_node(child, depth);
        *prev_was_comment = false;
        *prev_end = Some(child.end_byte());
    }

    fn format_embedded_child(
        &mut self,
        child: Node<'_>,
        language: EmbeddedLanguage,
        depth: usize,
        fmt: &mut dyn FnMut(EmbeddedContent<'_>) -> Option<String>,
        previous: (&mut Option<usize>, &mut bool),
        force_preserve: bool,
    ) {
        let (prev_end, prev_was_comment) = previous;
        if self.node_text(child).trim().is_empty() {
            return;
        }
        if let Some(end) = *prev_end {
            self.emit_gap(end, child.start_byte(), *prev_was_comment);
        }
        if !self.try_format_embedded_text(child, language, depth, fmt) {
            if force_preserve || self.options.text_content == TextContentMode::Maintain {
                self.write_preserved_embedded_text(child, depth);
            } else {
                self.write_text_node(child, depth);
            }
        }
        *prev_was_comment = false;
        *prev_end = Some(child.end_byte());
    }

    /// Format a text-content element whose children include entity
    /// references mixed with text. Extracts the raw source between start
    /// and end tags, normalizes whitespace into a single line, and inlines
    /// with the tags when it fits.
    ///
    /// Called only when `entity_reference` nodes are present — the whitespace
    /// around them is a formatting artifact, not meaningful content, so we
    /// always normalize regardless of [`TextContentMode`].
    fn format_text_content_element(&mut self, start: Node<'_>, end: Node<'_>, depth: usize) {
        let raw = std::str::from_utf8(&self.source[start.end_byte()..end.start_byte()])
            .unwrap_or_default();
        let normalized = normalize_text_content_with_entities(raw);
        let end_text = self.node_text(end).trim().to_string();

        // Render the start tag (capture output for potential inline rewrite).
        let out_before = self.out.len();
        self.write_tag_node(start, depth, false);
        let tag_output = self.out[out_before..].to_string();

        if normalized.is_empty() {
            self.write_line(depth, &end_text);
            return;
        }

        // Try to keep everything on one line: <tag>content</tag>
        let tag_str = tag_output.trim_end_matches('\n');
        if !tag_str.contains('\n') {
            let tag_inline = tag_str.trim_start();
            let candidate = format!("{tag_inline}{normalized}{end_text}");
            if self.indent(depth).len() + candidate.len() <= self.options.max_inline_tag_width {
                self.out.truncate(out_before);
                self.write_line(depth, &candidate);
                return;
            }
        }

        // Doesn't fit inline — write normalized content on its own line.
        self.write_line(depth + 1, &normalized);
        self.write_line(depth, &end_text);
    }

    fn write_tag_node(&mut self, node: Node<'_>, depth: usize, self_closing: bool) {
        let raw = self.node_text(node).trim().to_string();
        let Some(mut tag) = parse_tag(&raw, self_closing) else {
            self.write_line(depth, &raw);
            return;
        };
        reorder_attributes(&mut tag.attributes, self.options.attribute_sort);
        let rendered_attributes: Vec<String> = tag
            .attributes
            .iter()
            .map(|attribute| self.render_attribute(attribute))
            .collect();
        let inline = self.render_inline_tag(&tag.name, &rendered_attributes, self_closing);

        if !self.should_break_into_multiline(&raw, &inline, &rendered_attributes) {
            self.write_line(depth, &inline);
            return;
        }
        if rendered_attributes.is_empty() {
            self.emit_attributeless_multiline(depth, &tag.name, self_closing);
            return;
        }
        self.emit_multiline_tag(depth, &mut tag, self_closing);
    }

    /// Build the one-line rendering of a tag with all attributes inline.
    /// Used as the candidate both for the Auto-layout width check and as
    /// the direct output when no wrapping is needed.
    fn render_inline_tag(
        &self,
        name: &str,
        rendered_attributes: &[String],
        self_closing: bool,
    ) -> String {
        let mut inline = format!("<{name}");
        if !rendered_attributes.is_empty() {
            inline.push(' ');
            inline.push_str(&rendered_attributes.join(" "));
        }
        if self_closing {
            inline.push_str(self.self_closing_suffix());
        } else {
            inline.push('>');
        }
        inline
    }

    /// Decide whether the attribute layout forces (or permits) breaking
    /// a tag across multiple lines. `SingleLine` never breaks;
    /// `MultiLine` always does when any attributes exist; `Auto` breaks
    /// on source-side newlines or inline-width overflow.
    fn should_break_into_multiline(
        &self,
        raw: &str,
        inline: &str,
        rendered_attributes: &[String],
    ) -> bool {
        match self.options.attribute_layout {
            AttributeLayout::SingleLine => false,
            AttributeLayout::MultiLine => !rendered_attributes.is_empty(),
            AttributeLayout::Auto => {
                raw.contains('\n') || inline.len() > self.options.max_inline_tag_width
            }
        }
    }

    /// Emit an attributeless tag that still needs breaking onto its own
    /// line (e.g. forced by `MultiLine` layout). The open bracket goes
    /// on one line, closer on the next — mirrors the W3 convention.
    fn emit_attributeless_multiline(&mut self, depth: usize, tag_name: &str, self_closing: bool) {
        self.write_line(depth, &format!("<{tag_name}"));
        if self_closing {
            self.write_line(depth, self.self_closing_suffix());
        } else {
            self.write_line(depth, ">");
        }
    }

    /// Full multi-line tag emission: apply the path-data auto-wrap pass,
    /// choose a chunking strategy (canonical groups vs fixed chunks),
    /// then either ride the first chunk on the tag line
    /// (`AlignToTagName`) or place the opening bracket alone on line 1
    /// (`OneLevel`) and emit each remaining chunk on its own wrapped
    /// line.
    fn emit_multiline_tag(&mut self, depth: usize, tag: &mut ParsedTag, self_closing: bool) {
        let wrapped_prefix = self.wrapped_attribute_prefix(depth, &tag.name);
        self.auto_wrap_path_data_values(&mut tag.attributes, &wrapped_prefix);

        // Force one-attribute-per-line when any value carries internal
        // newlines (typical of `d="..."` path data in W3 samples). The
        // continuation-alignment logic in `render_attribute_aligned`
        // assumes a known start column for the attribute name; packing
        // multiple such attributes per wrapped line would break that.
        let has_multiline_value = tag
            .attributes
            .iter()
            .any(|a| a.value.as_ref().is_some_and(|v| v.raw.contains('\n')));

        // AlignToTagName pairs naturally with "first attribute inline on
        // the tag line": the wrapped-prefix width equals the column
        // where the first attribute would sit inline (indent + "<tag "),
        // so `render_attribute_aligned` produces correct continuation
        // alignment for the first attr's multi-line values *and* the
        // same prefix aligns subsequent wrapped attrs under the first.
        // OneLevel cannot do this cleanly — its column math differs —
        // so we keep the existing "<tag alone on line 1" layout there.
        let first_inline = matches!(
            self.options.wrapped_attribute_indent,
            WrappedAttributeIndent::AlignToTagName,
        );
        let closer = if self_closing {
            self.self_closing_suffix()
        } else {
            ">"
        };

        let chunks = self.build_wrap_chunks(&tag.attributes, &wrapped_prefix, has_multiline_value);

        if first_inline {
            self.emit_first_inline_layout(depth, tag, chunks, &wrapped_prefix, closer);
        } else {
            self.emit_one_level_layout(depth, tag, &chunks, &wrapped_prefix, closer);
        }
    }

    /// Auto-wrap minified `d="…"` path data and `<polyline/polygon>
    /// points="…"` values at semantic boundaries (M/L/C segments,
    /// coordinate pairs) when a single inline line would overflow
    /// `max_inline_tag_width`. Values that already carry source
    /// newlines skip this pass and keep their preserved layout.
    fn auto_wrap_path_data_values(&self, attributes: &mut [ParsedAttribute], wrapped_prefix: &str) {
        for attribute in attributes {
            let Some(value) = attribute.value.as_mut() else {
                continue;
            };
            let name_width = attribute.name.chars().count();
            let available = self
                .options
                .max_inline_tag_width
                .saturating_sub(wrapped_prefix.len() + name_width + 2);
            if let Some(wrapped) = wrap_path_data(&attribute.name, &value.raw, available) {
                value.raw = wrapped;
            }
        }
    }

    /// Partition attributes into chunks that will each occupy one
    /// wrapped line.
    ///
    /// - Canonical sort + no multiline values: one wrapped line per
    ///   canonical group (identity / geometry / drawing / refs /
    ///   presentation / other / namespaces / version). If a group's
    ///   rendered width exceeds budget, fall back to one-per-line
    ///   within that group.
    /// - Otherwise: chunks of `attributes_per_line` (existing
    ///   behavior; multiline values already force `per_line=1` because
    ///   the continuation-alignment helper assumes a known column).
    fn build_wrap_chunks(
        &self,
        attributes: &[ParsedAttribute],
        wrapped_prefix: &str,
        has_multiline_value: bool,
    ) -> Vec<Vec<usize>> {
        let budget = self
            .options
            .max_inline_tag_width
            .saturating_sub(wrapped_prefix.len());
        if matches!(self.options.attribute_sort, AttributeSort::Canonical) && !has_multiline_value {
            partition_by_canonical_group(attributes)
                .into_iter()
                .flat_map(|group| split_group_if_overflow(attributes, group, budget))
                .collect()
        } else {
            let per_line = if has_multiline_value {
                1
            } else {
                self.options.attributes_per_line.max(1)
            };
            (0..attributes.len())
                .collect::<Vec<_>>()
                .chunks(per_line)
                .map(<[usize]>::to_vec)
                .collect()
        }
    }

    /// `AlignToTagName` layout: the first chunk rides the tag line
    /// with `<tag ` prefix. If it would overflow the budget, pop
    /// attributes off its tail until it fits; popped attrs become a
    /// new wrapped chunk at the front of the rest. At minimum the
    /// first attribute stays on the tag line — matching W3 SVG sample
    /// style.
    fn emit_first_inline_layout(
        &mut self,
        depth: usize,
        tag: &ParsedTag,
        mut chunks: Vec<Vec<usize>>,
        wrapped_prefix: &str,
        closer: &str,
    ) {
        let (first_chunk_indices, rest_chunks) = split_first_chunk_for_tag_line(
            &tag.attributes,
            &mut chunks,
            self.indent(depth).len() + tag.name.chars().count() + 2, // "<" + name + " "
            self.options.max_inline_tag_width,
            |attr| self.render_attribute_aligned(attr, wrapped_prefix),
        );
        let first_rendered: Vec<String> = first_chunk_indices
            .iter()
            .map(|&i| self.render_attribute_aligned(&tag.attributes[i], wrapped_prefix))
            .collect();
        let mut tag_line = format!(
            "{}<{} {}",
            self.indent(depth),
            tag.name,
            first_rendered.join(" ")
        );
        if rest_chunks.is_empty() {
            tag_line.push_str(closer);
        }
        tag_line.push('\n');
        self.out.push_str(&tag_line);
        self.emit_wrapped_chunks(tag, &rest_chunks, wrapped_prefix, closer);
    }

    /// `OneLevel` layout: the opening bracket sits alone on line 1 at
    /// `depth` indent; every chunk wraps onto its own line at
    /// `depth + 1` indent (the `wrapped_prefix`).
    fn emit_one_level_layout(
        &mut self,
        depth: usize,
        tag: &ParsedTag,
        chunks: &[Vec<usize>],
        wrapped_prefix: &str,
        closer: &str,
    ) {
        self.write_line(depth, &format!("<{}", tag.name));
        self.emit_wrapped_chunks(tag, chunks, wrapped_prefix, closer);
    }

    /// Emit pre-computed chunks one-per-line at `wrapped_prefix`,
    /// appending `closer` to the final chunk's line.
    fn emit_wrapped_chunks(
        &mut self,
        tag: &ParsedTag,
        chunks: &[Vec<usize>],
        wrapped_prefix: &str,
        closer: &str,
    ) {
        for (index, chunk) in chunks.iter().enumerate() {
            let rendered: Vec<String> = chunk
                .iter()
                .map(|&i| self.render_attribute_aligned(&tag.attributes[i], wrapped_prefix))
                .collect();
            let mut line = rendered.join(" ");
            if index == chunks.len() - 1 {
                line.push_str(closer);
            }
            self.write_prefixed_line(wrapped_prefix, &line);
        }
    }

    const fn self_closing_suffix(&self) -> &'static str {
        if self.options.space_before_self_close {
            " />"
        } else {
            "/>"
        }
    }

    fn render_attribute(&self, attribute: &ParsedAttribute) -> String {
        attribute.value.as_ref().map_or_else(
            || attribute.name.clone(),
            |value| format!("{}={}", attribute.name, self.render_attribute_value(value)),
        )
    }

    fn render_attribute_value(&self, value: &ParsedAttributeValue) -> String {
        match self.options.quote_style {
            QuoteStyle::Preserve => match value.original_quote {
                Some('\'') => format!("'{}'", value.raw),
                Some('"') => format!("\"{}\"", value.raw),
                Some(other) => format!("{other}{}{other}", value.raw),
                None => value.raw.clone(),
            },
            QuoteStyle::Double => format!("\"{}\"", value.raw.replace('"', "&quot;")),
            QuoteStyle::Single => format!("'{}'", value.raw.replace('\'', "&apos;")),
        }
    }

    /// Render an attribute, aligning any continuation lines of a multi-line
    /// value to the column directly under the first value character (i.e.
    /// just after the opening quote).
    ///
    /// `prefix` is the whitespace string that will precede this attribute
    /// on its line (the wrapped-attribute indent, which may mix tabs and
    /// spaces). Continuation lines are emitted as `prefix` plus spaces
    /// spanning `name=` and the opening quote, so the visual alignment
    /// holds regardless of the caller's tab-width setting — mixing pure
    /// spaces with a tab-indented prefix would misalign at any tab width
    /// other than one.
    ///
    /// For values without embedded newlines this delegates to
    /// [`Self::render_attribute_value`]; for multi-line values it strips
    /// each continuation line's original leading whitespace and re-indents
    /// it, matching W3 SVG sample style where `<path d="M … " ` wrapping
    /// preserves logical path-command groupings under a stable column.
    fn render_attribute_aligned(&self, attribute: &ParsedAttribute, prefix: &str) -> String {
        let Some(value) = attribute.value.as_ref() else {
            return attribute.name.clone();
        };
        if !value.raw.contains('\n') {
            return format!("{}={}", attribute.name, self.render_attribute_value(value));
        }

        let quote = match self.options.quote_style {
            QuoteStyle::Preserve => value.original_quote.unwrap_or('"'),
            QuoteStyle::Double => '"',
            QuoteStyle::Single => '\'',
        };
        let name_width = attribute.name.chars().count();
        let mut pad = String::with_capacity(prefix.len() + name_width + 2);
        pad.push_str(prefix);
        // `name=` + opening quote → name_width + 2 spaces of alignment.
        for _ in 0..name_width + 2 {
            pad.push(' ');
        }

        let mut result = String::with_capacity(value.raw.len() + pad.len() * 2 + 8);
        let mut lines = value.raw.split('\n');
        if let Some(first) = lines.next() {
            result.push_str(&attribute.name);
            result.push('=');
            result.push(quote);
            result.push_str(first);
        }
        for line in lines {
            result.push('\n');
            result.push_str(&pad);
            result.push_str(line.trim_start());
        }
        result.push(quote);
        result
    }

    fn wrapped_attribute_prefix(&self, depth: usize, tag_name: &str) -> String {
        match self.options.wrapped_attribute_indent {
            WrappedAttributeIndent::OneLevel => self.indent(depth + 1),
            WrappedAttributeIndent::AlignToTagName => {
                let mut prefix = self.indent(depth);
                // Align to the column right after `<tag ` in a hypothetical one-line form.
                prefix.push_str(&" ".repeat(tag_name.chars().count() + 2));
                prefix
            }
        }
    }

    fn write_prefixed_line(&mut self, prefix: &str, text: &str) {
        self.out.push_str(prefix);
        self.out.push_str(text);
        self.out.push('\n');
    }

    fn write_text_node(&mut self, node: Node<'_>, depth: usize) {
        let text = self.node_text(node).to_string();
        self.write_text_str(&text, depth);
    }

    fn write_text_str(&mut self, text: &str, depth: usize) {
        if text.trim().is_empty() {
            return;
        }

        match self.options.text_content {
            TextContentMode::Collapse => {
                for line in text.lines() {
                    let collapsed = collapse_whitespace(line);
                    if collapsed.is_empty() {
                        continue;
                    }
                    self.write_line(depth, &collapsed);
                }
            }
            TextContentMode::Maintain => {
                self.write_preserved_str(text, depth);
            }
            TextContentMode::Prettify => {
                for line in text.lines() {
                    let trimmed = line.trim();
                    if trimmed.is_empty() {
                        continue;
                    }
                    self.write_line(depth, trimmed);
                }
            }
        }
    }

    fn write_preserved_block_text(&mut self, node: Node<'_>, depth: usize) {
        let text = self.node_text(node).to_string();
        self.write_preserved_str(&text, depth);
    }

    fn write_preserved_embedded_text(&mut self, node: Node<'_>, depth: usize) {
        let text = self.node_text(node).to_string();
        self.write_embedded_preserved_str(&text, depth);
    }

    fn write_preserved_str(&mut self, text: &str, depth: usize) {
        if text.trim().is_empty() {
            return;
        }

        let lines: Vec<&str> = text.lines().collect();
        let first_non_empty = lines.iter().position(|line| !line.trim().is_empty());
        let last_non_empty = lines.iter().rposition(|line| !line.trim().is_empty());
        let (Some(start), Some(end)) = (first_non_empty, last_non_empty) else {
            return;
        };

        let block = &lines[start..=end];
        let min_leading = block
            .iter()
            .filter(|line| !line.trim().is_empty())
            .map(|line| line.chars().take_while(|c| c.is_whitespace()).count())
            .min()
            .unwrap_or(0);

        for line in block {
            let without_common_indent = line.chars().skip(min_leading).collect::<String>();
            self.write_line(depth, without_common_indent.trim_end());
        }
    }

    fn write_embedded_preserved_str(&mut self, text: &str, depth: usize) {
        if text.trim().is_empty() {
            return;
        }

        let lines: Vec<&str> = text.lines().collect();
        let first_non_empty = lines.iter().position(|line| !line.trim().is_empty());
        let last_non_empty = lines.iter().rposition(|line| !line.trim().is_empty());
        let (Some(start), Some(end)) = (first_non_empty, last_non_empty) else {
            return;
        };

        let block = &lines[start..=end];
        let min_leading = block
            .iter()
            .filter(|line| !line.trim().is_empty())
            .map(|line| line.chars().take_while(|c| c.is_whitespace()).count())
            .min()
            .unwrap_or(0);

        let mut consecutive_blank = 0usize;
        for line in block {
            let without_common_indent = line.chars().skip(min_leading).collect::<String>();
            let trimmed = without_common_indent.trim_end();
            if trimmed.is_empty() {
                consecutive_blank += 1;
                if self.should_emit_embedded_blank(consecutive_blank) {
                    self.out.push('\n');
                }
            } else {
                consecutive_blank = 0;
                self.write_line(depth, trimmed);
            }
        }
    }

    /// Try to format embedded text (style/script `raw_text`) via the callback.
    /// Returns `true` if the callback produced a result.
    ///
    /// Handles CDATA-wrapped payloads specially: the `<![CDATA[`/`]]>` markers
    /// are stripped before the host formatter sees the content (the CSS/JS
    /// parsers reject them at column 0 as syntax errors — see W3 SVG path
    /// samples). When CDATA was present, XML entity decoding/encoding is
    /// skipped — inside a CDATA section, `&amp;` is literal, not escaped —
    /// and the wrapper is re-emitted on output to preserve the XML-safety
    /// semantics the author chose.
    fn try_format_embedded_text(
        &mut self,
        node: Node<'_>,
        language: EmbeddedLanguage,
        depth: usize,
        fmt: &mut dyn FnMut(EmbeddedContent<'_>) -> Option<String>,
    ) -> bool {
        let raw = self.node_text(node);
        let raw_start = node.start_byte();
        let (payload, cdata_wrapped, payload_offset) = strip_cdata_wrapper(raw).map_or_else(
            || {
                let (dedented, offset) = dedent_block_with_offset(raw);
                (decode_xml_entities(dedented), false, offset)
            },
            |(inner_offset, inner)| {
                // `inner_offset` is the byte position of `inner` within `raw`
                // (CDATA prefix + any leading whitespace stripped by trim),
                // both UTF-8 boundaries. Add the dedent offset within `inner`.
                let (dedented, offset) = dedent_block_with_offset(inner);
                (dedented, true, offset.map(|value| inner_offset + value))
            },
        );
        // `dedent_block_with_offset` yields `None` exactly when the block is
        // blank (no non-whitespace line), which also means `payload` is empty.
        // The `Some(offset)` gate below therefore subsumes an empty-payload
        // check — no separate `payload.is_empty()` guard is needed.
        let Some(payload_offset) = payload_offset else {
            return false;
        };
        let file_byte_offset = raw_start + payload_offset;
        let req = EmbeddedContent {
            language,
            content: &payload,
            indent_depth: depth,
            file_byte_offset,
        };
        fmt(req).is_some_and(|formatted| {
            if cdata_wrapped {
                self.write_cdata_block(&formatted, depth);
            } else {
                let encoded = encode_xml_entities(&formatted);
                self.write_indented_block(&encoded, depth);
            }
            true
        })
    }

    /// Write a formatted host block wrapped in a CDATA section.
    ///
    /// The opening `<![CDATA[` sits at `depth`, payload lines are indented
    /// at `depth + 1` via [`Self::write_indented_block`], and the closing
    /// `]]>` returns to `depth`. Matches the nested-tag indentation scheme
    /// used by surrounding element children.
    fn write_cdata_block(&mut self, text: &str, depth: usize) {
        self.write_line(depth, "<![CDATA[");
        self.write_indented_block(text, depth + 1);
        self.write_line(depth, "]]>");
    }

    /// Try to format `foreignObject` inner content via the callback.
    /// On success, writes the full element (start tag, formatted content, end tag).
    fn try_format_foreign_object(
        &mut self,
        children: &[Node<'_>],
        depth: usize,
        fmt: &mut dyn FnMut(EmbeddedContent<'_>) -> Option<String>,
    ) -> Option<()> {
        let start_tag = children.iter().find(|c| c.kind() == "start_tag")?;
        let end_tag = children.iter().find(|c| c.kind() == "end_tag")?;

        let content_start = start_tag.end_byte();
        let content_end = end_tag.start_byte();
        if content_start >= content_end {
            return None;
        }

        let raw = std::str::from_utf8(&self.source[content_start..content_end]).ok()?;
        let (content, offset) = dedent_block_with_offset(raw);
        // `dedent_block_with_offset` returns `None` exactly for blank blocks,
        // which is also the only case where `content` is empty — so the
        // `Some(offset)` gate alone rules out empty content.
        let offset = offset?;
        let file_byte_offset = content_start + offset;

        let req = EmbeddedContent {
            language: EmbeddedLanguage::Html,
            content: &content,
            indent_depth: depth + 1,
            file_byte_offset,
        };
        let formatted = fmt(req)?;

        // Write start tag, formatted content, end tag.
        self.write_tag_node(*start_tag, depth, false);
        self.write_indented_block(&formatted, depth + 1);
        let end_text = self.node_text(*end_tag).trim().to_string();
        self.write_line(depth, &end_text);
        Some(())
    }

    /// Write pre-formatted text, re-indented to the given depth.
    /// Preserves the content's internal indentation structure.
    /// Leading/trailing blank lines are stripped; interior consecutive
    /// blank lines are normalized per the `blank_lines` option.
    fn write_indented_block(&mut self, text: &str, depth: usize) {
        let lines: Vec<&str> = text.lines().collect();
        let Some(first) = lines.iter().position(|l| !l.trim().is_empty()) else {
            return;
        };
        let last = lines
            .iter()
            .rposition(|l| !l.trim().is_empty())
            .unwrap_or(first);
        let block = &lines[first..=last];

        let indent = self.indent(depth);
        let mut consecutive_blank = 0usize;
        for line in block {
            if line.trim().is_empty() {
                consecutive_blank += 1;
                if self.should_emit_embedded_blank(consecutive_blank) {
                    self.out.push('\n');
                }
            } else {
                consecutive_blank = 0;
                self.out.push_str(&indent);
                self.out.push_str(line);
                self.out.push('\n');
            }
        }
    }

    /// Process ignore directives and whitespace-skip logic for a child node.
    ///
    /// Returns `true` if the child was fully handled (caller should `continue`).
    fn handle_ignore(
        &mut self,
        child: Node<'_>,
        in_ignore_range: &mut bool,
        ignore_next: &mut bool,
        prev_was_comment: &mut bool,
        prev_end: &mut Option<usize>,
    ) -> bool {
        let mut skip_ignore_self = false;

        if child.kind() == "comment" {
            // Inside an ignore range, only look for the end marker.
            // All other directives are preserved verbatim.
            if *in_ignore_range {
                if self.is_ignore_directive(child, "ignore-end") {
                    self.write_source_span(*prev_end, child.end_byte());
                    *in_ignore_range = false;
                    *prev_was_comment = true;
                    *prev_end = Some(child.end_byte());
                    return true;
                }
                // Not an end marker — fall through to the in_ignore_range
                // raw-write below. Don't set ignore_next or skip_ignore_self.
            } else {
                if self.is_ignore_directive(child, "ignore-start") {
                    *in_ignore_range = true;
                    if let Some(end) = *prev_end {
                        self.emit_gap(end, child.start_byte(), *prev_was_comment);
                    }
                    self.write_source_span(Some(child.start_byte()), child.end_byte());
                    *prev_was_comment = true;
                    *prev_end = Some(child.end_byte());
                    return true;
                }
                if self.is_ignore_directive(child, "ignore") {
                    *ignore_next = true;
                    skip_ignore_self = true;
                }
            }
        }

        // Skip whitespace-only text — but not inside an ignore range,
        // where we need to preserve everything verbatim.
        if !*in_ignore_range
            && matches!(child.kind(), "text" | "raw_text")
            && self.node_text(child).trim().is_empty()
        {
            return true;
        }

        if !skip_ignore_self && *in_ignore_range {
            // Inside an ignore range: write from prev_end through this node,
            // preserving the original gap + content verbatim.
            self.write_source_span(*prev_end, child.end_byte());
            *prev_was_comment = child.kind() == "comment";
            *prev_end = Some(child.end_byte());
            return true;
        }

        if !skip_ignore_self && *ignore_next {
            // Single-element ignore: write only the node bytes.
            // The gap before it was already emitted by the previous
            // write_line/emit_gap, so don't re-emit it.
            self.write_source_span(Some(child.start_byte()), child.end_byte());
            if !self.out.ends_with('\n') {
                self.out.push('\n');
            }
            *ignore_next = false;
            *prev_was_comment = child.kind() == "comment";
            *prev_end = Some(child.end_byte());
            return true;
        }

        false
    }

    /// Check if a comment node matches `<!-- {prefix}-{suffix} -->`.
    ///
    /// Uses the tree-sitter `text` field on the comment node to get
    /// the inner content without manual `<!--`/`-->` stripping.
    fn is_ignore_directive(&self, node: Node<'_>, suffix: &str) -> bool {
        let inner = node
            .child_by_field_name("text")
            .map_or("", |t| self.node_text(t).trim());
        self.options
            .ignore_prefixes
            .iter()
            .any(|prefix| inner == format!("{prefix}-{suffix}"))
    }

    /// Write a source span verbatim, from `from` (or start of node if None)
    /// through `to`. Preserves original whitespace, gaps, and content exactly.
    fn write_source_span(&mut self, from: Option<usize>, to: usize) {
        let start = from.unwrap_or(to);
        if start < to {
            self.out
                .push_str(std::str::from_utf8(&self.source[start..to]).unwrap_or_default());
        }
    }

    /// Count blank lines in the source gap between two byte positions.
    fn source_blank_lines(&self, from: usize, to: usize) -> usize {
        if from >= to {
            return 0;
        }
        let gap = std::str::from_utf8(&self.source[from..to]).unwrap_or_default();
        let newlines = gap.chars().filter(|&c| c == '\n').count();
        newlines.saturating_sub(1)
    }

    /// Emit blank lines between siblings based on the `blank_lines` option.
    ///
    /// When `prev_was_comment` is true and mode is `Insert`, the gap is
    /// skipped — comments attach downward to the element they annotate.
    fn emit_gap(&mut self, prev_end: usize, next_start: usize, prev_was_comment: bool) {
        let source_gaps = self.source_blank_lines(prev_end, next_start);
        let count = match self.options.blank_lines {
            BlankLines::Remove => 0,
            BlankLines::Preserve => source_gaps,
            BlankLines::Truncate => source_gaps.min(1),
            BlankLines::Insert => usize::from(!prev_was_comment),
        };
        for _ in 0..count {
            self.out.push('\n');
        }
    }

    /// Whether an embedded-content blank line should be emitted.
    ///
    /// `consecutive` is how many blank lines in a row have been seen so far
    /// (1 = first blank, 2 = second, etc.). `Truncate` collapses runs of 2+
    /// to 1, `Remove` strips all, and `Preserve`/`Insert` pass through
    /// (those modes only meaningfully apply to sibling element gaps).
    const fn should_emit_embedded_blank(&self, consecutive: usize) -> bool {
        match self.options.blank_lines {
            BlankLines::Remove => false,
            BlankLines::Truncate => consecutive <= 1,
            BlankLines::Preserve | BlankLines::Insert => true,
        }
    }

    fn node_text(&self, node: Node<'_>) -> &str {
        std::str::from_utf8(&self.source[node.byte_range()]).unwrap_or_default()
    }

    fn write_line(&mut self, depth: usize, text: &str) {
        self.out.push_str(&self.indent(depth));
        self.out.push_str(text);
        self.out.push('\n');
    }

    fn indent(&self, depth: usize) -> String {
        if self.options.insert_spaces {
            " ".repeat(depth.saturating_mul(self.options.indent_width))
        } else {
            "\t".repeat(depth)
        }
    }
}

fn text_content_entity_bounds<'a>(
    children: &[Node<'a>],
    tag_name: &str,
) -> Option<(Node<'a>, Node<'a>)> {
    if !is_text_content_element(tag_name)
        || !children
            .iter()
            .any(|child| child.kind() == "entity_reference")
    {
        return None;
    }

    let start = children
        .iter()
        .find(|child| child.kind() == "start_tag")
        .copied()?;
    let end = children
        .iter()
        .find(|child| child.kind() == "end_tag")
        .copied()?;
    let all_inline = children
        .iter()
        .filter(|child| !matches!(child.kind(), "start_tag" | "end_tag"))
        .all(|child| matches!(child.kind(), "text" | "raw_text" | "entity_reference"));

    all_inline.then_some((start, end))
}