diffler 0.16.1

Standalone magit-style git TUI and code reviewer, on its own or with your coding agent
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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
//! Pure diff-line renderers shared by the status screen's inline diffs and
//! the diff view: hunk headers, gutter line numbers, line-kind backgrounds,
//! intra-line emphasis ranges, and optional syntax foregrounds composited
//! per cell (syntax = fg, diff kind = bg, emphasis = stronger bg).

use std::ops::Range;

use diffler_core::highlight::StyledRange;
use diffler_core::model::{DiffLine, FileDiff, Hunk, LineKind};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

use crate::app::walkthrough::FigureBlock;
use crate::app::{ScrollAlign, SplitSide};
use crate::graph::Fit;
use crate::theme::Theme;

pub(super) fn align_scroll(
    align: ScrollAlign,
    cur_start: usize,
    cur_height: usize,
    height: usize,
) -> usize {
    match align {
        ScrollAlign::Center => (cur_start + cur_height / 2).saturating_sub(height / 2),
        ScrollAlign::Top => cur_start,
        ScrollAlign::Bottom => (cur_start + cur_height).saturating_sub(height),
    }
}

/// Per-file syntax for both diff sides, `(old, new)`, each indexed by line
/// number. The renderer picks the side per line via [`line_syntax`].
pub type SideSyntax<'a> = (&'a [Vec<StyledRange>], &'a [Vec<StyledRange>]);

/// Render one hunk as terminal lines: index 0 is the `@@` header, the rest
/// map 1:1 to `hunk.lines`. `selected` is an index into the returned vec
/// (0 = header) and paints that row with the cursor-line background.
///
/// `syntax` is the file's per-line syntax for both sides (`(old, new)`); when
/// present each line is highlighted exactly as the diff pane does, with syntax
/// foregrounds composited over the diff-kind background. `None` renders plain.
pub fn render_hunk_lines(
    theme: &Theme,
    hunk: &Hunk,
    syntax: Option<SideSyntax<'_>>,
    width: u16,
    selected: Option<usize>,
) -> Vec<Line<'static>> {
    let gutter = hunk_gutter_width(hunk);
    let mut lines = vec![hunk_header(theme, hunk, width, selected == Some(0), true)];
    lines.extend(hunk.lines.iter().enumerate().flat_map(|(index, line)| {
        let per_line = syntax.and_then(|(old, new)| line_syntax(old, new, line));
        render_diff_line(
            theme,
            line,
            per_line,
            gutter,
            width,
            LineFlags {
                selected: selected == Some(index + 1),
                focused: true,
                annotated: false,
            },
            &[],
        )
    }));
    lines
}

/// The per-line syntax slice for `line`, picked from the file's cached
/// highlights: the old side for deletions, the new side for additions and
/// context, indexed by the line's number. `None` when the line has no number
/// on that side or the cache lacks it (e.g. a not-yet-highlighted file).
pub fn line_syntax<'a>(
    old: &'a [Vec<StyledRange>],
    new: &'a [Vec<StyledRange>],
    line: &DiffLine,
) -> Option<&'a [StyledRange]> {
    let (side, number) = match line.kind {
        LineKind::Deleted => (old, line.old_no),
        LineKind::Added | LineKind::Context => (new, line.new_no),
    };
    let index = usize::try_from(number?).ok()?.checked_sub(1)?;
    side.get(index).map(Vec::as_slice)
}

/// Digits needed for the widest line number in the hunk, with a sane floor
/// so neighbouring hunks rarely disagree.
pub fn hunk_gutter_width(hunk: &Hunk) -> usize {
    let max = (hunk.old_start + hunk.old_lines)
        .max(hunk.new_start + hunk.new_lines)
        .max(1);
    (max.ilog10() as usize + 1).max(4)
}

/// One gutter width for a whole file, so hunks in the continuous diff view
/// line up.
pub fn file_gutter_width(file: &FileDiff) -> usize {
    let max = file
        .hunks
        .iter()
        .map(|h| (h.old_start + h.old_lines).max(h.new_start + h.new_lines))
        .max()
        .unwrap_or(1)
        .max(1);
    (max.ilog10() as usize + 1).max(4)
}

/// How far the hunk band sits off the diff surface, toward the border tint.
/// It has to clear both surfaces: the diff pane's panel and the status
/// screen's background.
const HUNK_BAND: u16 = 45;

/// Share of a cursor band an out-of-focus pane keeps: one bright selection is
/// on screen at a time, and the quiet one stays findable. Only the band moves
/// with focus; foregrounds and intra-line emphasis are content.
const UNFOCUSED_BAND: u16 = 35;

/// The cursor band over `surface`, quieted while its pane is out of focus.
pub(super) fn cursor_band(theme: &Theme, surface: Color, focused: bool) -> Color {
    crate::theme::blend(surface, theme.cursor_line, band_strength(100, focused))
}

/// The background and left bar every card in the diff pane draws first: a
/// comment, a walkthrough stop, the open composer. Banded when the row is
/// selected, the plain surface otherwise, with a solid `accent` bar turning
/// the row into a card against the diff lines around it.
pub(super) fn card_frame(
    theme: &Theme,
    selected: bool,
    focused: bool,
    accent: Color,
) -> (Color, Span<'static>) {
    let bg = if selected {
        cursor_band(theme, theme.bg, focused)
    } else {
        theme.bg
    };
    let bar = Span::styled("  ▌ ".to_owned(), Style::new().fg(accent).bg(bg));
    (bg, bar)
}

/// A band's blend strength, scaled down when its pane is out of focus.
const fn band_strength(full: u16, focused: bool) -> u16 {
    if focused {
        full
    } else {
        full * UNFOCUSED_BAND / 100
    }
}

/// A dim labeled separator band: `text` at the left, padded to `width`.
/// [`hunk_header`] and [`fold_row`] both draw through it, so the two
/// separators read as one kind of row. Several themes put their cursor band
/// within a few shades of this one, so a selected band also takes the accent
/// on its text, the way a sidebar header under the cursor does.
fn band_line(
    theme: &Theme,
    text: &str,
    width: u16,
    selected: bool,
    focused: bool,
) -> Line<'static> {
    let band = crate::theme::blend(theme.panel, theme.border, HUNK_BAND);
    let (bg, fg) = if selected {
        (cursor_band(theme, band, focused), theme.accent)
    } else {
        (band, theme.dim)
    };
    let text = crate::text::elide(text, width as usize);
    let pad = (width as usize).saturating_sub(text.width());
    Line::from(vec![
        Span::styled(text, Style::new().fg(super::readable_on(fg, bg)).bg(bg)),
        Span::styled(" ".repeat(pad), Style::new().bg(bg)),
    ])
}

/// GitHub-style section separator: a dim full-width band carrying git's
/// enclosing-section context (the `@@` line numbers are dropped as redundant
/// with the gutter). When git names no section the band alone reads as the
/// hunk boundary. Stays a navigable row so `{`/`}` hunk jumps land on it.
pub fn hunk_header(
    theme: &Theme,
    hunk: &Hunk,
    width: u16,
    selected: bool,
    focused: bool,
) -> Line<'static> {
    let ranges = format!(
        "@@ -{},{} +{},{} @@",
        hunk.old_start, hunk.old_lines, hunk.new_start, hunk.new_lines
    );
    let text = if hunk.context.is_empty() {
        format!(" {ranges}")
    } else {
        format!(" {ranges} {}", hunk.context)
    };
    band_line(theme, &text, width, selected, focused)
}

/// A fold row: the hunk header's band, naming what it hides.
pub fn fold_row(
    theme: &Theme,
    label: &str,
    width: u16,
    selected: bool,
    focused: bool,
) -> Line<'static> {
    band_line(theme, &format!(" {label}"), width, selected, focused)
}

/// Columns a diff line's rail + gutter numbers occupy before the text.
fn prefix_width(gutter: usize) -> usize {
    1 + gutter * 2 + 2
}

/// Rows the greedy wrapper produces for characters of the given display
/// widths: the same loop as [`wrap_spans`], counting instead of building,
/// so height predictions can never drift from the render (a width-2 glyph
/// at a row boundary wastes a column that plain division would miscount).
fn greedy_rows(widths: impl Iterator<Item = usize>, budget: usize) -> usize {
    let mut rows = 1;
    let mut used = 0;
    for cw in widths {
        if used + cw > budget && used > 0 {
            rows += 1;
            used = 0;
        }
        used += cw;
    }
    rows
}

fn char_widths(text: &str) -> impl Iterator<Item = usize> + '_ {
    text.chars()
        .map(|c| UnicodeWidthChar::width(c).unwrap_or(0))
}

/// Terminal rows a diff line needs at `width`: 1 plus one per wrapped
/// continuation. Agrees with [`render_diff_line`]'s wrapping by construction.
pub fn diff_line_height(line: &DiffLine, gutter: usize, width: u16) -> usize {
    text_height(&line.text, prefix_width(gutter), width)
}

/// Terminal rows `text` needs beside a prefix of `prefix_cols`. Agrees with
/// [`wrapped_rows`] by construction, so a caller can predict heights without
/// building the rows.
pub(super) fn text_height(text: &str, prefix_cols: usize, width: u16) -> usize {
    let budget = (width as usize).saturating_sub(prefix_cols).max(1);
    greedy_rows(char_widths(text), budget)
}

/// A diff line's selection/annotation state, orthogonal to its content.
#[derive(Clone, Copy)]
pub struct LineFlags {
    pub selected: bool,
    pub focused: bool,
    pub annotated: bool,
}

/// Render one diff line: gutter numbers, then the text composited from the
/// optional per-line syntax spans (fg) and the line's emphasis ranges (bg).
/// Text wider than the pane wraps onto continuation rows under a blank gutter.
pub fn render_diff_line(
    theme: &Theme,
    line: &DiffLine,
    syntax: Option<&[StyledRange]>,
    gutter: usize,
    width: u16,
    flags: LineFlags,
    search: &[(Range<usize>, bool)],
) -> Vec<Line<'static>> {
    let LineFlags {
        selected,
        focused,
        annotated,
    } = flags;
    let (base_bg, emph_bg) = line_backgrounds(theme, line, selected, focused, annotated);

    let number = |n: Option<u32>| match n {
        Some(n) => format!("{n:>gutter$}"),
        None => " ".repeat(gutter),
    };
    let prefix = |first: bool| {
        vec![
            Span::styled(
                rail(line),
                Style::new()
                    .fg(rail_color(theme, line, selected))
                    .bg(base_bg),
            ),
            Span::styled(
                if first {
                    format!(
                        "{} {}{}",
                        number(line.old_no),
                        number(line.new_no),
                        gutter_mark(line)
                    )
                } else {
                    " ".repeat(gutter * 2 + 2)
                },
                Style::new().fg(theme.dim).bg(base_bg),
            ),
        ]
    };
    let content = line_content(theme, line, syntax, base_bg, emph_bg, search);
    wrapped_rows(content, prefix, prefix_width(gutter), width, base_bg)
}

/// Lay one logical line out as rows: the content wrapped to whatever the
/// prefix leaves, each row carrying the prefix (blank on continuations) and
/// padded to the full width so the row background runs to the edge. The diff
/// pane and the file view differ only in what their prefix is.
pub(super) fn wrapped_rows(
    content: Vec<Span<'static>>,
    prefix: impl Fn(bool) -> Vec<Span<'static>>,
    prefix_cols: usize,
    width: u16,
    bg: Color,
) -> Vec<Line<'static>> {
    let budget = (width as usize).saturating_sub(prefix_cols).max(1);
    wrap_spans(content, budget)
        .into_iter()
        .enumerate()
        .map(|(row, segment)| {
            let mut spans = prefix(row == 0);
            spans.extend(segment);
            let used: usize = spans.iter().map(Span::width).sum();
            let pad = (width as usize).saturating_sub(used);
            if pad > 0 {
                spans.push(Span::styled(" ".repeat(pad), Style::new().bg(bg)));
            }
            Line::from(spans)
        })
        .collect()
}

/// Split styled spans into rows of at most `budget` display columns, cutting
/// at character boundaries so every style survives the wrap. Always yields at
/// least one row.
fn wrap_spans(spans: Vec<Span<'static>>, budget: usize) -> Vec<Vec<Span<'static>>> {
    let mut rows: Vec<Vec<Span<'static>>> = Vec::new();
    let mut current: Vec<Span<'static>> = Vec::new();
    let mut used = 0usize;
    for span in spans {
        let style = span.style;
        let mut chunk = String::new();
        for c in span.content.chars() {
            let cw = UnicodeWidthChar::width(c).unwrap_or(0);
            if used + cw > budget && used > 0 {
                if !chunk.is_empty() {
                    current.push(Span::styled(std::mem::take(&mut chunk), style));
                }
                rows.push(std::mem::take(&mut current));
                used = 0;
            }
            chunk.push(c);
            used += cw;
        }
        if !chunk.is_empty() {
            current.push(Span::styled(chunk, style));
        }
    }
    rows.push(current);
    rows
}

/// How far a selected changed line travels from its own tint toward that
/// tint's emphasis colour. Short of the emphasis itself, so intra-line
/// emphasis still stands out on the row under the cursor.
const SELECTION_LIFT: u16 = 55;

/// The line (base) and emphasis backgrounds, given selection/annotation state.
/// Selection brightens whatever colour the row already carries, so a selected
/// addition still reads as an addition. Only the base moves with focus; the
/// emphasis colour is content and comes back at full strength.
fn line_backgrounds(
    theme: &Theme,
    line: &DiffLine,
    selected: bool,
    focused: bool,
    annotated: bool,
) -> (Color, Color) {
    let (line_bg, emph_bg) = if line.reformat_only {
        (theme.panel, theme.panel)
    } else {
        match line.kind {
            LineKind::Added => (theme.add_line_bg, theme.add_emph_bg),
            LineKind::Deleted => (theme.del_line_bg, theme.del_emph_bg),
            LineKind::Context => (theme.panel, theme.panel),
        }
    };
    let reads_as_context = line.kind == LineKind::Context || line.reformat_only;
    let base_bg = match selected {
        true if reads_as_context => cursor_band(theme, theme.panel, focused),
        true => crate::theme::blend(line_bg, emph_bg, band_strength(SELECTION_LIFT, focused)),
        false if annotated => theme.annotated,
        false => line_bg,
    };
    (base_bg, emph_bg)
}

/// The reserved leading cell: a bar on a changed line, blank on context and
/// on a reformat-only line, which is unchanged in substance.
/// [`rail_color`] already tints it, so the kind of a line reads from the
/// margin even where the background tint is washed out.
fn rail(line: &DiffLine) -> &'static str {
    match line.kind {
        _ if line.reformat_only => " ",
        LineKind::Added | LineKind::Deleted => "▌",
        LineKind::Context => " ",
    }
}

/// The cell between the gutter numbers and the text: `≈` on a reformat-only
/// line, so the reader can tell a dimmed layout change from a context line.
fn gutter_mark(line: &DiffLine) -> &'static str {
    if line.reformat_only { "≈" } else { " " }
}

/// A line's text composited for the pane. A reformat-only line keeps no
/// syntax colour and dims its text, the way outdated and stale things dim.
fn line_content(
    theme: &Theme,
    line: &DiffLine,
    syntax: Option<&[StyledRange]>,
    base_bg: Color,
    emph_bg: Color,
    search: &[(Range<usize>, bool)],
) -> Vec<Span<'static>> {
    if !line.reformat_only {
        return composite_spans(
            theme,
            &line.text,
            &line.emphasis,
            syntax,
            base_bg,
            emph_bg,
            search,
        );
    }
    let dim = super::readable_on(theme.dim, base_bg);
    composite_spans(theme, &line.text, &[], None, base_bg, emph_bg, search)
        .into_iter()
        .map(|span| {
            let style = span.style.fg(dim);
            span.style(style)
        })
        .collect()
}

/// The rail's tint: the line's kind, or the accent on the row under the
/// cursor so selection reads on a second channel besides the background.
fn rail_color(theme: &Theme, line: &DiffLine, selected: bool) -> Color {
    if selected {
        return theme.accent;
    }
    match line.kind {
        LineKind::Added => theme.added,
        LineKind::Deleted => theme.error_fg,
        LineKind::Context => theme.dim,
    }
}

/// One side of a side-by-side row: the line and its per-line syntax, or `None`
/// for a column with no counterpart (a lone deletion's right, a lone
/// addition's left).
pub type SplitCell<'a> = Option<(&'a DiffLine, Option<&'a [StyledRange]>, bool)>;

/// Render one side-by-side row: the old line in the left column, the new line
/// in the right, divided by a separator. Each column shows a single gutter
/// number (old on the left, new on the right) and the same composited text the
/// unified view draws. `sel_left`/`sel_right` paint a column with the
/// cursor-line background.
/// Columns of a split cell taken by its rail + one gutter number.
fn split_prefix_width(gutter: usize) -> usize {
    1 + gutter + 1
}

/// Terminal rows a side-by-side row needs at `width`: the taller of its two
/// wrapped sides. Must agree with [`render_split_pair`]'s wrapping.
pub fn split_pair_height(
    left: Option<&DiffLine>,
    right: Option<&DiffLine>,
    gutter: usize,
    width: u16,
) -> usize {
    let total = width as usize;
    let left_w = total.saturating_sub(1) / 2;
    let right_w = total.saturating_sub(1 + left_w);
    let side = |line: Option<&DiffLine>, col_width: usize| {
        let Some(line) = line else { return 1 };
        let budget = col_width.saturating_sub(split_prefix_width(gutter)).max(1);
        greedy_rows(char_widths(&line.text), budget)
    };
    side(left, left_w).max(side(right, right_w))
}

/// Which side of a split row is under the cursor, and whether the pane holds
/// focus. `left`/`right` and `focused` are independent: only the cursor's side
/// carries `left`/`right`, both keep `focused` for how bright that reads.
#[derive(Clone, Copy)]
pub struct PairSelection {
    pub left: bool,
    pub right: bool,
    pub focused: bool,
}

pub fn render_split_pair(
    theme: &Theme,
    left: SplitCell<'_>,
    right: SplitCell<'_>,
    gutter: usize,
    width: u16,
    selection: PairSelection,
) -> Vec<Line<'static>> {
    let total = width as usize;
    let left_w = total.saturating_sub(1) / 2;
    let right_w = total.saturating_sub(1 + left_w);
    let mut left_rows = side_rows(
        theme,
        left,
        SplitSide::Left,
        gutter,
        left_w,
        selection.left,
        selection.focused,
    );
    let mut right_rows = side_rows(
        theme,
        right,
        SplitSide::Right,
        gutter,
        right_w,
        selection.right,
        selection.focused,
    );
    let rows = left_rows.len().max(right_rows.len());
    let filler = |cell: SplitCell<'_>, selected: bool, col_width: usize| {
        let bg = match cell {
            Some((line, ..)) => line_backgrounds(theme, line, selected, selection.focused, false).0,
            None if selected => cursor_band(theme, theme.panel, selection.focused),
            None => theme.panel,
        };
        vec![Span::styled(" ".repeat(col_width), Style::new().bg(bg))]
    };
    while left_rows.len() < rows {
        left_rows.push(filler(left, selection.left, left_w));
    }
    while right_rows.len() < rows {
        right_rows.push(filler(right, selection.right, right_w));
    }
    left_rows
        .into_iter()
        .zip(right_rows)
        .map(|(mut spans, right)| {
            spans.push(Span::styled(
                "│",
                Style::new().fg(theme.dim).bg(theme.panel),
            ));
            spans.extend(right);
            Line::from(spans)
        })
        .collect()
}

/// Render one column of a side-by-side row, wrapped and padded to
/// `col_width`; continuations get a blank gutter.
fn side_rows(
    theme: &Theme,
    cell: SplitCell<'_>,
    side: SplitSide,
    gutter: usize,
    col_width: usize,
    selected: bool,
    focused: bool,
) -> Vec<Vec<Span<'static>>> {
    let Some((line, syntax, annotated)) = cell else {
        let bg = if selected {
            cursor_band(theme, theme.panel, focused)
        } else {
            theme.panel
        };
        return vec![vec![Span::styled(
            " ".repeat(col_width),
            Style::new().bg(bg),
        )]];
    };
    let (base_bg, emph_bg) = line_backgrounds(theme, line, selected, focused, annotated);
    let number = match side {
        SplitSide::Left => line.old_no,
        SplitSide::Right => line.new_no,
    };
    let number = match number {
        Some(n) => format!("{n:>gutter$}"),
        None => " ".repeat(gutter),
    };
    let prefix = |first: bool| {
        vec![
            Span::styled(
                rail(line),
                Style::new()
                    .fg(rail_color(theme, line, selected))
                    .bg(base_bg),
            ),
            Span::styled(
                if first {
                    format!("{number}{}", gutter_mark(line))
                } else {
                    " ".repeat(gutter + 1)
                },
                Style::new().fg(theme.dim).bg(base_bg),
            ),
        ]
    };
    let content = line_content(theme, line, syntax, base_bg, emph_bg, &[]);
    let budget = col_width.saturating_sub(split_prefix_width(gutter)).max(1);
    wrap_spans(content, budget)
        .into_iter()
        .enumerate()
        .map(|(row, segment)| {
            let mut spans = prefix(row == 0);
            spans.extend(segment);
            clip_pad(spans, col_width, base_bg)
        })
        .collect()
}

/// Clip a styled run to `width` display columns, padding the remainder with
/// the background so every column fills exactly.
fn clip_pad(spans: Vec<Span<'static>>, width: usize, bg: Color) -> Vec<Span<'static>> {
    let mut out = Vec::new();
    let mut used = 0;
    for span in spans {
        if used >= width {
            break;
        }
        let w = span.width();
        if used + w <= width {
            used += w;
            out.push(span);
        } else {
            // clip by display width, not char count, so a wide (CJK/emoji)
            // glyph at the boundary can't overrun the column and shove the
            // neighbouring column off the pane
            let mut clipped = String::new();
            for ch in span.content.chars() {
                let cw = UnicodeWidthChar::width(ch).unwrap_or(0);
                if used + cw > width {
                    break;
                }
                clipped.push(ch);
                used += cw;
            }
            out.push(Span::styled(clipped, span.style));
            break;
        }
    }
    if used < width {
        out.push(Span::styled(" ".repeat(width - used), Style::new().bg(bg)));
    }
    out
}

/// Split the text at every syntax/emphasis range boundary and style each
/// segment: foreground from the syntax span covering it, background from
/// whether an emphasis range covers it. Byte offsets are snapped to char
/// boundaries defensively so a malformed range can never split a
/// multi-byte character.
/// Composite one line of text: syntax foregrounds over the row background,
/// with intraline emphasis and search hits taking their own background. The
/// diff pane and the file view both render through this.
pub(super) fn composite_spans(
    theme: &Theme,
    text: &str,
    emphasis: &[Range<usize>],
    syntax: Option<&[StyledRange]>,
    base_bg: Color,
    emph_bg: Color,
    search: &[(Range<usize>, bool)],
) -> Vec<Span<'static>> {
    let snap = |index: usize| snap_to_boundary(text, index.min(text.len()));

    let mut bounds = vec![0, text.len()];
    for range in emphasis {
        bounds.push(snap(range.start));
        bounds.push(snap(range.end));
    }
    for styled in syntax.unwrap_or_default() {
        bounds.push(snap(styled.range.start));
        bounds.push(snap(styled.range.end));
    }
    for (range, _) in search {
        bounds.push(snap(range.start));
        bounds.push(snap(range.end));
    }
    bounds.sort_unstable();
    bounds.dedup();

    // a search match outranks emphasis on the chars it covers
    let search_at = |at: usize| {
        search
            .iter()
            .find(|(range, _)| snap(range.start) <= at && at < snap(range.end))
            .map(|(_, current)| *current)
    };
    let emphasized = |at: usize| {
        emphasis
            .iter()
            .any(|range| snap(range.start) <= at && at < snap(range.end))
    };
    let syntax_at = |at: usize| {
        syntax?
            .iter()
            .find(|styled| snap(styled.range.start) <= at && at < snap(styled.range.end))
    };

    let mut spans = Vec::new();
    for pair in bounds.windows(2) {
        let &[start, end] = pair else { continue };
        let Some(segment) = text.get(start..end) else {
            continue;
        };
        if segment.is_empty() {
            continue;
        }
        let bg = match search_at(start) {
            Some(true) => theme.search_current,
            Some(false) => theme.search,
            None if emphasized(start) => emph_bg,
            None => base_bg,
        };
        let mut style = Style::new().fg(theme.fg).bg(bg);
        if let Some(styled) = syntax_at(start) {
            let (r, g, b) = styled.fg;
            style = style.fg(Color::Rgb(r, g, b));
            if styled.bold {
                style = style.add_modifier(Modifier::BOLD);
            }
            if styled.italic {
                style = style.add_modifier(Modifier::ITALIC);
            }
        }
        spans.push(Span::styled(segment.to_owned(), style));
    }
    spans
}

fn snap_to_boundary(text: &str, mut index: usize) -> usize {
    while index > 0 && !text.is_char_boundary(index) {
        index -= 1;
    }
    index
}

/// A figure rasterised into an offscreen buffer, then copied out row by row.
/// That is what lets a graph be half on screen: a widget drawn straight into
/// the frame can only start at a row that exists.
pub(super) fn figure_lines(
    figure: &mut FigureBlock,
    ordinal: usize,
    width: u16,
    theme: &Theme,
    bg: Color,
    open_hint: Option<&str>,
) -> Vec<Line<'static>> {
    let mut rows = vec![figure_header(figure, ordinal, theme, bg)];
    let area =
        ratatui::layout::Rect::new(0, 0, width.saturating_sub(2).max(1), figure.drawn_rows());
    let mut buffer = ratatui::buffer::Buffer::empty(area);
    figure
        .view
        .render(area, &mut buffer, &crate::graph::graph_theme(theme));
    // the cache always renders unselected; the caller re-tints it with
    // `fill_row` when the row it lands on is the one under the cursor
    let (_, bar) = card_frame(theme, false, false, theme.accent);
    for y in 0..area.height {
        let mut spans = vec![bar.clone()];
        let mut covered = 0;
        for x in 0..area.width {
            let cell = &buffer[(x, y)];
            // the cells a wide glyph spans stay in the buffer as blanks, so we
            // skip them or every CJK label would widen its row
            if covered > 0 {
                covered -= 1;
                continue;
            }
            covered = cell.symbol().width().saturating_sub(1);
            spans.push(Span::styled(
                cell.symbol().to_owned(),
                Style::new()
                    .fg(cell.fg)
                    .bg(opaque(cell.bg, bg))
                    .add_modifier(cell.modifier),
            ));
        }
        rows.push(Line::from(spans));
    }
    if figure.fit != Fit::AsDrawn {
        rows.push(fit_notice(figure, open_hint, width, theme, bg));
    }
    rows
}

/// A buffer cell the graph never painted carries [`Color::Reset`], which a
/// terminal with a transparent background shows the desktop through. A card is
/// a surface, so every cell it prints owns its background.
fn opaque(color: Color, bg: Color) -> Color {
    if color == Color::Reset { bg } else { color }
}

/// The dim line under a figure the card had to help fit: redrawn top-down,
/// or (rarer) still cropped even so. Leads with the key that opens a graph
/// full-screen, when one is bound, so a narrow card elides the explanation
/// and keeps what the reader can do about it.
fn fit_notice(
    figure: &FigureBlock,
    open_hint: Option<&str>,
    width: u16,
    theme: &Theme,
    bg: Color,
) -> Line<'static> {
    let (_, bar) = card_frame(theme, false, false, theme.accent);
    let graph = figure.is_graph();
    let why = match figure.fit {
        Fit::AsDrawn => "",
        Fit::Redrawn => "too wide side to side, drawn top to bottom",
        Fit::Cropped if graph => "too wide even top to bottom, some of it is cropped",
        Fit::Cropped => "too wide for this card, some of it is cropped",
    };
    let text = match open_hint.filter(|_| graph) {
        Some(key) => format!("{key} open full graph · {why}"),
        None => why.to_owned(),
    };
    let room = (width as usize).saturating_sub(bar.width());
    Line::from(vec![
        bar,
        Span::styled(
            crate::text::elide(&text, room),
            Style::new().fg(theme.dim).bg(bg),
        ),
    ])
}

fn figure_header(figure: &FigureBlock, ordinal: usize, theme: &Theme, bg: Color) -> Line<'static> {
    // the cache always renders unselected, matching `figure_lines`'s own bar
    let (_, bar) = card_frame(theme, false, false, theme.accent);
    let mut spans = vec![
        bar,
        Span::styled(
            format!("figure {ordinal}"),
            Style::new().fg(theme.accent).bg(bg),
        ),
    ];
    let stale = figure.stale();
    if stale > 0 {
        spans.push(Span::styled(
            format!("  {stale} stale"),
            Style::new().fg(theme.warn_fg).bg(bg),
        ));
    }
    Line::from(spans)
}

#[cfg(test)]
mod tests {
    use diffler_core::model::HunkId;
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;
    use ratatui::widgets::Paragraph;

    use super::*;

    /// A figure the card had to redraw top-down carries a dim line under it
    /// naming the key that opens the full graph; one that fits as drawn
    /// carries no such line.
    #[test]
    fn a_redrawn_figure_names_the_key_that_opens_the_full_graph() {
        use crate::app::walkthrough::{Block, blocks};

        let (theme, _) = Theme::from_name("github-dark");
        let wide_body = "\
```mermaid
flowchart LR
  a[routers/ai_visualization.py<br/>create, edit, perspective] --> b[second stage of the pipeline]
  b --> c[third stage of the pipeline]
  c --> d[fourth stage of the pipeline]
  d --> e[fifth stage of the pipeline]
```
";
        let Some(Block::Figure(mut wide)) = blocks(wide_body, 40).into_iter().next() else {
            panic!("a figure");
        };
        assert_eq!(wide.fit, Fit::Redrawn);
        let rows = figure_lines(&mut wide, 1, 40, &theme, theme.bg, Some("o"));
        assert_eq!(rows.len(), wide.rows(), "row count matches what was drawn");
        let notice = rows.last().expect("a notice row").to_string();
        assert!(notice.contains("o open full graph · too wide"), "{notice}");
        assert!(
            notice.trim_end().ends_with('…'),
            "a narrow card elides: {notice}"
        );
        assert_eq!(rows.last().map(Line::width), Some(40), "{notice}");

        let fits_body = "```mermaid\nflowchart LR\n  a[a] --> b[b]\n```\n";
        let Some(Block::Figure(mut fits)) = blocks(fits_body, 80).into_iter().next() else {
            panic!("a figure");
        };
        assert_eq!(fits.fit, Fit::AsDrawn);
        let rows = figure_lines(&mut fits, 1, 80, &theme, theme.bg, Some("o"));
        assert_eq!(rows.len(), fits.rows(), "no notice row added");
    }

    fn card_snapshot(rows: &[Line<'static>]) -> String {
        let width = rows.iter().map(Line::width).max().unwrap_or(0);
        let height = u16::try_from(rows.len()).unwrap_or(u16::MAX);
        let backend = TestBackend::new(u16::try_from(width).unwrap_or(u16::MAX), height);
        let mut terminal = Terminal::new(backend).expect("terminal");
        terminal
            .draw(|frame| {
                frame.render_widget(Paragraph::new(rows.to_vec()), frame.area());
            })
            .expect("draw");
        terminal.backend().to_string()
    }

    /// A body's first figure drawn into an 80-column pane, laid out to the
    /// card budget the pane gives it.
    fn figure_card(body: &str) -> String {
        use crate::app::composer::card_budget;
        use crate::app::walkthrough::{Block, blocks};

        let (theme, _) = Theme::from_name("github-dark");
        let Some(Block::Figure(mut figure)) = blocks(body, card_budget(80)).into_iter().next()
        else {
            panic!("a figure");
        };
        card_snapshot(&figure_lines(
            &mut figure,
            1,
            80,
            &theme,
            theme.bg,
            Some("o"),
        ))
    }

    #[test]
    fn a_sequence_diagram_renders_in_a_card() {
        insta::assert_snapshot!(figure_card(
            "```mermaid
sequenceDiagram
  autonumber
  participant UI as Browser
  participant API
  participant Auth as AuthService
  participant DB
  UI->>API: POST /login {user, pass}
  API->>Auth: verify(credentials)
  Note over Auth,DB: bcrypt compare happens here
  Auth->>DB: SELECT hash FROM users WHERE name = ?
  DB-->>Auth: row
  alt password matches
    Auth-->>API: token
    API->>API: cache session
    API-->>UI: 200 OK + cookie
  else mismatch
    Auth--xAPI: denied
    API-->>UI: 401 Unauthorized
  end
  link Auth: verify @ src/auth.rs#verify
```
"
        ));
    }

    #[test]
    fn a_callstack_renders_in_a_card() {
        insta::assert_snapshot!(figure_card(
            "```callstack
main
  serve @ src/server.rs#serve
    handle_request @ src/http.rs#handle_request
      - legacy_auth @ src/auth.rs#legacy_auth
      + authenticate @ src/auth.rs#authenticate
        + verify_token_signature_against_the_rotating_keyset_of_the_issuer @ src/jwt.rs#verify
      respond
```
"
        ));
    }

    /// A wide glyph spans two buffer cells, and the copy out of the figure's
    /// buffer has to take it once, or every CJK label widens its row.
    #[test]
    fn a_figure_with_wide_labels_keeps_its_rows_at_the_card_width() {
        let card = figure_card(
            "```callstack
main
  serve
    - 旧的认证
    + 验证令牌签名
```
",
        );
        insta::assert_snapshot!(card);
        let box_line = |line: &str| line.chars().filter(|c| *c == '└' || *c == '├').count();
        assert!(
            card.lines()
                .any(|line| box_line(line) > 0 && line.contains("验证令牌签名"))
        );
        assert!(!card.contains("验 证"), "{card}");
    }

    /// Two subgraphs and a decision, redrawn top-down to fit the card: both
    /// outlines draw, an edge crossing one keeps its arrowhead, and a title
    /// moves off the border an arrowhead pierces.
    #[test]
    fn a_flowchart_with_subgraphs_renders_in_a_card() {
        insta::assert_snapshot!(figure_card(
            "```mermaid
flowchart LR
  req[request] --> check{token valid?}
  subgraph auth[Auth layer]
    check -->|yes| load[load session]
    check -->|no| reject[401]
  end
  subgraph data[Data layer]
    load --> query[query db]
    query --> render[render page]
  end
```
"
        ));
    }

    #[test]
    fn align_scroll_positions_the_cursor_row() {
        assert_eq!(align_scroll(ScrollAlign::Top, 20, 1, 10), 20);
        assert_eq!(align_scroll(ScrollAlign::Bottom, 20, 1, 10), 11);
        assert_eq!(align_scroll(ScrollAlign::Center, 20, 1, 10), 15);
        // clamps at the top of the buffer
        assert_eq!(align_scroll(ScrollAlign::Center, 1, 1, 10), 0);
    }

    fn line(kind: LineKind, old: Option<u32>, new: Option<u32>, text: &str) -> DiffLine {
        DiffLine::new(kind, old, new, text.to_owned())
    }

    /// A reformat-only paired line reads as context with its text dimmed and
    /// a `≈` between the gutter and the text, whichever side it is. Under the
    /// cursor it takes the context band.
    #[test]
    fn reformat_only_lines_dim_instead_of_red_or_green() {
        let (theme, _) = Theme::from_name("github-dark");
        for kind in [LineKind::Deleted, LineKind::Added] {
            let mut reformat = line(kind, Some(1), Some(1), "x");
            reformat.reformat_only = true;

            let (bg, _) = line_backgrounds(&theme, &reformat, false, true, false);
            assert_eq!(bg, theme.panel, "{kind:?} reads as context");
            let (lit, _) = line_backgrounds(&theme, &reformat, true, true, false);
            assert_eq!(lit, theme.cursor_line, "{kind:?} takes the context band");

            let rendered = render_diff_line(&theme, &reformat, None, 4, 40, focused_flags(), &[]);
            let text: String = rendered[0]
                .spans
                .iter()
                .map(|s| s.content.as_ref())
                .collect();
            assert!(text.starts_with(' '), "no rail: {text:?}");
            assert!(text.contains("≈x"), "{text:?}");
            let body = rendered[0].spans.iter().find(|s| s.content == "x");
            assert_eq!(body.and_then(|s| s.style.fg), Some(theme.dim));
        }
    }

    fn focused_flags() -> LineFlags {
        LineFlags {
            selected: false,
            focused: true,
            annotated: false,
        }
    }

    fn sample_hunk() -> Hunk {
        let mut deleted = line(LineKind::Deleted, Some(2), None, "    41");
        deleted.emphasis.push(5..6);
        let mut added = line(LineKind::Added, None, Some(2), "    42");
        added.emphasis.push(5..6);
        Hunk {
            id: HunkId("h".into()),
            old_start: 1,
            old_lines: 3,
            new_start: 1,
            new_lines: 3,
            context: String::new(),
            lines: vec![
                line(LineKind::Context, Some(1), Some(1), "fn answer() {"),
                deleted,
                added,
                line(LineKind::Context, Some(3), Some(3), "}"),
            ],
        }
    }

    fn render(lines: &[Line<'static>]) -> Terminal<TestBackend> {
        let backend = TestBackend::new(60, 8);
        let mut terminal = Terminal::new(backend).expect("terminal");
        terminal
            .draw(|frame| frame.render_widget(Paragraph::new(lines.to_vec()), frame.area()))
            .expect("draw");
        terminal
    }

    #[test]
    fn hunk_renders_header_gutter_and_emphasis() {
        let theme = Theme::github_dark();
        let lines = render_hunk_lines(&theme, &sample_hunk(), None, 60, None);
        assert_eq!(lines.len(), 5, "header + 4 diff lines");
        let has_bg = |line: &Line<'_>, bg| line.spans.iter().any(|s| s.style.bg == Some(bg));
        assert!(has_bg(&lines[2], theme.del_emph_bg), "deleted emphasis bg");
        assert!(has_bg(&lines[3], theme.add_emph_bg), "added emphasis bg");
        insta::assert_snapshot!(render(&lines).backend());
    }

    #[test]
    fn emphasis_starting_at_byte_zero_is_rendered() {
        let theme = Theme::github_dark();
        let mut first_word = line(LineKind::Added, None, Some(1), "boo bar");
        first_word.emphasis.push(0..3);
        let hunk = Hunk {
            id: HunkId("h".into()),
            old_start: 1,
            old_lines: 0,
            new_start: 1,
            new_lines: 1,
            context: String::new(),
            lines: vec![first_word],
        };
        let lines = render_hunk_lines(&theme, &hunk, None, 60, None);
        let emphasized: String = lines[1]
            .spans
            .iter()
            .filter(|s| s.style.bg == Some(theme.add_emph_bg))
            .map(|s| s.content.as_ref())
            .collect();
        assert_eq!(emphasized, "boo");
    }

    #[test]
    fn selected_row_gets_cursor_background() {
        let theme = Theme::github_dark();
        let plain = render_hunk_lines(&theme, &sample_hunk(), None, 60, None);
        let selected = render_hunk_lines(&theme, &sample_hunk(), None, 60, Some(2));
        assert_eq!(plain[1], selected[1], "unselected rows unchanged");
        assert_ne!(plain[2], selected[2], "selected row repainted");
    }

    #[test]
    fn selecting_a_changed_line_brightens_its_own_tint() {
        let theme = Theme::github_dark();
        let green = |color| match color {
            Color::Rgb(_, g, _) => g,
            _ => 0,
        };
        let added = line(LineKind::Added, None, Some(1), "x");
        let (plain, emph) = line_backgrounds(&theme, &added, false, true, false);
        let (lit, _) = line_backgrounds(&theme, &added, true, true, false);
        assert!(green(plain) < green(lit), "selection brightens the row");
        assert!(green(lit) < green(emph), "and stays under the emphasis bg");
        assert_ne!(lit, theme.cursor_line, "the addition keeps its own hue");

        let context = line(LineKind::Context, Some(1), Some(1), "x");
        assert_eq!(
            line_backgrounds(&theme, &context, true, true, false).0,
            theme.cursor_line,
            "an unchanged row still gets the plain cursor band"
        );
    }

    #[test]
    fn an_unfocused_cursor_quiets_the_band_and_leaves_emphasis_alone() {
        let theme = Theme::github_dark();
        let luma = |color| match color {
            Color::Rgb(r, g, b) => u16::from(r) + u16::from(g) + u16::from(b),
            _ => 0,
        };
        for kind in [LineKind::Context, LineKind::Added, LineKind::Deleted] {
            let row = line(kind, Some(1), Some(1), "x");
            let (unmarked, _) = line_backgrounds(&theme, &row, false, false, false);
            let (bright, emph) = line_backgrounds(&theme, &row, true, true, false);
            let (quiet, quiet_emph) = line_backgrounds(&theme, &row, true, false, false);
            assert_ne!(
                quiet, unmarked,
                "{kind:?}: the row still reads as the cursor"
            );
            assert!(
                luma(unmarked) < luma(quiet) && luma(quiet) < luma(bright),
                "{kind:?}: the out-of-focus band sits between the two"
            );
            assert_eq!(quiet_emph, emph, "{kind:?}: emphasis never follows focus");
        }
    }

    #[test]
    fn an_unfocused_cursor_on_a_changed_row_keeps_its_intraline_emphasis() {
        let theme = Theme::github_dark();
        let mut added = line(LineKind::Added, None, Some(1), "let x = 42;");
        added.emphasis.push(8..10);
        let flags = LineFlags {
            selected: true,
            focused: false,
            annotated: false,
        };
        let rendered = render_diff_line(&theme, &added, None, 4, 60, flags, &[]);
        let emphasized: String = rendered[0]
            .spans
            .iter()
            .filter(|s| s.style.bg == Some(theme.add_emph_bg))
            .map(|s| s.content.as_ref())
            .collect();
        assert_eq!(emphasized, "42", "the emphasis keeps its full-strength bg");
    }

    #[test]
    fn emphasis_mid_multibyte_char_does_not_panic_or_split() {
        let theme = Theme::github_dark();
        // "é" is 2 bytes: a range ending inside it must snap, not panic
        let mut bad = line(LineKind::Added, None, Some(1), "héllo");
        bad.emphasis = vec![1..2, 3..4];
        let hunk = Hunk {
            id: HunkId("h".into()),
            old_start: 1,
            old_lines: 0,
            new_start: 1,
            new_lines: 1,
            context: String::new(),
            lines: vec![bad],
        };
        let lines = render_hunk_lines(&theme, &hunk, None, 40, None);
        let text: String = lines[1]
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect::<String>();
        assert!(text.contains("héllo"));
    }

    #[test]
    fn emphasis_range_past_end_is_clamped() {
        let theme = Theme::github_dark();
        let mut over = line(LineKind::Deleted, Some(1), None, "ab");
        over.emphasis.push(1..99);
        let hunk = Hunk {
            id: HunkId("h".into()),
            old_start: 1,
            old_lines: 1,
            new_start: 1,
            new_lines: 0,
            context: String::new(),
            lines: vec![over],
        };
        let lines = render_hunk_lines(&theme, &hunk, None, 40, None);
        let text: String = lines[1]
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect::<String>();
        assert!(text.contains("ab"));
    }

    #[test]
    fn syntax_spans_color_the_foreground_and_emphasis_keeps_the_bg() {
        let theme = Theme::github_dark();
        let mut added = line(LineKind::Added, None, Some(1), "let x = 42;");
        added.emphasis.push(8..10);
        let syntax = vec![
            StyledRange {
                range: 0..3,
                fg: (255, 0, 0),
                bold: true,
                italic: false,
            },
            StyledRange {
                range: 4..11,
                fg: (0, 255, 0),
                bold: false,
                italic: false,
            },
        ];
        let rendered = render_diff_line(
            &theme,
            &added,
            Some(&syntax),
            4,
            60,
            LineFlags {
                selected: false,
                focused: true,
                annotated: false,
            },
            &[],
        );
        assert_eq!(rendered.len(), 1, "short line stays one row");
        let keyword: Vec<_> = rendered[0]
            .spans
            .iter()
            .filter(|s| s.style.fg == Some(Color::Rgb(255, 0, 0)))
            .collect();
        assert_eq!(keyword.len(), 1);
        assert_eq!(keyword[0].content.as_ref(), "let");
        assert!(keyword[0].style.add_modifier.contains(Modifier::BOLD));
        // "42" carries both the syntax fg and the emphasis bg
        let emphasized: Vec<_> = rendered[0]
            .spans
            .iter()
            .filter(|s| s.style.bg == Some(theme.add_emph_bg))
            .collect();
        assert_eq!(emphasized.len(), 1);
        assert_eq!(emphasized[0].content.as_ref(), "42");
        assert_eq!(emphasized[0].style.fg, Some(Color::Rgb(0, 255, 0)));
    }

    #[test]
    fn every_added_line_keeps_the_full_background() {
        // reindents/moves included: there is no in-between render state
        let theme = Theme::github_dark();
        let reindented = line(LineKind::Added, None, Some(2), "    <Form>");
        let rendered = render_diff_line(&theme, &reindented, None, 3, 60, focused_flags(), &[]);
        assert!(
            rendered[0]
                .spans
                .iter()
                .any(|s| s.style.bg == Some(theme.add_line_bg)),
            "added lines always carry the added background"
        );
    }

    #[test]
    fn long_lines_wrap_under_a_blank_gutter_and_keep_their_text() {
        let theme = Theme::github_dark();
        let text = "x".repeat(100);
        let long = line(LineKind::Added, None, Some(2), &text);
        let width = 40u16;
        let rendered = render_diff_line(&theme, &long, None, 4, width, focused_flags(), &[]);
        assert_eq!(rendered.len(), diff_line_height(&long, 4, width));
        assert!(rendered.len() > 1, "100 columns cannot fit in 40");
        for row in &rendered {
            let total: usize = row.spans.iter().map(Span::width).sum();
            assert_eq!(total, width as usize, "every row fills the pane exactly");
        }
        let joined: String = rendered
            .iter()
            .flat_map(|row| row.spans.iter().map(|s| s.content.as_ref()))
            .collect();
        assert_eq!(
            joined.chars().filter(|c| *c == 'x').count(),
            100,
            "no character is lost to the wrap"
        );
        let continuation = &rendered[1].spans[1];
        assert!(
            continuation.content.chars().all(|c| c == ' '),
            "continuations get a blank gutter: {continuation:?}"
        );
    }

    #[test]
    fn split_pair_height_is_the_taller_wrapped_side() {
        let long = line(LineKind::Added, None, Some(2), &"y".repeat(60));
        let short = line(LineKind::Deleted, Some(2), None, "one");
        assert_eq!(split_pair_height(None, None, 4, 80), 1);
        // right column: 80 - 1 (divider) - 39 (left) = 40 wide, minus the
        // rail + gutter prefix of 6 = 34 text columns
        assert_eq!(
            split_pair_height(Some(&short), Some(&long), 4, 80),
            60usize.div_ceil(34)
        );
    }

    #[test]
    fn height_prediction_matches_the_render_for_wide_glyphs() {
        // width-2 glyphs waste a column at odd budgets; plain division
        // miscounts what the greedy wrapper actually emits
        let theme = Theme::github_dark();
        let cjk = line(LineKind::Added, None, Some(2), &"あ".repeat(5));
        for width in [14u16, 15, 16, 40] {
            let rendered = render_diff_line(&theme, &cjk, None, 4, width, focused_flags(), &[]);
            assert_eq!(
                rendered.len(),
                diff_line_height(&cjk, 4, width),
                "width {width}"
            );
        }
        let long = line(LineKind::Added, None, Some(2), &"あ".repeat(441));
        let rendered = render_diff_line(&theme, &long, None, 4, 100, focused_flags(), &[]);
        assert_eq!(rendered.len(), diff_line_height(&long, 4, 100));
    }

    #[test]
    fn file_gutter_width_spans_all_hunks() {
        let file = FileDiff {
            path: "f.rs".into(),
            old_path: None,
            status: diffler_core::model::FileStatus::Modified,
            binary: false,
            old_text: None,
            new_text: None,
            hunks: vec![
                Hunk {
                    id: HunkId("a".into()),
                    old_start: 1,
                    old_lines: 3,
                    new_start: 1,
                    new_lines: 3,
                    context: String::new(),
                    lines: vec![],
                },
                Hunk {
                    id: HunkId("b".into()),
                    old_start: 99990,
                    old_lines: 12,
                    new_start: 99990,
                    new_lines: 12,
                    context: String::new(),
                    lines: vec![],
                },
            ],
            hashes: diffler_core::model::HashCache::default(),
            blobs: diffler_core::model::BlobIds::default(),
        };
        assert_eq!(file_gutter_width(&file), 6);
        let empty = FileDiff {
            hunks: vec![],
            hashes: diffler_core::model::HashCache::default(),
            blobs: diffler_core::model::BlobIds::default(),
            ..file
        };
        assert_eq!(file_gutter_width(&empty), 4);
    }

    #[test]
    fn clip_pad_clips_by_display_width_not_char_count() {
        // five double-width glyphs are ten columns; clipping to six must keep
        // three glyphs, never overrun the column and shove a neighbour aside
        let spans = vec![Span::raw("一二三四五")];
        let out = clip_pad(spans, 6, Color::Reset);
        let width: usize = out.iter().map(Span::width).sum();
        assert_eq!(width, 6);
    }

    #[test]
    fn clip_pad_pads_a_short_run_to_the_column_width() {
        let out = clip_pad(vec![Span::raw("ab")], 6, Color::Reset);
        let width: usize = out.iter().map(Span::width).sum();
        assert_eq!(width, 6);
    }
}