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, None)?;
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, None)?;
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    /// `elapsed` comes from the armed turn bracket; out-of-turn stamps pass
128    /// `None`.
129    pub(super) fn write_response_timestamp_footer(
130        &mut self,
131        indent: &str,
132        elapsed: Option<std::time::Duration>,
133    ) -> Result<()> {
134        let footer = vtcode_commons::message_timestamp::current_message_timestamp_footer_with_elapsed(elapsed);
135        self.buffer.clear();
136        if !indent.is_empty() {
137            self.buffer.push_str(indent);
138        }
139        self.buffer.push_str(&footer);
140        let style = theme::active_styles().status;
141        if self.color {
142            writeln!(self.writer, "{style}{}{Reset}", self.buffer)?;
143        } else {
144            writeln!(self.writer, "{}", self.buffer)?;
145        }
146        self.writer.flush()?;
147        self.last_line_was_empty = false;
148        self.buffer.clear();
149        Ok(())
150    }
151
152    pub(super) fn write_markdown_line(
153        &mut self,
154        style: MessageStyle,
155        indent: &str,
156        mut line: MarkdownLine,
157    ) -> Result<()> {
158        if !indent.is_empty() && !line.segments.is_empty() {
159            line.segments.insert(
160                0,
161                MarkdownSegment {
162                    style: style.style(),
163                    text: indent.to_string(),
164                    link_target: None,
165                },
166            );
167        }
168
169        if let Some(sink) = &mut self.sink {
170            sink.write_segments(&line.segments, Self::message_kind(style))?;
171            self.last_line_was_empty = line.is_empty();
172            return Ok(());
173        }
174
175        let mut plain = String::new();
176        if self.color {
177            for segment in &line.segments {
178                let clickable_target = segment.link_target.as_deref().and_then(make_clickable_target);
179                if let Some(target) = clickable_target.as_deref() {
180                    write!(self.writer, "\u{1b}]8;;{target}\u{1b}\\")?;
181                }
182                write!(self.writer, "{style}{}{Reset}", segment.text, style = segment.style)?;
183                if clickable_target.is_some() {
184                    write!(self.writer, "\u{1b}]8;;\u{1b}\\")?;
185                }
186                plain.push_str(&segment.text);
187            }
188            writeln!(self.writer)?;
189        } else {
190            for segment in &line.segments {
191                let clickable_target = segment.link_target.as_deref().and_then(make_clickable_target);
192                if let Some(target) = clickable_target.as_deref() {
193                    write!(self.writer, "\u{1b}]8;;{target}\u{1b}\\")?;
194                }
195                write!(self.writer, "{}", segment.text)?;
196                if clickable_target.is_some() {
197                    write!(self.writer, "\u{1b}]8;;\u{1b}\\")?;
198                }
199                plain.push_str(&segment.text);
200            }
201            writeln!(self.writer)?;
202        }
203        self.writer.flush()?;
204        transcript::append(&plain);
205        self.last_line_was_empty = plain.trim().is_empty();
206        Ok(())
207    }
208}