chordsketch-render-text 0.3.0

Plain text renderer for ChordPro 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
//! Plain text renderer for ChordPro documents.
//!
//! This crate converts a parsed ChordPro AST (from `chordsketch-chordpro`) into
//! formatted plain text with chords aligned above their corresponding lyrics.

use chordsketch_chordpro::ast::{CommentStyle, DirectiveKind, Line, LyricsLine, Song};
use chordsketch_chordpro::config::Config;
use chordsketch_chordpro::notation::NotationKind;
use chordsketch_chordpro::render_result::{
    RenderResult, push_warning, validate_capo, validate_strict_key,
};
use chordsketch_chordpro::resolve_diagrams_instrument;
use chordsketch_chordpro::transpose::transpose_chord;
use unicode_width::UnicodeWidthStr;

/// Maximum number of chorus recall directives allowed per song.
/// Prevents output amplification from malicious inputs with many `{chorus}` lines.
const MAX_CHORUS_RECALLS: usize = 1000;

/// Maximum number of warnings the renderer will accumulate for a single
/// render pass. Re-exported from the canonical location in
/// `chordsketch-chordpro::render_result` so existing downstream callers can
/// keep importing `chordsketch_render_text::MAX_WARNINGS` unchanged
/// (issue #1874).
pub use chordsketch_chordpro::render_result::MAX_WARNINGS;

/// Render a [`Song`] AST to plain text.
///
/// The output format:
/// - Title and subtitle are rendered as header lines.
/// - Section markers (chorus, verse, bridge, tab) render as labeled headers.
/// - Lyrics with chords produce two lines: chords above, lyrics below.
/// - Lyrics without chords produce a single lyrics line.
/// - Comments are rendered with style markers.
/// - The `{chorus}` directive recalls (re-renders) the most recently defined
///   chorus section. If no chorus has been defined yet, a `[Chorus]` marker
///   is emitted instead.
/// - Metadata directives (artist, key, capo, etc.) are silently consumed
///   (they populate [`Song::metadata`] but do not appear in the text body).
/// - Empty lines are preserved.
#[must_use]
pub fn render_song(song: &Song) -> String {
    render_song_with_transpose(song, 0, &Config::defaults())
}

/// Render a [`Song`] AST to plain text with an additional CLI transposition offset.
///
/// The `cli_transpose` parameter is added to any in-file `{transpose}` directive
/// values, allowing the CLI `--transpose` flag to combine with in-file directives.
///
/// Warnings are printed to stderr via `eprintln!`. Use
/// [`render_song_with_warnings`] to capture them programmatically.
#[must_use]
pub fn render_song_with_transpose(song: &Song, cli_transpose: i8, config: &Config) -> String {
    let result = render_song_with_warnings(song, cli_transpose, config);
    for w in &result.warnings {
        eprintln!("warning: {w}");
    }
    result.output
}

/// Render a [`Song`] AST to plain text, returning warnings programmatically.
///
/// This is the structured variant of [`render_song_with_transpose`]. Instead
/// of printing warnings to stderr, they are collected into
/// [`RenderResult::warnings`].
#[must_use = "caller must check warnings in the returned RenderResult"]
pub fn render_song_with_warnings(
    song: &Song,
    cli_transpose: i8,
    config: &Config,
) -> RenderResult<String> {
    let mut warnings = Vec::new();
    let output = render_song_impl(song, cli_transpose, config, &mut warnings);
    RenderResult::with_warnings(output, warnings)
}

/// Internal implementation that renders a song and collects warnings.
fn render_song_impl(
    song: &Song,
    cli_transpose: i8,
    config: &Config,
    warnings: &mut Vec<String>,
) -> String {
    // Apply song-level config overrides ({+config.KEY: VALUE} directives).
    // The effective config is used for diagram instrument selection and
    // strict-mode validation (validate_strict_key), consistent with the
    // HTML and PDF renderers.
    let song_overrides = song.config_overrides();
    let song_config;
    let _config = if song_overrides.is_empty() {
        config
    } else {
        song_config = config
            .clone()
            .with_song_overrides(&song_overrides, warnings);
        &song_config
    };
    // Extract song-level transpose delta from {+config.settings.transpose}.
    // The base config transpose is already folded into cli_transpose by the caller.
    let song_transpose_delta = Config::song_transpose_delta(&song_overrides);
    let mut output = Vec::new();
    let (combined_transpose, _) =
        chordsketch_chordpro::transpose::combine_transpose(cli_transpose, song_transpose_delta);
    let mut transpose_offset: i8 = combined_transpose;
    // Stores the AST lines of the most recently defined chorus body.
    // Re-rendered at recall time so the current transpose offset is applied.
    let mut chorus_body: Vec<Line> = Vec::new();
    // Temporary buffer for collecting chorus AST lines.
    let mut chorus_buf: Option<Vec<Line>> = None;
    let mut chorus_recall_count: usize = 0;

    // #1971: parity with the PDF renderer (#1825). When inside a
    // `{start_of_<tag>} … {end_of_<tag>}` pair for a notation block
    // (ABC, Lilypond, MusicXML, SVG), discard every body line and
    // emit a single structured warning at StartOf. Rendering the raw
    // notation source as plain text (as this renderer did before)
    // was just as unhelpful as in the PDF renderer — readers get a
    // wall of `X:1` / `K:C` / `\relative c' {` with no context.
    let mut in_notation_block: Option<NotationKind> = None;

    // Instrument for the auto-inject ASCII diagram block.
    // Set by {diagrams: guitar/ukulele/on}; cleared by {diagrams: off} / {no_diagrams}.
    let default_instrument = _config
        .get_path("diagrams.instrument")
        .as_str()
        .map(str::to_ascii_lowercase)
        .unwrap_or_else(|| "guitar".to_string());
    let mut auto_diagrams_instrument: Option<String> = None;

    validate_capo(&song.metadata, warnings);
    validate_strict_key(&song.metadata, _config, warnings);
    render_metadata(&song.metadata, &mut output);

    for line in &song.lines {
        // #1971: inside a notation block, discard every line until
        // the matching EndOf directive. Mirrors the PDF renderer's
        // skip-until-end window introduced in #1825/#1968.
        if let Some(kind) = in_notation_block {
            if let Line::Directive(d) = line {
                if kind.is_end_directive(&d.kind) {
                    in_notation_block = None;
                }
            }
            continue;
        }
        match line {
            Line::Lyrics(lyrics_line) => {
                if let Some(buf) = chorus_buf.as_mut() {
                    buf.push(line.clone());
                }
                render_lyrics(lyrics_line, transpose_offset, &mut output);
            }
            Line::Directive(directive) => {
                // Metadata directives are already rendered via song.metadata;
                // skip them in the body to avoid duplicate output.
                if directive.kind.is_metadata() {
                    continue;
                }
                // #1971: handle notation block openers. Route the
                // warning through `push_warning` (participates in the
                // MAX_WARNINGS cap), emit an inline placeholder, and
                // flip the skip window on. The section header still
                // renders so readers see where the block was.
                if let Some(kind) = NotationKind::from_start_directive(&directive.kind) {
                    render_section_header(kind.label(), &directive.value, &mut output);
                    let label = kind.label();
                    let tag = kind.tag();
                    push_warning(
                        warnings,
                        format!(
                            "Text renderer does not support {label} blocks; body of the \
                             `{{start_of_{tag}}}{{end_of_{tag}}}` section has been \
                             omitted. Use the HTML renderer for full {label} support.",
                        ),
                    );
                    output.push(format!(
                        "[{label} block omitted — use the HTML renderer to view it]",
                    ));
                    in_notation_block = Some(kind);
                    continue;
                }
                if directive.kind == DirectiveKind::Diagrams {
                    auto_diagrams_instrument = resolve_diagrams_instrument(
                        directive.value.as_deref(),
                        &default_instrument,
                    );
                    continue;
                }
                if directive.kind == DirectiveKind::NoDiagrams {
                    auto_diagrams_instrument = None;
                    continue;
                }
                if directive.kind == DirectiveKind::Transpose {
                    // {transpose: N} sets the in-file transposition amount.
                    // A missing or empty value silently resets to 0; only a
                    // non-empty value that cannot be parsed as i8 emits a warning.
                    let file_offset: i8 = match directive.value.as_deref() {
                        None | Some("") => 0,
                        Some(raw) => match raw.parse() {
                            Ok(v) => v,
                            Err(_) => {
                                push_warning(
                                    warnings,
                                    format!(
                                        "{{transpose}} value {raw:?} cannot be \
                                         parsed as i8, ignored (using 0)"
                                    ),
                                );
                                0
                            }
                        },
                    };
                    let (combined, saturated) = chordsketch_chordpro::transpose::combine_transpose(
                        file_offset,
                        cli_transpose,
                    );
                    if saturated {
                        push_warning(
                            warnings,
                            format!(
                                "transpose offset {file_offset} + {cli_transpose} \
                                 exceeds i8 range, clamped to {combined}"
                            ),
                        );
                    }
                    transpose_offset = combined;
                    continue;
                }
                match &directive.kind {
                    DirectiveKind::StartOfChorus => {
                        render_section_header("Chorus", &directive.value, &mut output);
                        // Begin collecting chorus content lines.
                        chorus_buf = Some(Vec::new());
                    }
                    DirectiveKind::EndOfChorus => {
                        if let Some(buf) = chorus_buf.take() {
                            chorus_body = buf;
                        }
                    }
                    DirectiveKind::Chorus => {
                        if chorus_recall_count < MAX_CHORUS_RECALLS {
                            render_chorus_recall(
                                &directive.value,
                                &chorus_body,
                                transpose_offset,
                                &mut output,
                                warnings,
                            );
                            chorus_recall_count += 1;
                        } else if chorus_recall_count == MAX_CHORUS_RECALLS {
                            push_warning(
                                warnings,
                                format!(
                                    "chorus recall limit ({MAX_CHORUS_RECALLS}) reached, \
                                     further recalls suppressed"
                                ),
                            );
                            chorus_recall_count += 1;
                        }
                    }
                    // All page-layout directives are intentionally excluded from the
                    // chorus buffer — they must not be replayed on chorus recall.
                    // Plain-text rendering produces no output for these directives
                    // (parity with HTML and PDF renderers which do the same exclusion).
                    DirectiveKind::NewPage
                    | DirectiveKind::NewPhysicalPage
                    | DirectiveKind::ColumnBreak
                    | DirectiveKind::Columns => {}
                    _ => {
                        if let Some(buf) = chorus_buf.as_mut() {
                            buf.push(line.clone());
                        }
                        let mut target = Vec::new();
                        render_directive(directive, &mut target, warnings);
                        output.extend(target);
                    }
                }
            }
            Line::Comment(style, text) => {
                if let Some(buf) = chorus_buf.as_mut() {
                    buf.push(line.clone());
                }
                render_comment(*style, text, &mut output);
            }
            Line::Empty => {
                if let Some(buf) = chorus_buf.as_mut() {
                    buf.push(line.clone());
                }
                output.push(String::new());
            }
        }
    }

    // Auto-inject ASCII diagram block when {diagrams} (or {diagrams: guitar/ukulele/piano}) was seen.
    if let Some(ref instrument) = auto_diagrams_instrument {
        if instrument == "piano" {
            // Plain-text rendering of keyboard diagrams is not supported; emit a note
            // listing the chord names so the reader knows which chords are in use.
            let kbd_defines = song.keyboard_defines();
            let voicings: Vec<_> = song
                .used_chord_names()
                .into_iter()
                .filter_map(|name| {
                    chordsketch_chordpro::lookup_keyboard_voicing(&name, &kbd_defines)
                })
                .collect();
            if !voicings.is_empty() {
                output.push(String::new());
                output.push("[Chord Diagrams]".to_string());
                for voicing in &voicings {
                    output.push(format!(
                        "  {}: keys {}",
                        voicing.title(),
                        voicing
                            .keys
                            .iter()
                            .map(|k| k.to_string())
                            .collect::<Vec<_>>()
                            .join(" ")
                    ));
                }
            }
        } else {
            let frets_shown = _config.get_path("diagrams.frets").as_f64().map_or(
                chordsketch_chordpro::chord_diagram::DEFAULT_FRETS_SHOWN,
                |n| (n as usize).max(1),
            );
            let defines = song.fretted_defines();
            let diagrams: Vec<_> = song
                .used_chord_names()
                .into_iter()
                .filter_map(|name| {
                    chordsketch_chordpro::lookup_diagram(&name, &defines, instrument, frets_shown)
                })
                .collect();
            if !diagrams.is_empty() {
                output.push(String::new());
                output.push("[Chord Diagrams]".to_string());
                for diagram in &diagrams {
                    output.push(String::new());
                    for diagram_line in
                        chordsketch_chordpro::chord_diagram::render_ascii(diagram).lines()
                    {
                        output.push(diagram_line.to_string());
                    }
                }
            }
        }
    }

    // Remove trailing empty lines, then add a final newline.
    while output.last().is_some_and(|l| l.is_empty()) {
        output.pop();
    }

    if output.is_empty() {
        return String::new();
    }

    let mut result = output.join("\n");
    result.push('\n');
    result
}

/// Render multiple [`Song`]s to plain text, separated by a blank line.
#[must_use]
pub fn render_songs(songs: &[Song]) -> String {
    render_songs_with_transpose(songs, 0, &Config::defaults())
}

/// Render multiple [`Song`]s to plain text with transposition.
///
/// Warnings are printed to stderr via `eprintln!`. Use
/// [`render_songs_with_warnings`] to capture them programmatically.
#[must_use]
pub fn render_songs_with_transpose(songs: &[Song], cli_transpose: i8, config: &Config) -> String {
    let result = render_songs_with_warnings(songs, cli_transpose, config);
    for w in &result.warnings {
        eprintln!("warning: {w}");
    }
    result.output
}

/// Render multiple [`Song`]s to plain text, returning warnings programmatically.
///
/// This is the structured variant of [`render_songs_with_transpose`]. Instead
/// of printing warnings to stderr, they are collected into
/// [`RenderResult::warnings`].
#[must_use = "caller must check warnings in the returned RenderResult"]
pub fn render_songs_with_warnings(
    songs: &[Song],
    cli_transpose: i8,
    config: &Config,
) -> RenderResult<String> {
    let mut warnings = Vec::new();
    let mut parts: Vec<String> = songs
        .iter()
        .map(|song| {
            render_song_impl(song, cli_transpose, config, &mut warnings)
                .trim_end()
                .to_string()
        })
        .collect();
    // Ensure the final output ends with a newline.
    if let Some(last) = parts.last_mut() {
        last.push('\n');
    }
    RenderResult::with_warnings(parts.join("\n\n"), warnings)
}

/// Parse a ChordPro source string and render it to plain text.
///
/// Returns `Ok(text)` on success, or the [`chordsketch_chordpro::ParseError`] if
/// the input cannot be parsed.
///
/// For pre-parsed input, use [`render_song`] directly.
#[must_use = "parse errors should be handled"]
pub fn try_render(input: &str) -> Result<String, chordsketch_chordpro::ParseError> {
    let song = chordsketch_chordpro::parse(input)?;
    Ok(render_song(&song))
}

/// Parse a ChordPro source string and render it to plain text.
///
/// This is a convenience wrapper around [`try_render`] that converts parse
/// errors into a human-readable error string. Because success and failure
/// both return a `String`, callers **cannot** distinguish between them
/// programmatically — use [`try_render`] if you need error handling.
#[must_use]
pub fn render(input: &str) -> String {
    match try_render(input) {
        Ok(text) => text,
        Err(e) => format!(
            "Parse error at line {} column {}: {}\n",
            e.line(),
            e.column(),
            e.message
        ),
    }
}

// ---------------------------------------------------------------------------
// Metadata header
// ---------------------------------------------------------------------------

/// Render the song metadata (title, subtitle) as a header block.
///
/// No trailing blank line is added — the document's own empty lines
/// provide spacing between the metadata header and the song body.
fn render_metadata(metadata: &chordsketch_chordpro::ast::Metadata, output: &mut Vec<String>) {
    if let Some(title) = &metadata.title {
        output.push(title.clone());
    }
    for subtitle in &metadata.subtitles {
        output.push(subtitle.clone());
    }
}

// ---------------------------------------------------------------------------
// Lyrics rendering (chord-over-lyrics alignment)
// ---------------------------------------------------------------------------

/// Render a lyrics line with chords aligned above the lyrics.
///
/// If the line has chords, two lines are produced:
///   1. A chord line with each chord positioned above its lyrics segment.
///   2. The lyrics text.
///
/// If the line has no chords, only the lyrics text is emitted.
///
/// Alignment is based on Unicode display width (`UnicodeWidthStr::width()`),
/// which correctly handles full-width CJK characters and other wide glyphs.
fn render_lyrics(lyrics_line: &LyricsLine, transpose_offset: i8, output: &mut Vec<String>) {
    if !lyrics_line.has_chords() {
        output.push(lyrics_line.text());
        return;
    }

    let mut chord_line = String::new();
    let mut lyric_line = String::new();

    for segment in &lyrics_line.segments {
        let transposed;
        let chord_name = if transpose_offset != 0 {
            if let Some(chord) = &segment.chord {
                transposed = transpose_chord(chord, transpose_offset);
                transposed.display_name()
            } else {
                ""
            }
        } else {
            segment.chord.as_ref().map_or("", |c| c.display_name())
        };
        let text = &segment.text;

        let chord_len = UnicodeWidthStr::width(chord_name);
        let text_len = UnicodeWidthStr::width(text.as_str());

        // Write the chord (or equivalent spacing) on the chord line.
        chord_line.push_str(chord_name);

        // Write the text on the lyric line.
        lyric_line.push_str(text);

        // Ensure alignment: both lines must advance to at least the same column.
        // If the chord is longer than the text, pad the lyric line.
        // If the text is longer than the chord, pad the chord line.
        // Add 1 space of padding after chord when chord >= text length,
        // so chords don't run together.
        if chord_len > 0 && chord_len >= text_len {
            let padding = chord_len - text_len + 1;
            lyric_line.extend(std::iter::repeat_n(' ', padding));
            chord_line.push(' ');
        } else if chord_len > 0 && text_len > chord_len {
            let padding = text_len - chord_len;
            chord_line.extend(std::iter::repeat_n(' ', padding));
        }
        // If chord_len == 0 (no chord), text just advances lyric_line naturally
        // and chord_line needs to keep up.
        if chord_len == 0 && text_len > 0 {
            chord_line.extend(std::iter::repeat_n(' ', text_len));
        }
    }

    output.push(chord_line.trim_end().to_string());
    output.push(lyric_line.trim_end().to_string());
}

// ---------------------------------------------------------------------------
// Directive rendering
// ---------------------------------------------------------------------------

/// Render a directive to text output.
///
/// - Section start directives produce a labeled header (e.g., "Chorus").
/// - Section end directives are not rendered (they are structural markers).
/// - Metadata directives are not rendered here (handled by `render_metadata`).
/// - Page-layout directives (`{new_page}`, `{new_physical_page}`, `{column_break}`,
///   `{columns}`) produce no output — plain text has no concept of pages or columns.
/// - Unknown directives are silently ignored.
fn render_directive(
    directive: &chordsketch_chordpro::ast::Directive,
    output: &mut Vec<String>,
    warnings: &mut Vec<String>,
) {
    match &directive.kind {
        DirectiveKind::StartOfChorus => {
            render_section_header("Chorus", &directive.value, output);
        }
        DirectiveKind::StartOfVerse => {
            render_section_header("Verse", &directive.value, output);
        }
        DirectiveKind::StartOfBridge => {
            render_section_header("Bridge", &directive.value, output);
        }
        DirectiveKind::StartOfTab => {
            render_section_header("Tab", &directive.value, output);
        }
        DirectiveKind::StartOfGrid => {
            render_section_header("Grid", &directive.value, output);
        }
        // Notation block openers (ABC / Lilypond / MusicXML / SVG) are
        // handled in the main render loop's notation-block skip window
        // so they never reach this function. The `{start_of_textblock}`
        // directive is NOT a notation block — it's documented text so
        // it renders its section header here like any other section.
        DirectiveKind::StartOfTextblock => {
            render_section_header("Textblock", &directive.value, output);
        }
        DirectiveKind::StartOfSection(section_name) => {
            // Capitalize the first letter of the section name for display.
            let label = chordsketch_chordpro::capitalize(section_name);
            render_section_header(&label, &directive.value, output);
        }
        DirectiveKind::Image(attrs) if attrs.has_src() => {
            // Validate the src for parity with the HTML renderer (#1832,
            // renderer-parity.md §Validation Parity). Dangerous URI
            // schemes such as `javascript:` and `file:///etc/passwd`
            // never belong in rendered output — text output is not
            // executed, but embedding such strings would mislead any
            // tool or human that copies them downstream.
            if !chordsketch_chordpro::image_path::is_safe_image_src(&attrs.src) {
                push_warning(
                    warnings,
                    format!(
                        "Image src {:?} rejected by sanitizer; omitted from text output",
                        attrs.src
                    ),
                );
            } else {
                output.push(format!("[Image: {}]", attrs.src));
            }
        }
        DirectiveKind::Image(_) => {}
        // Page-layout directives are intentionally no-ops in plain-text output:
        // plain text has no concept of pages, columns, or column breaks.
        // Explicit arms here make the omission visible to future contributors
        // (renderer-parity.md requires every directive to have an explicit arm).
        DirectiveKind::NewPage
        | DirectiveKind::NewPhysicalPage
        | DirectiveKind::ColumnBreak
        | DirectiveKind::Columns => {}
        // End-of-section, metadata, and unknown directives produce no output.
        _ => {}
    }
}

/// Render a `{chorus}` recall directive.
///
/// Re-renders the stored chorus AST lines with the current transpose offset,
/// so chords are transposed correctly even if `{transpose}` changed after
/// the chorus was defined.
fn render_chorus_recall(
    value: &Option<String>,
    chorus_body: &[Line],
    transpose_offset: i8,
    output: &mut Vec<String>,
    warnings: &mut Vec<String>,
) {
    render_section_header("Chorus", value, output);
    for line in chorus_body {
        match line {
            Line::Lyrics(lyrics) => render_lyrics(lyrics, transpose_offset, output),
            Line::Comment(style, text) => render_comment(*style, text, output),
            Line::Empty => output.push(String::new()),
            Line::Directive(d) if !d.kind.is_metadata() => {
                render_directive(d, output, warnings);
            }
            _ => {}
        }
    }
}

/// Render a section header like "Chorus" or "Verse 1".
fn render_section_header(label: &str, value: &Option<String>, output: &mut Vec<String>) {
    match value {
        Some(v) if !v.is_empty() => output.push(format!("[{label}: {v}]")),
        _ => output.push(format!("[{label}]")),
    }
}

// ---------------------------------------------------------------------------
// Comment rendering
// ---------------------------------------------------------------------------

/// Render a comment with its style marker.
///
/// - Normal comments: `(comment text)`
/// - Italic comments: `(*comment text*)`
/// - Boxed comments:  `[comment text]`
fn render_comment(style: CommentStyle, text: &str, output: &mut Vec<String>) {
    match style {
        CommentStyle::Normal => output.push(format!("({text})")),
        CommentStyle::Italic => output.push(format!("(*{text}*)")),
        CommentStyle::Boxed => output.push(format!("[{text}]")),
    }
}

// ===========================================================================
// Tests
// ===========================================================================

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

    #[test]
    fn test_render_empty() {
        assert_eq!(render(""), "");
    }

    #[test]
    fn test_render_title_only() {
        let input = "{title: Amazing Grace}";
        let output = render(input);
        assert_eq!(output, "Amazing Grace\n");
    }

    #[test]
    fn test_render_title_and_subtitle() {
        let input = "{title: Amazing Grace}\n{subtitle: Traditional}";
        let output = render(input);
        assert_eq!(output, "Amazing Grace\nTraditional\n");
    }

    #[test]
    fn test_render_plain_lyrics() {
        let input = "Hello world\nSecond line";
        let output = render(input);
        assert_eq!(output, "Hello world\nSecond line\n");
    }

    #[test]
    fn test_render_lyrics_with_chords() {
        let input = "[Am]Hello [G]world";
        let output = render(input);
        assert_eq!(output, "Am    G\nHello world\n");
    }

    #[test]
    fn test_render_chord_longer_than_text() {
        // Chord "Cmaj7" is 5 chars, text "I" is 1 char
        let input = "[Cmaj7]I [G]see";
        let output = render(input);
        assert_eq!(output, "Cmaj7 G\nI     see\n");
    }

    #[test]
    fn test_render_chorus_section() {
        let input = "{start_of_chorus}\n[G]La la la\n{end_of_chorus}";
        let output = render(input);
        assert_eq!(output, "[Chorus]\nG\nLa la la\n");
    }

    #[test]
    fn test_render_verse_with_label() {
        let input = "{start_of_verse: Verse 1}\nSome lyrics\n{end_of_verse}";
        let output = render(input);
        assert_eq!(output, "[Verse: Verse 1]\nSome lyrics\n");
    }

    #[test]
    fn test_render_comment_normal() {
        let input = "{comment: This is a comment}";
        let output = render(input);
        assert_eq!(output, "(This is a comment)\n");
    }

    #[test]
    fn test_render_comment_italic() {
        let input = "{comment_italic: Softly}";
        let output = render(input);
        assert_eq!(output, "(*Softly*)\n");
    }

    #[test]
    fn test_render_comment_box() {
        let input = "{comment_box: Important}";
        let output = render(input);
        assert_eq!(output, "[Important]\n");
    }

    #[test]
    fn test_render_empty_lines_preserved() {
        let input = "Line one\n\nLine two";
        let output = render(input);
        assert_eq!(output, "Line one\n\nLine two\n");
    }

    #[test]
    fn test_render_metadata_not_duplicated() {
        // Metadata directives like {artist} should NOT appear in body text
        let input = "{title: Test}\n{artist: Someone}\n{key: G}\nLyrics here";
        let output = render(input);
        assert_eq!(output, "Test\nLyrics here\n");
    }

    #[test]
    fn test_render_full_song() {
        let input = "\
{title: Amazing Grace}
{subtitle: Traditional}
{key: G}

{start_of_verse}
[G]Amazing [G7]grace, how [C]sweet the [G]sound
[G]That saved a [Em]wretch like [D]me
{end_of_verse}

{start_of_chorus}
[G]I once was [G7]lost, but [C]now am [G]found
{end_of_chorus}";
        let output = render(input);
        // Just verify it doesn't panic and produces non-empty output
        assert!(!output.is_empty());
        assert!(output.contains("Amazing Grace"));
        assert!(output.contains("[Verse]"));
        assert!(output.contains("[Chorus]"));
    }

    #[test]
    fn test_render_song_api() {
        let song = chordsketch_chordpro::parse("{title: Test}\n[Am]Hello").unwrap();
        let output = render_song(&song);
        assert!(output.contains("Test"));
        assert!(output.contains("Am"));
        assert!(output.contains("Hello"));
    }

    #[test]
    fn test_render_chord_only_segment() {
        // A chord at end of line with no following text
        let input = "[Am]Hello [G]";
        let output = render(input);
        assert!(output.contains("Am"));
        assert!(output.contains("G"));
        assert!(output.contains("Hello"));
    }

    #[test]
    fn test_render_bridge_section() {
        let input = "{start_of_bridge}\nBridge lyrics\n{end_of_bridge}";
        let output = render(input);
        assert_eq!(output, "[Bridge]\nBridge lyrics\n");
    }

    #[test]
    fn test_render_tab_section() {
        let input = "{start_of_tab}\ne|---0---|\n{end_of_tab}";
        let output = render(input);
        assert_eq!(output, "[Tab]\ne|---0---|\n");
    }

    // --- Issue #65: Unicode alignment ---

    #[test]
    fn test_render_multibyte_lyrics_alignment() {
        // Japanese text: each char is 3 bytes, 1 code point, but 2 columns wide.
        let input = "[Am]こんにちは [G]世界";
        let output = render(input);
        // "こんにちは " = 5×2 + 1 = 11 display columns, "Am" = 2 → pad chord by 9
        // "世界" = 2×2 = 4 display columns, "G" = 1 → pad chord by 3
        assert_eq!(output, "Am         G\nこんにちは 世界\n");
    }

    #[test]
    fn test_render_accented_lyrics_alignment() {
        let input = "[Em]café [D]résumé";
        let output = render(input);
        assert_eq!(output, "Em   D\ncafé résumé\n");
    }

    // --- Issue #66: Text before first chord ---

    #[test]
    fn test_render_text_before_first_chord() {
        let input = "Hello [Am]world";
        let output = render(input);
        assert_eq!(output, "      Am\nHello world\n");
    }

    #[test]
    fn test_render_text_before_first_chord_multiple() {
        let input = "I say [Am]hello [G]world";
        let output = render(input);
        assert_eq!(output, "      Am    G\nI say hello world\n");
    }

    // --- Issue #67: try_render API ---

    #[test]
    fn test_try_render_success() {
        let result = try_render("{title: Test}\n[Am]Hello");
        assert!(result.is_ok());
        let text = result.unwrap();
        assert!(text.contains("Test"));
        assert!(text.contains("Am"));
    }

    #[test]
    fn test_try_render_parse_error() {
        let result = try_render("{title: unclosed");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.line(), 1);
    }

    #[test]
    fn test_render_grid_section() {
        let input = "{start_of_grid}\n| Am . | C . |\n{end_of_grid}";
        let output = render(input);
        assert_eq!(output, "[Grid]\n| Am . | C . |\n");
    }

    #[test]
    fn test_render_grid_section_with_label() {
        let input = "{start_of_grid: Intro}\n| Am . | C . |\n{end_of_grid}";
        let output = render(input);
        assert_eq!(output, "[Grid: Intro]\n| Am . | C . |\n");
    }

    #[test]
    fn test_render_grid_short_alias() {
        let input = "{sog}\n| G . | D . |\n{eog}";
        let output = render(input);
        assert_eq!(output, "[Grid]\n| G . | D . |\n");
    }

    // --- Custom sections (#108) ---

    #[test]
    fn test_render_custom_section_intro() {
        let input = "{start_of_intro}\n[Am]Da da da\n{end_of_intro}";
        let output = render(input);
        assert!(output.contains("[Intro]"));
        assert!(output.contains("Am"));
        assert!(output.contains("Da da da"));
    }

    #[test]
    fn test_render_custom_section_with_label() {
        let input = "{start_of_intro: Guitar}\nSome notes\n{end_of_intro}";
        let output = render(input);
        assert_eq!(output, "[Intro: Guitar]\nSome notes\n");
    }

    #[test]
    fn test_render_custom_section_outro() {
        let input = "{start_of_outro}\nFinal notes\n{end_of_outro}";
        let output = render(input);
        assert!(output.contains("[Outro]"));
    }

    #[test]
    fn test_render_custom_section_solo() {
        let input = "{start_of_solo}\n[Em]Solo line\n{end_of_solo}";
        let output = render(input);
        assert!(output.contains("[Solo]"));
    }
}

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

    #[test]
    fn test_render_songs_two_songs() {
        let songs = chordsketch_chordpro::parse_multi(
            "{title: Song One}\n[Am]Hello\n{new_song}\n{title: Song Two}\n[G]World",
        )
        .unwrap();
        let output = render_songs(&songs);
        assert!(output.contains("Song One"));
        assert!(output.contains("Am"));
        assert!(output.contains("Hello"));
        assert!(output.contains("Song Two"));
        assert!(output.contains("G\nWorld"));
        // Two songs are separated by exactly one blank line (double newline).
        assert!(output.contains("\n\n"));
        // Must NOT contain triple newline.
        assert!(
            !output.contains("\n\n\n"),
            "Should not have triple newline between songs"
        );
    }

    #[test]
    fn test_render_songs_single_song() {
        let songs = chordsketch_chordpro::parse_multi("{title: Only One}\nLyrics").unwrap();
        let output = render_songs(&songs);
        assert_eq!(output, render_song(&songs[0]));
    }

    #[test]
    fn test_render_songs_with_transpose() {
        let songs =
            chordsketch_chordpro::parse_multi("{title: S1}\n[C]Do\n{new_song}\n{title: S2}\n[G]Re")
                .unwrap();
        let output = render_songs_with_transpose(&songs, 2, &Config::defaults());
        // C+2=D, G+2=A
        assert!(output.contains("D\nDo"));
        assert!(output.contains("A\nRe"));
    }
}

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

    #[test]
    fn test_transpose_directive_up_2() {
        let input = "{transpose: 2}\n[G]Hello [C]world";
        let song = chordsketch_chordpro::parse(input).unwrap();
        let output = render_song(&song);
        // G+2=A, C+2=D
        assert_eq!(output, "A     D\nHello world\n");
    }

    #[test]
    fn test_transpose_directive_down_3() {
        let input = "{transpose: -3}\n[Am]Hello [Em]world";
        let song = chordsketch_chordpro::parse(input).unwrap();
        let output = render_song(&song);
        // Am-3=F#m, Em-3=C#m
        assert_eq!(output, "F#m   C#m\nHello world\n");
    }

    #[test]
    fn test_transpose_directive_replaces_previous() {
        let input = "{transpose: 2}\n[G]First\n{transpose: -1}\n[G]Second";
        let song = chordsketch_chordpro::parse(input).unwrap();
        let output = render_song(&song);
        // First line: G+2=A, Second line: G-1=F#
        assert!(output.contains("A\nFirst"));
        assert!(output.contains("F#\nSecond"));
    }

    #[test]
    fn test_transpose_directive_zero_resets() {
        let input = "{transpose: 5}\n[C]Up\n{transpose: 0}\n[C]Normal";
        let song = chordsketch_chordpro::parse(input).unwrap();
        let output = render_song(&song);
        // First line: C+5=F, Second line: C+0=C
        assert!(output.contains("F\nUp"));
        assert!(output.contains("C\nNormal"));
    }

    #[test]
    fn test_transpose_directive_with_cli_offset() {
        let input = "{transpose: 2}\n[C]Hello";
        let song = chordsketch_chordpro::parse(input).unwrap();
        let output = render_song_with_transpose(&song, 3, &Config::defaults());
        // In-file 2 + CLI 3 = 5 total. C+5=F
        assert!(output.contains("F\nHello"));
    }

    #[test]
    fn test_cli_transpose_without_directive() {
        let input = "[G]Hello [C]world";
        let song = chordsketch_chordpro::parse(input).unwrap();
        let output = render_song_with_transpose(&song, 2, &Config::defaults());
        // CLI offset only: G+2=A, C+2=D
        assert_eq!(output, "A     D\nHello world\n");
    }

    #[test]
    fn test_transpose_directive_replaces_with_cli_additive() {
        let input = "{transpose: 2}\n[C]First\n{transpose: -1}\n[C]Second";
        let song = chordsketch_chordpro::parse(input).unwrap();
        let output = render_song_with_transpose(&song, 1, &Config::defaults());
        // First: 2+1=3, C+3=D#. Second: -1+1=0, C+0=C
        assert!(output.contains("D#\nFirst"));
        assert!(output.contains("C\nSecond"));
    }

    #[test]
    fn test_transpose_no_chord_lyrics_unaffected() {
        let input = "{transpose: 5}\nPlain lyrics no chords";
        let song = chordsketch_chordpro::parse(input).unwrap();
        let output = render_song(&song);
        assert_eq!(output, "Plain lyrics no chords\n");
    }

    #[test]
    fn test_transpose_invalid_value_treated_as_zero() {
        let input = "{transpose: abc}\n[G]Hello";
        let song = chordsketch_chordpro::parse(input).unwrap();
        let result =
            render_song_with_warnings(&song, 0, &chordsketch_chordpro::config::Config::defaults());
        // Invalid value -> treated as 0
        assert!(result.output.contains("G\nHello"));
        assert!(
            result.warnings.iter().any(|w| w.contains("\"abc\"")),
            "expected warning about unparseable value, got: {:?}",
            result.warnings
        );
    }

    #[test]
    fn test_transpose_out_of_i8_range_emits_warning() {
        // 999 cannot be represented as i8; should fall back to 0 with a warning
        let input = "{transpose: 999}\n[G]Hello";
        let song = chordsketch_chordpro::parse(input).unwrap();
        let result =
            render_song_with_warnings(&song, 0, &chordsketch_chordpro::config::Config::defaults());
        assert!(
            result.output.contains("G\nHello"),
            "chord should be untransposed"
        );
        assert!(
            result.warnings.iter().any(|w| w.contains("\"999\"")),
            "expected warning about out-of-range value, got: {:?}",
            result.warnings
        );
    }

    #[test]
    fn test_transpose_no_value_treated_as_zero() {
        let input = "{transpose}\n[G]Hello";
        let song = chordsketch_chordpro::parse(input).unwrap();
        let result =
            render_song_with_warnings(&song, 0, &chordsketch_chordpro::config::Config::defaults());
        // No value -> silently treated as 0, no warning emitted.
        assert!(result.output.contains("G\nHello"));
        assert!(
            result.warnings.is_empty(),
            "missing {{transpose}} value should not emit a warning; got: {:?}",
            result.warnings
        );
    }

    #[test]
    fn test_transpose_whitespace_value_treated_as_zero() {
        // {transpose:   } with whitespace-only value should silently reset to 0,
        // no warning emitted. The parser trims whitespace → Some(""), which the
        // Some("") arm converts to 0.
        let input = "{transpose:   }\n[G]Hello";
        let song = chordsketch_chordpro::parse(input).unwrap();
        let result =
            render_song_with_warnings(&song, 0, &chordsketch_chordpro::config::Config::defaults());
        assert!(
            result.output.contains("G\nHello"),
            "chord should be untransposed"
        );
        assert!(
            result.warnings.is_empty(),
            "whitespace-only {{transpose}} value should not emit a warning; got: {:?}",
            result.warnings
        );
    }

    // --- Issue #109: {chorus} recall ---

    #[test]
    fn test_render_chorus_recall_basic() {
        let input = "\
{start_of_chorus}
[G]La la la
{end_of_chorus}

{start_of_verse}
Some verse
{end_of_verse}

{chorus}";
        let output = render(input);
        // The chorus content should appear twice: once in the original and once recalled
        assert_eq!(
            output,
            "[Chorus]\nG\nLa la la\n\n[Verse]\nSome verse\n\n[Chorus]\nG\nLa la la\n"
        );
    }

    #[test]
    fn test_render_chorus_recall_with_label() {
        let input = "\
{start_of_chorus}
Sing along
{end_of_chorus}

{chorus: Repeat}";
        let output = render(input);
        assert!(output.contains("[Chorus: Repeat]"));
        assert_eq!(
            output,
            "[Chorus]\nSing along\n\n[Chorus: Repeat]\nSing along\n"
        );
    }

    #[test]
    fn test_render_chorus_recall_no_chorus_defined() {
        // When {chorus} is used before any chorus is defined, just show the header
        let input = "{chorus}";
        let output = render(input);
        assert_eq!(output, "[Chorus]\n");
    }

    #[test]
    fn test_render_chorus_recall_multiple() {
        let input = "\
{start_of_chorus}
Chorus line
{end_of_chorus}
{chorus}
{chorus}";
        let output = render(input);
        // Original chorus + two recalls
        assert_eq!(
            output,
            "[Chorus]\nChorus line\n[Chorus]\nChorus line\n[Chorus]\nChorus line\n"
        );
    }

    #[test]
    fn test_render_chorus_recall_uses_latest() {
        // If there are multiple chorus definitions, recall uses the latest
        let input = "\
{start_of_chorus}
First chorus
{end_of_chorus}

{start_of_chorus}
Second chorus
{end_of_chorus}

{chorus}";
        let output = render(input);
        // The recall should use "Second chorus", not "First chorus"
        assert!(output.ends_with("[Chorus]\nSecond chorus\n"));
    }

    #[test]
    fn test_chorus_recall_applies_current_transpose() {
        // Chorus defined with no transpose, recalled after {transpose: 2}.
        // G should become A in the recalled chorus.
        let input = "\
{start_of_chorus}
[G]La la
{end_of_chorus}
{transpose: 2}
{chorus}";
        let output = render(input);
        // Original chorus has [G], recalled chorus should have [A].
        // The recalled chorus should show "A" (G+2) not "G".
        // The output has chord on one line and lyrics on next.
        let recall_idx = output.rfind("[Chorus]").expect("should have recall");
        let recall_section = &output[recall_idx..];
        assert!(
            recall_section.contains('A') && !recall_section.contains('G'),
            "recalled chorus should have transposed chord A (not G), got:\n{recall_section}"
        );
    }

    #[test]
    fn test_chorus_recall_limit_exceeded() {
        // Generate input with more chorus recalls than the limit.
        let mut input = String::from("{start_of_chorus}\nChorus\n{end_of_chorus}\n");
        for _ in 0..1005 {
            input.push_str("{chorus}\n");
        }
        let output = render(&input);
        // Count occurrences of the chorus content (excluding the original).
        let recall_count = output.matches("[Chorus]\nChorus").count() - 1; // subtract original
        assert_eq!(
            recall_count,
            super::MAX_CHORUS_RECALLS,
            "should stop at MAX_CHORUS_RECALLS"
        );
    }

    #[test]
    fn test_page_control_not_replayed_in_chorus_recall() {
        // Page-control directives inside a chorus definition must NOT appear in
        // {chorus} recall output. This mirrors the equivalent test in the HTML and
        // PDF renderers (renderer-parity.md).
        let input = "\
{start_of_chorus}
[G]Chorus line
{new_page}
{column_break}
{columns: 2}
{end_of_chorus}
{chorus}";
        let output = render(input);
        // The recalled chorus must contain the lyric content …
        assert!(
            output.contains("G"),
            "chord from chorus must appear in recall: {output}"
        );
        assert!(
            output.contains("Chorus line"),
            "lyric from chorus must appear in recall: {output}"
        );
        // … but must NOT contain any page-control directive text.
        // (Page-control directives produce no text output in the text renderer,
        //  so if they were erroneously replayed, the output would be unchanged;
        //  the key assertion is that the chorus body stored during collection
        //  does not include the directive AST nodes and cause extra empty lines.)
        let chorus_section_lines: Vec<&str> = output.lines().collect();
        // The definition renders: [Chorus] header + chord line + lyric line.
        // The recall renders: [Chorus] header + chord line + lyric line again.
        // Total: 6 non-empty lines (3 original + 3 recall). No extra blank lines
        // introduced by replayed page-control directives.
        let non_empty_count = chorus_section_lines
            .iter()
            .filter(|l| !l.is_empty())
            .count();
        assert_eq!(
            non_empty_count, 6,
            "expected 6 non-empty output lines (3 original + 3 recall), got {non_empty_count}; \
             output:\n{output}"
        );
    }
}

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

    // -- Notation blocks (#1971): body is skipped, warning is captured,
    //    placeholder line renders. Parity with the PDF renderer's
    //    behaviour from #1825/#1968.

    #[test]
    fn test_render_abc_section() {
        let input = "{start_of_abc}\nX:1\nK:G\n{end_of_abc}";
        let output = render(input);
        assert!(output.contains("[ABC]"));
        assert!(
            !output.contains("X:1"),
            "ABC body must not leak into text output; got:\n{output}"
        );
        assert!(output.contains("[ABC block omitted"));
    }

    #[test]
    fn test_render_abc_section_with_label() {
        let input = "{start_of_abc: Melody}\nX:1\n{end_of_abc}";
        let output = render(input);
        // Section header + placeholder; body is gone.
        assert!(output.contains("[ABC: Melody]"));
        assert!(!output.contains("X:1"));
        assert!(output.contains("[ABC block omitted"));
    }

    #[test]
    fn test_render_abc_section_emits_warning() {
        let input = "{start_of_abc}\nX:1\n{end_of_abc}";
        let song = chordsketch_chordpro::parse(input).unwrap();
        let result = render_song_with_warnings(&song, 0, &Config::defaults());
        assert!(
            result.warnings.iter().any(|w| w.contains("ABC")),
            "expected an ABC warning; got {:?}",
            result.warnings,
        );
    }

    #[test]
    fn test_render_ly_section() {
        let input = "{start_of_ly}\n\\relative c' { c4 d }\n{end_of_ly}";
        let output = render(input);
        assert!(output.contains("[Lilypond]"));
        assert!(!output.contains("\\relative"));
        assert!(output.contains("[Lilypond block omitted"));
    }

    #[test]
    fn test_render_svg_section() {
        let input = "{start_of_svg}\n<svg><circle/></svg>\n{end_of_svg}";
        let output = render(input);
        assert!(output.contains("[SVG]"));
        assert!(!output.contains("<circle"));
        assert!(output.contains("[SVG block omitted"));
    }

    #[test]
    fn test_render_textblock_section() {
        // `{start_of_textblock}` is NOT a notation block — body must
        // continue to render as plain text. Guard against accidental
        // inclusion in the notation skip window.
        let input = "{start_of_textblock}\nPreformatted text\n{end_of_textblock}";
        let output = render(input);
        assert!(output.contains("[Textblock]"));
        assert!(output.contains("Preformatted text"));
    }

    #[test]
    fn test_render_musicxml_section() {
        let input =
            "{start_of_musicxml}\n<score-partwise>notes</score-partwise>\n{end_of_musicxml}";
        let output = render(input);
        assert!(output.contains("[MusicXML]"));
        assert!(!output.contains("<score-partwise"));
        assert!(output.contains("[MusicXML block omitted"));
    }

    #[test]
    fn test_render_musicxml_section_with_label() {
        let input = "{start_of_musicxml: Score}\n<score-partwise/>\n{end_of_musicxml}";
        let output = render(input);
        assert!(output.contains("[MusicXML: Score]"));
        assert!(output.contains("[MusicXML block omitted"));
        // Negative assertion — body must not leak even when the
        // section header carries a label. Mirrors the unlabelled
        // variant so a future regression touching either code path
        // fails here.
        assert!(
            !output.contains("<score-partwise"),
            "MusicXML body must not leak into text output; got:\n{output}"
        );
    }

    // #1974 — edge-case coverage for the notation-block skip window.
    // Mirrors the tests added to the PDF renderer in #1969 so both
    // skip-and-warn implementations are guarded by the same set of
    // scenarios.

    #[test]
    fn test_text_notation_block_inside_chorus_is_excluded_from_recall() {
        let input = "{start_of_chorus}\n\
                     [G]Sing along\n\
                     {start_of_abc}\n\
                     X:1\n\
                     {end_of_abc}\n\
                     [C]another line\n\
                     {end_of_chorus}\n\
                     {chorus}\n";
        let song = chordsketch_chordpro::parse(input).unwrap();
        let result = render_song_with_warnings(&song, 0, &Config::defaults());
        // One ABC block seen once → exactly one ABC warning. A recall
        // that re-emitted the placeholder would double this.
        let abc_warnings = result.warnings.iter().filter(|w| w.contains("ABC")).count();
        assert_eq!(
            abc_warnings, 1,
            "exactly one ABC warning expected (recall must not re-emit); got {:?}",
            result.warnings,
        );
        assert!(result.output.contains("Sing along"));
        assert!(result.output.contains("another line"));
    }

    #[test]
    fn test_text_unterminated_notation_block_renders_without_panic() {
        let input = "[C]Before\n{start_of_abc}\nX:1\nK:C\n";
        let song = chordsketch_chordpro::parse(input).unwrap();
        let result = render_song_with_warnings(&song, 0, &Config::defaults());
        assert!(
            result.warnings.iter().any(|w| w.contains("ABC")),
            "unterminated ABC block should still emit the warning; got {:?}",
            result.warnings,
        );
        assert!(result.output.contains("Before"));
        assert!(result.output.contains("[ABC block omitted"));
        // Body must not leak even though no EndOf was seen.
        assert!(!result.output.contains("X:1"));
        assert!(!result.output.contains("K:C"));
    }

    #[test]
    fn test_text_stray_end_of_notation_is_silently_ignored() {
        let input = "[C]Hello\n{end_of_abc}\n[D]World\n";
        let song = chordsketch_chordpro::parse(input).unwrap();
        let result = render_song_with_warnings(&song, 0, &Config::defaults());
        assert!(
            !result
                .warnings
                .iter()
                .any(|w| w.contains("ABC") && w.contains("omitted")),
            "stray `end_of_abc` must not trigger the notation-block warning; got {:?}",
            result.warnings,
        );
        assert!(result.output.contains("Hello"));
        assert!(result.output.contains("World"));
    }

    #[test]
    fn test_delegate_verbatim_no_chords() {
        let input = "{start_of_textblock}\n[Am]Not a chord\n{end_of_textblock}";
        let output = render(input);
        assert!(output.contains("[Am]Not a chord"));
    }

    // -- inline markup rendering (plain text strips all tags) ------------------

    #[test]
    fn test_markup_stripped_in_text_output() {
        let output = render("Hello <b>bold</b> world");
        assert!(output.contains("Hello bold world"));
        assert!(!output.contains("<b>"));
        assert!(!output.contains("</b>"));
    }

    #[test]
    fn test_markup_stripped_with_chord() {
        let output = render("[Am]Hello <b>bold</b> world");
        assert!(output.contains("Am"));
        assert!(output.contains("Hello bold world"));
        assert!(!output.contains("<b>"));
    }

    #[test]
    fn test_span_markup_stripped_in_text_output() {
        let output = render(r#"<span foreground="red">red text</span>"#);
        assert!(output.contains("red text"));
        assert!(!output.contains("<span"));
        assert!(!output.contains("foreground"));
    }

    // --- Unicode display width alignment ---

    #[test]
    fn test_render_fullwidth_cjk_alignment() {
        // Full-width CJK characters are 2 columns wide
        let input = "[C]日本語";
        let output = render(input);
        // "日本語" = 3×2 = 6 display columns, "C" = 1 → pad chord by 5
        assert_eq!(output, "C\n日本語\n");
    }

    #[test]
    fn test_render_mixed_width_alignment() {
        // Mix of ASCII (width 1) and CJK (width 2)
        let input = "[Am]hello世界 [G]test";
        let output = render(input);
        // "hello世界 " = 5 + 4 + 1 = 10, "Am" = 2 → pad chord by 8
        // "test" = 4, "G" = 1 → pad chord by 3
        assert_eq!(output, "Am        G\nhello世界 test\n");
    }

    #[test]
    fn test_render_image_placeholder() {
        let input = "{image: src=photo.jpg}";
        let output = render(input);
        assert!(output.contains("[Image: photo.jpg]"));
    }

    #[test]
    fn test_render_image_placeholder_with_path() {
        let input = "{image: src=images/cover.png width=200}";
        let output = render(input);
        assert!(output.contains("[Image: images/cover.png]"));
    }

    #[test]
    fn test_render_image_empty_src_suppressed() {
        let input = "{image}";
        let output = render(input);
        assert!(!output.contains("[Image"));
    }

    #[test]
    fn test_render_image_empty_src_with_other_attrs_suppressed() {
        let input = "{image: width=200 height=100}";
        let output = render(input);
        assert!(!output.contains("[Image"));
    }

    #[test]
    fn test_render_image_dangerous_scheme_rejected() {
        // #1832: text renderer must reject the same URI schemes HTML does.
        let song = chordsketch_chordpro::parse("{image: src=\"javascript:alert(1)\"}").unwrap();
        let result = render_song_with_warnings(&song, 0, &Config::defaults());
        assert!(
            !result.output.contains("[Image"),
            "javascript: src must not reach text output: {}",
            result.output
        );
        assert!(
            result.warnings.iter().any(|w| w.contains("javascript")),
            "expected a warning mentioning the rejected src; got {:?}",
            result.warnings
        );
    }

    #[test]
    fn test_render_image_file_uri_rejected() {
        let song = chordsketch_chordpro::parse("{image: src=\"file:///etc/passwd\"}").unwrap();
        let result = render_song_with_warnings(&song, 0, &Config::defaults());
        assert!(
            !result.output.contains("[Image"),
            "file: src must not reach text output"
        );
        // Sister-site parity with `test_render_image_dangerous_scheme_rejected`:
        // silent rejection is not enough — the renderer must surface a
        // warning so users know the `{image}` directive was dropped.
        assert!(
            result.warnings.iter().any(|w| w.contains("file")),
            "expected a warning mentioning the rejected src; got {:?}",
            result.warnings
        );
    }

    // -- {capo} validation parity (#1834) ---------------------------------

    #[test]
    fn test_capo_out_of_range_emits_warning() {
        let song = chordsketch_chordpro::parse("{title: T}\n{capo: 999}").unwrap();
        let result = render_song_with_warnings(&song, 0, &Config::defaults());
        assert!(
            result
                .warnings
                .iter()
                .any(|w| w.contains("capo") && w.contains("999")),
            "expected out-of-range {{capo}} warning; got {:?}",
            result.warnings
        );
    }

    #[test]
    fn test_capo_non_numeric_emits_warning() {
        let song = chordsketch_chordpro::parse("{title: T}\n{capo: foo}").unwrap();
        let result = render_song_with_warnings(&song, 0, &Config::defaults());
        assert!(
            result
                .warnings
                .iter()
                .any(|w| w.contains("capo") && w.contains("foo")),
            "expected non-integer {{capo}} warning; got {:?}",
            result.warnings
        );
    }

    #[test]
    fn test_capo_in_range_is_silent() {
        let song = chordsketch_chordpro::parse("{title: T}\n{capo: 5}").unwrap();
        let result = render_song_with_warnings(&song, 0, &Config::defaults());
        assert!(
            !result.warnings.iter().any(|w| w.contains("capo")),
            "valid {{capo: 5}} should not warn; got {:?}",
            result.warnings
        );
    }

    // -- settings.strict missing-{key} warning (R6.100.0, #2291) ----------

    #[test]
    fn test_strict_off_with_missing_key_is_silent() {
        let song = chordsketch_chordpro::parse("{title: T}").unwrap();
        let result = render_song_with_warnings(&song, 0, &Config::defaults());
        assert!(
            !result
                .warnings
                .iter()
                .any(|w| w.contains("settings.strict")),
            "default settings.strict=false must not warn on missing {{key}}; got {:?}",
            result.warnings
        );
    }

    #[test]
    fn test_strict_on_with_missing_key_warns() {
        let song = chordsketch_chordpro::parse("{title: T}").unwrap();
        let cfg = Config::defaults()
            .with_define("settings.strict=true")
            .unwrap();
        let result = render_song_with_warnings(&song, 0, &cfg);
        assert!(
            result
                .warnings
                .iter()
                .any(|w| w.contains("{key}") && w.contains("settings.strict")),
            "expected missing-{{key}} warning under settings.strict; got {:?}",
            result.warnings
        );
    }

    #[test]
    fn test_strict_on_with_present_key_is_silent() {
        let song = chordsketch_chordpro::parse("{title: T}\n{key: G}").unwrap();
        let cfg = Config::defaults()
            .with_define("settings.strict=true")
            .unwrap();
        let result = render_song_with_warnings(&song, 0, &cfg);
        assert!(
            !result
                .warnings
                .iter()
                .any(|w| w.contains("settings.strict")),
            "settings.strict warning must not fire when {{key}} is present; got {:?}",
            result.warnings
        );
    }

    // -- MAX_WARNINGS cap (#1833) -----------------------------------------

    #[test]
    fn test_max_warnings_truncates() {
        // Generate many bad {transpose} lines so every one emits a warning.
        let mut input = String::from("{title: T}\n");
        for _ in 0..(MAX_WARNINGS + 50) {
            input.push_str("{transpose: not-a-number}\n");
        }
        let song = chordsketch_chordpro::parse(&input).unwrap();
        let result = render_song_with_warnings(&song, 0, &Config::defaults());
        assert_eq!(
            result.warnings.len(),
            MAX_WARNINGS + 1,
            "expected exactly MAX_WARNINGS warnings plus one truncation marker"
        );
        assert!(
            result.warnings.last().unwrap().contains("MAX_WARNINGS"),
            "last entry must be the truncation marker; got {:?}",
            result.warnings.last()
        );
    }

    // -- Selector filtering integration (#320) --

    #[test]
    fn test_selector_filtering_removes_non_matching_directive() {
        let input = "{title: Song}\n{textfont-piano: Courier}\n[Am]Hello";
        let song = chordsketch_chordpro::parse(input).unwrap();
        let ctx = chordsketch_chordpro::selector::SelectorContext::new(Some("guitar"), None);
        let filtered = ctx.filter_song(&song);
        // The piano textfont directive should be absent from the filtered song.
        let has_textfont = filtered.lines.iter().any(|l| {
            matches!(l, chordsketch_chordpro::ast::Line::Directive(d) if d.kind == chordsketch_chordpro::ast::DirectiveKind::TextFont)
        });
        assert!(
            !has_textfont,
            "piano textfont directive should be removed for guitar context"
        );
        let output = render_song(&filtered);
        assert!(output.contains("Hello"), "lyrics should survive filtering");
    }

    #[test]
    fn test_selector_filtering_removes_section_with_contents() {
        let input = "{title: Song}\n{start_of_chorus-piano}\n[C]Piano only\n{end_of_chorus-piano}\n[Am]Guitar verse";
        let song = chordsketch_chordpro::parse(input).unwrap();
        let ctx = chordsketch_chordpro::selector::SelectorContext::new(Some("guitar"), None);
        let filtered = ctx.filter_song(&song);
        let output = render_song(&filtered);
        assert!(
            !output.contains("Piano only"),
            "piano chorus should be removed for guitar context"
        );
        assert!(
            output.contains("Guitar verse"),
            "unselectored content should remain"
        );
    }

    // -- auto-inject ASCII diagram block (issue #1140) ----------------------------

    #[test]
    fn test_diagrams_auto_inject_text() {
        let output = render("{diagrams}\n[Am]Hello");
        assert!(
            output.contains("[Chord Diagrams]"),
            "text output should include Chord Diagrams header"
        );
        assert!(output.contains("Am"), "Am ASCII diagram expected");
        // Am = x o 2 2 1 o (guitar open position)
        assert!(output.contains("x o"), "Am fret pattern expected");
    }

    #[test]
    fn test_no_diagrams_suppresses_text_inject() {
        let output = render("{no_diagrams}\n[Am]Hello");
        assert!(
            !output.contains("[Chord Diagrams]"),
            "{{no_diagrams}} should suppress ASCII diagram block"
        );
    }

    #[test]
    fn test_diagrams_off_suppresses_text_inject() {
        let output = render("{diagrams: off}\n[Am]Hello");
        assert!(
            !output.contains("[Chord Diagrams]"),
            "{{diagrams: off}} should suppress ASCII diagram block"
        );
    }

    #[test]
    fn test_diagrams_piano_auto_inject_text() {
        let output = render("{diagrams: piano}\n[Am]Hello [C]world");
        assert!(
            output.contains("[Chord Diagrams]"),
            "piano instrument should include Chord Diagrams header"
        );
        // Text renderer emits chord name + key numbers (no ASCII art for piano).
        assert!(output.contains("Am:"), "Am entry expected");
        assert!(output.contains("C:"), "C entry expected");
        assert!(output.contains("keys"), "key list label expected");
    }

    #[test]
    fn test_render_decomposed_diacritics_alignment() {
        // "e\u{0301}" is a decomposed e-acute (U+0065 + U+0301 combining acute).
        // The combining character has zero display width, so the word "cafe\u{0301}"
        // should have the same display width (4 columns) as "cafe".
        // This should produce identical alignment to composed "café".
        let input = "[Em]cafe\u{0301} [D]world";
        let output = render(input);
        // "cafe\u{0301} " = 5 display columns (4 + 0 + 1), "Em" = 2 → pad chord by 3
        // Matches composed form: "[Em]café [D]résumé" → "Em   D"
        assert_eq!(output, "Em   D\ncafe\u{0301} world\n");
    }
}