Skip to main content

vtcode_ui/tui/ui/markdown/
code_blocks.rs

1use super::parsing::{flush_current_line, push_blank_line};
2use super::{CODE_LINE_NUMBER_MIN_WIDTH, CodeBlockWeight, MarkdownLine, MarkdownSegment, RenderMarkdownOptions};
3use crate::tui::ui::syntax_highlight;
4use crate::tui::ui::theme::ThemeStyles;
5use crate::tui::utils::diff_styles::{
6    DiffLineType, current_diff_render_style_context, diff_add_fg, diff_del_fg, style_content_ansi,
7    style_file_header_new_ansi, style_file_header_old_ansi, style_hunk_header_ansi, style_sign_ansi,
8};
9use anstyle::{Color as AnstyleColor, Effects, Style};
10use pulldown_cmark::{Event, Options, Parser, Tag, TagEnd};
11use std::fmt::Write;
12use syntect::util::LinesWithEndings;
13use vtcode_commons::diff_paths::{
14    is_diff_addition_line, is_diff_deletion_line, is_diff_header_line, is_diff_new_file_marker_line,
15    is_prose_language_hint, language_hint_from_path, looks_like_diff_content, parse_diff_git_path,
16    parse_diff_marker_path,
17};
18use vtcode_commons::diff_preview::{DiffDisplayKind, DiffDisplayLine, annotate_word_level_diffs};
19use vtcode_config::loader::SyntaxHighlightingConfig;
20
21const DIFF_SUMMARY_PREFIX: &str = "• Diff ";
22
23/// Share of the theme background mixed into a muted code foreground.
24///
25/// Muted code keeps its hue, so syntax-highlighted tokens stay
26/// distinguishable while only their intensity drops. The blend is lighter
27/// than the line-number gutter blend, because the code body is content and the
28/// gutter is chrome. Both stop at the theme's contrast floor.
29const MUTED_CODE_BLEND_RATIO: f32 = 0.25;
30
31/// Share of the theme background mixed into a muted line-number gutter.
32///
33/// The same share the primary gutter blends by; unlike the primary gutter it
34/// stops at the theme's contrast floor, so the result can sit slightly
35/// brighter than a primary block's gutter when the blend would cross it.
36const MUTED_GUTTER_BLEND_RATIO: f32 = 0.35;
37
38#[derive(Clone, Debug)]
39pub(crate) struct CodeBlockState {
40    pub(crate) language: Option<String>,
41    pub(crate) buffer: String,
42}
43
44pub(crate) struct CodeBlockRenderEnv<'a> {
45    pub(crate) lines: &'a mut Vec<MarkdownLine>,
46    pub(crate) current_line: &'a mut MarkdownLine,
47    pub(crate) blockquote_depth: usize,
48    pub(crate) list_continuation_prefix: &'a str,
49    pub(crate) pending_list_prefix: &'a mut Option<String>,
50    pub(crate) base_style: Style,
51    pub(crate) theme_styles: &'a ThemeStyles,
52    pub(crate) highlight_config: Option<&'a SyntaxHighlightingConfig>,
53    pub(crate) render_options: RenderMarkdownOptions,
54}
55
56pub(crate) fn handle_code_block_event(
57    event: &Event<'_>,
58    code_block: &mut Option<CodeBlockState>,
59    env: &mut CodeBlockRenderEnv<'_>,
60) -> bool {
61    if code_block.is_none() {
62        return false;
63    }
64
65    match event {
66        Event::Text(text) => {
67            if let Some(state) = code_block.as_mut() {
68                state.buffer.push_str(text);
69            }
70            true
71        }
72        Event::End(TagEnd::CodeBlock) => {
73            finalize_code_block(env, code_block, true, true);
74            true
75        }
76        _ => false,
77    }
78}
79
80pub(crate) fn finalize_unclosed_code_block(code_block: &mut Option<CodeBlockState>, env: &mut CodeBlockRenderEnv<'_>) {
81    finalize_code_block(env, code_block, false, false);
82}
83
84fn finalize_code_block(
85    env: &mut CodeBlockRenderEnv<'_>,
86    code_block: &mut Option<CodeBlockState>,
87    allow_table_reparse: bool,
88    append_trailing_blank_line: bool,
89) {
90    flush_current_line(
91        env.lines,
92        env.current_line,
93        env.blockquote_depth,
94        env.list_continuation_prefix,
95        env.pending_list_prefix,
96        env.base_style,
97    );
98    if let Some(state) = code_block.take() {
99        let rendered = render_code_block_state(&state, env, allow_table_reparse);
100        env.lines.extend(rendered);
101        if append_trailing_blank_line {
102            push_blank_line(env.lines);
103        }
104    }
105}
106
107fn render_code_block_state(
108    state: &CodeBlockState,
109    env: &CodeBlockRenderEnv<'_>,
110    allow_table_reparse: bool,
111) -> Vec<MarkdownLine> {
112    if allow_table_reparse
113        && !env.render_options.disable_code_block_table_reparse
114        && code_block_contains_table(&state.buffer, state.language.as_deref())
115    {
116        return render_markdown_code_block_table(
117            &state.buffer,
118            env.base_style,
119            env.theme_styles,
120            env.highlight_config,
121            env.render_options,
122        );
123    }
124
125    let prefix = build_prefix_segments(env.blockquote_depth, env.list_continuation_prefix, env.base_style);
126    highlight_code_block(
127        &state.buffer,
128        state.language.as_deref(),
129        env.highlight_config,
130        env.theme_styles,
131        env.base_style,
132        &prefix,
133        env.render_options.preserve_code_indentation,
134        env.render_options.code_block_weight,
135    )
136}
137
138fn render_markdown_code_block_table(
139    source: &str,
140    base_style: Style,
141    theme_styles: &ThemeStyles,
142    highlight_config: Option<&SyntaxHighlightingConfig>,
143    render_options: RenderMarkdownOptions,
144) -> Vec<MarkdownLine> {
145    let mut nested_options = render_options;
146    nested_options.disable_code_block_table_reparse = true;
147    super::render_markdown_to_lines_with_options(source, base_style, theme_styles, highlight_config, nested_options)
148}
149
150fn build_prefix_segments(
151    _blockquote_depth: usize,
152    list_continuation_prefix: &str,
153    base_style: Style,
154) -> Vec<MarkdownSegment> {
155    let mut segments = Vec::with_capacity(usize::from(!list_continuation_prefix.is_empty()));
156    if !list_continuation_prefix.is_empty() {
157        segments.push(MarkdownSegment::new(base_style, list_continuation_prefix));
158    }
159    segments
160}
161
162fn highlight_code_block(
163    code: &str,
164    language: Option<&str>,
165    highlight_config: Option<&SyntaxHighlightingConfig>,
166    theme_styles: &ThemeStyles,
167    base_style: Style,
168    prefix_segments: &[MarkdownSegment],
169    preserve_code_indentation: bool,
170    code_block_weight: CodeBlockWeight,
171) -> Vec<MarkdownLine> {
172    let mut lines = Vec::new();
173
174    let normalized_code = normalize_code_indentation(code, language, preserve_code_indentation);
175    let code_to_display = &normalized_code;
176    if is_diff_language(language) || (language.is_none() && looks_like_diff_content(code_to_display)) {
177        return render_diff_code_block(code_to_display, theme_styles, base_style, prefix_segments);
178    }
179    let use_line_numbers = language.is_some_and(|lang| !lang.trim().is_empty()) && !is_diff_language(language);
180
181    if let Some(config) = highlight_config.filter(|cfg| cfg.enabled)
182        && let Some(highlighted) = try_highlight(code_to_display, language, config)
183    {
184        let source_lines: Vec<&str> = code_to_display.lines().collect();
185        let line_count = source_line_count(code_to_display);
186        let number_width = line_number_width(line_count);
187        let gutter_style = code_gutter_style(theme_styles, base_style, code_block_weight);
188        let code_style = code_block_style(theme_styles, base_style, code_block_weight);
189        let mut line_number = 1usize;
190        for (index, src) in source_lines.iter().enumerate() {
191            let Some(segments) = highlighted.get(index) else {
192                break;
193            };
194            let is_omitted = parse_omitted_line_count(src).is_some();
195            let (gutter_text, omitted) = if use_line_numbers {
196                let (text, om) = format_gutter_text(line_number, number_width, src);
197                (Some(text), om)
198            } else {
199                (None, 1)
200            };
201            let mut line = code_line_with_prefix(prefix_segments, gutter_text.as_deref(), gutter_style);
202            if is_omitted {
203                line.push_segment(gutter_style, src);
204            } else {
205                let mut in_leading_whitespace = true;
206                for (style, text) in segments {
207                    let is_leading_whitespace = in_leading_whitespace && text.trim().is_empty();
208                    if is_leading_whitespace {
209                        line.push_segment(code_style, text);
210                    } else {
211                        in_leading_whitespace = false;
212                        line.push_segment(apply_code_weight(*style, theme_styles, code_block_weight), text);
213                    }
214                }
215            }
216            line_number = line_number.saturating_add(omitted);
217            lines.push(line);
218        }
219        return lines;
220    }
221
222    let mut line_number = 1usize;
223    let line_count = source_line_count(code_to_display);
224    let number_width = line_number_width(line_count);
225    let gutter_style = code_gutter_style(theme_styles, base_style, code_block_weight);
226    let code_style = code_block_style(theme_styles, base_style, code_block_weight);
227
228    for raw_line in LinesWithEndings::from(code_to_display) {
229        let trimmed = raw_line.trim_end_matches('\n');
230        let is_omitted = parse_omitted_line_count(trimmed).is_some();
231        let (gutter_text, omitted) = if use_line_numbers {
232            let (text, om) = format_gutter_text(line_number, number_width, trimmed);
233            (Some(text), om)
234        } else {
235            (None, 1)
236        };
237        let mut line = code_line_with_prefix(prefix_segments, gutter_text.as_deref(), gutter_style);
238        if !trimmed.is_empty() {
239            if is_omitted {
240                line.push_segment(gutter_style, trimmed);
241            } else {
242                line.push_segment(code_style, trimmed);
243            }
244        }
245        lines.push(line);
246        line_number = line_number.saturating_add(omitted);
247    }
248
249    lines
250}
251
252pub(crate) fn normalize_diff_lines(code: &str) -> Vec<String> {
253    #[derive(Default)]
254    struct DiffBlock {
255        header: String,
256        path: String,
257        lines: Vec<String>,
258        additions: usize,
259        deletions: usize,
260    }
261
262    let mut preface = Vec::new();
263    let mut blocks = Vec::new();
264    let mut current: Option<DiffBlock> = None;
265    let mut fallback_additions = 0usize;
266    let mut fallback_deletions = 0usize;
267    let mut fallback_path: Option<String> = None;
268    let mut summary_insert_index: Option<usize> = None;
269
270    for line in code.lines() {
271        if fallback_path.is_none() {
272            fallback_path = parse_diff_marker_path(line);
273        }
274        if summary_insert_index.is_none() && is_diff_new_file_marker_line(line.trim_start()) {
275            summary_insert_index = Some(preface.len());
276        }
277        bump_diff_counters(line, &mut fallback_additions, &mut fallback_deletions);
278
279        if let Some(path) = parse_diff_git_path(line) {
280            if let Some(block) = current.take() {
281                blocks.push(block);
282            }
283            current = Some(DiffBlock {
284                header: line.to_string(),
285                path,
286                lines: Vec::new(),
287                additions: 0,
288                deletions: 0,
289            });
290            continue;
291        }
292
293        let rewritten = rewrite_diff_line(line);
294        if let Some(block) = current.as_mut() {
295            bump_diff_counters(line, &mut block.additions, &mut block.deletions);
296            block.lines.push(rewritten);
297        } else {
298            preface.push(rewritten);
299        }
300    }
301
302    if let Some(block) = current {
303        blocks.push(block);
304    }
305
306    if blocks.is_empty() {
307        let path = fallback_path.unwrap_or_else(|| "file".to_string());
308        let summary = format_diff_summary(path.as_str(), fallback_additions, fallback_deletions);
309
310        let mut output = Vec::with_capacity(preface.len() + 1);
311        if let Some(idx) = summary_insert_index {
312            output.extend(preface[..=idx].iter().cloned());
313            output.push(summary);
314            output.extend(preface[idx + 1..].iter().cloned());
315        } else {
316            output.push(summary);
317            output.extend(preface);
318        }
319        return output;
320    }
321
322    let mut output = Vec::new();
323    output.extend(preface);
324    for block in blocks {
325        output.push(block.header);
326        output.push(format_diff_summary(block.path.as_str(), block.additions, block.deletions));
327        output.extend(block.lines);
328    }
329    output
330}
331
332fn render_diff_code_block(
333    code: &str,
334    theme_styles: &ThemeStyles,
335    base_style: Style,
336    prefix_segments: &[MarkdownSegment],
337) -> Vec<MarkdownLine> {
338    render_diff_code_block_with_context(
339        code,
340        theme_styles,
341        base_style,
342        prefix_segments,
343        current_diff_render_style_context(),
344    )
345}
346
347pub(crate) fn render_diff_code_block_with_context(
348    code: &str,
349    theme_styles: &ThemeStyles,
350    base_style: Style,
351    prefix_segments: &[MarkdownSegment],
352    style_context: crate::tui::utils::diff_styles::DiffRenderStyleContext,
353) -> Vec<MarkdownLine> {
354    let mut lines = Vec::new();
355    // Diffs carry their own semantic palette (add/delete tints and chips), so
356    // they keep the primary code weight even on muted surfaces.
357    let context_style = code_block_style(theme_styles, base_style, CodeBlockWeight::Primary);
358    let metadata_style = Style::new()
359        .fg_color(Some(anstyle::Color::Ansi(anstyle::AnsiColor::BrightBlack)))
360        .effects(Effects::DIMMED);
361    let hunk_style = style_hunk_header_ansi(style_context);
362    let added_style = style_content_ansi(DiffLineType::Insert, style_context);
363    let removed_style = style_content_ansi(DiffLineType::Delete, style_context);
364    let added_marker_style = style_sign_ansi(DiffLineType::Insert, style_context);
365    let removed_marker_style = style_sign_ansi(DiffLineType::Delete, style_context);
366    let file_old_style = style_file_header_old_ansi(style_context);
367    let file_new_style = style_file_header_new_ansi(style_context);
368    let added_background = added_style.get_bg_color();
369    let removed_background = removed_style.get_bg_color();
370    let added_word = style_context.add_word_bg();
371    let removed_word = style_context.del_word_bg();
372    let mut current_language: Option<String> = None;
373    let normalized = normalize_diff_lines(code);
374    let word_ranges_by_line = word_level_ranges_for_normalized(&normalized);
375
376    for (line_index, line) in normalized.iter().enumerate() {
377        let trimmed = line.trim_end_matches('\n');
378        let trimmed_start = trimmed.trim_start();
379        if let Some(path) = diff_path_for_language(trimmed_start) {
380            current_language = language_hint_from_path(&path);
381        }
382        if let Some((path, additions, deletions)) = parse_diff_summary_line(trimmed_start) {
383            let leading_len = trimmed.len().saturating_sub(trimmed_start.len());
384            let leading = &trimmed[..leading_len];
385            let mut line = prefixed_line(prefix_segments);
386            if !leading.is_empty() {
387                line.push_segment(context_style, leading);
388            }
389            // Summary counts keep accessible red/green foregrounds without
390            // the body tint.
391            let count_style = |kind: DiffLineType| {
392                let fg = match kind {
393                    DiffLineType::Insert => Some(diff_add_fg(style_context.theme(), style_context.level())),
394                    DiffLineType::Delete => Some(diff_del_fg(style_context.theme(), style_context.level())),
395                    DiffLineType::Context => None,
396                };
397                Style::new().fg_color(fg)
398            };
399            line.push_segment(context_style, &format!("{DIFF_SUMMARY_PREFIX}{path} ("));
400            line.push_segment(count_style(DiffLineType::Insert), &format!("+{additions}"));
401            line.push_segment(context_style, " ");
402            line.push_segment(count_style(DiffLineType::Delete), &format!("-{deletions}"));
403            line.push_segment(context_style, ")");
404            lines.push(line);
405            continue;
406        }
407
408        let mut line = prefixed_line(prefix_segments);
409        if !trimmed.is_empty() {
410            if trimmed_start.starts_with("diff --git ") || trimmed_start.starts_with("index ") {
411                line.push_segment(metadata_style, trimmed);
412            } else if trimmed_start.starts_with("--- ") || trimmed_start.starts_with("*** Delete File:") {
413                line.push_segment(file_old_style, trimmed);
414            } else if trimmed_start.starts_with("+++ ") || trimmed_start.starts_with("*** Add File:") {
415                line.push_segment(file_new_style, trimmed);
416            } else if is_diff_header_line(trimmed_start) {
417                line.push_segment(hunk_style, trimmed);
418            } else if is_diff_addition_line(trimmed_start) {
419                line.push_segment(added_marker_style, "+");
420                let body = &trimmed_start[1..];
421                if body.is_empty() {
422                    line.push_segment(added_style, " ");
423                } else {
424                    let word_ranges = word_ranges_by_line.get(line_index).map(Vec::as_slice).unwrap_or(&[]);
425                    push_highlighted_diff_body(
426                        &mut line,
427                        body,
428                        current_language.as_deref(),
429                        added_style,
430                        added_background,
431                        word_ranges,
432                        added_word,
433                    );
434                }
435                paint_line_background(&mut line, added_background);
436                line.set_line_background(added_background);
437            } else if trimmed_start.starts_with("*** Update File:") {
438                line.push_segment(added_marker_style, "+");
439                line.push_segment(added_style, trimmed_start);
440                paint_line_background(&mut line, added_background);
441                line.set_line_background(added_background);
442            } else if is_diff_deletion_line(trimmed_start) {
443                line.push_segment(removed_marker_style, "-");
444                let body = &trimmed_start[1..];
445                if body.is_empty() {
446                    line.push_segment(removed_style, " ");
447                } else {
448                    let word_ranges = word_ranges_by_line.get(line_index).map(Vec::as_slice).unwrap_or(&[]);
449                    push_highlighted_diff_body(
450                        &mut line,
451                        body,
452                        current_language.as_deref(),
453                        removed_style,
454                        removed_background,
455                        word_ranges,
456                        removed_word,
457                    );
458                }
459                paint_line_background(&mut line, removed_background);
460                line.set_line_background(removed_background);
461            } else if let Some(context_body) = trimmed.strip_prefix(' ') {
462                line.push_segment(context_style, " ");
463                line.push_segment(context_style, context_body);
464            } else {
465                line.push_segment(context_style, trimmed);
466            }
467        }
468        lines.push(line);
469    }
470
471    lines
472}
473
474/// Fill unpainted holes on a tinted diff row, including any blockquote/list
475/// prefix that was added before the diff marker.
476fn paint_line_background(line: &mut MarkdownLine, background: Option<AnstyleColor>) {
477    let Some(background) = background else {
478        return;
479    };
480    for segment in &mut line.segments {
481        if segment.style.get_bg_color().is_none() {
482            segment.style = segment.style.bg_color(Some(background));
483        }
484    }
485}
486
487/// Push a `+`/`-` diff body while preserving syntax foregrounds and applying
488/// the stronger background only to changed intraline ranges.
489fn push_highlighted_diff_body(
490    line: &mut MarkdownLine,
491    body: &str,
492    language: Option<&str>,
493    fallback: Style,
494    row_background: Option<AnstyleColor>,
495    word_ranges: &[(usize, usize)],
496    word_background: Option<AnstyleColor>,
497) {
498    let segments = render_diff_content_segments(body, language, fallback);
499    if segments.is_empty() {
500        line.push_segment(fallback.bg_color(row_background), " ");
501        return;
502    }
503
504    let mut cursor = 0usize;
505    for segment in segments {
506        let segment_len = segment.text.len();
507        let segment_end = cursor.saturating_add(segment_len);
508        let mut boundaries = vec![0, segment_len];
509        for &(start, end) in word_ranges {
510            if start < segment_end && end > cursor {
511                boundaries.push(start.max(cursor).saturating_sub(cursor).min(segment_len));
512                boundaries.push(end.min(segment_end).saturating_sub(cursor).min(segment_len));
513            }
514        }
515        boundaries.sort_unstable();
516        boundaries.dedup();
517
518        for pair in boundaries.windows(2) {
519            let start = pair[0];
520            let end = pair[1];
521            if start >= end {
522                continue;
523            }
524            let global_start = cursor.saturating_add(start);
525            let global_end = cursor.saturating_add(end);
526            let changed = word_background.is_some()
527                && word_ranges
528                    .iter()
529                    .any(|&(range_start, range_end)| global_start < range_end && global_end > range_start);
530            let background = if changed { word_background } else { row_background };
531            let mut style = segment.style.bg_color(background);
532            if style.get_fg_color().is_none() {
533                style = style.fg_color(fallback.get_fg_color());
534            }
535            line.push_segment(style, &segment.text[start..end]);
536        }
537        cursor = segment_end;
538    }
539}
540
541/// Map each normalized body line to byte-safe word-level ranges against its
542/// consecutive opposite-side line.
543fn word_level_ranges_for_normalized(normalized: &[String]) -> Vec<Vec<(usize, usize)>> {
544    let mut display = Vec::with_capacity(normalized.len());
545    for line in normalized {
546        let trimmed = line.trim_end_matches('\n');
547        let trimmed_start = trimmed.trim_start();
548        let kind = if is_diff_addition_line(trimmed_start) {
549            DiffDisplayKind::Addition
550        } else if is_diff_deletion_line(trimmed_start) {
551            DiffDisplayKind::Deletion
552        } else {
553            DiffDisplayKind::Context
554        };
555        let body = match kind {
556            DiffDisplayKind::Addition | DiffDisplayKind::Deletion => {
557                trimmed_start.strip_prefix(['+', '-']).unwrap_or("").to_owned()
558            }
559            DiffDisplayKind::Context | DiffDisplayKind::Metadata | DiffDisplayKind::HunkHeader => trimmed.to_owned(),
560        };
561        display.push(DiffDisplayLine::body(kind, None, None, body));
562    }
563    annotate_word_level_diffs(&mut display);
564    display.into_iter().map(|line| line.changed).collect()
565}
566
567fn diff_path_for_language(line: &str) -> Option<String> {
568    parse_diff_git_path(line).or_else(|| parse_diff_marker_path(line)).or_else(|| {
569        ["*** Update File:", "*** Add File:", "*** Delete File:"]
570            .iter()
571            .find_map(|prefix| line.strip_prefix(prefix).map(str::trim).filter(|path| !path.is_empty()))
572            .map(ToOwned::to_owned)
573    })
574}
575
576fn parse_diff_summary_line(line: &str) -> Option<(&str, usize, usize)> {
577    let summary = line.strip_prefix(DIFF_SUMMARY_PREFIX)?;
578    let (path, counts) = summary.rsplit_once(" (")?;
579    let counts = counts.strip_suffix(')')?;
580    let mut parts = counts.split_whitespace();
581    let additions = parts.next()?.strip_prefix('+')?.parse().ok()?;
582    let deletions = parts.next()?.strip_prefix('-')?.parse().ok()?;
583    Some((path, additions, deletions))
584}
585
586fn format_diff_summary(path: &str, additions: usize, deletions: usize) -> String {
587    format!("{DIFF_SUMMARY_PREFIX}{path} (+{additions} -{deletions})")
588}
589
590fn append_prefix_segments(line: &mut MarkdownLine, prefix_segments: &[MarkdownSegment]) {
591    for segment in prefix_segments {
592        line.push_segment(segment.style, &segment.text);
593    }
594}
595
596fn prefixed_line(prefix_segments: &[MarkdownSegment]) -> MarkdownLine {
597    let mut line = MarkdownLine::default();
598    append_prefix_segments(&mut line, prefix_segments);
599    line
600}
601
602fn line_number_style(theme_styles: &ThemeStyles, base_style: Style) -> Style {
603    let source = if base_style == theme_styles.tool_output {
604        theme_styles.tool_detail
605    } else {
606        base_style
607    };
608    // Blend the foreground with background at 35% for a visible but subdued gutter color.
609    // No DIMMED effect — keep line numbers readable without squinting.
610    let blended_fg = source
611        .get_fg_color()
612        .and_then(|fg| vtcode_commons::colors::blend_colors(&fg, &theme_styles.background, 0.35));
613    let mut style = Style::new();
614    if let Some(color) = blended_fg {
615        style = style.fg_color(Some(color));
616    } else if let Some(fg) = source.get_fg_color() {
617        style = style.fg_color(Some(fg));
618    } else {
619        // Last resort: use the theme foreground color
620        style = style.fg_color(Some(theme_styles.foreground));
621    }
622    style
623}
624
625/// Gutter style for a code block at the given visual weight.
626fn code_gutter_style(theme_styles: &ThemeStyles, base_style: Style, weight: CodeBlockWeight) -> Style {
627    match weight {
628        CodeBlockWeight::Primary => line_number_style(theme_styles, base_style),
629        CodeBlockWeight::Muted => muted_line_number_style(theme_styles),
630    }
631}
632
633/// Gutter style for a muted code surface.
634///
635/// The gutter is chrome, so it stays neutral: a muted block introduces the
636/// code with the theme foreground rather than the severity color of the
637/// surrounding incident, which would read as part of the code. It recedes by
638/// the same share as the primary gutter and stops at the theme's contrast
639/// floor, so the numbers stay readable on light and dark backgrounds alike.
640fn muted_line_number_style(theme_styles: &ThemeStyles) -> Style {
641    let receded = crate::theme::recede_toward_background(
642        theme_styles.foreground,
643        theme_styles.background,
644        MUTED_GUTTER_BLEND_RATIO,
645        crate::theme::get_minimum_contrast(),
646    );
647    Style::new().fg_color(Some(receded))
648}
649
650/// Format the gutter text for a line. Returns `(gutter_text, source_line_advance)`.
651fn format_gutter_text(line_num: usize, width: usize, line_text: &str) -> (String, usize) {
652    if let Some(omitted) = parse_omitted_line_count(line_text) {
653        let range_end = line_num.saturating_add(omitted.saturating_sub(1));
654        let range = format!("{line_num}-{range_end}");
655        (format!("{range:>width$}  "), omitted)
656    } else {
657        (format!("{line_num:>width$}  "), 1)
658    }
659}
660
661fn code_line_with_prefix(
662    prefix_segments: &[MarkdownSegment],
663    gutter_text: Option<&str>,
664    gutter_style: Style,
665) -> MarkdownLine {
666    let mut line = MarkdownLine::default();
667    append_prefix_segments(&mut line, prefix_segments);
668    if let Some(text) = gutter_text {
669        line.push_segment(gutter_style, text);
670    }
671    line
672}
673
674fn line_number_width(line_count: usize) -> usize {
675    let digits = line_count.max(1).to_string().len();
676    digits.max(CODE_LINE_NUMBER_MIN_WIDTH)
677}
678
679fn source_line_count(code: &str) -> usize {
680    code.lines().map(|line| parse_omitted_line_count(line).unwrap_or(1)).sum()
681}
682
683/// Parse the number of omitted lines from a condensed line like
684/// `"… [+220 lines omitted; ...]"`.
685fn parse_omitted_line_count(text: &str) -> Option<usize> {
686    let trimmed = text.trim();
687    let after = trimmed.strip_prefix("… [+")?;
688    let end = after.find(' ')?;
689    let count_str = &after[..end];
690    count_str.parse::<usize>().ok()
691}
692
693fn code_block_contains_table(content: &str, language: Option<&str>) -> bool {
694    let Some(lang) = language else {
695        return false;
696    };
697    let lang_lower = lang.to_ascii_lowercase();
698    if !matches!(lang_lower.as_str(), "markdown" | "md") {
699        return false;
700    }
701
702    let trimmed = content.trim();
703    if trimmed.is_empty() {
704        return false;
705    }
706
707    let mut has_pipe_line = false;
708    let mut has_separator = false;
709    for line in trimmed.lines().take(4) {
710        let line = line.trim();
711        if line.contains('|') {
712            has_pipe_line = true;
713        }
714        if line.starts_with('|') && line.chars().all(|c| matches!(c, '|' | '-' | ':' | ' ')) {
715            has_separator = true;
716        }
717    }
718    if !has_pipe_line || !has_separator {
719        return false;
720    }
721
722    let options = Options::ENABLE_TABLES;
723    let parser = Parser::new_ext(trimmed, options);
724    for event in parser {
725        match event {
726            Event::Start(Tag::Table(_)) => return true,
727            Event::Start(Tag::Paragraph) | Event::Text(_) | Event::SoftBreak => continue,
728            _ => return false,
729        }
730    }
731    false
732}
733
734fn rewrite_diff_line(line: &str) -> String {
735    // Preserve the authored hunk header (including range counts). Rewriting to
736    // start-only form made partial hunks such as `@@ -65,19 +65,0 @@` read as a
737    // one-line change, contradicting the enclosing `• Diff … (+0 -19)` summary.
738    line.to_string()
739}
740
741fn bump_diff_counters(line: &str, additions: &mut usize, deletions: &mut usize) {
742    let trimmed = line.trim_start();
743    if is_diff_addition_line(trimmed) {
744        *additions += 1;
745    } else if is_diff_deletion_line(trimmed) {
746        *deletions += 1;
747    }
748}
749
750fn is_diff_language(language: Option<&str>) -> bool {
751    language.is_some_and(|lang| matches!(lang.to_ascii_lowercase().as_str(), "diff" | "patch" | "udiff" | "git"))
752}
753
754fn code_block_style(theme_styles: &ThemeStyles, base_style: Style, weight: CodeBlockWeight) -> Style {
755    let base_fg = base_style.get_fg_color();
756    let theme_fg = theme_styles.output.get_fg_color();
757    let fg = if base_style.get_effects().contains(Effects::DIMMED) {
758        base_fg.or(theme_fg)
759    } else {
760        theme_fg.or(base_fg)
761    };
762    let mut style = base_style;
763    if let Some(color) = fg {
764        style = style.fg_color(Some(color));
765    } else {
766        // Ensure code text always has a visible foreground color
767        style = style.fg_color(Some(theme_styles.foreground));
768    }
769    apply_code_weight(style, theme_styles, weight)
770}
771
772/// Recede a code foreground toward the theme background.
773///
774/// Muted code keeps its hue so syntax-highlighted tokens stay
775/// distinguishable; only the intensity drops. The recede never crosses the
776/// theme's contrast floor, so evidence stays readable on light and dark
777/// backgrounds alike. The result is an explicit color rather than a faint/dim
778/// attribute, so it is identical on every terminal.
779fn apply_code_weight(style: Style, theme_styles: &ThemeStyles, weight: CodeBlockWeight) -> Style {
780    if weight != CodeBlockWeight::Muted {
781        return style;
782    }
783    let Some(foreground) = style.get_fg_color() else {
784        return style;
785    };
786    let receded = crate::theme::recede_toward_background(
787        foreground,
788        theme_styles.background,
789        MUTED_CODE_BLEND_RATIO,
790        crate::theme::get_minimum_contrast(),
791    );
792    style.fg_color(Some(receded))
793}
794
795pub(crate) fn normalize_code_indentation(code: &str, language: Option<&str>, preserve_indentation: bool) -> String {
796    if preserve_indentation {
797        return code.to_string();
798    }
799    let has_language_hint = language.is_some_and(|hint| {
800        matches!(
801            hint.to_lowercase().as_str(),
802            "rust"
803                | "rs"
804                | "python"
805                | "py"
806                | "javascript"
807                | "js"
808                | "jsx"
809                | "typescript"
810                | "ts"
811                | "tsx"
812                | "go"
813                | "golang"
814                | "java"
815                | "cpp"
816                | "c"
817                | "php"
818                | "html"
819                | "css"
820                | "sql"
821                | "csharp"
822                | "bash"
823                | "sh"
824                | "swift"
825        )
826    });
827
828    if !has_language_hint && language.is_some() {
829        return code.to_string();
830    }
831
832    let lines: Vec<&str> = code.lines().collect();
833    let min_indent = lines
834        .iter()
835        .filter(|line| !line.trim().is_empty())
836        .map(|line| &line[..line.len() - line.trim_start().len()])
837        .reduce(|acc, p| {
838            let mut len = 0;
839            for (c1, c2) in acc.chars().zip(p.chars()) {
840                if c1 != c2 {
841                    break;
842                }
843                len += c1.len_utf8();
844            }
845            &acc[..len]
846        })
847        .map(|s| s.len())
848        .unwrap_or(0);
849
850    let normalized = lines
851        .iter()
852        .map(|line| {
853            if line.trim().is_empty() {
854                line
855            } else if line.len() >= min_indent {
856                &line[min_indent..]
857            } else {
858                line
859            }
860        })
861        .collect::<Vec<_>>()
862        .join("\n");
863
864    if code.ends_with('\n') {
865        format!("{normalized}\n")
866    } else {
867        normalized
868    }
869}
870
871pub fn highlight_line_for_diff(line: &str, language: Option<&str>) -> Option<Vec<(Style, String)>> {
872    syntax_highlight::highlight_line_to_anstyle_segments(
873        line,
874        language,
875        syntax_highlight::get_active_syntax_theme(),
876        true,
877    )
878    .map(|segments| {
879        segments
880            .into_iter()
881            .map(|(style, text)| {
882                let fg = style.get_fg_color().map(|c| match c {
883                    anstyle::Color::Rgb(rgb) => {
884                        let brighten = |v: u8| (v as u16 * 120 / 100).min(255) as u8;
885                        anstyle::Color::Rgb(anstyle::RgbColor(brighten(rgb.0), brighten(rgb.1), brighten(rgb.2)))
886                    }
887                    anstyle::Color::Ansi(ansi) => match ansi {
888                        anstyle::AnsiColor::Black => anstyle::Color::Ansi(anstyle::AnsiColor::BrightWhite),
889                        anstyle::AnsiColor::Red => anstyle::Color::Ansi(anstyle::AnsiColor::BrightRed),
890                        anstyle::AnsiColor::Green => anstyle::Color::Ansi(anstyle::AnsiColor::BrightGreen),
891                        anstyle::AnsiColor::Yellow => anstyle::Color::Ansi(anstyle::AnsiColor::BrightYellow),
892                        anstyle::AnsiColor::Blue => anstyle::Color::Ansi(anstyle::AnsiColor::BrightBlue),
893                        anstyle::AnsiColor::Magenta => anstyle::Color::Ansi(anstyle::AnsiColor::BrightMagenta),
894                        anstyle::AnsiColor::Cyan => anstyle::Color::Ansi(anstyle::AnsiColor::BrightCyan),
895                        anstyle::AnsiColor::White => anstyle::Color::Ansi(anstyle::AnsiColor::BrightWhite),
896                        other => anstyle::Color::Ansi(other),
897                    },
898                    other => other,
899                });
900                let bg = style.get_bg_color();
901                let new_style = style.fg_color(fg).bg_color(bg);
902                (new_style, text)
903            })
904            .collect()
905    })
906}
907
908pub(crate) fn render_diff_content_segments(
909    content: &str,
910    language: Option<&str>,
911    fallback_style: Style,
912) -> Vec<MarkdownSegment> {
913    let text = content.trim_end_matches('\n');
914    if text.is_empty() {
915        return vec![MarkdownSegment::new(fallback_style, " ")];
916    }
917
918    // Prose diffs render as solid fallback: syntax colors on tinted diff
919    // backgrounds hurt contrast and obscure add/del semantics.
920    if is_prose_language_hint(language) {
921        return vec![MarkdownSegment::new(fallback_style, text)];
922    }
923
924    // Unknown/missing languages must stay solid so the diff add/del color
925    // (green/red) is preserved. Syntect falls back to "Plain Text" with a
926    // single default-style span, which would drop the diff foreground.
927    let hint = language.map(str::trim).filter(|hint| !hint.is_empty());
928    let Some(hint) = hint else {
929        return vec![MarkdownSegment::new(fallback_style, text)];
930    };
931    if std::ptr::eq(syntax_highlight::find_syntax_by_token(hint), syntax_highlight::find_syntax_plain_text()) {
932        return vec![MarkdownSegment::new(fallback_style, text)];
933    }
934
935    if let Some(segments) = highlight_line_for_diff(text, Some(hint))
936        && !segments.is_empty()
937    {
938        return segments
939            .into_iter()
940            .map(|(style, text)| MarkdownSegment::new(style, text))
941            .collect();
942    }
943
944    vec![MarkdownSegment::new(fallback_style, text)]
945}
946
947fn try_highlight(
948    code: &str,
949    language: Option<&str>,
950    config: &SyntaxHighlightingConfig,
951) -> Option<Vec<Vec<(Style, String)>>> {
952    let max_bytes = config.max_file_size_mb.saturating_mul(1024 * 1024);
953    if max_bytes > 0 && code.len() > max_bytes {
954        return None;
955    }
956
957    if let Some(lang) = language
958        && !config.enabled_languages.is_empty()
959    {
960        let direct_match = config.enabled_languages.iter().any(|entry| entry.eq_ignore_ascii_case(lang));
961        if !direct_match {
962            let syntax_ref = syntax_highlight::find_syntax_by_token(lang);
963            let resolved_match = config
964                .enabled_languages
965                .iter()
966                .any(|entry| entry.eq_ignore_ascii_case(&syntax_ref.name));
967            if !resolved_match {
968                return None;
969            }
970        }
971    }
972
973    let rendered = syntax_highlight::highlight_code_to_anstyle_line_segments(code, language, &config.theme, true);
974
975    Some(rendered)
976}
977
978#[derive(Clone, Debug)]
979pub struct HighlightedSegment {
980    style: Style,
981    text: String,
982}
983
984pub fn highlight_code_to_segments(
985    code: &str,
986    language: Option<&str>,
987    theme_name: &str,
988) -> Vec<Vec<HighlightedSegment>> {
989    syntax_highlight::highlight_code_to_anstyle_line_segments(code, language, theme_name, true)
990        .into_iter()
991        .map(|segments| {
992            segments
993                .into_iter()
994                .map(|(style, text)| HighlightedSegment { style, text })
995                .collect()
996        })
997        .collect()
998}
999
1000pub fn highlight_code_to_ansi(code: &str, language: Option<&str>, theme_name: &str) -> Vec<String> {
1001    let segments = highlight_code_to_segments(code, language, theme_name);
1002    segments
1003        .into_iter()
1004        .map(|line_segments| {
1005            let mut ansi_line = String::new();
1006            for seg in line_segments {
1007                let rendered = seg.style.render();
1008                let _ = write!(ansi_line, "{rendered}{}{}", seg.text, anstyle::Reset);
1009            }
1010            ansi_line
1011        })
1012        .collect()
1013}