1use std::borrow::Cow;
19
20use pulldown_cmark::{Event, LinkType, Options, Parser, Tag, TagEnd};
21use similar::{Algorithm, DiffTag, capture_diff_slices};
22
23use crate::util::word_tokens as tokens;
24
25const WORD_DIFF_SIMILARITY: f64 = 0.3;
28
29const RARE_LINE_SHARE: usize = 8;
33
34const MAX_CANDIDATES: usize = 64;
36
37const REFLOW_MAX_BYTES: usize = 400_000;
41
42pub fn diff_markdown(old: &str, new: &str) -> String {
87 let old = old.replace("\r\n", "\n");
88 let new = new.replace("\r\n", "\n");
89 let old_lines = lines(&old);
90 let new_lines = lines(&new);
91 let mut out = Output::default();
92 let ops = capture_diff_slices(Algorithm::Patience, &old_lines, &new_lines);
93 for op in &ops {
94 let (tag, olds, news) = op.as_tag_tuple();
95 match tag {
96 DiffTag::Equal => {
97 for line in &new_lines[news] {
98 out.line(&escape(line));
99 }
100 }
101 DiffTag::Delete | DiffTag::Insert | DiffTag::Replace => {
102 hunk(&mut out, &old_lines[olds], &new_lines[news]);
103 }
104 }
105 }
106 out.finish(old.ends_with('\n'), new.ends_with('\n'))
107}
108
109fn lines(text: &str) -> Vec<&str> {
110 let text = text.strip_suffix('\n').unwrap_or(text);
111 if text.is_empty() {
112 return Vec::new();
113 }
114 opaque_units(text)
115}
116
117fn opaque_units(text: &str) -> Vec<&str> {
121 let mut starts: Vec<usize> = vec![0];
122 starts.extend(
123 text.match_indices('\n')
124 .map(|(at, _)| at + 1)
125 .filter(|&at| at < text.len()),
126 );
127 let line_of = |at: usize| starts.partition_point(|&start| start <= at) - 1;
128 let mut spans: Vec<(usize, usize)> = Vec::new();
129 let options = Options::ENABLE_STRIKETHROUGH | Options::ENABLE_MATH;
130 for (event, range) in Parser::new_ext(text, options).into_offset_iter() {
131 let opaque = match event {
132 Event::Code(_) => true,
133 Event::InlineMath(_) | Event::DisplayMath(_) => !opens_amount(text, range.start),
137 Event::Html(_) | Event::InlineHtml(_) => true,
138 Event::Start(Tag::Image { .. }) => true,
139 Event::Start(Tag::Link { link_type, .. }) => {
140 matches!(link_type, LinkType::Autolink | LinkType::Email)
141 }
142 _ => false,
143 };
144 if opaque && range.end > range.start && text[range.clone()].contains('\n') {
145 spans.push((line_of(range.start), line_of(range.end - 1)));
146 }
147 }
148 spans.sort_unstable();
149 let mut merged: Vec<(usize, usize)> = Vec::new();
151 for (first, last) in spans {
152 match merged.last_mut() {
153 Some((_, end)) if first <= *end + 1 => *end = (*end).max(last),
154 _ => merged.push((first, last)),
155 }
156 }
157 let end_of = |line: usize| match starts.get(line + 1) {
160 Some(&next_start) => next_start - 1,
161 None => text.len(),
162 };
163 let mut units: Vec<&str> = Vec::new();
164 let mut line = 0;
165 for (first, last) in merged {
166 while line < first {
167 units.push(&text[starts[line]..end_of(line)]);
168 line += 1;
169 }
170 units.push(&text[starts[first]..end_of(last)]);
171 line = last + 1;
172 }
173 while line < starts.len() {
174 units.push(&text[starts[line]..end_of(line)]);
175 line += 1;
176 }
177 units
178}
179
180#[doc(hidden)]
184pub fn marker_len(line: &str) -> usize {
185 let bytes = line.as_bytes();
186 let mut at = bytes
187 .iter()
188 .take_while(|b| **b == b' ' || **b == b'\t')
189 .count();
190 while bytes.get(at) == Some(&b'>') {
191 at += 1;
192 if bytes.get(at) == Some(&b' ') {
193 at += 1;
194 }
195 }
196 let rest = &line[at..];
197 if rest.starts_with("[^")
199 && let Some(end) = rest.find("]: ")
200 && !rest[2..end].contains([' ', ']'])
201 {
202 return at + end + 3;
203 }
204 let hashes = rest.bytes().take_while(|b| *b == b'#').count();
205 if (1..=6).contains(&hashes) && matches!(rest.as_bytes().get(hashes), None | Some(b' ')) {
206 return at + hashes + usize::from(rest.len() > hashes);
207 }
208 let list = match rest.as_bytes().first() {
209 Some(b'-' | b'*' | b'+') => 1,
210 Some(b'0'..=b'9') => {
211 let digits = rest.bytes().take_while(u8::is_ascii_digit).count();
212 if digits <= 9 && matches!(rest.as_bytes().get(digits), Some(b'.' | b')')) {
213 digits + 1
214 } else {
215 0
216 }
217 }
218 _ => 0,
219 };
220 if list > 0 && matches!(rest.as_bytes().get(list), Some(b' ' | b'\t')) {
221 at += list + 1;
222 let rest = &line[at..];
223 for task in ["[ ] ", "[x] ", "[X] "] {
224 if rest.starts_with(task) {
225 at += task.len();
226 }
227 }
228 }
229 at
230}
231
232#[doc(hidden)]
235pub fn continues(line: &str) -> bool {
236 let trimmed = line.trim_start();
237 !trimmed.is_empty() && marker_len(line) == 0 && !trimmed.starts_with("```") && !table_row(line)
238}
239
240#[doc(hidden)]
243pub fn open_paragraph(line: &str) -> bool {
244 let trimmed = line.trim_start();
245 !trimmed.is_empty()
246 && !trimmed.starts_with('#')
247 && !trimmed.starts_with("```")
248 && !table_row(line)
249}
250
251#[doc(hidden)]
253pub fn table_row(line: &str) -> bool {
254 line.trim_start().starts_with('|')
255}
256
257pub(super) fn table_row_change(line: &str, open: &str, close: &str) -> String {
260 let mut out = String::new();
261 let mut cell = String::new();
262 let mut escaped = false;
263 let flush = |out: &mut String, cell: &mut String| {
264 let text = cell.trim();
265 if text.is_empty() || text.chars().all(|c| matches!(c, '-' | ':')) {
266 out.push_str(cell);
267 } else {
268 let start = cell.len() - cell.trim_start().len();
269 let end = cell.trim_end().len();
270 out.push_str(&cell[..start]);
271 out.push_str(open);
272 out.push_str(&escape(&cell[start..end]));
273 out.push_str(close);
274 out.push_str(&cell[end..]);
275 }
276 cell.clear();
277 };
278 for c in line.chars() {
279 if c == '|' && !escaped {
280 flush(&mut out, &mut cell);
281 out.push('|');
282 } else {
283 cell.push(c);
284 }
285 escaped = c == '\\' && !escaped;
286 }
287 flush(&mut out, &mut cell);
288 out
289}
290
291fn escape(text: &str) -> Cow<'_, str> {
300 if !text_has_delimiter(text) {
301 return Cow::Borrowed(text);
302 }
303 let points = escape_points(text);
304 if points.is_empty() {
305 return Cow::Borrowed(text);
306 }
307 let mut out = String::with_capacity(text.len() + points.len());
308 let mut from = 0;
309 for at in points {
310 out.push_str(&text[from..at]);
311 out.push('\\');
312 from = at;
313 }
314 out.push_str(&text[from..]);
315 Cow::Owned(out)
316}
317
318const DELIMITERS: [(&str, usize); 11] = [
322 ("{++", 0),
323 ("{--", 0),
324 ("{~~", 0),
325 ("{==", 0),
326 ("{>>", 0),
327 ("++}", 2),
328 ("--}", 2),
329 ("~~}", 2),
330 ("==}", 2),
331 ("<<}", 2),
332 ("~>", 1),
333];
334
335fn text_has_delimiter(text: &str) -> bool {
336 DELIMITERS.iter().any(|(d, _)| text.contains(d))
337 || text
338 .match_indices('{')
339 .any(|(at, _)| super::critic::attribution_tag(&text[at..]).is_some())
340}
341
342fn escape_points(text: &str) -> Vec<usize> {
344 let spans = super::critic::verbatim_ranges(text);
345 let bytes = text.as_bytes();
346 let mut points = Vec::new();
347 let (mut span, mut end) = (0, 0);
349 for i in 0..bytes.len() {
350 if i < end {
351 continue;
352 }
353 if spans.get(span).is_some_and(|range| range.start <= i) {
354 end = spans[span].end;
355 span += 1;
356 continue;
357 }
358 if bytes[i] == b'{'
359 && !escaped_at(text, i)
360 && super::critic::attribution_tag(&text[i..]).is_some()
361 {
362 points.push(i);
363 }
364 for (delimiter, insert) in DELIMITERS {
365 if bytes[i..].starts_with(delimiter.as_bytes()) && !escaped_at(text, i) {
366 points.push(i + insert);
367 break;
368 }
369 }
370 }
371 points.sort_unstable();
372 points.dedup();
373 points
374}
375
376fn escaped_at(text: &str, at: usize) -> bool {
378 text[..at].bytes().rev().take_while(|b| *b == b'\\').count() % 2 == 1
379}
380
381#[derive(Default)]
383struct Output {
384 text: String,
385 started: bool,
386 carry: Option<&'static str>,
389 last: String,
391}
392
393impl Output {
394 fn line(&mut self, line: &str) {
395 if self.started {
396 self.text.push('\n');
397 }
398 self.started = true;
399 if let Some(close) = self.carry.take() {
400 self.text.push_str(close);
401 }
402 self.text.push_str(line);
403 self.last = line.to_string();
404 }
405
406 fn append(&mut self, text: &str) {
408 self.started = true;
409 self.text.push_str(text);
410 self.last.push_str(text);
411 }
412
413 fn finish(mut self, old_trailing: bool, new_trailing: bool) -> String {
414 if let Some(close) = self.carry.take() {
415 let trailing = if close == "--}" {
418 old_trailing
419 } else {
420 new_trailing
421 };
422 if trailing {
423 self.text.push('\n');
424 }
425 self.text.push_str(close);
426 return self.text;
427 }
428 if new_trailing && old_trailing {
429 if self.started {
430 self.text.push('\n');
431 }
432 } else if new_trailing != old_trailing {
433 self.add_trailing(new_trailing);
434 }
435 self.text
436 }
437
438 fn add_trailing(&mut self, inserted: bool) {
442 let close = if inserted { "++}" } else { "--}" };
443 if self.text.ends_with(close) {
444 let at = self.text.len() - close.len();
445 self.text.insert(at, '\n');
446 } else if self.text.ends_with("~~}") {
447 let at = if inserted {
450 self.text.len() - 3
451 } else {
452 self.text.rfind("~>").unwrap_or(self.text.len())
453 };
454 self.text.insert(at, '\n');
455 } else {
456 let open = if inserted { "{++" } else { "{--" };
457 self.text.push_str(&format!("{open}\n{close}"));
458 }
459 }
460}
461
462#[derive(Clone, Copy, PartialEq, Eq)]
463enum Side {
464 Delete,
465 Insert,
466}
467
468impl Side {
469 fn delimiters(self) -> (&'static str, &'static str) {
470 match self {
471 Self::Delete => ("{--", "--}"),
472 Self::Insert => ("{++", "++}"),
473 }
474 }
475}
476
477enum Entry<'a> {
479 Pair(&'a str, &'a str),
480 Only(Side, &'a str),
481}
482
483fn hunk(out: &mut Output, olds: &[&str], news: &[&str]) {
484 if let Some(body) = reflow(olds, news) {
485 for line in body.split('\n') {
486 out.line(line);
487 }
488 return;
489 }
490 let entries = pair(olds, news);
491 let mut at = 0;
492 while at < entries.len() {
493 match entries[at] {
494 Entry::Pair(old, new) => {
495 paired(out, old, new);
496 at += 1;
497 }
498 Entry::Only(..) => {
499 let end = entries[at..]
500 .iter()
501 .position(|e| matches!(e, Entry::Pair(..)))
502 .map_or(entries.len(), |i| at + i);
503 let only = |side: Side| -> Vec<&str> {
504 entries[at..end]
505 .iter()
506 .filter_map(|e| match e {
507 Entry::Only(s, line) if *s == side => Some(*line),
508 _ => None,
509 })
510 .collect()
511 };
512 let deleted = only(Side::Delete);
513 let inserted = only(Side::Insert);
514 group(out, Side::Delete, &deleted);
515 group(out, Side::Insert, &inserted);
516 at = end;
517 }
518 }
519 }
520}
521
522fn reflow(olds: &[&str], news: &[&str]) -> Option<String> {
530 if !plain_paragraph(olds) || !plain_paragraph(news) || (olds.len() < 2 && news.len() < 2) {
531 return None;
532 }
533 let (old, new) = (olds.join("\n"), news.join("\n"));
534 if old.len() + new.len() > REFLOW_MAX_BYTES {
535 return None;
536 }
537 let flat_old = old.replace('\n', " ");
538 let flat_new = new.replace('\n', " ");
539 if similarity(&flat_old, &flat_new) < 0.8 {
540 return None;
541 }
542 let flat = words_diff(&flat_old, &flat_new);
543 let marks =
544 flat.matches("{--").count() + flat.matches("{++").count() + flat.matches("{~~").count();
545 if marks > 2 {
548 return None;
549 }
550 Some(reflow_body(&old, &new))
554}
555
556fn reflow_body(old: &str, new: &str) -> String {
563 let a = tokens(old);
564 let b = tokens(new);
565 fn weigh<'a>(tokens: &[&'a str]) -> Vec<&'a str> {
566 tokens
567 .iter()
568 .flat_map(|token| std::iter::repeat_n(*token, weight(token) as usize))
569 .collect()
570 }
571 fn owner(tokens: &[&str]) -> Vec<usize> {
572 tokens
573 .iter()
574 .enumerate()
575 .flat_map(|(i, token)| std::iter::repeat_n(i, weight(token) as usize))
576 .collect()
577 }
578 let (wa, wb) = (weigh(&a), weigh(&b));
579 let (owners_a, owners_b) = (owner(&a), owner(&b));
580 let mut segments: Vec<(bool, String, String)> = Vec::new();
581 for op in capture_diff_slices(Algorithm::Myers, &wa, &wb) {
582 let (tag, olds, news) = op.as_tag_tuple();
583 let owned = |range: std::ops::Range<usize>, owners: &[usize]| match (
584 range.start,
585 range.end.checked_sub(1),
586 ) {
587 (start, Some(last)) if start <= last => owners[start]..owners[last] + 1,
588 _ => 0..0,
589 };
590 let old_range = owned(olds, &owners_a);
591 let new_range = owned(news, &owners_b);
592 let old_text = a[old_range].concat();
593 let new_text = b[new_range].concat();
594 let equal = tag == DiffTag::Equal;
595 match segments.last_mut() {
596 Some((same, o, n)) if *same == equal => {
597 o.push_str(&old_text);
598 n.push_str(&new_text);
599 }
600 _ => segments.push((equal, old_text, new_text)),
601 }
602 }
603 widen(segments, old, new)
604 .into_iter()
605 .map(|(equal, old_text, new_text)| {
606 if equal {
607 escape(&new_text).into_owned()
608 } else {
609 change(&old_text, &new_text)
610 }
611 })
612 .collect()
613}
614
615fn weight(token: &str) -> i32 {
617 if token.chars().any(char::is_alphanumeric) {
618 3
619 } else {
620 1
621 }
622}
623
624fn plain_paragraph(lines: &[&str]) -> bool {
625 let Some(first) = lines.first() else {
626 return false;
627 };
628 marker_len(first) == 0
629 && !first.trim().is_empty()
630 && !first.starts_with("```")
631 && lines[1..].iter().all(|line| continues(line))
632}
633
634fn pair<'a>(olds: &[&'a str], news: &[&'a str]) -> Vec<Entry<'a>> {
637 let matched = if olds.len() == 1 && news.len() == 1 {
642 vec![(0, 0)]
643 } else {
644 pair_by_similarity(olds, news)
645 };
646 let mut entries = Vec::new();
647 let (mut i, mut j) = (0, 0);
648 for (mi, mj) in matched
649 .into_iter()
650 .chain(std::iter::once((olds.len(), news.len())))
651 {
652 entries.extend(olds[i..mi].iter().map(|l| Entry::Only(Side::Delete, l)));
653 entries.extend(news[j..mj].iter().map(|l| Entry::Only(Side::Insert, l)));
654 if mi < olds.len() && mj < news.len() {
655 entries.push(Entry::Pair(olds[mi], news[mj]));
656 }
657 i = mi + 1;
658 j = mj + 1;
659 }
660 entries
661}
662
663fn pair_by_similarity(olds: &[&str], news: &[&str]) -> Vec<(usize, usize)> {
671 let mut ids = std::collections::HashMap::new();
672 let mut interned: Vec<Vec<u32>> = Vec::with_capacity(olds.len() + news.len());
673 for line in olds.iter().chain(news.iter()) {
674 interned.push(
675 body_words(line)
676 .into_iter()
677 .map(|word| intern(&mut ids, word))
678 .collect(),
679 );
680 }
681 let (old_words, new_words) = interned.split_at(olds.len());
682 let sorted = |words: &[u32]| -> Vec<u32> {
683 let mut out = words.to_vec();
684 out.sort_unstable();
685 out
686 };
687 let old_multiset: Vec<Vec<u32>> = old_words.iter().map(|w| sorted(w)).collect();
688 let new_multiset: Vec<Vec<u32>> = new_words.iter().map(|w| sorted(w)).collect();
689 let mut old_distinct: Vec<Vec<u32>> = old_multiset.clone();
690 for words in &mut old_distinct {
691 words.dedup();
692 }
693 let mut new_distinct: Vec<Vec<u32>> = new_multiset.clone();
694 for words in &mut new_distinct {
695 words.dedup();
696 }
697 let mut index: std::collections::HashMap<u32, Vec<usize>> = std::collections::HashMap::new();
699 for (i, words) in old_distinct.iter().enumerate() {
700 for &word in words {
701 index.entry(word).or_default().push(i);
702 }
703 }
704 let shape =
705 |lines: &[&str]| -> Vec<String> { lines.iter().map(|line| marker_shape(line)).collect() };
706 let (old_shape, new_shape) = (shape(olds), shape(news));
707 let mut candidates: Vec<Vec<usize>> = Vec::with_capacity(news.len());
710 for (j, words) in new_distinct.iter().enumerate() {
711 let mut by_rarity: Vec<(usize, u32)> = words
712 .iter()
713 .filter_map(|&word| index.get(&word).map(|lines| (lines.len(), word)))
714 .collect();
715 by_rarity.sort_unstable();
716 let mut lines = Vec::new();
717 if let Some(&(least, _)) = by_rarity.first() {
718 let limit = least.max(RARE_LINE_SHARE);
719 lines = by_rarity
720 .iter()
721 .take_while(|&&(count, _)| count <= limit)
722 .flat_map(|&(_, word)| index[&word].iter().copied())
723 .collect();
724 lines.sort_unstable();
725 lines.dedup();
726 lines.retain(|&i| old_shape[i] == new_shape[j]);
734 lines.truncate(MAX_CANDIDATES);
735 }
736 candidates.push(lines);
737 }
738 let mut pairs: Vec<(usize, usize, f64)> = Vec::new();
739 for (j, lines) in candidates.iter().enumerate() {
740 for &i in lines {
741 let score = dice(&old_multiset[i], &new_multiset[j]);
742 if score >= WORD_DIFF_SIMILARITY && old_shape[i] == new_shape[j] {
743 pairs.push((i, j, score));
744 }
745 }
746 }
747 weighted_pairs(&pairs, news.len())
748}
749
750fn dice<T: Ord>(a: &[T], b: &[T]) -> f64 {
753 if a.is_empty() && b.is_empty() {
754 return 1.0;
755 }
756 if a.is_empty() || b.is_empty() {
757 return 0.0;
758 }
759 let best = 2.0 * a.len().min(b.len()) as f64 / (a.len() + b.len()) as f64;
760 if best < WORD_DIFF_SIMILARITY {
761 return 0.0;
762 }
763 let (mut i, mut j, mut common) = (0, 0, 0usize);
764 while i < a.len() && j < b.len() {
765 match a[i].cmp(&b[j]) {
766 std::cmp::Ordering::Less => i += 1,
767 std::cmp::Ordering::Greater => j += 1,
768 std::cmp::Ordering::Equal => {
769 let (word, mut more_i, mut more_j) = (&a[i], 0, 0);
770 while a.get(i + more_i) == Some(word) {
771 more_i += 1;
772 }
773 while b.get(j + more_j) == Some(word) {
774 more_j += 1;
775 }
776 common += more_i.min(more_j);
777 i += more_i;
778 j += more_j;
779 }
780 }
781 }
782 2.0 * common as f64 / (a.len() + b.len()) as f64
783}
784
785fn weighted_pairs(pairs: &[(usize, usize, f64)], new_len: usize) -> Vec<(usize, usize)> {
790 let mut order: Vec<usize> = (0..pairs.len()).collect();
791 order.sort_by_key(|&at| (pairs[at].0, pairs[at].1));
792 let mut best = vec![0.0f64; pairs.len()];
793 let mut from = vec![usize::MAX; pairs.len()];
794 let mut tree = vec![(0.0f64, usize::MAX); new_len + 1];
795 let mut at = 0;
796 while at < order.len() {
797 let same_old = order[at..]
798 .iter()
799 .position(|&later| pairs[later].0 != pairs[order[at]].0)
800 .map_or(order.len(), |offset| at + offset);
801 for &candidate in &order[at..same_old] {
802 let (mut sum, mut parent) = (0.0f64, usize::MAX);
803 let mut node = pairs[candidate].1;
804 while node > 0 {
805 if tree[node].0 > sum {
806 sum = tree[node].0;
807 parent = tree[node].1;
808 }
809 node -= node & node.wrapping_neg();
810 }
811 best[candidate] = sum + pairs[candidate].2;
812 from[candidate] = parent;
813 }
814 for &candidate in &order[at..same_old] {
815 let mut node = pairs[candidate].1 + 1;
816 while node < tree.len() {
817 if best[candidate] > tree[node].0 {
818 tree[node] = (best[candidate], candidate);
819 }
820 node += node & node.wrapping_neg();
821 }
822 }
823 at = same_old;
824 }
825 let mut tip = usize::MAX;
826 for candidate in 0..pairs.len() {
827 if tip == usize::MAX || best[candidate] > best[tip] {
828 tip = candidate;
829 }
830 }
831 let mut matched = Vec::new();
832 if tip != usize::MAX && best[tip] > 1e-9 {
833 let mut at = tip;
834 while at != usize::MAX {
835 matched.push((pairs[at].0, pairs[at].1));
836 at = from[at];
837 }
838 }
839 matched.reverse();
840 matched
841}
842
843fn intern<'a>(ids: &mut std::collections::HashMap<&'a str, u32>, word: &'a str) -> u32 {
844 let next = ids.len() as u32;
845 *ids.entry(word).or_insert(next)
846}
847
848fn body_words(line: &str) -> Vec<&str> {
851 words(&line[marker_len(line)..])
852}
853
854fn marker_shape(line: &str) -> String {
855 let marker = &line[..marker_len(line)];
856 let mut out = String::with_capacity(marker.len());
857 for c in marker.chars() {
858 if c.is_ascii_digit() {
859 if !out.ends_with('0') {
860 out.push('0');
861 }
862 } else {
863 out.push(c);
864 }
865 }
866 out
867}
868
869#[doc(hidden)]
874pub fn similarity(old: &str, new: &str) -> f64 {
875 let (a, b) = (words(old), words(new));
876 if a.is_empty() && b.is_empty() {
877 return 1.0;
878 }
879 if a.is_empty() || b.is_empty() {
880 return 0.0;
881 }
882 let best = 2.0 * a.len().min(b.len()) as f64 / (a.len() + b.len()) as f64;
883 if best < WORD_DIFF_SIMILARITY {
884 return 0.0;
885 }
886 let common = capture_diff_slices(Algorithm::Myers, &a, &b)
887 .iter()
888 .filter(|op| matches!(op.as_tag_tuple().0, DiffTag::Equal))
889 .map(|op| op.as_tag_tuple().1.len())
890 .sum::<usize>();
891 2.0 * common as f64 / (a.len() + b.len()) as f64
892}
893
894fn words(line: &str) -> Vec<&str> {
895 tokens(line)
896 .into_iter()
897 .filter(|t| t.chars().any(char::is_alphanumeric))
898 .collect()
899}
900
901fn paired(out: &mut Output, old: &str, new: &str) {
908 let (old_marker, new_marker) = (&old[..marker_len(old)], &new[..marker_len(new)]);
909 if old_marker != new_marker {
910 out.line(&change(old, new));
911 return;
912 }
913 let (old_text, new_text) = (&old[old_marker.len()..], &new[new_marker.len()..]);
914 let mut line = escape(new_marker).into_owned();
915 if similarity(old_text, new_text) < WORD_DIFF_SIMILARITY {
916 line.push_str(&change(old_text, new_text));
917 } else {
918 line.push_str(&words_diff(old_text, new_text));
919 }
920 out.line(&line);
921}
922
923fn change(old: &str, new: &str) -> String {
925 match (old.is_empty(), new.is_empty()) {
926 (true, true) => String::new(),
927 (true, false) => format!("{{++{}++}}", escape(new)),
928 (false, true) => format!("{{--{}--}}", escape(old)),
929 (false, false) => format!("{{~~{}~>{}~~}}", escape(old), escape(new)),
930 }
931}
932
933fn words_diff(old: &str, new: &str) -> String {
936 let a = tokens(old);
937 let b = tokens(new);
938 let mut segments: Vec<(bool, String, String)> = Vec::new();
940 for op in capture_diff_slices(Algorithm::Myers, &a, &b) {
941 let (tag, olds, news) = op.as_tag_tuple();
942 let old_text = a[olds].concat();
943 let new_text = b[news].concat();
944 let equal = tag == DiffTag::Equal;
945 match segments.last_mut() {
946 Some((false, o, n)) if !equal => {
947 o.push_str(&old_text);
948 n.push_str(&new_text);
949 }
950 _ => segments.push((equal, old_text, new_text)),
951 }
952 }
953 let mut merged: Vec<(bool, String, String)> = Vec::new();
955 let mut index = 0;
956 while index < segments.len() {
957 let (equal, old_text, new_text) = segments[index].clone();
958 let bridge = equal
959 && old_text.trim().is_empty()
960 && index > 0
961 && index + 1 < segments.len()
962 && matches!(merged.last(), Some((false, ..)));
963 if bridge && let Some((false, o, n)) = merged.last_mut() {
964 o.push_str(&old_text);
965 n.push_str(&new_text);
966 let (_, next_old, next_new) = &segments[index + 1];
967 o.push_str(next_old);
968 n.push_str(next_new);
969 index += 2;
970 continue;
971 }
972 merged.push((equal, old_text, new_text));
973 index += 1;
974 }
975 widen(merged, old, new)
976 .into_iter()
977 .map(|(equal, old_text, new_text)| {
978 if equal {
979 escape(&new_text).into_owned()
980 } else {
981 change(&old_text, &new_text)
982 }
983 })
984 .collect()
985}
986
987struct OpenSpan {
991 start: usize,
992 inner: Option<(usize, usize)>,
993 whole: bool,
994}
995
996struct Atom {
999 range: (usize, usize),
1000 triggers: Vec<(usize, usize)>,
1001}
1002
1003fn atoms(text: &str) -> Vec<Atom> {
1008 scan_atoms(text, 0, true)
1009 .into_iter()
1010 .chain(numbers(text))
1011 .collect()
1012}
1013
1014fn scan_atoms(text: &str, offset: usize, math: bool) -> Vec<Atom> {
1020 let shift = |(start, end): (usize, usize)| (offset + start, offset + end);
1021 let mut out = Vec::new();
1022 let mut open: Vec<OpenSpan> = Vec::new();
1025 let mut options = Options::ENABLE_STRIKETHROUGH;
1026 if math {
1027 options |= Options::ENABLE_MATH;
1028 }
1029 for (event, range) in Parser::new_ext(text, options).into_offset_iter() {
1030 match event {
1031 Event::Start(tag) => match tag {
1032 Tag::Emphasis | Tag::Strong | Tag::Strikethrough => {
1033 open.push(OpenSpan {
1034 start: range.start,
1035 inner: None,
1036 whole: false,
1037 });
1038 }
1039 Tag::Link { link_type, .. } => {
1040 open.push(OpenSpan {
1041 start: range.start,
1042 inner: None,
1043 whole: matches!(link_type, LinkType::Autolink | LinkType::Email),
1044 });
1045 }
1046 Tag::Image { .. } => {
1047 open.push(OpenSpan {
1048 start: range.start,
1049 inner: None,
1050 whole: true,
1051 });
1052 }
1053 _ => extend(&mut open, (range.start, range.end)),
1054 },
1055 Event::End(end) if is_atom_end(&end) => {
1056 if let Some(OpenSpan {
1057 start,
1058 inner,
1059 whole,
1060 }) = open.pop()
1061 {
1062 let (inner_start, inner_end) = inner.unwrap_or((range.end, range.end));
1063 let triggers = if whole {
1068 vec![shift((start, range.end))]
1069 } else {
1070 vec![shift((start, inner_start)), shift((inner_end, range.end))]
1071 };
1072 out.push(Atom {
1073 range: shift((start, range.end)),
1074 triggers,
1075 });
1076 extend(&mut open, (start, range.end));
1077 }
1078 }
1079 Event::Code(_) => {
1080 out.push(Atom {
1081 range: shift((range.start, range.end)),
1082 triggers: vec![shift((range.start, range.end))],
1083 });
1084 extend(&mut open, (range.start, range.end));
1085 }
1086 Event::DisplayMath(_) if math => {
1087 out.push(Atom {
1088 range: shift((range.start, range.end)),
1089 triggers: vec![shift((range.start, range.end))],
1090 });
1091 extend(&mut open, (range.start, range.end));
1092 }
1093 Event::InlineMath(_) if math && !opens_amount(text, range.start) => {
1094 out.push(Atom {
1095 range: shift((range.start, range.end)),
1096 triggers: vec![shift((range.start, range.end))],
1097 });
1098 extend(&mut open, (range.start, range.end));
1099 }
1100 Event::InlineMath(_) if math => {
1101 let inside = &text[range.start + 1..range.end - 1];
1102 out.extend(scan_atoms(inside, offset + range.start + 1, false));
1103 extend(&mut open, (range.start, range.end));
1104 }
1105 Event::Html(_) | Event::InlineHtml(_) => {
1108 out.push(Atom {
1109 range: shift((range.start, range.end)),
1110 triggers: vec![shift((range.start, range.end))],
1111 });
1112 extend(&mut open, (range.start, range.end));
1113 }
1114 _ => extend(&mut open, (range.start, range.end)),
1115 }
1116 }
1117 out
1118}
1119
1120fn is_atom_end(end: &TagEnd) -> bool {
1122 matches!(
1123 end,
1124 TagEnd::Emphasis | TagEnd::Strong | TagEnd::Strikethrough | TagEnd::Link | TagEnd::Image
1125 )
1126}
1127
1128fn extend(open: &mut [OpenSpan], range: (usize, usize)) {
1130 if let Some(OpenSpan { inner, .. }) = open.last_mut() {
1131 *inner = Some(match inner {
1132 Some((start, end)) => ((*start).min(range.0), (*end).max(range.1)),
1133 None => range,
1134 });
1135 }
1136}
1137
1138pub(super) fn opens_amount(text: &str, at: usize) -> bool {
1143 text.as_bytes().get(at) == Some(&b'$')
1144 && text.as_bytes().get(at + 1).is_some_and(u8::is_ascii_digit)
1145}
1146
1147fn numbers(text: &str) -> Vec<Atom> {
1150 let chars: Vec<(usize, char)> = text.char_indices().collect();
1151 let mut out = Vec::new();
1152 let mut at = 0;
1153 while at < chars.len() {
1154 let currency = matches!(chars[at].1, '$' | '€' | '£' | '¥');
1155 let first = if currency { at + 1 } else { at };
1156 if !chars.get(first).is_some_and(|(_, c)| c.is_ascii_digit()) {
1157 at += 1;
1158 continue;
1159 }
1160 let mut end = first;
1161 while end < chars.len() {
1162 let c = chars[end].1;
1163 let joins = matches!(c, ',' | '.' | '/' | ':' | '-')
1164 && chars.get(end + 1).is_some_and(|(_, n)| n.is_ascii_digit())
1165 && end > first;
1166 if c.is_ascii_digit() || joins {
1167 end += 1;
1168 } else {
1169 break;
1170 }
1171 }
1172 if chars.get(end).is_some_and(|(_, c)| *c == '%') {
1173 end += 1;
1174 }
1175 let range = (chars[at].0, chars.get(end).map_or(text.len(), |(i, _)| *i));
1176 out.push(Atom {
1177 range,
1178 triggers: vec![range],
1179 });
1180 at = end;
1181 }
1182 out
1183}
1184
1185fn touches(range: (usize, usize), span: (usize, usize)) -> bool {
1187 if range.0 == range.1 {
1188 span.0 < range.0 && range.0 < span.1
1189 } else {
1190 range.0 < span.1 && span.0 < range.1
1191 }
1192}
1193
1194fn widen(
1198 mut segments: Vec<(bool, String, String)>,
1199 old: &str,
1200 new: &str,
1201) -> Vec<(bool, String, String)> {
1202 let (old_atoms, new_atoms) = (atoms(old), atoms(new));
1203 let mut index = 0;
1204 while index < segments.len() {
1205 if segments[index].0 {
1206 index += 1;
1207 continue;
1208 }
1209 loop {
1210 let (mut o, mut n) = (0, 0);
1211 for segment in &segments[..index] {
1212 o += segment.1.len();
1213 n += segment.2.len();
1214 }
1215 let (_, old_text, new_text) = &segments[index];
1216 let old_range = (o, o + old_text.len());
1217 let new_range = (n, n + new_text.len());
1218 let cover = |range: (usize, usize), atoms: &[Atom]| {
1219 atoms
1220 .iter()
1221 .filter(|a| a.triggers.iter().any(|t| touches(range, *t)))
1222 .fold(range, |(s, e), a| (s.min(a.range.0), e.max(a.range.1)))
1223 };
1224 let (old_to, new_to) = (cover(old_range, &old_atoms), cover(new_range, &new_atoms));
1225 let left = (old_range.0 - old_to.0).max(new_range.0 - new_to.0);
1226 let right = (old_to.1 - old_range.1).max(new_to.1 - new_range.1);
1227 if left == 0 && right == 0 {
1228 break;
1229 }
1230 let before = left > 0 && index > 0;
1233 let after = right > 0 && index + 1 < segments.len();
1234 if !before && !after {
1235 break;
1236 }
1237 if before && take(&mut segments, index - 1, left, true) {
1239 index -= 1;
1240 }
1241 if after {
1242 take(&mut segments, index + 1, right, false);
1243 }
1244 }
1245 index += 1;
1246 }
1247 segments
1248}
1249
1250fn take(
1255 segments: &mut Vec<(bool, String, String)>,
1256 at: usize,
1257 length: usize,
1258 into_next: bool,
1259) -> bool {
1260 let (equal, old_text, new_text) = segments[at].clone();
1261 let whole = !equal || length >= old_text.len();
1262 let (moved_old, moved_new, kept) = if whole {
1263 (old_text, new_text, None)
1264 } else if into_next {
1265 let cut = old_text.floor_char_boundary(old_text.len() - length);
1266 (
1267 old_text[cut..].to_string(),
1268 old_text[cut..].to_string(),
1269 Some(old_text[..cut].to_string()),
1270 )
1271 } else {
1272 let cut = old_text.ceil_char_boundary(length);
1273 (
1274 old_text[..cut].to_string(),
1275 old_text[..cut].to_string(),
1276 Some(old_text[cut..].to_string()),
1277 )
1278 };
1279 let change = if into_next { at + 1 } else { at - 1 };
1280 {
1281 let (_, o, n) = &mut segments[change];
1282 if into_next {
1283 o.insert_str(0, &moved_old);
1284 n.insert_str(0, &moved_new);
1285 } else {
1286 o.push_str(&moved_old);
1287 n.push_str(&moved_new);
1288 }
1289 }
1290 match kept {
1291 Some(kept) => {
1292 segments[at] = (true, kept.clone(), kept);
1293 false
1294 }
1295 None => {
1296 segments.remove(at);
1297 true
1298 }
1299 }
1300}
1301
1302fn group(out: &mut Output, side: Side, lines: &[&str]) {
1314 if lines.is_empty() {
1315 return;
1316 }
1317 let (open, close) = side.delimiters();
1318 let mut rest = lines;
1319 if out.started && open_paragraph(&out.last) && marker_len(&out.last) == 0 && continues(rest[0])
1323 {
1324 let length = rest.iter().take_while(|l| continues(l)).count();
1325 let joined: Vec<Cow<'_, str>> = rest[..length].iter().map(|l| escape(l)).collect();
1326 out.append(&format!("{open}\n{}{close}", joined.join("\n")));
1327 rest = &rest[length..];
1328 }
1329 if rest.is_empty() {
1330 return;
1331 }
1332 if side == Side::Insert && rest.iter().all(|l| table_row(l)) {
1335 for line in rest {
1336 out.line(&table_row_change(line, open, close));
1337 }
1338 return;
1339 }
1340 let run = rest;
1341 let doc_start = !out.started;
1342 let prev_blank = out.started && out.last.trim().is_empty();
1348 let mut prefix = String::new();
1349 if doc_start || prev_blank {
1350 prefix.push_str(open);
1351 } else if let Some(pending) = out.carry.take() {
1352 prefix.push_str(pending);
1353 prefix.push_str(open);
1354 } else {
1355 out.append(open);
1356 }
1357 let carry_closer = doc_start || prev_blank;
1365 let last = run.len() - 1;
1366 for (at, line) in run.iter().enumerate() {
1367 let mut text = if at == 0 && !prefix.is_empty() {
1368 format!("{prefix}{}", escape(line))
1369 } else {
1370 escape(line).into_owned()
1371 };
1372 if at == last && !carry_closer {
1373 text.push_str(close);
1374 }
1375 out.line(&text);
1376 }
1377 if carry_closer {
1378 out.carry = Some(close);
1379 }
1380}
1381
1382#[cfg(test)]
1383#[cfg_attr(all(coverage_nightly, test), coverage(off))]
1384mod tests {
1385 use super::*;
1386
1387 #[test]
1388 fn markers_are_found() {
1389 for (line, marker) in [
1390 ("# Title", "# "),
1391 ("###### Six", "###### "),
1392 ("####### Seven", ""),
1393 ("- item", "- "),
1394 (" * nested", " * "),
1395 ("12. twelfth", "12. "),
1396 ("3) third", "3) "),
1397 ("- [x] done", "- [x] "),
1398 ("> quoted", "> "),
1399 ("> > - deep", "> > - "),
1400 ("plain", ""),
1401 ("-5 degrees", ""),
1402 ("#hashtag", ""),
1403 ("#", "#"),
1404 ("[^note]: text", "[^note]: "),
1405 ("[^a b]: text", ""),
1406 ] {
1407 assert_eq!(&line[..marker_len(line)], marker, "{line}");
1408 }
1409 }
1410
1411 #[test]
1412 fn a_rewritten_phrase_is_one_change() {
1413 assert_eq!(
1414 words_diff("the quick brown fox", "the slow red fox"),
1415 "the {~~quick brown~>slow red~~} fox"
1416 );
1417 assert_eq!(words_diff("a b", "a b c"), "a b{++ c++}");
1418 assert_eq!(words_diff("a b c", "a c"), "a {--b --}c");
1419 }
1420
1421 #[test]
1422 fn a_decomposed_accent_is_part_of_the_word_replaced() {
1423 let (old, new) = ("Le cafe\u{301} est chaud.\n", "Le the\u{301} est chaud.\n");
1426 assert_eq!(
1427 diff_markdown(old, new),
1428 "Le {~~cafe\u{301}~>the\u{301}~~} est chaud.\n"
1429 );
1430 assert_eq!(
1432 diff_markdown("Le caf\u{e9} est chaud.\n", "Le th\u{e9} est chaud.\n"),
1433 "Le {~~caf\u{e9}~>th\u{e9}~~} est chaud.\n"
1434 );
1435 assert_eq!(
1437 words_diff("un cafe est", "un cafe\u{301} est"),
1438 "un {~~cafe~>cafe\u{301}~~} est"
1439 );
1440 }
1441
1442 #[test]
1443 fn a_change_inside_a_number_is_the_whole_number() {
1444 for (old, new, expected) in [
1445 (
1446 "exceeds **$250,000** now",
1447 "exceeds **$150,000** now",
1448 "exceeds **{~~$250,000~>$150,000~~}** now",
1449 ),
1450 (
1451 "on 04/20/26.",
1452 "on 10/30/26.",
1453 "on {~~04/20/26~>10/30/26~~}.",
1454 ),
1455 ("grew 3.5% a", "grew 4.25% a", "grew {~~3.5%~>4.25%~~} a"),
1456 (
1457 "cap of $5,000,000 total",
1458 "cap of $7,500,000 total",
1459 "cap of {~~$5,000,000~>$7,500,000~~} total",
1460 ),
1461 ("5 days", "5 business days", "5 {++business ++}days"),
1462 ("5 days", "5, days", "5{++,++} days"),
1464 ] {
1465 assert_eq!(words_diff(old, new), expected, "{old}");
1466 }
1467 }
1468
1469 #[test]
1470 fn a_formatting_change_is_the_whole_span() {
1471 for (old, new, expected) in [
1472 (
1473 "harmless *Buyer*, its",
1474 "harmless Buyer, its",
1475 "harmless {~~*Buyer*~>Buyer~~}, its",
1476 ),
1477 (
1478 "the \"Basket\")",
1479 "the \"**Basket**\")",
1480 "the \"{~~Basket~>**Basket**~~}\")",
1481 ),
1482 (
1484 "*provided, however*, that",
1485 "*provided, further*, that",
1486 "*provided, {~~however~>further~~}*, that",
1487 ),
1488 ] {
1489 assert_eq!(words_diff(old, new), expected, "{old}");
1490 }
1491 }
1492
1493 #[test]
1494 fn a_changed_link_target_is_the_whole_link() {
1495 assert_eq!(
1496 words_diff(
1497 "in [Section 7.4](#section-7-4).",
1498 "in [Section 7.5](#section-7-5)."
1499 ),
1500 "in {~~[Section 7.4](#section-7-4)~>[Section 7.5](#section-7-5)~~}."
1501 );
1502 assert_eq!(
1504 words_diff("see [the old terms](x)", "see [the new terms](x)"),
1505 "see [the {~~old~>new~~} terms](x)"
1506 );
1507 }
1508
1509 #[test]
1510 fn delimiters_in_the_text_are_escaped() {
1511 assert_eq!(escape("a {++ b ++} ~> c"), "a \\{++ b ++\\} ~\\> c");
1512 assert_eq!(
1513 diff_markdown("x {++y++}\n", "x {++z++}\n"),
1514 "x \\{++{~~y~>z~~}++\\}\n"
1515 );
1516 }
1517
1518 #[test]
1519 fn identical_documents_come_back_unchanged() {
1520 let text = "# Title\n\n- a\n- b\n\nText.\n";
1521 assert_eq!(diff_markdown(text, text), text);
1522 assert_eq!(diff_markdown("", ""), "");
1523 }
1524
1525 #[test]
1526 fn blocks_added_or_removed_keep_their_markers_outside() {
1527 assert_eq!(
1528 diff_markdown("- a\n- c\n", "- a\n- b\n- c\n"),
1529 "- a{++\n- b++}\n- c\n"
1530 );
1531 assert_eq!(
1532 diff_markdown("A\n\nOld paragraph.\n\nC\n", "A\n\nC\n"),
1533 "A\n\n{--Old paragraph.\n\n--}C\n"
1534 );
1535 assert_eq!(
1536 diff_markdown("# One\n", "# One\n\n## Two\n"),
1537 "# One{++\n\n## Two++}\n"
1538 );
1539 }
1540
1541 #[test]
1542 fn a_line_added_inside_a_paragraph_takes_its_line_break() {
1543 assert_eq!(
1544 diff_markdown("first\nthird\n", "first\nsecond\nthird\n"),
1545 "first{++\nsecond++}\nthird\n"
1546 );
1547 assert_eq!(diff_markdown("x\ny\n", "y\n"), "{--x\n--}y\n");
1548 }
1549
1550 #[test]
1551 fn a_changed_marker_replaces_the_block() {
1552 assert_eq!(
1556 diff_markdown("# Title\n", "## Title\n"),
1557 "{~~# Title~>## Title~~}\n"
1558 );
1559 round_trip("# Title\n", "## Title\n");
1560 assert_eq!(
1562 diff_markdown("- [ ] write\n", "- [x] write\n"),
1563 "{~~- [ ] write~>- [x] write~~}\n"
1564 );
1565 round_trip("- [ ] write\n", "- [x] write\n");
1566 assert_eq!(
1569 diff_markdown("- hello world\n", "hello world\n"),
1570 "{~~- hello world~>hello world~~}\n"
1571 );
1572 round_trip("- hello world\n", "hello world\n");
1573 }
1574
1575 #[test]
1576 fn a_table_row_changes_cell_by_cell() {
1577 assert_eq!(
1578 diff_markdown(
1579 "| a |\n|---|\n| 1 |\n",
1580 "| a |\n|---|\n| 1 |\n| 2 \\| 3 |\n"
1581 ),
1582 "| a |\n|---|\n| 1 |\n| {++2 \\| 3++} |\n"
1583 );
1584 assert_eq!(table_row_change("|---|:-:|", "{++", "++}"), "|---|:-:|");
1585 }
1586
1587 #[test]
1588 fn unrelated_lines_are_replaced_whole() {
1589 assert_eq!(
1590 diff_markdown("Lorem ipsum dolor.\n", "Completely other words here.\n"),
1591 "{~~Lorem ipsum dolor.~>Completely other words here.~~}\n"
1592 );
1593 }
1594
1595 fn round_trip(old: &str, new: &str) {
1596 let diff = diff_markdown(old, new);
1597 assert_eq!(
1598 crate::markdown::resolve_critic(&diff, crate::markdown::TrackChanges::Accept),
1599 new,
1600 "accept {diff:?}"
1601 );
1602 assert_eq!(
1603 crate::markdown::resolve_critic(&diff, crate::markdown::TrackChanges::Reject),
1604 old,
1605 "reject {diff:?}"
1606 );
1607 }
1608
1609 #[test]
1610 fn a_changed_code_span_is_wrapped_whole() {
1611 let (old, new) = ("Call `foo()` now.\n", "Call `bar()` now.\n");
1612 assert_eq!(
1613 diff_markdown(old, new),
1614 "Call {~~`foo()`~>`bar()`~~} now.\n"
1615 );
1616 let (old, new) = ("use `{++}` here.\n", "use `{--}` here.\n");
1619 assert_eq!(diff_markdown(old, new), "use {~~`{++}`~>`{--}`~~} here.\n");
1620 round_trip(old, new);
1621 round_trip("Call `foo()` now.\n", "Call `bar()` now.\n");
1622 }
1623
1624 #[test]
1625 fn a_changed_image_is_wrapped_whole() {
1626 let target = (
1627 "See  now.\n",
1628 "See  now.\n",
1629 "See {~~~>~~} now.\n",
1630 );
1631 let alt = (
1632 "See  now.\n",
1633 "See  now.\n",
1634 "See {~~~>~~} now.\n",
1635 );
1636 for (old, new, expected) in [target, alt] {
1637 assert_eq!(diff_markdown(old, new), expected, "{old}");
1638 round_trip(old, new);
1639 }
1640 }
1641
1642 #[test]
1643 fn a_changed_equation_is_wrapped_whole() {
1644 for (old, new, expected) in [
1645 (
1646 "Area is $a+b$ now.\n",
1647 "Area is $a+c$ now.\n",
1648 "Area is {~~$a+b$~>$a+c$~~} now.\n",
1649 ),
1650 (
1651 "Area is $$a+b$$ now.\n",
1652 "Area is $$a+c$$ now.\n",
1653 "Area is {~~$$a+b$$~>$$a+c$$~~} now.\n",
1654 ),
1655 ] {
1656 assert_eq!(diff_markdown(old, new), expected, "{old}");
1657 round_trip(old, new);
1658 }
1659 }
1660
1661 #[test]
1662 fn escape_counts_backslashes_and_skips_code() {
1663 assert_eq!(escape(r"\{++"), r"\{++");
1666 assert_eq!(escape(r"\\{++"), r"\\\{++");
1667 assert_eq!(escape(r"\~>"), r"\~>");
1668 assert_eq!(escape("a {++ b ++} ~> c"), "a \\{++ b ++\\} ~\\> c");
1669 assert_eq!(escape("a `{++}` b"), "a `{++}` b");
1671 assert_eq!(escape("a `{++}` {++} b"), "a `{++}` \\{++\\} b");
1672 let text = "call `{++}` now\n";
1673 assert_eq!(diff_markdown(text, text), text);
1674 }
1675
1676 #[test]
1677 fn twenty_one_changed_lines_and_an_insertion_pair_by_content() {
1678 let old: String = (0..21)
1681 .map(|i| format!("item {i:02} stays unique here\n"))
1682 .collect();
1683 let new: String = std::iter::once("item inserted at the top\n".to_string())
1684 .chain((0..21).map(|i| format!("item {i:02} stays unique there\n")))
1685 .collect();
1686 let diff = diff_markdown(&old, &new);
1687 assert!(
1690 diff.starts_with(
1691 "{++item inserted at the top\n++}item 00 stays unique {~~here~>there~~}\n"
1692 ),
1693 "{diff}"
1694 );
1695 assert!(
1696 diff.contains("item 20 stays unique {~~here~>there~~}"),
1697 "{diff}"
1698 );
1699 assert!(!diff.contains("inserted at the top~>"), "{diff}");
1700 round_trip(&old, &new);
1701 }
1702
1703 #[test]
1704 fn a_large_changed_hunk_still_pairs_similar_lines() {
1705 let n = 1500;
1706 let old: String = (0..n)
1707 .map(|i| format!("row {i} alpha beta gamma\n"))
1708 .collect();
1709 let new: String = std::iter::once("row inserted zeta eta theta\n".to_string())
1710 .chain((0..n).map(|i| format!("row {i} alpha beta delta\n")))
1711 .collect();
1712 let diff = diff_markdown(&old, &new);
1713 assert!(
1714 diff.contains("{++row inserted zeta eta theta\n++}row 0 alpha beta {~~gamma~>delta~~}"),
1715 "{}",
1716 &diff[..diff.len().min(400)]
1717 );
1718 assert!(diff.contains("row 1499 alpha beta {~~gamma~>delta~~}"));
1719 }
1720
1721 #[test]
1722 fn list_numbers_do_not_skew_pairing() {
1723 let old = "1. alpha\n2. beta\n3. gamma\n";
1724 let new = "1. inserted\n2. alpha\n3. beta\n4. gamma\n";
1725 assert_eq!(
1726 diff_markdown(old, new),
1727 "{++1. inserted\n++}{~~1. alpha~>2. alpha~~}\n{~~2. beta~>3. beta~~}\n{~~3. gamma~>4. gamma~~}\n"
1728 );
1729 round_trip(old, new);
1730 }
1731
1732 #[test]
1733 fn a_list_item_turned_into_a_paragraph_is_not_glued() {
1734 let old = "- hello world\n";
1735 let new = "hello world\n";
1736 assert_eq!(
1737 diff_markdown(old, new),
1738 "{~~- hello world~>hello world~~}\n"
1739 );
1740 round_trip(old, new);
1741 }
1742
1743 fn wrap_words(text: &str, width: usize) -> String {
1746 let mut lines = Vec::new();
1747 let mut line = String::new();
1748 for word in text.split_whitespace() {
1749 if !line.is_empty() && line.len() + 1 + word.len() > width {
1750 lines.push(std::mem::take(&mut line));
1751 }
1752 if !line.is_empty() {
1753 line.push(' ');
1754 }
1755 line.push_str(word);
1756 }
1757 if !line.is_empty() {
1758 lines.push(line);
1759 }
1760 lines.push(String::new());
1761 lines.join("\n")
1762 }
1763
1764 #[test]
1765 fn one_word_added_to_a_hard_wrapped_paragraph_is_one_change() {
1766 let base = "The quick brown fox jumps over the lazy dog and then runs around the old barn before sunset while the farmer watches quietly from the porch.";
1767 let added = base.replacen("lazy", "very lazy", 1);
1768 for width in [20, 24, 28, 32, 40, 48] {
1769 let old = wrap_words(base, width);
1770 let new = wrap_words(&added, width);
1771 let diff = diff_markdown(&old, &new);
1772 round_trip(&old, &new);
1773 assert!(
1774 diff.contains("{++very") || diff.contains("{++ very"),
1775 "width {width}: the added word is not one insertion\n{diff}"
1776 );
1777 for word in ["runs", "barn", "while", "watches"] {
1779 assert!(
1780 !diff.contains(&format!("{{--{word}"))
1781 && !diff.contains(&format!("{{++{word}")),
1782 "width {width}: {word} was rewritten\n{diff}"
1783 );
1784 }
1785 }
1786 }
1787
1788 #[test]
1789 fn a_changed_list_number_is_marked() {
1790 assert_eq!(diff_markdown("10. a\n", "9. a\n"), "{~~10. a~>9. a~~}\n");
1793 round_trip("10. a\n", "9. a\n");
1794 }
1795
1796 #[test]
1797 fn marker_shapes_change_whole() {
1798 for (old, new) in [
1799 ("# Title\n", "## Title\n"),
1800 ("* a\n", "+ a\n"),
1801 ("- a\n", " - a\n"),
1802 ] {
1803 round_trip(old, new);
1804 }
1805 }
1806
1807 #[test]
1808 fn blank_lines_added_and_removed_are_marked() {
1809 assert_eq!(diff_markdown("a\nb\n", "a\n\nb\n"), "a{++\n++}\nb\n");
1810 assert_eq!(diff_markdown("a\n\nb\n", "a\nb\n"), "a{--\n--}\nb\n");
1811 assert_eq!(diff_markdown("x\n\n\ny\n", "x\n\ny\n"), "x\n\n{--\n--}y\n");
1813 round_trip("a\nb\n", "a\n\nb\n");
1814 round_trip("a\n\nb\n", "a\nb\n");
1815 round_trip("x\n\n\ny\n", "x\n\ny\n");
1816 }
1817
1818 #[test]
1819 fn the_trailing_newline_is_part_of_the_change() {
1820 assert_eq!(diff_markdown("a", "a\n"), "a{++\n++}");
1821 assert_eq!(diff_markdown("a\n", "a"), "a{--\n--}");
1822 round_trip("a", "a\n");
1823 round_trip("a\n", "a");
1824 }
1825
1826 #[test]
1831 fn a_substitutions_trailing_break_stays_on_the_side_that_has_it() {
1832 assert_eq!(diff_markdown("a\nb\n", "a\nc"), "a\n{~~b\n~>c~~}");
1833 round_trip("a\nb\n", "a\nc");
1834 assert_eq!(diff_markdown("a\nb", "a\nc\n"), "a\n{~~b~>c\n~~}");
1836 round_trip("a\nb", "a\nc\n");
1837 assert_eq!(diff_markdown("a\nb\nc", "a\nb\nd"), "a\nb\n{~~c~>d~~}");
1840 round_trip("a\nb\nc", "a\nb\nd");
1841 }
1842
1843 #[test]
1844 fn a_deleted_table_row_takes_its_line_with_it() {
1845 assert_eq!(
1846 diff_markdown("| a |\n|---|\n| 1 |\n", "| a |\n|---|\n"),
1847 "| a |\n|---|{--\n| 1 |--}\n"
1848 );
1849 round_trip("| a |\n|---|\n| 1 |\n", "| a |\n|---|\n");
1850 assert_eq!(
1852 diff_markdown("| a |\n|---|\n| 1 |\n| 2 |\n", "| a |\n|---|\n| 2 |\n"),
1853 "| a |\n|---|{--\n| 1 |--}\n| 2 |\n"
1854 );
1855 round_trip("| a |\n|---|\n| 1 |\n| 2 |\n", "| a |\n|---|\n| 2 |\n");
1856 }
1857
1858 #[test]
1859 fn a_code_span_across_a_line_break_is_one_atom() {
1860 let (old, new) = ("x `a\nb` y\n", "x `a\nc` y\n");
1861 assert_eq!(diff_markdown(old, new), "x {~~`a\nb`~>`a\nc`~~} y\n");
1862 round_trip(old, new);
1863 }
1864
1865 #[test]
1866 fn a_multiline_display_equation_is_wrapped_whole() {
1867 let (old, new) = (
1868 "Area is\n$$\na+b\n$$\nnow.\n",
1869 "Area is\n$$\na+c\n$$\nnow.\n",
1870 );
1871 let diff = diff_markdown(old, new);
1872 assert!(diff.contains("{~~$$\na+b\n$$~>$$\na+c\n$$~~}"), "{diff}");
1873 round_trip(old, new);
1874 }
1875
1876 #[test]
1877 fn identical_documents_with_verbatim_delimiters_come_back_unchanged() {
1878 for text in [
1879 "<!-- {++x++} -->\ntext\n",
1880 "see <https://a.b/{++x> end\n",
1881 "see [t](https://a.b/{++x) more\n",
1882 "x `a\ncode {++i++} rest` y\n",
1883 ] {
1884 assert_eq!(diff_markdown(text, text), text, "{text:?}");
1885 }
1886 }
1887
1888 #[test]
1889 fn verbatim_constructs_change_whole() {
1890 round_trip("see <https://a.b/one> end\n", "see <https://a.b/two> end\n");
1893 round_trip(
1894 "see [t](https://a.b/one) more\n",
1895 "see [t](https://a.b/two) more\n",
1896 );
1897 round_trip("<!-- note one -->\ntext\n", "<!-- note two -->\ntext\n");
1898 }
1899
1900 #[test]
1901 fn escape_skips_the_readers_verbatim_ranges() {
1902 assert_eq!(escape("<!-- {++x++} -->"), "<!-- {++x++} -->");
1903 assert_eq!(escape("see <https://a.b/{++x>"), "see <https://a.b/{++x>");
1904 assert_eq!(
1905 escape("see [t](https://a.b/{++x)"),
1906 "see [t](https://a.b/{++x)"
1907 );
1908 assert_eq!(
1910 escape("x `a\ncode {++i++} rest` y"),
1911 "x `a\ncode {++i++} rest` y"
1912 );
1913 assert_eq!(escape("a {++ b ++} ~> c"), "a \\{++ b ++\\} ~\\> c");
1915 }
1916
1917 #[test]
1918 fn accept_and_reject_rebuild_the_documents_exactly() {
1919 let cases: &[(&str, &str)] = &[
1922 ("10. a\n", "9. a\n"),
1924 ("* a\n", "+ a\n"),
1925 ("# t\n", "## t\n"),
1926 ("- a\n", " - a\n"),
1927 ("a\nb\n", "a\n\nb\n"),
1929 ("a\n\nb\n", "a\nb\n"),
1930 ("x\n\n\ny\n", "x\n\ny\n"),
1931 ("a\n\nb\nc\n", "a\nb\n\nc\n"),
1932 ("a", "a\n"),
1934 ("a\n", "a"),
1935 ("", "a\n"),
1936 ("a\n", ""),
1937 ("| a |\n|---|\n| 1 |\n", "| a |\n|---|\n"),
1939 ("| a |\n|---|\n| 1 |\n| 2 |\n", "| a |\n|---|\n| 2 |\n"),
1940 ("- hello world\n", "hello world\n"),
1942 ("hello world\n", "- hello world\n"),
1943 ("a b c\n", "a b c\n- d\n"),
1944 ("x `a\nb` y\n", "x `a\nc` y\n"),
1946 ("x `a\nb` y\n", "x `a\nb` z\n"),
1947 ("<!-- note one -->\ntext\n", "<!-- note two -->\ntext\n"),
1949 ("see <https://a.b/one> end\n", "see <https://a.b/two> end\n"),
1950 (
1951 "see [t](https://a.b/one) more\n",
1952 "see [t](https://a.b/two) more\n",
1953 ),
1954 ("Area is $a+b$ now.\n", "Area is $a+c$ now.\n"),
1956 ("Area is $$a+b$$ now.\n", "Area is $$a+c$$ now.\n"),
1957 (
1958 "Area is\n$$\na+b\n$$\nnow.\n",
1959 "Area is\n$$\na+c\n$$\nnow.\n",
1960 ),
1961 ];
1962 for (old, new) in cases {
1963 round_trip(old, new);
1964 }
1965 }
1966
1967 #[test]
1968 fn escape_is_linear_on_backtick_runs() {
1969 let mut text = String::with_capacity(400_000);
1971 for _ in 0..100_000 {
1972 text.push_str("`x");
1973 }
1974 text.push_str("{++}");
1975 let escaped = escape(&text);
1976 assert_eq!(escaped.len(), text.len() + 2);
1979 }
1980
1981 #[test]
1982 fn a_large_rewrap_stays_fast() {
1983 let words: Vec<String> = (0..20_000).map(|i| format!("w{i}x")).collect();
1986 let text = words.join(" ");
1987 let wrap = |width: usize| {
1988 let mut lines = Vec::new();
1989 let mut line = String::new();
1990 for word in text.split(' ') {
1991 if !line.is_empty() && line.len() + 1 + word.len() > width {
1992 lines.push(std::mem::take(&mut line));
1993 }
1994 if !line.is_empty() {
1995 line.push(' ');
1996 }
1997 line.push_str(word);
1998 }
1999 if !line.is_empty() {
2000 lines.push(line);
2001 }
2002 lines.push(String::new());
2003 lines.join("\n")
2004 };
2005 let (old, new) = (wrap(40), wrap(45));
2006 round_trip(&old, &new);
2007 }
2008
2009 #[test]
2010 fn long_lines_pair_in_linear_time() {
2011 let lines = |tail: &str| -> String {
2014 (0..200)
2015 .map(|i| {
2016 let mut line = format!("row{i}");
2017 for w in 0..250 {
2018 line.push_str(&format!(" w{w}"));
2019 }
2020 format!("{line} {tail}\n")
2021 })
2022 .collect()
2023 };
2024 let (old, new) = (lines("tail"), lines("tailx"));
2025 let diff = diff_markdown(&old, &new);
2026 assert!(diff.contains("row0 w0"), "{}", &diff[..diff.len().min(200)]);
2027 round_trip(&old, &new);
2028 }
2029
2030 #[test]
2037 fn the_only_pairable_candidate_survives_the_candidate_bound() {
2038 let mut old = String::new();
2039 for _ in 0..MAX_CANDIDATES + 7 {
2040 old.push_str("- alpha beta gamma\n");
2041 }
2042 old.push_str("alpha beta gamma\n");
2043 let new = "alpha beta gamma zeta\n";
2044 let diff = diff_markdown(&old, new);
2045 assert!(diff.contains("alpha beta gamma{++ zeta++}"), "{diff}");
2048 assert!(
2049 !diff.contains("{--\nalpha beta gamma--}"),
2050 "the plain line was deleted whole\n{diff}"
2051 );
2052 round_trip(&old, new);
2053 }
2054
2055 #[test]
2059 fn each_of_two_identical_old_lines_still_pairs_in_order() {
2060 let old = "- alpha beta gamma delta\n- alpha beta gamma delta\n";
2061 let new = "- alpha beta gamma delta one\n- alpha beta gamma delta two\n";
2062 let diff = diff_markdown(old, new);
2063 assert!(diff.contains("alpha beta gamma delta{++ one++}"), "{diff}");
2064 assert!(diff.contains("alpha beta gamma delta{++ two++}"), "{diff}");
2065 round_trip(old, new);
2066 }
2067
2068 #[test]
2069 fn just_over_the_old_bound_pairs_by_content() {
2070 let old: String = (0..2001)
2074 .map(|i| format!("item {i:04} alpha beta gamma\n"))
2075 .collect();
2076 let new: String = std::iter::once("inserted first\n".to_string())
2077 .chain((0..2000).map(|i| format!("item {i:04} alpha beta delta\n")))
2078 .collect();
2079 let diff = diff_markdown(&old, &new);
2080 assert!(
2081 diff.contains("item 0000 alpha beta {~~gamma~>delta~~}"),
2082 "{diff}"
2083 );
2084 assert!(
2085 !diff.contains("item {~~0001~>0000~~}"),
2086 "a line was rewritten into its neighbour\n{diff}"
2087 );
2088 round_trip(&old, &new);
2089 }
2090}
2091
2092#[cfg(test)]
2093#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2094mod branch_tests {
2095 use super::*;
2096
2097 #[test]
2098 fn markers_end_where_the_block_marker_ends() {
2099 assert_eq!(marker_len(">quote"), 1);
2100 assert_eq!(marker_len("> > x"), 4);
2101 assert_eq!(marker_len("[^n]: note"), 6);
2102 assert_eq!(marker_len("[^a b]: note"), 0);
2103 assert_eq!(marker_len("1234567890. x"), 0);
2104 assert_eq!(marker_len("12) x"), 4);
2105 assert_eq!(marker_len("12x"), 0);
2106 assert_eq!(marker_len("###"), 3);
2107 assert_eq!(marker_shape("12. 3"), "0. ");
2108 assert_eq!(marker_shape("1.2. x"), "");
2109 }
2110
2111 #[test]
2112 fn similarity_and_dice_score_shared_words() {
2113 assert_eq!(dice::<u32>(&[], &[]), 1.0);
2114 assert_eq!(dice(&[1], &[]), 0.0);
2115 assert_eq!(dice(&[1], &[1, 2, 3, 4, 5, 6, 7, 8]), 0.0);
2116 assert_eq!(dice(&[1, 1, 2], &[1, 2, 2]), 2.0 * 2.0 / 6.0);
2117 assert_eq!(dice(&[1, 2, 3], &[1, 2, 3]), 1.0);
2118 assert_eq!(similarity("", "... --"), 1.0);
2119 assert_eq!(similarity("one", ""), 0.0);
2120 assert_eq!(similarity("one", "one two three four five six seven"), 0.0);
2121 assert_eq!(similarity("the cat sat", "the cat sat"), 1.0);
2122 assert!(weighted_pairs(&[], 3).is_empty());
2123 assert_eq!(
2124 weighted_pairs(&[(0, 1, 0.9), (1, 0, 0.8), (1, 2, 0.7), (0, 0, 0.6)], 3),
2125 [(0, 1), (1, 2)]
2126 );
2127 assert!(weighted_pairs(&[(0, 0, 0.0)], 1).is_empty());
2128 }
2129
2130 #[test]
2131 fn opaque_spans_across_lines_join_into_one_unit() {
2132 let units = opaque_units("a `code\nspan` b\nnext\n<div\nx>\n");
2133 assert_eq!(units, ["a `code\nspan` b", "next", "<div\nx>\n"]);
2135 assert_eq!(opaque_units("one\ntwo"), ["one", "two"]);
2136 }
2137
2138 #[test]
2139 fn diffs_mark_words_math_and_reflowed_paragraphs() {
2140 let out = diff_markdown(
2141 "Pay $x+1$ to the vendor now.\n\n$$\na=1\n$$\n\nOne two three four\nfive six.\n",
2142 "Pay $x+2$ to the vendor now.\n\n$$\na=2\n$$\n\nOne two three\nfour five six seven.\n",
2143 );
2144 assert!(
2145 out.contains("{--$x+1$--}") || out.contains("{~~$x+1$~>$x+2$~~}"),
2146 "{out}"
2147 );
2148 assert!(out.contains("seven"), "{out}");
2149 let same = diff_markdown("A.\n", "A.\n");
2150 assert_eq!(same, "A.\n");
2151 }
2152}