Skip to main content

vtcode_core/utils/ansi/
markdown.rs

1//! Markdown rendering for tool output.
2
3use super::*;
4
5use std::io::Write;
6
7use crate::utils::transcript;
8
9use crate::ui::markdown::{
10    CodeBlockWeight, MarkdownLine, MarkdownSegment, RenderMarkdownOptions, render_markdown_to_lines_with_options,
11};
12use crate::ui::theme;
13use anstyle::Reset;
14use anyhow::Result;
15
16impl AnsiRenderer {
17    /// Render markdown content with proper syntax highlighting and indentation normalization.
18    /// Use this for tool output that contains markdown code blocks.
19    pub fn render_markdown_output(&mut self, style: MessageStyle, text: &str) -> Result<()> {
20        self.flush_compact_command_group();
21        self.render_markdown(style, text)
22    }
23
24    pub(super) fn render_markdown(&mut self, style: MessageStyle, text: &str) -> Result<()> {
25        if !self.should_render_style(style) {
26            return Ok(());
27        }
28        let styles = theme::active_styles();
29        let base_style = style.style();
30        let indent = self.indent_for_style(style);
31        let preserve_code_indentation = matches!(
32            style,
33            MessageStyle::Output
34                | MessageStyle::ToolOutput
35                | MessageStyle::ToolDetail
36                | MessageStyle::Response
37                | MessageStyle::Reasoning
38                | MessageStyle::ReasoningEmphasis
39                | MessageStyle::User
40        );
41
42        // Strip ANSI codes from agent response to prevent interference with markdown rendering
43        let text_storage;
44        let text = if matches!(style, MessageStyle::Response) {
45            text_storage = crate::utils::ansi_parser::strip_ansi(text);
46            &text_storage
47        } else {
48            text
49        };
50
51        if let Some(sink) = &mut self.sink {
52            // Read terminal width fresh so tables adapt to resizes.
53            if sink.table_max_width_override.is_none()
54                && let Ok((w, _)) = crossterm::terminal::size()
55            {
56                sink.table_max_width = Some(w as usize);
57            }
58            let last_empty =
59                sink.write_markdown(text, indent, base_style, Self::message_kind(style), preserve_code_indentation)?;
60            self.last_line_was_empty = last_empty;
61            if matches!(style, MessageStyle::Response)
62                && self.show_message_timestamps
63                && !sink.in_transcript_batch()
64                && !text.trim().is_empty()
65            {
66                sink.append_response_timestamp_footer(styles.status, indent)?;
67                self.last_line_was_empty = false;
68            }
69            return Ok(());
70        }
71        let highlight_cfg = if self.highlight_config.enabled {
72            Some(&self.highlight_config)
73        } else {
74            None
75        };
76        let mut lines = render_markdown_to_lines_with_options(
77            text,
78            base_style,
79            &styles,
80            highlight_cfg,
81            RenderMarkdownOptions {
82                preserve_code_indentation,
83                disable_code_block_table_reparse: false,
84                table_max_width: terminal_table_content_width(""),
85                code_block_weight: CodeBlockWeight::Primary,
86            },
87        );
88        if lines.is_empty() {
89            lines.push(MarkdownLine::default());
90        }
91
92        // Pre-allocate buffer for markdown output if rendering many lines
93        if lines.len() > 10 {
94            self.buffer.reserve(lines.len() * 80);
95        }
96
97        for line in lines {
98            self.write_markdown_line(style, indent, line)?;
99        }
100        if matches!(style, MessageStyle::Response) && self.show_message_timestamps && !text.trim().is_empty() {
101            self.write_response_timestamp_footer(indent)?;
102        }
103        Ok(())
104    }
105
106    /// Write the wall-clock footer after a direct-mode agent response.
107    ///
108    /// Mirrors [`AnsiRenderer::flush`] without recording the global transcript
109    /// log: the footer is chrome, and the log feeds tail-matching,
110    /// session-end hooks, and snapshot assertions that must not see it.
111    fn write_response_timestamp_footer(&mut self, indent: &str) -> Result<()> {
112        let footer = vtcode_commons::message_timestamp::current_message_timestamp_footer();
113        self.buffer.clear();
114        if !indent.is_empty() {
115            self.buffer.push_str(indent);
116        }
117        self.buffer.push_str(&footer);
118        let style = theme::active_styles().status;
119        if self.color {
120            writeln!(self.writer, "{style}{}{Reset}", self.buffer)?;
121        } else {
122            writeln!(self.writer, "{}", self.buffer)?;
123        }
124        self.writer.flush()?;
125        self.last_line_was_empty = false;
126        self.buffer.clear();
127        Ok(())
128    }
129
130    pub(super) fn write_markdown_line(
131        &mut self,
132        style: MessageStyle,
133        indent: &str,
134        mut line: MarkdownLine,
135    ) -> Result<()> {
136        if !indent.is_empty() && !line.segments.is_empty() {
137            line.segments.insert(
138                0,
139                MarkdownSegment {
140                    style: style.style(),
141                    text: indent.to_string(),
142                    link_target: None,
143                },
144            );
145        }
146
147        if let Some(sink) = &mut self.sink {
148            sink.write_segments(&line.segments, Self::message_kind(style))?;
149            self.last_line_was_empty = line.is_empty();
150            return Ok(());
151        }
152
153        let mut plain = String::new();
154        if self.color {
155            for segment in &line.segments {
156                let clickable_target = segment.link_target.as_deref().and_then(make_clickable_target);
157                if let Some(target) = clickable_target.as_deref() {
158                    write!(self.writer, "\u{1b}]8;;{target}\u{1b}\\")?;
159                }
160                write!(self.writer, "{style}{}{Reset}", segment.text, style = segment.style)?;
161                if clickable_target.is_some() {
162                    write!(self.writer, "\u{1b}]8;;\u{1b}\\")?;
163                }
164                plain.push_str(&segment.text);
165            }
166            writeln!(self.writer)?;
167        } else {
168            for segment in &line.segments {
169                let clickable_target = segment.link_target.as_deref().and_then(make_clickable_target);
170                if let Some(target) = clickable_target.as_deref() {
171                    write!(self.writer, "\u{1b}]8;;{target}\u{1b}\\")?;
172                }
173                write!(self.writer, "{}", segment.text)?;
174                if clickable_target.is_some() {
175                    write!(self.writer, "\u{1b}]8;;\u{1b}\\")?;
176                }
177                plain.push_str(&segment.text);
178            }
179            writeln!(self.writer)?;
180        }
181        self.writer.flush()?;
182        transcript::append(&plain);
183        self.last_line_was_empty = plain.trim().is_empty();
184        Ok(())
185    }
186}