nextest-runner 0.121.0

Core runner logic for cargo nextest.
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
// Copyright (c) The nextest Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Renders MkDocs help-topic documents (help topics) to the terminal.

use crate::{config::core::NextestConfig, helpers::RESET_COLOR, user_config::UserConfig};
use indoc::formatdoc;
use nextest_filtering::FILTERSET_REFERENCE_MD;
use owo_colors::Style;
use pulldown_cmark::{CodeBlockKind, Event, Options, Parser, Tag, TagEnd};
use smallvec::SmallVec;
use std::borrow::Cow;
use swrite::{SWrite, swrite};
use synoptic::{TokOpt, from_extension};
use tracing::warn;
use unicode_width::UnicodeWidthStr;

const SITE_BASE: &str = "https://nexte.st";

/// A help topic document.
pub struct HelpDoc {
    /// The raw markdown content of the document.
    ///
    /// This is transformed by the renderer.
    pub markdown: Cow<'static, str>,
    /// The doc's directory within the site, e.g. `["docs", "filtersets"]`.
    ///
    /// This is used to resolve relative links within the document.
    pub site_dir: &'static [&'static str],
}

impl HelpDoc {
    /// The filterset reference document.
    pub fn filterset() -> Self {
        let markdown = formatdoc! {"
                # Filterset DSL reference

                This topic contains the full set of operators supported by the filterset DSL.

                This reference is also available [on the nextest site](https://nexte.st/docs/filtersets/reference/).

                {FILTERSET_REFERENCE_MD}
            "};
        Self {
            markdown: Cow::Owned(markdown),
            site_dir: &["docs", "filtersets"],
        }
    }

    /// The repository configuration reference document.
    pub fn repo_config() -> Self {
        Self {
            markdown: Cow::Owned(repo_config_markdown()),
            site_dir: &["docs", "configuration"],
        }
    }

    /// The user configuration reference document.
    pub fn user_config() -> Self {
        Self {
            markdown: Cow::Owned(user_config_markdown()),
            site_dir: &["docs", "user-config"],
        }
    }
}

fn repo_config_markdown() -> String {
    formatdoc! {"
            # Configuration reference

            This topic contains the full repository configuration reference for nextest.

            This reference is also available [on the nextest site](https://nexte.st/docs/configuration/reference/).

            {reference}

            ## Default configuration

            The default configuration shipped with cargo-nextest is:

            ```toml
            {default_config}
            ```
        ",
        reference = NextestConfig::REFERENCE_MD.trim_end(),
        default_config = NextestConfig::DEFAULT_CONFIG.trim_end(),
    }
}

fn user_config_markdown() -> String {
    formatdoc! {r#"
            # User config reference

            This topic contains the full user configuration reference for nextest.

            This reference is also available [on the nextest site](https://nexte.st/docs/user-config/reference/).

            For more information about how user configuration works, see the [user configuration overview](index.md).

            ## Configuration file location

            User configuration is loaded from one of the following platform-specific locations:

            1. On Linux, macOS, and other Unix platforms: `$XDG_CONFIG_HOME/nextest/config.toml`, or `~/.config/nextest/config.toml` if `$XDG_CONFIG_HOME` is unset or empty.
            2. On Windows: `%APPDATA%\nextest\config.toml`, falling back to `%XDG_CONFIG_HOME%\nextest\config.toml`, then `%HOME%\.config\nextest\config.toml`.

            For more information about configuration hierarchy, see [_Configuration hierarchy_](index.md#configuration-hierarchy).

            {reference}

            ## Default configuration

            The default user configuration is:

            ```toml
            {default_config}
            ```
        "#,
        reference = UserConfig::REFERENCE_MD.trim_end(),
        default_config = UserConfig::DEFAULT_CONFIG.trim_end(),
    }
}

/// Rendering options for help topic output.
pub struct RenderOptions {
    /// Whether to emit ANSI color and style codes.
    pub color: bool,
    /// Whether to emit OSC-8 hyperlinks for links.
    pub hyperlinks: bool,
    /// The maximum width, in columns, to wrap output to.
    pub width: usize,
}

/// Renders a help topic document to terminal-ready text.
pub fn render(doc: &HelpDoc, opts: RenderOptions) -> String {
    let preprocessed = preprocess(&doc.markdown);
    let rendered = render_markdown(&preprocessed, doc.site_dir, opts);
    if !rendered.dropped.is_empty() {
        warn!(
            "help renderer dropped unsupported markdown events: {:?}",
            rendered.dropped
        );
    }
    rendered.output
}

/// Preprocesses MkDocs markdown into a plain CommonMark subset.
fn preprocess(input: &str) -> String {
    let lines: Vec<&str> = input.lines().collect();
    let mut out: Vec<String> = Vec::with_capacity(lines.len());
    let mut i = 0;
    while i < lines.len() {
        let line = lines[i];
        let trimmed = line.trim_start();

        // Drop raw <div> wrappers -- no real way to support them in terminal
        // output.
        if trimmed.starts_with("<div") || trimmed == "</div>" {
            i += 1;
            continue;
        }

        // Convert admonitions into block quotes.
        if let Some(header) = admonition_header(trimmed) {
            let indent = line.len() - trimmed.len();
            let body_indent = indent + 4;
            i += 1;

            let mut body_lines: Vec<String> = Vec::new();
            while i < lines.len() {
                let l = lines[i];
                if l.trim().is_empty() {
                    body_lines.push(String::new());
                    i += 1;
                } else if leading_spaces(l) >= body_indent {
                    body_lines.push(l[l.ceil_char_boundary(body_indent)..].to_string());
                    i += 1;
                } else {
                    break;
                }
            }
            while body_lines.last().is_some_and(|s| s.is_empty()) {
                body_lines.pop();
            }

            out.push(header);
            out.push(">".to_string());
            for b in body_lines {
                if b.is_empty() {
                    out.push(">".to_string());
                } else {
                    out.push(format!("> {b}"));
                }
            }
            out.push(String::new());
            continue;
        }

        out.push(line.to_string());
        i += 1;
    }

    let joined = out.join("\n");
    apply_shortcodes(&joined)
}

fn leading_spaces(line: &str) -> usize {
    line.len() - line.trim_start().len()
}

/// Parses a `!!! kind "Title"` admonition header into a block-quote header
/// line.
fn admonition_header(trimmed: &str) -> Option<String> {
    let rest = trimmed.strip_prefix("!!! ")?;
    let (kind, title) = match rest.split_once(' ') {
        Some((kind, title)) => (kind, Some(title.trim())),
        None => (rest, None),
    };
    let label = capitalize(kind);
    let title = title.and_then(|t| t.strip_prefix('"').and_then(|t| t.strip_suffix('"')));
    Some(match title {
        Some(title) => format!("> **{label}: {title}**"),
        None => format!("> **{label}**"),
    })
}

fn capitalize(s: &str) -> String {
    let mut chars = s.chars();
    match chars.next() {
        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
        None => String::new(),
    }
}

/// Replaces `<!-- md:version X -->` with inline text, and strips other HTML
/// comments.
fn apply_shortcodes(input: &str) -> String {
    let mut out = String::new();
    let mut rest = input;
    while let Some(start) = rest.find("<!--") {
        out.push_str(&rest[..start]);
        let after = &rest[start + "<!--".len()..];
        let Some(end) = after.find("-->") else {
            out.push_str(&rest[start..]);
            return out;
        };
        let inner = after[..end].trim();
        let version = inner
            .strip_prefix("md:version")
            .filter(|rest| rest.is_empty() || rest.starts_with(char::is_whitespace));
        if let Some(version) = version {
            let version = version.trim();
            if !version.is_empty() {
                swrite!(out, "*(since {version})*");
            }
        }
        rest = &after[end + "-->".len()..];
    }
    out.push_str(rest);
    out
}

/// Rewrites a relative URL to an absolute `nexte.st` URL.
///
/// Returns `None` for same-page anchors, which are not rewritten.
fn rewrite_url(url: &str, site_dir: &[&str]) -> Option<String> {
    if url.starts_with("http://") || url.starts_with("https://") {
        return Some(url.to_string());
    }

    let (path, anchor) = match url.split_once('#') {
        Some((path, anchor)) => (path, Some(anchor)),
        None => (url, None),
    };

    // The target is a same-page anchor (e.g. [foo](#foo)). The content it
    // points to is already on screen, so drop the link.
    if path.is_empty() {
        return None;
    }

    let mut segments: Vec<String> = site_dir.iter().map(|s| s.to_string()).collect();
    for part in path.split('/') {
        match part {
            "" | "." => {}
            ".." => {
                // mkdocs would warn about this as well.
                assert!(
                    !segments.is_empty(),
                    "relative link in help doc escapes the site root: {url:?}"
                );
                segments.pop();
            }
            // With our configuration, mkdocs maps `index.md` to its containing
            // directory's URL, so this should be ignored.
            "index.md" => {}
            other => segments.push(other.trim_end_matches(".md").to_string()),
        }
    }
    let resolved = format!("{SITE_BASE}/{}/", segments.join("/"));

    Some(match anchor {
        Some(anchor) => format!("{resolved}#{anchor}"),
        None => resolved,
    })
}

const DEFINITION_INDENT: &str = "    ";
const QUOTE_PREFIX: &str = "│ ";
const CODE_INDENT: &str = "    ";

/// A stack of desired or currently-applied styles.
///
/// A capacity of 4 should cover all body text and headings in practice, and
/// most of them in theory.
type StyleStack = SmallVec<[Style; 4]>;

/// The target of a hyperlink for a run of text.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
enum LinkTarget {
    /// The text is not linked.
    #[default]
    Unlinked,
    /// The text is linked to the given URL.
    Linked(String),
}

impl LinkTarget {
    fn is_linked(&self) -> bool {
        match self {
            LinkTarget::Unlinked => false,
            LinkTarget::Linked(_) => true,
        }
    }
}

/// The presentation attributes of a run of text.
#[derive(Clone, Debug, Default)]
struct RunAttrs {
    styles: StyleStack,
    link: LinkTarget,
}

impl RunAttrs {
    /// Updates the current attributes to the desired ones, writing the
    /// corresponding escape sequences to transition over.
    fn sync(&mut self, desired: &RunAttrs, color: bool, hyperlinks: bool, out: &mut String) {
        if color {
            write_style_diff(&mut self.styles, &desired.styles, out);
        }
        if hyperlinks {
            sync_link(&mut self.link, &desired.link, out);
        }
    }
}

/// A styled run of text.
struct Span {
    text: String,
    desired: RunAttrs,
}

/// A single word to be rendered.
#[derive(Default)]
struct Word {
    /// The sequence of styled spans that make up this word.
    spans: Vec<Span>,
    /// The current width of this word, in display columns.
    width: usize,
}

impl Word {
    fn is_empty(&self) -> bool {
        self.spans.is_empty()
    }

    fn push(&mut self, text: &str, desired: &RunAttrs) {
        self.spans.push(Span {
            text: text.to_string(),
            desired: desired.clone(),
        });
        self.width += display_width(text);
    }

    fn take(&mut self) -> Vec<Span> {
        self.width = 0;
        std::mem::take(&mut self.spans)
    }
}

/// The set of styles for the help topic renderer.
#[derive(Default)]
struct Styles {
    heading: Style,
    emphasis: Style,
    strong: Style,
    strikethrough: Style,
    code: Style,
    term: Style,
    link: Style,
    toml_comment: Style,
    toml_table: Style,
    toml_string: Style,
    toml_number: Style,
    toml_boolean: Style,
}

impl Styles {
    fn colorize(&mut self) {
        self.heading = Style::new().bold().underline();
        self.emphasis = Style::new().italic();
        self.strong = Style::new().bold();
        self.strikethrough = Style::new().strikethrough();
        self.code = Style::new().cyan();
        self.term = Style::new().green().bold();
        self.link = Style::new().blue().underline();
        self.toml_comment = Style::new().dimmed();
        self.toml_table = Style::new().magenta().bold();
        self.toml_string = Style::new().green();
        self.toml_number = Style::new().yellow();
        self.toml_boolean = Style::new().yellow();
    }

    /// Maps synoptic's built-in toml token kinds onto our palette.
    fn toml_style(&self, kind: &str) -> Style {
        match kind {
            "comment" => self.toml_comment,
            "table" => self.toml_table,
            "string" => self.toml_string,
            "digit" | "keyword" => self.toml_number,
            "boolean" => self.toml_boolean,
            other => {
                // We're choosing to panic on an unknown kind because we're
                // targeting a small set of documents and we do snapshot tests
                // for all of them. (synoptic really should return a structured
                // enum rather than a string here!)
                //
                // Note that we use locked-tripwire to ensure cargo nextest
                // cannot be installed without --locked, so a newer version of
                // synoptic cannot come in and surprise us.
                panic!(
                    "unknown synoptic toml token kind {other:?} -- \
                     the built-in toml highlighter's token kinds may have changed"
                );
            }
        }
    }
}

/// The prefix written at the start of each line.
#[derive(Default)]
struct LinePrefix {
    // The stack of prefix segments, concatenated to form the prefix applied to
    // every line, unless the next line has an override.
    segments: SmallVec<[String; 4]>,
    // A one-shot override for the next line, if set.
    next_override: Option<String>,
}

impl LinePrefix {
    /// Pushes a prefix segment.
    fn push(&mut self, prefix: &str) {
        self.segments.push(prefix.to_string());
    }

    /// Pops the most recently pushed prefix segment.
    ///
    /// Panics if no segment has been pushed.
    fn pop(&mut self) {
        self.segments
            .pop()
            .expect("a prefix segment was pushed before this pop");
    }

    /// Sets an override for the next prefix by appending `marker` to the base
    /// prefix.
    fn set_next_override(&mut self, marker: &str) {
        let mut prefix = self.base();
        prefix.push_str(marker);
        self.next_override = Some(prefix);
    }

    /// Consumes the prefix for the next line.
    fn take_next(&mut self) -> String {
        self.next_override.take().unwrap_or_else(|| self.base())
    }

    fn base(&self) -> String {
        self.segments.concat()
    }
}

/// A line emitter.
///
/// This is the lower-level line-writing component. It is unaware of markdown.
struct LineWriter {
    out: String,
    color: bool,
    hyperlinks: bool,
    width: usize,

    prefix: LinePrefix,
    /// The state of the current line being written.
    line: LineState,

    /// The current word, plus a pending space that can act as a line break.
    word: Word,
    pending_space: Option<PendingSpace>,
    desired_attrs: RunAttrs,
}

/// A pending space that can also act as a line break.
///
/// Remembers the style and link currently active, so a space between two words
/// corresponding to the same link, e.g. the space between `a` and `b` in `[a
/// b](https://example.com)`, stays inside that link.
struct PendingSpace {
    desired: RunAttrs,
}

/// The mutable state of a line that is currently open.
#[derive(Clone, Debug)]
struct OpenLine {
    /// The number of visible columns used so far in this line.
    column: usize,
    /// The presentation emitted so far on this line.
    emitted: RunAttrs,
}

#[derive(Clone, Debug)]
enum LineState {
    /// The line has been opened: its prefix has been emitted, and content may
    /// follow.
    Open(OpenLine),
    /// The line is empty. Opening it writes the line prefix override if
    /// present, otherwise the prefix.
    AtStart,
    /// The line is empty.
    AfterBlock {
        /// The prefix to trim and write out on the blank line.
        prefix: String,
    },
}

impl LineWriter {
    fn new(color: bool, hyperlinks: bool, width: usize) -> Self {
        LineWriter {
            out: String::new(),
            color,
            hyperlinks,
            width,
            prefix: LinePrefix::default(),
            line: LineState::AtStart,
            word: Word::default(),
            pending_space: None,
            desired_attrs: RunAttrs::default(),
        }
    }

    fn push_style(&mut self, style: Style) {
        self.desired_attrs.styles.push(style);
    }

    fn pop_style(&mut self) {
        self.desired_attrs.styles.pop();
    }

    fn set_link(&mut self, link: LinkTarget) {
        self.desired_attrs.link = link;
    }

    fn take_link(&mut self) -> LinkTarget {
        std::mem::take(&mut self.desired_attrs.link)
    }

    /// Adds a styled segment into the current word.
    fn add_segment(&mut self, text: &str) {
        if text.is_empty() {
            return;
        }
        self.word.push(text, &self.desired_attrs);
    }

    /// Adds a breakable space, styled by the surrounding context.
    fn add_space(&mut self) {
        self.flush_word();
        self.pending_space = Some(PendingSpace {
            desired: self.desired_attrs.clone(),
        });
    }

    /// Emits the buffered word, wrapping to the provided width with a hanging
    /// indent.
    fn flush_word(&mut self) {
        if self.word.is_empty() {
            return;
        }
        let pending = self.pending_space.take();
        match &self.line {
            LineState::Open(open) => {
                if let Some(space) = pending {
                    if open.column + 1 + self.word.width > self.width {
                        self.end_line();
                        self.open_line();
                    } else {
                        self.emit_space(&space.desired);
                    }
                }
            }
            LineState::AtStart | LineState::AfterBlock { .. } => self.open_line(),
        }
        self.emit_word();
    }

    fn emit_word(&mut self) {
        let spans = self.word.take();
        let Self {
            out,
            line,
            color,
            hyperlinks,
            ..
        } = self;
        let LineState::Open(open) = line else {
            return;
        };
        for span in spans {
            open.emitted.sync(&span.desired, *color, *hyperlinks, out);
            out.push_str(&span.text);
            open.column += display_width(&span.text);
        }
    }

    fn emit_space(&mut self, desired: &RunAttrs) {
        self.write_open(" ", desired);
    }

    /// Writes styled text to the current open line, syncing styles and advancing
    /// the column.
    fn write_open(&mut self, text: &str, desired: &RunAttrs) {
        let Self {
            out,
            line,
            color,
            hyperlinks,
            ..
        } = self;
        let LineState::Open(open) = line else {
            return;
        };
        open.emitted.sync(desired, *color, *hyperlinks, out);
        out.push_str(text);
        open.column += display_width(text);
    }

    /// Writes text verbatim (without wrapping), preserving newlines.
    ///
    /// Used for code blocks.
    fn verbatim(&mut self, s: &str) {
        // Code blocks are never hyperlinked, but preserve the current styles.
        let mut desired = self.desired_attrs.clone();
        desired.link = LinkTarget::Unlinked;
        self.for_each_verbatim_line(s, |w, _, line| w.write_open(line, &desired));
    }

    /// Writes verbatim text with TOML highlighting.
    fn verbatim_toml(&mut self, s: &str, palette: &Styles) {
        let lines: Vec<String> = s.split('\n').map(str::to_string).collect();
        let mut highlighter =
            from_extension("toml", 4).expect("synoptic provides a built-in toml highlighter");
        highlighter.run(&lines);

        self.for_each_verbatim_line(s, |w, i, line| {
            for token in highlighter.line(i, line) {
                match token {
                    TokOpt::Some(text, kind) => {
                        let desired = RunAttrs {
                            styles: StyleStack::from_slice(&[palette.toml_style(&kind)]),
                            link: LinkTarget::Unlinked,
                        };
                        w.write_open(&text, &desired);
                    }
                    TokOpt::None(text) => w.write_open(&text, &RunAttrs::default()),
                }
            }
        });
    }

    fn for_each_verbatim_line(
        &mut self,
        s: &str,
        mut write_line: impl FnMut(&mut Self, usize, &str),
    ) {
        let lines: Vec<&str> = s.split('\n').collect();
        let last = lines.len() - 1;
        for (i, &line) in lines.iter().enumerate() {
            if i != 0 {
                self.end_line();
            }
            if line.is_empty() {
                // If i is not the very last line, insert a line that the next
                // iteration will end (to insert a blank line). If i is the last
                // line, then don't append a trailing line.
                if i != last {
                    self.open_line();
                }
            } else {
                self.open_line();
                write_line(self, i, line);
            }
        }
    }

    fn hard_break(&mut self) {
        self.flush_word();
        self.end_line();
    }

    fn push_prefix(&mut self, prefix: &str) {
        self.prefix.push(prefix);
    }

    fn pop_prefix(&mut self) {
        self.prefix.pop();
    }

    fn set_item_marker(&mut self, marker: &str) {
        self.prefix.set_next_override(marker);
    }

    fn open_line(&mut self) {
        match &self.line {
            LineState::Open(_) => return,
            LineState::AtStart => {}
            LineState::AfterBlock { prefix } => {
                // Preserve the block-quote border across blank lines.
                if !self.out.is_empty() {
                    self.out.push_str(prefix.trim_end());
                    self.out.push('\n');
                }
            }
        }
        let prefix = self.prefix.take_next();
        self.out.push_str(&prefix);
        self.line = LineState::Open(OpenLine {
            column: display_width(&prefix),
            emitted: RunAttrs::default(),
        });
    }

    fn end_line(&mut self) {
        let LineState::Open(open) = &self.line else {
            return;
        };
        let reset = self.color && !open.emitted.styles.is_empty();
        let close_link = open.emitted.link.is_linked();
        // Drop trailing spaces so that blank and prefix-only lines don't carry
        // any whitespace. We use trim_end_matches rather than trim_end to avoid
        // eating newlines. If we used trim_end, we'd potentially end up
        // consuming the `\n` from the previous line.
        self.out.truncate(self.out.trim_end_matches(' ').len());
        if close_link {
            self.out.push_str("\x1b]8;;\x1b\\");
        }
        if reset {
            self.out.push_str(RESET_COLOR);
        }
        self.out.push('\n');
        self.line = LineState::AtStart;
    }

    fn end_block(&mut self) {
        self.end_line();
        self.line = LineState::AfterBlock {
            prefix: self.prefix.base(),
        };
    }

    /// Finishes the renderer, flushing any pending word and returning the
    /// accumulated output.
    fn finish(mut self) -> String {
        self.flush_word();
        self.end_line();
        self.out
    }
}

/// Diffs the currently-emitted stack of styles with the desired set of styles,
/// emitting the minimum number of style changes to match the target.
fn write_style_diff(emitted: &mut StyleStack, desired: &[Style], out: &mut String) {
    if emitted.as_slice() == desired {
        return;
    }
    let common = emitted.len();
    if desired.len() > common && &desired[..common] == emitted.as_slice() {
        for style in &desired[common..] {
            out.push_str(&style.prefix_formatter().to_string());
        }
    } else {
        if !emitted.is_empty() {
            out.push_str(RESET_COLOR);
        }
        for style in desired {
            out.push_str(&style.prefix_formatter().to_string());
        }
    }
    *emitted = StyleStack::from_slice(desired);
}

/// Syncs the current OSC 8 hyperlink with the desired link.
///
/// This is similar to `write_style_diff` above. The main purpose of this is to
/// prevent splitting hyperlinks on word boundaries.
fn sync_link(emitted: &mut LinkTarget, desired: &LinkTarget, out: &mut String) {
    if *emitted == *desired {
        return;
    }
    if emitted.is_linked() {
        out.push_str("\x1b]8;;\x1b\\");
    }
    if let LinkTarget::Linked(url) = desired {
        swrite!(out, "\x1b]8;;{url}\x1b\\");
    }
    *emitted = desired.clone();
}

struct Rendered {
    output: String,
    dropped: Vec<String>,
}

/// The current code block being rendered.
enum CodeBlockState {
    /// A code block without highlighting.
    Verbatim,
    /// A TOML code block.
    Toml { buffer: String },
}

fn render_markdown(
    markdown: &str,
    site_dir: &'static [&'static str],
    opts: RenderOptions,
) -> Rendered {
    let parser_options = Options::ENABLE_DEFINITION_LIST | Options::ENABLE_STRIKETHROUGH;
    let mut palette = Styles::default();
    if opts.color {
        palette.colorize();
    }
    let mut renderer = Renderer {
        writer: LineWriter::new(opts.color, opts.hyperlinks, opts.width),
        palette,
        site_dir,
        block: BlockContext::Normal(InlineContext::Normal),
        list_stack: Vec::new(),
        dropped: Vec::new(),
    };

    for event in Parser::new_ext(markdown, parser_options) {
        renderer.handle(event);
    }
    Rendered {
        output: renderer.writer.finish(),
        dropped: renderer.dropped,
    }
}

/// The current inline context the renderer is in.
#[derive(Clone, Copy)]
enum InlineContext {
    Normal,
    Term,
}

/// Block-level context for the renderer.
enum BlockContext {
    /// The normal block context, with no code block open.
    Normal(InlineContext),
    /// A code block is open.
    Code(CodeBlockState),
}

/// State maintained for a single open list.
struct ListFrame {
    /// The ordinal counter for ordered lists, or `None` for unordered lists.
    ordinal: Option<u64>,
}

/// A renderer that translates pulldown events into `LineWriter` operations.
struct Renderer {
    writer: LineWriter,
    palette: Styles,
    site_dir: &'static [&'static str],
    block: BlockContext,
    // The stack of open lists.
    list_stack: Vec<ListFrame>,
    dropped: Vec<String>,
}

impl Renderer {
    fn handle(&mut self, event: Event<'_>) {
        match event {
            Event::Start(Tag::Paragraph) => {}
            Event::End(TagEnd::Paragraph) => {
                self.writer.flush_word();
                self.writer.end_block();
            }

            Event::Start(Tag::Heading { .. }) => {
                self.writer.end_block();
                self.writer.push_style(self.palette.heading);
            }
            Event::End(TagEnd::Heading(_)) => {
                self.writer.flush_word();
                self.writer.pop_style();
                self.writer.end_block();
            }

            Event::Start(Tag::BlockQuote(_)) => self.writer.push_prefix(QUOTE_PREFIX),
            Event::End(TagEnd::BlockQuote(_)) => {
                self.writer.flush_word();
                self.writer.pop_prefix();
                self.writer.end_block();
            }

            Event::Start(Tag::CodeBlock(kind)) => {
                // Flush inline text buffered by a tight list item (e.g. `-
                // label:` before a fenced block), so the item marker stays on
                // the label, not the first code line.
                self.writer.flush_word();
                self.writer.end_line();
                self.writer.push_prefix(CODE_INDENT);
                self.block = BlockContext::Code(self.code_block_state_for(&kind));
                self.writer.push_style(self.palette.code);
            }
            Event::End(TagEnd::CodeBlock) => {
                // Reset the block context to normal, grabbing the TOML buffer
                // if it exists.
                if let BlockContext::Code(CodeBlockState::Toml { buffer }) =
                    std::mem::replace(&mut self.block, BlockContext::Normal(InlineContext::Normal))
                {
                    // (Note that non-TOML contexts were being rendered
                    // just-in-time, not buffered.)
                    self.writer.verbatim_toml(&buffer, &self.palette);
                }
                self.writer.pop_style();
                self.writer.pop_prefix();
                self.writer.end_block();
            }

            Event::Start(Tag::List(start)) => {
                self.list_stack.push(ListFrame { ordinal: start });
            }
            Event::End(TagEnd::List(_)) => {
                self.list_stack.pop();
                self.writer.end_block();
            }
            Event::Start(Tag::Item) => {
                // Flush any inline content buffered by the parent item before a
                // nested item starts. (This is relevant for tight nested lists
                // to avoid lines running into each other.)
                self.writer.flush_word();
                self.writer.end_line();
                let frame = self
                    .list_stack
                    .last_mut()
                    .expect("a list item is inside a list");
                let marker = match &mut frame.ordinal {
                    Some(index) => {
                        let marker = format!("{index}. ");
                        *index += 1;
                        marker
                    }
                    None => "- ".to_string(),
                };
                let indent = " ".repeat(display_width(&marker));
                self.writer.set_item_marker(&marker);
                self.writer.push_prefix(&indent);
            }
            Event::End(TagEnd::Item) => {
                self.writer.flush_word();
                self.writer.pop_prefix();
                self.writer.end_line();
            }

            Event::Start(Tag::DefinitionList) => {}
            Event::End(TagEnd::DefinitionList) => {}
            Event::Start(Tag::DefinitionListTitle) => {
                self.writer.end_block();
                self.writer.push_style(self.palette.term);
                self.block = BlockContext::Normal(InlineContext::Term);
            }
            Event::End(TagEnd::DefinitionListTitle) => {
                self.writer.flush_word();
                self.block = BlockContext::Normal(InlineContext::Normal);
                self.writer.pop_style();
                self.writer.end_line();
            }
            Event::Start(Tag::DefinitionListDefinition) => {
                self.writer.push_prefix(DEFINITION_INDENT);
            }
            Event::End(TagEnd::DefinitionListDefinition) => {
                self.writer.flush_word();
                self.writer.pop_prefix();
                self.writer.end_block();
            }

            Event::Start(Tag::Emphasis) => self.writer.push_style(self.palette.emphasis),
            Event::End(TagEnd::Emphasis) => self.writer.pop_style(),
            Event::Start(Tag::Strong) => self.writer.push_style(self.palette.strong),
            Event::End(TagEnd::Strong) => self.writer.pop_style(),
            Event::Start(Tag::Strikethrough) => self.writer.push_style(self.palette.strikethrough),
            Event::End(TagEnd::Strikethrough) => self.writer.pop_style(),

            Event::Start(Tag::Link { dest_url, .. }) => {
                // None means this is a same-page anchor -- drop it and render
                // text only.
                if let Some(url) = rewrite_url(&dest_url, self.site_dir) {
                    if self.writer.hyperlinks {
                        self.writer.push_style(self.palette.link);
                    }
                    self.writer.set_link(LinkTarget::Linked(url));
                }
            }
            Event::End(TagEnd::Link) => {
                // (None was a same-page anchor -- see Event::Start(Tag::Link {
                // .. }) above.)
                if let LinkTarget::Linked(url) = self.writer.take_link() {
                    if self.writer.hyperlinks {
                        self.writer.pop_style();
                    } else {
                        // The terminal doesn't support hyperlinks, so show the
                        // URL inline in the surrounding style.
                        self.writer.add_space();
                        self.writer.add_segment(&format!("<{url}>"));
                    }
                }
            }

            Event::Text(text) => match &mut self.block {
                BlockContext::Code(CodeBlockState::Toml { buffer }) => buffer.push_str(&text),
                BlockContext::Code(CodeBlockState::Verbatim) => self.writer.verbatim(&text),
                BlockContext::Normal(InlineContext::Normal | InlineContext::Term) => {
                    self.push_text(&text)
                }
            },
            Event::Code(code) => {
                match self.block {
                    BlockContext::Normal(InlineContext::Term) => {
                        // A definition term is already fully styled, so don't
                        // additionally style it with the code style. (Maybe we
                        // want to revisit this later?)
                        self.writer.add_segment(&code);
                    }
                    BlockContext::Normal(InlineContext::Normal) => {
                        self.writer.push_style(self.palette.code);
                        self.writer.add_segment(&code);
                        self.writer.pop_style();
                    }
                    BlockContext::Code(_) => {
                        unreachable!("inline code events cannot occur inside code blocks")
                    }
                }
            }
            Event::SoftBreak => self.writer.add_space(),
            Event::HardBreak => self.writer.hard_break(),

            // Ignore other events such as images, raw HTML, tables, footnotes,
            // etc. We may want to add support for these in the future, but
            // they're not necessary for the current set of things we render.
            other => self.dropped.push(format!("{other:?}")),
        }
    }

    /// Pushes text into the word buffer, splitting it into words and breakable
    /// spaces.
    fn push_text(&mut self, s: &str) {
        let mut run_start = 0;
        // A little state machine to track whether we're in a whitespace run.
        let mut run_is_ws: Option<bool> = None;
        for (i, c) in s.char_indices() {
            let ws = c.is_whitespace();
            match run_is_ws {
                None => {
                    run_is_ws = Some(ws);
                    run_start = i;
                }
                Some(prev) if prev == ws => {}
                Some(prev) => {
                    self.emit_run(&s[run_start..i], prev);
                    run_is_ws = Some(ws);
                    run_start = i;
                }
            }
        }
        if let Some(prev) = run_is_ws {
            self.emit_run(&s[run_start..], prev);
        }
    }

    fn emit_run(&mut self, run: &str, is_ws: bool) {
        if is_ws {
            self.writer.add_space();
        } else {
            self.writer.add_segment(run);
        }
    }

    fn code_block_state_for(&self, kind: &CodeBlockKind) -> CodeBlockState {
        if !self.writer.color {
            return CodeBlockState::Verbatim;
        }
        let CodeBlockKind::Fenced(info) = kind else {
            return CodeBlockState::Verbatim;
        };
        match info.split_whitespace().next() {
            Some("toml") => CodeBlockState::Toml {
                buffer: String::new(),
            },
            _ => CodeBlockState::Verbatim,
        }
    }
}

fn display_width(s: &str) -> usize {
    UnicodeWidthStr::width(s)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::core::NextestConfig;
    use nextest_filtering::FILTERSET_REFERENCE_MD;

    #[test]
    fn hyperlinks_gate_osc8() {
        let with = render(
            &HelpDoc::filterset(),
            RenderOptions {
                color: false,
                hyperlinks: true,
                width: 80,
            },
        );
        assert!(
            with.contains("\x1b]8;;https://nexte.st/"),
            "emits OSC-8 hyperlinks"
        );
        assert!(
            !with.contains("<https://nexte.st/"),
            "no inline URL fallback"
        );

        let without = render(
            &HelpDoc::filterset(),
            RenderOptions {
                color: false,
                hyperlinks: false,
                width: 80,
            },
        );
        assert!(!without.contains("\x1b]8;;"), "no OSC-8 when unsupported");
        assert!(
            without.contains("<https://nexte.st/"),
            "inline URL fallback"
        );
    }

    #[test]
    fn multi_word_link_is_one_continuous_hyperlink() {
        let doc = HelpDoc {
            markdown: "[click here](https://example.com/page) and more text\n".into(),
            site_dir: &[],
        };
        let rendered = render(
            &doc,
            RenderOptions {
                color: false,
                hyperlinks: true,
                width: 80,
            },
        );
        insta::assert_snapshot!(rendered);
    }

    #[test]
    fn wrapped_link_does_not_span_a_newline() {
        let doc = HelpDoc {
            markdown: "[alpha beta gamma](https://example.com/x)\n".into(),
            site_dir: &[],
        };
        let rendered = render(
            &doc,
            RenderOptions {
                color: false,
                hyperlinks: true,
                width: 12,
            },
        );
        insta::assert_snapshot!(rendered);
    }

    #[test]
    fn color_nested_styles() {
        let doc = HelpDoc {
            markdown: "**bold _and italic_** then `code`.\n".into(),
            site_dir: &[],
        };
        let rendered = render(
            &doc,
            RenderOptions {
                color: true,
                hyperlinks: false,
                width: 80,
            },
        );
        insta::assert_snapshot!(rendered);
    }

    #[test]
    fn ordered_list_indent_matches_marker_width() {
        let doc = HelpDoc {
            markdown: "1. aaaa bbbb cccc dddd eeee ffff gggg hhhh iiii\n".into(),
            site_dir: &[],
        };
        let rendered = render(
            &doc,
            RenderOptions {
                color: false,
                hyperlinks: false,
                width: 20,
            },
        );
        let lines: Vec<&str> = rendered.lines().collect();
        assert!(lines[0].starts_with("1. "), "first line: {:?}", lines[0]);
        for cont in &lines[1..] {
            assert!(
                cont.starts_with("   ") && !cont.starts_with("    "),
                "continuation indented to marker width (3): {cont:?}"
            );
        }
    }

    #[test]
    fn nested_list_preserves_outer_ordinal() {
        let doc = HelpDoc {
            markdown: "1. first\n2. second\n   - nested a\n   - nested b\n3. third\n".into(),
            site_dir: &[],
        };
        let rendered = render(
            &doc,
            RenderOptions {
                color: false,
                hyperlinks: false,
                width: 80,
            },
        );
        insta::assert_snapshot!(rendered);
    }

    #[test]
    fn code_block_preserves_blank_lines() {
        let doc = HelpDoc {
            markdown: "```\nfirst\n\nsecond\n```\n".into(),
            site_dir: &[],
        };
        let rendered = render(
            &doc,
            RenderOptions {
                color: false,
                hyperlinks: false,
                width: 80,
            },
        );
        assert!(
            rendered.contains("first\n\n") && rendered.contains("second"),
            "interior blank line preserved: {rendered:?}"
        );
    }

    #[test]
    fn list_item_label_before_code_block_keeps_marker_on_label() {
        let doc = HelpDoc {
            markdown: "- **Examples**:\n  ```\n  retries = 3\n  ```\n".into(),
            site_dir: &[],
        };
        let rendered = render(
            &doc,
            RenderOptions {
                color: false,
                hyperlinks: false,
                width: 80,
            },
        );
        insta::assert_snapshot!(rendered);
    }

    #[test]
    fn blockquote_code_block_blank_line_keeps_border() {
        let doc = HelpDoc {
            markdown: "> ```\n> a\n>\n> b\n> ```\n".into(),
            site_dir: &[],
        };
        let rendered = render(
            &doc,
            RenderOptions {
                color: false,
                hyperlinks: false,
                width: 80,
            },
        );
        insta::assert_snapshot!(rendered);
    }

    #[test]
    fn admonition_with_unicode_indent_does_not_panic() {
        let doc = HelpDoc {
            markdown: "!!! note\n   \u{a0}body text\n".into(),
            site_dir: &[],
        };
        let _ = render(
            &doc,
            RenderOptions {
                color: false,
                hyperlinks: false,
                width: 80,
            },
        );
    }

    #[test]
    fn rewrite_url_resolves_relative_links() {
        let site_dir = HelpDoc::filterset().site_dir;
        assert_eq!(
            rewrite_url("https://example.com/x", site_dir).as_deref(),
            Some("https://example.com/x"),
        );
        assert_eq!(
            rewrite_url("http://example.com/x", site_dir).as_deref(),
            Some("http://example.com/x"),
        );
        assert_eq!(rewrite_url("#binary-kinds", site_dir), None);
        assert_eq!(
            rewrite_url("../glossary.md#binary-id", site_dir).as_deref(),
            Some("https://nexte.st/docs/glossary/#binary-id"),
        );
        assert_eq!(
            rewrite_url("../configuration/test-groups.md", site_dir).as_deref(),
            Some("https://nexte.st/docs/configuration/test-groups/"),
        );
        assert_eq!(
            rewrite_url("../selecting.md", site_dir).as_deref(),
            Some("https://nexte.st/docs/selecting/"),
        );

        // index.md resolves to the corresponding directory URL.
        let config_dir: &[&str] = &["docs", "configuration"];
        assert_eq!(
            rewrite_url("index.md", config_dir).as_deref(),
            Some("https://nexte.st/docs/configuration/"),
        );
        assert_eq!(
            rewrite_url("index.md#hierarchical-configuration", config_dir).as_deref(),
            Some("https://nexte.st/docs/configuration/#hierarchical-configuration"),
        );
        assert_eq!(
            rewrite_url("../user-config/index.md", config_dir).as_deref(),
            Some("https://nexte.st/docs/user-config/"),
        );
        assert_eq!(
            rewrite_url("../filtersets/index.md", config_dir).as_deref(),
            Some("https://nexte.st/docs/filtersets/"),
        );
    }

    #[test]
    #[should_panic(expected = "relative link in help doc escapes the site root")]
    fn rewrite_url_panics_on_escaping_links() {
        let site_dir = HelpDoc::filterset().site_dir;
        rewrite_url("../../../../foo.md", site_dir);
    }

    #[test]
    fn apply_shortcodes_handles_versions_and_comments() {
        assert_eq!(
            apply_shortcodes("a <!-- md:version 0.9.1 --> b"),
            "a *(since 0.9.1)* b",
        );
        assert_eq!(apply_shortcodes("a <!-- md:version --> b"), "a  b");
        assert_eq!(apply_shortcodes("a <!-- md:versionfoo --> b"), "a  b");
        assert_eq!(apply_shortcodes("a <!-- random comment --> b"), "a  b");
        assert_eq!(
            apply_shortcodes("a <!-- unterminated"),
            "a <!-- unterminated"
        );
    }

    #[test]
    fn reference_stays_within_supported_subset() {
        let markdown = FILTERSET_REFERENCE_MD;

        let mut rest = markdown;
        while let Some(idx) = rest.find("<!-- md:") {
            let after = &rest[idx + "<!-- md:".len()..];
            let name: String = after
                .chars()
                .take_while(|c| c.is_alphanumeric() || *c == '_')
                .collect();
            assert_eq!(
                name, "version",
                "unsupported `md:{name}` shortcode in the filterset reference; \
                 the CLI help renderer only handles `md:version` (see apply_shortcodes)"
            );
            rest = after;
        }

        let preprocessed = preprocess(markdown);
        let rendered = render_markdown(
            &preprocessed,
            HelpDoc::filterset().site_dir,
            RenderOptions {
                color: false,
                hyperlinks: false,
                width: 80,
            },
        );
        assert!(
            rendered.dropped.is_empty(),
            "filterset reference uses markdown the CLI help renderer silently drops: {:?}",
            rendered.dropped,
        );
    }

    #[test]
    fn repo_config_reference_stays_within_supported_subset() {
        let markdown = NextestConfig::REFERENCE_MD;

        let mut rest = markdown;
        while let Some(idx) = rest.find("<!-- md:") {
            let after = &rest[idx + "<!-- md:".len()..];
            let name: String = after
                .chars()
                .take_while(|c| c.is_alphanumeric() || *c == '_')
                .collect();
            assert_eq!(
                name, "version",
                "unsupported `md:{name}` shortcode in the repo-config reference; \
                 the CLI help renderer only handles `md:version` (see apply_shortcodes)"
            );
            rest = after;
        }

        let preprocessed = preprocess(markdown);
        let rendered = render_markdown(
            &preprocessed,
            &["docs", "configuration"],
            RenderOptions {
                color: false,
                hyperlinks: false,
                width: 80,
            },
        );
        assert!(
            rendered.dropped.is_empty(),
            "repo-config reference uses markdown the CLI help renderer silently drops: {:?}",
            rendered.dropped,
        );
    }

    #[test]
    fn repo_config_markdown_includes_reference_and_defaults() {
        let markdown = repo_config_markdown();
        assert!(
            markdown.contains("# Configuration reference"),
            "repo-config topic includes the reference body"
        );
        assert!(
            markdown.contains("## Default configuration"),
            "repo-config topic appends a default configuration section"
        );
        assert!(
            markdown.contains(NextestConfig::DEFAULT_CONFIG.trim_end()),
            "repo-config topic embeds the default config verbatim"
        );
    }

    #[test]
    fn user_config_reference_stays_within_supported_subset() {
        let markdown = UserConfig::REFERENCE_MD;

        let mut rest = markdown;
        while let Some(idx) = rest.find("<!-- md:") {
            let after = &rest[idx + "<!-- md:".len()..];
            let name: String = after
                .chars()
                .take_while(|c| c.is_alphanumeric() || *c == '_')
                .collect();
            assert_eq!(
                name, "version",
                "unsupported `md:{name}` shortcode in the user-config reference; \
                 the CLI help renderer only handles `md:version` (see apply_shortcodes)"
            );
            rest = after;
        }

        let preprocessed = preprocess(&user_config_markdown());
        let rendered = render_markdown(
            &preprocessed,
            &["docs", "user-config"],
            RenderOptions {
                color: false,
                hyperlinks: false,
                width: 80,
            },
        );
        assert!(
            rendered.dropped.is_empty(),
            "user-config reference uses markdown the CLI help renderer silently drops: {:?}",
            rendered.dropped,
        );
    }

    #[test]
    fn user_config_markdown_includes_reference_and_defaults() {
        let markdown = user_config_markdown();
        assert!(
            markdown.contains("# User config reference"),
            "user-config topic includes the reference body"
        );
        assert!(
            markdown.contains("## Default configuration"),
            "user-config topic appends a default configuration section"
        );
        assert!(
            markdown.contains(UserConfig::DEFAULT_CONFIG.trim_end()),
            "user-config topic embeds the default config verbatim"
        );
    }

    #[test]
    fn toml_code_block_is_highlighted() {
        let doc = HelpDoc {
            markdown: "```toml\n[profile.ci]\n# run all tests\nfail-fast = false\nretries = 3\nslow-timeout = \"60s\"\n```\n".into(),
            site_dir: &[],
        };
        let colored = render(
            &doc,
            RenderOptions {
                color: true,
                hyperlinks: false,
                width: 80,
            },
        );
        insta::assert_snapshot!("toml_highlight_color", colored);

        let plain = render(
            &doc,
            RenderOptions {
                color: false,
                hyperlinks: false,
                width: 80,
            },
        );
        assert!(
            !plain.contains('\x1b'),
            "a toml block emits no ANSI when color is off: {plain:?}"
        );
    }
}