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>)
| 409 | /// each paired Added line pulled forward to appear immediately after |
| 410 | /// its matching Removed line. |
| 411 | fn repair_diff_lines(lines: Vec<HunkLine>) -> Vec<HunkLine> { |
| 412 | use std::collections::{HashMap, HashSet}; |
| 413 | |
| 414 | // Helper: compute character bigrams for Jaccard similarity |
| 415 | fn bigrams(s: &str) -> HashSet<(u8, u8)> { |
| 416 | let bytes = s.trim().as_bytes(); |
| 417 | let mut set = HashSet::new(); |
| 418 | if bytes.len() >= 2 { |
| 419 | for w in bytes.windows(2) { |
| 420 | set.insert((w[0], w[1])); |
| 421 | } |
| 422 | } |
| 423 | set |
| 424 | } |
| 425 | |
| 426 | fn jaccard(a: &HashSet<(u8, u8)>, b: &HashSet<(u8, u8)>) -> f64 { |
| 427 | if a.is_empty() && b.is_empty() { |
| 428 | return 0.0; |
| 429 | } |
| 430 | let inter = a.intersection(b).count(); |
| 431 | let union = a.union(b).count(); |
| 432 | if union == 0 { |
| 433 | 0.0 |
| 434 | } else { |
| 435 | inter as f64 / union as f64 |
| 436 | } |
| 437 | } |
| 438 | |
| 439 | // 1. Collect all Removed and Added lines with their original indices |
| 440 | let mut rm_entries: Vec<(usize, &HunkLine)> = Vec::new(); |
| 441 | let mut add_entries: Vec<(usize, &HunkLine)> = Vec::new(); |
| 442 | |
| 443 | for (idx, line) in lines.iter().enumerate() { |
| 444 | if line.is_removed() { |
| 445 | rm_entries.push((idx, line)); |
| 446 | } else if line.is_added() { |
| 447 | add_entries.push((idx, line)); |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | // Short-circuit: nothing to pair |
| 452 | if rm_entries.is_empty() || add_entries.is_empty() { |
| 453 | return lines; |
| 454 | } |
| 455 | |
| 456 | // 2. Compute bigrams |
| 457 | let rm_bigrams: Vec<HashSet<(u8, u8)>> = rm_entries |
| 458 | .iter() |
| 459 | .map(|(_, l)| bigrams(&l.content)) |
| 460 | .collect(); |
| 461 | let add_bigrams: Vec<HashSet<(u8, u8)>> = add_entries |
| 462 | .iter() |
| 463 | .map(|(_, l)| bigrams(&l.content)) |
| 464 | .collect(); |
| 465 | |
| 466 | // 3. Greedy best-match pairing across ALL removes and adds |
| 467 | let mut candidates: Vec<(usize, usize, f64)> = Vec::new(); |
| 468 | for (ri, rb) in rm_bigrams.iter().enumerate() { |