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
//! Flattening a file's diff and its review comments into the row list the
//! pane renders.

use std::collections::HashMap;

use diffler_core::highlight::Highlighter;
use diffler_core::model::{DiffModel, FileDiff, Hunk, LineKind};
use diffler_core::session::{Anchor, Comment, CommentStatus, Session};
use diffler_core::walkthrough::Located;
use unicode_width::UnicodeWidthStr;

use crate::app::composer::{Composer, ComposerKind, ComposerLine, card_budget};
use crate::app::markdown::{self, MdSpan};
use crate::app::walkthrough::{Block, FigureCache, unresolved_explanation};

/// One terminal row of the diff pane. Indices point into the model the view
/// renders; the row list is rebuilt whenever the selected file, the model, or
/// the session change, so they never dangle. The `file` field equals the
/// selected file index everywhere except the walkthrough layout's all-slides
/// view, which windows several files' rows one after another.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiffRow {
    Hunk {
        file: usize,
        hunk: usize,
    },
    Line {
        file: usize,
        hunk: usize,
        line: usize,
    },
    /// One display line of a comment block; `line` indexes the block
    /// produced by [`comment_display`].
    Comment {
        comment: usize,
        line: usize,
        outdated: bool,
    },
    /// One display line of the open composer, sitting where its result will.
    Composer {
        line: usize,
    },
    /// One display line of the walkthrough's own summary card; `line` indexes
    /// the block produced by [`summary_display`].
    Summary {
        line: usize,
    },
    /// A folded hunk, standing in for its header and everything under it.
    /// `group` indexes the view's own `fold_groups`.
    Fold {
        file: usize,
        group: usize,
    },
}

impl DiffRow {
    /// A hunk's header row, open or folded: what `]`/`[` step between.
    pub(crate) fn is_hunk_header(&self) -> bool {
        matches!(self, Self::Hunk { .. } | Self::Fold { .. })
    }
}

/// One display line of a comment block. Body and reply text carry markdown
/// styling as flag-tagged runs; [`crate::ui`] maps the flags to concrete styles.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CommentLine {
    Header,
    Body(Vec<MdSpan>),
    /// Row `row` of the figure that is block `block` of the comment's body.
    Figure {
        block: usize,
        row: usize,
    },
    /// One line explaining why this stop or note has no code to show,
    /// rendered dim under the body.
    Note(Vec<MdSpan>),
    Reply {
        author: String,
        spans: Vec<MdSpan>,
        first: bool,
    },
    Footer,
}

/// What a visual selection yanks for one row, built alongside `rows` (which
/// carries indices, not text) since [`crate::app::rowsel::RowText::row_text`]
/// answers with no model or session in hand. A figure is the one row this
/// cannot resolve here: its box-drawing depends on the theme-driven graph
/// renderer that lives in `ui`, so it starts as a lookup key and the render
/// pass that already draws the same figure patches the text in once it runs.
#[derive(Debug, Clone)]
pub enum RowCopy {
    Text(String),
    Figure {
        key: String,
        block: usize,
        row: usize,
    },
}

impl RowCopy {
    pub fn text(&self) -> String {
        match self {
            Self::Text(text) => text.clone(),
            Self::Figure { .. } => String::new(),
        }
    }
}

fn md_spans_text(spans: &[MdSpan]) -> String {
    spans.iter().map(|span| span.text.as_str()).collect()
}

/// The marker and text of one diff line, exactly as a plain-text buffer would
/// hold it: `+`/`-`/` ` then the line's own text, gutter numbers left out.
pub(super) fn line_row_text(line: &diffler_core::model::DiffLine) -> String {
    let marker = match line.kind {
        LineKind::Added => '+',
        LineKind::Deleted => '-',
        LineKind::Context => ' ',
    };
    format!("{marker}{}", line.text)
}

/// A hunk row's header, the same ranges git itself prints.
fn hunk_header_text(hunk: &Hunk) -> String {
    let ranges = format!(
        "@@ -{},{} +{},{} @@",
        hunk.old_start, hunk.old_lines, hunk.new_start, hunk.new_lines
    );
    if hunk.context.is_empty() {
        ranges
    } else {
        format!("{ranges} {}", hunk.context)
    }
}

/// A comment card's header line as plain text: title (a stop's), author,
/// status, and the outdated/stale flags the card shows beside them.
fn comment_header_text(comment: &Comment, outdated: bool, unresolved: bool) -> String {
    let status = match comment.status {
        CommentStatus::Open => "open",
        CommentStatus::Replied => "replied",
        CommentStatus::Resolved => "resolved",
    };
    let mut text = String::new();
    if let Some(title) = comment.title.as_deref() {
        text.push_str(title);
        text.push_str("  ");
    }
    text.push_str(&comment.author);
    text.push_str(" · ");
    text.push_str(status);
    if outdated {
        text.push_str(" · outdated");
    }
    if unresolved {
        text.push_str(" · stale");
    }
    text
}

/// A composer row's text: the draft line itself for a body row, nothing for
/// the header/footer chrome around it.
fn composer_line_text(line: &ComposerLine) -> String {
    match line {
        ComposerLine::Body { text, .. } => text.clone(),
        ComposerLine::Header | ComposerLine::Footer => String::new(),
    }
}

/// What one display line of a comment or summary card yanks: its prose for a
/// body/note/reply line, so several selected rows read as the paragraph they
/// look like; `header` for the header line (built by the caller, since a
/// summary's is a bare title and a comment's carries status); nothing for the
/// footer, a bar with no content; a figure key for the caller's render pass
/// to resolve later.
pub(super) fn row_copy_for(line: &CommentLine, header: &str, key: &str) -> RowCopy {
    match line {
        CommentLine::Header => RowCopy::Text(header.to_owned()),
        CommentLine::Body(spans) | CommentLine::Note(spans) => RowCopy::Text(md_spans_text(spans)),
        CommentLine::Reply {
            author,
            spans,
            first,
        } => {
            let mut text = if *first {
                format!("â”” {author}: ")
            } else {
                "  ".to_owned()
            };
            text.push_str(&md_spans_text(spans));
            RowCopy::Text(text)
        }
        CommentLine::Figure { block, row } => RowCopy::Figure {
            key: key.to_owned(),
            block: *block,
            row: *row,
        },
        CommentLine::Footer => RowCopy::Text(String::new()),
    }
}

/// The header, body and figures of `body` at `row_width` columns, markdown
/// rendered and long text wrapped to fit. `blocks` is the body already split
/// around its `mermaid` fences, for a body that holds one; without it the
/// whole body is prose. Shared by a comment's card and the walkthrough
/// summary's, so a `mermaid` fence renders as a figure through the same path
/// in both.
fn body_display(
    body: &str,
    row_width: u16,
    highlighter: Option<&Highlighter>,
    blocks: Option<&[Block]>,
) -> Vec<CommentLine> {
    let budget = card_budget(row_width);
    let mut lines = vec![CommentLine::Header];
    match blocks {
        Some(blocks) => {
            for (block, part) in blocks.iter().enumerate() {
                match part {
                    Block::Prose(prose) => {
                        lines.extend(prose.iter().cloned().map(CommentLine::Body));
                    }
                    Block::Figure(figure) => {
                        lines.extend(
                            (0..figure.rows()).map(|row| CommentLine::Figure { block, row }),
                        );
                    }
                }
            }
        }
        None => {
            for logical in markdown::parse(body, highlighter, budget) {
                lines.extend(
                    markdown::wrap(&logical, budget, budget)
                        .into_iter()
                        .map(CommentLine::Body),
                );
            }
        }
    }
    lines
}

/// The terminal lines a comment occupies at `row_width` columns. Shared by
/// row flattening (for counts) and rendering (for content) so they can never
/// disagree. `unresolved` is the reason this comment's own anchor stopped
/// resolving, when it did; it renders as one dim line under the body.
pub fn comment_display(
    comment: &Comment,
    row_width: u16,
    highlighter: Option<&Highlighter>,
    blocks: Option<&[Block]>,
    unresolved: Option<Located>,
) -> Vec<CommentLine> {
    let budget = card_budget(row_width);
    let mut lines = body_display(&comment.body, row_width, highlighter, blocks);
    if let Some(reason) =
        unresolved.and_then(|reason| unresolved_explanation(&comment.anchor.file, reason))
    {
        for logical in markdown::parse(&reason, None, budget) {
            lines.extend(
                markdown::wrap(&logical, budget, budget)
                    .into_iter()
                    .map(CommentLine::Note),
            );
        }
    }
    for reply in &comment.replies {
        // the author label only renders on the first line; continuations get
        // the renderer's two-space indent
        let label = format!("â”” {}: ", reply.author).width();
        let mut first = true;
        // a table lays out at parse time and `wrap` then leaves it alone, so
        // it has to fit the narrowest line of the reply: the labelled one
        let laid_out = budget.saturating_sub(label.max(2)).max(8);
        for logical in markdown::parse(&reply.body, highlighter, laid_out) {
            let head = budget.saturating_sub(if first { label } else { 2 }).max(8);
            for spans in markdown::wrap(&logical, head, budget.saturating_sub(2).max(8)) {
                lines.push(CommentLine::Reply {
                    author: reply.author.clone(),
                    spans,
                    first,
                });
                first = false;
            }
        }
    }
    lines.push(CommentLine::Footer);
    lines
}

/// The terminal lines the walkthrough's own summary occupies: the same
/// header/body/figure/footer shape a comment's card gets, with no replies
/// since nothing answers a summary directly.
pub fn summary_display(
    body: &str,
    row_width: u16,
    highlighter: Option<&Highlighter>,
    blocks: Option<&[Block]>,
) -> Vec<CommentLine> {
    let mut lines = body_display(body, row_width, highlighter, blocks);
    lines.push(CommentLine::Footer);
    lines
}

/// Hunk and line indices a comment displays under; `None` when the
/// anchored line is absent from the file's hunks. Outdated detection lives
/// in [`Anchor::is_outdated`], which shares the same end-line semantics.
fn anchor_target(file: &FileDiff, anchor: &Anchor) -> Option<(usize, usize)> {
    // range comments display under the end of their range
    let target = anchor.line_end.or(anchor.line)?;
    for (hunk_idx, hunk) in file.hunks.iter().enumerate() {
        let found = hunk
            .lines
            .iter()
            .position(|l| l.number_on(anchor.on_old_side) == Some(target));
        if let Some(line_idx) = found {
            return Some((hunk_idx, line_idx));
        }
    }
    None
}

/// The open composer and the rows it draws, carried through row building so
/// its rows land exactly where its result will. `lines` is computed once and
/// doubles as the height, so text and count can never drift apart.
struct Draft<'a> {
    composer: &'a Composer,
    lines: Vec<ComposerLine>,
}

impl Draft<'_> {
    fn new(composer: Option<&Composer>, wrap_width: u16) -> Option<Draft<'_>> {
        let composer = composer?;
        Some(Draft {
            lines: composer.display(wrap_width),
            composer,
        })
    }

    fn edits(&self, id: &str) -> bool {
        matches!(self.composer.kind, ComposerKind::Edit { .. })
            && self.composer.comment_id() == Some(id)
    }

    fn replies_to(&self, id: &str) -> bool {
        matches!(self.composer.kind, ComposerKind::Reply { .. })
            && self.composer.comment_id() == Some(id)
    }

    /// The hunk and line the composer's new comment will display under, or
    /// `None` when it is file-level or belongs to another file.
    fn new_at(&self, file: &FileDiff) -> Option<(usize, usize)> {
        let anchor = self.composer.anchor()?;
        (anchor.file == file.path).then(|| anchor_target(file, anchor))?
    }

    /// A file-level new comment: the composer opens above the diff, where a
    /// whole-file comment renders.
    fn is_unanchored(&self, file: &FileDiff) -> bool {
        self.composer
            .anchor()
            .is_some_and(|anchor| anchor.file == file.path && anchor_target(file, anchor).is_none())
    }
}

/// The inputs a card row's build needs but that never vary within one row
/// pass: the session its comments live in, the width bodies wrap to, the
/// composer's open draft when there is one, the figure cache, and which
/// comments' anchors stopped resolving. Bundled the way `TreeRowCtx` bundles
/// a sidebar row's render inputs (`crate::ui::diff`), so they travel as one
/// value through row building instead of as five separate parameters.
#[derive(Clone, Copy)]
struct RowCtx<'a> {
    session: &'a Session,
    wrap_width: u16,
    draft: Option<&'a Draft<'a>>,
    figures: &'a FigureCache,
    unresolved_anchors: &'a HashMap<String, Located>,
}

fn push_comment_rows(
    rows: &mut Vec<DiffRow>,
    copy: &mut Vec<RowCopy>,
    comments: &[(usize, bool)],
    ctx: RowCtx<'_>,
) {
    for &(comment, outdated) in comments {
        let Some(c) = ctx.session.comments.get(comment) else {
            continue;
        };
        if ctx.draft.is_some_and(|d| d.edits(&c.id)) {
            push_draft_rows(rows, copy, ctx.draft);
            continue;
        }
        let unresolved = ctx.unresolved_anchors.get(&c.id).copied();
        let lines = comment_display(
            c,
            ctx.wrap_width,
            None,
            blocks_of(ctx.figures, &c.id),
            unresolved,
        );
        let header = comment_header_text(c, outdated, unresolved.is_some());
        for (line, part) in lines.iter().enumerate() {
            rows.push(DiffRow::Comment {
                comment,
                line,
                outdated,
            });
            copy.push(row_copy_for(part, &header, &c.id));
        }
        if ctx.draft.is_some_and(|d| d.replies_to(&c.id)) {
            push_draft_rows(rows, copy, ctx.draft);
        }
    }
}

fn push_draft_rows(rows: &mut Vec<DiffRow>, copy: &mut Vec<RowCopy>, draft: Option<&Draft<'_>>) {
    let Some(draft) = draft else { return };
    for (line, part) in draft.lines.iter().enumerate() {
        rows.push(DiffRow::Composer { line });
        copy.push(RowCopy::Text(composer_line_text(part)));
    }
}

/// A comment's body already split around its figures, for the ones that have
/// any. Row building and rendering both read it from here, so they count the
/// same lines.
pub fn blocks_of<'a>(figures: &'a FigureCache, id: &str) -> Option<&'a [Block]> {
    Some(figures.get(id)?.blocks.as_slice())
}

/// Bucket a file's comments by their `(hunk, line)` anchor for inline display.
/// A line anchor that no longer exists is outdated, and a file-level comment
/// has no line: both land in the unanchored list, rendered at the top.
type CommentBuckets = (
    HashMap<(usize, usize), Vec<(usize, bool)>>,
    Vec<(usize, bool)>,
);

fn collect_comments(file: &FileDiff, session: &Session, model: &DiffModel) -> CommentBuckets {
    let mut by_line: HashMap<(usize, usize), Vec<(usize, bool)>> = HashMap::new();
    let mut unanchored: Vec<(usize, bool)> = Vec::new();
    for (comment_idx, comment) in session.comments.iter().enumerate() {
        if comment.anchor.file != file.path {
            continue;
        }
        let outdated = comment.anchor.is_outdated(model);
        match anchor_target(file, &comment.anchor) {
            Some((hunk, line)) => by_line
                .entry((hunk, line))
                .or_default()
                .push((comment_idx, outdated)),
            None => unanchored.push((comment_idx, outdated)),
        }
    }
    (by_line, unanchored)
}

/// Build the diff-pane rows for one file: its hunks and lines, with comment
/// blocks under their anchored line, file-level (or orphaned) comments first.
/// `copy` is what a visual selection yanks for each row, built in the same
/// pass so it can never disagree with what `rows` holds.
pub(super) fn build_rows(
    model: &DiffModel,
    session: &Session,
    selected: usize,
    wrap_width: u16,
    composer: Option<&Composer>,
    figures: &FigureCache,
    unresolved_anchors: &HashMap<String, Located>,
) -> (Vec<DiffRow>, Vec<RowCopy>) {
    let mut rows = Vec::new();
    let mut copy = Vec::new();
    let Some(file) = model.files.get(selected) else {
        return (rows, copy);
    };
    let draft = Draft::new(composer, wrap_width);
    let ctx = RowCtx {
        session,
        wrap_width,
        draft: draft.as_ref(),
        figures,
        unresolved_anchors,
    };
    let (by_line, unanchored) = collect_comments(file, session, model);
    push_comment_rows(&mut rows, &mut copy, &unanchored, ctx);
    if ctx.draft.is_some_and(|d| d.is_unanchored(file)) {
        push_draft_rows(&mut rows, &mut copy, ctx.draft);
    }
    let new_at = ctx.draft.and_then(|d| d.new_at(file));
    for (hunk_idx, hunk) in file.hunks.iter().enumerate() {
        rows.push(DiffRow::Hunk {
            file: selected,
            hunk: hunk_idx,
        });
        copy.push(RowCopy::Text(hunk_header_text(hunk)));
        for (line_idx, line) in hunk.lines.iter().enumerate() {
            rows.push(DiffRow::Line {
                file: selected,
                hunk: hunk_idx,
                line: line_idx,
            });
            copy.push(RowCopy::Text(line_row_text(line)));
            if let Some(list) = by_line.get(&(hunk_idx, line_idx)) {
                push_comment_rows(&mut rows, &mut copy, list, ctx);
            }
            if new_at == Some((hunk_idx, line_idx)) {
                push_draft_rows(&mut rows, &mut copy, ctx.draft);
            }
        }
    }
    (rows, copy)
}

/// Which column of a side-by-side row a line belongs to: the old side renders
/// on the left, the new side on the right.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SplitSide {
    Left,
    Right,
}

/// One row of the side-by-side diff body. `left`/`right` index into the hunk's
/// lines: a context row carries the same index on both sides, a modified row
/// pairs a deletion with an addition, and a lone deletion or addition fills one
/// side with `None`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SplitRow {
    Hunk {
        hunk: usize,
    },
    Pair {
        hunk: usize,
        left: Option<usize>,
        right: Option<usize>,
    },
    Comment {
        comment: usize,
        line: usize,
        outdated: bool,
    },
    Composer {
        line: usize,
    },
    /// The side-by-side counterpart of [`DiffRow::Fold`]: folded hunk `hunk`.
    Fold {
        hunk: usize,
    },
}

fn push_split_comments(rows: &mut Vec<SplitRow>, comments: &[(usize, bool)], ctx: RowCtx<'_>) {
    for &(comment, outdated) in comments {
        let Some(c) = ctx.session.comments.get(comment) else {
            continue;
        };
        if ctx.draft.is_some_and(|d| d.edits(&c.id)) {
            push_split_draft_rows(rows, ctx.draft);
            continue;
        }
        let unresolved = ctx.unresolved_anchors.get(&c.id).copied();
        let count = comment_display(
            c,
            ctx.wrap_width,
            None,
            blocks_of(ctx.figures, &c.id),
            unresolved,
        )
        .len();
        rows.extend((0..count).map(|line| SplitRow::Comment {
            comment,
            line,
            outdated,
        }));
        if ctx.draft.is_some_and(|d| d.replies_to(&c.id)) {
            push_split_draft_rows(rows, ctx.draft);
        }
    }
}

fn push_split_draft_rows(rows: &mut Vec<SplitRow>, draft: Option<&Draft<'_>>) {
    let Some(draft) = draft else { return };
    rows.extend((0..draft.lines.len()).map(|line| SplitRow::Composer { line }));
}

/// Emit a change block as aligned pairs: deletions on the left, additions on
/// the right, zipped by position with `None` filling the shorter side. Any
/// comment anchored to a paired line follows its row.
fn flush_change_block(
    rows: &mut Vec<SplitRow>,
    by_line: &HashMap<(usize, usize), Vec<(usize, bool)>>,
    hunk: usize,
    dels: &[usize],
    adds: &[usize],
    new_at: Option<(usize, usize)>,
    ctx: RowCtx<'_>,
) {
    for k in 0..dels.len().max(adds.len()) {
        let left = dels.get(k).copied();
        let right = adds.get(k).copied();
        rows.push(SplitRow::Pair { hunk, left, right });
        for line in [left, right].into_iter().flatten() {
            if let Some(list) = by_line.get(&(hunk, line)) {
                push_split_comments(rows, list, ctx);
            }
            if new_at == Some((hunk, line)) {
                push_split_draft_rows(rows, ctx.draft);
            }
        }
    }
}

/// Build the side-by-side rows for one file, the split-mode counterpart to
/// [`build_rows`]. Same comment placement; lines are paired old-to-new.
pub(super) fn build_split_rows(
    model: &DiffModel,
    session: &Session,
    selected: usize,
    wrap_width: u16,
    composer: Option<&Composer>,
    figures: &FigureCache,
    unresolved_anchors: &HashMap<String, Located>,
) -> Vec<SplitRow> {
    let mut rows = Vec::new();
    let Some(file) = model.files.get(selected) else {
        return rows;
    };
    let draft = Draft::new(composer, wrap_width);
    let ctx = RowCtx {
        session,
        wrap_width,
        draft: draft.as_ref(),
        figures,
        unresolved_anchors,
    };
    let (by_line, unanchored) = collect_comments(file, session, model);
    push_split_comments(&mut rows, &unanchored, ctx);
    if ctx.draft.is_some_and(|d| d.is_unanchored(file)) {
        push_split_draft_rows(&mut rows, ctx.draft);
    }
    let new_at = ctx.draft.and_then(|d| d.new_at(file));
    for (hunk_idx, hunk) in file.hunks.iter().enumerate() {
        rows.push(SplitRow::Hunk { hunk: hunk_idx });
        let mut dels: Vec<usize> = Vec::new();
        let mut adds: Vec<usize> = Vec::new();
        for (line_idx, line) in hunk.lines.iter().enumerate() {
            match line.kind {
                LineKind::Context => {
                    flush_change_block(&mut rows, &by_line, hunk_idx, &dels, &adds, new_at, ctx);
                    dels.clear();
                    adds.clear();
                    rows.push(SplitRow::Pair {
                        hunk: hunk_idx,
                        left: Some(line_idx),
                        right: Some(line_idx),
                    });
                    if let Some(list) = by_line.get(&(hunk_idx, line_idx)) {
                        push_split_comments(&mut rows, list, ctx);
                    }
                    if new_at == Some((hunk_idx, line_idx)) {
                        push_split_draft_rows(&mut rows, ctx.draft);
                    }
                }
                LineKind::Deleted => dels.push(line_idx),
                LineKind::Added => adds.push(line_idx),
            }
        }
        flush_change_block(&mut rows, &by_line, hunk_idx, &dels, &adds, new_at, ctx);
    }
    rows
}