panache 2.34.0

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

const TABLE_BLOCK_INDENT: &str = "  ";

fn indent_table_block(block: &str) -> String {
    let already_indented = block
        .lines()
        .filter(|line| !line.is_empty())
        .all(|line| line.starts_with(TABLE_BLOCK_INDENT));
    if already_indented {
        return block.to_string();
    }

    let mut output = String::with_capacity(block.len() + 32);
    let mut line_start = 0;

    for (idx, ch) in block.char_indices() {
        if ch == '\n' {
            let line = &block[line_start..idx];
            if !line.is_empty() {
                output.push_str(TABLE_BLOCK_INDENT);
            }
            output.push_str(line);
            output.push('\n');
            line_start = idx + 1;
        }
    }

    if line_start < block.len() {
        let line = &block[line_start..];
        if !line.is_empty() {
            output.push_str(TABLE_BLOCK_INDENT);
        }
        output.push_str(line);
    }

    output
}

fn normalize_table_caption(caption_body: &str) -> String {
    let normalized_body = caption_body
        .lines()
        .map(str::trim)
        .collect::<Vec<_>>()
        .join("\n")
        .trim()
        .to_string();

    if normalized_body.is_empty() {
        "Table:".to_string()
    } else {
        format!("Table: {normalized_body}")
    }
}

fn collapse_ascii_whitespace(text: &str) -> String {
    text.split_ascii_whitespace().collect::<Vec<_>>().join(" ")
}

fn wrap_words_with_widths(words: &[&str], first_width: usize, rest_width: usize) -> Vec<String> {
    if words.is_empty() {
        return Vec::new();
    }

    let mut out = Vec::new();
    let mut current = String::new();
    let mut current_width = 0usize;
    let mut line_width = first_width.max(1);

    for word in words {
        let word_width = word.width();
        if current.is_empty() {
            current.push_str(word);
            current_width = word_width;
            continue;
        }

        if current_width + 1 + word_width > line_width {
            out.push(current);
            current = (*word).to_string();
            current_width = word_width;
            line_width = rest_width.max(1);
            continue;
        }

        current.push(' ');
        current.push_str(word);
        current_width += 1 + word_width;
    }

    if !current.is_empty() {
        out.push(current);
    }

    out
}

fn split_sentences(text: &str, language: SentenceLanguage) -> Vec<String> {
    split_sentence_text(text, language)
}

fn format_table_caption_with_language(
    caption_text: &str,
    config: &Config,
    sentence_language: SentenceLanguage,
) -> String {
    let Some(rest) = caption_text.strip_prefix("Table:") else {
        return caption_text.to_string();
    };
    let body = rest.trim();
    if body.is_empty() {
        return "Table:".to_string();
    }

    let wrap_mode = config.wrap.clone().unwrap_or(WrapMode::Reflow);
    let available_width = config
        .line_width
        .saturating_sub(TABLE_BLOCK_INDENT.len())
        .max(1);

    match wrap_mode {
        WrapMode::Preserve => caption_text.to_string(),
        WrapMode::Reflow => {
            let normalized = collapse_ascii_whitespace(body);
            let words: Vec<&str> = normalized.split_ascii_whitespace().collect();
            let first_width = available_width.saturating_sub("Table: ".width()).max(1);
            let wrapped = wrap_words_with_widths(&words, first_width, available_width);
            if wrapped.is_empty() {
                "Table:".to_string()
            } else {
                let mut out = String::new();
                out.push_str("Table: ");
                out.push_str(&wrapped[0]);
                for line in wrapped.iter().skip(1) {
                    out.push('\n');
                    out.push_str(line);
                }
                out
            }
        }
        WrapMode::Sentence => {
            let normalized = collapse_ascii_whitespace(body);
            let lines = split_sentences(&normalized, sentence_language);
            if lines.is_empty() {
                "Table:".to_string()
            } else {
                let mut out = String::new();
                out.push_str("Table: ");
                out.push_str(&lines[0]);
                for line in lines.iter().skip(1) {
                    out.push('\n');
                    out.push_str(line);
                }
                out
            }
        }
    }
}

fn format_table_caption(caption_text: &str, config: &Config, node: &SyntaxNode) -> String {
    let language = resolve_sentence_language(node);
    format_table_caption_with_language(caption_text, config, language)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Alignment {
    Left,
    Right,
    Center,
    Default,
}

struct TableData {
    rows: Vec<Vec<String>>,                        // All rows including header
    alignments: Vec<Alignment>,                    // Column alignments
    caption: Option<String>,                       // Optional caption text
    caption_after: bool,                           // True if caption comes after table
    column_widths: Option<Vec<usize>>, // For simple tables: preserve separator dash lengths
    column_positions: Option<Vec<(usize, usize)>>, // For simple tables: preserve (start, end) positions
    has_header: bool,                              // True if table has a header row
}

/// Format cell content, handling both TEXT tokens and inline elements
fn format_cell_content(node: &SyntaxNode, config: &Config) -> String {
    let mut result = String::new();

    for child in node.children_with_tokens() {
        match child {
            NodeOrToken::Token(token) => {
                if token.kind() == SyntaxKind::TEXT
                    || token.kind() == SyntaxKind::NEWLINE
                    || token.kind() == SyntaxKind::ESCAPED_CHAR
                {
                    result.push_str(token.text());
                }
            }
            NodeOrToken::Node(node) => {
                // Handle inline elements (emphasis, code, links, etc.)
                result.push_str(&format_inline_node(&node, config));
            }
        }
    }

    result
}

/// Extract cell contents from TABLE_CELL nodes if present, otherwise fall back to text splitting
fn extract_row_cells(row_node: &SyntaxNode, config: &Config) -> Vec<String> {
    let mut cells = Vec::new();

    // Check if this row has TABLE_CELL children
    let has_table_cells = row_node
        .children()
        .any(|child| child.kind() == SyntaxKind::TABLE_CELL);

    if has_table_cells {
        // New approach: extract from TABLE_CELL nodes
        for child in row_node.children() {
            if child.kind() == SyntaxKind::TABLE_CELL {
                cells.push(format_cell_content(&child, config));
            }
        }
    }

    cells
}

/// Extract alignments from separator line (e.g., "|:---|---:|:---:|")
fn extract_alignments(separator_text: &str) -> Vec<Alignment> {
    let trimmed = separator_text.trim();
    let cells: Vec<&str> = trimmed.split('|').collect();

    let mut alignments = Vec::new();

    for cell in cells {
        let cell = cell.trim();

        // Skip empty cells (from leading/trailing pipes)
        if cell.is_empty() {
            continue;
        }

        let starts_colon = cell.starts_with(':');
        let ends_colon = cell.ends_with(':');

        let alignment = match (starts_colon, ends_colon) {
            (true, true) => Alignment::Center,
            (true, false) => Alignment::Left,
            (false, true) => Alignment::Right,
            (false, false) => Alignment::Default,
        };

        alignments.push(alignment);
    }

    alignments
}

/// Split a row into cells, handling leading/trailing pipes
fn split_row(row_text: &str) -> Vec<String> {
    let trimmed = row_text.trim();
    let cells: Vec<&str> = trimmed.split('|').collect();

    cells
        .iter()
        .enumerate()
        .filter_map(|(i, cell)| {
            let cell = cell.trim();
            // Skip first and last if they're empty (from leading/trailing pipes)
            if (i == 0 || i == cells.len() - 1) && cell.is_empty() {
                None
            } else {
                Some(cell.to_string())
            }
        })
        .collect()
}

/// Extract structured data from pipe table AST node
fn extract_pipe_table_data(node: &SyntaxNode, config: &Config) -> TableData {
    let mut rows = Vec::new();
    let mut alignments = Vec::new();
    let mut caption = None;
    let mut caption_after = false;
    let mut seen_separator = false;

    for child in node.children() {
        match child.kind() {
            SyntaxKind::TABLE_CAPTION => {
                let mut caption_body = String::new();

                for caption_child in child.children_with_tokens() {
                    match caption_child {
                        rowan::NodeOrToken::Token(token)
                            if token.kind() == SyntaxKind::TABLE_CAPTION_PREFIX =>
                        {
                            // Skip the original prefix - we're adding normalized "Table: " above
                        }
                        rowan::NodeOrToken::Token(token) => {
                            caption_body.push_str(token.text());
                        }
                        rowan::NodeOrToken::Node(node) => {
                            caption_body.push_str(&node.text().to_string());
                        }
                    }
                }

                caption = Some(normalize_table_caption(&caption_body));
                caption_after = seen_separator; // After if we've seen separator/rows
            }
            SyntaxKind::TABLE_SEPARATOR => {
                let separator_text = child.text().to_string();
                alignments = extract_alignments(&separator_text);
                seen_separator = true;
            }
            SyntaxKind::TABLE_HEADER | SyntaxKind::TABLE_ROW => {
                let row_content = format_cell_content(&child, config);
                let cells = split_row(&row_content);
                rows.push(cells);
            }
            _ => {}
        }
    }

    TableData {
        rows,
        alignments,
        caption,
        caption_after,
        column_widths: None,
        column_positions: None,
        has_header: true, // Pipe tables always have headers
    }
}

/// Calculate the maximum width needed for each column
fn calculate_column_widths(rows: &[Vec<String>]) -> Vec<usize> {
    if rows.is_empty() {
        return Vec::new();
    }

    let num_cols = rows.iter().map(|r| r.len()).max().unwrap_or(0);
    let mut widths = vec![3; num_cols]; // Minimum width of 3 for "---"

    for row in rows {
        for (col_idx, cell) in row.iter().enumerate() {
            if col_idx < num_cols {
                // Use unicode display width instead of byte length
                widths[col_idx] = widths[col_idx].max(cell.width());
            }
        }
    }

    widths
}

/// Calculate the maximum width needed for each column (grid tables)
/// Grid tables don't have a minimum width constraint
fn calculate_grid_column_widths(rows: &[Vec<String>]) -> Vec<usize> {
    if rows.is_empty() {
        return Vec::new();
    }

    let num_cols = rows.iter().map(|r| r.len()).max().unwrap_or(0);
    let mut widths = vec![0; num_cols];

    for row in rows {
        for (col_idx, cell) in row.iter().enumerate() {
            if col_idx < num_cols {
                // Use unicode display width instead of byte length
                widths[col_idx] = widths[col_idx].max(cell.width());
            }
        }
    }

    widths
}

/// Format a pipe table with consistent alignment and padding
pub fn format_pipe_table(node: &SyntaxNode, config: &Config) -> String {
    let table_data = extract_pipe_table_data(node, config);
    let mut output = String::new();

    // Early return if no rows
    if table_data.rows.is_empty() {
        return node.text().to_string();
    }

    let widths = calculate_column_widths(&table_data.rows);

    // Emit caption before if present
    if let Some(ref caption_text) = table_data.caption
        && !table_data.caption_after
    {
        let formatted_caption = format_table_caption(caption_text, config, node);
        output.push_str(&formatted_caption);
        output.push_str("\n\n"); // Blank line between caption and table
    }

    // Format rows
    for (row_idx, row) in table_data.rows.iter().enumerate() {
        output.push('|');

        for (col_idx, cell) in row.iter().enumerate() {
            let width = widths.get(col_idx).copied().unwrap_or(3);
            let alignment = table_data
                .alignments
                .get(col_idx)
                .copied()
                .unwrap_or(Alignment::Default);

            // Add padding
            output.push(' ');

            // Apply alignment using unicode display width
            let cell_width = cell.width();
            let total_padding = width.saturating_sub(cell_width);

            let padded_cell = if row_idx == 0 {
                // Header row: always left-align
                format!("{}{}", cell, " ".repeat(total_padding))
            } else {
                // Data rows: respect alignment
                match alignment {
                    Alignment::Left | Alignment::Default => {
                        format!("{}{}", cell, " ".repeat(total_padding))
                    }
                    Alignment::Right => {
                        format!("{}{}", " ".repeat(total_padding), cell)
                    }
                    Alignment::Center => {
                        let left_padding = total_padding / 2;
                        let right_padding = total_padding - left_padding;
                        format!(
                            "{}{}{}",
                            " ".repeat(left_padding),
                            cell,
                            " ".repeat(right_padding)
                        )
                    }
                }
            };

            output.push_str(&padded_cell);
            output.push_str(" |");
        }

        output.push('\n');

        // Insert separator after first row (header)
        if row_idx == 0 {
            output.push('|');

            for (col_idx, width) in widths.iter().enumerate() {
                let alignment = table_data
                    .alignments
                    .get(col_idx)
                    .copied()
                    .unwrap_or(Alignment::Default);

                output.push(' ');

                // Create separator with alignment markers
                let separator = match alignment {
                    Alignment::Left => format!(":{:-<width$}", "", width = width - 1),
                    Alignment::Right => format!("{:->width$}:", "", width = width - 1),
                    Alignment::Center => format!(":{:-<width$}:", "", width = width - 2),
                    Alignment::Default => format!("{:-<width$}", "", width = width),
                };

                output.push_str(&separator);
                output.push_str(" |");
            }

            output.push('\n');
        }
    }

    // Emit caption after if present
    if let Some(ref caption_text) = table_data.caption
        && table_data.caption_after
    {
        output.push('\n');
        let formatted_caption = format_table_caption(caption_text, config, node);
        output.push_str(&formatted_caption);
        output.push('\n');
    }

    indent_table_block(&output)
}

// Grid Table Formatting
// ============================================================================

/// Extract alignments from grid table separator line (e.g., "+:---+---:+:---:+")
fn extract_grid_alignments(separator_text: &str) -> Vec<Alignment> {
    let trimmed = separator_text.trim();

    // Split by + to get column segments
    let segments: Vec<&str> = trimmed.split('+').collect();

    let mut alignments = Vec::new();

    // Parse each segment between + signs (skip first/last empty)
    for segment in segments
        .iter()
        .skip(1)
        .take(segments.len().saturating_sub(2))
    {
        if segment.is_empty() {
            continue;
        }

        let starts_colon = segment.starts_with(':');
        let ends_colon = segment.ends_with(':');

        let alignment = match (starts_colon, ends_colon) {
            (true, true) => Alignment::Center,
            (true, false) => Alignment::Left,
            (false, true) => Alignment::Right,
            (false, false) => Alignment::Default,
        };

        alignments.push(alignment);
    }

    alignments
}

/// Split a grid table row into cells (e.g., "| A | B |" -> ["A", "B"])
fn split_grid_row(row_text: &str) -> Vec<String> {
    let trimmed = row_text.trim();

    // Split by | and filter
    let cells: Vec<&str> = trimmed.split('|').collect();

    cells
        .iter()
        .enumerate()
        .filter_map(|(i, cell)| {
            let cell = cell.trim();
            // Skip first and last if they're empty (from leading/trailing pipes)
            if (i == 0 || i == cells.len() - 1) && cell.is_empty() {
                None
            } else {
                Some(cell.to_string())
            }
        })
        .collect()
}

fn grid_separator_widths(separator_text: &str) -> Vec<usize> {
    let trimmed = separator_text.trim();
    let segments: Vec<&str> = trimmed.split('+').collect();
    segments
        .iter()
        .skip(1)
        .take(segments.len().saturating_sub(2))
        .map(|seg| seg.chars().count().saturating_sub(2))
        .collect()
}

fn format_spanning_grid_table_raw(
    raw_table: &str,
    config: &Config,
    sentence_language: SentenceLanguage,
) -> String {
    let mut lines: Vec<&str> = raw_table.lines().collect();
    while lines.last().is_some_and(|l| l.trim().is_empty()) {
        lines.pop();
    }
    if lines.is_empty() {
        return raw_table.to_string();
    }

    let mut caption: Option<String> = None;
    if let Some(last) = lines.last().copied() {
        let trimmed = last.trim_start();
        if let Some(rest) = trimmed.strip_prefix(':') {
            caption = Some(format!("Table: {}", rest.trim()));
            lines.pop();
            while lines.last().is_some_and(|l| l.trim().is_empty()) {
                lines.pop();
            }
        } else if let Some(rest) = trimmed.strip_prefix("Table:") {
            caption = Some(format!("Table: {}", rest.trim()));
            lines.pop();
            while lines.last().is_some_and(|l| l.trim().is_empty()) {
                lines.pop();
            }
        }
    }

    let mut out = String::new();
    let mut in_header_rows = true;
    let mut current_schema_cols: Option<usize> = None;
    let mut schema_widths: HashMap<usize, Vec<usize>> = HashMap::new();
    let mut numeric_cols_by_schema: HashMap<usize, Vec<bool>> = HashMap::new();
    for line in &lines {
        let t = line.trim();
        if !(t.starts_with('|') && t.ends_with('|')) || t.contains('+') {
            continue;
        }
        let segments: Vec<&str> = t.split('|').collect();
        if segments.len() < 3 {
            continue;
        }
        let cells: Vec<String> = segments
            .iter()
            .skip(1)
            .take(segments.len().saturating_sub(2))
            .map(|c| c.trim().to_string())
            .collect();
        let col_count = cells.len();
        let entry = numeric_cols_by_schema
            .entry(col_count)
            .or_insert_with(|| vec![false; col_count]);
        for (idx, cell) in cells.iter().enumerate() {
            let s = cell
                .strip_prefix('-')
                .or_else(|| cell.strip_prefix('+'))
                .unwrap_or(cell.as_str());
            if !s.is_empty()
                && s.chars()
                    .all(|c| c.is_ascii_digit() || c == ',' || c == '.')
            {
                entry[idx] = true;
            }
        }
    }
    for line in &lines {
        let t = line.trim_end();
        let tt = t.trim_start();
        if tt.starts_with('+') {
            let widths = grid_separator_widths(tt);
            if !widths.is_empty() {
                let col_count = widths.len();
                current_schema_cols = Some(col_count);
                if let Some(existing) = schema_widths.get_mut(&col_count) {
                    for (idx, w) in widths.into_iter().enumerate() {
                        existing[idx] = existing[idx].max(w);
                    }
                } else {
                    schema_widths.insert(col_count, widths);
                }
            }
            if tt.contains('=') {
                in_header_rows = false;
            }
            out.push_str(tt);
            out.push('\n');
            continue;
        }
        if !(tt.starts_with('|') && tt.ends_with('|')) || tt.contains('+') {
            out.push_str(tt);
            out.push('\n');
            continue;
        }
        let segments: Vec<&str> = tt.split('|').collect();
        let cells: Vec<String> = segments
            .iter()
            .skip(1)
            .take(segments.len().saturating_sub(2))
            .map(|c| c.trim().to_string())
            .collect();
        let col_count = cells.len();
        let mut widths = schema_widths
            .get(&col_count)
            .cloned()
            .or_else(|| current_schema_cols.and_then(|n| schema_widths.get(&n).cloned()))
            .unwrap_or_else(|| vec![0usize; col_count]);
        if widths.len() < col_count {
            widths.resize(col_count, 0);
        } else if widths.len() > col_count {
            widths.truncate(col_count);
        }
        for (i, c) in cells.iter().enumerate() {
            widths[i] = widths[i].max(c.width());
        }
        let first_cell_filled = cells.first().is_some_and(|c| !c.trim().is_empty());
        out.push('|');
        for idx in 0..col_count {
            let cell = cells.get(idx).map(String::as_str).unwrap_or("");
            let width = widths.get(idx).copied().unwrap_or(3);
            let pad = width.saturating_sub(cell.width());
            let stripped = cell
                .trim()
                .strip_prefix('-')
                .or_else(|| cell.trim().strip_prefix('+'))
                .unwrap_or(cell.trim());
            let numeric_like = !stripped.is_empty()
                && stripped
                    .chars()
                    .all(|c| c.is_ascii_digit() || c == ',' || c == '.');
            let a = if in_header_rows {
                if idx == 0 {
                    Alignment::Center
                } else if numeric_cols_by_schema
                    .get(&col_count)
                    .and_then(|v| v.get(idx))
                    .copied()
                    .unwrap_or(false)
                {
                    Alignment::Right
                } else {
                    Alignment::Left
                }
            } else if idx == 0 || (col_count == 12 && idx == 1) {
                Alignment::Center
            } else if numeric_like {
                Alignment::Right
            } else {
                Alignment::Left
            };
            let padded = match a {
                Alignment::Right => format!("{}{}", " ".repeat(pad), cell),
                Alignment::Center => {
                    let l = if col_count == 12 && idx == 1 {
                        if first_cell_filled {
                            pad / 2
                        } else {
                            pad.div_ceil(2)
                        }
                    } else {
                        pad / 2
                    };
                    let r = pad - l;
                    format!("{}{}{}", " ".repeat(l), cell, " ".repeat(r))
                }
                _ => format!("{}{}", cell, " ".repeat(pad)),
            };
            out.push(' ');
            out.push_str(&padded);
            out.push_str(" |");
        }
        out.push('\n');
    }

    if let Some(caption) = caption {
        let caption = format_table_caption_with_language(&caption, config, sentence_language);
        out.push('\n');
        out.push_str(&caption);
        out.push('\n');
    }
    indent_table_block(&out)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum GridRowSection {
    Header,
    Body,
    Footer,
}

struct GridTableData {
    rows: Vec<Vec<String>>,
    row_sections: Vec<GridRowSection>,
    row_groups: Vec<usize>,
    alignments: Vec<Alignment>,
    caption: Option<String>,
    caption_after: bool,
}

/// Extract structured data from grid table AST node
fn extract_grid_table_data(node: &SyntaxNode, config: &Config) -> GridTableData {
    let mut rows = Vec::new();
    let mut row_sections = Vec::new();
    let mut row_groups = Vec::new();
    let mut alignments = Vec::new();
    let mut caption = None;
    let mut caption_after = false;
    let mut seen_header = false;
    let mut row_group_index = 0usize;

    for child in node.children() {
        match child.kind() {
            SyntaxKind::TABLE_CAPTION => {
                let mut caption_body = String::new();

                for caption_child in child.children_with_tokens() {
                    match caption_child {
                        rowan::NodeOrToken::Token(token)
                            if token.kind() == SyntaxKind::TABLE_CAPTION_PREFIX =>
                        {
                            // Skip the original prefix
                        }
                        rowan::NodeOrToken::Token(token) => caption_body.push_str(token.text()),
                        rowan::NodeOrToken::Node(node) => {
                            caption_body.push_str(&node.text().to_string())
                        }
                    }
                }

                caption = Some(normalize_table_caption(&caption_body));
                caption_after = seen_header; // After if we've seen table content
            }
            SyntaxKind::TABLE_SEPARATOR => {
                let separator_text = child.text().to_string();

                // Extract alignments from separators that have them
                // Grid tables have alignments in the first separator (headerless)
                // or header separator (tables with headers)
                // Priority: extract from any separator with colons, otherwise keep Default
                let extracted = extract_grid_alignments(&separator_text);
                if !extracted.is_empty() && extracted.iter().any(|a| *a != Alignment::Default) {
                    // Found a separator with alignment info, use it
                    alignments = extracted;
                } else if alignments.is_empty() && !extracted.is_empty() {
                    // No alignments yet, save these (even if all Default)
                    alignments = extracted;
                }

                // Check if this is a header separator (contains =)
                if separator_text.contains('=') {
                    seen_header = true;
                }
            }
            SyntaxKind::TABLE_HEADER | SyntaxKind::TABLE_ROW | SyntaxKind::TABLE_FOOTER => {
                let section = match child.kind() {
                    SyntaxKind::TABLE_HEADER => GridRowSection::Header,
                    SyntaxKind::TABLE_FOOTER => GridRowSection::Footer,
                    _ => GridRowSection::Body,
                };

                let cells = extract_row_cells(&child, config);
                let has_parsed_cells = !cells.is_empty();
                let mut seeded_from_plain_line = false;
                if !has_parsed_cells {
                    let row_text = child.text().to_string();
                    for line in row_text.lines() {
                        let trimmed_start = line.trim_start();
                        let trimmed_end = line.trim_end();
                        if !(trimmed_start.starts_with('|')
                            && trimmed_end.ends_with('|')
                            && !trimmed_start.contains('+'))
                        {
                            continue;
                        }
                        let parsed = split_grid_row(line);
                        if !parsed.is_empty() {
                            rows.push(parsed);
                            row_sections.push(section);
                            row_groups.push(row_group_index);
                            seeded_from_plain_line = true;
                        }
                        break;
                    }
                } else {
                    rows.push(cells);
                    row_sections.push(section);
                    row_groups.push(row_group_index);
                }

                // Continuation lines are emitted as raw text in CST rows; include
                // them for width calculation and output structure.
                let mut seen_first_content_line = false;
                let row_text = child.text().to_string();
                for line in row_text.lines() {
                    let trimmed_start = line.trim_start();
                    let trimmed_end = line.trim_end();
                    if !(trimmed_start.starts_with('|') && trimmed_end.ends_with('|')) {
                        continue;
                    }
                    // Spanning-style boundary lines contain embedded '+' separators.
                    // Keep them attached to the row text via parser losslessness, but
                    // don't treat them as independent logical rows for column sizing/output.
                    if trimmed_start.contains('+') {
                        continue;
                    }
                    if !seen_first_content_line {
                        seen_first_content_line = true;
                        if has_parsed_cells || seeded_from_plain_line {
                            continue;
                        }
                    }
                    let parsed = split_grid_row(line);
                    if !parsed.is_empty() {
                        rows.push(parsed);
                        row_sections.push(section);
                        row_groups.push(row_group_index);
                    }
                }
                row_group_index += 1;
            }
            _ => {}
        }
    }

    let target_cols = if !alignments.is_empty() {
        alignments.len()
    } else {
        rows.iter().map(|r| r.len()).max().unwrap_or(0)
    };

    if target_cols > 0 {
        for row in &mut rows {
            if row.len() > target_cols {
                row.truncate(target_cols);
            } else if row.len() < target_cols {
                row.resize(target_cols, String::new());
            }
        }
    }

    GridTableData {
        rows,
        row_sections,
        row_groups,
        alignments,
        caption,
        caption_after,
    }
}

/// Format a grid table with consistent alignment and padding
pub fn format_grid_table(node: &SyntaxNode, config: &Config) -> String {
    let raw_table = node.text().to_string();
    let sentence_language = resolve_sentence_language(node);
    if raw_table
        .lines()
        .any(|line| line.trim_start().starts_with('|') && line.contains('+'))
    {
        return format_spanning_grid_table_raw(&raw_table, config, sentence_language);
    }

    let table_data = extract_grid_table_data(node, config);
    let mut output = String::new();

    // Early return if no rows
    if table_data.rows.is_empty() {
        return node.text().to_string();
    }

    let widths = calculate_grid_column_widths(&table_data.rows);

    // Emit caption before if present
    if let Some(ref caption_text) = table_data.caption
        && !table_data.caption_after
    {
        let formatted_caption = format_table_caption(caption_text, config, node);
        output.push_str(&formatted_caption);
        output.push_str("\n\n");
    }

    // Helper to create separator line
    let make_separator = |fill_char: char, with_alignment_markers: bool| -> String {
        let mut line = String::from("+");

        for (col_idx, width) in widths.iter().enumerate() {
            let alignment = table_data
                .alignments
                .get(col_idx)
                .copied()
                .unwrap_or(Alignment::Default);

            // Create separator with optional alignment markers
            // Per Pandoc spec: alignment colons go in header separator ONLY, not row separators
            let segment = if with_alignment_markers {
                // Header separator: include alignment colons if specified
                match alignment {
                    Alignment::Left => {
                        let mut s = String::from(":");
                        s.push_str(&fill_char.to_string().repeat(width + 1));
                        s
                    }
                    Alignment::Right => {
                        let mut s = String::new();
                        s.push_str(&fill_char.to_string().repeat(width + 1));
                        s.push(':');
                        s
                    }
                    Alignment::Center => {
                        let mut s = String::from(":");
                        s.push_str(&fill_char.to_string().repeat(*width));
                        s.push(':');
                        s
                    }
                    Alignment::Default => fill_char.to_string().repeat(width + 2),
                }
            } else {
                // Row separator: no alignment colons
                fill_char.to_string().repeat(width + 2)
            };

            line.push_str(&segment);
            line.push('+');
        }

        line.push('\n');
        line
    };

    // Top border
    // Headerless grid tables encode alignment markers in the first separator,
    // so preserve markers there when no explicit header rows are present.
    let has_header_rows = table_data.row_sections.contains(&GridRowSection::Header);
    output.push_str(&make_separator('-', !has_header_rows));

    // Format rows
    for (row_idx, row) in table_data.rows.iter().enumerate() {
        let current_section = table_data
            .row_sections
            .get(row_idx)
            .copied()
            .unwrap_or(GridRowSection::Body);
        output.push('|');

        for (col_idx, _) in widths.iter().enumerate() {
            let cell = row.get(col_idx).map_or("", String::as_str);
            let width = widths.get(col_idx).copied().unwrap_or(3);
            let alignment = table_data
                .alignments
                .get(col_idx)
                .copied()
                .unwrap_or(Alignment::Default);

            output.push(' ');

            // Apply alignment using unicode display width
            let cell_width = cell.width();
            let total_padding = width.saturating_sub(cell_width);
            let effective_alignment = if current_section == GridRowSection::Header {
                match alignment {
                    Alignment::Center => Alignment::Center,
                    _ => Alignment::Left,
                }
            } else {
                alignment
            };

            let padded_cell = match effective_alignment {
                Alignment::Left | Alignment::Default => {
                    format!("{}{}", cell, " ".repeat(total_padding))
                }
                Alignment::Right => {
                    format!("{}{}", " ".repeat(total_padding), cell)
                }
                Alignment::Center => {
                    let left_padding = total_padding / 2;
                    let right_padding = total_padding - left_padding;
                    format!(
                        "{}{}{}",
                        " ".repeat(left_padding),
                        cell,
                        " ".repeat(right_padding)
                    )
                }
            };

            output.push_str(&padded_cell);
            output.push_str(" |");
        }

        output.push('\n');

        // Insert section-aware separator.
        let next_section = table_data.row_sections.get(row_idx + 1).copied();
        let current_group = table_data.row_groups.get(row_idx).copied();
        let next_group = table_data.row_groups.get(row_idx + 1).copied();

        if current_group.is_some() && current_group == next_group {
            continue;
        }

        let separator = match (current_section, next_section) {
            (GridRowSection::Header, Some(GridRowSection::Header)) => make_separator('-', false),
            (GridRowSection::Header, _) => make_separator('=', true),
            (GridRowSection::Body, Some(GridRowSection::Footer)) => make_separator('=', false),
            (GridRowSection::Footer, _) => make_separator('=', false),
            (_, _) => make_separator('-', false),
        };
        output.push_str(&separator);
    }

    // Emit caption after if present
    if let Some(ref caption_text) = table_data.caption
        && table_data.caption_after
    {
        output.push('\n');
        let formatted_caption = format_table_caption(caption_text, config, node);
        output.push_str(&formatted_caption);
        output.push('\n');
    }

    indent_table_block(&output)
}

// Simple Table Formatting
// ============================================================================

/// Column information for simple tables (extracted from separator line)
#[derive(Debug, Clone)]
struct SimpleColumn {
    /// Start position (byte index) in the line
    start: usize,
    /// End position (byte index) in the line
    end: usize,
    /// Column alignment
    alignment: Alignment,
}

/// Extract column positions from a simple table separator line.
/// Returns column boundaries and default alignments.
fn extract_simple_table_columns(separator_text: &str) -> Vec<SimpleColumn> {
    let trimmed = separator_text.trim_start();
    // Strip trailing newline if present
    let trimmed = if let Some(stripped) = trimmed.strip_suffix("\r\n") {
        stripped
    } else if let Some(stripped) = trimmed.strip_suffix('\n') {
        stripped
    } else {
        trimmed
    };

    let leading_spaces = separator_text.len()
        - trimmed.len()
        - if separator_text.ends_with("\r\n") {
            2
        } else if separator_text.ends_with('\n') {
            1
        } else {
            0
        };

    let mut columns = Vec::new();
    let mut in_dashes = false;
    let mut col_start = 0;

    for (i, ch) in trimmed.char_indices() {
        match ch {
            '-' => {
                if !in_dashes {
                    col_start = i + leading_spaces;
                    in_dashes = true;
                }
            }
            ' ' => {
                if in_dashes {
                    columns.push(SimpleColumn {
                        start: col_start,
                        end: i + leading_spaces,
                        alignment: Alignment::Default,
                    });
                    in_dashes = false;
                }
            }
            _ => {}
        }
    }

    // Handle last column if line ends with dashes
    if in_dashes {
        columns.push(SimpleColumn {
            start: col_start,
            end: trimmed.len() + leading_spaces,
            alignment: Alignment::Default,
        });
    }

    columns
}

/// Determine column alignments based on header text position relative to separator
fn determine_simple_alignments(
    columns: &mut [SimpleColumn],
    _separator_line: &str,
    header_line: Option<&str>,
) {
    if let Some(header) = header_line {
        for col in columns.iter_mut() {
            if col.end > header.len() {
                col.alignment = Alignment::Default;
                continue;
            }

            // Extract header text for this column
            let header_text = if col.end <= header.len() {
                header[col.start..col.end].trim()
            } else if col.start < header.len() {
                header[col.start..].trim()
            } else {
                ""
            };

            if header_text.is_empty() {
                col.alignment = Alignment::Default;
                continue;
            }

            // Find where the header text starts and ends within the column
            let header_in_col = &header[col.start..col.end.min(header.len())];
            let text_start = header_in_col.len() - header_in_col.trim_start().len();
            // text_end is the position AFTER the last non-whitespace character
            let trimmed_text = header_in_col.trim();
            let text_end = text_start + trimmed_text.len();

            // Column width is separator length
            let col_width = col.end - col.start;

            let flush_left = text_start == 0;
            let flush_right = text_end == col_width;

            col.alignment = match (flush_left, flush_right) {
                (true, true) => Alignment::Default,
                (true, false) => Alignment::Left,
                (false, true) => Alignment::Right,
                (false, false) => Alignment::Center,
            };
        }
    }
}

/// Split a simple table row into cells using column boundaries
fn split_simple_table_row(row_text: &str, columns: &[SimpleColumn]) -> Vec<String> {
    let mut cells = Vec::new();

    // Strip newline from row
    let row = if let Some(stripped) = row_text.strip_suffix("\r\n") {
        stripped
    } else if let Some(stripped) = row_text.strip_suffix('\n') {
        stripped
    } else {
        row_text
    };

    for col in columns {
        let cell_text = if col.end <= row.len() {
            row[col.start..col.end].trim()
        } else if col.start < row.len() {
            row[col.start..].trim()
        } else {
            ""
        };
        cells.push(cell_text.to_string());
    }

    cells
}

/// Extract structured data from simple table AST node
fn extract_simple_table_data(node: &SyntaxNode, config: &Config) -> TableData {
    let mut rows = Vec::new();
    let mut columns: Vec<SimpleColumn> = Vec::new();
    let mut caption = None;
    let mut caption_after = false;
    let mut separator_line = String::new();
    let mut header_line: Option<String> = None;
    let mut header_cells: Option<Vec<String>> = None;
    let mut seen_separator = false;

    for child in node.children() {
        match child.kind() {
            SyntaxKind::TABLE_CAPTION => {
                let mut caption_body = String::new();

                for caption_child in child.children_with_tokens() {
                    match caption_child {
                        rowan::NodeOrToken::Token(token)
                            if token.kind() == SyntaxKind::TABLE_CAPTION_PREFIX =>
                        {
                            // Skip the original prefix
                        }
                        rowan::NodeOrToken::Token(token) => {
                            caption_body.push_str(token.text());
                        }
                        rowan::NodeOrToken::Node(node) => {
                            caption_body.push_str(&node.text().to_string());
                        }
                    }
                }

                caption = Some(normalize_table_caption(&caption_body));
                caption_after = seen_separator;
            }
            SyntaxKind::TABLE_SEPARATOR => {
                separator_line = child.text().to_string();
                seen_separator = true;

                // Extract column positions
                columns = extract_simple_table_columns(&separator_line);
            }
            SyntaxKind::TABLE_HEADER => {
                // Always preserve RAW text for alignment detection
                let raw_text = child.text().to_string();
                header_line = Some(raw_text);

                // Try to extract from TABLE_CELL nodes for content
                let cells = extract_row_cells(&child, config);
                if !cells.is_empty() {
                    header_cells = Some(cells);
                } else {
                    header_cells = None;
                }
            }
            SyntaxKind::TABLE_ROW => {
                // Data rows come after separator
                if !columns.is_empty() {
                    // Try to extract from TABLE_CELL nodes first
                    let cells = extract_row_cells(&child, config);

                    if !cells.is_empty() {
                        // Check if this is actually a separator line (all cells are dashes/whitespace)
                        let is_separator = cells
                            .iter()
                            .all(|cell| cell.trim().chars().all(|c| c == '-'));

                        if !is_separator {
                            // Successfully extracted from TABLE_CELL nodes
                            rows.push(cells);
                        }
                    } else {
                        // Fall back to old approach (for backwards compatibility)
                        let row_content = format_cell_content(&child, config);

                        // Skip rows that are actually separator lines (for headerless tables)
                        let is_separator = row_content
                            .trim()
                            .chars()
                            .all(|c| c == '-' || c.is_whitespace());

                        if !is_separator {
                            let cells = split_simple_table_row(&row_content, &columns);
                            rows.push(cells);
                        }
                    }
                }
            }
            _ => {}
        }
    }

    // Determine alignments based on header
    if !columns.is_empty() {
        determine_simple_alignments(&mut columns, &separator_line, header_line.as_deref());
    }

    // Track if we have a header before potentially consuming header_line
    let has_header = header_line.is_some() || header_cells.is_some();

    // Add header row to rows if present
    if let Some(cells) = header_cells {
        // Already extracted from TABLE_CELL nodes
        rows.insert(0, cells);
    } else if let Some(header) = header_line {
        // Fall back to old text splitting approach
        let header_cells = split_simple_table_row(&header, &columns);
        rows.insert(0, header_cells);
    }

    let alignments = columns.iter().map(|c| c.alignment).collect();

    // For simple tables, preserve both separator dash lengths AND column positions
    let column_widths: Vec<usize> = columns.iter().map(|c| c.end - c.start).collect();
    let base_offset = columns.first().map(|c| c.start).unwrap_or(0);
    let column_positions: Vec<(usize, usize)> = columns
        .iter()
        .map(|c| (c.start - base_offset, c.end - base_offset))
        .collect();

    TableData {
        rows,
        alignments,
        caption,
        caption_after,
        column_widths: Some(column_widths),
        column_positions: Some(column_positions),
        has_header, // Simple tables may or may not have headers
    }
}

/// Format a simple table with consistent alignment and padding
pub fn format_simple_table(node: &SyntaxNode, config: &Config) -> String {
    if !node.text().to_string().is_ascii() {
        return node.text().to_string();
    }

    let table_data = extract_simple_table_data(node, config);
    let mut output = String::new();

    // Early return if no rows
    if table_data.rows.is_empty() {
        return node.text().to_string();
    }

    let content_widths = calculate_column_widths(&table_data.rows);
    let has_header = table_data.has_header;

    // For simple tables, preserve separator-derived geometry unless it's clearly oversized
    // compared to content; then shrink width while preserving column starts.
    let widths = if let Some(ref widths) = table_data.column_widths {
        widths.clone()
    } else {
        content_widths.clone()
    };

    let normalized_positions = if let Some(ref positions) = table_data.column_positions {
        let mut out = Vec::with_capacity(positions.len());
        for (col_idx, &(start, end)) in positions.iter().enumerate() {
            let original_width = end.saturating_sub(start);
            if has_header {
                let content_width = content_widths.get(col_idx).copied().unwrap_or(3);
                let alignment = table_data
                    .alignments
                    .get(col_idx)
                    .copied()
                    .unwrap_or(Alignment::Default);
                let preferred_width = content_width
                    + match alignment {
                        Alignment::Center => 4,
                        Alignment::Left | Alignment::Right => 2,
                        Alignment::Default => 0,
                    };
                let clamped_width = original_width.min(preferred_width).max(content_width);
                out.push((start, start + clamped_width));
            } else {
                out.push((start, end));
            }
        }
        Some(out)
    } else {
        None
    };

    // Emit caption before if present
    if let Some(ref caption_text) = table_data.caption
        && !table_data.caption_after
    {
        let formatted_caption = format_table_caption(caption_text, config, node);
        output.push_str(&formatted_caption);
        output.push_str("\n\n");
    }

    // For headerless simple tables, emit opening separator first
    if !has_header
        && normalized_positions.is_some()
        && let Some(ref positions) = normalized_positions
    {
        let last_col_end = positions.last().map(|(_, end)| *end).unwrap_or(0);
        let mut sep_chars: Vec<char> = vec![' '; last_col_end];
        for &(col_start, col_end) in positions.iter() {
            for i in col_start..col_end {
                if i < sep_chars.len() {
                    sep_chars[i] = '-';
                }
            }
        }
        output.push_str(&sep_chars.iter().collect::<String>());
        output.push('\n');
    }

    // Format header row if present
    if has_header {
        // For simple tables with column positions, use absolute positioning
        if let Some(ref positions) = normalized_positions {
            // Build header line using character buffer
            let last_col_end = positions.last().map(|(_, end)| *end).unwrap_or(0);
            let mut line_chars: Vec<char> = vec![' '; last_col_end];

            for (col_idx, cell) in table_data.rows[0].iter().enumerate() {
                if let Some(&(col_start, col_end)) = positions.get(col_idx) {
                    let alignment = table_data
                        .alignments
                        .get(col_idx)
                        .copied()
                        .unwrap_or(Alignment::Default);

                    let col_width = col_end - col_start;
                    let cell_chars: Vec<char> = cell.chars().collect();
                    let cell_width = cell.width();
                    let total_padding = col_width.saturating_sub(cell_width);

                    // Calculate where to place text within column based on alignment
                    let text_start_in_col = match alignment {
                        Alignment::Left | Alignment::Default => 0,
                        Alignment::Right => total_padding,
                        Alignment::Center => total_padding / 2,
                    };

                    // Place cell characters at the correct position
                    let mut char_pos = 0;
                    for &ch in &cell_chars {
                        let target_pos = col_start + text_start_in_col + char_pos;
                        if target_pos < line_chars.len() {
                            line_chars[target_pos] = ch;
                            char_pos += 1;
                        }
                    }
                }
            }

            output.push_str(line_chars.iter().collect::<String>().trim_end());
            output.push('\n');

            // Emit separator line at the same positions
            let mut sep_chars: Vec<char> = vec![' '; last_col_end];
            for &(col_start, col_end) in positions {
                for i in col_start..col_end {
                    if i < sep_chars.len() {
                        sep_chars[i] = '-';
                    }
                }
            }
            output.push_str(&sep_chars.iter().collect::<String>());
            output.push('\n');
        } else {
            // Fallback: use widths with single-space separation
            for (col_idx, cell) in table_data.rows[0].iter().enumerate() {
                let width = widths.get(col_idx).copied().unwrap_or(3);
                let alignment = table_data
                    .alignments
                    .get(col_idx)
                    .copied()
                    .unwrap_or(Alignment::Default);

                let cell_width = cell.width();
                let total_padding = width.saturating_sub(cell_width);

                let padded_cell = match alignment {
                    Alignment::Left | Alignment::Default => {
                        format!("{}{}", cell, " ".repeat(total_padding))
                    }
                    Alignment::Right => {
                        format!("{}{}", " ".repeat(total_padding), cell)
                    }
                    Alignment::Center => {
                        let left_padding = total_padding / 2;
                        let right_padding = total_padding - left_padding;
                        format!(
                            "{}{}{}",
                            " ".repeat(left_padding),
                            cell,
                            " ".repeat(right_padding)
                        )
                    }
                };

                output.push_str(&padded_cell);
                if col_idx < table_data.rows[0].len() - 1 {
                    output.push(' ');
                }
            }
            output.push('\n');

            // Emit separator line
            for (col_idx, width) in widths.iter().enumerate() {
                output.push_str(&"-".repeat(*width));
                if col_idx < widths.len() - 1 {
                    output.push(' ');
                }
            }
            output.push('\n');
        }
    }

    // Format data rows
    for row in table_data.rows.iter().skip(if has_header { 1 } else { 0 }) {
        if let Some(ref positions) = normalized_positions {
            // Build row using character buffer
            let last_col_end = positions.last().map(|(_, end)| *end).unwrap_or(0);
            let mut line_chars: Vec<char> = vec![' '; last_col_end];

            for (col_idx, cell) in row.iter().enumerate() {
                if let Some(&(col_start, col_end)) = positions.get(col_idx) {
                    let alignment = table_data
                        .alignments
                        .get(col_idx)
                        .copied()
                        .unwrap_or(Alignment::Default);

                    let col_width = col_end - col_start;
                    let cell_chars: Vec<char> = cell.chars().collect();
                    let cell_width = cell.width();
                    let total_padding = col_width.saturating_sub(cell_width);

                    // Calculate where to place text within column based on alignment
                    let text_start_in_col = match alignment {
                        Alignment::Left | Alignment::Default => 0,
                        Alignment::Right => total_padding,
                        Alignment::Center => total_padding / 2,
                    };

                    // Place cell characters at the correct position
                    let mut char_pos = 0;
                    for &ch in &cell_chars {
                        let target_pos = col_start + text_start_in_col + char_pos;
                        if target_pos < line_chars.len() {
                            line_chars[target_pos] = ch;
                            char_pos += 1;
                        }
                    }
                }
            }

            output.push_str(line_chars.iter().collect::<String>().trim_end());
            output.push('\n');
        } else {
            // Fallback: use widths with single-space separation
            for (col_idx, cell) in row.iter().enumerate() {
                let width = widths.get(col_idx).copied().unwrap_or(3);
                let alignment = table_data
                    .alignments
                    .get(col_idx)
                    .copied()
                    .unwrap_or(Alignment::Default);

                let cell_width = cell.width();
                let total_padding = width.saturating_sub(cell_width);

                let padded_cell = match alignment {
                    Alignment::Left | Alignment::Default => {
                        format!("{}{}", cell, " ".repeat(total_padding))
                    }
                    Alignment::Right => {
                        format!("{}{}", " ".repeat(total_padding), cell)
                    }
                    Alignment::Center => {
                        let left_padding = total_padding / 2;
                        let right_padding = total_padding - left_padding;
                        format!(
                            "{}{}{}",
                            " ".repeat(left_padding),
                            cell,
                            " ".repeat(right_padding)
                        )
                    }
                };

                output.push_str(&padded_cell);
                if col_idx < row.len() - 1 {
                    output.push(' ');
                }
            }
            output.push('\n');
        }
    }

    // For headerless simple tables, emit closing separator
    if !has_header
        && normalized_positions.is_some()
        && let Some(ref positions) = normalized_positions
    {
        let last_col_end = positions.last().map(|(_, end)| *end).unwrap_or(0);
        let mut sep_chars: Vec<char> = vec![' '; last_col_end];
        for &(col_start, col_end) in positions.iter() {
            for i in col_start..col_end {
                if i < sep_chars.len() {
                    sep_chars[i] = '-';
                }
            }
        }
        output.push_str(&sep_chars.iter().collect::<String>());
        output.push('\n');
    }

    // Emit caption after if present
    if let Some(ref caption_text) = table_data.caption
        && table_data.caption_after
    {
        output.push('\n');
        let formatted_caption = format_table_caption(caption_text, config, node);
        output.push_str(&formatted_caption);
        output.push('\n');
    }

    indent_table_block(&output)
}

/// Extract column information from multiline table separator line
fn extract_multiline_columns(separator_line: &str) -> Vec<(usize, usize)> {
    // DO NOT trim - we need to preserve leading spaces for column alignment
    // Column positions must be relative to the original line positions
    let line = separator_line.trim_end(); // Only remove trailing whitespace/newline

    let mut columns = Vec::new();
    let mut in_dashes = false;
    let mut col_start = 0;

    for (i, ch) in line.char_indices() {
        match ch {
            '-' => {
                if !in_dashes {
                    col_start = i;
                    in_dashes = true;
                }
            }
            ' ' => {
                if in_dashes {
                    columns.push((col_start, i));
                    in_dashes = false;
                }
            }
            _ => {}
        }
    }

    // Handle last column
    if in_dashes {
        columns.push((col_start, line.len()));
    }

    columns
}

/// Determine alignment for a column based on header text position
fn determine_multiline_alignment(header_text: &str, col_start: usize, col_end: usize) -> Alignment {
    if header_text.is_empty() {
        return Alignment::Default;
    }

    // Use first non-empty line of header to determine alignment
    let first_line = header_text
        .lines()
        .find(|line| !line.trim().is_empty())
        .unwrap_or("");

    // Extract text within this column using original line (not normalized)
    let header_in_col = if col_end <= first_line.len() {
        &first_line[col_start..col_end]
    } else if col_start < first_line.len() {
        &first_line[col_start..]
    } else {
        return Alignment::Default;
    };

    let text_start = header_in_col.len() - header_in_col.trim_start().len();
    let trimmed_text = header_in_col.trim();
    let text_end = text_start + trimmed_text.len();

    let col_width = col_end - col_start;
    let flush_left = text_start == 0;
    let flush_right = text_end == col_width;

    match (flush_left, flush_right) {
        (true, true) => Alignment::Default,
        (true, false) => Alignment::Left,
        (false, true) => Alignment::Right,
        (false, false) => Alignment::Center,
    }
}

/// Represents a multiline table with cells that can span multiple lines
struct MultilineTableData {
    /// Rows of cells, where each cell is a vector of lines
    rows: Vec<Vec<Vec<String>>>,
    alignments: Vec<Alignment>,
    caption: Option<String>,
    column_positions: Vec<(usize, usize)>,
    has_header: bool,
}

/// Extract multiline cell content from a text block  
fn extract_multiline_cells(text: &str, column_positions: &[(usize, usize)]) -> Vec<Vec<String>> {
    let lines: Vec<&str> = text.lines().collect();
    let num_cols = column_positions.len();

    // Initialize cells - each cell is a vec of lines
    let mut cells: Vec<Vec<String>> = vec![Vec::new(); num_cols];

    for line in lines {
        // Keep line as-is without normalization - column positions should work on original text
        for (col_idx, &(col_start, col_end)) in column_positions.iter().enumerate() {
            let cell_line = if col_end <= line.len() {
                &line[col_start..col_end]
            } else if col_start < line.len() {
                &line[col_start..]
            } else {
                ""
            };
            // Trim the cell line to normalize spacing - this ensures idempotency
            // We trim both leading and trailing whitespace because alignment will be
            // recalculated based on column positions
            cells[col_idx].push(cell_line.trim().to_string());
        }
    }

    cells
}

/// Extract cells from TABLE_CELL nodes and continuation TEXT (Phase 7.1)
fn extract_cells_from_table_cell_nodes(
    row: &SyntaxNode,
    config: &Config,
    column_positions: &[(usize, usize)],
) -> Vec<Vec<String>> {
    // Format TABLE_CELL inline content, then extract multi-line text
    let mut formatted_text = String::new();

    for child in row.children_with_tokens() {
        match child {
            rowan::NodeOrToken::Token(token) => {
                formatted_text.push_str(token.text());
            }
            rowan::NodeOrToken::Node(node) => {
                if node.kind() == SyntaxKind::TABLE_CELL {
                    // Format the inline content within the cell
                    formatted_text.push_str(&format_cell_content(&node, config));
                } else {
                    // Other nodes (shouldn't happen in well-formed CST)
                    formatted_text.push_str(&node.text().to_string());
                }
            }
        }
    }

    extract_multiline_cells(&formatted_text, column_positions)
}

/// Extract structured data from multiline table AST node
fn extract_multiline_table_data(node: &SyntaxNode, config: &Config) -> MultilineTableData {
    let mut rows: Vec<Vec<Vec<String>>> = Vec::new();
    let mut column_positions: Vec<(usize, usize)> = Vec::new();
    let mut alignments = Vec::new();
    let mut caption = None;
    let mut has_header = false;
    let mut header_text = String::new();
    let mut separator_count = 0;

    for child in node.children() {
        match child.kind() {
            SyntaxKind::TABLE_CAPTION => {
                let mut caption_body = String::new();

                for caption_child in child.children_with_tokens() {
                    match caption_child {
                        rowan::NodeOrToken::Token(token)
                            if token.kind() == SyntaxKind::TABLE_CAPTION_PREFIX =>
                        {
                            // Skip the original prefix
                        }
                        rowan::NodeOrToken::Token(token) => {
                            caption_body.push_str(token.text());
                        }
                        rowan::NodeOrToken::Node(node) => {
                            caption_body.push_str(&node.text().to_string());
                        }
                    }
                }

                caption = Some(normalize_table_caption(&caption_body));
            }
            SyntaxKind::TABLE_SEPARATOR => {
                separator_count += 1;
                let sep_text = child.text().to_string();

                // For headerless tables: first separator defines columns
                // For tables with headers: second separator (after header) defines columns
                // We extract from first separator and will overwrite if we see a second one
                if separator_count == 1 || (separator_count == 2 && has_header) {
                    column_positions = extract_multiline_columns(&sep_text);
                }
            }
            SyntaxKind::TABLE_HEADER => {
                has_header = true;
                // Always use raw text for alignment detection - it preserves original spacing
                header_text = child.text().to_string();
            }
            SyntaxKind::TABLE_ROW => {
                // Check if row has TABLE_CELL nodes (Phase 7.1)
                if child.children().any(|c| c.kind() == SyntaxKind::TABLE_CELL) {
                    let cells =
                        extract_cells_from_table_cell_nodes(&child, config, &column_positions);
                    rows.push(cells);
                } else {
                    // Old style: format cell content and split into cells
                    let row_content = format_cell_content(&child, config);
                    let cells = extract_multiline_cells(&row_content, &column_positions);
                    rows.push(cells);
                }
            }
            _ => {}
        }
    }

    // Add header as first row if present
    if has_header && !column_positions.is_empty() {
        let header_node = node
            .children()
            .find(|c| c.kind() == SyntaxKind::TABLE_HEADER);

        let header_cells = if let Some(hdr) = header_node {
            if hdr.children().any(|c| c.kind() == SyntaxKind::TABLE_CELL) {
                // New style: extract from TABLE_CELL nodes + continuation text
                extract_cells_from_table_cell_nodes(&hdr, config, &column_positions)
            } else {
                // Old style: extract from text
                extract_multiline_cells(&header_text, &column_positions)
            }
        } else {
            extract_multiline_cells(&header_text, &column_positions)
        };

        rows.insert(0, header_cells);

        // Determine alignments from header
        for &(col_start, col_end) in &column_positions {
            let alignment = determine_multiline_alignment(&header_text, col_start, col_end);
            alignments.push(alignment);
        }
    } else if !rows.is_empty() && !column_positions.is_empty() {
        // No header - determine alignment from first body row (per Pandoc spec)
        let first_row_node = node
            .children()
            .find(|c| c.kind() == SyntaxKind::TABLE_ROW)
            .unwrap();
        // Use raw text to preserve original spacing for alignment detection
        let first_row_text = first_row_node.text().to_string();
        for &(col_start, col_end) in &column_positions {
            let alignment = determine_multiline_alignment(&first_row_text, col_start, col_end);
            alignments.push(alignment);
        }
    } else {
        // Fallback - use default alignment
        alignments = vec![Alignment::Default; column_positions.len()];
    }

    MultilineTableData {
        rows,
        alignments,
        caption,
        column_positions,
        has_header,
    }
}

/// Format a multiline table preserving column widths and structure
pub fn format_multiline_table(node: &SyntaxNode, config: &Config) -> String {
    if !node.text().to_string().is_ascii() {
        return node.text().to_string();
    }

    let table_data = extract_multiline_table_data(node, config);
    let mut output = String::new();

    // Early return if no rows or no column info
    if table_data.rows.is_empty() || table_data.column_positions.is_empty() {
        return node.text().to_string();
    }

    let base_offset = table_data
        .column_positions
        .first()
        .map(|(start, _)| *start)
        .unwrap_or(0);
    let positions: Vec<(usize, usize)> = table_data
        .column_positions
        .iter()
        .map(|(start, end)| {
            (
                start.saturating_sub(base_offset),
                end.saturating_sub(base_offset),
            )
        })
        .collect();

    // Calculate total table width
    let last_col_end = positions.last().map(|(_, end)| *end).unwrap_or(0);

    // Emit caption before if present
    if let Some(ref caption_text) = table_data.caption {
        let formatted_caption = format_table_caption(caption_text, config, node);
        output.push_str(&formatted_caption);
        output.push_str("\n\n"); // Blank line between caption and table
    }

    // Emit opening separator
    if table_data.has_header {
        // With header: opening separator is full-width dashes
        output.push_str(&"-".repeat(last_col_end));
        output.push('\n');
    } else {
        // Headerless: opening separator shows column boundaries
        let mut sep_chars: Vec<char> = vec![' '; last_col_end];
        for &(col_start, col_end) in &positions {
            for item in sep_chars.iter_mut().take(col_end).skip(col_start) {
                *item = '-';
            }
        }
        output.push_str(&sep_chars.iter().collect::<String>());
        output.push('\n');
    }

    // Emit header if present
    if table_data.has_header && !table_data.rows.is_empty() {
        let header_row = &table_data.rows[0];

        // Determine max number of lines across all header cells
        let max_lines = header_row.iter().map(|cell| cell.len()).max().unwrap_or(0);

        // Emit each line of the header
        for line_idx in 0..max_lines {
            let mut line_chars: Vec<char> = vec![' '; last_col_end];

            for (col_idx, cell_lines) in header_row.iter().enumerate() {
                if let Some(&(col_start, col_end)) = positions.get(col_idx) {
                    let cell_text = cell_lines.get(line_idx).map(|s| s.as_str()).unwrap_or("");
                    let alignment = table_data
                        .alignments
                        .get(col_idx)
                        .copied()
                        .unwrap_or(Alignment::Default);

                    let col_width = col_end - col_start;
                    let cell_width = cell_text.trim_end().width();
                    let total_padding = col_width.saturating_sub(cell_width);

                    // Calculate text start position based on alignment
                    let text_start_in_col = match alignment {
                        Alignment::Left | Alignment::Default => 0,
                        Alignment::Right => total_padding,
                        Alignment::Center => total_padding / 2,
                    };

                    // Place characters
                    for (i, ch) in cell_text.trim_end().chars().enumerate() {
                        let target_pos = col_start + text_start_in_col + i;
                        if target_pos < line_chars.len() {
                            line_chars[target_pos] = ch;
                        }
                    }
                }
            }

            output.push_str(line_chars.iter().collect::<String>().trim_end());
            output.push('\n');
        }

        // Emit column separator (no indent)
        let mut sep_chars: Vec<char> = vec![' '; last_col_end];
        for &(col_start, col_end) in &positions {
            for item in sep_chars.iter_mut().take(col_end).skip(col_start) {
                *item = '-';
            }
        }
        output.push_str(&sep_chars.iter().collect::<String>());
        output.push('\n');
    }

    // Emit body rows
    let start_row = if table_data.has_header { 1 } else { 0 };
    for (row_idx, row) in table_data.rows.iter().enumerate().skip(start_row) {
        // Determine max number of lines across all cells in this row
        let max_lines = row.iter().map(|cell| cell.len()).max().unwrap_or(0);

        // Emit each line of the row
        for line_idx in 0..max_lines {
            let mut line_chars: Vec<char> = vec![' '; last_col_end];

            for (col_idx, cell_lines) in row.iter().enumerate() {
                if let Some(&(col_start, col_end)) = positions.get(col_idx) {
                    let cell_text = cell_lines.get(line_idx).map(|s| s.as_str()).unwrap_or("");
                    let alignment = table_data
                        .alignments
                        .get(col_idx)
                        .copied()
                        .unwrap_or(Alignment::Default);

                    let col_width = col_end - col_start;
                    let cell_width = cell_text.trim_end().width();
                    let total_padding = col_width.saturating_sub(cell_width);

                    // Calculate text start position based on alignment
                    let text_start_in_col = match alignment {
                        Alignment::Left | Alignment::Default => 0,
                        Alignment::Right => total_padding,
                        Alignment::Center => total_padding / 2,
                    };

                    // Place characters
                    for (i, ch) in cell_text.trim_end().chars().enumerate() {
                        let target_pos = col_start + text_start_in_col + i;
                        if target_pos < line_chars.len() {
                            line_chars[target_pos] = ch;
                        }
                    }
                }
            }

            output.push_str(line_chars.iter().collect::<String>().trim_end());
            output.push('\n');
        }

        // Emit blank line between rows
        if row_idx < table_data.rows.len() - 1 {
            output.push('\n');
        }
    }

    // For single-row tables, emit blank line before closing separator
    // (required by Pandoc spec to distinguish from simple tables)
    let num_body_rows = table_data.rows.len() - if table_data.has_header { 1 } else { 0 };
    if num_body_rows == 1 && table_data.has_header {
        output.push('\n');
    }

    // Emit closing separator
    if table_data.has_header {
        // With header: closing separator is full-width dashes
        output.push_str(&"-".repeat(last_col_end));
        output.push('\n');
    } else {
        // Headerless: closing separator shows column boundaries
        let mut sep_chars: Vec<char> = vec![' '; last_col_end];
        for &(col_start, col_end) in &positions {
            for item in sep_chars.iter_mut().take(col_end).skip(col_start) {
                *item = '-';
            }
        }
        output.push_str(&sep_chars.iter().collect::<String>());
        output.push('\n');
    }

    indent_table_block(&output)
}