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 Some((w, _)) = crate::utils::tty::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                if self.defer_turn_footer {
67                    // Inside a turn the footer is emitted once at turn end, so
68                    // intermediate responses (pre-tool commentary, plan prose)
69                    // stay unstamped.
70                    self.pending_response_footer = true;
71                } else {
72                    // Out-of-turn output (session-exit reprint, pre-turn prompt
73                    // replies) owns no boundary to flush at, so it stamps now.
74                    sink.append_response_timestamp_footer(styles.status, indent)?;
75                    self.last_line_was_empty = false;
76                }
77            }
78            return Ok(());
79        }
80        let highlight_cfg = if self.highlight_config.enabled {
81            Some(&self.highlight_config)
82        } else {
83            None
84        };
85        let mut lines = render_markdown_to_lines_with_options(
86            text,
87            base_style,
88            &styles,
89            highlight_cfg,
90            RenderMarkdownOptions {
91                preserve_code_indentation,
92                disable_code_block_table_reparse: false,
93                table_max_width: terminal_table_content_width(""),
94                code_block_weight: CodeBlockWeight::Primary,
95            },
96        );
97        if lines.is_empty() {
98            lines.push(MarkdownLine::default());
99        }
100
101        // Pre-allocate buffer for markdown output if rendering many lines
102        if lines.len() > 10 {
103            self.buffer.reserve(lines.len() * 80);
104        }
105
106        for line in lines {
107            self.write_markdown_line(style, indent, line)?;
108        }
109        if matches!(style, MessageStyle::Response) && self.show_message_timestamps && !text.trim().is_empty() {
110            if self.defer_turn_footer {
111                // Direct (non-inline) output defers the footer to turn end too,
112                // so one turn shows exactly one clock after its final message.
113                self.pending_response_footer = true;
114            } else {
115                self.write_response_timestamp_footer(indent)?;
116            }
117        }
118        Ok(())
119    }
120
121    /// Write the wall-clock footer for the turn that just completed in
122    /// direct-mode (non-inline) output.
123    ///
124    /// Mirrors [`AnsiRenderer::flush`] without recording the global transcript
125    /// log: the footer is chrome, and the log feeds tail-matching,
126    /// session-end hooks, and snapshot assertions that must not see it.
127    pub(super) fn write_response_timestamp_footer(&mut self, indent: &str) -> Result<()> {
128        let footer = vtcode_commons::message_timestamp::current_message_timestamp_footer();
129        self.buffer.clear();
130        if !indent.is_empty() {
131            self.buffer.push_str(indent);
132        }
133        self.buffer.push_str(&footer);
134        let style = theme::active_styles().status;
135        if self.color {
136            writeln!(self.writer, "{style}{}{Reset}", self.buffer)?;
137        } else {
138            writeln!(self.writer, "{}", self.buffer)?;
139        }
140        self.writer.flush()?;
141        self.last_line_was_empty = false;
142        self.buffer.clear();
143        Ok(())
144    }
145
146    pub(super) fn write_markdown_line(
147        &mut self,
148        style: MessageStyle,
149        indent: &str,
150        mut line: MarkdownLine,
151    ) -> Result<()> {
152        if !indent.is_empty() && !line.segments.is_empty() {
153            line.segments.insert(
154                0,
155                MarkdownSegment {
156                    style: style.style(),
157                    text: indent.to_string(),
158                    link_target: None,
159                },
160            );
161        }
162
163        if let Some(sink) = &mut self.sink {
164            sink.write_segments(&line.segments, Self::message_kind(style))?;
165            self.last_line_was_empty = line.is_empty();
166            return Ok(());
167        }
168
169        let mut plain = String::new();
170        if self.color {
171            for segment in &line.segments {
172                let clickable_target = segment.link_target.as_deref().and_then(make_clickable_target);
173                if let Some(target) = clickable_target.as_deref() {
174                    write!(self.writer, "\u{1b}]8;;{target}\u{1b}\\")?;
175                }
176                write!(self.writer, "{style}{}{Reset}", segment.text, style = segment.style)?;
177                if clickable_target.is_some() {
178                    write!(self.writer, "\u{1b}]8;;\u{1b}\\")?;
179                }
180                plain.push_str(&segment.text);
181            }
182            writeln!(self.writer)?;
183        } else {
184            for segment in &line.segments {
185                let clickable_target = segment.link_target.as_deref().and_then(make_clickable_target);
186                if let Some(target) = clickable_target.as_deref() {
187                    write!(self.writer, "\u{1b}]8;;{target}\u{1b}\\")?;
188                }
189                write!(self.writer, "{}", segment.text)?;
190                if clickable_target.is_some() {
191                    write!(self.writer, "\u{1b}]8;;\u{1b}\\")?;
192                }
193                plain.push_str(&segment.text);
194            }
195            writeln!(self.writer)?;
196        }
197        self.writer.flush()?;
198        transcript::append(&plain);
199        self.last_line_was_empty = plain.trim().is_empty();
200        Ok(())
201    }
202}