croft-software 0.2.132

VSCode-style TUI written in Rust
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
//! Three-way merge editor state (#253): VS Code's merge-editor model
//! adapted to the TUI. Current (ours) and Incoming (theirs) render as
//! read-only panes above an editable Result, with Base toggleable.
//!
//! The three-way computation diffs base→ours and base→theirs, clusters
//! overlapping hunks into conflict regions, and auto-resolves everything
//! else straight into the initial Result — the main UX win over the
//! in-buffer marker flow, where every hunk needs a click. The Result
//! buffer itself is the host editor's ordinary text buffer; this module
//! only tracks where each conflict region lives inside it and what state
//! the region is in.

use crate::merge::ConflictBlock;
use crate::widgets::diff::{DIFF_DEADLINE, DiffRow, build_diff_rows, build_diff_rows_within};

/// What the user decided for one conflict region.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ConflictState {
    /// Untouched: the Result still holds the base text for this region.
    Unresolved,
    /// Accept Current (ours).
    Current,
    /// Accept Incoming (theirs).
    Incoming,
    /// Accept Combination: ours then theirs.
    Both,
    /// Accept Combination: theirs then ours.
    BothReverse,
    /// Ignore: explicitly keep the base text.
    Base,
    /// The user edited the region by hand in the Result pane.
    Manual,
}

impl ConflictState {
    /// Counts toward "N of M resolved" — everything except Unresolved.
    pub fn resolved(self) -> bool {
        self != ConflictState::Unresolved
    }
}

/// One conflict region: the three-side content plus its current span in
/// the Result buffer. Side `*_start` fields index into the full side
/// texts, anchoring pane scroll during conflict navigation.
#[derive(Clone, Debug)]
pub struct MergeConflict {
    pub base: Vec<String>,
    pub ours: Vec<String>,
    pub theirs: Vec<String>,
    /// First line of the region in the base / ours / theirs full texts.
    pub base_start: usize,
    pub ours_start: usize,
    pub theirs_start: usize,
    /// Current span in the Result buffer, maintained across accepts and
    /// (heuristically) across manual edits.
    pub result_start: usize,
    pub result_len: usize,
    pub state: ConflictState,
}

impl MergeConflict {
    /// The Result lines an accept action splices in for `state`.
    pub fn replacement(&self, state: ConflictState) -> Vec<String> {
        match state {
            ConflictState::Current => self.ours.clone(),
            ConflictState::Incoming => self.theirs.clone(),
            ConflictState::Both => {
                let mut v = self.ours.clone();
                v.extend(self.theirs.iter().cloned());
                v
            }
            ConflictState::BothReverse => {
                let mut v = self.theirs.clone();
                v.extend(self.ours.iter().cloned());
                v
            }
            ConflictState::Base | ConflictState::Unresolved | ConflictState::Manual => {
                self.base.clone()
            }
        }
    }

    /// True when `row` (a Result line index) falls inside this region.
    /// A zero-length region claims its boundary row so an accept that
    /// emptied the region can still be re-accepted differently.
    pub fn contains_result_row(&self, row: usize) -> bool {
        if self.result_len == 0 {
            row == self.result_start
        } else {
            row >= self.result_start && row < self.result_start + self.result_len
        }
    }
}

/// Which pane a per-conflict checkbox belongs to (mouse hit-testing).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CheckSide {
    Current,
    Incoming,
}

/// The merge editor's whole state, hung off `Editor.merge`. The Result
/// text itself lives in the host editor's `lines`.
pub struct MergeView {
    pub base: Vec<String>,
    pub ours: Vec<String>,
    pub theirs: Vec<String>,
    pub conflicts: Vec<MergeConflict>,
    /// "Show Base" — a third source pane when there's room.
    pub show_base: bool,
    /// Conflict index the last navigation landed on; accept actions fall
    /// back to it when the cursor is not inside any region.
    pub active: usize,
    /// Source-pane viewports, re-anchored by conflict navigation and
    /// nudged together by Alt+Up / Alt+Down.
    pub ours_scroll: usize,
    pub theirs_scroll: usize,
    pub base_scroll: usize,
    /// True when the sides were synthesized from conflict markers rather
    /// than read from git index stages.
    pub from_markers: bool,
    /// Manual-edit sync bookkeeping: the Result length and `edit_seq`
    /// this view last reconciled against (see `sync_with_buffer`).
    pub synced_len: usize,
    pub synced_seq: u64,
    /// Per-frame checkbox hit rects: (screen y, x range, conflict, side).
    pub check_spans: Vec<(u16, std::ops::Range<u16>, usize, CheckSide)>,
    /// Per-frame accept-button hit rects (#1169): (screen y, x range,
    /// conflict, the state the button sets).
    pub action_spans: Vec<(u16, std::ops::Range<u16>, usize, ConflictState)>,
    /// Per-frame rect of the source-pane area (mouse routing).
    pub last_panes_area: ratatui::layout::Rect,
    /// The side that deleted the file in a modify/delete conflict (#1244):
    /// its pane is empty because the file is gone there, not because it was
    /// emptied, and taking it means removing the file.
    pub deleted: Option<CheckSide>,
    /// The agent whose proposal this merges with a tab's unsaved edits
    /// (#1353), when it is that merge rather than a git conflict: saving
    /// the Result approves it, and nothing is staged.
    pub proposal_from: Option<String>,
}

impl MergeView {
    /// Build the view plus the initial Result: non-overlapping hunks from
    /// either side are applied automatically; overlapping clusters become
    /// conflict regions holding the base text until acted on.
    pub fn new(
        base: Vec<String>,
        ours: Vec<String>,
        theirs: Vec<String>,
        from_markers: bool,
    ) -> (Self, Vec<String>) {
        let (result, conflicts) = three_way(&base, &ours, &theirs);
        let view = MergeView {
            base,
            ours,
            theirs,
            conflicts,
            show_base: false,
            active: 0,
            ours_scroll: 0,
            theirs_scroll: 0,
            base_scroll: 0,
            from_markers,
            synced_len: result.len().max(1),
            synced_seq: 0,
            check_spans: Vec::new(),
            action_spans: Vec::new(),
            last_panes_area: ratatui::layout::Rect::default(),
            deleted: None,
            proposal_from: None,
        };
        (view, result)
    }

    pub fn resolved_count(&self) -> usize {
        self.conflicts.iter().filter(|c| c.state.resolved()).count()
    }

    pub fn unresolved_count(&self) -> usize {
        self.conflicts.len() - self.resolved_count()
    }

    /// The conflict containing `row` in the Result, if any.
    pub fn conflict_at_result_row(&self, row: usize) -> Option<usize> {
        self.conflicts
            .iter()
            .position(|c| c.contains_result_row(row))
    }

    /// The next conflict strictly after / before `row` in the Result,
    /// wrapping — F7's jump order, matching the in-buffer flow.
    pub fn next_conflict(&self, row: usize, backwards: bool) -> Option<usize> {
        if self.conflicts.is_empty() {
            return None;
        }
        if backwards {
            self.conflicts
                .iter()
                .rposition(|c| c.result_start < row)
                .or_else(|| Some(self.conflicts.len() - 1))
        } else {
            self.conflicts
                .iter()
                .position(|c| c.result_start > row)
                .or(Some(0))
        }
    }

    /// Bookkeeping for a programmatic accept: region `idx` was replaced
    /// by `new_len` lines and is now in `state`; later regions shift by
    /// the length delta. The caller performed the actual buffer splice
    /// and passes the post-edit `len`/`seq` so `sync_with_buffer` treats
    /// this edit as already reconciled.
    pub fn note_accept(
        &mut self,
        idx: usize,
        new_len: usize,
        state: ConflictState,
        buffer_len: usize,
        edit_seq: u64,
    ) {
        let old_len = self.conflicts[idx].result_len;
        let delta = new_len as isize - old_len as isize;
        self.conflicts[idx].result_len = new_len;
        self.conflicts[idx].state = state;
        for c in self.conflicts.iter_mut().skip(idx + 1) {
            c.result_start = (c.result_start as isize + delta).max(0) as usize;
        }
        self.active = idx;
        self.synced_len = buffer_len;
        self.synced_seq = edit_seq;
    }

    /// Reconcile with a manual buffer edit the view didn't perform
    /// itself. `edit_row` is where the edit happened (the cursor row at
    /// undo-push time); the length delta shifts regions after it, grows
    /// or shrinks the region containing it, and an edit inside a region
    /// marks that conflict manually resolved. Heuristic by design: one
    /// keystroke per frame is the norm, and drift self-limits to region
    /// boundaries — content is never touched.
    pub fn sync_with_buffer(&mut self, buffer_len: usize, edit_seq: u64, edit_row: usize) {
        if edit_seq == self.synced_seq {
            return;
        }
        let delta = buffer_len as isize - self.synced_len as isize;
        let base_len = self.base.len();
        for c in self.conflicts.iter_mut() {
            // An empty region sits AT the row of the line after it, so an
            // edit to that next line read as an edit inside the conflict:
            // it was marked resolved, and Complete Merge dropped both sides.
            // Only text inserted at that row goes into an empty region.
            // An empty region with no base text after it (a conflict at the
            // end of the file, or a whole-file one) has no next line: the row
            // it sits at is the buffer's filler line, so typing there IS
            // typing into the conflict.
            let trailing = c.base_start + c.base.len() >= base_len;
            let inside = if c.result_len == 0 {
                c.result_start == edit_row && (delta > 0 || trailing)
            } else {
                c.contains_result_row(edit_row)
            };
            if inside {
                c.result_len = (c.result_len as isize + delta).max(0) as usize;
                c.state = ConflictState::Manual;
            } else if c.result_start > edit_row {
                c.result_start = (c.result_start as isize + delta).max(0) as usize;
            }
        }
        self.synced_len = buffer_len;
        self.synced_seq = edit_seq;
    }

    /// Re-anchor all source-pane viewports on conflict `idx`, keeping a
    /// couple of context lines above.
    pub fn anchor_panes_on(&mut self, idx: usize) {
        const CTX: usize = 2;
        let Some(c) = self.conflicts.get(idx) else {
            return;
        };
        self.active = idx;
        self.ours_scroll = c.ours_start.saturating_sub(CTX);
        self.theirs_scroll = c.theirs_start.saturating_sub(CTX);
        self.base_scroll = c.base_start.saturating_sub(CTX);
    }

    /// Scroll all source panes together by `delta` (Alt+Up / Alt+Down).
    pub fn scroll_panes(&mut self, delta: isize) {
        let apply = |s: usize, max: usize| -> usize {
            (s as isize + delta).clamp(0, max.saturating_sub(1) as isize) as usize
        };
        self.ours_scroll = apply(self.ours_scroll, self.ours.len());
        self.theirs_scroll = apply(self.theirs_scroll, self.theirs.len());
        self.base_scroll = apply(self.base_scroll, self.base.len());
    }

    /// Settle what a view built from the index stages opens on, given the
    /// working file `current` as the user left it (#906); `result` is the
    /// Result the stages give. A file with no markers left was resolved by
    /// hand (or by rerere, or `git checkout --ours`), so it IS the Result
    /// and each conflict takes the state its text there reads as. A file
    /// still exactly as git marked it loses nothing to the stages' Result.
    /// Anything else, such as resolved blocks or lines typed around them,
    /// opens on the markers left in it, so none of that work is lost.
    /// Returns the view plus the Result to put in the buffer, or None when
    /// `current` already is it.
    pub fn open_on_file(
        mut self,
        result: Vec<String>,
        current: &[String],
    ) -> (MergeView, Option<Vec<String>>) {
        let blocks = crate::merge::find_conflicts(current);
        if blocks.is_empty() {
            self.adopt_result(&result, current);
            return (self, None);
        }
        if self.marked_up_as(&result, current, &blocks) {
            return (self, Some(result));
        }
        view_from_markers(current).map_or((self, Some(result)), |(view, r)| (view, Some(r)))
    }

    /// Take the marker-free `current` as the Result in place of `result`:
    /// each conflict region is bounded by the nearest lines the two texts
    /// share, and its state is the side (or both sides) the text there
    /// matches, Unresolved while it still reads as base, else Manual.
    fn adopt_result(&mut self, result: &[String], current: &[String]) {
        self.adopt_result_within(result, current, DIFF_DEADLINE);
    }

    /// [`Self::adopt_result`] with the line diff bounded by `budget`. A
    /// diff cut short by it (#1152) matches only the lines the two texts
    /// open and close with, so a region's nearest shared line can lie past
    /// the next conflict: a region not pinned on both sides by the lines
    /// around it in `result` then takes no lines, and reads as Manual, so
    /// an accept on it cannot replace hand-resolved text it does not own.
    fn adopt_result_within(
        &mut self,
        result: &[String],
        current: &[String],
        budget: std::time::Duration,
    ) {
        let (rows, coarse) = build_diff_rows_within(result, current, budget);
        let shared: Vec<(usize, usize)> = rows
            .into_iter()
            .filter_map(|row| match row {
                DiffRow::Equal { left, right } => Some((left, right)),
                _ => None,
            })
            .collect();
        let mut floor = 0;
        for c in &mut self.conflicts {
            let before = shared.partition_point(|&(l, _)| l < c.result_start);
            let after = shared.partition_point(|&(l, _)| l < c.result_start + c.result_len);
            let start = before
                .checked_sub(1)
                .map_or(0, |i| shared[i].1 + 1)
                .max(floor);
            let end = shared
                .get(after)
                .map_or(current.len(), |&(_, r)| r)
                .max(start);
            let c_end = c.result_start + c.result_len;
            let pinned = before
                .checked_sub(1)
                .map_or(c.result_start == 0, |i| shared[i].0 + 1 == c.result_start)
                && shared
                    .get(after)
                    .map_or(c_end == result.len(), |&(l, _)| l == c_end);
            if coarse && !pinned {
                c.state = ConflictState::Manual;
                c.result_start = start;
                c.result_len = 0;
                floor = start;
                continue;
            }
            let text = &current[start..end];
            c.state = if text == c.base.as_slice() {
                ConflictState::Unresolved
            } else {
                [
                    ConflictState::Current,
                    ConflictState::Incoming,
                    ConflictState::Both,
                    ConflictState::BothReverse,
                ]
                .into_iter()
                .find(|&s| c.replacement(s) == text)
                .unwrap_or(ConflictState::Manual)
            };
            c.result_start = start;
            c.result_len = end - start;
            floor = end;
        }
    }

    /// True when `current` is this merge as git writes it to the working
    /// file: `result` with each conflict region shown as a marker block.
    /// Both are read once as all-ours and once as all-theirs, so a block
    /// git narrowed (its default and zdiff3 styles move the lines both
    /// sides share outside the markers) still matches, while a resolved
    /// block or any line the user typed does not.
    fn marked_up_as(
        &self,
        result: &[String],
        current: &[String],
        blocks: &[ConflictBlock],
    ) -> bool {
        [true, false].into_iter().all(|ours| {
            let regions: Vec<_> = self
                .conflicts
                .iter()
                .map(|c| {
                    let side = if ours { &c.ours } else { &c.theirs };
                    (
                        c.result_start,
                        c.result_start + c.result_len,
                        side.as_slice(),
                    )
                })
                .collect();
            let marked: Vec<_> = blocks
                .iter()
                .map(|b| {
                    let side = if ours {
                        &current[b.ours_start + 1..b.base_start.unwrap_or(b.sep)]
                    } else {
                        &current[b.sep + 1..b.theirs_end]
                    };
                    (b.ours_start, b.theirs_end + 1, side)
                })
                .collect();
            splice_spans(result, &regions) == splice_spans(current, &marked)
        })
    }
}

/// One maximal changed run from a two-way diff: base rows
/// `[base_lo, base_hi)` were replaced by derived rows
/// `[derived_lo, derived_hi)`.
#[derive(Clone, Copy, Debug)]
struct Hunk {
    base_lo: usize,
    base_hi: usize,
    derived_lo: usize,
    derived_hi: usize,
}

/// Collapse a `DiffRow` alignment into maximal non-Equal runs.
fn hunks(base: &[String], derived: &[String]) -> Vec<Hunk> {
    let rows = build_diff_rows(base, derived);
    let mut out: Vec<Hunk> = Vec::new();
    // Row cursors advance through both sides; a changed row extends the
    // open hunk (or opens one), an Equal row closes it.
    let mut b = 0usize;
    let mut d = 0usize;
    let mut open: Option<Hunk> = None;
    for row in &rows {
        let changed = !matches!(row, DiffRow::Equal { .. });
        if changed && open.is_none() {
            open = Some(Hunk {
                base_lo: b,
                base_hi: b,
                derived_lo: d,
                derived_hi: d,
            });
        }
        if !changed && let Some(h) = open.take() {
            out.push(h);
        }
        match *row {
            DiffRow::Equal { .. } => {
                b += 1;
                d += 1;
            }
            DiffRow::Removed { .. } => b += 1,
            DiffRow::Added { .. } => d += 1,
            DiffRow::Replaced { .. } => {
                b += 1;
                d += 1;
            }
        }
        if let Some(h) = open.as_mut() {
            h.base_hi = b;
            h.derived_hi = d;
        }
    }
    if let Some(h) = open.take() {
        out.push(h);
    }
    out
}

/// Which side a hunk came from during clustering.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Side {
    Ours,
    Theirs,
}

/// The three-way computation: diff base→ours and base→theirs, cluster
/// transitively overlapping hunks, then walk the base emitting auto-
/// resolved replacements and conflict regions (holding base text).
///
/// Overlap uses doubled coordinates so a pure insertion at base row `p`
/// occupies `(2p, 2p+1)` instead of the empty `[p, p)`: two insertions at
/// the same point conflict, while a hunk ending exactly where the other
/// side's begins stays independent (git's adjacency rule).
fn three_way(
    base: &[String],
    ours: &[String],
    theirs: &[String],
) -> (Vec<String>, Vec<MergeConflict>) {
    let a = hunks(base, ours);
    let b = hunks(base, theirs);
    let mut all: Vec<(Side, Hunk)> = a
        .iter()
        .map(|h| (Side::Ours, *h))
        .chain(b.iter().map(|h| (Side::Theirs, *h)))
        .collect();
    all.sort_by_key(|(_, h)| (h.base_lo, h.base_hi));
    let scaled = |h: &Hunk| -> (usize, usize) {
        if h.base_lo == h.base_hi {
            (2 * h.base_lo, 2 * h.base_lo + 1)
        } else {
            (2 * h.base_lo, 2 * h.base_hi)
        }
    };

    // Cluster transitively overlapping hunks (in scaled coordinates).
    let mut clusters: Vec<Vec<(Side, Hunk)>> = Vec::new();
    let mut cluster_hi = 0usize;
    for (side, h) in all {
        let (lo, hi) = scaled(&h);
        match clusters.last_mut() {
            Some(cur) if lo < cluster_hi => {
                cur.push((side, h));
                cluster_hi = cluster_hi.max(hi);
            }
            _ => {
                clusters.push(vec![(side, h)]);
                cluster_hi = hi;
            }
        }
    }

    // Cumulative side offsets: how far each side's text has drifted from
    // base line numbers before a given cluster, for `*_start` anchors.
    let mut result: Vec<String> = Vec::new();
    let mut conflicts: Vec<MergeConflict> = Vec::new();
    let mut base_pos = 0usize; // next base row not yet emitted
    let mut delta_ours = 0isize;
    let mut delta_theirs = 0isize;
    for cluster in clusters {
        let lo = cluster.iter().map(|(_, h)| h.base_lo).min().unwrap_or(0);
        let hi = cluster
            .iter()
            .map(|(_, h)| h.base_hi)
            .max()
            .unwrap_or(lo)
            .max(lo);
        result.extend(base[base_pos..lo].iter().cloned());
        let ours_in: Vec<&Hunk> = cluster
            .iter()
            .filter(|(s, _)| *s == Side::Ours)
            .map(|(_, h)| h)
            .collect();
        let theirs_in: Vec<&Hunk> = cluster
            .iter()
            .filter(|(s, _)| *s == Side::Theirs)
            .map(|(_, h)| h)
            .collect();
        let both = !ours_in.is_empty() && !theirs_in.is_empty();
        if both {
            // Conflict: Result holds the base slice until the user acts.
            let ours_slice = apply_hunks(base, ours, lo, hi, &ours_in);
            let theirs_slice = apply_hunks(base, theirs, lo, hi, &theirs_in);
            conflicts.push(MergeConflict {
                base: base[lo..hi].to_vec(),
                ours: ours_slice,
                theirs: theirs_slice,
                base_start: lo,
                ours_start: (lo as isize + delta_ours).max(0) as usize,
                theirs_start: (lo as isize + delta_theirs).max(0) as usize,
                result_start: result.len(),
                result_len: hi - lo,
                state: ConflictState::Unresolved,
            });
            result.extend(base[lo..hi].iter().cloned());
        } else {
            // One-sided cluster: auto-resolve into the Result.
            let (derived, hunks_in) = if theirs_in.is_empty() {
                (ours, &ours_in)
            } else {
                (theirs, &theirs_in)
            };
            result.extend(apply_hunks(base, derived, lo, hi, hunks_in));
        }
        for h in &ours_in {
            delta_ours += (h.derived_hi - h.derived_lo) as isize - (h.base_hi - h.base_lo) as isize;
        }
        for h in &theirs_in {
            delta_theirs +=
                (h.derived_hi - h.derived_lo) as isize - (h.base_hi - h.base_lo) as isize;
        }
        base_pos = hi;
    }
    result.extend(base[base_pos..].iter().cloned());
    (result, conflicts)
}

/// Apply `hunks_in` (sorted, all within base `[lo, hi)`) onto that base
/// slice, yielding the derived side's text for the region.
fn apply_hunks(
    base: &[String],
    derived: &[String],
    lo: usize,
    hi: usize,
    hunks_in: &[&Hunk],
) -> Vec<String> {
    let mut out = Vec::new();
    let mut pos = lo;
    let mut sorted: Vec<&&Hunk> = hunks_in.iter().collect();
    sorted.sort_by_key(|h| h.base_lo);
    for h in sorted {
        out.extend(base[pos..h.base_lo.max(pos)].iter().cloned());
        out.extend(derived[h.derived_lo..h.derived_hi].iter().cloned());
        pos = h.base_hi.max(pos);
    }
    out.extend(base[pos..hi.max(pos)].iter().cloned());
    out
}

/// Build the view (plus the initial Result) straight from a marker-filled
/// buffer, so the merge editor also works on a plain conflicted file
/// outside any git merge. Context outside blocks is shared verbatim;
/// inside a block each side gets its own section, base gets the diff3
/// `|||||||` section when present, and the Result holds the base section
/// until the block is acted on. Every block becomes a conflict BY
/// CONSTRUCTION rather than by re-diffing the synthesized sides: markers
/// mean git already judged the block unresolved, and a textual three-way
/// cannot — a block with one empty section and no diff3 base makes that
/// side indistinguishable from the (unknown) base, and the other side
/// would silently auto-apply. Returns None when there are no blocks.
pub fn view_from_markers(lines: &[String]) -> Option<(MergeView, Vec<String>)> {
    let blocks = crate::merge::find_conflicts(lines);
    if blocks.is_empty() {
        return None;
    }
    let mut base = Vec::new();
    let mut ours = Vec::new();
    let mut theirs = Vec::new();
    let mut result = Vec::new();
    let mut conflicts = Vec::new();
    let mut pos = 0usize;
    for b in &blocks {
        for l in &lines[pos..b.ours_start] {
            base.push(l.clone());
            ours.push(l.clone());
            theirs.push(l.clone());
            result.push(l.clone());
        }
        let ours_end = b.base_start.unwrap_or(b.sep);
        let ours_sec = lines[b.ours_start + 1..ours_end].to_vec();
        let base_sec = b
            .base_start
            .map(|bs| lines[bs + 1..b.sep].to_vec())
            .unwrap_or_default();
        let theirs_sec = lines[b.sep + 1..b.theirs_end].to_vec();
        conflicts.push(MergeConflict {
            base: base_sec.clone(),
            ours: ours_sec.clone(),
            theirs: theirs_sec.clone(),
            base_start: base.len(),
            ours_start: ours.len(),
            theirs_start: theirs.len(),
            result_start: result.len(),
            result_len: base_sec.len(),
            state: ConflictState::Unresolved,
        });
        base.extend(base_sec.iter().cloned());
        ours.extend(ours_sec);
        result.extend(base_sec);
        theirs.extend(theirs_sec);
        pos = b.theirs_end + 1;
    }
    for l in &lines[pos..] {
        base.push(l.clone());
        ours.push(l.clone());
        theirs.push(l.clone());
        result.push(l.clone());
    }
    let view = MergeView {
        base,
        ours,
        theirs,
        conflicts,
        show_base: false,
        active: 0,
        ours_scroll: 0,
        theirs_scroll: 0,
        base_scroll: 0,
        from_markers: true,
        synced_len: result.len().max(1),
        synced_seq: 0,
        check_spans: Vec::new(),
        action_spans: Vec::new(),
        last_panes_area: ratatui::layout::Rect::default(),
        deleted: None,
        proposal_from: None,
    };
    Some((view, result))
}

/// `lines` with each `(start, end, text)` span, in order, replaced by `text`.
fn splice_spans<'a>(
    lines: &'a [String],
    spans: &[(usize, usize, &'a [String])],
) -> Vec<&'a String> {
    let mut out = Vec::with_capacity(lines.len());
    let mut pos = 0;
    for &(start, end, text) in spans {
        out.extend(&lines[pos..start]);
        out.extend(text);
        pos = end;
    }
    out.extend(&lines[pos..]);
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    fn lines(strs: &[&str]) -> Vec<String> {
        strs.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn non_overlapping_hunks_auto_resolve_without_a_conflict() {
        let base = lines(&["a", "b", "c", "d", "e"]);
        let ours = lines(&["A", "b", "c", "d", "e"]); // changed line 0
        let theirs = lines(&["a", "b", "c", "d", "E"]); // changed line 4
        let (view, result) = MergeView::new(base, ours, theirs, false);
        assert!(view.conflicts.is_empty(), "distant edits merge cleanly");
        assert_eq!(result, lines(&["A", "b", "c", "d", "E"]));
    }

    #[test]
    fn overlapping_hunks_become_one_conflict_holding_base() {
        let base = lines(&["a", "b", "c"]);
        let ours = lines(&["a", "OURS", "c"]);
        let theirs = lines(&["a", "THEIRS", "c"]);
        let (view, result) = MergeView::new(base, ours, theirs, false);
        assert_eq!(view.conflicts.len(), 1);
        let c = &view.conflicts[0];
        assert_eq!(c.base, lines(&["b"]));
        assert_eq!(c.ours, lines(&["OURS"]));
        assert_eq!(c.theirs, lines(&["THEIRS"]));
        assert_eq!((c.result_start, c.result_len), (1, 1));
        assert_eq!(result, lines(&["a", "b", "c"]), "conflict keeps base");
    }

    #[test]
    fn same_point_insertions_conflict_but_adjacent_hunks_do_not() {
        let base = lines(&["a", "b"]);
        let ours = lines(&["a", "X", "b"]);
        let theirs = lines(&["a", "Y", "b"]);
        let (view, _) = MergeView::new(base.clone(), ours, theirs, false);
        assert_eq!(view.conflicts.len(), 1, "double insert at one point");

        // Ours edits row 0, theirs edits row 1: adjacent, independent.
        let ours2 = lines(&["A", "b"]);
        let theirs2 = lines(&["a", "B"]);
        let (view2, result2) = MergeView::new(base, ours2, theirs2, false);
        assert!(view2.conflicts.is_empty());
        assert_eq!(result2, lines(&["A", "B"]));
    }

    #[test]
    fn replacement_covers_every_state() {
        let base = lines(&["a", "mid", "z"]);
        let ours = lines(&["a", "one", "z"]);
        let theirs = lines(&["a", "two", "z"]);
        let (view, _) = MergeView::new(base, ours, theirs, false);
        let c = &view.conflicts[0];
        assert_eq!(c.replacement(ConflictState::Current), lines(&["one"]));
        assert_eq!(c.replacement(ConflictState::Incoming), lines(&["two"]));
        assert_eq!(c.replacement(ConflictState::Both), lines(&["one", "two"]));
        assert_eq!(
            c.replacement(ConflictState::BothReverse),
            lines(&["two", "one"])
        );
        assert_eq!(c.replacement(ConflictState::Base), lines(&["mid"]));
    }

    #[test]
    fn note_accept_shifts_later_regions_by_the_delta() {
        let base = lines(&["a", "x", "b", "c", "y", "d"]);
        let ours = lines(&["a", "O1", "O2", "b", "c", "OY", "d"]);
        let theirs = lines(&["a", "T", "b", "c", "TY", "d"]);
        let (mut view, result) = MergeView::new(base, ours, theirs, false);
        assert_eq!(view.conflicts.len(), 2);
        let second_before = view.conflicts[1].result_start;
        // Accept ours (2 lines) over base (1 line): +1 delta.
        view.note_accept(0, 2, ConflictState::Current, result.len() + 1, 1);
        assert_eq!(view.conflicts[0].state, ConflictState::Current);
        assert_eq!(view.conflicts[1].result_start, second_before + 1);
        assert_eq!(view.resolved_count(), 1);
        assert_eq!(view.unresolved_count(), 1);
    }

    #[test]
    fn sync_with_buffer_marks_the_edited_region_manual_and_shifts_the_rest() {
        let base = lines(&["a", "x", "b", "c", "y", "d"]);
        let ours = lines(&["a", "OX", "b", "c", "OY", "d"]);
        let theirs = lines(&["a", "TX", "b", "c", "TY", "d"]);
        let (mut view, result) = MergeView::new(base, ours, theirs, false);
        assert_eq!(view.conflicts.len(), 2);
        let first = view.conflicts[0].result_start;
        let second_before = view.conflicts[1].result_start;
        // Simulate the user pressing Enter inside region 0: +1 line.
        view.sync_with_buffer(result.len() + 1, 1, first);
        assert_eq!(view.conflicts[0].state, ConflictState::Manual);
        assert_eq!(view.conflicts[0].result_len, 2);
        assert_eq!(view.conflicts[1].result_start, second_before + 1);
        // An edit outside every region resolves nothing further.
        view.sync_with_buffer(result.len() + 1, 2, 0);
        assert_eq!(view.resolved_count(), 1);
    }

    #[test]
    fn editing_the_line_after_an_empty_region_leaves_it_unresolved() {
        // No base side (markers without diff3): the Result holds nothing for
        // the conflict, so its region is empty and sits at `b`'s row.
        let base = lines(&["a", "b"]);
        let ours = lines(&["a", "o", "b"]);
        let theirs = lines(&["a", "t", "b"]);
        let (mut view, result) = MergeView::new(base, ours, theirs, false);
        assert_eq!(view.conflicts.len(), 1);
        assert_eq!(view.conflicts[0].result_len, 0);
        let row = view.conflicts[0].result_start;
        // Typing into `b` changes no line count.
        view.sync_with_buffer(result.len(), 1, row);
        assert_eq!(view.unresolved_count(), 1, "still a conflict");
        // Text inserted at that row does go into the region.
        view.sync_with_buffer(result.len() + 1, 2, row);
        assert_eq!(view.unresolved_count(), 0);
    }

    #[test]
    fn typing_into_an_empty_trailing_region_resolves_it() {
        // A whole-file conflict with no base: the Result is one empty line,
        // and the region sits at it with no line after.
        let (mut view, _) = MergeView::new(vec![], lines(&["o"]), lines(&["t"]), false);
        assert_eq!(view.conflicts.len(), 1);
        let row = view.conflicts[0].result_start;
        // A keystroke on that line: no line count change.
        let len = view.synced_len;
        view.sync_with_buffer(len, 1, row);
        assert_eq!(view.unresolved_count(), 0);
    }

    #[test]
    fn next_conflict_wraps_in_both_directions() {
        let base = lines(&["a", "x", "b", "c", "y", "d"]);
        let ours = lines(&["a", "OX", "b", "c", "OY", "d"]);
        let theirs = lines(&["a", "TX", "b", "c", "TY", "d"]);
        let (view, _) = MergeView::new(base, ours, theirs, false);
        let starts: Vec<usize> = view.conflicts.iter().map(|c| c.result_start).collect();
        assert_eq!(
            view.next_conflict(0, false),
            (starts[0] > 0).then_some(0).or(Some(1))
        );
        assert_eq!(
            view.next_conflict(starts[1], false),
            Some(0),
            "wraps forward"
        );
        assert_eq!(
            view.next_conflict(starts[0], true),
            Some(1),
            "wraps backward"
        );
    }

    #[test]
    fn synthesize_from_markers_reconstructs_all_three_sides() {
        let doc = lines(&[
            "top",
            "<<<<<<< HEAD",
            "ours line",
            "||||||| merged common ancestors",
            "base line",
            "=======",
            "theirs line",
            ">>>>>>> feature",
            "bottom",
        ]);
        let (view, _) = view_from_markers(&doc).unwrap();
        assert_eq!(view.base, lines(&["top", "base line", "bottom"]));
        assert_eq!(view.ours, lines(&["top", "ours line", "bottom"]));
        assert_eq!(view.theirs, lines(&["top", "theirs line", "bottom"]));
        assert_eq!(view.conflicts.len(), 1);
        assert_eq!(view.conflicts[0].base, lines(&["base line"]));
        assert_eq!(
            (view.conflicts[0].result_start, view.conflicts[0].result_len),
            (1, 1)
        );
        assert!(view.from_markers);
    }

    #[test]
    fn synthesize_without_a_diff3_section_leaves_base_empty_for_the_block() {
        let doc = lines(&["<<<<<<< HEAD", "mine", "=======", "yours", ">>>>>>> br"]);
        let (view, result) = view_from_markers(&doc).unwrap();
        assert_eq!(view.conflicts.len(), 1);
        assert!(view.conflicts[0].base.is_empty());
        assert_eq!(view.conflicts[0].ours, lines(&["mine"]));
        assert_eq!(view.conflicts[0].theirs, lines(&["yours"]));
        assert!(result.is_empty(), "conflict region starts as (empty) base");
    }

    #[test]
    fn a_marker_block_with_an_empty_side_still_asks_for_a_decision() {
        // #253 review: an ours-only block with no diff3 section. A
        // textual three-way cannot tell the empty side from the
        // (unknown, also empty) base and would auto-apply "added by
        // us"; block construction keeps the decision with the user.
        let doc = lines(&["<<<<<<< HEAD", "added by us", "=======", ">>>>>>> br"]);
        let (view, result) = view_from_markers(&doc).unwrap();
        assert_eq!(view.conflicts.len(), 1);
        assert_eq!(view.conflicts[0].ours, lines(&["added by us"]));
        assert!(view.conflicts[0].theirs.is_empty());
        assert_eq!(view.conflicts[0].state, ConflictState::Unresolved);
        assert!(result.is_empty(), "nothing was auto-applied");
        assert_eq!(view.unresolved_count(), 1);
    }

    #[test]
    fn a_marker_free_buffer_synthesizes_nothing() {
        assert!(view_from_markers(&lines(&["plain", "text"])).is_none());
    }

    /// #906: the repro's config.toml, where both branches changed `timeout`.
    fn timeout_merge() -> (MergeView, Vec<String>) {
        MergeView::new(
            lines(&["retries = 3", "timeout = 10", "log = info"]),
            lines(&["retries = 3", "timeout = 20", "log = info"]),
            lines(&["retries = 3", "timeout = 30", "log = info"]),
            false,
        )
    }

    #[test]
    fn a_hand_resolved_file_is_the_result_with_the_state_its_text_reads_as() {
        for (region, state) in [
            (&["timeout = 45"][..], ConflictState::Manual),
            (&["timeout = 20"][..], ConflictState::Current),
            (
                &["timeout = 30", "timeout = 20"][..],
                ConflictState::BothReverse,
            ),
            (&["timeout = 10"][..], ConflictState::Unresolved),
        ] {
            let mut file = lines(&["# added", "retries = 3"]);
            file.extend(lines(region));
            file.push("log = info".into());
            let (view, result) = timeout_merge();
            let (view, splice) = view.open_on_file(result, &file);
            assert!(splice.is_none(), "{region:?}: the file stays as it is");
            let c = &view.conflicts[0];
            assert_eq!(
                (c.state, c.result_start, c.result_len),
                (state, 2, region.len())
            );
        }
    }

    /// #906: a diff cut short by its deadline matches only the shared
    /// first and last lines, so the first conflict's nearest shared line
    /// after it was the file's last, and its region swallowed the line
    /// between the conflicts and the second conflict's hand resolution. A
    /// region the cut-short diff cannot pin takes nothing instead.
    #[test]
    fn a_cut_short_diff_leaves_no_region_over_text_it_does_not_own() {
        let (base, ours, theirs) = (
            lines(&["a", "x = 1", "b", "y = 1", "c"]),
            lines(&["a", "x = 2", "b", "y = 2", "c"]),
            lines(&["a", "x = 3", "b", "y = 3", "c"]),
        );
        let file = lines(&["a", "x = 9", "b", "y = 9", "c"]);
        let spans = |budget| {
            let (mut view, result) =
                MergeView::new(base.clone(), ours.clone(), theirs.clone(), false);
            view.adopt_result_within(&result, &file, budget);
            view.conflicts
                .iter()
                .map(|c| (c.result_start, c.result_len, c.state))
                .collect::<Vec<_>>()
        };
        let manual = ConflictState::Manual;
        assert_eq!(
            spans(DIFF_DEADLINE),
            vec![(1, 1, manual), (3, 1, manual)],
            "the full diff pins each region on the lines around it"
        );
        let cut = spans(std::time::Duration::ZERO);
        assert!(
            cut.iter()
                .all(|&(start, len, _)| !(start..start + len).contains(&2)),
            "no region owns `b`: {cut:?}"
        );
        assert!(
            cut.iter()
                .all(|&(_, len, state)| len <= 1 && state == manual),
            "{cut:?}"
        );
    }

    #[test]
    fn git_s_own_marker_file_still_opens_on_the_stages() {
        let (view, result) = timeout_merge();
        let file = lines(&[
            "retries = 3",
            "<<<<<<< HEAD",
            "timeout = 20",
            "=======",
            "timeout = 30",
            ">>>>>>> feature",
            "log = info",
        ]);
        let (view, splice) = view.open_on_file(result.clone(), &file);
        assert!(!view.from_markers);
        assert_eq!(splice, Some(result));
        // Git's default style moves the line both sides share out of the
        // block; that is still git's untouched file.
        let (view, result) = MergeView::new(
            lines(&["a", "b"]),
            lines(&["x", "mine"]),
            lines(&["x", "yours"]),
            false,
        );
        let file = lines(&["x", "<<<<<<< HEAD", "mine", "=======", "yours", ">>>>>>> f"]);
        let (view, splice) = view.open_on_file(result.clone(), &file);
        assert!(!view.from_markers);
        assert_eq!(splice, Some(result));
    }

    #[test]
    fn a_marker_file_with_edits_opens_on_its_markers() {
        let (view, result) = timeout_merge();
        let file = lines(&[
            "# reviewed",
            "retries = 3",
            "<<<<<<< HEAD",
            "timeout = 20",
            "=======",
            "timeout = 30",
            ">>>>>>> feature",
            "log = info",
        ]);
        let (view, splice) = view.open_on_file(result, &file);
        assert!(view.from_markers);
        assert_eq!(view.conflicts.len(), 1);
        assert_eq!(
            splice.unwrap(),
            lines(&["# reviewed", "retries = 3", "log = info"])
        );
    }

    #[test]
    fn zero_length_region_still_claims_its_boundary_row() {
        let c = MergeConflict {
            base: vec![],
            ours: lines(&["x"]),
            theirs: lines(&["y"]),
            base_start: 0,
            ours_start: 0,
            theirs_start: 0,
            result_start: 3,
            result_len: 0,
            state: ConflictState::Unresolved,
        };
        assert!(c.contains_result_row(3));
        assert!(!c.contains_result_row(2));
        assert!(!c.contains_result_row(4));
    }
}