1#[derive(Clone, Debug, PartialEq, Eq)]
7pub enum Inline {
8 Text(String),
9 Code(String),
10 Bold(String),
11 Italic(String),
12}
13
14#[derive(Clone, Debug, PartialEq, Eq)]
16pub enum Block {
17 Code(String),
18 Paragraph(Vec<Inline>),
19}
20
21pub fn parse(text: &str) -> Vec<Block> {
24 let mut blocks = Vec::new();
25 let mut rest = text;
26 let mut in_code = false;
27 loop {
28 let (part, next) = match rest.find("```") {
29 Some(at) => {
30 let after = &rest[at + 3..];
32 let name = after.find(|c: char| !c.is_ascii_alphabetic()).unwrap_or(after.len());
33 let after = &after[name..];
34 (&rest[..at], Some(after.strip_prefix('\n').unwrap_or(after)))
35 }
36 None => (rest, None),
37 };
38 if !part.is_empty() {
39 if in_code {
40 blocks.push(Block::Code(part.strip_suffix('\n').unwrap_or(part).to_owned()));
41 } else {
42 let trimmed = part.trim_matches('\n');
43 if !trimmed.is_empty() {
44 blocks.push(Block::Paragraph(inline(trimmed)));
45 }
46 }
47 }
48 match next {
49 Some(n) => {
50 rest = n;
51 in_code = !in_code;
52 }
53 None => return blocks,
54 }
55 }
56}
57
58fn inline(text: &str) -> Vec<Inline> {
61 let chars: Vec<char> = text.chars().collect();
62 let mut out = Vec::new();
63 let mut plain = String::new();
64 let mut i = 0;
65 let find = |from: usize, c: char| chars[from..].iter().position(|&x| x == c).map(|p| from + p);
66 while i < chars.len() {
67 let span = match chars[i] {
68 '`' => {
69 find(i + 1, '`').filter(|&j| j > i + 1).map(|j| (j + 1, Inline::Code(chars[i + 1..j].iter().collect())))
70 }
71 '*' if chars.get(i + 1) == Some(&'*') => find(i + 2, '*')
72 .filter(|&j| j > i + 2 && chars.get(j + 1) == Some(&'*'))
73 .map(|j| (j + 2, Inline::Bold(chars[i + 2..j].iter().collect()))),
74 '*' if chars.get(i + 1).is_some_and(|c| !c.is_whitespace()) => {
75 find(i + 1, '*').map(|j| (j + 1, Inline::Italic(chars[i + 1..j].iter().collect())))
76 }
77 _ => None,
78 };
79 match span {
80 Some((end, piece)) => {
81 if !plain.is_empty() {
82 out.push(Inline::Text(std::mem::take(&mut plain)));
83 }
84 out.push(piece);
85 i = end;
86 }
87 None => {
88 plain.push(chars[i]);
89 i += 1;
90 }
91 }
92 }
93 if !plain.is_empty() {
94 out.push(Inline::Text(plain));
95 }
96 out
97}
98
99#[cfg(test)]
100mod tests {
101 use super::*;
102
103 fn text(s: &str) -> Inline {
104 Inline::Text(s.into())
105 }
106
107 #[test]
108 fn fences_and_inline_spans() {
109 let blocks = parse("```rust\nfn main() {}\n```\nCalls `run` **twice**, *then* stops.\n");
110 assert_eq!(
111 blocks,
112 vec![
113 Block::Code("fn main() {}".into()),
114 Block::Paragraph(vec![
115 text("Calls "),
116 Inline::Code("run".into()),
117 text(" "),
118 Inline::Bold("twice".into()),
119 text(", "),
120 Inline::Italic("then".into()),
121 text(" stops."),
122 ]),
123 ]
124 );
125 }
126
127 #[test]
128 fn unmatched_markers_stay_text() {
129 assert_eq!(parse("a * b and `x and **y"), vec![Block::Paragraph(vec![text("a * b and `x and **y")])]);
130 assert_eq!(parse("2 ** 3 = 8"), vec![Block::Paragraph(vec![text("2 ** 3 = 8")])]);
131 assert_eq!(parse("``\n\n"), vec![Block::Paragraph(vec![text("``")])]);
132 assert!(parse("").is_empty());
133 assert_eq!(parse("see\n```\nx = 1"), vec![Block::Paragraph(vec![text("see")]), Block::Code("x = 1".into())]);
135 }
136}