Skip to main content

mermaid_cli/render/
markdown.rs

1use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, Options, Parser, Tag, TagEnd};
2use ratatui::style::{Modifier, Style};
3use ratatui::text::{Line, Span};
4use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
5
6use crate::render::theme::Theme;
7
8/// A parsed markdown line plus whether it is **preformatted** — i.e. must NOT be
9/// word-wrapped by the chat renderer (which collapses runs of whitespace). Code
10/// blocks and tables are preformatted: their exact spacing carries meaning
11/// (indentation, column alignment). Everything else word-wraps normally.
12#[derive(Debug, Clone)]
13pub struct MarkdownLine {
14    pub line: Line<'static>,
15    pub preformatted: bool,
16}
17
18#[derive(Debug, Clone)]
19struct ListState {
20    next_number: Option<u64>,
21    /// Leading whitespace that aligns a continuation block (a 2nd+ paragraph in
22    /// a loose list item) under the current item's text — set when the item's
23    /// marker is emitted.
24    cont_indent: String,
25}
26
27/// Style the list markers ("• ", "1. ") are emitted with. Shared with
28/// [`line_hanging_indent`] so the indent logic recognizes a marker span without
29/// the two definitions drifting apart.
30fn list_marker_style(theme: &Theme) -> Style {
31    Style::new().fg(theme.colors.text_secondary.to_color())
32}
33
34/// Hanging indent (display cells) for hard-wrapping `line`: the column where the
35/// line's content begins, so a wrapped list item's continuation lines align
36/// under its text (after the marker) instead of snapping back to the flat
37/// message gutter. Counts leading whitespace plus a leading list marker; returns
38/// 0 for ordinary paragraphs and headings.
39pub fn line_hanging_indent(line: &Line, theme: &Theme) -> usize {
40    let marker = list_marker_style(theme);
41    let mut indent = 0usize;
42    for span in &line.spans {
43        let text = span.content.as_ref();
44        let trimmed = text.trim_start_matches(' ');
45        if trimmed.is_empty() {
46            indent += text.width(); // a blank span is part of the leading indent
47            continue;
48        }
49        // First span with real content: count its own leading spaces, and include
50        // the marker glyph itself when this span is the list marker.
51        indent += text.width() - trimmed.width();
52        if span.style == marker {
53            indent += trimmed.width();
54        }
55        break;
56    }
57    indent
58}
59
60/// Parse markdown into theme-styled lines, each flagged [`MarkdownLine::preformatted`]
61/// when it must not be word-wrapped — code blocks and tables, whose exact spacing
62/// carries meaning (indentation, column alignment). `width` is the available
63/// content width in display cells; tables are sized and wrapped to fit it.
64///
65/// Code-block lines also keep the theme's `code_background` on their base style
66/// (the gray panel look). Inline code carries the background on the *span*, not
67/// the line, so prose that merely contains `code` still word-wraps normally.
68pub fn parse_markdown(input: &str, theme: &Theme, width: usize) -> Vec<MarkdownLine> {
69    let mut options = Options::empty();
70    options.insert(Options::ENABLE_STRIKETHROUGH);
71    options.insert(Options::ENABLE_TABLES);
72
73    // Resolve the theme palette once.
74    let c = &theme.colors;
75    let code_bg = c.code_background.to_color();
76    let code_fg = c.code_foreground.to_color();
77    let heading1 = Style::new().fg(c.header.to_color()).bold();
78    let heading2 = Style::new().fg(c.info.to_color()).bold();
79    let heading3 = Style::new().fg(c.success.to_color()).bold();
80    let heading_other = Style::new().fg(c.warning.to_color()).bold();
81    let link_style = Style::new()
82        .fg(c.info.to_color())
83        .add_modifier(Modifier::UNDERLINED);
84    let marker_style = list_marker_style(theme);
85    let rule_style = Style::new().fg(c.text_disabled.to_color());
86    let quote_bar_style = Style::new().fg(c.text_disabled.to_color());
87    let quote_text_style = Style::new()
88        .fg(c.text_secondary.to_color())
89        .add_modifier(Modifier::ITALIC);
90
91    let parser = Parser::new_ext(input, options);
92    let mut lines: Vec<Line<'static>> = Vec::new();
93    let mut current_line_spans: Vec<Span<'static>> = Vec::new();
94    let mut style_stack = vec![Style::default()];
95    let mut in_code_block = false;
96    let mut code_block_content = String::new();
97    let mut code_block_lang = String::new();
98    let mut current_link_url: Option<String> = None;
99    let mut list_stack: Vec<ListState> = Vec::new();
100
101    // Table state
102    let mut in_table = false;
103    let mut table_rows: Vec<Vec<String>> = Vec::new();
104    let mut current_row: Vec<String> = Vec::new();
105    let mut current_cell = String::new();
106    let mut table_header_len: usize = 0;
107    // Indices into `lines` produced by `render_table` — these are preformatted
108    // (column-aligned) and must not be word-wrapped by the chat renderer.
109    let mut table_line_indices: std::collections::HashSet<usize> = std::collections::HashSet::new();
110
111    for event in parser {
112        match event {
113            Event::Start(tag) => {
114                let new_style = match tag {
115                    Tag::Heading { level, .. } => {
116                        if !current_line_spans.is_empty() {
117                            lines.push(Line::from(std::mem::take(&mut current_line_spans)));
118                        }
119                        // Blank line before heading (except the first thing).
120                        if !lines.is_empty() {
121                            lines.push(Line::from(""));
122                        }
123                        match level {
124                            HeadingLevel::H1 => heading1,
125                            HeadingLevel::H2 => heading2,
126                            HeadingLevel::H3 => heading3,
127                            _ => heading_other,
128                        }
129                    },
130                    Tag::Emphasis => style_stack.last().copied().unwrap_or_default().italic(),
131                    Tag::Strong => style_stack.last().copied().unwrap_or_default().bold(),
132                    Tag::Strikethrough => style_stack
133                        .last()
134                        .copied()
135                        .unwrap_or_default()
136                        .crossed_out(),
137                    Tag::CodeBlock(kind) => {
138                        in_code_block = true;
139                        code_block_content.clear();
140                        if !current_line_spans.is_empty() {
141                            lines.push(Line::from(std::mem::take(&mut current_line_spans)));
142                        }
143                        code_block_lang = match kind {
144                            CodeBlockKind::Fenced(lang) => lang.to_string(),
145                            CodeBlockKind::Indented => String::new(),
146                        };
147                        if !code_block_lang.is_empty() {
148                            lines.push(Line::from(Span::styled(
149                                code_block_lang.clone(),
150                                Style::new()
151                                    .fg(c.text_disabled.to_color())
152                                    .add_modifier(Modifier::ITALIC),
153                            )));
154                        }
155                        Style::default().fg(code_fg)
156                    },
157                    Tag::List(start) => {
158                        list_stack.push(ListState {
159                            next_number: start,
160                            cont_indent: String::new(),
161                        });
162                        if !current_line_spans.is_empty() {
163                            lines.push(Line::from(std::mem::take(&mut current_line_spans)));
164                        }
165                        style_stack.last().copied().unwrap_or_default()
166                    },
167                    Tag::Item => {
168                        let indent = "  ".repeat(list_stack.len());
169                        let marker = if let Some(state) = list_stack.last_mut() {
170                            if let Some(current) = state.next_number {
171                                state.next_number = Some(current + 1);
172                                format!("{}. ", current)
173                            } else {
174                                "• ".to_string()
175                            }
176                        } else {
177                            "• ".to_string()
178                        };
179                        // Body paragraphs of this item hang-indent to align under
180                        // the text that follows the marker.
181                        let cont_indent =
182                            format!("{}{}", indent, " ".repeat(marker.as_str().width()));
183                        if let Some(state) = list_stack.last_mut() {
184                            state.cont_indent = cont_indent;
185                        }
186                        current_line_spans.push(Span::raw(indent));
187                        current_line_spans.push(Span::styled(marker, marker_style));
188                        style_stack.last().copied().unwrap_or_default()
189                    },
190                    Tag::Paragraph => {
191                        // First paragraph of an item still carries the marker
192                        // spans (non-empty); a continuation paragraph starts
193                        // empty, so re-indent it to align under the item text.
194                        if current_line_spans.is_empty()
195                            && let Some(state) = list_stack.last()
196                            && !state.cont_indent.is_empty()
197                        {
198                            current_line_spans.push(Span::raw(state.cont_indent.clone()));
199                        }
200                        style_stack.last().copied().unwrap_or_default()
201                    },
202                    Tag::Table(_alignments) => {
203                        in_table = true;
204                        table_rows.clear();
205                        table_header_len = 0;
206                        if !current_line_spans.is_empty() {
207                            lines.push(Line::from(std::mem::take(&mut current_line_spans)));
208                        }
209                        style_stack.last().copied().unwrap_or_default()
210                    },
211                    Tag::TableHead | Tag::TableRow => {
212                        current_row.clear();
213                        style_stack.last().copied().unwrap_or_default()
214                    },
215                    Tag::TableCell => {
216                        current_cell.clear();
217                        style_stack.last().copied().unwrap_or_default()
218                    },
219                    Tag::Link { dest_url, .. } => {
220                        // Render the link text underlined in the accent color;
221                        // the destination URL is appended dimmed on the End tag
222                        // (terminals can't follow it without OSC-8).
223                        current_link_url = Some(dest_url.to_string());
224                        link_style
225                    },
226                    Tag::BlockQuote(_) => {
227                        if !current_line_spans.is_empty() {
228                            lines.push(Line::from(std::mem::take(&mut current_line_spans)));
229                        }
230                        current_line_spans.push(Span::styled("│ ", quote_bar_style));
231                        quote_text_style
232                    },
233                    _ => style_stack.last().copied().unwrap_or_default(),
234                };
235                style_stack.push(new_style);
236            },
237            Event::End(tag) => {
238                style_stack.pop();
239                match tag {
240                    TagEnd::Heading(_) => {
241                        if !current_line_spans.is_empty() {
242                            lines.push(Line::from(std::mem::take(&mut current_line_spans)));
243                        }
244                    },
245                    TagEnd::Paragraph | TagEnd::Item => {
246                        if !current_line_spans.is_empty() {
247                            lines.push(Line::from(std::mem::take(&mut current_line_spans)));
248                        }
249                    },
250                    TagEnd::CodeBlock => {
251                        in_code_block = false;
252                        let prefixes = line_comment_prefixes(&code_block_lang);
253                        let base = Style::default().fg(code_fg).bg(code_bg);
254                        for line_text in code_block_content.lines() {
255                            let spans = highlight_code_line(line_text, prefixes, theme);
256                            // Mark the LINE base style with the code bg so the
257                            // chat renderer treats it as pre-formatted.
258                            lines.push(Line::from(spans).style(base));
259                        }
260                        code_block_content.clear();
261                        code_block_lang.clear();
262                    },
263                    TagEnd::List(_) => {
264                        let _ = list_stack.pop();
265                        if list_stack.is_empty() {
266                            lines.push(Line::from(""));
267                        }
268                    },
269                    TagEnd::TableCell => {
270                        current_row.push(std::mem::take(&mut current_cell));
271                    },
272                    TagEnd::TableHead => {
273                        table_header_len = current_row.len();
274                        table_rows.push(std::mem::take(&mut current_row));
275                    },
276                    TagEnd::TableRow => {
277                        table_rows.push(std::mem::take(&mut current_row));
278                    },
279                    TagEnd::Table => {
280                        in_table = false;
281                        let from = lines.len();
282                        render_table(&mut lines, &table_rows, table_header_len, theme, width);
283                        table_line_indices.extend(from..lines.len());
284                        table_rows.clear();
285                    },
286                    TagEnd::Link => {
287                        // Append the destination as dimmed " (url)" unless it's
288                        // identical to the visible text (autolinks) or empty.
289                        if let Some(url) = current_link_url.take() {
290                            let text: String = current_line_spans
291                                .iter()
292                                .map(|s| s.content.as_ref())
293                                .collect();
294                            if !url.is_empty() && !text.ends_with(&url) {
295                                current_line_spans.push(Span::styled(
296                                    format!(" ({})", url),
297                                    Style::new().fg(c.text_disabled.to_color()),
298                                ));
299                            }
300                        }
301                    },
302                    TagEnd::BlockQuote(_) => {
303                        if !current_line_spans.is_empty() {
304                            lines.push(Line::from(std::mem::take(&mut current_line_spans)));
305                        }
306                    },
307                    _ => {},
308                }
309            },
310            Event::Text(text) => {
311                if in_code_block {
312                    code_block_content.push_str(&text);
313                } else if in_table {
314                    current_cell.push_str(&text);
315                } else {
316                    let style = style_stack.last().copied().unwrap_or_default();
317                    current_line_spans.push(Span::styled(text.to_string(), style));
318                }
319            },
320            Event::Code(code) => {
321                if in_table {
322                    current_cell.push_str(&code);
323                } else {
324                    // Inline code: tight (no padding spaces), code colors. The
325                    // background lives on the SPAN only — prose lines with
326                    // inline code still word-wrap normally.
327                    let style = Style::default().fg(code_fg).bg(code_bg);
328                    current_line_spans.push(Span::styled(code.to_string(), style));
329                }
330            },
331            Event::Rule => {
332                if !current_line_spans.is_empty() {
333                    lines.push(Line::from(std::mem::take(&mut current_line_spans)));
334                }
335                lines.push(Line::from(Span::styled("─".repeat(40), rule_style)));
336            },
337            Event::SoftBreak | Event::HardBreak => {
338                if !current_line_spans.is_empty() {
339                    lines.push(Line::from(std::mem::take(&mut current_line_spans)));
340                }
341            },
342            _ => {},
343        }
344    }
345
346    if !current_line_spans.is_empty() {
347        lines.push(Line::from(current_line_spans));
348    }
349
350    // A line is preformatted (no word-wrap) if it's a code-block line (tagged with
351    // the code background on its base style) or a table line (column-aligned).
352    lines
353        .into_iter()
354        .enumerate()
355        .map(|(i, line)| MarkdownLine {
356            preformatted: line.style.bg == Some(code_bg) || table_line_indices.contains(&i),
357            line,
358        })
359        .collect()
360}
361
362/// Render the accumulated table rows into aligned, themed lines that fit `width`
363/// display cells. Column widths come from content (CJK-safe, min 3); if the
364/// natural table is wider than `width`, the widest columns are shrunk and long
365/// cells are word-wrapped within their column — so nothing is lost and no row
366/// overflows the viewport.
367fn render_table(
368    lines: &mut Vec<Line<'static>>,
369    table_rows: &[Vec<String>],
370    table_header_len: usize,
371    theme: &Theme,
372    width: usize,
373) {
374    let c = &theme.colors;
375    let num_cols = table_rows.iter().map(|r| r.len()).max().unwrap_or(0);
376    if num_cols == 0 {
377        return;
378    }
379
380    // Natural column widths in DISPLAY CELLS (CJK-safe), min 3.
381    let mut col_widths = vec![0usize; num_cols];
382    for row in table_rows {
383        for (i, cell) in row.iter().enumerate() {
384            if i < num_cols {
385                col_widths[i] = col_widths[i].max(cell.width());
386            }
387        }
388    }
389    for w in &mut col_widths {
390        *w = (*w).max(3);
391    }
392
393    // Borders/padding cost: leading "| " (2) + " | " (3) per column. If the table
394    // is wider than the viewport, shrink the widest columns (each floored at 3)
395    // until it fits; cell text is then wrapped within the budgeted width.
396    let overhead = 2 + 3 * num_cols;
397    if col_widths.iter().sum::<usize>() + overhead > width {
398        let budget = width.saturating_sub(overhead).max(num_cols * 3);
399        let mut total: usize = col_widths.iter().sum();
400        while total > budget {
401            let widest = (0..num_cols)
402                .filter(|&i| col_widths[i] > 3)
403                .max_by_key(|&i| col_widths[i]);
404            match widest {
405                Some(i) => {
406                    col_widths[i] -= 1;
407                    total -= 1;
408                },
409                None => break, // every column already at the floor
410            }
411        }
412    }
413
414    let border_style = Style::default().fg(c.text_disabled.to_color());
415    let header_style = Style::default().fg(c.header.to_color()).bold();
416    let cell_style = Style::default().fg(c.text_primary.to_color());
417
418    for (row_idx, row) in table_rows.iter().enumerate() {
419        let style = if row_idx == 0 && table_header_len > 0 {
420            header_style
421        } else {
422            cell_style
423        };
424        // Wrap each cell to its column width; the row is as tall as its tallest cell.
425        let wrapped: Vec<Vec<String>> = (0..num_cols)
426            .map(|ci| {
427                wrap_cell(
428                    row.get(ci).map(String::as_str).unwrap_or(""),
429                    col_widths[ci],
430                )
431            })
432            .collect();
433        let row_height = wrapped.iter().map(Vec::len).max().unwrap_or(1).max(1);
434
435        for li in 0..row_height {
436            let mut spans = vec![Span::styled("| ", border_style)];
437            for ci in 0..num_cols {
438                let w = col_widths[ci];
439                let cell_line = wrapped[ci].get(li).map(String::as_str).unwrap_or("");
440                let padding = w.saturating_sub(cell_line.width());
441                let padded = format!("{}{}", cell_line, " ".repeat(padding));
442                spans.push(Span::styled(padded, style));
443                spans.push(Span::styled(" | ", border_style));
444            }
445            lines.push(Line::from(spans));
446        }
447
448        if row_idx == 0 && table_header_len > 0 {
449            let mut sep_spans = vec![Span::styled("|-", border_style)];
450            for &w in &col_widths {
451                sep_spans.push(Span::styled("-".repeat(w), border_style));
452                sep_spans.push(Span::styled("-|-", border_style));
453            }
454            lines.push(Line::from(sep_spans));
455        }
456    }
457
458    lines.push(Line::from(""));
459}
460
461/// Word-wrap `text` to `width` display cells, hard-breaking any word longer than
462/// the column. Always returns at least one (possibly empty) line.
463fn wrap_cell(text: &str, width: usize) -> Vec<String> {
464    if width == 0 {
465        return vec![String::new()];
466    }
467    let mut lines: Vec<String> = Vec::new();
468    let mut cur = String::new();
469    let mut cur_w = 0usize;
470    for word in text.split_whitespace() {
471        let ww = word.width();
472        if ww > width {
473            // A word too wide for the column: flush the current line, then
474            // hard-break the word; the final chunk stays open so the next word
475            // can continue after it.
476            if !cur.is_empty() {
477                lines.push(std::mem::take(&mut cur));
478                cur_w = 0;
479            }
480            let chunks = chunk_by_width(word, width);
481            let n = chunks.len();
482            for (k, chunk) in chunks.into_iter().enumerate() {
483                if k + 1 < n {
484                    lines.push(chunk);
485                } else {
486                    cur_w = chunk.width();
487                    cur = chunk;
488                }
489            }
490            continue;
491        }
492        let sep = usize::from(!cur.is_empty());
493        if cur_w + sep + ww > width {
494            lines.push(std::mem::take(&mut cur));
495            cur.push_str(word);
496            cur_w = ww;
497        } else {
498            if sep == 1 {
499                cur.push(' ');
500            }
501            cur.push_str(word);
502            cur_w += sep + ww;
503        }
504    }
505    if !cur.is_empty() || lines.is_empty() {
506        lines.push(cur);
507    }
508    lines
509}
510
511/// Split `s` into chunks each at most `width` display cells, never splitting a
512/// character. Used to hard-break a word longer than its column.
513fn chunk_by_width(s: &str, width: usize) -> Vec<String> {
514    let mut chunks: Vec<String> = Vec::new();
515    let mut cur = String::new();
516    let mut cur_w = 0usize;
517    for ch in s.chars() {
518        let cw = ch.width().unwrap_or(0);
519        if cur_w + cw > width && !cur.is_empty() {
520            chunks.push(std::mem::take(&mut cur));
521            cur_w = 0;
522        }
523        cur.push(ch);
524        cur_w += cw;
525    }
526    if !cur.is_empty() {
527        chunks.push(cur);
528    }
529    if chunks.is_empty() {
530        chunks.push(String::new());
531    }
532    chunks
533}
534
535/// Line-comment prefix(es) for a fenced-code language hint. Falls back to a
536/// permissive set so unknown languages still get comment coloring.
537fn line_comment_prefixes(lang: &str) -> &'static [&'static str] {
538    match lang.trim().to_ascii_lowercase().as_str() {
539        "rust" | "rs" | "c" | "cpp" | "c++" | "h" | "hpp" | "java" | "js" | "javascript" | "ts"
540        | "typescript" | "tsx" | "jsx" | "go" | "golang" | "swift" | "kotlin" | "kt" | "scala"
541        | "cs" | "csharp" | "php" | "dart" | "zig" | "rust,no_run" => &["//"],
542        "python" | "py" | "ruby" | "rb" | "sh" | "bash" | "zsh" | "shell" | "console" | "yaml"
543        | "yml" | "toml" | "ini" | "perl" | "pl" | "r" | "elixir" | "ex" | "makefile"
544        | "dockerfile" | "nix" => &["#"],
545        "sql" | "lua" | "haskell" | "hs" | "ada" => &["--"],
546        "lisp" | "clojure" | "clj" | "scheme" | "el" => &[";"],
547        _ => &["//", "#"],
548    }
549}
550
551/// Cross-language keyword set for the lightweight in-house highlighter.
552fn is_keyword(w: &str) -> bool {
553    matches!(
554        w,
555        "fn" | "let"
556            | "const"
557            | "mut"
558            | "pub"
559            | "struct"
560            | "enum"
561            | "impl"
562            | "trait"
563            | "use"
564            | "mod"
565            | "match"
566            | "if"
567            | "else"
568            | "for"
569            | "while"
570            | "loop"
571            | "return"
572            | "break"
573            | "continue"
574            | "async"
575            | "await"
576            | "move"
577            | "ref"
578            | "where"
579            | "type"
580            | "dyn"
581            | "as"
582            | "in"
583            | "static"
584            | "unsafe"
585            | "extern"
586            | "crate"
587            | "self"
588            | "Self"
589            | "super"
590            | "function"
591            | "var"
592            | "def"
593            | "class"
594            | "import"
595            | "from"
596            | "export"
597            | "default"
598            | "public"
599            | "private"
600            | "protected"
601            | "void"
602            | "int"
603            | "long"
604            | "float"
605            | "double"
606            | "bool"
607            | "boolean"
608            | "char"
609            | "string"
610            | "true"
611            | "false"
612            | "null"
613            | "nil"
614            | "None"
615            | "True"
616            | "False"
617            | "this"
618            | "new"
619            | "try"
620            | "catch"
621            | "finally"
622            | "throw"
623            | "throws"
624            | "package"
625            | "interface"
626            | "extends"
627            | "implements"
628            | "do"
629            | "then"
630            | "elif"
631            | "lambda"
632            | "yield"
633            | "with"
634            | "and"
635            | "or"
636            | "not"
637            | "is"
638            | "end"
639            | "begin"
640            | "val"
641            | "func"
642            | "defer"
643            | "select"
644            | "chan"
645            | "range"
646            | "switch"
647            | "case"
648    )
649}
650
651/// Tokenize one code line into styled spans (all sharing the code background)
652/// using a small, language-agnostic lexer: line comments, quoted strings, and
653/// a cross-language keyword set. Everything else is the default code color.
654fn highlight_code_line(text: &str, comment_prefixes: &[&str], theme: &Theme) -> Vec<Span<'static>> {
655    let c = &theme.colors;
656    let bg = c.code_background.to_color();
657    let base = Style::default().fg(c.code_foreground.to_color()).bg(bg);
658    let kw_style = Style::default().fg(c.code_keyword.to_color()).bg(bg);
659    let str_style = Style::default().fg(c.code_string.to_color()).bg(bg);
660    let com_style = Style::default().fg(c.code_comment.to_color()).bg(bg);
661
662    let mut spans: Vec<Span<'static>> = Vec::new();
663    let mut pending = String::new();
664    let flush = |spans: &mut Vec<Span<'static>>, pending: &mut String| {
665        if !pending.is_empty() {
666            spans.push(Span::styled(std::mem::take(pending), base));
667        }
668    };
669
670    let mut it = text.char_indices().peekable();
671    while let Some(&(byte_idx, ch)) = it.peek() {
672        // Line comment → rest of the line.
673        if comment_prefixes
674            .iter()
675            .any(|p| text[byte_idx..].starts_with(p))
676        {
677            flush(&mut spans, &mut pending);
678            spans.push(Span::styled(text[byte_idx..].to_string(), com_style));
679            break;
680        }
681        // String literal.
682        if ch == '"' || ch == '\'' || ch == '`' {
683            flush(&mut spans, &mut pending);
684            let quote = ch;
685            let start = byte_idx;
686            it.next(); // opening quote
687            let mut end = text.len();
688            let mut escaped = false;
689            while let Some(&(bi, ci)) = it.peek() {
690                it.next();
691                end = bi + ci.len_utf8();
692                if escaped {
693                    escaped = false;
694                } else if ci == '\\' {
695                    escaped = true;
696                } else if ci == quote {
697                    break;
698                }
699            }
700            spans.push(Span::styled(text[start..end].to_string(), str_style));
701            continue;
702        }
703        // Identifier / keyword.
704        if ch.is_alphanumeric() || ch == '_' {
705            let start = byte_idx;
706            let mut end = byte_idx + ch.len_utf8();
707            it.next();
708            while let Some(&(bi, ci)) = it.peek() {
709                if ci.is_alphanumeric() || ci == '_' {
710                    end = bi + ci.len_utf8();
711                    it.next();
712                } else {
713                    break;
714                }
715            }
716            let word = &text[start..end];
717            if is_keyword(word) {
718                flush(&mut spans, &mut pending);
719                spans.push(Span::styled(word.to_string(), kw_style));
720            } else {
721                pending.push_str(word);
722            }
723            continue;
724        }
725        // Anything else (whitespace, punctuation) → default run.
726        pending.push(ch);
727        it.next();
728    }
729    flush(&mut spans, &mut pending);
730    if spans.is_empty() {
731        spans.push(Span::styled(String::new(), base));
732    }
733    spans
734}
735
736#[cfg(test)]
737mod tests {
738    use super::*;
739
740    /// Parse with the dark theme at a typical width, returning the bare lines
741    /// (most tests here assert on text/structure, not the preformatted flag).
742    fn md(input: &str) -> Vec<Line<'static>> {
743        parse_markdown(input, &Theme::dark(), 80)
744            .into_iter()
745            .map(|ml| ml.line)
746            .collect()
747    }
748
749    /// Flatten all spans in all lines into a single string.
750    fn lines_to_text(lines: &[Line]) -> String {
751        lines
752            .iter()
753            .map(|line| {
754                line.spans
755                    .iter()
756                    .map(|s| s.content.as_ref())
757                    .collect::<String>()
758            })
759            .collect::<Vec<_>>()
760            .join("\n")
761    }
762
763    #[test]
764    fn test_plain_text() {
765        let lines = md("Hello, world!");
766        assert!(!lines.is_empty());
767        assert!(lines_to_text(&lines).contains("Hello, world!"));
768    }
769
770    #[test]
771    fn test_heading_levels() {
772        let lines = md("# H1\n## H2\n### H3");
773        let text = lines_to_text(&lines);
774        assert!(text.contains("H1"));
775        assert!(text.contains("H2"));
776        assert!(text.contains("H3"));
777        assert!(lines.len() >= 3);
778    }
779
780    #[test]
781    fn line_hanging_indent_aligns_under_list_marker() {
782        let theme = Theme::dark();
783        fn find<'a>(lines: &'a [Line<'static>], needle: &str) -> &'a Line<'static> {
784            lines
785                .iter()
786                .find(|l| lines_to_text(std::slice::from_ref(l)).contains(needle))
787                .expect("line present")
788        }
789
790        // Bulleted item: continuations hang under the text after "• "
791        // (2-cell nesting indent + 2-cell marker).
792        let bullet = md("- Alpha item");
793        assert_eq!(
794            line_hanging_indent(find(&bullet, "Alpha"), &theme),
795            4,
796            "bullet: 2 indent + 2 marker"
797        );
798
799        // Numbered item: the marker "1. " is 3 cells wide.
800        let numbered = md("1. First item");
801        assert_eq!(
802            line_hanging_indent(find(&numbered, "First"), &theme),
803            5,
804            "numbered: 2 indent + 3 marker"
805        );
806
807        // Ordinary paragraph: no marker, no leading indent, so no hang.
808        let para = md("Just a sentence.");
809        assert_eq!(
810            line_hanging_indent(find(&para, "sentence"), &theme),
811            0,
812            "paragraph: flush to the gutter"
813        );
814    }
815
816    #[test]
817    fn test_code_block() {
818        let lines = md("```rust\nfn main() {}\n```");
819        let text = lines_to_text(&lines);
820        assert!(text.contains("fn main() {}"));
821        assert!(text.contains("rust"));
822    }
823
824    #[test]
825    fn code_block_lines_tagged_with_code_background() {
826        let lines = md("```rust\nfn main() {}\n```");
827        let code_bg = Theme::dark().colors.code_background.to_color();
828        // The line carrying the code body must be flagged via its base style
829        // background (this is what the chat renderer keys off to skip wrap).
830        assert!(
831            lines.iter().any(|l| l.style.bg == Some(code_bg)
832                && l.spans
833                    .iter()
834                    .map(|s| s.content.as_ref())
835                    .collect::<String>()
836                    .contains("fn main")),
837            "code body line must carry the code_background marker"
838        );
839    }
840
841    #[test]
842    fn code_block_highlights_keywords() {
843        let lines = md("```rust\nfn main() {}\n```");
844        let kw = Theme::dark().colors.code_keyword.to_color();
845        // "fn" should be styled with the keyword color.
846        let fn_styled_as_keyword = lines.iter().any(|l| {
847            l.spans
848                .iter()
849                .any(|s| s.content.as_ref() == "fn" && s.style.fg == Some(kw))
850        });
851        assert!(
852            fn_styled_as_keyword,
853            "`fn` should be highlighted as a keyword"
854        );
855    }
856
857    #[test]
858    fn code_block_preserves_indentation() {
859        let lines = md("```rust\n    indented();\n```");
860        // The leading 4 spaces must survive (no whitespace collapse).
861        assert!(
862            lines.iter().any(|l| l
863                .spans
864                .iter()
865                .map(|s| s.content.as_ref())
866                .collect::<String>()
867                .starts_with("    indented")),
868            "code indentation must be preserved verbatim"
869        );
870    }
871
872    #[test]
873    fn test_code_block_no_lang() {
874        let lines = md("```\nsome code\n```");
875        assert!(lines_to_text(&lines).contains("some code"));
876    }
877
878    #[test]
879    fn test_inline_code_has_no_padding() {
880        let lines = md("Use `cargo build` to compile");
881        let code_bg = Theme::dark().colors.code_background.to_color();
882        // The inline-code span must be exactly "cargo build" — not the old
883        // " cargo build " with padding spaces baked into the highlight.
884        let tight = lines.iter().any(|l| {
885            l.spans
886                .iter()
887                .any(|s| s.style.bg == Some(code_bg) && s.content.as_ref() == "cargo build")
888        });
889        assert!(
890            tight,
891            "inline code should be tight (no surrounding padding spaces)"
892        );
893    }
894
895    #[test]
896    fn test_unordered_list() {
897        let lines = md("- Item 1\n- Item 2\n- Item 3");
898        let text = lines_to_text(&lines);
899        assert!(text.contains("Item 1"));
900        assert!(text.contains("•"));
901    }
902
903    #[test]
904    fn test_ordered_list_preserves_numbers() {
905        let lines = md("1. First\n2. Second\n3. Third");
906        let text = lines_to_text(&lines);
907        assert!(text.contains("1. First"));
908        assert!(text.contains("2. Second"));
909        assert!(!text.contains("• First"));
910    }
911
912    #[test]
913    fn loose_list_item_body_hangs_under_item_text() {
914        // A 2nd+ paragraph inside a list item must align under the item's text
915        // (hanging indent), not fall back flush to column 0.
916        let lines = md("- **Finding** — verified\n\n  Body paragraph explaining the finding.");
917        let rendered: Vec<String> = lines
918            .iter()
919            .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
920            .collect();
921        assert!(
922            rendered
923                .iter()
924                .any(|l| l.starts_with("  • ") && l.contains("Finding")),
925            "marker line should carry the bullet + indent"
926        );
927        let body = rendered
928            .iter()
929            .find(|l| l.contains("Body paragraph"))
930            .expect("body line present");
931        // 4 cols of hanging indent: 2 (depth) + 2 ("• " marker width), aligning
932        // the body under the item text rather than flush at column 0.
933        assert_eq!(
934            body, "    Body paragraph explaining the finding.",
935            "continuation paragraph must hang-indent under the item text"
936        );
937    }
938
939    #[test]
940    fn test_nested_list() {
941        let lines = md("- Outer\n  - Inner");
942        let text = lines_to_text(&lines);
943        assert!(text.contains("Outer"));
944        assert!(text.contains("Inner"));
945    }
946
947    #[test]
948    fn test_bold_and_italic() {
949        let lines = md("**bold** and *italic*");
950        let text = lines_to_text(&lines);
951        assert!(text.contains("bold"));
952        assert!(text.contains("italic"));
953    }
954
955    #[test]
956    fn test_link_shows_text_and_url() {
957        let lines = md("[click here](https://example.com)");
958        let text = lines_to_text(&lines);
959        assert!(text.contains("click here"));
960        // The destination is appended (dimmed) so the user can see where it goes.
961        assert!(text.contains("https://example.com"));
962    }
963
964    #[test]
965    fn test_autolink_does_not_duplicate_url() {
966        // When the visible text already is the URL, don't append it twice.
967        let lines = md("<https://example.com>");
968        let text = lines_to_text(&lines);
969        assert_eq!(text.matches("https://example.com").count(), 1);
970    }
971
972    #[test]
973    fn test_blockquote() {
974        let lines = md("> Quoted text");
975        let text = lines_to_text(&lines);
976        assert!(text.contains("Quoted text"));
977        assert!(text.contains("│"));
978    }
979
980    #[test]
981    fn test_horizontal_rule() {
982        let lines = md("above\n\n---\n\nbelow");
983        let text = lines_to_text(&lines);
984        assert!(text.contains("above"));
985        assert!(text.contains("below"));
986        // The rule renders as a run of box-drawing dashes.
987        assert!(text.contains("───"), "thematic break should render a rule");
988    }
989
990    #[test]
991    fn test_table() {
992        let lines = md("| Header1 | Header2 |\n|---------|--------|\n| Cell1   | Cell2  |");
993        let text = lines_to_text(&lines);
994        assert!(text.contains("Header1"));
995        assert!(text.contains("Cell1"));
996        assert!(text.contains("|"));
997    }
998
999    #[test]
1000    fn test_strikethrough() {
1001        let lines = md("~~deleted~~");
1002        assert!(lines_to_text(&lines).contains("deleted"));
1003    }
1004
1005    #[test]
1006    fn test_empty_input() {
1007        assert!(md("").is_empty());
1008    }
1009
1010    #[test]
1011    fn test_multiple_paragraphs() {
1012        let lines = md("Paragraph 1\n\nParagraph 2");
1013        let text = lines_to_text(&lines);
1014        assert!(text.contains("Paragraph 1"));
1015        assert!(text.contains("Paragraph 2"));
1016    }
1017
1018    #[test]
1019    fn highlight_code_line_marks_strings_and_comments() {
1020        let theme = Theme::dark();
1021        let spans = highlight_code_line("let s = \"hi\"; // note", &["//"], &theme);
1022        let str_color = theme.colors.code_string.to_color();
1023        let com_color = theme.colors.code_comment.to_color();
1024        assert!(
1025            spans
1026                .iter()
1027                .any(|s| s.content.contains("\"hi\"") && s.style.fg == Some(str_color)),
1028            "string literal must use the string color"
1029        );
1030        assert!(
1031            spans
1032                .iter()
1033                .any(|s| s.content.contains("// note") && s.style.fg == Some(com_color)),
1034            "trailing comment must use the comment color"
1035        );
1036    }
1037
1038    /// Tables with CJK cells align because column widths are display-cell
1039    /// based, not byte based.
1040    #[test]
1041    fn table_column_widths_use_display_cells() {
1042        let lines = md("| Name | Score |\n|------|-------|\n| 你好 | 100   |\n| ab   | 50    |");
1043        let mut cjk_row_width = 0usize;
1044        let mut ascii_row_width = 0usize;
1045        for line in &lines {
1046            let rendered: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
1047            if rendered.contains("你好") {
1048                cjk_row_width = rendered.width();
1049            } else if rendered.contains("ab") && rendered.contains("|") {
1050                ascii_row_width = rendered.width();
1051            }
1052        }
1053        assert!(cjk_row_width > 0, "did not find the CJK body row");
1054        assert!(ascii_row_width > 0, "did not find the ASCII body row");
1055        assert_eq!(
1056            cjk_row_width, ascii_row_width,
1057            "CJK and ASCII rows must have equal display width to align"
1058        );
1059    }
1060
1061    #[test]
1062    fn table_lines_flagged_preformatted_prose_is_not() {
1063        // Table rows must be flagged preformatted so the chat renderer doesn't
1064        // word-wrap them (which would collapse the column padding); prose must not.
1065        let out = parse_markdown(
1066            "Intro paragraph.\n\n| A | B |\n|---|---|\n| 1 | 2 |",
1067            &Theme::dark(),
1068            80,
1069        );
1070        let para = out
1071            .iter()
1072            .find(|ml| ml.line.spans.iter().any(|s| s.content.contains("Intro")))
1073            .expect("paragraph present");
1074        assert!(!para.preformatted, "prose must word-wrap normally");
1075        let table_rows: Vec<_> = out
1076            .iter()
1077            .filter(|ml| {
1078                ml.line
1079                    .spans
1080                    .first()
1081                    .is_some_and(|s| s.content.starts_with('|'))
1082            })
1083            .collect();
1084        assert!(!table_rows.is_empty(), "table should render rows");
1085        assert!(
1086            table_rows.iter().all(|ml| ml.preformatted),
1087            "every table line must be preformatted"
1088        );
1089    }
1090
1091    #[test]
1092    fn code_lines_flagged_preformatted() {
1093        let out = parse_markdown("```\nlet x = 1;\n```", &Theme::dark(), 80);
1094        assert!(
1095            out.iter()
1096                .filter(|ml| ml.line.spans.iter().any(|s| s.content.contains("let x")))
1097                .all(|ml| ml.preformatted),
1098            "code-block lines must be preformatted"
1099        );
1100    }
1101
1102    #[test]
1103    fn wide_table_wraps_cells_to_fit() {
1104        // A table wider than the viewport wraps cell text within columns rather
1105        // than overflowing. Every rendered table line must fit `width`, and no
1106        // cell content is lost.
1107        let width = 30;
1108        let out = parse_markdown(
1109            "| Item | Detail |\n|------|--------|\n| one | a very long cell that cannot fit on a single line at this width |",
1110            &Theme::dark(),
1111            width,
1112        );
1113        let mut saw_table = false;
1114        for ml in &out {
1115            let rendered: String = ml.line.spans.iter().map(|s| s.content.as_ref()).collect();
1116            if rendered.starts_with('|') {
1117                saw_table = true;
1118                assert!(
1119                    rendered.width() <= width,
1120                    "table line must fit width {width}, got {} for {rendered:?}",
1121                    rendered.width()
1122                );
1123            }
1124        }
1125        assert!(saw_table, "table should have rendered");
1126        // No content lost: every word of the long cell appears across the wraps.
1127        let all: String = out
1128            .iter()
1129            .map(|ml| {
1130                ml.line
1131                    .spans
1132                    .iter()
1133                    .map(|s| s.content.as_ref())
1134                    .collect::<String>()
1135            })
1136            .collect::<Vec<_>>()
1137            .join(" ");
1138        for word in ["very", "long", "cell", "cannot", "single", "width"] {
1139            assert!(all.contains(word), "wrapped table lost the word {word:?}");
1140        }
1141    }
1142}