Skip to main content

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