Skip to main content

rustaco_core/
diff_view.rs

1//! What a diff view needs from a [`Diff`](crate::Diff), independent of how it draws: the
2//! ranges to mark, the filler blocks that keep two panes aligned, stepping between changes,
3//! the edit that reverts a change, and the unchanged stretches worth collapsing. Offsets are
4//! chars, lines are 0-based.
5
6use std::ops::Range;
7
8use ropey::Rope;
9
10use crate::diff::LineChange;
11
12/// What a marked range is.
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum DiffMark {
15    /// A whole line of the original that was removed or replaced.
16    RemovedLine,
17    /// A whole line of the modified text that was inserted or replaces others.
18    InsertedLine,
19    /// Chars inside a changed line of the original.
20    RemovedText,
21    /// Chars inside a changed line of the modified text.
22    InsertedText,
23}
24
25/// From the start of `lines`' first line to the end of its last line, without the line
26/// break.
27fn line_span(rope: &Rope, lines: &Range<usize>) -> Range<usize> {
28    let last_line = rope.len_lines().saturating_sub(1);
29    let first = lines.start.min(last_line);
30    let last = lines.end.saturating_sub(1).max(lines.start).min(last_line);
31    rope.line_to_char(first)..rope.line_to_char(last) + crate::line_len(rope, last)
32}
33
34/// The ranges to mark: the original's in `old`, the modified text's in `new`. With
35/// `inline` the original is not shown, so it gets no marks.
36pub fn marks(old: &Rope, new: &Rope, changes: &[LineChange], inline: bool) -> Vec<(DiffMark, Range<usize>)> {
37    let mut out = Vec::new();
38    for c in changes {
39        if !c.old.is_empty() && !inline {
40            out.push((DiffMark::RemovedLine, line_span(old, &c.old)));
41        }
42        if !c.new.is_empty() {
43            out.push((DiffMark::InsertedLine, line_span(new, &c.new)));
44        }
45        for i in &c.inner {
46            if !i.old.is_empty() && !inline {
47                out.push((DiffMark::RemovedText, i.old.clone()));
48            }
49            if !i.new.is_empty() {
50                out.push((DiffMark::InsertedText, i.new.clone()));
51            }
52        }
53    }
54    out
55}
56
57/// A block of empty lines in one pane, so the panes stay aligned.
58#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59pub struct Filler {
60    /// True for the modified pane, false for the original.
61    pub in_modified: bool,
62    /// The line the block follows (-1: before the first line).
63    pub after_line: isize,
64    pub lines: usize,
65}
66
67/// Side by side, the shorter side of each change gets the missing lines.
68pub fn fillers(changes: &[LineChange]) -> Vec<Filler> {
69    changes
70        .iter()
71        .filter_map(|c| {
72            let (old, new) = (c.old.len() as isize, c.new.len() as isize);
73            match old.cmp(&new) {
74                std::cmp::Ordering::Greater => {
75                    Some(Filler { in_modified: true, after_line: c.new.end as isize - 1, lines: (old - new) as usize })
76                }
77                std::cmp::Ordering::Less => {
78                    Some(Filler { in_modified: false, after_line: c.old.end as isize - 1, lines: (new - old) as usize })
79                }
80                std::cmp::Ordering::Equal => None,
81            }
82        })
83        .collect()
84}
85
86/// The first line of the next change after `line` in the modified text (or the previous one
87/// before it), wrapping around; None without changes.
88pub fn next_change(changes: &[LineChange], line: usize, forward: bool) -> Option<usize> {
89    let starts = changes.iter().map(|c| c.new.start);
90    if forward {
91        starts.clone().find(|&s| s > line).or_else(|| starts.clone().next())
92    } else {
93        starts.clone().rev().find(|&s| s < line).or_else(|| starts.clone().next_back())
94    }
95}
96
97/// From the start of `lines` to the start of the line after them (the end of the text for
98/// the last lines).
99fn block_span(rope: &Rope, lines: &Range<usize>) -> Range<usize> {
100    let line_count = rope.len_lines();
101    let at = |line: usize| if line >= line_count { rope.len_chars() } else { rope.line_to_char(line) };
102    let start = at(lines.start);
103    start..at(lines.end).max(start)
104}
105
106/// True when the text does not end with a line break.
107fn open_ended(rope: &Rope) -> bool {
108    rope.len_chars() > 0 && rope.char(rope.len_chars() - 1) != '\n'
109}
110
111/// The edit to the modified text that puts change `c`'s original lines back.
112pub fn revert_edit(old: &Rope, new: &Rope, c: &LineChange) -> (Range<usize>, String) {
113    let from = block_span(old, &c.old);
114    let mut text = old.slice(from.clone()).to_string();
115    let mut to = block_span(new, &c.new);
116    // At the end of a text without a final line break, the break between the last two
117    // lines belongs to the block: reverting an addition takes it away, reverting a deletion
118    // brings it back before the lines.
119    if from.is_empty()
120        && from.start == old.len_chars()
121        && open_ended(old)
122        && to.start > 0
123        && new.char(to.start - 1) == '\n'
124    {
125        to.start -= 1;
126    } else if to.is_empty() && to.start == new.len_chars() && open_ended(new) {
127        if text.ends_with('\n') {
128            text.pop();
129        }
130        text.insert(0, '\n');
131    }
132    (to, text)
133}
134
135/// Unchanged stretches longer than `2 * context` lines on one side (`in_modified` picks it),
136/// as (first, last) lines to fold, keeping `context` lines around each change.
137pub fn unchanged_regions(
138    changes: &[LineChange],
139    in_modified: bool,
140    line_count: usize,
141    context: usize,
142) -> Vec<(usize, usize)> {
143    let mut out = Vec::new();
144    let mut at = 0;
145    for c in changes {
146        let lines = if in_modified { &c.new } else { &c.old };
147        if lines.start.saturating_sub(at) > 2 * context {
148            // At the top of the file there is no change above to keep context for.
149            let first = if at == 0 { at } else { at + context };
150            out.push((first, lines.start - context - 1));
151        }
152        at = lines.end;
153    }
154    let last = line_count.saturating_sub(1);
155    if last.saturating_sub(at) > 2 * context {
156        out.push((at + context, last));
157    }
158    out.retain(|(a, b)| b > a);
159    out
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165    use crate::{DiffOptions, diff};
166
167    fn changes(a: &str, b: &str) -> (Rope, Rope, Vec<LineChange>) {
168        let (a, b) = (Rope::from_str(a), Rope::from_str(b));
169        let d = diff(&a, &b, DiffOptions::default(), &mut || true);
170        (a, b, d.changes)
171    }
172
173    #[test]
174    fn marks_fillers_and_steps() {
175        let (a, b, c) = changes("one\ntwo\nthree\nfour\n", "one\n2\nthree\nfour\nfive\nsix\n");
176        let m = marks(&a, &b, &c, false);
177        assert!(m.contains(&(DiffMark::RemovedLine, 4..7)));
178        assert!(m.contains(&(DiffMark::InsertedLine, 4..5)));
179        assert!(
180            marks(&a, &b, &c, true).iter().all(|(k, _)| matches!(k, DiffMark::InsertedLine | DiffMark::InsertedText))
181        );
182        // Two lines were added at the end: the original pane gets a two-line filler.
183        assert!(fillers(&c).contains(&Filler { in_modified: false, after_line: 3, lines: 2 }));
184        assert_eq!(next_change(&c, 0, true), Some(1));
185        assert_eq!(next_change(&c, 1, true), Some(4));
186        assert_eq!(next_change(&c, 4, true), Some(1));
187        assert_eq!(next_change(&c, 1, false), Some(4));
188        assert_eq!(next_change(&[], 1, false), None);
189    }
190
191    #[test]
192    fn revert_puts_the_original_back_in_chars() {
193        // An emoji before the change: offsets are chars, not UTF-16 units.
194        let (a, b, c) = changes("😀\nold\nend", "😀\nnew\nend");
195        let (range, text) = revert_edit(&a, &b, &c[0]);
196        assert_eq!((range, text.as_str()), (2..6, "old\n"));
197        // Every change reverted gives the original back, also at the end of texts with and
198        // without a final line break.
199        for (before, after) in [
200            ("a\nb", "a\nb\nc"),
201            ("a\nb\nc", "a\nb"),
202            ("a\nb\n", "a\nb\nc\n"),
203            ("a\nb\nc\n", "a\nb\n"),
204            ("a\nb", "a\nB\nc"),
205            ("x", ""),
206            ("", "x\ny"),
207        ] {
208            let (a, b, c) = changes(before, after);
209            let mut reverted = b.clone();
210            for change in c.iter().rev() {
211                let (range, text) = revert_edit(&a, &reverted, change);
212                reverted.remove(range.clone());
213                reverted.insert(range.start, &text);
214            }
215            assert_eq!(reverted.to_string(), before, "reverting {after:?}");
216        }
217    }
218
219    #[test]
220    fn collapsible_stretches_keep_context() {
221        let a: String = (0..30).map(|i| format!("{i}\n")).collect();
222        let b = a.replace("15\n", "fifteen\n");
223        let (_, _, c) = changes(&a, &b);
224        assert_eq!(unchanged_regions(&c, true, 31, 3), vec![(0, 11), (19, 30)]);
225    }
226}