croft 0.1.1

Per-project dev-loop tool: Docker Compose, scripts, hooks, and agents in one config
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
//! Render for the Diff view.
//!
//! Entry point: [`render`]. Three stacked panels share the area:
//! a top-left comparison banner, the file list below it, and the
//! diff/read body on the right. Body rendering branches on
//! [`crate::tui::views::diff::state::BodyMode`] into either the
//! unified-diff path or the read-full-file path; both share the
//! line-rendering helpers (`render_diff_body_line`,
//! `render_read_body_line`) and the bg-padding helper
//! (`fill_row_bg`).

use crate::tui::app::App;
use crate::tui::shared::scroll::Axis;
use crate::tui::ui::{SELECTION_BG, SELECTION_FG, SIDEBAR_RATIO, accent_of, panel_block_titled};
use crate::tui::views::diff::line_width::{diff_line_rendered_width, read_line_rendered_width};
use crate::tui::views::diff::state::{
    BodyMode, DiffFile, DiffFocus, DiffLine, DiffLineKind, DiffStatus, ReadLine, ReadLineKind,
};
use ratatui::Frame;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style, Stylize};
use ratatui::text::{Line, Span};
use ratatui::widgets::{
    Block, BorderType, Borders, HighlightSpacing, List, ListItem, ListState, Padding, Paragraph,
    Wrap,
};

/// Real Diff body: file list sidebar + diff body right pane.
pub fn render(app: &App, frame: &mut Frame, area: Rect) {
    let body = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(SIDEBAR_RATIO),
            Constraint::Percentage(100 - SIDEBAR_RATIO),
        ])
        .split(area);
    // Banner sits above the file list because it summarises the
    // whole comparison (branch → trunk, total churn), not the
    // currently-selected file's diff. Visual hierarchy: scope on
    // the left, contents on the right.
    let left = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(4), Constraint::Min(0)])
        .split(body[0]);
    render_header(app, frame, left[0]);
    // Stash the file-list and body rects so the mouse handler can
    // hit-test wheel/click events. Updated every frame so a window
    // resize is reflected on the next click.
    app.diff().files_rect.set(Some(left[1]));
    app.diff().body_rect.set(Some(body[1]));
    render_files(app, frame, left[1]);
    render_body(app, frame, body[1]);
}

/// Bordered block whose border colour changes with focus: bright
/// accent + bold when this pane has the keyboard focus, dim grey
/// otherwise. Mirrors the visual language used elsewhere; users see
/// a single "active" frame at a time. Bold on the focused border
/// gives a second cue (weight, not just colour) so the active pane
/// is unmistakable even on terminals that wash out 256-colour
/// indices.
fn diff_panel_block(title: Line<'static>, focused: bool, accent: Color) -> Block<'static> {
    let border = if focused {
        Style::default().fg(accent).add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(Color::DarkGray)
    };
    let border_type = if focused {
        BorderType::Thick
    } else {
        BorderType::Rounded
    };
    Block::default()
        .title(title)
        .borders(Borders::ALL)
        .border_type(border_type)
        .border_style(border)
}

/// Comparison banner — sits above the file list and tells the
/// user the scope of the diff: `<branch> → <trunk> · <short-sha>`
/// on row 1, `<n> files · +X −Y` on row 2. A bordered panel like
/// the file list and body so the three visually stack as one unit.
fn render_header(app: &App, frame: &mut Frame, area: Rect) {
    let diff = app.diff();
    let accent = accent_of(app);
    let trunk_label = diff.trunk.clone().unwrap_or_else(|| "HEAD".into());
    let branch_label = diff
        .branch
        .clone()
        .or_else(|| app.branch().map(str::to_string))
        .unwrap_or_else(|| "(detached)".into());

    let title = Line::from(vec![
        Span::raw(" "),
        Span::styled(
            "compare",
            Style::default().fg(accent).add_modifier(Modifier::BOLD),
        ),
        Span::raw(" "),
    ]);
    let block = panel_block_titled(title).padding(Padding::horizontal(2));

    let mut row1: Vec<Span<'static>> = vec![
        Span::styled(
            branch_label,
            Style::default().fg(accent).add_modifier(Modifier::BOLD),
        ),
        Span::styled(" → ", Style::default().fg(Color::DarkGray)),
        Span::styled(trunk_label, Style::default().add_modifier(Modifier::BOLD)),
    ];
    if let Some(sha) = diff.anchor_short.as_ref() {
        row1.push(Span::styled(" · ", Style::default().fg(Color::DarkGray)));
        row1.push(Span::styled(
            sha.clone(),
            Style::default().fg(Color::DarkGray),
        ));
    }

    let n = diff.files.len();
    let row2 = vec![
        Span::styled(
            format!("{n} {}", if n == 1 { "file" } else { "files" }),
            Style::default().fg(Color::White).dim(),
        ),
        Span::styled(" · ", Style::default().fg(Color::DarkGray)),
        Span::styled(
            format!("+{}", diff.additions_total),
            Style::default()
                .fg(Color::Green)
                .add_modifier(Modifier::BOLD),
        ),
        Span::raw(" "),
        Span::styled(
            format!("−{}", diff.deletions_total),
            Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
        ),
    ];

    let body = Paragraph::new(vec![Line::from(row1), Line::from(row2)])
        .block(block)
        .wrap(Wrap { trim: true });
    frame.render_widget(body, area);
}

fn render_files(app: &App, frame: &mut Frame, area: Rect) {
    let accent = accent_of(app);
    let diff = app.diff();
    let focused = diff.focus == DiffFocus::Files;
    let title = Line::from(vec![
        Span::raw(" "),
        Span::styled(
            "changes",
            Style::default().fg(accent).add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!(" ({}) ", diff.files.len()),
            Style::default().fg(Color::DarkGray),
        ),
    ]);
    let block = diff_panel_block(title, focused, accent);

    if !diff.loaded {
        let body = Paragraph::new(Line::from(Span::styled(
            "  loading…",
            Style::default().fg(Color::DarkGray),
        )))
        .block(block);
        frame.render_widget(body, area);
        return;
    }
    if let Some(err) = diff.error.as_ref() {
        let body = Paragraph::new(vec![
            Line::from(Span::styled(
                "  error".to_string(),
                Style::default().fg(Color::Red),
            )),
            Line::from(Span::styled(
                format!("  {err}"),
                Style::default().fg(Color::DarkGray),
            )),
        ])
        .block(block);
        frame.render_widget(body, area);
        return;
    }
    if diff.files.is_empty() {
        let trunk_hint = diff
            .trunk
            .as_deref()
            .map(|t| format!("  no changes vs {t}"))
            .unwrap_or_else(|| "  no changes — working tree clean".into());
        let body = Paragraph::new(vec![
            Line::from(""),
            Line::from(Span::styled(
                trunk_hint,
                Style::default().fg(Color::DarkGray),
            )),
            Line::from(""),
            Line::from(Span::styled(
                "  press r to refresh",
                Style::default().fg(Color::DarkGray),
            )),
        ])
        .block(block);
        frame.render_widget(body, area);
        return;
    }

    // Right-align the churn column — pad inner area so paths
    // truncate gracefully on narrow terminals before the churn.
    let inner_w = area.width.saturating_sub(2) as usize; // borders
    let churn_w = 14usize; // ` +999 -999 `, generous
    let path_w = inner_w.saturating_sub(churn_w + 4); // status letter + spaces

    let items: Vec<ListItem> = diff
        .files
        .iter()
        .map(|f| {
            let letter_style = match f.status {
                DiffStatus::Modified => Style::default().fg(Color::Yellow),
                DiffStatus::Added | DiffStatus::Untracked => Style::default().fg(Color::Green),
                DiffStatus::Deleted => Style::default().fg(Color::Red),
                DiffStatus::Renamed => Style::default().fg(Color::Indexed(75)),
                DiffStatus::Other => Style::default().fg(Color::DarkGray),
            };
            // Path elision: keep the tail (filename) over the head
            // when truncating — `…/tui/src/ui.rs` is more useful
            // than `crates/croft-tui/src/u…`.
            let path = elide_left(&f.path, path_w);
            let path_pad = path_w.saturating_sub(path.chars().count());
            let churn = if f.binary {
                vec![Span::styled("  bin", Style::default().fg(Color::DarkGray))]
            } else if f.status == DiffStatus::Untracked {
                // Untracked files can't have deletions by definition,
                // but we still render the `−0` column so the grid
                // aligns with tracked rows. Dim it so the eye lands
                // on the meaningful `+N` first.
                vec![
                    Span::styled(
                        format!("+{}", f.additions),
                        Style::default().fg(Color::Green),
                    ),
                    Span::raw(" "),
                    Span::styled("−0", Style::default().fg(Color::DarkGray)),
                ]
            } else {
                vec![
                    Span::styled(
                        format!("+{}", f.additions),
                        Style::default().fg(Color::Green),
                    ),
                    Span::raw(" "),
                    Span::styled(format!("−{}", f.deletions), Style::default().fg(Color::Red)),
                ]
            };
            let mut spans: Vec<Span<'static>> = vec![
                Span::styled(format!(" {} ", f.status.letter()), letter_style),
                Span::raw(path),
                Span::raw(" ".repeat(path_pad)),
            ];
            spans.extend(churn);
            ListItem::new(Line::from(spans))
        })
        .collect();
    let list = List::new(items)
        .block(block)
        .highlight_style(
            Style::default()
                .fg(SELECTION_FG)
                .bg(SELECTION_BG)
                .add_modifier(Modifier::BOLD),
        )
        .highlight_spacing(HighlightSpacing::Always);
    let mut state = ListState::default();
    state.select(Some(diff.selected));
    frame.render_stateful_widget(list, area, &mut state);

    // Capture per-file row rects for mouse hit-testing. ratatui's
    // List has auto-scrolled `state.offset()` so the selection stays
    // in view; we use that offset to map file index → on-screen row.
    // Items outside the visible window get a zero-area sentinel —
    // `rect_contains` filters them out at hit-test time.
    let inner_x = area.x.saturating_add(1);
    let inner_y = area.y.saturating_add(1);
    let inner_w = area.width.saturating_sub(2);
    let inner_h = area.height.saturating_sub(2);
    let offset = state.offset();
    let mut rects = diff.file_row_rects.borrow_mut();
    rects.clear();
    rects.reserve(diff.files.len());
    for i in 0..diff.files.len() {
        if i < offset {
            rects.push(Rect::default());
            continue;
        }
        let row = (i - offset) as u16;
        if row >= inner_h {
            rects.push(Rect::default());
            continue;
        }
        rects.push(Rect {
            x: inner_x,
            y: inner_y + row,
            width: inner_w,
            height: 1,
        });
    }
}

/// Truncate `s` from the left (head), keeping the tail. Adds an
/// ellipsis prefix when truncation happens. Operates on chars so
/// non-ASCII paths don't get sliced mid-codepoint.
fn elide_left(s: &str, max: usize) -> String {
    let count = s.chars().count();
    if count <= max {
        return s.to_string();
    }
    if max <= 1 {
        return "…".into();
    }
    let skip = count - (max - 1);
    let tail: String = s.chars().skip(skip).collect();
    format!("…{tail}")
}

fn render_body(app: &App, frame: &mut Frame, area: Rect) {
    let accent = accent_of(app);
    let diff = app.diff();
    let focused = diff.focus == DiffFocus::Body;
    let mode = diff.body_mode;
    let mode_label = match mode {
        BodyMode::Diff => "diff",
        BodyMode::Read => "read",
    };
    let title_text = match app.diff().selected_file() {
        Some(f) => format!("{mode_label} · {}", f.path),
        None => mode_label.into(),
    };
    let title = Line::from(vec![
        Span::raw(" "),
        Span::styled(
            title_text,
            Style::default().fg(accent).add_modifier(Modifier::BOLD),
        ),
        Span::raw(" "),
    ]);
    let block = diff_panel_block(title, focused, accent).padding(Padding::horizontal(1));

    // Stash the body's inner viewport height so the key handler
    // can size half-pages and clamp G to the bottom. -2 for the
    // top/bottom borders.
    let inner_height = area.height.saturating_sub(2);
    diff.body_height.set(inner_height);
    // Inner width = area width minus 2 borders minus 2 cols of
    // `Padding::horizontal(1)`. Used by the horizontal-scroll clamp
    // so panning stops when the longest row's right edge meets the
    // viewport's right edge.
    diff.body_width.set(area.width.saturating_sub(4));

    let Some(file) = app.diff().selected_file() else {
        let body = Paragraph::new(Line::from(Span::styled(
            "select a file on the left",
            Style::default().fg(Color::DarkGray),
        )))
        .block(block);
        frame.render_widget(body, area);
        return;
    };

    match mode {
        BodyMode::Diff => render_body_diff(app, frame, area, file, block, inner_height),
        BodyMode::Read => render_body_read(app, frame, area, file, block, inner_height),
    }
}

fn render_body_diff(
    app: &App,
    frame: &mut Frame,
    area: Rect,
    file: &DiffFile,
    block: Block<'static>,
    inner_height: u16,
) {
    let diff = app.diff();
    let lines = match app.diff().cache_for(&file.path) {
        Some(l) => l,
        None => {
            let body = Paragraph::new(Line::from(Span::styled(
                "loading diff…",
                Style::default().fg(Color::DarkGray),
            )))
            .block(block);
            frame.render_widget(body, area);
            return;
        }
    };

    // Gutter width: max line number across this file. Use string
    // length so 4-digit lines aren't squashed against the sigil.
    let max_lineno = lines
        .iter()
        .filter_map(|l| l.new_lineno.map(u64::from).or(l.old_lineno.map(u64::from)))
        .max()
        .unwrap_or(0);
    let gutter_w = max_lineno.to_string().len().max(1);

    let scroll = diff.diff_scroll.get(&file.path, Axis::Vertical);
    // `body_h_scroll` clamps to 0 when wrap is on — wrap mode
    // has no horizontal axis, and a stale map entry must not bleed
    // into rendering. Cast saturates so a >u16::MAX offset (which
    // would be a bug elsewhere) doesn't wrap around.
    let h_scroll: u16 = app.diff().body_h_scroll().min(u16::MAX as usize) as u16;
    let pane_w = area.width.saturating_sub(4) as usize;
    if diff.wrap {
        // Wrap mode: pre-wrap each rendered Line into pane-width
        // rows and bg-pad every wrapped row so the Added/Removed
        // tint extends to the right edge across continuations.
        // Done by hand because Paragraph's built-in wrap only paints
        // bg on the actual character cells of each soft-wrapped row.
        let rendered: Vec<Line<'static>> = lines
            .iter()
            .flat_map(|l| {
                let bg = diff_line_bg(l.kind);
                wrap_line_with_bg(render_diff_body_line(l, gutter_w, None), pane_w, bg)
            })
            .collect();
        let para = Paragraph::new(rendered)
            .block(block)
            .scroll((scroll as u16, 0));
        frame.render_widget(para, area);
    } else {
        // In non-wrap mode pad tinted rows to `max(pane_width,
        // longest_line)`. The pane-width floor extends bg out to
        // the right edge for short lines; the longest-line ceiling
        // keeps bg continuous as the user horizontally scrolls past
        // the pane edge — without it, scrolling reveals plain
        // terminal cells to the right of short tinted rows.
        let longest = lines
            .iter()
            .map(|l| diff_line_rendered_width(l, gutter_w))
            .max()
            .unwrap_or(0);
        let pad_to = Some(pane_w.max(longest));
        // Non-wrap: pre-slice to viewport so we don't pay for
        // off-screen lines on huge diffs.
        let max = inner_height as usize;
        let visible: Vec<Line<'static>> = lines
            .iter()
            .skip(scroll)
            .take(max)
            .map(|l| render_diff_body_line(l, gutter_w, pad_to))
            .collect();
        frame.render_widget(
            Paragraph::new(visible).block(block).scroll((0, h_scroll)),
            area,
        );
    }
}

fn render_body_read(
    app: &App,
    frame: &mut Frame,
    area: Rect,
    file: &DiffFile,
    block: Block<'static>,
    inner_height: u16,
) {
    let diff = app.diff();
    let lines = match app.diff().read_cache_for(&file.path) {
        Some(l) => l,
        None => {
            let body = Paragraph::new(Line::from(Span::styled(
                "loading file…",
                Style::default().fg(Color::DarkGray),
            )))
            .block(block);
            frame.render_widget(body, area);
            return;
        }
    };

    let max_lineno = lines.iter().map(|l| l.lineno).max().unwrap_or(0);
    let gutter_w = max_lineno.to_string().len().max(1);

    let scroll = diff.read_scroll.get(&file.path, Axis::Vertical);
    let h_scroll: u16 = app.diff().body_h_scroll().min(u16::MAX as usize) as u16;
    let pane_w = area.width.saturating_sub(4) as usize;
    if diff.wrap {
        let rendered: Vec<Line<'static>> = lines
            .iter()
            .flat_map(|l| {
                let bg = read_line_bg(l.kind);
                wrap_line_with_bg(render_read_body_line(l, gutter_w, None), pane_w, bg)
            })
            .collect();
        let para = Paragraph::new(rendered)
            .block(block)
            .scroll((scroll as u16, 0));
        frame.render_widget(para, area);
    } else {
        let longest = lines
            .iter()
            .map(|l| read_line_rendered_width(l, gutter_w))
            .max()
            .unwrap_or(0);
        let pad_to = Some(pane_w.max(longest));
        let max = inner_height as usize;
        let visible: Vec<Line<'static>> = lines
            .iter()
            .skip(scroll)
            .take(max)
            .map(|l| render_read_body_line(l, gutter_w, pad_to))
            .collect();
        frame.render_widget(
            Paragraph::new(visible).block(block).scroll((0, h_scroll)),
            area,
        );
    }
}

/// Right-pad the spans with bg-tinted whitespace so the row's
/// background extends to `pad_to` cells. No-op when `pad_to` is
/// None (wrap mode) or when the content already exceeds the
/// target. `bg` is the colour to fill; for non-tinted rows we
/// still fill so the row's bg matches the terminal default —
/// callers pass `None` to skip the fill entirely.
fn fill_row_bg(spans: &mut Vec<Span<'static>>, pad_to: Option<usize>, bg: Option<Color>) {
    let Some(width) = pad_to else { return };
    let Some(bg) = bg else { return };
    let used: usize = spans.iter().map(|s| s.width()).sum();
    if used >= width {
        return;
    }
    let pad = " ".repeat(width - used);
    spans.push(Span::styled(pad, Style::default().bg(bg)));
}

/// Hand-wrap a fully-styled Line into one-or-more Lines of `width`
/// cells each, padding each wrapped row's tail with bg-tinted
/// whitespace so the tint extends to the right edge. Used in wrap
/// mode in place of Paragraph's built-in wrap — ratatui's wrap only
/// paints bg on the actual character cells of each soft-wrapped
/// row, which leaves continuation rows visually disconnected from
/// the tinted first row.
fn wrap_line_with_bg(line: Line<'static>, width: usize, bg: Option<Color>) -> Vec<Line<'static>> {
    if width == 0 {
        return vec![line];
    }
    let mut rows: Vec<Vec<Span<'static>>> = Vec::new();
    let mut current: Vec<Span<'static>> = Vec::new();
    let mut current_w: usize = 0;

    for span in line.spans {
        if span.content.is_empty() {
            continue;
        }
        let style = span.style;
        let chars: Vec<char> = span.content.chars().collect();
        let mut idx = 0;
        while idx < chars.len() {
            if current_w == width {
                rows.push(std::mem::take(&mut current));
                current_w = 0;
            }
            let take = (width - current_w).min(chars.len() - idx);
            let chunk: String = chars[idx..idx + take].iter().collect();
            current.push(Span::styled(chunk, style));
            current_w += take;
            idx += take;
        }
    }
    if !current.is_empty() || rows.is_empty() {
        rows.push(current);
    }

    if let Some(bg_color) = bg {
        for row in &mut rows {
            let used: usize = row.iter().map(|s| s.width()).sum();
            if used < width {
                row.push(Span::styled(
                    " ".repeat(width - used),
                    Style::default().bg(bg_color),
                ));
            }
        }
    }

    rows.into_iter().map(Line::from).collect()
}

/// Diff-body row tint. Added → green, Removed → red, all other
/// kinds → none. Mirrors `read_line_bg` so wrap-mode can compute
/// the bg externally without re-running the renderer.
fn diff_line_bg(kind: DiffLineKind) -> Option<Color> {
    match kind {
        DiffLineKind::Added => Some(Color::Rgb(20, 38, 24)),
        DiffLineKind::Removed => Some(Color::Rgb(46, 22, 22)),
        _ => None,
    }
}

/// Read-mode row tint. Added → green, Modified → blue, Separator
/// → red, Plain → none. Matches the diff body's green/red palette
/// so a side-by-side comparison reads consistently.
fn read_line_bg(kind: ReadLineKind) -> Option<Color> {
    match kind {
        ReadLineKind::Added => Some(Color::Rgb(20, 38, 24)),
        ReadLineKind::Modified => Some(Color::Rgb(22, 30, 52)),
        ReadLineKind::Separator { .. } => Some(Color::Rgb(46, 22, 22)),
        ReadLineKind::Plain => None,
    }
}

/// Render one read-mode line. Plain → unstyled; Added/Modified →
/// row tint behind the gutter and source; Separator → synthetic
/// red row with a "− N lines removed" label centered in the gutter
/// + body area.
fn render_read_body_line(line: &ReadLine, gutter_w: usize, pad_to: Option<usize>) -> Line<'static> {
    let bg = read_line_bg(line.kind);

    if let ReadLineKind::Separator { removed } = line.kind {
        // Synthetic row marking a deleted block. The gutter is
        // blank but takes the same width so adjacent lines stay
        // aligned. The body shows a faint count, left-aligned with
        // a single leading space so it doesn't collide with the
        // gutter divider.
        let label = if removed == 1 {
            "− 1 line removed".to_string()
        } else {
            format!("− {removed} lines removed")
        };
        let mut spans: Vec<Span<'static>> = Vec::with_capacity(4);
        let gutter = format!("{:>width$} ", "", width = gutter_w);
        let red_dim = Color::Rgb(140, 90, 90);
        let row_bg = Style::default().bg(bg.unwrap_or(Color::Reset));
        spans.push(Span::styled(gutter, row_bg));
        spans.push(Span::styled(label, row_bg.fg(red_dim)));
        fill_row_bg(&mut spans, pad_to, bg);
        return Line::from(spans);
    }

    let mut spans: Vec<Span<'static>> = Vec::with_capacity(line.spans.len() + 3);
    let mut gutter_style = Style::default().fg(Color::DarkGray);
    if let Some(c) = bg {
        gutter_style = gutter_style.bg(c);
    }
    let gutter = format!("{:>width$} ", line.lineno, width = gutter_w);
    spans.push(Span::styled(gutter, gutter_style));
    if line.spans.is_empty() {
        let mut style = Style::default();
        if let Some(c) = bg {
            style = style.bg(c);
        }
        spans.push(Span::styled(line.text.clone(), style));
    } else {
        for s in &line.spans {
            let mut style = s.style;
            if let Some(c) = bg {
                style = style.bg(c);
            }
            spans.push(Span::styled(s.text.clone(), style));
        }
    }
    fill_row_bg(&mut spans, pad_to, bg);
    Line::from(spans)
}

/// Render one diff line: `<old> <new> <sigil> <code>` with a bg
/// tint on Added / Removed / Hunk lines and syntect-derived spans
/// for the inner code.
fn render_diff_body_line(line: &DiffLine, gutter_w: usize, pad_to: Option<usize>) -> Line<'static> {
    // Header lines (`diff --git`, `---`, `+++`, `index …`) keep
    // their full text and sit dim — no gutter, no sigil.
    if line.kind == DiffLineKind::Header {
        return Line::from(Span::styled(
            line.text.clone(),
            Style::default().fg(Color::DarkGray),
        ));
    }
    // Hunk headers fill the row width-ish with a cyan tint so
    // they stand out as section breaks.
    if line.kind == DiffLineKind::Hunk {
        return Line::from(Span::styled(
            line.text.clone(),
            Style::default()
                .fg(Color::Indexed(73))
                .add_modifier(Modifier::BOLD),
        ));
    }

    let bg_tint = diff_line_bg(line.kind);
    let sigil = match line.kind {
        DiffLineKind::Added => "+",
        DiffLineKind::Removed => "−",
        DiffLineKind::Context => " ",
        _ => " ",
    };
    let sigil_color = match line.kind {
        DiffLineKind::Added => Color::Green,
        DiffLineKind::Removed => Color::Red,
        _ => Color::DarkGray,
    };

    fn fmt_no(no: Option<u32>, width: usize) -> String {
        match no {
            Some(n) => format!("{:>width$}", n, width = width),
            None => format!("{:>width$}", "", width = width),
        }
    }

    let mut spans: Vec<Span<'static>> = Vec::with_capacity(line.spans.len() + 5);
    let gutter = format!(
        "{} {} ",
        fmt_no(line.old_lineno, gutter_w),
        fmt_no(line.new_lineno, gutter_w),
    );
    let mut gutter_style = Style::default().fg(Color::DarkGray);
    if let Some(bg) = bg_tint {
        gutter_style = gutter_style.bg(bg);
    }
    spans.push(Span::styled(gutter, gutter_style));
    let mut sigil_style = Style::default()
        .fg(sigil_color)
        .add_modifier(Modifier::BOLD);
    if let Some(bg) = bg_tint {
        sigil_style = sigil_style.bg(bg);
    }
    spans.push(Span::styled(format!("{sigil} "), sigil_style));
    if line.spans.is_empty() {
        // No syntect spans — fall back to the raw inner text so
        // we still render something readable.
        let inner = line.text.get(1..).unwrap_or("");
        let mut style = Style::default();
        if let Some(bg) = bg_tint {
            style = style.bg(bg);
        }
        spans.push(Span::styled(inner.to_string(), style));
    } else {
        for s in &line.spans {
            let mut style = s.style;
            if let Some(bg) = bg_tint {
                style = style.bg(bg);
            }
            spans.push(Span::styled(s.text.clone(), style));
        }
    }
    fill_row_bg(&mut spans, pad_to, bg_tint);
    Line::from(spans)
}