1use std::ops::Range;
7
8use ropey::Rope;
9
10use crate::diff::LineChange;
11
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum DiffMark {
15 RemovedLine,
17 InsertedLine,
19 RemovedText,
21 InsertedText,
23}
24
25fn 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
34pub 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59pub struct Filler {
60 pub in_modified: bool,
62 pub after_line: isize,
64 pub lines: usize,
65}
66
67pub 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
86pub 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
97fn 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
106fn open_ended(rope: &Rope) -> bool {
108 rope.len_chars() > 0 && rope.char(rope.len_chars() - 1) != '\n'
109}
110
111pub 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 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
135pub 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 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 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 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 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}