Skip to content

Commit 3d184fb

Browse files
committed
Add a separate mode to parse footnotes the same way GitHub does
Resolves #20 Resolves #530 Resolves #623 This change is similar to, but a more limited change than, <#544>. It changes the syntax, but does not touch the generated HTML or event API. Motivation ---------- This commit is written with usage in mdBook, rustdoc, and docs.rs in mind. * Having a standard to follow, or at least a public test suite in [cmark-gfm] [^c], makes it easier to distinguish bugs from features. * It makes sense to commit to following GitHub's behavior specifically, because mdBook chapters and docs.rs README files are often viewed in GitHub preview windows, so any divergence will be very annoying. * If mdBook and docs.rs are going to use this syntax, then rustdoc should, too. * Having both footnote syntaxes use the same API and rendering makes it more feasible for rustdoc to change the syntax over an [edition]. To introduce a syntax change in a new edition of Rust, we must make rustdoc warn anyone who writes code that will have its meaning change. To do it, run the parser twice in lockstep (with `ENABLE_FOOTNOTES` on one parser, and `ENABLE_GFM_FOOTNOTES` on the other), and warn if they diverge. * Alternatively, run a Crater build with this same code to check if this actually causes widespread breakage. * In particular, using tree rewriting to push the footnotes to the end is not as useful as it sounds, since that's not enough to exactly copy the way GitHub renders footnotes. To do that, you also need to sort the footnotes by the order in which they are *referenced*, not the order in which they are defined. This type of tree rewriting is also a waste of time if you want "margin note" rendering instead of putting them all at the end. [cmark-gfm]: https://github.com/github/cmark-gfm/blob/1e230827a584ebc9938c3eadc5059c55ef3c9abf/test/extensions.txt#L702 [edition]: https://doc.rust-lang.org/edition-guide/editions/index.html [^c]: cmark-gfm is under the MIT license, so incorporating parts of its test suite into pulldown-cmark should be fine.
1 parent 4921c42 commit 3d184fb

21 files changed

Lines changed: 2073 additions & 867 deletions

‎build.rs‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ fn generate_tests_from_spec() {
6464

6565
let spec_name = file_path.file_stem().unwrap().to_str().unwrap();
6666

67-
let spec = Spec::new(&raw_spec);
67+
let spec = Spec::new(&raw_spec, spec_name.starts_with("gfm_"));
6868
let mut n_tests = 0;
6969

7070
spec_rs
@@ -86,7 +86,7 @@ fn {}_test_{i}() {{
8686
let original = r##"{original}"##;
8787
let expected = r##"{expected}"##;
8888
89-
test_markdown_html(original, expected, {smart_punct}, {metadata_blocks});
89+
test_markdown_html(original, expected, {smart_punct}, {metadata_blocks}, {is_gfm});
9090
}}
9191
"###,
9292
spec_name,
@@ -95,6 +95,7 @@ fn {}_test_{i}() {{
9595
expected = testcase.expected,
9696
smart_punct = testcase.smart_punct,
9797
metadata_blocks = testcase.metadata_blocks,
98+
is_gfm = testcase.is_gfm,
9899
))
99100
.unwrap();
100101

@@ -134,12 +135,13 @@ fn {}_test_{i}() {{
134135
#[cfg(feature = "gen-tests")]
135136
pub struct Spec<'a> {
136137
spec: &'a str,
138+
is_gfm: bool,
137139
}
138140

139141
#[cfg(feature = "gen-tests")]
140142
impl<'a> Spec<'a> {
141-
pub fn new(spec: &'a str) -> Self {
142-
Spec { spec }
143+
pub fn new(spec: &'a str, is_gfm: bool) -> Self {
144+
Spec { spec, is_gfm }
143145
}
144146
}
145147

@@ -149,6 +151,7 @@ pub struct TestCase {
149151
pub expected: String,
150152
pub smart_punct: bool,
151153
pub metadata_blocks: bool,
154+
pub is_gfm: bool,
152155
}
153156

154157
#[cfg(feature = "gen-tests")]
@@ -190,6 +193,7 @@ impl<'a> Iterator for Spec<'a> {
190193
let test_case = TestCase {
191194
original: spec[i_start..i_end].to_string().replace("→", "\t"),
192195
expected: spec[i_end + 2..e_end].to_string().replace("→", "\t"),
196+
is_gfm: self.is_gfm,
193197
smart_punct,
194198
metadata_blocks,
195199
};

‎examples/footnote-rewrite.rs‎

Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
use std::io::Write as _;
2+
use std::fmt::Write as _;
3+
use std::collections::HashMap;
4+
5+
use pulldown_cmark::{html, Event, Options, Parser, Tag, TagEnd, CowStr};
6+
7+
/// This example shows how to do footnotes as bottom-notes, in the style of GitHub.
8+
fn main() {
9+
let markdown_input: &str = "This is an [^a] footnote [^a].\n\n[^a]: footnote contents";
10+
println!("Parsing the following markdown string:\n{}", markdown_input);
11+
12+
// To generate this style, you have to collect the footnotes at the end, while parsing.
13+
// You also need to count usages.
14+
let mut footnotes = Vec::new();
15+
let mut in_footnote = Vec::new();
16+
let mut footnote_numbers = HashMap::new();
17+
// ENABLE_GFM_FOOTNOTES is used in this example, but ENABLE_FOOTNOTES would work, too.
18+
let parser = Parser::new_ext(markdown_input, Options::ENABLE_GFM_FOOTNOTES)
19+
.filter_map(|event| {
20+
match event {
21+
Event::Start(Tag::FootnoteDefinition(_)) => {
22+
in_footnote.push(vec![event]);
23+
None
24+
}
25+
Event::End(TagEnd::FootnoteDefinition) => {
26+
let mut f = in_footnote.pop().unwrap();
27+
f.push(event);
28+
footnotes.push(f);
29+
None
30+
}
31+
Event::FootnoteReference(name) => {
32+
let n = footnote_numbers.len() + 1;
33+
let (n, nr) = footnote_numbers.entry(name.clone()).or_insert((n, 0usize));
34+
*nr += 1;
35+
let html = Event::Html(format!(r##"<sup class="footnote-reference" id="fr-{name}-{nr}"><a href="#fn-{name}">[{n}]</a></sup>"##).into());
36+
if in_footnote.len() == 0 {
37+
Some(html)
38+
} else {
39+
in_footnote.last_mut().unwrap().push(html);
40+
None
41+
}
42+
}
43+
_ if in_footnote.len() != 0 => {
44+
in_footnote.last_mut().unwrap().push(event);
45+
None
46+
}
47+
_ => Some(event),
48+
}
49+
});
50+
51+
// Write to anything implementing the `Write` trait. This could also be a file
52+
// or network socket.
53+
let stdout = std::io::stdout();
54+
let mut handle = stdout.lock();
55+
handle.write_all(b"\nHTML output:\n").unwrap();
56+
html::write_html(&mut handle, parser).unwrap();
57+
58+
// To make the footnotes look right, we need to sort them by their appearance order, not by
59+
// the in-tree order of their actual definitions. Unused items are omitted entirely.
60+
//
61+
// For example, this code:
62+
//
63+
// test [^1] [^2]
64+
// [^2]: second used, first defined
65+
// [^1]: test
66+
//
67+
// Gets rendered like *this* if you copy it into a GitHub comment box:
68+
//
69+
// <p>test <sup>[1]</sup> <sup>[2]</sup></p>
70+
// <hr>
71+
// <ol>
72+
// <li>test ↩</li>
73+
// <li>second used, first defined ↩</li>
74+
// </ol>
75+
if footnotes.len() != 0 {
76+
footnotes.retain(|f| match f.first() {
77+
Some(Event::Start(Tag::FootnoteDefinition(name))) => footnote_numbers.get(name).unwrap_or(&(0, 0)).1 != 0,
78+
_ => false,
79+
});
80+
footnotes.sort_by_cached_key(|f| match f.first() {
81+
Some(Event::Start(Tag::FootnoteDefinition(name))) => footnote_numbers.get(name).unwrap_or(&(0, 0)).0,
82+
_ => unreachable!(),
83+
});
84+
handle.write_all(b"<hr><ol class=\"footnotes-list\">\n").unwrap();
85+
html::write_html(&mut handle, footnotes.into_iter().flat_map(|fl| {
86+
// To write backrefs, the name needs kept until the end of the footnote definition.
87+
let mut name = CowStr::from("");
88+
// Backrefs are included in the final paragraph of the footnote, if it's normal text.
89+
// For example, this DOM can be produced:
90+
//
91+
// Markdown:
92+
//
93+
// five [^feet].
94+
//
95+
// [^feet]:
96+
// A foot is defined, in this case, as 0.3048 m.
97+
//
98+
// Historically, the foot has not been defined this way, corresponding to many
99+
// subtly different units depending on the location.
100+
//
101+
// HTML:
102+
//
103+
// <p>five <sup class="footnote-reference" id="fr-feet-1"><a href="#fn-feet">[1]</a></sup>.</p>
104+
//
105+
// <ol class="footnotes-list">
106+
// <li id="fn-feet">
107+
// <p>A foot is defined, in this case, as 0.3048 m.</p>
108+
// <p>Historically, the foot has not been defined this way, corresponding to many
109+
// subtly different units depending on the location. <a href="#fr-feet-1">↩</a></p>
110+
// </li>
111+
// </ol>
112+
//
113+
// This is mostly a visual hack, so that footnotes use less vertical space.
114+
//
115+
// If there is no final paragraph, such as a tabular, list, or image footnote, it gets
116+
// pushed after the last tag instead.
117+
let mut has_written_backrefs = false;
118+
let fl_len = fl.len();
119+
let footnote_numbers = &footnote_numbers;
120+
fl.into_iter().enumerate().map(move |(i, f)| {
121+
match f {
122+
Event::Start(Tag::FootnoteDefinition(current_name)) => {
123+
name = current_name;
124+
has_written_backrefs = false;
125+
Event::Html(format!(r##"<li id="fn-{name}">"##).into())
126+
}
127+
Event::End(TagEnd::FootnoteDefinition) | Event::End(TagEnd::Paragraph) if !has_written_backrefs && i >= fl_len - 2 => {
128+
let usage_count = footnote_numbers.get(&name).unwrap().1;
129+
let mut end = String::with_capacity(name.len() + (r##" <a href="#fr--1">↩</a></li>"##.len() * usage_count));
130+
for usage in 1 ..= usage_count {
131+
if usage == 1 {
132+
write!(&mut end, r##" <a href="#fr-{name}-{usage}">↩</a>"##).unwrap();
133+
} else {
134+
write!(&mut end, r##" <a href="#fr-{name}-{usage}">↩{usage}</a>"##).unwrap();
135+
}
136+
}
137+
has_written_backrefs = true;
138+
if f == Event::End(TagEnd::FootnoteDefinition) {
139+
end.push_str("</li>\n");
140+
} else {
141+
end.push_str("</p>\n");
142+
}
143+
Event::Html(end.into())
144+
}
145+
Event::End(TagEnd::FootnoteDefinition) => Event::Html("</li>\n".into()),
146+
Event::FootnoteReference(_) => unreachable!("converted to HTML earlier"),
147+
f => f,
148+
}
149+
})
150+
})).unwrap();
151+
handle.write_all(b"</ol>\n").unwrap();
152+
}
153+
}

‎specs/footnotes.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
Run this with `cargo run -- -F -s specs/footnotes.txt`.
1+
Run this with `cargo test --features gen-tests suite::footnotes`.
22

33
This is how footnotes are basically used.
44

0 commit comments

Comments
 (0)