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