forked from SpaceManiac/SpacemanDMM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmarkdown.rs
163 lines (140 loc) · 4.77 KB
/
markdown.rs
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
//! Parser for "doc-block" markdown documents.
use std::ops::Range;
use std::collections::VecDeque;
use pulldown_cmark::{self, Parser, Tag, Event};
pub type BrokenLinkCallback<'a> = Option<&'a dyn Fn(&str, &str) -> Option<(String, String)>>;
pub fn render(markdown: &str, broken_link_callback: BrokenLinkCallback) -> String {
let mut buf = String::new();
push_html(&mut buf, parser(markdown, broken_link_callback));
buf
}
/// A rendered markdown document with the teaser identified.
#[derive(Serialize)]
pub struct DocBlock {
pub html: String,
pub has_description: bool,
teaser: Range<usize>,
}
impl DocBlock {
pub fn parse(markdown: &str, broken_link_callback: BrokenLinkCallback) -> Self {
parse_main(parser(markdown, broken_link_callback).peekable())
}
pub fn parse_with_title(markdown: &str, broken_link_callback: BrokenLinkCallback) -> (Option<String>, Self) {
let mut parser = parser(markdown, broken_link_callback).peekable();
(
if let Some(&Event::Start(Tag::Heading(1))) = parser.peek() {
parser.next();
let mut pieces = Vec::new();
loop {
match parser.next() {
None | Some(Event::End(Tag::Heading(1))) => break,
Some(other) => pieces.push(other),
}
}
let mut title = String::new();
push_html(&mut title, pieces);
Some(title)
} else {
None
},
parse_main(parser),
)
}
pub fn teaser(&self) -> &str {
&self.html[self.teaser.clone()]
}
}
fn parser<'a>(markdown: &'a str, broken_link_callback: BrokenLinkCallback<'a>) -> Parser<'a> {
Parser::new_with_broken_link_callback(
markdown,
pulldown_cmark::Options::ENABLE_TABLES | pulldown_cmark::Options::ENABLE_STRIKETHROUGH,
broken_link_callback
)
}
fn parse_main(mut parser: std::iter::Peekable<Parser>) -> DocBlock {
let mut html = String::new();
let teaser;
if let Some(&Event::Start(Tag::Paragraph)) = parser.peek() {
push_html(&mut html, parser.next());
let start = html.len();
let mut pieces = Vec::new();
loop {
match parser.next() {
None | Some(Event::End(Tag::Paragraph)) => break,
Some(other) => pieces.push(other),
}
}
push_html(&mut html, pieces);
teaser = start..html.len();
push_html(&mut html, Some(Event::End(Tag::Paragraph)));
} else {
teaser = 0..0;
}
let has_description = parser.peek().is_some();
push_html(&mut html, parser);
trim_right(&mut html);
DocBlock { html, teaser, has_description }
}
fn push_html<'a, I: IntoIterator<Item=Event<'a>>>(buf: &mut String, iter: I) {
pulldown_cmark::html::push_html(buf, HeadingLinker {
inner: iter.into_iter(),
output: Default::default(),
});
}
fn trim_right(buf: &mut String) {
let len = buf.trim_end().len();
buf.truncate(len);
}
/// Iterator adapter which replaces Start(Heading) tags with HTML including
/// an anchor.
struct HeadingLinker<'a, I> {
inner: I,
output: VecDeque<Event<'a>>,
}
impl<'a, I: Iterator<Item=Event<'a>>> Iterator for HeadingLinker<'a, I> {
type Item = Event<'a>;
fn next(&mut self) -> Option<Event<'a>> {
if let Some(output) = self.output.pop_front() {
return Some(output);
}
let original = self.inner.next();
if let Some(Event::Start(Tag::Heading(heading))) = original {
let mut text_buf = String::new();
while let Some(event) = self.inner.next() {
if let Event::Text(ref text) = event {
text_buf.push_str(text.as_ref());
}
if let Event::End(Tag::Heading(_)) = event {
break;
}
self.output.push_back(event);
}
self.output.push_back(Event::Html(format!("</h{}>", heading).into()));
return Some(Event::Html(format!("<h{} id=\"{}\">", heading, slugify(&text_buf)).into()));
}
original
}
}
fn slugify(input: &str) -> String {
let mut output = String::new();
let mut want_dash = false;
for ch in input.chars() {
if ch == '\'' {
continue;
}
for ch in ch.to_lowercase() {
if !ch.is_alphanumeric() {
if want_dash {
output.push('-');
want_dash = false;
}
} else {
output.push(ch);
want_dash = true;
}
}
}
let len = output.trim_end_matches('-').len();
output.truncate(len);
output
}