Skip to content
1        10        20        30        40        50        60        70        80        901use eframe::egui;2use pulldown_cmark::{CodeBlockKind, Event, Options, Parser, Tag, TagEnd};34#[derive(Debug, Clone, Copy, PartialEq, Eq)]5enum BlockKind {6    Heading(u8),7    Paragraph,8    Quote,9    ListItem { depth: usize, number: Option<u64> },10    Code,11    Rule,12}1314#[derive(Debug, Clone, PartialEq, Eq)]15struct Span {16    text: String,17    style: u8,18}1920const STRONG: u8 = 1;21const EMPHASIS: u8 = 2;22const STRIKE: u8 = 4;23const CODE: u8 = 8;2425#[derive(Debug, Clone, PartialEq, Eq)]26struct Block {27    kind: BlockKind,28    spans: Vec<Span>,29}3031#[derive(Default)]32struct InlineStyle {33    strong: usize,34    emphasis: usize,35    strike: usize,36}3738impl InlineStyle {39    fn span(&self, text: String) -> Span {40        let mut style = 0;41        if self.strong > 0 {42            style |= STRONG;43        }44        if self.emphasis > 0 {45            style |= EMPHASIS;46        }47        if self.strike > 0 {48            style |= STRIKE;49        }50        Span { text, style }51    }52}5354fn blocks(markdown: &str) -> Vec<Block> {55    let mut state = PreviewState::default();56    for event in Parser::new_ext(markdown, preview_options()) {57        state.handle(event);58    }59    state.output60}6162fn preview_options() -> Options {63    Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TASKLISTS64}6566#[derive(Default)]67struct PreviewState {68    output: Vec<Block>,69    lists: Vec<Option<u64>>,70    quote_depth: usize,71    style: InlineStyle,72}7374impl PreviewState {75    fn handle(&mut self, event: Event<'_>) {76        match event {77            Event::Start(Tag::Heading { level, .. }) => self.output.push(Block {78                kind: BlockKind::Heading(level as u8),79                spans: Vec::new(),80            }),81            Event::Start(Tag::Paragraph) => {82                let kind = if let Some(block) = self.output.last() {83                    if matches!(block.kind, BlockKind::ListItem { .. }) {84                        None85                    } else if self.quote_depth > 0 {86                        Some(BlockKind::Quote)87                    } else {88                        Some(BlockKind::Paragraph)89                    }90                } else if self.quote_depth > 0 {91                    Some(BlockKind::Quote)92                } else {93                    Some(BlockKind::Paragraph)94                };95                if let Some(kind) = kind {96                    self.output.push(Block {97                        kind,98                        spans: Vec::new(),99                    });100                }101            }102            Event::Start(Tag::BlockQuote(_)) => self.quote_depth += 1,103            Event::Start(Tag::List(start)) => self.lists.push(start),104            Event::Start(Tag::Item) => {105                let number = self.lists.last_mut().and_then(|list| {106                    list.as_mut().map(|value| {107                        let current = *value;108                        *value += 1;109                        current110                    })111                });112                self.output.push(Block {113                    kind: BlockKind::ListItem {114                        depth: self.lists.len().saturating_sub(1),115                        number,116                    },117                    spans: Vec::new(),118                });119            }120            Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(_) | CodeBlockKind::Indented)) => {121                self.output.push(Block {122                    kind: BlockKind::Code,123                    spans: Vec::new(),124                });125            }126            Event::Start(Tag::Strong) => self.style.strong += 1,127            Event::Start(Tag::Emphasis) => self.style.emphasis += 1,128            Event::Start(Tag::Strikethrough) => self.style.strike += 1,129            Event::End(TagEnd::BlockQuote(_)) => {130                self.quote_depth = self.quote_depth.saturating_sub(1);131            }132            Event::End(TagEnd::List(_)) => {133                self.lists.pop();134            }135            Event::End(TagEnd::Strong) => self.style.strong = self.style.strong.saturating_sub(1),136            Event::End(TagEnd::Emphasis) => {137                self.style.emphasis = self.style.emphasis.saturating_sub(1);138            }139            Event::End(TagEnd::Strikethrough) => {140                self.style.strike = self.style.strike.saturating_sub(1);141            }142            Event::Rule => self.output.push(Block {143                kind: BlockKind::Rule,144                spans: Vec::new(),145            }),146            Event::Text(text) => {147                let span = self.style.span(text.into_string());148                self.push_text(span);149            }150            Event::Code(text) | Event::InlineMath(text) | Event::DisplayMath(text) => {151                let mut span = self.style.span(text.into_string());152                span.style |= CODE;153                self.push_text(span);154            }155            Event::SoftBreak => {156                let span = self.style.span(" ".to_owned());157                self.push_text(span);158            }159            Event::HardBreak => {160                let span = self.style.span("\n".to_owned());161                self.push_text(span);162            }163            Event::TaskListMarker(checked) => {164                let marker = if checked { "☑ " } else { "☐ " };165                let span = self.style.span(marker.to_owned());166                self.push_text(span);167            }168            Event::Start(_)169            | Event::End(_)170            | Event::Html(_)171            | Event::InlineHtml(_)172            | Event::FootnoteReference(_) => {}173        }174    }175176    fn push_text(&mut self, span: Span) {177        if span.text.is_empty() {178            return;179        }180        if let Some(block) = self.output.last_mut() {181            if let Some(previous) = block.spans.last_mut()182                && previous.style == span.style183            {184                previous.text.push_str(&span.text);185                return;186            }187            block.spans.push(span);188        }189    }190}191192pub fn render(ui: &mut egui::Ui, markdown: &str) {193    for block in blocks(markdown) {194        match block.kind {195            BlockKind::Heading(level) => {196                let size = match level {197                    1 => 30.0,198                    2 => 25.0,199                    3 => 21.0,200                    4 => 18.0,201                    _ => 16.0,202                };203                render_spans(ui, &block.spans, size, true);204                ui.add_space(4.0);205            }206            BlockKind::Paragraph => {207                render_spans(ui, &block.spans, 16.0, false);208                ui.add_space(8.0);209            }210            BlockKind::Quote => {211                ui.horizontal(|ui| {212                    ui.add_sized(213                        [3.0, ui.available_height().max(24.0)],214                        egui::Label::new(215                            egui::RichText::new(" ").background_color(216                                ui.visuals().widgets.noninteractive.bg_stroke.color,217                            ),218                        ),219                    );220                    render_spans(ui, &block.spans, 16.0, false);221                });222                ui.add_space(6.0);223            }224            BlockKind::ListItem { depth, number } => {225                ui.horizontal(|ui| {226                    for _ in 0..depth {227                        ui.add_space(16.0);228                    }229                    let marker = number.map_or_else(|| "•".to_owned(), |n| format!("{n}."));230                    ui.label(marker);231                    render_spans(ui, &block.spans, 16.0, false);232                });233            }234            BlockKind::Code => {235                egui::Frame::group(ui.style()).show(ui, |ui| {236                    ui.set_width(ui.available_width());237                    ui.horizontal_wrapped(|ui| {238                        for span in block.spans {239                            ui.label(egui::RichText::new(span.text).monospace());240                        }241                    });242                });243                ui.add_space(8.0);244            }245            BlockKind::Rule => {246                ui.separator();247            }248        }249    }250}251252fn render_spans(ui: &mut egui::Ui, spans: &[Span], size: f32, heading: bool) {253    ui.horizontal_wrapped(|ui| {254        for span in spans {255            let mut text = egui::RichText::new(&span.text).size(size);256            if span.style & STRONG != 0 || heading {257                text = text.strong();258            }259            if span.style & EMPHASIS != 0 {260                text = text.italics();261            }262            if span.style & STRIKE != 0 {263                text = text.strikethrough();264            }265            if span.style & CODE != 0 {266                text = text267                    .monospace()268                    .background_color(ui.visuals().code_bg_color);269            }270            ui.label(text);271        }272    });273}274275#[cfg(test)]276mod tests {277    use super::{BlockKind, EMPHASIS, STRONG, blocks};278279    #[test]280    fn parses_headings_paragraphs_lists_and_code_blocks() {281        let parsed = blocks("# Title\n\nA paragraph.\n\n- One\n- Two\n\n```\nlet x = 1;\n```\n");282        let kinds: Vec<_> = parsed.iter().map(|block| block.kind).collect();283284        assert_eq!(285            kinds,286            [287                BlockKind::Heading(1),288                BlockKind::Paragraph,289                BlockKind::ListItem {290                    depth: 0,291                    number: None292                },293                BlockKind::ListItem {294                    depth: 0,295                    number: None296                },297                BlockKind::Code298            ]299        );300        assert_eq!(parsed[0].spans[0].text, "Title");301        assert_eq!(parsed[2].spans[0].text, "One");302        assert!(parsed[4].spans[0].text.contains("let x = 1;"));303    }304305    #[test]306    fn preserves_inline_emphasis_and_ordered_list_markers() {307        let parsed = blocks("**bold** and *italic*\n\n3. first\n4. second");308309        assert!(310            parsed[0]311                .spans312                .iter()313                .any(|span| span.text == "bold" && span.style & STRONG != 0)314        );315        assert!(316            parsed[0]317                .spans318                .iter()319                .any(|span| span.text == "italic" && span.style & EMPHASIS != 0)320        );321        assert_eq!(322            parsed[1].kind,323            BlockKind::ListItem {324                depth: 0,325                number: Some(3)326            }327        );328        assert_eq!(329            parsed[2].kind,330            BlockKind::ListItem {331                depth: 0,332                number: Some(4)333            }334        );335    }336}