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
#![allow(
    unused,
    dead_code,
    unused_variables,
    unused_imports,
    unused_mut,
    unused_assignments
)]

use pulldown_cmark::{
    BlockQuoteKind, CodeBlockKind, CowStr, Event, HeadingLevel, Options, Tag, TagEnd,
};
use ratatui::{
    prelude::{Color, Line, Span, Style, Stylize, Text},
    symbols::line,
};
use tracing::{debug, info};

pub fn from_str(input: &str) -> Text {
    let mut options = Options::empty();
    options.insert(Options::ENABLE_STRIKETHROUGH);
    let parser = pulldown_cmark::Parser::new_ext(input, options);
    let text = Text::default();
    let mut writer = TextWriter::new(parser, text);
    writer.run();
    writer.text
}

struct TextWriter<'a, I> {
    /// Iterator supplying events.
    iter: I,

    /// Text to write to.
    text: Text<'a>,

    /// Current line.
    line: Option<Line<'a>>,

    /// Current style.
    style: Style,

    /// Current list index as a stack of indices.
    list_index: Vec<u64>,
}

impl<'a, I> TextWriter<'a, I>
where
    I: Iterator<Item = Event<'a>>,
{
    fn new(iter: I, text: Text<'a>) -> Self {
        Self {
            iter,
            text,
            line: None,
            style: Style::default(),
            list_index: vec![],
        }
    }

    fn run(&mut self) {
        debug!("Running text writer");
        while let Some(event) = self.iter.next() {
            debug!("Event: {:?}", event);
            match event {
                Event::Start(tag) => self.start_tag(tag),
                Event::End(tag) => self.end_tag(tag),
                Event::Text(text) => self.text(text),
                Event::Code(code) => self.code(code),
                Event::Html(html) => todo!(),
                Event::InlineHtml(html) => todo!(),
                Event::FootnoteReference(_) => todo!(),
                Event::SoftBreak => self.soft_break(),
                Event::HardBreak => self.hard_break(),
                Event::Rule => todo!(),
                Event::TaskListMarker(_) => todo!(),
                Event::InlineMath(_) => todo!(),
                Event::DisplayMath(_) => todo!(),
            };
        }
    }

    fn start_tag(&mut self, tag: Tag<'a>) {
        match tag {
            Tag::Paragraph => {}
            Tag::Heading {
                level,
                id,
                classes,
                attrs,
            } => {
                self.start_heading(level);
            }
            Tag::BlockQuote(kind) => self.start_blockquote(kind),
            Tag::CodeBlock(kind) => self.start_codeblock(kind),
            Tag::HtmlBlock => todo!(),
            Tag::List(start_index) => {
                // TODO handle unordered lists properly (start_index is None for unordered lists)
                self.start_list(start_index.unwrap_or(0));
            }
            Tag::Item => {
                let width = self.list_index.len() * 4 - 3;
                if let Some(index) = self.list_index.last_mut() {
                    let span =
                        Span::styled(format!("{:width$}. ", index), Style::new().light_blue());
                    self.line = Some(span.into());
                    *index += 1;
                }
            }
            Tag::FootnoteDefinition(_) => todo!(),
            Tag::Table(_) => todo!(),
            Tag::TableHead => todo!(),
            Tag::TableRow => todo!(),
            Tag::TableCell => todo!(),
            Tag::Emphasis => self.style = self.style.italic(),
            Tag::Strong => self.style = self.style.bold(),
            Tag::Strikethrough => self.style = self.style.crossed_out(),
            Tag::Link {
                link_type,
                dest_url,
                title,
                id,
            } => todo!(),
            Tag::Image {
                link_type,
                dest_url,
                title,
                id,
            } => todo!(),
            Tag::MetadataBlock(_) => todo!(),
            Tag::DefinitionList => todo!(),
            Tag::DefinitionListTitle => todo!(),
            Tag::DefinitionListDefinition => todo!(),
        }
    }

    fn end_tag(&mut self, tag: TagEnd) {
        match tag {
            TagEnd::Paragraph => {
                if let Some(line) = self.line.take() {
                    self.text.lines.push(line);
                    self.text.lines.push(Line::raw(""));
                }
            }
            TagEnd::Heading(_) => {
                if let Some(line) = self.line.take() {
                    self.text.lines.push(line);
                    self.text.lines.push(Line::raw(""));
                }
            }
            TagEnd::BlockQuote(_) => {
                if let Some(line) = self.line.take() {
                    self.text.lines.push(line);
                    self.text.lines.push(Line::raw(""));
                }
            }
            TagEnd::CodeBlock => self.end_codeblock(),
            TagEnd::HtmlBlock => todo!(),
            TagEnd::List(is_ordered) => {
                if let Some(line) = self.line.take() {
                    self.text.lines.push(line);
                }
                self.text.lines.push(Line::raw(""));
                self.list_index.pop();
            }
            TagEnd::Item => {
                if let Some(line) = self.line.take() {
                    self.text.lines.push(line);
                }
            }
            TagEnd::FootnoteDefinition => todo!(),
            TagEnd::Table => todo!(),
            TagEnd::TableHead => todo!(),
            TagEnd::TableRow => todo!(),
            TagEnd::TableCell => todo!(),
            TagEnd::Emphasis => self.style = self.style.not_italic(),
            TagEnd::Strong => self.style = self.style.not_bold(),
            TagEnd::Strikethrough => self.style = self.style.not_crossed_out(),
            TagEnd::Link => todo!(),
            TagEnd::Image => todo!(),
            TagEnd::MetadataBlock(_) => todo!(),
            TagEnd::DefinitionList => todo!(),
            TagEnd::DefinitionListTitle => todo!(),
            TagEnd::DefinitionListDefinition => todo!(),
        }
    }

    fn start_heading(&mut self, level: HeadingLevel) {
        let style = match level {
            HeadingLevel::H1 => Style::new().on_cyan().bold().underlined(),
            HeadingLevel::H2 => Style::new().cyan().bold(),
            HeadingLevel::H3 => Style::new().cyan().bold().italic(),
            HeadingLevel::H4 => Style::new().light_cyan().italic(),
            HeadingLevel::H5 => Style::new().light_cyan().italic(),
            HeadingLevel::H6 => Style::new().light_cyan().italic(),
        };
        let level_index = level as usize;
        let prefix = "#".repeat(level_index);
        self.line = Some(Line::styled(format!("{} ", prefix), style));
        debug!(?self.line, "Start heading");
    }

    fn start_blockquote(&mut self, kind: Option<BlockQuoteKind>) {
        let span = Span::styled("> ", Style::new().green());
        self.line = Some(span.into());
        debug!(?self.line, "Start blockquote");
    }

    fn text(&mut self, text: CowStr<'a>) {
        /// TODO this may have newlines in it, which should be handled differently, we likely need
        /// to be better about handling newlines in general
        let span = Span::styled(text, self.style);
        if let Some(mut line) = self.line.take() {
            line.spans.push(span);
            self.line = Some(line);
        } else {
            self.line = Some(span.into());
        }
        debug!(?self.line, "Text");
    }

    fn hard_break(&mut self) {
        debug!("Newline");
        if let Some(line) = self.line.take() {
            self.text.lines.push(line);
        }
    }

    fn start_list(&mut self, index: u64) {
        self.list_index.push(index);
    }

    fn soft_break(&mut self) {
        let span = Span::styled(" ", self.style);
        if let Some(mut line) = self.line.take() {
            line.spans.push(span);
            self.line = Some(line);
        } else {
            self.line = Some(span.into());
        }
    }

    fn start_codeblock(&mut self, kind: CodeBlockKind<'_>) {
        let lang = match kind {
            CodeBlockKind::Fenced(ref lang) => lang.as_ref(),
            CodeBlockKind::Indented => "",
        };
        let span = Span::styled(format!("```{}", lang), (Color::White, Color::Black));
        self.push_line(span);
    }

    fn end_codeblock(&mut self) {
        let span = Span::styled("```", Style::new().on_black().white());
        if let Some(mut line) = self.line.take() {
            line.spans.push(span);
            self.text.lines.push(line);
        } else {
            self.text.lines.push(span.into());
        }
    }

    fn code(&mut self, code: CowStr<'a>) {
        let span = Span::styled(code, Style::new().on_black().white());
        if let Some(mut line) = self.line.take() {
            line.spans.push(span);
            self.line = Some(line);
        } else {
            self.line = Some(span.into());
        }
    }

    fn push_line<T>(&mut self, line: T)
    where
        T: Into<Line<'a>>,
    {
        self.text.lines.push(line.into());
    }
}