Re-pair Delete+Insert lines by content similarity for display. The CRDT builder emits all Deletes before all Inserts within each Replace block (to preserve BRANCH_AFTER chain ordering). When the Myers diff creates multiple Replace blocks for one file, a deleted line and its matching insertion may land in different blocks. This post-pass collects ALL Removed and Added lines across the entire hun
(lines: Vec<HunkLine>)
| 1095 | /// each paired Added line pulled forward to appear immediately after |
| 1096 | /// its matching Removed line. |
| 1097 | fn repair_diff_lines(lines: Vec<HunkLine>) -> Vec<HunkLine> { |
| 1098 | use std::collections::{HashMap, HashSet}; |
| 1099 | |
| 1100 | // Helper: compute character bigrams for Jaccard similarity |
| 1101 | fn bigrams(s: &str) -> HashSet<(u8, u8)> { |
| 1102 | let bytes = s.trim().as_bytes(); |
| 1103 | let mut set = HashSet::new(); |
| 1104 | if bytes.len() >= 2 { |
| 1105 | for w in bytes.windows(2) { |
| 1106 | set.insert((w[0], w[1])); |
| 1107 | } |
| 1108 | } |
| 1109 | set |
| 1110 | } |
| 1111 | |
| 1112 | fn jaccard(a: &HashSet<(u8, u8)>, b: &HashSet<(u8, u8)>) -> f64 { |
| 1113 | if a.is_empty() && b.is_empty() { |
| 1114 | return 0.0; |
| 1115 | } |
| 1116 | let inter = a.intersection(b).count(); |
| 1117 | let union = a.union(b).count(); |
| 1118 | if union == 0 { |
| 1119 | 0.0 |
| 1120 | } else { |
| 1121 | inter as f64 / union as f64 |
| 1122 | } |
| 1123 | } |
| 1124 | |
| 1125 | // 1. Collect all Removed and Added lines with their original indices |
| 1126 | let mut rm_entries: Vec<(usize, &HunkLine)> = Vec::new(); |
| 1127 | let mut add_entries: Vec<(usize, &HunkLine)> = Vec::new(); |
| 1128 | |
| 1129 | for (idx, line) in lines.iter().enumerate() { |
| 1130 | if line.is_removed() { |
| 1131 | rm_entries.push((idx, line)); |
| 1132 | } else if line.is_added() { |
| 1133 | add_entries.push((idx, line)); |
| 1134 | } |
| 1135 | } |
| 1136 | |
| 1137 | // Short-circuit: nothing to pair |
| 1138 | if rm_entries.is_empty() || add_entries.is_empty() { |
| 1139 | return lines; |
| 1140 | } |
| 1141 | |
| 1142 | // 2. Compute bigrams |
| 1143 | let rm_bigrams: Vec<HashSet<(u8, u8)>> = rm_entries |
| 1144 | .iter() |
| 1145 | .map(|(_, l)| bigrams(&l.content)) |
| 1146 | .collect(); |
| 1147 | let add_bigrams: Vec<HashSet<(u8, u8)>> = add_entries |
| 1148 | .iter() |
| 1149 | .map(|(_, l)| bigrams(&l.content)) |
| 1150 | .collect(); |
| 1151 | |
| 1152 | // 3. Greedy best-match pairing across ALL removes and adds |
| 1153 | let mut candidates: Vec<(usize, usize, f64)> = Vec::new(); |
| 1154 | for (ri, rb) in rm_bigrams.iter().enumerate() { |