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
use std::borrow::Cow;
use pulldown_cmark::{CodeBlockKind, CowStr, Event, Tag, TagEnd};
pub(super) fn convert<'a, 'b>(
events: impl IntoIterator<Item = Event<'a>> + 'b,
) -> impl Iterator<Item = Event<'a>> + 'b {
let mut in_codeblock = None;
events.into_iter().map(move |mut event| {
if let Some(is_rust) = in_codeblock {
match &mut event {
Event::Text(text) => {
if !text.ends_with('\n') {
// workaround for https://github.com/Byron/pulldown-cmark-to-cmark/issues/48
*text = format!("{text}\n").into();
}
if is_rust {
// Hide lines starting with any number of whitespace
// followed by `# ` (comments), or just `#`. But `## `
// should be converted to `# `.
*text = text
.lines()
.filter_map(|line| {
// Adapted from
// https://github.com/rust-lang/rust/blob/942db6782f4a28c55b0b75b38fd4394d0483390f/src/librustdoc/html/markdown.rs#L169-L182.
let trimmed = line.trim();
if trimmed.starts_with("##") {
// It would be nice to reuse
// `pulldown_cmark::CowStr` here, but (at
// least as of version 0.12.2) it doesn't
// support collecting into a `String`.
Some(Cow::Owned(line.replacen("##", "#", 1)))
} else if trimmed.starts_with("# ") {
// Hidden line.
None
} else if trimmed == "#" {
// A plain # is a hidden line.
None
} else {
Some(Cow::Borrowed(line))
}
})
.flat_map(|line| [line, Cow::Borrowed("\n")])
.collect::<String>()
.into();
}
}
Event::End(TagEnd::CodeBlock) => {}
_ => unreachable!(),
}
}
match &mut event {
Event::Start(Tag::CodeBlock(kind)) => {
let is_rust;
match kind {
CodeBlockKind::Indented => {
is_rust = true;
*kind = CodeBlockKind::Fenced("rust".into());
}
CodeBlockKind::Fenced(tag) => {
is_rust = update_codeblock_tag(tag);
}
}
assert!(in_codeblock.is_none());
in_codeblock = Some(is_rust);
}
Event::End(TagEnd::CodeBlock) => {
assert!(in_codeblock.is_some());
in_codeblock = None;
}
_ => {}
}
event
})
}
fn is_attribute_tag(tag: &str) -> bool {
// https://doc.rust-lang.org/rustdoc/write-documentation/documentation-tests.html#attributes
// to support future rust edition, `edition\d{4}` treated as attribute tag
matches!(
tag,
"" | "ignore" | "should_panic" | "no_run" | "compile_fail"
) || tag
.strip_prefix("edition")
.is_some_and(|x| x.len() == 4 && x.chars().all(|ch| ch.is_ascii_digit()))
}
fn update_codeblock_tag(tag: &mut CowStr<'_>) -> bool {
let mut tag_count = 0;
let is_rust = tag
.split(',')
.filter(|tag| !is_attribute_tag(tag))
.all(|tag| {
tag_count += 1;
tag == "rust"
});
if is_rust && tag_count == 0 {
if tag.is_empty() {
*tag = "rust".into();
} else {
*tag = format!("rust,{tag}").into();
}
}
is_rust
}
#[cfg(test)]
mod tests {
use indoc::indoc;
#[test]
fn update_codeblock_tag() {
fn check(tag: &str, expected_tag: &str, expected_is_rust: bool) {
let mut tag = tag.into();
let is_rust = super::update_codeblock_tag(&mut tag);
assert_eq!(tag.as_ref(), expected_tag);
assert_eq!(is_rust, expected_is_rust);
}
check("", "rust", true);
check("typescript", "typescript", false);
check("rust", "rust", true);
check("ignore", "rust,ignore", true);
check("ignore,rust", "ignore,rust", true);
check("ignore,typescript", "ignore,typescript", false);
check(
"ignore,should_panic,no_run,compile_fail,edition2015,edition2018,edition2021",
"rust,ignore,should_panic,no_run,compile_fail,edition2015,edition2018,edition2021",
true,
);
check("edition9999", "rust,edition9999", true);
check("edition99999", "edition99999", false);
check("editionabcd", "editionabcd", false);
}
#[test]
fn hide_codeblock_line() {
let input = indoc! {r"
Lorem ipsum
```rust
# This line and the next should be hidden, but the following should not.
#
#[derive(Debug)]
struct Foo;
fn main() {
# As should this and the next line.
#
#But not this.
## This should become a single #.
##And this.
}
```
```toml
# This is not Rust so it should not be hidden.
```
"};
let expected = indoc! {r"
Lorem ipsum
````rust
#[derive(Debug)]
struct Foo;
fn main() {
#But not this.
# This should become a single #.
#And this.
}
````
````toml
# This is not Rust so it should not be hidden.
````"};
let events: Vec<_> = pulldown_cmark::Parser::new(input).collect();
let events: Vec<_> = super::convert(events).collect();
let mut output = String::new();
pulldown_cmark_to_cmark::cmark(events.into_iter(), &mut output).unwrap();
assert_eq!(output, expected, "output matches expected");
}
}