1use std::collections::VecDeque;
4use std::hash::{DefaultHasher, Hash, Hasher};
5use std::mem::discriminant;
6use std::ops::Range;
7
8use similar::{Algorithm, DiffOp, DiffTag, capture_diff_slices};
9use unicode_segmentation::UnicodeSegmentation;
10
11use crate::document::{Block, Line, Rgb, Settings, Span};
12use crate::markdown::{Section, SectionKind, render_sections};
13use crate::text::{first_word_width, trimmed_width};
14
15const MAX_SECTIONS: usize = 10_000;
18const MAX_WORDS: usize = 20_000;
20const MAX_DIFFED_WORDS: usize = 50_000;
22
23#[derive(Clone, Debug, PartialEq, Eq)]
25#[non_exhaustive]
26pub enum SectionChange {
27 Same {
29 old: Section,
30 new: Section,
31 },
32 Added(Section),
33 Removed(Section),
34 Changed {
39 old: Section,
40 new: Section,
41 old_words: Vec<Range<usize>>,
42 new_words: Vec<Range<usize>>,
43 },
44}
45
46pub fn sections(old: &str, new: &str, settings: &Settings) -> Vec<SectionChange> {
48 let old = render_sections(old, settings);
49 let new = render_sections(new, settings);
50 let ops = section_ops(&old, &new, settings);
51 paired(&ops, old, new)
52}
53
54#[derive(PartialEq, Eq, PartialOrd, Ord)]
57struct Key<'a> {
58 hash: u64,
61 kind: &'a SectionKind,
62 lines: Vec<String>,
63 pictures: Vec<&'a [u8]>,
64}
65
66impl<'a> Key<'a> {
67 fn of(section: &'a Section, settings: &Settings) -> Self {
68 let pictures: Vec<&[u8]> = section
69 .blocks
70 .iter()
71 .filter_map(|block| if let Block::Picture(picture) = block { Some(&picture.png[..]) } else { None })
72 .collect();
73 let lines = written_lines(section, settings);
74 Self { hash: hash_of(&(§ion.kind, &lines, &pictures)), kind: §ion.kind, lines, pictures }
75 }
76}
77
78fn hash_of(value: &impl Hash) -> u64 {
79 let mut hasher = DefaultHasher::new();
80 value.hash(&mut hasher);
81 hasher.finish()
82}
83
84impl Hash for Key<'_> {
85 fn hash<H: Hasher>(&self, state: &mut H) {
86 state.write_u64(self.hash);
87 }
88}
89
90fn written_lines(section: &Section, settings: &Settings) -> Vec<String> {
93 let lines: Vec<&Line> = lines(section).collect();
94 let wrapped = std::iter::once(false).chain(lines.windows(2).map(|pair| is_wrapped(§ion.kind, pair[0], pair[1], settings)));
95 let surface = settings.theme.palette.surface;
96 let mut joined: Vec<String> = Vec::new();
97 for (line, wrapped) in lines.iter().zip(wrapped) {
98 let text = written(line, keeps_spacing(§ion.kind, line, surface));
99 match joined.last_mut() {
100 Some(previous) if wrapped => {
101 previous.push(' ');
102 previous.push_str(&text);
103 }
104 _ => joined.push(text),
105 }
106 }
107 joined
108}
109
110fn is_wrapped(kind: &SectionKind, line: &Line, next: &Line, settings: &Settings) -> bool {
113 let surface = settings.theme.palette.surface;
114 let flows = *kind != SectionKind::Table && !keeps_spacing(kind, line, surface) && !keeps_spacing(kind, next, surface);
115 flows && first_word_width(opening_text(next)).is_some_and(|word| text_end(line) + 1 + word > settings.width)
116}
117
118fn text_end(line: &Line) -> usize {
120 let end = line.spans.iter().rposition(|span| !span.is_frame).map_or(0, |last| last + 1);
121 trimmed_width(&line.spans[..end])
122}
123
124fn opening_text(line: &Line) -> &[Span] {
126 let start = line.spans.iter().position(|span| !span.is_frame).unwrap_or(line.spans.len());
127 let text = &line.spans[start..];
128 &text[..text.iter().position(|span| span.is_frame).unwrap_or(text.len())]
129}
130
131fn keeps_spacing(kind: &SectionKind, line: &Line, surface: Rgb) -> bool {
134 matches!(kind, SectionKind::Mermaid | SectionKind::FrontMatter | SectionKind::Html)
135 || line.spans.iter().any(|span| !span.is_frame && span.style.bg == Some(surface))
136}
137
138fn lines(section: &Section) -> impl Iterator<Item = &Line> {
139 section.blocks.iter().flat_map(Block::lines)
140}
141
142fn written(line: &Line, keeps_spacing: bool) -> String {
144 let text: String = line.spans.iter().map(|span| if span.is_frame { " " } else { span.text.as_str() }).collect();
145 if keeps_spacing { text } else { text.split_whitespace().collect::<Vec<_>>().join(" ") }
146}
147
148fn section_ops(old: &[Section], new: &[Section], settings: &Settings) -> Vec<DiffOp> {
149 let old_keys: Vec<Key> = old.iter().map(|section| Key::of(section, settings)).collect();
150 let new_keys: Vec<Key> = new.iter().map(|section| Key::of(section, settings)).collect();
151 if old_keys.len() + new_keys.len() > MAX_SECTIONS {
152 return ends_only(&old_keys, &new_keys);
153 }
154 capture_diff_slices(Algorithm::Patience, &old_keys, &new_keys)
155}
156
157fn ends_only<T: PartialEq>(old: &[T], new: &[T]) -> Vec<DiffOp> {
159 let start = old.iter().zip(new).take_while(|(old, new)| old == new).count();
160 let end = old[start..].iter().rev().zip(new[start..].iter().rev()).take_while(|(old, new)| old == new).count();
161 let (old_len, new_len) = (old.len() - start - end, new.len() - start - end);
162 let ops = [
163 DiffOp::Equal { old_index: 0, new_index: 0, len: start },
164 DiffOp::Replace { old_index: start, old_len, new_index: start, new_len },
165 DiffOp::Equal { old_index: start + old_len, new_index: start + new_len, len: end },
166 ];
167 ops.into_iter().filter(|op| op.old_range().len() + op.new_range().len() > 0).collect()
168}
169
170fn is_equal(op: &DiffOp) -> bool {
171 op.tag() == DiffTag::Equal
172}
173
174fn paired(ops: &[DiffOp], old: Vec<Section>, new: Vec<Section>) -> Vec<SectionChange> {
177 let (mut old, mut new) = (old.into_iter(), new.into_iter());
178 let mut changes = Vec::new();
179 let mut budget = MAX_DIFFED_WORDS;
180 for run in ops.chunk_by(|left, right| is_equal(left) == is_equal(right)) {
181 let removed: Vec<Section> = old.by_ref().take(run.iter().map(|op| op.old_range().len()).sum()).collect();
182 let added: Vec<Section> = new.by_ref().take(run.iter().map(|op| op.new_range().len()).sum()).collect();
183 if run.iter().all(is_equal) {
184 changes.extend(removed.into_iter().zip(added).map(|(old, new)| SectionChange::Same { old, new }));
185 } else {
186 let (pairs, left) = pair(removed, added, budget);
187 changes.extend(pairs);
188 budget = left;
189 }
190 }
191 changes
192}
193
194fn pairs_with(old: &SectionKind, new: &SectionKind) -> bool {
196 discriminant(old) == discriminant(new)
197}
198
199fn pair(removed: Vec<Section>, added: Vec<Section>, budget: usize) -> (Vec<SectionChange>, usize) {
202 let mut added = VecDeque::from(added);
203 let mut changes = Vec::new();
204 let mut budget = budget;
205 let mut kinds_left_alone = Vec::new();
207 for old in removed {
208 let kind = discriminant(&old.kind);
209 let partner = if kinds_left_alone.contains(&kind) { None } else { added.iter().position(|new| pairs_with(&old.kind, &new.kind)) };
210 let Some(skipped) = partner else {
211 kinds_left_alone.push(kind);
212 changes.push(SectionChange::Removed(old));
213 continue;
214 };
215 changes.extend(added.drain(..skipped).map(SectionChange::Added));
216 let Some(new) = added.pop_front() else {
217 changes.push(SectionChange::Removed(old));
218 continue;
219 };
220 let (change, left) = changed(old, new, budget);
221 changes.push(change);
222 budget = left;
223 }
224 changes.extend(added.into_iter().map(SectionChange::Added));
225 (changes, budget)
226}
227
228fn changed(old: Section, new: Section, budget: usize) -> (SectionChange, usize) {
230 let (old_words, new_words, budget) =
231 if old.kind == SectionKind::Mermaid { (Vec::new(), Vec::new(), budget) } else { changed_words(&words(&old), &words(&new), budget) };
232 (SectionChange::Changed { old, new, old_words, new_words }, budget)
233}
234
235struct Word<'a> {
238 text: &'a str,
239 chars: Range<usize>,
240 joins_previous: bool,
241}
242
243fn words(section: &Section) -> Vec<Word<'_>> {
245 let mut words = Vec::new();
246 let mut next = 0;
247 for line in lines(section) {
248 let mut joins_previous = false;
249 for span in &line.spans {
250 if span.is_frame {
251 next += span.text.chars().count();
252 joins_previous = false;
253 continue;
254 }
255 for text in span.text.split_word_bounds() {
256 let chars = next..next + text.chars().count();
257 next = chars.end;
258 if !text.chars().all(char::is_whitespace) {
259 words.push(Word { text, chars, joins_previous });
260 joins_previous = true;
261 }
262 }
263 }
264 }
265 words
266}
267
268fn changed_words(old: &[Word], new: &[Word], budget: usize) -> (Vec<Range<usize>>, Vec<Range<usize>>, usize) {
270 let count = old.len() + new.len();
271 let (ops, budget) = if count > MAX_WORDS || count > budget {
272 (vec![DiffOp::Replace { old_index: 0, old_len: old.len(), new_index: 0, new_len: new.len() }], budget)
273 } else {
274 (capture_diff_slices(Algorithm::Myers, &texts(old), &texts(new)), budget - count)
275 };
276 (marked(&ops, old, DiffOp::old_range), marked(&ops, new, DiffOp::new_range), budget)
277}
278
279fn texts<'a>(words: &[Word<'a>]) -> Vec<&'a str> {
280 words.iter().map(|word| word.text).collect()
281}
282
283fn marked(ops: &[DiffOp], words: &[Word], side: fn(&DiffOp) -> Range<usize>) -> Vec<Range<usize>> {
285 let changed = ops.iter().flat_map(|op| std::iter::repeat_n(!is_equal(op), side(op).len()));
286 let flagged: Vec<(&Word, bool)> = words.iter().zip(changed).collect();
287 let runs = flagged.chunk_by(|(_, left), (word, right)| word.joins_previous && left == right);
288 let changed_runs = runs.filter(|run| run.iter().all(|(_, changed)| *changed));
289 changed_runs.filter_map(|run| Some(run.first()?.0.chars.start..run.last()?.0.chars.end)).collect()
290}
291
292#[cfg(test)]
293mod tests {
294 #![allow(clippy::unwrap_used)]
295
296 use super::*;
297 use crate::document::{CellSize, test_settings};
298
299 const README: &str = "# mrk\n\n## Install\n\nRun the installer once.\n\n- fast\n- safe\n\nThat is all.\n";
300 const MERMAID: &str = "```mermaid\ngraph TD\n A --> B\n```\n";
301
302 fn diff(old: &str, new: &str) -> Vec<SectionChange> {
303 sections(old, new, &test_settings())
304 }
305
306 fn diff_at(old: &str, new: &str, width: usize) -> Vec<SectionChange> {
307 sections(old, new, &Settings { width, ..test_settings() })
308 }
309
310 fn outcomes(changes: &[SectionChange]) -> Vec<&'static str> {
311 let outcome = |change: &SectionChange| match change {
312 SectionChange::Same { .. } => "same",
313 SectionChange::Added(_) => "added",
314 SectionChange::Removed(_) => "removed",
315 SectionChange::Changed { .. } => "changed",
316 };
317 changes.iter().map(outcome).collect()
318 }
319
320 fn sides(changes: Vec<SectionChange>) -> (Vec<Section>, Vec<Section>) {
321 let (mut old, mut new) = (Vec::new(), Vec::new());
322 for change in changes {
323 match change {
324 SectionChange::Same { old: before, new: after } | SectionChange::Changed { old: before, new: after, .. } => {
325 old.push(before);
326 new.push(after);
327 }
328 SectionChange::Added(after) => new.push(after),
329 SectionChange::Removed(before) => old.push(before),
330 }
331 }
332 (old, new)
333 }
334
335 fn marked_text(section: &Section, ranges: &[Range<usize>]) -> Vec<String> {
337 let text: Vec<char> = lines(section).map(Line::plain).collect::<String>().chars().collect();
338 ranges.iter().map(|range| text[range.clone()].iter().collect()).collect()
339 }
340
341 fn marked_words(changes: &[SectionChange]) -> (Vec<String>, Vec<String>) {
343 let [SectionChange::Changed { old, new, old_words, new_words }] = changes else { panic!("{changes:#?}") };
344 (marked_text(old, old_words), marked_text(new, new_words))
345 }
346
347 fn texts(words: &[&str]) -> Vec<String> {
348 words.iter().map(|word| (*word).to_owned()).collect()
349 }
350
351 #[test]
352 fn an_edited_readme_gives_one_change_of_each_sort_and_keeps_the_rest() {
353 let new = README.replace("## Install\n\n", "").replace("once", "twice").replace("- safe\n", "- safe\n- small\n");
354
355 assert_eq!(outcomes(&diff(README, &new)), ["same", "removed", "changed", "same", "same", "added", "same"]);
356 }
357
358 #[test]
359 fn one_word_changed_in_a_wrapped_paragraph_marks_that_word_on_each_side() {
360 let old = "The quick brown fox jumps over the lazy dog, then runs far into the woods and over the hills, where nobody can see.\n";
361 let new = old.replace("quick", "slow");
362
363 assert_eq!(marked_words(&diff_at(old, &new, 30)), (texts(&["quick"]), texts(&["slow"])));
364 }
365
366 #[test]
367 fn neighbouring_changed_words_are_one_range_without_the_spaces_around() {
368 let changes = diff("Keep this text and that.\n", "Keep other words and that.\n");
369
370 assert_eq!(marked_words(&changes), (texts(&["this text"]), texts(&["other words"])));
371 }
372
373 #[test]
374 fn a_quote_that_wraps_again_marks_its_word_and_never_its_bar() {
375 let old = "> The quick brown fox jumps over the lazy dog, then runs far into the woods and over the hills.\n";
376 let new = old.replace("quick", "very slow");
377
378 assert_eq!(marked_words(&diff_at(old, &new, 30)), (texts(&["quick"]), texts(&["very slow"])));
379 }
380
381 #[test]
382 fn changed_words_across_a_line_end_are_marked_line_by_line_without_the_frame() {
383 let quote = "> one two three four five six seven eight nine ten\n";
384 let code = "```\nalpha beta gamma delta epsilon zeta\n```\n";
385
386 assert_eq!(marked_words(&diff_at(quote, "e.replace("four five", "4 5"), 20)).0, ["four", "five"]);
387 assert_eq!(marked_words(&diff_at(code, &code.replace("gamma delta", "G D"), 20)).0, ["gamma", "delta epsilon"]);
388 }
389
390 #[test]
391 fn cells_side_by_side_are_marked_apart_from_the_border_between_them() {
392 let changes = diff("| a | b |\n|---|---|\n| one | two |\n", "| a | b |\n|---|---|\n| uno | dos |\n");
393
394 assert_eq!(marked_words(&changes), (texts(&["one", "two"]), texts(&["uno", "dos"])));
395 }
396
397 #[test]
398 fn a_list_renumbered_wider_keeps_its_items_the_same() {
399 let nine: String = (1..=9).map(|number| format!("{number}. item\n")).collect();
400 let ten = format!("{nine}10. item\n");
401
402 assert_eq!(outcomes(&diff(&nine, &ten)), [vec!["same"; 9], vec!["added"]].concat());
403 }
404
405 #[test]
406 fn a_list_renumbered_wider_keeps_an_item_that_wraps_again_the_same() {
407 let long = format!("5. {}\n", "word ".repeat(14) + "seventy");
408 let nine: String = (1..=9).map(|number| if number == 5 { long.clone() } else { format!("{number}. item\n") }).collect();
409 let ten = format!("{nine}10. x\n");
410
411 assert_eq!(outcomes(&diff(&nine, &ten)), [vec!["same"; 9], vec!["added"]].concat());
412 }
413
414 #[test]
415 fn text_the_layout_wraps_in_any_container_is_compared_as_one_line() {
416 let text = "The quick brown fox jumps over the lazy dog, then runs far into the woods and over the hills.";
417 let containers = ["", "# ", "- ", "10. ", "> ", "> [!NOTE]\n> ", "- a\n - ", "> - ", "Note[^1]\n\n[^1]: "];
418 for width in [20, 33, 47, 80] {
419 let settings = Settings { width, ..test_settings() };
420 for container in containers {
421 let sections = render_sections(&format!("{container}{text}\n"), &settings);
422 let key = Key::of(sections.last().unwrap(), &settings);
423
424 assert!(key.lines.iter().any(|line| line.ends_with(text)), "{container:?} at {width}: {:?}", key.lines);
425 }
426 }
427 }
428
429 #[test]
430 fn a_paragraph_wrapped_over_many_rows_is_compared_as_its_whole_text() {
431 let text = (0..2_000).map(|index| format!("w{index}")).collect::<Vec<_>>().join(" ");
432 let settings = Settings { width: 20, ..test_settings() };
433
434 let sections = render_sections(&text, &settings);
435
436 assert_eq!(Key::of(§ions[0], &settings).lines, [text]);
437 }
438
439 #[test]
440 fn a_break_the_input_forced_in_wrapped_text_is_a_change() {
441 let text = "The quick brown fox jumps over the lazy dog";
442
443 assert_eq!(outcomes(&diff_at(&format!("- {text} end\n"), &format!("- {text}\\\nend\n"), 30)), ["changed"]);
444 }
445
446 #[test]
447 fn spacing_in_code_is_a_change() {
448 assert_eq!(outcomes(&diff("```\nif a:\n b\n```\n", "```\nif a:\n b\n```\n")), ["changed"]);
449 }
450
451 #[test]
452 fn spacing_in_code_inside_a_list_item_or_a_quote_is_a_change() {
453 let item = |indent: &str| format!("- x\n\n ```\n if a:\n {indent}b\n ```\n");
454 let quote = |indent: &str| format!("> ```\n> if a:\n> {indent}b\n> ```\n");
455 for code in [item, quote] {
456 assert_eq!(outcomes(&diff(&code(" "), &code(" "))), ["changed"], "{}", code(" "));
457 }
458 }
459
460 #[test]
461 fn spacing_inside_a_line_and_written_box_characters_are_changes() {
462 for (old, new) in [("a+b\n", "a + b\n"), ("f(x)\n", "f (x)\n"), ("a, b\n", "a ,b\n"), ("a \u{2500} b\n", "a b\n")] {
463 assert_eq!(outcomes(&diff(old, new)), ["changed"], "{old:?} -> {new:?}");
464 }
465 assert_eq!(marked_words(&diff("see \u{2502} here\n", "see here\n")).0, ["\u{2502}"]);
466 }
467
468 #[test]
469 fn a_paragraph_rewrapped_with_wider_spaces_is_the_same() {
470 assert_eq!(outcomes(&diff("one two\nthree\n", "one two three\n")), ["same"]);
471 }
472
473 #[test]
474 fn past_the_section_limit_only_equal_ends_pair_as_same() {
475 let ops = ends_only(&[1, 2, 3, 4], &[1, 9, 8, 4]);
476
477 assert_eq!(
478 ops.iter().map(|op| (op.tag(), op.old_range(), op.new_range())).collect::<Vec<_>>(),
479 [(DiffTag::Equal, 0..1, 0..1), (DiffTag::Replace, 1..3, 1..3), (DiffTag::Equal, 3..4, 3..4)]
480 );
481 assert_eq!(ends_only(&[1, 2], &[1, 2]).len(), 1);
482 }
483
484 #[test]
485 fn a_pair_over_what_is_left_of_the_word_budget_is_marked_whole_and_a_smaller_one_after_it_diffed() {
486 let paragraph = |word: &str| format!("{}\n\n", "word ".repeat(MAX_WORDS / 2 - 1) + word);
487 let old = ["a", "b", "c"].map(paragraph).concat() + "short a";
488 let new = ["x", "y", "z"].map(paragraph).concat() + "short x";
489
490 let changes = diff_at(&old, &new, 1000);
491
492 let marks: Vec<usize> =
493 changes.iter().map(|change| if let SectionChange::Changed { old_words, .. } = change { old_words.len() } else { 0 }).collect();
494 assert_eq!(marks[..2], [1, 1]);
495 assert!(marks[2] > 1, "{marks:?}");
496 let SectionChange::Changed { old_words, .. } = &changes[3] else { panic!("a changed short paragraph") };
497 assert_eq!(old_words.first(), Some(&(6..7)), "{old_words:?}");
498 }
499
500 #[test]
501 fn the_same_input_gives_the_same_output() {
502 let new = README.replace("once", "twice") + "\n" + MERMAID;
503
504 assert_eq!(diff(README, &new), diff(README, &new));
505 }
506
507 #[test]
508 fn a_paragraph_over_the_word_limit_is_marked_whole() {
509 let old = "word ".repeat(MAX_WORDS / 2 + 1);
510 let new = old.replacen("word", "other", 1);
511
512 let changes = diff_at(&old, &new, 1000);
513
514 let [SectionChange::Changed { old, old_words, .. }] = &changes[..] else { panic!("one change") };
515 assert_eq!(old_words.len(), old.blocks.iter().flat_map(Block::lines).count());
516 }
517
518 #[test]
519 fn a_changed_mermaid_section_marks_no_words() {
520 let new = MERMAID.replace('B', "C");
521 for cell in [None, Some(CellSize { width_px: 10, height_px: 22 })] {
522 let changes = sections(MERMAID, &new, &Settings { cell, ..test_settings() });
523
524 assert!(
525 matches!(&changes[..], [SectionChange::Changed { old_words, new_words, .. }] if old_words.is_empty() && new_words.is_empty()),
526 "cell {cell:?}: {changes:#?}"
527 );
528 }
529 }
530
531 #[test]
532 fn a_line_break_added_inside_a_paragraph_is_a_change() {
533 assert_eq!(outcomes(&diff("one two\n", "one\\\ntwo\n")), ["changed"]);
534 }
535
536 #[test]
537 fn a_heading_that_changes_level_or_a_ticked_task_is_changed() {
538 assert_eq!(outcomes(&diff("# Title\n", "## Title\n")), ["changed"]);
539 assert_eq!(outcomes(&diff("- [ ] ship\n", "- [x] ship\n")), ["changed"]);
540 }
541
542 #[test]
543 fn a_removed_section_pairs_with_the_next_added_section_of_its_kind() {
544 assert_eq!(outcomes(&diff("# Title\n\nOld text.\n", "- new\n\nNew text.\n")), ["removed", "added", "changed"]);
545 }
546
547 #[test]
548 fn every_section_of_each_side_comes_up_once_in_order() {
549 let pairs = [("- a\n- b\n", "- b\n- a\n"), (README, "- safe\n- fast\n\n# mrk\n"), ("", README), (README, ""), (README, README)];
550 for (old, new) in pairs {
551 let (before, after) = sides(diff(old, new));
552
553 assert_eq!(before, render_sections(old, &test_settings()), "{old:?} -> {new:?}");
554 assert_eq!(after, render_sections(new, &test_settings()), "{old:?} -> {new:?}");
555 }
556 }
557
558 #[test]
559 fn an_empty_side_gives_only_added_or_removed_sections() {
560 assert!(diff("", README).iter().all(|change| matches!(change, SectionChange::Added(_))));
561 assert!(diff(README, "").iter().all(|change| matches!(change, SectionChange::Removed(_))));
562 assert_eq!(diff(README, README).len(), 6);
563 }
564
565 #[test]
566 fn an_item_inserted_above_renumbers_the_rest_and_keeps_them_the_same() {
567 assert_eq!(outcomes(&diff("1. a\n2. b\n", "1. new\n2. a\n3. b\n")), ["added", "same", "same"]);
568 }
569}