use std::borrow::Cow;
use pulldown_cmark::{Event, LinkType, Options, Parser, Tag, TagEnd};
use similar::{Algorithm, DiffTag, capture_diff_slices};
use crate::util::word_tokens as tokens;
const WORD_DIFF_SIMILARITY: f64 = 0.3;
const RARE_LINE_SHARE: usize = 8;
const MAX_CANDIDATES: usize = 64;
const REFLOW_MAX_BYTES: usize = 400_000;
pub fn diff_markdown(old: &str, new: &str) -> String {
let old = old.replace("\r\n", "\n");
let new = new.replace("\r\n", "\n");
let old_lines = lines(&old);
let new_lines = lines(&new);
let mut out = Output::default();
let ops = capture_diff_slices(Algorithm::Patience, &old_lines, &new_lines);
for op in &ops {
let (tag, olds, news) = op.as_tag_tuple();
match tag {
DiffTag::Equal => {
for line in &new_lines[news] {
out.line(&escape(line));
}
}
DiffTag::Delete | DiffTag::Insert | DiffTag::Replace => {
hunk(&mut out, &old_lines[olds], &new_lines[news]);
}
}
}
out.finish(old.ends_with('\n'), new.ends_with('\n'))
}
fn lines(text: &str) -> Vec<&str> {
let text = text.strip_suffix('\n').unwrap_or(text);
if text.is_empty() {
return Vec::new();
}
opaque_units(text)
}
fn opaque_units(text: &str) -> Vec<&str> {
let mut starts: Vec<usize> = vec![0];
starts.extend(
text.match_indices('\n')
.map(|(at, _)| at + 1)
.filter(|&at| at < text.len()),
);
let line_of = |at: usize| starts.partition_point(|&start| start <= at) - 1;
let mut spans: Vec<(usize, usize)> = Vec::new();
let options = Options::ENABLE_STRIKETHROUGH | Options::ENABLE_MATH;
for (event, range) in Parser::new_ext(text, options).into_offset_iter() {
let opaque = match event {
Event::Code(_) => true,
Event::InlineMath(_) | Event::DisplayMath(_) => !opens_amount(text, range.start),
Event::Html(_) | Event::InlineHtml(_) => true,
Event::Start(Tag::Image { .. }) => true,
Event::Start(Tag::Link { link_type, .. }) => {
matches!(link_type, LinkType::Autolink | LinkType::Email)
}
_ => false,
};
if opaque && range.end > range.start && text[range.clone()].contains('\n') {
spans.push((line_of(range.start), line_of(range.end - 1)));
}
}
spans.sort_unstable();
let mut merged: Vec<(usize, usize)> = Vec::new();
for (first, last) in spans {
match merged.last_mut() {
Some((_, end)) if first <= *end + 1 => *end = (*end).max(last),
_ => merged.push((first, last)),
}
}
let end_of = |line: usize| match starts.get(line + 1) {
Some(&next_start) => next_start - 1,
None => text.len(),
};
let mut units: Vec<&str> = Vec::new();
let mut line = 0;
for (first, last) in merged {
while line < first {
units.push(&text[starts[line]..end_of(line)]);
line += 1;
}
units.push(&text[starts[first]..end_of(last)]);
line = last + 1;
}
while line < starts.len() {
units.push(&text[starts[line]..end_of(line)]);
line += 1;
}
units
}
#[doc(hidden)]
pub fn marker_len(line: &str) -> usize {
let bytes = line.as_bytes();
let mut at = bytes
.iter()
.take_while(|b| **b == b' ' || **b == b'\t')
.count();
while bytes.get(at) == Some(&b'>') {
at += 1;
if bytes.get(at) == Some(&b' ') {
at += 1;
}
}
let rest = &line[at..];
if rest.starts_with("[^")
&& let Some(end) = rest.find("]: ")
&& !rest[2..end].contains([' ', ']'])
{
return at + end + 3;
}
let hashes = rest.bytes().take_while(|b| *b == b'#').count();
if (1..=6).contains(&hashes) && matches!(rest.as_bytes().get(hashes), None | Some(b' ')) {
return at + hashes + usize::from(rest.len() > hashes);
}
let list = match rest.as_bytes().first() {
Some(b'-' | b'*' | b'+') => 1,
Some(b'0'..=b'9') => {
let digits = rest.bytes().take_while(u8::is_ascii_digit).count();
if digits <= 9 && matches!(rest.as_bytes().get(digits), Some(b'.' | b')')) {
digits + 1
} else {
0
}
}
_ => 0,
};
if list > 0 && matches!(rest.as_bytes().get(list), Some(b' ' | b'\t')) {
at += list + 1;
let rest = &line[at..];
for task in ["[ ] ", "[x] ", "[X] "] {
if rest.starts_with(task) {
at += task.len();
}
}
}
at
}
#[doc(hidden)]
pub fn continues(line: &str) -> bool {
let trimmed = line.trim_start();
!trimmed.is_empty() && marker_len(line) == 0 && !trimmed.starts_with("```") && !table_row(line)
}
#[doc(hidden)]
pub fn open_paragraph(line: &str) -> bool {
let trimmed = line.trim_start();
!trimmed.is_empty()
&& !trimmed.starts_with('#')
&& !trimmed.starts_with("```")
&& !table_row(line)
}
#[doc(hidden)]
pub fn table_row(line: &str) -> bool {
line.trim_start().starts_with('|')
}
pub(super) fn table_row_change(line: &str, open: &str, close: &str) -> String {
let mut out = String::new();
let mut cell = String::new();
let mut escaped = false;
let flush = |out: &mut String, cell: &mut String| {
let text = cell.trim();
if text.is_empty() || text.chars().all(|c| matches!(c, '-' | ':')) {
out.push_str(cell);
} else {
let start = cell.len() - cell.trim_start().len();
let end = cell.trim_end().len();
out.push_str(&cell[..start]);
out.push_str(open);
out.push_str(&escape(&cell[start..end]));
out.push_str(close);
out.push_str(&cell[end..]);
}
cell.clear();
};
for c in line.chars() {
if c == '|' && !escaped {
flush(&mut out, &mut cell);
out.push('|');
} else {
cell.push(c);
}
escaped = c == '\\' && !escaped;
}
flush(&mut out, &mut cell);
out
}
fn escape(text: &str) -> Cow<'_, str> {
if !text_has_delimiter(text) {
return Cow::Borrowed(text);
}
let points = escape_points(text);
if points.is_empty() {
return Cow::Borrowed(text);
}
let mut out = String::with_capacity(text.len() + points.len());
let mut from = 0;
for at in points {
out.push_str(&text[from..at]);
out.push('\\');
from = at;
}
out.push_str(&text[from..]);
Cow::Owned(out)
}
const DELIMITERS: [(&str, usize); 11] = [
("{++", 0),
("{--", 0),
("{~~", 0),
("{==", 0),
("{>>", 0),
("++}", 2),
("--}", 2),
("~~}", 2),
("==}", 2),
("<<}", 2),
("~>", 1),
];
fn text_has_delimiter(text: &str) -> bool {
DELIMITERS.iter().any(|(d, _)| text.contains(d))
|| text
.match_indices('{')
.any(|(at, _)| super::critic::attribution_tag(&text[at..]).is_some())
}
fn escape_points(text: &str) -> Vec<usize> {
let spans = super::critic::verbatim_ranges(text);
let bytes = text.as_bytes();
let mut points = Vec::new();
let (mut span, mut end) = (0, 0);
for i in 0..bytes.len() {
if i < end {
continue;
}
if spans.get(span).is_some_and(|range| range.start <= i) {
end = spans[span].end;
span += 1;
continue;
}
if bytes[i] == b'{'
&& !escaped_at(text, i)
&& super::critic::attribution_tag(&text[i..]).is_some()
{
points.push(i);
}
for (delimiter, insert) in DELIMITERS {
if bytes[i..].starts_with(delimiter.as_bytes()) && !escaped_at(text, i) {
points.push(i + insert);
break;
}
}
}
points.sort_unstable();
points.dedup();
points
}
fn escaped_at(text: &str, at: usize) -> bool {
text[..at].bytes().rev().take_while(|b| *b == b'\\').count() % 2 == 1
}
#[derive(Default)]
struct Output {
text: String,
started: bool,
carry: Option<&'static str>,
last: String,
}
impl Output {
fn line(&mut self, line: &str) {
if self.started {
self.text.push('\n');
}
self.started = true;
if let Some(close) = self.carry.take() {
self.text.push_str(close);
}
self.text.push_str(line);
self.last = line.to_string();
}
fn append(&mut self, text: &str) {
self.started = true;
self.text.push_str(text);
self.last.push_str(text);
}
fn finish(mut self, old_trailing: bool, new_trailing: bool) -> String {
if let Some(close) = self.carry.take() {
let trailing = if close == "--}" {
old_trailing
} else {
new_trailing
};
if trailing {
self.text.push('\n');
}
self.text.push_str(close);
return self.text;
}
if new_trailing && old_trailing {
if self.started {
self.text.push('\n');
}
} else if new_trailing != old_trailing {
self.add_trailing(new_trailing);
}
self.text
}
fn add_trailing(&mut self, inserted: bool) {
let close = if inserted { "++}" } else { "--}" };
if self.text.ends_with(close) {
let at = self.text.len() - close.len();
self.text.insert(at, '\n');
} else if self.text.ends_with("~~}") {
let at = if inserted {
self.text.len() - 3
} else {
self.text.rfind("~>").unwrap_or(self.text.len())
};
self.text.insert(at, '\n');
} else {
let open = if inserted { "{++" } else { "{--" };
self.text.push_str(&format!("{open}\n{close}"));
}
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Side {
Delete,
Insert,
}
impl Side {
fn delimiters(self) -> (&'static str, &'static str) {
match self {
Self::Delete => ("{--", "--}"),
Self::Insert => ("{++", "++}"),
}
}
}
enum Entry<'a> {
Pair(&'a str, &'a str),
Only(Side, &'a str),
}
fn hunk(out: &mut Output, olds: &[&str], news: &[&str]) {
if let Some(body) = reflow(olds, news) {
for line in body.split('\n') {
out.line(line);
}
return;
}
let entries = pair(olds, news);
let mut at = 0;
while at < entries.len() {
match entries[at] {
Entry::Pair(old, new) => {
paired(out, old, new);
at += 1;
}
Entry::Only(..) => {
let end = entries[at..]
.iter()
.position(|e| matches!(e, Entry::Pair(..)))
.map_or(entries.len(), |i| at + i);
let only = |side: Side| -> Vec<&str> {
entries[at..end]
.iter()
.filter_map(|e| match e {
Entry::Only(s, line) if *s == side => Some(*line),
_ => None,
})
.collect()
};
let deleted = only(Side::Delete);
let inserted = only(Side::Insert);
group(out, Side::Delete, &deleted);
group(out, Side::Insert, &inserted);
at = end;
}
}
}
}
fn reflow(olds: &[&str], news: &[&str]) -> Option<String> {
if !plain_paragraph(olds) || !plain_paragraph(news) || (olds.len() < 2 && news.len() < 2) {
return None;
}
let (old, new) = (olds.join("\n"), news.join("\n"));
if old.len() + new.len() > REFLOW_MAX_BYTES {
return None;
}
let flat_old = old.replace('\n', " ");
let flat_new = new.replace('\n', " ");
if similarity(&flat_old, &flat_new) < 0.8 {
return None;
}
let flat = words_diff(&flat_old, &flat_new);
let marks =
flat.matches("{--").count() + flat.matches("{++").count() + flat.matches("{~~").count();
if marks > 2 {
return None;
}
Some(reflow_body(&old, &new))
}
fn reflow_body(old: &str, new: &str) -> String {
let a = tokens(old);
let b = tokens(new);
fn weigh<'a>(tokens: &[&'a str]) -> Vec<&'a str> {
tokens
.iter()
.flat_map(|token| std::iter::repeat_n(*token, weight(token) as usize))
.collect()
}
fn owner(tokens: &[&str]) -> Vec<usize> {
tokens
.iter()
.enumerate()
.flat_map(|(i, token)| std::iter::repeat_n(i, weight(token) as usize))
.collect()
}
let (wa, wb) = (weigh(&a), weigh(&b));
let (owners_a, owners_b) = (owner(&a), owner(&b));
let mut segments: Vec<(bool, String, String)> = Vec::new();
for op in capture_diff_slices(Algorithm::Myers, &wa, &wb) {
let (tag, olds, news) = op.as_tag_tuple();
let owned = |range: std::ops::Range<usize>, owners: &[usize]| match (
range.start,
range.end.checked_sub(1),
) {
(start, Some(last)) if start <= last => owners[start]..owners[last] + 1,
_ => 0..0,
};
let old_range = owned(olds, &owners_a);
let new_range = owned(news, &owners_b);
let old_text = a[old_range].concat();
let new_text = b[new_range].concat();
let equal = tag == DiffTag::Equal;
match segments.last_mut() {
Some((same, o, n)) if *same == equal => {
o.push_str(&old_text);
n.push_str(&new_text);
}
_ => segments.push((equal, old_text, new_text)),
}
}
widen(segments, old, new)
.into_iter()
.map(|(equal, old_text, new_text)| {
if equal {
escape(&new_text).into_owned()
} else {
change(&old_text, &new_text)
}
})
.collect()
}
fn weight(token: &str) -> i32 {
if token.chars().any(char::is_alphanumeric) {
3
} else {
1
}
}
fn plain_paragraph(lines: &[&str]) -> bool {
let Some(first) = lines.first() else {
return false;
};
marker_len(first) == 0
&& !first.trim().is_empty()
&& !first.starts_with("```")
&& lines[1..].iter().all(|line| continues(line))
}
fn pair<'a>(olds: &[&'a str], news: &[&'a str]) -> Vec<Entry<'a>> {
let matched = if olds.len() == 1 && news.len() == 1 {
vec![(0, 0)]
} else {
pair_by_similarity(olds, news)
};
let mut entries = Vec::new();
let (mut i, mut j) = (0, 0);
for (mi, mj) in matched
.into_iter()
.chain(std::iter::once((olds.len(), news.len())))
{
entries.extend(olds[i..mi].iter().map(|l| Entry::Only(Side::Delete, l)));
entries.extend(news[j..mj].iter().map(|l| Entry::Only(Side::Insert, l)));
if mi < olds.len() && mj < news.len() {
entries.push(Entry::Pair(olds[mi], news[mj]));
}
i = mi + 1;
j = mj + 1;
}
entries
}
fn pair_by_similarity(olds: &[&str], news: &[&str]) -> Vec<(usize, usize)> {
let mut ids = std::collections::HashMap::new();
let mut interned: Vec<Vec<u32>> = Vec::with_capacity(olds.len() + news.len());
for line in olds.iter().chain(news.iter()) {
interned.push(
body_words(line)
.into_iter()
.map(|word| intern(&mut ids, word))
.collect(),
);
}
let (old_words, new_words) = interned.split_at(olds.len());
let sorted = |words: &[u32]| -> Vec<u32> {
let mut out = words.to_vec();
out.sort_unstable();
out
};
let old_multiset: Vec<Vec<u32>> = old_words.iter().map(|w| sorted(w)).collect();
let new_multiset: Vec<Vec<u32>> = new_words.iter().map(|w| sorted(w)).collect();
let mut old_distinct: Vec<Vec<u32>> = old_multiset.clone();
for words in &mut old_distinct {
words.dedup();
}
let mut new_distinct: Vec<Vec<u32>> = new_multiset.clone();
for words in &mut new_distinct {
words.dedup();
}
let mut index: std::collections::HashMap<u32, Vec<usize>> = std::collections::HashMap::new();
for (i, words) in old_distinct.iter().enumerate() {
for &word in words {
index.entry(word).or_default().push(i);
}
}
let shape =
|lines: &[&str]| -> Vec<String> { lines.iter().map(|line| marker_shape(line)).collect() };
let (old_shape, new_shape) = (shape(olds), shape(news));
let mut candidates: Vec<Vec<usize>> = Vec::with_capacity(news.len());
for (j, words) in new_distinct.iter().enumerate() {
let mut by_rarity: Vec<(usize, u32)> = words
.iter()
.filter_map(|&word| index.get(&word).map(|lines| (lines.len(), word)))
.collect();
by_rarity.sort_unstable();
let mut lines = Vec::new();
if let Some(&(least, _)) = by_rarity.first() {
let limit = least.max(RARE_LINE_SHARE);
lines = by_rarity
.iter()
.take_while(|&&(count, _)| count <= limit)
.flat_map(|&(_, word)| index[&word].iter().copied())
.collect();
lines.sort_unstable();
lines.dedup();
lines.retain(|&i| old_shape[i] == new_shape[j]);
lines.truncate(MAX_CANDIDATES);
}
candidates.push(lines);
}
let mut pairs: Vec<(usize, usize, f64)> = Vec::new();
for (j, lines) in candidates.iter().enumerate() {
for &i in lines {
let score = dice(&old_multiset[i], &new_multiset[j]);
if score >= WORD_DIFF_SIMILARITY && old_shape[i] == new_shape[j] {
pairs.push((i, j, score));
}
}
}
weighted_pairs(&pairs, news.len())
}
fn dice<T: Ord>(a: &[T], b: &[T]) -> f64 {
if a.is_empty() && b.is_empty() {
return 1.0;
}
if a.is_empty() || b.is_empty() {
return 0.0;
}
let best = 2.0 * a.len().min(b.len()) as f64 / (a.len() + b.len()) as f64;
if best < WORD_DIFF_SIMILARITY {
return 0.0;
}
let (mut i, mut j, mut common) = (0, 0, 0usize);
while i < a.len() && j < b.len() {
match a[i].cmp(&b[j]) {
std::cmp::Ordering::Less => i += 1,
std::cmp::Ordering::Greater => j += 1,
std::cmp::Ordering::Equal => {
let (word, mut more_i, mut more_j) = (&a[i], 0, 0);
while a.get(i + more_i) == Some(word) {
more_i += 1;
}
while b.get(j + more_j) == Some(word) {
more_j += 1;
}
common += more_i.min(more_j);
i += more_i;
j += more_j;
}
}
}
2.0 * common as f64 / (a.len() + b.len()) as f64
}
fn weighted_pairs(pairs: &[(usize, usize, f64)], new_len: usize) -> Vec<(usize, usize)> {
let mut order: Vec<usize> = (0..pairs.len()).collect();
order.sort_by_key(|&at| (pairs[at].0, pairs[at].1));
let mut best = vec![0.0f64; pairs.len()];
let mut from = vec![usize::MAX; pairs.len()];
let mut tree = vec![(0.0f64, usize::MAX); new_len + 1];
let mut at = 0;
while at < order.len() {
let same_old = order[at..]
.iter()
.position(|&later| pairs[later].0 != pairs[order[at]].0)
.map_or(order.len(), |offset| at + offset);
for &candidate in &order[at..same_old] {
let (mut sum, mut parent) = (0.0f64, usize::MAX);
let mut node = pairs[candidate].1;
while node > 0 {
if tree[node].0 > sum {
sum = tree[node].0;
parent = tree[node].1;
}
node -= node & node.wrapping_neg();
}
best[candidate] = sum + pairs[candidate].2;
from[candidate] = parent;
}
for &candidate in &order[at..same_old] {
let mut node = pairs[candidate].1 + 1;
while node < tree.len() {
if best[candidate] > tree[node].0 {
tree[node] = (best[candidate], candidate);
}
node += node & node.wrapping_neg();
}
}
at = same_old;
}
let mut tip = usize::MAX;
for candidate in 0..pairs.len() {
if tip == usize::MAX || best[candidate] > best[tip] {
tip = candidate;
}
}
let mut matched = Vec::new();
if tip != usize::MAX && best[tip] > 1e-9 {
let mut at = tip;
while at != usize::MAX {
matched.push((pairs[at].0, pairs[at].1));
at = from[at];
}
}
matched.reverse();
matched
}
fn intern<'a>(ids: &mut std::collections::HashMap<&'a str, u32>, word: &'a str) -> u32 {
let next = ids.len() as u32;
*ids.entry(word).or_insert(next)
}
fn body_words(line: &str) -> Vec<&str> {
words(&line[marker_len(line)..])
}
fn marker_shape(line: &str) -> String {
let marker = &line[..marker_len(line)];
let mut out = String::with_capacity(marker.len());
for c in marker.chars() {
if c.is_ascii_digit() {
if !out.ends_with('0') {
out.push('0');
}
} else {
out.push(c);
}
}
out
}
#[doc(hidden)]
pub fn similarity(old: &str, new: &str) -> f64 {
let (a, b) = (words(old), words(new));
if a.is_empty() && b.is_empty() {
return 1.0;
}
if a.is_empty() || b.is_empty() {
return 0.0;
}
let best = 2.0 * a.len().min(b.len()) as f64 / (a.len() + b.len()) as f64;
if best < WORD_DIFF_SIMILARITY {
return 0.0;
}
let common = capture_diff_slices(Algorithm::Myers, &a, &b)
.iter()
.filter(|op| matches!(op.as_tag_tuple().0, DiffTag::Equal))
.map(|op| op.as_tag_tuple().1.len())
.sum::<usize>();
2.0 * common as f64 / (a.len() + b.len()) as f64
}
fn words(line: &str) -> Vec<&str> {
tokens(line)
.into_iter()
.filter(|t| t.chars().any(char::is_alphanumeric))
.collect()
}
fn paired(out: &mut Output, old: &str, new: &str) {
let (old_marker, new_marker) = (&old[..marker_len(old)], &new[..marker_len(new)]);
if old_marker != new_marker {
out.line(&change(old, new));
return;
}
let (old_text, new_text) = (&old[old_marker.len()..], &new[new_marker.len()..]);
let mut line = escape(new_marker).into_owned();
if similarity(old_text, new_text) < WORD_DIFF_SIMILARITY {
line.push_str(&change(old_text, new_text));
} else {
line.push_str(&words_diff(old_text, new_text));
}
out.line(&line);
}
fn change(old: &str, new: &str) -> String {
match (old.is_empty(), new.is_empty()) {
(true, true) => String::new(),
(true, false) => format!("{{++{}++}}", escape(new)),
(false, true) => format!("{{--{}--}}", escape(old)),
(false, false) => format!("{{~~{}~>{}~~}}", escape(old), escape(new)),
}
}
fn words_diff(old: &str, new: &str) -> String {
let a = tokens(old);
let b = tokens(new);
let mut segments: Vec<(bool, String, String)> = Vec::new();
for op in capture_diff_slices(Algorithm::Myers, &a, &b) {
let (tag, olds, news) = op.as_tag_tuple();
let old_text = a[olds].concat();
let new_text = b[news].concat();
let equal = tag == DiffTag::Equal;
match segments.last_mut() {
Some((false, o, n)) if !equal => {
o.push_str(&old_text);
n.push_str(&new_text);
}
_ => segments.push((equal, old_text, new_text)),
}
}
let mut merged: Vec<(bool, String, String)> = Vec::new();
let mut index = 0;
while index < segments.len() {
let (equal, old_text, new_text) = segments[index].clone();
let bridge = equal
&& old_text.trim().is_empty()
&& index > 0
&& index + 1 < segments.len()
&& matches!(merged.last(), Some((false, ..)));
if bridge && let Some((false, o, n)) = merged.last_mut() {
o.push_str(&old_text);
n.push_str(&new_text);
let (_, next_old, next_new) = &segments[index + 1];
o.push_str(next_old);
n.push_str(next_new);
index += 2;
continue;
}
merged.push((equal, old_text, new_text));
index += 1;
}
widen(merged, old, new)
.into_iter()
.map(|(equal, old_text, new_text)| {
if equal {
escape(&new_text).into_owned()
} else {
change(&old_text, &new_text)
}
})
.collect()
}
struct OpenSpan {
start: usize,
inner: Option<(usize, usize)>,
whole: bool,
}
struct Atom {
range: (usize, usize),
triggers: Vec<(usize, usize)>,
}
fn atoms(text: &str) -> Vec<Atom> {
scan_atoms(text, 0, true)
.into_iter()
.chain(numbers(text))
.collect()
}
fn scan_atoms(text: &str, offset: usize, math: bool) -> Vec<Atom> {
let shift = |(start, end): (usize, usize)| (offset + start, offset + end);
let mut out = Vec::new();
let mut open: Vec<OpenSpan> = Vec::new();
let mut options = Options::ENABLE_STRIKETHROUGH;
if math {
options |= Options::ENABLE_MATH;
}
for (event, range) in Parser::new_ext(text, options).into_offset_iter() {
match event {
Event::Start(tag) => match tag {
Tag::Emphasis | Tag::Strong | Tag::Strikethrough => {
open.push(OpenSpan {
start: range.start,
inner: None,
whole: false,
});
}
Tag::Link { link_type, .. } => {
open.push(OpenSpan {
start: range.start,
inner: None,
whole: matches!(link_type, LinkType::Autolink | LinkType::Email),
});
}
Tag::Image { .. } => {
open.push(OpenSpan {
start: range.start,
inner: None,
whole: true,
});
}
_ => extend(&mut open, (range.start, range.end)),
},
Event::End(end) if is_atom_end(&end) => {
if let Some(OpenSpan {
start,
inner,
whole,
}) = open.pop()
{
let (inner_start, inner_end) = inner.unwrap_or((range.end, range.end));
let triggers = if whole {
vec![shift((start, range.end))]
} else {
vec![shift((start, inner_start)), shift((inner_end, range.end))]
};
out.push(Atom {
range: shift((start, range.end)),
triggers,
});
extend(&mut open, (start, range.end));
}
}
Event::Code(_) => {
out.push(Atom {
range: shift((range.start, range.end)),
triggers: vec![shift((range.start, range.end))],
});
extend(&mut open, (range.start, range.end));
}
Event::DisplayMath(_) if math => {
out.push(Atom {
range: shift((range.start, range.end)),
triggers: vec![shift((range.start, range.end))],
});
extend(&mut open, (range.start, range.end));
}
Event::InlineMath(_) if math && !opens_amount(text, range.start) => {
out.push(Atom {
range: shift((range.start, range.end)),
triggers: vec![shift((range.start, range.end))],
});
extend(&mut open, (range.start, range.end));
}
Event::InlineMath(_) if math => {
let inside = &text[range.start + 1..range.end - 1];
out.extend(scan_atoms(inside, offset + range.start + 1, false));
extend(&mut open, (range.start, range.end));
}
Event::Html(_) | Event::InlineHtml(_) => {
out.push(Atom {
range: shift((range.start, range.end)),
triggers: vec![shift((range.start, range.end))],
});
extend(&mut open, (range.start, range.end));
}
_ => extend(&mut open, (range.start, range.end)),
}
}
out
}
fn is_atom_end(end: &TagEnd) -> bool {
matches!(
end,
TagEnd::Emphasis | TagEnd::Strong | TagEnd::Strikethrough | TagEnd::Link | TagEnd::Image
)
}
fn extend(open: &mut [OpenSpan], range: (usize, usize)) {
if let Some(OpenSpan { inner, .. }) = open.last_mut() {
*inner = Some(match inner {
Some((start, end)) => ((*start).min(range.0), (*end).max(range.1)),
None => range,
});
}
}
pub(super) fn opens_amount(text: &str, at: usize) -> bool {
text.as_bytes().get(at) == Some(&b'$')
&& text.as_bytes().get(at + 1).is_some_and(u8::is_ascii_digit)
}
fn numbers(text: &str) -> Vec<Atom> {
let chars: Vec<(usize, char)> = text.char_indices().collect();
let mut out = Vec::new();
let mut at = 0;
while at < chars.len() {
let currency = matches!(chars[at].1, '$' | '€' | '£' | '¥');
let first = if currency { at + 1 } else { at };
if !chars.get(first).is_some_and(|(_, c)| c.is_ascii_digit()) {
at += 1;
continue;
}
let mut end = first;
while end < chars.len() {
let c = chars[end].1;
let joins = matches!(c, ',' | '.' | '/' | ':' | '-')
&& chars.get(end + 1).is_some_and(|(_, n)| n.is_ascii_digit())
&& end > first;
if c.is_ascii_digit() || joins {
end += 1;
} else {
break;
}
}
if chars.get(end).is_some_and(|(_, c)| *c == '%') {
end += 1;
}
let range = (chars[at].0, chars.get(end).map_or(text.len(), |(i, _)| *i));
out.push(Atom {
range,
triggers: vec![range],
});
at = end;
}
out
}
fn touches(range: (usize, usize), span: (usize, usize)) -> bool {
if range.0 == range.1 {
span.0 < range.0 && range.0 < span.1
} else {
range.0 < span.1 && span.0 < range.1
}
}
fn widen(
mut segments: Vec<(bool, String, String)>,
old: &str,
new: &str,
) -> Vec<(bool, String, String)> {
let (old_atoms, new_atoms) = (atoms(old), atoms(new));
let mut index = 0;
while index < segments.len() {
if segments[index].0 {
index += 1;
continue;
}
loop {
let (mut o, mut n) = (0, 0);
for segment in &segments[..index] {
o += segment.1.len();
n += segment.2.len();
}
let (_, old_text, new_text) = &segments[index];
let old_range = (o, o + old_text.len());
let new_range = (n, n + new_text.len());
let cover = |range: (usize, usize), atoms: &[Atom]| {
atoms
.iter()
.filter(|a| a.triggers.iter().any(|t| touches(range, *t)))
.fold(range, |(s, e), a| (s.min(a.range.0), e.max(a.range.1)))
};
let (old_to, new_to) = (cover(old_range, &old_atoms), cover(new_range, &new_atoms));
let left = (old_range.0 - old_to.0).max(new_range.0 - new_to.0);
let right = (old_to.1 - old_range.1).max(new_to.1 - new_range.1);
if left == 0 && right == 0 {
break;
}
let before = left > 0 && index > 0;
let after = right > 0 && index + 1 < segments.len();
if !before && !after {
break;
}
if before && take(&mut segments, index - 1, left, true) {
index -= 1;
}
if after {
take(&mut segments, index + 1, right, false);
}
}
index += 1;
}
segments
}
fn take(
segments: &mut Vec<(bool, String, String)>,
at: usize,
length: usize,
into_next: bool,
) -> bool {
let (equal, old_text, new_text) = segments[at].clone();
let whole = !equal || length >= old_text.len();
let (moved_old, moved_new, kept) = if whole {
(old_text, new_text, None)
} else if into_next {
let cut = old_text.floor_char_boundary(old_text.len() - length);
(
old_text[cut..].to_string(),
old_text[cut..].to_string(),
Some(old_text[..cut].to_string()),
)
} else {
let cut = old_text.ceil_char_boundary(length);
(
old_text[..cut].to_string(),
old_text[..cut].to_string(),
Some(old_text[cut..].to_string()),
)
};
let change = if into_next { at + 1 } else { at - 1 };
{
let (_, o, n) = &mut segments[change];
if into_next {
o.insert_str(0, &moved_old);
n.insert_str(0, &moved_new);
} else {
o.push_str(&moved_old);
n.push_str(&moved_new);
}
}
match kept {
Some(kept) => {
segments[at] = (true, kept.clone(), kept);
false
}
None => {
segments.remove(at);
true
}
}
}
fn group(out: &mut Output, side: Side, lines: &[&str]) {
if lines.is_empty() {
return;
}
let (open, close) = side.delimiters();
let mut rest = lines;
if out.started && open_paragraph(&out.last) && marker_len(&out.last) == 0 && continues(rest[0])
{
let length = rest.iter().take_while(|l| continues(l)).count();
let joined: Vec<Cow<'_, str>> = rest[..length].iter().map(|l| escape(l)).collect();
out.append(&format!("{open}\n{}{close}", joined.join("\n")));
rest = &rest[length..];
}
if rest.is_empty() {
return;
}
if side == Side::Insert && rest.iter().all(|l| table_row(l)) {
for line in rest {
out.line(&table_row_change(line, open, close));
}
return;
}
let run = rest;
let doc_start = !out.started;
let prev_blank = out.started && out.last.trim().is_empty();
let mut prefix = String::new();
if doc_start || prev_blank {
prefix.push_str(open);
} else if let Some(pending) = out.carry.take() {
prefix.push_str(pending);
prefix.push_str(open);
} else {
out.append(open);
}
let carry_closer = doc_start || prev_blank;
let last = run.len() - 1;
for (at, line) in run.iter().enumerate() {
let mut text = if at == 0 && !prefix.is_empty() {
format!("{prefix}{}", escape(line))
} else {
escape(line).into_owned()
};
if at == last && !carry_closer {
text.push_str(close);
}
out.line(&text);
}
if carry_closer {
out.carry = Some(close);
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod tests {
use super::*;
#[test]
fn markers_are_found() {
for (line, marker) in [
("# Title", "# "),
("###### Six", "###### "),
("####### Seven", ""),
("- item", "- "),
(" * nested", " * "),
("12. twelfth", "12. "),
("3) third", "3) "),
("- [x] done", "- [x] "),
("> quoted", "> "),
("> > - deep", "> > - "),
("plain", ""),
("-5 degrees", ""),
("#hashtag", ""),
("#", "#"),
("[^note]: text", "[^note]: "),
("[^a b]: text", ""),
] {
assert_eq!(&line[..marker_len(line)], marker, "{line}");
}
}
#[test]
fn a_rewritten_phrase_is_one_change() {
assert_eq!(
words_diff("the quick brown fox", "the slow red fox"),
"the {~~quick brown~>slow red~~} fox"
);
assert_eq!(words_diff("a b", "a b c"), "a b{++ c++}");
assert_eq!(words_diff("a b c", "a c"), "a {--b --}c");
}
#[test]
fn a_decomposed_accent_is_part_of_the_word_replaced() {
let (old, new) = ("Le cafe\u{301} est chaud.\n", "Le the\u{301} est chaud.\n");
assert_eq!(
diff_markdown(old, new),
"Le {~~cafe\u{301}~>the\u{301}~~} est chaud.\n"
);
assert_eq!(
diff_markdown("Le caf\u{e9} est chaud.\n", "Le th\u{e9} est chaud.\n"),
"Le {~~caf\u{e9}~>th\u{e9}~~} est chaud.\n"
);
assert_eq!(
words_diff("un cafe est", "un cafe\u{301} est"),
"un {~~cafe~>cafe\u{301}~~} est"
);
}
#[test]
fn a_change_inside_a_number_is_the_whole_number() {
for (old, new, expected) in [
(
"exceeds **$250,000** now",
"exceeds **$150,000** now",
"exceeds **{~~$250,000~>$150,000~~}** now",
),
(
"on 04/20/26.",
"on 10/30/26.",
"on {~~04/20/26~>10/30/26~~}.",
),
("grew 3.5% a", "grew 4.25% a", "grew {~~3.5%~>4.25%~~} a"),
(
"cap of $5,000,000 total",
"cap of $7,500,000 total",
"cap of {~~$5,000,000~>$7,500,000~~} total",
),
("5 days", "5 business days", "5 {++business ++}days"),
("5 days", "5, days", "5{++,++} days"),
] {
assert_eq!(words_diff(old, new), expected, "{old}");
}
}
#[test]
fn a_formatting_change_is_the_whole_span() {
for (old, new, expected) in [
(
"harmless *Buyer*, its",
"harmless Buyer, its",
"harmless {~~*Buyer*~>Buyer~~}, its",
),
(
"the \"Basket\")",
"the \"**Basket**\")",
"the \"{~~Basket~>**Basket**~~}\")",
),
(
"*provided, however*, that",
"*provided, further*, that",
"*provided, {~~however~>further~~}*, that",
),
] {
assert_eq!(words_diff(old, new), expected, "{old}");
}
}
#[test]
fn a_changed_link_target_is_the_whole_link() {
assert_eq!(
words_diff(
"in [Section 7.4](#section-7-4).",
"in [Section 7.5](#section-7-5)."
),
"in {~~[Section 7.4](#section-7-4)~>[Section 7.5](#section-7-5)~~}."
);
assert_eq!(
words_diff("see [the old terms](x)", "see [the new terms](x)"),
"see [the {~~old~>new~~} terms](x)"
);
}
#[test]
fn delimiters_in_the_text_are_escaped() {
assert_eq!(escape("a {++ b ++} ~> c"), "a \\{++ b ++\\} ~\\> c");
assert_eq!(
diff_markdown("x {++y++}\n", "x {++z++}\n"),
"x \\{++{~~y~>z~~}++\\}\n"
);
}
#[test]
fn identical_documents_come_back_unchanged() {
let text = "# Title\n\n- a\n- b\n\nText.\n";
assert_eq!(diff_markdown(text, text), text);
assert_eq!(diff_markdown("", ""), "");
}
#[test]
fn blocks_added_or_removed_keep_their_markers_outside() {
assert_eq!(
diff_markdown("- a\n- c\n", "- a\n- b\n- c\n"),
"- a{++\n- b++}\n- c\n"
);
assert_eq!(
diff_markdown("A\n\nOld paragraph.\n\nC\n", "A\n\nC\n"),
"A\n\n{--Old paragraph.\n\n--}C\n"
);
assert_eq!(
diff_markdown("# One\n", "# One\n\n## Two\n"),
"# One{++\n\n## Two++}\n"
);
}
#[test]
fn a_line_added_inside_a_paragraph_takes_its_line_break() {
assert_eq!(
diff_markdown("first\nthird\n", "first\nsecond\nthird\n"),
"first{++\nsecond++}\nthird\n"
);
assert_eq!(diff_markdown("x\ny\n", "y\n"), "{--x\n--}y\n");
}
#[test]
fn a_changed_marker_replaces_the_block() {
assert_eq!(
diff_markdown("# Title\n", "## Title\n"),
"{~~# Title~>## Title~~}\n"
);
round_trip("# Title\n", "## Title\n");
assert_eq!(
diff_markdown("- [ ] write\n", "- [x] write\n"),
"{~~- [ ] write~>- [x] write~~}\n"
);
round_trip("- [ ] write\n", "- [x] write\n");
assert_eq!(
diff_markdown("- hello world\n", "hello world\n"),
"{~~- hello world~>hello world~~}\n"
);
round_trip("- hello world\n", "hello world\n");
}
#[test]
fn a_table_row_changes_cell_by_cell() {
assert_eq!(
diff_markdown(
"| a |\n|---|\n| 1 |\n",
"| a |\n|---|\n| 1 |\n| 2 \\| 3 |\n"
),
"| a |\n|---|\n| 1 |\n| {++2 \\| 3++} |\n"
);
assert_eq!(table_row_change("|---|:-:|", "{++", "++}"), "|---|:-:|");
}
#[test]
fn unrelated_lines_are_replaced_whole() {
assert_eq!(
diff_markdown("Lorem ipsum dolor.\n", "Completely other words here.\n"),
"{~~Lorem ipsum dolor.~>Completely other words here.~~}\n"
);
}
fn round_trip(old: &str, new: &str) {
let diff = diff_markdown(old, new);
assert_eq!(
crate::markdown::resolve_critic(&diff, crate::markdown::TrackChanges::Accept),
new,
"accept {diff:?}"
);
assert_eq!(
crate::markdown::resolve_critic(&diff, crate::markdown::TrackChanges::Reject),
old,
"reject {diff:?}"
);
}
#[test]
fn a_changed_code_span_is_wrapped_whole() {
let (old, new) = ("Call `foo()` now.\n", "Call `bar()` now.\n");
assert_eq!(
diff_markdown(old, new),
"Call {~~`foo()`~>`bar()`~~} now.\n"
);
let (old, new) = ("use `{++}` here.\n", "use `{--}` here.\n");
assert_eq!(diff_markdown(old, new), "use {~~`{++}`~>`{--}`~~} here.\n");
round_trip(old, new);
round_trip("Call `foo()` now.\n", "Call `bar()` now.\n");
}
#[test]
fn a_changed_image_is_wrapped_whole() {
let target = (
"See  now.\n",
"See  now.\n",
"See {~~~>~~} now.\n",
);
let alt = (
"See  now.\n",
"See  now.\n",
"See {~~~>~~} now.\n",
);
for (old, new, expected) in [target, alt] {
assert_eq!(diff_markdown(old, new), expected, "{old}");
round_trip(old, new);
}
}
#[test]
fn a_changed_equation_is_wrapped_whole() {
for (old, new, expected) in [
(
"Area is $a+b$ now.\n",
"Area is $a+c$ now.\n",
"Area is {~~$a+b$~>$a+c$~~} now.\n",
),
(
"Area is $$a+b$$ now.\n",
"Area is $$a+c$$ now.\n",
"Area is {~~$$a+b$$~>$$a+c$$~~} now.\n",
),
] {
assert_eq!(diff_markdown(old, new), expected, "{old}");
round_trip(old, new);
}
}
#[test]
fn escape_counts_backslashes_and_skips_code() {
assert_eq!(escape(r"\{++"), r"\{++");
assert_eq!(escape(r"\\{++"), r"\\\{++");
assert_eq!(escape(r"\~>"), r"\~>");
assert_eq!(escape("a {++ b ++} ~> c"), "a \\{++ b ++\\} ~\\> c");
assert_eq!(escape("a `{++}` b"), "a `{++}` b");
assert_eq!(escape("a `{++}` {++} b"), "a `{++}` \\{++\\} b");
let text = "call `{++}` now\n";
assert_eq!(diff_markdown(text, text), text);
}
#[test]
fn twenty_one_changed_lines_and_an_insertion_pair_by_content() {
let old: String = (0..21)
.map(|i| format!("item {i:02} stays unique here\n"))
.collect();
let new: String = std::iter::once("item inserted at the top\n".to_string())
.chain((0..21).map(|i| format!("item {i:02} stays unique there\n")))
.collect();
let diff = diff_markdown(&old, &new);
assert!(
diff.starts_with(
"{++item inserted at the top\n++}item 00 stays unique {~~here~>there~~}\n"
),
"{diff}"
);
assert!(
diff.contains("item 20 stays unique {~~here~>there~~}"),
"{diff}"
);
assert!(!diff.contains("inserted at the top~>"), "{diff}");
round_trip(&old, &new);
}
#[test]
fn a_large_changed_hunk_still_pairs_similar_lines() {
let n = 1500;
let old: String = (0..n)
.map(|i| format!("row {i} alpha beta gamma\n"))
.collect();
let new: String = std::iter::once("row inserted zeta eta theta\n".to_string())
.chain((0..n).map(|i| format!("row {i} alpha beta delta\n")))
.collect();
let diff = diff_markdown(&old, &new);
assert!(
diff.contains("{++row inserted zeta eta theta\n++}row 0 alpha beta {~~gamma~>delta~~}"),
"{}",
&diff[..diff.len().min(400)]
);
assert!(diff.contains("row 1499 alpha beta {~~gamma~>delta~~}"));
}
#[test]
fn list_numbers_do_not_skew_pairing() {
let old = "1. alpha\n2. beta\n3. gamma\n";
let new = "1. inserted\n2. alpha\n3. beta\n4. gamma\n";
assert_eq!(
diff_markdown(old, new),
"{++1. inserted\n++}{~~1. alpha~>2. alpha~~}\n{~~2. beta~>3. beta~~}\n{~~3. gamma~>4. gamma~~}\n"
);
round_trip(old, new);
}
#[test]
fn a_list_item_turned_into_a_paragraph_is_not_glued() {
let old = "- hello world\n";
let new = "hello world\n";
assert_eq!(
diff_markdown(old, new),
"{~~- hello world~>hello world~~}\n"
);
round_trip(old, new);
}
fn wrap_words(text: &str, width: usize) -> String {
let mut lines = Vec::new();
let mut line = String::new();
for word in text.split_whitespace() {
if !line.is_empty() && line.len() + 1 + word.len() > width {
lines.push(std::mem::take(&mut line));
}
if !line.is_empty() {
line.push(' ');
}
line.push_str(word);
}
if !line.is_empty() {
lines.push(line);
}
lines.push(String::new());
lines.join("\n")
}
#[test]
fn one_word_added_to_a_hard_wrapped_paragraph_is_one_change() {
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.";
let added = base.replacen("lazy", "very lazy", 1);
for width in [20, 24, 28, 32, 40, 48] {
let old = wrap_words(base, width);
let new = wrap_words(&added, width);
let diff = diff_markdown(&old, &new);
round_trip(&old, &new);
assert!(
diff.contains("{++very") || diff.contains("{++ very"),
"width {width}: the added word is not one insertion\n{diff}"
);
for word in ["runs", "barn", "while", "watches"] {
assert!(
!diff.contains(&format!("{{--{word}"))
&& !diff.contains(&format!("{{++{word}")),
"width {width}: {word} was rewritten\n{diff}"
);
}
}
}
#[test]
fn a_changed_list_number_is_marked() {
assert_eq!(diff_markdown("10. a\n", "9. a\n"), "{~~10. a~>9. a~~}\n");
round_trip("10. a\n", "9. a\n");
}
#[test]
fn marker_shapes_change_whole() {
for (old, new) in [
("# Title\n", "## Title\n"),
("* a\n", "+ a\n"),
("- a\n", " - a\n"),
] {
round_trip(old, new);
}
}
#[test]
fn blank_lines_added_and_removed_are_marked() {
assert_eq!(diff_markdown("a\nb\n", "a\n\nb\n"), "a{++\n++}\nb\n");
assert_eq!(diff_markdown("a\n\nb\n", "a\nb\n"), "a{--\n--}\nb\n");
assert_eq!(diff_markdown("x\n\n\ny\n", "x\n\ny\n"), "x\n\n{--\n--}y\n");
round_trip("a\nb\n", "a\n\nb\n");
round_trip("a\n\nb\n", "a\nb\n");
round_trip("x\n\n\ny\n", "x\n\ny\n");
}
#[test]
fn the_trailing_newline_is_part_of_the_change() {
assert_eq!(diff_markdown("a", "a\n"), "a{++\n++}");
assert_eq!(diff_markdown("a\n", "a"), "a{--\n--}");
round_trip("a", "a\n");
round_trip("a\n", "a");
}
#[test]
fn a_substitutions_trailing_break_stays_on_the_side_that_has_it() {
assert_eq!(diff_markdown("a\nb\n", "a\nc"), "a\n{~~b\n~>c~~}");
round_trip("a\nb\n", "a\nc");
assert_eq!(diff_markdown("a\nb", "a\nc\n"), "a\n{~~b~>c\n~~}");
round_trip("a\nb", "a\nc\n");
assert_eq!(diff_markdown("a\nb\nc", "a\nb\nd"), "a\nb\n{~~c~>d~~}");
round_trip("a\nb\nc", "a\nb\nd");
}
#[test]
fn a_deleted_table_row_takes_its_line_with_it() {
assert_eq!(
diff_markdown("| a |\n|---|\n| 1 |\n", "| a |\n|---|\n"),
"| a |\n|---|{--\n| 1 |--}\n"
);
round_trip("| a |\n|---|\n| 1 |\n", "| a |\n|---|\n");
assert_eq!(
diff_markdown("| a |\n|---|\n| 1 |\n| 2 |\n", "| a |\n|---|\n| 2 |\n"),
"| a |\n|---|{--\n| 1 |--}\n| 2 |\n"
);
round_trip("| a |\n|---|\n| 1 |\n| 2 |\n", "| a |\n|---|\n| 2 |\n");
}
#[test]
fn a_code_span_across_a_line_break_is_one_atom() {
let (old, new) = ("x `a\nb` y\n", "x `a\nc` y\n");
assert_eq!(diff_markdown(old, new), "x {~~`a\nb`~>`a\nc`~~} y\n");
round_trip(old, new);
}
#[test]
fn a_multiline_display_equation_is_wrapped_whole() {
let (old, new) = (
"Area is\n$$\na+b\n$$\nnow.\n",
"Area is\n$$\na+c\n$$\nnow.\n",
);
let diff = diff_markdown(old, new);
assert!(diff.contains("{~~$$\na+b\n$$~>$$\na+c\n$$~~}"), "{diff}");
round_trip(old, new);
}
#[test]
fn identical_documents_with_verbatim_delimiters_come_back_unchanged() {
for text in [
"<!-- {++x++} -->\ntext\n",
"see <https://a.b/{++x> end\n",
"see [t](https://a.b/{++x) more\n",
"x `a\ncode {++i++} rest` y\n",
] {
assert_eq!(diff_markdown(text, text), text, "{text:?}");
}
}
#[test]
fn verbatim_constructs_change_whole() {
round_trip("see <https://a.b/one> end\n", "see <https://a.b/two> end\n");
round_trip(
"see [t](https://a.b/one) more\n",
"see [t](https://a.b/two) more\n",
);
round_trip("<!-- note one -->\ntext\n", "<!-- note two -->\ntext\n");
}
#[test]
fn escape_skips_the_readers_verbatim_ranges() {
assert_eq!(escape("<!-- {++x++} -->"), "<!-- {++x++} -->");
assert_eq!(escape("see <https://a.b/{++x>"), "see <https://a.b/{++x>");
assert_eq!(
escape("see [t](https://a.b/{++x)"),
"see [t](https://a.b/{++x)"
);
assert_eq!(
escape("x `a\ncode {++i++} rest` y"),
"x `a\ncode {++i++} rest` y"
);
assert_eq!(escape("a {++ b ++} ~> c"), "a \\{++ b ++\\} ~\\> c");
}
#[test]
fn accept_and_reject_rebuild_the_documents_exactly() {
let cases: &[(&str, &str)] = &[
("10. a\n", "9. a\n"),
("* a\n", "+ a\n"),
("# t\n", "## t\n"),
("- a\n", " - a\n"),
("a\nb\n", "a\n\nb\n"),
("a\n\nb\n", "a\nb\n"),
("x\n\n\ny\n", "x\n\ny\n"),
("a\n\nb\nc\n", "a\nb\n\nc\n"),
("a", "a\n"),
("a\n", "a"),
("", "a\n"),
("a\n", ""),
("| a |\n|---|\n| 1 |\n", "| a |\n|---|\n"),
("| a |\n|---|\n| 1 |\n| 2 |\n", "| a |\n|---|\n| 2 |\n"),
("- hello world\n", "hello world\n"),
("hello world\n", "- hello world\n"),
("a b c\n", "a b c\n- d\n"),
("x `a\nb` y\n", "x `a\nc` y\n"),
("x `a\nb` y\n", "x `a\nb` z\n"),
("<!-- note one -->\ntext\n", "<!-- note two -->\ntext\n"),
("see <https://a.b/one> end\n", "see <https://a.b/two> end\n"),
(
"see [t](https://a.b/one) more\n",
"see [t](https://a.b/two) more\n",
),
("Area is $a+b$ now.\n", "Area is $a+c$ now.\n"),
("Area is $$a+b$$ now.\n", "Area is $$a+c$$ now.\n"),
(
"Area is\n$$\na+b\n$$\nnow.\n",
"Area is\n$$\na+c\n$$\nnow.\n",
),
];
for (old, new) in cases {
round_trip(old, new);
}
}
#[test]
fn escape_is_linear_on_backtick_runs() {
let mut text = String::with_capacity(400_000);
for _ in 0..100_000 {
text.push_str("`x");
}
text.push_str("{++}");
let escaped = escape(&text);
assert_eq!(escaped.len(), text.len() + 2);
}
#[test]
fn a_large_rewrap_stays_fast() {
let words: Vec<String> = (0..20_000).map(|i| format!("w{i}x")).collect();
let text = words.join(" ");
let wrap = |width: usize| {
let mut lines = Vec::new();
let mut line = String::new();
for word in text.split(' ') {
if !line.is_empty() && line.len() + 1 + word.len() > width {
lines.push(std::mem::take(&mut line));
}
if !line.is_empty() {
line.push(' ');
}
line.push_str(word);
}
if !line.is_empty() {
lines.push(line);
}
lines.push(String::new());
lines.join("\n")
};
let (old, new) = (wrap(40), wrap(45));
round_trip(&old, &new);
}
#[test]
fn long_lines_pair_in_linear_time() {
let lines = |tail: &str| -> String {
(0..200)
.map(|i| {
let mut line = format!("row{i}");
for w in 0..250 {
line.push_str(&format!(" w{w}"));
}
format!("{line} {tail}\n")
})
.collect()
};
let (old, new) = (lines("tail"), lines("tailx"));
let diff = diff_markdown(&old, &new);
assert!(diff.contains("row0 w0"), "{}", &diff[..diff.len().min(200)]);
round_trip(&old, &new);
}
#[test]
fn the_only_pairable_candidate_survives_the_candidate_bound() {
let mut old = String::new();
for _ in 0..MAX_CANDIDATES + 7 {
old.push_str("- alpha beta gamma\n");
}
old.push_str("alpha beta gamma\n");
let new = "alpha beta gamma zeta\n";
let diff = diff_markdown(&old, new);
assert!(diff.contains("alpha beta gamma{++ zeta++}"), "{diff}");
assert!(
!diff.contains("{--\nalpha beta gamma--}"),
"the plain line was deleted whole\n{diff}"
);
round_trip(&old, new);
}
#[test]
fn each_of_two_identical_old_lines_still_pairs_in_order() {
let old = "- alpha beta gamma delta\n- alpha beta gamma delta\n";
let new = "- alpha beta gamma delta one\n- alpha beta gamma delta two\n";
let diff = diff_markdown(old, new);
assert!(diff.contains("alpha beta gamma delta{++ one++}"), "{diff}");
assert!(diff.contains("alpha beta gamma delta{++ two++}"), "{diff}");
round_trip(old, new);
}
#[test]
fn just_over_the_old_bound_pairs_by_content() {
let old: String = (0..2001)
.map(|i| format!("item {i:04} alpha beta gamma\n"))
.collect();
let new: String = std::iter::once("inserted first\n".to_string())
.chain((0..2000).map(|i| format!("item {i:04} alpha beta delta\n")))
.collect();
let diff = diff_markdown(&old, &new);
assert!(
diff.contains("item 0000 alpha beta {~~gamma~>delta~~}"),
"{diff}"
);
assert!(
!diff.contains("item {~~0001~>0000~~}"),
"a line was rewritten into its neighbour\n{diff}"
);
round_trip(&old, &new);
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod branch_tests {
use super::*;
#[test]
fn markers_end_where_the_block_marker_ends() {
assert_eq!(marker_len(">quote"), 1);
assert_eq!(marker_len("> > x"), 4);
assert_eq!(marker_len("[^n]: note"), 6);
assert_eq!(marker_len("[^a b]: note"), 0);
assert_eq!(marker_len("1234567890. x"), 0);
assert_eq!(marker_len("12) x"), 4);
assert_eq!(marker_len("12x"), 0);
assert_eq!(marker_len("###"), 3);
assert_eq!(marker_shape("12. 3"), "0. ");
assert_eq!(marker_shape("1.2. x"), "");
}
#[test]
fn similarity_and_dice_score_shared_words() {
assert_eq!(dice::<u32>(&[], &[]), 1.0);
assert_eq!(dice(&[1], &[]), 0.0);
assert_eq!(dice(&[1], &[1, 2, 3, 4, 5, 6, 7, 8]), 0.0);
assert_eq!(dice(&[1, 1, 2], &[1, 2, 2]), 2.0 * 2.0 / 6.0);
assert_eq!(dice(&[1, 2, 3], &[1, 2, 3]), 1.0);
assert_eq!(similarity("", "... --"), 1.0);
assert_eq!(similarity("one", ""), 0.0);
assert_eq!(similarity("one", "one two three four five six seven"), 0.0);
assert_eq!(similarity("the cat sat", "the cat sat"), 1.0);
assert!(weighted_pairs(&[], 3).is_empty());
assert_eq!(
weighted_pairs(&[(0, 1, 0.9), (1, 0, 0.8), (1, 2, 0.7), (0, 0, 0.6)], 3),
[(0, 1), (1, 2)]
);
assert!(weighted_pairs(&[(0, 0, 0.0)], 1).is_empty());
}
#[test]
fn opaque_spans_across_lines_join_into_one_unit() {
let units = opaque_units("a `code\nspan` b\nnext\n<div\nx>\n");
assert_eq!(units, ["a `code\nspan` b", "next", "<div\nx>\n"]);
assert_eq!(opaque_units("one\ntwo"), ["one", "two"]);
}
#[test]
fn diffs_mark_words_math_and_reflowed_paragraphs() {
let out = diff_markdown(
"Pay $x+1$ to the vendor now.\n\n$$\na=1\n$$\n\nOne two three four\nfive six.\n",
"Pay $x+2$ to the vendor now.\n\n$$\na=2\n$$\n\nOne two three\nfour five six seven.\n",
);
assert!(
out.contains("{--$x+1$--}") || out.contains("{~~$x+1$~>$x+2$~~}"),
"{out}"
);
assert!(out.contains("seven"), "{out}");
let same = diff_markdown("A.\n", "A.\n");
assert_eq!(same, "A.\n");
}
}