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
#[cfg(test)]
mod tests;
use super::{Callbacks, Method, Property, Resolver};
use pulldown_cmark::{Alignment, CodeBlockKind, Event, LinkType, Tag};
use std::collections::HashMap;
#[derive(Clone, Copy, PartialEq)]
enum Nesting {
/// Tracks the index of the current list
ListLevel(Option<u64>),
/// Member of a list item
ListItem,
/// Quoted text: `"> "`
Quote,
/// Indented code: add 4 spaces
IndentedCode,
}
/// Implementation of [`Callbacks`] for markdown.
#[derive(Default)]
pub(crate) struct MarkdownCallbacks {
/// The same name can be used for multiple shortcut links, because they
/// are not all defined in the same place.
///
/// So we keep them all, and disambiguate via `name`, `name-1`,
/// `name-2`, ...
links: HashMap<String, Vec<String>>,
/// Shortcut link whose name we are currently building
shortcut_link: Option<String>,
/// Stack of tables alignment
tables_alignements: Vec<Vec<Alignment>>,
/// Information for indentation
nesting: Vec<Nesting>,
/// Have we written to the string since we last pushed to `nesting` ?
top_written: bool,
}
impl Callbacks for MarkdownCallbacks {
fn extension(&self) -> &'static str {
"md"
}
fn start_method(&mut self, s: &mut String, resolver: &Resolver, method: &Method) {
(self as &mut dyn Callbacks).start_method_default(s, resolver, method)
}
fn start_property(&mut self, s: &mut String, resolver: &Resolver, property: &Property) {
(self as &mut dyn Callbacks).start_property_default(s, resolver, property)
}
fn encode(&mut self, s: &mut String, events: Vec<Event<'_>>) {
for event in events {
match event {
Event::Start(tag) => match tag {
Tag::Paragraph => {
self.apply_nesting(s);
if self.top_written {
self.apply_nesting(s)
}
}
Tag::Heading(level) => {
self.apply_nesting(s);
self.top_written = true;
for _ in 0..level {
s.push('#');
}
s.push(' ');
}
Tag::BlockQuote => self.nesting.push(Nesting::Quote),
Tag::CodeBlock(kind) => match kind {
CodeBlockKind::Indented => {
self.apply_nesting(s);
trim(s);
self.nesting.push(Nesting::IndentedCode);
self.apply_nesting(s);
}
CodeBlockKind::Fenced(lang) => {
self.apply_nesting(s);
self.top_written = true;
s.push_str("```");
s.push_str(&lang);
self.apply_nesting(s);
}
},
Tag::List(level) => self.nesting.push(Nesting::ListLevel(level)),
Tag::Item => {
self.apply_nesting(s);
self.start_new_item(s);
self.nesting.push(Nesting::ListItem);
self.top_written = false;
}
Tag::FootnoteDefinition(_) => {
log::warn!("FootnoteDefinition: Unsupported at the moment")
}
Tag::Table(alignment) => {
self.tables_alignements.push(alignment);
}
Tag::TableHead => self.apply_nesting(s),
Tag::TableRow => self.apply_nesting(s),
Tag::TableCell => s.push_str("| "),
Tag::Emphasis => s.push('*'),
Tag::Strong => s.push_str("**"),
Tag::Strikethrough => s.push_str("~~"),
Tag::Link(link_type, _, _) => {
if link_type == LinkType::Shortcut {
if self.shortcut_link.is_some() {
log::error!("Links are not supposed to be nested")
}
self.shortcut_link = Some("".to_string());
}
s.push('[')
}
Tag::Image(_, dest, title) => {
s.push_str(";
s.push_str(&dest);
if !title.is_empty() {
s.push_str(" \"");
s.push_str(&title);
s.push('"');
}
s.push(')');
}
},
Event::End(tag) => match tag {
Tag::Paragraph => {}
Tag::Heading(_) => {}
Tag::BlockQuote => {
self.nesting.pop();
}
Tag::CodeBlock(kind) => match kind {
CodeBlockKind::Indented => {
self.nesting.pop();
}
CodeBlockKind::Fenced(_) => {
trim(s);
self.apply_nesting(s);
s.push_str("```");
}
},
Tag::List(_) => {
self.nesting.pop();
}
Tag::Item => {
self.nesting.pop();
}
Tag::FootnoteDefinition(_) => {}
Tag::Table(_) => s.push('\n'),
Tag::TableHead => {
if let Some(alignement) = self.tables_alignements.pop() {
self.apply_nesting(s);
for align in alignement {
s.push_str("| ");
match align {
Alignment::None => s.push_str("--- "),
Alignment::Left => s.push_str(":--- "),
Alignment::Center => s.push_str(":---: "),
Alignment::Right => s.push_str("---: "),
}
}
}
}
Tag::TableRow => {}
Tag::TableCell => {}
Tag::Emphasis => s.push('*'),
Tag::Strong => s.push_str("**"),
Tag::Strikethrough => s.push_str("~~"),
Tag::Link(link_type, dest, title) => {
s.push(']');
let closing_character = match link_type {
LinkType::Shortcut => {
if let Some(shortcut) = self.shortcut_link.take() {
self.add_shortcut_link(shortcut, &dest);
}
None
}
_ => {
s.push('(');
s.push_str(&dest);
Some(')')
}
};
if !title.is_empty() {
s.push_str(" \"");
s.push_str(&title);
s.push('"');
}
if let Some(closing) = closing_character {
s.push(closing);
}
}
Tag::Image(_, _, _) => {}
},
Event::Text(text) => {
self.top_written = true;
self.push_str(s, &text)
}
Event::Code(code) => {
self.top_written = true;
self.push_str(s, "`");
self.push_str(s, &code);
self.push_str(s, "`");
}
Event::Html(html) => {
self.top_written = true;
s.push_str(&html)
}
Event::FootnoteReference(_) => {
log::warn!("FootnoteReference: Unsupported at the moment")
}
Event::SoftBreak => self.apply_nesting(s),
Event::HardBreak => {
s.push_str(" \\");
self.apply_nesting(s)
}
Event::Rule => {
self.apply_nesting(s);
s.push_str("________\n");
}
Event::TaskListMarker(checked) => {
self.top_written = true;
s.push_str(if checked { "[X] " } else { "[ ] " })
}
}
}
}
fn finish_encoding(&mut self, s: &mut String) {
s.push('\n');
let mut link_lines = Vec::new();
self.shortcut_link.take();
let links = std::mem::take(&mut self.links);
for (shortcut, links) in links {
for (index, link) in links.into_iter().enumerate() {
let mut line = String::new();
line.push_str("[");
line.push_str(&shortcut);
if index != 0 {
line.push_str(&format!("-{}", index));
}
line.push_str("]: ");
line.push_str(&link);
link_lines.push(line);
}
}
link_lines.sort_unstable();
for line in link_lines {
s.push('\n');
s.push_str(&line)
}
}
}
impl MarkdownCallbacks {
/// Push `string` in both `s` and `self.shortcut_link` if is is `Some`.
fn push_str(&mut self, s: &mut String, string: &str) {
self.top_written = true;
s.push_str(string);
if let Some(shortcut) = &mut self.shortcut_link {
shortcut.push_str(string)
}
}
/// Tries to add the `shortcut` to the list.
///
/// - If it is not present, add it as-is.
/// - If it is already present with the same `link`, at index:
/// - `0`: does nothing.
/// - `> 0`: change `shortcut` to `shortcut-index`.
/// - If it is already present, but none of the `n` links associated
/// with it correspond to `link`, add `link` to its list and change
/// `shortcut` to `shortcut-n`.
fn add_shortcut_link(&mut self, mut shortcut: String, link: &str) {
if let Some(links) = self.links.get_mut(&shortcut) {
if let Some((index, _)) = links.iter().enumerate().find(|(_, l)| l == &link) {
if index > 0 {
shortcut.push_str(&format!("-{}", index));
}
} else {
let index = links.len();
links.push(link.to_string());
if index > 0 {
shortcut.push_str(&format!("-{}", index));
}
}
} else {
self.links.insert(shortcut, vec![link.to_string()]);
}
}
/// Start a new list item, like `"- "` or `"2. "`.
fn start_new_item(&mut self, s: &mut String) {
if let Some(Nesting::ListLevel(Some(index))) = self.nesting.last_mut() {
*index += 1;
s.push_str(&format!("{}. ", *index - 1))
} else {
s.push_str("- ");
}
}
/// - If the last item in `self.nesting` is `Nesting::StartListItem`, replace it
/// with `Nesting::ListItem` and returns.
/// - Else, push a new line in `s` with indentation given by `self.nesting`.
fn apply_nesting(&mut self, s: &mut String) {
if !self.top_written {
if matches!(self.nesting.last(), Some(Nesting::Quote)) {
s.push_str("> ")
}
return;
}
s.push('\n');
for nesting in &mut self.nesting {
match nesting {
Nesting::ListLevel(_) => {}
Nesting::ListItem => s.push_str(" "),
Nesting::Quote => s.push_str("> "),
Nesting::IndentedCode => s.push_str(" "),
}
}
}
}
/// Remove trailing whitespace.
fn trim(s: &mut String) {
while let Some(c) = s.pop() {
if !c.is_whitespace() {
s.push(c);
break;
}
}
}