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                    // Every block-level close flushes the pending inline spans
241                    // as one finished line.
242                    TagEnd::Heading(_)
243                    | TagEnd::Paragraph
244                    | TagEnd::Item
245                    | TagEnd::BlockQuote(_)
246                        if !current_line_spans.is_empty() =>
247                    {
248                        lines.push(Line::from(std::mem::take(&mut current_line_spans)));
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                    _ => {},
303                }
304            },
305            Event::Text(text) => {
306                if in_code_block {
307                    code_block_content.push_str(&text);
308                } else if in_table {
309                    current_cell.push_str(&text);
310                } else {
311                    let style = style_stack.last().copied().unwrap_or_default();
312                    current_line_spans.push(Span::styled(text.to_string(), style));
313                }
314            },
315            Event::Code(code) => {
316                if in_table {
317                    current_cell.push_str(&code);
318                } else {
319                    // Inline code: tight (no padding spaces), code colors. The
320                    // background lives on the SPAN only — prose lines with
321                    // inline code still word-wrap normally.
322                    let style = Style::default().fg(code_fg).bg(code_bg);
323                    current_line_spans.push(Span::styled(code.to_string(), style));
324                }
325            },
326            Event::Rule => {
327                if !current_line_spans.is_empty() {
328                    lines.push(Line::from(std::mem::take(&mut current_line_spans)));
329                }
330                lines.push(Line::from(Span::styled("─".repeat(40), rule_style)));
331            },
332            Event::SoftBreak | Event::HardBreak if !current_line_spans.is_empty() => {
333                lines.push(Line::from(std::mem::take(&mut current_line_spans)));
334            },
335            _ => {},
336        }
337    }
338
339    if !current_line_spans.is_empty() {
340        lines.push(Line::from(current_line_spans));
341    }
342
343    // A line is preformatted (no word-wrap) if it's a code-block line (tagged with
344    // the code background on its base style) or a table line (column-aligned).
345    lines
346        .into_iter()
347        .enumerate()
348        .map(|(i, line)| MarkdownLine {
349            preformatted: line.style.bg == Some(code_bg) || table_line_indices.contains(&i),
350            line,
351        })
352        .collect()
353}
354
355/// Render the accumulated table rows into aligned, themed lines that fit `width`
356/// display cells. Column widths come from content (CJK-safe, min 3); if the
357/// natural table is wider than `width`, the widest columns are shrunk and long
358/// cells are word-wrapped within their column — so nothing is lost and no row
359/// overflows the viewport.
360fn render_table(
361    lines: &mut Vec<Line<'static>>,
362    table_rows: &[Vec<String>],
363    table_header_len: usize,
364    theme: &Theme,
365    width: usize,
366) {
367    let c = &theme.colors;
368    let num_cols = table_rows.iter().map(|r| r.len()).max().unwrap_or(0);
369    if num_cols == 0 {
370        return;
371    }
372
373    // Natural column widths in DISPLAY CELLS (CJK-safe), min 3.
374    let mut col_widths = vec![0usize; num_cols];
375    for row in table_rows {
376        for (i, cell) in row.iter().enumerate() {
377            if i < num_cols {
378                col_widths[i] = col_widths[i].max(cell.width());
379            }
380        }
381    }
382    for w in &mut col_widths {
383        *w = (*w).max(3);
384    }
385
386    // Borders/padding cost: leading "| " (2) + " | " (3) per column. If the table
387    // is wider than the viewport, shrink the widest columns until it fits; cell
388    // text is then wrapped within the budgeted width. Columns shrink all the way
389    // to a 1-cell minimum on a narrow terminal (no `num_cols * 3` budget floor),
390    // so a many-column table fits instead of overflowing and clipping at the edge.
391    // (In the extreme where the per-column border overhead alone exceeds the
392    // width — more columns than the terminal has cells — nothing fits in-budget
393    // and the terminal clips the row; that's unavoidable without dropping columns.)
394    let overhead = 2 + 3 * num_cols;
395    if col_widths.iter().sum::<usize>() + overhead > width {
396        let budget = width.saturating_sub(overhead);
397        let mut total: usize = col_widths.iter().sum();
398        while total > budget {
399            let widest = (0..num_cols)
400                .filter(|&i| col_widths[i] > 1)
401                .max_by_key(|&i| col_widths[i]);
402            match widest {
403                Some(i) => {
404                    col_widths[i] -= 1;
405                    total -= 1;
406                },
407                None => break, // every column already at the 1-cell floor
408            }
409        }
410    }
411
412    let border_style = Style::default().fg(c.text_disabled.to_color());
413    let header_style = Style::default().fg(c.header.to_color()).bold();
414    let cell_style = Style::default().fg(c.text_primary.to_color());
415
416    for (row_idx, row) in table_rows.iter().enumerate() {
417        let style = if row_idx == 0 && table_header_len > 0 {
418            header_style
419        } else {
420            cell_style
421        };
422        // Wrap each cell to its column width; the row is as tall as its tallest cell.
423        let wrapped: Vec<Vec<String>> = (0..num_cols)
424            .map(|ci| {
425                wrap_cell(
426                    row.get(ci).map(String::as_str).unwrap_or(""),
427                    col_widths[ci],
428                )
429            })
430            .collect();
431        let row_height = wrapped.iter().map(Vec::len).max().unwrap_or(1).max(1);
432
433        for li in 0..row_height {
434            let mut spans = vec![Span::styled("| ", border_style)];
435            for ci in 0..num_cols {
436                let w = col_widths[ci];
437                let cell_line = wrapped[ci].get(li).map(String::as_str).unwrap_or("");
438                let padding = w.saturating_sub(cell_line.width());
439                let padded = format!("{}{}", cell_line, " ".repeat(padding));
440                spans.push(Span::styled(padded, style));
441                spans.push(Span::styled(" | ", border_style));
442            }
443            lines.push(Line::from(spans));
444        }
445
446        if row_idx == 0 && table_header_len > 0 {
447            let mut sep_spans = vec![Span::styled("|-", border_style)];
448            for &w in &col_widths {
449                sep_spans.push(Span::styled("-".repeat(w), border_style));
450                sep_spans.push(Span::styled("-|-", border_style));
451            }
452            lines.push(Line::from(sep_spans));
453        }
454    }
455
456    lines.push(Line::from(""));
457}
458
459/// Word-wrap `text` to `width` display cells, hard-breaking any word longer than
460/// the column. Always returns at least one (possibly empty) line.
461fn wrap_cell(text: &str, width: usize) -> Vec<String> {
462    if width == 0 {
463        return vec![String::new()];
464    }
465    let mut lines: Vec<String> = Vec::new();
466    let mut cur = String::new();
467    let mut cur_w = 0usize;
468    for word in text.split_whitespace() {
469        let ww = word.width();
470        if ww > width {
471            // A word too wide for the column: flush the current line, then
472            // hard-break the word; the final chunk stays open so the next word
473            // can continue after it.
474            if !cur.is_empty() {
475                lines.push(std::mem::take(&mut cur));
476                cur_w = 0;
477            }
478            let chunks = chunk_by_width(word, width);
479            let n = chunks.len();
480            for (k, chunk) in chunks.into_iter().enumerate() {
481                if k + 1 < n {
482                    lines.push(chunk);
483                } else {
484                    cur_w = chunk.width();
485                    cur = chunk;
486                }
487            }
488            continue;
489        }
490        let sep = usize::from(!cur.is_empty());
491        if cur_w + sep + ww > width {
492            lines.push(std::mem::take(&mut cur));
493            cur.push_str(word);
494            cur_w = ww;
495        } else {
496            if sep == 1 {
497                cur.push(' ');
498            }
499            cur.push_str(word);
500            cur_w += sep + ww;
501        }
502    }
503    if !cur.is_empty() || lines.is_empty() {
504        lines.push(cur);
505    }
506    lines
507}
508
509/// Split `s` into chunks each at most `width` display cells, never splitting a
510/// character. Used to hard-break a word longer than its column.
511fn chunk_by_width(s: &str, width: usize) -> Vec<String> {
512    let mut chunks: Vec<String> = Vec::new();
513    let mut cur = String::new();
514    let mut cur_w = 0usize;
515    for ch in s.chars() {
516        let cw = ch.width().unwrap_or(0);
517        if cur_w + cw > width && !cur.is_empty() {
518            chunks.push(std::mem::take(&mut cur));
519            cur_w = 0;
520        }
521        cur.push(ch);
522        cur_w += cw;
523    }
524    if !cur.is_empty() {
525        chunks.push(cur);
526    }
527    if chunks.is_empty() {
528        chunks.push(String::new());
529    }
530    chunks
531}
532
533/// Line-comment prefix(es) for a fenced-code language hint. Falls back to a
534/// permissive set so unknown languages still get comment coloring.
535fn line_comment_prefixes(lang: &str) -> &'static [&'static str] {
536    match lang.trim().to_ascii_lowercase().as_str() {
537        "rust" | "rs" | "c" | "cpp" | "c++" | "h" | "hpp" | "java" | "js" | "javascript" | "ts"
538        | "typescript" | "tsx" | "jsx" | "go" | "golang" | "swift" | "kotlin" | "kt" | "scala"
539        | "cs" | "csharp" | "php" | "dart" | "zig" | "rust,no_run" => &["//"],
540        "python" | "py" | "ruby" | "rb" | "sh" | "bash" | "zsh" | "shell" | "console" | "yaml"
541        | "yml" | "toml" | "ini" | "perl" | "pl" | "r" | "elixir" | "ex" | "makefile"
542        | "dockerfile" | "nix" => &["#"],
543        "sql" | "lua" | "haskell" | "hs" | "ada" => &["--"],
544        "lisp" | "clojure" | "clj" | "scheme" | "el" => &[";"],
545        _ => &["//", "#"],
546    }
547}
548
549/// Cross-language keyword set for the lightweight in-house highlighter.
550fn is_keyword(w: &str) -> bool {
551    matches!(
552        w,
553        "fn" | "let"
554            | "const"
555            | "mut"
556            | "pub"
557            | "struct"
558            | "enum"
559            | "impl"
560            | "trait"
561            | "use"
562            | "mod"
563            | "match"
564            | "if"
565            | "else"
566            | "for"
567            | "while"
568            | "loop"
569            | "return"
570            | "break"
571            | "continue"
572            | "async"
573            | "await"
574            | "move"
575            | "ref"
576            | "where"
577            | "type"
578            | "dyn"
579            | "as"
580            | "in"
581            | "static"
582            | "unsafe"
583            | "extern"
584            | "crate"
585            | "self"
586            | "Self"
587            | "super"
588            | "function"
589            | "var"
590            | "def"
591            | "class"
592            | "import"
593            | "from"
594            | "export"
595            | "default"
596            | "public"
597            | "private"
598            | "protected"
599            | "void"
600            | "int"
601            | "long"
602            | "float"
603            | "double"
604            | "bool"
605            | "boolean"
606            | "char"
607            | "string"
608            | "true"
609            | "false"
610            | "null"
611            | "nil"
612            | "None"
613            | "True"
614            | "False"
615            | "this"
616            | "new"
617            | "try"
618            | "catch"
619            | "finally"
620            | "throw"
621            | "throws"
622            | "package"
623            | "interface"
624            | "extends"
625            | "implements"
626            | "do"
627            | "then"
628            | "elif"
629            | "lambda"
630            | "yield"
631            | "with"
632            | "and"
633            | "or"
634            | "not"
635            | "is"
636            | "end"
637            | "begin"
638            | "val"
639            | "func"
640            | "defer"
641            | "select"
642            | "chan"
643            | "range"
644            | "switch"
645            | "case"
646    )
647}
648
649/// Tokenize one code line into styled spans (all sharing the code background)
650/// using a small, language-agnostic lexer: line comments, quoted strings, and
651/// a cross-language keyword set. Everything else is the default code color.
652fn highlight_code_line(text: &str, comment_prefixes: &[&str], theme: &Theme) -> Vec<Span<'static>> {
653    let c = &theme.colors;
654    let bg = c.code_background.to_color();
655    let base = Style::default().fg(c.code_foreground.to_color()).bg(bg);
656    let kw_style = Style::default().fg(c.code_keyword.to_color()).bg(bg);
657    let str_style = Style::default().fg(c.code_string.to_color()).bg(bg);
658    let com_style = Style::default().fg(c.code_comment.to_color()).bg(bg);
659
660    let mut spans: Vec<Span<'static>> = Vec::new();
661    let mut pending = String::new();
662    let flush = |spans: &mut Vec<Span<'static>>, pending: &mut String| {
663        if !pending.is_empty() {
664            spans.push(Span::styled(std::mem::take(pending), base));
665        }
666    };
667
668    let mut it = text.char_indices().peekable();
669    while let Some(&(byte_idx, ch)) = it.peek() {
670        // Line comment → rest of the line.
671        if comment_prefixes
672            .iter()
673            .any(|p| text[byte_idx..].starts_with(p))
674        {
675            flush(&mut spans, &mut pending);
676            spans.push(Span::styled(text[byte_idx..].to_string(), com_style));
677            break;
678        }
679        // String literal.
680        if ch == '"' || ch == '\'' || ch == '`' {
681            flush(&mut spans, &mut pending);
682            let quote = ch;
683            let start = byte_idx;
684            it.next(); // opening quote
685            let mut end = text.len();
686            let mut escaped = false;
687            while let Some(&(bi, ci)) = it.peek() {
688                it.next();
689                end = bi + ci.len_utf8();
690                if escaped {
691                    escaped = false;
692                } else if ci == '\\' {
693                    escaped = true;
694                } else if ci == quote {
695                    break;
696                }
697            }
698            spans.push(Span::styled(text[start..end].to_string(), str_style));
699            continue;
700        }
701        // Identifier / keyword.
702        if ch.is_alphanumeric() || ch == '_' {
703            let start = byte_idx;
704            let mut end = byte_idx + ch.len_utf8();
705            it.next();
706            while let Some(&(bi, ci)) = it.peek() {
707                if ci.is_alphanumeric() || ci == '_' {
708                    end = bi + ci.len_utf8();
709                    it.next();
710                } else {
711                    break;
712                }
713            }
714            let word = &text[start..end];
715            if is_keyword(word) {
716                flush(&mut spans, &mut pending);
717                spans.push(Span::styled(word.to_string(), kw_style));
718            } else {
719                pending.push_str(word);
720            }
721            continue;
722        }
723        // Anything else (whitespace, punctuation) → default run.
724        pending.push(ch);
725        it.next();
726    }
727    flush(&mut spans, &mut pending);
728    if spans.is_empty() {
729        spans.push(Span::styled(String::new(), base));
730    }
731    spans
732}
733
734#[cfg(test)]
735mod tests {
736    use super::*;
737
738    /// Parse with the dark theme at a typical width, returning the bare lines
739    /// (most tests here assert on text/structure, not the preformatted flag).
740    fn md(input: &str) -> Vec<Line<'static>> {
741        parse_markdown(input, &Theme::dark(), 80)
742            .into_iter()
743            .map(|ml| ml.line)
744            .collect()
745    }
746
747    /// Flatten all spans in all lines into a single string.
748    fn lines_to_text(lines: &[Line]) -> String {
749        lines
750            .iter()
751            .map(|line| {
752                line.spans
753                    .iter()
754                    .map(|s| s.content.as_ref())
755                    .collect::<String>()
756            })
757            .collect::<Vec<_>>()
758            .join("\n")
759    }
760
761    #[test]
762    fn wide_table_fits_narrow_viewport() {
763        // #136: a 3-column table whose natural width far exceeds a narrow
764        // viewport must shrink to fit, not overflow and clip at the edge.
765        let width = 16;
766        let lines = parse_markdown(
767            "| aaaa | bbbb | cccc |\n|---|---|---|\n| aaaaaaaa | bbbbbbbb | cccccccc |\n",
768            &Theme::dark(),
769            width,
770        );
771        for ml in &lines {
772            let w: usize = ml.line.spans.iter().map(|s| s.content.width()).sum();
773            assert!(w <= width, "table row width {w} exceeds viewport {width}");
774        }
775    }
776
777    #[test]
778    fn test_plain_text() {
779        let lines = md("Hello, world!");
780        assert!(!lines.is_empty());
781        assert!(lines_to_text(&lines).contains("Hello, world!"));
782    }
783
784    #[test]
785    fn test_heading_levels() {
786        let lines = md("# H1\n## H2\n### H3");
787        let text = lines_to_text(&lines);
788        assert!(text.contains("H1"));
789        assert!(text.contains("H2"));
790        assert!(text.contains("H3"));
791        assert!(lines.len() >= 3);
792    }
793
794    #[test]
795    fn line_hanging_indent_aligns_under_list_marker() {
796        let theme = Theme::dark();
797        fn find<'a>(lines: &'a [Line<'static>], needle: &str) -> &'a Line<'static> {
798            lines
799                .iter()
800                .find(|l| lines_to_text(std::slice::from_ref(l)).contains(needle))
801                .expect("line present")
802        }
803
804        // Bulleted item: continuations hang under the text after "• "
805        // (2-cell nesting indent + 2-cell marker).
806        let bullet = md("- Alpha item");
807        assert_eq!(
808            line_hanging_indent(find(&bullet, "Alpha"), &theme),
809            4,
810            "bullet: 2 indent + 2 marker"
811        );
812
813        // Numbered item: the marker "1. " is 3 cells wide.
814        let numbered = md("1. First item");
815        assert_eq!(
816            line_hanging_indent(find(&numbered, "First"), &theme),
817            5,
818            "numbered: 2 indent + 3 marker"
819        );
820
821        // Ordinary paragraph: no marker, no leading indent, so no hang.
822        let para = md("Just a sentence.");
823        assert_eq!(
824            line_hanging_indent(find(&para, "sentence"), &theme),
825            0,
826            "paragraph: flush to the gutter"
827        );
828    }
829
830    #[test]
831    fn test_code_block() {
832        let lines = md("```rust\nfn main() {}\n```");
833        let text = lines_to_text(&lines);
834        assert!(text.contains("fn main() {}"));
835        assert!(text.contains("rust"));
836    }
837
838    #[test]
839    fn code_block_lines_tagged_with_code_background() {
840        let lines = md("```rust\nfn main() {}\n```");
841        let code_bg = Theme::dark().colors.code_background.to_color();
842        // The line carrying the code body must be flagged via its base style
843        // background (this is what the chat renderer keys off to skip wrap).
844        assert!(
845            lines.iter().any(|l| l.style.bg == Some(code_bg)
846                && l.spans
847                    .iter()
848                    .map(|s| s.content.as_ref())
849                    .collect::<String>()
850                    .contains("fn main")),
851            "code body line must carry the code_background marker"
852        );
853    }
854
855    #[test]
856    fn code_block_highlights_keywords() {
857        let lines = md("```rust\nfn main() {}\n```");
858        let kw = Theme::dark().colors.code_keyword.to_color();
859        // "fn" should be styled with the keyword color.
860        let fn_styled_as_keyword = lines.iter().any(|l| {
861            l.spans
862                .iter()
863                .any(|s| s.content.as_ref() == "fn" && s.style.fg == Some(kw))
864        });
865        assert!(
866            fn_styled_as_keyword,
867            "`fn` should be highlighted as a keyword"
868        );
869    }
870
871    #[test]
872    fn code_block_preserves_indentation() {
873        let lines = md("```rust\n    indented();\n```");
874        // The leading 4 spaces must survive (no whitespace collapse).
875        assert!(
876            lines.iter().any(|l| l
877                .spans
878                .iter()
879                .map(|s| s.content.as_ref())
880                .collect::<String>()
881                .starts_with("    indented")),
882            "code indentation must be preserved verbatim"
883        );
884    }
885
886    #[test]
887    fn test_code_block_no_lang() {
888        let lines = md("```\nsome code\n```");
889        assert!(lines_to_text(&lines).contains("some code"));
890    }
891
892    #[test]
893    fn test_inline_code_has_no_padding() {
894        let lines = md("Use `cargo build` to compile");
895        let code_bg = Theme::dark().colors.code_background.to_color();
896        // The inline-code span must be exactly "cargo build" — not the old
897        // " cargo build " with padding spaces baked into the highlight.
898        let tight = lines.iter().any(|l| {
899            l.spans
900                .iter()
901                .any(|s| s.style.bg == Some(code_bg) && s.content.as_ref() == "cargo build")
902        });
903        assert!(
904            tight,
905            "inline code should be tight (no surrounding padding spaces)"
906        );
907    }
908
909    #[test]
910    fn test_unordered_list() {
911        let lines = md("- Item 1\n- Item 2\n- Item 3");
912        let text = lines_to_text(&lines);
913        assert!(text.contains("Item 1"));
914        assert!(text.contains("•"));
915    }
916
917    #[test]
918    fn test_ordered_list_preserves_numbers() {
919        let lines = md("1. First\n2. Second\n3. Third");
920        let text = lines_to_text(&lines);
921        assert!(text.contains("1. First"));
922        assert!(text.contains("2. Second"));
923        assert!(!text.contains("• First"));
924    }
925
926    #[test]
927    fn loose_list_item_body_hangs_under_item_text() {
928        // A 2nd+ paragraph inside a list item must align under the item's text
929        // (hanging indent), not fall back flush to column 0.
930        let lines = md("- **Finding** — verified\n\n  Body paragraph explaining the finding.");
931        let rendered: Vec<String> = lines
932            .iter()
933            .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
934            .collect();
935        assert!(
936            rendered
937                .iter()
938                .any(|l| l.starts_with("  • ") && l.contains("Finding")),
939            "marker line should carry the bullet + indent"
940        );
941        let body = rendered
942            .iter()
943            .find(|l| l.contains("Body paragraph"))
944            .expect("body line present");
945        // 4 cols of hanging indent: 2 (depth) + 2 ("• " marker width), aligning
946        // the body under the item text rather than flush at column 0.
947        assert_eq!(
948            body, "    Body paragraph explaining the finding.",
949            "continuation paragraph must hang-indent under the item text"
950        );
951    }
952
953    #[test]
954    fn test_nested_list() {
955        let lines = md("- Outer\n  - Inner");
956        let text = lines_to_text(&lines);
957        assert!(text.contains("Outer"));
958        assert!(text.contains("Inner"));
959    }
960
961    #[test]
962    fn test_bold_and_italic() {
963        let lines = md("**bold** and *italic*");
964        let text = lines_to_text(&lines);
965        assert!(text.contains("bold"));
966        assert!(text.contains("italic"));
967    }
968
969    #[test]
970    fn test_link_shows_text_and_url() {
971        let lines = md("[click here](https://example.com)");
972        let text = lines_to_text(&lines);
973        assert!(text.contains("click here"));
974        // The destination is appended (dimmed) so the user can see where it goes.
975        assert!(text.contains("https://example.com"));
976    }
977
978    #[test]
979    fn test_autolink_does_not_duplicate_url() {
980        // When the visible text already is the URL, don't append it twice.
981        let lines = md("<https://example.com>");
982        let text = lines_to_text(&lines);
983        assert_eq!(text.matches("https://example.com").count(), 1);
984    }
985
986    #[test]
987    fn test_blockquote() {
988        let lines = md("> Quoted text");
989        let text = lines_to_text(&lines);
990        assert!(text.contains("Quoted text"));
991        assert!(text.contains("│"));
992    }
993
994    #[test]
995    fn test_horizontal_rule() {
996        let lines = md("above\n\n---\n\nbelow");
997        let text = lines_to_text(&lines);
998        assert!(text.contains("above"));
999        assert!(text.contains("below"));
1000        // The rule renders as a run of box-drawing dashes.
1001        assert!(text.contains("───"), "thematic break should render a rule");
1002    }
1003
1004    #[test]
1005    fn test_table() {
1006        let lines = md("| Header1 | Header2 |\n|---------|--------|\n| Cell1   | Cell2  |");
1007        let text = lines_to_text(&lines);
1008        assert!(text.contains("Header1"));
1009        assert!(text.contains("Cell1"));
1010        assert!(text.contains("|"));
1011    }
1012
1013    #[test]
1014    fn test_strikethrough() {
1015        let lines = md("~~deleted~~");
1016        assert!(lines_to_text(&lines).contains("deleted"));
1017    }
1018
1019    #[test]
1020    fn test_empty_input() {
1021        assert!(md("").is_empty());
1022    }
1023
1024    #[test]
1025    fn test_multiple_paragraphs() {
1026        let lines = md("Paragraph 1\n\nParagraph 2");
1027        let text = lines_to_text(&lines);
1028        assert!(text.contains("Paragraph 1"));
1029        assert!(text.contains("Paragraph 2"));
1030    }
1031
1032    #[test]
1033    fn highlight_code_line_marks_strings_and_comments() {
1034        let theme = Theme::dark();
1035        let spans = highlight_code_line("let s = \"hi\"; // note", &["//"], &theme);
1036        let str_color = theme.colors.code_string.to_color();
1037        let com_color = theme.colors.code_comment.to_color();
1038        assert!(
1039            spans
1040                .iter()
1041                .any(|s| s.content.contains("\"hi\"") && s.style.fg == Some(str_color)),
1042            "string literal must use the string color"
1043        );
1044        assert!(
1045            spans
1046                .iter()
1047                .any(|s| s.content.contains("// note") && s.style.fg == Some(com_color)),
1048            "trailing comment must use the comment color"
1049        );
1050    }
1051
1052    /// Tables with CJK cells align because column widths are display-cell
1053    /// based, not byte based.
1054    #[test]
1055    fn table_column_widths_use_display_cells() {
1056        let lines = md("| Name | Score |\n|------|-------|\n| 你好 | 100   |\n| ab   | 50    |");
1057        let mut cjk_row_width = 0usize;
1058        let mut ascii_row_width = 0usize;
1059        for line in &lines {
1060            let rendered: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
1061            if rendered.contains("你好") {
1062                cjk_row_width = rendered.width();
1063            } else if rendered.contains("ab") && rendered.contains("|") {
1064                ascii_row_width = rendered.width();
1065            }
1066        }
1067        assert!(cjk_row_width > 0, "did not find the CJK body row");
1068        assert!(ascii_row_width > 0, "did not find the ASCII body row");
1069        assert_eq!(
1070            cjk_row_width, ascii_row_width,
1071            "CJK and ASCII rows must have equal display width to align"
1072        );
1073    }
1074
1075    #[test]
1076    fn table_lines_flagged_preformatted_prose_is_not() {
1077        // Table rows must be flagged preformatted so the chat renderer doesn't
1078        // word-wrap them (which would collapse the column padding); prose must not.
1079        let out = parse_markdown(
1080            "Intro paragraph.\n\n| A | B |\n|---|---|\n| 1 | 2 |",
1081            &Theme::dark(),
1082            80,
1083        );
1084        let para = out
1085            .iter()
1086            .find(|ml| ml.line.spans.iter().any(|s| s.content.contains("Intro")))
1087            .expect("paragraph present");
1088        assert!(!para.preformatted, "prose must word-wrap normally");
1089        let table_rows: Vec<_> = out
1090            .iter()
1091            .filter(|ml| {
1092                ml.line
1093                    .spans
1094                    .first()
1095                    .is_some_and(|s| s.content.starts_with('|'))
1096            })
1097            .collect();
1098        assert!(!table_rows.is_empty(), "table should render rows");
1099        assert!(
1100            table_rows.iter().all(|ml| ml.preformatted),
1101            "every table line must be preformatted"
1102        );
1103    }
1104
1105    #[test]
1106    fn code_lines_flagged_preformatted() {
1107        let out = parse_markdown("```\nlet x = 1;\n```", &Theme::dark(), 80);
1108        assert!(
1109            out.iter()
1110                .filter(|ml| ml.line.spans.iter().any(|s| s.content.contains("let x")))
1111                .all(|ml| ml.preformatted),
1112            "code-block lines must be preformatted"
1113        );
1114    }
1115
1116    #[test]
1117    fn wide_table_wraps_cells_to_fit() {
1118        // A table wider than the viewport wraps cell text within columns rather
1119        // than overflowing. Every rendered table line must fit `width`, and no
1120        // cell content is lost.
1121        let width = 30;
1122        let out = parse_markdown(
1123            "| Item | Detail |\n|------|--------|\n| one | a very long cell that cannot fit on a single line at this width |",
1124            &Theme::dark(),
1125            width,
1126        );
1127        let mut saw_table = false;
1128        for ml in &out {
1129            let rendered: String = ml.line.spans.iter().map(|s| s.content.as_ref()).collect();
1130            if rendered.starts_with('|') {
1131                saw_table = true;
1132                assert!(
1133                    rendered.width() <= width,
1134                    "table line must fit width {width}, got {} for {rendered:?}",
1135                    rendered.width()
1136                );
1137            }
1138        }
1139        assert!(saw_table, "table should have rendered");
1140        // No content lost: every word of the long cell appears across the wraps.
1141        let all: String = out
1142            .iter()
1143            .map(|ml| {
1144                ml.line
1145                    .spans
1146                    .iter()
1147                    .map(|s| s.content.as_ref())
1148                    .collect::<String>()
1149            })
1150            .collect::<Vec<_>>()
1151            .join(" ");
1152        for word in ["very", "long", "cell", "cannot", "single", "width"] {
1153            assert!(all.contains(word), "wrapped table lost the word {word:?}");
1154        }
1155    }
1156}