1pub use pulldown_cmark::Alignment;
4use pulldown_cmark::{CodeBlockKind, Event, LinkType, Options, Parser, Tag, TagEnd};
5
6pub const GITHUB_FLAVORED: Options = Options::ENABLE_TABLES
9 .union(Options::ENABLE_STRIKETHROUGH)
10 .union(Options::ENABLE_TASKLISTS);
11
12#[derive(Clone, Debug, PartialEq)]
14pub enum Block {
15 Paragraph(Vec<Inline>),
16 Heading {
18 level: u8,
19 content: Vec<Inline>,
20 },
21 Quote(Vec<Block>),
22 List {
25 start: Option<u64>,
26 tight: bool,
27 items: Vec<ListItem>,
28 },
29 CodeBlock {
32 language: Option<String>,
33 text: String,
34 },
35 Table {
37 alignments: Vec<Alignment>,
38 head: Vec<Cell>,
39 rows: Vec<Vec<Cell>>,
40 },
41 Rule,
42}
43
44#[derive(Clone, Debug, PartialEq)]
46pub enum Inline {
47 Text(String),
49 Emphasis(Vec<Inline>),
50 Strong(Vec<Inline>),
51 Strikethrough(Vec<Inline>),
52 Code(String),
53 Link {
55 url: String,
56 title: String,
57 content: Vec<Inline>,
58 },
59 Image(Image),
60 LineBreak,
62}
63
64#[derive(Clone, Debug, PartialEq)]
66pub struct Image {
67 pub url: String,
69 pub title: String,
70 pub alt: String,
72}
73
74#[derive(Clone, Debug, PartialEq)]
76pub struct ListItem {
77 pub checked: Option<bool>,
79 pub content: Vec<Block>,
80}
81
82#[derive(Clone, Debug, Default, PartialEq)]
84pub struct Cell {
85 pub content: Vec<Inline>,
86}
87
88pub fn parse(markdown: &str, options: Options) -> Vec<Block> {
92 let mut builder = DocumentBuilder::default();
93 for event in Parser::new_ext(markdown, options) {
94 builder.event(event);
95 }
96 builder.finish()
97}
98
99enum Frame {
101 Blocks {
102 blocks: Vec<Block>,
103 container: BlockContainer,
104 },
105 List {
106 start: Option<u64>,
107 tight: bool,
108 items: Vec<ListItem>,
109 },
110 Inlines {
111 inlines: Vec<Inline>,
112 container: InlineContainer,
113 },
114 CodeBlock {
115 language: Option<String>,
116 text: String,
117 },
118 Table {
119 alignments: Vec<Alignment>,
120 head: Vec<Cell>,
121 rows: Vec<Vec<Cell>>,
122 row: Vec<Cell>,
123 },
124 Dropped,
126}
127
128enum BlockContainer {
129 Quote,
130 Item {
131 checked: Option<bool>,
132 },
133 Transparent,
136}
137
138enum InlineContainer {
139 Paragraph,
140 ImplicitParagraph,
142 Heading(u8),
143 Emphasis,
144 Strong,
145 Strikethrough,
146 Link {
147 url: String,
148 title: String,
149 },
150 Image {
151 url: String,
152 title: String,
153 },
154 Cell,
155 Transparent,
158}
159
160#[derive(Default)]
161struct DocumentBuilder {
162 document: Vec<Block>,
163 stack: Vec<Frame>,
164}
165
166impl DocumentBuilder {
167 fn event(&mut self, event: Event<'_>) {
168 if matches!(self.stack.last(), Some(Frame::Dropped)) {
169 match event {
170 Event::Start(_) => self.stack.push(Frame::Dropped),
171 Event::End(_) => {
172 self.stack.pop();
173 }
174 _ => {}
175 }
176 return;
177 }
178 match event {
179 Event::Start(tag) => self.start(tag),
180 Event::End(tag) => self.end(tag),
181 Event::Text(text) => self.text(&text),
182 Event::Code(code) => self.push_inline(Inline::Code(code.into_string())),
183 Event::InlineHtml(html) => self.push_text(&html),
184 Event::InlineMath(math) | Event::DisplayMath(math) => self.push_text(&math),
185 Event::FootnoteReference(label) => self.push_text(&format!("[{label}]")),
186 Event::SoftBreak => self.push_text(" "),
187 Event::HardBreak => self.push_inline(Inline::LineBreak),
188 Event::Rule => self.push_block(Block::Rule),
189 Event::TaskListMarker(checked) => self.check_item(checked),
190 Event::Html(_) => {}
191 }
192 }
193
194 fn finish(mut self) -> Vec<Block> {
195 self.close_implicit_paragraph();
196 self.document
197 }
198
199 fn start(&mut self, tag: Tag<'_>) {
200 if is_block(&tag) {
201 self.close_implicit_paragraph();
202 }
203 let frame = match tag {
204 Tag::Paragraph => {
205 self.loosen_list();
206 inlines(InlineContainer::Paragraph)
207 }
208 Tag::Heading { level, .. } => inlines(InlineContainer::Heading(level as u8)),
209 Tag::BlockQuote(_) => blocks(BlockContainer::Quote),
210 Tag::CodeBlock(kind) => Frame::CodeBlock {
211 language: match kind {
212 CodeBlockKind::Fenced(info) => {
213 info.split_whitespace().next().map(str::to_owned)
214 }
215 CodeBlockKind::Indented => None,
216 },
217 text: String::new(),
218 },
219 Tag::HtmlBlock | Tag::MetadataBlock(_) => Frame::Dropped,
220 Tag::List(start) => Frame::List {
221 start,
222 tight: true,
223 items: Vec::new(),
224 },
225 Tag::Item => blocks(BlockContainer::Item { checked: None }),
226 Tag::Table(alignments) => Frame::Table {
227 alignments,
228 head: Vec::new(),
229 rows: Vec::new(),
230 row: Vec::new(),
231 },
232 Tag::TableHead | Tag::TableRow => return,
233 Tag::TableCell => inlines(InlineContainer::Cell),
234 Tag::FootnoteDefinition(_) | Tag::DefinitionList | Tag::DefinitionListDefinition => {
235 blocks(BlockContainer::Transparent)
236 }
237 Tag::DefinitionListTitle => inlines(InlineContainer::Paragraph),
238 Tag::Emphasis => self.inline_frame(InlineContainer::Emphasis),
239 Tag::Strong => self.inline_frame(InlineContainer::Strong),
240 Tag::Strikethrough => self.inline_frame(InlineContainer::Strikethrough),
241 Tag::Superscript | Tag::Subscript => self.inline_frame(InlineContainer::Transparent),
242 Tag::Link {
243 link_type,
244 dest_url,
245 title,
246 ..
247 } => self.inline_frame(InlineContainer::Link {
248 url: match link_type {
249 LinkType::Email => format!("mailto:{dest_url}"),
250 _ => dest_url.into_string(),
251 },
252 title: title.into_string(),
253 }),
254 Tag::Image {
255 dest_url, title, ..
256 } => self.inline_frame(InlineContainer::Image {
257 url: dest_url.into_string(),
258 title: title.into_string(),
259 }),
260 };
261 self.stack.push(frame);
262 }
263
264 fn end(&mut self, tag: TagEnd) {
265 match tag {
266 TagEnd::TableHead => {
267 if let Some(Frame::Table {
268 alignments,
269 head,
270 row,
271 ..
272 }) = self.stack.last_mut()
273 {
274 *head = padded_row(std::mem::take(row), alignments.len());
275 }
276 return;
277 }
278 TagEnd::TableRow => {
279 if let Some(Frame::Table {
280 alignments,
281 rows,
282 row,
283 ..
284 }) = self.stack.last_mut()
285 {
286 rows.push(padded_row(std::mem::take(row), alignments.len()));
287 }
288 return;
289 }
290 _ => {}
291 }
292 self.close_implicit_paragraph();
294 let Some(frame) = self.stack.pop() else {
295 return;
296 };
297 match frame {
298 Frame::Blocks {
299 blocks: content,
300 container,
301 } => match container {
302 BlockContainer::Quote => self.push_block(Block::Quote(content)),
303 BlockContainer::Item { checked } => {
304 if let Some(Frame::List { items, .. }) = self.stack.last_mut() {
305 items.push(ListItem { checked, content });
306 }
307 }
308 BlockContainer::Transparent => {
309 for block in content {
310 self.push_block(block);
311 }
312 }
313 },
314 Frame::List {
315 start,
316 tight,
317 items,
318 } => self.push_block(Block::List {
319 start,
320 tight,
321 items,
322 }),
323 Frame::Inlines {
324 inlines: content,
325 container,
326 } => self.close_inlines(content, container),
327 Frame::CodeBlock { language, mut text } => {
328 if text.ends_with('\n') {
329 text.pop();
330 }
331 self.push_block(Block::CodeBlock { language, text });
332 }
333 Frame::Table {
334 alignments,
335 head,
336 rows,
337 ..
338 } => self.push_block(Block::Table {
339 alignments,
340 head,
341 rows,
342 }),
343 Frame::Dropped => {}
344 }
345 }
346
347 fn close_inlines(&mut self, content: Vec<Inline>, container: InlineContainer) {
348 match container {
349 InlineContainer::Paragraph | InlineContainer::ImplicitParagraph => {
350 self.push_block(Block::Paragraph(content));
351 }
352 InlineContainer::Heading(level) => self.push_block(Block::Heading { level, content }),
353 InlineContainer::Emphasis => self.push_inline(Inline::Emphasis(content)),
354 InlineContainer::Strong => self.push_inline(Inline::Strong(content)),
355 InlineContainer::Strikethrough => self.push_inline(Inline::Strikethrough(content)),
356 InlineContainer::Link { url, title } => self.push_inline(Inline::Link {
357 url,
358 title,
359 content,
360 }),
361 InlineContainer::Image { url, title } => self.push_inline(Inline::Image(Image {
362 url,
363 title,
364 alt: plain_text(&content),
365 })),
366 InlineContainer::Cell => {
367 if let Some(Frame::Table { row, .. }) = self.stack.last_mut() {
368 row.push(Cell { content });
369 }
370 }
371 InlineContainer::Transparent => {
372 for inline in content {
373 self.push_inline(inline);
374 }
375 }
376 }
377 }
378
379 fn text(&mut self, text: &str) {
380 match self.stack.last_mut() {
381 Some(Frame::CodeBlock { text: code, .. }) => code.push_str(text),
382 _ => self.push_text(text),
383 }
384 }
385
386 fn push_text(&mut self, text: &str) {
388 let inlines = self.open_inlines();
389 if let Some(Inline::Text(last)) = inlines.last_mut() {
390 last.push_str(text);
391 } else {
392 inlines.push(Inline::Text(text.to_owned()));
393 }
394 }
395
396 fn push_inline(&mut self, inline: Inline) {
397 self.open_inlines().push(inline);
398 }
399
400 fn open_inlines(&mut self) -> &mut Vec<Inline> {
403 if !matches!(self.stack.last(), Some(Frame::Inlines { .. })) {
404 self.stack.push(inlines(InlineContainer::ImplicitParagraph));
405 }
406 match self.stack.last_mut() {
407 Some(Frame::Inlines { inlines, .. }) => inlines,
408 _ => unreachable!("an inline frame was just pushed"),
409 }
410 }
411
412 fn inline_frame(&mut self, container: InlineContainer) -> Frame {
414 self.open_inlines();
415 inlines(container)
416 }
417
418 fn push_block(&mut self, block: Block) {
419 self.close_implicit_paragraph();
420 match self.stack.last_mut() {
421 Some(Frame::Blocks { blocks, .. }) => blocks.push(block),
422 None => self.document.push(block),
423 Some(_) => {}
424 }
425 }
426
427 fn close_implicit_paragraph(&mut self) {
428 if let Some(Frame::Inlines {
429 container: InlineContainer::ImplicitParagraph,
430 ..
431 }) = self.stack.last()
432 && let Some(Frame::Inlines { inlines, .. }) = self.stack.pop()
433 {
434 self.push_block(Block::Paragraph(inlines));
435 }
436 }
437
438 fn loosen_list(&mut self) {
440 let depth = self.stack.len();
441 if depth >= 2
442 && let [
443 Frame::List { tight, .. },
444 Frame::Blocks {
445 container: BlockContainer::Item { .. },
446 ..
447 },
448 ] = &mut self.stack[depth - 2..]
449 {
450 *tight = false;
451 }
452 }
453
454 fn check_item(&mut self, is_checked: bool) {
455 let item = self.stack.iter_mut().rev().find_map(|frame| match frame {
456 Frame::Blocks {
457 container: BlockContainer::Item { checked },
458 ..
459 } => Some(checked),
460 _ => None,
461 });
462 if let Some(checked) = item {
463 *checked = Some(is_checked);
464 }
465 }
466}
467
468fn blocks(container: BlockContainer) -> Frame {
469 Frame::Blocks {
470 blocks: Vec::new(),
471 container,
472 }
473}
474
475fn inlines(container: InlineContainer) -> Frame {
476 Frame::Inlines {
477 inlines: Vec::new(),
478 container,
479 }
480}
481
482fn is_block(tag: &Tag<'_>) -> bool {
483 matches!(
484 tag,
485 Tag::Paragraph
486 | Tag::Heading { .. }
487 | Tag::BlockQuote(_)
488 | Tag::CodeBlock(_)
489 | Tag::HtmlBlock
490 | Tag::List(_)
491 | Tag::Item
492 | Tag::FootnoteDefinition(_)
493 | Tag::DefinitionList
494 | Tag::DefinitionListTitle
495 | Tag::DefinitionListDefinition
496 | Tag::Table(_)
497 | Tag::MetadataBlock(_)
498 )
499}
500
501fn padded_row(mut row: Vec<Cell>, columns: usize) -> Vec<Cell> {
504 row.resize_with(columns, Cell::default);
505 row
506}
507
508fn plain_text(inlines: &[Inline]) -> String {
510 let mut text = String::new();
511 for inline in inlines {
512 match inline {
513 Inline::Text(run) | Inline::Code(run) => text.push_str(run),
514 Inline::Emphasis(content)
515 | Inline::Strong(content)
516 | Inline::Strikethrough(content)
517 | Inline::Link { content, .. } => text.push_str(&plain_text(content)),
518 Inline::Image(image) => text.push_str(&image.alt),
519 Inline::LineBreak => text.push('\n'),
520 }
521 }
522 text
523}
524
525#[cfg(test)]
526mod tests {
527 use super::*;
528
529 fn text(text: &str) -> Inline {
530 Inline::Text(text.to_owned())
531 }
532
533 fn paragraph(text: &str) -> Block {
534 Block::Paragraph(vec![self::text(text)])
535 }
536
537 fn item(checked: Option<bool>, content: Vec<Block>) -> ListItem {
538 ListItem { checked, content }
539 }
540
541 #[test]
542 fn headings_and_paragraphs_carry_their_inline_formatting() {
543 let document = parse(
544 "# Title\n\n### Small\n\nSome *em*, **strong**, ~~gone~~ and `code`.\n\n> quoted\n\n---\n",
545 GITHUB_FLAVORED,
546 );
547 assert_eq!(
548 document,
549 [
550 Block::Heading {
551 level: 1,
552 content: vec![text("Title")],
553 },
554 Block::Heading {
555 level: 3,
556 content: vec![text("Small")],
557 },
558 Block::Paragraph(vec![
559 text("Some "),
560 Inline::Emphasis(vec![text("em")]),
561 text(", "),
562 Inline::Strong(vec![text("strong")]),
563 text(", "),
564 Inline::Strikethrough(vec![text("gone")]),
565 text(" and "),
566 Inline::Code("code".to_owned()),
567 text("."),
568 ]),
569 Block::Quote(vec![paragraph("quoted")]),
570 Block::Rule,
571 ]
572 );
573 }
574
575 #[test]
576 fn a_soft_break_is_a_space_and_a_hard_break_is_a_line_break() {
577 assert_eq!(parse("one\ntwo", GITHUB_FLAVORED), [paragraph("one two")]);
578 assert_eq!(
579 parse("one \ntwo", GITHUB_FLAVORED),
580 [Block::Paragraph(vec![
581 text("one"),
582 Inline::LineBreak,
583 text("two")
584 ])]
585 );
586 }
587
588 #[test]
589 fn a_tight_list_nests_and_a_loose_one_keeps_its_paragraphs() {
590 assert_eq!(
591 parse("- outer\n - inner\n- next\n", GITHUB_FLAVORED),
592 [Block::List {
593 start: None,
594 tight: true,
595 items: vec![
596 item(
597 None,
598 vec![
599 paragraph("outer"),
600 Block::List {
601 start: None,
602 tight: true,
603 items: vec![item(None, vec![paragraph("inner")])],
604 },
605 ]
606 ),
607 item(None, vec![paragraph("next")]),
608 ],
609 }]
610 );
611 assert_eq!(
612 parse("3. three\n\n4. four\n\n more\n", GITHUB_FLAVORED),
613 [Block::List {
614 start: Some(3),
615 tight: false,
616 items: vec![
617 item(None, vec![paragraph("three")]),
618 item(None, vec![paragraph("four"), paragraph("more")]),
619 ],
620 }]
621 );
622 }
623
624 #[test]
625 fn task_items_carry_whether_they_are_ticked() {
626 let [Block::List { items, .. }] =
627 &parse("- [x] done\n- [ ] todo\n- plain\n", GITHUB_FLAVORED)[..]
628 else {
629 panic!("one list");
630 };
631 assert_eq!(
632 items,
633 &[
634 item(Some(true), vec![paragraph("done")]),
635 item(Some(false), vec![paragraph("todo")]),
636 item(None, vec![paragraph("plain")]),
637 ]
638 );
639 let [Block::List { items, tight, .. }] =
640 &parse("- [x] done\n\n- [ ] todo\n", GITHUB_FLAVORED)[..]
641 else {
642 panic!("one list");
643 };
644 assert!(!tight);
645 assert_eq!(items[0], item(Some(true), vec![paragraph("done")]));
646 }
647
648 #[test]
649 fn a_table_keeps_its_alignments_and_pads_short_rows() {
650 let cell = |content: &str| Cell {
651 content: vec![text(content)],
652 };
653 assert_eq!(
654 parse(
655 "| a | b | c |\n|:--|:-:|--:|\n| 1 | **2** |\n",
656 GITHUB_FLAVORED
657 ),
658 [Block::Table {
659 alignments: vec![Alignment::Left, Alignment::Center, Alignment::Right],
660 head: vec![cell("a"), cell("b"), cell("c")],
661 rows: vec![vec![
662 cell("1"),
663 Cell {
664 content: vec![Inline::Strong(vec![text("2")])],
665 },
666 Cell::default(),
667 ]],
668 }]
669 );
670 }
671
672 #[test]
673 fn a_code_block_keeps_its_language_and_drops_its_last_line_break() {
674 assert_eq!(
675 parse(
676 "```rust title\nfn main() {}\n```\n\n indented\n",
677 GITHUB_FLAVORED
678 ),
679 [
680 Block::CodeBlock {
681 language: Some("rust".to_owned()),
682 text: "fn main() {}".to_owned(),
683 },
684 Block::CodeBlock {
685 language: None,
686 text: "indented".to_owned(),
687 },
688 ]
689 );
690 }
691
692 #[test]
693 fn links_and_images_carry_their_address_title_and_text() {
694 assert_eq!(
695 parse(
696 "[Seede *home*](https://seede.ai \"home\")  <me@seede.ai>",
697 GITHUB_FLAVORED,
698 ),
699 [Block::Paragraph(vec![
700 Inline::Link {
701 url: "https://seede.ai".to_owned(),
702 title: "home".to_owned(),
703 content: vec![text("Seede "), Inline::Emphasis(vec![text("home")])],
704 },
705 text(" "),
706 Inline::Image(Image {
707 url: "cat.png".to_owned(),
708 title: "Cat".to_owned(),
709 alt: "a cat".to_owned(),
710 }),
711 text(" "),
712 Inline::Link {
713 url: "mailto:me@seede.ai".to_owned(),
714 title: String::new(),
715 content: vec![text("me@seede.ai")],
716 },
717 ])]
718 );
719 }
720
721 #[test]
722 fn an_html_block_is_left_out() {
723 assert_eq!(
724 parse(
725 "<div>\nhidden\n</div>\n\nshown <b>bold</b>\n",
726 GITHUB_FLAVORED
727 ),
728 [paragraph("shown <b>bold</b>")]
729 );
730 }
731}