Damson/src/text/diff.rs
astar76 5ef45b0ba7 Sudo saves, session-only change bars, a rail that follows the drag
- Saving a file you can't write asks for your password and saves it
  through sudo (cp keeps the file's owner and mode). The password goes to
  sudo's stdin once and isn't kept.
- Change bars and the tree's edited dots now describe this session only:
  a line diff against the file as it was opened, not git diff HEAD, so
  they're gone after a restart.
- Dragging the scroll rail keeps the viewport bubble under the pointer
  all the way to the end of long files, and grabbing it again no longer
  jumps. The bubble stays inside the rail when popped out.
- About shows the language count without naming Kate.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 19:30:15 -06:00

125 lines
4.3 KiB
Rust

//! Which lines changed since a file was opened, for the change bars. A Myers diff over line hashes,
//! so the bars only ever describe this session's edits.
use ropey::Rope;
use std::hash::Hasher;
/// One hash per line, without its line break.
pub fn line_hashes(rope: &Rope) -> Vec<u64> {
rope.lines().map(|l| {
let mut h = std::hash::DefaultHasher::new();
for c in l.chunks() { h.write(c.trim_end_matches(['\n', '\r']).as_bytes()) }
h.finish()
}).collect()
}
/// Hunks of `new` against `old`: (first line, line count, kind: 0 add, 1 change, 2 delete).
/// A deletion marks the line that now sits where the removed lines were.
pub fn hunks(old: &[u64], new: &[u64]) -> Vec<(usize, usize, u8)> {
let pre = old.iter().zip(new).take_while(|(a, b)| a == b).count();
let suf = old[pre..].iter().rev().zip(new[pre..].iter().rev()).take_while(|(a, b)| a == b).count();
let (a, b) = (&old[pre..old.len() - suf], &new[pre..new.len() - suf]);
if a.is_empty() && b.is_empty() {
return vec![];
}
// scattered edits all over a huge file would cost too much: past a budget it's one hunk
let cap = (20_000_000 / (a.len() + b.len()).max(1)).clamp(16, 1000);
let same = myers(a, b, cap).unwrap_or_default();
let mut v = vec![];
let (mut i, mut j) = (0, 0);
for (mi, mj) in same.into_iter().chain([(a.len(), b.len())]) {
if mi > i || mj > j {
if mj > j {
v.push((pre + j, mj - j, if mi > i { 1 } else { 0 }));
} else {
v.push(((pre + j).min(new.len().saturating_sub(1)), 1, 2));
}
}
(i, j) = (mi + 1, mj + 1);
}
v
}
/// Matching line pairs, in order, or None past `cap` edits.
fn myers(a: &[u64], b: &[u64], cap: usize) -> Option<Vec<(usize, usize)>> {
let (n, m) = (a.len() as isize, b.len() as isize);
let cap = cap.min((n + m) as usize) as isize;
let off = cap + 1;
let mut v = vec![0isize; 2 * cap as usize + 3];
// the frontier before each round, k from -d to d
let mut trace: Vec<Vec<isize>> = vec![];
for d in 0..=cap {
trace.push(v[(off - d) as usize..=(off + d) as usize].to_vec());
let mut k = -d;
while k <= d {
let mut x = if k == -d || (k != d && v[(off + k - 1) as usize] < v[(off + k + 1) as usize]) { v[(off + k + 1) as usize] } else { v[(off + k - 1) as usize] + 1 };
let mut y = x - k;
while x < n && y < m && a[x as usize] == b[y as usize] { x += 1; y += 1 }
v[(off + k) as usize] = x;
if x >= n && y >= m {
return Some(backtrack(&trace, n, m));
}
k += 2;
}
}
None
}
fn backtrack(trace: &[Vec<isize>], n: isize, m: isize) -> Vec<(usize, usize)> {
let mut pairs = vec![];
let (mut x, mut y) = (n, m);
for d in (0..trace.len() as isize).rev() {
let v = &trace[d as usize];
let at = |k: isize| v[(k + d) as usize];
let k = x - y;
let (px, py) = if d == 0 { (0, 0) } else {
let pk = if k == -d || (k != d && at(k - 1) < at(k + 1)) { k + 1 } else { k - 1 };
(at(pk), at(pk) - pk)
};
// the snake back to where this round's edit landed
while x > px && y > py {
x -= 1;
y -= 1;
pairs.push((x as usize, y as usize));
}
(x, y) = (px, py);
}
pairs.reverse();
pairs
}
#[cfg(test)]
mod tests {
use super::*;
fn h(s: &str) -> Vec<u64> {
line_hashes(&Rope::from_str(s))
}
#[test]
fn nothing_changed_means_no_marks() {
assert!(hunks(&h("a\nb\nc"), &h("a\nb\nc")).is_empty());
}
#[test]
fn adds_changes_and_deletes_land_on_the_right_lines() {
let old = h("a\nb\nc\nd\ne\nf\ng");
// b changed, an x added after d, f removed
let new = h("a\nB\nc\nd\nx\ne\ng");
assert_eq!(hunks(&old, &new), vec![(1, 1, 1), (4, 1, 0), (6, 1, 2)]);
}
#[test]
fn separate_edits_stay_separate_in_a_long_file() {
let old: Vec<u64> = (0..5000).collect();
let mut new = old.clone();
new[10] = 99_999;
new[4000] = 88_888;
assert_eq!(hunks(&old, &new), vec![(10, 1, 1), (4000, 1, 1)]);
}
#[test]
fn deleting_the_last_lines_marks_the_new_last_line() {
assert_eq!(hunks(&h("a\nb\nc\n"), &h("a\n")), vec![(1, 1, 2)]);
}
}