Skip to main content

vtcode_ui/tui/ui/markdown/
mod.rs

1//! Markdown rendering utilities for terminal output with syntax highlighting support.
2
3mod code_blocks;
4mod links;
5mod parsing;
6mod tables;
7
8use crate::tui::ui::theme::{self, ThemeStyles};
9use anstyle::Style;
10use code_blocks::{CodeBlockRenderEnv, CodeBlockState, finalize_unclosed_code_block, handle_code_block_event};
11use parsing::{
12    LinkState, ListState, MarkdownContext, append_text, handle_end_tag, handle_start_tag, inline_code_style,
13    push_blank_line, trim_trailing_blank_lines,
14};
15use pulldown_cmark::{Event, Options, Parser};
16use tables::TableBuffer;
17use unicode_width::UnicodeWidthStr;
18use vtcode_config::loader::SyntaxHighlightingConfig;
19
20pub(crate) use code_blocks::render_diff_content_segments;
21pub use code_blocks::{
22    HighlightedSegment, highlight_code_to_ansi, highlight_code_to_segments, highlight_line_for_diff,
23};
24pub use vtcode_commons::ui_protocol::CodeBlockWeight;
25
26pub(crate) const LIST_INDENT_WIDTH: usize = 2;
27pub(crate) const CODE_LINE_NUMBER_MIN_WIDTH: usize = 3;
28
29/// A styled text segment.
30///
31/// Keep field-compatible with the headless `vtcode_commons::ui_protocol::MarkdownSegment`
32/// (this TUI variant is used when the `tui` feature is on); both are serialized into
33/// the same inline-stream shapes.
34#[derive(Clone, Debug)]
35pub struct MarkdownSegment {
36    pub style: Style,
37    pub text: String,
38    pub link_target: Option<Box<str>>,
39}
40
41impl MarkdownSegment {
42    fn new(style: Style, text: impl Into<String>) -> Self {
43        Self { style, text: text.into(), link_target: None }
44    }
45
46    fn with_link(style: Style, text: impl Into<String>, link_target: Option<impl Into<Box<str>>>) -> Self {
47        Self {
48            style,
49            text: text.into(),
50            link_target: link_target.map(Into::into),
51        }
52    }
53}
54
55/// A rendered line composed of styled segments.
56#[derive(Clone, Debug, Default)]
57pub struct MarkdownLine {
58    pub segments: Vec<MarkdownSegment>,
59    pub line_background: Option<anstyle::Color>,
60}
61
62impl MarkdownLine {
63    fn set_line_background(&mut self, color: Option<anstyle::Color>) {
64        self.line_background = color;
65    }
66
67    fn push_segment(&mut self, style: Style, text: &str) {
68        self.push_segment_with_link(style, text, None::<String>);
69    }
70
71    fn push_segment_with_link(&mut self, style: Style, text: &str, link_target: Option<impl Into<Box<str>>>) {
72        let link_target = link_target.map(Into::into);
73        if text.is_empty() {
74            return;
75        }
76        if let Some(last) = self.segments.last_mut()
77            && last.style == style
78            && last.link_target == link_target
79        {
80            last.text.push_str(text);
81            return;
82        }
83        self.segments.push(MarkdownSegment::with_link(style, text, link_target));
84    }
85
86    pub fn is_empty(&self) -> bool {
87        self.segments.iter().all(|segment| segment.text.trim().is_empty())
88    }
89
90    fn width(&self) -> usize {
91        self.segments.iter().map(|seg| UnicodeWidthStr::width(seg.text.as_str())).sum()
92    }
93}
94
95#[derive(Debug, Clone, Copy, Default)]
96pub struct RenderMarkdownOptions {
97    pub preserve_code_indentation: bool,
98    pub disable_code_block_table_reparse: bool,
99    /// Available content width for tables. Headered tables keep a padded,
100    /// width-aware grid while cells remain readable, then fall back to aligned
101    /// labeled records when the grid becomes too cramped. Headerless tables
102    /// retain their grid layout and scale columns to fit.
103    pub table_max_width: Option<usize>,
104    /// Visual weight applied to fenced code blocks. Secondary surfaces use
105    /// [`CodeBlockWeight::Muted`] so evidence recedes behind its summary.
106    pub code_block_weight: CodeBlockWeight,
107}
108
109/// Highlight configuration for TUI-rendered markdown code blocks.
110///
111/// The TUI owns the code palette: the syntax theme that matches the active UI
112/// theme keeps code legible against the terminal background, so the palette
113/// follows the UI theme rather than a fixed name. The user's configuration
114/// still decides whether highlighting happens at all and which languages are
115/// eligible.
116pub fn theme_matched_highlight_config(user: &SyntaxHighlightingConfig) -> SyntaxHighlightingConfig {
117    SyntaxHighlightingConfig {
118        enabled: user.enabled,
119        theme: crate::tui::ui::syntax_highlight::get_active_syntax_theme().to_string(),
120        cache_themes: user.cache_themes,
121        max_file_size_mb: user.max_file_size_mb,
122        enabled_languages: user.enabled_languages.clone(),
123        highlight_timeout_ms: user.highlight_timeout_ms,
124    }
125}
126
127/// Render markdown text to styled lines that can be written to the terminal renderer.
128fn render_markdown_to_lines(
129    source: &str,
130    base_style: Style,
131    theme_styles: &ThemeStyles,
132    highlight_config: Option<&SyntaxHighlightingConfig>,
133) -> Vec<MarkdownLine> {
134    render_markdown_to_lines_with_options(
135        source,
136        base_style,
137        theme_styles,
138        highlight_config,
139        RenderMarkdownOptions::default(),
140    )
141}
142
143pub fn render_markdown_to_lines_with_options(
144    source: &str,
145    base_style: Style,
146    theme_styles: &ThemeStyles,
147    highlight_config: Option<&SyntaxHighlightingConfig>,
148    render_options: RenderMarkdownOptions,
149) -> Vec<MarkdownLine> {
150    // Plan wrappers are control markup rather than user-visible prose. Remove
151    // them only outside fenced code blocks so ordinary markdown and code
152    // examples remain lossless.
153    let preprocessed = preprocess_plan_wrappers(source);
154    let parser_options =
155        Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TABLES | Options::ENABLE_TASKLISTS | Options::ENABLE_FOOTNOTES;
156
157    let parser = Parser::new_ext(&preprocessed, parser_options);
158
159    // Output lines track the source roughly 1:1, so size from the source line
160    // count to avoid reallocations during per-message rendering.
161    let mut lines = Vec::with_capacity(source.lines().count());
162    let mut current_line = MarkdownLine::default();
163    let mut style_stack = vec![base_style];
164    let mut blockquote_depth = 0usize;
165    // List nesting is shallow in practice; bound the stack up front.
166    let mut list_stack: Vec<ListState> = Vec::with_capacity(4);
167    let mut list_continuation_prefix = String::new();
168    let mut pending_list_prefix: Option<String> = None;
169    let mut code_block: Option<CodeBlockState> = None;
170    let mut active_table: Option<TableBuffer> = None;
171    let mut link_state: Option<LinkState> = None;
172
173    for event in parser {
174        let mut code_block_env = code_block_render_env(
175            &mut lines,
176            &mut current_line,
177            blockquote_depth,
178            &list_continuation_prefix,
179            &mut pending_list_prefix,
180            base_style,
181            theme_styles,
182            highlight_config,
183            render_options,
184        );
185        if handle_code_block_event(&event, &mut code_block, &mut code_block_env) {
186            continue;
187        }
188
189        let mut ctx = MarkdownContext {
190            style_stack: &mut style_stack,
191            blockquote_depth: &mut blockquote_depth,
192            list_stack: &mut list_stack,
193            pending_list_prefix: &mut pending_list_prefix,
194            list_continuation_prefix: &mut list_continuation_prefix,
195            lines: &mut lines,
196            current_line: &mut current_line,
197            theme_styles,
198            base_style,
199            code_block: &mut code_block,
200            active_table: &mut active_table,
201            link_state: &mut link_state,
202            table_max_width: render_options.table_max_width,
203        };
204
205        match event {
206            Event::Start(ref tag) => handle_start_tag(tag, &mut ctx),
207            Event::End(tag) => handle_end_tag(tag, &mut ctx),
208            Event::Text(text) => append_text(&text, &mut ctx),
209            Event::Code(code) => {
210                ctx.ensure_prefix();
211                ctx.current_line.push_segment_with_link(
212                    inline_code_style(theme_styles, base_style),
213                    &code,
214                    ctx.active_link_target(),
215                );
216            }
217            Event::SoftBreak | Event::HardBreak => ctx.flush_line(),
218            Event::Rule => {
219                ctx.flush_line();
220                let mut line = MarkdownLine::default();
221                line.push_segment(base_style.dimmed(), &"―".repeat(32));
222                ctx.lines.push(line);
223                push_blank_line(ctx.lines);
224            }
225            Event::TaskListMarker(checked) => {
226                ctx.ensure_prefix();
227                ctx.current_line.push_segment(base_style, if checked { "[x] " } else { "[ ] " });
228            }
229            Event::Html(html) | Event::InlineHtml(html) => {
230                // Keep the event-level guard for split or oddly-cased tags;
231                // other HTML is preserved as text.
232                if !is_plan_markup_html(&html) {
233                    append_text(&html, &mut ctx);
234                }
235            }
236            Event::FootnoteReference(r) => append_text(&format!("[^{r}]"), &mut ctx),
237            Event::InlineMath(m) => append_text(&format!("${m}$"), &mut ctx),
238            Event::DisplayMath(m) => append_text(&format!("$$\n{m}\n$$"), &mut ctx),
239        }
240    }
241
242    let mut code_block_env = code_block_render_env(
243        &mut lines,
244        &mut current_line,
245        blockquote_depth,
246        &list_continuation_prefix,
247        &mut pending_list_prefix,
248        base_style,
249        theme_styles,
250        highlight_config,
251        render_options,
252    );
253    finalize_unclosed_code_block(&mut code_block, &mut code_block_env);
254
255    if !current_line.segments.is_empty() {
256        lines.push(current_line);
257    }
258
259    trim_trailing_blank_lines(&mut lines);
260    lines
261}
262
263/// Convenience helper that renders markdown using the active theme without emitting output.
264pub(crate) fn render_markdown(source: &str) -> Vec<MarkdownLine> {
265    let styles = theme::active_styles();
266    render_markdown_to_lines(source, Style::default(), &styles, None)
267}
268
269fn code_block_render_env<'a>(
270    lines: &'a mut Vec<MarkdownLine>,
271    current_line: &'a mut MarkdownLine,
272    blockquote_depth: usize,
273    list_continuation_prefix: &'a str,
274    pending_list_prefix: &'a mut Option<String>,
275    base_style: Style,
276    theme_styles: &'a ThemeStyles,
277    highlight_config: Option<&'a SyntaxHighlightingConfig>,
278    render_options: RenderMarkdownOptions,
279) -> CodeBlockRenderEnv<'a> {
280    CodeBlockRenderEnv {
281        lines,
282        current_line,
283        blockquote_depth,
284        list_continuation_prefix,
285        pending_list_prefix,
286        base_style,
287        theme_styles,
288        highlight_config,
289        render_options,
290    }
291}
292
293/// Plan wrappers that must never appear literally in rendered output.
294const PLAN_MARKUP_TAGS: &[&str] = &["<proposed_plan>", "</proposed_plan>", "<plan>", "</plan>"];
295
296fn is_plan_markup_html(html: &str) -> bool {
297    let normalized: String = html.chars().filter(|ch| !ch.is_whitespace()).collect();
298    let lowered = normalized.to_ascii_lowercase();
299    PLAN_MARKUP_TAGS.iter().any(|tag| lowered.contains(tag))
300}
301
302fn strip_plan_markup_tags(text: &str, inline_code_ticks: &mut Option<usize>) -> String {
303    let mut out = String::with_capacity(text.len());
304    let mut cursor = 0;
305
306    while cursor < text.len() {
307        let remainder = &text[cursor..];
308        if remainder.starts_with('`') {
309            let run_length = remainder.bytes().take_while(|byte| *byte == b'`').count();
310            out.push_str(&remainder[..run_length]);
311            if inline_code_ticks.is_some_and(|ticks| ticks == run_length) {
312                *inline_code_ticks = None;
313            } else if inline_code_ticks.is_none() {
314                *inline_code_ticks = Some(run_length);
315            }
316            cursor += run_length;
317            continue;
318        }
319
320        if inline_code_ticks.is_none()
321            && let Some(tag) = PLAN_MARKUP_TAGS.iter().find(|tag| {
322                remainder
323                    .get(..tag.len())
324                    .is_some_and(|prefix| prefix.eq_ignore_ascii_case(tag))
325            })
326        {
327            cursor += tag.len();
328            continue;
329        }
330
331        let character = remainder.chars().next().expect("cursor is on a character boundary");
332        out.push(character);
333        cursor += character.len_utf8();
334    }
335
336    out
337}
338
339fn preprocess_plan_wrappers(source: &str) -> String {
340    let mut out = String::with_capacity(source.len());
341    let mut may_have_plan_tags = None;
342    let mut in_fenced_code = false;
343    let mut inline_code_ticks = None;
344
345    for (index, line) in source.lines().enumerate() {
346        if index > 0 {
347            out.push('\n');
348        }
349
350        let is_fence = is_fence_delimiter(line);
351        if in_fenced_code || is_fence || !*may_have_plan_tags.get_or_insert_with(|| source.contains('<')) {
352            out.push_str(line);
353        } else {
354            out.push_str(&strip_plan_markup_tags(line, &mut inline_code_ticks));
355        }
356
357        if is_fence {
358            in_fenced_code = !in_fenced_code;
359            inline_code_ticks = None;
360        }
361    }
362
363    if source.ends_with('\n') && !out.ends_with('\n') {
364        out.push('\n');
365    }
366    out
367}
368
369fn is_fence_delimiter(line: &str) -> bool {
370    vtcode_commons::formatting::is_markdown_fence_delimiter(line)
371}
372
373#[cfg(test)]
374mod tests;