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
// Slide hierarchy:
//
// # h1 slide section
// ## h2 slide
// ### h3 slide header text
// #### h4 slide sub-header
use std::{path::PathBuf, str::FromStr};
use anyhow::anyhow;
#[derive(Clone, Debug)]
pub enum TextItem {
Header(String),
SubHeader(String),
Body(String),
Quote(String),
/// String name, String content
Code((String, String)),
/// String link name, String link url
Link((String, String)),
}
#[derive(Clone, Debug)]
pub enum ListItem {
Bullet(String),
Number(String),
/// String content, bool checkmark
Check((String, bool)),
}
#[derive(Clone, Debug)]
pub enum SlideItem {
Text(TextItem),
/// String name, PathBuf filepath
Image((String, PathBuf)),
List(Vec<ListItem>),
}
impl SlideItem {
pub fn to_html(&self) -> String {
match self {
SlideItem::Text(item) => match item {
TextItem::Header(s) => return format!("<h2>{}</h2>", s),
TextItem::SubHeader(s) => return format!("<h3>{}</h3>", s),
TextItem::Body(s) => return format!("<p>{}</p>", s),
TextItem::Quote(s) => {
return format!("<blockquote>\"{}\"</blockquote>", s);
}
TextItem::Code((name, content)) => {
return format!(
"<pre><code lang=\"{}\">{content}</code></pre>",
name
);
}
TextItem::Link((name, url)) => {
return format!(
"<a href=\"{url}\" target=\"_blank\">{name}</a>"
);
}
},
SlideItem::Image((name, path)) => {
return format!(
"<img src=\"{}\" alt=\"{name}\">",
path.to_str().unwrap()
);
}
SlideItem::List(items) => {
let mut op = String::new();
let mut el_first = "";
let mut el_last = "";
if let Some(last_item) = items.last() {
match last_item {
ListItem::Bullet(_s) => {
el_first = "<ul>";
el_last = "</ul>";
}
ListItem::Number(_s) => {
el_first = "<ol>";
el_last = "</ol>";
}
ListItem::Check((_s, _checked)) => {
el_first = "<ol class=\"checklist\">";
el_last = "</ol>";
}
}
}
op.push_str(el_first);
for item in items {
match item {
ListItem::Bullet(s) => op.push_str(
format!("\n<li>{s}</li>").as_str(),
),
ListItem::Number(s) => op.push_str(
format!("\n<li>{s}</li>").as_str(),
),
ListItem::Check((s, checked)) => {
if *checked {
op.push_str(
format!(
"<li><input type=\"checkbox\" checked disabled> {s}</li>"
)
.as_str(),
);
} else {
op.push_str(
format!(
"<li><input type=\"checkbox\" disabled> {s}</li>"
)
.as_str(),
);
}
}
}
}
op.push_str(el_last);
return op;
}
}
}
}
#[derive(Clone, Debug, Default)]
pub struct Slide {
pub name: Option<String>,
pub items: Vec<SlideItem>,
}
impl Slide {
fn new(name: Option<String>) -> Self {
Self {
name,
items: Vec::new(),
}
}
fn push_list_item(&mut self, item: ListItem) {
match self.items.last_mut() {
Some(SlideItem::List(list)) => {
list.push(item);
}
_ => {
self.items.push(SlideItem::List(vec![item]));
}
}
}
}
#[derive(Clone, Debug, Default)]
pub struct Section {
pub name: Option<String>,
pub slides: Vec<Slide>,
}
impl Section {
fn new() -> Self {
Self {
name: None,
slides: Vec::new(),
}
}
}
pub fn md_parse(md_contents: String) -> anyhow::Result<Vec<Section>> {
let mut slideshow: Vec<Section> = Vec::new();
// println!("{}", md_contents);
let mut md_lines = md_contents.lines().into_iter();
slideshow = parse_section(&slideshow, &mut md_lines)?;
Ok(slideshow)
}
/// recursive
fn parse_section(
slideshow: &Vec<Section>,
mut md_lines: &mut std::str::Lines<'_>,
) -> anyhow::Result<Vec<Section>> {
let mut slideshow = slideshow.clone();
while let Some(line) = md_lines.next() {
match line {
// new section
_ if line.trim_start().starts_with("# ") => {
slideshow.push(Section::new());
if !line.split_at(2).1.is_empty() {
if let Some(a) = slideshow.last_mut() {
a.name = Some(line.split_at(2).1.to_string());
}
}
slideshow = parse_section(&slideshow, &mut md_lines)?;
}
// new slide
_ if line.trim_start().starts_with("## ") => {
if let Some(a) = slideshow.last_mut() {
let mut name: Option<String> =
Some(line.split_at(2).1.trim().to_string());
if name.clone().unwrap().is_empty() {
name = None;
}
a.slides.push(Slide::new(name));
}
}
// text header
_ if line.trim_start().starts_with("### ") => {
if let Some(a) = slideshow.last_mut() {
if let Some(a) = a.slides.last_mut() {
let si = SlideItem::Text(TextItem::Header(
line.split_at(3).1.trim().to_string(),
));
a.items.push(si);
}
}
}
// text sub-header
_ if line.trim_start().starts_with("#### ") => {
if let Some(a) = slideshow.last_mut() {
if let Some(a) = a.slides.last_mut() {
let si = SlideItem::Text(TextItem::SubHeader(
line.split_at(4).1.trim().to_string(),
));
a.items.push(si);
}
}
}
// quote
_ if line.trim_start().starts_with("> ") => {
if let Some(a) = slideshow.last_mut() {
if let Some(a) = a.slides.last_mut() {
let si = SlideItem::Text(TextItem::Quote(
line.split_at(1).1.trim().to_string(),
));
a.items.push(si);
}
}
}
// code
_ if line.trim_start().starts_with("```") => {
let lang_name = line
.get(4..)
.map(|s| s.to_string())
.unwrap_or("terminal".to_string());
// println!("lang: {}", lang_name);
let mut content = String::new();
'get_content: while let Some(line) = md_lines.next() {
if line.trim_start().starts_with("```") {
break 'get_content;
}
content.push_str(format!("\n{line}").as_str());
}
if let Some(a) = slideshow.last_mut() {
if let Some(a) = a.slides.last_mut() {
let si = SlideItem::Text(TextItem::Code((
lang_name, content,
)));
a.items.push(si);
}
}
}
// image
_ if line.trim_start().starts_with("![") => {
let mut line_c_it = line.chars();
let mut name = String::new();
let mut path = String::new();
while let Some(c) = line_c_it.next() {
if c == '\n' {
return Err(anyhow!(
"premature EOL whilst parsing image item"
));
}
if c == '[' {
while let Some(ci) = line_c_it.next() {
if ci == ']' {
break;
}
name.push(ci);
}
}
if c == '(' {
while let Some(ci) = line_c_it.next() {
if ci == ')' || c == '\n' {
break;
}
path.push(ci);
}
}
}
path = resolve_path_str(path)?;
let path_b = PathBuf::from_str(&path)?.canonicalize()?;
if !path_b.is_file() {
return Err(anyhow!(
"image item \"{}\" could not be found or is not a valid file",
path_b.display()
));
}
if let Some(a) = slideshow.last_mut() {
if let Some(a) = a.slides.last_mut() {
let si = SlideItem::Image((name, path_b));
a.items.push(si);
}
}
}
// bullet list item
_ if (line.trim_start().starts_with("- ")
&& !line.trim_start().starts_with("- ["))
|| line.trim_start().starts_with("+ ")
|| line.trim_start().starts_with("* ") =>
{
if let Some(a) = slideshow.last_mut() {
if let Some(a) = a.slides.last_mut() {
a.push_list_item(ListItem::Bullet(
line.split_at(2).1.trim().to_string(),
));
}
}
}
// check list item
_ if line.trim_start().starts_with("- [") => {
let mut checked = false;
if line.trim().as_bytes()[3] == b'x' {
checked = true;
}
if let Some(a) = slideshow.last_mut() {
if let Some(a) = a.slides.last_mut() {
a.push_list_item(ListItem::Check((
line.split_at(5).1.trim().to_string(),
checked,
)));
}
}
}
// link
_ if (line.trim_start().contains('[')
&& line.trim_start().contains(']'))
&& line.trim_start().contains('(')
&& line.trim_start().contains(')') =>
{
let mut line_c_it = line.chars();
let mut name = String::new();
let mut url = String::new();
while let Some(c) = line_c_it.next() {
if c == '\n' {
return Err(anyhow!(
"premature EOL whilst parsing link item"
));
}
if c == '[' {
while let Some(ci) = line_c_it.next() {
if ci == ']' {
break;
}
name.push(ci);
}
}
if c == '(' {
while let Some(ci) = line_c_it.next() {
if ci == ')' || c == '\n' {
break;
}
url.push(ci);
}
}
}
if let Some(a) = slideshow.last_mut() {
if let Some(a) = a.slides.last_mut() {
let si = SlideItem::Text(TextItem::Link((
name, url,
)));
a.items.push(si);
}
}
}
// numbered list item
_ if !line.is_empty()
&& line.trim().as_bytes()[0].is_ascii_digit()
&& line.trim().as_bytes()[1] == b'.'
&& line.trim().as_bytes()[2] == b' ' =>
{
if let Some(a) = slideshow.last_mut() {
if let Some(a) = a.slides.last_mut() {
a.push_list_item(ListItem::Number(
line.split_at(3).1.trim().to_string(),
));
}
}
}
// body
_ => {
if let Some(a) = slideshow.last_mut() {
if let Some(a) = a.slides.last_mut() {
let si = SlideItem::Text(TextItem::Body(
line.split_at(0).1.trim().to_string(),
));
a.items.push(si);
}
}
}
}
}
Ok(slideshow.clone())
}
fn resolve_path_str(mut path: String) -> anyhow::Result<String> {
if path.starts_with("~") {
let home = std::env::var("HOME")?;
path = path.replace("~", &home);
}
if path.starts_with(".") {
path = path.replace(
"~",
std::env::current_dir()?
.to_str()
.expect("could not expand relative path of \"{path}\""),
);
}
Ok(path)
}